Merge from Chromium at DEPS revision 237746

This commit was generated by merge_to_master.py.

Change-Id: Ia99affe6e2cf9342843aa38fa1d75355fd5c71f7
diff --git a/Source/core/DEPS b/Source/core/DEPS
index 69c8fe4..1ed8c84 100644
--- a/Source/core/DEPS
+++ b/Source/core/DEPS
@@ -9,7 +9,6 @@
 
 # core/ should not depend on modules/ at all, but there are a number of pieces
 # of code that do. Please don't add to this list of exceptions.
-    "!modules/device_orientation/NewDeviceOrientationController.h",
     "!modules/encryptedmedia/MediaKeyNeededEvent.h",
     "!modules/encryptedmedia/MediaKeys.h",
     "!modules/filesystem/DraggedIsolatedFileSystem.h",
diff --git a/Source/core/Init.cpp b/Source/core/Init.cpp
index 0c7b07b..8b7304d 100644
--- a/Source/core/Init.cpp
+++ b/Source/core/Init.cpp
@@ -37,6 +37,7 @@
 #include "FetchInitiatorTypeNames.h"
 #include "FontFamilyNames.h"
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "MathMLNames.h"
 #include "SVGNames.h"
 #include "XLinkNames.h"
@@ -71,6 +72,7 @@
     EventTypeNames::init();
     FetchInitiatorTypeNames::init();
     FontFamilyNames::init();
+    InputTypeNames::init();
     MediaFeatureNames::init();
     WTF::StringStatics::init();
     QualifiedName::init();
diff --git a/Source/core/accessibility/AXMediaControls.cpp b/Source/core/accessibility/AXMediaControls.cpp
index 1e12617..5f42630 100644
--- a/Source/core/accessibility/AXMediaControls.cpp
+++ b/Source/core/accessibility/AXMediaControls.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace HTMLNames;
 
 
diff --git a/Source/core/accessibility/AXMenuListPopup.cpp b/Source/core/accessibility/AXMenuListPopup.cpp
index 7c27138..145792a 100644
--- a/Source/core/accessibility/AXMenuListPopup.cpp
+++ b/Source/core/accessibility/AXMenuListPopup.cpp
@@ -66,7 +66,7 @@
 
 AXMenuListOption* AXMenuListPopup::menuListOptionAXObject(HTMLElement* element) const
 {
-    if (!element || !element->hasTagName(optionTag) || !element->confusingAndOftenMisusedAttached())
+    if (!element->hasTagName(optionTag))
         return 0;
 
     AXObject* object = document()->axObjectCache()->getOrCreate(MenuListOptionRole);
@@ -114,7 +114,9 @@
     AXObjectCache* cache = axObjectCache();
     for (size_t i = m_children.size(); i > 0 ; --i) {
         AXObject* child = m_children[i - 1].get();
-        if (child->actionElement() && !child->actionElement()->confusingAndOftenMisusedAttached()) {
+        // FIXME: How could children end up in here that have no actionElement(), the check
+        // in menuListOptionAXObject would seem to prevent that.
+        if (child->actionElement()) {
             child->detachFromParent();
             cache->remove(child->axObjectID());
         }
@@ -122,11 +124,15 @@
 
     m_children.clear();
     m_haveChildren = false;
-    addChildren();
 }
 
 void AXMenuListPopup::didUpdateActiveOption(int optionIndex)
 {
+    // We defer creation of the children until updating the active option so that we don't
+    // create AXObjects for <option> elements while they're in the middle of removal.
+    if (!m_haveChildren)
+        addChildren();
+
     ASSERT_ARG(optionIndex, optionIndex >= 0);
     ASSERT_ARG(optionIndex, optionIndex < static_cast<int>(m_children.size()));
 
diff --git a/Source/core/accessibility/AXNodeObject.cpp b/Source/core/accessibility/AXNodeObject.cpp
index 0cb3469..439e7cd 100644
--- a/Source/core/accessibility/AXNodeObject.cpp
+++ b/Source/core/accessibility/AXNodeObject.cpp
@@ -98,7 +98,7 @@
         Element* idElement = elements[i];
 
         builder.append(accessibleNameForNode(idElement));
-        for (Node* n = idElement->firstChild(); n; n = NodeTraversal::next(n, idElement))
+        for (Node* n = idElement->firstChild(); n; n = NodeTraversal::next(*n, idElement))
             builder.append(accessibleNameForNode(n));
 
         if (i != size - 1)
diff --git a/Source/core/accessibility/AXObject.cpp b/Source/core/accessibility/AXObject.cpp
index a96bfc7..24f3285 100644
--- a/Source/core/accessibility/AXObject.cpp
+++ b/Source/core/accessibility/AXObject.cpp
@@ -42,7 +42,7 @@
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/WTFString.h"
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace std;
 
 namespace WebCore {
@@ -289,14 +289,15 @@
 
 bool AXObject::isInertOrAriaHidden() const
 {
-    if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "true"))
-        return true;
-    if (node() && node()->isInert())
-        return true;
-
-    for (AXObject* object = parentObject(); object; object = object->parentObject()) {
+    bool mightBeInInertSubtree = true;
+    for (const AXObject* object = this; object; object = object->parentObject()) {
         if (equalIgnoringCase(object->getAttribute(aria_hiddenAttr), "true"))
             return true;
+        if (mightBeInInertSubtree && object->node()) {
+            if (object->node()->isInert())
+                return true;
+            mightBeInInertSubtree = false;
+        }
     }
 
     return false;
@@ -526,10 +527,10 @@
     AXObjectCache* cache = node->document().axObjectCache();
     AXObject* accessibleObject = cache->getOrCreate(node->renderer());
     while (accessibleObject && accessibleObject->accessibilityIsIgnored()) {
-        node = NodeTraversal::next(node);
+        node = NodeTraversal::next(*node);
 
         while (node && !node->renderer())
-            node = NodeTraversal::nextSkippingChildren(node);
+            node = NodeTraversal::nextSkippingChildren(*node);
 
         if (!node)
             return 0;
@@ -591,14 +592,6 @@
     return object->documentFrameView();
 }
 
-Page* AXObject::page() const
-{
-    Document* document = this->document();
-    if (!document)
-        return 0;
-    return document->page();
-}
-
 String AXObject::language() const
 {
     const AtomicString& lang = getAttribute(langAttr);
diff --git a/Source/core/accessibility/AXObject.h b/Source/core/accessibility/AXObject.h
index 53b2587..e66ba18 100644
--- a/Source/core/accessibility/AXObject.h
+++ b/Source/core/accessibility/AXObject.h
@@ -49,7 +49,6 @@
 class IntPoint;
 class IntSize;
 class Node;
-class Page;
 class RenderObject;
 class RenderListItem;
 class ScrollableArea;
@@ -508,7 +507,6 @@
     virtual Element* anchorElement() const { return 0; }
     virtual Element* actionElement() const { return 0; }
     virtual Widget* widgetForAttachmentView() const { return 0; }
-    Page* page() const;
     String language() const;
     bool hasAttribute(const QualifiedName&) const;
     const AtomicString& getAttribute(const QualifiedName&) const;
diff --git a/Source/core/accessibility/AXRenderObject.cpp b/Source/core/accessibility/AXRenderObject.cpp
index c65147e..5951359 100644
--- a/Source/core/accessibility/AXRenderObject.cpp
+++ b/Source/core/accessibility/AXRenderObject.cpp
@@ -72,7 +72,7 @@
 #include "platform/text/PlatformLocale.h"
 #include "wtf/StdLibExtras.h"
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace std;
 
 namespace WebCore {
@@ -150,42 +150,6 @@
     return prev;
 }
 
-static inline RenderObject* childBeforeConsideringContinuations(RenderInline* r, RenderObject* child)
-{
-    RenderBoxModelObject* curContainer = r;
-    RenderObject* cur = 0;
-    RenderObject* prev = 0;
-
-    while (curContainer) {
-        if (curContainer->isRenderInline()) {
-            cur = curContainer->firstChild();
-            while (cur) {
-                if (cur == child)
-                    return prev;
-                prev = cur;
-                cur = cur->nextSibling();
-            }
-
-            curContainer = toRenderInline(curContainer)->continuation();
-        } else if (curContainer->isRenderBlock()) {
-            if (curContainer == child)
-                return prev;
-
-            prev = curContainer;
-            curContainer = toRenderBlock(curContainer)->inlineElementContinuation();
-        }
-    }
-
-    ASSERT_NOT_REACHED();
-
-    return 0;
-}
-
-static inline bool firstChildIsInlineContinuation(RenderObject* renderer)
-{
-    return renderer->firstChild() && renderer->firstChild()->isInlineElementContinuation();
-}
-
 static inline bool lastChildHasContinuation(RenderObject* renderer)
 {
     return renderer->lastChild() && isInlineWithContinuation(renderer->lastChild());
@@ -2232,7 +2196,7 @@
     if (!map)
         return;
 
-    for (Element* current = ElementTraversal::firstWithin(map); current; current = ElementTraversal::next(current, map)) {
+    for (Element* current = ElementTraversal::firstWithin(*map); current; current = ElementTraversal::next(*current, map)) {
         // add an <area> element for this child if it has a link
         if (isHTMLAreaElement(current) && current->isLink()) {
             AXImageMapLink* areaObject = toAXImageMapLink(axObjectCache()->getOrCreate(ImageMapLinkRole));
diff --git a/Source/core/animation/ActiveAnimations.cpp b/Source/core/animation/ActiveAnimations.cpp
new file mode 100644
index 0000000..037e3df
--- /dev/null
+++ b/Source/core/animation/ActiveAnimations.cpp
@@ -0,0 +1,102 @@
+/*
+ * 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/animation/ActiveAnimations.h"
+
+#include "core/frame/animation/AnimationController.h"
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+bool shouldCompositeForActiveAnimations(const RenderObject& renderer, bool renderViewInCompositingMode)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+
+    if (!renderer.node() || !renderer.node()->isElementNode())
+        return false;
+
+    const Element* element = toElement(renderer.node());
+    if (const ActiveAnimations* activeAnimations = element->activeAnimations()) {
+        // FIXME: remove compositing mode check once compositing is forced on all platforms
+        if ((renderViewInCompositingMode && activeAnimations->hasActiveAnimations(CSSPropertyOpacity))
+            || activeAnimations->hasActiveAnimations(CSSPropertyWebkitTransform)
+            || activeAnimations->hasActiveAnimations(CSSPropertyWebkitFilter))
+            return true;
+    }
+
+    return false;
+}
+
+bool hasActiveAnimations(const RenderObject& renderer, CSSPropertyID property)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+
+    if (!renderer.node() || !renderer.node()->isElementNode())
+        return false;
+
+    const Element* element = toElement(renderer.node());
+    if (const ActiveAnimations* activeAnimations = element->activeAnimations())
+        return activeAnimations->hasActiveAnimations(property);
+
+    return false;
+}
+
+bool hasActiveAnimationsOnCompositor(const RenderObject& renderer, CSSPropertyID property)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+
+    if (!renderer.node() || !renderer.node()->isElementNode())
+        return false;
+
+    const Element* element = toElement(renderer.node());
+    if (const ActiveAnimations* activeAnimations = element->activeAnimations())
+        return activeAnimations->hasActiveAnimationsOnCompositor(property);
+
+    return false;
+}
+
+bool ActiveAnimations::hasActiveAnimations(CSSPropertyID property) const
+{
+    return m_defaultStack.affects(property);
+}
+
+bool ActiveAnimations::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
+{
+    return m_defaultStack.hasActiveAnimationsOnCompositor(property);
+}
+
+void ActiveAnimations::cancelAnimationOnCompositor()
+{
+    for (PlayerSet::iterator it = m_players.begin(); it != players().end(); ++it)
+        it->key->cancelAnimationOnCompositor();
+}
+
+} // namespace WebCore
diff --git a/Source/core/animation/ActiveAnimations.h b/Source/core/animation/ActiveAnimations.h
index bf2cb9a..6cb2387 100644
--- a/Source/core/animation/ActiveAnimations.h
+++ b/Source/core/animation/ActiveAnimations.h
@@ -33,12 +33,21 @@
 
 #include "core/animation/AnimationStack.h"
 #include "core/animation/css/CSSAnimations.h"
+#include "wtf/HashCountedSet.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
+class RenderObject;
+class Element;
+
+// FIXME: Move these to CompositorAnimations
+bool shouldCompositeForActiveAnimations(const RenderObject&, bool renderViewInCompositingMode);
+bool hasActiveAnimations(const RenderObject&, CSSPropertyID);
+bool hasActiveAnimationsOnCompositor(const RenderObject&, CSSPropertyID);
+
 class ActiveAnimations {
 public:
     // Animations that are currently active for this element, their effects will be applied
@@ -48,10 +57,23 @@
     // will also be part of the default stack, but the mapping betwen animation name and
     // player is kept here.
     CSSAnimations& cssAnimations() { return m_cssAnimations; }
+    const CSSAnimations& cssAnimations() const { return m_cssAnimations; }
+
+    typedef HashCountedSet<Player*> PlayerSet;
+    // Players which have animations targeting this element.
+    const PlayerSet& players() const { return m_players; }
+    PlayerSet& players() { return m_players; }
+
     bool isEmpty() const { return m_defaultStack.isEmpty() && m_cssAnimations.isEmpty(); }
+
+    bool hasActiveAnimations(CSSPropertyID) const;
+    bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
+    void cancelAnimationOnCompositor();
+
 private:
     AnimationStack m_defaultStack;
     CSSAnimations m_cssAnimations;
+    PlayerSet m_players;
 };
 
 } // namespace WebCore
diff --git a/Source/core/animation/AnimatableClipPathOperation.cpp b/Source/core/animation/AnimatableClipPathOperation.cpp
index 6312682..f539df4 100644
--- a/Source/core/animation/AnimatableClipPathOperation.cpp
+++ b/Source/core/animation/AnimatableClipPathOperation.cpp
@@ -37,11 +37,11 @@
 {
     const AnimatableClipPathOperation* toOperation = toAnimatableClipPathOperation(value);
 
-    if (m_operation->getOperationType() != ClipPathOperation::SHAPE || toOperation->m_operation->getOperationType() != ClipPathOperation::SHAPE)
+    if (m_operation->type() != ClipPathOperation::SHAPE || toOperation->m_operation->type() != ClipPathOperation::SHAPE)
         return defaultInterpolateTo(this, value, fraction);
 
-    const BasicShape* fromShape = static_cast<ShapeClipPathOperation*>(clipPathOperation())->basicShape();
-    const BasicShape* toShape = static_cast<ShapeClipPathOperation*>(toOperation->clipPathOperation())->basicShape();
+    const BasicShape* fromShape = toShapeClipPathOperation(clipPathOperation())->basicShape();
+    const BasicShape* toShape = toShapeClipPathOperation(toOperation->clipPathOperation())->basicShape();
 
     if (!fromShape->canBlend(toShape))
         return defaultInterpolateTo(this, value, fraction);
diff --git a/Source/core/animation/AnimatableClipPathOperation.h b/Source/core/animation/AnimatableClipPathOperation.h
index fe5b67a..0a2401f 100644
--- a/Source/core/animation/AnimatableClipPathOperation.h
+++ b/Source/core/animation/AnimatableClipPathOperation.h
@@ -52,6 +52,7 @@
     AnimatableClipPathOperation(ClipPathOperation* operation)
         : m_operation(operation)
     {
+        ASSERT(m_operation);
     }
     virtual AnimatableType type() const OVERRIDE { return TypeClipPathOperation; }
     virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
diff --git a/Source/core/animation/AnimatableColorTest.cpp b/Source/core/animation/AnimatableColorTest.cpp
index fda5304..1e6ae35 100644
--- a/Source/core/animation/AnimatableColorTest.cpp
+++ b/Source/core/animation/AnimatableColorTest.cpp
@@ -37,7 +37,7 @@
 
 namespace {
 
-TEST(CoreAnimationAnimatableColorTest, ToColor)
+TEST(AnimationAnimatableColorTest, ToColor)
 {
     Color transparent = AnimatableColorImpl(Color::transparent).toColor();
     EXPECT_TRUE(transparent.isValid());
@@ -47,7 +47,7 @@
     EXPECT_EQ(red.rgb(), 0xFFFF0000);
 }
 
-TEST(CoreAnimationAnimatableColorTest, Interpolate)
+TEST(AnimationAnimatableColorTest, Interpolate)
 {
     EXPECT_EQ(AnimatableColorImpl(Color(0xFF00FF00)).interpolateTo(Color(0xFF00FF00), -10).toColor().rgb(), 0xFF00FF00);
     EXPECT_EQ(AnimatableColorImpl(Color(0xFF00FF00)).interpolateTo(Color(0xFFFF00FF), -10).toColor().rgb(), 0xFF00FF00);
@@ -67,7 +67,7 @@
     EXPECT_EQ(AnimatableColorImpl(Color(0x10204080)).interpolateTo(Color(0x104080C0), 0.5).toColor().rgb(), 0x103060A0u);
 }
 
-TEST(CoreAnimationAnimatableColorTest, Add)
+TEST(AnimationAnimatableColorTest, Add)
 {
     EXPECT_EQ(AnimatableColorImpl(Color(0xFF012345)).addWith(Color(0xFF543210)).toColor().rgb(), 0xFF555555);
     EXPECT_EQ(AnimatableColorImpl(Color(0xFF808080)).addWith(Color(0xFF808080)).toColor().rgb(), 0xFFFFFFFF);
diff --git a/Source/core/animation/AnimatableDoubleTest.cpp b/Source/core/animation/AnimatableDoubleTest.cpp
index ea1ab5d..ce8510b 100644
--- a/Source/core/animation/AnimatableDoubleTest.cpp
+++ b/Source/core/animation/AnimatableDoubleTest.cpp
@@ -39,19 +39,19 @@
 
 namespace {
 
-TEST(CoreAnimationAnimatableDoubleTest, Create)
+TEST(AnimationAnimatableDoubleTest, Create)
 {
     EXPECT_TRUE(static_cast<bool>(AnimatableDouble::create(5).get()));
     EXPECT_TRUE(static_cast<bool>(AnimatableDouble::create(10).get()));
 }
 
-TEST(CoreAnimationAnimatableDoubleTest, Equal)
+TEST(AnimationAnimatableDoubleTest, Equal)
 {
     EXPECT_TRUE(AnimatableDouble::create(10)->equals(AnimatableDouble::create(10).get()));
     EXPECT_FALSE(AnimatableDouble::create(5)->equals(AnimatableDouble::create(10).get()));
 }
 
-TEST(CoreAnimationAnimatableDoubleTest, ToCSSValue)
+TEST(AnimationAnimatableDoubleTest, ToCSSValue)
 {
     RefPtr<CSSValue> cssValue5 = CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_NUMBER);
     RefPtr<CSSValue> cssValue10 = CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_NUMBER);
@@ -59,14 +59,14 @@
     EXPECT_FALSE(AnimatableDouble::create(5)->toCSSValue()->equals(*cssValue10.get()));
 }
 
-TEST(CoreAnimationAnimatableDoubleTest, ToDouble)
+TEST(AnimationAnimatableDoubleTest, ToDouble)
 {
     EXPECT_EQ(5.9, AnimatableDouble::create(5.9)->toDouble());
     EXPECT_EQ(-10, AnimatableDouble::create(-10)->toDouble());
 }
 
 
-TEST(CoreAnimationAnimatableDoubleTest, Interpolate)
+TEST(AnimationAnimatableDoubleTest, Interpolate)
 {
     RefPtr<AnimatableDouble> from10 = AnimatableDouble::create(10);
     RefPtr<AnimatableDouble> to20 = AnimatableDouble::create(20);
@@ -79,7 +79,7 @@
     EXPECT_EQ(25, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), 1.5).get())->toDouble());
 }
 
-TEST(CoreAnimationAnimatableDoubleTest, Add)
+TEST(AnimationAnimatableDoubleTest, Add)
 {
     EXPECT_EQ(-10, toAnimatableDouble(AnimatableValue::add(AnimatableDouble::create(-2).get(), AnimatableDouble::create(-8).get()).get())->toDouble());
     EXPECT_EQ(0, toAnimatableDouble(AnimatableValue::add(AnimatableDouble::create(50).get(), AnimatableDouble::create(-50).get()).get())->toDouble());
diff --git a/Source/core/animation/AnimatableFilterOperations.cpp b/Source/core/animation/AnimatableFilterOperations.cpp
index d755442..31edeab 100644
--- a/Source/core/animation/AnimatableFilterOperations.cpp
+++ b/Source/core/animation/AnimatableFilterOperations.cpp
@@ -59,8 +59,8 @@
 
 PassRefPtr<AnimatableValue> AnimatableFilterOperations::addWith(const AnimatableValue* value) const
 {
-    RELEASE_ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: AnimatableFilterOperations::addWith()");
-    return 0;
+    ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: AnimatableFilterOperations::addWith()");
+    return defaultAddWith(this, value);
 }
 
 bool AnimatableFilterOperations::equalTo(const AnimatableValue* value) const
diff --git a/Source/core/animation/AnimatableLength.cpp b/Source/core/animation/AnimatableLength.cpp
index b26207a..886ff9b 100644
--- a/Source/core/animation/AnimatableLength.cpp
+++ b/Source/core/animation/AnimatableLength.cpp
@@ -45,8 +45,9 @@
         const CSSCalcValue* calcValue = primitiveValue->cssCalcValue();
         if (calcValue)
             return create(calcValue->expressionNode(), primitiveValue);
-        NumberUnitType unitType = primitiveUnitToNumberType(primitiveValue->primitiveType());
-        ASSERT(unitType != UnitTypeInvalid);
+        NumberUnitType unitType;
+        bool isPrimitiveLength = primitiveUnitToNumberType(primitiveValue->primitiveType(), unitType);
+        ASSERT_UNUSED(isPrimitiveLength, isPrimitiveLength);
         const double scale = CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(primitiveValue->primitiveType());
         return create(primitiveValue->getDoubleValue() * scale, unitType, primitiveValue);
     }
@@ -65,7 +66,10 @@
         const CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value);
         if (primitiveValue->cssCalcValue())
             return true;
-        return primitiveUnitToNumberType(primitiveValue->primitiveType()) != UnitTypeInvalid;
+
+        NumberUnitType unitType;
+        // Only returns true if the type is a primitive length unit.
+        return primitiveUnitToNumberType(primitiveValue->primitiveType(), unitType);
     }
     return value->isCalcValue();
 }
@@ -77,13 +81,12 @@
 
 Length AnimatableLength::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom, NumberRange range) const
 {
-    if (!m_isCalc) {
-        // Avoid creating a CSSValue in the common cases
-        if (m_unitType == UnitTypePixels)
-            return Length(clampedNumber(range) * zoom, Fixed);
-        if (m_unitType == UnitTypePercentage)
-            return Length(clampedNumber(range), Percent);
-    }
+    // Avoid creating a CSSValue in the common cases
+    if (m_unitType == UnitTypePixels)
+        return Length(clampedNumber(range) * zoom, Fixed);
+    if (m_unitType == UnitTypePercentage)
+        return Length(clampedNumber(range), Percent);
+
     return toCSSPrimitiveValue(range)->convertToLength<AnyConversion>(style, rootStyle, zoom);
 }
 
@@ -91,7 +94,7 @@
 {
     const AnimatableLength* length = toAnimatableLength(value);
     NumberUnitType type = commonUnitType(length);
-    if (type != UnitTypeInvalid)
+    if (type != UnitTypeCalc)
         return AnimatableLength::create(blend(m_number, length->m_number, fraction), type);
 
     return AnimatableLength::create(scale(1 - fraction).get(), length->scale(fraction).get());
@@ -108,7 +111,7 @@
         return takeConstRef(this);
 
     NumberUnitType type = commonUnitType(length);
-    if (type != UnitTypeInvalid)
+    if (type != UnitTypeCalc)
         return AnimatableLength::create(m_number + length->m_number, type);
 
     return AnimatableLength::create(this, length);
@@ -117,16 +120,16 @@
 bool AnimatableLength::equalTo(const AnimatableValue* value) const
 {
     const AnimatableLength* length = toAnimatableLength(value);
-    if (m_isCalc != length->m_isCalc)
+    if (m_unitType != length->m_unitType)
         return false;
-    if (m_isCalc && length->m_isCalc)
+    if (isCalc())
         return m_calcExpression == length->m_calcExpression || m_calcExpression->equals(*length->m_calcExpression);
-    return m_number == length->m_number && m_unitType == length->m_unitType;
+    return m_number == length->m_number;
 }
 
 PassRefPtr<CSSCalcExpressionNode> AnimatableLength::toCSSCalcExpressionNode() const
 {
-    if (m_isCalc)
+    if (isCalc())
         return m_calcExpression;
     return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(AllValues), m_number == trunc(m_number));
 }
@@ -143,9 +146,8 @@
 
 PassRefPtr<CSSPrimitiveValue> AnimatableLength::toCSSPrimitiveValue(NumberRange range) const
 {
-    ASSERT(m_isCalc || m_unitType != UnitTypeInvalid);
     if (!m_cachedCSSPrimitiveValue || !isCompatibleWithRange(m_cachedCSSPrimitiveValue.get(), range)) {
-        if (m_isCalc)
+        if (isCalc())
             m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, range == AllValues ? ValueRangeAll : ValueRangeNonNegative));
         else
             m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(clampedNumber(range), static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType)));
@@ -155,7 +157,7 @@
 
 PassRefPtr<AnimatableLength> AnimatableLength::scale(double factor) const
 {
-    if (m_isCalc) {
+    if (isCalc()) {
         return AnimatableLength::create(CSSCalcValue::createExpressionNode(
             m_calcExpression,
             CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(factor, CSSPrimitiveValue::CSS_NUMBER)),
@@ -164,7 +166,7 @@
     return AnimatableLength::create(m_number * factor, m_unitType);
 }
 
-AnimatableLength::NumberUnitType AnimatableLength::primitiveUnitToNumberType(unsigned short primitiveUnit)
+bool AnimatableLength::primitiveUnitToNumberType(unsigned short primitiveUnit, NumberUnitType& numberType)
 {
     switch (primitiveUnit) {
     case CSSPrimitiveValue::CSS_PX:
@@ -173,25 +175,34 @@
     case CSSPrimitiveValue::CSS_IN:
     case CSSPrimitiveValue::CSS_PT:
     case CSSPrimitiveValue::CSS_PC:
-        return UnitTypePixels;
+        numberType = UnitTypePixels;
+        return true;
     case CSSPrimitiveValue::CSS_EMS:
-        return UnitTypeFontSize;
+        numberType = UnitTypeFontSize;
+        return true;
     case CSSPrimitiveValue::CSS_EXS:
-        return UnitTypeFontXSize;
+        numberType = UnitTypeFontXSize;
+        return true;
     case CSSPrimitiveValue::CSS_REMS:
-        return UnitTypeRootFontSize;
+        numberType = UnitTypeRootFontSize;
+        return true;
     case CSSPrimitiveValue::CSS_PERCENTAGE:
-        return UnitTypePercentage;
+        numberType = UnitTypePercentage;
+        return true;
     case CSSPrimitiveValue::CSS_VW:
-        return UnitTypeViewportWidth;
+        numberType = UnitTypeViewportWidth;
+        return true;
     case CSSPrimitiveValue::CSS_VH:
-        return UnitTypeViewportHeight;
+        numberType = UnitTypeViewportHeight;
+        return true;
     case CSSPrimitiveValue::CSS_VMIN:
-        return UnitTypeViewportMin;
+        numberType = UnitTypeViewportMin;
+        return true;
     case CSSPrimitiveValue::CSS_VMAX:
-        return UnitTypeViewportMax;
+        numberType = UnitTypeViewportMax;
+        return true;
     default:
-        return UnitTypeInvalid;
+        return false;
     }
 }
 
@@ -216,7 +227,7 @@
         return CSSPrimitiveValue::CSS_VMIN;
     case UnitTypeViewportMax:
         return CSSPrimitiveValue::CSS_VMAX;
-    case UnitTypeInvalid:
+    case UnitTypeCalc:
         return CSSPrimitiveValue::CSS_UNKNOWN;
     }
     ASSERT_NOT_REACHED();
diff --git a/Source/core/animation/AnimatableLength.h b/Source/core/animation/AnimatableLength.h
index 8cf6e59..167ff84 100644
--- a/Source/core/animation/AnimatableLength.h
+++ b/Source/core/animation/AnimatableLength.h
@@ -44,11 +44,12 @@
 };
 
 // Handles animation of CSS length and percentage values including CSS calc.
-// See primitiveUnitToNumberType() for the list of supported units (with the exception of calc).
+// See primitiveUnitToNumberType() for the list of supported units.
 // If created from a CSSPrimitiveValue this class will cache it to be returned in toCSSValue().
 class AnimatableLength : public AnimatableValue {
 public:
     enum NumberUnitType {
+        UnitTypeCalc,
         UnitTypePixels,
         UnitTypePercentage,
         UnitTypeFontSize,
@@ -58,7 +59,6 @@
         UnitTypeViewportHeight,
         UnitTypeViewportMin,
         UnitTypeViewportMax,
-        UnitTypeInvalid,
     };
 
     virtual ~AnimatableLength() { }
@@ -81,15 +81,14 @@
 
 private:
     AnimatableLength(double number, NumberUnitType unitType, CSSPrimitiveValue* cssPrimitiveValue)
-        : m_isCalc(false)
-        , m_number(number)
+        : m_number(number)
         , m_unitType(unitType)
         , m_cachedCSSPrimitiveValue(cssPrimitiveValue)
     {
-        ASSERT(m_unitType != UnitTypeInvalid);
+        ASSERT(m_unitType != UnitTypeCalc);
     }
     AnimatableLength(PassRefPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue)
-        : m_isCalc(true)
+        : m_unitType(UnitTypeCalc)
         , m_calcExpression(calcExpression)
         , m_cachedCSSPrimitiveValue(cssPrimitiveValue)
     {
@@ -98,6 +97,11 @@
     virtual AnimatableType type() const OVERRIDE { return TypeLength; }
     virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
 
+    bool isCalc() const
+    {
+        return m_unitType == UnitTypeCalc;
+    }
+
     static PassRefPtr<AnimatableLength> create(const AnimatableLength* leftAddend, const AnimatableLength* rightAddend)
     {
         ASSERT(leftAddend && rightAddend);
@@ -110,10 +114,13 @@
     PassRefPtr<AnimatableLength> scale(double) const;
     double clampedNumber(NumberRange range) const
     {
-        ASSERT(!m_isCalc);
+        ASSERT(!isCalc());
         return (range == NonNegativeValues && m_number <= 0) ? 0 : m_number;
     }
-    static NumberUnitType primitiveUnitToNumberType(unsigned short primitiveUnit);
+
+    // Returns true and populates numberType, if primitiveUnit is a primitive length unit. Otherwise, returns false.
+    static bool primitiveUnitToNumberType(unsigned short primitiveUnit, NumberUnitType& numberType);
+
     static unsigned short numberTypeToPrimitiveUnit(NumberUnitType numberType);
 
     // Zero is effectively unitless, except in the case of percentage.
@@ -121,14 +128,11 @@
     // e.g. calc(100% - 100% + 1em) resolves to calc(0% + 1em), not to calc(1em)
     bool isUnitlessZero() const
     {
-        return !m_isCalc && !m_number && m_unitType != UnitTypePercentage;
+        return !isCalc() && !m_number && m_unitType != UnitTypePercentage;
     }
 
     NumberUnitType commonUnitType(const AnimatableLength* length) const
     {
-        if (m_isCalc || length->m_isCalc)
-            return UnitTypeInvalid;
-
         if (m_unitType == length->m_unitType)
             return m_unitType;
 
@@ -137,19 +141,17 @@
         if (length->isUnitlessZero())
             return m_unitType;
 
-        return UnitTypeInvalid;
+        return UnitTypeCalc;
     }
 
-    bool m_isCalc;
-
     double m_number;
-    NumberUnitType m_unitType;
+    const NumberUnitType m_unitType;
 
     RefPtr<CSSCalcExpressionNode> m_calcExpression;
 
     mutable RefPtr<CSSPrimitiveValue> m_cachedCSSPrimitiveValue;
 
-    friend class CoreAnimationAnimatableLengthTest;
+    friend class AnimationAnimatableLengthTest;
 };
 
 DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableLength, isLength());
diff --git a/Source/core/animation/AnimatableLengthTest.cpp b/Source/core/animation/AnimatableLengthTest.cpp
index 85e455c..b8772ab 100644
--- a/Source/core/animation/AnimatableLengthTest.cpp
+++ b/Source/core/animation/AnimatableLengthTest.cpp
@@ -46,7 +46,7 @@
 
 namespace WebCore {
 
-class CoreAnimationAnimatableLengthTest : public ::testing::Test {
+class AnimationAnimatableLengthTest : public ::testing::Test {
 protected:
     virtual void SetUp()
     {
@@ -90,7 +90,7 @@
     RefPtr<RenderStyle> style;
 };
 
-TEST_F(CoreAnimationAnimatableLengthTest, CanCreateFrom)
+TEST_F(AnimationAnimatableLengthTest, CanCreateFrom)
 {
     EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PX).get()));
     EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_CM).get()));
@@ -113,7 +113,7 @@
     EXPECT_FALSE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create("NaN", CSSPrimitiveValue::CSS_STRING).get()));
 }
 
-TEST_F(CoreAnimationAnimatableLengthTest, Create)
+TEST_F(AnimationAnimatableLengthTest, Create)
 {
     EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PX).get()));
     EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_CM).get()));
@@ -139,7 +139,7 @@
 }
 
 
-TEST_F(CoreAnimationAnimatableLengthTest, ToCSSValue)
+TEST_F(AnimationAnimatableLengthTest, ToCSSValue)
 {
 
     EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PX), toCSSValue);
@@ -162,7 +162,7 @@
 }
 
 
-TEST_F(CoreAnimationAnimatableLengthTest, ToLength)
+TEST_F(AnimationAnimatableLengthTest, ToLength)
 {
     EXPECT_EQ(Length(-5, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 1));
     EXPECT_EQ(Length(-15, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 3));
@@ -208,7 +208,7 @@
         create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3, NonNegativeValues));
 }
 
-TEST_F(CoreAnimationAnimatableLengthTest, Interpolate)
+TEST_F(AnimationAnimatableLengthTest, Interpolate)
 {
     RefPtr<AnimatableLength> from10px = create(10, CSSPrimitiveValue::CSS_PX);
     RefPtr<AnimatableLength> to20pxAsInches = create(20.0 / 96, CSSPrimitiveValue::CSS_IN);
@@ -276,7 +276,7 @@
         AnimatableValue::interpolate(from0percent.get(), to20rem.get(), 1.5));
 }
 
-TEST_F(CoreAnimationAnimatableLengthTest, Add)
+TEST_F(AnimationAnimatableLengthTest, Add)
 {
     EXPECT_REFV_EQ(create(10, CSSPrimitiveValue::CSS_PX),
         AnimatableValue::add(create(10, CSSPrimitiveValue::CSS_PX).get(), create(0, CSSPrimitiveValue::CSS_MM).get()));
@@ -305,7 +305,7 @@
         AnimatableValue::add(create(-10, CSSPrimitiveValue::CSS_REMS).get(), zeropercent.get()));
 }
 
-TEST_F(CoreAnimationAnimatableLengthTest, IsUnitless)
+TEST_F(AnimationAnimatableLengthTest, IsUnitless)
 {
     EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_PX)));
     EXPECT_FALSE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_PERCENTAGE)));
@@ -328,35 +328,35 @@
     EXPECT_FALSE(isUnitlessZero(create(9, CSSPrimitiveValue::CSS_VMAX)));
 }
 
-TEST_F(CoreAnimationAnimatableLengthTest, CommonUnitType)
+TEST_F(AnimationAnimatableLengthTest, CommonUnitType)
 {
     RefPtr<AnimatableLength> length10px = create(10, CSSPrimitiveValue::CSS_PX);
     EXPECT_EQ(AnimatableLength::UnitTypePixels,  commonUnitType(length10px, create(1, CSSPrimitiveValue::CSS_PX).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(length10px, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(length10px, create(3, CSSPrimitiveValue::CSS_EMS).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(length10px, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(length10px, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(3, CSSPrimitiveValue::CSS_EMS).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
 
     RefPtr<AnimatableLength> length0px = create(0, CSSPrimitiveValue::CSS_PX);
     EXPECT_EQ(AnimatableLength::UnitTypePixels,     commonUnitType(length0px, create(1, CSSPrimitiveValue::CSS_PX).get()));
     EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0px, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
     EXPECT_EQ(AnimatableLength::UnitTypeFontSize,   commonUnitType(length0px, create(3, CSSPrimitiveValue::CSS_EMS).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid,    commonUnitType(length0px, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc,    commonUnitType(length0px, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
     EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0px, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
 
     RefPtr<AnimatableLength> length0percent = create(0, CSSPrimitiveValue::CSS_PERCENTAGE);
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid,    commonUnitType(length0percent, create(1, CSSPrimitiveValue::CSS_PX).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc,    commonUnitType(length0percent, create(1, CSSPrimitiveValue::CSS_PX).get()));
     EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0percent, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid,    commonUnitType(length0percent, create(3, CSSPrimitiveValue::CSS_EMS).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid,    commonUnitType(length0percent, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc,    commonUnitType(length0percent, create(3, CSSPrimitiveValue::CSS_EMS).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc,    commonUnitType(length0percent, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
     EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0percent, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
 
     RefPtr<AnimatableLength> lengthCalc = create(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM);
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(lengthCalc, create(1, CSSPrimitiveValue::CSS_PX).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(lengthCalc, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(lengthCalc, create(3, CSSPrimitiveValue::CSS_EMS).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(lengthCalc, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
-    EXPECT_EQ(AnimatableLength::UnitTypeInvalid, commonUnitType(lengthCalc, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(1, CSSPrimitiveValue::CSS_PX).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(3, CSSPrimitiveValue::CSS_EMS).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+    EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
 }
 
 } // namespace WebCore
diff --git a/Source/core/animation/AnimatableNeutralTest.cpp b/Source/core/animation/AnimatableNeutralTest.cpp
index cfa7a84..dbf685a 100644
--- a/Source/core/animation/AnimatableNeutralTest.cpp
+++ b/Source/core/animation/AnimatableNeutralTest.cpp
@@ -40,12 +40,12 @@
 
 namespace {
 
-TEST(CoreAnimationAnimatableNeutralTest, Create)
+TEST(AnimationAnimatableNeutralTest, Create)
 {
     EXPECT_TRUE(AnimatableValue::neutralValue());
 }
 
-TEST(CoreAnimationAnimatableNeutralTest, Add)
+TEST(AnimationAnimatableNeutralTest, Add)
 {
     RefPtr<CSSValue> cssValue = CSSArrayFunctionValue::create();
     RefPtr<AnimatableValue> animatableUnknown = AnimatableUnknown::create(cssValue);
diff --git a/Source/core/animation/AnimatableSVGLength.cpp b/Source/core/animation/AnimatableSVGLength.cpp
index bbf13e3..97f4158 100644
--- a/Source/core/animation/AnimatableSVGLength.cpp
+++ b/Source/core/animation/AnimatableSVGLength.cpp
@@ -42,8 +42,8 @@
 
 PassRefPtr<AnimatableValue> AnimatableSVGLength::addWith(const AnimatableValue* value) const
 {
-    RELEASE_ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: AnimatableSVGLength::addWith()");
-    return 0;
+    ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: AnimatableSVGLength::addWith()");
+    return defaultAddWith(this, value);
 }
 
 bool AnimatableSVGLength::equalTo(const AnimatableValue* value) const
diff --git a/Source/core/animation/AnimatableShapeValue.h b/Source/core/animation/AnimatableShapeValue.h
index 696a376..1d5382b 100644
--- a/Source/core/animation/AnimatableShapeValue.h
+++ b/Source/core/animation/AnimatableShapeValue.h
@@ -52,6 +52,7 @@
     AnimatableShapeValue(ShapeValue* shape)
         : m_shape(shape)
     {
+        ASSERT(m_shape);
     }
     virtual AnimatableType type() const OVERRIDE { return TypeShapeValue; }
     virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
diff --git a/Source/core/animation/AnimatableStrokeDasharrayList.cpp b/Source/core/animation/AnimatableStrokeDasharrayList.cpp
index 7feff52..b8951cc 100644
--- a/Source/core/animation/AnimatableStrokeDasharrayList.cpp
+++ b/Source/core/animation/AnimatableStrokeDasharrayList.cpp
@@ -66,11 +66,11 @@
     if (from.isEmpty() && to.isEmpty())
         return takeConstRef(this);
     if (from.isEmpty() || to.isEmpty()) {
-        DEFINE_STATIC_LOCAL(RefPtr<AnimatableSVGLength>, zeroPixels, ());
+        DEFINE_STATIC_REF(AnimatableSVGLength, zeroPixels, 0);
         if (!zeroPixels) {
             SVGLength length;
             length.newValueSpecifiedUnits(LengthTypePX, 0, IGNORE_EXCEPTION);
-            zeroPixels = AnimatableSVGLength::create(length);
+            zeroPixels = AnimatableSVGLength::create(length).leakRef();
         }
         if (from.isEmpty()) {
             from.append(zeroPixels);
diff --git a/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp b/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
index b688075..6a2756d 100644
--- a/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
+++ b/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
@@ -39,7 +39,7 @@
 
 namespace {
 
-TEST(CoreAnimationAnimatableStrokeDasharrayListTest, EqualTo)
+TEST(AnimationAnimatableStrokeDasharrayListTest, EqualTo)
 {
     Vector<SVGLength> vectorA(4);
     Vector<SVGLength> vectorB(4);
@@ -47,8 +47,8 @@
     RefPtr<AnimatableStrokeDasharrayList> listB = AnimatableStrokeDasharrayList::create(vectorB);
     EXPECT_TRUE(listA->equals(listB.get()));
 
-    TrackExceptionState es;
-    vectorB[3].newValueSpecifiedUnits(LengthTypePX, 50, es);
+    TrackExceptionState exceptionState;
+    vectorB[3].newValueSpecifiedUnits(LengthTypePX, 50, exceptionState);
     listB = AnimatableStrokeDasharrayList::create(vectorB);
     EXPECT_FALSE(listA->equals(listB.get()));
 
diff --git a/Source/core/animation/AnimatableUnknownTest.cpp b/Source/core/animation/AnimatableUnknownTest.cpp
index 2407300..5ca1760 100644
--- a/Source/core/animation/AnimatableUnknownTest.cpp
+++ b/Source/core/animation/AnimatableUnknownTest.cpp
@@ -40,7 +40,7 @@
 
 namespace {
 
-class CoreAnimationAnimatableUnknownTest : public ::testing::Test {
+class AnimationAnimatableUnknownTest : public ::testing::Test {
 protected:
     virtual void SetUp()
     {
@@ -58,17 +58,17 @@
     RefPtr<AnimatableValue> otherAnimatableUnknown;
 };
 
-TEST_F(CoreAnimationAnimatableUnknownTest, Create)
+TEST_F(AnimationAnimatableUnknownTest, Create)
 {
     EXPECT_TRUE(animatableUnknown);
 }
 
-TEST_F(CoreAnimationAnimatableUnknownTest, ToCSSValue)
+TEST_F(AnimationAnimatableUnknownTest, ToCSSValue)
 {
     EXPECT_EQ(cssValue, toAnimatableUnknown(animatableUnknown.get())->toCSSValue());
 }
 
-TEST_F(CoreAnimationAnimatableUnknownTest, Interpolate)
+TEST_F(AnimationAnimatableUnknownTest, Interpolate)
 {
     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());
@@ -83,7 +83,7 @@
     EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 1).get())->toCSSValue());
 }
 
-TEST_F(CoreAnimationAnimatableUnknownTest, Add)
+TEST_F(AnimationAnimatableUnknownTest, Add)
 {
     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.cpp b/Source/core/animation/AnimatableValue.cpp
index 5c0d57b..1c9d175 100644
--- a/Source/core/animation/AnimatableValue.cpp
+++ b/Source/core/animation/AnimatableValue.cpp
@@ -31,13 +31,14 @@
 #include "config.h"
 #include "core/animation/AnimatableValue.h"
 #include "core/animation/AnimatableNeutral.h"
+#include "wtf/StdLibExtras.h"
 #include <algorithm>
 
 namespace WebCore {
 
 const AnimatableValue* AnimatableValue::neutralValue()
 {
-    static AnimatableNeutral* neutralSentinelValue = AnimatableNeutral::create().leakRef();
+    DEFINE_STATIC_REF(AnimatableNeutral, neutralSentinelValue, (AnimatableNeutral::create()));
     return neutralSentinelValue;
 }
 
diff --git a/Source/core/animation/AnimatableValueTestHelperTest.cpp b/Source/core/animation/AnimatableValueTestHelperTest.cpp
index 13d4b83..fad1a5a 100644
--- a/Source/core/animation/AnimatableValueTestHelperTest.cpp
+++ b/Source/core/animation/AnimatableValueTestHelperTest.cpp
@@ -48,7 +48,7 @@
 
 namespace {
 
-class CoreAnimationAnimatableValueTestHelperTest : public ::testing::Test {
+class AnimationAnimatableValueTestHelperTest : public ::testing::Test {
 protected:
     ::std::string PrintToString(PassRefPtr<AnimatableValue> animValue)
     {
@@ -61,7 +61,7 @@
     }
 };
 
-TEST_F(CoreAnimationAnimatableValueTestHelperTest, PrintTo)
+TEST_F(AnimationAnimatableValueTestHelperTest, PrintTo)
 {
     EXPECT_THAT(
         PrintToString(AnimatableClipPathOperation::create(ShapeClipPathOperation::create(BasicShapeCircle::create().get()).get())),
diff --git a/Source/core/animation/Animation.cpp b/Source/core/animation/Animation.cpp
index 73038bb..489c60c 100644
--- a/Source/core/animation/Animation.cpp
+++ b/Source/core/animation/Animation.cpp
@@ -32,6 +32,8 @@
 #include "core/animation/Animation.h"
 
 #include "core/animation/ActiveAnimations.h"
+#include "core/animation/CompositorAnimations.h"
+#include "core/animation/KeyframeAnimationEffect.h"
 #include "core/animation/Player.h"
 #include "core/dom/Element.h"
 
@@ -51,8 +53,16 @@
 {
 }
 
+void Animation::didAttach()
+{
+    if (m_target)
+        m_target->ensureActiveAnimations()->players().add(player());
+}
+
 void Animation::willDetach()
 {
+    if (m_target)
+        m_target->activeAnimations()->players().remove(player());
     if (m_activeInAnimationStack)
         clearEffects();
 }
@@ -64,18 +74,20 @@
 
 bool Animation::applyEffects(bool previouslyInEffect)
 {
-    ASSERT(player());
     if (!m_target || !m_effect)
         return false;
 
-    if (!previouslyInEffect) {
+    if (player() && !previouslyInEffect) {
         ensureAnimationStack(m_target.get()).add(this);
         m_activeInAnimationStack = true;
     }
 
     m_compositableValues = m_effect->sample(currentIteration(), timeFraction());
-    m_target->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-    return true;
+    if (player()) {
+        m_target->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+        return true;
+    }
+    return false;
 }
 
 void Animation::clearEffects()
@@ -83,6 +95,7 @@
     ASSERT(player());
     ASSERT(m_activeInAnimationStack);
     ensureAnimationStack(m_target.get()).remove(this);
+    cancelAnimationOnCompositor();
     m_activeInAnimationStack = false;
     m_compositableValues.clear();
     m_target->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
@@ -103,12 +116,19 @@
     return false;
 }
 
-double Animation::calculateTimeToEffectChange(double inheritedTime, double activeTime, Phase phase) const
+double Animation::calculateTimeToEffectChange(double localTime, double timeToNextIteration) const
 {
-    switch (phase) {
+    const double activeStartTime = startTime() + specified().startDelay;
+    switch (phase()) {
     case PhaseBefore:
-        return activeTime - inheritedTime;
+        return activeStartTime - localTime;
     case PhaseActive:
+        if (hasActiveAnimationsOnCompositor()) {
+            // Need service to apply fill / fire events.
+            const double activeEndTime = activeStartTime + activeDuration();
+            ASSERT(isNull(timeToNextIteration) || timeToNextIteration <= (activeEndTime - localTime));
+            return isNull(timeToNextIteration) ? activeEndTime - localTime : timeToNextIteration;
+        }
         return 0;
     case PhaseAfter:
         // If this Animation is still in effect then it will need to update
@@ -122,4 +142,59 @@
     }
 }
 
+bool Animation::isCandidateForAnimationOnCompositor() const
+{
+    if (!effect() || !m_target)
+        return false;
+    return CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(specified(), *effect());
+}
+
+bool Animation::maybeStartAnimationOnCompositor()
+{
+    ASSERT(!hasActiveAnimationsOnCompositor());
+    if (!isCandidateForAnimationOnCompositor())
+        return false;
+    if (!CompositorAnimations::instance()->canStartAnimationOnCompositor(*m_target.get()))
+        return false;
+    if (!CompositorAnimations::instance()->startAnimationOnCompositor(*m_target.get(), specified(), *effect(), m_compositorAnimationIds))
+        return false;
+    ASSERT(!m_compositorAnimationIds.isEmpty());
+    return true;
+}
+
+bool Animation::hasActiveAnimationsOnCompositor() const
+{
+    return !m_compositorAnimationIds.isEmpty();
+}
+
+bool Animation::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
+{
+    return hasActiveAnimationsOnCompositor() && affects(property);
+}
+
+bool Animation::affects(CSSPropertyID property) const
+{
+    return m_effect && m_effect->affects(property);
+}
+
+void Animation::cancelAnimationOnCompositor()
+{
+    if (!hasActiveAnimationsOnCompositor())
+        return;
+    if (!m_target || !m_target->renderer())
+        return;
+    for (size_t i = 0; i < m_compositorAnimationIds.size(); ++i)
+        CompositorAnimations::instance()->cancelAnimationOnCompositor(*m_target.get(), m_compositorAnimationIds[i]);
+    m_compositorAnimationIds.clear();
+}
+
+void Animation::pauseAnimationForTestingOnCompositor(double pauseTime)
+{
+    ASSERT(hasActiveAnimationsOnCompositor());
+    if (!m_target || !m_target->renderer())
+        return;
+    for (size_t i = 0; i < m_compositorAnimationIds.size(); ++i)
+        CompositorAnimations::instance()->pauseAnimationForTestingOnCompositor(*m_target.get(), m_compositorAnimationIds[i], pauseTime);
+}
+
 } // namespace WebCore
diff --git a/Source/core/animation/Animation.h b/Source/core/animation/Animation.h
index 75e89a9..74da933 100644
--- a/Source/core/animation/Animation.h
+++ b/Source/core/animation/Animation.h
@@ -45,6 +45,7 @@
     enum Priority { DefaultPriority, TransitionPriority };
 
     static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority = DefaultPriority, PassOwnPtr<EventDelegate> = nullptr);
+    virtual bool isAnimation() const OVERRIDE FINAL { return true; }
 
     const AnimationEffect::CompositableValueMap* compositableValues() const
     {
@@ -52,16 +53,27 @@
         return m_compositableValues.get();
     }
 
+    bool affects(CSSPropertyID) const;
     const AnimationEffect* effect() const { return m_effect.get(); }
     Priority priority() const { return m_priority; }
+    Element* target() { return m_target.get(); }
+
+    bool isCandidateForAnimationOnCompositor() const;
+    // Must only be called once and assumes to be part of a player without a start time.
+    bool maybeStartAnimationOnCompositor();
+    bool hasActiveAnimationsOnCompositor() const;
+    bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
+    void cancelAnimationOnCompositor();
+    void pauseAnimationForTestingOnCompositor(double pauseTime);
 
 protected:
     // Returns whether style recalc was triggered.
     virtual bool applyEffects(bool previouslyInEffect);
     virtual void clearEffects();
     virtual bool updateChildrenAndEffects() const OVERRIDE FINAL;
+    virtual void didAttach() OVERRIDE FINAL;
     virtual void willDetach() OVERRIDE FINAL;
-    virtual double calculateTimeToEffectChange(double inheritedTime, double activeTime, Phase) const OVERRIDE FINAL;
+    virtual double calculateTimeToEffectChange(double inheritedTime, double timeToNextIteration) const OVERRIDE FINAL;
 
 private:
     Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority, PassOwnPtr<EventDelegate>);
@@ -73,8 +85,14 @@
     OwnPtr<AnimationEffect::CompositableValueMap> m_compositableValues;
 
     Priority m_priority;
+
+    Vector<int> m_compositorAnimationIds;
+
+    friend class CSSAnimations;
 };
 
+DEFINE_TYPE_CASTS(Animation, TimedItem, timedItem, timedItem->isAnimation(), timedItem.isAnimation());
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/animation/AnimationClock.h b/Source/core/animation/AnimationClock.h
index c2585db..f6a2cdb 100644
--- a/Source/core/animation/AnimationClock.h
+++ b/Source/core/animation/AnimationClock.h
@@ -45,8 +45,8 @@
 
     void updateTime(double time)
     {
-        ASSERT(m_time <= time);
-        m_time = time;
+        if (time > m_time)
+            m_time = time;
         m_frozen = true;
     }
 
diff --git a/Source/core/animation/AnimationClockTest.cpp b/Source/core/animation/AnimationClockTest.cpp
index ef28f28..248da7b 100644
--- a/Source/core/animation/AnimationClockTest.cpp
+++ b/Source/core/animation/AnimationClockTest.cpp
@@ -38,7 +38,7 @@
 
 namespace {
 
-class CoreAnimationAnimationClockTest : public ::testing::Test {
+class AnimationAnimationClockTest : public ::testing::Test {
 protected:
     virtual void SetUp()
     {
@@ -55,9 +55,9 @@
     OwnPtr<AnimationClock> animationClock;
 };
 
-double CoreAnimationAnimationClockTest::mockTime;
+double AnimationAnimationClockTest::mockTime;
 
-TEST_F(CoreAnimationAnimationClockTest, CurrentTime)
+TEST_F(AnimationAnimationClockTest, CurrentTime)
 {
     EXPECT_EQ(200, animationClock->currentTime());
     EXPECT_EQ(200, animationClock->currentTime());
@@ -66,7 +66,7 @@
     EXPECT_EQ(201, animationClock->currentTime());
 }
 
-TEST_F(CoreAnimationAnimationClockTest, UpdateTime)
+TEST_F(AnimationAnimationClockTest, UpdateTime)
 {
     animationClock->updateTime(100);
     EXPECT_EQ(100, animationClock->currentTime());
diff --git a/Source/core/animation/AnimationEffect.h b/Source/core/animation/AnimationEffect.h
index 89b3494..6c39478 100644
--- a/Source/core/animation/AnimationEffect.h
+++ b/Source/core/animation/AnimationEffect.h
@@ -59,6 +59,9 @@
     virtual ~AnimationEffect() { }
     typedef HashMap<CSSPropertyID, RefPtr<CompositableValue> > CompositableValueMap;
     virtual PassOwnPtr<CompositableValueMap> sample(int iteration, double fraction) const = 0;
+
+    virtual bool affects(CSSPropertyID) { return false; };
+    virtual bool isKeyframeAnimationEffect() const { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/animation/AnimationStack.cpp b/Source/core/animation/AnimationStack.cpp
index c48e914..e849c95 100644
--- a/Source/core/animation/AnimationStack.cpp
+++ b/Source/core/animation/AnimationStack.cpp
@@ -47,6 +47,24 @@
 
 } // namespace
 
+bool AnimationStack::affects(CSSPropertyID property) const
+{
+    for (size_t i = 0; i < m_activeAnimations.size(); ++i) {
+        if (m_activeAnimations[i]->affects(property))
+            return true;
+    }
+    return false;
+}
+
+bool AnimationStack::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
+{
+    for (size_t i = 0; i < m_activeAnimations.size(); ++i) {
+        if (m_activeAnimations[i]->hasActiveAnimationsOnCompositor(property))
+            return true;
+    }
+    return false;
+}
+
 AnimationEffect::CompositableValueMap AnimationStack::compositableValues(const AnimationStack* animationStack, const Vector<InertAnimation*>* newAnimations, const HashSet<const Player*>* cancelledPlayers, Animation::Priority priority)
 {
     AnimationEffect::CompositableValueMap result;
diff --git a/Source/core/animation/AnimationStack.h b/Source/core/animation/AnimationStack.h
index fe1ffc5..e7ad32f 100644
--- a/Source/core/animation/AnimationStack.h
+++ b/Source/core/animation/AnimationStack.h
@@ -51,6 +51,8 @@
         m_activeAnimations.remove(position);
     }
     bool isEmpty() const { return m_activeAnimations.isEmpty(); }
+    bool affects(CSSPropertyID) const;
+    bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
     static AnimationEffect::CompositableValueMap compositableValues(const AnimationStack*, const Vector<InertAnimation*>* newAnimations, const HashSet<const Player*>* cancelledPlayers, Animation::Priority);
 
 private:
diff --git a/Source/core/animation/CompositorAnimations.cpp b/Source/core/animation/CompositorAnimations.cpp
index 505e294..59f1435 100644
--- a/Source/core/animation/CompositorAnimations.cpp
+++ b/Source/core/animation/CompositorAnimations.cpp
@@ -31,6 +31,12 @@
 #include "config.h"
 #include "core/animation/CompositorAnimations.h"
 
+#include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
+#include "core/animation/AnimatableTransform.h"
+#include "core/animation/AnimatableValue.h"
+#include "core/animation/CompositorAnimationsImpl.h"
+#include "core/platform/animation/AnimationTranslationUtil.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/RenderLayer.h"
@@ -38,33 +44,506 @@
 #include "public/platform/Platform.h"
 #include "public/platform/WebAnimation.h"
 #include "public/platform/WebCompositorSupport.h"
+#include "public/platform/WebFilterAnimationCurve.h"
+#include "public/platform/WebFilterKeyframe.h"
 #include "public/platform/WebFloatAnimationCurve.h"
 #include "public/platform/WebFloatKeyframe.h"
+#include "public/platform/WebTransformAnimationCurve.h"
+#include "public/platform/WebTransformKeyframe.h"
+
+#include <algorithm>
+#include <cmath>
 
 namespace WebCore {
 
-bool CompositorAnimations::isCandidateForCompositorAnimation(const Timing& timing, const AnimationEffect* effect)
+namespace {
+
+void getKeyframeValuesForProperty(const KeyframeAnimationEffect* effect, CSSPropertyID id, double scale, bool reverse, KeyframeVector& values)
 {
-    // FIXME: Implement.
-    ASSERT_NOT_REACHED();
+    ASSERT(values.isEmpty());
+    const KeyframeVector& group = effect->getPropertySpecificKeyframes(id);
+
+    if (reverse) {
+        for (size_t i = group.size(); i--;) {
+            double offset = (1 - group[i]->offset()) * scale;
+            values.append(group[i]->cloneWithOffset(offset));
+        }
+    } else {
+        for (size_t i = 0; i < group.size(); ++i) {
+            double offset = group[i]->offset() * scale;
+            values.append(group[i]->cloneWithOffset(offset));
+        }
+    }
+}
+
+}
+
+// -----------------------------------------------------------------------
+// TimingFunctionReverser methods
+// -----------------------------------------------------------------------
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const LinearTimingFunction* timefunc)
+{
+    return const_cast<LinearTimingFunction*>(timefunc);
+}
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const CubicBezierTimingFunction* timefunc)
+{
+    switch (timefunc->subType()) {
+    case CubicBezierTimingFunction::EaseIn:
+        return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+    case CubicBezierTimingFunction::EaseOut:
+        return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    case CubicBezierTimingFunction::EaseInOut:
+        return const_cast<CubicBezierTimingFunction*>(timefunc);
+    case CubicBezierTimingFunction::Ease: // Ease is not symmetrical
+    case CubicBezierTimingFunction::Custom:
+        return CubicBezierTimingFunction::create(1 - timefunc->x2(), 1 - timefunc->y2(), 1 - timefunc->x1(), 1 - timefunc->y1());
+    default:
+        ASSERT_NOT_REACHED();
+        return PassRefPtr<TimingFunction>();
+    }
+}
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const ChainedTimingFunction* timefunc)
+{
+    RefPtr<ChainedTimingFunction> reversed = ChainedTimingFunction::create();
+    for (size_t i = 0; i < timefunc->m_segments.size(); i++) {
+        size_t index = timefunc->m_segments.size() - i - 1;
+
+        RefPtr<TimingFunction> rtf = reverse(timefunc->m_segments[index].m_timingFunction.get());
+        reversed->appendSegment(1 - timefunc->m_segments[index].m_min, rtf.get());
+    }
+    return reversed;
+}
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const TimingFunction* timefunc)
+{
+    switch (timefunc->type()) {
+    case TimingFunction::LinearFunction: {
+        const LinearTimingFunction* linear = toLinearTimingFunction(timefunc);
+        return reverse(linear);
+    }
+    case TimingFunction::CubicBezierFunction: {
+        const CubicBezierTimingFunction* cubic = toCubicBezierTimingFunction(timefunc);
+        return reverse(cubic);
+    }
+    case TimingFunction::ChainedFunction: {
+        const ChainedTimingFunction* chained = toChainedTimingFunction(timefunc);
+        return reverse(chained);
+    }
+
+    // Steps function can not be reversed.
+    case TimingFunction::StepsFunction:
+    default:
+        ASSERT_NOT_REACHED();
+        return PassRefPtr<TimingFunction>();
+    }
+}
+
+// -----------------------------------------------------------------------
+// CompositorAnimations public API
+// -----------------------------------------------------------------------
+
+bool CompositorAnimations::isCandidateForAnimationOnCompositor(const Timing& timing, const AnimationEffect& effect)
+{
+    const KeyframeAnimationEffect& keyframeEffect = *toKeyframeAnimationEffect(&effect);
+
+    return CompositorAnimationsImpl::isCandidateForCompositor(keyframeEffect)
+        && CompositorAnimationsImpl::isCandidateForCompositor(timing, keyframeEffect.getFrames());
+}
+
+bool CompositorAnimations::canStartAnimationOnCompositor(const Element& element)
+{
+    return element.renderer() && element.renderer()->compositingState() == PaintsIntoOwnBacking;
+}
+
+bool CompositorAnimations::startAnimationOnCompositor(const Element& element, const Timing& timing, const AnimationEffect& effect, Vector<int>& startedAnimationIds)
+{
+    ASSERT(startedAnimationIds.isEmpty());
+    ASSERT(isCandidateForAnimationOnCompositor(timing, effect));
+    ASSERT(canStartAnimationOnCompositor(element));
+
+    const KeyframeAnimationEffect& keyframeEffect = *toKeyframeAnimationEffect(&effect);
+
+    RenderLayer* layer = toRenderBoxModelObject(element.renderer())->layer();
+    ASSERT(layer);
+
+    Vector<OwnPtr<blink::WebAnimation> > animations;
+    CompositorAnimationsImpl::getAnimationOnCompositor(timing, keyframeEffect, animations);
+    for (size_t i = 0; i < animations.size(); ++i) {
+        int id = animations[i]->id();
+        if (!layer->compositedLayerMapping()->mainGraphicsLayer()->addAnimation(animations[i].release())) {
+            // FIXME: We should know ahead of time whether these animations can be started.
+            for (size_t j = 0; j < startedAnimationIds.size(); ++j)
+                cancelAnimationOnCompositor(element, startedAnimationIds[j]);
+            startedAnimationIds.clear();
+            return false;
+        }
+        startedAnimationIds.append(id);
+    }
+    return true;
+}
+
+void CompositorAnimations::cancelAnimationOnCompositor(const Element& element, int id)
+{
+    if (!element.renderer() || element.renderer()->compositingState() != PaintsIntoOwnBacking)
+        return;
+    toRenderBoxModelObject(element.renderer())->layer()->compositedLayerMapping()->mainGraphicsLayer()->removeAnimation(id);
+}
+
+void CompositorAnimations::pauseAnimationForTestingOnCompositor(const Element& element, int id, double pauseTime)
+{
+    ASSERT(canStartAnimationOnCompositor(element));
+    toRenderBoxModelObject(element.renderer())->layer()->compositedLayerMapping()->mainGraphicsLayer()->pauseAnimation(id, pauseTime);
+}
+
+bool CompositorAnimationsImpl::isCandidateForCompositor(const Keyframe& keyframe)
+{
+    // Only replace mode can be accelerated
+    if (keyframe.composite() != AnimationEffect::CompositeReplace)
+        return false;
+    // Check all the properties can be accelerated
+    const PropertySet properties = keyframe.properties();
+    for (PropertySet::const_iterator it = properties.begin(); it != properties.end(); ++it) {
+        switch (*it) {
+        case CSSPropertyOpacity:
+            continue;
+        case CSSPropertyWebkitTransform:
+            if (toAnimatableTransform(keyframe.propertyValue(CSSPropertyWebkitTransform))->transformOperations().dependsOnBoxSize())
+                return false;
+            continue;
+        case CSSPropertyWebkitFilter: {
+            const FilterOperations& operations = toAnimatableFilterOperations(keyframe.propertyValue(CSSPropertyWebkitFilter))->operations();
+            if (operations.hasFilterThatMovesPixels())
+                return false;
+            for (size_t i = 0; i < operations.size(); i++) {
+                const FilterOperation& op = *operations.at(i);
+                if (op.type() == FilterOperation::VALIDATED_CUSTOM || op.type() == FilterOperation::CUSTOM)
+                    return false;
+            }
+            continue;
+        }
+        default:
+            return false;
+        }
+    }
+    return true;
+}
+
+bool CompositorAnimationsImpl::isCandidateForCompositor(const KeyframeAnimationEffect& effect)
+{
+    const KeyframeAnimationEffect::KeyframeVector frames = effect.getFrames();
+    for (size_t i = 0; i < frames.size(); ++i) {
+        if (!isCandidateForCompositor(*frames[i].get()))
+            return false;
+    }
+    return true;
+}
+
+bool CompositorAnimationsImpl::isCandidateForCompositor(const Timing& timing, const KeyframeAnimationEffect::KeyframeVector& frames)
+{
+    CompositorTiming out;
+    if (!convertTimingForCompositor(timing, out))
+        return false;
+
+    return isCandidateForCompositor(*timing.timingFunction.get(), &frames);
+}
+
+bool CompositorAnimationsImpl::isCandidateForCompositor(const TimingFunction& timingFunction, const KeyframeAnimationEffect::KeyframeVector* frames, bool isNestedCall)
+{
+    switch (timingFunction.type()) {
+    case TimingFunction::LinearFunction:
+        return true;
+
+    case TimingFunction::CubicBezierFunction:
+        // Can have a cubic if we don't have to split it (IE only have two frames).
+        if (!(isNestedCall || (frames && frames->size() == 2)))
+            return false;
+
+        ASSERT(!frames || (frames->at(0)->offset() == 0.0 && frames->at(1)->offset() == 1.0));
+
+        return true;
+
+    case TimingFunction::StepsFunction:
+        return false;
+
+    case TimingFunction::ChainedFunction: {
+        // Currently we only support chained segments in the form the CSS code
+        // generates. These chained segments are only one level deep and have
+        // one timing function per frame.
+        const ChainedTimingFunction& chained = toChainedTimingFunction(timingFunction);
+        if (isNestedCall)
+            return false;
+
+        if (!chained.m_segments.size())
+            return false;
+
+        if (frames->size() != chained.m_segments.size() + 1)
+            return false;
+
+        for (size_t timeIndex = 0; timeIndex < chained.m_segments.size(); timeIndex++) {
+            const ChainedTimingFunction::Segment& segment = chained.m_segments[timeIndex];
+
+            if (frames->at(timeIndex)->offset() != segment.m_min || frames->at(timeIndex + 1)->offset() != segment.m_max)
+                return false;
+
+            if (!isCandidateForCompositor(*segment.m_timingFunction.get(), 0, true))
+                return false;
+        }
+        return true;
+    }
+    default:
+        ASSERT_NOT_REACHED();
+    };
     return false;
 }
 
-bool CompositorAnimations::canStartCompositorAnimation(const Element* element)
+bool CompositorAnimationsImpl::convertTimingForCompositor(const Timing& timing, CompositorTiming& out)
 {
-    return element->renderer() && element->renderer()->compositingState() == PaintsIntoOwnBacking;
+    timing.assertValid();
+
+    // FIXME: Support positive startDelay
+    if (timing.startDelay > 0.0)
+        return false;
+
+    // All fill modes are supported (the calling code handles them).
+
+    // FIXME: Support non-zero iteration start.
+    if (timing.iterationStart)
+        return false;
+
+    // FIXME: Compositor only supports positive, integer iteration counts.
+    // Zero iterations could be converted, but silly.
+    if ((std::floor(timing.iterationCount) != timing.iterationCount) || timing.iterationCount <= 0)
+        return false;
+
+    if (!timing.iterationDuration)
+        return false;
+
+    // FIXME: Support other playback rates
+    if (timing.playbackRate != 1)
+        return false;
+
+    // All directions are supported.
+
+    // Now attempt an actual conversion
+    out.scaledDuration = timing.iterationDuration;
+    ASSERT(out.scaledDuration > 0);
+
+    double scaledStartDelay = timing.startDelay;
+    ASSERT(scaledStartDelay <= 0);
+
+    int skippedIterations = std::floor(std::abs(scaledStartDelay) / out.scaledDuration);
+    ASSERT(skippedIterations >= 0);
+    if (skippedIterations >= timing.iterationCount)
+        return false;
+
+    out.reverse = (timing.direction == Timing::PlaybackDirectionReverse
+        || timing.direction == Timing::PlaybackDirectionAlternateReverse);
+    out.alternate = (timing.direction == Timing::PlaybackDirectionAlternate
+        || timing.direction == Timing::PlaybackDirectionAlternateReverse);
+    if (out.alternate && (skippedIterations % 2))
+        out.reverse = !out.reverse;
+
+    if (!std::isfinite(timing.iterationCount)) {
+        out.adjustedIterationCount = -1;
+    } else {
+        out.adjustedIterationCount = std::floor(timing.iterationCount) - skippedIterations;
+        ASSERT(out.adjustedIterationCount > 0);
+    }
+
+    out.scaledTimeOffset = scaledStartDelay + skippedIterations * out.scaledDuration;
+    ASSERT(out.scaledTimeOffset <= 0);
+    return true;
 }
 
-void CompositorAnimations::startCompositorAnimation(const Element* element, const Timing&, const AnimationEffect*, Vector<int>& startedAnimationIds)
+namespace {
+
+template<typename PlatformAnimationKeyframeType>
+static PassOwnPtr<PlatformAnimationKeyframeType> createPlatformKeyframe(double offset, const AnimatableValue&)
 {
-    // FIXME: Implement.
+    // Only the specialized versions of this templated function (found in
+    // the cpp file) should ever be called.
+    // FIXME: COMPILE_ASSERT(false, CompositorAnimationsNonSpecializedCreateKeyframeShouldNeverBeUsed);
     ASSERT_NOT_REACHED();
 }
 
-void CompositorAnimations::cancelCompositorAnimation(const Element* element, int id)
+template<>
+PassOwnPtr<blink::WebFloatKeyframe> createPlatformKeyframe<blink::WebFloatKeyframe>(
+    double offset, const AnimatableValue& value)
 {
-    // FIXME: Implement.
-    ASSERT_NOT_REACHED();
+    const AnimatableDouble* d = toAnimatableDouble(&value);
+    return adoptPtr(new blink::WebFloatKeyframe(offset, d->toDouble()));
 }
 
+template<>
+PassOwnPtr<blink::WebTransformKeyframe> createPlatformKeyframe<blink::WebTransformKeyframe>(
+    double offset, const AnimatableValue& value)
+{
+    const AnimatableTransform* t = toAnimatableTransform(&value);
+    blink::WebTransformOperations* ops = blink::Platform::current()->compositorSupport()->createTransformOperations();
+    toWebTransformOperations(t->transformOperations(), FloatSize(), ops);
+    return adoptPtr(new blink::WebTransformKeyframe(offset, adoptPtr(ops)));
 }
+
+template<>
+PassOwnPtr<blink::WebFilterKeyframe> createPlatformKeyframe<blink::WebFilterKeyframe>(
+    double offset, const AnimatableValue& value)
+{
+    const AnimatableFilterOperations* f = toAnimatableFilterOperations(&value);
+    blink::WebFilterOperations* operations = blink::Platform::current()->compositorSupport()->createFilterOperations();
+    bool converted = toWebFilterOperations(f->operations(), operations);
+    ASSERT_UNUSED(converted, converted);
+    return adoptPtr(new blink::WebFilterKeyframe(offset, adoptPtr(operations)));
+}
+
+template<typename PlatformAnimationCurveType, typename PlatformAnimationKeyframeType>
+void addKeyframeWithTimingFunction(PlatformAnimationCurveType& curve, const PlatformAnimationKeyframeType& keyframe, const TimingFunction* timingFunction)
+{
+    if (!timingFunction) {
+        curve.add(keyframe);
+        return;
+    }
+
+    switch (timingFunction->type()) {
+    case TimingFunction::LinearFunction:
+        curve.add(keyframe, blink::WebAnimationCurve::TimingFunctionTypeLinear);
+        return;
+
+    case TimingFunction::CubicBezierFunction: {
+        const CubicBezierTimingFunction* cubic = toCubicBezierTimingFunction(timingFunction);
+
+        if (cubic->subType() == CubicBezierTimingFunction::Custom) {
+            curve.add(keyframe, cubic->x1(), cubic->y1(), cubic->x2(), cubic->y2());
+        } else {
+
+            blink::WebAnimationCurve::TimingFunctionType easeType;
+            switch (cubic->subType()) {
+            case CubicBezierTimingFunction::Ease:
+                easeType = blink::WebAnimationCurve::TimingFunctionTypeEase;
+                break;
+            case CubicBezierTimingFunction::EaseIn:
+                easeType = blink::WebAnimationCurve::TimingFunctionTypeEaseIn;
+                break;
+            case CubicBezierTimingFunction::EaseOut:
+                easeType = blink::WebAnimationCurve::TimingFunctionTypeEaseOut;
+                break;
+            case CubicBezierTimingFunction::EaseInOut:
+                easeType = blink::WebAnimationCurve::TimingFunctionTypeEaseInOut;
+                break;
+
+            // Custom Bezier are handled seperately.
+            case CubicBezierTimingFunction::Custom:
+            default:
+                ASSERT_NOT_REACHED();
+                return;
+            }
+
+            curve.add(keyframe, easeType);
+        }
+        return;
+    }
+
+    case TimingFunction::StepsFunction:
+    case TimingFunction::ChainedFunction:
+    default:
+        ASSERT_NOT_REACHED();
+        return;
+    }
+}
+
+} // namespace anoymous
+
+template<typename PlatformAnimationCurveType, typename PlatformAnimationKeyframeType>
+void CompositorAnimationsImpl::addKeyframesToCurve(PlatformAnimationCurveType& curve, const KeyframeAnimationEffect::PropertySpecificKeyframeVector& keyframes, const TimingFunction& timingFunction)
+{
+    for (size_t i = 0; i < keyframes.size(); i++) {
+        const TimingFunction* keyframeTimingFunction = 0;
+        if (i + 1 < keyframes.size()) { // Last keyframe has no timing function
+            switch (timingFunction.type()) {
+            case TimingFunction::LinearFunction:
+            case TimingFunction::CubicBezierFunction:
+                keyframeTimingFunction = &timingFunction;
+                break;
+
+            case TimingFunction::ChainedFunction: {
+                const ChainedTimingFunction& chained = toChainedTimingFunction(timingFunction);
+                // ChainedTimingFunction criteria was checked in isCandidate,
+                // assert it is valid.
+                ASSERT(keyframes.size() == chained.m_segments.size() + 1);
+
+                keyframeTimingFunction = chained.m_segments[i].m_timingFunction.get();
+                break;
+            }
+            case TimingFunction::StepsFunction:
+            default:
+                ASSERT_NOT_REACHED();
+            }
+        }
+
+        ASSERT(!keyframes[i]->value()->dependsOnUnderlyingValue());
+        RefPtr<AnimatableValue> value = keyframes[i]->value()->compositeOnto(0);
+        OwnPtr<PlatformAnimationKeyframeType> keyframe = createPlatformKeyframe<PlatformAnimationKeyframeType>(keyframes[i]->offset(), *value.get());
+        addKeyframeWithTimingFunction(curve, *keyframe.get(), keyframeTimingFunction);
+    }
+}
+
+void CompositorAnimationsImpl::getAnimationOnCompositor(
+    const Timing& timing, const KeyframeAnimationEffect& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
+{
+    CompositorTiming compositorTiming;
+    bool timingValid = convertTimingForCompositor(timing, compositorTiming);
+    ASSERT_UNUSED(timingValid, timingValid);
+
+    RefPtr<TimingFunction> timingFunction = timing.timingFunction;
+    if (compositorTiming.reverse)
+        timingFunction = CompositorAnimationsTimingFunctionReverser::reverse(timingFunction.get());
+
+    PropertySet properties = effect.properties();
+    for (PropertySet::iterator it = properties.begin(); it != properties.end(); ++it) {
+
+        KeyframeVector values;
+        getKeyframeValuesForProperty(&effect, *it, compositorTiming.scaledDuration, compositorTiming.reverse, values);
+
+        blink::WebAnimation::TargetProperty targetProperty;
+        OwnPtr<blink::WebAnimationCurve> curve;
+        switch (*it) {
+        case CSSPropertyOpacity: {
+            targetProperty = blink::WebAnimation::TargetPropertyOpacity;
+            blink::WebFloatAnimationCurve* floatCurve = blink::Platform::current()->compositorSupport()->createFloatAnimationCurve();
+            addKeyframesToCurve<blink::WebFloatAnimationCurve, blink::WebFloatKeyframe>(*floatCurve, values, *timingFunction.get());
+            curve = adoptPtr(floatCurve);
+            break;
+        }
+        case CSSPropertyWebkitFilter: {
+            targetProperty = blink::WebAnimation::TargetPropertyFilter;
+            blink::WebFilterAnimationCurve* filterCurve = blink::Platform::current()->compositorSupport()->createFilterAnimationCurve();
+            addKeyframesToCurve<blink::WebFilterAnimationCurve, blink::WebFilterKeyframe>(*filterCurve, values, *timingFunction);
+            curve = adoptPtr(filterCurve);
+            break;
+        }
+        case CSSPropertyWebkitTransform: {
+            targetProperty = blink::WebAnimation::TargetPropertyTransform;
+            blink::WebTransformAnimationCurve* transformCurve = blink::Platform::current()->compositorSupport()->createTransformAnimationCurve();
+            addKeyframesToCurve<blink::WebTransformAnimationCurve, blink::WebTransformKeyframe>(*transformCurve, values, *timingFunction.get());
+            curve = adoptPtr(transformCurve);
+            break;
+        }
+        default:
+            ASSERT_NOT_REACHED();
+            continue;
+        }
+        ASSERT(curve.get());
+
+        OwnPtr<blink::WebAnimation> animation = adoptPtr(blink::Platform::current()->compositorSupport()->createAnimation(*curve, targetProperty));
+
+        animation->setIterations(compositorTiming.adjustedIterationCount);
+        animation->setTimeOffset(compositorTiming.scaledTimeOffset);
+        animation->setAlternatesDirection(compositorTiming.alternate);
+
+        animations.append(animation.release());
+    }
+}
+
+} // namespace WebCore
diff --git a/Source/core/animation/CompositorAnimations.h b/Source/core/animation/CompositorAnimations.h
index d95196d..9a52973 100644
--- a/Source/core/animation/CompositorAnimations.h
+++ b/Source/core/animation/CompositorAnimations.h
@@ -31,30 +31,45 @@
 #ifndef CompositorAnimations_h
 #define CompositorAnimations_h
 
+#include "core/animation/AnimationEffect.h"
 #include "core/animation/Timing.h"
+#include "core/platform/animation/TimingFunction.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
 class Element;
-class AnimationEffect;
+
+// Given an input timing function between keyframe at 0 and keyframe at 1.0, we
+// need a timing function such that the behavior with the keyframes swapped is
+// equivalent to reversing time with the input timing function and keyframes.
+// This means flipping the timing function about x=0.5 and about y=0.5.
+// FIXME: Remove once the Compositor natively understands reversing time.
+class CompositorAnimationsTimingFunctionReverser {
+public:
+    static PassRefPtr<TimingFunction> reverse(const LinearTimingFunction* timefunc);
+    static PassRefPtr<TimingFunction> reverse(const CubicBezierTimingFunction* timefunc);
+    static PassRefPtr<TimingFunction> reverse(const ChainedTimingFunction* timefunc);
+    static PassRefPtr<TimingFunction> reverse(const TimingFunction* timefunc);
+};
 
 class CompositorAnimations {
-
 public:
     static CompositorAnimations* instance() { return instance(0); }
     static void setInstanceForTesting(CompositorAnimations* newInstance) { instance(newInstance); }
 
-    virtual bool isCandidateForCompositorAnimation(const Timing&, const AnimationEffect*);
-    virtual bool canStartCompositorAnimation(const Element*);
-    virtual void startCompositorAnimation(const Element*, const Timing&, const AnimationEffect*, Vector<int>& startedAnimationIds);
-    virtual void cancelCompositorAnimation(const Element*, int id);
+    virtual bool isCandidateForAnimationOnCompositor(const Timing&, const AnimationEffect&);
+    virtual bool canStartAnimationOnCompositor(const Element&);
+    // FIXME: This should return void. We should know ahead of time whether these animations can be started.
+    virtual bool startAnimationOnCompositor(const Element&, const Timing&, const AnimationEffect&, Vector<int>& startedAnimationIds);
+    virtual void cancelAnimationOnCompositor(const Element&, int id);
+    virtual void pauseAnimationForTestingOnCompositor(const Element&, int id, double pauseTime);
 
 protected:
     CompositorAnimations() { }
 
 private:
-    static CompositorAnimations* instance(CompositorAnimations* newInstance = 0)
+    static CompositorAnimations* instance(CompositorAnimations* newInstance)
     {
         static CompositorAnimations* instance = new CompositorAnimations();
         if (newInstance) {
diff --git a/Source/core/animation/CompositorAnimationsImpl.h b/Source/core/animation/CompositorAnimationsImpl.h
new file mode 100644
index 0000000..c2bc2ee
--- /dev/null
+++ b/Source/core/animation/CompositorAnimationsImpl.h
@@ -0,0 +1,66 @@
+/*
+ * 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 "core/animation/AnimationEffect.h"
+#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/Timing.h"
+#include "core/platform/animation/TimingFunction.h"
+#include "public/platform/WebAnimation.h"
+
+namespace WebCore {
+
+typedef KeyframeAnimationEffect::PropertySpecificKeyframeVector KeyframeVector;
+
+class CompositorAnimationsImpl {
+private:
+    struct CompositorTiming {
+        bool reverse;
+        bool alternate;
+        double scaledDuration;
+        double scaledTimeOffset;
+        int adjustedIterationCount;
+    };
+
+    static bool convertTimingForCompositor(const Timing&, CompositorTiming& out);
+
+    static bool isCandidateForCompositor(const Keyframe&);
+    static bool isCandidateForCompositor(const KeyframeAnimationEffect&);
+    static bool isCandidateForCompositor(const Timing&, const KeyframeAnimationEffect::KeyframeVector&);
+    static bool isCandidateForCompositor(const TimingFunction&, const KeyframeAnimationEffect::KeyframeVector*, bool isNestedCall = false);
+    static void getAnimationOnCompositor(const Timing&, const KeyframeAnimationEffect&, Vector<OwnPtr<blink::WebAnimation> >& animations);
+
+    template<typename PlatformAnimationCurveType, typename PlatformAnimationKeyframeType>
+    static void addKeyframesToCurve(PlatformAnimationCurveType&, const KeyframeVector&, const TimingFunction&);
+
+    friend class CompositorAnimations;
+    friend class AnimationCompositorAnimationsTest;
+};
+
+} // WebCore
diff --git a/Source/core/animation/CompositorAnimationsTest.cpp b/Source/core/animation/CompositorAnimationsTest.cpp
new file mode 100644
index 0000000..dade0cb
--- /dev/null
+++ b/Source/core/animation/CompositorAnimationsTest.cpp
@@ -0,0 +1,1094 @@
+/*
+ * 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/animation/CompositorAnimations.h"
+
+#include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
+#include "core/animation/AnimatableTransform.h"
+#include "core/animation/AnimatableValueTestHelper.h"
+#include "core/animation/CompositorAnimationsImpl.h"
+#include "core/animation/CompositorAnimationsTestHelper.h"
+#include "core/platform/animation/TimingFunctionTestHelper.h"
+#include "core/platform/graphics/filters/FilterOperations.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/transforms/TransformOperations.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+#include "public/platform/WebAnimation.h"
+#include "wtf/HashFunctions.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+using ::testing::CloneToPassOwnPtr;
+using ::testing::ExpectationSet;
+using ::testing::Ref;
+using ::testing::Return;
+using ::testing::_;
+
+class AnimationCompositorAnimationsTest : public AnimationCompositorAnimationsTestBase {
+
+protected:
+    RefPtr<TimingFunction> m_linearTimingFunction;
+    RefPtr<TimingFunction> m_cubicEaseTimingFunction;
+    RefPtr<TimingFunction> m_cubicCustomTimingFunction;
+    RefPtr<TimingFunction> m_stepTimingFunction;
+
+    Timing m_timing;
+    CompositorAnimationsImpl::CompositorTiming m_compositorTiming;
+    KeyframeAnimationEffect::KeyframeVector m_keyframeVector2;
+    KeyframeAnimationEffect::KeyframeVector m_keyframeVector5;
+
+    virtual void SetUp()
+    {
+        AnimationCompositorAnimationsTestBase::SetUp();
+
+        m_linearTimingFunction = LinearTimingFunction::create();
+        m_cubicEaseTimingFunction = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease);
+        m_cubicCustomTimingFunction = CubicBezierTimingFunction::create(1, 2, 3, 4);
+        m_stepTimingFunction = StepsTimingFunction::create(1, false);
+
+        m_timing = createCompositableTiming();
+        m_compositorTiming = CompositorAnimationsImpl::CompositorTiming();
+        // Make sure the CompositableTiming is really compositable, otherwise
+        // most other tests will fail.
+        ASSERT(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+        m_keyframeVector2 = createCompositableFloatKeyframeVector(2);
+        m_keyframeVector5 = createCompositableFloatKeyframeVector(5);
+    }
+
+public:
+
+    bool convertTimingForCompositor(const Timing& t, CompositorAnimationsImpl::CompositorTiming& out)
+    {
+        return CompositorAnimationsImpl::convertTimingForCompositor(t, out);
+    }
+    bool isCandidateForCompositor(const Timing& t, const KeyframeAnimationEffect::KeyframeVector& frames)
+    {
+        return CompositorAnimationsImpl::isCandidateForCompositor(t, frames);
+    }
+    bool isCandidateForCompositor(TimingFunction& t, const KeyframeAnimationEffect::KeyframeVector* frames)
+    {
+        return CompositorAnimationsImpl::isCandidateForCompositor(t, frames);
+    }
+    bool isCandidateForCompositor(const Keyframe& k)
+    {
+        return CompositorAnimationsImpl::isCandidateForCompositor(k);
+    }
+    bool isCandidateForCompositor(const KeyframeAnimationEffect& k)
+    {
+        return CompositorAnimationsImpl::isCandidateForCompositor(k);
+    }
+    void getAnimationOnCompositor(Timing& timing, KeyframeAnimationEffect& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
+    {
+        return CompositorAnimationsImpl::getAnimationOnCompositor(timing, effect, animations);
+    }
+
+    // -------------------------------------------------------------------
+
+    Timing createCompositableTiming()
+    {
+        Timing timing;
+        timing.startDelay = 0;
+        timing.fillMode = Timing::FillModeNone;
+        timing.iterationStart = 0;
+        timing.iterationCount = 1;
+        timing.hasIterationDuration = true;
+        timing.iterationDuration = 1.0;
+        timing.playbackRate = 1.0;
+        timing.direction = Timing::PlaybackDirectionNormal;
+        ASSERT(m_linearTimingFunction);
+        timing.timingFunction = m_linearTimingFunction;
+        return timing;
+    }
+
+    PassRefPtr<Keyframe> createReplaceOpKeyframe(CSSPropertyID id, AnimatableValue* value, double offset = 0)
+    {
+        RefPtr<Keyframe> keyframe = Keyframe::create();
+        keyframe->setPropertyValue(id, value);
+        keyframe->setComposite(AnimationEffect::CompositeReplace);
+        keyframe->setOffset(offset);
+        return keyframe;
+    }
+
+    PassRefPtr<Keyframe> createDefaultKeyframe(CSSPropertyID id, AnimationEffect::CompositeOperation op, double offset = 0)
+    {
+        RefPtr<AnimatableValue> value;
+        if (id == CSSPropertyWebkitTransform)
+            value = AnimatableTransform::create(TransformOperations());
+        else
+            value = AnimatableDouble::create(10.0);
+
+        RefPtr<Keyframe> keyframe = createReplaceOpKeyframe(id, value.get(), offset);
+        keyframe->setComposite(op);
+        return keyframe;
+    }
+
+    KeyframeAnimationEffect::KeyframeVector createCompositableFloatKeyframeVector(size_t n)
+    {
+        Vector<double> values;
+        for (size_t i = 0; i < n; i++) {
+            values.append(static_cast<double>(i));
+        }
+        return createCompositableFloatKeyframeVector(values);
+    }
+
+    KeyframeAnimationEffect::KeyframeVector createCompositableFloatKeyframeVector(Vector<double>& values)
+    {
+        KeyframeAnimationEffect::KeyframeVector frames;
+        for (size_t i = 0; i < values.size(); i++) {
+            double offset = 1.0 / (values.size() - 1) * i;
+            RefPtr<AnimatableDouble> value = AnimatableDouble::create(values[i]);
+            frames.append(createReplaceOpKeyframe(CSSPropertyOpacity, value.get(), offset).get());
+        }
+        return frames;
+    }
+
+    PassRefPtr<KeyframeAnimationEffect> createKeyframeAnimationEffect(PassRefPtr<Keyframe> prpFrom, PassRefPtr<Keyframe> prpTo, PassRefPtr<Keyframe> prpC = 0, PassRefPtr<Keyframe> prpD = 0)
+    {
+        RefPtr<Keyframe> from = prpFrom;
+        RefPtr<Keyframe> to = prpTo;
+        RefPtr<Keyframe> c = prpC;
+        RefPtr<Keyframe> d = prpD;
+
+        EXPECT_EQ(from->offset(), 0);
+        KeyframeAnimationEffect::KeyframeVector frames;
+        frames.append(from);
+        EXPECT_LE(from->offset(), to->offset());
+        frames.append(to);
+        if (c) {
+            EXPECT_LE(to->offset(), c->offset());
+            frames.append(c);
+        }
+        if (d) {
+            frames.append(d);
+            EXPECT_LE(c->offset(), d->offset());
+            EXPECT_EQ(d->offset(), 1.0);
+        } else {
+            EXPECT_EQ(to->offset(), 1.0);
+        }
+        if (!HasFatalFailure()) {
+            return KeyframeAnimationEffect::create(frames);
+        }
+        return PassRefPtr<KeyframeAnimationEffect>();
+    }
+
+};
+
+class CustomFilterOperationMock : public FilterOperation {
+public:
+    virtual bool operator==(const FilterOperation&) const OVERRIDE FINAL {
+        ASSERT_NOT_REACHED();
+        return false;
+    }
+
+    MOCK_CONST_METHOD2(blend, PassRefPtr<FilterOperation>(const FilterOperation*, double));
+
+    static PassRefPtr<CustomFilterOperationMock> create()
+    {
+        return adoptRef(new CustomFilterOperationMock());
+    }
+
+    CustomFilterOperationMock()
+        : FilterOperation(FilterOperation::CUSTOM)
+    {
+    }
+};
+
+// -----------------------------------------------------------------------
+// -----------------------------------------------------------------------
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorKeyframeCSSPropertySupported)
+{
+    EXPECT_TRUE(
+        isCandidateForCompositor(
+            *createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace).get()));
+
+    EXPECT_TRUE(
+        isCandidateForCompositor(
+            *createDefaultKeyframe(CSSPropertyWebkitTransform, AnimationEffect::CompositeReplace).get()));
+
+    EXPECT_FALSE(
+        isCandidateForCompositor(
+            *createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeAdd).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorKeyframeCSSPropertyNotSupported)
+{
+    EXPECT_FALSE(
+        isCandidateForCompositor(
+            *createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace).get()));
+
+    EXPECT_FALSE(
+        isCandidateForCompositor(
+            *createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeAdd).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorKeyframeMultipleCSSProperties)
+{
+    // In this test, we cheat by using an AnimatableDouble even with Transform
+    // as the actual value isn't considered.
+    RefPtr<Keyframe> keyframeGoodMultiple = createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace);
+    keyframeGoodMultiple->setPropertyValue(CSSPropertyWebkitTransform, AnimatableTransform::create(TransformOperations()).get());
+    EXPECT_TRUE(isCandidateForCompositor(*keyframeGoodMultiple.get()));
+
+    RefPtr<Keyframe> keyframeBadMultipleOp = createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeAdd);
+    keyframeBadMultipleOp->setPropertyValue(CSSPropertyWebkitTransform, AnimatableDouble::create(10.0).get());
+    EXPECT_FALSE(isCandidateForCompositor(*keyframeBadMultipleOp.get()));
+
+    // Check both an unsupported property which hashes before and after the
+    // supported property.
+    typedef DefaultHash<CSSPropertyID>::Hash HashFunctions;
+
+    RefPtr<Keyframe> keyframeBadMultiple1ID = createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace);
+    keyframeBadMultiple1ID->setPropertyValue(CSSPropertyOpacity, AnimatableDouble::create(10.0).get());
+    EXPECT_FALSE(isCandidateForCompositor(*keyframeBadMultiple1ID.get()));
+    EXPECT_LT(HashFunctions::hash(CSSPropertyColor), HashFunctions::hash(CSSPropertyOpacity));
+
+    RefPtr<Keyframe> keyframeBadMultiple2ID = createDefaultKeyframe(CSSPropertyWebkitTransform, AnimationEffect::CompositeReplace);
+    keyframeBadMultiple2ID->setPropertyValue(CSSPropertyWidth, AnimatableDouble::create(10.0).get());
+    EXPECT_FALSE(isCandidateForCompositor(*keyframeBadMultiple2ID.get()));
+    EXPECT_GT(HashFunctions::hash(CSSPropertyWebkitTransform), HashFunctions::hash(CSSPropertyWidth));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isNotCandidateForCompositorCustomFilter)
+{
+    FilterOperations ops;
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
+    RefPtr<Keyframe> goodKeyframe = createReplaceOpKeyframe(CSSPropertyWebkitFilter, AnimatableFilterOperations::create(ops).get());
+    EXPECT_TRUE(isCandidateForCompositor(*goodKeyframe.get()));
+
+    ops.operations().append(CustomFilterOperationMock::create());
+    RefPtr<Keyframe> badKeyframe = createReplaceOpKeyframe(CSSPropertyFilter, AnimatableFilterOperations::create(ops).get());
+    EXPECT_FALSE(isCandidateForCompositor(*badKeyframe.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorKeyframeEffectGoodSingleFrame)
+{
+    KeyframeAnimationEffect::KeyframeVector frames;
+    frames.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace).get());
+    EXPECT_TRUE(isCandidateForCompositor(*KeyframeAnimationEffect::create(frames).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorKeyframeEffectBadSingleFrame)
+{
+    KeyframeAnimationEffect::KeyframeVector framesBadSingle;
+    framesBadSingle.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace).get());
+    EXPECT_FALSE(isCandidateForCompositor(*KeyframeAnimationEffect::create(framesBadSingle).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorKeyframeEffectMultipleFramesOkay)
+{
+    KeyframeAnimationEffect::KeyframeVector framesSame;
+    framesSame.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+    framesSame.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
+    EXPECT_TRUE(isCandidateForCompositor(*KeyframeAnimationEffect::create(framesSame).get()));
+
+    KeyframeAnimationEffect::KeyframeVector framesMixed;
+    framesMixed.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+    framesMixed.append(createDefaultKeyframe(CSSPropertyWebkitTransform, AnimationEffect::CompositeReplace, 1.0).get());
+    EXPECT_TRUE(isCandidateForCompositor(*KeyframeAnimationEffect::create(framesMixed).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorKeyframeEffectMultipleFramesNotOkay)
+{
+    KeyframeAnimationEffect::KeyframeVector framesSame;
+    framesSame.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 0.0).get());
+    framesSame.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 1.0).get());
+    EXPECT_FALSE(isCandidateForCompositor(*KeyframeAnimationEffect::create(framesSame).get()));
+
+    KeyframeAnimationEffect::KeyframeVector framesMixedProperties;
+    framesMixedProperties.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+    framesMixedProperties.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 1.0).get());
+    EXPECT_FALSE(isCandidateForCompositor(*KeyframeAnimationEffect::create(framesMixedProperties).get()));
+
+    KeyframeAnimationEffect::KeyframeVector framesMixedOps;
+    framesMixedOps.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+    framesMixedOps.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeAdd, 1.0).get());
+    EXPECT_FALSE(isCandidateForCompositor(*KeyframeAnimationEffect::create(framesMixedOps).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorStartDelay)
+{
+    m_timing.iterationDuration = 20.0;
+
+    m_timing.startDelay = 2.0;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+    m_timing.startDelay = -2.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_DOUBLE_EQ(-2.0, m_compositorTiming.scaledTimeOffset);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorIterationStart)
+{
+    m_timing.iterationStart = 2.2;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorIterationCount)
+{
+    m_timing.iterationCount = 5.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_EQ(5, m_compositorTiming.adjustedIterationCount);
+
+    m_timing.iterationCount = 5.5;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+    // Asserts will only trigger on DEBUG build.
+    // EXPECT_DEATH tests are flaky on Android.
+#if !defined(NDEBUG) && !OS(ANDROID)
+    m_timing.iterationCount = -1;
+    EXPECT_DEATH(convertTimingForCompositor(m_timing, m_compositorTiming), "");
+#endif
+
+    m_timing.iterationCount = std::numeric_limits<double>::infinity();
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_EQ(-1, m_compositorTiming.adjustedIterationCount);
+
+    m_timing.iterationCount = std::numeric_limits<double>::infinity();
+    m_timing.iterationDuration = 5.0;
+    m_timing.startDelay = -6.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_DOUBLE_EQ(-1.0, m_compositorTiming.scaledTimeOffset);
+    EXPECT_EQ(-1, m_compositorTiming.adjustedIterationCount);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorIterationsAndStartDelay)
+{
+    m_timing.iterationCount = 4.0;
+    m_timing.iterationDuration = 5.0;
+
+    m_timing.startDelay = -6.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_DOUBLE_EQ(-1.0, m_compositorTiming.scaledTimeOffset);
+    EXPECT_DOUBLE_EQ(3.0, m_compositorTiming.adjustedIterationCount);
+    EXPECT_FALSE(m_compositorTiming.reverse);
+
+    m_timing.iterationCount = 1.0;
+    m_timing.iterationDuration = 5.0;
+    m_timing.startDelay = -6.0;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+    m_timing.iterationCount = 5.0;
+    m_timing.iterationDuration = 1.0;
+    m_timing.startDelay = -6.0;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorPlaybackRate)
+{
+    m_timing.playbackRate = 2.0;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+    m_timing.playbackRate = 0.0;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+    m_timing.playbackRate = -2.0;
+    EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorDirection)
+{
+    m_timing.direction = Timing::PlaybackDirectionAlternate;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_TRUE(m_compositorTiming.alternate);
+    EXPECT_FALSE(m_compositorTiming.reverse);
+
+    m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_TRUE(m_compositorTiming.alternate);
+    EXPECT_TRUE(m_compositorTiming.reverse);
+
+    m_timing.direction = Timing::PlaybackDirectionReverse;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_FALSE(m_compositorTiming.alternate);
+    EXPECT_TRUE(m_compositorTiming.reverse);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorDirectionIterationsAndStartDelay)
+{
+    m_timing.direction = Timing::PlaybackDirectionAlternate;
+    m_timing.iterationCount = 4.0;
+    m_timing.iterationDuration = 5.0;
+    m_timing.startDelay = -6.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_DOUBLE_EQ(-1.0, m_compositorTiming.scaledTimeOffset);
+    EXPECT_EQ(3, m_compositorTiming.adjustedIterationCount);
+    EXPECT_TRUE(m_compositorTiming.alternate);
+    EXPECT_TRUE(m_compositorTiming.reverse);
+
+    m_timing.direction = Timing::PlaybackDirectionAlternate;
+    m_timing.iterationCount = 4.0;
+    m_timing.iterationDuration = 5.0;
+    m_timing.startDelay = -11.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_DOUBLE_EQ(-1.0, m_compositorTiming.scaledTimeOffset);
+    EXPECT_EQ(2, m_compositorTiming.adjustedIterationCount);
+    EXPECT_TRUE(m_compositorTiming.alternate);
+    EXPECT_FALSE(m_compositorTiming.reverse);
+
+    m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+    m_timing.iterationCount = 4.0;
+    m_timing.iterationDuration = 5.0;
+    m_timing.startDelay = -6.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_DOUBLE_EQ(-1.0, m_compositorTiming.scaledTimeOffset);
+    EXPECT_EQ(3, m_compositorTiming.adjustedIterationCount);
+    EXPECT_TRUE(m_compositorTiming.alternate);
+    EXPECT_FALSE(m_compositorTiming.reverse);
+
+    m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+    m_timing.iterationCount = 4.0;
+    m_timing.iterationDuration = 5.0;
+    m_timing.startDelay = -11.0;
+    EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+    EXPECT_DOUBLE_EQ(-1.0, m_compositorTiming.scaledTimeOffset);
+    EXPECT_EQ(2, m_compositorTiming.adjustedIterationCount);
+    EXPECT_TRUE(m_compositorTiming.alternate);
+    EXPECT_TRUE(m_compositorTiming.reverse);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTiming)
+{
+    EXPECT_TRUE(isCandidateForCompositor(m_timing, m_keyframeVector2));
+
+    m_timing.startDelay = 2.0;
+    EXPECT_FALSE(isCandidateForCompositor(m_timing, m_keyframeVector2));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingTimingFunctionPassThru)
+{
+    m_timing.timingFunction = m_stepTimingFunction;
+    EXPECT_FALSE(isCandidateForCompositor(m_timing, m_keyframeVector2));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionLinear)
+{
+    EXPECT_TRUE(isCandidateForCompositor(*m_linearTimingFunction.get(), &m_keyframeVector2));
+    EXPECT_TRUE(isCandidateForCompositor(*m_linearTimingFunction.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionCubic)
+{
+    // Cubic bezier are okay if we only have two keyframes
+    EXPECT_TRUE(isCandidateForCompositor(*m_cubicEaseTimingFunction.get(), &m_keyframeVector2));
+    EXPECT_FALSE(isCandidateForCompositor(*m_cubicEaseTimingFunction.get(), &m_keyframeVector5));
+
+    EXPECT_TRUE(isCandidateForCompositor(*m_cubicCustomTimingFunction.get(), &m_keyframeVector2));
+    EXPECT_FALSE(isCandidateForCompositor(*m_cubicCustomTimingFunction.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionSteps)
+{
+    RefPtr<TimingFunction> stepTiming = StepsTimingFunction::create(1, false);
+    EXPECT_FALSE(isCandidateForCompositor(*m_stepTimingFunction.get(), &m_keyframeVector2));
+    EXPECT_FALSE(isCandidateForCompositor(*m_stepTimingFunction.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionChainedEmpty)
+{
+    RefPtr<ChainedTimingFunction> chainedEmpty = ChainedTimingFunction::create();
+    EXPECT_FALSE(isCandidateForCompositor(*chainedEmpty.get(), &m_keyframeVector2));
+    EXPECT_FALSE(isCandidateForCompositor(*chainedEmpty.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionChainedLinear)
+{
+    RefPtr<ChainedTimingFunction> chainedLinearSingle = ChainedTimingFunction::create();
+    chainedLinearSingle->appendSegment(1.0, m_linearTimingFunction.get());
+    EXPECT_TRUE(isCandidateForCompositor(*chainedLinearSingle.get(), &m_keyframeVector2));
+
+    RefPtr<ChainedTimingFunction> chainedLinearMultiple = ChainedTimingFunction::create();
+    chainedLinearMultiple->appendSegment(0.25, m_linearTimingFunction.get());
+    chainedLinearMultiple->appendSegment(0.5, m_linearTimingFunction.get());
+    chainedLinearMultiple->appendSegment(0.75, m_linearTimingFunction.get());
+    chainedLinearMultiple->appendSegment(1.0, m_linearTimingFunction.get());
+    EXPECT_TRUE(isCandidateForCompositor(*chainedLinearMultiple.get(), &m_keyframeVector5));
+
+    // FIXME: Technically a chained timing function of linear functions don't
+    // have to be aligned to keyframes. We don't support that currently as
+    // nothing generates that yet.
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionChainedCubicMatchingOffsets)
+{
+    RefPtr<ChainedTimingFunction> chainedSingleAGood = ChainedTimingFunction::create();
+    chainedSingleAGood->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_TRUE(isCandidateForCompositor(*chainedSingleAGood.get(), &m_keyframeVector2));
+
+    RefPtr<ChainedTimingFunction> chainedSingleBGood = ChainedTimingFunction::create();
+    chainedSingleBGood->appendSegment(1.0, m_cubicCustomTimingFunction.get());
+    EXPECT_TRUE(isCandidateForCompositor(*chainedSingleBGood.get(), &m_keyframeVector2));
+
+    RefPtr<ChainedTimingFunction> chainedMultipleGood = ChainedTimingFunction::create();
+    chainedMultipleGood->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chainedMultipleGood->appendSegment(0.5, m_cubicCustomTimingFunction.get());
+    chainedMultipleGood->appendSegment(0.75, m_cubicCustomTimingFunction.get());
+    chainedMultipleGood->appendSegment(1.0, m_cubicCustomTimingFunction.get());
+    EXPECT_TRUE(isCandidateForCompositor(*chainedMultipleGood.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionChainedCubicNonMatchingOffsets)
+{
+    RefPtr<ChainedTimingFunction> chained0 = ChainedTimingFunction::create();
+    chained0->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained0.get(), &m_keyframeVector2));
+
+    RefPtr<ChainedTimingFunction> chained1 = ChainedTimingFunction::create();
+    chained1->appendSegment(0.24, m_cubicEaseTimingFunction.get());
+    chained1->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chained1->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chained1->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained1.get(), &m_keyframeVector5));
+
+    RefPtr<ChainedTimingFunction> chained2 = ChainedTimingFunction::create();
+    chained2->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(0.51, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained2.get(), &m_keyframeVector5));
+
+    RefPtr<ChainedTimingFunction> chained3 = ChainedTimingFunction::create();
+    chained3->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chained3->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chained3->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chained3->appendSegment(0.8, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained3.get(), &m_keyframeVector5));
+
+    RefPtr<ChainedTimingFunction> chained4 = ChainedTimingFunction::create();
+    chained4->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chained4->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chained4->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chained4->appendSegment(1.1, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained4.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionMissingFrames)
+{
+    // Missing first
+    RefPtr<ChainedTimingFunction> chained1 = ChainedTimingFunction::create();
+    chained1->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chained1->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chained1->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained1.get(), &m_keyframeVector5));
+
+    // Missing middle
+    RefPtr<ChainedTimingFunction> chained2 = ChainedTimingFunction::create();
+    chained2->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained2.get(), &m_keyframeVector5));
+
+    // Missing last
+    RefPtr<ChainedTimingFunction> chained3 = ChainedTimingFunction::create();
+    chained3->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chained3->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chained3->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained3.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionToManyFrames)
+{
+    RefPtr<ChainedTimingFunction> chained1 = ChainedTimingFunction::create();
+    chained1->appendSegment(0.1, m_cubicEaseTimingFunction.get());
+    chained1->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained1.get(), &m_keyframeVector2));
+
+    RefPtr<ChainedTimingFunction> chained2 = ChainedTimingFunction::create();
+    chained2->appendSegment(0.1, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chained2->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chained2.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionMixedGood)
+{
+    RefPtr<ChainedTimingFunction> chainedMixed = ChainedTimingFunction::create();
+    chainedMixed->appendSegment(0.25, m_linearTimingFunction.get());
+    chainedMixed->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chainedMixed->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+    chainedMixed->appendSegment(1.0, m_linearTimingFunction.get());
+    EXPECT_TRUE(isCandidateForCompositor(*chainedMixed.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionWithStepNotOkay)
+{
+    RefPtr<ChainedTimingFunction> chainedStepSingle = ChainedTimingFunction::create();
+    chainedStepSingle->appendSegment(1.0, m_stepTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chainedStepSingle.get(), &m_keyframeVector2));
+
+    RefPtr<ChainedTimingFunction> chainedStepMixedA = ChainedTimingFunction::create();
+    chainedStepMixedA->appendSegment(0.25, m_stepTimingFunction.get());
+    chainedStepMixedA->appendSegment(0.5, m_linearTimingFunction.get());
+    chainedStepMixedA->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chainedStepMixedA.get(), &m_keyframeVector5));
+
+    RefPtr<ChainedTimingFunction> chainedStepMixedB = ChainedTimingFunction::create();
+    chainedStepMixedB->appendSegment(0.25, m_linearTimingFunction.get());
+    chainedStepMixedB->appendSegment(0.5, m_stepTimingFunction.get());
+    chainedStepMixedB->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chainedStepMixedB.get(), &m_keyframeVector5));
+
+    RefPtr<ChainedTimingFunction> chainedStepMixedC = ChainedTimingFunction::create();
+    chainedStepMixedC->appendSegment(0.25, m_linearTimingFunction.get());
+    chainedStepMixedC->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+    chainedStepMixedC->appendSegment(1.0, m_stepTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chainedStepMixedC.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositorTimingFunctionNestedNotOkay)
+{
+    RefPtr<ChainedTimingFunction> chainedChild = ChainedTimingFunction::create();
+    chainedChild->appendSegment(1.0, m_linearTimingFunction.get());
+
+    RefPtr<ChainedTimingFunction> chainedParent = ChainedTimingFunction::create();
+    chainedParent->appendSegment(0.25, m_linearTimingFunction.get());
+    chainedParent->appendSegment(0.5, chainedChild.get());
+    chainedParent->appendSegment(0.75, m_linearTimingFunction.get());
+    chainedParent->appendSegment(1.0, m_linearTimingFunction.get());
+    EXPECT_FALSE(isCandidateForCompositor(*chainedParent.get(), &m_keyframeVector5));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForCompositor)
+{
+    Timing linearTiming(createCompositableTiming());
+
+    RefPtr<TimingFunction> cubicTimingFunc = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    Timing cubicTiming(createCompositableTiming());
+    cubicTiming.timingFunction = cubicTimingFunc;
+
+    RefPtr<ChainedTimingFunction> chainedTimingFunc = ChainedTimingFunction::create();
+    chainedTimingFunc->appendSegment(0.5, m_linearTimingFunction.get());
+    chainedTimingFunc->appendSegment(1.0, cubicTimingFunc.get());
+    Timing chainedTiming(createCompositableTiming());
+    chainedTiming.timingFunction = chainedTimingFunc;
+
+    KeyframeAnimationEffect::KeyframeVector basicFramesVector;
+    basicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+    basicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
+    RefPtr<KeyframeAnimationEffect> basicFrames = KeyframeAnimationEffect::create(basicFramesVector).get();
+
+    EXPECT_TRUE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(linearTiming, *basicFrames.get()));
+    EXPECT_TRUE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(cubicTiming, *basicFrames.get()));
+    // number of timing function and keyframes don't match
+    EXPECT_FALSE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(chainedTiming, *basicFrames.get()));
+
+    KeyframeAnimationEffect::KeyframeVector nonBasicFramesVector;
+    nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+    nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.5).get());
+    nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
+    RefPtr<KeyframeAnimationEffect> nonBasicFrames = KeyframeAnimationEffect::create(nonBasicFramesVector).get();
+
+    EXPECT_TRUE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(linearTiming, *nonBasicFrames.get()));
+    EXPECT_FALSE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(cubicTiming, *nonBasicFrames.get()));
+    EXPECT_TRUE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(chainedTiming, *nonBasicFrames.get()));
+}
+
+// -----------------------------------------------------------------------
+// -----------------------------------------------------------------------
+
+TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimation)
+{
+    // Animation to convert
+    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+    // --
+
+    WebCompositorSupportMock mockCompositor;
+
+    // Curve is created
+    blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+    ExpectationSet usesMockCurve;
+    EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+        .WillOnce(Return(mockCurvePtr));
+
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 5.0)));
+
+    // Create animation
+    blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+    ExpectationSet usesMockAnimation;
+
+    usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+        .WillOnce(Return(mockAnimationPtr));
+
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(1));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(false));
+
+    EXPECT_CALL(*mockAnimationPtr, delete_())
+        .Times(1)
+        .After(usesMockAnimation);
+    EXPECT_CALL(*mockCurvePtr, delete_())
+        .Times(1)
+        .After(usesMockCurve);
+
+    // Go!
+    setCompositorForTesting(mockCompositor);
+    Vector<OwnPtr<blink::WebAnimation> > result;
+    getAnimationOnCompositor(m_timing, *effect.get(), result);
+    EXPECT_EQ(1U, result.size());
+    result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimationDuration)
+{
+    // Animation to convert
+    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+    m_timing.iterationDuration = 10.0;
+    // --
+
+    WebCompositorSupportMock mockCompositor;
+
+    // Curve is created
+    blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+    ExpectationSet usesMockCurve;
+    EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+        .WillOnce(Return(mockCurvePtr));
+
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(10.0, 5.0)));
+
+    // Create animation
+    blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+    ExpectationSet usesMockAnimation;
+
+    usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+        .WillOnce(Return(mockAnimationPtr));
+
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(1));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(false));
+
+    EXPECT_CALL(*mockAnimationPtr, delete_())
+        .Times(1)
+        .After(usesMockAnimation);
+    EXPECT_CALL(*mockCurvePtr, delete_())
+        .Times(1)
+        .After(usesMockCurve);
+
+    // Go!
+    setCompositorForTesting(mockCompositor);
+    Vector<OwnPtr<blink::WebAnimation> > result;
+    getAnimationOnCompositor(m_timing, *effect.get(), result);
+    EXPECT_EQ(1U, result.size());
+    result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createMultipleKeyframeOpacityAnimationLinear)
+{
+    // Animation to convert
+    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+    m_timing.iterationCount = 5;
+    m_timing.direction = Timing::PlaybackDirectionAlternate;
+    // --
+
+    WebCompositorSupportMock mockCompositor;
+
+    // Curve is created
+    blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock();
+    ExpectationSet usesMockCurve;
+
+    EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+        .WillOnce(Return(mockCurvePtr));
+
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.25, -1.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.5, 20.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 5.0)));
+
+    // Animation is created
+    blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+    ExpectationSet usesMockAnimation;
+
+    usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+        .WillOnce(Return(mockAnimationPtr));
+
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(5));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+    EXPECT_CALL(*mockAnimationPtr, delete_())
+        .Times(1)
+        .After(usesMockAnimation);
+    EXPECT_CALL(*mockCurvePtr, delete_())
+        .Times(1)
+        .After(usesMockCurve);
+
+    // Go!
+    setCompositorForTesting(mockCompositor);
+    Vector<OwnPtr<blink::WebAnimation> > result;
+    getAnimationOnCompositor(m_timing, *effect.get(), result);
+    EXPECT_EQ(1U, result.size());
+    result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimationNegativeStartDelay)
+{
+    // Animation to convert
+    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+    m_timing.iterationCount = 5.0;
+    m_timing.iterationDuration = 1.75;
+    m_timing.startDelay = -3.25;
+    // --
+
+    WebCompositorSupportMock mockCompositor;
+
+    // Curve is created
+    blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+    ExpectationSet usesMockCurve;
+    EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+        .WillOnce(Return(mockCurvePtr));
+
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.75, 5.0)));
+
+    // Create animation
+    blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+    ExpectationSet usesMockAnimation;
+
+    usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+        .WillOnce(Return(mockAnimationPtr));
+
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(4));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(-1.5));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(false));
+
+    EXPECT_CALL(*mockAnimationPtr, delete_())
+        .Times(1)
+        .After(usesMockAnimation);
+    EXPECT_CALL(*mockCurvePtr, delete_())
+        .Times(1)
+        .After(usesMockCurve);
+
+    // Go!
+    setCompositorForTesting(mockCompositor);
+    Vector<OwnPtr<blink::WebAnimation> > result;
+    getAnimationOnCompositor(m_timing, *effect.get(), result);
+    EXPECT_EQ(1U, result.size());
+    result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createMultipleKeyframeOpacityAnimationChained)
+{
+    // Animation to convert
+    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+    RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
+    chainedTimingFunction->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+    chainedTimingFunction->appendSegment(0.5, m_linearTimingFunction.get());
+    chainedTimingFunction->appendSegment(1.0, m_cubicCustomTimingFunction.get());
+
+    m_timing.timingFunction = chainedTimingFunction;
+    m_timing.iterationDuration = 2.0;
+    m_timing.iterationCount = 10;
+    m_timing.direction = Timing::PlaybackDirectionAlternate;
+    // --
+
+    WebCompositorSupportMock mockCompositor;
+
+    // Curve is created
+    blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock();
+    ExpectationSet usesMockCurve;
+
+    EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+        .WillOnce(Return(mockCurvePtr));
+
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeEase));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.5, -1.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 20.0), 1.0, 2.0, 3.0, 4.0));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(2.0, 5.0)));
+
+    // Animation is created
+    blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+    ExpectationSet usesMockAnimation;
+
+    usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+        .WillOnce(Return(mockAnimationPtr));
+
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(10));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+    EXPECT_CALL(*mockAnimationPtr, delete_())
+        .Times(1)
+        .After(usesMockAnimation);
+    EXPECT_CALL(*mockCurvePtr, delete_())
+        .Times(1)
+        .After(usesMockCurve);
+
+    // Go!
+    setCompositorForTesting(mockCompositor);
+    Vector<OwnPtr<blink::WebAnimation> > result;
+    getAnimationOnCompositor(m_timing, *effect.get(), result);
+    EXPECT_EQ(1U, result.size());
+    result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createReversedOpacityAnimation)
+{
+    // Animation to convert
+    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+    RefPtr<TimingFunction> cubicEasyFlipTimingFunction = CubicBezierTimingFunction::create(0.0, 0.0, 0.0, 1.0);
+    RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
+    chainedTimingFunction->appendSegment(0.25, CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn));
+    chainedTimingFunction->appendSegment(0.5, m_linearTimingFunction.get());
+    chainedTimingFunction->appendSegment(1.0, cubicEasyFlipTimingFunction.get());
+
+    m_timing.timingFunction = chainedTimingFunction;
+    m_timing.iterationCount = 10;
+    m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+    // --
+
+    WebCompositorSupportMock mockCompositor;
+
+    // Curve is created
+    blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock();
+    ExpectationSet usesMockCurve;
+
+    EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+        .WillOnce(Return(mockCurvePtr));
+
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 5.0), 1.0, 0.0, 1.0, 1.0));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.5, 20.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.75, -1.0), blink::WebAnimationCurve::TimingFunctionTypeEaseOut));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 2.0)));
+
+    // Create the animation
+    blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+    ExpectationSet usesMockAnimation;
+
+    usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+        .WillOnce(Return(mockAnimationPtr));
+
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(10));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+    EXPECT_CALL(*mockAnimationPtr, delete_())
+        .Times(1)
+        .After(usesMockAnimation);
+    EXPECT_CALL(*mockCurvePtr, delete_())
+        .Times(1)
+        .After(usesMockCurve);
+
+    // Go!
+    setCompositorForTesting(mockCompositor);
+    Vector<OwnPtr<blink::WebAnimation> > result;
+    getAnimationOnCompositor(m_timing, *effect.get(), result);
+    EXPECT_EQ(1U, result.size());
+    result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createReversedOpacityAnimationNegativeStartDelay)
+{
+    // Animation to convert
+    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+        createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+    m_timing.iterationCount = 5.0;
+    m_timing.iterationDuration = 2.0;
+    m_timing.startDelay = -3;
+    m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+    // --
+
+    WebCompositorSupportMock mockCompositor;
+
+    // Curve is created
+    blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+    ExpectationSet usesMockCurve;
+    EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+        .WillOnce(Return(mockCurvePtr));
+
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+    usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(2.0, 5.0)));
+
+    // Create animation
+    blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+    ExpectationSet usesMockAnimation;
+
+    usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+        .WillOnce(Return(mockAnimationPtr));
+
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(4));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(-1.0));
+    usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+    EXPECT_CALL(*mockAnimationPtr, delete_())
+        .Times(1)
+        .After(usesMockAnimation);
+    EXPECT_CALL(*mockCurvePtr, delete_())
+        .Times(1)
+        .After(usesMockCurve);
+
+    // Go!
+    setCompositorForTesting(mockCompositor);
+    Vector<OwnPtr<blink::WebAnimation> > result;
+    getAnimationOnCompositor(m_timing, *effect.get(), result);
+    EXPECT_EQ(1U, result.size());
+    result[0].clear();
+}
+
+
+} // namespace WebCore
diff --git a/Source/core/animation/CompositorAnimationsTestHelper.h b/Source/core/animation/CompositorAnimationsTestHelper.h
new file mode 100644
index 0000000..5bba3ca
--- /dev/null
+++ b/Source/core/animation/CompositorAnimationsTestHelper.h
@@ -0,0 +1,170 @@
+/*
+ * 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 INC. 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 INC. 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.
+ */
+
+#ifndef CompositorAnimationsTestHelper_h
+#define CompositorAnimationsTestHelper_h
+
+#include "core/animation/CompositorAnimations.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebCompositorSupport.h"
+#include "public/platform/WebFloatAnimationCurve.h"
+#include "public/platform/WebFloatKeyframe.h"
+#include "wtf/PassOwnPtr.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+
+namespace testing {
+
+template<typename T>
+PassOwnPtr<T> CloneToPassOwnPtr(T& o)
+{
+    return adoptPtr(new T(o));
+}
+
+} // namespace testing
+
+
+// Test helpers and mocks for blink::Web* types
+// -----------------------------------------------------------------------
+namespace blink {
+
+// blink::WebFloatKeyframe is a plain struct, so we just create an == operator
+// for it.
+inline bool operator==(const WebFloatKeyframe& a, const WebFloatKeyframe& b)
+{
+    return a.time == b.time && a.value == b.value;
+}
+
+inline void PrintTo(const WebFloatKeyframe& frame, ::std::ostream* os)
+{
+    *os << "WebFloatKeyframe@" << &frame << "(" << frame.time << ", " << frame.value << ")";
+}
+
+// -----------------------------------------------------------------------
+
+class WebAnimationMock : public blink::WebAnimation {
+private:
+    blink::WebAnimation::TargetProperty m_property;
+
+public:
+    // Target Property is set through the constructor.
+    WebAnimationMock(blink::WebAnimation::TargetProperty p) : m_property(p) { }
+    virtual blink::WebAnimation::TargetProperty targetProperty() const { return m_property; };
+
+    MOCK_METHOD0(id, int());
+
+    MOCK_CONST_METHOD0(iterations, int());
+    MOCK_METHOD1(setIterations, void(int));
+
+    MOCK_CONST_METHOD0(startTime, double());
+    MOCK_METHOD1(setStartTime, void(double));
+
+    MOCK_CONST_METHOD0(timeOffset, double());
+    MOCK_METHOD1(setTimeOffset, void(double));
+
+    MOCK_CONST_METHOD0(alternatesDirection, bool());
+    MOCK_METHOD1(setAlternatesDirection, void(bool));
+
+    MOCK_METHOD0(delete_, void());
+    ~WebAnimationMock() { delete_(); }
+};
+
+template<typename CurveType, blink::WebAnimationCurve::AnimationCurveType CurveId, typename KeyframeType>
+class WebAnimationCurveMock : public CurveType {
+public:
+    MOCK_METHOD1_T(add, void(const KeyframeType&));
+    MOCK_METHOD2_T(add, void(const KeyframeType&, blink::WebAnimationCurve::TimingFunctionType));
+    MOCK_METHOD5_T(add, void(const KeyframeType&, double, double, double, double));
+
+    MOCK_CONST_METHOD1_T(getValue, float(double)); // Only on WebFloatAnimationCurve, but can't hurt to have here.
+
+    virtual blink::WebAnimationCurve::AnimationCurveType type() const { return CurveId; };
+
+    MOCK_METHOD0(delete_, void());
+    ~WebAnimationCurveMock() { delete_(); }
+};
+
+typedef WebAnimationCurveMock<blink::WebFloatAnimationCurve, blink::WebAnimationCurve::AnimationCurveTypeFloat, blink::WebFloatKeyframe> WebFloatAnimationCurveMock;
+
+} // namespace blink
+
+namespace WebCore {
+
+class AnimationCompositorAnimationsTestBase : public ::testing::Test {
+public:
+    AnimationCompositorAnimationsTestBase() : m_proxyPlatform(&m_mockCompositor) { };
+
+    class WebCompositorSupportMock : public blink::WebCompositorSupport {
+    public:
+        MOCK_METHOD3(createAnimation, blink::WebAnimation*(const blink::WebAnimationCurve& curve, blink::WebAnimation::TargetProperty target, int animationId));
+        MOCK_METHOD0(createFloatAnimationCurve, blink::WebFloatAnimationCurve*());
+    };
+
+private:
+    class PlatformProxy : public blink::Platform {
+    public:
+        PlatformProxy(WebCompositorSupportMock** compositor) : m_compositor(compositor) { }
+
+        virtual void cryptographicallyRandomValues(unsigned char* buffer, size_t length) { ASSERT_NOT_REACHED(); }
+    private:
+        WebCompositorSupportMock** m_compositor;
+        blink::WebCompositorSupport* compositorSupport() OVERRIDE { return *m_compositor; }
+    };
+
+    WebCompositorSupportMock* m_mockCompositor;
+    PlatformProxy m_proxyPlatform;
+
+protected:
+    bool m_enabled;
+    blink::Platform* m_platform;
+
+    virtual void SetUp()
+    {
+        m_enabled = RuntimeEnabledFeatures::webAnimationsEnabled();
+        // Needed for ChainedTimingFunction support
+        RuntimeEnabledFeatures::setWebAnimationsEnabled(true);
+
+        m_mockCompositor = 0;
+        m_platform = blink::Platform::current();
+        blink::Platform::initialize(&m_proxyPlatform);
+    }
+
+    virtual void TearDown()
+    {
+        RuntimeEnabledFeatures::setWebAnimationsEnabled(m_enabled);
+        blink::Platform::initialize(m_platform);
+    }
+
+    void setCompositorForTesting(WebCompositorSupportMock& mock)
+    {
+        ASSERT(!m_mockCompositor);
+        m_mockCompositor = &mock;
+    }
+};
+
+}
+
+#endif
diff --git a/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp b/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp
new file mode 100644
index 0000000..e1dabda
--- /dev/null
+++ b/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp
@@ -0,0 +1,120 @@
+/*
+ * 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/animation/CompositorAnimations.h"
+
+#include "core/platform/animation/TimingFunctionTestHelper.h"
+
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+// FIXME: Remove once https://codereview.chromium.org/50603011/ lands.
+#define EXPECT_REFV_EQ(a, b) EXPECT_EQ(*(a.get()), *(b.get()))
+#define EXPECT_REFV_NE(a, b) EXPECT_NE(*(a.get()), *(b.get()))
+
+namespace {
+
+using namespace WebCore;
+
+class AnimationCompositorAnimationsTimingFunctionReverserTest : public ::testing::Test {
+protected:
+    bool m_enabled;
+
+    virtual void SetUp()
+    {
+        m_enabled = RuntimeEnabledFeatures::webAnimationsEnabled();
+        // Needed for ChainedTimingFunction support
+        RuntimeEnabledFeatures::setWebAnimationsEnabled(true);
+    }
+
+    virtual void TearDown()
+    {
+        RuntimeEnabledFeatures::setWebAnimationsEnabled(m_enabled);
+    }
+
+public:
+    PassRefPtr<TimingFunction> reverse(const RefPtr<TimingFunction>& timefunc)
+    {
+        return CompositorAnimationsTimingFunctionReverser::reverse(timefunc.get());
+    }
+};
+
+TEST_F(AnimationCompositorAnimationsTimingFunctionReverserTest, LinearReverse)
+{
+    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+    EXPECT_REFV_EQ(linearTiming, reverse(linearTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTimingFunctionReverserTest, CubicReverse)
+{
+    RefPtr<TimingFunction> cubicEaseInTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    RefPtr<TimingFunction> cubicEaseOutTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+    RefPtr<TimingFunction> cubicEaseInOutTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
+
+    EXPECT_REFV_EQ(cubicEaseOutTiming, reverse(cubicEaseInTiming));
+    EXPECT_REFV_EQ(cubicEaseInTiming, reverse(cubicEaseOutTiming));
+    EXPECT_REFV_EQ(cubicEaseInOutTiming, reverse(cubicEaseInOutTiming));
+
+    RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+    // Due to floating point, 1.0-(-1.73) != 2.73
+    RefPtr<TimingFunction> cubicCustomTimingReversed = CubicBezierTimingFunction::create(0, 1.0 - (-1.73), 1.0 - 0.17, 1.0 - 0.67);
+    EXPECT_REFV_EQ(cubicCustomTimingReversed, reverse(cubicCustomTiming));
+
+    RefPtr<TimingFunction> cubicEaseTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease);
+    RefPtr<TimingFunction> cubicEaseTimingReversed = CubicBezierTimingFunction::create(1.0 - 0.25, 0.0, 1.0 - 0.25, 1.0 - 0.1);
+    EXPECT_REFV_EQ(cubicEaseTimingReversed, reverse(cubicEaseTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTimingFunctionReverserTest, ChainedReverse)
+{
+    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+    RefPtr<ChainedTimingFunction> chainedLinearSingle = ChainedTimingFunction::create();
+    chainedLinearSingle->appendSegment(1.0, linearTiming.get());
+    EXPECT_REFV_EQ(chainedLinearSingle, reverse(chainedLinearSingle));
+
+    RefPtr<TimingFunction> cubicEaseInTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    RefPtr<TimingFunction> cubicEaseOutTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+
+    RefPtr<ChainedTimingFunction> chainedMixed = ChainedTimingFunction::create();
+    chainedMixed->appendSegment(0.75, chainedLinearSingle.get());
+    chainedMixed->appendSegment(1.0, cubicEaseInTiming.get());
+
+    RefPtr<ChainedTimingFunction> chainedMixedReversed = ChainedTimingFunction::create();
+    chainedMixedReversed->appendSegment(0.25, cubicEaseOutTiming.get());
+    chainedMixedReversed->appendSegment(1.0, chainedLinearSingle.get());
+    EXPECT_REFV_EQ(chainedMixedReversed, reverse(chainedMixed));
+}
+
+} // namespace
diff --git a/Source/core/animation/DocumentAnimations.cpp b/Source/core/animation/DocumentAnimations.cpp
new file mode 100644
index 0000000..69085bf
--- /dev/null
+++ b/Source/core/animation/DocumentAnimations.cpp
@@ -0,0 +1,108 @@
+/*
+ * 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/animation/DocumentAnimations.h"
+
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationClock.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/Node.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderView.h"
+
+namespace WebCore {
+
+namespace {
+
+void updateAnimationTiming(Document& document, double monotonicAnimationStartTime)
+{
+    document.animationClock().updateTime(monotonicAnimationStartTime);
+    bool didTriggerStyleRecalc = document.timeline()->serviceAnimations();
+    didTriggerStyleRecalc |= document.transitionTimeline()->serviceAnimations();
+    if (!didTriggerStyleRecalc)
+        document.animationClock().unfreeze();
+}
+
+void dispatchAnimationEvents(Document& document)
+{
+    document.timeline()->dispatchEvents();
+    document.transitionTimeline()->dispatchEvents();
+}
+
+void dispatchAnimationEventsAsync(Document& document)
+{
+    document.timeline()->dispatchEventsAsync();
+    document.transitionTimeline()->dispatchEventsAsync();
+}
+
+} // namespace
+
+void DocumentAnimations::serviceOnAnimationFrame(Document& document, double monotonicAnimationStartTime)
+{
+    if (!RuntimeEnabledFeatures::webAnimationsEnabled())
+        return;
+
+    updateAnimationTiming(document, monotonicAnimationStartTime);
+    dispatchAnimationEvents(document);
+}
+
+void DocumentAnimations::serviceBeforeGetComputedStyle(Node& node, CSSPropertyID property)
+{
+    if (!RuntimeEnabledFeatures::webAnimationsEnabled())
+        return;
+
+    if (node.isElementNode()) {
+        const Element& element = toElement(node);
+        if (const ActiveAnimations* activeAnimations = element.activeAnimations()) {
+            if (activeAnimations->hasActiveAnimationsOnCompositor(property))
+                updateAnimationTiming(element.document(), monotonicallyIncreasingTime());
+        }
+    }
+
+}
+
+void DocumentAnimations::serviceAfterStyleRecalc(Document& document)
+{
+    if (!RuntimeEnabledFeatures::webAnimationsEnabled())
+        return;
+
+    if (document.cssPendingAnimations().startPendingAnimations() && document.view())
+        document.view()->scheduleAnimation();
+
+    document.animationClock().unfreeze();
+    dispatchAnimationEventsAsync(document);
+}
+
+} // namespace WebCore
diff --git a/Source/core/rendering/RenderingConfiguration.cpp b/Source/core/animation/DocumentAnimations.h
similarity index 76%
rename from Source/core/rendering/RenderingConfiguration.cpp
rename to Source/core/animation/DocumentAnimations.h
index 77060a3..b952c53 100644
--- a/Source/core/rendering/RenderingConfiguration.cpp
+++ b/Source/core/animation/DocumentAnimations.h
@@ -28,29 +28,27 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/rendering/RenderingConfiguration.h"
+#ifndef DocumentAnimations_h
+#define DocumentAnimations_h
 
-#include "core/dom/Document.h"
+#include "CSSPropertyNames.h"
 
 namespace WebCore {
 
-RenderingConfiguration::RenderingConfiguration()
-    : m_inQuirksMode(false)
-    , m_paginated(false)
-    , m_printing(false)
-{
-}
+class Document;
+class FrameView;
+class Node;
 
-RenderingConfiguration::~RenderingConfiguration()
-{
-}
+class DocumentAnimations  {
+public:
+    static void serviceOnAnimationFrame(Document&, double monotonicAnimationStartTime);
+    static void serviceBeforeGetComputedStyle(Node&, CSSPropertyID);
+    static void serviceAfterStyleRecalc(Document&);
 
-void RenderingConfiguration::update(Document& document)
-{
-    m_inQuirksMode = document.inQuirksMode();
-    m_paginated = document.paginated();
-    m_printing = document.printing();
-}
+private:
+    DocumentAnimations() { }
+};
 
-}
+} // namespace
+
+#endif
diff --git a/Source/core/animation/DocumentTimeline.cpp b/Source/core/animation/DocumentTimeline.cpp
index e8ee686..398e508 100644
--- a/Source/core/animation/DocumentTimeline.cpp
+++ b/Source/core/animation/DocumentTimeline.cpp
@@ -52,6 +52,7 @@
 DocumentTimeline::DocumentTimeline(Document* document, PassOwnPtr<PlatformTiming> timing)
     : m_zeroTime(nullValue())
     , m_document(document)
+    , m_eventDistpachTimer(this, &DocumentTimeline::eventDispatchTimerFired)
 {
     if (!timing)
         m_timing = adoptPtr(new DocumentTimelineTiming(this));
@@ -61,15 +62,21 @@
     ASSERT(document);
 }
 
-PassRefPtr<Player> DocumentTimeline::play(TimedItem* child)
+Player* DocumentTimeline::createPlayer(TimedItem* child)
 {
     RefPtr<Player> player = Player::create(*this, child);
-    m_players.append(player);
-
+    Player* result = player.get();
+    m_players.append(player.release());
     if (m_document->view())
         m_timing->serviceOnNextFrame();
+    return result;
+}
 
-    return player.release();
+Player* DocumentTimeline::play(TimedItem* child)
+{
+    Player* player = createPlayer(child);
+    player->setStartTime(currentTime());
+    return player;
 }
 
 void DocumentTimeline::wake()
@@ -102,9 +109,6 @@
             m_timing->wakeAfter(timeToNextEffect - s_minimumDelay);
     }
 
-    if (m_document->view() && !m_players.isEmpty())
-        m_document->view()->scheduleAnimation();
-
     return didTriggerStyleRecalc;
 }
 
@@ -152,11 +156,33 @@
         events[i].target->dispatchEvent(events[i].event.release());
 }
 
+void DocumentTimeline::dispatchEventsAsync()
+{
+    if (m_events.isEmpty() || m_eventDistpachTimer.isActive())
+        return;
+    m_eventDistpachTimer.startOneShot(0);
+}
+
+void DocumentTimeline::eventDispatchTimerFired(Timer<DocumentTimeline>*)
+{
+    dispatchEvents();
+}
+
 size_t DocumentTimeline::numberOfActiveAnimationsForTesting() const
 {
+    if (isNull(m_zeroTime))
+        return 0;
     // Includes all players whose directly associated timed items
     // are current or in effect.
-    return isNull(m_zeroTime) ? 0 : m_players.size();
+    if (isNull(m_zeroTime))
+        return 0;
+    size_t count = 0;
+    for (size_t i = 0; i < m_players.size(); ++i) {
+        const TimedItem* timedItem = m_players[i]->source();
+        if (m_players[i]->hasStartTime())
+            count += (timedItem && (timedItem->isCurrent() || timedItem->isInEffect()));
+    }
+    return count;
 }
 
 } // namespace
diff --git a/Source/core/animation/DocumentTimeline.h b/Source/core/animation/DocumentTimeline.h
index e48536e..25bf835 100644
--- a/Source/core/animation/DocumentTimeline.h
+++ b/Source/core/animation/DocumentTimeline.h
@@ -62,10 +62,16 @@
     static PassRefPtr<DocumentTimeline> create(Document*, PassOwnPtr<PlatformTiming> = nullptr);
     // Returns whether style recalc was triggered.
     bool serviceAnimations();
-    PassRefPtr<Player> play(TimedItem*);
+
+    // Creates a player attached to this timeline, but without a start time.
+    Player* createPlayer(TimedItem*);
+    Player* play(TimedItem*);
+
     // Called from setReadyState() in Document.cpp to set m_zeroTime to
     // performance.timing.domInteractive
     void setZeroTime(double);
+    bool hasStarted() const { return !isNull(m_zeroTime); }
+    double zeroTime() const { return m_zeroTime; }
     double currentTime();
     void pauseAnimationsForTesting(double);
     size_t numberOfActiveAnimationsForTesting() const;
@@ -76,6 +82,7 @@
     }
 
     void dispatchEvents();
+    void dispatchEventsAsync();
 
 protected:
     DocumentTimeline(Document*, PassOwnPtr<PlatformTiming>);
@@ -83,8 +90,10 @@
 private:
     double m_zeroTime;
     Document* m_document;
+    Timer<DocumentTimeline> m_eventDistpachTimer;
     Vector<RefPtr<Player> > m_players;
 
+    void eventDispatchTimerFired(Timer<DocumentTimeline>*);
     void wake();
 
     struct EventToDispatch {
@@ -123,7 +132,7 @@
 
     };
 
-    friend class CoreAnimationDocumentTimelineTest;
+    friend class AnimationDocumentTimelineTest;
 };
 
 } // namespace
diff --git a/Source/core/animation/DocumentTimelineTest.cpp b/Source/core/animation/DocumentTimelineTest.cpp
index fa5d042..41fad8c 100644
--- a/Source/core/animation/DocumentTimelineTest.cpp
+++ b/Source/core/animation/DocumentTimelineTest.cpp
@@ -38,7 +38,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/QualifiedName.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
@@ -79,7 +79,7 @@
     }
 };
 
-class CoreAnimationDocumentTimelineTest : public ::testing::Test {
+class AnimationDocumentTimelineTest : public ::testing::Test {
 protected:
     virtual void SetUp()
     {
@@ -122,7 +122,15 @@
     }
 };
 
-TEST_F(CoreAnimationDocumentTimelineTest, EmptyKeyframeAnimation)
+TEST_F(AnimationDocumentTimelineTest, HasStarted)
+{
+    timeline = DocumentTimeline::create(document.get());
+    EXPECT_FALSE(timeline->hasStarted());
+    timeline->setZeroTime(0);
+    EXPECT_TRUE(timeline->hasStarted());
+}
+
+TEST_F(AnimationDocumentTimelineTest, EmptyKeyframeAnimation)
 {
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector());
     RefPtr<Animation> anim = Animation::create(element.get(), effect, timing);
@@ -139,20 +147,20 @@
     EXPECT_FLOAT_EQ(100, timeline->currentTime());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, EmptyTimelineDoesNotTriggerStyleRecalc)
+TEST_F(AnimationDocumentTimelineTest, EmptyTimelineDoesNotTriggerStyleRecalc)
 {
     document->animationClock().updateTime(100);
     EXPECT_FALSE(timeline->serviceAnimations());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, EmptyPlayerDoesNotTriggerStyleRecalc)
+TEST_F(AnimationDocumentTimelineTest, EmptyPlayerDoesNotTriggerStyleRecalc)
 {
     timeline->play(0);
     document->animationClock().updateTime(100);
     EXPECT_FALSE(timeline->serviceAnimations());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, EmptyTargetDoesNotTriggerStyleRecalc)
+TEST_F(AnimationDocumentTimelineTest, EmptyTargetDoesNotTriggerStyleRecalc)
 {
     timing.iterationDuration = 200;
     timeline->play(Animation::create(0, KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing).get());
@@ -160,21 +168,21 @@
     EXPECT_FALSE(timeline->serviceAnimations());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, EmptyEffectDoesNotTriggerStyleRecalc)
+TEST_F(AnimationDocumentTimelineTest, EmptyEffectDoesNotTriggerStyleRecalc)
 {
     timeline->play(Animation::create(element.get(), 0, timing).get());
     document->animationClock().updateTime(100);
     EXPECT_FALSE(timeline->serviceAnimations());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, TriggerStyleRecalc)
+TEST_F(AnimationDocumentTimelineTest, TriggerStyleRecalc)
 {
     timeline->play(Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing).get());
     document->animationClock().updateTime(100);
     EXPECT_TRUE(timeline->serviceAnimations());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, ZeroTime)
+TEST_F(AnimationDocumentTimelineTest, ZeroTime)
 {
     timeline = DocumentTimeline::create(document.get());
 
@@ -192,20 +200,20 @@
     EXPECT_EQ(100, timeline->currentTime());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, PauseForTesting)
+TEST_F(AnimationDocumentTimelineTest, PauseForTesting)
 {
     float seekTime = 1;
     RefPtr<Animation> anim1 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing);
     RefPtr<Animation> anim2  = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing);
-    RefPtr<Player> player1 = timeline->play(anim1.get());
-    RefPtr<Player> player2 = timeline->play(anim2.get());
+    Player* player1 = timeline->play(anim1.get());
+    Player* player2 = timeline->play(anim2.get());
     timeline->pauseAnimationsForTesting(seekTime);
 
     EXPECT_FLOAT_EQ(seekTime, player1->currentTime());
     EXPECT_FLOAT_EQ(seekTime, player2->currentTime());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, NumberOfActiveAnimations)
+TEST_F(AnimationDocumentTimelineTest, NumberOfActiveAnimations)
 {
     Timing timingForwardFill;
     timingForwardFill.hasIterationDuration = true;
@@ -233,10 +241,10 @@
     RefPtr<Animation> anim3 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingBackwardFillDelay);
     RefPtr<Animation> anim4 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingNoFillDelay);
 
-    RefPtr<Player> player1 = timeline->play(anim1.get());
-    RefPtr<Player> player2 = timeline->play(anim2.get());
-    RefPtr<Player> player3 = timeline->play(anim3.get());
-    RefPtr<Player> player4 = timeline->play(anim4.get());
+    timeline->play(anim1.get());
+    timeline->play(anim2.get());
+    timeline->play(anim3.get());
+    timeline->play(anim4.get());
 
     platformTiming->expectNextFrameAction();
     updateClockAndService(0);
@@ -252,7 +260,7 @@
     EXPECT_EQ(1U, timeline->numberOfActiveAnimationsForTesting());
 }
 
-TEST_F(CoreAnimationDocumentTimelineTest, DelayBeforeAnimationStart)
+TEST_F(AnimationDocumentTimelineTest, DelayBeforeAnimationStart)
 {
     timing.hasIterationDuration = true;
     timing.iterationDuration = 2;
@@ -260,7 +268,7 @@
 
     RefPtr<Animation> anim = Animation::create(element.get(), 0, timing);
 
-    RefPtr<Player> player = timeline->play(anim.get());
+    timeline->play(anim.get());
 
     // TODO: Put the player startTime in the future when we add the capability to change player startTime
     platformTiming->expectDelayedAction(timing.startDelay - minimumDelay());
diff --git a/Source/core/animation/InertAnimation.cpp b/Source/core/animation/InertAnimation.cpp
index ef613d3..a7de9e2 100644
--- a/Source/core/animation/InertAnimation.cpp
+++ b/Source/core/animation/InertAnimation.cpp
@@ -52,7 +52,7 @@
 }
 
 
-double InertAnimation::calculateTimeToEffectChange(double, double, Phase) const
+double InertAnimation::calculateTimeToEffectChange(double, double) const
 {
     return std::numeric_limits<double>::infinity();
 }
diff --git a/Source/core/animation/InertAnimation.h b/Source/core/animation/InertAnimation.h
index d154891..2794acc 100644
--- a/Source/core/animation/InertAnimation.h
+++ b/Source/core/animation/InertAnimation.h
@@ -48,7 +48,7 @@
 protected:
     virtual bool updateChildrenAndEffects() const OVERRIDE { return false; };
     virtual void willDetach() OVERRIDE { };
-    virtual double calculateTimeToEffectChange(double inheritedTime, double activeTime, Phase) const OVERRIDE FINAL;
+    virtual double calculateTimeToEffectChange(double inheritedTime, double timeToNextIteration) const OVERRIDE FINAL;
 
 private:
     InertAnimation(PassRefPtr<AnimationEffect>, const Timing&, bool paused);
diff --git a/Source/core/animation/KeyframeAnimationEffect.cpp b/Source/core/animation/KeyframeAnimationEffect.cpp
index 240cbf4..d7e12d1 100644
--- a/Source/core/animation/KeyframeAnimationEffect.cpp
+++ b/Source/core/animation/KeyframeAnimationEffect.cpp
@@ -31,6 +31,8 @@
 #include "config.h"
 #include "core/animation/KeyframeAnimationEffect.h"
 
+#include "core/animation/TimedItem.h"
+
 #include "wtf/MathExtras.h"
 #include "wtf/text/StringHash.h"
 
@@ -119,6 +121,14 @@
     , m_composite(AnimationEffect::CompositeReplace)
 { }
 
+Keyframe::Keyframe(const Keyframe& copyFrom)
+    : m_offset(copyFrom.m_offset)
+    , m_composite(copyFrom.m_composite)
+{
+    for (PropertyValueMap::const_iterator iter = copyFrom.m_propertyValues.begin(); iter != copyFrom.m_propertyValues.end(); ++iter)
+        setPropertyValue(iter->key, iter->value.get());
+}
+
 void Keyframe::setPropertyValue(CSSPropertyID property, const AnimatableValue* value)
 {
     m_propertyValues.add(property, const_cast<AnimatableValue*>(value));
@@ -137,8 +147,8 @@
 
 PropertySet Keyframe::properties() const
 {
-    // This is only used when setting up the keyframe groups, so there's no
-    // need to cache the result.
+    // This is not used in time-critical code, so we probably don't need to
+    // worry about caching this result.
     PropertySet properties;
     for (PropertyValueMap::const_iterator iter = m_propertyValues.begin(); iter != m_propertyValues.end(); ++iter)
         properties.add(*iter.keys());
@@ -147,22 +157,37 @@
 
 PassRefPtr<Keyframe> Keyframe::cloneWithOffset(double offset) const
 {
-    RefPtr<Keyframe> clone = Keyframe::create();
-    clone->setOffset(offset);
-    clone->setComposite(m_composite);
-    for (PropertyValueMap::const_iterator iter = m_propertyValues.begin(); iter != m_propertyValues.end(); ++iter)
-        clone->setPropertyValue(iter->key, iter->value.get());
-    return clone.release();
+    RefPtr<Keyframe> theClone = clone();
+    theClone->setOffset(offset);
+    return theClone.release();
 }
 
-
 KeyframeAnimationEffect::KeyframeAnimationEffect(const KeyframeVector& keyframes)
     : m_keyframes(keyframes)
 {
 }
 
+PropertySet KeyframeAnimationEffect::properties() const
+{
+    PropertySet result;
+    const KeyframeVector& frames = getFrames();
+    if (!frames.size()) {
+        return result;
+    }
+    result = frames[0]->properties();
+    for (size_t i = 1; i < frames.size(); i++) {
+        PropertySet extras = frames[i]->properties();
+        for (PropertySet::const_iterator it = extras.begin(); it != extras.end(); ++it) {
+            result.add(*it);
+        }
+    }
+    return result;
+}
+
 PassOwnPtr<AnimationEffect::CompositableValueMap> KeyframeAnimationEffect::sample(int iteration, double fraction) const
 {
+    ASSERT(iteration >= 0);
+    ASSERT(!isNull(fraction));
     const_cast<KeyframeAnimationEffect*>(this)->ensureKeyframeGroups();
     OwnPtr<CompositableValueMap> map = adoptPtr(new CompositableValueMap());
     for (KeyframeGroupMap::const_iterator iter = m_keyframeGroups->begin(); iter != m_keyframeGroups->end(); ++iter)
@@ -195,7 +220,7 @@
     return keyframes;
 }
 
-void KeyframeAnimationEffect::ensureKeyframeGroups()
+void KeyframeAnimationEffect::ensureKeyframeGroups() const
 {
     if (m_keyframeGroups)
         return;
@@ -296,6 +321,7 @@
 {
     // FIXME: Implement accumulation.
     ASSERT_UNUSED(iteration, iteration >= 0);
+    ASSERT(!isNull(offset));
 
     double minimumOffset = m_keyframes.first()->offset();
     double maximumOffset = m_keyframes.last()->offset();
diff --git a/Source/core/animation/KeyframeAnimationEffect.h b/Source/core/animation/KeyframeAnimationEffect.h
index ea1b401..0d92542 100644
--- a/Source/core/animation/KeyframeAnimationEffect.h
+++ b/Source/core/animation/KeyframeAnimationEffect.h
@@ -63,9 +63,11 @@
     void clearPropertyValue(CSSPropertyID);
     const AnimatableValue* propertyValue(CSSPropertyID) const;
     PropertySet properties() const;
+    PassRefPtr<Keyframe> clone() const { return adoptRef(new Keyframe(*this)); }
     PassRefPtr<Keyframe> cloneWithOffset(double offset) const;
 private:
     Keyframe();
+    Keyframe(const Keyframe&);
     double m_offset;
     AnimationEffect::CompositeOperation m_composite;
     typedef HashMap<CSSPropertyID, RefPtr<AnimatableValue> > PropertyValueMap;
@@ -74,20 +76,31 @@
 
 class KeyframeAnimationEffect : public AnimationEffect {
 public:
+    class PropertySpecificKeyframe;
     typedef Vector<RefPtr<Keyframe> > KeyframeVector;
+    typedef Vector<OwnPtr<KeyframeAnimationEffect::PropertySpecificKeyframe> > PropertySpecificKeyframeVector;
     // FIXME: Implement accumulation.
     static PassRefPtr<KeyframeAnimationEffect> create(const KeyframeVector& keyframes)
     {
         return adoptRef(new KeyframeAnimationEffect(keyframes));
     }
 
+    virtual bool affects(CSSPropertyID property) OVERRIDE
+    {
+        ensureKeyframeGroups();
+        return m_keyframeGroups->contains(property);
+    }
+
     // AnimationEffect implementation.
     virtual PassOwnPtr<CompositableValueMap> sample(int iteration, double fraction) const OVERRIDE;
 
     // FIXME: Implement setFrames()
     const KeyframeVector& getFrames() const { return m_keyframes; }
 
-private:
+    virtual bool isKeyframeAnimationEffect() const OVERRIDE { return true; }
+
+    PropertySet properties() const;
+
     class PropertySpecificKeyframe {
     public:
         PropertySpecificKeyframe(double offset, const AnimatableValue*, CompositeOperation);
@@ -104,28 +117,39 @@
     class PropertySpecificKeyframeGroup {
     public:
         void appendKeyframe(PassOwnPtr<PropertySpecificKeyframe>);
+        PassRefPtr<CompositableValue> sample(int iteration, double offset) const;
+        const PropertySpecificKeyframeVector& keyframes() const { return m_keyframes; }
+    private:
+        PropertySpecificKeyframeVector m_keyframes;
         void removeRedundantKeyframes();
         void addSyntheticKeyframeIfRequired();
-        PassRefPtr<CompositableValue> sample(int iteration, double offset) const;
-    private:
-        typedef Vector<OwnPtr<PropertySpecificKeyframe> > PropertySpecificKeyframeVector;
-        PropertySpecificKeyframeVector m_keyframes;
+
+        friend class KeyframeAnimationEffect;
     };
 
+    const PropertySpecificKeyframeVector& getPropertySpecificKeyframes(CSSPropertyID id) const
+    {
+        ensureKeyframeGroups();
+        return m_keyframeGroups->get(id)->keyframes();
+    }
+
+private:
     KeyframeAnimationEffect(const KeyframeVector& keyframes);
 
     KeyframeVector normalizedKeyframes() const;
     // Lazily computes the groups of property-specific keyframes.
-    void ensureKeyframeGroups();
+    void ensureKeyframeGroups() const;
 
     KeyframeVector m_keyframes;
     // The spec describes filtering the normalized keyframes at sampling time
     // to get the 'property-specific keyframes'. For efficiency, we cache the
     // property-specific lists.
     typedef HashMap<CSSPropertyID, OwnPtr<PropertySpecificKeyframeGroup> > KeyframeGroupMap;
-    OwnPtr<KeyframeGroupMap> m_keyframeGroups;
+    mutable OwnPtr<KeyframeGroupMap> m_keyframeGroups;
 };
 
+DEFINE_TYPE_CASTS(KeyframeAnimationEffect, AnimationEffect, value, value->isKeyframeAnimationEffect(), value.isKeyframeAnimationEffect());
+
 } // namespace WebCore
 
 #endif // KeyframeAnimationEffect_h
diff --git a/Source/core/animation/KeyframeAnimationEffectTest.cpp b/Source/core/animation/KeyframeAnimationEffectTest.cpp
index 13c260f..58472a6 100644
--- a/Source/core/animation/KeyframeAnimationEffectTest.cpp
+++ b/Source/core/animation/KeyframeAnimationEffectTest.cpp
@@ -76,17 +76,17 @@
 }
 
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, BasicOperation)
+TEST(AnimationKeyframeAnimationEffectTest, BasicOperation)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
     OwnPtr<AnimationEffect::CompositableValueMap> values = effect->sample(0, 0.6);
-    ASSERT_EQ(1, values->size());
+    ASSERT_EQ(1UL, values->size());
     EXPECT_EQ(CSSPropertyLeft, values->begin()->key);
     expectDoubleValue(5.0, values->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, CompositeReplaceNonInterpolable)
+TEST(AnimationKeyframeAnimationEffectTest, CompositeReplaceNonInterpolable)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
@@ -95,7 +95,7 @@
     expectDoubleValue(5.0, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, CompositeReplace)
+TEST(AnimationKeyframeAnimationEffectTest, CompositeReplace)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
@@ -104,7 +104,7 @@
     expectDoubleValue(3.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, CompositeAdd)
+TEST(AnimationKeyframeAnimationEffectTest, CompositeAdd)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
@@ -113,7 +113,7 @@
     expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, ExtrapolateReplaceNonInterpolable)
+TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateReplaceNonInterpolable)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
@@ -122,7 +122,7 @@
     expectDoubleValue(5.0, effect->sample(0, 1.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, ExtrapolateReplace)
+TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateReplace)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
@@ -131,7 +131,7 @@
     expectDoubleValue(3.0 * -0.6 + 5.0 * 1.6, effect->sample(0, 1.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, ExtrapolateAdd)
+TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateAdd)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
@@ -140,13 +140,13 @@
     expectDoubleValue((7.0 + 3.0) * -0.6 + (7.0 + 5.0) * 1.6, effect->sample(0, 1.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, ZeroKeyframes)
+TEST(AnimationKeyframeAnimationEffectTest, ZeroKeyframes)
 {
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector());
     EXPECT_TRUE(effect->sample(0, 0.5)->isEmpty());
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetZero)
+TEST(AnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetZero)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(1);
     keyframes[0] = Keyframe::create();
@@ -157,7 +157,7 @@
     expectDoubleValue(3.0, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetOne)
+TEST(AnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetOne)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(1);
     keyframes[0] = Keyframe::create();
@@ -168,7 +168,7 @@
     expectDoubleValue(7.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, MoreThanTwoKeyframes)
+TEST(AnimationKeyframeAnimationEffectTest, MoreThanTwoKeyframes)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(3);
     keyframes[0] = Keyframe::create();
@@ -186,7 +186,7 @@
     expectDoubleValue(5.0, effect->sample(0, 0.8)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, EndKeyframeOffsetsUnspecified)
+TEST(AnimationKeyframeAnimationEffectTest, EndKeyframeOffsetsUnspecified)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(3);
     keyframes[0] = Keyframe::create();
@@ -203,7 +203,7 @@
     expectDoubleValue(5.0, effect->sample(0, 0.9)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, SampleOnKeyframe)
+TEST(AnimationKeyframeAnimationEffectTest, SampleOnKeyframe)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(3);
     keyframes[0] = Keyframe::create();
@@ -223,7 +223,7 @@
 }
 
 // Note that this tests an implementation detail, not behaviour defined by the spec.
-TEST(CoreAnimationKeyframeAnimationEffectTest, SampleReturnsSameAnimatableValueInstance)
+TEST(AnimationKeyframeAnimationEffectTest, SampleReturnsSameAnimatableValueInstance)
 {
     AnimatableValue* threePixelsValue = unknownAnimatableValue(3.0);
     AnimatableValue* fourPixelsValue = unknownAnimatableValue(4.0);
@@ -250,7 +250,7 @@
     EXPECT_EQ(fivePixelsValue, effect->sample(0, 1.0)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, MultipleKeyframesWithSameOffset)
+TEST(AnimationKeyframeAnimationEffectTest, MultipleKeyframesWithSameOffset)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(7);
     keyframes[0] = Keyframe::create();
@@ -285,7 +285,7 @@
     expectDoubleValue(6.0, effect->sample(0, 1.0)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, PerKeyframeComposite)
+TEST(AnimationKeyframeAnimationEffectTest, PerKeyframeComposite)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(2);
     keyframes[0] = Keyframe::create();
@@ -300,7 +300,7 @@
     expectDoubleValue(3.0 * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, MultipleProperties)
+TEST(AnimationKeyframeAnimationEffectTest, MultipleProperties)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(2);
     keyframes[0] = Keyframe::create();
@@ -314,14 +314,14 @@
 
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
     OwnPtr<AnimationEffect::CompositableValueMap> values = effect->sample(0, 0.6);
-    ASSERT_EQ(2, values->size());
+    ASSERT_EQ(2UL, values->size());
     ASSERT_TRUE(values->contains(CSSPropertyLeft));
     expectDoubleValue(5.0, values->get(CSSPropertyLeft)->compositeOnto(unknownAnimatableValue(7.0)));
     ASSERT_TRUE(values->contains(CSSPropertyRight));
     expectDoubleValue(6.0, values->get(CSSPropertyRight)->compositeOnto(unknownAnimatableValue(7.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, RecompositeCompositableValue)
+TEST(AnimationKeyframeAnimationEffectTest, RecompositeCompositableValue)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
@@ -332,7 +332,7 @@
     expectDoubleValue((9.0 + 3.0) * 0.4 + (9.0 + 5.0) * 0.6, values->begin()->value->compositeOnto(pixelAnimatableValue(9.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, MultipleIterations)
+TEST(AnimationKeyframeAnimationEffectTest, MultipleIterations)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(1.0), pixelAnimatableValue(3.0));
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
@@ -341,7 +341,7 @@
     expectDoubleValue(2.0, effect->sample(2, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(0.0)));
 }
 
-TEST(CoreAnimationKeyframeAnimationEffectTest, DependsOnUnderlyingValue)
+TEST(AnimationKeyframeAnimationEffectTest, DependsOnUnderlyingValue)
 {
     KeyframeAnimationEffect::KeyframeVector keyframes(3);
     keyframes[0] = Keyframe::create();
@@ -367,4 +367,13 @@
     EXPECT_FALSE(effect->sample(0, 1)->begin()->value->dependsOnUnderlyingValue());
 }
 
+TEST(AnimationKeyframeAnimationEffectTest, ToKeyframeAnimationEffect)
+{
+    KeyframeAnimationEffect::KeyframeVector keyframes(0);
+    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
+
+    AnimationEffect* baseEffect = effect.get();
+    EXPECT_TRUE(toKeyframeAnimationEffect(baseEffect));
+}
+
 } // namespace
diff --git a/Source/core/animation/Player.cpp b/Source/core/animation/Player.cpp
index 35f7d97..1d3b0af 100644
--- a/Source/core/animation/Player.cpp
+++ b/Source/core/animation/Player.cpp
@@ -32,6 +32,7 @@
 #include "config.h"
 #include "core/animation/Player.h"
 
+#include "core/animation/Animation.h"
 #include "core/animation/DocumentTimeline.h"
 #include "core/animation/TimedItem.h"
 
@@ -52,15 +53,14 @@
     : m_pauseStartTime(nullValue())
     , m_playbackRate(1)
     , m_timeDrift(0)
-    , m_startTime(effectiveTime(timeline.currentTime()))
+    , m_startTime(nullValue())
+    , m_lastUpdateTime(nullValue())
     , m_content(content)
     , m_timeline(timeline)
     , m_isPausedForTesting(false)
 {
-    ASSERT(m_startTime >= 0);
     if (m_content)
         m_content->attach(this);
-    update();
 }
 
 Player::~Player()
@@ -69,9 +69,43 @@
         m_content->detach();
 }
 
+void Player::setStartTime(double startTime)
+{
+    ASSERT(!isNull(startTime));
+    ASSERT(!hasStartTime());
+    m_startTime = startTime;
+    update();
+}
+
 double Player::currentTimeBeforeDrift() const
 {
-    return (effectiveTime(m_timeline.currentTime()) - m_startTime) * m_playbackRate;
+    if (isNull(m_startTime))
+        return 0;
+    return (effectiveTime(m_timeline.currentTime()) - startTime()) * m_playbackRate;
+}
+
+bool Player::maybeStartAnimationOnCompositor()
+{
+    // FIXME: Support starting compositor animations that have a fixed
+    // start time.
+    ASSERT(!hasStartTime());
+    if (!m_content || !m_content->isAnimation())
+        return false;
+
+    return toAnimation(m_content.get())->maybeStartAnimationOnCompositor();
+}
+
+bool Player::hasActiveAnimationsOnCompositor()
+{
+    if (!m_content || !m_content->isAnimation())
+        return false;
+    return toAnimation(m_content.get())->hasActiveAnimationsOnCompositor();
+}
+
+void Player::cancelAnimationOnCompositor()
+{
+    if (hasActiveAnimationsOnCompositor())
+        toAnimation(m_content.get())->cancelAnimationOnCompositor();
 }
 
 double Player::pausedTimeDrift() const
@@ -101,7 +135,12 @@
     }
 
     double newTime = isNull(m_timeline.currentTime()) ? nullValue() : currentTime();
-    bool didTriggerStyleRecalcLocal = m_content->updateInheritedTime(newTime);
+    bool didTriggerStyleRecalcLocal = false;
+    // FIXME: Further checks will be required once the animation tree can be mutated.
+    if (newTime != m_lastUpdateTime) {
+        didTriggerStyleRecalcLocal = m_content->updateInheritedTime(newTime);
+        m_lastUpdateTime = newTime;
+    }
     if (timeToEffectChange)
         *timeToEffectChange = m_content->timeToEffectChange();
     if (didTriggerStyleRecalc)
@@ -126,12 +165,16 @@
     else
         m_timeDrift = currentTimeBeforeDrift() - seekTime;
 
+    if (m_isPausedForTesting && hasActiveAnimationsOnCompositor())
+        toAnimation(m_content.get())->pauseAnimationForTestingOnCompositor(currentTime());
     update();
 }
 
 void Player::pauseForTesting()
 {
-    ASSERT(!paused());
+    RELEASE_ASSERT(!paused());
+    if (!m_isPausedForTesting && hasActiveAnimationsOnCompositor())
+        toAnimation(m_content.get())->pauseAnimationForTestingOnCompositor(currentTime());
     m_isPausedForTesting = true;
     setPausedImpl(true);
 }
@@ -147,9 +190,11 @@
     if (pausedInternal() == newValue)
         return;
 
-    if (newValue)
+    if (newValue) {
+        // FIXME: resume compositor animation rather than pull back to main-thread
+        cancelAnimationOnCompositor();
         m_pauseStartTime = currentTime();
-    else {
+    } else {
         m_timeDrift = pausedTimeDrift();
         m_pauseStartTime = nullValue();
     }
diff --git a/Source/core/animation/Player.h b/Source/core/animation/Player.h
index 59d4787..b9a90a8 100644
--- a/Source/core/animation/Player.h
+++ b/Source/core/animation/Player.h
@@ -50,17 +50,23 @@
     //  0         - if this player requires an update on the next frame
     //  n         - if this player requires an update after 'n' units of time
     bool update(double* timeToEffectChange = 0, bool* didTriggerStyleRecalc = 0);
-
     void cancel();
+
     double currentTime() const;
     void setCurrentTime(double);
+
     bool paused() const { return !m_isPausedForTesting && pausedInternal(); }
     void setPaused(bool);
+
     double playbackRate() const { return m_playbackRate; }
     void setPlaybackRate(double);
-    double startTime() const { return m_startTime; }
     double timeDrift() const;
     DocumentTimeline& timeline() { return m_timeline; }
+
+    bool hasStartTime() const { return !isNull(m_startTime); }
+    double startTime() const { return m_startTime; }
+    void setStartTime(double);
+
     TimedItem* source() { return m_content.get(); }
 
     // Pausing via this method is not reflected in the value returned by
@@ -69,17 +75,23 @@
     // Reflects all pausing, including via pauseForTesting().
     bool pausedInternal() const { return !isNull(m_pauseStartTime); }
 
+    bool maybeStartAnimationOnCompositor();
+    void cancelAnimationOnCompositor();
+    bool hasActiveAnimationsOnCompositor();
+
 private:
     Player(DocumentTimeline&, TimedItem*);
     inline double pausedTimeDrift() const;
     inline double currentTimeBeforeDrift() const;
 
+
     void setPausedImpl(bool);
 
     double m_pauseStartTime;
     double m_playbackRate;
     double m_timeDrift;
-    const double m_startTime;
+    double m_startTime;
+    double m_lastUpdateTime;
 
     RefPtr<TimedItem> m_content;
     DocumentTimeline& m_timeline;
diff --git a/Source/core/animation/PlayerTest.cpp b/Source/core/animation/PlayerTest.cpp
index cf87c6b..ee79f37 100644
--- a/Source/core/animation/PlayerTest.cpp
+++ b/Source/core/animation/PlayerTest.cpp
@@ -31,19 +31,20 @@
 #include "config.h"
 #include "core/animation/Player.h"
 
+#include "core/animation/ActiveAnimations.h"
 #include "core/animation/Animation.h"
 #include "core/animation/AnimationClock.h"
 #include "core/animation/DocumentTimeline.h"
 #include "core/dom/Document.h"
 #include "core/dom/QualifiedName.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include <gtest/gtest.h>
 
 using namespace WebCore;
 
 namespace {
 
-class CoreAnimationPlayerTest : public ::testing::Test {
+class AnimationPlayerTest : public ::testing::Test {
 protected:
     virtual void SetUp()
     {
@@ -51,6 +52,7 @@
         document->animationClock().resetTimeForTesting();
         timeline = DocumentTimeline::create(document.get());
         player = Player::create(*timeline, 0);
+        player->setStartTime(0);
         timeline->setZeroTime(0);
     }
 
@@ -66,7 +68,7 @@
     RefPtr<Player> player;
 };
 
-TEST_F(CoreAnimationPlayerTest, InitialState)
+TEST_F(AnimationPlayerTest, InitialState)
 {
     EXPECT_EQ(0, timeline->currentTime());
     EXPECT_EQ(0, player->currentTime());
@@ -76,16 +78,7 @@
     EXPECT_EQ(0, player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, CreatePlayerAfterTimelineStarted)
-{
-    updateTimeline(1234);
-    EXPECT_EQ(1234, timeline->currentTime());
-    RefPtr<Player> player = Player::create(*timeline, 0);
-    EXPECT_EQ(1234, player->startTime());
-    EXPECT_EQ(0, player->currentTime());
-}
-
-TEST_F(CoreAnimationPlayerTest, PauseUnpause)
+TEST_F(AnimationPlayerTest, PauseUnpause)
 {
     updateTimeline(200);
     player->setPaused(true);
@@ -104,7 +97,7 @@
     EXPECT_EQ(200, player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, PauseBeforeTimelineStarted)
+TEST_F(AnimationPlayerTest, PauseBeforeTimelineStarted)
 {
     player->setPaused(true);
     EXPECT_TRUE(player->paused());
@@ -127,7 +120,27 @@
     EXPECT_EQ(100, player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetCurrentTime)
+TEST_F(AnimationPlayerTest, PauseBeforeStartTimeSet)
+{
+    player = Player::create(*timeline, 0);
+    updateTimeline(100);
+    EXPECT_EQ(0, player->currentTime());
+
+    player->setPaused(true);
+    updateTimeline(200);
+    EXPECT_EQ(0, player->currentTime());
+
+    player->setStartTime(150);
+    EXPECT_EQ(0, player->currentTime());
+
+    player->setPaused(false);
+    EXPECT_EQ(0, player->currentTime());
+
+    updateTimeline(300);
+    EXPECT_EQ(100, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetCurrentTime)
 {
     updateTimeline(0);
     player->setCurrentTime(250);
@@ -135,7 +148,26 @@
     EXPECT_EQ(-250, player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetCurrentTimeBeforeTimelineStarted)
+TEST_F(AnimationPlayerTest, SetStartTime)
+{
+    updateTimeline(0);
+    player = Player::create(*timeline, 0);
+    EXPECT_FALSE(player->hasStartTime());
+    EXPECT_TRUE(isNull(player->startTime()));
+    EXPECT_EQ(0, player->currentTime());
+
+    updateTimeline(100);
+    player->setStartTime(50);
+    EXPECT_TRUE(player->hasStartTime());
+    EXPECT_EQ(50, player->startTime());
+    EXPECT_EQ(50, player->currentTime());
+
+    updateTimeline(200);
+    EXPECT_EQ(150, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, SetCurrentTimeBeforeTimelineStarted)
 {
     player->setCurrentTime(250);
     EXPECT_EQ(250, player->currentTime());
@@ -145,7 +177,21 @@
     EXPECT_EQ(250, player->currentTime());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetPlaybackRate)
+TEST_F(AnimationPlayerTest, SetCurrentTimeBeforeStartTimeSet)
+{
+    updateTimeline(0);
+    player = Player::create(*timeline, 0);
+
+    player->setCurrentTime(250);
+    EXPECT_EQ(250, player->currentTime());
+    EXPECT_EQ(-250, player->timeDrift());
+
+    updateTimeline(100);
+    player->setStartTime(50);
+    EXPECT_EQ(300, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetPlaybackRate)
 {
     updateTimeline(0);
     player->setPlaybackRate(2);
@@ -158,7 +204,7 @@
     EXPECT_EQ(0, player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetPlaybackRateBeforeTimelineStarted)
+TEST_F(AnimationPlayerTest, SetPlaybackRateBeforeTimelineStarted)
 {
     player->setPlaybackRate(2);
     EXPECT_EQ(0, player->currentTime());
@@ -169,7 +215,7 @@
     EXPECT_EQ(0, player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetPlaybackRateWhilePaused)
+TEST_F(AnimationPlayerTest, SetPlaybackRateWhilePaused)
 {
     updateTimeline(100);
     player->setPaused(true);
@@ -187,7 +233,7 @@
     EXPECT_EQ(300, player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetPlaybackRateNaN)
+TEST_F(AnimationPlayerTest, SetPlaybackRateNaN)
 {
     updateTimeline(0);
     player->setPlaybackRate(nullValue());
@@ -200,7 +246,7 @@
     EXPECT_TRUE(isNull(player->timeDrift()));
 }
 
-TEST_F(CoreAnimationPlayerTest, SetPlaybackRateInfinity)
+TEST_F(AnimationPlayerTest, SetPlaybackRateInfinity)
 {
     updateTimeline(0);
     player->setPlaybackRate(std::numeric_limits<double>::infinity());
@@ -213,7 +259,7 @@
     EXPECT_TRUE(isNull(player->timeDrift()));
 }
 
-TEST_F(CoreAnimationPlayerTest, SetPlaybackRateMax)
+TEST_F(AnimationPlayerTest, SetPlaybackRateMax)
 {
     updateTimeline(0);
     player->setPlaybackRate(std::numeric_limits<double>::max());
@@ -225,7 +271,7 @@
     EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetCurrentTimeNan)
+TEST_F(AnimationPlayerTest, SetCurrentTimeNan)
 {
     updateTimeline(0);
     player->setCurrentTime(nullValue());
@@ -237,7 +283,7 @@
     EXPECT_TRUE(isNull(player->timeDrift()));
 }
 
-TEST_F(CoreAnimationPlayerTest, SetCurrentTimeInfinity)
+TEST_F(AnimationPlayerTest, SetCurrentTimeInfinity)
 {
     updateTimeline(0);
     player->setCurrentTime(std::numeric_limits<double>::infinity());
@@ -249,7 +295,7 @@
     EXPECT_EQ(-std::numeric_limits<double>::infinity(), player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, SetCurrentTimeMax)
+TEST_F(AnimationPlayerTest, SetCurrentTimeMax)
 {
     updateTimeline(0);
     player->setCurrentTime(std::numeric_limits<double>::max());
@@ -261,7 +307,7 @@
     EXPECT_EQ(-std::numeric_limits<double>::max(), player->timeDrift());
 }
 
-TEST_F(CoreAnimationPlayerTest, EmptyPlayersDontUpdateEffects)
+TEST_F(AnimationPlayerTest, EmptyPlayersDontUpdateEffects)
 {
     double timeToNextEffect;
     updateTimeline(0, &timeToNextEffect);
@@ -272,7 +318,7 @@
     EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
 }
 
-TEST_F(CoreAnimationPlayerTest, PlayersReturnTimeToNextEffect)
+TEST_F(AnimationPlayerTest, PlayersReturnTimeToNextEffect)
 {
     Timing timing;
     timing.startDelay = 1;
@@ -280,6 +326,7 @@
     timing.hasIterationDuration = true;
     RefPtr<Animation> animation = Animation::create(0, 0, timing);
     player = Player::create(*timeline, animation.get());
+    player->setStartTime(0);
 
     double timeToNextEffect;
     updateTimeline(0, &timeToNextEffect);
@@ -301,4 +348,17 @@
     EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
 }
 
+TEST_F(AnimationPlayerTest, AttachedPlayers)
+{
+    RefPtr<Element> element = document->createElement("foo", ASSERT_NO_EXCEPTION);
+
+    Timing timing;
+    RefPtr<Animation> animation = Animation::create(element, 0, timing);
+    RefPtr<Player> player = Player::create(*timeline, animation.get());
+    ASSERT_EQ(1U, element->activeAnimations()->players().find(player.get())->value);
+
+    player.release();
+    ASSERT_TRUE(element->activeAnimations()->players().isEmpty());
+}
+
 }
diff --git a/Source/core/animation/TimedItem.cpp b/Source/core/animation/TimedItem.cpp
index 5c630d5..582863b 100644
--- a/Source/core/animation/TimedItem.cpp
+++ b/Source/core/animation/TimedItem.cpp
@@ -43,7 +43,7 @@
     , m_calculated()
     , m_isFirstSample(true)
 {
-    timing.assertValid();
+    m_specified.assertValid();
 }
 
 bool TimedItem::updateInheritedTime(double inheritedTime) const
@@ -52,40 +52,53 @@
     const double iterationDuration = m_specified.hasIterationDuration
         ? m_specified.iterationDuration
         : intrinsicIterationDuration();
+    ASSERT(iterationDuration >= 0);
 
-    const double repeatedDuration = iterationDuration * m_specified.iterationCount;
+    // When iterationDuration = 0 and iterationCount = infinity,
+    // repeatedDuration should be 0, not NaN as operator*() would give.
+    // FIXME: The spec is unclear about this.
+    const double repeatedDuration = iterationDuration
+        ? iterationDuration * m_specified.iterationCount
+        : 0;
+    ASSERT(repeatedDuration >= 0);
     const double activeDuration = m_specified.playbackRate
         ? repeatedDuration / abs(m_specified.playbackRate)
         : std::numeric_limits<double>::infinity();
+    ASSERT(activeDuration >= 0);
 
     const Phase currentPhase = calculatePhase(activeDuration, localTime, m_specified);
     // FIXME: parentPhase depends on groups being implemented.
     const TimedItem::Phase parentPhase = TimedItem::PhaseActive;
     const double activeTime = calculateActiveTime(activeDuration, localTime, parentPhase, currentPhase, m_specified);
 
-    double currentIteration = nullValue();
-    double timeFraction = nullValue();
-    ASSERT(iterationDuration >= 0);
+    double currentIteration;
+    double timeFraction;
+    double timeToNextIteration = nullValue();
     if (iterationDuration) {
         const double startOffset = m_specified.iterationStart * iterationDuration;
+        ASSERT(startOffset >= 0);
         const double scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, m_specified);
         const double iterationTime = calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, m_specified);
 
         currentIteration = calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, m_specified);
         timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified) / iterationDuration;
+        timeToNextIteration = (iterationDuration - iterationTime) / abs(m_specified.playbackRate);
     } else {
-        const double iterationDuration = 1;
-        const double repeatedDuration = iterationDuration * m_specified.iterationCount;
-        const double activeDuration = m_specified.playbackRate ? repeatedDuration / abs(m_specified.playbackRate) : std::numeric_limits<double>::infinity();
-        const double newLocalTime = localTime < m_specified.startDelay ? m_specified.startDelay - 1 : activeDuration + m_specified.startDelay;
-        const TimedItem::Phase localPhase = calculatePhase(activeDuration, newLocalTime, m_specified);
-        const double activeTime = calculateActiveTime(activeDuration, newLocalTime, parentPhase, localPhase, m_specified);
-        const double startOffset = m_specified.iterationStart * iterationDuration;
-        const double scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, m_specified);
-        const double iterationTime = calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, m_specified);
+        const double localIterationDuration = 1;
+        const double localRepeatedDuration = localIterationDuration * m_specified.iterationCount;
+        ASSERT(localRepeatedDuration >= 0);
+        const double localActiveDuration = m_specified.playbackRate ? localRepeatedDuration / abs(m_specified.playbackRate) : std::numeric_limits<double>::infinity();
+        ASSERT(localActiveDuration >= 0);
+        const double localLocalTime = localTime < m_specified.startDelay ? m_specified.startDelay - 1 : localActiveDuration + m_specified.startDelay;
+        const TimedItem::Phase localCurrentPhase = calculatePhase(localActiveDuration, localLocalTime, m_specified);
+        const double localActiveTime = calculateActiveTime(localActiveDuration, localLocalTime, parentPhase, localCurrentPhase, m_specified);
+        const double startOffset = m_specified.iterationStart * localIterationDuration;
+        ASSERT(startOffset >= 0);
+        const double scaledActiveTime = calculateScaledActiveTime(localActiveDuration, localActiveTime, startOffset, m_specified);
+        const double iterationTime = calculateIterationTime(localIterationDuration, localRepeatedDuration, scaledActiveTime, startOffset, m_specified);
 
-        currentIteration = calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, m_specified);
-        timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified);
+        currentIteration = calculateCurrentIteration(localIterationDuration, iterationTime, scaledActiveTime, m_specified);
+        timeFraction = calculateTransformedTime(currentIteration, localIterationDuration, iterationTime, m_specified);
     }
 
     const double previousIteration = m_calculated.currentIteration;
@@ -108,7 +121,10 @@
     // FIXME: This probably shouldn't be recursive.
     bool didTriggerStyleRecalc = updateChildrenAndEffects();
 
-    m_calculated.timeToEffectChange = calculateTimeToEffectChange(localTime, m_startTime + m_specified.startDelay, m_calculated.phase);
+    if (activeDuration - activeTime < timeToNextIteration)
+        timeToNextIteration = nullValue();
+
+    m_calculated.timeToEffectChange = calculateTimeToEffectChange(localTime, timeToNextIteration);
     return didTriggerStyleRecalc;
 }
 
diff --git a/Source/core/animation/TimedItem.h b/Source/core/animation/TimedItem.h
index aa2ab26..ae95014 100644
--- a/Source/core/animation/TimedItem.h
+++ b/Source/core/animation/TimedItem.h
@@ -70,20 +70,20 @@
 
     virtual ~TimedItem() { }
 
+    virtual bool isAnimation() const { return false; }
+
     Phase phase() const { return ensureCalculated().phase; }
     bool isCurrent() const { return ensureCalculated().isCurrent; }
     bool isInEffect() const { return ensureCalculated().isInEffect; }
     bool isInPlay() const { return ensureCalculated().isInPlay; }
     double timeToEffectChange() const { return ensureCalculated().timeToEffectChange; }
 
-    double startTime() const { return m_startTime; }
-
     double currentIteration() const { return ensureCalculated().currentIteration; }
     double activeDuration() const { return ensureCalculated().activeDuration; }
     double timeFraction() const { return ensureCalculated().timeFraction; }
+    double startTime() const { return m_startTime; }
     const Player* player() const { return m_player; }
     Player* player() { return m_player; }
-
     const Timing& specified() const { return m_specified; }
 
 protected:
@@ -99,10 +99,16 @@
     // Returns whether style recalc was triggered.
     virtual bool updateChildrenAndEffects() const = 0;
     virtual double intrinsicIterationDuration() const { return 0; };
-    virtual void willDetach() = 0;
-    virtual double calculateTimeToEffectChange(double inheritedTime, double activeTime, Phase) const = 0;
+    virtual double calculateTimeToEffectChange(double localTime, double timeToNextIteration) const = 0;
+    virtual void didAttach() { };
+    virtual void willDetach() { };
 
-    void attach(Player* player) { m_player = player; };
+    void attach(Player* player)
+    {
+        m_player = player;
+        didAttach();
+    };
+
     void detach()
     {
         ASSERT(m_player);
diff --git a/Source/core/animation/TimedItemCalculations.h b/Source/core/animation/TimedItemCalculations.h
index 174dd73..c085231 100644
--- a/Source/core/animation/TimedItemCalculations.h
+++ b/Source/core/animation/TimedItemCalculations.h
@@ -100,19 +100,19 @@
     if (isNull(activeTime))
         return nullValue();
 
-    ASSERT(activeTime >= 0);
-
+    ASSERT(activeTime >= 0 && activeTime <= activeDuration);
     return (specified.playbackRate < 0 ? activeTime - activeDuration : activeTime) * specified.playbackRate + startOffset;
 }
 
 static inline bool endsOnIterationBoundary(double iterationCount, double iterationStart)
 {
+    ASSERT(std::isfinite(iterationCount));
     return !fmod(iterationCount + iterationStart, 1);
 }
 
 static inline double calculateIterationTime(double iterationDuration, double repeatedDuration, double scaledActiveTime, double startOffset, const Timing& specified)
 {
-    ASSERT(iterationDuration >= 0);
+    ASSERT(iterationDuration > 0);
     ASSERT(repeatedDuration == iterationDuration * specified.iterationCount);
 
     if (isNull(scaledActiveTime))
@@ -121,18 +121,17 @@
     ASSERT(scaledActiveTime >= 0);
     ASSERT(scaledActiveTime <= repeatedDuration + startOffset);
 
-    if (!iterationDuration)
-        return 0;
-
-    if (scaledActiveTime - startOffset == repeatedDuration && specified.iterationCount && endsOnIterationBoundary(specified.iterationCount, specified.iterationStart))
+    if (!std::isfinite(scaledActiveTime)
+        || (scaledActiveTime - startOffset == repeatedDuration && specified.iterationCount && endsOnIterationBoundary(specified.iterationCount, specified.iterationStart)))
         return iterationDuration;
 
+    ASSERT(std::isfinite(scaledActiveTime));
     return fmod(scaledActiveTime, iterationDuration);
 }
 
 static inline double calculateCurrentIteration(double iterationDuration, double iterationTime, double scaledActiveTime, const Timing& specified)
 {
-    ASSERT(iterationDuration >= 0);
+    ASSERT(iterationDuration > 0);
     ASSERT(isNull(iterationTime) || iterationTime >= 0);
 
     if (isNull(scaledActiveTime))
@@ -145,9 +144,6 @@
     if (!scaledActiveTime)
         return 0;
 
-    if (!iterationDuration)
-        return floor(specified.iterationStart + specified.iterationCount);
-
     if (iterationTime == iterationDuration)
         return specified.iterationStart + specified.iterationCount - 1;
 
diff --git a/Source/core/animation/TimedItemCalculationsTest.cpp b/Source/core/animation/TimedItemCalculationsTest.cpp
index cfd905d..47148c1 100644
--- a/Source/core/animation/TimedItemCalculationsTest.cpp
+++ b/Source/core/animation/TimedItemCalculationsTest.cpp
@@ -37,7 +37,7 @@
 
 namespace {
 
-TEST(CoreAnimationTimedItemCalculationsTest, ActiveTime)
+TEST(AnimationTimedItemCalculationsTest, ActiveTime)
 {
     Timing timing;
 
@@ -85,7 +85,7 @@
     ASSERT_TRUE(isNull(calculateActiveTime(32, nullValue(), TimedItem::PhaseNone, TimedItem::PhaseNone, timing)));
 }
 
-TEST(CoreAnimationTimedItemCalculationsTest, ScaledActiveTime)
+TEST(AnimationTimedItemCalculationsTest, ScaledActiveTime)
 {
     Timing timing;
 
@@ -96,16 +96,16 @@
 
     // if the playback rate is negative
     timing.playbackRate = -1;
-    ASSERT_EQ(-5, calculateScaledActiveTime(10, 20, 5, timing));
+    ASSERT_EQ(35, calculateScaledActiveTime(40, 10, 5, timing));
 
     // otherwise
     timing.playbackRate = 0;
-    ASSERT_EQ(5, calculateScaledActiveTime(10, 20, 5, timing));
+    ASSERT_EQ(5, calculateScaledActiveTime(40, 10, 5, timing));
     timing.playbackRate = 1;
-    ASSERT_EQ(25, calculateScaledActiveTime(10, 20, 5, timing));
+    ASSERT_EQ(15, calculateScaledActiveTime(40, 10, 5, timing));
 }
 
-TEST(CoreAnimationTimedItemCalculationsTest, IterationTime)
+TEST(AnimationTimedItemCalculationsTest, IterationTime)
 {
     Timing timing;
 
@@ -114,9 +114,6 @@
     // if the scaled active time is null
     ASSERT_TRUE(isNull(calculateIterationTime(1, 1, nullValue(), 1, timing)));
 
-    // if the iteration duration is zero
-    ASSERT_EQ(0, calculateIterationTime(0, 0, 0, 4, timing));
-
     // if (complex-conditions)...
     ASSERT_EQ(12, calculateIterationTime(12, 12, 12, 0, timing));
 
@@ -128,7 +125,7 @@
     ASSERT_EQ(8, calculateIterationTime(12, 120, 20, 7, timing));
 }
 
-TEST(CoreAnimationTimedItemCalculationsTest, CurrentIteration)
+TEST(AnimationTimedItemCalculationsTest, CurrentIteration)
 {
     Timing timing;
 
@@ -140,9 +137,6 @@
     // if the scaled active time is zero
     ASSERT_EQ(0, calculateCurrentIteration(1, 1, 0, timing));
 
-    // if iterationDuration is zero
-    ASSERT_EQ(1, calculateCurrentIteration(0, 0, 9, timing));
-
     // if the iteration time equals the iteration duration
     timing.iterationStart = 4;
     timing.iterationCount = 7;
@@ -152,7 +146,7 @@
     ASSERT_EQ(3, calculateCurrentIteration(3.2, 3.1, 10, timing));
 }
 
-TEST(CoreAnimationTimedItemCalculationsTest, DirectedTime)
+TEST(AnimationTimedItemCalculationsTest, DirectedTime)
 {
     Timing timing;
 
@@ -183,7 +177,7 @@
     ASSERT_EQ(3, calculateDirectedTime(2, 20, 17, timing));
 }
 
-TEST(CoreAnimationTimedItemCalculationsTest, TransformedTime)
+TEST(AnimationTimedItemCalculationsTest, TransformedTime)
 {
     Timing timing;
 
diff --git a/Source/core/animation/TimedItemTest.cpp b/Source/core/animation/TimedItemTest.cpp
index 74a287a..b568693 100644
--- a/Source/core/animation/TimedItemTest.cpp
+++ b/Source/core/animation/TimedItemTest.cpp
@@ -75,10 +75,29 @@
         TimedItem::updateInheritedTime(time);
     }
 
-    bool updateChildrenAndEffects() const FINAL OVERRIDE { return false; }
+    bool updateChildrenAndEffects() const OVERRIDE { return false; }
     void willDetach() { }
     TestTimedItemEventDelegate* eventDelegate() { return m_eventDelegate; }
-    double calculateTimeToEffectChange(double inheritedTime, double activeTime, Phase) const FINAL OVERRIDE { return -1; }
+    double calculateTimeToEffectChange(double localTime, double timeToNextIteration) const OVERRIDE
+    {
+        m_localTime = localTime;
+        m_timeToNextIteration = timeToNextIteration;
+        return -1;
+    }
+
+    double takeLocalTime()
+    {
+        const double result = m_localTime;
+        m_localTime = nullValue();
+        return result;
+    }
+
+    double takeTimeToNextIteration()
+    {
+        const double result = m_timeToNextIteration;
+        m_timeToNextIteration = nullValue();
+        return result;
+    }
 
 private:
     TestTimedItem(const Timing& specified, TestTimedItemEventDelegate* eventDelegate)
@@ -88,9 +107,11 @@
     }
 
     TestTimedItemEventDelegate* m_eventDelegate;
+    mutable double m_localTime;
+    mutable double m_timeToNextIteration;
 };
 
-TEST(CoreAnimationTimedItemTest, Sanity)
+TEST(AnimationTimedItemTest, Sanity)
 {
     Timing timing;
     timing.hasIterationDuration = true;
@@ -144,7 +165,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, FillForwards)
+TEST(AnimationTimedItemTest, FillForwards)
 {
     Timing timing;
     timing.hasIterationDuration = true;
@@ -158,7 +179,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, FillBackwards)
+TEST(AnimationTimedItemTest, FillBackwards)
 {
     Timing timing;
     timing.hasIterationDuration = true;
@@ -173,7 +194,7 @@
     ASSERT_TRUE(isNull(timedItem->timeFraction()));
 }
 
-TEST(CoreAnimationTimedItemTest, FillBoth)
+TEST(AnimationTimedItemTest, FillBoth)
 {
     Timing timing;
     timing.hasIterationDuration = true;
@@ -188,7 +209,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, StartDelay)
+TEST(AnimationTimedItemTest, StartDelay)
 {
     Timing timing;
     timing.hasIterationDuration = true;
@@ -206,7 +227,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, InfiniteIteration)
+TEST(AnimationTimedItemTest, InfiniteIteration)
 {
     Timing timing;
     timing.hasIterationDuration = true;
@@ -225,7 +246,7 @@
     ASSERT_EQ(0, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, Iteration)
+TEST(AnimationTimedItemTest, Iteration)
 {
     Timing timing;
     timing.iterationCount = 2;
@@ -254,7 +275,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, IterationStart)
+TEST(AnimationTimedItemTest, IterationStart)
 {
     Timing timing;
     timing.iterationStart = 1.2;
@@ -277,7 +298,7 @@
     ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
 }
 
-TEST(CoreAnimationTimedItemTest, IterationAlternate)
+TEST(AnimationTimedItemTest, IterationAlternate)
 {
     Timing timing;
     timing.iterationCount = 10;
@@ -299,7 +320,7 @@
     ASSERT_EQ(0.75, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, IterationAlternateReverse)
+TEST(AnimationTimedItemTest, IterationAlternateReverse)
 {
     Timing timing;
     timing.iterationCount = 10;
@@ -321,7 +342,7 @@
     ASSERT_EQ(0.25, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationSanity)
+TEST(AnimationTimedItemTest, ZeroDurationSanity)
 {
     Timing timing;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
@@ -351,7 +372,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationFillForwards)
+TEST(AnimationTimedItemTest, ZeroDurationFillForwards)
 {
     Timing timing;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
@@ -366,7 +387,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationFillBackwards)
+TEST(AnimationTimedItemTest, ZeroDurationFillBackwards)
 {
     Timing timing;
     timing.fillMode = Timing::FillModeBackwards;
@@ -382,7 +403,7 @@
     ASSERT_TRUE(isNull(timedItem->timeFraction()));
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationFillBoth)
+TEST(AnimationTimedItemTest, ZeroDurationFillBoth)
 {
     Timing timing;
     timing.fillMode = Timing::FillModeBoth;
@@ -398,7 +419,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationStartDelay)
+TEST(AnimationTimedItemTest, ZeroDurationStartDelay)
 {
     Timing timing;
     timing.startDelay = 0.5;
@@ -414,7 +435,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationIterationStartAndCount)
+TEST(AnimationTimedItemTest, ZeroDurationIterationStartAndCount)
 {
     Timing timing;
     timing.iterationStart = 0.1;
@@ -433,24 +454,25 @@
     ASSERT_DOUBLE_EQ(0.3, timedItem->timeFraction());
 }
 
-// FIXME: Needs specification work -- ASSERTION FAILED: activeDuration >= 0
-TEST(CoreAnimationTimedItemTest, DISABLED_ZeroDurationInfiniteIteration)
+// FIXME: Needs specification work.
+TEST(AnimationTimedItemTest, ZeroDurationInfiniteIteration)
 {
     Timing timing;
     timing.iterationCount = std::numeric_limits<double>::infinity();
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
+    ASSERT_EQ(0, timedItem->activeDuration());
     ASSERT_TRUE(isNull(timedItem->currentIteration()));
     ASSERT_TRUE(isNull(timedItem->timeFraction()));
-    ASSERT_TRUE(isNull(timedItem->activeDuration()));
 
     timedItem->updateInheritedTime(0);
+    ASSERT_EQ(0, timedItem->activeDuration());
     ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->currentIteration());
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationIteration)
+TEST(AnimationTimedItemTest, ZeroDurationIteration)
 {
     Timing timing;
     timing.iterationCount = 2;
@@ -469,7 +491,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationIterationStart)
+TEST(AnimationTimedItemTest, ZeroDurationIterationStart)
 {
     Timing timing;
     timing.iterationStart = 1.2;
@@ -490,7 +512,7 @@
     ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationIterationAlternate)
+TEST(AnimationTimedItemTest, ZeroDurationIterationAlternate)
 {
     Timing timing;
     timing.iterationCount = 2;
@@ -510,7 +532,7 @@
     ASSERT_EQ(0, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, ZeroDurationIterationAlternateReverse)
+TEST(AnimationTimedItemTest, ZeroDurationIterationAlternateReverse)
 {
     Timing timing;
     timing.iterationCount = 2;
@@ -530,7 +552,7 @@
     ASSERT_EQ(1, timedItem->timeFraction());
 }
 
-TEST(CoreAnimationTimedItemTest, Events)
+TEST(AnimationTimedItemTest, Events)
 {
     Timing timing;
     timing.hasIterationDuration = true;
@@ -574,4 +596,43 @@
     timedItem->updateInheritedTime(3.6);
     ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
 }
+
+TEST(AnimationTimedItemTest, TimeToEffectChange)
+{
+    Timing timing;
+    timing.hasIterationDuration = true;
+    timing.iterationDuration = 1;
+    timing.iterationStart = 0.2;
+    timing.iterationCount = 2.5;
+    timing.startDelay = 1;
+    timing.direction = Timing::PlaybackDirectionAlternate;
+    RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+    timedItem->updateInheritedTime(0);
+    EXPECT_EQ(0, timedItem->takeLocalTime());
+    EXPECT_TRUE(isNull(timedItem->takeTimeToNextIteration()));
+
+    // Normal iteration.
+    timedItem->updateInheritedTime(1.75);
+    EXPECT_EQ(1.75, timedItem->takeLocalTime());
+    EXPECT_NEAR(0.05, timedItem->takeTimeToNextIteration(), 0.000000000000001);
+
+    // Reverse iteration.
+    timedItem->updateInheritedTime(2.75);
+    EXPECT_EQ(2.75, timedItem->takeLocalTime());
+    EXPECT_NEAR(0.05, timedItem->takeTimeToNextIteration(), 0.000000000000001);
+
+    // Item ends before iteration finishes.
+    timedItem->updateInheritedTime(3.4);
+    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_EQ(3.4, timedItem->takeLocalTime());
+    EXPECT_TRUE(isNull(timedItem->takeTimeToNextIteration()));
+
+    // Item has finished.
+    timedItem->updateInheritedTime(3.5);
+    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_EQ(3.5, timedItem->takeLocalTime());
+    EXPECT_TRUE(isNull(timedItem->takeTimeToNextIteration()));
+}
+
 }
diff --git a/Source/core/animation/Timing.h b/Source/core/animation/Timing.h
index 43b04c0..9a3bc4e 100644
--- a/Source/core/animation/Timing.h
+++ b/Source/core/animation/Timing.h
@@ -61,7 +61,7 @@
         , iterationDuration(0)
         , playbackRate(1)
         , direction(PlaybackDirectionNormal)
-        , timingFunction(0)
+        , timingFunction(LinearTimingFunction::create())
     {
     }
 
@@ -73,6 +73,7 @@
         ASSERT(iterationCount >= 0);
         ASSERT(iterationDuration >= 0);
         ASSERT(std::isfinite(playbackRate));
+        ASSERT(timingFunction);
     }
 
     double startDelay;
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index e770d7a..26c2fc9 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -61,7 +61,7 @@
 
 namespace WebCore {
 
-static PassRefPtr<AnimatableValue> createFromLength(const Length& length, const RenderStyle* style)
+static PassRefPtr<AnimatableValue> createFromLength(const Length& length, const RenderStyle& style)
 {
     switch (length.type()) {
     case Fixed:
@@ -77,7 +77,7 @@
     case ViewportPercentageMax:
         return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportMax);
     case Calculated:
-        return AnimatableLength::create(CSSCalcValue::createExpressionNode(length.calculationValue()->expression(), style->effectiveZoom()));
+        return AnimatableLength::create(CSSCalcValue::createExpressionNode(length.calculationValue()->expression(), style.effectiveZoom()));
     case Auto:
     case Intrinsic:
     case MinIntrinsic:
@@ -89,7 +89,6 @@
     case Undefined:
         return AnimatableUnknown::create(CSSValueNone);
     case ExtendToZoom: // Does not apply to elements.
-    case Relative: // Does not get used by interpolable properties.
         ASSERT_NOT_REACHED();
         return 0;
     }
@@ -97,7 +96,7 @@
     return 0;
 }
 
-static PassRefPtr<AnimatableValue> createFromLineHeight(const Length& length, const RenderStyle* style)
+static PassRefPtr<AnimatableValue> createFromLineHeight(const Length& length, const RenderStyle& style)
 {
     double value = length.value();
     switch (length.type()) {
@@ -119,7 +118,7 @@
     return AnimatableDouble::create(value, constraint);
 }
 
-inline static PassRefPtr<AnimatableValue> createFromLengthBox(const LengthBox& lengthBox, const RenderStyle* style)
+inline static PassRefPtr<AnimatableValue> createFromLengthBox(const LengthBox& lengthBox, const RenderStyle& style)
 {
     return AnimatableLengthBox::create(
         createFromLength(lengthBox.left(), style),
@@ -128,21 +127,37 @@
         createFromLength(lengthBox.bottom(), style));
 }
 
-inline static PassRefPtr<AnimatableValue> createFromLengthBoxAndBool(const LengthBox lengthBox, const bool flag, const RenderStyle *style)
+static PassRefPtr<AnimatableValue> createFromBorderImageLength(const BorderImageLength& borderImageLength, const RenderStyle& style)
+{
+    if (borderImageLength.isNumber())
+        return createFromDouble(borderImageLength.number());
+    return createFromLength(borderImageLength.length(), style);
+}
+
+inline static PassRefPtr<AnimatableValue> createFromBorderImageLengthBox(const BorderImageLengthBox& borderImageLengthBox, const RenderStyle& style)
+{
+    return AnimatableLengthBox::create(
+        createFromBorderImageLength(borderImageLengthBox.left(), style),
+        createFromBorderImageLength(borderImageLengthBox.right(), style),
+        createFromBorderImageLength(borderImageLengthBox.top(), style),
+        createFromBorderImageLength(borderImageLengthBox.bottom(), style));
+}
+
+inline static PassRefPtr<AnimatableValue> createFromLengthBoxAndBool(const LengthBox lengthBox, const bool flag, const RenderStyle& style)
 {
     return AnimatableLengthBoxAndBool::create(
         createFromLengthBox(lengthBox, style),
         flag);
 }
 
-inline static PassRefPtr<AnimatableValue> createFromLengthPoint(const LengthPoint& lengthPoint, const RenderStyle* style)
+inline static PassRefPtr<AnimatableValue> createFromLengthPoint(const LengthPoint& lengthPoint, const RenderStyle& style)
 {
     return AnimatableLengthPoint::create(
         createFromLength(lengthPoint.x(), style),
         createFromLength(lengthPoint.y(), style));
 }
 
-inline static PassRefPtr<AnimatableValue> createFromLengthSize(const LengthSize& lengthSize, const RenderStyle* style)
+inline static PassRefPtr<AnimatableValue> createFromLengthSize(const LengthSize& lengthSize, const RenderStyle& style)
 {
     return AnimatableLengthSize::create(
         createFromLength(lengthSize.width(), style),
@@ -156,7 +171,7 @@
     return AnimatableUnknown::create(CSSValueNone);
 }
 
-inline static PassRefPtr<AnimatableValue> createFromFillSize(const FillSize& fillSize, const RenderStyle* style)
+inline static PassRefPtr<AnimatableValue> createFromFillSize(const FillSize& fillSize, const RenderStyle& style)
 {
     switch (fillSize.type) {
     case SizeLength:
@@ -172,7 +187,7 @@
 }
 
 template<CSSPropertyID property>
-inline static PassRefPtr<AnimatableValue> createFromFillLayers(const FillLayer* fillLayer, const RenderStyle* style)
+inline static PassRefPtr<AnimatableValue> createFromFillLayers(const FillLayer* fillLayer, const RenderStyle& style)
 {
     ASSERT(fillLayer);
     Vector<RefPtr<AnimatableValue> > values;
@@ -201,12 +216,12 @@
     return AnimatableRepeatable::create(values);
 }
 
-PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::createFromColor(CSSPropertyID property, const RenderStyle* style)
+PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::createFromColor(CSSPropertyID property, const RenderStyle& style)
 {
-    Color color = style->colorIncludingFallback(property, false);
-    Color visitedLinkColor = style->colorIncludingFallback(property, true);
-    Color fallbackColor = style->color();
-    Color fallbackVisitedLinkColor = style->visitedLinkColor();
+    Color color = style.colorIncludingFallback(property, false);
+    Color visitedLinkColor = style.colorIncludingFallback(property, true);
+    Color fallbackColor = style.color();
+    Color fallbackVisitedLinkColor = style.visitedLinkColor();
     Color resolvedColor;
     if (color.isValid())
         resolvedColor = color;
@@ -220,234 +235,252 @@
     return AnimatableColor::create(resolvedColor, resolvedVisitedLinkColor);
 }
 
+inline static PassRefPtr<AnimatableValue> createFromShapeValue(ShapeValue* value)
+{
+    if (value)
+        return AnimatableShapeValue::create(value);
+    return AnimatableUnknown::create(CSSValueAuto);
+}
+
 // FIXME: Generate this function.
-PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::create(CSSPropertyID property, const RenderStyle* style)
+PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::create(CSSPropertyID property, const RenderStyle& style)
 {
     switch (property) {
     case CSSPropertyBackgroundColor:
         return createFromColor(property, style);
     case CSSPropertyBackgroundImage:
-        return createFromFillLayers<CSSPropertyBackgroundImage>(style->backgroundLayers(), style);
+        return createFromFillLayers<CSSPropertyBackgroundImage>(style.backgroundLayers(), style);
     case CSSPropertyBackgroundPositionX:
-        return createFromFillLayers<CSSPropertyBackgroundPositionX>(style->backgroundLayers(), style);
+        return createFromFillLayers<CSSPropertyBackgroundPositionX>(style.backgroundLayers(), style);
     case CSSPropertyBackgroundPositionY:
-        return createFromFillLayers<CSSPropertyBackgroundPositionY>(style->backgroundLayers(), style);
+        return createFromFillLayers<CSSPropertyBackgroundPositionY>(style.backgroundLayers(), style);
     case CSSPropertyBackgroundSize:
     case CSSPropertyWebkitBackgroundSize:
-        return createFromFillLayers<CSSPropertyBackgroundSize>(style->backgroundLayers(), style);
+        return createFromFillLayers<CSSPropertyBackgroundSize>(style.backgroundLayers(), style);
     case CSSPropertyBaselineShift:
-        return AnimatableSVGLength::create(style->baselineShiftValue());
+        return AnimatableSVGLength::create(style.baselineShiftValue());
     case CSSPropertyBorderBottomColor:
         return createFromColor(property, style);
     case CSSPropertyBorderBottomLeftRadius:
-        return createFromLengthSize(style->borderBottomLeftRadius(), style);
+        return createFromLengthSize(style.borderBottomLeftRadius(), style);
     case CSSPropertyBorderBottomRightRadius:
-        return createFromLengthSize(style->borderBottomRightRadius(), style);
+        return createFromLengthSize(style.borderBottomRightRadius(), style);
     case CSSPropertyBorderBottomWidth:
-        return createFromDouble(style->borderBottomWidth());
+        return createFromDouble(style.borderBottomWidth());
     case CSSPropertyBorderImageOutset:
-        return createFromLengthBox(style->borderImageOutset(), style);
+        return createFromBorderImageLengthBox(style.borderImageOutset(), style);
     case CSSPropertyBorderImageSlice:
-        return createFromLengthBox(style->borderImageSlices(), style);
+        return createFromLengthBox(style.borderImageSlices(), style);
     case CSSPropertyBorderImageSource:
-        return createFromStyleImage(style->borderImageSource());
+        return createFromStyleImage(style.borderImageSource());
     case CSSPropertyBorderImageWidth:
-        return createFromLengthBox(style->borderImageWidth(), style);
+        return createFromBorderImageLengthBox(style.borderImageWidth(), style);
     case CSSPropertyBorderLeftColor:
         return createFromColor(property, style);
     case CSSPropertyBorderLeftWidth:
-        return createFromDouble(style->borderLeftWidth());
+        return createFromDouble(style.borderLeftWidth());
     case CSSPropertyBorderRightColor:
         return createFromColor(property, style);
     case CSSPropertyBorderRightWidth:
-        return createFromDouble(style->borderRightWidth());
+        return createFromDouble(style.borderRightWidth());
     case CSSPropertyBorderTopColor:
         return createFromColor(property, style);
     case CSSPropertyBorderTopLeftRadius:
-        return createFromLengthSize(style->borderTopLeftRadius(), style);
+        return createFromLengthSize(style.borderTopLeftRadius(), style);
     case CSSPropertyBorderTopRightRadius:
-        return createFromLengthSize(style->borderTopRightRadius(), style);
+        return createFromLengthSize(style.borderTopRightRadius(), style);
     case CSSPropertyBorderTopWidth:
-        return createFromDouble(style->borderTopWidth());
+        return createFromDouble(style.borderTopWidth());
     case CSSPropertyBottom:
-        return createFromLength(style->bottom(), style);
+        return createFromLength(style.bottom(), style);
     case CSSPropertyBoxShadow:
     case CSSPropertyWebkitBoxShadow:
-        return AnimatableShadow::create(style->boxShadow());
+        return AnimatableShadow::create(style.boxShadow());
     case CSSPropertyClip:
-        if (style->hasClip())
-            return createFromLengthBox(style->clip(), style);
+        if (style.hasClip())
+            return createFromLengthBox(style.clip(), style);
         return AnimatableUnknown::create(CSSPrimitiveValue::create(CSSValueAuto));
     case CSSPropertyColor:
         return createFromColor(property, style);
     case CSSPropertyFillOpacity:
-        return createFromDouble(style->fillOpacity());
+        return createFromDouble(style.fillOpacity());
     case CSSPropertyFill:
-        return AnimatableSVGPaint::create(style->svgStyle()->fillPaintType(), style->svgStyle()->fillPaintColor(), style->svgStyle()->fillPaintUri());
+        return AnimatableSVGPaint::create(style.svgStyle()->fillPaintType(), style.svgStyle()->fillPaintColor(), style.svgStyle()->fillPaintUri());
     case CSSPropertyFlexGrow:
-        return createFromDouble(style->flexGrow(), AnimatableDouble::InterpolationIsNonContinuousWithZero);
+        return createFromDouble(style.flexGrow(), AnimatableDouble::InterpolationIsNonContinuousWithZero);
     case CSSPropertyFlexShrink:
-        return createFromDouble(style->flexShrink(), AnimatableDouble::InterpolationIsNonContinuousWithZero);
+        return createFromDouble(style.flexShrink(), AnimatableDouble::InterpolationIsNonContinuousWithZero);
     case CSSPropertyFlexBasis:
-        return createFromLength(style->flexBasis(), style);
+        return createFromLength(style.flexBasis(), style);
     case CSSPropertyFloodColor:
         return createFromColor(property, style);
     case CSSPropertyFloodOpacity:
-        return createFromDouble(style->floodOpacity());
+        return createFromDouble(style.floodOpacity());
     case CSSPropertyFontSize:
         // Must pass a specified size to setFontSize if Text Autosizing is enabled, but a computed size
         // if text zoom is enabled (if neither is enabled it's irrelevant as they're probably the same).
         // FIXME: Should we introduce an option to pass the computed font size here, allowing consumers to
         // enable text zoom rather than Text Autosizing? See http://crbug.com/227545.
-        return createFromDouble(style->specifiedFontSize());
+        return createFromDouble(style.specifiedFontSize());
     case CSSPropertyHeight:
-        return createFromLength(style->height(), style);
+        return createFromLength(style.height(), style);
     case CSSPropertyKerning:
-        return AnimatableSVGLength::create(style->kerning());
+        return AnimatableSVGLength::create(style.kerning());
     case CSSPropertyLightingColor:
         return createFromColor(property, style);
     case CSSPropertyListStyleImage:
-        return createFromStyleImage(style->listStyleImage());
+        return createFromStyleImage(style.listStyleImage());
     case CSSPropertyLeft:
-        return createFromLength(style->left(), style);
+        return createFromLength(style.left(), style);
     case CSSPropertyLetterSpacing:
-        return createFromDouble(style->letterSpacing());
+        return createFromDouble(style.letterSpacing());
     case CSSPropertyLineHeight:
-        return createFromLineHeight(style->specifiedLineHeight(), style);
+        return createFromLineHeight(style.specifiedLineHeight(), style);
     case CSSPropertyMarginBottom:
-        return createFromLength(style->marginBottom(), style);
+        return createFromLength(style.marginBottom(), style);
     case CSSPropertyMarginLeft:
-        return createFromLength(style->marginLeft(), style);
+        return createFromLength(style.marginLeft(), style);
     case CSSPropertyMarginRight:
-        return createFromLength(style->marginRight(), style);
+        return createFromLength(style.marginRight(), style);
     case CSSPropertyMarginTop:
-        return createFromLength(style->marginTop(), style);
+        return createFromLength(style.marginTop(), style);
     case CSSPropertyMaxHeight:
-        return createFromLength(style->maxHeight(), style);
+        return createFromLength(style.maxHeight(), style);
     case CSSPropertyMaxWidth:
-        return createFromLength(style->maxWidth(), style);
+        return createFromLength(style.maxWidth(), style);
     case CSSPropertyMinHeight:
-        return createFromLength(style->minHeight(), style);
+        return createFromLength(style.minHeight(), style);
     case CSSPropertyMinWidth:
-        return createFromLength(style->minWidth(), style);
+        return createFromLength(style.minWidth(), style);
     case CSSPropertyObjectPosition:
-        return createFromLengthPoint(style->objectPosition(), style);
+        return createFromLengthPoint(style.objectPosition(), style);
     case CSSPropertyOpacity:
-        return createFromDouble(style->opacity());
+        return createFromDouble(style.opacity());
     case CSSPropertyOrphans:
-        return createFromDouble(style->orphans());
+        return createFromDouble(style.orphans());
     case CSSPropertyOutlineColor:
         return createFromColor(property, style);
     case CSSPropertyOutlineOffset:
-        return createFromDouble(style->outlineOffset());
+        return createFromDouble(style.outlineOffset());
     case CSSPropertyOutlineWidth:
-        return createFromDouble(style->outlineWidth());
+        return createFromDouble(style.outlineWidth());
     case CSSPropertyPaddingBottom:
-        return createFromLength(style->paddingBottom(), style);
+        return createFromLength(style.paddingBottom(), style);
     case CSSPropertyPaddingLeft:
-        return createFromLength(style->paddingLeft(), style);
+        return createFromLength(style.paddingLeft(), style);
     case CSSPropertyPaddingRight:
-        return createFromLength(style->paddingRight(), style);
+        return createFromLength(style.paddingRight(), style);
     case CSSPropertyPaddingTop:
-        return createFromLength(style->paddingTop(), style);
+        return createFromLength(style.paddingTop(), style);
     case CSSPropertyRight:
-        return createFromLength(style->right(), style);
+        return createFromLength(style.right(), style);
     case CSSPropertyStrokeWidth:
-        return AnimatableSVGLength::create(style->strokeWidth());
+        return AnimatableSVGLength::create(style.strokeWidth());
     case CSSPropertyStopColor:
         return createFromColor(property, style);
     case CSSPropertyStopOpacity:
-        return createFromDouble(style->stopOpacity());
+        return createFromDouble(style.stopOpacity());
     case CSSPropertyStrokeDasharray:
-        return AnimatableStrokeDasharrayList::create(style->strokeDashArray());
+        return AnimatableStrokeDasharrayList::create(style.strokeDashArray());
     case CSSPropertyStrokeDashoffset:
-        return AnimatableSVGLength::create(style->strokeDashOffset());
+        return AnimatableSVGLength::create(style.strokeDashOffset());
     case CSSPropertyStrokeMiterlimit:
-        return createFromDouble(style->strokeMiterLimit());
+        return createFromDouble(style.strokeMiterLimit());
     case CSSPropertyStrokeOpacity:
-        return createFromDouble(style->strokeOpacity());
+        return createFromDouble(style.strokeOpacity());
     case CSSPropertyStroke:
-        return AnimatableSVGPaint::create(style->svgStyle()->strokePaintType(), style->svgStyle()->strokePaintColor(), style->svgStyle()->strokePaintUri());
+        return AnimatableSVGPaint::create(style.svgStyle()->strokePaintType(), style.svgStyle()->strokePaintColor(), style.svgStyle()->strokePaintUri());
     case CSSPropertyTextDecorationColor:
         return createFromColor(property, style);
     case CSSPropertyTextIndent:
-        return createFromLength(style->textIndent(), style);
+        return createFromLength(style.textIndent(), style);
     case CSSPropertyTextShadow:
-        return AnimatableShadow::create(style->textShadow());
+        return AnimatableShadow::create(style.textShadow());
     case CSSPropertyTop:
-        return createFromLength(style->top(), style);
+        return createFromLength(style.top(), style);
     case CSSPropertyWebkitBorderHorizontalSpacing:
-        return createFromDouble(style->horizontalBorderSpacing());
+        return createFromDouble(style.horizontalBorderSpacing());
     case CSSPropertyWebkitBorderVerticalSpacing:
-        return createFromDouble(style->verticalBorderSpacing());
+        return createFromDouble(style.verticalBorderSpacing());
     case CSSPropertyWebkitClipPath:
-        return AnimatableClipPathOperation::create(style->clipPath());
+        if (ClipPathOperation* operation = style.clipPath())
+            return AnimatableClipPathOperation::create(operation);
+        return AnimatableUnknown::create(CSSValueNone);
     case CSSPropertyWebkitColumnCount:
-        return createFromDouble(style->columnCount());
+        return createFromDouble(style.columnCount());
     case CSSPropertyWebkitColumnGap:
-        return createFromDouble(style->columnGap());
+        return createFromDouble(style.columnGap());
     case CSSPropertyWebkitColumnRuleColor:
         return createFromColor(property, style);
     case CSSPropertyWebkitColumnRuleWidth:
-        return createFromDouble(style->columnRuleWidth());
+        return createFromDouble(style.columnRuleWidth());
     case CSSPropertyWebkitColumnWidth:
-        return createFromDouble(style->columnWidth());
+        return createFromDouble(style.columnWidth());
     case CSSPropertyWebkitFilter:
-        return AnimatableFilterOperations::create(style->filter());
+        return AnimatableFilterOperations::create(style.filter());
     case CSSPropertyWebkitMaskBoxImageOutset:
-        return createFromLengthBox(style->maskBoxImageOutset(), style);
+        return createFromBorderImageLengthBox(style.maskBoxImageOutset(), style);
     case CSSPropertyWebkitMaskBoxImageSlice:
-        return createFromLengthBoxAndBool(style->maskBoxImageSlices(), style->maskBoxImageSlicesFill(), style);
+        return createFromLengthBoxAndBool(style.maskBoxImageSlices(), style.maskBoxImageSlicesFill(), style);
     case CSSPropertyWebkitMaskBoxImageSource:
-        return createFromStyleImage(style->maskBoxImageSource());
+        return createFromStyleImage(style.maskBoxImageSource());
     case CSSPropertyWebkitMaskBoxImageWidth:
-        return createFromLengthBox(style->maskBoxImageWidth(), style);
+        return createFromBorderImageLengthBox(style.maskBoxImageWidth(), style);
     case CSSPropertyWebkitMaskImage:
-        return createFromFillLayers<CSSPropertyWebkitMaskImage>(style->maskLayers(), style);
+        return createFromFillLayers<CSSPropertyWebkitMaskImage>(style.maskLayers(), style);
     case CSSPropertyWebkitMaskPositionX:
-        return createFromFillLayers<CSSPropertyWebkitMaskPositionX>(style->maskLayers(), style);
+        return createFromFillLayers<CSSPropertyWebkitMaskPositionX>(style.maskLayers(), style);
     case CSSPropertyWebkitMaskPositionY:
-        return createFromFillLayers<CSSPropertyWebkitMaskPositionY>(style->maskLayers(), style);
+        return createFromFillLayers<CSSPropertyWebkitMaskPositionY>(style.maskLayers(), style);
     case CSSPropertyWebkitMaskSize:
-        return createFromFillLayers<CSSPropertyWebkitMaskSize>(style->maskLayers(), style);
+        return createFromFillLayers<CSSPropertyWebkitMaskSize>(style.maskLayers(), style);
     case CSSPropertyWebkitPerspective:
-        return createFromDouble(style->perspective());
+        return createFromDouble(style.perspective());
     case CSSPropertyWebkitPerspectiveOriginX:
-        return createFromLength(style->perspectiveOriginX(), style);
+        return createFromLength(style.perspectiveOriginX(), style);
     case CSSPropertyWebkitPerspectiveOriginY:
-        return createFromLength(style->perspectiveOriginY(), style);
+        return createFromLength(style.perspectiveOriginY(), style);
     case CSSPropertyShapeInside:
-        return AnimatableShapeValue::create(style->shapeInside());
+        return createFromShapeValue(style.shapeInside());
     case CSSPropertyShapeOutside:
-        return AnimatableShapeValue::create(style->shapeOutside());
+        return createFromShapeValue(style.shapeOutside());
     case CSSPropertyShapeMargin:
-        return createFromLength(style->shapeMargin(), style);
+        return createFromLength(style.shapeMargin(), style);
+    case CSSPropertyShapeImageThreshold:
+        return createFromDouble(style.shapeImageThreshold());
     case CSSPropertyWebkitTextStrokeColor:
         return createFromColor(property, style);
-    case CSSPropertyWebkitTransform:
-        return AnimatableTransform::create(style->transform());
+    case CSSPropertyWebkitTransform: {
+        // FIXME: This forces a layer to be created in the presence of a
+        // transform animation.
+        const TransformOperations& transform = style.transform();
+        if (!transform.size())
+            return AnimatableTransform::create(TransformOperations(true));
+        return AnimatableTransform::create(style.transform());
+    }
     case CSSPropertyWebkitTransformOriginX:
-        return createFromLength(style->transformOriginX(), style);
+        return createFromLength(style.transformOriginX(), style);
     case CSSPropertyWebkitTransformOriginY:
-        return createFromLength(style->transformOriginY(), style);
+        return createFromLength(style.transformOriginY(), style);
     case CSSPropertyWebkitTransformOriginZ:
-        return createFromDouble(style->transformOriginZ());
+        return createFromDouble(style.transformOriginZ());
     case CSSPropertyWidows:
-        return createFromDouble(style->widows());
+        return createFromDouble(style.widows());
     case CSSPropertyWidth:
-        return createFromLength(style->width(), style);
+        return createFromLength(style.width(), style);
     case CSSPropertyWordSpacing:
-        return createFromDouble(style->wordSpacing());
+        return createFromDouble(style.wordSpacing());
     case CSSPropertyVisibility:
-        return AnimatableVisibility::create(style->visibility());
+        return AnimatableVisibility::create(style.visibility());
     case CSSPropertyZIndex:
-        return createFromDouble(style->zIndex());
+        return createFromDouble(style.zIndex());
     case CSSPropertyZoom:
-        return createFromDouble(style->zoom());
+        return createFromDouble(style.zoom());
     default:
-        RELEASE_ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Create AnimatableValue from render style: %s", getPropertyNameString(property).utf8().data());
+        ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Create AnimatableValue from render style: %s", getPropertyNameString(property).utf8().data());
         ASSERT_NOT_REACHED();
-        return 0;
+        // This return value is to avoid a release crash if possible.
+        return AnimatableUnknown::create(0);
     }
 }
 
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.h b/Source/core/animation/css/CSSAnimatableValueFactory.h
index d9e6ce2..bac18c1 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.h
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.h
@@ -41,9 +41,9 @@
 
 class CSSAnimatableValueFactory {
 public:
-    static PassRefPtr<AnimatableValue> create(CSSPropertyID, const RenderStyle*);
+    static PassRefPtr<AnimatableValue> create(CSSPropertyID, const RenderStyle&);
 private:
-    static PassRefPtr<AnimatableValue> createFromColor(CSSPropertyID, const RenderStyle*);
+    static PassRefPtr<AnimatableValue> createFromColor(CSSPropertyID, const RenderStyle&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/animation/css/CSSAnimations.cpp b/Source/core/animation/css/CSSAnimations.cpp
index 5ba36b0..f87eba6 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -33,18 +33,24 @@
 
 #include "StylePropertyShorthand.h"
 #include "core/animation/ActiveAnimations.h"
+#include "core/animation/CompositorAnimations.h"
 #include "core/animation/DocumentTimeline.h"
 #include "core/animation/KeyframeAnimationEffect.h"
 #include "core/animation/css/CSSAnimatableValueFactory.h"
 #include "core/css/CSSKeyframeRule.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Element.h"
+#include "core/dom/PseudoElement.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/events/TransitionEvent.h"
 #include "core/events/WebKitAnimationEvent.h"
+#include "core/frame/UseCounter.h"
 #include "core/frame/animation/CSSPropertyAnimation.h"
 #include "core/platform/animation/CSSAnimationDataList.h"
 #include "core/platform/animation/TimingFunction.h"
+#include "core/rendering/RenderObject.h"
+#include "core/rendering/style/KeyframeList.h"
+#include "public/platform/Platform.h"
 #include "wtf/HashSet.h"
 
 namespace WebCore {
@@ -79,6 +85,194 @@
     return target > reference;
 }
 
+static PassRefPtr<TimingFunction> generateTimingFunction(const KeyframeAnimationEffect::KeyframeVector keyframes, const HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions)
+{
+    // Generate the chained timing function. Note that timing functions apply
+    // from the keyframe in which they're specified to the next keyframe.
+    bool isTimingFunctionLinearThroughout = true;
+    RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
+    for (size_t i = 0; i < keyframes.size() - 1; ++i) {
+        double lowerBound = keyframes[i]->offset();
+        ASSERT(lowerBound >=0 && lowerBound < 1);
+        double upperBound = keyframes[i + 1]->offset();
+        ASSERT(upperBound > 0 && upperBound <= 1);
+        TimingFunction* timingFunction = perKeyframeTimingFunctions.get(lowerBound);
+        isTimingFunctionLinearThroughout &= timingFunction->type() == TimingFunction::LinearFunction;
+        chainedTimingFunction->appendSegment(upperBound, timingFunction);
+    }
+    if (isTimingFunctionLinearThroughout)
+        return LinearTimingFunction::create();
+    return chainedTimingFunction;
+}
+
+static void resolveKeyframes(StyleResolver* resolver, Element* element, const RenderStyle& style, const AtomicString& name, TimingFunction* defaultTimingFunction,
+    Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > >& keyframesAndTimingFunctions)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+    const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(resolver, element, name.impl());
+    if (!keyframesRule)
+        return;
+
+    const Vector<RefPtr<StyleKeyframe> >& styleKeyframes = keyframesRule->keyframes();
+    if (styleKeyframes.isEmpty())
+        return;
+
+    // Construct and populate the style for each keyframe
+    PropertySet specifiedProperties;
+    KeyframeAnimationEffect::KeyframeVector keyframes;
+    HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions;
+    for (size_t i = 0; i < styleKeyframes.size(); ++i) {
+        const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
+        RefPtr<RenderStyle> keyframeStyle = resolver->styleForKeyframe(element, style, styleKeyframe, name);
+        RefPtr<Keyframe> keyframe = Keyframe::create();
+        const Vector<double>& offsets = styleKeyframe->keys();
+        ASSERT(!offsets.isEmpty());
+        keyframe->setOffset(offsets[0]);
+        TimingFunction* timingFunction = defaultTimingFunction;
+        const StylePropertySet* properties = styleKeyframe->properties();
+        for (unsigned j = 0; j < properties->propertyCount(); j++) {
+            CSSPropertyID property = properties->propertyAt(j).id();
+            specifiedProperties.add(property);
+            if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction)
+                timingFunction = KeyframeValue::timingFunction(*keyframeStyle);
+            else if (CSSAnimations::isAnimatableProperty(property))
+                keyframe->setPropertyValue(property, CSSAnimatableValueFactory::create(property, *keyframeStyle).get());
+        }
+        keyframes.append(keyframe);
+        // The last keyframe specified at a given offset is used.
+        perKeyframeTimingFunctions.set(offsets[0], timingFunction);
+        for (size_t j = 1; j < offsets.size(); ++j) {
+            keyframes.append(keyframe->cloneWithOffset(offsets[j]));
+            perKeyframeTimingFunctions.set(offsets[j], timingFunction);
+        }
+    }
+    ASSERT(!keyframes.isEmpty());
+
+    if (!perKeyframeTimingFunctions.contains(0))
+        perKeyframeTimingFunctions.set(0, defaultTimingFunction);
+
+    for (PropertySet::const_iterator iter = specifiedProperties.begin(); iter != specifiedProperties.end(); ++iter) {
+        const CSSPropertyID property = *iter;
+        ASSERT(property != CSSPropertyInvalid);
+        blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(property));
+    }
+
+    // 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())
+            targetIndex++;
+        if (targetIndex != i)
+            keyframes[targetIndex] = keyframes[i];
+    }
+    keyframes.shrink(targetIndex + 1);
+
+    // Add 0% and 100% keyframes if absent.
+    RefPtr<Keyframe> startKeyframe = keyframes[0];
+    if (startKeyframe->offset()) {
+        startKeyframe = Keyframe::create();
+        startKeyframe->setOffset(0);
+        keyframes.prepend(startKeyframe);
+    }
+    RefPtr<Keyframe> endKeyframe = keyframes[keyframes.size() - 1];
+    if (endKeyframe->offset() != 1) {
+        endKeyframe = Keyframe::create();
+        endKeyframe->setOffset(1);
+        keyframes.append(endKeyframe);
+    }
+    ASSERT(keyframes.size() >= 2);
+    ASSERT(!keyframes.first()->offset());
+    ASSERT(keyframes.last()->offset() == 1);
+
+    // Snapshot current property values for 0% and 100% if missing.
+    PropertySet allProperties;
+    size_t numKeyframes = keyframes.size();
+    for (size_t i = 0; i < numKeyframes; i++) {
+        const PropertySet& keyframeProperties = keyframes[i]->properties();
+        for (PropertySet::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
+            allProperties.add(*iter);
+    }
+    const PropertySet& startKeyframeProperties = startKeyframe->properties();
+    const PropertySet& endKeyframeProperties = endKeyframe->properties();
+    bool missingStartValues = startKeyframeProperties.size() < allProperties.size();
+    bool missingEndValues = endKeyframeProperties.size() < allProperties.size();
+    if (missingStartValues || missingEndValues) {
+        for (PropertySet::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());
+        }
+    }
+    ASSERT(startKeyframe->properties().size() == allProperties.size());
+    ASSERT(endKeyframe->properties().size() == allProperties.size());
+
+    // Determine how many keyframes specify each property. Note that this must
+    // be done after we've filled in end keyframes.
+    typedef HashCountedSet<CSSPropertyID> PropertyCountedSet;
+    PropertyCountedSet propertyCounts;
+    for (size_t i = 0; i < numKeyframes; ++i) {
+        const PropertySet& properties = keyframes[i]->properties();
+        for (PropertySet::const_iterator iter = properties.begin(); iter != properties.end(); ++iter)
+            propertyCounts.add(*iter);
+    }
+
+    // Split keyframes into groups, where each group contains only keyframes
+    // which specify all properties used in that group. Each group is animated
+    // in a separate animation, to allow per-keyframe timing functions to be
+    // applied correctly.
+    for (PropertyCountedSet::const_iterator iter = propertyCounts.begin(); iter != propertyCounts.end(); ++iter) {
+        const CSSPropertyID property = iter->key;
+        const size_t count = iter->value;
+        ASSERT(count <= numKeyframes);
+        if (count == numKeyframes)
+            continue;
+        KeyframeAnimationEffect::KeyframeVector splitOutKeyframes;
+        for (size_t i = 0; i < numKeyframes; i++) {
+            Keyframe* keyframe = keyframes[i].get();
+            if (!keyframe->properties().contains(property)) {
+                ASSERT(i && i != numKeyframes - 1);
+                continue;
+            }
+            RefPtr<Keyframe> clonedKeyframe = Keyframe::create();
+            clonedKeyframe->setOffset(keyframe->offset());
+            clonedKeyframe->setComposite(keyframe->composite());
+            clonedKeyframe->setPropertyValue(property, keyframe->propertyValue(property));
+            splitOutKeyframes.append(clonedKeyframe);
+            // Note that it's OK if this keyframe ends up having no
+            // properties. This can only happen when none of the properties
+            // are specified in all keyframes, in which case we won't animate
+            // anything with these keyframes.
+            keyframe->clearPropertyValue(property);
+        }
+        ASSERT(!splitOutKeyframes.first()->offset());
+        ASSERT(splitOutKeyframes.last()->offset() == 1);
+#ifndef NDEBUG
+        for (size_t j = 0; j < splitOutKeyframes.size(); ++j)
+            ASSERT(splitOutKeyframes[j]->properties().size() == 1);
+#endif
+        keyframesAndTimingFunctions.append(std::make_pair(splitOutKeyframes, generateTimingFunction(splitOutKeyframes, perKeyframeTimingFunctions)));
+    }
+
+    unsigned numPropertiesSpecifiedInAllKeyframes = keyframes.first()->properties().size();
+#ifndef NDEBUG
+    for (size_t i = 1; i < numKeyframes; ++i)
+        ASSERT(keyframes[i]->properties().size() == numPropertiesSpecifiedInAllKeyframes);
+#endif
+
+    // If the animation specifies any keyframes, we always provide at least one
+    // vector of resolved keyframes, even if no properties are animated.
+    if (numPropertiesSpecifiedInAllKeyframes || keyframesAndTimingFunctions.isEmpty())
+        keyframesAndTimingFunctions.append(std::make_pair(keyframes, generateTimingFunction(keyframes, perKeyframeTimingFunctions)));
+}
+
 // Returns the default timing function.
 const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing, bool& isPaused)
 {
@@ -136,9 +330,9 @@
     return animationData->isTimingFunctionSet() ? animationData->timingFunction() : CSSAnimationData::initialAnimationTimingFunction();
 }
 
-void calculateCandidateTransitionForProperty(const CSSAnimationData* anim, CSSPropertyID id, const RenderStyle* oldStyle, const RenderStyle* newStyle, CandidateTransitionMap& candidateMap)
+static void calculateCandidateTransitionForProperty(const CSSAnimationData* anim, CSSPropertyID id, const RenderStyle& oldStyle, const RenderStyle& newStyle, CandidateTransitionMap& candidateMap)
 {
-    if (!CSSPropertyAnimation::propertiesEqual(id, oldStyle, newStyle)) {
+    if (!CSSPropertyAnimation::propertiesEqual(id, &oldStyle, &newStyle)) {
         RefPtr<AnimatableValue> from = CSSAnimatableValueFactory::create(id, oldStyle);
         RefPtr<AnimatableValue> to = CSSAnimatableValueFactory::create(id, newStyle);
         // If we have multiple transitions on the same property, we will use the
@@ -149,13 +343,13 @@
     }
 }
 
-void computeCandidateTransitions(const RenderStyle* oldStyle, const RenderStyle* newStyle, CandidateTransitionMap& candidateMap, HashSet<CSSPropertyID>& listedProperties)
+static void computeCandidateTransitions(const RenderStyle& oldStyle, const RenderStyle& newStyle, CandidateTransitionMap& candidateMap, HashSet<CSSPropertyID>& listedProperties)
 {
-    if (!newStyle->transitions())
+    if (!newStyle.transitions())
         return;
 
-    for (size_t i = 0; i < newStyle->transitions()->size(); ++i) {
-        const CSSAnimationData* anim = newStyle->transitions()->animation(i);
+    for (size_t i = 0; i < newStyle.transitions()->size(); ++i) {
+        const CSSAnimationData* anim = newStyle.transitions()->animation(i);
         CSSAnimationData::AnimationMode mode = anim->animationMode();
         if (anim->duration() + anim->delay() <= 0 || mode == CSSAnimationData::AnimateNone)
             continue;
@@ -202,7 +396,24 @@
         activeAnimations->cssAnimations().maybeApplyPendingUpdate(m_target);
 }
 
-PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(Element* element, const RenderStyle* style, StyleResolver* resolver)
+const StyleRuleKeyframes* CSSAnimations::matchScopedKeyframesRule(StyleResolver* resolver, const Element* e, const StringImpl* animationName)
+{
+    if (resolver->styleTreeHasOnlyScopedResolverForDocument())
+        return resolver->styleTreeScopedStyleResolverForDocument()->keyframeStylesForAnimation(animationName);
+
+    Vector<ScopedStyleResolver*, 8> stack;
+    resolver->styleTreeResolveScopedKeyframesRules(e, stack);
+    if (stack.isEmpty())
+        return 0;
+
+    for (size_t i = 0; i < stack.size(); ++i) {
+        if (const StyleRuleKeyframes* keyframesRule = stack.at(i)->keyframeStylesForAnimation(animationName))
+            return keyframesRule;
+    }
+    return 0;
+}
+
+PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(Element* element, const RenderStyle& style, StyleResolver* resolver)
 {
     ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
     OwnPtr<CSSAnimationUpdate> update = adoptPtr(new CSSAnimationUpdate());
@@ -213,9 +424,9 @@
     return update->isEmpty() ? nullptr : update.release();
 }
 
-void CSSAnimations::calculateAnimationUpdate(CSSAnimationUpdate* update, Element* element, const RenderStyle* style, StyleResolver* resolver)
+void CSSAnimations::calculateAnimationUpdate(CSSAnimationUpdate* update, Element* element, const RenderStyle& style, StyleResolver* resolver)
 {
-    const CSSAnimationDataList* animationDataList = style->animations();
+    const CSSAnimationDataList* animationDataList = style.animations();
     const CSSAnimations* cssAnimations = element->activeAnimations() ? &element->activeAnimations()->cssAnimations() : 0;
 
     HashSet<AtomicString> inactive;
@@ -223,7 +434,7 @@
         for (AnimationMap::const_iterator iter = cssAnimations->m_animations.begin(); iter != cssAnimations->m_animations.end(); ++iter)
             inactive.add(iter->key);
 
-    if (style->display() != NONE) {
+    if (style.display() != NONE) {
         for (size_t i = 0; animationDataList && i < animationDataList->size(); ++i) {
             const CSSAnimationData* animationData = animationDataList->animation(i);
             if (animationData->isNoneAnimation())
@@ -255,7 +466,7 @@
             bool isPaused;
             RefPtr<TimingFunction> defaultTimingFunction = timingFromAnimationData(animationData, timing, isPaused);
             Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > > keyframesAndTimingFunctions;
-            resolver->resolveKeyframes(element, style, animationName, defaultTimingFunction.get(), keyframesAndTimingFunctions);
+            resolveKeyframes(resolver, element, style, animationName, defaultTimingFunction.get(), keyframesAndTimingFunctions);
             if (!keyframesAndTimingFunctions.isEmpty()) {
                 HashSet<RefPtr<InertAnimation> > animations;
                 for (size_t j = 0; j < keyframesAndTimingFunctions.size(); ++j) {
@@ -275,9 +486,6 @@
 
 void CSSAnimations::maybeApplyPendingUpdate(Element* element)
 {
-    if (!element->renderer())
-        m_pendingUpdate = nullptr;
-
     if (!m_pendingUpdate) {
         m_previousCompositableValuesForAnimations.clear();
         return;
@@ -312,16 +520,35 @@
             // The event delegate is set on the the first animation only. We
             // rely on the behavior of OwnPtr::release() to achieve this.
             RefPtr<Animation> animation = Animation::create(element, inertAnimation->effect(), inertAnimation->specified(), Animation::DefaultPriority, eventDelegate.release());
-            RefPtr<Player> player = element->document().timeline()->play(animation.get());
+            Player* player = element->document().timeline()->createPlayer(animation.get());
             player->setPaused(inertAnimation->paused());
-            players.add(player.release());
+            element->document().cssPendingAnimations().add(player);
+            player->update();
+            players.add(player);
         }
         m_animations.set(iter->name, players);
     }
 
+    // Transitions that are run on the compositor only update main-thread state
+    // lazily. However, we need the new state to know what the from state shoud
+    // be when transitions are retargeted. Instead of triggering complete style
+    // recalculation, we find these cases by searching for new transitions that
+    // have matching cancelled animation property IDs on the compositor.
+    HashMap<CSSPropertyID, std::pair<RefPtr<Animation>, double> > retargetedCompositorTransitions;
     for (HashSet<CSSPropertyID>::iterator iter = update->cancelledTransitions().begin(); iter != update->cancelledTransitions().end(); ++iter) {
-        ASSERT(m_transitions.contains(*iter));
-        m_transitions.take(*iter).transition->player()->cancel();
+        CSSPropertyID id = *iter;
+        ASSERT(m_transitions.contains(id));
+        Player* player = m_transitions.take(id).transition->player();
+        ActiveAnimations* activeAnimations = element->activeAnimations();
+        if (activeAnimations && activeAnimations->hasActiveAnimationsOnCompositor(id)) {
+            for (size_t i = 0; i < update->newTransitions().size(); ++i) {
+                if (update->newTransitions()[i].id == id) {
+                    retargetedCompositorTransitions.add(id, std::pair<RefPtr<Animation>, double>(toAnimation(player->source()), player->startTime()));
+                    break;
+                }
+            }
+        }
+        player->cancel();
     }
 
     for (size_t i = 0; i < update->newTransitions().size(); ++i) {
@@ -334,10 +561,34 @@
         CSSPropertyID id = newTransition.id;
         InertAnimation* inertAnimation = newTransition.animation.get();
         OwnPtr<TransitionEventDelegate> eventDelegate = adoptPtr(new TransitionEventDelegate(element, id));
-        RefPtr<Animation> transition = Animation::create(element, inertAnimation->effect(), inertAnimation->specified(), Animation::TransitionPriority, eventDelegate.release());
-        element->document().transitionTimeline()->play(transition.get());
+
+        RefPtr<AnimationEffect> effect = inertAnimation->effect();
+
+        if (retargetedCompositorTransitions.contains(id)) {
+            const std::pair<RefPtr<Animation>, double>& oldTransition = retargetedCompositorTransitions.get(id);
+            RefPtr<Animation> oldAnimation = oldTransition.first;
+            double oldStartTime = oldTransition.second;
+            double inheritedTime = isNull(oldStartTime) ? 0 : element->document().transitionTimeline()->currentTime() - oldStartTime;
+            oldAnimation->updateInheritedTime(inheritedTime);
+            KeyframeAnimationEffect* oldEffect = toKeyframeAnimationEffect(inertAnimation->effect());
+            const KeyframeAnimationEffect::KeyframeVector& frames = oldEffect->getFrames();
+            KeyframeAnimationEffect::KeyframeVector newFrames;
+            newFrames.append(frames[0]->clone());
+            newFrames[0]->clearPropertyValue(id);
+            AnimationEffect::CompositableValue* compositableValue = oldAnimation->compositableValues()->get(id);
+            ASSERT(!compositableValue->dependsOnUnderlyingValue());
+            newFrames[0]->setPropertyValue(id, compositableValue->compositeOnto(0).get());
+            newFrames.append(frames[1]->clone());
+            effect = KeyframeAnimationEffect::create(newFrames);
+        }
+        RefPtr<Animation> transition = Animation::create(element, effect, inertAnimation->specified(), Animation::TransitionPriority, eventDelegate.release());
+        RefPtr<Player> player = element->document().transitionTimeline()->createPlayer(transition.get());
+        player->update();
+        element->document().cssPendingAnimations().add(player.get());
         runningTransition.transition = transition.get();
         m_transitions.set(id, runningTransition);
+        ASSERT(id != CSSPropertyInvalid);
+        blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(id));
     }
 }
 
@@ -379,15 +630,15 @@
     update->startTransition(id, newTransition.from.get(), newTransition.to.get(), InertAnimation::create(effect, timing, isPaused));
 }
 
-void CSSAnimations::calculateTransitionUpdate(CSSAnimationUpdate* update, const Element* element, const RenderStyle* style)
+void CSSAnimations::calculateTransitionUpdate(CSSAnimationUpdate* update, const Element* element, const RenderStyle& style)
 {
     ActiveAnimations* activeAnimations = element->activeAnimations();
     const TransitionMap* transitions = activeAnimations ? &activeAnimations->cssAnimations().m_transitions : 0;
 
     HashSet<CSSPropertyID> listedProperties;
-    if (style->display() != NONE && element->renderer() && element->renderer()->style()) {
+    if (style.display() != NONE && element->renderer() && element->renderer()->style()) {
         CandidateTransitionMap candidateMap;
-        computeCandidateTransitions(element->renderer()->style(), style, candidateMap, listedProperties);
+        computeCandidateTransitions(*element->renderer()->style(), style, candidateMap, listedProperties);
         for (CandidateTransitionMap::const_iterator iter = candidateMap.begin(); iter != candidateMap.end(); ++iter) {
             // FIXME: We should transition if an !important property changes even when an animation is running,
             // but this is a bit hard to do with the current applyMatchedProperties system.
@@ -431,6 +682,7 @@
     if (update->newAnimations().isEmpty() && update->cancelledAnimationPlayers().isEmpty()) {
         AnimationEffect::CompositableValueMap compositableValuesForAnimations(AnimationStack::compositableValues(animationStack, 0, 0, Animation::DefaultPriority));
         update->adoptCompositableValuesForAnimations(compositableValuesForAnimations);
+        return;
     }
 
     Vector<InertAnimation*> newAnimations;
@@ -634,6 +886,7 @@
     case CSSPropertyShapeInside:
     case CSSPropertyShapeOutside:
     case CSSPropertyShapeMargin:
+    case CSSPropertyShapeImageThreshold:
     case CSSPropertyWebkitTextStrokeColor:
     case CSSPropertyWebkitTransform:
     case CSSPropertyWebkitTransformOriginX:
@@ -649,7 +902,6 @@
     // CSSPropertyAnimation implements animation of these shorthands
     // directly and makes use of this method.
     case CSSPropertyFlex:
-    case CSSPropertyWebkitMaskBoxImage:
         return !RuntimeEnabledFeatures::webAnimationsCSSEnabled();
     default:
         return false;
diff --git a/Source/core/animation/css/CSSAnimations.h b/Source/core/animation/css/CSSAnimations.h
index 83f492b..fe4bde6 100644
--- a/Source/core/animation/css/CSSAnimations.h
+++ b/Source/core/animation/css/CSSAnimations.h
@@ -48,6 +48,7 @@
 class Element;
 class StylePropertyShorthand;
 class StyleResolver;
+class StyleRuleKeyframes;
 
 // Applied to scopes where an animation update will be added as pending and should then be applied (eg. Element style recalc).
 class CSSAnimationUpdateScope FINAL {
@@ -148,16 +149,22 @@
 
 class CSSAnimations FINAL {
 public:
+    // FIXME: This method is only used here and in the legacy animations
+    // implementation. It should be made private or file-scope when the legacy
+    // engine is removed.
+    static const StyleRuleKeyframes* matchScopedKeyframesRule(StyleResolver*, const Element*, const StringImpl*);
+
     static bool isAnimatableProperty(CSSPropertyID);
     static const StylePropertyShorthand& animatableProperties();
     // FIXME: This should take a const ScopedStyleTree instead of a StyleResolver.
     // We should also change the Element* to a const Element*
-    static PassOwnPtr<CSSAnimationUpdate> calculateUpdate(Element*, const RenderStyle*, StyleResolver*);
+    static PassOwnPtr<CSSAnimationUpdate> calculateUpdate(Element*, const RenderStyle&, StyleResolver*);
 
     void setPendingUpdate(PassOwnPtr<CSSAnimationUpdate> update) { m_pendingUpdate = update; }
     void maybeApplyPendingUpdate(Element*);
     bool isEmpty() const { return m_animations.isEmpty() && m_transitions.isEmpty() && !m_pendingUpdate; }
     void cancel();
+
 private:
     // Note that a single animation name may map to multiple players due to
     // the way in which we split up animations with incomplete keyframes.
@@ -176,8 +183,8 @@
 
     AnimationEffect::CompositableValueMap m_previousCompositableValuesForAnimations;
 
-    static void calculateAnimationUpdate(CSSAnimationUpdate*, Element*, const RenderStyle*, StyleResolver*);
-    static void calculateTransitionUpdate(CSSAnimationUpdate*, const Element*, const RenderStyle*);
+    static void calculateAnimationUpdate(CSSAnimationUpdate*, Element*, const RenderStyle&, StyleResolver*);
+    static void calculateTransitionUpdate(CSSAnimationUpdate*, const Element*, const RenderStyle&);
     static void calculateTransitionUpdateForProperty(CSSAnimationUpdate*, CSSPropertyID, const CandidateTransition&, const TransitionMap*);
 
     static void calculateAnimationCompositableValues(CSSAnimationUpdate*, const Element*);
diff --git a/Source/core/animation/css/CSSPendingAnimations.cpp b/Source/core/animation/css/CSSPendingAnimations.cpp
new file mode 100644
index 0000000..3a4ec03
--- /dev/null
+++ b/Source/core/animation/css/CSSPendingAnimations.cpp
@@ -0,0 +1,94 @@
+/*
+ * 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/animation/css/CSSPendingAnimations.h"
+
+#include "core/animation/Animation.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/frame/FrameView.h"
+
+namespace WebCore {
+
+void CSSPendingAnimations::add(Player* player)
+{
+    ASSERT(player->source()->isAnimation());
+    // The actual start time is either this value, or the time that
+    // this animation, or an animation that it is synchronized with
+    // is started on the compositor.
+    const double defaultStartTime = player->timeline().currentTime();
+    m_pending.append(std::make_pair(player, defaultStartTime));
+}
+
+bool CSSPendingAnimations::startPendingAnimations()
+{
+    bool startedOnCompositor = false;
+    for (size_t i = 0; i < m_pending.size(); ++i) {
+        if (m_pending[i].first->maybeStartAnimationOnCompositor())
+            startedOnCompositor = true;
+    }
+
+    // If any animations were started on the compositor, all remaining
+    // need to wait for a synchronized start time. Otherwise they may
+    // start immediately.
+    if (startedOnCompositor) {
+        for (size_t i = 0; i < m_pending.size(); ++i)
+            m_waitingForCompositorAnimationStart.append(m_pending[i].first);
+    } else {
+        for (size_t i = 0; i < m_pending.size(); ++i)
+            m_pending[i].first->setStartTime(m_pending[i].second);
+    }
+    m_pending.clear();
+
+    if (startedOnCompositor || m_waitingForCompositorAnimationStart.isEmpty())
+        return !m_waitingForCompositorAnimationStart.isEmpty();
+
+    // Check if we're still waiting for any compositor animations to start.
+    for (size_t i = 0; i < m_waitingForCompositorAnimationStart.size(); ++i) {
+        if (m_waitingForCompositorAnimationStart[i].get()->hasActiveAnimationsOnCompositor())
+            return true;
+    }
+
+    // If not, go ahead and start any animations that were waiting.
+    notifyCompositorAnimationStarted(monotonicallyIncreasingTime());
+    return false;
+}
+
+void CSSPendingAnimations::notifyCompositorAnimationStarted(double monotonicAnimationStartTime)
+{
+    for (size_t i = 0; i < m_waitingForCompositorAnimationStart.size(); ++i) {
+        Player* player = m_waitingForCompositorAnimationStart[i].get();
+        player->setStartTime(monotonicAnimationStartTime - player->timeline().zeroTime());
+    }
+
+    m_waitingForCompositorAnimationStart.clear();
+}
+
+} // namespace
diff --git a/Source/core/platform/graphics/MediaSourcePrivate.h b/Source/core/animation/css/CSSPendingAnimations.h
similarity index 68%
rename from Source/core/platform/graphics/MediaSourcePrivate.h
rename to Source/core/animation/css/CSSPendingAnimations.h
index e3f606e..1bb3c28 100644
--- a/Source/core/platform/graphics/MediaSourcePrivate.h
+++ b/Source/core/animation/css/CSSPendingAnimations.h
@@ -27,31 +27,30 @@
  * (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 MediaSourcePrivate_h
-#define MediaSourcePrivate_h
 
-#include "wtf/Forward.h"
+#ifndef CSSPendingAnimations_h
+#define CSSPendingAnimations_h
+
+#include "core/animation/Player.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class SourceBufferPrivate;
-
-class MediaSourcePrivate {
+// Used to synchronize the start of main-thread animations with compositor
+// animations when both classes of CSS Animations are triggered by the same recalc
+class CSSPendingAnimations FINAL {
 public:
-    typedef Vector<String, 0> CodecsArray;
+    void add(Player*);
+    // Returns whether we are waiting for an animation to start and should
+    // service again on the next frame.
+    bool startPendingAnimations();
+    void notifyCompositorAnimationStarted(double monotonicAnimationStartTime);
 
-    MediaSourcePrivate() { }
-    virtual ~MediaSourcePrivate() { }
-
-    enum AddStatus { Ok, NotSupported, ReachedIdLimit };
-    virtual AddStatus addSourceBuffer(const String& type, const CodecsArray&, OwnPtr<SourceBufferPrivate>*) = 0;
-    virtual double duration() = 0;
-    virtual void setDuration(double) = 0;
-    enum EndOfStreamStatus { EosNoError, EosNetworkError, EosDecodeError };
-    virtual void markEndOfStream(EndOfStreamStatus) = 0;
-    virtual void unmarkEndOfStream() = 0;
+private:
+    Vector<std::pair<RefPtr<Player>, double> > m_pending;
+    Vector<RefPtr<Player> > m_waitingForCompositorAnimationStart;
 };
 
-}
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index 2d4a319..b68e206 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -274,7 +274,10 @@
         '<(SHARED_INTERMEDIATE_DIR)/blink/FetchInitiatorTypeNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.h',
+        '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.cpp',
+        '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.h',
         '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLNames.cpp',
+        '<(SHARED_INTERMEDIATE_DIR)/blink/InputTypeNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/MathMLNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/PickerCommon.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.cpp',
@@ -287,6 +290,9 @@
         # Generated from HTMLEntityNames.in
         '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLEntityTable.cpp',
 
+        # Generated from CSSTokenizer-in.cpp
+        '<(SHARED_INTERMEDIATE_DIR)/blink/CSSTokenizer.cpp',
+
         # Generated from CSSParser-in.cpp
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSParser.cpp',
 
@@ -357,7 +363,6 @@
         '../wtf/wtf.gyp:wtf',
         '../config.gyp:config',
         '../platform/blink_platform.gyp:blink_platform',
-        '../weborigin/weborigin.gyp:weborigin',
         '<(DEPTH)/gpu/gpu.gyp:gles2_c_lib',
         '<(DEPTH)/skia/skia.gyp:skia',
         '<(DEPTH)/third_party/angle_dx11/src/build_angle.gyp:translator',
@@ -405,10 +410,6 @@
           '<(DEPTH)/gpu',
           '<(DEPTH)/third_party/angle_dx11/include',
         ],
-        'msvs_disabled_warnings': [
-          4138, 4244, 4291, 4305, 4344, 4355, 4521, 4099,
-        ],
-        'scons_line_length' : 1,
         'xcode_settings': {
           # Some Mac-specific parts of WebKit won't compile without having this
           # prefix header injected.
@@ -665,14 +666,8 @@
             # the specific exclusions in the "exclude" list below.
             ['include', 'platform/graphics/mac/ColorMac\\.mm$'],
             ['include', 'platform/graphics/mac/ComplexTextControllerCoreText\\.mm$'],
-            ['include', 'platform/graphics/mac/FloatPointMac\\.mm$'],
-            ['include', 'platform/graphics/mac/FloatRectMac\\.mm$'],
-            ['include', 'platform/graphics/mac/FloatSizeMac\\.mm$'],
             ['include', 'platform/graphics/mac/GlyphPageTreeNodeMac\\.cpp$'],
-            ['include', 'platform/graphics/mac/IntPointMac\\.mm$'],
-            ['include', 'platform/graphics/mac/IntRectMac\\.mm$'],
             ['include', 'platform/mac/BlockExceptions\\.mm$'],
-            ['include', 'platform/mac/KillRingMac\\.mm$'],
             ['include', 'platform/mac/LocalCurrentGraphicsContext\\.mm$'],
             ['include', 'platform/mac/NSScrollerImpDetails\\.mm$'],
             ['include', 'platform/mac/ScrollAnimatorMac\\.mm$'],
@@ -686,10 +681,6 @@
             # Use USE_NEW_THEME on Mac.
             ['include', 'platform/Theme\\.cpp$'],
 
-            # The Mac uses platform/mac/KillRingMac.mm instead of the dummy
-            # implementation.
-            ['exclude', 'platform/KillRingNone\\.cpp$'],
-
             # The Mac currently uses FontCustomPlatformDataMac.cpp,
             # included by regex above, instead.
             ['exclude', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
@@ -700,12 +691,6 @@
             ['exclude', 'platform/ScrollAnimatorNone\\.cpp$'],
             ['exclude', 'platform/ScrollAnimatorNone\\.h$'],
 
-            ['include', 'platform/graphics/cg/FloatPointCG\\.cpp$'],
-            ['include', 'platform/graphics/cg/FloatRectCG\\.cpp$'],
-            ['include', 'platform/graphics/cg/FloatSizeCG\\.cpp$'],
-            ['include', 'platform/graphics/cg/IntPointCG\\.cpp$'],
-            ['include', 'platform/graphics/cg/IntRectCG\\.cpp$'],
-            ['include', 'platform/graphics/cg/IntSizeCG\\.cpp$'],
             ['exclude', 'platform/graphics/skia/FontCacheSkia\\.cpp$'],
             ['exclude', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
             ['exclude', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
@@ -736,8 +721,12 @@
             ['exclude', 'Posix\\.cpp$'],
 
             ['include', 'platform/ScrollbarThemeWin\\.(cpp|h)$'],
-            ['include', 'platform/graphics/chromium/FontFallbackWin\\.(cpp|h)$'],
-            ['include', 'platform/graphics/chromium/TransparencyWin\\.(cpp|h)$'],
+            ['include', 'platform/graphics/win/FontFallbackWin\\.(cpp|h)$'],
+            ['include', 'platform/graphics/win/FontPlatformDataWin\\.(cpp|h)$'],
+            ['include', 'platform/graphics/win/FontWin\\.cpp$'],
+            ['include', 'platform/graphics/win/TransparencyWin\\.(cpp|h)$'],
+            ['include', 'platform/graphics/win/UniscribeHelper\\.(cpp|h)$'],
+            ['include', 'platform/graphics/win/UniscribeHelperTextRun\\.(cpp|h)$'],
             ['include', 'platform/graphics/opentype/'],
             ['include', 'platform/graphics/skia/SkiaFontWin\\.(cpp|h)$'],
 
@@ -761,9 +750,9 @@
                 ['include', 'platform/graphics/skia/FontCacheSkiaWin\\.cpp$'],
                 ['include', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
                 ['include', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
-                ['exclude', 'platform/graphics/chromium/SimpleFontDataChromiumWin\\.cpp$'],
-                ['exclude', 'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin\\.cpp$'],
-                ['exclude', 'platform/graphics/chromium/FontCacheChromiumWin\\.cpp$'],
+                ['exclude', 'platform/graphics/win/SimpleFontDataWin\\.cpp$'],
+                ['exclude', 'platform/graphics/win/GlyphPageTreeNodeWin\\.cpp$'],
+                ['exclude', 'platform/graphics/win/FontCacheWin\\.cpp$'],
                 ['exclude', 'platform/graphics/win/FontCustomPlatformDataWin\\.cpp$'],
               ],
             }],
@@ -774,7 +763,7 @@
                 ['include', 'platform/graphics/harfbuzz/HarfBuzzShaper\\.(cpp|h)$'],
                 ['include', 'platform/graphics/harfbuzz/HarfBuzzShaperBase\\.(cpp|h)$'],
                 ['include', 'platform/graphics/harfbuzz/HarfBuzzFaceSkia\\.cpp$'],
-                ['exclude', 'platform/graphics/chromium/FontChromiumWin\\.cpp$'],
+                ['exclude', 'platform/graphics/win/FontWin\\.cpp$'],
                 ['exclude', '/(Uniscribe)[^/]*\\.(cpp|h)$'],
               ],
               'dependencies': [
@@ -798,8 +787,8 @@
           'sources/': [
             ['include', 'platform/chromium/ClipboardChromiumLinux\\.cpp$'],
             ['include', 'platform/chromium/FileSystemChromiumLinux\\.cpp$'],
-            ['include', 'platform/graphics/chromium/GlyphPageTreeNodeLinux\\.cpp$'],
-            ['include', 'platform/graphics/chromium/VDMXParser\\.cpp$'],
+            ['include', 'platform/graphics/linux/GlyphPageTreeNodeLinux\\.cpp$'],
+            ['include', 'platform/graphics/VDMXParser\\.cpp$'],
           ],
         }, { # OS!="android"
           'sources/': [
@@ -969,6 +958,7 @@
           ],
         }],
         ['OS=="android"', {
+          'sources/': [['exclude', 'ViewportStyle\\.cpp$']],
           'cflags': [
             # WebCore does not work with strict aliasing enabled.
             # https://bugs.webkit.org/show_bug.cgi?id=25864
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index 452058a..1cf56e5 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -5,7 +5,6 @@
             'css/CSSCharsetRule.idl',
             'css/CSSFontFaceLoadEvent.idl',
             'css/CSSFontFaceRule.idl',
-            'css/CSSHostRule.idl',
             'css/CSSImportRule.idl',
             'css/CSSKeyframeRule.idl',
             'css/CSSKeyframesRule.idl',
@@ -274,8 +273,9 @@
             'html/track/TextTrackCueList.idl',
             'html/track/TextTrackList.idl',
             'html/track/TrackEvent.idl',
-            'html/track/VTTRegion.idl',
-            'html/track/VTTRegionList.idl',
+            'html/track/vtt/VTTCue.idl',
+            'html/track/vtt/VTTRegion.idl',
+            'html/track/vtt/VTTRegionList.idl',
             'inspector/InjectedScriptHost.idl',
             'inspector/InspectorFrontendHost.idl',
             'inspector/InspectorOverlayHost.idl',
@@ -398,6 +398,7 @@
             'svg/SVGGElement.idl',
             'svg/SVGGlyphElement.idl',
             'svg/SVGGlyphRefElement.idl',
+            'svg/SVGGeometryElement.idl',
             'svg/SVGGradientElement.idl',
             'svg/SVGGraphicsElement.idl',
             'svg/SVGHKernElement.idl',
@@ -530,6 +531,7 @@
             'accessibility/AXTableHeaderContainer.h',
             'accessibility/AXTableRow.cpp',
             'accessibility/AXTableRow.h',
+            'animation/ActiveAnimations.cpp',
             'animation/ActiveAnimations.h',
             'animation/AnimatableClipPathOperation.cpp',
             'animation/AnimatableClipPathOperation.h',
@@ -579,6 +581,9 @@
             'animation/AnimationStack.h',
             'animation/CompositorAnimations.cpp',
             'animation/CompositorAnimations.h',
+            'animation/CompositorAnimationsImpl.h',
+            'animation/DocumentAnimations.cpp',
+            'animation/DocumentAnimations.h',
             'animation/DocumentTimeline.cpp',
             'animation/DocumentTimeline.h',
             'animation/InertAnimation.cpp',
@@ -595,6 +600,8 @@
             'animation/css/CSSAnimatableValueFactory.h',
             'animation/css/CSSAnimations.cpp',
             'animation/css/CSSAnimations.h',
+            'animation/css/CSSPendingAnimations.cpp',
+            'animation/css/CSSPendingAnimations.h',
             'animation/css/TransitionTimeline.cpp',
             'animation/css/TransitionTimeline.h',
             'css/BasicShapeFunctions.cpp',
@@ -616,6 +623,7 @@
             'css/CSSComputedStyleDeclaration.cpp',
             'css/CSSCrossfadeValue.cpp',
             'css/CSSCrossfadeValue.h',
+            'css/CSSCustomFontData.h',
             'css/CSSCursorImageValue.cpp',
             'css/CSSDefaultStyleSheets.cpp',
             'css/CSSDefaultStyleSheets.h',
@@ -643,12 +651,12 @@
             'css/CSSFunctionValue.h',
             'css/CSSGradientValue.cpp',
             'css/CSSGradientValue.h',
+            'css/CSSGridLineNamesValue.cpp',
+            'css/CSSGridLineNamesValue.h',
             'css/CSSGridTemplateValue.cpp',
             'css/CSSGridTemplateValue.h',
             'css/CSSGroupingRule.cpp',
             'css/CSSGroupingRule.h',
-            'css/CSSHostRule.cpp',
-            'css/CSSHostRule.h',
             'css/CSSImageGeneratorValue.cpp',
             'css/CSSImageSetValue.cpp',
             'css/CSSImageValue.cpp',
@@ -676,6 +684,7 @@
             'css/CSSPageRule.cpp',
             'css/CSSPageRule.h',
             'css/CSSParser.h',
+            'css/CSSParserMode.cpp',
             'css/CSSParserMode.h',
             'css/CSSParserValues.cpp',
             'css/CSSPrimitiveValue.cpp',
@@ -712,6 +721,7 @@
             'css/CSSSVGDocumentValue.h',
             'css/CSSTimingFunctionValue.cpp',
             'css/CSSTimingFunctionValue.h',
+            'css/CSSTokenizer.h',
             'css/CSSToStyleMap.cpp',
             'css/CSSToStyleMap.h',
             'css/CSSTransformValue.cpp',
@@ -734,8 +744,6 @@
             'css/DOMWindowCSS.h',
             'css/DocumentFontFaceSet.h',
             'css/DocumentFontFaceSet.cpp',
-            'css/DocumentRuleSets.cpp',
-            'css/DocumentRuleSets.h',
             'css/ElementRuleCollector.cpp',
             'css/ElementRuleCollector.h',
             'css/FontFaceSet.h',
@@ -804,6 +812,11 @@
             'css/StyleSheetContents.h',
             'css/StyleSheetList.cpp',
             'css/StyleSheetList.h',
+            'css/TreeBoundaryCrossingRules.cpp',
+            'css/TreeBoundaryCrossingRules.h',
+            'css/ViewportStyle.cpp',
+            'css/ViewportStyleAndroid.cpp',
+            'css/ViewportStyle.h',
             'css/resolver/AnimatedStyleBuilder.cpp',
             'css/resolver/AnimatedStyleBuilder.h',
             'css/resolver/ElementResolveContext.cpp',
@@ -822,6 +835,8 @@
             'css/resolver/MediaQueryResult.h',
             'css/resolver/ScopedStyleResolver.cpp',
             'css/resolver/ScopedStyleResolver.h',
+            'css/resolver/ScopedStyleTree.cpp',
+            'css/resolver/ScopedStyleTree.h',
             'css/resolver/SharedStyleFinder.cpp',
             'css/resolver/SharedStyleFinder.h',
             'css/resolver/StyleAdjuster.cpp',
@@ -833,6 +848,8 @@
             'css/resolver/StyleResolverIncludes.h',
             'css/resolver/StyleResolverState.cpp',
             'css/resolver/StyleResolverState.h',
+            'css/resolver/StyleResolverStats.cpp',
+            'css/resolver/StyleResolverStats.h',
             'css/resolver/StyleResourceLoader.cpp',
             'css/resolver/StyleResourceLoader.h',
             'css/resolver/TransformBuilder.cpp',
@@ -859,6 +876,7 @@
             'editing/EditingStyle.cpp',
             'editing/Editor.cpp',
             'editing/EditorCommand.cpp',
+            'editing/EditorKeyBindings.cpp',
             'editing/FormatBlockCommand.cpp',
             'editing/FormatBlockCommand.h',
             'editing/FrameSelection.cpp',
@@ -901,6 +919,7 @@
             'editing/ReplaceNodeWithSpanCommand.cpp',
             'editing/ReplaceNodeWithSpanCommand.h',
             'editing/ReplaceSelectionCommand.cpp',
+            'editing/SelectionType.h',
             'editing/SetNodeAttributeCommand.cpp',
             'editing/SetNodeAttributeCommand.h',
             'editing/SetSelectionCommand.cpp',
@@ -928,6 +947,8 @@
             'editing/TextInsertionBaseCommand.h',
             'editing/TextIterator.cpp',
             'editing/TypingCommand.cpp',
+            'editing/UndoStack.cpp',
+            'editing/UndoStack.h',
             'editing/UndoStep.h',
             'editing/UnlinkCommand.cpp',
             'editing/UnlinkCommand.h',
@@ -1147,8 +1168,6 @@
             'loader/FrameLoader.cpp',
             'loader/FrameLoaderStateMachine.cpp',
             'loader/HistoryController.cpp',
-            'loader/IconController.cpp',
-            'loader/IconController.h',
             'loader/ImageLoader.cpp',
             'loader/ImageLoader.h',
             'loader/LinkLoader.cpp',
@@ -1185,13 +1204,6 @@
             'loader/appcache/ApplicationCache.cpp',
             'loader/appcache/ApplicationCache.h',
             'loader/appcache/ApplicationCacheHost.h',
-            'loader/archive/ArchiveResource.cpp',
-            'loader/archive/ArchiveResourceCollection.cpp',
-            'loader/archive/ArchiveResourceCollection.h',
-            'loader/archive/MHTMLArchive.cpp',
-            'loader/archive/MHTMLArchive.h',
-            'loader/archive/MHTMLParser.cpp',
-            'loader/archive/MHTMLParser.h',
             'page/AutoscrollController.cpp',
             'page/AutoscrollController.h',
             'frame/BarProp.cpp',
@@ -1230,6 +1242,7 @@
             'frame/DOMWindowProperty.cpp',
             'frame/DOMWindowProperty.h',
             'page/DragController.cpp',
+            'page/DragData.cpp',
             'page/EventHandler.cpp',
             'page/EventSource.cpp',
             'page/EventSource.h',
@@ -1304,7 +1317,7 @@
             'page/TouchAdjustment.h',
             'page/TouchDisambiguation.cpp',
             'page/TouchDisambiguation.h',
-            'page/UseCounter.cpp',
+            'frame/UseCounter.cpp',
             'page/WindowFeatures.cpp',
             'page/WindowFocusAllowedIndicator.cpp',
             'workers/WorkerNavigator.cpp',
@@ -1333,10 +1346,6 @@
             'plugins/DOMPlugin.h',
             'plugins/DOMPluginArray.cpp',
             'plugins/DOMPluginArray.h',
-            'plugins/PluginData.cpp',
-            'plugins/PluginData.h',
-            'plugins/PluginListBuilder.cpp',
-            'plugins/PluginListBuilder.h',
             'plugins/PluginOcclusionSupport.cpp',
             'plugins/PluginOcclusionSupport.h',
             'plugins/PluginView.h',
@@ -1349,6 +1358,8 @@
             'rendering/ClipRect.cpp',
             'rendering/ClipRect.h',
             'rendering/CompositedLayerMapping.cpp',
+            'rendering/CompositedLayerMapping.h',
+            'rendering/CompositedLayerMappingPtr.h',
             'rendering/CompositingReasons.h',
             'rendering/CounterNode.cpp',
             'rendering/CounterNode.h',
@@ -1382,6 +1393,7 @@
             'rendering/OrderIterator.h',
             'rendering/LayoutIndicator.cpp',
             'rendering/LayoutIndicator.h',
+            'rendering/LayoutRectRecorder.cpp',
             'rendering/LayoutRepainter.cpp',
             'rendering/LineWidth.cpp',
             'rendering/LineWidth.h',
@@ -1474,6 +1486,8 @@
             'rendering/RenderMultiColumnFlowThread.h',
             'rendering/RenderMultiColumnSet.cpp',
             'rendering/RenderMultiColumnSet.h',
+            'rendering/RenderNamedFlowFragment.cpp',
+            'rendering/RenderNamedFlowFragment.h',
             'rendering/RenderNamedFlowThread.cpp',
             'rendering/RenderNamedFlowThread.h',
             'rendering/RenderObject.cpp',
@@ -1530,8 +1544,6 @@
             'rendering/RenderTextControlSingleLine.h',
             'rendering/RenderTextFragment.cpp',
             'rendering/RenderTextFragment.h',
-            'rendering/RenderTextTrackCue.cpp',
-            'rendering/RenderTextTrackCue.h',
             'rendering/RenderTheme.cpp',
             'rendering/RenderTheme.h',
             'rendering/RenderThemeChromiumAndroid.cpp',
@@ -1549,14 +1561,14 @@
             'rendering/RenderThemeChromiumWin.cpp',
             'rendering/RenderThemeChromiumWin.h',
             'rendering/RenderTreeAsText.cpp',
+            'rendering/RenderVTTCue.cpp',
+            'rendering/RenderVTTCue.h',
             'rendering/RenderVideo.cpp',
             'rendering/RenderVideo.h',
             'rendering/RenderView.cpp',
             'rendering/RenderWidget.cpp',
             'rendering/RenderWordBreak.cpp',
             'rendering/RenderWordBreak.h',
-            'rendering/RenderingConfiguration.cpp',
-            'rendering/RenderingConfiguration.h',
             'rendering/RootInlineBox.cpp',
             'rendering/ScrollBehavior.cpp',
             'rendering/SubtreeLayoutScope.cpp',
@@ -1584,6 +1596,8 @@
             'rendering/shapes/ShapeOutsideInfo.cpp',
             'rendering/shapes/ShapeOutsideInfo.h',
             'rendering/style/BasicShapes.cpp',
+            'rendering/style/BorderImageLength.h',
+            'rendering/style/BorderImageLengthBox.h',
             'rendering/style/CachedUAStyle.h',
             'rendering/style/ContentData.cpp',
             'rendering/style/CounterDirectives.cpp',
@@ -1706,8 +1720,9 @@
             'workers/WorkerConsole.h',
             'workers/WorkerEventQueue.cpp',
             'workers/WorkerEventQueue.h',
-            'workers/WorkerGlobalScopeProxy.cpp',
             'workers/WorkerGlobalScopeProxy.h',
+            'workers/WorkerGlobalScopeProxyProvider.h',
+            'workers/WorkerGlobalScopeProxyProvider.cpp',
             'workers/WorkerGlobalScope.cpp',
             'workers/WorkerGlobalScope.h',
             'workers/WorkerLoaderProxy.h',
@@ -1830,6 +1845,7 @@
             'dom/DecodedDataDocumentParser.cpp',
             'dom/DecodedDataDocumentParser.h',
             'dom/Document.cpp',
+            'dom/DocumentEncodingData.h',
             'dom/DocumentFragment.cpp',
             'dom/DocumentFullscreen.cpp',
             'dom/DocumentFullscreen.h',
@@ -1882,6 +1898,8 @@
             'dom/Entity.h',
             'dom/ExecutionContextTask.cpp',
             'dom/ExecutionContextTask.h',
+            'dom/MainThreadTaskRunner.cpp',
+            'dom/MainThreadTaskRunner.h',
             'dom/FullscreenElementStack.cpp',
             'dom/FullscreenElementStack.h',
             'dom/GlobalEventHandlers.h',
@@ -1897,7 +1915,6 @@
             'dom/MessageChannel.cpp',
             'dom/MessageChannel.h',
             'dom/MessagePort.cpp',
-            'dom/MessagePortChannel.cpp',
             'dom/Microtask.cpp',
             'dom/Microtask.h',
             'dom/MutationCallback.h',
@@ -2026,6 +2043,8 @@
             'dom/StyleSheetCollection.h',
             'dom/StyleSheetScopingNodeList.cpp',
             'dom/StyleSheetScopingNodeList.h',
+            'dom/StyleTreeScopeTracker.cpp',
+            'dom/StyleTreeScopeTracker.h',
             'dom/TagNodeList.cpp',
             'dom/TagNodeList.h',
             'dom/Text.cpp',
@@ -2054,7 +2073,6 @@
             'dom/VisitedLinkState.h',
             'dom/WheelController.cpp',
             'dom/WheelController.h',
-            'dom/WhitespaceChildList.h',
             'events/AutocompleteErrorEvent.h',
             'events/BeforeLoadEvent.h',
             'events/BeforeTextInsertedEvent.cpp',
@@ -2473,8 +2491,6 @@
             'html/forms/ImageInputType.h',
             'html/forms/InputType.cpp',
             'html/forms/InputType.h',
-            'html/forms/InputTypeNames.cpp',
-            'html/forms/InputTypeNames.h',
             'html/forms/InputTypeView.cpp',
             'html/forms/InputTypeView.h',
             'html/forms/MonthInputType.cpp',
@@ -2635,34 +2651,29 @@
             'html/track/TextTrackList.cpp',
             'html/track/TrackBase.h',
             'html/track/TrackEvent.cpp',
-            'html/track/VTTRegion.cpp',
-            'html/track/VTTRegion.h',
-            'html/track/VTTRegionList.cpp',
-            'html/track/VTTRegionList.h',
-            'html/track/WebVTTElement.cpp',
-            'html/track/WebVTTElement.h',
-            'html/track/WebVTTParser.cpp',
-            'html/track/WebVTTParser.h',
-            'html/track/WebVTTToken.h',
-            'html/track/WebVTTTokenizer.cpp',
-            'html/track/WebVTTTokenizer.h',
+            'html/track/vtt/BufferedLineReader.cpp',
+            'html/track/vtt/BufferedLineReader.h',
+            'html/track/vtt/VTTCue.cpp',
+            'html/track/vtt/VTTCue.h',
+            'html/track/vtt/VTTElement.cpp',
+            'html/track/vtt/VTTElement.h',
+            'html/track/vtt/VTTParser.cpp',
+            'html/track/vtt/VTTParser.h',
+            'html/track/vtt/VTTRegion.cpp',
+            'html/track/vtt/VTTRegion.h',
+            'html/track/vtt/VTTRegionList.cpp',
+            'html/track/vtt/VTTRegionList.h',
+            'html/track/vtt/VTTToken.h',
+            'html/track/vtt/VTTTokenizer.cpp',
+            'html/track/vtt/VTTTokenizer.h',
         ],
         'webcore_platform_files': [
-            'platform/ContextMenu.cpp',
-            'platform/ContextMenuItem.cpp',
             'platform/Cursor.cpp',
-            'platform/DragData.cpp',
             'platform/DragImage.cpp',
-            'platform/KillRing.h',
-            'platform/KillRingNone.cpp',
-            'platform/MIMETypeFromURL.cpp',
-            'platform/MIMETypeFromURL.h',
             'platform/OverscrollTheme.cpp',
             'platform/OverscrollTheme.h',
             'platform/Pasteboard.cpp',
             'platform/Pasteboard.h',
-            'platform/PlatformInstrumentation.cpp',
-            'platform/PlatformInstrumentation.h',
             'platform/PlatformSpeechSynthesisUtterance.cpp',
             'platform/PlatformSpeechSynthesisUtterance.h',
             'platform/PlatformSpeechSynthesisVoice.cpp',
@@ -2695,9 +2706,9 @@
             'platform/ScrollbarThemeWin.cpp',
             'platform/ScrollbarThemeWin.h',
             'platform/Theme.cpp',
-            'platform/animation/AnimationValue.h',
             'platform/animation/AnimationTranslationUtil.cpp',
             'platform/animation/AnimationTranslationUtil.h',
+            'platform/animation/AnimationValue.h',
             'platform/animation/CSSAnimationData.cpp',
             'platform/animation/CSSAnimationDataList.cpp',
             'platform/animation/KeyframeValueList.cpp',
@@ -2713,115 +2724,104 @@
             'platform/chromium/KeyCodeConversionAndroid.cpp',
             'platform/chromium/KeyCodeConversionGtk.cpp',
             'platform/chromium/KeyboardCodes.h',
-            'platform/chromium/MIMETypeRegistryChromium.cpp',
             'platform/graphics/BitmapImage.cpp',
+            'platform/graphics/Canvas2DLayerBridge.cpp',
+            'platform/graphics/Canvas2DLayerBridge.h',
+            'platform/graphics/Canvas2DLayerManager.cpp',
+            'platform/graphics/Canvas2DLayerManager.h',
+            'platform/graphics/CrossfadeGeneratedImage.cpp',
             'platform/graphics/CrossfadeGeneratedImage.cpp',
             'platform/graphics/CrossfadeGeneratedImage.h',
-            'platform/graphics/GradientGeneratedImage.cpp',
-            'platform/graphics/GradientGeneratedImage.h',
+            'platform/graphics/CrossfadeGeneratedImage.h',
+            'platform/graphics/CustomFontData.h',
+            'platform/graphics/CustomFontData.h',
+            'platform/graphics/DeferredImageDecoder.cpp',
+            'platform/graphics/DeferredImageDecoder.h',
+            'platform/graphics/DiscardablePixelRef.cpp',
+            'platform/graphics/DiscardablePixelRef.h',
+            'platform/graphics/Extensions3D.cpp',
             'platform/graphics/Extensions3D.cpp',
             'platform/graphics/Extensions3D.h',
+            'platform/graphics/Extensions3D.h',
             'platform/graphics/Font.cpp',
+            'platform/graphics/Font.cpp',
+            'platform/graphics/FontDataCache.cpp',
+            'platform/graphics/FontDataCache.h',
+            'platform/graphics/FontCache.cpp',
             'platform/graphics/FontCache.cpp',
             'platform/graphics/FontFallbackList.cpp',
+            'platform/graphics/FontFallbackList.cpp',
+            'platform/graphics/FontFastPath.cpp',
             'platform/graphics/FontFastPath.cpp',
             'platform/graphics/FontPlatformData.cpp',
+            'platform/graphics/FontPlatformData.cpp',
+            'platform/graphics/FontPlatformData.h',
             'platform/graphics/FontPlatformData.h',
             'platform/graphics/FrameData.cpp',
+            'platform/graphics/FrameData.cpp',
             'platform/graphics/FrameData.h',
+            'platform/graphics/FrameData.h',
+            'platform/graphics/GaneshUtils.cpp',
+            'platform/graphics/GeneratedImage.cpp',
             'platform/graphics/GeneratedImage.cpp',
             'platform/graphics/GeneratedImage.h',
+            'platform/graphics/GeneratedImage.h',
+            'platform/graphics/GlyphPageTreeNode.cpp',
             'platform/graphics/GlyphPageTreeNode.cpp',
             'platform/graphics/Gradient.cpp',
+            'platform/graphics/Gradient.cpp',
+            'platform/graphics/GradientGeneratedImage.cpp',
+            'platform/graphics/GradientGeneratedImage.cpp',
+            'platform/graphics/GradientGeneratedImage.h',
+            'platform/graphics/GradientGeneratedImage.h',
+            'platform/graphics/GraphicsContext.cpp',
             'platform/graphics/GraphicsContext.cpp',
             'platform/graphics/GraphicsContext3D.cpp',
+            'platform/graphics/GraphicsContext3D.cpp',
+            'platform/graphics/GraphicsContext3DImagePacking.cpp',
             'platform/graphics/GraphicsContext3DImagePacking.cpp',
             'platform/graphics/GraphicsContextAnnotation.cpp',
+            'platform/graphics/GraphicsContextAnnotation.cpp',
+            'platform/graphics/GraphicsLayer.cpp',
             'platform/graphics/GraphicsLayer.cpp',
             'platform/graphics/Image.cpp',
+            'platform/graphics/Image.cpp',
             'platform/graphics/ImageBuffer.cpp',
+            'platform/graphics/ImageBuffer.cpp',
+            'platform/graphics/ImageDecodingStore.cpp',
+            'platform/graphics/ImageDecodingStore.h',
+            'platform/graphics/ImageFrameGenerator.cpp',
+            'platform/graphics/ImageFrameGenerator.h',
             'platform/graphics/ImageSource.cpp',
-            'platform/graphics/InbandTextTrackPrivate.h',
-            'platform/graphics/InbandTextTrackPrivateClient.h',
-            'platform/graphics/MediaPlayer.cpp',
-            'platform/graphics/MediaPlayer.h',
+            'platform/graphics/ImageSource.cpp',
+            'platform/graphics/LazyDecodingPixelRef.cpp',
+            'platform/graphics/LazyDecodingPixelRef.h',
+            'platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp',
+            'platform/graphics/OpaqueRectTrackingContentLayerDelegate.h',
+            'platform/graphics/Path.cpp',
             'platform/graphics/Path.cpp',
             'platform/graphics/Pattern.cpp',
+            'platform/graphics/Pattern.cpp',
+            'platform/graphics/SVGGlyph.cpp',
+            'platform/graphics/SVGGlyph.cpp',
+            'platform/graphics/SegmentedFontData.cpp',
             'platform/graphics/SegmentedFontData.cpp',
             'platform/graphics/SegmentedFontData.h',
+            'platform/graphics/SegmentedFontData.h',
             'platform/graphics/SimpleFontData.cpp',
-            'platform/graphics/SVGGlyph.cpp',
+            'platform/graphics/SimpleFontData.cpp',
+            'platform/graphics/StringTruncator.cpp',
             'platform/graphics/StringTruncator.cpp',
             'platform/graphics/StrokeData.cpp',
+            'platform/graphics/StrokeData.cpp',
+            'platform/graphics/VDMXParser.cpp',
+            'platform/graphics/VDMXParser.h',
+            'platform/graphics/WidthIterator.cpp',
             'platform/graphics/WidthIterator.cpp',
             'platform/graphics/WidthIterator.h',
-            'platform/graphics/cg/FloatPointCG.cpp',
-            'platform/graphics/cg/FloatRectCG.cpp',
-            'platform/graphics/cg/FloatSizeCG.cpp',
-            'platform/graphics/cg/IntPointCG.cpp',
-            'platform/graphics/cg/IntRectCG.cpp',
-            'platform/graphics/cg/IntSizeCG.cpp',
-            'platform/graphics/chromium/Canvas2DLayerBridge.cpp',
-            'platform/graphics/chromium/Canvas2DLayerBridge.h',
-            'platform/graphics/chromium/Canvas2DLayerManager.cpp',
-            'platform/graphics/chromium/Canvas2DLayerManager.h',
-            'platform/graphics/chromium/CrossProcessFontLoading.h',
-            'platform/graphics/chromium/CrossProcessFontLoading.mm',
-            'platform/graphics/chromium/DeferredImageDecoder.cpp',
-            'platform/graphics/chromium/DeferredImageDecoder.h',
-            'platform/graphics/chromium/DiscardablePixelRef.cpp',
-            'platform/graphics/chromium/DiscardablePixelRef.h',
-            'platform/graphics/chromium/FontCacheAndroid.cpp',
-            'platform/graphics/chromium/FontCacheChromiumLinux.cpp',
-            'platform/graphics/chromium/FontCacheChromiumWin.cpp',
-            'platform/graphics/chromium/FontChromiumWin.cpp',
-            'platform/graphics/chromium/FontFallbackWin.cpp',
-            'platform/graphics/chromium/FontFallbackWin.h',
-            'platform/graphics/chromium/FontPlatformDataChromiumWin.cpp',
-            'platform/graphics/chromium/FontPlatformDataChromiumWin.h',
-            'platform/graphics/chromium/FontRenderStyle.h',
-            'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp',
-            'platform/graphics/chromium/ImageDecodingStore.cpp',
-            'platform/graphics/chromium/ImageDecodingStore.h',
-            'platform/graphics/chromium/ImageFrameGenerator.cpp',
-            'platform/graphics/chromium/ImageFrameGenerator.h',
-            'platform/graphics/chromium/LazyDecodingPixelRef.cpp',
-            'platform/graphics/chromium/LazyDecodingPixelRef.h',
-            'platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp',
-            'platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h',
-            'platform/graphics/chromium/SimpleFontDataChromiumWin.cpp',
-            'platform/graphics/chromium/TransparencyWin.cpp',
-            'platform/graphics/chromium/TransparencyWin.h',
-            'platform/graphics/chromium/UniscribeHelper.cpp',
-            'platform/graphics/chromium/UniscribeHelper.h',
-            'platform/graphics/chromium/UniscribeHelperTextRun.cpp',
-            'platform/graphics/chromium/UniscribeHelperTextRun.h',
-            'platform/graphics/chromium/VDMXParser.cpp',
-            'platform/graphics/chromium/VDMXParser.h',
+            'platform/graphics/WidthIterator.h',
+            'platform/graphics/android/FontCacheAndroid.cpp',
             'platform/graphics/cocoa/FontPlatformDataCocoa.mm',
-            'platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp',
-            'platform/graphics/filters/custom/CustomFilterCompiledProgram.h',
-            'platform/graphics/filters/custom/CustomFilterGlobalContext.cpp',
-            'platform/graphics/filters/custom/CustomFilterGlobalContext.h',
-            'platform/graphics/filters/custom/CustomFilterMesh.cpp',
-            'platform/graphics/filters/custom/CustomFilterMesh.h',
-            'platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp',
-            'platform/graphics/filters/custom/CustomFilterMeshGenerator.h',
-            'platform/graphics/filters/custom/CustomFilterOperation.cpp',
-            'platform/graphics/filters/custom/CustomFilterOperation.h',
-            'platform/graphics/filters/custom/CustomFilterProgram.cpp',
-            'platform/graphics/filters/custom/CustomFilterProgram.h',
-            'platform/graphics/filters/custom/CustomFilterProgramInfo.cpp',
-            'platform/graphics/filters/custom/CustomFilterProgramInfo.h',
-            'platform/graphics/filters/custom/CustomFilterRenderer.cpp',
-            'platform/graphics/filters/custom/CustomFilterRenderer.h',
-            'platform/graphics/filters/custom/CustomFilterTransformParameter.h',
-            'platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp',
-            'platform/graphics/filters/custom/CustomFilterValidatedProgram.h',
-            'platform/graphics/filters/custom/FECustomFilter.cpp',
-            'platform/graphics/filters/custom/FECustomFilter.h',
-            'platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp',
-            'platform/graphics/filters/custom/ValidatedCustomFilterOperation.h',
             'platform/graphics/filters/DistantLightSource.cpp',
             'platform/graphics/filters/DistantLightSource.h',
             'platform/graphics/filters/FEBlend.cpp',
@@ -2865,7 +2865,7 @@
             'platform/graphics/filters/FilterOperation.h',
             'platform/graphics/filters/FilterOperations.cpp',
             'platform/graphics/filters/FilterOperations.h',
-            'platform/graphics/filters/LightSource.h',
+            'platform/graphics/filters/ParallelJobs.h',
             'platform/graphics/filters/PointLightSource.cpp',
             'platform/graphics/filters/PointLightSource.h',
             'platform/graphics/filters/ReferenceFilter.cpp',
@@ -2878,6 +2878,24 @@
             'platform/graphics/filters/SourceGraphic.h',
             'platform/graphics/filters/SpotLightSource.cpp',
             'platform/graphics/filters/SpotLightSource.h',
+            'platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp',
+            'platform/graphics/filters/custom/CustomFilterCompiledProgram.h',
+            'platform/graphics/filters/custom/CustomFilterGlobalContext.cpp',
+            'platform/graphics/filters/custom/CustomFilterGlobalContext.h',
+            'platform/graphics/filters/custom/CustomFilterMesh.cpp',
+            'platform/graphics/filters/custom/CustomFilterMesh.h',
+            'platform/graphics/filters/custom/CustomFilterOperation.cpp',
+            'platform/graphics/filters/custom/CustomFilterOperation.h',
+            'platform/graphics/filters/custom/CustomFilterProgram.cpp',
+            'platform/graphics/filters/custom/CustomFilterProgram.h',
+            'platform/graphics/filters/custom/CustomFilterRenderer.cpp',
+            'platform/graphics/filters/custom/CustomFilterRenderer.h',
+            'platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp',
+            'platform/graphics/filters/custom/CustomFilterValidatedProgram.h',
+            'platform/graphics/filters/custom/FECustomFilter.cpp',
+            'platform/graphics/filters/custom/FECustomFilter.h',
+            'platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp',
+            'platform/graphics/filters/custom/ValidatedCustomFilterOperation.h',
             'platform/graphics/gpu/DrawingBuffer.cpp',
             'platform/graphics/gpu/DrawingBuffer.h',
             'platform/graphics/gpu/SharedGraphicsContext3D.cpp',
@@ -2885,33 +2903,29 @@
             'platform/graphics/harfbuzz/FontHarfBuzz.cpp',
             'platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp',
             'platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h',
-            'platform/graphics/harfbuzz/HarfBuzzFaceCoreText.cpp',
-            'platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp',
             'platform/graphics/harfbuzz/HarfBuzzFace.cpp',
             'platform/graphics/harfbuzz/HarfBuzzFace.h',
+            'platform/graphics/harfbuzz/HarfBuzzFaceCoreText.cpp',
+            'platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp',
             'platform/graphics/harfbuzz/HarfBuzzShaper.cpp',
             'platform/graphics/harfbuzz/HarfBuzzShaper.h',
+            'platform/graphics/linux/FontCacheLinux.cpp',
             'platform/graphics/mac/ColorMac.h',
             'platform/graphics/mac/ColorMac.mm',
             'platform/graphics/mac/ComplexTextController.cpp',
             'platform/graphics/mac/ComplexTextController.h',
             'platform/graphics/mac/ComplexTextControllerCoreText.mm',
-            'platform/graphics/mac/FloatPointMac.mm',
-            'platform/graphics/mac/FloatRectMac.mm',
-            'platform/graphics/mac/FloatSizeMac.mm',
             'platform/graphics/mac/FontCacheMac.mm',
             'platform/graphics/mac/FontComplexTextMac.cpp',
             'platform/graphics/mac/FontCustomPlatformDataMac.cpp',
             'platform/graphics/mac/FontMac.cpp',
             'platform/graphics/mac/GlyphPageTreeNodeMac.cpp',
-            'platform/graphics/mac/IntPointMac.mm',
-            'platform/graphics/mac/IntRectMac.mm',
-            'platform/graphics/mac/IntSizeMac.mm',
+            'platform/graphics/mac/MemoryActivatedFont.h',
+            'platform/graphics/mac/MemoryActivatedFont.mm',
             'platform/graphics/mac/SimpleFontDataCoreText.cpp',
             'platform/graphics/mac/SimpleFontDataMac.mm',
             'platform/graphics/opentype/OpenTypeSanitizer.cpp',
             'platform/graphics/opentype/OpenTypeSanitizer.h',
-            'platform/graphics/opentype/OpenTypeTypes.h',
             'platform/graphics/opentype/OpenTypeUtilities.cpp',
             'platform/graphics/opentype/OpenTypeUtilities.h',
             'platform/graphics/opentype/OpenTypeVerticalData.cpp',
@@ -2928,11 +2942,21 @@
             'platform/graphics/skia/SimpleFontDataSkia.cpp',
             'platform/graphics/skia/SkiaFontWin.cpp',
             'platform/graphics/skia/SkiaFontWin.h',
-            'platform/graphics/skia/SkiaSharedBufferStream.cpp',
-            'platform/graphics/skia/SkiaSharedBufferStream.h',
             'platform/graphics/skia/SkiaUtils.cpp',
             'platform/graphics/skia/SkiaUtils.h',
+            'platform/graphics/win/FontCacheWin.cpp',
             'platform/graphics/win/FontCustomPlatformDataWin.cpp',
+            'platform/graphics/win/FontPlatformDataWin.cpp',
+            'platform/graphics/win/FontPlatformDataWin.h',
+            'platform/graphics/win/FontWin.cpp',
+            'platform/graphics/win/GlyphPageTreeNodeWin.cpp',
+            'platform/graphics/win/SimpleFontDataWin.cpp',
+            'platform/graphics/win/TransparencyWin.cpp',
+            'platform/graphics/win/TransparencyWin.h',
+            'platform/graphics/win/UniscribeHelper.cpp',
+            'platform/graphics/win/UniscribeHelper.h',
+            'platform/graphics/win/UniscribeHelperTextRun.cpp',
+            'platform/graphics/win/UniscribeHelperTextRun.h',
             'platform/image-decoders/ImageDecoder.cpp',
             'platform/image-decoders/ImageDecoder.h',
             'platform/image-decoders/ImageFrame.cpp',
@@ -2958,8 +2982,6 @@
             'platform/image-encoders/skia/PNGImageEncoder.h',
             'platform/image-encoders/skia/WEBPImageEncoder.cpp',
             'platform/image-encoders/skia/WEBPImageEncoder.h',
-            'platform/mac/BlockExceptions.mm',
-            'platform/mac/KillRingMac.mm',
             'platform/mac/LocalCurrentGraphicsContext.h',
             'platform/mac/LocalCurrentGraphicsContext.mm',
             'platform/mac/NSScrollerImpDetails.h',
@@ -2970,28 +2992,17 @@
             'platform/mac/ScrollElasticityController.mm',
             'platform/mac/ThemeMac.h',
             'platform/mac/ThemeMac.mm',
-            'platform/mac/WebFontCache.mm',
-            'platform/mediastream/MediaConstraints.h',
             'platform/mediastream/MediaStreamCenter.cpp',
             'platform/mediastream/MediaStreamCenter.h',
-            'platform/mediastream/MediaStreamComponent.cpp',
-            'platform/mediastream/MediaStreamComponent.h',
             'platform/mediastream/MediaStreamDescriptor.cpp',
             'platform/mediastream/MediaStreamDescriptor.h',
-            'platform/mediastream/MediaStreamSource.cpp',
-            'platform/mediastream/MediaStreamSource.h',
-            'platform/mediastream/RTCDTMFSenderHandler.cpp',
-            'platform/mediastream/RTCDTMFSenderHandler.h',
-            'platform/mediastream/RTCDTMFSenderHandlerClient.h',
             'platform/mediastream/RTCDataChannelHandler.cpp',
             'platform/mediastream/RTCDataChannelHandler.h',
             'platform/mediastream/RTCDataChannelHandlerClient.h',
             'platform/mediastream/RTCPeerConnectionHandler.cpp',
             'platform/mediastream/RTCPeerConnectionHandler.h',
             'platform/mediastream/RTCPeerConnectionHandlerClient.h',
-            'platform/mediastream/RTCSessionDescriptionRequest.h',
             'platform/mediastream/RTCStatsRequest.h',
-            'platform/mediastream/RTCVoidRequest.h',
             'platform/mock/GeolocationClientMock.cpp',
             'platform/mock/PlatformSpeechSynthesizerMock.cpp',
             'platform/mock/PlatformSpeechSynthesizerMock.h',
@@ -3262,6 +3273,8 @@
             'svg/SVGGlyphRefElement.cpp',
             'svg/SVGGlyphRefElement.h',
             'svg/SVGGlyphMap.h',
+            'svg/SVGGeometryElement.cpp',
+            'svg/SVGGeometryElement.h',
             'svg/SVGGradientElement.cpp',
             'svg/SVGGradientElement.h',
             'svg/SVGGraphicsElement.cpp',
@@ -3281,7 +3294,6 @@
             'svg/SVGLineElement.h',
             'svg/SVGLinearGradientElement.cpp',
             'svg/SVGLinearGradientElement.h',
-            'svg/SVGLocatable.cpp',
             'svg/SVGMPathElement.cpp',
             'svg/SVGMPathElement.h',
             'svg/SVGMarkerElement.cpp',
@@ -3407,8 +3419,6 @@
             'svg/SVGTransformDistance.cpp',
             'svg/SVGTransformDistance.h',
             'svg/SVGTransformList.cpp',
-            'svg/SVGTransformable.cpp',
-            'svg/SVGTransformable.h',
             'svg/SVGURIReference.cpp',
             'svg/SVGURIReference.h',
             'svg/SVGUnitTypes.h',
@@ -3466,6 +3476,8 @@
         'webcore_test_support_files': [
             'testing/v8/WebCoreTestSupport.cpp',
             'testing/v8/WebCoreTestSupport.h',
+            'testing/DummyPageHolder.cpp',
+            'testing/DummyPageHolder.h',
             'testing/GCObservation.cpp',
             'testing/GCObservation.h',
             'testing/InspectorFrontendClientLocal.cpp',
@@ -3490,15 +3502,11 @@
             'platform/chromium/support/WebArrayBuffer.cpp',
             'platform/chromium/support/WebCrypto.cpp',
             'platform/chromium/support/WebCursorInfo.cpp',
-            'platform/chromium/support/WebMediaConstraints.cpp',
             'platform/chromium/support/WebMediaStream.cpp',
-            'platform/chromium/support/WebMediaStreamSource.cpp',
             'platform/chromium/support/WebMediaStreamTrack.cpp',
             'platform/chromium/support/WebRTCSessionDescription.cpp',
             'platform/chromium/support/WebRTCSessionDescriptionRequest.cpp',
             'platform/chromium/support/WebRTCStatsRequest.cpp',
-            'platform/chromium/support/WebRTCStatsResponse.cpp',
-            'platform/chromium/support/WebRTCVoidRequest.cpp',
             'platform/chromium/support/WebScrollbarImpl.cpp',
             'platform/chromium/support/WebScrollbarImpl.h',
             'platform/chromium/support/WebScrollbarThemeClientImpl.cpp',
@@ -3521,6 +3529,9 @@
             'animation/AnimatableValueTestHelper.h',
             'animation/AnimatableValueTestHelperTest.cpp',
             'animation/AnimationClockTest.cpp',
+            'animation/CompositorAnimationsTest.cpp',
+            'animation/CompositorAnimationsTestHelper.h',
+            'animation/CompositorAnimationsTimingFunctionReverserTest.cpp',
             'animation/DocumentTimelineTest.cpp',
             'animation/KeyframeAnimationEffectTest.cpp',
             'animation/PlayerTest.cpp',
@@ -3529,31 +3540,40 @@
             'css/CSSParserValuesTest.cpp',
             'css/CSSCalculationValueTest.cpp',
             'css/CSSValueTestHelper.h',
+            'editing/TextIteratorTest.cpp',
+            'dom/MainThreadTaskRunnerTest.cpp',
             'fetch/ImageResourceTest.cpp',
             'fetch/MemoryCacheTest.cpp',
+            'fetch/RawResourceTest.cpp',
             'fetch/ResourceFetcherTest.cpp',
             'html/HTMLDimensionTest.cpp',
             'html/LinkRelAttributeTest.cpp',
             'html/TimeRangesTest.cpp',
+            'html/track/vtt/BufferedLineReaderTest.cpp',
             'frame/ImageBitmapTest.cpp',
             'platform/animation/AnimationTranslationUtilTest.cpp',
+            'platform/animation/TimingFunctionTestHelper.h',
+            'platform/animation/TimingFunctionTestHelper.cpp',
+            'platform/animation/TimingFunctionTestHelperTest.cpp',
             'platform/graphics/BitmapImageTest.cpp',
+            'platform/graphics/Canvas2DLayerBridgeTest.cpp',
+            'platform/graphics/Canvas2DLayerManagerTest.cpp',
+            'platform/graphics/DeferredImageDecoderTest.cpp',
             'platform/graphics/FontTest.cpp',
-            'platform/graphics/GraphicsContextTest.cpp',
-            'platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp',
-            'platform/graphics/chromium/Canvas2DLayerManagerTest.cpp',
-            'platform/graphics/chromium/DeferredImageDecoderTest.cpp',
-            'platform/graphics/chromium/ImageDecodingStoreTest.cpp',
-            'platform/graphics/chromium/ImageFrameGeneratorTest.cpp',
-            'platform/graphics/chromium/test/MockDiscardablePixelRef.h',
-            'platform/graphics/chromium/test/MockImageDecoder.h',
             'platform/graphics/gpu/DrawingBufferTest.cpp',
+            'platform/graphics/GraphicsContextTest.cpp',
+            'platform/graphics/ImageDecodingStoreTest.cpp',
+            'platform/graphics/ImageFrameGeneratorTest.cpp',
+            'platform/graphics/test/MockDiscardablePixelRef.h',
+            'platform/graphics/test/MockImageDecoder.h',
             'platform/image-decoders/ImageDecoderTest.cpp',
             'platform/image-decoders/gif/GIFImageDecoderTest.cpp',
             'platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp',
             'platform/image-decoders/webp/WEBPImageDecoderTest.cpp',
             'platform/testing/FakeWebGraphicsContext3D.h',
             'rendering/RenderOverflowTest.cpp',
+            'testing/UnitTestHelpers.h',
+            'testing/UnitTestHelpers.cpp',
         ],
     }
 }
diff --git a/Source/core/core_derived_sources.gyp b/Source/core/core_derived_sources.gyp
index 01b695c..1ff6624 100644
--- a/Source/core/core_derived_sources.gyp
+++ b/Source/core/core_derived_sources.gyp
@@ -95,6 +95,7 @@
       'hard_dependency': 1,
       'dependencies': [
         'generate_test_support_idls',
+        '../config.gyp:config',
       ],
       'sources': [
         # bison rule
@@ -319,8 +320,7 @@
         {
           'action_name': 'EventFactory',
           'inputs': [
-            '<@(scripts_for_in_files)',
-            '../build/scripts/make_event_factory.py',
+            '<@(make_event_factory_files)',
             '<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.in',
             'events/EventAliases.in',
           ],
@@ -359,8 +359,7 @@
         {
           'action_name': 'EventTargetFactory',
           'inputs': [
-            '<@(scripts_for_in_files)',
-            '../build/scripts/make_event_factory.py',
+            '<@(make_event_factory_files)',
             'events/EventTargetFactory.in',
           ],
           'outputs': [
@@ -436,6 +435,7 @@
               'css/mediaControlsAndroid.css',
               'css/fullscreen.css',
               'css/xhtmlmp.css',
+              'css/viewportAndroid.css',
             ],
           },
           'inputs': [
@@ -495,6 +495,24 @@
           ],
         },
         {
+          'action_name': 'InputTypeNames',
+          'inputs': [
+            '<@(make_names_files)',
+            'html/forms/InputTypeNames.in',
+          ],
+          'outputs': [
+            '<(SHARED_INTERMEDIATE_DIR)/blink/InputTypeNames.cpp',
+            '<(SHARED_INTERMEDIATE_DIR)/blink/InputTypeNames.h',
+          ],
+          'action': [
+            'python',
+            '../build/scripts/make_names.py',
+            'html/forms/InputTypeNames.in',
+            '--output_dir',
+            '<(SHARED_INTERMEDIATE_DIR)/blink',
+          ],
+        },
+        {
           'action_name': 'XLinkNames',
           'inputs': [
             '<@(make_qualified_names_files)',
@@ -553,6 +571,23 @@
           'inputs': [
             '<@(scripts_for_in_files)',
             '../build/scripts/make_token_matcher.py',
+            '../core/css/CSSTokenizer-in.cpp',
+          ],
+          'outputs': [
+            '<(SHARED_INTERMEDIATE_DIR)/blink/CSSTokenizer.cpp',
+          ],
+          'action': [
+            'python',
+            '../build/scripts/make_token_matcher.py',
+            '../core/css/CSSTokenizer-in.cpp',
+            '<(SHARED_INTERMEDIATE_DIR)/blink/CSSTokenizer.cpp',
+          ],
+        },
+        {
+          'action_name': 'MakeParser',
+          'inputs': [
+            '<@(scripts_for_in_files)',
+            '../build/scripts/make_token_matcher.py',
             '../core/css/CSSParser-in.cpp',
           ],
           'outputs': [
@@ -582,6 +617,27 @@
             '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLMetaElement.cpp',
           ],
         },
+        {
+          'action_name': 'HTMLElementLookupTrie',
+          'inputs': [
+            '<@(scripts_for_in_files)',
+            '../build/scripts/make_element_lookup_trie.py',
+            '../build/scripts/templates/ElementLookupTrie.cpp.tmpl',
+            '../build/scripts/templates/ElementLookupTrie.h.tmpl',
+            'html/HTMLTagNames.in',
+          ],
+          'outputs': [
+            '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.cpp',
+            '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.h',
+          ],
+          'action': [
+            'python',
+            '../build/scripts/make_element_lookup_trie.py',
+            'html/HTMLTagNames.in',
+            '--output_dir',
+            '<(SHARED_INTERMEDIATE_DIR)/blink',
+          ],
+        },
       ],
       'rules': [
         {
diff --git a/Source/core/css/BasicShapeFunctions.cpp b/Source/core/css/BasicShapeFunctions.cpp
index cc9f57b..3f827df 100644
--- a/Source/core/css/BasicShapeFunctions.cpp
+++ b/Source/core/css/BasicShapeFunctions.cpp
@@ -39,7 +39,7 @@
 
 namespace WebCore {
 
-PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle* style, const BasicShape* basicShape)
+PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle& style, const BasicShape* basicShape)
 {
     CSSValuePool& pool = cssValuePool();
 
@@ -116,7 +116,7 @@
 
 static Length convertToLength(const StyleResolverState& state, CSSPrimitiveValue* value)
 {
-    return value->convertToLength<FixedIntegerConversion | FixedFloatConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    return value->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
 }
 
 PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState& state, const CSSBasicShape* basicShapeValue)
diff --git a/Source/core/css/BasicShapeFunctions.h b/Source/core/css/BasicShapeFunctions.h
index c0cd68a..7d07e31 100644
--- a/Source/core/css/BasicShapeFunctions.h
+++ b/Source/core/css/BasicShapeFunctions.h
@@ -40,7 +40,7 @@
 class StyleResolverState;
 class RenderStyle;
 
-PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle*, const BasicShape*);
+PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle&, const BasicShape*);
 PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState&, const CSSBasicShape*);
 
 }
diff --git a/Source/core/css/CSSCalculationValue.cpp b/Source/core/css/CSSCalculationValue.cpp
index c5ed81a..6c5ebc5 100644
--- a/Source/core/css/CSSCalculationValue.cpp
+++ b/Source/core/css/CSSCalculationValue.cpp
@@ -235,7 +235,7 @@
         case CalcPercentLength: {
             CSSPrimitiveValue* primitiveValue = m_value.get();
             return adoptPtr(new CalcExpressionLength(primitiveValue
-                ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion>(style, rootStyle, zoom)
+                ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(style, rootStyle, zoom)
                 : Length(Undefined)));
         }
         // Only types that could be part of a Length expression can be converted
@@ -763,7 +763,6 @@
     case FillAvailable:
     case FitContent:
     case ExtendToZoom:
-    case Relative:
     case Undefined:
         ASSERT_NOT_REACHED();
         return 0;
diff --git a/Source/core/css/CSSCharsetRule.idl b/Source/core/css/CSSCharsetRule.idl
index a6eab93..dcd89ac 100644
--- a/Source/core/css/CSSCharsetRule.idl
+++ b/Source/core/css/CSSCharsetRule.idl
@@ -19,6 +19,6 @@
  */
 
 interface CSSCharsetRule : CSSRule {
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString encoding;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter] attribute DOMString encoding;
 };
 
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index 708de22..c95f4b9 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -29,6 +29,7 @@
 #include "RuntimeEnabledFeatures.h"
 #include "StylePropertyShorthand.h"
 #include "bindings/v8/ExceptionState.h"
+#include "core/animation/DocumentAnimations.h"
 #include "core/css/BasicShapeFunctions.h"
 #include "core/css/CSSArrayFunctionValue.h"
 #include "core/css/CSSAspectRatioValue.h"
@@ -37,6 +38,7 @@
 #include "core/css/CSSFontFeatureValue.h"
 #include "core/css/CSSFontValue.h"
 #include "core/css/CSSFunctionValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
 #include "core/css/CSSGridTemplateValue.h"
 #include "core/css/CSSLineBoxContainValue.h"
 #include "core/css/CSSMixFunctionValue.h"
@@ -72,11 +74,11 @@
 #include "wtf/text/StringBuilder.h"
 
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 #include "core/rendering/style/StyleCustomFilterProgram.h"
 #include "platform/graphics/filters/custom/CustomFilterArrayParameter.h"
 #include "platform/graphics/filters/custom/CustomFilterNumberParameter.h"
 #include "platform/graphics/filters/custom/CustomFilterParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 
 namespace WebCore {
 
@@ -461,7 +463,7 @@
     return CSSBorderImageSliceValue::create(cssValuePool().createValue(quad.release()), image.fill());
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const LengthBox& box, const RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const BorderImageLengthBox& box, const RenderStyle& style)
 {
     // Create the slices.
     RefPtr<CSSPrimitiveValue> top;
@@ -469,37 +471,37 @@
     RefPtr<CSSPrimitiveValue> bottom;
     RefPtr<CSSPrimitiveValue> left;
 
-    if (box.top().isRelative())
-        top = cssValuePool().createValue(box.top().value(), CSSPrimitiveValue::CSS_NUMBER);
+    if (box.top().isNumber())
+        top = cssValuePool().createValue(box.top().number(), CSSPrimitiveValue::CSS_NUMBER);
     else
-        top = cssValuePool().createValue(box.top(), style);
+        top = cssValuePool().createValue(box.top().length(), style);
 
     if (box.right() == box.top() && box.bottom() == box.top() && box.left() == box.top()) {
         right = top;
         bottom = top;
         left = top;
     } else {
-        if (box.right().isRelative())
-            right = cssValuePool().createValue(box.right().value(), CSSPrimitiveValue::CSS_NUMBER);
+        if (box.right().isNumber())
+            right = cssValuePool().createValue(box.right().number(), CSSPrimitiveValue::CSS_NUMBER);
         else
-            right = cssValuePool().createValue(box.right(), style);
+            right = cssValuePool().createValue(box.right().length(), style);
 
         if (box.bottom() == box.top() && box.right() == box.left()) {
             bottom = top;
             left = right;
         } else {
-            if (box.bottom().isRelative())
-                bottom = cssValuePool().createValue(box.bottom().value(), CSSPrimitiveValue::CSS_NUMBER);
+            if (box.bottom().isNumber())
+                bottom = cssValuePool().createValue(box.bottom().number(), CSSPrimitiveValue::CSS_NUMBER);
             else
-                bottom = cssValuePool().createValue(box.bottom(), style);
+                bottom = cssValuePool().createValue(box.bottom().length(), style);
 
             if (box.left() == box.right())
                 left = right;
             else {
-                if (box.left().isRelative())
-                    left = cssValuePool().createValue(box.left().value(), CSSPrimitiveValue::CSS_NUMBER);
+                if (box.left().isNumber())
+                    left = cssValuePool().createValue(box.left().number(), CSSPrimitiveValue::CSS_NUMBER);
                 else
-                    left = cssValuePool().createValue(box.left(), style);
+                    left = cssValuePool().createValue(box.left().length(), style);
             }
         }
     }
@@ -526,7 +528,7 @@
     return cssValuePool().createValue(Pair::create(horizontalRepeat.release(), verticalRepeat.release(), Pair::DropIdenticalValues));
 }
 
-static PassRefPtr<CSSValue> valueForNinePieceImage(const NinePieceImage& image, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForNinePieceImage(const NinePieceImage& image, const RenderStyle& style)
 {
     if (!image.hasImage())
         return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -551,24 +553,24 @@
     return createBorderImageValue(imageValue.release(), imageSlices.release(), borderSlices.release(), outset.release(), repeat.release());
 }
 
-inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const RenderStyle* style)
+inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const RenderStyle& style)
 {
     return cssValuePool().createValue(adjustFloatForAbsoluteZoom(value, style), CSSPrimitiveValue::CSS_PX);
 }
 
-inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedNumberValue(double value, const RenderStyle* style)
+inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedNumberValue(double value, const RenderStyle& style)
 {
-    return cssValuePool().createValue(value / style->effectiveZoom(), CSSPrimitiveValue::CSS_NUMBER);
+    return cssValuePool().createValue(value / style.effectiveZoom(), CSSPrimitiveValue::CSS_NUMBER);
 }
 
-static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValueForLength(const Length& length, const RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValueForLength(const Length& length, const RenderStyle& style)
 {
     if (length.isFixed())
         return zoomAdjustedPixelValue(length.value(), style);
     return cssValuePool().createValue(length, style);
 }
 
-static PassRefPtr<CSSValue> valueForReflection(const StyleReflection* reflection, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForReflection(const StyleReflection* reflection, const RenderStyle& style)
 {
     if (!reflection)
         return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -598,7 +600,7 @@
     return CSSReflectValue::create(direction.release(), offset.release(), valueForNinePieceImage(reflection->mask(), style));
 }
 
-static PassRefPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer* layer, const RenderStyle* style)
+static PassRefPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer* layer, const RenderStyle& style)
 {
     ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
     RefPtr<CSSValueList> positionList = CSSValueList::createSpaceSeparated();
@@ -609,24 +611,21 @@
     return positionList.release();
 }
 
-static PassRefPtr<CSSValue> valueForPositionOffset(RenderStyle* style, CSSPropertyID propertyID, const RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForPositionOffset(RenderStyle& style, CSSPropertyID propertyID, const RenderObject* renderer, RenderView* renderView)
 {
-    if (!style)
-        return 0;
-
     Length l;
     switch (propertyID) {
         case CSSPropertyLeft:
-            l = style->left();
+            l = style.left();
             break;
         case CSSPropertyRight:
-            l = style->right();
+            l = style.right();
             break;
         case CSSPropertyTop:
-            l = style->top();
+            l = style.top();
             break;
         case CSSPropertyBottom:
-            l = style->bottom();
+            l = style.bottom();
             break;
         default:
             return 0;
@@ -650,15 +649,15 @@
     return zoomAdjustedPixelValueForLength(l, style);
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(const RenderStyle* style, const Color& color) const
+PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(const RenderStyle& style, const Color& color) const
 {
     // This function does NOT look at visited information, so that computed style doesn't expose that.
     if (!color.isValid())
-        return cssValuePool().createColorValue(style->color().rgb());
+        return cssValuePool().createColorValue(style.color().rgb());
     return cssValuePool().createColorValue(color.rgb());
 }
 
-static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle* style)
+static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle& style)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     if (radius.width().type() == Percent)
@@ -672,7 +671,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle& style)
 {
     RefPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style);
     if (list->item(0)->equals(*list->item(1)))
@@ -680,22 +679,22 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle* style)
+static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle& style)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
 
-    bool showHorizontalBottomLeft = style->borderTopRightRadius().width() != style->borderBottomLeftRadius().width();
-    bool showHorizontalBottomRight = showHorizontalBottomLeft || (style->borderBottomRightRadius().width() != style->borderTopLeftRadius().width());
-    bool showHorizontalTopRight = showHorizontalBottomRight || (style->borderTopRightRadius().width() != style->borderTopLeftRadius().width());
+    bool showHorizontalBottomLeft = style.borderTopRightRadius().width() != style.borderBottomLeftRadius().width();
+    bool showHorizontalBottomRight = showHorizontalBottomLeft || (style.borderBottomRightRadius().width() != style.borderTopLeftRadius().width());
+    bool showHorizontalTopRight = showHorizontalBottomRight || (style.borderTopRightRadius().width() != style.borderTopLeftRadius().width());
 
-    bool showVerticalBottomLeft = style->borderTopRightRadius().height() != style->borderBottomLeftRadius().height();
-    bool showVerticalBottomRight = showVerticalBottomLeft || (style->borderBottomRightRadius().height() != style->borderTopLeftRadius().height());
-    bool showVerticalTopRight = showVerticalBottomRight || (style->borderTopRightRadius().height() != style->borderTopLeftRadius().height());
+    bool showVerticalBottomLeft = style.borderTopRightRadius().height() != style.borderBottomLeftRadius().height();
+    bool showVerticalBottomRight = showVerticalBottomLeft || (style.borderBottomRightRadius().height() != style.borderTopLeftRadius().height());
+    bool showVerticalTopRight = showVerticalBottomRight || (style.borderTopRightRadius().height() != style.borderTopLeftRadius().height());
 
-    RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style->borderTopLeftRadius(), style);
-    RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style->borderTopRightRadius(), style);
-    RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style->borderBottomRightRadius(), style);
-    RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style->borderBottomLeftRadius(), style);
+    RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style.borderTopLeftRadius(), style);
+    RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style.borderTopRightRadius(), style);
+    RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style.borderBottomRightRadius(), style);
+    RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style.borderBottomLeftRadius(), style);
 
     RefPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
     horizontalRadii->append(topLeftRadius->item(0));
@@ -732,7 +731,7 @@
     return box->style()->boxSizing() == BORDER_BOX ? box->borderBoxRect() : box->computedCSSContentBoxRect();
 }
 
-static PassRefPtr<CSSTransformValue> valueForMatrixTransform(const TransformationMatrix& transform, const RenderStyle* style)
+static PassRefPtr<CSSTransformValue> valueForMatrixTransform(const TransformationMatrix& transform, const RenderStyle& style)
 {
     RefPtr<CSSTransformValue> transformValue;
     if (transform.isAffine()) {
@@ -771,9 +770,9 @@
     return transformValue.release();
 }
 
-static PassRefPtr<CSSValue> computedTransform(RenderObject* renderer, const RenderStyle* style)
+static PassRefPtr<CSSValue> computedTransform(RenderObject* renderer, const RenderStyle& style)
 {
-    if (!renderer || !renderer->hasTransform() || !style->hasTransform())
+    if (!renderer || !renderer->hasTransform() || !style.hasTransform())
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
     IntRect box;
@@ -781,7 +780,7 @@
         box = pixelSnappedIntRect(toRenderBox(renderer)->borderBoxRect());
 
     TransformationMatrix transform;
-    style->applyTransform(transform, box.size(), RenderStyle::ExcludeTransformOrigin);
+    style.applyTransform(transform, box.size(), RenderStyle::ExcludeTransformOrigin);
 
     // FIXME: Need to print out individual functions (https://bugs.webkit.org/show_bug.cgi?id=23924)
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
@@ -806,7 +805,7 @@
     return numberParameterValue.release();
 }
 
-static PassRefPtr<CSSValue> valueForCustomFilterTransformParameter(const RenderObject* renderer, const RenderStyle* style, const CustomFilterTransformParameter* transformParameter)
+static PassRefPtr<CSSValue> valueForCustomFilterTransformParameter(const RenderObject* renderer, const RenderStyle& style, const CustomFilterTransformParameter* transformParameter)
 {
     IntSize size;
     if (renderer && renderer->isBox())
@@ -818,7 +817,7 @@
     return valueForMatrixTransform(transform, style);
 }
 
-static PassRefPtr<CSSValue> valueForCustomFilterParameter(const RenderObject* renderer, const RenderStyle* style, const CustomFilterParameter* parameter)
+static PassRefPtr<CSSValue> valueForCustomFilterParameter(const RenderObject* renderer, const RenderStyle& style, const CustomFilterParameter* parameter)
 {
     // FIXME: Add here computed style for the other types: boolean, transform, matrix, texture.
     ASSERT(parameter);
@@ -835,81 +834,61 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObject* renderer, const RenderStyle* style) const
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObject* renderer, const RenderStyle& style) const
 {
-    if (style->filter().operations().isEmpty())
+    if (style.filter().operations().isEmpty())
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
 
     RefPtr<CSSFilterValue> filterValue;
 
-    Vector<RefPtr<FilterOperation> >::const_iterator end = style->filter().operations().end();
-    for (Vector<RefPtr<FilterOperation> >::const_iterator it = style->filter().operations().begin(); it != end; ++it) {
+    Vector<RefPtr<FilterOperation> >::const_iterator end = style.filter().operations().end();
+    for (Vector<RefPtr<FilterOperation> >::const_iterator it = style.filter().operations().begin(); it != end; ++it) {
         FilterOperation* filterOperation = (*it).get();
-        switch (filterOperation->getOperationType()) {
-        case FilterOperation::REFERENCE: {
-            ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
+        switch (filterOperation->type()) {
+        case FilterOperation::REFERENCE:
             filterValue = CSSFilterValue::create(CSSFilterValue::ReferenceFilterOperation);
-            filterValue->append(cssValuePool().createValue(referenceOperation->url(), CSSPrimitiveValue::CSS_STRING));
+            filterValue->append(cssValuePool().createValue(toReferenceFilterOperation(filterOperation)->url(), CSSPrimitiveValue::CSS_STRING));
             break;
-        }
-        case FilterOperation::GRAYSCALE: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+        case FilterOperation::GRAYSCALE:
             filterValue = CSSFilterValue::create(CSSFilterValue::GrayscaleFilterOperation);
-            filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+            filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
             break;
-        }
-        case FilterOperation::SEPIA: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+        case FilterOperation::SEPIA:
             filterValue = CSSFilterValue::create(CSSFilterValue::SepiaFilterOperation);
-            filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+            filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
             break;
-        }
-        case FilterOperation::SATURATE: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+        case FilterOperation::SATURATE:
             filterValue = CSSFilterValue::create(CSSFilterValue::SaturateFilterOperation);
-            filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+            filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
             break;
-        }
-        case FilterOperation::HUE_ROTATE: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+        case FilterOperation::HUE_ROTATE:
             filterValue = CSSFilterValue::create(CSSFilterValue::HueRotateFilterOperation);
-            filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_DEG));
+            filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_DEG));
             break;
-        }
-        case FilterOperation::INVERT: {
-            BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+        case FilterOperation::INVERT:
             filterValue = CSSFilterValue::create(CSSFilterValue::InvertFilterOperation);
-            filterValue->append(cssValuePool().createValue(componentTransferOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+            filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
             break;
-        }
-        case FilterOperation::OPACITY: {
-            BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+        case FilterOperation::OPACITY:
             filterValue = CSSFilterValue::create(CSSFilterValue::OpacityFilterOperation);
-            filterValue->append(cssValuePool().createValue(componentTransferOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+            filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
             break;
-        }
-        case FilterOperation::BRIGHTNESS: {
-            BasicComponentTransferFilterOperation* brightnessOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+        case FilterOperation::BRIGHTNESS:
             filterValue = CSSFilterValue::create(CSSFilterValue::BrightnessFilterOperation);
-            filterValue->append(cssValuePool().createValue(brightnessOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+            filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
             break;
-        }
-        case FilterOperation::CONTRAST: {
-            BasicComponentTransferFilterOperation* contrastOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+        case FilterOperation::CONTRAST:
             filterValue = CSSFilterValue::create(CSSFilterValue::ContrastFilterOperation);
-            filterValue->append(cssValuePool().createValue(contrastOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+            filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
             break;
-        }
-        case FilterOperation::BLUR: {
-            BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
+        case FilterOperation::BLUR:
             filterValue = CSSFilterValue::create(CSSFilterValue::BlurFilterOperation);
-            filterValue->append(zoomAdjustedPixelValue(blurOperation->stdDeviation().value(), style));
+            filterValue->append(zoomAdjustedPixelValue(toBlurFilterOperation(filterOperation)->stdDeviation().value(), style));
             break;
-        }
         case FilterOperation::DROP_SHADOW: {
-            DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
+            DropShadowFilterOperation* dropShadowOperation = toDropShadowFilterOperation(filterOperation);
             filterValue = CSSFilterValue::create(CSSFilterValue::DropShadowFilterOperation);
             // We want our computed style to look like that of a text shadow (has neither spread nor inset style).
             ShadowData shadow(dropShadowOperation->location(), dropShadowOperation->stdDeviation(), 0, Normal, dropShadowOperation->color());
@@ -921,7 +900,7 @@
             ASSERT_NOT_REACHED();
             break;
         case FilterOperation::CUSTOM: {
-            CustomFilterOperation* customOperation = static_cast<CustomFilterOperation*>(filterOperation);
+            CustomFilterOperation* customOperation = toCustomFilterOperation(filterOperation);
             filterValue = CSSFilterValue::create(CSSFilterValue::CustomFilterOperation);
 
             // The output should be verbose, even if the values are the default ones.
@@ -988,7 +967,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> valueForGridTrackBreadth(const GridLength& trackBreadth, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> specifiedValueForGridTrackBreadth(const GridLength& trackBreadth, const RenderStyle& style, RenderView* renderView)
 {
     if (!trackBreadth.isLength())
         return cssValuePool().createValue(trackBreadth.flex(), CSSPrimitiveValue::CSS_FR);
@@ -1001,15 +980,15 @@
     return zoomAdjustedPixelValueForLength(trackBreadthLength, style);
 }
 
-static PassRefPtr<CSSValue> specifiedValueForGridTrackSize(const GridTrackSize& trackSize, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> specifiedValueForGridTrackSize(const GridTrackSize& trackSize, const RenderStyle& style, RenderView* renderView)
 {
     switch (trackSize.type()) {
     case LengthTrackSizing:
-        return valueForGridTrackBreadth(trackSize.length(), style, renderView);
+        return specifiedValueForGridTrackBreadth(trackSize.length(), style, renderView);
     case MinMaxTrackSizing:
         RefPtr<CSSValueList> minMaxTrackBreadths = CSSValueList::createCommaSeparated();
-        minMaxTrackBreadths->append(valueForGridTrackBreadth(trackSize.minTrackBreadth(), style, renderView));
-        minMaxTrackBreadths->append(valueForGridTrackBreadth(trackSize.maxTrackBreadth(), style, renderView));
+        minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.minTrackBreadth(), style, renderView));
+        minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.maxTrackBreadth(), style, renderView));
         return CSSFunctionValue::create("minmax(", minMaxTrackBreadths);
     }
     ASSERT_NOT_REACHED();
@@ -1019,14 +998,19 @@
 static void addValuesForNamedGridLinesAtIndex(const OrderedNamedGridLines& orderedNamedGridLines, size_t i, CSSValueList& list)
 {
     const Vector<String>& namedGridLines = orderedNamedGridLines.get(i);
+    if (namedGridLines.isEmpty())
+        return;
+
+    RefPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
     for (size_t j = 0; j < namedGridLines.size(); ++j)
-        list.append(cssValuePool().createValue(namedGridLines[j], CSSPrimitiveValue::CSS_STRING));
+        lineNames->append(cssValuePool().createValue(namedGridLines[j], CSSPrimitiveValue::CSS_STRING));
+    list.append(lineNames.release());
 }
 
-static PassRefPtr<CSSValue> valueForGridTrackList(GridTrackSizingDirection direction, RenderObject* renderer, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForGridTrackList(GridTrackSizingDirection direction, RenderObject* renderer, const RenderStyle& style, RenderView* renderView)
 {
-    const Vector<GridTrackSize>& trackSizes = direction == ForColumns ? style->gridDefinitionColumns() : style->gridDefinitionRows();
-    const OrderedNamedGridLines& orderedNamedGridLines = direction == ForColumns ? style->orderedNamedGridColumnLines() : style->orderedNamedGridRowLines();
+    const Vector<GridTrackSize>& trackSizes = direction == ForColumns ? style.gridDefinitionColumns() : style.gridDefinitionRows();
+    const OrderedNamedGridLines& orderedNamedGridLines = direction == ForColumns ? style.orderedNamedGridColumnLines() : style.orderedNamedGridRowLines();
 
     // Handle the 'none' case here.
     if (!trackSizes.size()) {
@@ -1128,7 +1112,7 @@
     switch (timingFunction->type()) {
     case TimingFunction::CubicBezierFunction:
         {
-            const CubicBezierTimingFunction* bezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(timingFunction);
+            const CubicBezierTimingFunction* bezierTimingFunction = toCubicBezierTimingFunction(timingFunction);
             if (bezierTimingFunction->subType() != CubicBezierTimingFunction::Custom) {
                 CSSValueID valueId = CSSValueInvalid;
                 switch (bezierTimingFunction->subType()) {
@@ -1155,7 +1139,7 @@
 
     case TimingFunction::StepsFunction:
         {
-            const StepsTimingFunction* stepsTimingFunction = static_cast<const StepsTimingFunction*>(timingFunction);
+            const StepsTimingFunction* stepsTimingFunction = toStepsTimingFunction(timingFunction);
             if (stepsTimingFunction->subType() == StepsTimingFunction::Custom)
                 return CSSStepsTimingFunctionValue::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart());
             CSSValueID valueId;
@@ -1274,9 +1258,9 @@
     return result.toString();
 }
 
-void CSSComputedStyleDeclaration::setCSSText(const String&, ExceptionState& es)
+void CSSComputedStyleDeclaration::setCSSText(const String&, ExceptionState& exceptionState)
 {
-    es.throwDOMException(NoModificationAllowedError, "Failed to set the 'cssText' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+    exceptionState.throwDOMException(NoModificationAllowedError, "Failed to set the 'cssText' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
 }
 
 static CSSValueID cssIdentifierForFontSizeKeyword(int keywordSize)
@@ -1301,7 +1285,7 @@
         return cssValuePool().createIdentifierValue(cssIdentifierForFontSizeKeyword(keywordSize));
 
 
-    return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), style.get());
+    return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), *style);
 }
 
 bool CSSComputedStyleDeclaration::useFixedFontDefaultSize() const
@@ -1316,7 +1300,7 @@
     return style->fontDescription().useFixedDefaultSize();
 }
 
-PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowData(const ShadowData& shadow, const RenderStyle* style, bool useSpread) const
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowData(const ShadowData& shadow, const RenderStyle& style, bool useSpread) const
 {
     RefPtr<CSSPrimitiveValue> x = zoomAdjustedPixelValue(shadow.x(), style);
     RefPtr<CSSPrimitiveValue> y = zoomAdjustedPixelValue(shadow.y(), style);
@@ -1327,7 +1311,7 @@
     return CSSShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), shadowStyle.release(), color.release());
 }
 
-PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowList(const ShadowList* shadowList, const RenderStyle* style, bool useSpread) const
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowList(const ShadowList* shadowList, const RenderStyle& style, bool useSpread) const
 {
     if (!shadowList)
         return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -1434,7 +1418,7 @@
     return 0;
 }
 
-static PassRefPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const RenderStyle& style)
 {
     if (fillSize.type == Contain)
         return cssValuePool().createIdentifierValue(CSSValueContain);
@@ -1451,10 +1435,10 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> valueForContentData(const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForContentData(const RenderStyle& style)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    for (const ContentData* contentData = style->contentData(); contentData; contentData = contentData->next()) {
+    for (const ContentData* contentData = style.contentData(); contentData; contentData = contentData->next()) {
         if (contentData->isCounter()) {
             const CounterContent* counter = static_cast<const CounterContentData*>(contentData)->counter();
             ASSERT(counter);
@@ -1466,14 +1450,14 @@
         } else if (contentData->isText())
             list->append(cssValuePool().createValue(static_cast<const TextContentData*>(contentData)->text(), CSSPrimitiveValue::CSS_STRING));
     }
-    if (style->hasFlowFrom())
-        list->append(cssValuePool().createValue(style->regionThread(), CSSPrimitiveValue::CSS_STRING));
+    if (style.hasFlowFrom())
+        list->append(cssValuePool().createValue(style.regionThread(), CSSPrimitiveValue::CSS_STRING));
     return list.release();
 }
 
-static PassRefPtr<CSSValue> valueForCounterDirectives(const RenderStyle* style, CSSPropertyID propertyID)
+static PassRefPtr<CSSValue> valueForCounterDirectives(const RenderStyle& style, CSSPropertyID propertyID)
 {
-    const CounterDirectiveMap* map = style->counterDirectives();
+    const CounterDirectiveMap* map = style.counterDirectives();
     if (!map)
         return 0;
 
@@ -1495,46 +1479,46 @@
     LOG_ERROR("WebKit does not yet implement getComputedStyle for '%s'.", getPropertyName(propertyID));
 }
 
-static PassRefPtr<CSSValueList> valueForFontFamily(RenderStyle* style)
+static PassRefPtr<CSSValueList> valueForFontFamily(RenderStyle& style)
 {
-    const FontFamily& firstFamily = style->fontDescription().family();
+    const FontFamily& firstFamily = style.fontDescription().family();
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     for (const FontFamily* family = &firstFamily; family; family = family->next())
         list->append(valueForFamily(family->family()));
     return list.release();
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForLineHeight(RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSPrimitiveValue> valueForLineHeight(RenderStyle& style, RenderView* renderView)
 {
-    Length length = style->lineHeight();
+    Length length = style.lineHeight();
     if (length.isNegative())
         return cssValuePool().createIdentifierValue(CSSValueNormal);
 
-    return zoomAdjustedPixelValue(floatValueForLength(length, style->fontDescription().specifiedSize(), renderView), style);
+    return zoomAdjustedPixelValue(floatValueForLength(length, style.fontDescription().specifiedSize(), renderView), style);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontSize(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontSize(RenderStyle& style)
 {
-    return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), style);
+    return zoomAdjustedPixelValue(style.fontDescription().computedPixelSize(), style);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontStyle(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontStyle(RenderStyle& style)
 {
-    if (style->fontDescription().italic())
+    if (style.fontDescription().italic())
         return cssValuePool().createIdentifierValue(CSSValueItalic);
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontVariant(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontVariant(RenderStyle& style)
 {
-    if (style->fontDescription().smallCaps())
+    if (style.fontDescription().smallCaps())
         return cssValuePool().createIdentifierValue(CSSValueSmallCaps);
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle& style)
 {
-    switch (style->fontDescription().weight()) {
+    switch (style.fontDescription().weight()) {
     case FontWeight100:
         return cssValuePool().createIdentifierValue(CSSValue100);
     case FontWeight200:
@@ -1643,6 +1627,10 @@
     if (updateLayout) {
         Document& document = styledNode->document();
 
+        // If a compositor animation is running we may need to service animations
+        // in order to generate an up to date value.
+        DocumentAnimations::serviceBeforeGetComputedStyle(*styledNode, propertyID);
+
         document.updateStyleForNodeIfNeeded(styledNode);
 
         // The style recalc could have caused the styled node to be discarded or replaced
@@ -1654,7 +1642,7 @@
 
         bool forceFullLayout = isLayoutDependent(propertyID, style, renderer)
             || styledNode->isInShadowTree()
-            || (document.styleResolverIfExists() && document.styleResolverIfExists()->hasViewportDependentMediaQueries() && document.ownerElement())
+            || (document.ownerElement() && document.styleResolver()->hasViewportDependentMediaQueries())
             || document.seamlessParentIFrame();
 
         if (forceFullLayout) {
@@ -1706,11 +1694,11 @@
         case CSSPropertyWebkitMaskSize: {
             const FillLayer* layers = propertyID == CSSPropertyWebkitMaskSize ? style->maskLayers() : style->backgroundLayers();
             if (!layers->next())
-                return valueForFillSize(layers->size(), style.get());
+                return valueForFillSize(layers->size(), *style);
 
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
-                list->append(valueForFillSize(currLayer->size(), style.get()));
+                list->append(valueForFillSize(currLayer->size(), *style));
 
             return list.release();
         }
@@ -1789,11 +1777,11 @@
         case CSSPropertyWebkitMaskPosition: {
             const FillLayer* layers = propertyID == CSSPropertyWebkitMaskPosition ? style->maskLayers() : style->backgroundLayers();
             if (!layers->next())
-                return createPositionListForLayer(propertyID, layers, style.get());
+                return createPositionListForLayer(propertyID, layers, *style);
 
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
-                list->append(createPositionListForLayer(propertyID, currLayer, style.get()));
+                list->append(createPositionListForLayer(propertyID, currLayer, *style));
             return list.release();
         }
         case CSSPropertyBackgroundPositionX:
@@ -1826,26 +1814,26 @@
             return cssValuePool().createIdentifierValue(CSSValueSeparate);
         case CSSPropertyBorderSpacing: {
             RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-            list->append(zoomAdjustedPixelValue(style->horizontalBorderSpacing(), style.get()));
-            list->append(zoomAdjustedPixelValue(style->verticalBorderSpacing(), style.get()));
+            list->append(zoomAdjustedPixelValue(style->horizontalBorderSpacing(), *style));
+            list->append(zoomAdjustedPixelValue(style->verticalBorderSpacing(), *style));
             return list.release();
         }
         case CSSPropertyWebkitBorderHorizontalSpacing:
-            return zoomAdjustedPixelValue(style->horizontalBorderSpacing(), style.get());
+            return zoomAdjustedPixelValue(style->horizontalBorderSpacing(), *style);
         case CSSPropertyWebkitBorderVerticalSpacing:
-            return zoomAdjustedPixelValue(style->verticalBorderSpacing(), style.get());
+            return zoomAdjustedPixelValue(style->verticalBorderSpacing(), *style);
         case CSSPropertyBorderImageSource:
             if (style->borderImageSource())
                 return style->borderImageSource()->cssValue();
             return cssValuePool().createIdentifierValue(CSSValueNone);
         case CSSPropertyBorderTopColor:
-            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderTopColor).rgb()) : currentColorOrValidColor(style.get(), style->borderTopColor());
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderTopColor).rgb()) : currentColorOrValidColor(*style, style->borderTopColor());
         case CSSPropertyBorderRightColor:
-            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderRightColor).rgb()) : currentColorOrValidColor(style.get(), style->borderRightColor());
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderRightColor).rgb()) : currentColorOrValidColor(*style, style->borderRightColor());
         case CSSPropertyBorderBottomColor:
-            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderBottomColor).rgb()) : currentColorOrValidColor(style.get(), style->borderBottomColor());
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderBottomColor).rgb()) : currentColorOrValidColor(*style, style->borderBottomColor());
         case CSSPropertyBorderLeftColor:
-            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderLeftColor).rgb()) : currentColorOrValidColor(style.get(), style->borderLeftColor());
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderLeftColor).rgb()) : currentColorOrValidColor(*style, style->borderLeftColor());
         case CSSPropertyBorderTopStyle:
             return cssValuePool().createValue(style->borderTopStyle());
         case CSSPropertyBorderRightStyle:
@@ -1855,15 +1843,15 @@
         case CSSPropertyBorderLeftStyle:
             return cssValuePool().createValue(style->borderLeftStyle());
         case CSSPropertyBorderTopWidth:
-            return zoomAdjustedPixelValue(style->borderTopWidth(), style.get());
+            return zoomAdjustedPixelValue(style->borderTopWidth(), *style);
         case CSSPropertyBorderRightWidth:
-            return zoomAdjustedPixelValue(style->borderRightWidth(), style.get());
+            return zoomAdjustedPixelValue(style->borderRightWidth(), *style);
         case CSSPropertyBorderBottomWidth:
-            return zoomAdjustedPixelValue(style->borderBottomWidth(), style.get());
+            return zoomAdjustedPixelValue(style->borderBottomWidth(), *style);
         case CSSPropertyBorderLeftWidth:
-            return zoomAdjustedPixelValue(style->borderLeftWidth(), style.get());
+            return zoomAdjustedPixelValue(style->borderLeftWidth(), *style);
         case CSSPropertyBottom:
-            return valueForPositionOffset(style.get(), CSSPropertyBottom, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyBottom, renderer, m_node->document().renderView());
         case CSSPropertyWebkitBoxAlign:
             return cssValuePool().createValue(style->boxAlign());
         case CSSPropertyWebkitBoxDecorationBreak:
@@ -1885,10 +1873,10 @@
         case CSSPropertyWebkitBoxPack:
             return cssValuePool().createValue(style->boxPack());
         case CSSPropertyWebkitBoxReflect:
-            return valueForReflection(style->boxReflect(), style.get());
+            return valueForReflection(style->boxReflect(), *style);
         case CSSPropertyBoxShadow:
         case CSSPropertyWebkitBoxShadow:
-            return valueForShadowList(style->boxShadow(), style.get(), true);
+            return valueForShadowList(style->boxShadow(), *style, true);
         case CSSPropertyCaptionSide:
             return cssValuePool().createValue(style->captionSide());
         case CSSPropertyClear:
@@ -1910,15 +1898,15 @@
         case CSSPropertyWebkitColumnGap:
             if (style->hasNormalColumnGap())
                 return cssValuePool().createIdentifierValue(CSSValueNormal);
-            return zoomAdjustedPixelValue(style->columnGap(), style.get());
+            return zoomAdjustedPixelValue(style->columnGap(), *style);
         case CSSPropertyWebkitColumnProgression:
             return cssValuePool().createValue(style->columnProgression());
         case CSSPropertyWebkitColumnRuleColor:
-            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(style.get(), style->columnRuleColor());
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(*style, style->columnRuleColor());
         case CSSPropertyWebkitColumnRuleStyle:
             return cssValuePool().createValue(style->columnRuleStyle());
         case CSSPropertyWebkitColumnRuleWidth:
-            return zoomAdjustedPixelValue(style->columnRuleWidth(), style.get());
+            return zoomAdjustedPixelValue(style->columnRuleWidth(), *style);
         case CSSPropertyWebkitColumnSpan:
             return cssValuePool().createIdentifierValue(style->columnSpan() ? CSSValueAll : CSSValueNone);
         case CSSPropertyWebkitColumnBreakAfter:
@@ -1930,7 +1918,7 @@
         case CSSPropertyWebkitColumnWidth:
             if (style->hasAutoColumnWidth())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
-            return zoomAdjustedPixelValue(style->columnWidth(), style.get());
+            return zoomAdjustedPixelValue(style->columnWidth(), *style);
         case CSSPropertyTabSize:
             return cssValuePool().createValue(style->tabSize(), CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyWebkitRegionBreakAfter:
@@ -1997,16 +1985,16 @@
             return cssValuePool().createValue(style->floating());
         case CSSPropertyFont: {
             RefPtr<CSSFontValue> computedFont = CSSFontValue::create();
-            computedFont->style = valueForFontStyle(style.get());
-            computedFont->variant = valueForFontVariant(style.get());
-            computedFont->weight = valueForFontWeight(style.get());
-            computedFont->size = valueForFontSize(style.get());
-            computedFont->lineHeight = valueForLineHeight(style.get(), m_node->document().renderView());
-            computedFont->family = valueForFontFamily(style.get());
+            computedFont->style = valueForFontStyle(*style);
+            computedFont->variant = valueForFontVariant(*style);
+            computedFont->weight = valueForFontWeight(*style);
+            computedFont->size = valueForFontSize(*style);
+            computedFont->lineHeight = valueForLineHeight(*style, m_node->document().renderView());
+            computedFont->family = valueForFontFamily(*style);
             return computedFont.release();
         }
         case CSSPropertyFontFamily: {
-            RefPtr<CSSValueList> fontFamilyList = valueForFontFamily(style.get());
+            RefPtr<CSSValueList> fontFamilyList = valueForFontFamily(*style);
             // If there's only a single family, return that as a CSSPrimitiveValue.
             // NOTE: Gecko always returns this as a comma-separated CSSPrimitiveValue string.
             if (fontFamilyList->length() == 1)
@@ -2014,13 +2002,13 @@
             return fontFamilyList.release();
         }
         case CSSPropertyFontSize:
-            return valueForFontSize(style.get());
+            return valueForFontSize(*style);
         case CSSPropertyFontStyle:
-            return valueForFontStyle(style.get());
+            return valueForFontStyle(*style);
         case CSSPropertyFontVariant:
-            return valueForFontVariant(style.get());
+            return valueForFontVariant(*style);
         case CSSPropertyFontWeight:
-            return valueForFontWeight(style.get());
+            return valueForFontWeight(*style);
         case CSSPropertyWebkitFontFeatureSettings: {
             const FontFeatureSettings* featureSettings = style->fontDescription().featureSettings();
             if (!featureSettings || !featureSettings->size())
@@ -2042,14 +2030,14 @@
         // depending on the size of the explicit grid or the number of implicit tracks added to the grid. See
         // http://lists.w3.org/Archives/Public/www-style/2013Nov/0014.html
         case CSSPropertyGridAutoColumns:
-            return specifiedValueForGridTrackSize(style->gridAutoColumns(), style.get(), m_node->document().renderView());
+            return specifiedValueForGridTrackSize(style->gridAutoColumns(), *style, m_node->document().renderView());
         case CSSPropertyGridAutoRows:
-            return specifiedValueForGridTrackSize(style->gridAutoRows(), style.get(), m_node->document().renderView());
+            return specifiedValueForGridTrackSize(style->gridAutoRows(), *style, m_node->document().renderView());
 
         case CSSPropertyGridDefinitionColumns:
-            return valueForGridTrackList(ForColumns, renderer, style.get(), m_node->document().renderView());
+            return valueForGridTrackList(ForColumns, renderer, *style, m_node->document().renderView());
         case CSSPropertyGridDefinitionRows:
-            return valueForGridTrackList(ForRows, renderer, style.get(), m_node->document().renderView());
+            return valueForGridTrackList(ForRows, renderer, *style, m_node->document().renderView());
 
         case CSSPropertyGridColumnStart:
             return valueForGridPosition(style->gridColumnStart());
@@ -2080,9 +2068,9 @@
                 // the "height" property does not apply for non-replaced inline elements.
                 if (!renderer->isReplaced() && renderer->isInline())
                     return cssValuePool().createIdentifierValue(CSSValueAuto);
-                return zoomAdjustedPixelValue(sizingBox(renderer).height(), style.get());
+                return zoomAdjustedPixelValue(sizingBox(renderer).height(), *style);
             }
-            return zoomAdjustedPixelValueForLength(style->height(), style.get());
+            return zoomAdjustedPixelValueForLength(style->height(), *style);
         case CSSPropertyWebkitHighlight:
             if (style->highlight() == nullAtom)
                 return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -2100,17 +2088,17 @@
         case CSSPropertyIsolation:
             return cssValuePool().createValue(style->isolation());
         case CSSPropertyLeft:
-            return valueForPositionOffset(style.get(), CSSPropertyLeft, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyLeft, renderer, m_node->document().renderView());
         case CSSPropertyLetterSpacing:
             if (!style->letterSpacing())
                 return cssValuePool().createIdentifierValue(CSSValueNormal);
-            return zoomAdjustedPixelValue(style->letterSpacing(), style.get());
+            return zoomAdjustedPixelValue(style->letterSpacing(), *style);
         case CSSPropertyWebkitLineClamp:
             if (style->lineClamp().isNone())
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             return cssValuePool().createValue(style->lineClamp().value(), style->lineClamp().isPercentage() ? CSSPrimitiveValue::CSS_PERCENTAGE : CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyLineHeight:
-            return valueForLineHeight(style.get(), m_node->document().renderView());
+            return valueForLineHeight(*style, m_node->document().renderView());
         case CSSPropertyListStyleImage:
             if (style->listStyleImage())
                 return style->listStyleImage()->cssValue();
@@ -2126,13 +2114,13 @@
         case CSSPropertyMarginTop: {
             Length marginTop = style->marginTop();
             if (marginTop.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(marginTop, style.get());
-            return zoomAdjustedPixelValue(toRenderBox(renderer)->marginTop(), style.get());
+                return zoomAdjustedPixelValueForLength(marginTop, *style);
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->marginTop(), *style);
         }
         case CSSPropertyMarginRight: {
             Length marginRight = style->marginRight();
             if (marginRight.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(marginRight, style.get());
+                return zoomAdjustedPixelValueForLength(marginRight, *style);
             float value;
             if (marginRight.isPercent() || marginRight.isViewportPercentage()) {
                 // RenderBox gives a marginRight() that is the distance between the right-edge of the child box
@@ -2142,19 +2130,19 @@
             } else {
                 value = toRenderBox(renderer)->marginRight();
             }
-            return zoomAdjustedPixelValue(value, style.get());
+            return zoomAdjustedPixelValue(value, *style);
         }
         case CSSPropertyMarginBottom: {
             Length marginBottom = style->marginBottom();
             if (marginBottom.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(marginBottom, style.get());
-            return zoomAdjustedPixelValue(toRenderBox(renderer)->marginBottom(), style.get());
+                return zoomAdjustedPixelValueForLength(marginBottom, *style);
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->marginBottom(), *style);
         }
         case CSSPropertyMarginLeft: {
             Length marginLeft = style->marginLeft();
             if (marginLeft.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(marginLeft, style.get());
-            return zoomAdjustedPixelValue(toRenderBox(renderer)->marginLeft(), style.get());
+                return zoomAdjustedPixelValueForLength(marginLeft, *style);
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->marginLeft(), *style);
         }
         case CSSPropertyWebkitUserModify:
             return cssValuePool().createValue(style->userModify());
@@ -2162,31 +2150,31 @@
             const Length& maxHeight = style->maxHeight();
             if (maxHeight.isUndefined())
                 return cssValuePool().createIdentifierValue(CSSValueNone);
-            return zoomAdjustedPixelValueForLength(maxHeight, style.get());
+            return zoomAdjustedPixelValueForLength(maxHeight, *style);
         }
         case CSSPropertyMaxWidth: {
             const Length& maxWidth = style->maxWidth();
             if (maxWidth.isUndefined())
                 return cssValuePool().createIdentifierValue(CSSValueNone);
-            return zoomAdjustedPixelValueForLength(maxWidth, style.get());
+            return zoomAdjustedPixelValueForLength(maxWidth, *style);
         }
         case CSSPropertyMinHeight:
             // FIXME: For flex-items, min-height:auto should compute to min-content.
             if (style->minHeight().isAuto())
-                return zoomAdjustedPixelValue(0, style.get());
-            return zoomAdjustedPixelValueForLength(style->minHeight(), style.get());
+                return zoomAdjustedPixelValue(0, *style);
+            return zoomAdjustedPixelValueForLength(style->minHeight(), *style);
         case CSSPropertyMinWidth:
             // FIXME: For flex-items, min-width:auto should compute to min-content.
             if (style->minWidth().isAuto())
-                return zoomAdjustedPixelValue(0, style.get());
-            return zoomAdjustedPixelValueForLength(style->minWidth(), style.get());
+                return zoomAdjustedPixelValue(0, *style);
+            return zoomAdjustedPixelValueForLength(style->minWidth(), *style);
         case CSSPropertyObjectFit:
             return cssValuePool().createValue(style->objectFit());
         case CSSPropertyObjectPosition:
             return cssValuePool().createValue(
                 Pair::create(
-                    zoomAdjustedPixelValueForLength(style->objectPosition().x(), style.get()),
-                    zoomAdjustedPixelValueForLength(style->objectPosition().y(), style.get()),
+                    zoomAdjustedPixelValueForLength(style->objectPosition().x(), *style),
+                    zoomAdjustedPixelValueForLength(style->objectPosition().y(), *style),
                     Pair::KeepIdenticalValues));
         case CSSPropertyOpacity:
             return cssValuePool().createValue(style->opacity(), CSSPrimitiveValue::CSS_NUMBER);
@@ -2195,15 +2183,15 @@
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
             return cssValuePool().createValue(style->orphans(), CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyOutlineColor:
-            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(style.get(), style->outlineColor());
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(*style, style->outlineColor());
         case CSSPropertyOutlineOffset:
-            return zoomAdjustedPixelValue(style->outlineOffset(), style.get());
+            return zoomAdjustedPixelValue(style->outlineOffset(), *style);
         case CSSPropertyOutlineStyle:
             if (style->outlineStyleIsAuto())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
             return cssValuePool().createValue(style->outlineStyle());
         case CSSPropertyOutlineWidth:
-            return zoomAdjustedPixelValue(style->outlineWidth(), style.get());
+            return zoomAdjustedPixelValue(style->outlineWidth(), *style);
         case CSSPropertyOverflow:
             return cssValuePool().createValue(max(style->overflowX(), style->overflowY()));
         case CSSPropertyOverflowWrap:
@@ -2215,26 +2203,26 @@
         case CSSPropertyPaddingTop: {
             Length paddingTop = style->paddingTop();
             if (paddingTop.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(paddingTop, style.get());
-            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), style.get());
+                return zoomAdjustedPixelValueForLength(paddingTop, *style);
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), *style);
         }
         case CSSPropertyPaddingRight: {
             Length paddingRight = style->paddingRight();
             if (paddingRight.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(paddingRight, style.get());
-            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), style.get());
+                return zoomAdjustedPixelValueForLength(paddingRight, *style);
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), *style);
         }
         case CSSPropertyPaddingBottom: {
             Length paddingBottom = style->paddingBottom();
             if (paddingBottom.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(paddingBottom, style.get());
-            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), style.get());
+                return zoomAdjustedPixelValueForLength(paddingBottom, *style);
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), *style);
         }
         case CSSPropertyPaddingLeft: {
             Length paddingLeft = style->paddingLeft();
             if (paddingLeft.isFixed() || !renderer || !renderer->isBox())
-                return zoomAdjustedPixelValueForLength(paddingLeft, style.get());
-            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), style.get());
+                return zoomAdjustedPixelValueForLength(paddingLeft, *style);
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), *style);
         }
         case CSSPropertyPageBreakAfter:
             return cssValuePool().createValue(style->pageBreakAfter());
@@ -2250,7 +2238,7 @@
         case CSSPropertyPosition:
             return cssValuePool().createValue(style->position());
         case CSSPropertyRight:
-            return valueForPositionOffset(style.get(), CSSPropertyRight, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyRight, renderer, m_node->document().renderView());
         case CSSPropertyWebkitRubyPosition:
             return cssValuePool().createValue(style->rubyPosition());
         case CSSPropertyTableLayout:
@@ -2266,7 +2254,7 @@
         case CSSPropertyTextDecorationStyle:
             return valueForTextDecorationStyle(style->textDecorationStyle());
         case CSSPropertyTextDecorationColor:
-            return currentColorOrValidColor(style.get(), style->textDecorationColor());
+            return currentColorOrValidColor(*style, style->textDecorationColor());
         case CSSPropertyTextJustify:
             return cssValuePool().createValue(style->textJustify());
         case CSSPropertyTextUnderlinePosition:
@@ -2274,9 +2262,9 @@
         case CSSPropertyWebkitTextDecorationsInEffect:
             return renderTextDecorationFlagsToCSSValue(style->textDecorationsInEffect());
         case CSSPropertyWebkitTextFillColor:
-            return currentColorOrValidColor(style.get(), style->textFillColor());
+            return currentColorOrValidColor(*style, style->textFillColor());
         case CSSPropertyWebkitTextEmphasisColor:
-            return currentColorOrValidColor(style.get(), style->textEmphasisColor());
+            return currentColorOrValidColor(*style, style->textEmphasisColor());
         case CSSPropertyWebkitTextEmphasisPosition:
             return cssValuePool().createValue(style->textEmphasisPosition());
         case CSSPropertyWebkitTextEmphasisStyle:
@@ -2300,7 +2288,7 @@
             }
             }
         case CSSPropertyTextIndent: {
-            RefPtr<CSSValue> textIndent = zoomAdjustedPixelValueForLength(style->textIndent(), style.get());
+            RefPtr<CSSValue> textIndent = zoomAdjustedPixelValueForLength(style->textIndent(), *style);
             if (RuntimeEnabledFeatures::css3TextEnabled() && style->textIndentLine() == TextIndentEachLine) {
                 RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
                 list->append(textIndent.release());
@@ -2310,7 +2298,7 @@
             return textIndent.release();
         }
         case CSSPropertyTextShadow:
-            return valueForShadowList(style->textShadow(), style.get(), false);
+            return valueForShadowList(style->textShadow(), *style, false);
         case CSSPropertyTextRendering:
             return cssValuePool().createValue(style->fontDescription().textRenderingMode());
         case CSSPropertyTextOverflow:
@@ -2320,13 +2308,13 @@
         case CSSPropertyWebkitTextSecurity:
             return cssValuePool().createValue(style->textSecurity());
         case CSSPropertyWebkitTextStrokeColor:
-            return currentColorOrValidColor(style.get(), style->textStrokeColor());
+            return currentColorOrValidColor(*style, style->textStrokeColor());
         case CSSPropertyWebkitTextStrokeWidth:
-            return zoomAdjustedPixelValue(style->textStrokeWidth(), style.get());
+            return zoomAdjustedPixelValue(style->textStrokeWidth(), *style);
         case CSSPropertyTextTransform:
             return cssValuePool().createValue(style->textTransform());
         case CSSPropertyTop:
-            return valueForPositionOffset(style.get(), CSSPropertyTop, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyTop, renderer, m_node->document().renderView());
         case CSSPropertyTouchAction:
             return cssValuePool().createValue(style->touchAction());
         case CSSPropertyTouchActionDelay:
@@ -2372,13 +2360,13 @@
                 // the "width" property does not apply for non-replaced inline elements.
                 if (!renderer->isReplaced() && renderer->isInline())
                     return cssValuePool().createIdentifierValue(CSSValueAuto);
-                return zoomAdjustedPixelValue(sizingBox(renderer).width(), style.get());
+                return zoomAdjustedPixelValue(sizingBox(renderer).width(), *style);
             }
-            return zoomAdjustedPixelValueForLength(style->width(), style.get());
+            return zoomAdjustedPixelValueForLength(style->width(), *style);
         case CSSPropertyWordBreak:
             return cssValuePool().createValue(style->wordBreak());
         case CSSPropertyWordSpacing:
-            return zoomAdjustedPixelValue(style->wordSpacing(), style.get());
+            return zoomAdjustedPixelValue(style->wordSpacing(), *style);
         case CSSPropertyWordWrap:
             return cssValuePool().createValue(style->overflowWrap());
         case CSSPropertyWebkitLineBreak:
@@ -2549,25 +2537,25 @@
         case CSSPropertyWebkitBackfaceVisibility:
             return cssValuePool().createIdentifierValue((style->backfaceVisibility() == BackfaceVisibilityHidden) ? CSSValueHidden : CSSValueVisible);
         case CSSPropertyWebkitBorderImage:
-            return valueForNinePieceImage(style->borderImage(), style.get());
+            return valueForNinePieceImage(style->borderImage(), *style);
         case CSSPropertyBorderImageOutset:
-            return valueForNinePieceImageQuad(style->borderImage().outset(), style.get());
+            return valueForNinePieceImageQuad(style->borderImage().outset(), *style);
         case CSSPropertyBorderImageRepeat:
             return valueForNinePieceImageRepeat(style->borderImage());
         case CSSPropertyBorderImageSlice:
             return valueForNinePieceImageSlice(style->borderImage());
         case CSSPropertyBorderImageWidth:
-            return valueForNinePieceImageQuad(style->borderImage().borderSlices(), style.get());
+            return valueForNinePieceImageQuad(style->borderImage().borderSlices(), *style);
         case CSSPropertyWebkitMaskBoxImage:
-            return valueForNinePieceImage(style->maskBoxImage(), style.get());
+            return valueForNinePieceImage(style->maskBoxImage(), *style);
         case CSSPropertyWebkitMaskBoxImageOutset:
-            return valueForNinePieceImageQuad(style->maskBoxImage().outset(), style.get());
+            return valueForNinePieceImageQuad(style->maskBoxImage().outset(), *style);
         case CSSPropertyWebkitMaskBoxImageRepeat:
             return valueForNinePieceImageRepeat(style->maskBoxImage());
         case CSSPropertyWebkitMaskBoxImageSlice:
             return valueForNinePieceImageSlice(style->maskBoxImage());
         case CSSPropertyWebkitMaskBoxImageWidth:
-            return valueForNinePieceImageQuad(style->maskBoxImage().borderSlices(), style.get());
+            return valueForNinePieceImageQuad(style->maskBoxImage().borderSlices(), *style);
         case CSSPropertyWebkitMaskBoxImageSource:
             if (style->maskBoxImageSource())
                 return style->maskBoxImageSource()->cssValue();
@@ -2584,7 +2572,7 @@
         case CSSPropertyWebkitPerspective:
             if (!style->hasPerspective())
                 return cssValuePool().createIdentifierValue(CSSValueNone);
-            return zoomAdjustedPixelValue(style->perspective(), style.get());
+            return zoomAdjustedPixelValue(style->perspective(), *style);
         case CSSPropertyWebkitPerspectiveOrigin: {
             RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
             if (renderer) {
@@ -2593,12 +2581,12 @@
                     box = toRenderBox(renderer)->borderBoxRect();
 
                 RenderView* renderView = m_node->document().renderView();
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginX(), box.width(), renderView), style.get()));
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginY(), box.height(), renderView), style.get()));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginX(), box.width(), renderView), *style));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginY(), box.height(), renderView), *style));
             }
             else {
-                list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginX(), style.get()));
-                list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginY(), style.get()));
+                list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginX(), *style));
+                list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginY(), *style));
 
             }
             return list.release();
@@ -2606,33 +2594,33 @@
         case CSSPropertyWebkitRtlOrdering:
             return cssValuePool().createIdentifierValue(style->rtlOrdering() ? CSSValueVisual : CSSValueLogical);
         case CSSPropertyWebkitTapHighlightColor:
-            return currentColorOrValidColor(style.get(), style->tapHighlightColor());
+            return currentColorOrValidColor(*style, style->tapHighlightColor());
         case CSSPropertyWebkitUserDrag:
             return cssValuePool().createValue(style->userDrag());
         case CSSPropertyWebkitUserSelect:
             return cssValuePool().createValue(style->userSelect());
         case CSSPropertyBorderBottomLeftRadius:
-            return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), style.get());
+            return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), *style);
         case CSSPropertyBorderBottomRightRadius:
-            return valueForBorderRadiusCorner(style->borderBottomRightRadius(), style.get());
+            return valueForBorderRadiusCorner(style->borderBottomRightRadius(), *style);
         case CSSPropertyBorderTopLeftRadius:
-            return valueForBorderRadiusCorner(style->borderTopLeftRadius(), style.get());
+            return valueForBorderRadiusCorner(style->borderTopLeftRadius(), *style);
         case CSSPropertyBorderTopRightRadius:
-            return valueForBorderRadiusCorner(style->borderTopRightRadius(), style.get());
+            return valueForBorderRadiusCorner(style->borderTopRightRadius(), *style);
         case CSSPropertyClip: {
             if (!style->hasClip())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
             RefPtr<Rect> rect = Rect::create();
-            rect->setTop(zoomAdjustedPixelValue(style->clip().top().value(), style.get()));
-            rect->setRight(zoomAdjustedPixelValue(style->clip().right().value(), style.get()));
-            rect->setBottom(zoomAdjustedPixelValue(style->clip().bottom().value(), style.get()));
-            rect->setLeft(zoomAdjustedPixelValue(style->clip().left().value(), style.get()));
+            rect->setTop(zoomAdjustedPixelValue(style->clip().top().value(), *style));
+            rect->setRight(zoomAdjustedPixelValue(style->clip().right().value(), *style));
+            rect->setBottom(zoomAdjustedPixelValue(style->clip().bottom().value(), *style));
+            rect->setLeft(zoomAdjustedPixelValue(style->clip().left().value(), *style));
             return cssValuePool().createValue(rect.release());
         }
         case CSSPropertySpeak:
             return cssValuePool().createValue(style->speak());
         case CSSPropertyWebkitTransform:
-            return computedTransform(renderer, style.get());
+            return computedTransform(renderer, *style);
         case CSSPropertyWebkitTransformOrigin: {
             RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
             if (renderer) {
@@ -2641,15 +2629,15 @@
                     box = toRenderBox(renderer)->borderBoxRect();
 
                 RenderView* renderView = m_node->document().renderView();
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginX(), box.width(), renderView), style.get()));
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginY(), box.height(), renderView), style.get()));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginX(), box.width(), renderView), *style));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginY(), box.height(), renderView), *style));
                 if (style->transformOriginZ() != 0)
-                    list->append(zoomAdjustedPixelValue(style->transformOriginZ(), style.get()));
+                    list->append(zoomAdjustedPixelValue(style->transformOriginZ(), *style));
             } else {
-                list->append(zoomAdjustedPixelValueForLength(style->transformOriginX(), style.get()));
-                list->append(zoomAdjustedPixelValueForLength(style->transformOriginY(), style.get()));
+                list->append(zoomAdjustedPixelValueForLength(style->transformOriginX(), *style));
+                list->append(zoomAdjustedPixelValueForLength(style->transformOriginY(), *style));
                 if (style->transformOriginZ() != 0)
-                    list->append(zoomAdjustedPixelValue(style->transformOriginZ(), style.get()));
+                    list->append(zoomAdjustedPixelValue(style->transformOriginZ(), *style));
             }
             return list.release();
         }
@@ -2711,19 +2699,17 @@
         case CSSPropertyWebkitLineBoxContain:
             return createLineBoxContainValue(style->lineBoxContain());
         case CSSPropertyContent:
-            return valueForContentData(style.get());
+            return valueForContentData(*style);
         case CSSPropertyCounterIncrement:
-            return valueForCounterDirectives(style.get(), propertyID);
+            return valueForCounterDirectives(*style, propertyID);
         case CSSPropertyCounterReset:
-            return valueForCounterDirectives(style.get(), propertyID);
+            return valueForCounterDirectives(*style, propertyID);
         case CSSPropertyWebkitClipPath:
             if (ClipPathOperation* operation = style->clipPath()) {
-                if (operation->getOperationType() == ClipPathOperation::SHAPE)
-                    return valueForBasicShape(style.get(), static_cast<ShapeClipPathOperation*>(operation)->basicShape());
-                if (operation->getOperationType() == ClipPathOperation::REFERENCE) {
-                    ReferenceClipPathOperation* referenceOperation = static_cast<ReferenceClipPathOperation*>(operation);
-                    return CSSPrimitiveValue::create(referenceOperation->url(), CSSPrimitiveValue::CSS_URI);
-                }
+                if (operation->type() == ClipPathOperation::SHAPE)
+                    return valueForBasicShape(*style, toShapeClipPathOperation(operation)->basicShape());
+                if (operation->type() == ClipPathOperation::REFERENCE)
+                    return CSSPrimitiveValue::create(toReferenceClipPathOperation(operation)->url(), CSSPrimitiveValue::CSS_URI);
             }
             return cssValuePool().createIdentifierValue(CSSValueNone);
         case CSSPropertyWebkitFlowInto:
@@ -2755,7 +2741,7 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
             ASSERT(style->shapeInside()->type() == ShapeValue::Shape);
-            return valueForBasicShape(style.get(), style->shapeInside()->shape());
+            return valueForBasicShape(*style, style->shapeInside()->shape());
         case CSSPropertyShapeOutside:
             if (!style->shapeOutside())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -2765,11 +2751,11 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
             ASSERT(style->shapeOutside()->type() == ShapeValue::Shape);
-            return valueForBasicShape(style.get(), style->shapeOutside()->shape());
+            return valueForBasicShape(*style, style->shapeOutside()->shape());
         case CSSPropertyWebkitWrapThrough:
             return cssValuePool().createValue(style->wrapThrough());
         case CSSPropertyWebkitFilter:
-            return valueForFilter(renderer, style.get());
+            return valueForFilter(renderer, *style);
         case CSSPropertyMixBlendMode:
             return cssValuePool().createValue(style->blendMode());
 
@@ -2803,9 +2789,9 @@
         case CSSPropertyBorderLeft:
             return valuesForShorthandProperty(borderLeftShorthand());
         case CSSPropertyBorderImage:
-            return valueForNinePieceImage(style->borderImage(), style.get());
+            return valueForNinePieceImage(style->borderImage(), *style);
         case CSSPropertyBorderRadius:
-            return valueForBorderRadiusShorthand(style.get());
+            return valueForBorderRadiusShorthand(*style);
         case CSSPropertyBorderRight:
             return valuesForShorthandProperty(borderRightShorthand());
         case CSSPropertyBorderStyle:
@@ -3124,14 +3110,14 @@
     return false;
 }
 
-void CSSComputedStyleDeclaration::setProperty(const String& name, const String&, const String&, ExceptionState& es)
+void CSSComputedStyleDeclaration::setProperty(const String& name, const String&, const String&, ExceptionState& exceptionState)
 {
-    es.throwDOMException(NoModificationAllowedError, "Failed to set the '" + name + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+    exceptionState.throwDOMException(NoModificationAllowedError, "Failed to set the '" + name + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
 }
 
-String CSSComputedStyleDeclaration::removeProperty(const String& name, ExceptionState& es)
+String CSSComputedStyleDeclaration::removeProperty(const String& name, ExceptionState& exceptionState)
 {
-    es.throwDOMException(NoModificationAllowedError, "Failed to remove the '" + name + "' property from a computed 'CSSStyleDeclaration': computed styles are read-only.");
+    exceptionState.throwDOMException(NoModificationAllowedError, "Failed to remove the '" + name + "' property from a computed 'CSSStyleDeclaration': computed styles are read-only.");
     return String();
 }
 
@@ -3145,9 +3131,9 @@
     return getPropertyValue(propertyID);
 }
 
-void CSSComputedStyleDeclaration::setPropertyInternal(CSSPropertyID id, const String&, bool, ExceptionState& es)
+void CSSComputedStyleDeclaration::setPropertyInternal(CSSPropertyID id, const String&, bool, ExceptionState& exceptionState)
 {
-    es.throwDOMException(NoModificationAllowedError, "Failed to set the '" + getPropertyNameString(id) + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+    exceptionState.throwDOMException(NoModificationAllowedError, "Failed to set the '" + getPropertyNameString(id) + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
 }
 
 const HashMap<AtomicString, String>* CSSComputedStyleDeclaration::variableMap() const
@@ -3183,10 +3169,10 @@
     return it->value;
 }
 
-bool CSSComputedStyleDeclaration::setVariableValue(const AtomicString& name, const String&, ExceptionState& es)
+bool CSSComputedStyleDeclaration::setVariableValue(const AtomicString& name, const String&, ExceptionState& exceptionState)
 {
     ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    es.throwDOMException(NoModificationAllowedError, "Failed to set the '" + name + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+    exceptionState.throwDOMException(NoModificationAllowedError, "Failed to set the '" + name + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
     return false;
 }
 
@@ -3196,10 +3182,10 @@
     return false;
 }
 
-bool CSSComputedStyleDeclaration::clearVariables(ExceptionState& es)
+bool CSSComputedStyleDeclaration::clearVariables(ExceptionState& exceptionState)
 {
     ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    es.throwDOMException(NoModificationAllowedError, "Failed to clear variables from a computed 'CSSStyleDeclaration': computed styles are read-only.");
+    exceptionState.throwDOMException(NoModificationAllowedError, "Failed to clear variables from a computed 'CSSStyleDeclaration': computed styles are read-only.");
     return false;
 }
 
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index 74b881d..a3ff877 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -128,12 +128,12 @@
 
     virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE;
 
-    PassRefPtr<CSSValue> valueForShadowData(const ShadowData&, const RenderStyle*, bool useSpread) const;
-    PassRefPtr<CSSValue> valueForShadowList(const ShadowList*, const RenderStyle*, bool useSpread) const;
-    PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(const RenderStyle*, const Color&) const;
-    PassRefPtr<SVGPaint> adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint>, RenderStyle*) const;
+    PassRefPtr<CSSValue> valueForShadowData(const ShadowData&, const RenderStyle&, bool useSpread) const;
+    PassRefPtr<CSSValue> valueForShadowList(const ShadowList*, const RenderStyle&, bool useSpread) const;
+    PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(const RenderStyle&, const Color&) const;
+    PassRefPtr<SVGPaint> adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint>, RenderStyle&) const;
 
-    PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle*) const;
+    PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle&) const;
 
     PassRefPtr<CSSValueList> valuesForShorthandProperty(const StylePropertyShorthand&) const;
     PassRefPtr<CSSValueList> valuesForSidesShorthand(const StylePropertyShorthand&) const;
diff --git a/Source/core/css/CSSCursorImageValue.cpp b/Source/core/css/CSSCursorImageValue.cpp
index 0c3c30a..59e9de5 100644
--- a/Source/core/css/CSSCursorImageValue.cpp
+++ b/Source/core/css/CSSCursorImageValue.cpp
@@ -146,8 +146,7 @@
     }
 
     if (m_image && m_image->isImageResource())
-        return static_cast<StyleFetchedImage*>(m_image.get());
-
+        return toStyleFetchedImage(m_image);
     return 0;
 }
 
@@ -177,7 +176,7 @@
 {
     if (!m_image || !m_image->isImageResource())
         return String();
-    return static_cast<StyleFetchedImage*>(m_image.get())->cachedImage()->url().string();
+    return toStyleFetchedImage(m_image)->cachedImage()->url().string();
 }
 
 void CSSCursorImageValue::clearImageResource()
diff --git a/Source/core/css/CSSCustomFontData.h b/Source/core/css/CSSCustomFontData.h
new file mode 100644
index 0000000..22dbae1
--- /dev/null
+++ b/Source/core/css/CSSCustomFontData.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2013 Google, Inc.
+ *
+ * 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.
+ *
+ */
+
+#ifndef CSSCustomFontData_h
+#define CSSCustomFontData_h
+
+#include "core/css/CSSFontFaceSource.h"
+#include "core/platform/graphics/CustomFontData.h"
+
+namespace WebCore {
+
+class CSSCustomFontData FINAL : public CustomFontData {
+public:
+    static PassRefPtr<CSSCustomFontData> create(bool isLoadingFallback = false)
+    {
+        return adoptRef(new CSSCustomFontData(isLoadingFallback));
+    }
+
+    virtual ~CSSCustomFontData() { }
+
+    virtual void beginLoadIfNeeded() const OVERRIDE
+    {
+        if (!m_isUsed && m_isLoadingFallback && m_fontFaceSource) {
+            m_isUsed = true;
+            m_fontFaceSource->beginLoadingFontSoon();
+        }
+    }
+
+    virtual void setCSSFontFaceSource(CSSFontFaceSource* source) OVERRIDE { m_fontFaceSource = source; }
+    virtual void clearCSSFontFaceSource() OVERRIDE { m_fontFaceSource = 0; }
+
+private:
+    CSSCustomFontData(bool isLoadingFallback)
+        : CustomFontData(isLoadingFallback)
+        , m_fontFaceSource(0)
+    {
+    }
+
+    CSSFontFaceSource* m_fontFaceSource;
+};
+
+}
+
+#endif // CSSCustomFontData_h
diff --git a/Source/core/css/CSSDefaultStyleSheets.cpp b/Source/core/css/CSSDefaultStyleSheets.cpp
index 2799cff..e6f28d6 100644
--- a/Source/core/css/CSSDefaultStyleSheets.cpp
+++ b/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -33,6 +33,7 @@
 #include "core/css/MediaQueryEvaluator.h"
 #include "core/css/RuleSet.h"
 #include "core/css/StyleSheetContents.h"
+#include "core/css/ViewportStyle.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLHtmlElement.h"
@@ -49,21 +50,12 @@
 RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle;
 RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle;
 
-StyleSheetContents* CSSDefaultStyleSheets::simpleDefaultStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::defaultStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::quirksStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::svgStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::mediaControlsStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::fullscreenStyleSheet;
 
-// FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
-static const char simpleUserAgentStyleSheet[] = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus,a:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}body:-webkit-seamless-document{margin:0}body:-webkit-full-page-media{background-color:black}@viewport{min-width:980px}@page{size:auto;margin:auto;padding:0;border-width:0}";
-
-static inline bool elementCanUseSimpleDefaultStyle(Element* e)
-{
-    return isHTMLHtmlElement(e) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || isHTMLAnchorElement(e);
-}
-
 static const MediaQueryEvaluator& screenEval()
 {
     DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
@@ -88,37 +80,24 @@
     return parseUASheet(String(characters, size));
 }
 
-void CSSDefaultStyleSheets::initDefaultStyle(Element* root)
+void CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary()
 {
-    if (!defaultStyle) {
-        if (!root || elementCanUseSimpleDefaultStyle(root))
-            loadSimpleDefaultStyle();
-        else
-            loadFullDefaultStyle();
-    }
+    if (!defaultStyle)
+        loadDefaultStyle();
 }
 
-void CSSDefaultStyleSheets::loadFullDefaultStyle()
+void CSSDefaultStyleSheets::loadDefaultStyle()
 {
-    if (simpleDefaultStyleSheet) {
-        ASSERT(defaultStyle);
-        ASSERT(defaultPrintStyle == defaultStyle);
-        delete defaultStyle;
-        simpleDefaultStyleSheet->deref();
-        defaultStyle = RuleSet::create().leakPtr();
-        defaultPrintStyle = RuleSet::create().leakPtr();
-        simpleDefaultStyleSheet = 0;
-    } else {
-        ASSERT(!defaultStyle);
-        defaultStyle = RuleSet::create().leakPtr();
-        defaultPrintStyle = RuleSet::create().leakPtr();
-        defaultQuirksStyle = RuleSet::create().leakPtr();
-    }
+    ASSERT(!defaultStyle);
+    defaultStyle = RuleSet::create().leakPtr();
+    defaultPrintStyle = RuleSet::create().leakPtr();
+    defaultQuirksStyle = RuleSet::create().leakPtr();
 
     // Strict-mode rules.
     String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
     defaultStyleSheet = parseUASheet(defaultRules);
     defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
+    defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval());
     defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
 
     // Quirks-mode rules.
@@ -127,22 +106,6 @@
     defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
 }
 
-void CSSDefaultStyleSheets::loadSimpleDefaultStyle()
-{
-    ASSERT(!defaultStyle);
-    ASSERT(!simpleDefaultStyleSheet);
-
-    defaultStyle = RuleSet::create().leakPtr();
-    // There are no media-specific rules in the simple default style.
-    defaultPrintStyle = defaultStyle;
-    defaultQuirksStyle = RuleSet::create().leakPtr();
-
-    simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
-    defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
-
-    // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
-}
-
 RuleSet* CSSDefaultStyleSheets::viewSourceStyle()
 {
     if (!defaultViewSourceStyle) {
@@ -163,11 +126,6 @@
 
 void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
 {
-    if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element)) {
-        loadFullDefaultStyle();
-        changedDefaultStyle = true;
-    }
-
     // FIXME: We should assert that the sheet only styles SVG elements.
     if (element->isSVGElement() && !svgStyleSheet) {
         svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
diff --git a/Source/core/css/CSSDefaultStyleSheets.h b/Source/core/css/CSSDefaultStyleSheets.h
index 5cf0035..a9ca837 100644
--- a/Source/core/css/CSSDefaultStyleSheets.h
+++ b/Source/core/css/CSSDefaultStyleSheets.h
@@ -37,7 +37,6 @@
     static RuleSet* defaultViewSourceStyle;
     static RuleSet* defaultXHTMLMobileProfileStyle;
 
-    static StyleSheetContents* simpleDefaultStyleSheet;
     static StyleSheetContents* defaultStyleSheet;
     static StyleSheetContents* quirksStyleSheet;
     static StyleSheetContents* svgStyleSheet;
@@ -45,11 +44,16 @@
     static StyleSheetContents* fullscreenStyleSheet;
 
     static void ensureDefaultStyleSheetsForElement(Element*, bool& changedDefaultStyle);
-    static void loadFullDefaultStyle();
-    static void loadSimpleDefaultStyle();
-    static void initDefaultStyle(Element*);
+    // FIXME: defaultStyleSheet should have an accessor which incorporates this branch:
+    static void loadDefaultStylesheetIfNecessary();
+
     static RuleSet* viewSourceStyle();
+
+    // FIXME: Remove WAP support.
     static RuleSet* xhtmlMobileProfileStyle();
+
+private:
+    static void loadDefaultStyle();
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSFontFace.cpp b/Source/core/css/CSSFontFace.cpp
index affaa14..5ad1bf1 100644
--- a/Source/core/css/CSSFontFace.cpp
+++ b/Source/core/css/CSSFontFace.cpp
@@ -31,7 +31,7 @@
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/FontFaceSet.h"
 #include "core/dom/Document.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/platform/graphics/SimpleFontData.h"
 
 namespace WebCore {
@@ -84,6 +84,7 @@
 {
     if (source != m_activeSource)
         return;
+    m_activeSource = 0;
 
     // FIXME: Can we assert that m_segmentedFontFace is non-null? That may
     // require stopping in-progress font loading when the last
@@ -107,7 +108,7 @@
     m_segmentedFontFace->fontLoaded(this);
 }
 
-PassRefPtr<SimpleFontData> CSSFontFace::getFontData(const FontDescription& fontDescription, bool syntheticBold, bool syntheticItalic)
+PassRefPtr<SimpleFontData> CSSFontFace::getFontData(const FontDescription& fontDescription)
 {
     m_activeSource = 0;
     if (!isValid())
@@ -118,7 +119,7 @@
 
     size_t size = m_sources.size();
     for (size_t i = 0; i < size; ++i) {
-        if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription, syntheticBold, syntheticItalic, fontSelector)) {
+        if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription, fontSelector)) {
             m_activeSource = m_sources[i].get();
             if (loadStatus() == FontFace::Unloaded && (m_sources[i]->isLoading() || m_sources[i]->isLoaded()))
                 setLoadStatus(FontFace::Loading);
@@ -137,7 +138,16 @@
 
 void CSSFontFace::willUseFontData(const FontDescription& fontDescription)
 {
-    if (loadStatus() != FontFace::Unloaded)
+    if (loadStatus() != FontFace::Unloaded || m_activeSource)
+        return;
+
+    // Kicks off font load here only if the @font-face has no unicode-range.
+    // @font-faces with unicode-range will be loaded when a GlyphPage for the
+    // font is created.
+    // FIXME: Pass around the text to render from RenderText, and kick download
+    // if m_ranges intersects with the text. Make sure this does not cause
+    // performance regression.
+    if (!m_ranges.isEntireRange())
         return;
 
     ASSERT(m_segmentedFontFace);
@@ -146,8 +156,10 @@
     for (size_t i = 0; i < size; ++i) {
         if (!m_sources[i]->isValid() || (m_sources[i]->isLocal() && !m_sources[i]->isLocalFontAvailable(fontDescription)))
             continue;
-        if (!m_sources[i]->isLocal())
+        if (!m_sources[i]->isLocal()) {
+            m_activeSource = m_sources[i].get();
             m_sources[i]->willUseFontData();
+        }
         break;
     }
 }
@@ -180,8 +192,8 @@
 {
     if (text.isEmpty())
         return false;
-    if (m_ranges.isEmpty())
-        return true; // Empty UnicodeRangeSet represents the whole code space.
+    if (isEntireRange())
+        return true;
 
     // FIXME: This takes O(text.length() * m_ranges.size()) time. It would be
     // better to make m_ranges sorted and use binary search.
diff --git a/Source/core/css/CSSFontFace.h b/Source/core/css/CSSFontFace.h
index b547667..87170db 100644
--- a/Source/core/css/CSSFontFace.h
+++ b/Source/core/css/CSSFontFace.h
@@ -62,7 +62,7 @@
     void beginLoadingFontSoon(FontResource*);
     void fontLoaded(CSSFontFaceSource*);
 
-    PassRefPtr<SimpleFontData> getFontData(const FontDescription&, bool syntheticBold, bool syntheticItalic);
+    PassRefPtr<SimpleFontData> getFontData(const FontDescription&);
 
     struct UnicodeRange {
         UnicodeRange(UChar32 from, UChar32 to)
@@ -84,13 +84,14 @@
     public:
         void add(UChar32 from, UChar32 to) { m_ranges.append(UnicodeRange(from, to)); }
         bool intersectsWith(const String&) const;
+        bool isEntireRange() const { return m_ranges.isEmpty(); }
         size_t size() const { return m_ranges.size(); }
         const UnicodeRange& rangeAt(size_t i) const { return m_ranges[i]; }
     private:
-        Vector<UnicodeRange> m_ranges;
+        Vector<UnicodeRange> m_ranges; // If empty, represents the whole code space.
     };
 
-    FontFace::LoadStatus loadStatus() const { return m_fontFace ? m_fontFace->loadStatus() : FontFace::Loaded; }
+    FontFace::LoadStatus loadStatus() const { return m_fontFace->loadStatus(); }
     void willUseFontData(const FontDescription&);
 
 private:
@@ -99,6 +100,7 @@
         , m_activeSource(0)
         , m_fontFace(fontFace)
     {
+        ASSERT(m_fontFace);
     }
     void setLoadStatus(FontFace::LoadStatus);
 
diff --git a/Source/core/css/CSSFontFaceSource.cpp b/Source/core/css/CSSFontFaceSource.cpp
index 48b5257..6614f8e 100644
--- a/Source/core/css/CSSFontFaceSource.cpp
+++ b/Source/core/css/CSSFontFaceSource.cpp
@@ -27,6 +27,7 @@
 #include "core/css/CSSFontFaceSource.h"
 
 #include "RuntimeEnabledFeatures.h"
+#include "core/css/CSSCustomFontData.h"
 #include "core/css/CSSFontFace.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/fetch/FontResource.h"
@@ -70,8 +71,9 @@
         return;
 
     for (FontDataTable::iterator it = m_fontDataTable.begin(); it != m_fontDataTable.end(); ++it) {
-        if (SimpleFontData* fontData = it->value.get())
-            fontData->clearCSSFontFaceSource();
+        SimpleFontData* fontData = it->value.get();
+        if (fontData && fontData->customFontData())
+            fontData->customFontData()->clearCSSFontFaceSource();
     }
     m_fontDataTable.clear();
 }
@@ -126,7 +128,7 @@
         m_face->fontLoaded(this);
 }
 
-PassRefPtr<SimpleFontData> CSSFontFaceSource::getFontData(const FontDescription& fontDescription, bool syntheticBold, bool syntheticItalic, CSSFontSelector* fontSelector)
+PassRefPtr<SimpleFontData> CSSFontFaceSource::getFontData(const FontDescription& fontDescription, CSSFontSelector* fontSelector)
 {
     // If the font hasn't loaded or an error occurred, then we've got nothing.
     if (!isValid())
@@ -143,7 +145,6 @@
     // See if we have a mapping in our FontData cache.
     AtomicString emptyFontFamily = "";
     FontCacheKey key = fontDescription.cacheKey(emptyFontFamily);
-    key.setSynthetic(syntheticBold, syntheticItalic);
 
     RefPtr<SimpleFontData>& fontData = m_fontDataTable.add(key.hash(), 0).iterator->value;
     if (fontData)
@@ -186,7 +187,11 @@
                         m_svgFontFaceElement = fontFaceElement;
                     }
 
-                    fontData = SimpleFontData::create(SVGFontData::create(fontFaceElement), fontDescription.effectiveFontSize(), syntheticBold, syntheticItalic);
+                    fontData = SimpleFontData::create(
+                        SVGFontData::create(fontFaceElement),
+                        fontDescription.effectiveFontSize(),
+                        fontDescription.isSyntheticBold(),
+                        fontDescription.isSyntheticItalic());
                 }
             } else
 #endif
@@ -195,22 +200,30 @@
                 if (!m_font->ensureCustomFontData())
                     return 0;
 
-                fontData = SimpleFontData::create(m_font->platformDataFromCustomData(fontDescription.effectiveFontSize(), syntheticBold, syntheticItalic,
-                    fontDescription.orientation(), fontDescription.widthVariant()), true, false);
+                fontData = SimpleFontData::create(
+                    m_font->platformDataFromCustomData(fontDescription.effectiveFontSize(),
+                        fontDescription.isSyntheticBold(), fontDescription.isSyntheticItalic(),
+                        fontDescription.orientation(), fontDescription.widthVariant()), CustomFontData::create(false));
             }
         } else {
 #if ENABLE(SVG_FONTS)
             // In-Document SVG Fonts
-            if (m_svgFontFaceElement)
-                fontData = SimpleFontData::create(SVGFontData::create(m_svgFontFaceElement.get()), fontDescription.effectiveFontSize(), syntheticBold, syntheticItalic);
+            if (m_svgFontFaceElement) {
+                fontData = SimpleFontData::create(
+                    SVGFontData::create(m_svgFontFaceElement.get()),
+                    fontDescription.effectiveFontSize(),
+                    fontDescription.isSyntheticBold(),
+                    fontDescription.isSyntheticItalic());
+            }
 #endif
         }
     } else {
         // This temporary font is not retained and should not be returned.
         FontCachePurgePreventer fontCachePurgePreventer;
         SimpleFontData* temporaryFont = fontCache()->getNonRetainedLastResortFallbackFont(fontDescription);
-        fontData = SimpleFontData::create(temporaryFont->platformData(), true, true);
-        fontData->setCSSFontFaceSource(this);
+        RefPtr<CSSCustomFontData> cssFontData = CSSCustomFontData::create(true);
+        cssFontData->setCSSFontFaceSource(this);
+        fontData = SimpleFontData::create(temporaryFont->platformData(), cssFontData);
     }
 
     return fontData; // No release, because fontData is a reference to a RefPtr that is held in the m_fontDataTable.
@@ -233,13 +246,6 @@
 }
 #endif
 
-bool CSSFontFaceSource::isDecodeError() const
-{
-    if (m_font)
-        return m_font->status() == Resource::DecodeError;
-    return false;
-}
-
 bool CSSFontFaceSource::ensureFontData()
 {
     if (!m_font)
@@ -255,13 +261,13 @@
 {
     if (!isLocal())
         return false;
-    return fontCache()->isPlatformFontAvailable(fontDescription, m_string, true);
+    return fontCache()->isPlatformFontAvailable(fontDescription, m_string);
 }
 
 void CSSFontFaceSource::willUseFontData()
 {
-    if (m_font)
-        m_font->willUseFontData();
+    if (m_face && m_font && m_font->stillNeedsLoad())
+        beginLoadingFontSoon();
 }
 
 void CSSFontFaceSource::beginLoadingFontSoon()
@@ -280,7 +286,7 @@
 void CSSFontFaceSource::FontLoadHistograms::recordLocalFont(bool loadSuccess)
 {
     if (!m_loadStartTime) {
-        WebKit::Platform::current()->histogramEnumeration("WebFont.LocalFontUsed", loadSuccess ? 1 : 0, 2);
+        blink::Platform::current()->histogramEnumeration("WebFont.LocalFontUsed", loadSuccess ? 1 : 0, 2);
         m_loadStartTime = -1; // Do not count this font again.
     }
 }
@@ -289,14 +295,14 @@
 {
     if (m_loadStartTime > 0 && font && !font->isLoading()) {
         int duration = static_cast<int>(currentTimeMS() - m_loadStartTime);
-        WebKit::Platform::current()->histogramCustomCounts(histogramName(font), duration, 0, 10000, 50);
+        blink::Platform::current()->histogramCustomCounts(histogramName(font), duration, 0, 10000, 50);
         m_loadStartTime = -1;
 
         enum { Miss, Hit, DataUrl, CacheHitEnumMax };
         int histogramValue = font->url().protocolIsData() ? DataUrl
             : font->response().wasCached() ? Hit
             : Miss;
-        WebKit::Platform::current()->histogramEnumeration("WebFont.CacheHit", histogramValue, CacheHitEnumMax);
+        blink::Platform::current()->histogramEnumeration("WebFont.CacheHit", histogramValue, CacheHitEnumMax);
     }
 }
 
diff --git a/Source/core/css/CSSFontFaceSource.h b/Source/core/css/CSSFontFaceSource.h
index a30f994..9635f93 100644
--- a/Source/core/css/CSSFontFaceSource.h
+++ b/Source/core/css/CSSFontFaceSource.h
@@ -55,14 +55,12 @@
     bool isLoaded() const;
     bool isValid() const;
 
-    const AtomicString& string() const { return m_string; }
-
     void setFontFace(CSSFontFace* face) { m_face = face; }
 
     virtual void didStartFontLoad(FontResource*) OVERRIDE;
     virtual void fontLoaded(FontResource*);
 
-    PassRefPtr<SimpleFontData> getFontData(const FontDescription&, bool syntheticBold, bool syntheticItalic, CSSFontSelector*);
+    PassRefPtr<SimpleFontData> getFontData(const FontDescription&, CSSFontSelector*);
 
     void pruneTable();
 
@@ -73,7 +71,6 @@
     void setHasExternalSVGFont(bool value) { m_hasExternalSVGFont = value; }
 #endif
 
-    bool isDecodeError() const;
     bool ensureFontData();
     bool isLocalFontAvailable(const FontDescription&);
     void willUseFontData();
diff --git a/Source/core/css/CSSFontSelector.cpp b/Source/core/css/CSSFontSelector.cpp
index 3c25503..5e2ffff 100644
--- a/Source/core/css/CSSFontSelector.cpp
+++ b/Source/core/css/CSSFontSelector.cpp
@@ -56,7 +56,7 @@
 
 void FontLoader::addFontToBeginLoading(FontResource* fontResource)
 {
-    if (!m_resourceFetcher)
+    if (!m_resourceFetcher || !fontResource->stillNeedsLoad())
         return;
 
     m_fontsToBeginLoading.append(fontResource);
@@ -70,6 +70,11 @@
 
 void FontLoader::beginLoadTimerFired(Timer<WebCore::FontLoader>*)
 {
+    loadPendingFonts();
+}
+
+void FontLoader::loadPendingFonts()
+{
     ASSERT(m_resourceFetcher);
 
     Vector<ResourcePtr<FontResource> > fontsToBeginLoading;
@@ -151,12 +156,56 @@
     m_cssSegmentedFontFaceCache.addFontFaceRule(this, fontFaceRule);
 }
 
+void CSSFontSelector::removeFontFaceRule(const StyleRuleFontFace* fontFaceRule)
+{
+    m_cssSegmentedFontFaceCache.removeFontFaceRule(fontFaceRule);
+}
+
+static AtomicString familyNameFromSettings(Settings* settings, const FontDescription& fontDescription, const AtomicString& genericFamilyName)
+{
+    if (!settings)
+        return emptyAtom;
+
+    UScriptCode script = fontDescription.script();
+
+    if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
+        return settings->standardFontFamily(script);
+
+#if OS(ANDROID)
+    return FontCache::getGenericFamilyNameForScript(genericFamilyName, script);
+#else
+    if (genericFamilyName == FontFamilyNames::webkit_serif)
+        return settings->serifFontFamily(script);
+    if (genericFamilyName == FontFamilyNames::webkit_sans_serif)
+        return settings->sansSerifFontFamily(script);
+    if (genericFamilyName == FontFamilyNames::webkit_cursive)
+        return settings->cursiveFontFamily(script);
+    if (genericFamilyName == FontFamilyNames::webkit_fantasy)
+        return settings->fantasyFontFamily(script);
+    if (genericFamilyName == FontFamilyNames::webkit_monospace)
+        return settings->fixedFontFamily(script);
+    if (genericFamilyName == FontFamilyNames::webkit_pictograph)
+        return settings->pictographFontFamily(script);
+    if (genericFamilyName == FontFamilyNames::webkit_standard)
+        return settings->standardFontFamily(script);
+#endif
+    return emptyAtom;
+}
+
 PassRefPtr<FontData> CSSFontSelector::getFontData(const FontDescription& fontDescription, const AtomicString& familyName)
 {
     if (!m_document || !m_document->frame())
         return 0;
 
-    return m_cssSegmentedFontFaceCache.getFontData(m_document->frame()->settings(), fontDescription, familyName);
+    if (CSSSegmentedFontFace* face = m_cssSegmentedFontFaceCache.getFontFace(fontDescription, familyName))
+        return face->getFontData(fontDescription);
+
+    // Try to return the correct font based off our settings, in case we were handed the generic font family name.
+    AtomicString settingsFamilyName = familyNameFromSettings(m_document->frame()->settings(), fontDescription, familyName);
+    if (settingsFamilyName.isEmpty())
+        return 0;
+
+    return fontCache()->getFontResourceData(fontDescription, settingsFamilyName);
 }
 
 CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& familyName)
@@ -182,4 +231,9 @@
     m_fontLoader.addFontToBeginLoading(font);
 }
 
+void CSSFontSelector::loadPendingFonts()
+{
+    m_fontLoader.loadPendingFonts();
+}
+
 }
diff --git a/Source/core/css/CSSFontSelector.h b/Source/core/css/CSSFontSelector.h
index 6df1ac6..1bdd88d 100644
--- a/Source/core/css/CSSFontSelector.h
+++ b/Source/core/css/CSSFontSelector.h
@@ -49,6 +49,7 @@
     explicit FontLoader(ResourceFetcher*);
 
     void addFontToBeginLoading(FontResource*);
+    void loadPendingFonts();
 
     void clearResourceFetcher();
 
@@ -77,6 +78,7 @@
     void clearDocument();
 
     void addFontFaceRule(const StyleRuleFontFace*);
+    void removeFontFaceRule(const StyleRuleFontFace*);
 
     void fontLoaded();
     virtual void fontCacheInvalidated();
@@ -87,6 +89,7 @@
     Document* document() const { return m_document; }
 
     void beginLoadingFontSoon(FontResource*);
+    void loadPendingFonts();
 
 private:
     explicit CSSFontSelector(Document*);
diff --git a/Source/core/css/CSSGrammar.y b/Source/core/css/CSSGrammar.y
index ad5e331..50d92d2 100644
--- a/Source/core/css/CSSGrammar.y
+++ b/Source/core/css/CSSGrammar.y
@@ -99,6 +99,7 @@
     return 1;
 }
 
+#if YYDEBUG > 0
 static inline bool isCSSTokenAString(int yytype)
 {
     switch (yytype) {
@@ -125,6 +126,7 @@
         return false;
     }
 }
+#endif
 
 inline static CSSParserValue makeOperatorValue(int value)
 {
@@ -135,6 +137,15 @@
     return v;
 }
 
+inline static CSSParserValue makeIdentValue(CSSParserString string)
+{
+    CSSParserValue v;
+    v.id = cssValueKeywordID(string);
+    v.unit = CSSPrimitiveValue::CSS_IDENT;
+    v.string = string;
+    return v;
+}
+
 %}
 
 %expect 0
@@ -170,7 +181,6 @@
 %token MEDIA_SYM
 %token SUPPORTS_SYM
 %token FONT_FACE_SYM
-%token HOST_SYM
 %token CHARSET_SYM
 %token NAMESPACE_SYM
 %token VIEWPORT_RULE_SYM
@@ -259,14 +269,12 @@
 %token <string> MAXFUNCTION
 %token <string> VARFUNCTION
 %token <string> VAR_DEFINITION
-%token <string> PARTFUNCTION
 %token <string> HOSTFUNCTION
 
 %token <string> UNICODERANGE
 
 %type <relation> combinator
 
-%type <rule> charset
 %type <rule> ruleset
 %type <rule> media
 %type <rule> import
@@ -274,9 +282,7 @@
 %type <rule> page
 %type <rule> margin_box
 %type <rule> font_face
-%type <rule> host
 %type <rule> keyframes
-%type <rule> invalid_rule
 %type <rule> rule
 %type <rule> valid_rule
 %type <ruleList> block_rule_body
@@ -285,10 +291,13 @@
 %type <ruleList> region_block_rule_list
 %type <rule> block_rule
 %type <rule> block_valid_rule
+%type <rule> region_block_rule
+%type <rule> region_block_valid_rule
 %type <rule> region
 %type <rule> supports
 %type <rule> viewport
 %type <rule> filter
+%type <boolean> keyframes_rule_start
 
 %type <string> maybe_ns_prefix
 
@@ -370,6 +379,9 @@
 
 %type <location> error_location
 
+%type <valueList> ident_list
+%type <value> track_names_list
+
 %%
 
 stylesheet:
@@ -453,11 +465,6 @@
   | maybe_sgml WHITESPACE
   ;
 
-maybe_charset:
-  /* empty */
-  | charset
-  ;
-
 closing_brace:
     '}'
   | %prec LOWEST_PREC TOKEN_EOF
@@ -478,16 +485,14 @@
   | TOKEN_EOF
   ;
 
-charset:
-  CHARSET_SYM maybe_space STRING maybe_space semi_or_eof {
-     if (parser->m_styleSheet)
-         parser->m_styleSheet->parserSetEncodingFromCharsetRule($3);
-     parser->startEndUnknownRule();
-     $$ = 0;
-  }
-  | CHARSET_SYM at_rule_recovery {
-     $$ = 0;
-  }
+maybe_charset:
+    /* empty */
+  | CHARSET_SYM maybe_space STRING maybe_space semi_or_eof {
+       if (parser->m_styleSheet)
+           parser->m_styleSheet->parserSetEncodingFromCharsetRule($3);
+       parser->startEndUnknownRule();
+    }
+  | CHARSET_SYM at_rule_recovery
   ;
 
 rule_list:
@@ -508,54 +513,78 @@
   | import
   | region
   | supports
-  | host
   | viewport
   | filter
   ;
 
-rule:
-    valid_rule {
-        parser->m_hadSyntacticallyValidCSSRule = true;
+before_rule:
+    /* empty */ {
+        parser->startRule();
     }
-  | invalid_rule
+  ;
+
+rule:
+    before_rule valid_rule {
+        $$ = $2;
+        parser->m_hadSyntacticallyValidCSSRule = true;
+        parser->endRule(!!$$);
+    }
+  | before_rule invalid_rule {
+        $$ = 0;
+        parser->endRule(false);
+    }
   ;
 
 block_rule_body:
     block_rule_list
-  | block_rule_list error error_location rule_error_recovery {
-        parser->reportError($3, CSSParser::InvalidRuleError);
-    }
+  | block_rule_list block_rule_recovery
     ;
 
 block_rule_list:
     /* empty */ { $$ = 0; }
   | block_rule_list block_rule maybe_sgml {
-      $$ = $1;
-      if ($2) {
-          if (!$$)
-              $$ = parser->createRuleList();
-          $$->append($2);
-      }
+      $$ = parser->appendRule($1, $2);
     }
     ;
 
 region_block_rule_body:
     region_block_rule_list
-  | region_block_rule_list error error_location rule_error_recovery {
-        parser->reportError($3, CSSParser::InvalidRuleError);
-    }
+  | region_block_rule_list block_rule_recovery
     ;
 
 region_block_rule_list:
     /* empty */ { $$ = 0; }
-  | region_block_rule_list block_valid_rule maybe_sgml {
-      $$ = $1;
-      if ($2) {
-          if (!$$)
-              $$ = parser->createRuleList();
-          $$->append($2);
-      }
-  }
+  | region_block_rule_list region_block_rule maybe_sgml {
+        $$ = parser->appendRule($1, $2);
+    }
+  ;
+
+region_block_rule:
+    before_rule region_block_valid_rule {
+        $$ = $2;
+        parser->endRule(!!$$);
+    }
+  | before_rule invalid_rule {
+        $$ = 0;
+        parser->endRule(false);
+    }
+  ;
+
+block_rule_recovery:
+    before_rule invalid_rule_header {
+        parser->endRule(false);
+    }
+  ;
+
+region_block_valid_rule:
+    ruleset
+  | page
+  | font_face
+  | media
+  | keyframes
+  | supports
+  | viewport
+  | filter
   ;
 
 block_valid_rule:
@@ -567,22 +596,20 @@
   | supports
   | viewport
   | filter
-  ;
-
-block_rule:
-    block_valid_rule
-  | invalid_rule
   | namespace
-  | import
   | region
   ;
 
-at_import_header_end_maybe_space:
-    maybe_space {
-        parser->endRuleHeader();
-        parser->startRuleBody();
+block_rule:
+    before_rule block_valid_rule {
+        $$ = $2;
+        parser->endRule(!!$$);
     }
-    ;
+  | before_rule invalid_rule {
+        $$ = 0;
+        parser->endRule(false);
+    }
+  ;
 
 before_import_rule:
     /* empty */ {
@@ -590,35 +617,25 @@
     }
     ;
 
-import:
-    before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list semi_or_eof {
-        $$ = parser->createImportRule($4, $7);
-    }
-  | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list invalid_block {
-        $$ = 0;
-        parser->endRuleBody(true);
-    }
-  | before_import_rule IMPORT_SYM at_rule_recovery {
-        $$ = 0;
-        parser->endRuleBody(true);
+import_rule_start:
+    before_import_rule IMPORT_SYM maybe_space {
+        parser->endRuleHeader();
+        parser->startRuleBody();
     }
   ;
 
-before_namespace_rule:
-    /* empty */ {
-        // FIXME: There should be parser->startRuleHeader.
+import:
+    import_rule_start string_or_uri maybe_space location_label maybe_media_list semi_or_eof {
+        $$ = parser->createImportRule($2, $5);
     }
-    ;
+  | import_rule_start string_or_uri maybe_space location_label maybe_media_list invalid_block {
+        $$ = 0;
+    }
+  ;
 
 namespace:
-    before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space semi_or_eof {
-        parser->addNamespace($4, $5);
-        $$ = 0;
-    }
-  | before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space invalid_block {
-        $$ = 0;
-    }
-  | before_namespace_rule NAMESPACE_SYM at_rule_recovery {
+    NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space semi_or_eof {
+        parser->addNamespace($3, $4);
         $$ = 0;
     }
   ;
@@ -759,20 +776,12 @@
     }
     ;
 
+media_rule_start:
+    before_media_rule MEDIA_SYM maybe_space;
+
 media:
-    before_media_rule MEDIA_SYM maybe_space location_label media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
-        $$ = parser->createMediaRule($5, $10);
-    }
-    | before_media_rule MEDIA_SYM at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space block_rule_body closing_brace {
-        $$ = parser->createMediaRule(0, $7);
-    }
-    | before_media_rule MEDIA_SYM maybe_space location_label media_list semi_or_eof {
-        $$ = 0;
-        parser->endRuleBody(true);
-    }
-    | before_media_rule MEDIA_SYM at_rule_recovery {
-        $$ = 0;
-        parser->endRuleBody(true);
+    media_rule_start maybe_media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
+        $$ = parser->createMediaRule($2, $7);
     }
     ;
 
@@ -784,12 +793,6 @@
     before_supports_rule SUPPORTS_SYM maybe_space supports_condition at_supports_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
         $$ = parser->createSupportsRule($4, $9);
     }
-    | before_supports_rule SUPPORTS_SYM error error_location rule_error_recovery at_rule_end {
-        $$ = 0;
-        parser->reportError($4, CSSParser::InvalidSupportsConditionError);
-        parser->endRuleBody(true);
-        parser->popSupportsRuleData();
-    }
     ;
 
 before_supports_rule:
@@ -875,21 +878,18 @@
     }
     ;
 
+keyframes_rule_start:
+    before_keyframes_rule KEYFRAMES_SYM maybe_space {
+        $$ = false;
+    }
+  | before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space {
+        $$ = true;
+    }
+    ;
+
 keyframes:
-    before_keyframes_rule KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
-        $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($10), false /* isPrefixed */);
-    }
-  |
-    before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
-        $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($10), true /* isPrefixed */);
-    }
-  | before_keyframes_rule KEYFRAMES_SYM at_rule_recovery {
-        $$ = 0;
-        parser->endRuleBody(true);
-    }
-  | before_keyframes_rule WEBKIT_KEYFRAMES_SYM at_rule_recovery {
-        $$ = 0;
-        parser->endRuleBody(true);
+    keyframes_rule_start keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
+        $$ = parser->createKeyframesRule($2, parser->sinkFloatingKeyframeVector($8), $1 /* isPrefixed */);
     }
     ;
 
@@ -973,13 +973,8 @@
             parser->clearProperties();
             // Also clear margin at-rules here once we fully implement margin at-rules parsing.
             $$ = 0;
-            parser->endRuleBody(true);
         }
     }
-    | before_page_rule PAGE_SYM at_rule_recovery {
-      parser->endRuleBody(true);
-      $$ = 0;
-    }
     ;
 
 page_selector:
@@ -1077,27 +1072,6 @@
     '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
         $$ = parser->createFontFaceRule();
     }
-    | before_font_face_rule FONT_FACE_SYM at_rule_recovery {
-      $$ = 0;
-      parser->endRuleBody(true);
-    }
-;
-
-before_host_rule:
-    /* empty */ {
-        parser->startRuleHeader(CSSRuleSourceData::HOST_RULE);
-    }
-    ;
-
-host:
-    before_host_rule HOST_SYM at_rule_header_end_maybe_space
-    '{' at_rule_body_start maybe_space block_rule_body closing_brace {
-        $$ = parser->createHostRule($7);
-    }
-    | before_host_rule HOST_SYM at_rule_recovery {
-        $$ = 0;
-        parser->endRuleBody(true);
-    }
     ;
 
 before_viewport_rule:
@@ -1113,11 +1087,6 @@
         $$ = parser->createViewportRule();
         parser->markViewportRuleBodyEnd();
     }
-    | before_viewport_rule VIEWPORT_RULE_SYM at_rule_recovery {
-        $$ = 0;
-        parser->endRuleBody(true);
-        parser->markViewportRuleBodyEnd();
-    }
 ;
 
 region_selector:
@@ -1137,10 +1106,6 @@
     before_region_rule WEBKIT_REGION_RULE_SYM maybe_space region_selector at_rule_header_end '{' at_rule_body_start maybe_space region_block_rule_body closing_brace {
         $$ = parser->createRegionRule($4, $9);
     }
-  | before_region_rule WEBKIT_REGION_RULE_SYM at_rule_recovery {
-        $$ = 0;
-        parser->endRuleBody(true);
-    }
 ;
 
 before_filter_rule:
@@ -1156,9 +1121,6 @@
         parser->m_inFilterRule = false;
         $$ = parser->createFilterRule($4);
     }
-  | before_filter_rule WEBKIT_FILTER_RULE_SYM at_rule_recovery {
-        $$ = 0;
-    }
     ;
 
 combinator:
@@ -1322,7 +1284,7 @@
 
 element_name:
     IDENT {
-        if (parser->m_context.isHTMLDocument)
+        if (parser->m_context.isHTMLDocument())
             parser->tokenToLowerCase($1);
         $$ = $1;
     }
@@ -1343,7 +1305,7 @@
     IDSEL {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::Id);
-        if (isQuirksModeBehavior(parser->m_context.mode))
+        if (isQuirksModeBehavior(parser->m_context.mode()))
             parser->tokenToLowerCase($1);
         $$->setValue($1);
     }
@@ -1353,7 +1315,7 @@
         } else {
             $$ = parser->createFloatingSelector();
             $$->setMatch(CSSSelector::Id);
-            if (isQuirksModeBehavior(parser->m_context.mode))
+            if (isQuirksModeBehavior(parser->m_context.mode()))
                 parser->tokenToLowerCase($1);
             $$->setValue($1);
         }
@@ -1367,7 +1329,7 @@
     '.' IDENT {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::Class);
-        if (isQuirksModeBehavior(parser->m_context.mode))
+        if (isQuirksModeBehavior(parser->m_context.mode()))
             parser->tokenToLowerCase($2);
         $$->setValue($2);
     }
@@ -1375,7 +1337,7 @@
 
 attr_name:
     IDENT maybe_space {
-        if (parser->m_context.isHTMLDocument)
+        if (parser->m_context.isHTMLDocument())
             parser->tokenToLowerCase($1);
         $$ = $1;
     }
@@ -1577,21 +1539,6 @@
     | ':' NOTFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
-    | ':' ':' PARTFUNCTION maybe_space IDENT maybe_space closing_parenthesis {
-        $$ = parser->createFloatingSelector();
-        $$->setMatch(CSSSelector::PseudoElement);
-        $$->setArgument($5);
-        if ($5.startsWithIgnoringCase("-webkit"))
-            $$->setMatchUserAgentOnly();
-        parser->tokenToLowerCase($3);
-        $$->setValue($3);
-        CSSSelector::PseudoType type = $$->pseudoType();
-        if (type != CSSSelector::PseudoPart)
-            YYERROR;
-    }
-    | ':' ':' PARTFUNCTION selector_recovery closing_parenthesis {
-        YYERROR;
-    }
     | ':' HOSTFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
@@ -1703,6 +1650,29 @@
     | /* empty */ { $$ = false; }
   ;
 
+ident_list:
+    IDENT maybe_space {
+        $$ = parser->createFloatingValueList();
+        $$->addValue(makeIdentValue($1));
+    }
+    | ident_list IDENT maybe_space {
+        $$ = $1;
+        $$->addValue(makeIdentValue($2));
+    }
+    ;
+
+track_names_list:
+    '(' maybe_space closing_parenthesis {
+        $$.setFromValueList(parser->sinkFloatingValueList(parser->createFloatingValueList()));
+    }
+    | '(' maybe_space ident_list closing_parenthesis {
+        $$.setFromValueList(parser->sinkFloatingValueList($3));
+    }
+    | '(' maybe_space expr_recovery closing_parenthesis {
+        YYERROR;
+    }
+  ;
+
 expr:
     term {
         $$ = parser->createFloatingValueList();
@@ -1738,11 +1708,7 @@
   unary_term maybe_space
   | unary_operator unary_term maybe_space { $$ = $2; $$.fValue *= $1; }
   | STRING maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_STRING; }
-  | IDENT maybe_space {
-      $$.id = cssValueKeywordID($1);
-      $$.unit = CSSPrimitiveValue::CSS_IDENT;
-      $$.string = $1;
-  }
+  | IDENT maybe_space { $$ = makeIdentValue($1); }
   /* We might need to actually parse the number from a dimension, but we can't just put something that uses $$.string into unary_term. */
   | DIMEN maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_DIMENSION; }
   | unary_operator DIMEN maybe_space { $$.id = CSSValueInvalid; $$.string = $2; $$.unit = CSSPrimitiveValue::CSS_DIMENSION; }
@@ -1765,6 +1731,7 @@
   | '%' maybe_space { /* Handle width: %; */
       $$.id = CSSValueInvalid; $$.unit = 0;
   }
+  | track_names_list maybe_space
   ;
 
 unary_term:
@@ -1928,16 +1895,42 @@
   | at_invalid_rule_header_end invalid_block
     ;
 
+regular_invalid_at_rule_header:
+    keyframes_rule_start at_rule_header_recovery
+  | before_page_rule PAGE_SYM at_rule_header_recovery
+  | before_font_face_rule FONT_FACE_SYM at_rule_header_recovery
+  | before_supports_rule SUPPORTS_SYM error error_location rule_error_recovery {
+        parser->reportError($4, CSSParser::InvalidSupportsConditionError);
+        parser->popSupportsRuleData();
+    }
+  | before_viewport_rule VIEWPORT_RULE_SYM at_rule_header_recovery {
+        parser->markViewportRuleBodyEnd();
+    }
+  | before_filter_rule WEBKIT_FILTER_RULE_SYM at_rule_header_recovery
+  | import_rule_start at_rule_header_recovery
+  | NAMESPACE_SYM at_rule_header_recovery
+  | before_region_rule WEBKIT_REGION_RULE_SYM at_rule_header_recovery
+  | error_location invalid_at at_rule_header_recovery {
+        parser->resumeErrorLogging();
+        parser->reportError($1, CSSParser::InvalidRuleError);
+    }
+  ;
+
 invalid_rule:
     error error_location rule_error_recovery at_invalid_rule_header_end invalid_block {
         parser->reportError($2, CSSParser::InvalidRuleError);
-        $$ = 0;
     }
-  | error_location invalid_at rule_error_recovery at_invalid_rule_header_end at_rule_end {
-        parser->resumeErrorLogging();
-        parser->reportError($1, CSSParser::InvalidRuleError);
-        $$ = 0;
+  | regular_invalid_at_rule_header at_invalid_rule_header_end ';'
+  | regular_invalid_at_rule_header at_invalid_rule_header_end invalid_block
+  | media_rule_start maybe_media_list ';'
+    ;
+
+invalid_rule_header:
+    error error_location rule_error_recovery at_invalid_rule_header_end {
+        parser->reportError($2, CSSParser::InvalidRuleError);
     }
+  | regular_invalid_at_rule_header at_invalid_rule_header_end
+  | media_rule_start maybe_media_list
     ;
 
 at_invalid_rule_header_end:
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.cpp b/Source/core/css/CSSGridLineNamesValue.cpp
similarity index 76%
copy from Source/core/workers/WorkerGlobalScopeProxy.cpp
copy to Source/core/css/CSSGridLineNamesValue.cpp
index 06471bb..3a2877d 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ b/Source/core/css/CSSGridLineNamesValue.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Igalia, S.L. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,10 +29,24 @@
  */
 
 #include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
+#include "core/css/CSSGridLineNamesValue.h"
 
 namespace WebCore {
 
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
+String CSSGridLineNamesValue::customCSSText() const
+{
+    return "(" + CSSValueList::customCSSText() + ")";
+}
 
-} // namespace WebCore
+CSSGridLineNamesValue::CSSGridLineNamesValue()
+    : CSSValueList(GridLineNamesClass, SpaceSeparator)
+{
+}
+
+PassRefPtr<CSSGridLineNamesValue> CSSGridLineNamesValue::cloneForCSSOM() const
+{
+    return adoptRef(new CSSGridLineNamesValue(*this));
+}
+
+}
+
diff --git a/Source/core/rendering/RenderingConfiguration.cpp b/Source/core/css/CSSGridLineNamesValue.h
similarity index 71%
copy from Source/core/rendering/RenderingConfiguration.cpp
copy to Source/core/css/CSSGridLineNamesValue.h
index 77060a3..da97e05 100644
--- a/Source/core/rendering/RenderingConfiguration.cpp
+++ b/Source/core/css/CSSGridLineNamesValue.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Igalia, S.L. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,29 +28,31 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/rendering/RenderingConfiguration.h"
+#ifndef CSSGridLineNamesValue_h
+#define CSSGridLineNamesValue_h
 
-#include "core/dom/Document.h"
+#include "core/css/CSSValueList.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
-RenderingConfiguration::RenderingConfiguration()
-    : m_inQuirksMode(false)
-    , m_paginated(false)
-    , m_printing(false)
-{
+class CSSGridLineNamesValue : public CSSValueList {
+public:
+    static PassRefPtr<CSSGridLineNamesValue> create()
+    {
+        return adoptRef(new CSSGridLineNamesValue());
+    }
+
+    String customCSSText() const;
+
+    PassRefPtr<CSSGridLineNamesValue> cloneForCSSOM() const;
+
+private:
+    CSSGridLineNamesValue();
+};
+
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSGridLineNamesValue, isGridLineNamesValue());
 }
 
-RenderingConfiguration::~RenderingConfiguration()
-{
-}
 
-void RenderingConfiguration::update(Document& document)
-{
-    m_inQuirksMode = document.inQuirksMode();
-    m_paginated = document.paginated();
-    m_printing = document.printing();
-}
-
-}
+#endif
diff --git a/Source/core/css/CSSGroupingRule.cpp b/Source/core/css/CSSGroupingRule.cpp
index b858baa..1fbc5f8 100644
--- a/Source/core/css/CSSGroupingRule.cpp
+++ b/Source/core/css/CSSGroupingRule.cpp
@@ -58,12 +58,12 @@
     }
 }
 
-unsigned CSSGroupingRule::insertRule(const String& ruleString, unsigned index, ExceptionState& es)
+unsigned CSSGroupingRule::insertRule(const String& ruleString, unsigned index, ExceptionState& exceptionState)
 {
     ASSERT(m_childRuleCSSOMWrappers.size() == m_groupRule->childRules().size());
 
     if (index > m_groupRule->childRules().size()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "the index " + String::number(index) + " must be less than or equal to the length of the rule list."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "the index " + String::number(index) + " must be less than or equal to the length of the rule list."));
         return 0;
     }
 
@@ -71,7 +71,7 @@
     CSSParser parser(parserContext(), UseCounter::getFrom(styleSheet));
     RefPtr<StyleRuleBase> newRule = parser.parseRule(styleSheet ? styleSheet->contents() : 0, ruleString);
     if (!newRule) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "the rule '" + ruleString + "' is invalid and cannot be parsed."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "the rule '" + ruleString + "' is invalid and cannot be parsed."));
         return 0;
     }
 
@@ -79,7 +79,7 @@
         // FIXME: an HierarchyRequestError should also be thrown for a @charset or a nested
         // @media rule. They are currently not getting parsed, resulting in a SyntaxError
         // to get raised above.
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "'@import' rules cannot be inserted inside a group rule."));
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "'@import' rules cannot be inserted inside a group rule."));
         return 0;
     }
     CSSStyleSheet::RuleMutationScope mutationScope(this);
@@ -90,12 +90,12 @@
     return index;
 }
 
-void CSSGroupingRule::deleteRule(unsigned index, ExceptionState& es)
+void CSSGroupingRule::deleteRule(unsigned index, ExceptionState& exceptionState)
 {
     ASSERT(m_childRuleCSSOMWrappers.size() == m_groupRule->childRules().size());
 
     if (index >= m_groupRule->childRules().size()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteRule", "CSSGroupingRule", "the index " + String::number(index) + " is greated than the length of the rule list."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteRule", "CSSGroupingRule", "the index " + String::number(index) + " is greated than the length of the rule list."));
         return;
     }
 
diff --git a/Source/core/css/CSSHostRule.cpp b/Source/core/css/CSSHostRule.cpp
deleted file mode 100644
index f75f80e..0000000
--- a/Source/core/css/CSSHostRule.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * (C) 2002-2003 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2002, 2005, 2006, 2012 Apple Computer, Inc.
- * Copyright (C) 2006 Samuel Weinig (sam@webkit.org)
- *
- * 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.
- */
-
-#include "config.h"
-#include "core/css/CSSHostRule.h"
-
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-CSSHostRule::CSSHostRule(StyleRuleHost* hostRule, CSSStyleSheet* parent)
-    : CSSGroupingRule(hostRule, parent)
-{
-}
-
-String CSSHostRule::cssText() const
-{
-    StringBuilder result;
-    result.appendLiteral("@host { \n");
-    appendCSSTextForItems(result);
-    result.append('}');
-    return result.toString();
-}
-
-} // namespace WebCore
-
diff --git a/Source/core/css/CSSHostRule.h b/Source/core/css/CSSHostRule.h
deleted file mode 100644
index 9dafa63..0000000
--- a/Source/core/css/CSSHostRule.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * (C) 2002-2003 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2002, 2006, 2008, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig (sam@webkit.org)
- *
- * 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.
- */
-
-#ifndef CSSHostRule_h
-#define CSSHostRule_h
-
-#include "core/css/CSSGroupingRule.h"
-
-namespace WebCore {
-
-class CSSHostRule : public CSSGroupingRule {
-public:
-    static PassRefPtr<CSSHostRule> create(StyleRuleHost* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSHostRule(rule, sheet)); }
-
-    virtual CSSRule::Type type() const OVERRIDE { return CSSRule::HOST_RULE; }
-    virtual String cssText() const OVERRIDE;
-
-private:
-    CSSHostRule(StyleRuleHost*, CSSStyleSheet*);
-};
-
-
-} // namespace WebCore
-
-#endif // CSSHostRule_h
diff --git a/Source/core/css/CSSHostRule.idl b/Source/core/css/CSSHostRule.idl
deleted file mode 100644
index d86b738..0000000
--- a/Source/core/css/CSSHostRule.idl
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- *
- * 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.
- */
-
-// Introduced in Shadow DOM spec:
-interface CSSHostRule : CSSRule {
-    readonly attribute CSSRuleList cssRules;
-
-    [RaisesException] unsigned long      insertRule(DOMString rule, unsigned long index);
-    [RaisesException] void               deleteRule(unsigned long index);
-};
-
diff --git a/Source/core/css/CSSImageGeneratorValue.cpp b/Source/core/css/CSSImageGeneratorValue.cpp
index 0fb08b1..974592c 100644
--- a/Source/core/css/CSSImageGeneratorValue.cpp
+++ b/Source/core/css/CSSImageGeneratorValue.cpp
@@ -63,7 +63,7 @@
 {
     ASSERT(renderer);
     RenderObjectSizeCountMap::iterator it = m_clients.find(renderer);
-    ASSERT(it != m_clients.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(it != m_clients.end());
 
     IntSize removedImageSize;
     SizeAndCount& sizeCount = it->value;
diff --git a/Source/core/css/CSSImageGeneratorValue.h b/Source/core/css/CSSImageGeneratorValue.h
index ea989b3..d5803d3 100644
--- a/Source/core/css/CSSImageGeneratorValue.h
+++ b/Source/core/css/CSSImageGeneratorValue.h
@@ -27,7 +27,7 @@
 #define CSSImageGeneratorValue_h
 
 #include "core/css/CSSValue.h"
-#include "core/platform/graphics/IntSizeHash.h"
+#include "platform/geometry/IntSizeHash.h"
 #include "wtf/HashCountedSet.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/css/CSSImageSetValue.cpp b/Source/core/css/CSSImageSetValue.cpp
index f3c55ea..ef63219 100644
--- a/Source/core/css/CSSImageSetValue.cpp
+++ b/Source/core/css/CSSImageSetValue.cpp
@@ -49,7 +49,7 @@
 CSSImageSetValue::~CSSImageSetValue()
 {
     if (m_imageSet && m_imageSet->isImageResourceSet())
-        static_cast<StyleFetchedImageSet*>(m_imageSet.get())->clearImageSetValue();
+        toStyleFetchedImageSet(m_imageSet)->clearImageSetValue();
 }
 
 void CSSImageSetValue::fillImageSet()
@@ -111,7 +111,7 @@
         }
     }
 
-    return (m_imageSet && m_imageSet->isImageResourceSet()) ? static_cast<StyleFetchedImageSet*>(m_imageSet.get()) : 0;
+    return (m_imageSet && m_imageSet->isImageResourceSet()) ? toStyleFetchedImageSet(m_imageSet) : 0;
 }
 
 StyleImage* CSSImageSetValue::cachedOrPendingImageSet(float deviceScaleFactor)
@@ -163,10 +163,9 @@
 {
     if (!m_imageSet || !m_imageSet->isImageResourceSet())
         return false;
-    Resource* cachedResource = static_cast<StyleFetchedImageSet*>(m_imageSet.get())->cachedImage();
-    if (!cachedResource)
-        return true;
-    return cachedResource->loadFailedOrCanceled();
+    if (Resource* cachedResource = toStyleFetchedImageSet(m_imageSet)->cachedImage())
+        return cachedResource->loadFailedOrCanceled();
+    return true;
 }
 
 CSSImageSetValue::CSSImageSetValue(const CSSImageSetValue& cloneFrom)
diff --git a/Source/core/css/CSSImageValue.cpp b/Source/core/css/CSSImageValue.cpp
index 39a1b6e..9fcfbee 100644
--- a/Source/core/css/CSSImageValue.cpp
+++ b/Source/core/css/CSSImageValue.cpp
@@ -60,33 +60,32 @@
     return m_image.get();
 }
 
-StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* loader, const ResourceLoaderOptions& options)
+StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* fetcher, const ResourceLoaderOptions& options, CORSEnabled corsEnabled)
 {
-    ASSERT(loader);
+    ASSERT(fetcher);
 
     if (!m_accessedImage) {
         m_accessedImage = true;
 
-        FetchRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
+        FetchRequest request(ResourceRequest(fetcher->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
 
-        if (options.requestOriginPolicy == PotentiallyCrossOriginEnabled)
-            updateRequestForAccessControl(request.mutableResourceRequest(), loader->document()->securityOrigin(), options.allowCredentials);
+        if (corsEnabled == PotentiallyCORSEnabled)
+            updateRequestForAccessControl(request.mutableResourceRequest(), fetcher->document()->securityOrigin(), options.allowCredentials);
 
-        if (ResourcePtr<ImageResource> cachedImage = loader->fetchImage(request))
+        if (ResourcePtr<ImageResource> cachedImage = fetcher->fetchImage(request))
             m_image = StyleFetchedImage::create(cachedImage.get());
     }
 
-    return (m_image && m_image->isImageResource()) ? static_cast<StyleFetchedImage*>(m_image.get()) : 0;
+    return (m_image && m_image->isImageResource()) ? toStyleFetchedImage(m_image) : 0;
 }
 
 bool CSSImageValue::hasFailedOrCanceledSubresources() const
 {
     if (!m_image || !m_image->isImageResource())
         return false;
-    Resource* cachedResource = static_cast<StyleFetchedImage*>(m_image.get())->cachedImage();
-    if (!cachedResource)
-        return true;
-    return cachedResource->loadFailedOrCanceled();
+    if (Resource* cachedResource = toStyleFetchedImage(m_image)->cachedImage())
+        return cachedResource->loadFailedOrCanceled();
+    return true;
 }
 
 bool CSSImageValue::equals(const CSSImageValue& other) const
diff --git a/Source/core/css/CSSImageValue.h b/Source/core/css/CSSImageValue.h
index 31665e9..a84afa5 100644
--- a/Source/core/css/CSSImageValue.h
+++ b/Source/core/css/CSSImageValue.h
@@ -38,8 +38,8 @@
     static PassRefPtr<CSSImageValue> create(const String& url, StyleImage* image) { return adoptRef(new CSSImageValue(url, image)); }
     ~CSSImageValue();
 
-    StyleFetchedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&);
-    StyleFetchedImage* cachedImage(ResourceFetcher* loader) { return cachedImage(loader, ResourceFetcher::defaultResourceOptions()); }
+    StyleFetchedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&, CORSEnabled);
+    StyleFetchedImage* cachedImage(ResourceFetcher* fetcher) { return cachedImage(fetcher, ResourceFetcher::defaultResourceOptions(), NotCORSEnabled); }
     // Returns a StyleFetchedImage if the image is cached already, otherwise a StylePendingImage.
     StyleImage* cachedOrPendingImage();
 
diff --git a/Source/core/css/CSSKeyframeRule.cpp b/Source/core/css/CSSKeyframeRule.cpp
index e665e9e..65aa307 100644
--- a/Source/core/css/CSSKeyframeRule.cpp
+++ b/Source/core/css/CSSKeyframeRule.cpp
@@ -95,7 +95,7 @@
 {
     if (!m_properties->isMutable())
         m_properties = m_properties->mutableCopy();
-    return static_cast<MutableStylePropertySet*>(m_properties.get());
+    return toMutableStylePropertySet(m_properties);
 }
 
 void StyleKeyframe::setProperties(PassRefPtr<StylePropertySet> properties)
diff --git a/Source/core/css/CSSLengthFunctions.cpp b/Source/core/css/CSSLengthFunctions.cpp
index 9cbd70e..94acda3 100644
--- a/Source/core/css/CSSLengthFunctions.cpp
+++ b/Source/core/css/CSSLengthFunctions.cpp
@@ -65,7 +65,6 @@
     case FillAvailable:
     case Auto:
         return 0;
-    case Relative:
     case Intrinsic:
     case MinIntrinsic:
     case MinContent:
@@ -94,7 +93,6 @@
     case FillAvailable:
     case Auto:
         return maximumValue;
-    case Relative:
     case Intrinsic:
     case MinIntrinsic:
     case MinContent:
@@ -134,7 +132,6 @@
         return static_cast<int>(renderView->viewportPercentageMin(length.viewportPercentageLength()));
     case ViewportPercentageMax:
         return static_cast<int>(renderView->viewportPercentageMax(length.viewportPercentageLength()));
-    case Relative:
     case Intrinsic:
     case MinIntrinsic:
     case MinContent:
diff --git a/Source/core/css/CSSMatrix.cpp b/Source/core/css/CSSMatrix.cpp
index c4b90d7..08a8391 100644
--- a/Source/core/css/CSSMatrix.cpp
+++ b/Source/core/css/CSSMatrix.cpp
@@ -43,13 +43,13 @@
     ScriptWrappable::init(this);
 }
 
-CSSMatrix::CSSMatrix(const String& s, ExceptionState& es)
+CSSMatrix::CSSMatrix(const String& s, ExceptionState& exceptionState)
 {
     ScriptWrappable::init(this);
-    setMatrixValue(s, es);
+    setMatrixValue(s, exceptionState);
 }
 
-void CSSMatrix::setMatrixValue(const String& string, ExceptionState& es)
+void CSSMatrix::setMatrixValue(const String& string, ExceptionState& exceptionState)
 {
     if (string.isEmpty())
         return;
@@ -66,24 +66,21 @@
 
         TransformOperations operations;
         if (!TransformBuilder::createTransformOperations(value.get(), 0, 0, operations)) {
-            es.throwUninformativeAndGenericDOMException(SyntaxError);
+            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
             return;
         }
 
         // Convert transform operations to a TransformationMatrix. This can fail
         // if a param has a percentage ('%')
+        if (operations.dependsOnBoxSize())
+            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         TransformationMatrix t;
-        for (unsigned i = 0; i < operations.operations().size(); ++i) {
-            if (operations.operations()[i].get()->apply(t, IntSize(0, 0))) {
-                es.throwUninformativeAndGenericDOMException(SyntaxError);
-                return;
-            }
-        }
+        operations.apply(FloatSize(0, 0), t);
 
         // set the matrix
         m_matrix = t;
     } else { // There is something there but parsing failed.
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
     }
 }
 
@@ -96,10 +93,10 @@
     return CSSMatrix::create(TransformationMatrix(m_matrix).multiply(secondMatrix->m_matrix));
 }
 
-PassRefPtr<CSSMatrix> CSSMatrix::inverse(ExceptionState& es) const
+PassRefPtr<CSSMatrix> CSSMatrix::inverse(ExceptionState& exceptionState) const
 {
     if (!m_matrix.isInvertible()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
diff --git a/Source/core/css/CSSMatrix.h b/Source/core/css/CSSMatrix.h
index e4b4e1f..92c6cb1 100644
--- a/Source/core/css/CSSMatrix.h
+++ b/Source/core/css/CSSMatrix.h
@@ -41,9 +41,9 @@
     {
         return adoptRef(new CSSMatrix(m));
     }
-    static PassRefPtr<CSSMatrix> create(const String& s, ExceptionState& es)
+    static PassRefPtr<CSSMatrix> create(const String& s, ExceptionState& exceptionState)
     {
-        return adoptRef(new CSSMatrix(s, es));
+        return adoptRef(new CSSMatrix(s, exceptionState));
     }
 
     double a() const { return m_matrix.a(); }
diff --git a/Source/core/css/CSSParser-in.cpp b/Source/core/css/CSSParser-in.cpp
index a63d5b7..52a25c7 100644
--- a/Source/core/css/CSSParser-in.cpp
+++ b/Source/core/css/CSSParser-in.cpp
@@ -41,6 +41,7 @@
 #include "core/css/CSSFontFeatureValue.h"
 #include "core/css/CSSFunctionValue.h"
 #include "core/css/CSSGradientValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
 #include "core/css/CSSGridTemplateValue.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSImageValue.h"
@@ -183,41 +184,6 @@
     bool m_hasSeenAnimationPropertyKeyword;
 };
 
-const CSSParserContext& strictCSSParserContext()
-{
-    DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (HTMLStandardMode));
-    return strictContext;
-}
-
-CSSParserContext::CSSParserContext(CSSParserMode mode, const KURL& baseURL)
-    : baseURL(baseURL)
-    , mode(mode)
-    , isHTMLDocument(false)
-    , needsSiteSpecificQuirks(false)
-    , useLegacyBackgroundSizeShorthandBehavior(false)
-{
-}
-
-CSSParserContext::CSSParserContext(const Document& document, const KURL& baseURL, const String& charset)
-    : baseURL(baseURL.isNull() ? document.baseURL() : baseURL)
-    , charset(charset)
-    , mode(document.inQuirksMode() ? HTMLQuirksMode : HTMLStandardMode)
-    , isHTMLDocument(document.isHTMLDocument())
-    , needsSiteSpecificQuirks(document.settings() ? document.settings()->needsSiteSpecificQuirks() : false)
-    , useLegacyBackgroundSizeShorthandBehavior(document.settings() ? document.settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
-{
-}
-
-bool operator==(const CSSParserContext& a, const CSSParserContext& b)
-{
-    return a.baseURL == b.baseURL
-        && a.charset == b.charset
-        && a.mode == b.mode
-        && a.isHTMLDocument == b.isHTMLDocument
-        && a.needsSiteSpecificQuirks == b.needsSiteSpecificQuirks
-        && a.useLegacyBackgroundSizeShorthandBehavior == b.useLegacyBackgroundSizeShorthandBehavior;
-}
-
 CSSParser::CSSParser(const CSSParserContext& context, UseCounter* counter)
     : m_context(context)
     , m_important(false)
@@ -235,28 +201,18 @@
     , m_ignoreErrors(false)
     , m_inFilterRule(false)
     , m_defaultNamespace(starAtom)
-    , m_parsedTextPrefixLength(0)
-    , m_parsedTextSuffixLength(0)
     , m_sourceDataHandler(0)
-    , m_parsingMode(NormalMode)
-    , m_is8BitSource(false)
-    , m_currentCharacter8(0)
-    , m_currentCharacter16(0)
     , m_source(0)
-    , m_length(0)
-    , m_token(0)
-    , m_lineNumber(0)
-    , m_tokenStartLineNumber(0)
     , m_ruleHeaderType(CSSRuleSourceData::UNKNOWN_RULE)
     , m_allowImportRules(true)
     , m_allowNamespaceDeclarations(true)
     , m_inViewport(false)
     , m_useCounter(counter)
+    , m_tokenizer(*this)
 {
 #if YYDEBUG > 0
     cssyydebug = 1;
 #endif
-    m_tokenStart.ptr8 = 0;
     CSSPropertySourceData::init();
 }
 
@@ -270,76 +226,10 @@
     deleteAllValues(m_floatingFunctions);
 }
 
-AtomicString CSSParserString::atomicSubstring(unsigned position, unsigned length) const
-{
-    ASSERT(m_length >= position + length);
-
-    if (is8Bit())
-        return AtomicString(characters8() + position, length);
-    return AtomicString(characters16() + position, length);
-}
-
-void CSSParserString::trimTrailingWhitespace()
-{
-    if (is8Bit()) {
-        while (m_length > 0 && isHTMLSpace<LChar>(m_data.characters8[m_length - 1]))
-            --m_length;
-    } else {
-        while (m_length > 0 && isHTMLSpace<UChar>(m_data.characters16[m_length - 1]))
-            --m_length;
-    }
-}
-
 void CSSParser::setupParser(const char* prefix, unsigned prefixLength, const String& string, const char* suffix, unsigned suffixLength)
 {
-    m_parsedTextPrefixLength = prefixLength;
-    m_parsedTextSuffixLength = suffixLength;
-    unsigned stringLength = string.length();
-    unsigned length = stringLength + m_parsedTextPrefixLength + m_parsedTextSuffixLength + 1;
-    m_length = length;
-
-    if (!stringLength || string.is8Bit()) {
-        m_dataStart8 = adoptArrayPtr(new LChar[length]);
-        for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
-            m_dataStart8[i] = prefix[i];
-
-        if (stringLength)
-            memcpy(m_dataStart8.get() + m_parsedTextPrefixLength, string.characters8(), stringLength * sizeof(LChar));
-
-        unsigned start = m_parsedTextPrefixLength + stringLength;
-        unsigned end = start + suffixLength;
-        for (unsigned i = start; i < end; i++)
-            m_dataStart8[i] = suffix[i - start];
-
-        m_dataStart8[length - 1] = 0;
-
-        m_is8BitSource = true;
-        m_currentCharacter8 = m_dataStart8.get();
-        m_currentCharacter16 = 0;
-        setTokenStart<LChar>(m_currentCharacter8);
-        m_lexFunc = &CSSParser::realLex<LChar>;
-        return;
-    }
-
-    m_dataStart16 = adoptArrayPtr(new UChar[length]);
-    for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
-        m_dataStart16[i] = prefix[i];
-
-    ASSERT(stringLength);
-    memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters16(), stringLength * sizeof(UChar));
-
-    unsigned start = m_parsedTextPrefixLength + stringLength;
-    unsigned end = start + suffixLength;
-    for (unsigned i = start; i < end; i++)
-        m_dataStart16[i] = suffix[i - start];
-
-    m_dataStart16[length - 1] = 0;
-
-    m_is8BitSource = false;
-    m_currentCharacter8 = 0;
-    m_currentCharacter16 = m_dataStart16.get();
-    setTokenStart<UChar>(m_currentCharacter16);
-    m_lexFunc = &CSSParser::realLex<UChar>;
+    m_tokenizer.setupTokenizer(prefix, prefixLength, string, suffix, suffixLength);
+    m_ruleHasHeader = true;
 }
 
 void CSSParser::parseSheet(StyleSheetContents* sheet, const String& string, const TextPosition& startPosition, SourceDataHandler* sourceDataHandler, bool logErrors)
@@ -349,9 +239,10 @@
     m_sourceDataHandler = sourceDataHandler;
     m_logErrors = logErrors && sheet->singleOwnerDocument() && !sheet->baseURL().isEmpty() && sheet->singleOwnerDocument()->page();
     m_ignoreErrors = false;
-    m_lineNumber = 0;
+    m_tokenizer.m_lineNumber = 0;
     m_startPosition = startPosition;
     m_source = &string;
+    m_tokenizer.m_internal = false;
     setupParser("", string, "");
     cssyyparse(this);
     sheet->shrinkToFit();
@@ -361,6 +252,7 @@
     m_lineEndings.clear();
     m_ignoreErrors = false;
     m_logErrors = false;
+    m_tokenizer.m_internal = true;
 }
 
 PassRefPtr<StyleRuleBase> CSSParser::parseRule(StyleSheetContents* sheet, const String& string)
@@ -1093,7 +985,7 @@
 }
 
 template <typename CharacterType>
-static bool parseTransformArguments(CSSTransformValue* transformValue, CharacterType* characters, unsigned length, unsigned start, unsigned expectedCount)
+static bool parseTransformTranslateArguments(CSSTransformValue* transformValue, CharacterType* characters, unsigned length, unsigned start, unsigned expectedCount)
 {
     while (expectedCount) {
         size_t end = WTF::find(characters, length, expectedCount == 1 ? ')' : ',', start);
@@ -1106,7 +998,7 @@
             return false;
         if (unit != CSSPrimitiveValue::CSS_PX && (number || unit != CSSPrimitiveValue::CSS_NUMBER))
             return false;
-        transformValue->append(cssValuePool().createValue(number, unit));
+        transformValue->append(cssValuePool().createValue(number, CSSPrimitiveValue::CSS_PX));
         start = end + 1;
         --expectedCount;
     }
@@ -1149,9 +1041,9 @@
     RefPtr<CSSTransformValue> transformValue = CSSTransformValue::create(transformType);
     bool success;
     if (string.is8Bit())
-        success = parseTransformArguments(transformValue.get(), string.characters8(), string.length(), argumentStart, expectedArgumentCount);
+        success = parseTransformTranslateArguments(transformValue.get(), string.characters8(), string.length(), argumentStart, expectedArgumentCount);
     else
-        success = parseTransformArguments(transformValue.get(), string.characters16(), string.length(), argumentStart, expectedArgumentCount);
+        success = parseTransformTranslateArguments(transformValue.get(), string.characters16(), string.length(), argumentStart, expectedArgumentCount);
     if (!success)
         return false;
     RefPtr<CSSValueList> result = CSSValueList::createSpaceSeparated();
@@ -1181,9 +1073,9 @@
 
     CSSParserContext context(document);
 
-    if (parseSimpleLengthValue(declaration, propertyID, string, important, context.mode))
+    if (parseSimpleLengthValue(declaration, propertyID, string, important, context.mode()))
         return true;
-    if (parseColorValue(declaration, propertyID, string, important, context.mode))
+    if (parseColorValue(declaration, propertyID, string, important, context.mode()))
         return true;
     if (parseKeywordValue(declaration, propertyID, string, important, context))
         return true;
@@ -1203,7 +1095,7 @@
     CSSParserContext context(cssParserMode);
     if (contextStyleSheet) {
         context = contextStyleSheet->parserContext();
-        context.mode = cssParserMode;
+        context.setMode(cssParserMode);
     }
 
     if (parseKeywordValue(declaration, propertyID, string, important, context))
@@ -1314,7 +1206,7 @@
 {
     Document& document = element->document();
     CSSParserContext context = document.elementSheet()->contents()->parserContext();
-    context.mode = (element->isHTMLElement() && !document.inQuirksMode()) ? HTMLStandardMode : HTMLQuirksMode;
+    context.setMode((element->isHTMLElement() && !document.inQuirksMode()) ? HTMLStandardMode : HTMLQuirksMode);
     return CSSParser(context, UseCounter::getFrom(&document)).parseDeclaration(string, document.elementSheet()->contents());
 }
 
@@ -1419,7 +1311,7 @@
     if (unusedEntries)
         results.remove(0, unusedEntries);
 
-    CSSParserMode mode = inViewport() ? CSSViewportRuleMode : m_context.mode;
+    CSSParserMode mode = inViewport() ? CSSViewportRuleMode : m_context.mode();
 
     return ImmutableStylePropertySet::create(results.data(), results.size(), mode);
 }
@@ -1452,7 +1344,8 @@
         return;
     }
 
-    const Vector<StylePropertyShorthand> shorthands = matchingShorthandsForLonghand(propId);
+    Vector<StylePropertyShorthand, 4> shorthands;
+    getMatchingShorthandsForLonghand(propId, &shorthands);
     // The longhand does not belong to multiple shorthands.
     if (shorthands.size() == 1)
         m_parsedProperties.append(CSSProperty(propId, value, important, true, CSSPropertyInvalid, m_implicitShorthand || implicit));
@@ -1474,13 +1367,14 @@
     m_hasFontFaceOnlyValues = false;
 }
 
+// FIXME: Move to CSSParserContext?
 KURL CSSParser::completeURL(const CSSParserContext& context, const String& url)
 {
     if (url.isNull())
         return KURL();
-    if (context.charset.isEmpty())
-        return KURL(context.baseURL, url);
-    return KURL(context.baseURL, url, context.charset);
+    if (context.charset().isEmpty())
+        return KURL(context.baseURL(), url);
+    return KURL(context.baseURL(), url, context.charset());
 }
 
 KURL CSSParser::completeURL(const String& url) const
@@ -1644,6 +1538,24 @@
     return value->unit == CSSParserValue::Operator && value->iValue == '/';
 }
 
+static bool isGeneratedImageValue(CSSParserValue* val)
+{
+    if (val->unit != CSSParserValue::Function)
+        return false;
+
+    return equalIgnoringCase(val->function->name, "-webkit-gradient(")
+        || equalIgnoringCase(val->function->name, "-webkit-linear-gradient(")
+        || equalIgnoringCase(val->function->name, "linear-gradient(")
+        || equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(")
+        || equalIgnoringCase(val->function->name, "repeating-linear-gradient(")
+        || equalIgnoringCase(val->function->name, "-webkit-radial-gradient(")
+        || equalIgnoringCase(val->function->name, "radial-gradient(")
+        || equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(")
+        || equalIgnoringCase(val->function->name, "repeating-radial-gradient(")
+        || equalIgnoringCase(val->function->name, "-webkit-canvas(")
+        || equalIgnoringCase(val->function->name, "-webkit-cross-fade(");
+}
+
 bool CSSParser::validWidthOrHeight(CSSParserValue* value)
 {
     int id = value->id;
@@ -1699,7 +1611,7 @@
 
 bool CSSParser::parseValue(CSSPropertyID propId, bool important)
 {
-    if (!isInternalPropertyAndValueParsingEnabledForMode(m_context.mode) && isInternalProperty(propId))
+    if (!isInternalPropertyAndValueParsingEnabledForMode(m_context.mode()) && isInternalProperty(propId))
         return false;
 
     // We don't count the UA style sheet in our statistics.
@@ -1716,7 +1628,7 @@
 
     if (inViewport()) {
         // Allow @viewport rules from UA stylesheets even if the feature is disabled.
-        if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode))
+        if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode()))
             return false;
 
         return parseViewportProperty(propId, important);
@@ -1880,7 +1792,7 @@
             return false;
 
         if ((id >= CSSValueAqua && id <= CSSValueWebkitText) || id == CSSValueMenu) {
-            validPrimitive = isValueAllowedInMode(id, m_context.mode);
+            validPrimitive = isValueAllowedInMode(id, m_context.mode());
         } else {
             parsedValue = parseColor();
             if (parsedValue)
@@ -2182,7 +2094,7 @@
         break;
 
     case CSSPropertyTextUnderlinePosition:
-        // auto | alphabetic | under
+        // auto | under | inherit
         if (RuntimeEnabledFeatures::css3TextDecorationsEnabled())
             return parseTextUnderlinePosition(important);
         return false;
@@ -2204,19 +2116,17 @@
 
     /* CSS3 properties */
 
-    case CSSPropertyBorderImage: {
-        RefPtr<CSSValue> result;
-        return parseBorderImage(propId, result, important);
-    }
-    case CSSPropertyWebkitBorderImage:
-    case CSSPropertyWebkitMaskBoxImage: {
-        RefPtr<CSSValue> result;
-        if (parseBorderImage(propId, result)) {
+    case CSSPropertyBorderImage:
+    case CSSPropertyWebkitMaskBoxImage:
+        return parseBorderImageShorthand(propId, important);
+    case CSSPropertyWebkitBorderImage: {
+        if (RefPtr<CSSValue> result = parseBorderImage(propId)) {
             addProperty(propId, result, important);
             return true;
         }
-        break;
+        return false;
     }
+
     case CSSPropertyBorderImageOutset:
     case CSSPropertyWebkitMaskBoxImageOutset: {
         RefPtr<CSSPrimitiveValue> result;
@@ -2285,7 +2195,7 @@
     case CSSPropertyWebkitBorderRadius:
         return parseBorderRadius(propId, important);
     case CSSPropertyOutlineOffset:
-        validPrimitive = validUnit(value, FLength | FPercent);
+        validPrimitive = validUnit(value, FLength);
         break;
     case CSSPropertyTextShadow: // CSS2 property, dropped in CSS2.1, back in CSS3, so treat as CSS3
     case CSSPropertyBoxShadow:
@@ -2956,7 +2866,7 @@
 
 bool CSSParser::useLegacyBackgroundSizeShorthandBehavior() const
 {
-    return m_context.useLegacyBackgroundSizeShorthandBehavior;
+    return m_context.useLegacyBackgroundSizeShorthandBehavior();
 }
 
 const int cMaxFillProperties = 9;
@@ -3671,7 +3581,7 @@
     if (attrName[0] == '-')
         return 0;
 
-    if (m_context.isHTMLDocument)
+    if (m_context.isHTMLDocument())
         attrName = attrName.lower();
 
     return cssValuePool().createValue(attrName, CSSPrimitiveValue::CSS_ATTR);
@@ -4810,6 +4720,28 @@
     return true;
 }
 
+void CSSParser::parseGridLineNames(CSSParserValueList* parserValueList, CSSValueList& valueList)
+{
+    ASSERT(parserValueList->current() && parserValueList->current()->unit == CSSParserValue::ValueList);
+
+    CSSParserValueList* identList = parserValueList->current()->valueList;
+    if (!identList->size()) {
+        parserValueList->next();
+        return;
+    }
+
+    RefPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
+    while (CSSParserValue* identValue = identList->current()) {
+        ASSERT(identValue->unit == CSSPrimitiveValue::CSS_IDENT);
+        RefPtr<CSSPrimitiveValue> lineName = createPrimitiveStringValue(identValue);
+        lineNames->append(lineName.release());
+        identList->next();
+    }
+    valueList.append(lineNames.release());
+
+    parserValueList->next();
+}
+
 bool CSSParser::parseGridTrackList(CSSPropertyID propId, bool important)
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
@@ -4824,12 +4756,10 @@
     }
 
     RefPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
-    // Handle leading <string>*.
-    while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
-        RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
-        values->append(name);
-        m_valueList->next();
-    }
+    // Handle leading  <ident>*.
+    value = m_valueList->current();
+    if (value && value->unit == CSSParserValue::ValueList)
+        parseGridLineNames(m_valueList.get(), *values);
 
     bool seenTrackSizeOrRepeatFunction = false;
     while (CSSParserValue* currentValue = m_valueList->current()) {
@@ -4844,13 +4774,10 @@
             values->append(value);
             seenTrackSizeOrRepeatFunction = true;
         }
-
-        // This will handle the trailing <string>* in the grammar.
-        while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
-            RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
-            values->append(name);
-            m_valueList->next();
-        }
+        // This will handle the trailing <ident>* in the grammar.
+        value = m_valueList->current();
+        if (value && value->unit == CSSParserValue::ValueList)
+            parseGridLineNames(m_valueList.get(), *values);
     }
 
     // We should have found a <track-size> or else it is not a valid <track-list>
@@ -4873,12 +4800,10 @@
     arguments->next(); // Skip the repetition count.
     arguments->next(); // Skip the comma.
 
-    // Handle leading <string>*.
-    while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
-        RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
-        repeatedValues->append(name);
-        arguments->next();
-    }
+    // Handle leading <ident>*.
+    CSSParserValue* currentValue = arguments->current();
+    if (currentValue && currentValue->unit == CSSParserValue::ValueList)
+        parseGridLineNames(arguments, *repeatedValues);
 
     while (arguments->current()) {
         RefPtr<CSSValue> trackSize = parseGridTrackSize(*arguments);
@@ -4887,12 +4812,10 @@
 
         repeatedValues->append(trackSize);
 
-        // This takes care of any trailing <string>* in the grammar.
-        while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
-            RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
-            repeatedValues->append(name);
-            arguments->next();
-        }
+        // This takes care of any trailing <ident>* in the grammar.
+        currentValue = arguments->current();
+        if (currentValue && currentValue->unit == CSSParserValue::ValueList)
+            parseGridLineNames(arguments, *repeatedValues);
     }
 
     for (size_t i = 0; i < repetitions; ++i) {
@@ -6586,7 +6509,8 @@
     RefPtr<CSSValue> mask;
     val = m_valueList->next();
     if (val) {
-        if (!parseBorderImage(propId, mask))
+        mask = parseBorderImage(propId);
+        if (!mask)
             return false;
     }
 
@@ -6736,11 +6660,20 @@
         m_allowImage = !m_image;
     }
 
-    PassRefPtr<CSSValue> commitWebKitBorderImage()
+    PassRefPtr<CSSValue> commitCSSValue()
     {
         return createBorderImageValue(m_image, m_imageSlice, m_borderSlice, m_outset, m_repeat);
     }
 
+    void commitMaskBoxImage(CSSParser* parser, bool important)
+    {
+        commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageSource, parser, m_image, important);
+        commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageSlice, parser, m_imageSlice, important);
+        commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageWidth, parser, m_borderSlice, important);
+        commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageOutset, parser, m_outset, important);
+        commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageRepeat, parser, m_repeat, important);
+    }
+
     void commitBorderImage(CSSParser* parser, bool important)
     {
         commitBorderImageProperty(CSSPropertyBorderImageSource, parser, m_image, important);
@@ -6777,27 +6710,26 @@
     RefPtr<CSSValue> m_repeat;
 };
 
-bool CSSParser::parseBorderImage(CSSPropertyID propId, RefPtr<CSSValue>& result, bool important)
+static bool buildBorderImageParseContext(CSSParser& parser, CSSPropertyID propId, BorderImageParseContext& context)
 {
-    ShorthandScope scope(this, propId);
-    BorderImageParseContext context;
-    while (CSSParserValue* val = m_valueList->current()) {
+    ShorthandScope scope(&parser, propId);
+    while (CSSParserValue* val = parser.m_valueList->current()) {
         context.setCanAdvance(false);
 
         if (!context.canAdvance() && context.allowForwardSlashOperator() && isForwardSlashOperator(val))
             context.commitForwardSlashOperator();
 
         if (!context.canAdvance() && context.allowImage()) {
-            if (val->unit == CSSPrimitiveValue::CSS_URI)
-                context.commitImage(CSSImageValue::create(completeURL(val->string)));
-            else if (isGeneratedImageValue(val)) {
+            if (val->unit == CSSPrimitiveValue::CSS_URI) {
+                context.commitImage(CSSImageValue::create(parser.completeURL(parser.m_context, val->string)));
+            } else if (isGeneratedImageValue(val)) {
                 RefPtr<CSSValue> value;
-                if (parseGeneratedImage(m_valueList.get(), value))
+                if (parser.parseGeneratedImage(parser.m_valueList.get(), value))
                     context.commitImage(value.release());
                 else
                     return false;
             } else if (val->unit == CSSParserValue::Function && equalIgnoringCase(val->function->name, "-webkit-image-set(")) {
-                RefPtr<CSSValue> value = parseImageSet(m_valueList.get());
+                RefPtr<CSSValue> value = parser.parseImageSet(parser.m_valueList.get());
                 if (value)
                     context.commitImage(value.release());
                 else
@@ -6808,46 +6740,65 @@
 
         if (!context.canAdvance() && context.allowImageSlice()) {
             RefPtr<CSSBorderImageSliceValue> imageSlice;
-            if (parseBorderImageSlice(propId, imageSlice))
+            if (parser.parseBorderImageSlice(propId, imageSlice))
                 context.commitImageSlice(imageSlice.release());
         }
 
         if (!context.canAdvance() && context.allowRepeat()) {
             RefPtr<CSSValue> repeat;
-            if (parseBorderImageRepeat(repeat))
+            if (parser.parseBorderImageRepeat(repeat))
                 context.commitRepeat(repeat.release());
         }
 
         if (!context.canAdvance() && context.requireWidth()) {
             RefPtr<CSSPrimitiveValue> borderSlice;
-            if (parseBorderImageWidth(borderSlice))
+            if (parser.parseBorderImageWidth(borderSlice))
                 context.commitBorderWidth(borderSlice.release());
         }
 
         if (!context.canAdvance() && context.requireOutset()) {
             RefPtr<CSSPrimitiveValue> borderOutset;
-            if (parseBorderImageOutset(borderOutset))
+            if (parser.parseBorderImageOutset(borderOutset))
                 context.commitBorderOutset(borderOutset.release());
         }
 
         if (!context.canAdvance())
             return false;
 
-        m_valueList->next();
+        parser.m_valueList->next();
     }
 
-    if (context.allowCommit()) {
-        if (propId == CSSPropertyBorderImage)
+    return context.allowCommit();
+}
+
+bool CSSParser::parseBorderImageShorthand(CSSPropertyID propId, bool important)
+{
+    BorderImageParseContext context;
+    if (buildBorderImageParseContext(*this, propId, context)) {
+        switch (propId) {
+        case CSSPropertyWebkitMaskBoxImage:
+            context.commitMaskBoxImage(this, important);
+            return true;
+        case CSSPropertyBorderImage:
             context.commitBorderImage(this, important);
-        else
-            // Need to fully commit as a single value.
-            result = context.commitWebKitBorderImage();
-        return true;
+            return true;
+        default:
+            ASSERT_NOT_REACHED();
+            return false;
+        }
     }
-
     return false;
 }
 
+PassRefPtr<CSSValue> CSSParser::parseBorderImage(CSSPropertyID propId)
+{
+    BorderImageParseContext context;
+    if (buildBorderImageParseContext(*this, propId, context)) {
+        return context.commitCSSValue();
+    }
+    return 0;
+}
+
 static bool isBorderImageRepeatKeyword(int id)
 {
     return id == CSSValueStretch || id == CSSValueRepeat || id == CSSValueSpace || id == CSSValueRound;
@@ -7104,12 +7055,12 @@
 
 bool CSSParser::parseBorderImageWidth(RefPtr<CSSPrimitiveValue>& result)
 {
-    return parseBorderImageQuad(FLength | FInteger | FNonNeg | FPercent, result);
+    return parseBorderImageQuad(FLength | FNumber | FNonNeg | FPercent, result);
 }
 
 bool CSSParser::parseBorderImageOutset(RefPtr<CSSPrimitiveValue>& result)
 {
-    return parseBorderImageQuad(FLength | FInteger | FNonNeg, result);
+    return parseBorderImageQuad(FLength | FNumber | FNonNeg, result);
 }
 
 static void completeBorderRadii(RefPtr<CSSPrimitiveValue> radii[4])
@@ -7917,24 +7868,6 @@
     return gradient->stopCount() >= 2;
 }
 
-bool CSSParser::isGeneratedImageValue(CSSParserValue* val) const
-{
-    if (val->unit != CSSParserValue::Function)
-        return false;
-
-    return equalIgnoringCase(val->function->name, "-webkit-gradient(")
-        || equalIgnoringCase(val->function->name, "-webkit-linear-gradient(")
-        || equalIgnoringCase(val->function->name, "linear-gradient(")
-        || equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(")
-        || equalIgnoringCase(val->function->name, "repeating-linear-gradient(")
-        || equalIgnoringCase(val->function->name, "-webkit-radial-gradient(")
-        || equalIgnoringCase(val->function->name, "radial-gradient(")
-        || equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(")
-        || equalIgnoringCase(val->function->name, "repeating-radial-gradient(")
-        || equalIgnoringCase(val->function->name, "-webkit-canvas(")
-        || equalIgnoringCase(val->function->name, "-webkit-cross-fade(");
-}
-
 bool CSSParser::parseGeneratedImage(CSSParserValueList* valueList, RefPtr<CSSValue>& value)
 {
     CSSParserValue* val = valueList->current();
@@ -8769,7 +8702,6 @@
     clearProperties();
     StyleRuleFilter* result = rule.get();
     m_parsedRules.append(rule.release());
-    endRuleBody();
     return result;
 }
 
@@ -9134,13 +9066,12 @@
 
 bool CSSParser::parseTextUnderlinePosition(bool important)
 {
-    // The text-underline-position property has sintax "auto | alphabetic | [ under || [ left | right ] ]".
-    // However, values 'left' and 'right' are not implemented yet, so we will parse sintax
-    // "auto | alphabetic | under" for now.
+    // The text-underline-position property has syntax "auto | [ under || [ left | right ] ]".
+    // However, values 'left' and 'right' are not implemented yet, so we will parse syntax
+    // "auto | under" for now.
     CSSParserValue* value = m_valueList->current();
     switch (value->id) {
     case CSSValueAuto:
-    case CSSValueAlphabetic:
     case CSSValueUnder:
         if (m_valueList->next())
             return false;
@@ -9420,1484 +9351,12 @@
 
 #define END_TOKEN 0
 
-#include "CSSGrammar.h"
-
-enum CharacterType {
-    // Types for the main switch.
-
-    // The first 4 types must be grouped together, as they
-    // represent the allowed chars in an identifier.
-    CharacterCaselessU,
-    CharacterIdentifierStart,
-    CharacterNumber,
-    CharacterDash,
-
-    CharacterOther,
-    CharacterNull,
-    CharacterWhiteSpace,
-    CharacterEndMediaQueryOrSupports,
-    CharacterEndNthChild,
-    CharacterQuote,
-    CharacterExclamationMark,
-    CharacterHashmark,
-    CharacterDollar,
-    CharacterAsterisk,
-    CharacterPlus,
-    CharacterDot,
-    CharacterSlash,
-    CharacterLess,
-    CharacterAt,
-    CharacterBackSlash,
-    CharacterXor,
-    CharacterVerticalBar,
-    CharacterTilde,
-};
-
-// 128 ASCII codes
-static const CharacterType typesOfASCIICharacters[128] = {
-/*   0 - Null               */ CharacterNull,
-/*   1 - Start of Heading   */ CharacterOther,
-/*   2 - Start of Text      */ CharacterOther,
-/*   3 - End of Text        */ CharacterOther,
-/*   4 - End of Transm.     */ CharacterOther,
-/*   5 - Enquiry            */ CharacterOther,
-/*   6 - Acknowledgment     */ CharacterOther,
-/*   7 - Bell               */ CharacterOther,
-/*   8 - Back Space         */ CharacterOther,
-/*   9 - Horizontal Tab     */ CharacterWhiteSpace,
-/*  10 - Line Feed          */ CharacterWhiteSpace,
-/*  11 - Vertical Tab       */ CharacterOther,
-/*  12 - Form Feed          */ CharacterWhiteSpace,
-/*  13 - Carriage Return    */ CharacterWhiteSpace,
-/*  14 - Shift Out          */ CharacterOther,
-/*  15 - Shift In           */ CharacterOther,
-/*  16 - Data Line Escape   */ CharacterOther,
-/*  17 - Device Control 1   */ CharacterOther,
-/*  18 - Device Control 2   */ CharacterOther,
-/*  19 - Device Control 3   */ CharacterOther,
-/*  20 - Device Control 4   */ CharacterOther,
-/*  21 - Negative Ack.      */ CharacterOther,
-/*  22 - Synchronous Idle   */ CharacterOther,
-/*  23 - End of Transmit    */ CharacterOther,
-/*  24 - Cancel             */ CharacterOther,
-/*  25 - End of Medium      */ CharacterOther,
-/*  26 - Substitute         */ CharacterOther,
-/*  27 - Escape             */ CharacterOther,
-/*  28 - File Separator     */ CharacterOther,
-/*  29 - Group Separator    */ CharacterOther,
-/*  30 - Record Separator   */ CharacterOther,
-/*  31 - Unit Separator     */ CharacterOther,
-/*  32 - Space              */ CharacterWhiteSpace,
-/*  33 - !                  */ CharacterExclamationMark,
-/*  34 - "                  */ CharacterQuote,
-/*  35 - #                  */ CharacterHashmark,
-/*  36 - $                  */ CharacterDollar,
-/*  37 - %                  */ CharacterOther,
-/*  38 - &                  */ CharacterOther,
-/*  39 - '                  */ CharacterQuote,
-/*  40 - (                  */ CharacterOther,
-/*  41 - )                  */ CharacterEndNthChild,
-/*  42 - *                  */ CharacterAsterisk,
-/*  43 - +                  */ CharacterPlus,
-/*  44 - ,                  */ CharacterOther,
-/*  45 - -                  */ CharacterDash,
-/*  46 - .                  */ CharacterDot,
-/*  47 - /                  */ CharacterSlash,
-/*  48 - 0                  */ CharacterNumber,
-/*  49 - 1                  */ CharacterNumber,
-/*  50 - 2                  */ CharacterNumber,
-/*  51 - 3                  */ CharacterNumber,
-/*  52 - 4                  */ CharacterNumber,
-/*  53 - 5                  */ CharacterNumber,
-/*  54 - 6                  */ CharacterNumber,
-/*  55 - 7                  */ CharacterNumber,
-/*  56 - 8                  */ CharacterNumber,
-/*  57 - 9                  */ CharacterNumber,
-/*  58 - :                  */ CharacterOther,
-/*  59 - ;                  */ CharacterEndMediaQueryOrSupports,
-/*  60 - <                  */ CharacterLess,
-/*  61 - =                  */ CharacterOther,
-/*  62 - >                  */ CharacterOther,
-/*  63 - ?                  */ CharacterOther,
-/*  64 - @                  */ CharacterAt,
-/*  65 - A                  */ CharacterIdentifierStart,
-/*  66 - B                  */ CharacterIdentifierStart,
-/*  67 - C                  */ CharacterIdentifierStart,
-/*  68 - D                  */ CharacterIdentifierStart,
-/*  69 - E                  */ CharacterIdentifierStart,
-/*  70 - F                  */ CharacterIdentifierStart,
-/*  71 - G                  */ CharacterIdentifierStart,
-/*  72 - H                  */ CharacterIdentifierStart,
-/*  73 - I                  */ CharacterIdentifierStart,
-/*  74 - J                  */ CharacterIdentifierStart,
-/*  75 - K                  */ CharacterIdentifierStart,
-/*  76 - L                  */ CharacterIdentifierStart,
-/*  77 - M                  */ CharacterIdentifierStart,
-/*  78 - N                  */ CharacterIdentifierStart,
-/*  79 - O                  */ CharacterIdentifierStart,
-/*  80 - P                  */ CharacterIdentifierStart,
-/*  81 - Q                  */ CharacterIdentifierStart,
-/*  82 - R                  */ CharacterIdentifierStart,
-/*  83 - S                  */ CharacterIdentifierStart,
-/*  84 - T                  */ CharacterIdentifierStart,
-/*  85 - U                  */ CharacterCaselessU,
-/*  86 - V                  */ CharacterIdentifierStart,
-/*  87 - W                  */ CharacterIdentifierStart,
-/*  88 - X                  */ CharacterIdentifierStart,
-/*  89 - Y                  */ CharacterIdentifierStart,
-/*  90 - Z                  */ CharacterIdentifierStart,
-/*  91 - [                  */ CharacterOther,
-/*  92 - \                  */ CharacterBackSlash,
-/*  93 - ]                  */ CharacterOther,
-/*  94 - ^                  */ CharacterXor,
-/*  95 - _                  */ CharacterIdentifierStart,
-/*  96 - `                  */ CharacterOther,
-/*  97 - a                  */ CharacterIdentifierStart,
-/*  98 - b                  */ CharacterIdentifierStart,
-/*  99 - c                  */ CharacterIdentifierStart,
-/* 100 - d                  */ CharacterIdentifierStart,
-/* 101 - e                  */ CharacterIdentifierStart,
-/* 102 - f                  */ CharacterIdentifierStart,
-/* 103 - g                  */ CharacterIdentifierStart,
-/* 104 - h                  */ CharacterIdentifierStart,
-/* 105 - i                  */ CharacterIdentifierStart,
-/* 106 - j                  */ CharacterIdentifierStart,
-/* 107 - k                  */ CharacterIdentifierStart,
-/* 108 - l                  */ CharacterIdentifierStart,
-/* 109 - m                  */ CharacterIdentifierStart,
-/* 110 - n                  */ CharacterIdentifierStart,
-/* 111 - o                  */ CharacterIdentifierStart,
-/* 112 - p                  */ CharacterIdentifierStart,
-/* 113 - q                  */ CharacterIdentifierStart,
-/* 114 - r                  */ CharacterIdentifierStart,
-/* 115 - s                  */ CharacterIdentifierStart,
-/* 116 - t                  */ CharacterIdentifierStart,
-/* 117 - u                  */ CharacterCaselessU,
-/* 118 - v                  */ CharacterIdentifierStart,
-/* 119 - w                  */ CharacterIdentifierStart,
-/* 120 - x                  */ CharacterIdentifierStart,
-/* 121 - y                  */ CharacterIdentifierStart,
-/* 122 - z                  */ CharacterIdentifierStart,
-/* 123 - {                  */ CharacterEndMediaQueryOrSupports,
-/* 124 - |                  */ CharacterVerticalBar,
-/* 125 - }                  */ CharacterOther,
-/* 126 - ~                  */ CharacterTilde,
-/* 127 - Delete             */ CharacterOther,
-};
-
-// Utility functions for the CSS tokenizer.
-
-template <typename CharacterType>
-static inline bool isCSSLetter(CharacterType character)
-{
-    return character >= 128 || typesOfASCIICharacters[character] <= CharacterDash;
-}
-
-template <typename CharacterType>
-static inline bool isCSSEscape(CharacterType character)
-{
-    return character >= ' ' && character != 127;
-}
-
-template <typename CharacterType>
-static inline bool isURILetter(CharacterType character)
-{
-    return (character >= '*' && character != 127) || (character >= '#' && character <= '&') || character == '!';
-}
-
-template <typename CharacterType>
-static inline bool isIdentifierStartAfterDash(CharacterType* currentCharacter)
-{
-    return isASCIIAlpha(currentCharacter[0]) || currentCharacter[0] == '_' || currentCharacter[0] >= 128
-        || (currentCharacter[0] == '\\' && isCSSEscape(currentCharacter[1]));
-}
-
-template <typename CharacterType>
-static inline bool isEqualToCSSIdentifier(CharacterType* cssString, const char* constantString)
-{
-    // Compare an character memory data with a zero terminated string.
-    do {
-        // The input must be part of an identifier if constantChar or constString
-        // contains '-'. Otherwise toASCIILowerUnchecked('\r') would be equal to '-'.
-        ASSERT((*constantString >= 'a' && *constantString <= 'z') || *constantString == '-');
-        ASSERT(*constantString != '-' || isCSSLetter(*cssString));
-        if (toASCIILowerUnchecked(*cssString++) != (*constantString++))
-            return false;
-    } while (*constantString);
-    return true;
-}
-
-template <typename CharacterType>
-static inline bool isEqualToCSSCaseSensitiveIdentifier(CharacterType* string, const char* constantString)
-{
-    ASSERT(*constantString);
-
-    do {
-        if (*string++ != *constantString++)
-            return false;
-    } while (*constantString);
-    return true;
-}
-
-template <typename CharacterType>
-static CharacterType* checkAndSkipEscape(CharacterType* currentCharacter)
-{
-    // Returns with 0, if escape check is failed. Otherwise
-    // it returns with the following character.
-    ASSERT(*currentCharacter == '\\');
-
-    ++currentCharacter;
-    if (!isCSSEscape(*currentCharacter))
-        return 0;
-
-    if (isASCIIHexDigit(*currentCharacter)) {
-        int length = 6;
-
-        do {
-            ++currentCharacter;
-        } while (isASCIIHexDigit(*currentCharacter) && --length);
-
-        // Optional space after the escape sequence.
-        if (isHTMLSpace<CharacterType>(*currentCharacter))
-            ++currentCharacter;
-        return currentCharacter;
-    }
-    return currentCharacter + 1;
-}
-
-template <typename CharacterType>
-static inline CharacterType* skipWhiteSpace(CharacterType* currentCharacter)
-{
-    while (isHTMLSpace<CharacterType>(*currentCharacter))
-        ++currentCharacter;
-    return currentCharacter;
-}
-
-// Main CSS tokenizer functions.
-
-template <>
-const LChar* CSSParserString::characters<LChar>() const { return characters8(); }
-
-template <>
-const UChar* CSSParserString::characters<UChar>() const { return characters16(); }
-
-template <>
-inline LChar*& CSSParser::currentCharacter<LChar>()
-{
-    return m_currentCharacter8;
-}
-
-template <>
-inline UChar*& CSSParser::currentCharacter<UChar>()
-{
-    return m_currentCharacter16;
-}
-
-UChar*& CSSParser::currentCharacter16()
-{
-    if (!m_currentCharacter16) {
-        m_dataStart16 = adoptArrayPtr(new UChar[m_length]);
-        m_currentCharacter16 = m_dataStart16.get();
-    }
-
-    return m_currentCharacter16;
-}
-
-template <>
-inline LChar* CSSParser::tokenStart<LChar>()
-{
-    return m_tokenStart.ptr8;
-}
-
-template <>
-inline UChar* CSSParser::tokenStart<UChar>()
-{
-    return m_tokenStart.ptr16;
-}
-
-template <>
-inline LChar* CSSParser::dataStart<LChar>()
-{
-    return m_dataStart8.get();
-}
-
-template <>
-inline UChar* CSSParser::dataStart<UChar>()
-{
-    return m_dataStart16.get();
-}
-
 void CSSParser::ensureLineEndings()
 {
     if (!m_lineEndings)
         m_lineEndings = lineEndings(*m_source);
 }
 
-template <typename CharacterType>
-inline CSSParserLocation CSSParser::tokenLocation()
-{
-    CSSParserLocation location;
-    location.token.init(tokenStart<CharacterType>(), currentCharacter<CharacterType>() - tokenStart<CharacterType>());
-    location.lineNumber = m_tokenStartLineNumber;
-    location.offset = tokenStart<CharacterType>() - dataStart<CharacterType>();
-    return location;
-}
-
-CSSParserLocation CSSParser::currentLocation()
-{
-    if (is8BitSource())
-        return tokenLocation<LChar>();
-    else
-        return tokenLocation<UChar>();
-}
-
-template <typename CharacterType>
-inline bool CSSParser::isIdentifierStart()
-{
-    // Check whether an identifier is started.
-    return isIdentifierStartAfterDash((*currentCharacter<CharacterType>() != '-') ? currentCharacter<CharacterType>() : currentCharacter<CharacterType>() + 1);
-}
-
-template <typename CharacterType>
-static inline CharacterType* checkAndSkipString(CharacterType* currentCharacter, int quote)
-{
-    // Returns with 0, if string check is failed. Otherwise
-    // it returns with the following character. This is necessary
-    // since we cannot revert escape sequences, thus strings
-    // must be validated before parsing.
-    while (true) {
-        if (UNLIKELY(*currentCharacter == quote)) {
-            // String parsing is successful.
-            return currentCharacter + 1;
-        }
-        if (UNLIKELY(!*currentCharacter)) {
-            // String parsing is successful up to end of input.
-            return currentCharacter;
-        }
-        if (UNLIKELY(*currentCharacter <= '\r' && (*currentCharacter == '\n' || (*currentCharacter | 0x1) == '\r'))) {
-            // String parsing is failed for character '\n', '\f' or '\r'.
-            return 0;
-        }
-
-        if (LIKELY(currentCharacter[0] != '\\'))
-            ++currentCharacter;
-        else if (currentCharacter[1] == '\n' || currentCharacter[1] == '\f')
-            currentCharacter += 2;
-        else if (currentCharacter[1] == '\r')
-            currentCharacter += currentCharacter[2] == '\n' ? 3 : 2;
-        else {
-            currentCharacter = checkAndSkipEscape(currentCharacter);
-            if (!currentCharacter)
-                return 0;
-        }
-    }
-}
-
-template <typename CharacterType>
-unsigned CSSParser::parseEscape(CharacterType*& src)
-{
-    ASSERT(*src == '\\' && isCSSEscape(src[1]));
-
-    unsigned unicode = 0;
-
-    ++src;
-    if (isASCIIHexDigit(*src)) {
-
-        int length = 6;
-
-        do {
-            unicode = (unicode << 4) + toASCIIHexValue(*src++);
-        } while (--length && isASCIIHexDigit(*src));
-
-        // Characters above 0x10ffff are not handled.
-        if (unicode > 0x10ffff)
-            unicode = 0xfffd;
-
-        // Optional space after the escape sequence.
-        if (isHTMLSpace<CharacterType>(*src))
-            ++src;
-
-        return unicode;
-    }
-
-    return *currentCharacter<CharacterType>()++;
-}
-
-template <>
-inline void CSSParser::UnicodeToChars<LChar>(LChar*& result, unsigned unicode)
-{
-    ASSERT(unicode <= 0xff);
-    *result = unicode;
-
-    ++result;
-}
-
-template <>
-inline void CSSParser::UnicodeToChars<UChar>(UChar*& result, unsigned unicode)
-{
-    // Replace unicode with a surrogate pairs when it is bigger than 0xffff
-    if (U16_LENGTH(unicode) == 2) {
-        *result++ = U16_LEAD(unicode);
-        *result = U16_TRAIL(unicode);
-    } else
-        *result = unicode;
-
-    ++result;
-}
-
-template <typename SrcCharacterType, typename DestCharacterType>
-inline bool CSSParser::parseIdentifierInternal(SrcCharacterType*& src, DestCharacterType*& result, bool& hasEscape)
-{
-    hasEscape = false;
-    do {
-        if (LIKELY(*src != '\\'))
-            *result++ = *src++;
-        else {
-            hasEscape = true;
-            SrcCharacterType* savedEscapeStart = src;
-            unsigned unicode = parseEscape<SrcCharacterType>(src);
-            if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
-                src = savedEscapeStart;
-                return false;
-            }
-            UnicodeToChars(result, unicode);
-        }
-    } while (isCSSLetter(src[0]) || (src[0] == '\\' && isCSSEscape(src[1])));
-
-    return true;
-}
-
-template <typename CharacterType>
-inline void CSSParser::parseIdentifier(CharacterType*& result, CSSParserString& resultString, bool& hasEscape)
-{
-    // If a valid identifier start is found, we can safely
-    // parse the identifier until the next invalid character.
-    ASSERT(isIdentifierStart<CharacterType>());
-
-    CharacterType* start = currentCharacter<CharacterType>();
-    if (UNLIKELY(!parseIdentifierInternal(currentCharacter<CharacterType>(), result, hasEscape))) {
-        // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
-        ASSERT(is8BitSource());
-        UChar*& result16 = currentCharacter16();
-        UChar* start16 = result16;
-        int i = 0;
-        for (; i < result - start; i++)
-            result16[i] = start[i];
-
-        result16 += i;
-
-        parseIdentifierInternal(currentCharacter<CharacterType>(), result16, hasEscape);
-
-        resultString.init(start16, result16 - start16);
-
-        return;
-    }
-
-    resultString.init(start, result - start);
-}
-
-template <typename SrcCharacterType, typename DestCharacterType>
-inline bool CSSParser::parseStringInternal(SrcCharacterType*& src, DestCharacterType*& result, UChar quote)
-{
-    while (true) {
-        if (UNLIKELY(*src == quote)) {
-            // String parsing is done.
-            ++src;
-            return true;
-        }
-        if (UNLIKELY(!*src)) {
-            // String parsing is done, but don't advance pointer if at the end of input.
-            return true;
-        }
-        ASSERT(*src > '\r' || (*src < '\n' && *src) || *src == '\v');
-
-        if (LIKELY(src[0] != '\\'))
-            *result++ = *src++;
-        else if (src[1] == '\n' || src[1] == '\f')
-            src += 2;
-        else if (src[1] == '\r')
-            src += src[2] == '\n' ? 3 : 2;
-        else {
-            SrcCharacterType* savedEscapeStart = src;
-            unsigned unicode = parseEscape<SrcCharacterType>(src);
-            if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
-                src = savedEscapeStart;
-                return false;
-            }
-            UnicodeToChars(result, unicode);
-        }
-    }
-
-    return true;
-}
-
-template <typename CharacterType>
-inline void CSSParser::parseString(CharacterType*& result, CSSParserString& resultString, UChar quote)
-{
-    CharacterType* start = currentCharacter<CharacterType>();
-
-    if (UNLIKELY(!parseStringInternal(currentCharacter<CharacterType>(), result, quote))) {
-        // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
-        ASSERT(is8BitSource());
-        UChar*& result16 = currentCharacter16();
-        UChar* start16 = result16;
-        int i = 0;
-        for (; i < result - start; i++)
-            result16[i] = start[i];
-
-        result16 += i;
-
-        parseStringInternal(currentCharacter<CharacterType>(), result16, quote);
-
-        resultString.init(start16, result16 - start16);
-        return;
-    }
-
-    resultString.init(start, result - start);
-}
-
-template <typename CharacterType>
-inline bool CSSParser::findURI(CharacterType*& start, CharacterType*& end, UChar& quote)
-{
-    start = skipWhiteSpace(currentCharacter<CharacterType>());
-
-    if (*start == '"' || *start == '\'') {
-        quote = *start++;
-        end = checkAndSkipString(start, quote);
-        if (!end)
-            return false;
-    } else {
-        quote = 0;
-        end = start;
-        while (isURILetter(*end)) {
-            if (LIKELY(*end != '\\'))
-                ++end;
-            else {
-                end = checkAndSkipEscape(end);
-                if (!end)
-                    return false;
-            }
-        }
-    }
-
-    end = skipWhiteSpace(end);
-    if (*end != ')')
-        return false;
-
-    return true;
-}
-
-template <typename SrcCharacterType, typename DestCharacterType>
-inline bool CSSParser::parseURIInternal(SrcCharacterType*& src, DestCharacterType*& dest, UChar quote)
-{
-    if (quote) {
-        ASSERT(quote == '"' || quote == '\'');
-        return parseStringInternal(src, dest, quote);
-    }
-
-    while (isURILetter(*src)) {
-        if (LIKELY(*src != '\\'))
-            *dest++ = *src++;
-        else {
-            unsigned unicode = parseEscape<SrcCharacterType>(src);
-            if (unicode > 0xff && sizeof(SrcCharacterType) == 1)
-                return false;
-            UnicodeToChars(dest, unicode);
-        }
-    }
-
-    return true;
-}
-
-template <typename CharacterType>
-inline void CSSParser::parseURI(CSSParserString& string)
-{
-    CharacterType* uriStart;
-    CharacterType* uriEnd;
-    UChar quote;
-    if (!findURI(uriStart, uriEnd, quote))
-        return;
-
-    CharacterType* dest = currentCharacter<CharacterType>() = uriStart;
-    if (LIKELY(parseURIInternal(currentCharacter<CharacterType>(), dest, quote)))
-        string.init(uriStart, dest - uriStart);
-    else {
-        // An escape sequence was encountered that can't be stored in 8 bits.
-        // Reset the current character to the start of the URI and re-parse with
-        // a 16-bit destination.
-        ASSERT(is8BitSource());
-        UChar* uriStart16 = currentCharacter16();
-        currentCharacter<CharacterType>() = uriStart;
-        bool result = parseURIInternal(currentCharacter<CharacterType>(), currentCharacter16(), quote);
-        ASSERT_UNUSED(result, result);
-        string.init(uriStart16, currentCharacter16() - uriStart16);
-    }
-
-    currentCharacter<CharacterType>() = uriEnd + 1;
-    m_token = URI;
-}
-
-template <typename CharacterType>
-inline bool CSSParser::parseUnicodeRange()
-{
-    CharacterType* character = currentCharacter<CharacterType>() + 1;
-    int length = 6;
-    ASSERT(*currentCharacter<CharacterType>() == '+');
-
-    while (isASCIIHexDigit(*character) && length) {
-        ++character;
-        --length;
-    }
-
-    if (length && *character == '?') {
-        // At most 5 hex digit followed by a question mark.
-        do {
-            ++character;
-            --length;
-        } while (*character == '?' && length);
-        currentCharacter<CharacterType>() = character;
-        return true;
-    }
-
-    if (length < 6) {
-        // At least one hex digit.
-        if (character[0] == '-' && isASCIIHexDigit(character[1])) {
-            // Followed by a dash and a hex digit.
-            ++character;
-            length = 6;
-            do {
-                ++character;
-            } while (--length && isASCIIHexDigit(*character));
-        }
-        currentCharacter<CharacterType>() = character;
-        return true;
-    }
-    return false;
-}
-
-template <typename CharacterType>
-bool CSSParser::parseNthChild()
-{
-    CharacterType* character = currentCharacter<CharacterType>();
-
-    while (isASCIIDigit(*character))
-        ++character;
-    if (isASCIIAlphaCaselessEqual(*character, 'n')) {
-        currentCharacter<CharacterType>() = character + 1;
-        return true;
-    }
-    return false;
-}
-
-template <typename CharacterType>
-bool CSSParser::parseNthChildExtra()
-{
-    CharacterType* character = skipWhiteSpace(currentCharacter<CharacterType>());
-    if (*character != '+' && *character != '-')
-        return false;
-
-    character = skipWhiteSpace(character + 1);
-    if (!isASCIIDigit(*character))
-        return false;
-
-    do {
-        ++character;
-    } while (isASCIIDigit(*character));
-
-    currentCharacter<CharacterType>() = character;
-    return true;
-}
-
-template <typename CharacterType>
-inline bool CSSParser::detectFunctionTypeToken(int length)
-{
-    ASSERT(length > 0);
-    CharacterType* name = tokenStart<CharacterType>();
-    SWITCH(name, length) {
-        CASE("not") {
-            m_token = NOTFUNCTION;
-            return true;
-        }
-        CASE("url") {
-            m_token = URI;
-            return true;
-        }
-        CASE("cue") {
-            m_token = CUEFUNCTION;
-            return true;
-        }
-        CASE("var") {
-            if (!RuntimeEnabledFeatures::cssVariablesEnabled())
-                return false;
-            m_token = VARFUNCTION;
-            return true;
-        }
-        CASE("calc") {
-            m_token = CALCFUNCTION;
-            return true;
-        }
-        CASE("host") {
-            m_token = HOSTFUNCTION;
-            return true;
-        }
-        CASE("nth-child") {
-            m_parsingMode = NthChildMode;
-            return true;
-        }
-        CASE("nth-of-type") {
-            m_parsingMode = NthChildMode;
-            return true;
-        }
-        CASE("nth-last-child") {
-            m_parsingMode = NthChildMode;
-            return true;
-        }
-        CASE("nth-last-of-type") {
-            m_parsingMode = NthChildMode;
-            return true;
-        }
-        CASE("part") {
-            m_token = PARTFUNCTION;
-            return true;
-        }
-    }
-    return false;
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectMediaQueryToken(int length)
-{
-    ASSERT(m_parsingMode == MediaQueryMode);
-    CharacterType* name = tokenStart<CharacterType>();
-
-    SWITCH(name, length) {
-        CASE("and") {
-            m_token = MEDIA_AND;
-        }
-        CASE("not") {
-            m_token = MEDIA_NOT;
-        }
-        CASE("only") {
-            m_token = MEDIA_ONLY;
-        }
-        CASE("or") {
-            m_token = MEDIA_OR;
-        }
-    }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectNumberToken(CharacterType* type, int length)
-{
-    ASSERT(length > 0);
-
-    SWITCH(type, length) {
-        CASE("cm") {
-            m_token = CMS;
-        }
-        CASE("ch") {
-            m_token = CHS;
-        }
-        CASE("deg") {
-            m_token = DEGS;
-        }
-        CASE("dppx") {
-                // There is a discussion about the name of this unit on www-style.
-                // Keep this compile time guard in place until that is resolved.
-                // http://lists.w3.org/Archives/Public/www-style/2012May/0915.html
-            m_token = DPPX;
-        }
-        CASE("dpcm") {
-            m_token = DPCM;
-        }
-        CASE("dpi") {
-            m_token = DPI;
-        }
-        CASE("em") {
-            m_token = EMS;
-        }
-        CASE("ex") {
-            m_token = EXS;
-        }
-        CASE("fr") {
-            m_token = FR;
-        }
-        CASE("grad") {
-            m_token = GRADS;
-        }
-        CASE("hz") {
-            m_token = HERTZ;
-        }
-        CASE("in") {
-            m_token = INS;
-        }
-        CASE("khz") {
-            m_token = KHERTZ;
-        }
-        CASE("mm") {
-            m_token = MMS;
-        }
-        CASE("ms") {
-            m_token = MSECS;
-        }
-        CASE("px") {
-            m_token = PXS;
-        }
-        CASE("pt") {
-            m_token = PTS;
-        }
-        CASE("pc") {
-            m_token = PCS;
-        }
-        CASE("rad") {
-            m_token = RADS;
-        }
-        CASE("rem") {
-            m_token = REMS;
-        }
-        CASE("s") {
-            m_token = SECS;
-        }
-        CASE("turn") {
-            m_token = TURNS;
-        }
-        CASE("vw") {
-            m_token = VW;
-        }
-        CASE("vh") {
-            m_token = VH;
-        }
-        CASE("vmin") {
-            m_token = VMIN;
-        }
-        CASE("vmax") {
-            m_token = VMAX;
-        }
-        CASE("__qem") {
-            m_token = QEMS;
-        }
-    }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectDashToken(int length)
-{
-    CharacterType* name = tokenStart<CharacterType>();
-
-    // Ignore leading dash.
-    ++name;
-    --length;
-
-    SWITCH(name, length) {
-        CASE("webkit-any") {
-            m_token = ANYFUNCTION;
-        }
-        CASE("webkit-min") {
-            m_token = MINFUNCTION;
-        }
-        CASE("webkit-max") {
-            m_token = MAXFUNCTION;
-        }
-        CASE("webkit-calc") {
-            m_token = CALCFUNCTION;
-        }
-        CASE("webkit-distributed") {
-            m_token = DISTRIBUTEDFUNCTION;
-        }
-    }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectAtToken(int length, bool hasEscape)
-{
-    CharacterType* name = tokenStart<CharacterType>();
-    ASSERT(name[0] == '@' && length >= 2);
-
-    // Ignore leading @.
-    ++name;
-    --length;
-
-    // charset, font-face, import, media, namespace, page, supports,
-    // -webkit-keyframes, keyframes, and -webkit-mediaquery are not affected by hasEscape.
-    SWITCH(name, length) {
-        CASE("bottom-left") {
-            if (LIKELY(!hasEscape))
-                m_token = BOTTOMLEFT_SYM;
-        }
-        CASE("bottom-right") {
-            if (LIKELY(!hasEscape))
-                m_token = BOTTOMRIGHT_SYM;
-        }
-        CASE("bottom-center") {
-            if (LIKELY(!hasEscape))
-                m_token = BOTTOMCENTER_SYM;
-        }
-        CASE("bottom-left-corner") {
-            if (LIKELY(!hasEscape))
-                m_token = BOTTOMLEFTCORNER_SYM;
-        }
-        CASE("bottom-right-corner") {
-            if (LIKELY(!hasEscape))
-                m_token = BOTTOMRIGHTCORNER_SYM;
-        }
-        CASE("charset") {
-            if (name - 1 == dataStart<CharacterType>())
-                m_token = CHARSET_SYM;
-        }
-        CASE("font-face") {
-            m_token = FONT_FACE_SYM;
-        }
-        CASE("host") {
-            m_token = HOST_SYM;
-        }
-        CASE("import") {
-            m_parsingMode = MediaQueryMode;
-            m_token = IMPORT_SYM;
-        }
-        CASE("keyframes") {
-            if (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                m_token = KEYFRAMES_SYM;
-        }
-        CASE("left-top") {
-            if (LIKELY(!hasEscape))
-                m_token = LEFTTOP_SYM;
-        }
-        CASE("left-middle") {
-            if (LIKELY(!hasEscape))
-                m_token = LEFTMIDDLE_SYM;
-        }
-        CASE("left-bottom") {
-            if (LIKELY(!hasEscape))
-                m_token = LEFTBOTTOM_SYM;
-        }
-        CASE("media") {
-            m_parsingMode = MediaQueryMode;
-            m_token = MEDIA_SYM;
-        }
-        CASE("namespace") {
-            m_token = NAMESPACE_SYM;
-        }
-        CASE("page") {
-            m_token = PAGE_SYM;
-        }
-        CASE("right-top") {
-            if (LIKELY(!hasEscape))
-                m_token = RIGHTTOP_SYM;
-        }
-        CASE("right-middle") {
-            if (LIKELY(!hasEscape))
-                m_token = RIGHTMIDDLE_SYM;
-        }
-        CASE("right-bottom") {
-            if (LIKELY(!hasEscape))
-                m_token = RIGHTBOTTOM_SYM;
-        }
-        CASE("supports") {
-            m_parsingMode = SupportsMode;
-            m_token = SUPPORTS_SYM;
-        }
-        CASE("top-left") {
-            if (LIKELY(!hasEscape))
-                m_token = TOPLEFT_SYM;
-        }
-        CASE("top-right") {
-            if (LIKELY(!hasEscape))
-                m_token = TOPRIGHT_SYM;
-        }
-        CASE("top-center") {
-            if (LIKELY(!hasEscape))
-                m_token = TOPCENTER_SYM;
-        }
-        CASE("top-left-corner") {
-            if (LIKELY(!hasEscape))
-                m_token = TOPLEFTCORNER_SYM;
-        }
-        CASE("top-right-corner") {
-            if (LIKELY(!hasEscape))
-                m_token = TOPRIGHTCORNER_SYM;
-        }
-        CASE("viewport") {
-            m_token = VIEWPORT_RULE_SYM;
-        }
-        CASE("-internal-rule") {
-            if (LIKELY(!hasEscape))
-                m_token = INTERNAL_RULE_SYM;
-        }
-        CASE("-webkit-region") {
-            if (LIKELY(!hasEscape))
-                m_token = WEBKIT_REGION_RULE_SYM;
-        }
-        CASE("-webkit-filter") {
-            if (LIKELY(!hasEscape))
-                m_token = WEBKIT_FILTER_RULE_SYM;
-        }
-        CASE("-internal-decls") {
-            if (LIKELY(!hasEscape))
-                m_token = INTERNAL_DECLS_SYM;
-        }
-        CASE("-internal-value") {
-            if (LIKELY(!hasEscape))
-                m_token = INTERNAL_VALUE_SYM;
-        }
-        CASE("-webkit-keyframes") {
-            m_token = WEBKIT_KEYFRAMES_SYM;
-        }
-        CASE("-internal-selector") {
-            if (LIKELY(!hasEscape))
-                m_token = INTERNAL_SELECTOR_SYM;
-        }
-        CASE("-internal-medialist") {
-            m_parsingMode = MediaQueryMode;
-            m_token = INTERNAL_MEDIALIST_SYM;
-        }
-        CASE("-internal-keyframe-rule") {
-            if (LIKELY(!hasEscape))
-                m_token = INTERNAL_KEYFRAME_RULE_SYM;
-        }
-        CASE("-internal-keyframe-key-list") {
-            m_token = INTERNAL_KEYFRAME_KEY_LIST_SYM;
-        }
-        CASE("-internal-supports-condition") {
-            m_parsingMode = SupportsMode;
-            m_token = INTERNAL_SUPPORTS_CONDITION_SYM;
-        }
-    }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectSupportsToken(int length)
-{
-    ASSERT(m_parsingMode == SupportsMode);
-    CharacterType* name = tokenStart<CharacterType>();
-
-    SWITCH(name, length) {
-        CASE("or") {
-            m_token = SUPPORTS_OR;
-        }
-        CASE("and") {
-            m_token = SUPPORTS_AND;
-        }
-        CASE("not") {
-            m_token = SUPPORTS_NOT;
-        }
-    }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectCSSVariableDefinitionToken(int length)
-{
-    static const int prefixLength = static_cast<int>(sizeof("var-") - 1);
-    if (length <= prefixLength)
-        return;
-    CharacterType* name = tokenStart<CharacterType>();
-    COMPILE_ASSERT(prefixLength > 0, CSS_variable_prefix_must_be_nonempty);
-    if (name[prefixLength - 1] == '-' && isIdentifierStartAfterDash(name + prefixLength) && isEqualToCSSCaseSensitiveIdentifier(name, "var"))
-        m_token = VAR_DEFINITION;
-}
-
-template <typename SrcCharacterType>
-int CSSParser::realLex(void* yylvalWithoutType)
-{
-    YYSTYPE* yylval = static_cast<YYSTYPE*>(yylvalWithoutType);
-    // Write pointer for the next character.
-    SrcCharacterType* result;
-    CSSParserString resultString;
-    bool hasEscape;
-
-    // The input buffer is terminated by a \0 character, so
-    // it is safe to read one character ahead of a known non-null.
-#ifndef NDEBUG
-    // In debug we check with an ASSERT that the length is > 0 for string types.
-    yylval->string.clear();
-#endif
-
-restartAfterComment:
-    result = currentCharacter<SrcCharacterType>();
-    setTokenStart(result);
-    m_tokenStartLineNumber = m_lineNumber;
-    m_token = *currentCharacter<SrcCharacterType>();
-    ++currentCharacter<SrcCharacterType>();
-
-    switch ((m_token <= 127) ? typesOfASCIICharacters[m_token] : CharacterIdentifierStart) {
-    case CharacterCaselessU:
-        if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '+'))
-            if (parseUnicodeRange<SrcCharacterType>()) {
-                m_token = UNICODERANGE;
-                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
-                break;
-            }
-        // Fall through to CharacterIdentifierStart.
-
-    case CharacterIdentifierStart:
-        --currentCharacter<SrcCharacterType>();
-        parseIdentifier(result, yylval->string, hasEscape);
-        m_token = IDENT;
-
-        if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '(')) {
-            if (m_parsingMode == SupportsMode && !hasEscape) {
-                detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
-                if (m_token != IDENT)
-                    break;
-            }
-
-            m_token = FUNCTION;
-            if (!hasEscape)
-                detectFunctionTypeToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
-
-            // Skip parenthesis
-            ++currentCharacter<SrcCharacterType>();
-            ++result;
-            ++yylval->string.m_length;
-
-            if (token() == URI) {
-                m_token = FUNCTION;
-                // Check whether it is really an URI.
-                if (yylval->string.is8Bit())
-                    parseURI<LChar>(yylval->string);
-                else
-                    parseURI<UChar>(yylval->string);
-            }
-        } else if (UNLIKELY(m_parsingMode != NormalMode) && !hasEscape) {
-            if (m_parsingMode == MediaQueryMode)
-                detectMediaQueryToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
-            else if (m_parsingMode == SupportsMode)
-                detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
-            else if (m_parsingMode == NthChildMode && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[0], 'n')) {
-                if (result - tokenStart<SrcCharacterType>() == 1) {
-                    // String "n" is IDENT but "n+1" is NTH.
-                    if (parseNthChildExtra<SrcCharacterType>()) {
-                        m_token = NTH;
-                        yylval->string.m_length = currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>();
-                    }
-                } else if (result - tokenStart<SrcCharacterType>() >= 2 && tokenStart<SrcCharacterType>()[1] == '-') {
-                    // String "n-" is IDENT but "n-1" is NTH.
-                    // Set currentCharacter to '-' to continue parsing.
-                    SrcCharacterType* nextCharacter = result;
-                    currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 1;
-                    if (parseNthChildExtra<SrcCharacterType>()) {
-                        m_token = NTH;
-                        yylval->string.setLength(currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
-                    } else {
-                        // Revert the change to currentCharacter if unsuccessful.
-                        currentCharacter<SrcCharacterType>() = nextCharacter;
-                    }
-                }
-            }
-        } else if (UNLIKELY(RuntimeEnabledFeatures::cssVariablesEnabled())) {
-            detectCSSVariableDefinitionToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
-        }
-        break;
-
-    case CharacterDot:
-        if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0]))
-            break;
-        // Fall through to CharacterNumber.
-
-    case CharacterNumber: {
-        bool dotSeen = (m_token == '.');
-
-        while (true) {
-            if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0])) {
-                // Only one dot is allowed for a number,
-                // and it must be followed by a digit.
-                if (currentCharacter<SrcCharacterType>()[0] != '.' || dotSeen || !isASCIIDigit(currentCharacter<SrcCharacterType>()[1]))
-                    break;
-                dotSeen = true;
-            }
-            ++currentCharacter<SrcCharacterType>();
-        }
-
-        if (UNLIKELY(m_parsingMode == NthChildMode) && !dotSeen && isASCIIAlphaCaselessEqual(*currentCharacter<SrcCharacterType>(), 'n')) {
-            // "[0-9]+n" is always an NthChild.
-            ++currentCharacter<SrcCharacterType>();
-            parseNthChildExtra<SrcCharacterType>();
-            m_token = NTH;
-            yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
-            break;
-        }
-
-        // Use SVG parser for numbers on SVG presentation attributes.
-        if (isSVGNumberParsingEnabledForMode(m_context.mode)) {
-            // We need to take care of units like 'em' or 'ex'.
-            SrcCharacterType* character = currentCharacter<SrcCharacterType>();
-            if (isASCIIAlphaCaselessEqual(*character, 'e')) {
-                ASSERT(character - tokenStart<SrcCharacterType>() > 0);
-                ++character;
-                if (*character == '-' || *character == '+' || isASCIIDigit(*character)) {
-                    ++character;
-                    while (isASCIIDigit(*character))
-                        ++character;
-                    // Use FLOATTOKEN if the string contains exponents.
-                    dotSeen = true;
-                    currentCharacter<SrcCharacterType>() = character;
-                }
-            }
-            if (!parseSVGNumber(tokenStart<SrcCharacterType>(), character - tokenStart<SrcCharacterType>(), yylval->number))
-                break;
-        } else {
-            yylval->number = charactersToDouble(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
-        }
-
-        // Type of the function.
-        if (isIdentifierStart<SrcCharacterType>()) {
-            SrcCharacterType* type = currentCharacter<SrcCharacterType>();
-            result = currentCharacter<SrcCharacterType>();
-
-            parseIdentifier(result, resultString, hasEscape);
-
-            m_token = DIMEN;
-            if (!hasEscape)
-                detectNumberToken(type, currentCharacter<SrcCharacterType>() - type);
-
-            if (m_token == DIMEN) {
-                // The decoded number is overwritten, but this is intentional.
-                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
-            }
-        } else if (*currentCharacter<SrcCharacterType>() == '%') {
-            // Although the CSS grammar says {num}% we follow
-            // webkit at the moment which uses {num}%+.
-            do {
-                ++currentCharacter<SrcCharacterType>();
-            } while (*currentCharacter<SrcCharacterType>() == '%');
-            m_token = PERCENTAGE;
-        } else
-            m_token = dotSeen ? FLOATTOKEN : INTEGER;
-        break;
-    }
-
-    case CharacterDash:
-        if (isIdentifierStartAfterDash(currentCharacter<SrcCharacterType>())) {
-            --currentCharacter<SrcCharacterType>();
-            parseIdentifier(result, resultString, hasEscape);
-            m_token = IDENT;
-
-            if (*currentCharacter<SrcCharacterType>() == '(') {
-                m_token = FUNCTION;
-                if (!hasEscape)
-                    detectDashToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
-                ++currentCharacter<SrcCharacterType>();
-                ++result;
-            } else if (UNLIKELY(m_parsingMode == NthChildMode) && !hasEscape && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[1], 'n')) {
-                if (result - tokenStart<SrcCharacterType>() == 2) {
-                    // String "-n" is IDENT but "-n+1" is NTH.
-                    if (parseNthChildExtra<SrcCharacterType>()) {
-                        m_token = NTH;
-                        result = currentCharacter<SrcCharacterType>();
-                    }
-                } else if (result - tokenStart<SrcCharacterType>() >= 3 && tokenStart<SrcCharacterType>()[2] == '-') {
-                    // String "-n-" is IDENT but "-n-1" is NTH.
-                    // Set currentCharacter to second '-' of '-n-' to continue parsing.
-                    SrcCharacterType* nextCharacter = result;
-                    currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 2;
-                    if (parseNthChildExtra<SrcCharacterType>()) {
-                        m_token = NTH;
-                        result = currentCharacter<SrcCharacterType>();
-                    } else {
-                        // Revert the change to currentCharacter if unsuccessful.
-                        currentCharacter<SrcCharacterType>() = nextCharacter;
-                    }
-                }
-            }
-            resultString.setLength(result - tokenStart<SrcCharacterType>());
-            yylval->string = resultString;
-        } else if (currentCharacter<SrcCharacterType>()[0] == '-' && currentCharacter<SrcCharacterType>()[1] == '>') {
-            currentCharacter<SrcCharacterType>() += 2;
-            m_token = SGML_CD;
-        } else if (UNLIKELY(m_parsingMode == NthChildMode)) {
-            // "-[0-9]+n" is always an NthChild.
-            if (parseNthChild<SrcCharacterType>()) {
-                parseNthChildExtra<SrcCharacterType>();
-                m_token = NTH;
-                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
-            }
-        }
-        break;
-
-    case CharacterOther:
-        // m_token is simply the current character.
-        break;
-
-    case CharacterNull:
-        // Do not advance pointer at the end of input.
-        --currentCharacter<SrcCharacterType>();
-        break;
-
-    case CharacterWhiteSpace:
-        m_token = WHITESPACE;
-        // Might start with a '\n'.
-        --currentCharacter<SrcCharacterType>();
-        do {
-            if (*currentCharacter<SrcCharacterType>() == '\n')
-                ++m_lineNumber;
-            ++currentCharacter<SrcCharacterType>();
-        } while (*currentCharacter<SrcCharacterType>() <= ' ' && (typesOfASCIICharacters[*currentCharacter<SrcCharacterType>()] == CharacterWhiteSpace));
-        break;
-
-    case CharacterEndMediaQueryOrSupports:
-        if (m_parsingMode == MediaQueryMode || m_parsingMode == SupportsMode)
-            m_parsingMode = NormalMode;
-        break;
-
-    case CharacterEndNthChild:
-        if (m_parsingMode == NthChildMode)
-            m_parsingMode = NormalMode;
-        break;
-
-    case CharacterQuote:
-        if (checkAndSkipString(currentCharacter<SrcCharacterType>(), m_token)) {
-            ++result;
-            parseString<SrcCharacterType>(result, yylval->string, m_token);
-            m_token = STRING;
-        }
-        break;
-
-    case CharacterExclamationMark: {
-        SrcCharacterType* start = skipWhiteSpace(currentCharacter<SrcCharacterType>());
-        if (isEqualToCSSIdentifier(start, "important")) {
-            m_token = IMPORTANT_SYM;
-            currentCharacter<SrcCharacterType>() = start + 9;
-        }
-        break;
-    }
-
-    case CharacterHashmark: {
-        SrcCharacterType* start = currentCharacter<SrcCharacterType>();
-        result = currentCharacter<SrcCharacterType>();
-
-        if (isASCIIDigit(*currentCharacter<SrcCharacterType>())) {
-            // This must be a valid hex number token.
-            do {
-                ++currentCharacter<SrcCharacterType>();
-            } while (isASCIIHexDigit(*currentCharacter<SrcCharacterType>()));
-            m_token = HEX;
-            yylval->string.init(start, currentCharacter<SrcCharacterType>() - start);
-        } else if (isIdentifierStart<SrcCharacterType>()) {
-            m_token = IDSEL;
-            parseIdentifier(result, yylval->string, hasEscape);
-            if (!hasEscape) {
-                // Check whether the identifier is also a valid hex number.
-                SrcCharacterType* current = start;
-                m_token = HEX;
-                do {
-                    if (!isASCIIHexDigit(*current)) {
-                        m_token = IDSEL;
-                        break;
-                    }
-                    ++current;
-                } while (current < result);
-            }
-        }
-        break;
-    }
-
-    case CharacterSlash:
-        // Ignore comments. They are not even considered as white spaces.
-        if (*currentCharacter<SrcCharacterType>() == '*') {
-            const CSSParserLocation startLocation = currentLocation();
-            if (m_sourceDataHandler) {
-                unsigned startOffset = (is8BitSource() ? currentCharacter<LChar>() - m_dataStart8.get() : currentCharacter<UChar>() - m_dataStart16.get()) - 1; // Start with a slash.
-                m_sourceDataHandler->startComment(startOffset - m_parsedTextPrefixLength);
-            }
-            ++currentCharacter<SrcCharacterType>();
-            while (currentCharacter<SrcCharacterType>()[0] != '*' || currentCharacter<SrcCharacterType>()[1] != '/') {
-                if (*currentCharacter<SrcCharacterType>() == '\n')
-                    ++m_lineNumber;
-                if (*currentCharacter<SrcCharacterType>() == '\0') {
-                    // Unterminated comments are simply ignored.
-                    currentCharacter<SrcCharacterType>() -= 2;
-                    reportError(startLocation, UnterminatedCommentError);
-                    break;
-                }
-                ++currentCharacter<SrcCharacterType>();
-            }
-            currentCharacter<SrcCharacterType>() += 2;
-            if (m_sourceDataHandler) {
-                unsigned endOffset = is8BitSource() ? currentCharacter<LChar>() - m_dataStart8.get() : currentCharacter<UChar>() - m_dataStart16.get();
-                unsigned userTextEndOffset = static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength);
-                m_sourceDataHandler->endComment(min(endOffset, userTextEndOffset) - m_parsedTextPrefixLength);
-            }
-            goto restartAfterComment;
-        }
-        break;
-
-    case CharacterDollar:
-        if (*currentCharacter<SrcCharacterType>() == '=') {
-            ++currentCharacter<SrcCharacterType>();
-            m_token = ENDSWITH;
-        }
-        break;
-
-    case CharacterAsterisk:
-        if (*currentCharacter<SrcCharacterType>() == '=') {
-            ++currentCharacter<SrcCharacterType>();
-            m_token = CONTAINS;
-        }
-        break;
-
-    case CharacterPlus:
-        if (UNLIKELY(m_parsingMode == NthChildMode)) {
-            // Simplest case. "+[0-9]*n" is always NthChild.
-            if (parseNthChild<SrcCharacterType>()) {
-                parseNthChildExtra<SrcCharacterType>();
-                m_token = NTH;
-                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
-            }
-        }
-        break;
-
-    case CharacterLess:
-        if (currentCharacter<SrcCharacterType>()[0] == '!' && currentCharacter<SrcCharacterType>()[1] == '-' && currentCharacter<SrcCharacterType>()[2] == '-') {
-            currentCharacter<SrcCharacterType>() += 3;
-            m_token = SGML_CD;
-        }
-        break;
-
-    case CharacterAt:
-        if (isIdentifierStart<SrcCharacterType>()) {
-            m_token = ATKEYWORD;
-            ++result;
-            parseIdentifier(result, resultString, hasEscape);
-            detectAtToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>(), hasEscape);
-        }
-        break;
-
-    case CharacterBackSlash:
-        if (isCSSEscape(*currentCharacter<SrcCharacterType>())) {
-            --currentCharacter<SrcCharacterType>();
-            parseIdentifier(result, yylval->string, hasEscape);
-            m_token = IDENT;
-        }
-        break;
-
-    case CharacterXor:
-        if (*currentCharacter<SrcCharacterType>() == '=') {
-            ++currentCharacter<SrcCharacterType>();
-            m_token = BEGINSWITH;
-        }
-        break;
-
-    case CharacterVerticalBar:
-        if (*currentCharacter<SrcCharacterType>() == '=') {
-            ++currentCharacter<SrcCharacterType>();
-            m_token = DASHMATCH;
-        }
-        break;
-
-    case CharacterTilde:
-        if (*currentCharacter<SrcCharacterType>() == '=') {
-            ++currentCharacter<SrcCharacterType>();
-            m_token = INCLUDES;
-        }
-        break;
-
-    default:
-        ASSERT_NOT_REACHED();
-        break;
-    }
-
-    return token();
-}
-
 CSSParserSelector* CSSParser::createFloatingSelectorWithTagName(const QualifiedName& tagQName)
 {
     CSSParserSelector* selector = new CSSParserSelector(tagQName);
@@ -11054,14 +9513,11 @@
 
 StyleRuleBase* CSSParser::createImportRule(const CSSParserString& url, MediaQuerySet* media)
 {
-    if (!media || !m_allowImportRules) {
-        endRuleBody(true);
+    if (!media || !m_allowImportRules)
         return 0;
-    }
     RefPtr<StyleRuleImport> rule = StyleRuleImport::create(url, media);
     StyleRuleImport* result = rule.get();
     m_parsedRules.append(rule.release());
-    endRuleBody();
     return result;
 }
 
@@ -11069,15 +9525,14 @@
 {
     m_allowImportRules = m_allowNamespaceDeclarations = false;
     RefPtr<StyleRuleMedia> rule;
-    if (rules)
+    if (rules) {
         rule = StyleRuleMedia::create(media ? media : MediaQuerySet::create(), *rules);
-    else {
+    } else {
         RuleList emptyRules;
         rule = StyleRuleMedia::create(media ? media : MediaQuerySet::create(), emptyRules);
     }
     StyleRuleMedia* result = rule.get();
     m_parsedRules.append(rule.release());
-    endRuleBody();
     return result;
 }
 
@@ -11091,21 +9546,20 @@
     unsigned conditionOffset = data->ruleHeaderRange.start + 9;
     unsigned conditionLength = data->ruleHeaderRange.length() - 9;
 
-    if (is8BitSource())
-        conditionText = String(m_dataStart8.get() + conditionOffset, conditionLength).stripWhiteSpace();
+    if (m_tokenizer.is8BitSource())
+        conditionText = String(m_tokenizer.m_dataStart8.get() + conditionOffset, conditionLength).stripWhiteSpace();
     else
-        conditionText = String(m_dataStart16.get() + conditionOffset, conditionLength).stripWhiteSpace();
+        conditionText = String(m_tokenizer.m_dataStart16.get() + conditionOffset, conditionLength).stripWhiteSpace();
 
-    if (rules)
+    if (rules) {
         rule = StyleRuleSupports::create(conditionText, conditionIsSupported, *rules);
-    else {
+    } else {
         RuleList emptyRules;
         rule = StyleRuleSupports::create(conditionText, conditionIsSupported, emptyRules);
     }
 
     StyleRuleSupports* result = rule.get();
     m_parsedRules.append(rule.release());
-    endRuleBody();
 
     return result;
 }
@@ -11116,7 +9570,7 @@
         m_supportsRuleDataStack = adoptPtr(new RuleSourceDataList());
 
     RefPtr<CSSRuleSourceData> data = CSSRuleSourceData::create(CSSRuleSourceData::SUPPORTS_RULE);
-    data->ruleHeaderRange.start = tokenStartOffset();
+    data->ruleHeaderRange.start = m_tokenizer.tokenStartOffset();
     m_supportsRuleDataStack->append(data);
 }
 
@@ -11124,10 +9578,10 @@
 {
     ASSERT(m_supportsRuleDataStack && !m_supportsRuleDataStack->isEmpty());
 
-    if (is8BitSource())
-        m_supportsRuleDataStack->last()->ruleHeaderRange.end = tokenStart<LChar>() - m_dataStart8.get();
+    if (m_tokenizer.is8BitSource())
+        m_supportsRuleDataStack->last()->ruleHeaderRange.end = m_tokenizer.tokenStart<LChar>() - m_tokenizer.m_dataStart8.get();
     else
-        m_supportsRuleDataStack->last()->ruleHeaderRange.end = tokenStart<UChar>() - m_dataStart16.get();
+        m_supportsRuleDataStack->last()->ruleHeaderRange.end = m_tokenizer.tokenStart<UChar>() - m_tokenizer.m_dataStart16.get();
 }
 
 PassRefPtr<CSSRuleSourceData> CSSParser::popSupportsRuleData()
@@ -11147,6 +9601,15 @@
     return listPtr;
 }
 
+CSSParser::RuleList* CSSParser::appendRule(RuleList* ruleList, StyleRuleBase* rule)
+{
+    if (rule) {
+        if (!ruleList)
+            ruleList = createRuleList();
+        ruleList->append(rule);
+    }
+    return ruleList;
+}
 
 template <typename CharacterType>
 ALWAYS_INLINE static void makeLower(const CharacterType* input, CharacterType* output, unsigned length)
@@ -11169,12 +9632,12 @@
 void CSSParser::tokenToLowerCase(const CSSParserString& token)
 {
     size_t length = token.length();
-    if (is8BitSource()) {
-        size_t offset = token.characters8() - m_dataStart8.get();
-        makeLower(token.characters8(), m_dataStart8.get() + offset, length);
+    if (m_tokenizer.is8BitSource()) {
+        size_t offset = token.characters8() - m_tokenizer.m_dataStart8.get();
+        makeLower(token.characters8(), m_tokenizer.m_dataStart8.get() + offset, length);
     } else {
-        size_t offset = token.characters16() - m_dataStart16.get();
-        makeLower(token.characters16(), m_dataStart16.get() + offset, length);
+        size_t offset = token.characters16() - m_tokenizer.m_dataStart16.get();
+        makeLower(token.characters16(), m_tokenizer.m_dataStart16.get() + offset, length);
     }
 }
 
@@ -11184,12 +9647,12 @@
         return;
 
     CSSParserLocation location;
-    location.lineNumber = m_lineNumber;
+    location.lineNumber = m_tokenizer.m_lineNumber;
     location.offset = m_ruleHeaderStartOffset;
-    if (is8BitSource())
-        location.token.init(m_dataStart8.get() + m_ruleHeaderStartOffset, 0);
+    if (m_tokenizer.is8BitSource())
+        location.token.init(m_tokenizer.m_dataStart8.get() + m_ruleHeaderStartOffset, 0);
     else
-        location.token.init(m_dataStart16.get() + m_ruleHeaderStartOffset, 0);
+        location.token.init(m_tokenizer.m_dataStart16.get() + m_ruleHeaderStartOffset, 0);
 
     reportError(location, m_ruleHeaderType == CSSRuleSourceData::STYLE_RULE ? InvalidSelectorError : InvalidRuleError);
 
@@ -11233,7 +9696,6 @@
     rule->setVendorPrefixed(isPrefixed);
     StyleRuleKeyframes* rulePtr = rule.get();
     m_parsedRules.append(rule.release());
-    endRuleBody();
     return rulePtr;
 }
 
@@ -11249,9 +9711,7 @@
         rule->setProperties(createStylePropertySet());
         result = rule.get();
         m_parsedRules.append(rule.release());
-        endRuleBody();
-    } else
-        endRuleBody(true);
+    }
     clearProperties();
     return result;
 }
@@ -11269,7 +9729,6 @@
             // have 'initial' value and cannot 'inherit' from parent.
             // See http://dev.w3.org/csswg/css3-fonts/#font-family-desc
             clearProperties();
-            endRuleBody(true);
             return 0;
         }
     }
@@ -11278,23 +9737,8 @@
     clearProperties();
     StyleRuleFontFace* result = rule.get();
     m_parsedRules.append(rule.release());
-    endRuleBody();
-    return result;
-}
-
-StyleRuleBase* CSSParser::createHostRule(RuleList* rules)
-{
-    m_allowImportRules = m_allowNamespaceDeclarations = false;
-    RefPtr<StyleRuleHost> rule;
-    if (rules)
-        rule = StyleRuleHost::create(*rules);
-    else {
-        RuleList emptyRules;
-        rule = StyleRuleHost::create(emptyRules);
-    }
-    StyleRuleHost* result = rule.get();
-    m_parsedRules.append(rule.release());
-    endRuleBody();
+    if (m_styleSheet)
+        m_styleSheet->setHasFontFaceRule(true);
     return result;
 }
 
@@ -11465,9 +9909,7 @@
         rule->setProperties(createStylePropertySet());
         pageRule = rule.get();
         m_parsedRules.append(rule.release());
-        endRuleBody();
-    } else
-        endRuleBody(true);
+    }
     clearProperties();
     return pageRule;
 }
@@ -11480,10 +9922,11 @@
 
 StyleRuleBase* CSSParser::createRegionRule(Vector<OwnPtr<CSSParserSelector> >* regionSelector, RuleList* rules)
 {
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !regionSelector || !rules) {
-        endRuleBody(true);
+    if (m_useCounter)
+        m_useCounter->count(UseCounter::CSSWebkitRegionAtRule);
+
+    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !regionSelector || !rules)
         return 0;
-    }
 
     m_allowImportRules = m_allowNamespaceDeclarations = false;
 
@@ -11555,59 +9998,78 @@
         m_styleSheet->setHasSyntacticallyValidCSSHeader(false);
 }
 
+void CSSParser::startRule()
+{
+    if (!m_sourceDataHandler)
+        return;
+
+    ASSERT(m_ruleHasHeader);
+    m_ruleHasHeader = false;
+}
+
+void CSSParser::endRule(bool valid)
+{
+    if (!m_sourceDataHandler)
+        return;
+
+    if (m_ruleHasHeader)
+        m_sourceDataHandler->endRuleBody(m_tokenizer.safeUserStringTokenOffset(), !valid);
+    m_ruleHasHeader = true;
+}
+
 void CSSParser::startRuleHeader(CSSRuleSourceData::Type ruleType)
 {
     resumeErrorLogging();
     m_ruleHeaderType = ruleType;
-    m_ruleHeaderStartOffset = safeUserStringTokenOffset();
-    m_ruleHeaderStartLineNumber = m_tokenStartLineNumber;
-    if (m_sourceDataHandler)
+    m_ruleHeaderStartOffset = m_tokenizer.safeUserStringTokenOffset();
+    m_ruleHeaderStartLineNumber = m_tokenizer.m_tokenStartLineNumber;
+    if (m_sourceDataHandler) {
+        ASSERT(!m_ruleHasHeader);
         m_sourceDataHandler->startRuleHeader(ruleType, m_ruleHeaderStartOffset);
+        m_ruleHasHeader = true;
+    }
 }
 
 void CSSParser::endRuleHeader()
 {
+    ASSERT(m_ruleHeaderType != CSSRuleSourceData::UNKNOWN_RULE);
     m_ruleHeaderType = CSSRuleSourceData::UNKNOWN_RULE;
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->endRuleHeader(safeUserStringTokenOffset());
+    if (m_sourceDataHandler) {
+        ASSERT(m_ruleHasHeader);
+        m_sourceDataHandler->endRuleHeader(m_tokenizer.safeUserStringTokenOffset());
+    }
 }
 
 void CSSParser::startSelector()
 {
     if (m_sourceDataHandler)
-        m_sourceDataHandler->startSelector(safeUserStringTokenOffset());
+        m_sourceDataHandler->startSelector(m_tokenizer.safeUserStringTokenOffset());
 }
 
 void CSSParser::endSelector()
 {
     if (m_sourceDataHandler)
-        m_sourceDataHandler->endSelector(safeUserStringTokenOffset());
+        m_sourceDataHandler->endSelector(m_tokenizer.safeUserStringTokenOffset());
 }
 
 void CSSParser::startRuleBody()
 {
     if (m_sourceDataHandler)
-        m_sourceDataHandler->startRuleBody(safeUserStringTokenOffset());
-}
-
-void CSSParser::endRuleBody(bool discard)
-{
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->endRuleBody(safeUserStringTokenOffset(), discard);
+        m_sourceDataHandler->startRuleBody(m_tokenizer.safeUserStringTokenOffset());
 }
 
 void CSSParser::startProperty()
 {
     resumeErrorLogging();
     if (m_sourceDataHandler)
-        m_sourceDataHandler->startProperty(safeUserStringTokenOffset());
+        m_sourceDataHandler->startProperty(m_tokenizer.safeUserStringTokenOffset());
 }
 
 void CSSParser::endProperty(bool isImportantFound, bool isPropertyParsed, ErrorType errorType)
 {
     m_id = CSSPropertyInvalid;
     if (m_sourceDataHandler)
-        m_sourceDataHandler->endProperty(isImportantFound, isPropertyParsed, safeUserStringTokenOffset(), errorType);
+        m_sourceDataHandler->endProperty(isImportantFound, isPropertyParsed, m_tokenizer.safeUserStringTokenOffset(), errorType);
 }
 
 void CSSParser::startEndUnknownRule()
@@ -11616,18 +10078,11 @@
         m_sourceDataHandler->startEndUnknownRule();
 }
 
-unsigned CSSParser::safeUserStringTokenOffset()
-{
-    return min(tokenStartOffset(), static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength)) - m_parsedTextPrefixLength;
-}
-
 StyleRuleBase* CSSParser::createViewportRule()
 {
     // Allow @viewport rules from UA stylesheets even if the feature is disabled.
-    if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode)) {
-        endRuleBody(true);
+    if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode()))
         return 0;
-    }
 
     m_allowImportRules = m_allowNamespaceDeclarations = false;
 
@@ -11638,14 +10093,13 @@
 
     StyleRuleViewport* result = rule.get();
     m_parsedRules.append(rule.release());
-    endRuleBody();
 
     return result;
 }
 
 bool CSSParser::parseViewportProperty(CSSPropertyID propId, bool important)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode));
+    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode()));
 
     CSSParserValue* value = m_valueList->current();
     if (!value)
@@ -11705,7 +10159,7 @@
 
 bool CSSParser::parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode));
+    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode()));
     unsigned numValues = m_valueList->size();
 
     if (numValues > 2)
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/CSSParser.h
index 48ddf1e..c973b77 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/CSSParser.h
@@ -33,9 +33,10 @@
 #include "core/css/CSSProperty.h"
 #include "core/css/CSSPropertySourceData.h"
 #include "core/css/CSSSelector.h"
+#include "core/css/CSSTokenizer.h"
 #include "core/css/MediaQuery.h"
 #include "core/css/StylePropertySet.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "platform/graphics/Color.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
@@ -68,6 +69,7 @@
 class StyleKeyframe;
 class StyleSheetContents;
 
+// FIXME: This class is shared with CSSTokenizer so should we rename it to CSSSourceLocation?
 struct CSSParserLocation {
     unsigned offset;
     unsigned lineNumber;
@@ -185,6 +187,7 @@
     PassRefPtr<CSSValue> parseGridTrackSize(CSSParserValueList& inputList);
     PassRefPtr<CSSPrimitiveValue> parseGridBreadth(CSSParserValue*);
     PassRefPtr<CSSValue> parseGridTemplate();
+    void parseGridLineNames(CSSParserValueList* inputList, CSSValueList&);
 
     bool parseClipShape(CSSPropertyID, bool important);
 
@@ -226,7 +229,8 @@
 
     // CSS3 Parsing Routines (for properties specific to CSS3)
     PassRefPtr<CSSValueList> parseShadow(CSSParserValueList*, CSSPropertyID);
-    bool parseBorderImage(CSSPropertyID, RefPtr<CSSValue>&, bool important = false);
+    bool parseBorderImageShorthand(CSSPropertyID, bool important);
+    PassRefPtr<CSSValue> parseBorderImage(CSSPropertyID);
     bool parseBorderImageRepeat(RefPtr<CSSValue>&);
     bool parseBorderImageSlice(CSSPropertyID, RefPtr<CSSBorderImageSliceValue>&);
     bool parseBorderImageWidth(RefPtr<CSSPrimitiveValue>&);
@@ -295,6 +299,8 @@
 
     bool parseFontVariantLigatures(bool important);
 
+    bool parseGeneratedImage(CSSParserValueList*, RefPtr<CSSValue>&);
+
     CSSParserSelector* createFloatingSelector();
     CSSParserSelector* createFloatingSelectorWithTagName(const QualifiedName&);
     PassOwnPtr<CSSParserSelector> sinkFloatingSelector(CSSParserSelector*);
@@ -319,6 +325,7 @@
     typedef Vector<RefPtr<StyleRuleBase> > RuleList;
     StyleRuleBase* createMediaRule(MediaQuerySet*, RuleList*);
     RuleList* createRuleList();
+    RuleList* appendRule(RuleList*, StyleRuleBase*);
     StyleRuleBase* createStyleRule(Vector<OwnPtr<CSSParserSelector> >* selectors);
     StyleRuleBase* createFontFaceRule();
     StyleRuleBase* createPageRule(PassOwnPtr<CSSParserSelector> pageSelector);
@@ -398,16 +405,15 @@
     AtomicString m_defaultNamespace;
 
     // tokenizer methods and data
-    size_t m_parsedTextPrefixLength;
-    size_t m_parsedTextSuffixLength;
     SourceDataHandler* m_sourceDataHandler;
 
+    void startRule();
+    void endRule(bool valid);
     void startRuleHeader(CSSRuleSourceData::Type);
     void endRuleHeader();
     void startSelector();
     void endSelector();
     void startRuleBody();
-    void endRuleBody(bool discard = false);
     void startProperty();
     void endProperty(bool isImportantFound, bool isPropertyParsed, ErrorType = NoError);
     void startEndUnknownRule();
@@ -418,10 +424,6 @@
     void setLocationLabel(const CSSParserLocation& location) { m_locationLabel = location; }
     const CSSParserLocation& lastLocationLabel() const { return m_locationLabel; }
 
-    inline int lex(void* yylval) { return (this->*m_lexFunc)(yylval); }
-
-    int token() { return m_token; }
-
     void tokenToLowerCase(const CSSParserString& token);
 
     void markViewportRuleBodyStart() { m_inViewport = true; }
@@ -434,7 +436,7 @@
 
     static KURL completeURL(const CSSParserContext&, const String& url);
 
-    CSSParserLocation currentLocation();
+    CSSParserLocation currentLocation() { return m_tokenizer.currentLocation(); }
 
 private:
     enum PropertyType {
@@ -484,84 +486,11 @@
         CSSParserMode m_mode;
     };
 
-    bool is8BitSource() const { return m_is8BitSource; }
-
-    template <typename SourceCharacterType>
-    int realLex(void* yylval);
-
-    UChar*& currentCharacter16();
-
-    template <typename CharacterType>
-    inline CharacterType*& currentCharacter();
-
-    template <typename CharacterType>
-    inline CharacterType* tokenStart();
-
-    template <typename CharacterType>
-    inline CharacterType* dataStart();
-
-    template <typename CharacterType>
-    inline void setTokenStart(CharacterType*);
-
-    inline unsigned tokenStartOffset();
-    inline UChar tokenStartChar();
-
-    template <typename CharacterType>
-    inline bool isIdentifierStart();
-
     inline void ensureLineEndings();
 
-    template <typename CharacterType>
-    inline CSSParserLocation tokenLocation();
-
-    template <typename CharacterType>
-    unsigned parseEscape(CharacterType*&);
-    template <typename DestCharacterType>
-    inline void UnicodeToChars(DestCharacterType*&, unsigned);
-    template <typename SrcCharacterType, typename DestCharacterType>
-    inline bool parseIdentifierInternal(SrcCharacterType*&, DestCharacterType*&, bool&);
-
-    template <typename CharacterType>
-    inline void parseIdentifier(CharacterType*&, CSSParserString&, bool&);
-
-    template <typename SrcCharacterType, typename DestCharacterType>
-    inline bool parseStringInternal(SrcCharacterType*&, DestCharacterType*&, UChar);
-
-    template <typename CharacterType>
-    inline void parseString(CharacterType*&, CSSParserString& resultString, UChar);
-
-    template <typename CharacterType>
-    inline bool findURI(CharacterType*& start, CharacterType*& end, UChar& quote);
-
-    template <typename SrcCharacterType, typename DestCharacterType>
-    inline bool parseURIInternal(SrcCharacterType*&, DestCharacterType*&, UChar quote);
-
-    template <typename CharacterType>
-    inline void parseURI(CSSParserString&);
-    template <typename CharacterType>
-    inline bool parseUnicodeRange();
-    template <typename CharacterType>
-    bool parseNthChild();
-    template <typename CharacterType>
-    bool parseNthChildExtra();
-    template <typename CharacterType>
-    inline bool detectFunctionTypeToken(int);
-    template <typename CharacterType>
-    inline void detectMediaQueryToken(int);
-    template <typename CharacterType>
-    inline void detectNumberToken(CharacterType*, int);
-    template <typename CharacterType>
-    inline void detectDashToken(int);
-    template <typename CharacterType>
-    inline void detectAtToken(int, bool);
-    template <typename CharacterType>
-    inline void detectSupportsToken(int);
-    template <typename CharacterType>
-    inline void detectCSSVariableDefinitionToken(int);
-
     void setStyleSheet(StyleSheetContents* styleSheet) { m_styleSheet = styleSheet; }
 
-    bool inQuirksMode() const { return isQuirksModeBehavior(m_context.mode); }
+    bool inQuirksMode() const { return isQuirksModeBehavior(m_context.mode()); }
     bool inViewport() const { return m_inViewport; }
 
     KURL completeURL(const String& url) const;
@@ -580,9 +509,6 @@
 
     void deleteFontFaceOnlyValues();
 
-    bool isGeneratedImageValue(CSSParserValue*) const;
-    bool parseGeneratedImage(CSSParserValueList*, RefPtr<CSSValue>&);
-
     bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, StyleSheetContents* contextStyleSheet);
     PassRefPtr<ImmutableStylePropertySet> parseDeclaration(const String&, StyleSheetContents* contextStyleSheet);
 
@@ -603,34 +529,15 @@
 
     bool parseColor(const String&);
 
-    enum ParsingMode {
-        NormalMode,
-        MediaQueryMode,
-        SupportsMode,
-        NthChildMode
-    };
-
-    ParsingMode m_parsingMode;
-    bool m_is8BitSource;
-    OwnPtr<LChar[]> m_dataStart8;
-    OwnPtr<UChar[]> m_dataStart16;
-    LChar* m_currentCharacter8;
-    UChar* m_currentCharacter16;
     const String* m_source;
-    union {
-        LChar* ptr8;
-        UChar* ptr16;
-    } m_tokenStart;
-    unsigned m_length;
-    int m_token;
     TextPosition m_startPosition;
-    int m_lineNumber;
-    int m_tokenStartLineNumber;
     CSSRuleSourceData::Type m_ruleHeaderType;
     unsigned m_ruleHeaderStartOffset;
     int m_ruleHeaderStartLineNumber;
     OwnPtr<Vector<unsigned> > m_lineEndings;
 
+    bool m_ruleHasHeader;
+
     bool m_allowImportRules;
     bool m_allowNamespaceDeclarations;
 
@@ -643,8 +550,6 @@
 
     bool useLegacyBackgroundSizeShorthandBehavior() const;
 
-    int (CSSParser::*m_lexFunc)(void*);
-
     Vector<RefPtr<StyleRuleBase> > m_parsedRules;
     Vector<RefPtr<StyleKeyframe> > m_parsedKeyframes;
     Vector<RefPtr<MediaQuerySet> > m_parsedMediaQuerySets;
@@ -700,7 +605,7 @@
 
     bool shouldAcceptUnitLessValues(CSSParserValue*, Units, CSSParserMode);
 
-    inline bool validUnit(CSSParserValue* value, Units unitflags, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue) { return validUnit(value, unitflags, m_context.mode, releaseCalc); }
+    inline bool validUnit(CSSParserValue* value, Units unitflags, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue) { return validUnit(value, unitflags, m_context.mode(), releaseCalc); }
     bool validUnit(CSSParserValue*, Units, CSSParserMode, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue);
 
     bool parseBorderImageQuad(Units, RefPtr<CSSPrimitiveValue>&);
@@ -708,10 +613,10 @@
     double parsedDouble(CSSParserValue*, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue);
     bool isCalculation(CSSParserValue*);
 
-    inline unsigned safeUserStringTokenOffset();
-
     UseCounter* m_useCounter;
 
+    CSSTokenizer m_tokenizer;
+
     friend class TransformOperationInfo;
     friend class FilterOperationInfo;
 };
@@ -759,35 +664,9 @@
 
 bool isValidNthToken(const CSSParserString&);
 
-template <>
-inline void CSSParser::setTokenStart<LChar>(LChar* tokenStart)
-{
-    m_tokenStart.ptr8 = tokenStart;
-}
-
-template <>
-inline void CSSParser::setTokenStart<UChar>(UChar* tokenStart)
-{
-    m_tokenStart.ptr16 = tokenStart;
-}
-
-inline unsigned CSSParser::tokenStartOffset()
-{
-    if (is8BitSource())
-        return m_tokenStart.ptr8 - m_dataStart8.get();
-    return m_tokenStart.ptr16 - m_dataStart16.get();
-}
-
-inline UChar CSSParser::tokenStartChar()
-{
-    if (is8BitSource())
-        return *m_tokenStart.ptr8;
-    return *m_tokenStart.ptr16;
-}
-
 inline int cssyylex(void* yylval, CSSParser* parser)
 {
-    return parser->lex(yylval);
+    return parser->m_tokenizer.lex(yylval);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSParserMode.cpp b/Source/core/css/CSSParserMode.cpp
new file mode 100644
index 0000000..420ecfa
--- /dev/null
+++ b/Source/core/css/CSSParserMode.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
+ * Copyright (C) 2012 Intel Corporation. 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.
+ */
+
+#include "config.h"
+#include "core/css/CSSParserMode.h"
+
+#include "core/dom/Document.h"
+#include "core/page/Settings.h"
+
+namespace WebCore {
+
+CSSParserContext::CSSParserContext(CSSParserMode mode)
+    : m_mode(mode)
+    , m_isHTMLDocument(false)
+    , m_useLegacyBackgroundSizeShorthandBehavior(false)
+{
+}
+
+CSSParserContext::CSSParserContext(const Document& document, const KURL& baseURL, const String& charset)
+    : m_baseURL(baseURL.isNull() ? document.baseURL() : baseURL)
+    , m_charset(charset)
+    , m_mode(document.inQuirksMode() ? HTMLQuirksMode : HTMLStandardMode)
+    , m_isHTMLDocument(document.isHTMLDocument())
+    , m_useLegacyBackgroundSizeShorthandBehavior(document.settings() ? document.settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
+{
+}
+
+bool CSSParserContext::operator==(const CSSParserContext& other) const
+{
+    return m_baseURL == other.m_baseURL
+        && m_charset == other.m_charset
+        && m_mode == other.m_mode
+        && m_isHTMLDocument == other.m_isHTMLDocument
+        && m_useLegacyBackgroundSizeShorthandBehavior == other.m_useLegacyBackgroundSizeShorthandBehavior;
+}
+
+const CSSParserContext& strictCSSParserContext()
+{
+    DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (HTMLStandardMode));
+    return strictContext;
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/CSSParserMode.h b/Source/core/css/CSSParserMode.h
index e093976..efcac21 100644
--- a/Source/core/css/CSSParserMode.h
+++ b/Source/core/css/CSSParserMode.h
@@ -31,7 +31,7 @@
 #ifndef CSSParserMode_h
 #define CSSParserMode_h
 
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 
 namespace WebCore {
 
@@ -88,25 +88,38 @@
     return mode != UASheetMode;
 }
 
-struct CSSParserContext {
+class CSSParserContext {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    CSSParserContext(CSSParserMode, const KURL& baseURL = KURL());
+    CSSParserContext(CSSParserMode);
     CSSParserContext(const Document&, const KURL& baseURL = KURL(), const String& charset = emptyString());
 
-    KURL baseURL;
-    String charset;
-    CSSParserMode mode;
-    bool isHTMLDocument;
-    bool needsSiteSpecificQuirks;
+    bool operator==(const CSSParserContext&) const;
+    bool operator!=(const CSSParserContext& other) const { return !(*this == other); }
+
+    CSSParserMode mode() const { return m_mode; }
+    const KURL& baseURL() const { return m_baseURL; }
+    const String& charset() const { return m_charset; }
+    bool isHTMLDocument() const { return m_isHTMLDocument; }
+
     // This quirk is to maintain compatibility with Android apps built on
     // the Android SDK prior to and including version 18. Presumably, this
     // can be removed any time after 2015. See http://crbug.com/277157.
-    bool useLegacyBackgroundSizeShorthandBehavior;
-};
+    bool useLegacyBackgroundSizeShorthandBehavior() const { return m_useLegacyBackgroundSizeShorthandBehavior; }
 
-bool operator==(const CSSParserContext&, const CSSParserContext&);
-inline bool operator!=(const CSSParserContext& a, const CSSParserContext& b) { return !(a == b); }
+    // FIXME: These setters shouldn't exist, however the current lifetime of CSSParserContext
+    // is not well understood and thus we sometimes need to override these fields.
+    void setMode(CSSParserMode mode) { m_mode = mode; }
+    void setBaseURL(const KURL& baseURL) { m_baseURL = baseURL; }
+    void setCharset(const String& charset) { m_charset = charset; }
+
+private:
+    KURL m_baseURL;
+    String m_charset;
+    CSSParserMode m_mode;
+    bool m_isHTMLDocument;
+    bool m_useLegacyBackgroundSizeShorthandBehavior;
+};
 
 const CSSParserContext& strictCSSParserContext();
 
diff --git a/Source/core/css/CSSParserValues.cpp b/Source/core/css/CSSParserValues.cpp
index 9863e9a..5d883e2 100644
--- a/Source/core/css/CSSParserValues.cpp
+++ b/Source/core/css/CSSParserValues.cpp
@@ -25,17 +25,40 @@
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSSelectorList.h"
+#include "core/html/parser/HTMLParserIdioms.h"
 
 namespace WebCore {
 
 using namespace WTF;
 
+AtomicString CSSParserString::atomicSubstring(unsigned position, unsigned length) const
+{
+    ASSERT(m_length >= position + length);
+
+    if (is8Bit())
+        return AtomicString(characters8() + position, length);
+    return AtomicString(characters16() + position, length);
+}
+
+void CSSParserString::trimTrailingWhitespace()
+{
+    if (is8Bit()) {
+        while (m_length > 0 && isHTMLSpace<LChar>(m_data.characters8[m_length - 1]))
+            --m_length;
+    } else {
+        while (m_length > 0 && isHTMLSpace<UChar>(m_data.characters16[m_length - 1]))
+            --m_length;
+    }
+}
+
 CSSParserValueList::~CSSParserValueList()
 {
     size_t numValues = m_values.size();
     for (size_t i = 0; i < numValues; i++) {
         if (m_values[i].unit == CSSParserValue::Function)
             delete m_values[i].function;
+        else if (m_values[i].unit == CSSParserValue::ValueList)
+            delete m_values[i].valueList;
     }
 }
 
@@ -73,6 +96,8 @@
     }
     if (unit == CSSParserValue::Function)
         return CSSFunctionValue::create(function);
+    if (unit == CSSParserValue::ValueList)
+        return CSSValueList::createFromParserValueList(valueList);
     if (unit >= CSSParserValue::Q_EMS)
         return CSSPrimitiveValue::createAllowingMarginQuirk(fValue, CSSPrimitiveValue::CSS_EMS);
 
@@ -234,5 +259,4 @@
     return 0;
 }
 
-}
-
+} // namespace WebCore
diff --git a/Source/core/css/CSSParserValues.h b/Source/core/css/CSSParserValues.h
index 0aafa37..7d423e7 100644
--- a/Source/core/css/CSSParserValues.h
+++ b/Source/core/css/CSSParserValues.h
@@ -131,6 +131,12 @@
     bool m_is8Bit;
 };
 
+template <>
+inline const LChar* CSSParserString::characters<LChar>() const { return characters8(); }
+
+template <>
+inline const UChar* CSSParserString::characters<UChar>() const { return characters16(); }
+
 struct CSSParserFunction;
 
 struct CSSParserValue {
@@ -141,16 +147,19 @@
         int iValue;
         CSSParserString string;
         CSSParserFunction* function;
+        CSSParserValueList* valueList;
     };
     enum {
-        Operator = 0x100000,
-        Function = 0x100001,
-        Q_EMS    = 0x100002
+        Operator  = 0x100000,
+        Function  = 0x100001,
+        ValueList = 0x100002,
+        Q_EMS     = 0x100003,
     };
     int unit;
 
     inline void setFromNumber(double value, int unit = CSSPrimitiveValue::CSS_NUMBER);
     inline void setFromFunction(CSSParserFunction*);
+    inline void setFromValueList(PassOwnPtr<CSSParserValueList>);
 
     PassRefPtr<CSSValue> createCSSValue();
 };
@@ -215,7 +224,6 @@
     void setForPage() { m_selector->setForPage(); }
     void setRelationIsAffectedByPseudoContent() { m_selector->setRelationIsAffectedByPseudoContent(); }
     bool relationIsAffectedByPseudoContent() const { return m_selector->relationIsAffectedByPseudoContent(); }
-    void setMatchUserAgentOnly() { m_selector->setMatchUserAgentOnly(); }
 
     void adoptSelectorVector(Vector<OwnPtr<CSSParserSelector> >& selectorVector);
 
@@ -265,6 +273,13 @@
     unit = Function;
 }
 
+inline void CSSParserValue::setFromValueList(PassOwnPtr<CSSParserValueList> valueList)
+{
+    id = CSSValueInvalid;
+    this->valueList = valueList.leakPtr();
+    unit = ValueList;
+}
+
 }
 
 #endif
diff --git a/Source/core/css/CSSPrimitiveValue.cpp b/Source/core/css/CSSPrimitiveValue.cpp
index 2bc98a8..16612d6 100644
--- a/Source/core/css/CSSPrimitiveValue.cpp
+++ b/Source/core/css/CSSPrimitiveValue.cpp
@@ -301,7 +301,6 @@
     case Calculated:
         init(CSSCalcValue::create(length.calculationValue(), zoom));
         return;
-    case Relative:
     case Undefined:
         ASSERT_NOT_REACHED();
         break;
@@ -369,7 +368,6 @@
             m_value.num = length.viewportPercentageLength();
             break;
         case Calculated:
-        case Relative:
         case Undefined:
             ASSERT_NOT_REACHED();
             break;
@@ -624,12 +622,12 @@
     return result * multiplier;
 }
 
-void CSSPrimitiveValue::setFloatValue(unsigned short, double, ExceptionState& es)
+void CSSPrimitiveValue::setFloatValue(unsigned short, double, ExceptionState& exceptionState)
 {
     // Keeping values immutable makes optimizations easier and allows sharing of the primitive value objects.
     // No other engine supports mutating style through this API. Computed style is always read-only anyway.
     // Supporting setter would require making primitive value copy-on-write and taking care of style invalidation.
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
 double CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(unsigned short unitType)
@@ -684,12 +682,12 @@
     return factor;
 }
 
-double CSSPrimitiveValue::getDoubleValue(unsigned short unitType, ExceptionState& es) const
+double CSSPrimitiveValue::getDoubleValue(unsigned short unitType, ExceptionState& exceptionState) const
 {
     double result = 0;
     bool success = getDoubleValueInternal(static_cast<UnitTypes>(unitType), &result);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0.0;
     }
 
@@ -784,15 +782,15 @@
     return true;
 }
 
-void CSSPrimitiveValue::setStringValue(unsigned short, const String&, ExceptionState& es)
+void CSSPrimitiveValue::setStringValue(unsigned short, const String&, ExceptionState& exceptionState)
 {
     // Keeping values immutable makes optimizations easier and allows sharing of the primitive value objects.
     // No other engine supports mutating style through this API. Computed style is always read-only anyway.
     // Supporting setter would require making primitive value copy-on-write and taking care of style invalidation.
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
-String CSSPrimitiveValue::getStringValue(ExceptionState& es) const
+String CSSPrimitiveValue::getStringValue(ExceptionState& exceptionState) const
 {
     switch (m_primitiveUnitType) {
         case CSS_STRING:
@@ -805,7 +803,7 @@
         case CSS_PROPERTY_ID:
             return propertyName(m_value.propertyID);
         default:
-            es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
             break;
     }
 
@@ -831,40 +829,40 @@
     return String();
 }
 
-Counter* CSSPrimitiveValue::getCounterValue(ExceptionState& es) const
+Counter* CSSPrimitiveValue::getCounterValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_COUNTER) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return m_value.counter;
 }
 
-Rect* CSSPrimitiveValue::getRectValue(ExceptionState& es) const
+Rect* CSSPrimitiveValue::getRectValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_RECT) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return m_value.rect;
 }
 
-Quad* CSSPrimitiveValue::getQuadValue(ExceptionState& es) const
+Quad* CSSPrimitiveValue::getQuadValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_QUAD) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return m_value.quad;
 }
 
-PassRefPtr<RGBColor> CSSPrimitiveValue::getRGBColorValue(ExceptionState& es) const
+PassRefPtr<RGBColor> CSSPrimitiveValue::getRGBColorValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_RGBCOLOR) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -872,10 +870,10 @@
     return RGBColor::create(m_value.rgbcolor);
 }
 
-Pair* CSSPrimitiveValue::getPairValue(ExceptionState& es) const
+Pair* CSSPrimitiveValue::getPairValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_PAIR) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
diff --git a/Source/core/css/CSSPrimitiveValue.h b/Source/core/css/CSSPrimitiveValue.h
index c4f2e36..086532e 100644
--- a/Source/core/css/CSSPrimitiveValue.h
+++ b/Source/core/css/CSSPrimitiveValue.h
@@ -267,15 +267,15 @@
     double getDoubleValue() const;
 
     void setFloatValue(unsigned short unitType, double floatValue, ExceptionState&);
-    float getFloatValue(unsigned short unitType, ExceptionState& es) const { return getValue<float>(unitType, es); }
+    float getFloatValue(unsigned short unitType, ExceptionState& exceptionState) const { return getValue<float>(unitType, exceptionState); }
     float getFloatValue(unsigned short unitType) const { return getValue<float>(unitType); }
     float getFloatValue() const { return getValue<float>(); }
 
-    int getIntValue(unsigned short unitType, ExceptionState& es) const { return getValue<int>(unitType, es); }
+    int getIntValue(unsigned short unitType, ExceptionState& exceptionState) const { return getValue<int>(unitType, exceptionState); }
     int getIntValue(unsigned short unitType) const { return getValue<int>(unitType); }
     int getIntValue() const { return getValue<int>(); }
 
-    template<typename T> inline T getValue(unsigned short unitType, ExceptionState& es) const { return clampTo<T>(getDoubleValue(unitType, es)); }
+    template<typename T> inline T getValue(unsigned short unitType, ExceptionState& exceptionState) const { return clampTo<T>(getDoubleValue(unitType, exceptionState)); }
     template<typename T> inline T getValue(unsigned short unitType) const { return clampTo<T>(getDoubleValue(unitType)); }
     template<typename T> inline T getValue() const { return clampTo<T>(getDoubleValue()); }
 
diff --git a/Source/core/css/CSSPrimitiveValueMappings.h b/Source/core/css/CSSPrimitiveValueMappings.h
index 2b293fa..67cd5ea 100644
--- a/Source/core/css/CSSPrimitiveValueMappings.h
+++ b/Source/core/css/CSSPrimitiveValueMappings.h
@@ -34,12 +34,12 @@
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSReflectionDirection.h"
-#include "core/platform/ThemeTypes.h"
 #include "core/platform/graphics/Path.h"
 #include "core/rendering/style/LineClampValue.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/SVGRenderStyleDefs.h"
 #include "platform/Length.h"
+#include "platform/ThemeTypes.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/fonts/FontSmoothingMode.h"
 #include "platform/fonts/TextRenderingMode.h"
@@ -2505,9 +2505,6 @@
     case TextUnderlinePositionAuto:
         m_value.valueID = CSSValueAuto;
         break;
-    case TextUnderlinePositionAlphabetic:
-        m_value.valueID = CSSValueAlphabetic;
-        break;
     case TextUnderlinePositionUnder:
         m_value.valueID = CSSValueUnder;
         break;
@@ -2522,8 +2519,6 @@
     switch (m_value.valueID) {
     case CSSValueAuto:
         return TextUnderlinePositionAuto;
-    case CSSValueAlphabetic:
-        return TextUnderlinePositionAlphabetic;
     case CSSValueUnder:
         return TextUnderlinePositionUnder;
     default:
@@ -4435,31 +4430,25 @@
 
 enum LengthConversion {
     AnyConversion = ~0,
-    FixedIntegerConversion = 1 << 0,
-    FixedFloatConversion = 1 << 1,
-    AutoConversion = 1 << 2,
-    PercentConversion = 1 << 3,
-    FractionConversion = 1 << 4,
+    FixedConversion = 1 << 0,
+    AutoConversion = 1 << 1,
+    PercentConversion = 1 << 2,
 };
 
 template<int supported> Length CSSPrimitiveValue::convertToLength(const RenderStyle* style, const RenderStyle* rootStyle, double multiplier, bool computingFontSize)
 {
     ASSERT(!hasVariableReference());
-    if ((supported & (FixedIntegerConversion | FixedFloatConversion)) && isFontRelativeLength() && (!style || !rootStyle))
+    if ((supported & FixedConversion) && isFontRelativeLength() && (!style || !rootStyle))
         return Length(Undefined);
-    if ((supported & FixedIntegerConversion) && isLength())
+    if ((supported & FixedConversion) && isLength())
         return computeLength<Length>(style, rootStyle, multiplier, computingFontSize);
-    if ((supported & FixedFloatConversion) && isLength())
-        return Length(computeLength<double>(style, rootStyle, multiplier), Fixed);
     if ((supported & PercentConversion) && isPercentage())
         return Length(getDoubleValue(), Percent);
-    if ((supported & FractionConversion) && isNumber())
-        return Length(getDoubleValue() * 100.0, Percent);
     if ((supported & AutoConversion) && getValueID() == CSSValueAuto)
         return Length(Auto);
-    if ((supported & (FixedIntegerConversion | FixedFloatConversion)) && (supported & PercentConversion) && isCalculated())
+    if ((supported & FixedConversion) && (supported & PercentConversion) && isCalculated())
         return Length(cssCalcValue()->toCalcValue(style, rootStyle, multiplier));
-    if ((supported & (FixedIntegerConversion | FixedFloatConversion)) && isViewportPercentageLength())
+    if ((supported & FixedConversion) && isViewportPercentageLength())
         return viewportPercentageLength();
     return Length(Undefined);
 }
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index f71cf63..9eeae4a 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -207,7 +207,6 @@
 -internal-marquee-repetition type_name=int, name_for_methods=MarqueeLoopCount, custom_value
 -internal-marquee-speed custom_value, name_for_methods=MarqueeSpeed
 -internal-marquee-style name_for_methods=MarqueeBehavior
--webkit-mask-box-image initial=initialNinePieceImage, custom_value
 -webkit-mask-box-image-outset custom_all
 -webkit-mask-box-image-repeat custom_all
 -webkit-mask-box-image-slice custom_all
@@ -256,16 +255,30 @@
 
 alignment-baseline svg
 buffered-rendering svg
+clip-path svg, type_name=String, name_for_methods=ClipperResource, converter=convertFragmentIdentifier
 clip-rule svg, type_name=WindRule
 color-interpolation svg
 color-interpolation-filters svg, type_name=EColorInterpolation
 color-rendering svg
 dominant-baseline svg
+fill-opacity svg, type_name=float, converter=convertNumberOrPercentage
 fill-rule svg, type_name=WindRule
+filter svg, type_name=String, name_for_methods=FilterResource, converter=convertFragmentIdentifier
+flood-opacity svg, type_name=float, converter=convertNumberOrPercentage
+kerning svg, type_name=SVGLength, converter=convertSVGLength
+marker-start svg, type_name=String, name_for_methods=MarkerStartResource, converter=convertFragmentIdentifier
+marker-mid svg, type_name=String, name_for_methods=MarkerMidResource, converter=convertFragmentIdentifier
+marker-end svg, type_name=String, name_for_methods=MarkerEndResource, converter=convertFragmentIdentifier
+mask svg, type_name=String, name_for_methods=MaskerResource, converter=convertFragmentIdentifier
 mask-type svg
 shape-rendering svg
+stop-opacity svg, type_name=float, converter=convertNumberOrPercentage
+stroke-dashoffset svg, type_name=SVGLength, name_for_methods=StrokeDashOffset, converter=convertSVGLength
 stroke-linecap svg, type_name=LineCap, name_for_methods=CapStyle
 stroke-linejoin svg, type_name=LineJoin, name_for_methods=JoinStyle
+stroke-miterlimit svg, type_name=float, name_for_methods=StrokeMiterLimit
+stroke-opacity svg, type_name=float, converter=convertNumberOrPercentage
+stroke-width svg, type_name=SVGLength, converter=convertSVGLength
 text-anchor svg
 vector-effect svg
 writing-mode svg, type_name=SVGWritingMode
diff --git a/Source/core/css/CSSProperty.cpp b/Source/core/css/CSSProperty.cpp
index 3c4a3ff..2d86abd 100644
--- a/Source/core/css/CSSProperty.cpp
+++ b/Source/core/css/CSSProperty.cpp
@@ -39,7 +39,8 @@
     if (!m_isSetFromShorthand)
         return CSSPropertyInvalid;
 
-    const Vector<StylePropertyShorthand> shorthands = matchingShorthandsForLonghand(static_cast<CSSPropertyID>(m_propertyID));
+    Vector<StylePropertyShorthand, 4> shorthands;
+    getMatchingShorthandsForLonghand(static_cast<CSSPropertyID>(m_propertyID), &shorthands);
     ASSERT(shorthands.size() && m_indexInShorthandsVector >= 0 && m_indexInShorthandsVector < shorthands.size());
     return shorthands.at(m_indexInShorthandsVector).id();
 }
diff --git a/Source/core/css/CSSPropertySourceData.h b/Source/core/css/CSSPropertySourceData.h
index f08deea..7b964d4 100644
--- a/Source/core/css/CSSPropertySourceData.h
+++ b/Source/core/css/CSSPropertySourceData.h
@@ -95,7 +95,6 @@
         PAGE_RULE,
         KEYFRAMES_RULE,
         REGION_RULE,
-        HOST_RULE,
         VIEWPORT_RULE,
         SUPPORTS_RULE,
         FILTER_RULE
diff --git a/Source/core/css/CSSRule.h b/Source/core/css/CSSRule.h
index c3afea0..85a4a5d 100644
--- a/Source/core/css/CSSRule.h
+++ b/Source/core/css/CSSRule.h
@@ -28,9 +28,9 @@
 
 namespace WebCore {
 
+class CSSParserContext;
 class CSSStyleSheet;
 class StyleRuleBase;
-struct CSSParserContext;
 
 class CSSRule : public RefCounted<CSSRule> {
 public:
@@ -54,8 +54,7 @@
         SUPPORTS_RULE = 12,
         VIEWPORT_RULE = 15,
         WEBKIT_REGION_RULE = 16,
-        WEBKIT_FILTER_RULE = 17,
-        HOST_RULE = 1001,
+        WEBKIT_FILTER_RULE = 17
     };
 
     virtual Type type() const = 0;
diff --git a/Source/core/css/CSSRule.idl b/Source/core/css/CSSRule.idl
index 2489d2d..43130a7 100644
--- a/Source/core/css/CSSRule.idl
+++ b/Source/core/css/CSSRule.idl
@@ -20,7 +20,7 @@
 
 // Introduced in DOM Level 2:
 [
-    CustomToV8,
+    CustomWrap,
     DependentLifetime
 ] interface CSSRule {
 
@@ -40,7 +40,6 @@
     [RuntimeEnabled=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
     [RuntimeEnabled=CSSRegions] const unsigned short WEBKIT_REGION_RULE = 16;
     const unsigned short WEBKIT_FILTER_RULE = 17;
-    const unsigned short HOST_RULE = 1001;
 
     readonly attribute unsigned short   type;
 
diff --git a/Source/core/css/CSSSegmentedFontFace.cpp b/Source/core/css/CSSSegmentedFontFace.cpp
index 7db0e79..ff2c981 100644
--- a/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/Source/core/css/CSSSegmentedFontFace.cpp
@@ -35,10 +35,9 @@
 
 namespace WebCore {
 
-CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector, FontTraitsMask traitsMask, bool isLocalFallback)
+CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector, FontTraitsMask traitsMask)
     : m_fontSelector(fontSelector)
     , m_traitsMask(traitsMask)
-    , m_isLocalFallback(isLocalFallback)
 {
 }
 
@@ -93,6 +92,16 @@
     m_fontFaces.append(fontFace);
 }
 
+void CSSSegmentedFontFace::removeFontFace(PassRefPtr<CSSFontFace> fontFace)
+{
+    size_t index = m_fontFaces.find(fontFace);
+    if (index != kNotFound) {
+        pruneTable();
+        m_fontFaces.remove(index);
+        fontFace->clearSegmentedFontFace();
+    }
+}
+
 static void appendFontData(SegmentedFontData* newFontData, PassRefPtr<SimpleFontData> prpFaceFontData, const CSSFontFace::UnicodeRangeSet& ranges)
 {
     RefPtr<SimpleFontData> faceFontData = prpFaceFontData;
@@ -122,13 +131,15 @@
     if (!fontData)
         fontData = SegmentedFontData::create();
 
-    bool syntheticBold = !(m_traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask));
-    bool syntheticItalic = !(m_traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask);
+    FontDescription requestedFontDescription(fontDescription);
+    requestedFontDescription.setTraitsMask(m_traitsMask);
+    requestedFontDescription.setSyntheticBold(!(m_traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)));
+    requestedFontDescription.setSyntheticItalic(!(m_traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask));
 
     for (int i = m_fontFaces.size() - 1; i >= 0; --i) {
         if (!m_fontFaces[i]->isValid())
             continue;
-        if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(fontDescription, syntheticBold, syntheticItalic)) {
+        if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(requestedFontDescription)) {
             ASSERT(!faceFontData->isSegmented());
 #if ENABLE(SVG_FONTS)
             // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
@@ -187,8 +198,9 @@
     unsigned size = m_fontFaces.size();
     for (unsigned i = 0; i < size; i++) {
         if (m_fontFaces[i]->loadStatus() == FontFace::Unloaded && m_fontFaces[i]->ranges().intersectsWith(text)) {
-            RefPtr<SimpleFontData> fontData = m_fontFaces[i]->getFontData(fontDescription, false, false);
-            fontData->beginLoadIfNeeded();
+            RefPtr<SimpleFontData> fontData = m_fontFaces[i]->getFontData(fontDescription);
+            if (fontData->customFontData())
+                fontData->customFontData()->beginLoadIfNeeded();
         }
     }
 
@@ -207,9 +219,8 @@
     Vector<RefPtr<FontFace> > fontFaces;
     unsigned size = m_fontFaces.size();
     for (unsigned i = 0; i < size; i++) {
-        RefPtr<FontFace> face = m_fontFaces[i]->fontFace();
-        if (face && m_fontFaces[i]->ranges().intersectsWith(text))
-            fontFaces.append(face);
+        if (m_fontFaces[i]->ranges().intersectsWith(text))
+            fontFaces.append(m_fontFaces[i]->fontFace());
     }
     return fontFaces;
 }
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 7c9b0d2..26c5bb1 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -44,16 +44,17 @@
 
 class CSSSegmentedFontFace : public RefCounted<CSSSegmentedFontFace> {
 public:
-    static PassRefPtr<CSSSegmentedFontFace> create(CSSFontSelector* selector, FontTraitsMask traitsMask, bool isLocalFallback) { return adoptRef(new CSSSegmentedFontFace(selector, traitsMask, isLocalFallback)); }
+    static PassRefPtr<CSSSegmentedFontFace> create(CSSFontSelector* selector, FontTraitsMask traitsMask) { return adoptRef(new CSSSegmentedFontFace(selector, traitsMask)); }
     ~CSSSegmentedFontFace();
 
     CSSFontSelector* fontSelector() const { return m_fontSelector; }
     FontTraitsMask traitsMask() const { return m_traitsMask; }
-    bool isLocalFallback() const { return m_isLocalFallback; }
 
     void fontLoaded(CSSFontFace*);
 
     void appendFontFace(PassRefPtr<CSSFontFace>);
+    void removeFontFace(PassRefPtr<CSSFontFace>);
+    bool isEmpty() const { return m_fontFaces.isEmpty(); }
 
     PassRefPtr<FontData> getFontData(const FontDescription&);
 
@@ -70,7 +71,7 @@
     void willUseFontData(const FontDescription&);
 
 private:
-    CSSSegmentedFontFace(CSSFontSelector*, FontTraitsMask, bool isLocalFallback);
+    CSSSegmentedFontFace(CSSFontSelector*, FontTraitsMask);
 
     void pruneTable();
     bool isValid() const;
@@ -79,7 +80,6 @@
 
     CSSFontSelector* m_fontSelector;
     FontTraitsMask m_traitsMask;
-    bool m_isLocalFallback;
     HashMap<unsigned, RefPtr<SegmentedFontData> > m_fontDataTable;
     Vector<RefPtr<CSSFontFace>, 1> m_fontFaces;
     Vector<RefPtr<LoadFontCallback> > m_callbacks;
diff --git a/Source/core/css/CSSSegmentedFontFaceCache.cpp b/Source/core/css/CSSSegmentedFontFaceCache.cpp
index 84ecc07..da50415 100644
--- a/Source/core/css/CSSSegmentedFontFaceCache.cpp
+++ b/Source/core/css/CSSSegmentedFontFaceCache.cpp
@@ -38,10 +38,6 @@
 #include "core/dom/Document.h"
 #include "core/fetch/FontResource.h"
 #include "core/fetch/ResourceFetcher.h"
-#include "core/frame/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/SimpleFontData.h"
 #include "platform/fonts/FontDescription.h"
 #include "wtf/text/AtomicString.h"
 
@@ -66,72 +62,48 @@
     if (!cssFontFace || !cssFontFace->isValid())
         return;
 
-    OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& familyFontFaces = m_fontFaces.add(fontFace->family(), nullptr).iterator->value;
-    if (!familyFontFaces) {
-        familyFontFaces = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);
+    if (!m_styleRuleToFontFace.add(fontFaceRule, cssFontFace).isNewEntry)
+        return;
 
-        ASSERT(!m_locallyInstalledFontFaces.contains(fontFace->family()));
-
-        Vector<unsigned> locallyInstalledFontsTraitsMasks;
-        fontCache()->getTraitsInFamily(fontFace->family(), locallyInstalledFontsTraitsMasks);
-        if (unsigned numLocallyInstalledFaces = locallyInstalledFontsTraitsMasks.size()) {
-            OwnPtr<Vector<RefPtr<CSSSegmentedFontFace> > > familyLocallyInstalledFaces = adoptPtr(new Vector<RefPtr<CSSSegmentedFontFace> >);
-
-            for (unsigned i = 0; i < numLocallyInstalledFaces; ++i) {
-                RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(0);
-                locallyInstalledFontFace->addSource(adoptPtr(new CSSFontFaceSource(fontFace->family())));
-                ASSERT(locallyInstalledFontFace->isValid());
-
-                RefPtr<CSSSegmentedFontFace> segmentedFontFace = CSSSegmentedFontFace::create(cssFontSelector, static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]), true);
-                segmentedFontFace->appendFontFace(locallyInstalledFontFace.release());
-                familyLocallyInstalledFaces->append(segmentedFontFace);
-            }
-
-            m_locallyInstalledFontFaces.set(fontFace->family(), familyLocallyInstalledFaces.release());
-        }
-    }
+    OwnPtr<TraitsMap>& familyFontFaces = m_fontFaces.add(fontFace->family(), nullptr).iterator->value;
+    if (!familyFontFaces)
+        familyFontFaces = adoptPtr(new TraitsMap);
 
     RefPtr<CSSSegmentedFontFace>& segmentedFontFace = familyFontFaces->add(traitsMask, 0).iterator->value;
     if (!segmentedFontFace)
-        segmentedFontFace = CSSSegmentedFontFace::create(cssFontSelector, static_cast<FontTraitsMask>(traitsMask), false);
+        segmentedFontFace = CSSSegmentedFontFace::create(cssFontSelector, static_cast<FontTraitsMask>(traitsMask));
 
     segmentedFontFace->appendFontFace(cssFontFace);
 
     ++m_version;
 }
 
-
-static PassRefPtr<FontData> fontDataForGenericFamily(Settings* settings, const FontDescription& fontDescription, const AtomicString& familyName)
+void CSSSegmentedFontFaceCache::removeFontFaceRule(const StyleRuleFontFace* fontFaceRule)
 {
-    if (!settings)
-        return 0;
+    StyleRuleToFontFace::iterator styleRuleToFontFaceIter = m_styleRuleToFontFace.find(fontFaceRule);
+    if (styleRuleToFontFaceIter == m_styleRuleToFontFace.end())
+        return;
+    RefPtr<CSSFontFace> cssFontFace = styleRuleToFontFaceIter->value;
 
-    AtomicString genericFamily;
-    UScriptCode script = fontDescription.script();
+    FamilyToTraitsMap::iterator fontFacesIter = m_fontFaces.find(cssFontFace->fontFace()->family());
+    if (fontFacesIter == m_fontFaces.end())
+        return;
+    TraitsMap* familyFontFaces = fontFacesIter->value.get();
 
-#if OS(ANDROID)
-    genericFamily = FontCache::getGenericFamilyNameForScript(familyName, script);
-#else
-    if (familyName == FontFamilyNames::webkit_serif)
-        genericFamily = settings->serifFontFamily(script);
-    else if (familyName == FontFamilyNames::webkit_sans_serif)
-        genericFamily = settings->sansSerifFontFamily(script);
-    else if (familyName == FontFamilyNames::webkit_cursive)
-        genericFamily = settings->cursiveFontFamily(script);
-    else if (familyName == FontFamilyNames::webkit_fantasy)
-        genericFamily = settings->fantasyFontFamily(script);
-    else if (familyName == FontFamilyNames::webkit_monospace)
-        genericFamily = settings->fixedFontFamily(script);
-    else if (familyName == FontFamilyNames::webkit_pictograph)
-        genericFamily = settings->pictographFontFamily(script);
-    else if (familyName == FontFamilyNames::webkit_standard)
-        genericFamily = settings->standardFontFamily(script);
-#endif
+    TraitsMap::iterator familyFontFacesIter = familyFontFaces->find(cssFontFace->fontFace()->traitsMask());
+    if (familyFontFacesIter == familyFontFaces->end())
+        return;
+    RefPtr<CSSSegmentedFontFace> segmentedFontFace = familyFontFacesIter->value;
 
-    if (!genericFamily.isEmpty())
-        return fontCache()->getFontResourceData(fontDescription, genericFamily);
-
-    return 0;
+    segmentedFontFace->removeFontFace(cssFontFace);
+    if (segmentedFontFace->isEmpty()) {
+        familyFontFaces->remove(familyFontFacesIter);
+        if (familyFontFaces->isEmpty())
+            m_fontFaces.remove(fontFacesIter);
+    }
+    m_styleRuleToFontFace.remove(styleRuleToFontFaceIter);
+    m_fonts.clear();
+    ++m_version;
 }
 
 static inline bool compareFontFaces(CSSSegmentedFontFace* first, CSSSegmentedFontFace* second, FontTraitsMask desiredTraitsMask)
@@ -146,7 +118,7 @@
         return firstHasDesiredVariant;
 
     // We need to check font-variant css property for CSS2.1 compatibility.
-    if ((desiredTraitsMask & FontVariantSmallCapsMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
+    if (desiredTraitsMask & FontVariantSmallCapsMask) {
         // Prefer a font that has indicated that it can only support small-caps to a font that claims to support
         // all variants. The specialized font is more likely to be true small-caps and not require synthesis.
         bool firstRequiresSmallCaps = (firstTraitsMask & FontVariantSmallCapsMask) && !(firstTraitsMask & FontVariantNormalMask);
@@ -161,7 +133,7 @@
     if (firstHasDesiredStyle != secondHasDesiredStyle)
         return firstHasDesiredStyle;
 
-    if ((desiredTraitsMask & FontStyleItalicMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
+    if (desiredTraitsMask & FontStyleItalicMask) {
         // Prefer a font that has indicated that it can only support italics to a font that claims to support
         // all styles. The specialized font is more likely to be the one the author wants used.
         bool firstRequiresItalics = (firstTraitsMask & FontStyleItalicMask) && !(firstTraitsMask & FontStyleNormalMask);
@@ -214,45 +186,21 @@
     return false;
 }
 
-PassRefPtr<FontData> CSSSegmentedFontFaceCache::getFontData(Settings* settings, const FontDescription& fontDescription, const AtomicString& familyName)
-{
-    if (m_fontFaces.isEmpty()) {
-        if (familyName.startsWith("-webkit-"))
-            return fontDataForGenericFamily(settings, fontDescription, familyName);
-        if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
-            return fontDataForGenericFamily(settings, fontDescription, "-webkit-standard");
-        return 0;
-    }
-
-    CSSSegmentedFontFace* face = getFontFace(fontDescription, familyName);
-    // If no face was found, then return 0 and let the OS come up with its best match for the name.
-    if (!face) {
-        // If we were handed a generic family, but there was no match, go ahead and return the correct font based off our
-        // settings.
-        if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
-            return fontDataForGenericFamily(settings, fontDescription, "-webkit-standard");
-        return fontDataForGenericFamily(settings, fontDescription, familyName);
-    }
-
-    // We have a face. Ask it for a font data. If it cannot produce one, it will fail, and the OS will take over.
-    return face->getFontData(fontDescription);
-}
-
 CSSSegmentedFontFace* CSSSegmentedFontFaceCache::getFontFace(const FontDescription& fontDescription, const AtomicString& family)
 {
-    HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >* familyFontFaces = m_fontFaces.get(family);
+    TraitsMap* familyFontFaces = m_fontFaces.get(family);
     if (!familyFontFaces || familyFontFaces->isEmpty())
         return 0;
 
-    OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& segmentedFontFaceCache = m_fonts.add(family, nullptr).iterator->value;
+    OwnPtr<TraitsMap>& segmentedFontFaceCache = m_fonts.add(family, nullptr).iterator->value;
     if (!segmentedFontFaceCache)
-        segmentedFontFaceCache = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);
+        segmentedFontFaceCache = adoptPtr(new TraitsMap);
 
     FontTraitsMask traitsMask = fontDescription.traitsMask();
 
     RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).iterator->value;
     if (!face) {
-        for (HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >::const_iterator i = familyFontFaces->begin(); i != familyFontFaces->end(); ++i) {
+        for (TraitsMap::const_iterator i = familyFontFaces->begin(); i != familyFontFaces->end(); ++i) {
             CSSSegmentedFontFace* candidate = i->value.get();
             unsigned candidateTraitsMask = candidate->traitsMask();
             if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
@@ -262,20 +210,6 @@
             if (!face || compareFontFaces(candidate, face.get(), traitsMask))
                 face = candidate;
         }
-
-        if (Vector<RefPtr<CSSSegmentedFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
-            unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
-            for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
-                CSSSegmentedFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
-                unsigned candidateTraitsMask = candidate->traitsMask();
-                if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
-                    continue;
-                if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
-                    continue;
-                if (!face || compareFontFaces(candidate, face.get(), traitsMask))
-                    face = candidate;
-            }
-        }
     }
     return face.get();
 }
diff --git a/Source/core/css/CSSSegmentedFontFaceCache.h b/Source/core/css/CSSSegmentedFontFaceCache.h
index 4b005a9..e753dd7 100644
--- a/Source/core/css/CSSSegmentedFontFaceCache.h
+++ b/Source/core/css/CSSSegmentedFontFaceCache.h
@@ -33,12 +33,11 @@
 
 namespace WebCore {
 
+class CSSFontFace;
 class CSSFontSelector;
 class CSSSegmentedFontFace;
-class FontData;
 class FontDescription;
 class StyleRuleFontFace;
-class Settings;
 
 class CSSSegmentedFontFaceCache {
 public:
@@ -47,15 +46,18 @@
     // FIXME: Remove CSSFontSelector as argument. Passing CSSFontSelector here is
     // a result of egregious spaghettification in CSSFontFace/FontFaceSet.
     void addFontFaceRule(CSSFontSelector*, const StyleRuleFontFace*);
-    PassRefPtr<FontData> getFontData(Settings*, const FontDescription&, const AtomicString&);
+    void removeFontFaceRule(const StyleRuleFontFace*);
     CSSSegmentedFontFace* getFontFace(const FontDescription&, const AtomicString& family);
 
     unsigned version() const { return m_version; }
 
 private:
-    HashMap<String, OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >, CaseFoldingHash> m_fontFaces;
-    HashMap<String, OwnPtr<Vector<RefPtr<CSSSegmentedFontFace> > >, CaseFoldingHash> m_locallyInstalledFontFaces;
-    HashMap<String, OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >, CaseFoldingHash> m_fonts;
+    typedef HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > TraitsMap;
+    typedef HashMap<String, OwnPtr<TraitsMap>, CaseFoldingHash> FamilyToTraitsMap;
+    typedef HashMap<const StyleRuleFontFace*, RefPtr<CSSFontFace> > StyleRuleToFontFace;
+    FamilyToTraitsMap m_fontFaces;
+    FamilyToTraitsMap m_fonts;
+    StyleRuleToFontFace m_styleRuleToFontFace;
 
     // FIXME: See if this could be ditched
     // Used to compare Font instances, and the usage seems suspect.
diff --git a/Source/core/css/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index 2d5c336..ad9db5a 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -249,7 +249,6 @@
     case PseudoPastCue:
     case PseudoSeamlessDocument:
     case PseudoDistributed:
-    case PseudoPart:
     case PseudoUnresolved:
     case PseudoContent:
     case PseudoHost:
@@ -341,7 +340,6 @@
     DEFINE_STATIC_LOCAL(AtomicString, inRange, ("in-range", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, outOfRange, ("out-of-range", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, scope, ("scope", AtomicString::ConstructFromLiteral));
-    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));
@@ -426,12 +424,11 @@
         nameToPseudoType->set(inRange.impl(), CSSSelector::PseudoInRange);
         nameToPseudoType->set(outOfRange.impl(), CSSSelector::PseudoOutOfRange);
         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::customElementsEnabled() || RuntimeEnabledFeatures::embedderCustomElementsEnabled())
+        if (RuntimeEnabledFeatures::customElementsEnabled())
             nameToPseudoType->set(unresolved.impl(), CSSSelector::PseudoUnresolved);
     }
     return nameToPseudoType;
@@ -485,7 +482,6 @@
     case PseudoSelection:
     case PseudoUserAgentCustomElement:
     case PseudoWebKitCustomElement:
-    case PseudoPart:
     case PseudoContent:
         element = true;
         break;
@@ -668,17 +664,9 @@
             str.appendLiteral("::");
             str.append(cs->value());
 
-            switch (cs->pseudoType()) {
-            case PseudoPart:
-                str.append(cs->argument());
-                str.append(')');
-                break;
-            case PseudoContent:
+            if (cs->pseudoType() == PseudoContent) {
                 if (cs->relation() == CSSSelector::SubSelector && cs->tagHistory())
                     return cs->tagHistory()->selectorText() + str.toString() + rightSide;
-                break;
-            default:
-                break;
             }
         } else if (cs->isAttributeSelector()) {
             str.append('[');
@@ -769,12 +757,6 @@
     m_data.m_rareData->m_selectorList = selectorList;
 }
 
-void CSSSelector::setMatchUserAgentOnly()
-{
-    createRareData();
-    m_data.m_rareData->m_matchUserAgentOnly = true;
-}
-
 static bool validateSubSelector(const CSSSelector* selector)
 {
     switch (selector->m_match) {
@@ -864,7 +846,6 @@
     , m_b(0)
     , m_attribute(anyQName())
     , m_argument(nullAtom)
-    , m_matchUserAgentOnly(0)
 {
 }
 
diff --git a/Source/core/css/CSSSelector.h b/Source/core/css/CSSSelector.h
index 8897261..0bba6f3 100644
--- a/Source/core/css/CSSSelector.h
+++ b/Source/core/css/CSSSelector.h
@@ -163,7 +163,6 @@
             PseudoPastCue,
             PseudoSeamlessDocument,
             PseudoDistributed,
-            PseudoPart,
             PseudoUnresolved,
             PseudoContent,
             PseudoHost
@@ -207,7 +206,6 @@
         const QualifiedName& attribute() const;
         const AtomicString& argument() const { return m_hasRareData ? m_data.m_rareData->m_argument : nullAtom; }
         const CSSSelectorList* selectorList() const { return m_hasRareData ? m_data.m_rareData->m_selectorList.get() : 0; }
-        bool isMatchUserAgentOnly() const { return m_hasRareData ? m_data.m_rareData->m_matchUserAgentOnly : false; }
 
         void setValue(const AtomicString&);
         void setAttribute(const QualifiedName&);
@@ -275,9 +273,8 @@
             int m_a; // Used for :nth-*
             int m_b; // Used for :nth-*
             QualifiedName m_attribute; // used for attribute selector
-            AtomicString m_argument; // Used for :contains, :lang, :nth-* and ::part
+            AtomicString m_argument; // Used for :contains, :lang, :nth-*
             OwnPtr<CSSSelectorList> m_selectorList; // Used for :-webkit-any and :not
-            unsigned m_matchUserAgentOnly : 1; // Used to make ::part with "-webkit"-prefixed part name match only elements in UA shadow roots.
 
         private:
             RareData(PassRefPtr<StringImpl> value);
@@ -313,7 +310,7 @@
 
 inline bool CSSSelector::isCustomPseudoElement() const
 {
-    return m_match == PseudoElement && (m_pseudoType == PseudoUserAgentCustomElement || m_pseudoType == PseudoWebKitCustomElement || m_pseudoType == PseudoPart);
+    return m_match == PseudoElement && (m_pseudoType == PseudoUserAgentCustomElement || m_pseudoType == PseudoWebKitCustomElement);
 }
 
 inline bool CSSSelector::isHostPseudoClass() const
diff --git a/Source/core/css/CSSShorthands.in b/Source/core/css/CSSShorthands.in
index ea55299..f66d649 100644
--- a/Source/core/css/CSSShorthands.in
+++ b/Source/core/css/CSSShorthands.in
@@ -43,6 +43,7 @@
 -webkit-column-rule longhands=-webkit-column-rule-width;-webkit-column-rule-style;-webkit-column-rule-color
 -webkit-margin-collapse longhands=-webkit-margin-before-collapse;-webkit-margin-after-collapse
 -webkit-mask longhands=-webkit-mask-image;-webkit-mask-position-x;-webkit-mask-position-y;-webkit-mask-size;-webkit-mask-repeat-x;-webkit-mask-repeat-y;-webkit-mask-origin;-webkit-mask-clip
+-webkit-mask-box-image longhands=-webkit-mask-box-image-source;-webkit-mask-box-image-slice;-webkit-mask-box-image-width;-webkit-mask-box-image-outset;-webkit-mask-box-image-repeat
 -webkit-mask-position longhands=-webkit-mask-position-x;-webkit-mask-position-y
 -webkit-mask-repeat longhands=-webkit-mask-repeat-x;-webkit-mask-repeat-y
 -webkit-text-emphasis longhands=-webkit-text-emphasis-style;-webkit-text-emphasis-color
diff --git a/Source/core/css/CSSStyleDeclaration.idl b/Source/core/css/CSSStyleDeclaration.idl
index 649a579..f552573 100644
--- a/Source/core/css/CSSStyleDeclaration.idl
+++ b/Source/core/css/CSSStyleDeclaration.idl
@@ -22,7 +22,7 @@
 [
     DependentLifetime
 ] interface CSSStyleDeclaration {
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString        cssText;
+             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter] attribute DOMString        cssText;
 
     [TreatReturnedNullStringAs=Null] DOMString          getPropertyValue([Default=Undefined] optional DOMString propertyName);
     CSSValue           getPropertyCSSValue([Default=Undefined] optional DOMString propertyName);
diff --git a/Source/core/css/CSSStyleSheet.cpp b/Source/core/css/CSSStyleSheet.cpp
index 02e6f54..e7fe16e 100644
--- a/Source/core/css/CSSStyleSheet.cpp
+++ b/Source/core/css/CSSStyleSheet.cpp
@@ -35,7 +35,9 @@
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Node.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/frame/UseCounter.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
@@ -153,8 +155,10 @@
 
 void CSSStyleSheet::willMutateRules()
 {
+    InspectorInstrumentation::willMutateRules(this);
     // If we are the only client it is safe to mutate.
     if (m_contents->hasOneClient() && !m_contents->isInMemoryCache()) {
+        m_contents->clearRuleSet();
         m_contents->setMutable();
         return;
     }
@@ -180,6 +184,7 @@
     ASSERT(m_contents->isMutable());
     ASSERT(m_contents->hasOneClient());
 
+    InspectorInstrumentation::didMutateRules(this);
     didMutate(PartialRuleUpdate);
 }
 
@@ -289,26 +294,26 @@
     return nonCharsetRules.release();
 }
 
-unsigned CSSStyleSheet::insertRule(const String& ruleString, unsigned index, ExceptionState& es)
+unsigned CSSStyleSheet::insertRule(const String& ruleString, unsigned index, ExceptionState& exceptionState)
 {
     ASSERT(m_childRuleCSSOMWrappers.isEmpty() || m_childRuleCSSOMWrappers.size() == m_contents->ruleCount());
 
     if (index > length()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return 0;
     }
     CSSParser p(m_contents->parserContext(), UseCounter::getFrom(this));
     RefPtr<StyleRuleBase> rule = p.parseRule(m_contents.get(), ruleString);
 
     if (!rule) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return 0;
     }
     RuleMutationScope mutationScope(this);
 
     bool success = m_contents->wrapperInsertRule(rule, index);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return 0;
     }
     if (!m_childRuleCSSOMWrappers.isEmpty())
@@ -317,12 +322,18 @@
     return index;
 }
 
-void CSSStyleSheet::deleteRule(unsigned index, ExceptionState& es)
+unsigned CSSStyleSheet::insertRule(const String& rule, ExceptionState& exceptionState)
+{
+    UseCounter::countDeprecation(activeExecutionContext(), UseCounter::CSSStyleSheetInsertRuleOptionalArg);
+    return insertRule(rule, 0, exceptionState);
+}
+
+void CSSStyleSheet::deleteRule(unsigned index, ExceptionState& exceptionState)
 {
     ASSERT(m_childRuleCSSOMWrappers.isEmpty() || m_childRuleCSSOMWrappers.size() == m_contents->ruleCount());
 
     if (index >= length()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
     RuleMutationScope mutationScope(this);
@@ -336,7 +347,7 @@
     }
 }
 
-int CSSStyleSheet::addRule(const String& selector, const String& style, int index, ExceptionState& es)
+int CSSStyleSheet::addRule(const String& selector, const String& style, int index, ExceptionState& exceptionState)
 {
     StringBuilder text;
     text.append(selector);
@@ -345,15 +356,15 @@
     if (!style.isEmpty())
         text.append(' ');
     text.append('}');
-    insertRule(text.toString(), index, es);
+    insertRule(text.toString(), index, exceptionState);
 
     // As per Microsoft documentation, always return -1.
     return -1;
 }
 
-int CSSStyleSheet::addRule(const String& selector, const String& style, ExceptionState& es)
+int CSSStyleSheet::addRule(const String& selector, const String& style, ExceptionState& exceptionState)
 {
-    return addRule(selector, style, length(), es);
+    return addRule(selector, style, length(), exceptionState);
 }
 
 
diff --git a/Source/core/css/CSSStyleSheet.h b/Source/core/css/CSSStyleSheet.h
index 6740a6b..3c02c23 100644
--- a/Source/core/css/CSSStyleSheet.h
+++ b/Source/core/css/CSSStyleSheet.h
@@ -64,13 +64,14 @@
 
     PassRefPtr<CSSRuleList> cssRules();
     unsigned insertRule(const String& rule, unsigned index, ExceptionState&);
+    unsigned insertRule(const String& rule, ExceptionState&); // Deprecated.
     void deleteRule(unsigned index, ExceptionState&);
 
     // IE Extensions
     PassRefPtr<CSSRuleList> rules();
     int addRule(const String& selector, const String& style, int index, ExceptionState&);
     int addRule(const String& selector, const String& style, ExceptionState&);
-    void removeRule(unsigned index, ExceptionState& es) { deleteRule(index, es); }
+    void removeRule(unsigned index, ExceptionState& exceptionState) { deleteRule(index, exceptionState); }
 
     // For CSSRuleList.
     unsigned length() const;
@@ -162,6 +163,8 @@
         m_styleSheet->didMutateRules();
 }
 
+DEFINE_TYPE_CASTS(CSSStyleSheet, StyleSheet, sheet, sheet->isCSSStyleSheet(), sheet.isCSSStyleSheet());
+
 } // namespace
 
 #endif
diff --git a/Source/core/css/CSSStyleSheet.idl b/Source/core/css/CSSStyleSheet.idl
index 986303a..88a49fe 100644
--- a/Source/core/css/CSSStyleSheet.idl
+++ b/Source/core/css/CSSStyleSheet.idl
@@ -20,12 +20,12 @@
 
 // Introduced in DOM Level 2:
 [
-    GenerateIsReachable=ownerNode
+    GenerateVisitDOMWrapper=ownerNode,
 ] interface CSSStyleSheet : StyleSheet {
     readonly attribute CSSRule          ownerRule;
     readonly attribute CSSRuleList      cssRules;
 
-    [RaisesException] unsigned long insertRule(DOMString rule, unsigned long index);
+    [RaisesException] unsigned long insertRule(DOMString rule, optional unsigned long index);
     [RaisesException] void deleteRule(unsigned long index);
 
     // IE Extensions
diff --git a/Source/core/css/CSSToStyleMap.cpp b/Source/core/css/CSSToStyleMap.cpp
index 180d310..eecea91 100644
--- a/Source/core/css/CSSToStyleMap.cpp
+++ b/Source/core/css/CSSToStyleMap.cpp
@@ -37,6 +37,7 @@
 #include "core/css/Rect.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/platform/animation/CSSAnimationData.h"
+#include "core/rendering/style/BorderImageLengthBox.h"
 #include "core/rendering/style/FillLayer.h"
 
 namespace WebCore {
@@ -565,14 +566,14 @@
         // We have to preserve the legacy behavior of -webkit-border-image and make the border slices
         // also set the border widths. We don't need to worry about percentages, since we don't even support
         // those on real borders yet.
-        if (image.borderSlices().top().isFixed())
-            mutableStyle->setBorderTopWidth(image.borderSlices().top().value());
-        if (image.borderSlices().right().isFixed())
-            mutableStyle->setBorderRightWidth(image.borderSlices().right().value());
-        if (image.borderSlices().bottom().isFixed())
-            mutableStyle->setBorderBottomWidth(image.borderSlices().bottom().value());
-        if (image.borderSlices().left().isFixed())
-            mutableStyle->setBorderLeftWidth(image.borderSlices().left().value());
+        if (image.borderSlices().top().isLength() && image.borderSlices().top().length().isFixed())
+            mutableStyle->setBorderTopWidth(image.borderSlices().top().length().value());
+        if (image.borderSlices().right().isLength() && image.borderSlices().right().length().isFixed())
+            mutableStyle->setBorderRightWidth(image.borderSlices().right().length().value());
+        if (image.borderSlices().bottom().isLength() && image.borderSlices().bottom().length().isFixed())
+            mutableStyle->setBorderBottomWidth(image.borderSlices().bottom().length().value());
+        if (image.borderSlices().left().isLength() && image.borderSlices().left().length().isFixed())
+            mutableStyle->setBorderLeftWidth(image.borderSlices().left().length().value());
     }
 }
 
@@ -609,49 +610,31 @@
     image.setFill(borderImageSlice->m_fill);
 }
 
-LengthBox CSSToStyleMap::mapNinePieceImageQuad(CSSValue* value) const
+static BorderImageLength toBorderImageLength(CSSPrimitiveValue& value, const RenderStyle* currentStyle, const RenderStyle* rootStyle, float multiplier)
+{
+    if (value.isNumber())
+        return value.getDoubleValue();
+    if (value.isPercentage())
+        return Length(value.getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
+    if (value.getValueID() != CSSValueAuto)
+        return value.computeLength<Length>(currentStyle, rootStyle, multiplier);
+    return Length(Auto);
+}
+
+BorderImageLengthBox CSSToStyleMap::mapNinePieceImageQuad(CSSValue* value) const
 {
     if (!value || !value->isPrimitiveValue())
-        return LengthBox();
+        return BorderImageLengthBox(Length(Auto));
 
-    // Get our zoom value.
     float zoom = useSVGZoomRules() ? 1.0f : style()->effectiveZoom();
+    Quad* slices = toCSSPrimitiveValue(value)->getQuadValue();
 
-    // Retrieve the primitive value.
-    CSSPrimitiveValue* borderWidths = toCSSPrimitiveValue(value);
-
-    // Set up a length box to represent our image slices.
-    LengthBox box; // Defaults to 'auto' so we don't have to handle that explicitly below.
-    Quad* slices = borderWidths->getQuadValue();
-    if (slices->top()->isNumber())
-        box.m_top = Length(slices->top()->getIntValue(), Relative);
-    else if (slices->top()->isPercentage())
-        box.m_top = Length(slices->top()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
-    else if (slices->top()->getValueID() != CSSValueAuto)
-        box.m_top = slices->top()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
-    if (slices->right()->isNumber())
-        box.m_right = Length(slices->right()->getIntValue(), Relative);
-    else if (slices->right()->isPercentage())
-        box.m_right = Length(slices->right()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
-    else if (slices->right()->getValueID() != CSSValueAuto)
-        box.m_right = slices->right()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
-    if (slices->bottom()->isNumber())
-        box.m_bottom = Length(slices->bottom()->getIntValue(), Relative);
-    else if (slices->bottom()->isPercentage())
-        box.m_bottom = Length(slices->bottom()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
-    else if (slices->bottom()->getValueID() != CSSValueAuto)
-        box.m_bottom = slices->bottom()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
-    if (slices->left()->isNumber())
-        box.m_left = Length(slices->left()->getIntValue(), Relative);
-    else if (slices->left()->isPercentage())
-        box.m_left = Length(slices->left()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
-    else if (slices->left()->getValueID() != CSSValueAuto)
-        box.m_left = slices->left()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
-    return box;
+    // Set up a border image length box to represent our image slices.
+    return BorderImageLengthBox(
+        toBorderImageLength(*slices->top(), style(), rootElementStyle(), zoom),
+        toBorderImageLength(*slices->right(), style(), rootElementStyle(), zoom),
+        toBorderImageLength(*slices->bottom(), style(), rootElementStyle(), zoom),
+        toBorderImageLength(*slices->left(), style(), rootElementStyle(), zoom));
 }
 
 void CSSToStyleMap::mapNinePieceImageRepeat(CSSValue* value, NinePieceImage& image) const
diff --git a/Source/core/css/CSSToStyleMap.h b/Source/core/css/CSSToStyleMap.h
index af1ce05..e916462 100644
--- a/Source/core/css/CSSToStyleMap.h
+++ b/Source/core/css/CSSToStyleMap.h
@@ -24,7 +24,6 @@
 
 #include "CSSPropertyNames.h"
 #include "core/css/resolver/ElementStyleResources.h"
-#include "platform/LengthBox.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
@@ -36,6 +35,7 @@
 class StyleImage;
 class StyleResolverState;
 class NinePieceImage;
+class BorderImageLengthBox;
 
 // CSSToStyleMap is a short-lived helper object which
 // given the current StyleResolverState can map
@@ -71,7 +71,7 @@
 
     void mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID, CSSValue*, NinePieceImage&);
     void mapNinePieceImageSlice(CSSValue*, NinePieceImage&) const;
-    LengthBox mapNinePieceImageQuad(CSSValue*) const;
+    BorderImageLengthBox mapNinePieceImageQuad(CSSValue*) const;
     void mapNinePieceImageRepeat(CSSValue*, NinePieceImage&) const;
 
 private:
diff --git a/Source/core/css/CSSTokenizer-in.cpp b/Source/core/css/CSSTokenizer-in.cpp
new file mode 100644
index 0000000..5ee194a
--- /dev/null
+++ b/Source/core/css/CSSTokenizer-in.cpp
@@ -0,0 +1,1559 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
+ * Copyright (C) 2012 Intel Corporation. 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.
+ */
+
+#include "config.h"
+#include "core/css/CSSTokenizer.h"
+
+#include "core/css/CSSKeyframeRule.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSParserValues.h"
+#include "core/css/MediaQuery.h"
+#include "core/css/StyleRule.h"
+#include "core/html/parser/HTMLParserIdioms.h"
+#include "core/svg/SVGParserUtilities.h"
+
+namespace WebCore {
+
+#include "CSSGrammar.h"
+
+enum CharacterType {
+    // Types for the main switch.
+
+    // The first 4 types must be grouped together, as they
+    // represent the allowed chars in an identifier.
+    CharacterCaselessU,
+    CharacterIdentifierStart,
+    CharacterNumber,
+    CharacterDash,
+
+    CharacterOther,
+    CharacterNull,
+    CharacterWhiteSpace,
+    CharacterEndMediaQueryOrSupports,
+    CharacterEndNthChild,
+    CharacterQuote,
+    CharacterExclamationMark,
+    CharacterHashmark,
+    CharacterDollar,
+    CharacterAsterisk,
+    CharacterPlus,
+    CharacterDot,
+    CharacterSlash,
+    CharacterLess,
+    CharacterAt,
+    CharacterBackSlash,
+    CharacterXor,
+    CharacterVerticalBar,
+    CharacterTilde,
+};
+
+// 128 ASCII codes
+static const CharacterType typesOfASCIICharacters[128] = {
+/*   0 - Null               */ CharacterNull,
+/*   1 - Start of Heading   */ CharacterOther,
+/*   2 - Start of Text      */ CharacterOther,
+/*   3 - End of Text        */ CharacterOther,
+/*   4 - End of Transm.     */ CharacterOther,
+/*   5 - Enquiry            */ CharacterOther,
+/*   6 - Acknowledgment     */ CharacterOther,
+/*   7 - Bell               */ CharacterOther,
+/*   8 - Back Space         */ CharacterOther,
+/*   9 - Horizontal Tab     */ CharacterWhiteSpace,
+/*  10 - Line Feed          */ CharacterWhiteSpace,
+/*  11 - Vertical Tab       */ CharacterOther,
+/*  12 - Form Feed          */ CharacterWhiteSpace,
+/*  13 - Carriage Return    */ CharacterWhiteSpace,
+/*  14 - Shift Out          */ CharacterOther,
+/*  15 - Shift In           */ CharacterOther,
+/*  16 - Data Line Escape   */ CharacterOther,
+/*  17 - Device Control 1   */ CharacterOther,
+/*  18 - Device Control 2   */ CharacterOther,
+/*  19 - Device Control 3   */ CharacterOther,
+/*  20 - Device Control 4   */ CharacterOther,
+/*  21 - Negative Ack.      */ CharacterOther,
+/*  22 - Synchronous Idle   */ CharacterOther,
+/*  23 - End of Transmit    */ CharacterOther,
+/*  24 - Cancel             */ CharacterOther,
+/*  25 - End of Medium      */ CharacterOther,
+/*  26 - Substitute         */ CharacterOther,
+/*  27 - Escape             */ CharacterOther,
+/*  28 - File Separator     */ CharacterOther,
+/*  29 - Group Separator    */ CharacterOther,
+/*  30 - Record Separator   */ CharacterOther,
+/*  31 - Unit Separator     */ CharacterOther,
+/*  32 - Space              */ CharacterWhiteSpace,
+/*  33 - !                  */ CharacterExclamationMark,
+/*  34 - "                  */ CharacterQuote,
+/*  35 - #                  */ CharacterHashmark,
+/*  36 - $                  */ CharacterDollar,
+/*  37 - %                  */ CharacterOther,
+/*  38 - &                  */ CharacterOther,
+/*  39 - '                  */ CharacterQuote,
+/*  40 - (                  */ CharacterOther,
+/*  41 - )                  */ CharacterEndNthChild,
+/*  42 - *                  */ CharacterAsterisk,
+/*  43 - +                  */ CharacterPlus,
+/*  44 - ,                  */ CharacterOther,
+/*  45 - -                  */ CharacterDash,
+/*  46 - .                  */ CharacterDot,
+/*  47 - /                  */ CharacterSlash,
+/*  48 - 0                  */ CharacterNumber,
+/*  49 - 1                  */ CharacterNumber,
+/*  50 - 2                  */ CharacterNumber,
+/*  51 - 3                  */ CharacterNumber,
+/*  52 - 4                  */ CharacterNumber,
+/*  53 - 5                  */ CharacterNumber,
+/*  54 - 6                  */ CharacterNumber,
+/*  55 - 7                  */ CharacterNumber,
+/*  56 - 8                  */ CharacterNumber,
+/*  57 - 9                  */ CharacterNumber,
+/*  58 - :                  */ CharacterOther,
+/*  59 - ;                  */ CharacterEndMediaQueryOrSupports,
+/*  60 - <                  */ CharacterLess,
+/*  61 - =                  */ CharacterOther,
+/*  62 - >                  */ CharacterOther,
+/*  63 - ?                  */ CharacterOther,
+/*  64 - @                  */ CharacterAt,
+/*  65 - A                  */ CharacterIdentifierStart,
+/*  66 - B                  */ CharacterIdentifierStart,
+/*  67 - C                  */ CharacterIdentifierStart,
+/*  68 - D                  */ CharacterIdentifierStart,
+/*  69 - E                  */ CharacterIdentifierStart,
+/*  70 - F                  */ CharacterIdentifierStart,
+/*  71 - G                  */ CharacterIdentifierStart,
+/*  72 - H                  */ CharacterIdentifierStart,
+/*  73 - I                  */ CharacterIdentifierStart,
+/*  74 - J                  */ CharacterIdentifierStart,
+/*  75 - K                  */ CharacterIdentifierStart,
+/*  76 - L                  */ CharacterIdentifierStart,
+/*  77 - M                  */ CharacterIdentifierStart,
+/*  78 - N                  */ CharacterIdentifierStart,
+/*  79 - O                  */ CharacterIdentifierStart,
+/*  80 - P                  */ CharacterIdentifierStart,
+/*  81 - Q                  */ CharacterIdentifierStart,
+/*  82 - R                  */ CharacterIdentifierStart,
+/*  83 - S                  */ CharacterIdentifierStart,
+/*  84 - T                  */ CharacterIdentifierStart,
+/*  85 - U                  */ CharacterCaselessU,
+/*  86 - V                  */ CharacterIdentifierStart,
+/*  87 - W                  */ CharacterIdentifierStart,
+/*  88 - X                  */ CharacterIdentifierStart,
+/*  89 - Y                  */ CharacterIdentifierStart,
+/*  90 - Z                  */ CharacterIdentifierStart,
+/*  91 - [                  */ CharacterOther,
+/*  92 - \                  */ CharacterBackSlash,
+/*  93 - ]                  */ CharacterOther,
+/*  94 - ^                  */ CharacterXor,
+/*  95 - _                  */ CharacterIdentifierStart,
+/*  96 - `                  */ CharacterOther,
+/*  97 - a                  */ CharacterIdentifierStart,
+/*  98 - b                  */ CharacterIdentifierStart,
+/*  99 - c                  */ CharacterIdentifierStart,
+/* 100 - d                  */ CharacterIdentifierStart,
+/* 101 - e                  */ CharacterIdentifierStart,
+/* 102 - f                  */ CharacterIdentifierStart,
+/* 103 - g                  */ CharacterIdentifierStart,
+/* 104 - h                  */ CharacterIdentifierStart,
+/* 105 - i                  */ CharacterIdentifierStart,
+/* 106 - j                  */ CharacterIdentifierStart,
+/* 107 - k                  */ CharacterIdentifierStart,
+/* 108 - l                  */ CharacterIdentifierStart,
+/* 109 - m                  */ CharacterIdentifierStart,
+/* 110 - n                  */ CharacterIdentifierStart,
+/* 111 - o                  */ CharacterIdentifierStart,
+/* 112 - p                  */ CharacterIdentifierStart,
+/* 113 - q                  */ CharacterIdentifierStart,
+/* 114 - r                  */ CharacterIdentifierStart,
+/* 115 - s                  */ CharacterIdentifierStart,
+/* 116 - t                  */ CharacterIdentifierStart,
+/* 117 - u                  */ CharacterCaselessU,
+/* 118 - v                  */ CharacterIdentifierStart,
+/* 119 - w                  */ CharacterIdentifierStart,
+/* 120 - x                  */ CharacterIdentifierStart,
+/* 121 - y                  */ CharacterIdentifierStart,
+/* 122 - z                  */ CharacterIdentifierStart,
+/* 123 - {                  */ CharacterEndMediaQueryOrSupports,
+/* 124 - |                  */ CharacterVerticalBar,
+/* 125 - }                  */ CharacterOther,
+/* 126 - ~                  */ CharacterTilde,
+/* 127 - Delete             */ CharacterOther,
+};
+
+// Utility functions for the CSS tokenizer.
+
+template <typename CharacterType>
+static inline bool isCSSLetter(CharacterType character)
+{
+    return character >= 128 || typesOfASCIICharacters[character] <= CharacterDash;
+}
+
+template <typename CharacterType>
+static inline bool isCSSEscape(CharacterType character)
+{
+    return character >= ' ' && character != 127;
+}
+
+template <typename CharacterType>
+static inline bool isURILetter(CharacterType character)
+{
+    return (character >= '*' && character != 127) || (character >= '#' && character <= '&') || character == '!';
+}
+
+template <typename CharacterType>
+static inline bool isIdentifierStartAfterDash(CharacterType* currentCharacter)
+{
+    return isASCIIAlpha(currentCharacter[0]) || currentCharacter[0] == '_' || currentCharacter[0] >= 128
+        || (currentCharacter[0] == '\\' && isCSSEscape(currentCharacter[1]));
+}
+
+template <typename CharacterType>
+static inline bool isEqualToCSSIdentifier(CharacterType* cssString, const char* constantString)
+{
+    // Compare an character memory data with a zero terminated string.
+    do {
+        // The input must be part of an identifier if constantChar or constString
+        // contains '-'. Otherwise toASCIILowerUnchecked('\r') would be equal to '-'.
+        ASSERT((*constantString >= 'a' && *constantString <= 'z') || *constantString == '-');
+        ASSERT(*constantString != '-' || isCSSLetter(*cssString));
+        if (toASCIILowerUnchecked(*cssString++) != (*constantString++))
+            return false;
+    } while (*constantString);
+    return true;
+}
+
+template <typename CharacterType>
+static inline bool isEqualToCSSCaseSensitiveIdentifier(CharacterType* string, const char* constantString)
+{
+    ASSERT(*constantString);
+
+    do {
+        if (*string++ != *constantString++)
+            return false;
+    } while (*constantString);
+    return true;
+}
+
+template <typename CharacterType>
+static CharacterType* checkAndSkipEscape(CharacterType* currentCharacter)
+{
+    // Returns with 0, if escape check is failed. Otherwise
+    // it returns with the following character.
+    ASSERT(*currentCharacter == '\\');
+
+    ++currentCharacter;
+    if (!isCSSEscape(*currentCharacter))
+        return 0;
+
+    if (isASCIIHexDigit(*currentCharacter)) {
+        int length = 6;
+
+        do {
+            ++currentCharacter;
+        } while (isASCIIHexDigit(*currentCharacter) && --length);
+
+        // Optional space after the escape sequence.
+        if (isHTMLSpace<CharacterType>(*currentCharacter))
+            ++currentCharacter;
+        return currentCharacter;
+    }
+    return currentCharacter + 1;
+}
+
+template <typename CharacterType>
+static inline CharacterType* skipWhiteSpace(CharacterType* currentCharacter)
+{
+    while (isHTMLSpace<CharacterType>(*currentCharacter))
+        ++currentCharacter;
+    return currentCharacter;
+}
+
+// Main CSS tokenizer functions.
+
+template <>
+inline LChar*& CSSTokenizer::currentCharacter<LChar>()
+{
+    return m_currentCharacter8;
+}
+
+template <>
+inline UChar*& CSSTokenizer::currentCharacter<UChar>()
+{
+    return m_currentCharacter16;
+}
+
+UChar*& CSSTokenizer::currentCharacter16()
+{
+    if (!m_currentCharacter16) {
+        m_dataStart16 = adoptArrayPtr(new UChar[m_length]);
+        m_currentCharacter16 = m_dataStart16.get();
+    }
+
+    return m_currentCharacter16;
+}
+
+template <>
+inline LChar* CSSTokenizer::dataStart<LChar>()
+{
+    return m_dataStart8.get();
+}
+
+template <>
+inline UChar* CSSTokenizer::dataStart<UChar>()
+{
+    return m_dataStart16.get();
+}
+
+template <typename CharacterType>
+inline CSSParserLocation CSSTokenizer::tokenLocation()
+{
+    CSSParserLocation location;
+    location.token.init(tokenStart<CharacterType>(), currentCharacter<CharacterType>() - tokenStart<CharacterType>());
+    location.lineNumber = m_tokenStartLineNumber;
+    location.offset = tokenStart<CharacterType>() - dataStart<CharacterType>();
+    return location;
+}
+
+CSSParserLocation CSSTokenizer::currentLocation()
+{
+    if (is8BitSource())
+        return tokenLocation<LChar>();
+    return tokenLocation<UChar>();
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::isIdentifierStart()
+{
+    // Check whether an identifier is started.
+    return isIdentifierStartAfterDash((*currentCharacter<CharacterType>() != '-') ? currentCharacter<CharacterType>() : currentCharacter<CharacterType>() + 1);
+}
+
+template <typename CharacterType>
+static inline CharacterType* checkAndSkipString(CharacterType* currentCharacter, int quote)
+{
+    // Returns with 0, if string check is failed. Otherwise
+    // it returns with the following character. This is necessary
+    // since we cannot revert escape sequences, thus strings
+    // must be validated before parsing.
+    while (true) {
+        if (UNLIKELY(*currentCharacter == quote)) {
+            // String parsing is successful.
+            return currentCharacter + 1;
+        }
+        if (UNLIKELY(!*currentCharacter)) {
+            // String parsing is successful up to end of input.
+            return currentCharacter;
+        }
+        if (UNLIKELY(*currentCharacter <= '\r' && (*currentCharacter == '\n' || (*currentCharacter | 0x1) == '\r'))) {
+            // String parsing is failed for character '\n', '\f' or '\r'.
+            return 0;
+        }
+
+        if (LIKELY(currentCharacter[0] != '\\')) {
+            ++currentCharacter;
+        } else if (currentCharacter[1] == '\n' || currentCharacter[1] == '\f') {
+            currentCharacter += 2;
+        } else if (currentCharacter[1] == '\r') {
+            currentCharacter += currentCharacter[2] == '\n' ? 3 : 2;
+        } else {
+            currentCharacter = checkAndSkipEscape(currentCharacter);
+            if (!currentCharacter)
+                return 0;
+        }
+    }
+}
+
+template <typename CharacterType>
+unsigned CSSTokenizer::parseEscape(CharacterType*& src)
+{
+    ASSERT(*src == '\\' && isCSSEscape(src[1]));
+
+    unsigned unicode = 0;
+
+    ++src;
+    if (isASCIIHexDigit(*src)) {
+
+        int length = 6;
+
+        do {
+            unicode = (unicode << 4) + toASCIIHexValue(*src++);
+        } while (--length && isASCIIHexDigit(*src));
+
+        // Characters above 0x10ffff are not handled.
+        if (unicode > 0x10ffff)
+            unicode = 0xfffd;
+
+        // Optional space after the escape sequence.
+        if (isHTMLSpace<CharacterType>(*src))
+            ++src;
+
+        return unicode;
+    }
+
+    return *currentCharacter<CharacterType>()++;
+}
+
+template <>
+inline void CSSTokenizer::UnicodeToChars<LChar>(LChar*& result, unsigned unicode)
+{
+    ASSERT(unicode <= 0xff);
+    *result = unicode;
+
+    ++result;
+}
+
+template <>
+inline void CSSTokenizer::UnicodeToChars<UChar>(UChar*& result, unsigned unicode)
+{
+    // Replace unicode with a surrogate pairs when it is bigger than 0xffff
+    if (U16_LENGTH(unicode) == 2) {
+        *result++ = U16_LEAD(unicode);
+        *result = U16_TRAIL(unicode);
+    } else {
+        *result = unicode;
+    }
+
+    ++result;
+}
+
+template <typename SrcCharacterType, typename DestCharacterType>
+inline bool CSSTokenizer::parseIdentifierInternal(SrcCharacterType*& src, DestCharacterType*& result, bool& hasEscape)
+{
+    hasEscape = false;
+    do {
+        if (LIKELY(*src != '\\')) {
+            *result++ = *src++;
+        } else {
+            hasEscape = true;
+            SrcCharacterType* savedEscapeStart = src;
+            unsigned unicode = parseEscape<SrcCharacterType>(src);
+            if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
+                src = savedEscapeStart;
+                return false;
+            }
+            UnicodeToChars(result, unicode);
+        }
+    } while (isCSSLetter(src[0]) || (src[0] == '\\' && isCSSEscape(src[1])));
+
+    return true;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::parseIdentifier(CharacterType*& result, CSSParserString& resultString, bool& hasEscape)
+{
+    // If a valid identifier start is found, we can safely
+    // parse the identifier until the next invalid character.
+    ASSERT(isIdentifierStart<CharacterType>());
+
+    CharacterType* start = currentCharacter<CharacterType>();
+    if (UNLIKELY(!parseIdentifierInternal(currentCharacter<CharacterType>(), result, hasEscape))) {
+        // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
+        ASSERT(is8BitSource());
+        UChar*& result16 = currentCharacter16();
+        UChar* start16 = result16;
+        int i = 0;
+        for (; i < result - start; i++)
+            result16[i] = start[i];
+
+        result16 += i;
+
+        parseIdentifierInternal(currentCharacter<CharacterType>(), result16, hasEscape);
+
+        resultString.init(start16, result16 - start16);
+
+        return;
+    }
+
+    resultString.init(start, result - start);
+}
+
+template <typename SrcCharacterType, typename DestCharacterType>
+inline bool CSSTokenizer::parseStringInternal(SrcCharacterType*& src, DestCharacterType*& result, UChar quote)
+{
+    while (true) {
+        if (UNLIKELY(*src == quote)) {
+            // String parsing is done.
+            ++src;
+            return true;
+        }
+        if (UNLIKELY(!*src)) {
+            // String parsing is done, but don't advance pointer if at the end of input.
+            return true;
+        }
+        ASSERT(*src > '\r' || (*src < '\n' && *src) || *src == '\v');
+
+        if (LIKELY(src[0] != '\\')) {
+            *result++ = *src++;
+        } else if (src[1] == '\n' || src[1] == '\f') {
+            src += 2;
+        } else if (src[1] == '\r') {
+            src += src[2] == '\n' ? 3 : 2;
+        } else {
+            SrcCharacterType* savedEscapeStart = src;
+            unsigned unicode = parseEscape<SrcCharacterType>(src);
+            if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
+                src = savedEscapeStart;
+                return false;
+            }
+            UnicodeToChars(result, unicode);
+        }
+    }
+
+    return true;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::parseString(CharacterType*& result, CSSParserString& resultString, UChar quote)
+{
+    CharacterType* start = currentCharacter<CharacterType>();
+
+    if (UNLIKELY(!parseStringInternal(currentCharacter<CharacterType>(), result, quote))) {
+        // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
+        ASSERT(is8BitSource());
+        UChar*& result16 = currentCharacter16();
+        UChar* start16 = result16;
+        int i = 0;
+        for (; i < result - start; i++)
+            result16[i] = start[i];
+
+        result16 += i;
+
+        parseStringInternal(currentCharacter<CharacterType>(), result16, quote);
+
+        resultString.init(start16, result16 - start16);
+        return;
+    }
+
+    resultString.init(start, result - start);
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::findURI(CharacterType*& start, CharacterType*& end, UChar& quote)
+{
+    start = skipWhiteSpace(currentCharacter<CharacterType>());
+
+    if (*start == '"' || *start == '\'') {
+        quote = *start++;
+        end = checkAndSkipString(start, quote);
+        if (!end)
+            return false;
+    } else {
+        quote = 0;
+        end = start;
+        while (isURILetter(*end)) {
+            if (LIKELY(*end != '\\')) {
+                ++end;
+            } else {
+                end = checkAndSkipEscape(end);
+                if (!end)
+                    return false;
+            }
+        }
+    }
+
+    end = skipWhiteSpace(end);
+    if (*end != ')')
+        return false;
+
+    return true;
+}
+
+template <typename SrcCharacterType, typename DestCharacterType>
+inline bool CSSTokenizer::parseURIInternal(SrcCharacterType*& src, DestCharacterType*& dest, UChar quote)
+{
+    if (quote) {
+        ASSERT(quote == '"' || quote == '\'');
+        return parseStringInternal(src, dest, quote);
+    }
+
+    while (isURILetter(*src)) {
+        if (LIKELY(*src != '\\')) {
+            *dest++ = *src++;
+        } else {
+            unsigned unicode = parseEscape<SrcCharacterType>(src);
+            if (unicode > 0xff && sizeof(SrcCharacterType) == 1)
+                return false;
+            UnicodeToChars(dest, unicode);
+        }
+    }
+
+    return true;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::parseURI(CSSParserString& string)
+{
+    CharacterType* uriStart;
+    CharacterType* uriEnd;
+    UChar quote;
+    if (!findURI(uriStart, uriEnd, quote))
+        return;
+
+    CharacterType* dest = currentCharacter<CharacterType>() = uriStart;
+    if (LIKELY(parseURIInternal(currentCharacter<CharacterType>(), dest, quote))) {
+        string.init(uriStart, dest - uriStart);
+    } else {
+        // An escape sequence was encountered that can't be stored in 8 bits.
+        // Reset the current character to the start of the URI and re-parse with
+        // a 16-bit destination.
+        ASSERT(is8BitSource());
+        UChar* uriStart16 = currentCharacter16();
+        currentCharacter<CharacterType>() = uriStart;
+        bool result = parseURIInternal(currentCharacter<CharacterType>(), currentCharacter16(), quote);
+        ASSERT_UNUSED(result, result);
+        string.init(uriStart16, currentCharacter16() - uriStart16);
+    }
+
+    currentCharacter<CharacterType>() = uriEnd + 1;
+    m_token = URI;
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::parseUnicodeRange()
+{
+    CharacterType* character = currentCharacter<CharacterType>() + 1;
+    int length = 6;
+    ASSERT(*currentCharacter<CharacterType>() == '+');
+
+    while (isASCIIHexDigit(*character) && length) {
+        ++character;
+        --length;
+    }
+
+    if (length && *character == '?') {
+        // At most 5 hex digit followed by a question mark.
+        do {
+            ++character;
+            --length;
+        } while (*character == '?' && length);
+        currentCharacter<CharacterType>() = character;
+        return true;
+    }
+
+    if (length < 6) {
+        // At least one hex digit.
+        if (character[0] == '-' && isASCIIHexDigit(character[1])) {
+            // Followed by a dash and a hex digit.
+            ++character;
+            length = 6;
+            do {
+                ++character;
+            } while (--length && isASCIIHexDigit(*character));
+        }
+        currentCharacter<CharacterType>() = character;
+        return true;
+    }
+    return false;
+}
+
+template <typename CharacterType>
+bool CSSTokenizer::parseNthChild()
+{
+    CharacterType* character = currentCharacter<CharacterType>();
+
+    while (isASCIIDigit(*character))
+        ++character;
+    if (isASCIIAlphaCaselessEqual(*character, 'n')) {
+        currentCharacter<CharacterType>() = character + 1;
+        return true;
+    }
+    return false;
+}
+
+template <typename CharacterType>
+bool CSSTokenizer::parseNthChildExtra()
+{
+    CharacterType* character = skipWhiteSpace(currentCharacter<CharacterType>());
+    if (*character != '+' && *character != '-')
+        return false;
+
+    character = skipWhiteSpace(character + 1);
+    if (!isASCIIDigit(*character))
+        return false;
+
+    do {
+        ++character;
+    } while (isASCIIDigit(*character));
+
+    currentCharacter<CharacterType>() = character;
+    return true;
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::detectFunctionTypeToken(int length)
+{
+    ASSERT(length > 0);
+    CharacterType* name = tokenStart<CharacterType>();
+    SWITCH(name, length) {
+        CASE("not") {
+            m_token = NOTFUNCTION;
+            return true;
+        }
+        CASE("url") {
+            m_token = URI;
+            return true;
+        }
+        CASE("cue") {
+            m_token = CUEFUNCTION;
+            return true;
+        }
+        CASE("var") {
+            if (!RuntimeEnabledFeatures::cssVariablesEnabled())
+                return false;
+            m_token = VARFUNCTION;
+            return true;
+        }
+        CASE("calc") {
+            m_token = CALCFUNCTION;
+            return true;
+        }
+        CASE("host") {
+            m_token = HOSTFUNCTION;
+            return true;
+        }
+        CASE("nth-child") {
+            m_parsingMode = NthChildMode;
+            return true;
+        }
+        CASE("nth-of-type") {
+            m_parsingMode = NthChildMode;
+            return true;
+        }
+        CASE("nth-last-child") {
+            m_parsingMode = NthChildMode;
+            return true;
+        }
+        CASE("nth-last-of-type") {
+            m_parsingMode = NthChildMode;
+            return true;
+        }
+    }
+    return false;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectMediaQueryToken(int length)
+{
+    ASSERT(m_parsingMode == MediaQueryMode);
+    CharacterType* name = tokenStart<CharacterType>();
+
+    SWITCH(name, length) {
+        CASE("and") {
+            m_token = MEDIA_AND;
+        }
+        CASE("not") {
+            m_token = MEDIA_NOT;
+        }
+        CASE("only") {
+            m_token = MEDIA_ONLY;
+        }
+        CASE("or") {
+            m_token = MEDIA_OR;
+        }
+    }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectNumberToken(CharacterType* type, int length)
+{
+    ASSERT(length > 0);
+
+    SWITCH(type, length) {
+        CASE("cm") {
+            m_token = CMS;
+        }
+        CASE("ch") {
+            m_token = CHS;
+        }
+        CASE("deg") {
+            m_token = DEGS;
+        }
+        CASE("dppx") {
+            // There is a discussion about the name of this unit on www-style.
+            // Keep this compile time guard in place until that is resolved.
+            // http://lists.w3.org/Archives/Public/www-style/2012May/0915.html
+            m_token = DPPX;
+        }
+        CASE("dpcm") {
+            m_token = DPCM;
+        }
+        CASE("dpi") {
+            m_token = DPI;
+        }
+        CASE("em") {
+            m_token = EMS;
+        }
+        CASE("ex") {
+            m_token = EXS;
+        }
+        CASE("fr") {
+            m_token = FR;
+        }
+        CASE("grad") {
+            m_token = GRADS;
+        }
+        CASE("hz") {
+            m_token = HERTZ;
+        }
+        CASE("in") {
+            m_token = INS;
+        }
+        CASE("khz") {
+            m_token = KHERTZ;
+        }
+        CASE("mm") {
+            m_token = MMS;
+        }
+        CASE("ms") {
+            m_token = MSECS;
+        }
+        CASE("px") {
+            m_token = PXS;
+        }
+        CASE("pt") {
+            m_token = PTS;
+        }
+        CASE("pc") {
+            m_token = PCS;
+        }
+        CASE("rad") {
+            m_token = RADS;
+        }
+        CASE("rem") {
+            m_token = REMS;
+        }
+        CASE("s") {
+            m_token = SECS;
+        }
+        CASE("turn") {
+            m_token = TURNS;
+        }
+        CASE("vw") {
+            m_token = VW;
+        }
+        CASE("vh") {
+            m_token = VH;
+        }
+        CASE("vmin") {
+            m_token = VMIN;
+        }
+        CASE("vmax") {
+            m_token = VMAX;
+        }
+        CASE("__qem") {
+            m_token = QEMS;
+        }
+    }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectDashToken(int length)
+{
+    CharacterType* name = tokenStart<CharacterType>();
+
+    // Ignore leading dash.
+    ++name;
+    --length;
+
+    SWITCH(name, length) {
+        CASE("webkit-any") {
+            m_token = ANYFUNCTION;
+        }
+        CASE("webkit-min") {
+            m_token = MINFUNCTION;
+        }
+        CASE("webkit-max") {
+            m_token = MAXFUNCTION;
+        }
+        CASE("webkit-calc") {
+            m_token = CALCFUNCTION;
+        }
+        CASE("webkit-distributed") {
+            m_token = DISTRIBUTEDFUNCTION;
+        }
+    }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectAtToken(int length, bool hasEscape)
+{
+    CharacterType* name = tokenStart<CharacterType>();
+    ASSERT(name[0] == '@' && length >= 2);
+
+    // Ignore leading @.
+    ++name;
+    --length;
+
+    // charset, font-face, import, media, namespace, page, supports,
+    // -webkit-keyframes, keyframes, and -webkit-mediaquery are not affected by hasEscape.
+    SWITCH(name, length) {
+        CASE("bottom-left") {
+            if (LIKELY(!hasEscape))
+                m_token = BOTTOMLEFT_SYM;
+        }
+        CASE("bottom-right") {
+            if (LIKELY(!hasEscape))
+                m_token = BOTTOMRIGHT_SYM;
+        }
+        CASE("bottom-center") {
+            if (LIKELY(!hasEscape))
+                m_token = BOTTOMCENTER_SYM;
+        }
+        CASE("bottom-left-corner") {
+            if (LIKELY(!hasEscape))
+                m_token = BOTTOMLEFTCORNER_SYM;
+        }
+        CASE("bottom-right-corner") {
+            if (LIKELY(!hasEscape))
+                m_token = BOTTOMRIGHTCORNER_SYM;
+        }
+        CASE("charset") {
+            if (name - 1 == dataStart<CharacterType>())
+                m_token = CHARSET_SYM;
+        }
+        CASE("font-face") {
+            m_token = FONT_FACE_SYM;
+        }
+        CASE("import") {
+            m_parsingMode = MediaQueryMode;
+            m_token = IMPORT_SYM;
+        }
+        CASE("keyframes") {
+            if (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                m_token = KEYFRAMES_SYM;
+        }
+        CASE("left-top") {
+            if (LIKELY(!hasEscape))
+                m_token = LEFTTOP_SYM;
+        }
+        CASE("left-middle") {
+            if (LIKELY(!hasEscape))
+                m_token = LEFTMIDDLE_SYM;
+        }
+        CASE("left-bottom") {
+            if (LIKELY(!hasEscape))
+                m_token = LEFTBOTTOM_SYM;
+        }
+        CASE("media") {
+            m_parsingMode = MediaQueryMode;
+            m_token = MEDIA_SYM;
+        }
+        CASE("namespace") {
+            m_token = NAMESPACE_SYM;
+        }
+        CASE("page") {
+            m_token = PAGE_SYM;
+        }
+        CASE("right-top") {
+            if (LIKELY(!hasEscape))
+                m_token = RIGHTTOP_SYM;
+        }
+        CASE("right-middle") {
+            if (LIKELY(!hasEscape))
+                m_token = RIGHTMIDDLE_SYM;
+        }
+        CASE("right-bottom") {
+            if (LIKELY(!hasEscape))
+                m_token = RIGHTBOTTOM_SYM;
+        }
+        CASE("supports") {
+            m_parsingMode = SupportsMode;
+            m_token = SUPPORTS_SYM;
+        }
+        CASE("top-left") {
+            if (LIKELY(!hasEscape))
+                m_token = TOPLEFT_SYM;
+        }
+        CASE("top-right") {
+            if (LIKELY(!hasEscape))
+                m_token = TOPRIGHT_SYM;
+        }
+        CASE("top-center") {
+            if (LIKELY(!hasEscape))
+                m_token = TOPCENTER_SYM;
+        }
+        CASE("top-left-corner") {
+            if (LIKELY(!hasEscape))
+                m_token = TOPLEFTCORNER_SYM;
+        }
+        CASE("top-right-corner") {
+            if (LIKELY(!hasEscape))
+                m_token = TOPRIGHTCORNER_SYM;
+        }
+        CASE("viewport") {
+            m_token = VIEWPORT_RULE_SYM;
+        }
+        CASE("-internal-rule") {
+            if (LIKELY(!hasEscape && m_internal))
+                m_token = INTERNAL_RULE_SYM;
+        }
+        CASE("-webkit-region") {
+            if (LIKELY(!hasEscape))
+                m_token = WEBKIT_REGION_RULE_SYM;
+        }
+        CASE("-webkit-filter") {
+            if (LIKELY(!hasEscape))
+                m_token = WEBKIT_FILTER_RULE_SYM;
+        }
+        CASE("-internal-decls") {
+            if (LIKELY(!hasEscape && m_internal))
+                m_token = INTERNAL_DECLS_SYM;
+        }
+        CASE("-internal-value") {
+            if (LIKELY(!hasEscape && m_internal))
+                m_token = INTERNAL_VALUE_SYM;
+        }
+        CASE("-webkit-keyframes") {
+            m_token = WEBKIT_KEYFRAMES_SYM;
+        }
+        CASE("-internal-selector") {
+            if (LIKELY(!hasEscape && m_internal))
+                m_token = INTERNAL_SELECTOR_SYM;
+        }
+        CASE("-internal-medialist") {
+            if (!m_internal)
+                return;
+            m_parsingMode = MediaQueryMode;
+            m_token = INTERNAL_MEDIALIST_SYM;
+        }
+        CASE("-internal-keyframe-rule") {
+            if (LIKELY(!hasEscape && m_internal))
+                m_token = INTERNAL_KEYFRAME_RULE_SYM;
+        }
+        CASE("-internal-keyframe-key-list") {
+            if (!m_internal)
+                return;
+            m_token = INTERNAL_KEYFRAME_KEY_LIST_SYM;
+        }
+        CASE("-internal-supports-condition") {
+            if (!m_internal)
+                return;
+            m_parsingMode = SupportsMode;
+            m_token = INTERNAL_SUPPORTS_CONDITION_SYM;
+        }
+    }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectSupportsToken(int length)
+{
+    ASSERT(m_parsingMode == SupportsMode);
+    CharacterType* name = tokenStart<CharacterType>();
+
+    SWITCH(name, length) {
+        CASE("or") {
+            m_token = SUPPORTS_OR;
+        }
+        CASE("and") {
+            m_token = SUPPORTS_AND;
+        }
+        CASE("not") {
+            m_token = SUPPORTS_NOT;
+        }
+    }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectCSSVariableDefinitionToken(int length)
+{
+    static const int prefixLength = static_cast<int>(sizeof("var-") - 1);
+    if (length <= prefixLength)
+        return;
+    CharacterType* name = tokenStart<CharacterType>();
+    COMPILE_ASSERT(prefixLength > 0, CSS_variable_prefix_must_be_nonempty);
+    if (name[prefixLength - 1] == '-' && isIdentifierStartAfterDash(name + prefixLength) && isEqualToCSSCaseSensitiveIdentifier(name, "var"))
+        m_token = VAR_DEFINITION;
+}
+
+template <typename SrcCharacterType>
+int CSSTokenizer::realLex(void* yylvalWithoutType)
+{
+    YYSTYPE* yylval = static_cast<YYSTYPE*>(yylvalWithoutType);
+    // Write pointer for the next character.
+    SrcCharacterType* result;
+    CSSParserString resultString;
+    bool hasEscape;
+
+    // The input buffer is terminated by a \0 character, so
+    // it is safe to read one character ahead of a known non-null.
+#ifndef NDEBUG
+    // In debug we check with an ASSERT that the length is > 0 for string types.
+    yylval->string.clear();
+#endif
+
+restartAfterComment:
+    result = currentCharacter<SrcCharacterType>();
+    setTokenStart(result);
+    m_tokenStartLineNumber = m_lineNumber;
+    m_token = *currentCharacter<SrcCharacterType>();
+    ++currentCharacter<SrcCharacterType>();
+
+    switch ((m_token <= 127) ? typesOfASCIICharacters[m_token] : CharacterIdentifierStart) {
+    case CharacterCaselessU:
+        if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '+')) {
+            if (parseUnicodeRange<SrcCharacterType>()) {
+                m_token = UNICODERANGE;
+                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+                break;
+            }
+        }
+        // Fall through to CharacterIdentifierStart.
+
+    case CharacterIdentifierStart:
+        --currentCharacter<SrcCharacterType>();
+        parseIdentifier(result, yylval->string, hasEscape);
+        m_token = IDENT;
+
+        if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '(')) {
+            if (m_parsingMode == SupportsMode && !hasEscape) {
+                detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+                if (m_token != IDENT)
+                    break;
+            }
+
+            m_token = FUNCTION;
+            if (!hasEscape)
+                detectFunctionTypeToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+
+            // Skip parenthesis
+            ++currentCharacter<SrcCharacterType>();
+            ++result;
+            ++yylval->string.m_length;
+
+            if (m_token == URI) {
+                m_token = FUNCTION;
+                // Check whether it is really an URI.
+                if (yylval->string.is8Bit())
+                    parseURI<LChar>(yylval->string);
+                else
+                    parseURI<UChar>(yylval->string);
+            }
+        } else if (UNLIKELY(m_parsingMode != NormalMode) && !hasEscape) {
+            if (m_parsingMode == MediaQueryMode) {
+                detectMediaQueryToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+            } else if (m_parsingMode == SupportsMode) {
+                detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+            } else if (m_parsingMode == NthChildMode && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[0], 'n')) {
+                if (result - tokenStart<SrcCharacterType>() == 1) {
+                    // String "n" is IDENT but "n+1" is NTH.
+                    if (parseNthChildExtra<SrcCharacterType>()) {
+                        m_token = NTH;
+                        yylval->string.m_length = currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>();
+                    }
+                } else if (result - tokenStart<SrcCharacterType>() >= 2 && tokenStart<SrcCharacterType>()[1] == '-') {
+                    // String "n-" is IDENT but "n-1" is NTH.
+                    // Set currentCharacter to '-' to continue parsing.
+                    SrcCharacterType* nextCharacter = result;
+                    currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 1;
+                    if (parseNthChildExtra<SrcCharacterType>()) {
+                        m_token = NTH;
+                        yylval->string.setLength(currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+                    } else {
+                        // Revert the change to currentCharacter if unsuccessful.
+                        currentCharacter<SrcCharacterType>() = nextCharacter;
+                    }
+                }
+            }
+        } else if (UNLIKELY(RuntimeEnabledFeatures::cssVariablesEnabled())) {
+            detectCSSVariableDefinitionToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+        }
+        break;
+
+    case CharacterDot:
+        if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0]))
+            break;
+        // Fall through to CharacterNumber.
+
+    case CharacterNumber: {
+        bool dotSeen = (m_token == '.');
+
+        while (true) {
+            if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0])) {
+                // Only one dot is allowed for a number,
+                // and it must be followed by a digit.
+                if (currentCharacter<SrcCharacterType>()[0] != '.' || dotSeen || !isASCIIDigit(currentCharacter<SrcCharacterType>()[1]))
+                    break;
+                dotSeen = true;
+            }
+            ++currentCharacter<SrcCharacterType>();
+        }
+
+        if (UNLIKELY(m_parsingMode == NthChildMode) && !dotSeen && isASCIIAlphaCaselessEqual(*currentCharacter<SrcCharacterType>(), 'n')) {
+            // "[0-9]+n" is always an NthChild.
+            ++currentCharacter<SrcCharacterType>();
+            parseNthChildExtra<SrcCharacterType>();
+            m_token = NTH;
+            yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+            break;
+        }
+
+        // Use SVG parser for numbers on SVG presentation attributes.
+        if (isSVGNumberParsingEnabledForMode(m_parser.m_context.mode())) {
+            // We need to take care of units like 'em' or 'ex'.
+            SrcCharacterType* character = currentCharacter<SrcCharacterType>();
+            if (isASCIIAlphaCaselessEqual(*character, 'e')) {
+                ASSERT(character - tokenStart<SrcCharacterType>() > 0);
+                ++character;
+                if (*character == '-' || *character == '+' || isASCIIDigit(*character)) {
+                    ++character;
+                    while (isASCIIDigit(*character))
+                        ++character;
+                    // Use FLOATTOKEN if the string contains exponents.
+                    dotSeen = true;
+                    currentCharacter<SrcCharacterType>() = character;
+                }
+            }
+            if (!parseSVGNumber(tokenStart<SrcCharacterType>(), character - tokenStart<SrcCharacterType>(), yylval->number))
+                break;
+        } else {
+            yylval->number = charactersToDouble(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+        }
+
+        // Type of the function.
+        if (isIdentifierStart<SrcCharacterType>()) {
+            SrcCharacterType* type = currentCharacter<SrcCharacterType>();
+            result = currentCharacter<SrcCharacterType>();
+
+            parseIdentifier(result, resultString, hasEscape);
+
+            m_token = DIMEN;
+            if (!hasEscape)
+                detectNumberToken(type, currentCharacter<SrcCharacterType>() - type);
+
+            if (m_token == DIMEN) {
+                // The decoded number is overwritten, but this is intentional.
+                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+            }
+        } else if (*currentCharacter<SrcCharacterType>() == '%') {
+            // Although the CSS grammar says {num}% we follow
+            // webkit at the moment which uses {num}%+.
+            do {
+                ++currentCharacter<SrcCharacterType>();
+            } while (*currentCharacter<SrcCharacterType>() == '%');
+            m_token = PERCENTAGE;
+        } else {
+            m_token = dotSeen ? FLOATTOKEN : INTEGER;
+        }
+        break;
+    }
+
+    case CharacterDash:
+        if (isIdentifierStartAfterDash(currentCharacter<SrcCharacterType>())) {
+            --currentCharacter<SrcCharacterType>();
+            parseIdentifier(result, resultString, hasEscape);
+            m_token = IDENT;
+
+            if (*currentCharacter<SrcCharacterType>() == '(') {
+                m_token = FUNCTION;
+                if (!hasEscape)
+                    detectDashToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+                ++currentCharacter<SrcCharacterType>();
+                ++result;
+            } else if (UNLIKELY(m_parsingMode == NthChildMode) && !hasEscape && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[1], 'n')) {
+                if (result - tokenStart<SrcCharacterType>() == 2) {
+                    // String "-n" is IDENT but "-n+1" is NTH.
+                    if (parseNthChildExtra<SrcCharacterType>()) {
+                        m_token = NTH;
+                        result = currentCharacter<SrcCharacterType>();
+                    }
+                } else if (result - tokenStart<SrcCharacterType>() >= 3 && tokenStart<SrcCharacterType>()[2] == '-') {
+                    // String "-n-" is IDENT but "-n-1" is NTH.
+                    // Set currentCharacter to second '-' of '-n-' to continue parsing.
+                    SrcCharacterType* nextCharacter = result;
+                    currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 2;
+                    if (parseNthChildExtra<SrcCharacterType>()) {
+                        m_token = NTH;
+                        result = currentCharacter<SrcCharacterType>();
+                    } else {
+                        // Revert the change to currentCharacter if unsuccessful.
+                        currentCharacter<SrcCharacterType>() = nextCharacter;
+                    }
+                }
+            }
+            resultString.setLength(result - tokenStart<SrcCharacterType>());
+            yylval->string = resultString;
+        } else if (currentCharacter<SrcCharacterType>()[0] == '-' && currentCharacter<SrcCharacterType>()[1] == '>') {
+            currentCharacter<SrcCharacterType>() += 2;
+            m_token = SGML_CD;
+        } else if (UNLIKELY(m_parsingMode == NthChildMode)) {
+            // "-[0-9]+n" is always an NthChild.
+            if (parseNthChild<SrcCharacterType>()) {
+                parseNthChildExtra<SrcCharacterType>();
+                m_token = NTH;
+                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+            }
+        }
+        break;
+
+    case CharacterOther:
+        // m_token is simply the current character.
+        break;
+
+    case CharacterNull:
+        // Do not advance pointer at the end of input.
+        --currentCharacter<SrcCharacterType>();
+        break;
+
+    case CharacterWhiteSpace:
+        m_token = WHITESPACE;
+        // Might start with a '\n'.
+        --currentCharacter<SrcCharacterType>();
+        do {
+            if (*currentCharacter<SrcCharacterType>() == '\n')
+                ++m_lineNumber;
+            ++currentCharacter<SrcCharacterType>();
+        } while (*currentCharacter<SrcCharacterType>() <= ' ' && (typesOfASCIICharacters[*currentCharacter<SrcCharacterType>()] == CharacterWhiteSpace));
+        break;
+
+    case CharacterEndMediaQueryOrSupports:
+        if (m_parsingMode == MediaQueryMode || m_parsingMode == SupportsMode)
+            m_parsingMode = NormalMode;
+        break;
+
+    case CharacterEndNthChild:
+        if (m_parsingMode == NthChildMode)
+            m_parsingMode = NormalMode;
+        break;
+
+    case CharacterQuote:
+        if (checkAndSkipString(currentCharacter<SrcCharacterType>(), m_token)) {
+            ++result;
+            parseString<SrcCharacterType>(result, yylval->string, m_token);
+            m_token = STRING;
+        }
+        break;
+
+    case CharacterExclamationMark: {
+        SrcCharacterType* start = skipWhiteSpace(currentCharacter<SrcCharacterType>());
+        if (isEqualToCSSIdentifier(start, "important")) {
+            m_token = IMPORTANT_SYM;
+            currentCharacter<SrcCharacterType>() = start + 9;
+        }
+        break;
+    }
+
+    case CharacterHashmark: {
+        SrcCharacterType* start = currentCharacter<SrcCharacterType>();
+        result = currentCharacter<SrcCharacterType>();
+
+        if (isASCIIDigit(*currentCharacter<SrcCharacterType>())) {
+            // This must be a valid hex number token.
+            do {
+                ++currentCharacter<SrcCharacterType>();
+            } while (isASCIIHexDigit(*currentCharacter<SrcCharacterType>()));
+            m_token = HEX;
+            yylval->string.init(start, currentCharacter<SrcCharacterType>() - start);
+        } else if (isIdentifierStart<SrcCharacterType>()) {
+            m_token = IDSEL;
+            parseIdentifier(result, yylval->string, hasEscape);
+            if (!hasEscape) {
+                // Check whether the identifier is also a valid hex number.
+                SrcCharacterType* current = start;
+                m_token = HEX;
+                do {
+                    if (!isASCIIHexDigit(*current)) {
+                        m_token = IDSEL;
+                        break;
+                    }
+                    ++current;
+                } while (current < result);
+            }
+        }
+        break;
+    }
+
+    case CharacterSlash:
+        // Ignore comments. They are not even considered as white spaces.
+        if (*currentCharacter<SrcCharacterType>() == '*') {
+            const CSSParserLocation startLocation = currentLocation();
+            if (m_parser.m_sourceDataHandler) {
+                unsigned startOffset = currentCharacter<SrcCharacterType>() - dataStart<SrcCharacterType>() - 1; // Start with a slash.
+                m_parser.m_sourceDataHandler->startComment(startOffset - m_parsedTextPrefixLength);
+            }
+            ++currentCharacter<SrcCharacterType>();
+            while (currentCharacter<SrcCharacterType>()[0] != '*' || currentCharacter<SrcCharacterType>()[1] != '/') {
+                if (*currentCharacter<SrcCharacterType>() == '\n')
+                    ++m_lineNumber;
+                if (*currentCharacter<SrcCharacterType>() == '\0') {
+                    // Unterminated comments are simply ignored.
+                    currentCharacter<SrcCharacterType>() -= 2;
+                    m_parser.reportError(startLocation, CSSParser::UnterminatedCommentError);
+                    break;
+                }
+                ++currentCharacter<SrcCharacterType>();
+            }
+            currentCharacter<SrcCharacterType>() += 2;
+            if (m_parser.m_sourceDataHandler) {
+                unsigned endOffset = currentCharacter<SrcCharacterType>() - dataStart<SrcCharacterType>();
+                unsigned userTextEndOffset = static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength);
+                m_parser.m_sourceDataHandler->endComment(std::min(endOffset, userTextEndOffset) - m_parsedTextPrefixLength);
+            }
+            goto restartAfterComment;
+        }
+        break;
+
+    case CharacterDollar:
+        if (*currentCharacter<SrcCharacterType>() == '=') {
+            ++currentCharacter<SrcCharacterType>();
+            m_token = ENDSWITH;
+        }
+        break;
+
+    case CharacterAsterisk:
+        if (*currentCharacter<SrcCharacterType>() == '=') {
+            ++currentCharacter<SrcCharacterType>();
+            m_token = CONTAINS;
+        }
+        break;
+
+    case CharacterPlus:
+        if (UNLIKELY(m_parsingMode == NthChildMode)) {
+            // Simplest case. "+[0-9]*n" is always NthChild.
+            if (parseNthChild<SrcCharacterType>()) {
+                parseNthChildExtra<SrcCharacterType>();
+                m_token = NTH;
+                yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+            }
+        }
+        break;
+
+    case CharacterLess:
+        if (currentCharacter<SrcCharacterType>()[0] == '!' && currentCharacter<SrcCharacterType>()[1] == '-' && currentCharacter<SrcCharacterType>()[2] == '-') {
+            currentCharacter<SrcCharacterType>() += 3;
+            m_token = SGML_CD;
+        }
+        break;
+
+    case CharacterAt:
+        if (isIdentifierStart<SrcCharacterType>()) {
+            m_token = ATKEYWORD;
+            ++result;
+            parseIdentifier(result, resultString, hasEscape);
+            detectAtToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>(), hasEscape);
+        }
+        break;
+
+    case CharacterBackSlash:
+        if (isCSSEscape(*currentCharacter<SrcCharacterType>())) {
+            --currentCharacter<SrcCharacterType>();
+            parseIdentifier(result, yylval->string, hasEscape);
+            m_token = IDENT;
+        }
+        break;
+
+    case CharacterXor:
+        if (*currentCharacter<SrcCharacterType>() == '=') {
+            ++currentCharacter<SrcCharacterType>();
+            m_token = BEGINSWITH;
+        }
+        break;
+
+    case CharacterVerticalBar:
+        if (*currentCharacter<SrcCharacterType>() == '=') {
+            ++currentCharacter<SrcCharacterType>();
+            m_token = DASHMATCH;
+        }
+        break;
+
+    case CharacterTilde:
+        if (*currentCharacter<SrcCharacterType>() == '=') {
+            ++currentCharacter<SrcCharacterType>();
+            m_token = INCLUDES;
+        }
+        break;
+
+    default:
+        ASSERT_NOT_REACHED();
+        break;
+    }
+
+    return m_token;
+}
+
+template <>
+inline void CSSTokenizer::setTokenStart<LChar>(LChar* tokenStart)
+{
+    m_tokenStart.ptr8 = tokenStart;
+}
+
+template <>
+inline void CSSTokenizer::setTokenStart<UChar>(UChar* tokenStart)
+{
+    m_tokenStart.ptr16 = tokenStart;
+}
+
+void CSSTokenizer::setupTokenizer(const char* prefix, unsigned prefixLength, const String& string, const char* suffix, unsigned suffixLength)
+{
+    m_parsedTextPrefixLength = prefixLength;
+    m_parsedTextSuffixLength = suffixLength;
+    unsigned stringLength = string.length();
+    unsigned length = stringLength + m_parsedTextPrefixLength + m_parsedTextSuffixLength + 1;
+    m_length = length;
+
+    if (!stringLength || string.is8Bit()) {
+        m_dataStart8 = adoptArrayPtr(new LChar[length]);
+        for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
+            m_dataStart8[i] = prefix[i];
+
+        if (stringLength)
+            memcpy(m_dataStart8.get() + m_parsedTextPrefixLength, string.characters8(), stringLength * sizeof(LChar));
+
+        unsigned start = m_parsedTextPrefixLength + stringLength;
+        unsigned end = start + suffixLength;
+        for (unsigned i = start; i < end; i++)
+            m_dataStart8[i] = suffix[i - start];
+
+        m_dataStart8[length - 1] = 0;
+
+        m_is8BitSource = true;
+        m_currentCharacter8 = m_dataStart8.get();
+        m_currentCharacter16 = 0;
+        setTokenStart<LChar>(m_currentCharacter8);
+        m_lexFunc = &CSSTokenizer::realLex<LChar>;
+        return;
+    }
+
+    m_dataStart16 = adoptArrayPtr(new UChar[length]);
+    for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
+        m_dataStart16[i] = prefix[i];
+
+    ASSERT(stringLength);
+    memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters16(), stringLength * sizeof(UChar));
+
+    unsigned start = m_parsedTextPrefixLength + stringLength;
+    unsigned end = start + suffixLength;
+    for (unsigned i = start; i < end; i++)
+        m_dataStart16[i] = suffix[i - start];
+
+    m_dataStart16[length - 1] = 0;
+
+    m_is8BitSource = false;
+    m_currentCharacter8 = 0;
+    m_currentCharacter16 = m_dataStart16.get();
+    setTokenStart<UChar>(m_currentCharacter16);
+    m_lexFunc = &CSSTokenizer::realLex<UChar>;
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/CSSTokenizer.h b/Source/core/css/CSSTokenizer.h
new file mode 100644
index 0000000..05b319c
--- /dev/null
+++ b/Source/core/css/CSSTokenizer.h
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 - 2010  Torch Mobile (Beijing) Co. Ltd. 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.
+ */
+
+#ifndef CSSTokenizer_h
+#define CSSTokenizer_h
+
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class CSSParser;
+struct CSSParserLocation;
+struct CSSParserString;
+
+class CSSTokenizer {
+    WTF_MAKE_NONCOPYABLE(CSSTokenizer);
+public:
+    // FIXME: This should not be needed but there are still some ties between the 2 classes.
+    friend class CSSParser;
+
+    CSSTokenizer(CSSParser& parser)
+        : m_parser(parser)
+        , m_parsedTextPrefixLength(0)
+        , m_parsedTextSuffixLength(0)
+        , m_parsingMode(NormalMode)
+        , m_is8BitSource(false)
+        , m_length(0)
+        , m_token(0)
+        , m_lineNumber(0)
+        , m_tokenStartLineNumber(0)
+        , m_internal(true)
+    {
+        m_tokenStart.ptr8 = 0;
+    }
+
+    void setupTokenizer(const char* prefix, unsigned prefixLength, const String&, const char* suffix, unsigned suffixLength);
+
+    CSSParserLocation currentLocation();
+
+    inline int lex(void* yylval) { return (this->*m_lexFunc)(yylval); }
+
+    inline unsigned safeUserStringTokenOffset()
+    {
+        return std::min(tokenStartOffset(), static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength)) - m_parsedTextPrefixLength;
+    }
+
+    bool is8BitSource() const { return m_is8BitSource; }
+
+    // FIXME: These 2 functions should be private so that we don't need the definitions below.
+    template <typename CharacterType>
+    inline CharacterType* tokenStart();
+
+    inline unsigned tokenStartOffset();
+
+private:
+    UChar*& currentCharacter16();
+
+    template <typename CharacterType>
+    inline CharacterType*& currentCharacter();
+
+    template <typename CharacterType>
+    inline CharacterType* dataStart();
+
+    template <typename CharacterType>
+    inline void setTokenStart(CharacterType*);
+
+    template <typename CharacterType>
+    inline bool isIdentifierStart();
+
+    template <typename CharacterType>
+    inline CSSParserLocation tokenLocation();
+
+    template <typename CharacterType>
+    unsigned parseEscape(CharacterType*&);
+    template <typename DestCharacterType>
+    inline void UnicodeToChars(DestCharacterType*&, unsigned);
+    template <typename SrcCharacterType, typename DestCharacterType>
+    inline bool parseIdentifierInternal(SrcCharacterType*&, DestCharacterType*&, bool&);
+
+    template <typename CharacterType>
+    inline void parseIdentifier(CharacterType*&, CSSParserString&, bool&);
+
+    template <typename SrcCharacterType, typename DestCharacterType>
+    inline bool parseStringInternal(SrcCharacterType*&, DestCharacterType*&, UChar);
+
+    template <typename CharacterType>
+    inline void parseString(CharacterType*&, CSSParserString& resultString, UChar);
+
+    template <typename CharacterType>
+    inline bool findURI(CharacterType*& start, CharacterType*& end, UChar& quote);
+
+    template <typename SrcCharacterType, typename DestCharacterType>
+    inline bool parseURIInternal(SrcCharacterType*&, DestCharacterType*&, UChar quote);
+
+    template <typename CharacterType>
+    inline void parseURI(CSSParserString&);
+    template <typename CharacterType>
+    inline bool parseUnicodeRange();
+    template <typename CharacterType>
+    bool parseNthChild();
+    template <typename CharacterType>
+    bool parseNthChildExtra();
+    template <typename CharacterType>
+    inline bool detectFunctionTypeToken(int);
+    template <typename CharacterType>
+    inline void detectMediaQueryToken(int);
+    template <typename CharacterType>
+    inline void detectNumberToken(CharacterType*, int);
+    template <typename CharacterType>
+    inline void detectDashToken(int);
+    template <typename CharacterType>
+    inline void detectAtToken(int, bool);
+    template <typename CharacterType>
+    inline void detectSupportsToken(int);
+    template <typename CharacterType>
+    inline void detectCSSVariableDefinitionToken(int);
+
+    template <typename SourceCharacterType>
+    int realLex(void* yylval);
+
+    CSSParser& m_parser;
+
+    size_t m_parsedTextPrefixLength;
+    size_t m_parsedTextSuffixLength;
+
+    enum ParsingMode {
+        NormalMode,
+        MediaQueryMode,
+        SupportsMode,
+        NthChildMode
+    };
+
+    ParsingMode m_parsingMode;
+    bool m_is8BitSource;
+    OwnPtr<LChar[]> m_dataStart8;
+    OwnPtr<UChar[]> m_dataStart16;
+    LChar* m_currentCharacter8;
+    UChar* m_currentCharacter16;
+    union {
+        LChar* ptr8;
+        UChar* ptr16;
+    } m_tokenStart;
+    unsigned m_length;
+    int m_token;
+    int m_lineNumber;
+    int m_tokenStartLineNumber;
+
+    // FIXME: This boolean is misnamed. Also it would be nice if we could consolidate it
+    // with the CSSParserMode logic to determine if internal properties are allowed.
+    bool m_internal;
+
+    int (CSSTokenizer::*m_lexFunc)(void*);
+};
+
+inline unsigned CSSTokenizer::tokenStartOffset()
+{
+    if (is8BitSource())
+        return m_tokenStart.ptr8 - m_dataStart8.get();
+    return m_tokenStart.ptr16 - m_dataStart16.get();
+}
+
+template <>
+inline LChar* CSSTokenizer::tokenStart<LChar>()
+{
+    return m_tokenStart.ptr8;
+}
+
+template <>
+inline UChar* CSSTokenizer::tokenStart<UChar>()
+{
+    return m_tokenStart.ptr16;
+}
+
+} // namespace WebCore
+
+#endif // CSSTokenizer_h
diff --git a/Source/core/css/CSSValue.cpp b/Source/core/css/CSSValue.cpp
index c0a0511..6d74434 100644
--- a/Source/core/css/CSSValue.cpp
+++ b/Source/core/css/CSSValue.cpp
@@ -40,6 +40,7 @@
 #include "core/css/CSSFontValue.h"
 #include "core/css/CSSFunctionValue.h"
 #include "core/css/CSSGradientValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
 #include "core/css/CSSGridTemplateValue.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSImageValue.h"
@@ -182,6 +183,8 @@
             return compareCSSValues<CSSInheritedValue>(*this, other);
         case InitialClass:
             return compareCSSValues<CSSInitialValue>(*this, other);
+        case GridLineNamesClass:
+            return compareCSSValues<CSSGridLineNamesValue>(*this, other);
         case GridTemplateClass:
             return compareCSSValues<CSSGridTemplateValue>(*this, other);
         case PrimitiveClass:
@@ -270,6 +273,8 @@
         return toCSSInheritedValue(this)->customCSSText();
     case InitialClass:
         return toCSSInitialValue(this)->customCSSText();
+    case GridLineNamesClass:
+        return toCSSGridLineNamesValue(this)->customCSSText();
     case GridTemplateClass:
         return toCSSGridTemplateValue(this)->customCSSText();
     case PrimitiveClass:
@@ -383,6 +388,9 @@
     case InitialClass:
         delete toCSSInitialValue(this);
         return;
+    case GridLineNamesClass:
+        delete toCSSGridLineNamesValue(this);
+        return;
     case GridTemplateClass:
         delete toCSSGridTemplateValue(this);
         return;
diff --git a/Source/core/css/CSSValue.h b/Source/core/css/CSSValue.h
index 76c04cb..8a6ff43 100644
--- a/Source/core/css/CSSValue.h
+++ b/Source/core/css/CSSValue.h
@@ -22,7 +22,7 @@
 #define CSSValue_h
 
 #include "core/dom/ExceptionCode.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
@@ -105,6 +105,7 @@
     bool isSVGPaint() const { return m_classType == SVGPaintClass; }
     bool isSVGDocumentValue() const { return m_classType == CSSSVGDocumentClass; }
     bool isUnicodeRangeValue() const { return m_classType == UnicodeRangeClass; }
+    bool isGridLineNamesValue() const { return m_classType == GridLineNamesClass; }
 
     bool isCSSOMSafe() const { return m_isCSSOMSafe; }
     bool isSubtypeExposedToCSSOM() const
@@ -172,6 +173,7 @@
         CSSArrayFunctionValueClass,
         CSSMixFunctionValueClass,
         CSSTransformClass,
+        GridLineNamesClass,
         // Do not append non-list class types here.
     };
 
diff --git a/Source/core/css/CSSValue.idl b/Source/core/css/CSSValue.idl
index 9ac1fc8..e0aa3f8 100644
--- a/Source/core/css/CSSValue.idl
+++ b/Source/core/css/CSSValue.idl
@@ -19,9 +19,8 @@
  */
 
 [
-    CustomToV8,
-
-    DependentLifetime
+    CustomWrap,
+    DependentLifetime,
 ] interface CSSValue {
 
     // UnitTypes
@@ -30,7 +29,7 @@
     const unsigned short CSS_VALUE_LIST      = 2;
     const unsigned short CSS_CUSTOM          = 3;
 
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString cssText;
+             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter] attribute DOMString cssText;
 
     readonly attribute unsigned short cssValueType;
 
diff --git a/Source/core/css/CSSValuePool.cpp b/Source/core/css/CSSValuePool.cpp
index 140dc72..cdd434e 100644
--- a/Source/core/css/CSSValuePool.cpp
+++ b/Source/core/css/CSSValuePool.cpp
@@ -76,7 +76,7 @@
         return m_colorBlack;
 
     // Just wipe out the cache and start rebuilding if it gets too big.
-    const int maximumColorCacheSize = 512;
+    const unsigned maximumColorCacheSize = 512;
     if (m_colorValueCache.size() > maximumColorCacheSize)
         m_colorValueCache.clear();
 
@@ -116,9 +116,9 @@
     return cache[intValue];
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSValuePool::createValue(const Length& value, const RenderStyle* style)
+PassRefPtr<CSSPrimitiveValue> CSSValuePool::createValue(const Length& value, const RenderStyle& style)
 {
-    return CSSPrimitiveValue::create(value, style->effectiveZoom());
+    return CSSPrimitiveValue::create(value, style.effectiveZoom());
 }
 
 PassRefPtr<CSSPrimitiveValue> CSSValuePool::createFontFamilyValue(const String& familyName)
@@ -132,7 +132,7 @@
 PassRefPtr<CSSValueList> CSSValuePool::createFontFaceValue(const AtomicString& string)
 {
     // Just wipe out the cache and start rebuilding if it gets too big.
-    const int maximumFontFaceCacheSize = 128;
+    const unsigned maximumFontFaceCacheSize = 128;
     if (m_fontFaceValueCache.size() > maximumFontFaceCacheSize)
         m_fontFaceValueCache.clear();
 
diff --git a/Source/core/css/CSSValuePool.h b/Source/core/css/CSSValuePool.h
index 02376a0..75b8984 100644
--- a/Source/core/css/CSSValuePool.h
+++ b/Source/core/css/CSSValuePool.h
@@ -52,7 +52,7 @@
     PassRefPtr<CSSPrimitiveValue> createColorValue(unsigned rgbValue);
     PassRefPtr<CSSPrimitiveValue> createValue(double value, CSSPrimitiveValue::UnitTypes);
     PassRefPtr<CSSPrimitiveValue> createValue(const String& value, CSSPrimitiveValue::UnitTypes type) { return CSSPrimitiveValue::create(value, type); }
-    PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, const RenderStyle*);
+    PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, const RenderStyle&);
     PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, float zoom) { return CSSPrimitiveValue::create(value, zoom); }
     template<typename T> static PassRefPtr<CSSPrimitiveValue> createValue(T value) { return CSSPrimitiveValue::create(value); }
 
diff --git a/Source/core/css/CSSVariablesMap.cpp b/Source/core/css/CSSVariablesMap.cpp
index 48e67eb..c62bc21 100644
--- a/Source/core/css/CSSVariablesMap.cpp
+++ b/Source/core/css/CSSVariablesMap.cpp
@@ -55,11 +55,11 @@
     return false;
 }
 
-void CSSVariablesMap::set(const AtomicString& name, const String& value, ExceptionState& es)
+void CSSVariablesMap::set(const AtomicString& name, const String& value, ExceptionState& exceptionState)
 {
     if (!m_styleDeclaration)
         return;
-    if (m_styleDeclaration->setVariableValue(name, value, es)) {
+    if (m_styleDeclaration->setVariableValue(name, value, exceptionState)) {
         Iterators::iterator end = m_activeIterators.end();
         for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
             (*it)->addedVariable(name);
@@ -79,11 +79,11 @@
     return false;
 }
 
-void CSSVariablesMap::clear(ExceptionState& es)
+void CSSVariablesMap::clear(ExceptionState& exceptionState)
 {
     if (!m_styleDeclaration)
         return;
-    if (m_styleDeclaration->clearVariables(es)) {
+    if (m_styleDeclaration->clearVariables(exceptionState)) {
         Iterators::iterator end = m_activeIterators.end();
         for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
             (*it)->clearedVariables();
diff --git a/Source/core/css/DocumentRuleSets.cpp b/Source/core/css/DocumentRuleSets.cpp
deleted file mode 100644
index d8811bc..0000000
--- a/Source/core/css/DocumentRuleSets.cpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
- * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
- * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
- * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- * Copyright (C) 2013 Google 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.
- */
-
-#include "config.h"
-#include "core/css/DocumentRuleSets.h"
-
-#include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/StyleSheetContents.h"
-#include "core/css/resolver/MatchRequest.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/StyleEngine.h"
-
-namespace WebCore {
-
-void TreeBoundaryCrossingRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
-{
-    if (m_treeBoundaryCrossingRuleSetMap.contains(scopingNode))
-        m_treeBoundaryCrossingRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
-    else {
-        OwnPtr<RuleSet> ruleSetForScope = RuleSet::create();
-        ruleSetForScope->addRule(rule, selectorIndex, addRuleFlags);
-        m_treeBoundaryCrossingRuleSetMap.add(scopingNode, ruleSetForScope.release());
-        m_scopingNodes.add(scopingNode);
-    }
-}
-
-void TreeBoundaryCrossingRules::reset(const ContainerNode* scopingNode)
-{
-    m_treeBoundaryCrossingRuleSetMap.remove(scopingNode);
-    m_scopingNodes.remove(scopingNode);
-}
-
-void TreeBoundaryCrossingRules::collectFeaturesTo(RuleFeatureSet& features)
-{
-    for (TreeBoundaryCrossingRuleSetMap::iterator::Values it = m_treeBoundaryCrossingRuleSetMap.values().begin(); it != m_treeBoundaryCrossingRuleSetMap.values().end(); ++it) {
-        RuleSet* ruleSet = it->get();
-        features.add(ruleSet->features());
-    }
-}
-
-DocumentRuleSets::DocumentRuleSets()
-{
-}
-
-DocumentRuleSets::~DocumentRuleSets()
-{
-}
-
-void DocumentRuleSets::initUserStyle(StyleEngine* styleSheetCollection, const Vector<RefPtr<StyleRule> >& watchedSelectors, const MediaQueryEvaluator& medium, StyleResolver& resolver)
-{
-    OwnPtr<RuleSet> tempUserStyle = RuleSet::create();
-    if (CSSStyleSheet* pageUserSheet = styleSheetCollection->pageUserSheet())
-        tempUserStyle->addRulesFromSheet(pageUserSheet->contents(), medium, &resolver);
-    collectRulesFromUserStyleSheets(styleSheetCollection->documentUserStyleSheets(), *tempUserStyle, medium, resolver);
-    collectRulesFromWatchedSelectors(watchedSelectors, *tempUserStyle);
-    if (tempUserStyle->ruleCount() > 0 || tempUserStyle->pageRules().size() > 0)
-        m_userStyle = tempUserStyle.release();
-}
-
-void DocumentRuleSets::collectRulesFromUserStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& userSheets, RuleSet& userStyle, const MediaQueryEvaluator& medium, StyleResolver& resolver)
-{
-    for (unsigned i = 0; i < userSheets.size(); ++i) {
-        ASSERT(userSheets[i]->contents()->isUserStyleSheet());
-        userStyle.addRulesFromSheet(userSheets[i]->contents(), medium, &resolver);
-    }
-}
-
-void DocumentRuleSets::collectRulesFromWatchedSelectors(const Vector<RefPtr<StyleRule> >& watchedSelectors, RuleSet& userStyle)
-{
-    for (unsigned i = 0; i < watchedSelectors.size(); ++i)
-        userStyle.addStyleRule(watchedSelectors[i].get(), RuleHasNoSpecialState);
-}
-
-void DocumentRuleSets::resetAuthorStyle()
-{
-    m_treeBoundaryCrossingRules.clear();
-}
-
-void DocumentRuleSets::collectFeaturesTo(RuleFeatureSet& features, bool isViewSource)
-{
-    // Collect all ids and rules using sibling selectors (:first-child and similar)
-    // in the current set of stylesheets. Style sharing code uses this information to reject
-    // sharing candidates.
-    if (CSSDefaultStyleSheets::defaultStyle)
-        features.add(CSSDefaultStyleSheets::defaultStyle->features());
-
-    if (isViewSource)
-        features.add(CSSDefaultStyleSheets::viewSourceStyle()->features());
-
-    if (m_userStyle)
-        features.add(m_userStyle->features());
-
-    m_treeBoundaryCrossingRules.collectFeaturesTo(features);
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index d59f50d..f2f90ae 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -32,6 +32,7 @@
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSStyleRule.h"
+#include "core/css/CSSStyleSheet.h"
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/StylePropertySet.h"
@@ -76,11 +77,11 @@
     return m_cssRuleList.release();
 }
 
-inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex)
 {
     if (!m_matchedRules)
         m_matchedRules = adoptPtr(new Vector<MatchedRule, 32>);
-    m_matchedRules->append(MatchedRule(rule, cascadeScope, cascadeOrder));
+    m_matchedRules->append(MatchedRule(rule, cascadeScope, cascadeOrder, styleSheetIndex));
 }
 
 void ElementRuleCollector::clearMatchedRules()
@@ -148,7 +149,7 @@
         collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId.impl()), behaviorAtBoundary, ignoreCascadeScope, cascadeOrder, matchRequest, ruleRange);
     }
 
-    if (element.isWebVTTElement())
+    if (element.isVTTElement())
         collectMatchingRulesForList(matchRequest.ruleSet->cuePseudoRules(), behaviorAtBoundary, 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
@@ -185,7 +186,7 @@
     unsigned size = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.size();
     for (unsigned i = 0; i < size; ++i) {
         const CSSSelector* regionSelector = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).selector;
-        if (checkRegionSelector(regionSelector, toElement(m_regionForStyling->node()))) {
+        if (checkRegionSelector(regionSelector, toElement(m_regionForStyling->nodeForRegion()))) {
             RuleSet* regionRules = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
             ASSERT(regionRules);
             collectMatchingRules(MatchRequest(regionRules, matchRequest.includeEmptyRules, matchRequest.scope), ruleRange, behaviorAtBoundary, cascadeScope, cascadeOrder);
@@ -257,10 +258,9 @@
 
 inline bool ElementRuleCollector::ruleMatches(const RuleData& ruleData, const ContainerNode* scope, PseudoId& dynamicPseudo, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary)
 {
-    // They can't match because the fast path uses a pool of tag/class/ids, collected from
+    // Scoped rules can't match because the fast path uses a pool of tag/class/ids, collected from
     // elements in that tree and those will never match the host, since it's in a different pool.
-    // So when adding scoped rules to RuleSet, RuleCanUseFastCheckSelector is not used.
-    if (ruleData.hasFastCheckableSelector()) {
+    if (ruleData.hasFastCheckableSelector() && !scope) {
         // We know this selector does not include any pseudo elements.
         if (m_pseudoStyleRequest.pseudoId != NOPSEUDO)
             return false;
@@ -327,7 +327,7 @@
                 ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
 
             // Add this rule to our list of matched rules.
-            addMatchedRule(&ruleData, cascadeScope, cascadeOrder);
+            addMatchedRule(&ruleData, cascadeScope, cascadeOrder, matchRequest.styleSheetIndex);
             return;
         }
     }
@@ -353,11 +353,18 @@
 
 static inline bool compareRules(const MatchedRule& matchedRule1, const MatchedRule& matchedRule2)
 {
+    if (matchedRule1.cascadeScope() != matchedRule2.cascadeScope())
+        return matchedRule1.cascadeScope() > matchedRule2.cascadeScope();
+
     unsigned specificity1 = matchedRule1.ruleData()->specificity();
     unsigned specificity2 = matchedRule2.ruleData()->specificity();
-    return matchedRule1.cascadeScope() == matchedRule2.cascadeScope() ?
-        ((specificity1 == specificity2) ? matchedRule1.position() < matchedRule2.position() : specificity1 < specificity2) :
-        matchedRule1.cascadeScope() > matchedRule2.cascadeScope();
+    if (specificity1 != specificity2)
+        return specificity1 < specificity2;
+
+    if (matchedRule1.styleSheetIndex() != matchedRule2.styleSheetIndex())
+        return matchedRule1.styleSheetIndex() < matchedRule2.styleSheetIndex();
+
+    return matchedRule1.position() < matchedRule2.position();
 }
 
 void ElementRuleCollector::sortMatchedRules()
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index 79622d6..c54f6f9 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -34,7 +34,6 @@
 namespace WebCore {
 
 class CSSRuleList;
-class DocumentRuleSets;
 class RenderRegion;
 class RuleData;
 class RuleSet;
@@ -51,9 +50,10 @@
 class MatchedRule {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit MatchedRule(const RuleData* ruleData, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+    explicit MatchedRule(const RuleData* ruleData, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex)
         : m_ruleData(ruleData)
         , m_cascadeScope(cascadeScope)
+        , m_styleSheetIndex(styleSheetIndex)
     {
         ASSERT(m_ruleData);
         static const unsigned BitsForPositionInRuleData = 18;
@@ -63,11 +63,13 @@
     const RuleData* ruleData() const { return m_ruleData; }
     uint32_t cascadeScope() const { return m_cascadeScope; }
     uint32_t position() const { return m_position; }
+    uint32_t styleSheetIndex() const { return m_styleSheetIndex; }
 
 private:
     const RuleData* m_ruleData;
     CascadeScope m_cascadeScope;
     uint32_t m_position;
+    uint32_t m_styleSheetIndex;
 };
 
 class StyleRuleList : public RefCounted<StyleRuleList> {
@@ -86,9 +88,6 @@
     ElementRuleCollector(const ElementResolveContext&, const SelectorFilter&, RenderStyle* = 0, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
     ~ElementRuleCollector();
 
-    void setCanUseFastReject(bool canUseFastReject) { m_canUseFastReject = canUseFastReject; }
-    bool canUseFastReject() const { return m_canUseFastReject; }
-
     void setMode(SelectorChecker::Mode mode) { m_mode = mode; }
     void setPseudoStyleRequest(const PseudoStyleRequest& request) { m_pseudoStyleRequest = request; }
     void setSameOriginOnly(bool f) { m_sameOriginOnly = f; }
@@ -120,7 +119,7 @@
     void appendCSSOMWrapperForRule(StyleRule*);
 
     void sortMatchedRules();
-    void addMatchedRule(const RuleData*, CascadeScope, CascadeOrder);
+    void addMatchedRule(const RuleData*, CascadeScope, CascadeOrder, unsigned styleSheetIndex);
 
     StaticCSSRuleList* ensureRuleList();
     StyleRuleList* ensureStyleRuleList();
diff --git a/Source/core/css/FontFace.cpp b/Source/core/css/FontFace.cpp
index c7018f8..6361c31 100644
--- a/Source/core/css/FontFace.cpp
+++ b/Source/core/css/FontFace.cpp
@@ -61,48 +61,48 @@
     return parsedStyle->getPropertyCSSValue(propertyID);
 }
 
-PassRefPtr<FontFace> FontFace::create(const String& family, const String& source, const Dictionary& descriptors, ExceptionState& es)
+PassRefPtr<FontFace> FontFace::create(const String& family, const String& source, const Dictionary& descriptors, ExceptionState& exceptionState)
 {
     RefPtr<CSSValue> src = parseCSSValue(source, CSSPropertySrc);
     if (!src || !src->isValueList()) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return 0;
     }
 
     RefPtr<FontFace> fontFace = adoptRef<FontFace>(new FontFace(src));
-    fontFace->setFamily(family, es);
-    if (es.hadException())
+    fontFace->setFamily(family, exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     String value;
     if (descriptors.get("style", value)) {
-        fontFace->setStyle(value, es);
-        if (es.hadException())
+        fontFace->setStyle(value, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("weight", value)) {
-        fontFace->setWeight(value, es);
-        if (es.hadException())
+        fontFace->setWeight(value, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("stretch", value)) {
-        fontFace->setStretch(value, es);
-        if (es.hadException())
+        fontFace->setStretch(value, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("unicodeRange", value)) {
-        fontFace->setUnicodeRange(value, es);
-        if (es.hadException())
+        fontFace->setUnicodeRange(value, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("variant", value)) {
-        fontFace->setVariant(value, es);
-        if (es.hadException())
+        fontFace->setVariant(value, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("featureSettings", value)) {
-        fontFace->setFeatureSettings(value, es);
-        if (es.hadException())
+        fontFace->setFeatureSettings(value, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
 
@@ -174,41 +174,41 @@
     return m_featureSettings ? m_featureSettings->cssText() : "normal";
 }
 
-void FontFace::setStyle(const String& s, ExceptionState& es)
+void FontFace::setStyle(const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontStyle, es);
+    setPropertyFromString(s, CSSPropertyFontStyle, exceptionState);
 }
 
-void FontFace::setWeight(const String& s, ExceptionState& es)
+void FontFace::setWeight(const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontWeight, es);
+    setPropertyFromString(s, CSSPropertyFontWeight, exceptionState);
 }
 
-void FontFace::setStretch(const String& s, ExceptionState& es)
+void FontFace::setStretch(const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontStretch, es);
+    setPropertyFromString(s, CSSPropertyFontStretch, exceptionState);
 }
 
-void FontFace::setUnicodeRange(const String& s, ExceptionState& es)
+void FontFace::setUnicodeRange(const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyUnicodeRange, es);
+    setPropertyFromString(s, CSSPropertyUnicodeRange, exceptionState);
 }
 
-void FontFace::setVariant(const String& s, ExceptionState& es)
+void FontFace::setVariant(const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontVariant, es);
+    setPropertyFromString(s, CSSPropertyFontVariant, exceptionState);
 }
 
-void FontFace::setFeatureSettings(const String& s, ExceptionState& es)
+void FontFace::setFeatureSettings(const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyWebkitFontFeatureSettings, es);
+    setPropertyFromString(s, CSSPropertyWebkitFontFeatureSettings, exceptionState);
 }
 
-void FontFace::setPropertyFromString(const String& s, CSSPropertyID propertyID, ExceptionState& es)
+void FontFace::setPropertyFromString(const String& s, CSSPropertyID propertyID, ExceptionState& exceptionState)
 {
     RefPtr<CSSValue> value = parseCSSValue(s, propertyID);
     if (!value || !setPropertyValue(value, propertyID))
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
 }
 
 bool FontFace::setPropertyFromStyle(const StylePropertySet* properties, CSSPropertyID propertyID)
diff --git a/Source/core/css/FontFace.idl b/Source/core/css/FontFace.idl
index 874872f..152c1ef 100644
--- a/Source/core/css/FontFace.idl
+++ b/Source/core/css/FontFace.idl
@@ -38,16 +38,16 @@
 [
     RuntimeEnabled=FontLoadEvents,
     Constructor(DOMString family, DOMString source, Dictionary descriptors),
-    ConstructorRaisesException
+    RaisesException=Constructor
 ] interface FontFace {
 
-    [SetterRaisesException] attribute DOMString family;
-    [SetterRaisesException] attribute DOMString style;
-    [SetterRaisesException] attribute DOMString weight;
-    [SetterRaisesException] attribute DOMString stretch;
-    [SetterRaisesException] attribute DOMString unicodeRange;
-    [SetterRaisesException] attribute DOMString variant;
-    [SetterRaisesException] attribute DOMString featureSettings;
+    [RaisesException=Setter] attribute DOMString family;
+    [RaisesException=Setter] attribute DOMString style;
+    [RaisesException=Setter] attribute DOMString weight;
+    [RaisesException=Setter] attribute DOMString stretch;
+    [RaisesException=Setter] attribute DOMString unicodeRange;
+    [RaisesException=Setter] attribute DOMString variant;
+    [RaisesException=Setter] attribute DOMString featureSettings;
 
     readonly attribute FontFaceLoadStatus status;
 
diff --git a/Source/core/css/FontFaceSet.cpp b/Source/core/css/FontFaceSet.cpp
index f7dfa54..dd501ca 100644
--- a/Source/core/css/FontFaceSet.cpp
+++ b/Source/core/css/FontFaceSet.cpp
@@ -27,7 +27,6 @@
 #include "core/css/FontFaceSet.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "V8FontFaceSet.h"
 #include "bindings/v8/Dictionary.h"
 #include "bindings/v8/ScriptPromiseResolver.h"
 #include "bindings/v8/ScriptScope.h"
@@ -40,6 +39,7 @@
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
+#include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "public/platform/Platform.h"
 
@@ -177,8 +177,7 @@
 
 void FontFaceSet::didLayout()
 {
-    Document* d = document();
-    if (d->page() && d->page()->mainFrame() == d->frame())
+    if (document()->frame()->isMainFrame())
         m_histogram.record();
     if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
         return;
@@ -329,13 +328,13 @@
     return s.isNull() ? space : s;
 }
 
-Vector<RefPtr<FontFace> > FontFaceSet::match(const String& fontString, const String& text, ExceptionState& es)
+Vector<RefPtr<FontFace> > FontFaceSet::match(const String& fontString, const String& text, ExceptionState& exceptionState)
 {
     Vector<RefPtr<FontFace> > matchedFonts;
 
     Font font;
     if (!resolveFontStyle(fontString, font)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return matchedFonts;
     }
 
@@ -347,11 +346,11 @@
     return matchedFonts;
 }
 
-ScriptPromise FontFaceSet::load(const String& fontString, const String& text, ExceptionState& es)
+ScriptPromise FontFaceSet::load(const String& fontString, const String& text, ExceptionState& exceptionState)
 {
     Font font;
     if (!resolveFontStyle(fontString, font)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return ScriptPromise();
     }
 
@@ -369,11 +368,11 @@
     return promise;
 }
 
-bool FontFaceSet::check(const String& fontString, const String& text, ExceptionState& es)
+bool FontFaceSet::check(const String& fontString, const String& text, ExceptionState& exceptionState)
 {
     Font font;
     if (!resolveFontStyle(fontString, font)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return false;
     }
 
@@ -436,7 +435,7 @@
     if (m_recorded)
         return;
     m_recorded = true;
-    WebKit::Platform::current()->histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
+    blink::Platform::current()->histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
 }
 
 static const char* supplementName()
diff --git a/Source/core/css/FontFaceSet.idl b/Source/core/css/FontFaceSet.idl
index daa2e8e..643c335 100644
--- a/Source/core/css/FontFaceSet.idl
+++ b/Source/core/css/FontFaceSet.idl
@@ -31,10 +31,10 @@
 enum FontFaceSetLoadStatus { "loading", "loaded" };
 
 [
+    ActiveDOMObject,
+    GenerateVisitDOMWrapper=document,
     NoInterfaceObject,
     RuntimeEnabled=FontLoadEvents,
-    ActiveDOMObject,
-    GenerateIsReachable=document
 ] interface FontFaceSet : EventTarget {
 
     attribute EventHandler onloading;
diff --git a/Source/core/css/InspectorCSSOMWrappers.cpp b/Source/core/css/InspectorCSSOMWrappers.cpp
index 7474b7f..3c9037d 100644
--- a/Source/core/css/InspectorCSSOMWrappers.cpp
+++ b/Source/core/css/InspectorCSSOMWrappers.cpp
@@ -30,7 +30,6 @@
 #include "core/css/InspectorCSSOMWrappers.h"
 
 #include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSHostRule.h"
 #include "core/css/CSSImportRule.h"
 #include "core/css/CSSMediaRule.h"
 #include "core/css/CSSRegionRule.h"
@@ -76,9 +75,6 @@
         case CSSRule::WEBKIT_REGION_RULE:
             collect(static_cast<CSSRegionRule*>(cssRule));
             break;
-        case CSSRule::HOST_RULE:
-            collect(static_cast<CSSHostRule*>(cssRule));
-            break;
         case CSSRule::STYLE_RULE:
             m_styleRuleToCSSOMWrapperMap.add(static_cast<CSSStyleRule*>(cssRule)->styleRule(), static_cast<CSSStyleRule*>(cssRule));
             break;
@@ -109,14 +105,11 @@
     styleSheetCollection->getActiveAuthorStyleSheets(activeAuthorStyleSheets);
     for (size_t i = 0; i < activeAuthorStyleSheets.size(); ++i)
         collectFromStyleSheets(*activeAuthorStyleSheets[i]);
-    collect(styleSheetCollection->pageUserSheet());
-    collectFromStyleSheets(styleSheetCollection->documentUserStyleSheets());
 }
 
 CSSStyleRule* InspectorCSSOMWrappers::getWrapperForRuleInSheets(StyleRule* rule, StyleEngine* styleSheetCollection)
 {
     if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::simpleDefaultStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::defaultStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::quirksStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::svgStyleSheet);
diff --git a/Source/core/css/MediaList.cpp b/Source/core/css/MediaList.cpp
index 00a30e7..23fd56b 100644
--- a/Source/core/css/MediaList.cpp
+++ b/Source/core/css/MediaList.cpp
@@ -196,26 +196,26 @@
     return String();
 }
 
-void MediaList::deleteMedium(const String& medium, ExceptionState& es)
+void MediaList::deleteMedium(const String& medium, ExceptionState& exceptionState)
 {
     CSSStyleSheet::RuleMutationScope mutationScope(m_parentRule);
 
     bool success = m_mediaQueries->remove(medium);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
     if (m_parentStyleSheet)
         m_parentStyleSheet->didMutate();
 }
 
-void MediaList::appendMedium(const String& medium, ExceptionState& es)
+void MediaList::appendMedium(const String& medium, ExceptionState& exceptionState)
 {
     CSSStyleSheet::RuleMutationScope mutationScope(m_parentRule);
 
     bool success = m_mediaQueries->add(medium);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
         return;
     }
 
diff --git a/Source/core/css/MediaQueryEvaluator.cpp b/Source/core/css/MediaQueryEvaluator.cpp
index 840faa7..3674430 100644
--- a/Source/core/css/MediaQueryEvaluator.cpp
+++ b/Source/core/css/MediaQueryEvaluator.cpp
@@ -138,7 +138,7 @@
             for (; j < expressions.size(); ++j) {
                 bool exprResult = eval(expressions.at(j).get());
                 if (viewportDependentMediaQueryResults && expressions.at(j)->isViewportDependent())
-                    viewportDependentMediaQueryResults->append(adoptPtr(new MediaQueryResult(*expressions.at(j), exprResult)));
+                    viewportDependentMediaQueryResults->append(adoptRef(new MediaQueryResult(*expressions.at(j), exprResult)));
                 if (!exprResult)
                     break;
             }
diff --git a/Source/core/css/MediaQueryEvaluator.h b/Source/core/css/MediaQueryEvaluator.h
index c663d12..60bd9cd 100644
--- a/Source/core/css/MediaQueryEvaluator.h
+++ b/Source/core/css/MediaQueryEvaluator.h
@@ -37,6 +37,8 @@
 class MediaQuerySet;
 class RenderStyle;
 
+typedef Vector<RefPtr<MediaQueryResult> > MediaQueryResultList;
+
 /**
  * Class that evaluates css media queries as defined in
  * CSS3 Module "Media Queries" (http://www.w3.org/TR/css3-mediaqueries/)
@@ -73,7 +75,6 @@
     bool mediaTypeMatch(const AtomicString& mediaTypeToMatch) const;
     bool mediaTypeMatchSpecific(const char* mediaTypeToMatch) const;
 
-    typedef Vector<OwnPtr<MediaQueryResult> > MediaQueryResultList;
     /** Evaluates a list of media queries */
     bool eval(const MediaQuerySet*, MediaQueryResultList* = 0) const;
 
diff --git a/Source/core/css/MediaQueryListListener.idl b/Source/core/css/MediaQueryListListener.idl
deleted file mode 100644
index 755c416..0000000
--- a/Source/core/css/MediaQueryListListener.idl
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- *
- *  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.
- */
-
-[
-
-    CPPPureInterface
-] interface MediaQueryListListener {
-    void queryChanged([Default=Undefined] optional MediaQueryList list);
-};
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index 87cc928..6d41e4f 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -44,6 +44,7 @@
 public:
     StyleAttributeMutationScope(PropertySetCSSStyleDeclaration* decl)
     {
+        InspectorInstrumentation::willMutateStyle(decl);
         ++s_scopeCount;
 
         if (s_scopeCount != 1) {
@@ -83,13 +84,15 @@
             m_mutationRecipients->enqueueMutationRecord(m_mutation);
 
         s_shouldDeliver = false;
-        if (!s_shouldNotifyInspector) {
-            s_currentDecl = 0;
-            return;
-        }
+
         // We have to clear internal state before calling Inspector's code.
         PropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
         s_currentDecl = 0;
+        InspectorInstrumentation::didMutateStyle(localCopyStyleDecl, localCopyStyleDecl->parentElement());
+
+        if (!s_shouldNotifyInspector)
+            return;
+
         s_shouldNotifyInspector = false;
         if (localCopyStyleDecl->parentElement())
             InspectorInstrumentation::didInvalidateStyleAttr(localCopyStyleDecl->parentElement());
@@ -149,12 +152,12 @@
     return m_propertySet->asText();
 }
 
-void PropertySetCSSStyleDeclaration::setCSSText(const String& text, ExceptionState& es)
+void PropertySetCSSStyleDeclaration::setCSSText(const String& text, ExceptionState& exceptionState)
 {
     StyleAttributeMutationScope mutationScope(this);
     willMutate();
 
-    // FIXME: Detect syntax errors and set es.
+    // FIXME: Detect syntax errors and set exceptionState.
     m_propertySet->parseDeclaration(text, contextStyleSheet());
 
     didMutate(PropertyChanged);
@@ -205,7 +208,7 @@
     return m_propertySet->isPropertyImplicit(propertyID);
 }
 
-void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& es)
+void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& exceptionState)
 {
     StyleAttributeMutationScope mutationScope(this);
     CSSPropertyID propertyID = cssPropertyID(propertyName);
@@ -227,7 +230,7 @@
     }
 }
 
-String PropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& es)
+String PropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& exceptionState)
 {
     StyleAttributeMutationScope mutationScope(this);
     CSSPropertyID propertyID = cssPropertyID(propertyName);
@@ -256,7 +259,7 @@
     return m_propertySet->getPropertyValue(propertyID);
 }
 
-void PropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState& es)
+void PropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState& exceptionState)
 {
     StyleAttributeMutationScope mutationScope(this);
     willMutate();
diff --git a/Source/core/css/RuleFeature.cpp b/Source/core/css/RuleFeature.cpp
index e75d8fe..755a4b5 100644
--- a/Source/core/css/RuleFeature.cpp
+++ b/Source/core/css/RuleFeature.cpp
@@ -48,9 +48,6 @@
         m_usesFirstLineRules = true;
         break;
         break;
-    case CSSSelector::PseudoPart:
-        attrsInRules.add(HTMLNames::partAttr.localName().impl());
-        break;
     case CSSSelector::PseudoHost:
         collectFeaturesFromSelectorList(selector->selectorList());
         break;
diff --git a/Source/core/css/RuleSet.cpp b/Source/core/css/RuleSet.cpp
index cce6f47..e709e48 100644
--- a/Source/core/css/RuleSet.cpp
+++ b/Source/core/css/RuleSet.cpp
@@ -32,7 +32,6 @@
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFontSelector.h"
-#include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSSelectorList.h"
 #include "core/css/MediaQueryEvaluator.h"
@@ -42,9 +41,8 @@
 #include "core/css/StyleRule.h"
 #include "core/css/StyleRuleImport.h"
 #include "core/css/StyleSheetContents.h"
-#include "core/css/resolver/StyleResolver.h"
 #include "core/html/track/TextTrackCue.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
@@ -52,16 +50,6 @@
 
 // -----------------------------------------------------------------
 
-static inline bool isDocumentScope(const ContainerNode* scope)
-{
-    return !scope || scope->isDocumentNode();
-}
-
-static inline bool isScopingNodeInShadowTree(const ContainerNode* scopingNode)
-{
-    return scopingNode && scopingNode->isInShadowTree();
-}
-
 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
 {
     ASSERT(selector);
@@ -272,8 +260,7 @@
         return true;
     }
     if (component->isCustomPseudoElement()) {
-        StringImpl* pseudoValue = component->pseudoType() == CSSSelector::PseudoPart ? component->argument().impl() : component->value().impl();
-        addToRuleSet(pseudoValue, ensurePendingRules()->shadowPseudoElementRules, ruleData);
+        addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
         return true;
     }
     if (component->pseudoType() == CSSSelector::PseudoCue) {
@@ -334,7 +321,19 @@
     m_viewportRules.append(rule);
 }
 
-void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin, const ContainerNode* scope)
+void RuleSet::addFontFaceRule(StyleRuleFontFace* rule)
+{
+    ensurePendingRules(); // So that m_fontFaceRules.shrinkToFit() gets called.
+    m_fontFaceRules.append(rule);
+}
+
+void RuleSet::addKeyframesRule(StyleRuleKeyframes* rule)
+{
+    ensurePendingRules(); // So that m_keyframesRules.shrinkToFit() gets called.
+    m_keyframesRules.append(rule);
+}
+
+void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
 {
     ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
     OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
@@ -347,7 +346,7 @@
     // FIXME: Should this add other types of rules? (i.e. use addChildRules() directly?)
     const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
     AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
-    addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleIsInRegionRule | (!scope ? RuleCanUseFastCheckSelector : 0));
+    addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleIsInRegionRule | RuleCanUseFastCheckSelector);
     for (unsigned i = 0; i < childRules.size(); ++i) {
         StyleRuleBase* regionStylingRule = childRules[i].get();
         if (regionStylingRule->isStyleRule())
@@ -359,7 +358,7 @@
     m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
 }
 
-void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, StyleResolver* resolver, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags addRuleFlags)
+void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
 {
     for (unsigned i = 0; i < rules.size(); ++i) {
         StyleRuleBase* rule = rules[i].get();
@@ -370,66 +369,45 @@
             const CSSSelectorList& selectorList = styleRule->selectorList();
             for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = selectorList.indexOfNextSelectorAfter(selectorIndex)) {
                 if (selectorList.hasCombinatorCrossingTreeBoundaryAt(selectorIndex)) {
-                    resolver->ruleSets().treeBoundaryCrossingRules().addRule(styleRule, selectorIndex, const_cast<ContainerNode*>(scope), addRuleFlags);
+                    m_treeBoundaryCrossingRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
                 } else if (selectorList.hasShadowDistributedAt(selectorIndex)) {
-                    if (isDocumentScope(scope))
-                        continue;
-                    resolver->ruleSets().treeBoundaryCrossingRules().addRule(styleRule, selectorIndex, const_cast<ContainerNode*>(scope), addRuleFlags);
-                } else
+                    m_shadowDistributedRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
+                } else {
                     addRule(styleRule, selectorIndex, addRuleFlags);
+                }
             }
-        } else if (rule->isPageRule())
+        } else if (rule->isPageRule()) {
             addPageRule(static_cast<StyleRulePage*>(rule));
-        else if (rule->isMediaRule()) {
+        } else if (rule->isMediaRule()) {
             StyleRuleMedia* mediaRule = static_cast<StyleRuleMedia*>(rule);
-            if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), resolver->viewportDependentMediaQueryResults())))
-                addChildRules(mediaRule->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
-        } else if (rule->isFontFaceRule() && resolver) {
-            // Add this font face to our set.
-            // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
-            if (!isDocumentScope(scope))
-                continue;
-            const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(rule);
-            resolver->fontSelector()->addFontFaceRule(fontFaceRule);
-            resolver->invalidateMatchedPropertiesCache();
-        } else if (rule->isKeyframesRule() && resolver) {
-            resolver->ensureScopedStyleResolver(scope)->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(rule));
-        } else if (rule->isRegionRule() && resolver) {
-            // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
-            addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin, scope);
-        } else if (rule->isHostRule() && resolver) {
-            if (!isScopingNodeInShadowTree(scope))
-                continue;
-            bool enabled = resolver->buildScopedStyleTreeInDocumentOrder();
-            resolver->setBuildScopedStyleTreeInDocumentOrder(false);
-            resolver->ensureScopedStyleResolver(scope->shadowHost())->addHostRule(static_cast<StyleRuleHost*>(rule), hasDocumentSecurityOrigin, scope);
-            resolver->setBuildScopedStyleTreeInDocumentOrder(enabled);
+            if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
+                addChildRules(mediaRule->childRules(), medium, addRuleFlags);
+        } else if (rule->isFontFaceRule()) {
+            addFontFaceRule(static_cast<StyleRuleFontFace*>(rule));
+        } else if (rule->isKeyframesRule()) {
+            addKeyframesRule(static_cast<StyleRuleKeyframes*>(rule));
+        } else if (rule->isRegionRule()) {
+            addRegionRule(static_cast<StyleRuleRegion*>(rule), addRuleFlags & RuleHasDocumentSecurityOrigin);
         } else if (rule->isViewportRule()) {
-            // @viewport should not be scoped.
-            if (!isDocumentScope(scope))
-                continue;
             addViewportRule(static_cast<StyleRuleViewport*>(rule));
+        } else if (rule->isSupportsRule() && static_cast<StyleRuleSupports*>(rule)->conditionIsSupported()) {
+            addChildRules(static_cast<StyleRuleSupports*>(rule)->childRules(), medium, addRuleFlags);
         }
-        else if (rule->isSupportsRule() && static_cast<StyleRuleSupports*>(rule)->conditionIsSupported())
-            addChildRules(static_cast<StyleRuleSupports*>(rule)->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
     }
 }
 
-void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* resolver, const ContainerNode* scope)
+void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
 {
     ASSERT(sheet);
 
     const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
     for (unsigned i = 0; i < importRules.size(); ++i) {
         StyleRuleImport* importRule = importRules[i].get();
-        if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), resolver->viewportDependentMediaQueryResults())))
-            addRulesFromSheet(importRule->styleSheet(), medium, resolver, scope);
+        if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
+            addRulesFromSheet(importRule->styleSheet(), medium, addRuleFlags);
     }
 
-    bool hasDocumentSecurityOrigin = resolver && resolver->document().securityOrigin()->canRequest(sheet->baseURL());
-    AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>((hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : 0) | (!scope ? RuleCanUseFastCheckSelector : 0));
-
-    addChildRules(sheet->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
+    addChildRules(sheet->childRules(), medium, static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector));
 }
 
 void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
@@ -470,6 +448,10 @@
     m_universalRules.shrinkToFit();
     m_pageRules.shrinkToFit();
     m_viewportRules.shrinkToFit();
+    m_fontFaceRules.shrinkToFit();
+    m_keyframesRules.shrinkToFit();
+    m_treeBoundaryCrossingRules.shrinkToFit();
+    m_shadowDistributedRules.shrinkToFit();
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleSet.h b/Source/core/css/RuleSet.h
index 7bae0c0..d8249a3 100644
--- a/Source/core/css/RuleSet.h
+++ b/Source/core/css/RuleSet.h
@@ -22,8 +22,11 @@
 #ifndef RuleSet_h
 #define RuleSet_h
 
+#include "core/css/CSSKeyframesRule.h"
+#include "core/css/MediaQueryEvaluator.h"
 #include "core/css/RuleFeature.h"
 #include "core/css/StyleRule.h"
+#include "core/css/resolver/MediaQueryResult.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/LinkedStack.h"
@@ -44,12 +47,23 @@
 };
 
 class CSSSelector;
-class ContainerNode;
 class MediaQueryEvaluator;
-class StyleResolver;
 class StyleRuleRegion;
 class StyleSheetContents;
 
+struct MinimalRuleData {
+    MinimalRuleData(StyleRule* rule, unsigned selectorIndex, AddRuleFlags flags)
+    : m_rule(rule)
+    , m_selectorIndex(selectorIndex)
+    , m_flags(flags)
+    {
+    }
+
+    StyleRule* m_rule;
+    unsigned m_selectorIndex;
+    AddRuleFlags m_flags;
+};
+
 class RuleData {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -108,7 +122,7 @@
 public:
     static PassOwnPtr<RuleSet> create() { return adoptPtr(new RuleSet); }
 
-    void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver* = 0, const ContainerNode* = 0);
+    void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, AddRuleFlags = RuleHasNoSpecialState);
     void addStyleRule(StyleRule*, AddRuleFlags);
     void addRule(StyleRule*, unsigned selectorIndex, AddRuleFlags);
 
@@ -124,6 +138,11 @@
     const Vector<RuleData>* universalRules() const { ASSERT(!m_pendingRules); return &m_universalRules; }
     const Vector<StyleRulePage*>& pageRules() const { ASSERT(!m_pendingRules); return m_pageRules; }
     const Vector<StyleRuleViewport*>& viewportRules() const { ASSERT(!m_pendingRules); return m_viewportRules; }
+    const Vector<StyleRuleFontFace*>& fontFaceRules() const { return m_fontFaceRules; }
+    const Vector<StyleRuleKeyframes*>& keyframesRules() const { return m_keyframesRules; }
+    const Vector<MinimalRuleData>& treeBoundaryCrossingRules() const { return m_treeBoundaryCrossingRules; }
+    const Vector<MinimalRuleData>& shadowDistributedRules() const { return m_shadowDistributedRules; }
+    const MediaQueryResultList& viewportDependentMediaQueryResults() const { return m_viewportDependentMediaQueryResults; }
 
     unsigned ruleCount() const { return m_ruleCount; }
 
@@ -156,9 +175,11 @@
     void addToRuleSet(StringImpl* key, PendingRuleMap&, const RuleData&);
     void addPageRule(StyleRulePage*);
     void addViewportRule(StyleRuleViewport*);
-    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin, const ContainerNode* scope);
+    void addFontFaceRule(StyleRuleFontFace*);
+    void addKeyframesRule(StyleRuleKeyframes*);
+    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
 
-    void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, StyleResolver*, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags);
+    void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, AddRuleFlags);
     bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
 
     void compactRules();
@@ -189,6 +210,12 @@
     RuleFeatureSet m_features;
     Vector<StyleRulePage*> m_pageRules;
     Vector<StyleRuleViewport*> m_viewportRules;
+    Vector<StyleRuleFontFace*> m_fontFaceRules;
+    Vector<StyleRuleKeyframes*> m_keyframesRules;
+    Vector<MinimalRuleData> m_treeBoundaryCrossingRules;
+    Vector<MinimalRuleData> m_shadowDistributedRules;
+
+    MediaQueryResultList m_viewportDependentMediaQueryResults;
 
     unsigned m_ruleCount;
     OwnPtr<PendingRuleMaps> m_pendingRules;
diff --git a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
index 5858b48..e55a966 100644
--- a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
@@ -80,11 +80,11 @@
     return list.release();
 }
 
-PassRefPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint> newPaint, RenderStyle* style) const
+PassRefPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint> newPaint, RenderStyle& style) const
 {
     RefPtr<SVGPaint> paint = newPaint;
     if (paint->paintType() == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR || paint->paintType() == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR)
-        paint->setColor(style->color());
+        paint->setColor(style.color());
     return paint.release();
 }
 
@@ -154,13 +154,13 @@
                 return CSSPrimitiveValue::create(svgStyle->filterResource(), CSSPrimitiveValue::CSS_URI);
             return CSSPrimitiveValue::createIdentifier(CSSValueNone);
         case CSSPropertyFloodColor:
-            return currentColorOrValidColor(style, svgStyle->floodColor());
+            return currentColorOrValidColor(*style, svgStyle->floodColor());
         case CSSPropertyLightingColor:
-            return currentColorOrValidColor(style, svgStyle->lightingColor());
+            return currentColorOrValidColor(*style, svgStyle->lightingColor());
         case CSSPropertyStopColor:
-            return currentColorOrValidColor(style, svgStyle->stopColor());
+            return currentColorOrValidColor(*style, svgStyle->stopColor());
         case CSSPropertyFill:
-            return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->fillPaintType(), svgStyle->fillPaintUri(), svgStyle->fillPaintColor()), style);
+            return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->fillPaintType(), svgStyle->fillPaintUri(), svgStyle->fillPaintColor()), *style);
         case CSSPropertyKerning:
             return SVGLength::toCSSPrimitiveValue(svgStyle->kerning());
         case CSSPropertyMarkerEnd:
@@ -176,7 +176,7 @@
                 return CSSPrimitiveValue::create(svgStyle->markerStartResource(), CSSPrimitiveValue::CSS_URI);
             return CSSPrimitiveValue::createIdentifier(CSSValueNone);
         case CSSPropertyStroke:
-            return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->strokePaintType(), svgStyle->strokePaintUri(), svgStyle->strokePaintColor()), style);
+            return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->strokePaintType(), svgStyle->strokePaintUri(), svgStyle->strokePaintColor()), *style);
         case CSSPropertyStrokeDasharray:
             return strokeDashArrayToCSSValueList(svgStyle->strokeDashArray());
         case CSSPropertyStrokeDashoffset:
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index f9f11f3..0e6d251 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -47,6 +47,7 @@
 #include "core/html/HTMLOptGroupElement.h"
 #include "core/html/HTMLOptionElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/html/track/vtt/VTTElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/FocusController.h"
 #include "core/frame/Frame.h"
@@ -56,8 +57,6 @@
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/style/RenderStyle.h"
 
-#include "core/html/track/WebVTTElement.h"
-
 namespace WebCore {
 
 using namespace HTMLNames;
@@ -75,18 +74,10 @@
     if (!root)
         return false;
 
-    if (selector->pseudoType() != CSSSelector::PseudoPart) {
-        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->part() != selector->argument())
+    const AtomicString& pseudoId = selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement ? element->shadowPseudoId() : element->pseudo();
+    if (pseudoId != selector->value())
         return false;
-    if (selector->isMatchUserAgentOnly() && root->type() != ShadowRoot::UserAgentShadowRoot)
+    if (selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement && root->type() != ShadowRoot::UserAgentShadowRoot)
         return false;
     return true;
 }
@@ -299,9 +290,21 @@
 {
     ASSERT(element);
     Vector<InsertionPoint*, 8> insertionPoints;
+
+    const ContainerNode* scope = nextContext.scope;
+    BehaviorAtBoundary behaviorAtBoundary = nextContext.behaviorAtBoundary;
+
     collectDestinationInsertionPoints(*element, insertionPoints);
     for (size_t i = 0; i < insertionPoints.size(); ++i) {
         nextContext.element = insertionPoints[i];
+
+        // If a given scope is a shadow host of an insertion point but behaviorAtBoundary doesn't have ScopeIsShadowHost,
+        // we need to update behaviorAtBoundary to make selectors like ":host > ::content" work correctly.
+        if (scope == insertionPoints[i]->containingShadowRoot()->shadowHost() && !(behaviorAtBoundary & ScopeIsShadowHost))
+            nextContext.behaviorAtBoundary = static_cast<BehaviorAtBoundary>(behaviorAtBoundary | ScopeIsShadowHost);
+        else
+            nextContext.behaviorAtBoundary = behaviorAtBoundary;
+
         nextContext.isSubSelector = false;
         nextContext.elementStyle = 0;
         if (match(nextContext, dynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
@@ -644,12 +647,18 @@
                 if (context.elementStyle)
                     context.elementStyle->setAffectedByDrag();
                 else
-                    element.setChildrenAffectedByDrag(true);
+                    element.setChildrenAffectedByDrag();
             }
             if (element.renderer() && element.renderer()->isDragging())
                 return true;
             break;
         case CSSSelector::PseudoFocus:
+            if (m_mode == ResolvingStyle) {
+                if (context.elementStyle)
+                    context.elementStyle->setAffectedByFocus();
+                else
+                    element.setChildrenAffectedByFocus();
+            }
             return matchesFocusPseudoClass(element);
         case CSSSelector::PseudoHover:
             // If we're in quirks mode, then hover should never match anchors with no
@@ -659,7 +668,7 @@
                     if (context.elementStyle)
                         context.elementStyle->setAffectedByHover();
                     else
-                        element.setChildrenAffectedByHover(true);
+                        element.setChildrenAffectedByHover();
                 }
                 if (element.hovered() || InspectorInstrumentation::forcePseudoState(&element, CSSSelector::PseudoHover))
                     return true;
@@ -673,7 +682,7 @@
                     if (context.elementStyle)
                         context.elementStyle->setAffectedByActive();
                     else
-                        element.setChildrenAffectedByActive(true);
+                        element.setChildrenAffectedByActive();
                 }
                 if (element.active() || InspectorInstrumentation::forcePseudoState(&element, CSSSelector::PseudoActive))
                     return true;
@@ -730,8 +739,8 @@
         case CSSSelector::PseudoLang:
             {
                 AtomicString value;
-                if (element.isWebVTTElement())
-                    value = toWebVTTElement(element).language();
+                if (element.isVTTElement())
+                    value = toVTTElement(element).language();
                 else
                     value = element.computeInheritedLanguage();
                 const AtomicString& argument = selector->argument();
@@ -773,9 +782,9 @@
             element.document().setContainsValidityStyleRules();
             return element.isOutOfRange();
         case CSSSelector::PseudoFutureCue:
-            return (element.isWebVTTElement() && !toWebVTTElement(element).isPastNode());
+            return (element.isVTTElement() && !toVTTElement(element).isPastNode());
         case CSSSelector::PseudoPastCue:
-            return (element.isWebVTTElement() && toWebVTTElement(element).isPastNode());
+            return (element.isVTTElement() && toVTTElement(element).isPastNode());
 
         case CSSSelector::PseudoScope:
             {
@@ -803,8 +812,8 @@
 
                 SelectorCheckingContext subContext(context);
                 subContext.isSubSelector = true;
-                subContext.behaviorAtBoundary = CrossesBoundary;
-                subContext.scope = 0;
+                subContext.behaviorAtBoundary = static_cast<BehaviorAtBoundary>(CrossesBoundary | ScopeIsShadowHost | TreatShadowHostAsNormalScope);
+                subContext.scope = context.scope;
                 // Use NodeRenderingTraversal to traverse a composed ancestor list of a given element.
                 for (Element* nextElement = &element; nextElement; nextElement = NodeRenderingTraversal::parentElement(nextElement)) {
                     // If one of simple selectors matches an element, returns SelectorMatches. Just "OR".
@@ -814,6 +823,8 @@
                         if (match(subContext, ignoreDynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
                             return true;
                     }
+                    subContext.behaviorAtBoundary = CrossesBoundary;
+                    subContext.scope = 0;
                 }
             }
             break;
diff --git a/Source/core/css/SelectorChecker.h b/Source/core/css/SelectorChecker.h
index 2d228a8..0107b4f 100644
--- a/Source/core/css/SelectorChecker.h
+++ b/Source/core/css/SelectorChecker.h
@@ -29,11 +29,13 @@
 #define SelectorChecker_h
 
 #include "core/css/CSSSelector.h"
-#include "core/inspector/InspectorInstrumentation.h"
+#include "core/dom/Element.h"
+#include "platform/scroll/ScrollTypes.h"
 
 namespace WebCore {
 
 class CSSSelector;
+class ContainerNode;
 class Element;
 class RenderScrollbar;
 class RenderStyle;
@@ -51,7 +53,8 @@
         StaysWithinTreeScope = 2,
         BoundaryBehaviorMask = 3, // 2bit for boundary behavior
         ScopeContainsLastMatchedElement = 4,
-        ScopeIsShadowHost = 8
+        ScopeIsShadowHost = 8,
+        TreatShadowHostAsNormalScope = 16
     };
 
     enum MatchingTagType {
@@ -162,7 +165,7 @@
 
 inline bool SelectorChecker::isHostInItsShadowTree(const Element& element, BehaviorAtBoundary behaviorAtBoundary, const ContainerNode* scope)
 {
-    return (behaviorAtBoundary & ScopeIsShadowHost) && scope == element;
+    return (behaviorAtBoundary & (ScopeIsShadowHost | TreatShadowHostAsNormalScope)) == ScopeIsShadowHost && scope == element;
 }
 
 }
diff --git a/Source/core/css/SelectorFilter.cpp b/Source/core/css/SelectorFilter.cpp
index 0530099..8dd9529 100644
--- a/Source/core/css/SelectorFilter.cpp
+++ b/Source/core/css/SelectorFilter.cpp
@@ -37,24 +37,24 @@
 // Salt to separate otherwise identical string hashes so a class-selector like .article won't match <article> elements.
 enum { TagNameSalt = 13, IdAttributeSalt = 17, ClassAttributeSalt = 19 };
 
-static inline void collectElementIdentifierHashes(const Element* element, Vector<unsigned, 4>& identifierHashes)
+static inline void collectElementIdentifierHashes(const Element& element, Vector<unsigned, 4>& identifierHashes)
 {
-    identifierHashes.append(element->localName().impl()->existingHash() * TagNameSalt);
-    if (element->hasID())
-        identifierHashes.append(element->idForStyleResolution().impl()->existingHash() * IdAttributeSalt);
-    if (element->isStyledElement() && element->hasClass()) {
-        const SpaceSplitString& classNames = element->classNames();
+    identifierHashes.append(element.localName().impl()->existingHash() * TagNameSalt);
+    if (element.hasID())
+        identifierHashes.append(element.idForStyleResolution().impl()->existingHash() * IdAttributeSalt);
+    if (element.isStyledElement() && element.hasClass()) {
+        const SpaceSplitString& classNames = element.classNames();
         size_t count = classNames.size();
         for (size_t i = 0; i < count; ++i)
             identifierHashes.append(classNames[i].impl()->existingHash() * ClassAttributeSalt);
     }
 }
 
-void SelectorFilter::pushParentStackFrame(Element* parent)
+void SelectorFilter::pushParentStackFrame(Element& parent)
 {
     ASSERT(m_ancestorIdentifierFilter);
-    ASSERT(m_parentStack.isEmpty() || m_parentStack.last().element == parent->parentOrShadowHostElement());
-    ASSERT(!m_parentStack.isEmpty() || !parent->parentOrShadowHostElement());
+    ASSERT(m_parentStack.isEmpty() || m_parentStack.last().element == parent.parentOrShadowHostElement());
+    ASSERT(!m_parentStack.isEmpty() || !parent.parentOrShadowHostElement());
     m_parentStack.append(ParentStackFrame(parent));
     ParentStackFrame& parentFrame = m_parentStack.last();
     // Mix tags, class names and ids into some sort of weird bouillabaisse.
@@ -80,31 +80,31 @@
     }
 }
 
-void SelectorFilter::setupParentStack(Element* parent)
+void SelectorFilter::setupParentStack(Element& parent)
 {
     ASSERT(m_parentStack.isEmpty() == !m_ancestorIdentifierFilter);
     // Kill whatever we stored before.
     m_parentStack.shrink(0);
     m_ancestorIdentifierFilter = adoptPtr(new BloomFilter<bloomFilterKeyBits>);
     // Fast version if parent is a root element:
-    if (!parent->parentOrShadowHostNode()) {
+    if (!parent.parentOrShadowHostNode()) {
         pushParentStackFrame(parent);
         return;
     }
     // Otherwise climb up the tree.
     Vector<Element*, 30> ancestors;
-    for (Element* ancestor = parent; ancestor; ancestor = ancestor->parentOrShadowHostElement())
+    for (Element* ancestor = &parent; ancestor; ancestor = ancestor->parentOrShadowHostElement())
         ancestors.append(ancestor);
     for (size_t n = ancestors.size(); n; --n)
-        pushParentStackFrame(ancestors[n - 1]);
+        pushParentStackFrame(*ancestors[n - 1]);
 }
 
-void SelectorFilter::pushParent(Element* parent)
+void SelectorFilter::pushParent(Element& parent)
 {
     ASSERT(m_ancestorIdentifierFilter);
     // We may get invoked for some random elements in some wacky cases during style resolve.
     // Pause maintaining the stack in this case.
-    if (m_parentStack.last().element != parent->parentOrShadowHostElement())
+    if (m_parentStack.last().element != parent.parentOrShadowHostElement())
         return;
     pushParentStackFrame(parent);
 }
@@ -148,16 +148,18 @@
         case CSSSelector::DirectAdjacent:
         case CSSSelector::IndirectAdjacent:
         case CSSSelector::ShadowPseudo:
-        case CSSSelector::ChildTree:
-        case CSSSelector::DescendantTree:
             skipOverSubselectors = true;
             break;
         case CSSSelector::Descendant:
         case CSSSelector::Child:
             if (relationIsAffectedByPseudoContent) {
-                skipOverSubselectors = true;
-                break;
+                // Disable fastRejectSelector.
+                *identifierHashes = 0;
+                return;
             }
+            // Fall through.
+        case CSSSelector::ChildTree:
+        case CSSSelector::DescendantTree:
             skipOverSubselectors = false;
             collectDescendantSelectorIdentifierHashes(selector, hash);
             break;
diff --git a/Source/core/css/SelectorFilter.h b/Source/core/css/SelectorFilter.h
index 4ffde10..905edb6 100644
--- a/Source/core/css/SelectorFilter.h
+++ b/Source/core/css/SelectorFilter.h
@@ -39,11 +39,11 @@
 
 class SelectorFilter {
 public:
-    void pushParentStackFrame(Element* parent);
+    void pushParentStackFrame(Element& parent);
     void popParentStackFrame();
 
-    void setupParentStack(Element* parent);
-    void pushParent(Element* parent);
+    void setupParentStack(Element& parent);
+    void pushParent(Element& parent);
     void popParent() { popParentStackFrame(); }
     bool parentStackIsEmpty() const { return m_parentStack.isEmpty(); }
     bool parentStackIsConsistent(const ContainerNode* parentNode) const { return !m_parentStack.isEmpty() && m_parentStack.last().element == parentNode; }
@@ -55,7 +55,7 @@
 private:
     struct ParentStackFrame {
         ParentStackFrame() : element(0) { }
-        ParentStackFrame(Element* element) : element(element) { }
+        ParentStackFrame(Element& element) : element(&element) { }
         Element* element;
         Vector<unsigned, 4> identifierHashes;
     };
diff --git a/Source/core/css/StyleInvalidationAnalysis.cpp b/Source/core/css/StyleInvalidationAnalysis.cpp
index b0053cb..440e17f 100644
--- a/Source/core/css/StyleInvalidationAnalysis.cpp
+++ b/Source/core/css/StyleInvalidationAnalysis.cpp
@@ -88,17 +88,6 @@
     return false;
 }
 
-static bool hasAtHostRule(StyleSheetContents* styleSheetContents)
-{
-    const Vector<RefPtr<StyleRuleBase> >& rules = styleSheetContents->childRules();
-    for (unsigned i = 0; i < rules.size(); i++) {
-        const StyleRuleBase* rule = rules[i].get();
-        if (rule->isHostRule())
-            return true;
-    }
-    return false;
-}
-
 static Node* determineScopingNodeForStyleScoped(HTMLStyleElement* ownerElement, StyleSheetContents* styleSheetContents)
 {
     ASSERT(ownerElement && ownerElement->isRegisteredAsScoped());
@@ -112,7 +101,7 @@
 
             return scope;
         }
-        if (ownerElement->isRegisteredAsScoped() && hasAtHostRule(styleSheetContents))
+        if (ownerElement->isRegisteredAsScoped())
             return ownerElement->containingShadowRoot()->shadowHost();
     }
 
@@ -136,7 +125,6 @@
     // FIXME: Unclear if any of the rest need to cause style recalc:
     case StyleRule::Region:
     case StyleRule::Filter:
-    case StyleRule::HostInternal:
         return true;
 
     // These should all be impossible to reach:
@@ -204,7 +192,7 @@
     return false;
 }
 
-void StyleInvalidationAnalysis::invalidateStyle(Document* document)
+void StyleInvalidationAnalysis::invalidateStyle(Document& document)
 {
     ASSERT(!m_dirtiesAllStyle);
 
@@ -220,10 +208,10 @@
         if (elementMatchesSelectorScopes(element, m_idScopes, m_classScopes)) {
             element->setNeedsStyleRecalc();
             // The whole subtree is now invalidated, we can skip to the next sibling.
-            element = ElementTraversal::nextSkippingChildren(element);
+            element = ElementTraversal::nextSkippingChildren(*element);
             continue;
         }
-        element = ElementTraversal::next(element);
+        element = ElementTraversal::next(*element);
     }
 }
 
diff --git a/Source/core/css/StyleInvalidationAnalysis.h b/Source/core/css/StyleInvalidationAnalysis.h
index e58f37a..79cf3d8 100644
--- a/Source/core/css/StyleInvalidationAnalysis.h
+++ b/Source/core/css/StyleInvalidationAnalysis.h
@@ -41,7 +41,7 @@
     StyleInvalidationAnalysis(const Vector<StyleSheetContents*>&);
 
     bool dirtiesAllStyle() const { return m_dirtiesAllStyle; }
-    void invalidateStyle(Document*);
+    void invalidateStyle(Document&);
 
 private:
 
diff --git a/Source/core/css/StylePropertySet.cpp b/Source/core/css/StylePropertySet.cpp
index 270bd4b..7160423 100644
--- a/Source/core/css/StylePropertySet.cpp
+++ b/Source/core/css/StylePropertySet.cpp
@@ -58,8 +58,8 @@
 PassRefPtr<ImmutableStylePropertySet> StylePropertySet::immutableCopyIfNeeded() const
 {
     if (!isMutable())
-        return static_cast<ImmutableStylePropertySet*>(const_cast<StylePropertySet*>(this));
-    const MutableStylePropertySet* mutableThis = static_cast<const MutableStylePropertySet*>(this);
+        return toImmutableStylePropertySet(const_cast<StylePropertySet*>(this));
+    const MutableStylePropertySet* mutableThis = toMutableStylePropertySet(this);
     return ImmutableStylePropertySet::create(mutableThis->m_propertyVector.data(), mutableThis->m_propertyVector.size(), cssParserMode());
 }
 
@@ -98,9 +98,9 @@
 MutableStylePropertySet::MutableStylePropertySet(const StylePropertySet& other)
     : StylePropertySet(other.cssParserMode())
 {
-    if (other.isMutable())
-        m_propertyVector = static_cast<const MutableStylePropertySet&>(other).m_propertyVector;
-    else {
+    if (other.isMutable()) {
+        m_propertyVector = toMutableStylePropertySet(other).m_propertyVector;
+    } else {
         m_propertyVector.reserveInitialCapacity(other.propertyCount());
         for (unsigned i = 0; i < other.propertyCount(); ++i)
             m_propertyVector.uncheckedAppend(other.propertyAt(i).toCSSProperty());
@@ -275,7 +275,9 @@
         return 0;
 
     CSSPropertyID prefixedShorthand = prefixingVariantForPropertyId(property.shorthandID());
-    return indexOfShorthandForLonghand(prefixedShorthand, matchingShorthandsForLonghand(prefixingVariant));
+    Vector<StylePropertyShorthand, 4> shorthands;
+    getMatchingShorthandsForLonghand(prefixingVariant, &shorthands);
+    return indexOfShorthandForLonghand(prefixedShorthand, shorthands);
 }
 
 bool MutableStylePropertySet::setVariableValue(const AtomicString& name, const String& value, bool important)
@@ -337,7 +339,7 @@
     CSSParserContext context(cssParserMode());
     if (contextStyleSheet) {
         context = contextStyleSheet->parserContext();
-        context.mode = cssParserMode();
+        context.setMode(cssParserMode());
     }
 
     CSSParser parser(context, UseCounter::getFrom(contextStyleSheet));
@@ -365,7 +367,7 @@
 
 bool StylePropertySet::hasCSSOMWrapper() const
 {
-    return m_isMutable && static_cast<const MutableStylePropertySet*>(this)->m_cssomWrapper;
+    return m_isMutable && toMutableStylePropertySet(this)->m_cssomWrapper;
 }
 
 void MutableStylePropertySet::mergeAndOverrideOnConflict(const StylePropertySet* other)
diff --git a/Source/core/css/StylePropertySet.h b/Source/core/css/StylePropertySet.h
index 30a8c50..1003f3b 100644
--- a/Source/core/css/StylePropertySet.h
+++ b/Source/core/css/StylePropertySet.h
@@ -173,6 +173,13 @@
     return reinterpret_cast<const StylePropertyMetadata*>(&reinterpret_cast<const char*>(&(this->m_storage))[m_arraySize * sizeof(CSSValue*)]);
 }
 
+DEFINE_TYPE_CASTS(ImmutableStylePropertySet, StylePropertySet, set, !set->isMutable(), !set.isMutable());
+
+inline ImmutableStylePropertySet* toImmutableStylePropertySet(const RefPtr<StylePropertySet>& set)
+{
+    return toImmutableStylePropertySet(set.get());
+}
+
 class MutableStylePropertySet : public StylePropertySet {
 public:
     ~MutableStylePropertySet() { }
@@ -250,24 +257,31 @@
     friend class StylePropertySet;
 };
 
+DEFINE_TYPE_CASTS(MutableStylePropertySet, StylePropertySet, set, set->isMutable(), set.isMutable());
+
+inline MutableStylePropertySet* toMutableStylePropertySet(const RefPtr<StylePropertySet>& set)
+{
+    return toMutableStylePropertySet(set.get());
+}
+
 inline const StylePropertyMetadata& StylePropertySet::PropertyReference::propertyMetadata() const
 {
     if (m_propertySet.isMutable())
-        return static_cast<const MutableStylePropertySet&>(m_propertySet).m_propertyVector.at(m_index).metadata();
-    return static_cast<const ImmutableStylePropertySet&>(m_propertySet).metadataArray()[m_index];
+        return toMutableStylePropertySet(m_propertySet).m_propertyVector.at(m_index).metadata();
+    return toImmutableStylePropertySet(m_propertySet).metadataArray()[m_index];
 }
 
 inline const CSSValue* StylePropertySet::PropertyReference::propertyValue() const
 {
     if (m_propertySet.isMutable())
-        return static_cast<const MutableStylePropertySet&>(m_propertySet).m_propertyVector.at(m_index).value();
-    return static_cast<const ImmutableStylePropertySet&>(m_propertySet).valueArray()[m_index];
+        return toMutableStylePropertySet(m_propertySet).m_propertyVector.at(m_index).value();
+    return toImmutableStylePropertySet(m_propertySet).valueArray()[m_index];
 }
 
 inline unsigned StylePropertySet::propertyCount() const
 {
     if (m_isMutable)
-        return static_cast<const MutableStylePropertySet*>(this)->m_propertyVector.size();
+        return toMutableStylePropertySet(this)->m_propertyVector.size();
     return m_arraySize;
 }
 
@@ -282,9 +296,9 @@
         return;
 
     if (m_isMutable)
-        delete static_cast<MutableStylePropertySet*>(this);
+        delete toMutableStylePropertySet(this);
     else
-        delete static_cast<ImmutableStylePropertySet*>(this);
+        delete toImmutableStylePropertySet(this);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/StylePropertyShorthandCustom.cpp b/Source/core/css/StylePropertyShorthandCustom.cpp
index c3d44ac..b157746 100644
--- a/Source/core/css/StylePropertyShorthandCustom.cpp
+++ b/Source/core/css/StylePropertyShorthandCustom.cpp
@@ -113,7 +113,7 @@
     return shorthandForProperty(id).length();
 }
 
-unsigned indexOfShorthandForLonghand(CSSPropertyID shorthandID, const Vector<StylePropertyShorthand>& shorthands)
+unsigned indexOfShorthandForLonghand(CSSPropertyID shorthandID, const Vector<StylePropertyShorthand, 4>& shorthands)
 {
     for (unsigned i = 0; i < shorthands.size(); ++i) {
         if (shorthands.at(i).id() == shorthandID)
diff --git a/Source/core/css/StyleRule.cpp b/Source/core/css/StyleRule.cpp
index bb53bb8..0a4651a 100644
--- a/Source/core/css/StyleRule.cpp
+++ b/Source/core/css/StyleRule.cpp
@@ -25,7 +25,6 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFilterRule.h"
 #include "core/css/CSSFontFaceRule.h"
-#include "core/css/CSSHostRule.h"
 #include "core/css/CSSImportRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSMediaRule.h"
@@ -82,9 +81,6 @@
     case Keyframes:
         delete static_cast<StyleRuleKeyframes*>(this);
         return;
-    case HostInternal:
-        delete static_cast<StyleRuleHost*>(this);
-        return;
     case Viewport:
         delete static_cast<StyleRuleViewport*>(this);
         return;
@@ -121,8 +117,6 @@
         return 0;
     case Keyframes:
         return static_cast<const StyleRuleKeyframes*>(this)->copy();
-    case HostInternal:
-        return static_cast<const StyleRuleHost*>(this)->copy();
     case Viewport:
         return static_cast<const StyleRuleViewport*>(this)->copy();
     case Filter:
@@ -169,9 +163,6 @@
     case Viewport:
         rule = CSSViewportRule::create(static_cast<StyleRuleViewport*>(self), parentSheet);
         break;
-    case HostInternal:
-        rule = CSSHostRule::create(static_cast<StyleRuleHost*>(self), parentSheet);
-        break;
     case Filter:
         rule = CSSFilterRule::create(static_cast<StyleRuleFilter*>(self), parentSheet);
         break;
@@ -211,7 +202,7 @@
 {
     if (!m_properties->isMutable())
         m_properties = m_properties->mutableCopy();
-    return static_cast<MutableStylePropertySet*>(m_properties.get());
+    return toMutableStylePropertySet(m_properties);
 }
 
 void StyleRule::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -239,7 +230,7 @@
 {
     if (!m_properties->isMutable())
         m_properties = m_properties->mutableCopy();
-    return static_cast<MutableStylePropertySet*>(m_properties.get());
+    return toMutableStylePropertySet(m_properties);
 }
 
 void StyleRulePage::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -266,7 +257,7 @@
 {
     if (!m_properties->isMutable())
         m_properties = m_properties->mutableCopy();
-    return static_cast<MutableStylePropertySet*>(m_properties.get());
+    return toMutableStylePropertySet(m_properties);
 }
 
 void StyleRuleFontFace::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -358,7 +349,7 @@
 {
     if (!m_properties->isMutable())
         m_properties = m_properties->mutableCopy();
-    return static_cast<MutableStylePropertySet*>(m_properties.get());
+    return toMutableStylePropertySet(m_properties);
 }
 
 void StyleRuleViewport::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -387,7 +378,7 @@
 {
     if (!m_properties->isMutable())
         m_properties = m_properties->mutableCopy();
-    return static_cast<MutableStylePropertySet*>(m_properties.get());
+    return toMutableStylePropertySet(m_properties);
 }
 
 void StyleRuleFilter::setProperties(PassRefPtr<StylePropertySet> properties)
diff --git a/Source/core/css/StyleRule.h b/Source/core/css/StyleRule.h
index aa319ed..e65c737 100644
--- a/Source/core/css/StyleRule.h
+++ b/Source/core/css/StyleRule.h
@@ -50,8 +50,7 @@
         Supports = 12,
         Viewport = 15,
         Region = 16,
-        Filter = 17,
-        HostInternal = 18, // Spec says Host = 1001, but we can use only 5 bit for type().
+        Filter = 17
     };
 
     Type type() const { return static_cast<Type>(m_type); }
@@ -66,7 +65,6 @@
     bool isSupportsRule() const { return type() == Supports; }
     bool isViewportRule() const { return type() == Viewport; }
     bool isImportRule() const { return type() == Import; }
-    bool isHostRule() const { return type() == HostInternal; }
     bool isFilterRule() const { return type() == Filter; }
 
     PassRefPtr<StyleRuleBase> copy() const;
@@ -156,6 +154,12 @@
     RefPtr<StylePropertySet> m_properties;
 };
 
+inline const StyleRuleFontFace* toStyleRuleFontFace(const StyleRuleBase* rule)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isFontFaceRule());
+    return static_cast<const StyleRuleFontFace*>(rule);
+}
+
 class StyleRulePage : public StyleRuleBase {
 public:
     static PassRefPtr<StyleRulePage> create() { return adoptRef(new StyleRulePage); }
@@ -250,20 +254,6 @@
     CSSSelectorList m_selectorList;
 };
 
-class StyleRuleHost : public StyleRuleGroup {
-public:
-    static PassRefPtr<StyleRuleHost> create(Vector<RefPtr<StyleRuleBase> >& adoptRules)
-    {
-        return adoptRef(new StyleRuleHost(adoptRules));
-    }
-
-    PassRefPtr<StyleRuleHost> copy() const { return adoptRef(new StyleRuleHost(*this)); }
-
-private:
-    StyleRuleHost(Vector<RefPtr<StyleRuleBase> >& adoptRules) : StyleRuleGroup(HostInternal, adoptRules) { }
-    StyleRuleHost(const StyleRuleHost& o) : StyleRuleGroup(o) { }
-};
-
 class StyleRuleViewport : public StyleRuleBase {
 public:
     static PassRefPtr<StyleRuleViewport> create() { return adoptRef(new StyleRuleViewport); }
@@ -290,6 +280,12 @@
     return static_cast<const StyleRuleMedia*>(rule);
 }
 
+inline const StyleRuleMedia* toStyleRuleMedia(const StyleRuleBase* rule)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isMediaRule());
+    return static_cast<const StyleRuleMedia*>(rule);
+}
+
 inline const StyleRuleSupports* toStyleRuleSupports(const StyleRuleGroup* rule)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isSupportsRule());
@@ -302,6 +298,12 @@
     return static_cast<const StyleRuleRegion*>(rule);
 }
 
+inline StyleRuleViewport* toStyleRuleViewport(StyleRuleBase* rule)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isViewportRule());
+    return static_cast<StyleRuleViewport*>(rule);
+}
+
 class StyleRuleFilter : public StyleRuleBase {
 public:
     static PassRefPtr<StyleRuleFilter> create(const String& filterName) { return adoptRef(new StyleRuleFilter(filterName)); }
diff --git a/Source/core/css/StyleRuleImport.cpp b/Source/core/css/StyleRuleImport.cpp
index 5167a42..aff60cb 100644
--- a/Source/core/css/StyleRuleImport.cpp
+++ b/Source/core/css/StyleRuleImport.cpp
@@ -63,9 +63,9 @@
         m_styleSheet->clearOwnerRule();
 
     CSSParserContext context = m_parentStyleSheet ? m_parentStyleSheet->parserContext() : HTMLStandardMode;
-    context.charset = charset;
+    context.setCharset(charset);
     if (!baseURL.isNull())
-        context.baseURL = baseURL;
+        context.setBaseURL(baseURL);
 
     m_styleSheet = StyleSheetContents::create(this, href, context);
 
@@ -115,10 +115,7 @@
     }
 
     FetchRequest request(ResourceRequest(absURL), FetchInitiatorTypeNames::css, m_parentStyleSheet->charset());
-    if (m_parentStyleSheet->isUserStyleSheet())
-        m_resource = fetcher->fetchUserCSSStyleSheet(request);
-    else
-        m_resource = fetcher->fetchCSSStyleSheet(request);
+    m_resource = fetcher->fetchCSSStyleSheet(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
diff --git a/Source/core/css/StyleSheet.idl b/Source/core/css/StyleSheet.idl
index 2c179ac..04416bf 100644
--- a/Source/core/css/StyleSheet.idl
+++ b/Source/core/css/StyleSheet.idl
@@ -20,8 +20,8 @@
 
 // Introduced in DOM Level 2:
 [
-    CustomToV8,
-    GenerateIsReachable=ownerNode
+    CustomWrap,
+    GenerateVisitDOMWrapper=ownerNode,
 ] interface StyleSheet {
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString        type;
              attribute boolean          disabled;
diff --git a/Source/core/css/StyleSheetContents.cpp b/Source/core/css/StyleSheetContents.cpp
index 1bcbbda..7db643c 100644
--- a/Source/core/css/StyleSheetContents.cpp
+++ b/Source/core/css/StyleSheetContents.cpp
@@ -27,10 +27,12 @@
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
 #include "core/css/StyleRuleImport.h"
+#include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Node.h"
+#include "core/dom/StyleEngine.h"
 #include "core/fetch/CSSStyleSheetResource.h"
 #include "platform/TraceEvent.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Deque.h"
 
 namespace WebCore {
@@ -57,12 +59,12 @@
     : m_ownerRule(ownerRule)
     , m_originalURL(originalURL)
     , m_loadCompleted(false)
-    , m_isUserStyleSheet(ownerRule && ownerRule->parentStyleSheet() && ownerRule->parentStyleSheet()->isUserStyleSheet())
     , m_hasSyntacticallyValidCSSHeader(true)
     , m_didLoadErrorOccur(false)
     , m_usesRemUnits(false)
     , m_isMutable(false)
     , m_isInMemoryCache(false)
+    , m_hasFontFaceRule(false)
     , m_parserContext(context)
 {
 }
@@ -76,12 +78,12 @@
     , m_childRules(o.m_childRules.size())
     , m_namespaces(o.m_namespaces)
     , m_loadCompleted(true)
-    , m_isUserStyleSheet(o.m_isUserStyleSheet)
     , m_hasSyntacticallyValidCSSHeader(o.m_hasSyntacticallyValidCSSHeader)
     , m_didLoadErrorOccur(false)
     , m_usesRemUnits(o.m_usesRemUnits)
     , m_isMutable(false)
     , m_isInMemoryCache(false)
+    , m_hasFontFaceRule(o.m_hasFontFaceRule)
     , m_parserContext(o.m_parserContext)
 {
     ASSERT(o.isCacheable());
@@ -100,6 +102,13 @@
 
 bool StyleSheetContents::isCacheable() const
 {
+    // FIXME: StyleSheets with media queries can't be cached because their RuleSet
+    // is processed differently based off the media queries, which might resolve
+    // differently depending on the context of the parent CSSStyleSheet (e.g.
+    // if they are in differently sized iframes). Once RuleSets are media query
+    // agnostic, we can restore sharing of StyleSheetContents with medea queries.
+    if (m_hasMediaQueries)
+        return false;
     // FIXME: Support copying import rules.
     if (!m_importRules.isEmpty())
         return false;
@@ -127,19 +136,31 @@
     if (rule->isImportRule()) {
         // Parser enforces that @import rules come before anything else except @charset.
         ASSERT(m_childRules.isEmpty());
-        m_importRules.append(static_cast<StyleRuleImport*>(rule.get()));
+        StyleRuleImport* importRule = static_cast<StyleRuleImport*>(rule.get());
+        if (importRule->mediaQueries())
+            setHasMediaQueries();
+        m_importRules.append(importRule);
         m_importRules.last()->setParentStyleSheet(this);
         m_importRules.last()->requestStyleSheet();
         return;
     }
 
     // Add warning message to inspector if dpi/dpcm values are used for screen media.
-    if (rule->isMediaRule())
+    if (rule->isMediaRule()) {
+        setHasMediaQueries();
         reportMediaQueryWarningIfNeeded(singleOwnerDocument(), static_cast<StyleRuleMedia*>(rule.get())->mediaQueries());
+    }
 
     m_childRules.append(rule);
 }
 
+void StyleSheetContents::setHasMediaQueries()
+{
+    m_hasMediaQueries = true;
+    if (parentStyleSheet())
+        parentStyleSheet()->setHasMediaQueries();
+}
+
 StyleRuleBase* StyleSheetContents::ruleAt(unsigned index) const
 {
     ASSERT_WITH_SECURITY_IMPLICATION(index < ruleCount());
@@ -274,7 +295,7 @@
 {
     TRACE_EVENT0("webkit", "StyleSheetContents::parseAuthorStyleSheet");
 
-    bool quirksMode = isQuirksModeBehavior(m_parserContext.mode);
+    bool quirksMode = isQuirksModeBehavior(m_parserContext.mode());
 
     bool enforceMIMEType = !quirksMode;
     bool hasValidMIMEType = false;
@@ -293,15 +314,6 @@
             return;
         }
     }
-    if (!quirksMode && m_parserContext.needsSiteSpecificQuirks) {
-        // Work around <https://bugs.webkit.org/show_bug.cgi?id=28350>.
-        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)
-            && sheetText.length() >= mediaWikiKHTMLFixesStyleSheet.length() - 1)
-            clearRules();
-    }
 }
 
 bool StyleSheetContents::parseString(const String& sheetText)
@@ -356,6 +368,10 @@
 {
     ASSERT(sheet);
     m_didLoadErrorOccur |= sheet->errorOccurred();
+    // updateLayoutIgnorePendingStyleSheets can cause us to create the RuleSet on this
+    // sheet before its imports have loaded. So clear the RuleSet when the imports
+    // load since the import's subrules are flattened into its parent sheet's RuleSet.
+    clearRuleSet();
 }
 
 void StyleSheetContents::startLoadingDynamicSheet()
@@ -446,10 +462,6 @@
             if (childRulesHaveFailedOrCanceledSubresources(static_cast<const StyleRuleRegion*>(rule)->childRules()))
                 return true;
             break;
-        case StyleRuleBase::HostInternal:
-            if (childRulesHaveFailedOrCanceledSubresources(static_cast<const StyleRuleHost*>(rule)->childRules()))
-                return true;
-            break;
         case StyleRuleBase::Import:
             ASSERT_NOT_REACHED();
         case StyleRuleBase::Page:
@@ -510,4 +522,27 @@
     m_childRules.shrinkToFit();
 }
 
+RuleSet& StyleSheetContents::ensureRuleSet(const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
+{
+    if (!m_ruleSet) {
+        m_ruleSet = RuleSet::create();
+        m_ruleSet->addRulesFromSheet(this, medium, addRuleFlags);
+    }
+    return *m_ruleSet.get();
+}
+
+void StyleSheetContents::clearRuleSet()
+{
+    // Clearing the ruleSet means we need to recreate the styleResolver data structures.
+    // See the StyleResolver calls in ScopedStyleResolver::addRulesFromSheet.
+    for (size_t i = 0; i < m_clients.size(); ++i) {
+        if (Document* document = m_clients[i]->ownerDocument())
+            document->styleEngine()->clearResolver();
+    }
+    m_ruleSet.clear();
+    if (StyleSheetContents* parentSheet = parentStyleSheet())
+        parentSheet->clearRuleSet();
+}
+
+
 }
diff --git a/Source/core/css/StyleSheetContents.h b/Source/core/css/StyleSheetContents.h
index e9ec47e..7d59d80 100644
--- a/Source/core/css/StyleSheetContents.h
+++ b/Source/core/css/StyleSheetContents.h
@@ -22,12 +22,14 @@
 #define StyleSheetContents_h
 
 #include "core/css/CSSParserMode.h"
-#include "weborigin/KURL.h"
+#include "core/css/RuleSet.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/HashMap.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 #include "wtf/text/AtomicStringHash.h"
+#include "wtf/text/StringHash.h"
 #include "wtf/text/TextPosition.h"
 
 
@@ -78,7 +80,7 @@
     Node* singleOwnerNode() const;
     Document* singleOwnerDocument() const;
 
-    const String& charset() const { return m_parserContext.charset; }
+    const String& charset() const { return m_parserContext.charset(); }
 
     bool loadCompleted() const { return m_loadCompleted; }
     bool hasFailedOrCanceledSubresources() const;
@@ -86,11 +88,12 @@
     KURL completeURL(const String& url) const;
     void addSubresourceStyleURLs(ListHashSet<KURL>&);
 
-    void setIsUserStyleSheet(bool b) { m_isUserStyleSheet = b; }
-    bool isUserStyleSheet() const { return m_isUserStyleSheet; }
     void setHasSyntacticallyValidCSSHeader(bool b) { m_hasSyntacticallyValidCSSHeader = b; }
     bool hasSyntacticallyValidCSSHeader() const { return m_hasSyntacticallyValidCSSHeader; }
 
+    void setHasFontFaceRule(bool b) { m_hasFontFaceRule = b; }
+    bool hasFontFaceRule() const { return m_hasFontFaceRule; }
+
     void parserAddNamespace(const AtomicString& prefix, const AtomicString& uri);
     void parserAppendRule(PassRefPtr<StyleRuleBase>);
     void parserSetEncodingFromCharsetRule(const String& encoding);
@@ -114,7 +117,7 @@
     // this style sheet. This property probably isn't useful for much except
     // the JavaScript binding (which needs to use this value for security).
     String originalURL() const { return m_originalURL; }
-    const KURL& baseURL() const { return m_parserContext.baseURL; }
+    const KURL& baseURL() const { return m_parserContext.baseURL(); }
 
     unsigned ruleCount() const;
     StyleRuleBase* ruleAt(unsigned index) const;
@@ -139,7 +142,13 @@
     void addedToMemoryCache();
     void removedFromMemoryCache();
 
+    void setHasMediaQueries();
+    bool hasMediaQueries() { return m_hasMediaQueries; }
+
     void shrinkToFit();
+    RuleSet& ruleSet() { ASSERT(m_ruleSet); return *m_ruleSet.get(); }
+    RuleSet& ensureRuleSet(const MediaQueryEvaluator&, AddRuleFlags);
+    void clearRuleSet();
 
 private:
     StyleSheetContents(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext&);
@@ -158,16 +167,18 @@
     PrefixNamespaceURIMap m_namespaces;
 
     bool m_loadCompleted : 1;
-    bool m_isUserStyleSheet : 1;
     bool m_hasSyntacticallyValidCSSHeader : 1;
     bool m_didLoadErrorOccur : 1;
     bool m_usesRemUnits : 1;
     bool m_isMutable : 1;
     bool m_isInMemoryCache : 1;
+    bool m_hasFontFaceRule : 1;
+    bool m_hasMediaQueries : 1;
 
     CSSParserContext m_parserContext;
 
     Vector<CSSStyleSheet*> m_clients;
+    OwnPtr<RuleSet> m_ruleSet;
 };
 
 } // namespace
diff --git a/Source/core/css/StyleSheetList.idl b/Source/core/css/StyleSheetList.idl
index dcf92c2..7341728 100644
--- a/Source/core/css/StyleSheetList.idl
+++ b/Source/core/css/StyleSheetList.idl
@@ -20,7 +20,7 @@
 
 // Introduced in DOM Level 2:
 [
-    GenerateIsReachable=document,
+    GenerateVisitDOMWrapper=document,
 ] interface StyleSheetList {
     readonly attribute unsigned long    length;
     getter StyleSheet         item(unsigned long index);
diff --git a/Source/core/css/TreeBoundaryCrossingRules.cpp b/Source/core/css/TreeBoundaryCrossingRules.cpp
new file mode 100644
index 0000000..30a5604
--- /dev/null
+++ b/Source/core/css/TreeBoundaryCrossingRules.cpp
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
+ * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
+ * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2013 Google 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.
+ */
+
+#include "config.h"
+#include "core/css/TreeBoundaryCrossingRules.h"
+
+#include "core/css/RuleFeature.h"
+#include "core/dom/StyleEngine.h"
+
+namespace WebCore {
+
+void TreeBoundaryCrossingRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
+{
+    if (m_treeBoundaryCrossingRuleSetMap.contains(scopingNode)) {
+        m_treeBoundaryCrossingRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
+    } else {
+        OwnPtr<RuleSet> ruleSetForScope = RuleSet::create();
+        ruleSetForScope->addRule(rule, selectorIndex, addRuleFlags);
+        m_treeBoundaryCrossingRuleSetMap.add(scopingNode, ruleSetForScope.release());
+        m_scopingNodes.add(scopingNode);
+    }
+}
+
+void TreeBoundaryCrossingRules::reset(const ContainerNode* scopingNode)
+{
+    m_treeBoundaryCrossingRuleSetMap.remove(scopingNode);
+    m_scopingNodes.remove(scopingNode);
+}
+
+void TreeBoundaryCrossingRules::collectFeaturesTo(RuleFeatureSet& features)
+{
+    for (TreeBoundaryCrossingRuleSetMap::iterator::Values it = m_treeBoundaryCrossingRuleSetMap.values().begin(); it != m_treeBoundaryCrossingRuleSetMap.values().end(); ++it) {
+        RuleSet* ruleSet = it->get();
+        features.add(ruleSet->features());
+    }
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/DocumentRuleSets.h b/Source/core/css/TreeBoundaryCrossingRules.h
similarity index 65%
rename from Source/core/css/DocumentRuleSets.h
rename to Source/core/css/TreeBoundaryCrossingRules.h
index 3bec3e9..bba30ed 100644
--- a/Source/core/css/DocumentRuleSets.h
+++ b/Source/core/css/TreeBoundaryCrossingRules.h
@@ -20,10 +20,9 @@
  *
  */
 
-#ifndef DocumentRuleSets_h
-#define DocumentRuleSets_h
+#ifndef TreeBoundaryCrossingRules_h
+#define TreeBoundaryCrossingRules_h
 
-#include "core/css/RuleFeature.h"
 #include "core/css/RuleSet.h"
 #include "core/dom/DocumentOrderedList.h"
 
@@ -33,13 +32,8 @@
 
 namespace WebCore {
 
-class CSSStyleRule;
-class CSSStyleSheet;
-class InspectorCSSOMWrappers;
-class MatchRequest;
-class MediaQueryEvaluator;
-class RuleSet;
-class StyleEngine;
+class ContainerNode;
+class RuleFeatureSet;
 
 class TreeBoundaryCrossingRules {
 public:
@@ -59,25 +53,6 @@
     TreeBoundaryCrossingRuleSetMap m_treeBoundaryCrossingRuleSetMap;
 };
 
-class DocumentRuleSets {
-public:
-    DocumentRuleSets();
-    ~DocumentRuleSets();
-    RuleSet* userStyle() const { return m_userStyle.get(); }
-
-    void initUserStyle(StyleEngine*, const Vector<RefPtr<StyleRule> >& watchedSelectors, const MediaQueryEvaluator&, StyleResolver&);
-    void resetAuthorStyle();
-    void collectFeaturesTo(RuleFeatureSet&, bool isViewSource);
-
-    TreeBoundaryCrossingRules& treeBoundaryCrossingRules() { return m_treeBoundaryCrossingRules; }
-
-private:
-    void collectRulesFromUserStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&, RuleSet& userStyle, const MediaQueryEvaluator&, StyleResolver&);
-    void collectRulesFromWatchedSelectors(const Vector<RefPtr<StyleRule> >&, RuleSet& userStyle);
-    OwnPtr<RuleSet> m_userStyle;
-    TreeBoundaryCrossingRules m_treeBoundaryCrossingRules;
-};
-
 } // namespace WebCore
 
-#endif // DocumentRuleSets_h
+#endif // TreeBoundaryCrossingRules_h
diff --git a/Source/core/platform/graphics/chromium/LayerPainterChromium.h b/Source/core/css/ViewportStyle.cpp
similarity index 77%
copy from Source/core/platform/graphics/chromium/LayerPainterChromium.h
copy to Source/core/css/ViewportStyle.cpp
index a526f83..a031542 100644
--- a/Source/core/platform/graphics/chromium/LayerPainterChromium.h
+++ b/Source/core/css/ViewportStyle.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 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
@@ -23,23 +23,14 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-
-#ifndef LayerPainterChromium_h
-#define LayerPainterChromium_h
-
-class SkCanvas;
+#include "config.h"
+#include "ViewportStyle.h"
 
 namespace WebCore {
 
-class FloatRect;
-class IntRect;
-
-class LayerPainterChromium {
-public:
-    virtual ~LayerPainterChromium() { }
-    virtual void paint(SkCanvas*, const IntRect& contentRect, FloatRect& opaque) = 0;
-};
+String ViewportStyle::viewportStyleSheet()
+{
+    return String();
+}
 
 } // namespace WebCore
-
-#endif // LayerPainterChromium_h
diff --git a/Source/core/platform/graphics/chromium/LayerPainterChromium.h b/Source/core/css/ViewportStyle.h
similarity index 78%
rename from Source/core/platform/graphics/chromium/LayerPainterChromium.h
rename to Source/core/css/ViewportStyle.h
index a526f83..903ad0f 100644
--- a/Source/core/platform/graphics/chromium/LayerPainterChromium.h
+++ b/Source/core/css/ViewportStyle.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 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
@@ -23,23 +23,18 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#ifndef ViewportStyle_h
+#define ViewportStyle_h
 
-#ifndef LayerPainterChromium_h
-#define LayerPainterChromium_h
-
-class SkCanvas;
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class FloatRect;
-class IntRect;
-
-class LayerPainterChromium {
+class ViewportStyle {
 public:
-    virtual ~LayerPainterChromium() { }
-    virtual void paint(SkCanvas*, const IntRect& contentRect, FloatRect& opaque) = 0;
+    static String viewportStyleSheet();
 };
 
 } // namespace WebCore
 
-#endif // LayerPainterChromium_h
+#endif // ViewportStyle_h
diff --git a/Source/core/platform/graphics/chromium/LayerPainterChromium.h b/Source/core/css/ViewportStyleAndroid.cpp
similarity index 77%
copy from Source/core/platform/graphics/chromium/LayerPainterChromium.h
copy to Source/core/css/ViewportStyleAndroid.cpp
index a526f83..c5e1932 100644
--- a/Source/core/platform/graphics/chromium/LayerPainterChromium.h
+++ b/Source/core/css/ViewportStyleAndroid.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 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
@@ -23,23 +23,16 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "config.h"
+#include "ViewportStyle.h"
 
-#ifndef LayerPainterChromium_h
-#define LayerPainterChromium_h
-
-class SkCanvas;
+#include "UserAgentStyleSheets.h"
 
 namespace WebCore {
 
-class FloatRect;
-class IntRect;
-
-class LayerPainterChromium {
-public:
-    virtual ~LayerPainterChromium() { }
-    virtual void paint(SkCanvas*, const IntRect& contentRect, FloatRect& opaque) = 0;
-};
+String ViewportStyle::viewportStyleSheet()
+{
+    return String(viewportAndroidUserAgentStyleSheet, sizeof(viewportAndroidUserAgentStyleSheet));
+}
 
 } // namespace WebCore
-
-#endif // LayerPainterChromium_h
diff --git a/Source/core/css/WebKitCSSMatrix.idl b/Source/core/css/WebKitCSSMatrix.idl
index b3232da..0016fcf 100644
--- a/Source/core/css/WebKitCSSMatrix.idl
+++ b/Source/core/css/WebKitCSSMatrix.idl
@@ -27,7 +27,7 @@
 [
     Constructor([Default=NullString] optional DOMString cssValue),
     ImplementedAs=CSSMatrix,
-    ConstructorRaisesException
+    RaisesException=Constructor
 ] interface WebKitCSSMatrix {
 
     // These attributes are simple aliases for certain elements of the 4x4 matrix
diff --git a/Source/core/css/html.css b/Source/core/css/html.css
index 335a57e..bd8fdf3 100644
--- a/Source/core/css/html.css
+++ b/Source/core/css/html.css
@@ -787,7 +787,6 @@
     -webkit-user-modify: read-only !important;
 }
 
-#if defined(ENABLE_CALENDAR_PICKER) && ENABLE_CALENDAR_PICKER
 input::-webkit-calendar-picker-indicator {
     display: inline-block;
     width: 0.66em;
@@ -820,7 +819,6 @@
 input[readonly]::-webkit-calendar-picker-indicator {
     visibility: hidden;
 }
-#endif // ENABLE_CALENDAR_PICKER
 
 select {
     -webkit-appearance: menulist;
@@ -1130,11 +1128,5 @@
     border-width: 0px;
 }
 
-/* viewport */
-
-@viewport {
-    min-width: 980px;
-}
-
 /* noscript is handled internally, as it depends on settings. */
 
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index 8a832a7..af33c08 100644
--- a/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -73,6 +73,18 @@
     return cssPrimitiveValue->convertToLength<AnyConversion>(style, state.rootElementStyle(), style->effectiveZoom());
 }
 
+BorderImageLength animatableValueToBorderImageLength(const AnimatableValue* value, const StyleResolverState& state)
+{
+    const RenderStyle* style = state.style();
+    if (value->isLength())
+        return BorderImageLength(toAnimatableLength(value)->toLength(style, state.rootElementStyle(), style->effectiveZoom(), NonNegativeValues));
+    if (value->isDouble())
+        return BorderImageLength(clampTo<double>(toAnimatableDouble(value)->toDouble(), 0));
+    RefPtr<CSSValue> cssValue = toAnimatableUnknown(value)->toCSSValue();
+    CSSPrimitiveValue* cssPrimitiveValue = toCSSPrimitiveValue(cssValue.get());
+    return BorderImageLength(cssPrimitiveValue->convertToLength<AnyConversion>(style, state.rootElementStyle(), style->effectiveZoom()));
+}
+
 template<typename T> T animatableValueRoundClampTo(const AnimatableValue* value, T min = defaultMinimumForClamp<T>(), T max = defaultMaximumForClamp<T>())
 {
     COMPILE_ASSERT(WTF::IsInteger<T>::value, ShouldUseIntegralTypeTWhenRoundingValues);
@@ -89,6 +101,16 @@
         animatableValueToLength(animatableLengthBox->left(), state, range));
 }
 
+BorderImageLengthBox animatableValueToBorderImageLengthBox(const AnimatableValue* value, const StyleResolverState& state)
+{
+    const AnimatableLengthBox* animatableLengthBox = toAnimatableLengthBox(value);
+    return BorderImageLengthBox(
+        animatableValueToBorderImageLength(animatableLengthBox->top(), state),
+        animatableValueToBorderImageLength(animatableLengthBox->right(), state),
+        animatableValueToBorderImageLength(animatableLengthBox->bottom(), state),
+        animatableValueToBorderImageLength(animatableLengthBox->left(), state));
+}
+
 LengthPoint animatableValueToLengthPoint(const AnimatableValue* value, const StyleResolverState& state, NumberRange range = AllValues)
 {
     const AnimatableLengthPoint* animatableLengthPoint = toAnimatableLengthPoint(value);
@@ -249,7 +271,7 @@
         style->setBorderBottomWidth(animatableValueRoundClampTo<unsigned>(value));
         return;
     case CSSPropertyBorderImageOutset:
-        style->setBorderImageOutset(animatableValueToLengthBox(value, state, NonNegativeValues));
+        style->setBorderImageOutset(animatableValueToBorderImageLengthBox(value, state));
         return;
     case CSSPropertyBorderImageSlice:
         style->setBorderImageSlices(animatableValueToLengthBox(value, state, NonNegativeValues));
@@ -258,7 +280,7 @@
         style->setBorderImageSource(toAnimatableImage(value)->toStyleImage());
         return;
     case CSSPropertyBorderImageWidth:
-        style->setBorderImageWidth(animatableValueToLengthBox(value, state, NonNegativeValues));
+        style->setBorderImageWidth(animatableValueToBorderImageLengthBox(value, state));
         return;
     case CSSPropertyBorderLeftColor:
         style->setBorderLeftColor(toAnimatableColor(value)->color());
@@ -303,7 +325,9 @@
         style->setVisitedLinkColor(toAnimatableColor(value)->visitedLinkColor());
         return;
     case CSSPropertyFillOpacity:
-        style->setFillOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
+        // FIXME: This forces a layer to be created in the presence of an
+        // opacity animation.
+        style->setFillOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 0.999999));
         return;
     case CSSPropertyFill:
         {
@@ -483,7 +507,7 @@
         style->setFilter(toAnimatableFilterOperations(value)->operations());
         return;
     case CSSPropertyWebkitMaskBoxImageOutset:
-        style->setMaskBoxImageOutset(animatableValueToLengthBox(value, state, NonNegativeValues));
+        style->setMaskBoxImageOutset(animatableValueToBorderImageLengthBox(value, state));
         return;
     case CSSPropertyWebkitMaskBoxImageSlice:
         style->setMaskBoxImageSlices(animatableValueToLengthBox(toAnimatableLengthBoxAndBool(value)->box(), state, NonNegativeValues));
@@ -493,7 +517,7 @@
         style->setMaskBoxImageSource(toAnimatableImage(value)->toStyleImage());
         return;
     case CSSPropertyWebkitMaskBoxImageWidth:
-        style->setMaskBoxImageWidth(animatableValueToLengthBox(value, state, NonNegativeValues));
+        style->setMaskBoxImageWidth(animatableValueToBorderImageLengthBox(value, state));
         return;
     case CSSPropertyWebkitMaskImage:
         setOnFillLayers<CSSPropertyWebkitMaskImage>(style->accessMaskLayers(), value, state);
@@ -525,6 +549,9 @@
     case CSSPropertyShapeMargin:
         style->setShapeMargin(animatableValueToLength(value, state, NonNegativeValues));
         return;
+    case CSSPropertyShapeImageThreshold:
+        style->setShapeImageThreshold(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
+        return;
     case CSSPropertyWebkitTextStrokeColor:
         style->setTextStrokeColor(toAnimatableColor(value)->color());
         style->setVisitedLinkTextStrokeColor(toAnimatableColor(value)->visitedLinkColor());
@@ -560,7 +587,7 @@
         style->setZoom(clampTo<float>(toAnimatableDouble(value)->toDouble(), std::numeric_limits<float>::denorm_min()));
         return;
     default:
-        RELEASE_ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Unable to apply AnimatableValue to RenderStyle: %s", getPropertyNameString(property).utf8().data());
+        ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Unable to apply AnimatableValue to RenderStyle: %s", getPropertyNameString(property).utf8().data());
         ASSERT_NOT_REACHED();
     }
 }
diff --git a/Source/core/css/resolver/FilterOperationResolver.cpp b/Source/core/css/resolver/FilterOperationResolver.cpp
index 38d3d10..8079f9c 100644
--- a/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -37,21 +37,22 @@
 #include "core/css/CSSShadowValue.h"
 #include "core/css/resolver/TransformBuilder.h"
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 #include "core/rendering/style/StyleCustomFilterProgram.h"
 #include "core/rendering/style/StyleShader.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
 #include "core/svg/SVGURIReference.h"
 #include "platform/graphics/filters/custom/CustomFilterArrayParameter.h"
 #include "platform/graphics/filters/custom/CustomFilterConstants.h"
 #include "platform/graphics/filters/custom/CustomFilterNumberParameter.h"
 #include "platform/graphics/filters/custom/CustomFilterParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
+#include "platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 
 namespace WebCore {
 
 static Length convertToFloatLength(CSSPrimitiveValue* primitiveValue, const RenderStyle* style, const RenderStyle* rootStyle, double multiplier)
 {
-    return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion>(style, rootStyle, multiplier) : Length(Undefined);
+    return primitiveValue ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(style, rootStyle, multiplier) : Length(Undefined);
 }
 
 static FilterOperation::OperationType filterOperationForType(CSSFilterValue::FilterOperationType type)
@@ -401,12 +402,12 @@
             CSSSVGDocumentValue* svgDocumentValue = toCSSSVGDocumentValue(argument);
             KURL url = state.document().completeURL(svgDocumentValue->url());
 
-            RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier(), operationType);
+            RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier());
             if (SVGURIReference::isExternalURIReference(svgDocumentValue->url(), state.document())) {
                 if (!svgDocumentValue->loadRequested())
                     state.elementStyleResources().addPendingSVGDocument(operation.get(), svgDocumentValue);
                 else if (svgDocumentValue->cachedSVGDocument())
-                    operation->setDocumentResourceReference(adoptPtr(new DocumentResourceReference(svgDocumentValue->cachedSVGDocument())));
+                    ReferenceFilterBuilder::setDocumentResourceReference(operation.get(), adoptPtr(new DocumentResourceReference(svgDocumentValue->cachedSVGDocument())));
             }
             operations.operations().append(operation);
             continue;
@@ -470,7 +471,7 @@
             if (stdDeviation.isUndefined())
                 return false;
 
-            operations.operations().append(BlurFilterOperation::create(stdDeviation, operationType));
+            operations.operations().append(BlurFilterOperation::create(stdDeviation));
             break;
         }
         case CSSFilterValue::DropShadowFilterOperation: {
@@ -488,7 +489,7 @@
             if (item->color)
                 shadowColor = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->visitedDependentColor(CSSPropertyColor));
 
-            operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor.isValid() ? shadowColor : Color::transparent, operationType));
+            operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor.isValid() ? shadowColor : Color::transparent));
             break;
         }
         case CSSFilterValue::UnknownFilterOperation:
diff --git a/Source/core/css/resolver/MatchRequest.h b/Source/core/css/resolver/MatchRequest.h
index 8b120d4..df0207f 100644
--- a/Source/core/css/resolver/MatchRequest.h
+++ b/Source/core/css/resolver/MatchRequest.h
@@ -31,11 +31,12 @@
 
 class MatchRequest {
 public:
-    MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true)
+    MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true, unsigned styleSheetIndex = 0)
         : ruleSet(ruleSet)
         , includeEmptyRules(includeEmptyRules)
         , scope(scope)
         , elementApplyAuthorStyles(elementApplyAuthorStyles)
+        , styleSheetIndex(styleSheetIndex)
     {
         // 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.
@@ -46,6 +47,7 @@
     const bool includeEmptyRules;
     const ContainerNode* scope;
     const bool elementApplyAuthorStyles;
+    const unsigned styleSheetIndex;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/MatchedPropertiesCache.cpp b/Source/core/css/resolver/MatchedPropertiesCache.cpp
index 86c4c73..d3c222a 100644
--- a/Source/core/css/resolver/MatchedPropertiesCache.cpp
+++ b/Source/core/css/resolver/MatchedPropertiesCache.cpp
@@ -154,12 +154,6 @@
     // The cache assumes static knowledge about which properties are inherited.
     if (parentStyle->hasExplicitlyInheritedProperties())
         return false;
-    if (RuntimeEnabledFeatures::webAnimationsEnabled()) {
-        if (style->transitions() && !style->transitions()->isEmpty())
-            return false;
-        if (style->animations() && !style->animations()->isEmpty())
-            return false;
-    }
     return true;
 }
 
diff --git a/Source/core/css/resolver/MediaQueryResult.h b/Source/core/css/resolver/MediaQueryResult.h
index e18cbcf..1dc00f4 100644
--- a/Source/core/css/resolver/MediaQueryResult.h
+++ b/Source/core/css/resolver/MediaQueryResult.h
@@ -25,10 +25,11 @@
 
 #include "core/css/MediaQueryExp.h"
 #include "wtf/Noncopyable.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-class MediaQueryResult {
+class MediaQueryResult : public RefCounted<MediaQueryResult> {
     WTF_MAKE_NONCOPYABLE(MediaQueryResult); WTF_MAKE_FAST_ALLOCATED;
 public:
     MediaQueryResult(const MediaQueryExp& expr, bool result)
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index 0f06542..e26bc5f 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -33,6 +33,7 @@
 #include "core/css/RuleFeature.h"
 #include "core/css/RuleSet.h"
 #include "core/css/StyleRule.h"
+#include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h" // For MatchRequest.
 #include "core/css/resolver/ViewportStyleResolver.h"
 #include "core/dom/Document.h"
@@ -42,202 +43,23 @@
 
 namespace WebCore {
 
-ScopedStyleResolver* ScopedStyleTree::ensureScopedStyleResolver(const ContainerNode& scopingNode)
-{
-    bool isNewEntry;
-    ScopedStyleResolver* scopedStyleResolver = addScopedStyleResolver(scopingNode, isNewEntry);
-    if (isNewEntry)
-        setupScopedStylesTree(scopedStyleResolver);
-    return scopedStyleResolver;
-}
-
-ScopedStyleResolver* ScopedStyleTree::scopedStyleResolverFor(const ContainerNode& scopingNode)
-{
-    if (!scopingNode.hasScopedHTMLStyleChild()
-        && !isShadowHost(&scopingNode)
-        && !scopingNode.isDocumentNode()
-        && !scopingNode.isShadowRoot())
-        return 0;
-    return lookupScopedStyleResolverFor(&scopingNode);
-}
-
-ScopedStyleResolver* ScopedStyleTree::addScopedStyleResolver(const ContainerNode& scopingNode, bool& isNewEntry)
-{
-    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::AddResult addResult = m_authorStyles.add(&scopingNode, nullptr);
-
-    if (addResult.isNewEntry) {
-        addResult.iterator->value = ScopedStyleResolver::create(scopingNode);
-        if (scopingNode.isDocumentNode())
-            m_scopedResolverForDocument = addResult.iterator->value.get();
-    }
-    isNewEntry = addResult.isNewEntry;
-    return addResult.iterator->value.get();
-}
-
-void ScopedStyleTree::setupScopedStylesTree(ScopedStyleResolver* target)
-{
-    ASSERT(target);
-
-    const ContainerNode& scopingNode = target->scopingNode();
-
-    // Since StyleResolver creates RuleSets according to styles' document
-    // order, a parent of the given ScopedRuleData has been already
-    // prepared.
-    for (const ContainerNode* node = scopingNode.parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
-        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(*node)) {
-            target->setParent(scopedResolver);
-            break;
-        }
-        if (node->isDocumentNode()) {
-            bool dummy;
-            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(*node, dummy);
-            target->setParent(scopedResolver);
-            setupScopedStylesTree(scopedResolver);
-            break;
-        }
-    }
-
-    if (m_buildInDocumentOrder)
-        return;
-
-    // Reparent all nodes whose scoping node is contained by target's one.
-    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
-        if (it->value == target)
-            continue;
-        ASSERT(it->key->inDocument());
-        if (it->value->parent() == target->parent() && scopingNode.containsIncludingShadowDOM(it->key))
-            it->value->setParent(target);
-    }
-}
-
-void ScopedStyleTree::clear()
-{
-    m_authorStyles.clear();
-    m_scopedResolverForDocument = 0;
-    m_cache.clear();
-}
-
-void ScopedStyleTree::resolveScopedStyles(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
-{
-    for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent())
-        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();
-    TreeScope& treeScope = element->treeScope();
-    bool applyAuthorStyles = treeScope.applyAuthorStyles();
-
-    for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent()) {
-        if (scopedResolver->treeScope() == treeScope || (applyAuthorStyles && scopedResolver->treeScope() == document))
-            resolvers.append(scopedResolver);
-    }
-}
-
-inline ScopedStyleResolver* ScopedStyleTree::enclosingScopedStyleResolverFor(const ContainerNode* scopingNode)
-{
-    for (; scopingNode; scopingNode = scopingNode->parentOrShadowHostNode()) {
-        if (ScopedStyleResolver* scopedStyleResolver = scopedStyleResolverFor(*scopingNode))
-            return scopedStyleResolver;
-    }
-    return 0;
-}
-
-void ScopedStyleTree::resolveStyleCache(const ContainerNode* scopingNode)
-{
-    m_cache.scopedResolver = enclosingScopedStyleResolverFor(scopingNode);
-    m_cache.nodeForScopedStyles = scopingNode;
-}
-
-void ScopedStyleTree::pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent)
-{
-    if (m_authorStyles.isEmpty())
-        return;
-
-    if (!cacheIsValid(parent)) {
-        resolveStyleCache(&scopingNode);
-        return;
-    }
-
-    ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(scopingNode);
-    if (scopedResolver)
-        m_cache.scopedResolver = scopedResolver;
-    m_cache.nodeForScopedStyles = &scopingNode;
-}
-
-void ScopedStyleTree::popStyleCache(const ContainerNode& scopingNode)
-{
-    if (!cacheIsValid(&scopingNode))
-        return;
-
-    if (m_cache.scopedResolver && m_cache.scopedResolver->scopingNode() == scopingNode)
-        m_cache.scopedResolver = m_cache.scopedResolver->parent();
-    m_cache.nodeForScopedStyles = scopingNode.parentOrShadowHostNode();
-}
-
-void ScopedStyleTree::collectFeaturesTo(RuleFeatureSet& features)
-{
-    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it)
-        it->value->collectFeaturesTo(features);
-}
-
-inline void ScopedStyleTree::reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent)
-{
-    // FIXME: this takes O(N) (N = number of all scoping nodes).
-    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
-        if (it->value->parent() == oldParent)
-            it->value->setParent(newParent);
-    }
-}
-
-void ScopedStyleTree::remove(const ContainerNode* scopingNode)
-{
-    if (!scopingNode || scopingNode->isDocumentNode())
-        return;
-
-    ScopedStyleResolver* resolverRemoved = lookupScopedStyleResolverFor(scopingNode);
-    if (!resolverRemoved)
-        return;
-
-    reparentNodes(resolverRemoved, resolverRemoved->parent());
-    if (m_cache.scopedResolver == resolverRemoved)
-        m_cache.clear();
-
-    m_authorStyles.remove(scopingNode);
-}
-
-const ContainerNode* ScopedStyleResolver::scopingNodeFor(const CSSStyleSheet* sheet)
+ContainerNode* ScopedStyleResolver::scopingNodeFor(Document& document, const CSSStyleSheet* sheet)
 {
     ASSERT(sheet);
 
-    Document* document = sheet->ownerDocument();
-    if (!document)
+    Document* sheetDocument = sheet->ownerDocument();
+    if (!sheetDocument)
         return 0;
     Node* ownerNode = sheet->ownerNode();
-    if (!ownerNode || !ownerNode->hasTagName(HTMLNames::styleTag))
-        return 0;
+    if (!ownerNode || !isHTMLStyleElement(ownerNode))
+        return &document;
 
     HTMLStyleElement* styleElement = toHTMLStyleElement(ownerNode);
-    if (!styleElement->scoped())
-        return styleElement->isInShadowTree() ? styleElement->containingShadowRoot() : 0;
+    if (!styleElement->scoped()) {
+        if (styleElement->isInShadowTree())
+            return styleElement->containingShadowRoot();
+        return &document;
+    }
 
     ContainerNode* parent = styleElement->parentNode();
     if (!parent)
@@ -248,72 +70,35 @@
 
 void ScopedStyleResolver::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* resolver)
 {
-    if (!m_authorStyle)
-        m_authorStyle = RuleSet::create();
-    m_authorStyle->addRulesFromSheet(sheet, medium, resolver, &m_scopingNode);
-}
+    m_authorStyleSheets.append(sheet);
 
-inline RuleSet* ScopedStyleResolver::ensureAtHostRuleSetFor(const ShadowRoot* shadowRoot)
-{
-    HashMap<const ShadowRoot*, OwnPtr<RuleSet> >::AddResult addResult = m_atHostRules.add(shadowRoot, nullptr);
-    if (addResult.isNewEntry)
-        addResult.iterator->value = RuleSet::create();
-    return addResult.iterator->value.get();
-}
-
-void ScopedStyleResolver::addHostRule(StyleRuleHost* hostRule, bool hasDocumentSecurityOrigin, const ContainerNode* scopingNode)
-{
-    if (!scopingNode)
-        return;
-
-    ShadowRoot* shadowRoot = scopingNode->containingShadowRoot();
-    if (!shadowRoot || !shadowRoot->host())
-        return;
-
-    RuleSet* rule = ensureAtHostRuleSetFor(shadowRoot);
-
-    const Vector<RefPtr<StyleRuleBase> >& childRules = hostRule->childRules();
-    AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>(hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState);
-    for (unsigned i = 0; i < childRules.size(); ++i) {
-        StyleRuleBase* hostStylingRule = childRules[i].get();
-        if (hostStylingRule->isStyleRule())
-            rule->addStyleRule(static_cast<StyleRule*>(hostStylingRule), addRuleFlags);
-    }
+    AddRuleFlags addRuleFlags = resolver->document().securityOrigin()->canRequest(sheet->baseURL()) ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
+    const RuleSet& ruleSet = sheet->ensureRuleSet(medium, addRuleFlags);
+    resolver->addMediaQueryResults(ruleSet.viewportDependentMediaQueryResults());
+    resolver->processScopedRules(ruleSet, sheet->baseURL(), &m_scopingNode);
 }
 
 void ScopedStyleResolver::collectFeaturesTo(RuleFeatureSet& features)
 {
-    if (m_authorStyle)
-        features.add(m_authorStyle->features());
-
-    if (m_atHostRules.isEmpty())
-        return;
-
-    for (HashMap<const ShadowRoot*, OwnPtr<RuleSet> >::iterator it = m_atHostRules.begin(); it != m_atHostRules.end(); ++it)
-        features.add(it->value->features());
+    for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
+        features.add(m_authorStyleSheets[i]->ruleSet().features());
 }
 
 void ScopedStyleResolver::resetAuthorStyle()
 {
-    m_authorStyle = RuleSet::create();
+    m_authorStyleSheets.clear();
     m_keyframesRuleMap.clear();
 }
 
-void ScopedStyleResolver::resetAtHostRules(const ShadowRoot* shadowRoot)
-{
-    m_atHostRules.remove(shadowRoot);
-}
-
 bool ScopedStyleResolver::checkRegionStyle(Element* regionElement)
 {
-    if (!m_authorStyle)
-        return false;
-
-    unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
-    for (unsigned i = 0; i < rulesSize; ++i) {
-        ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
-        if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
-            return true;
+    for (size_t i = 0; i < m_authorStyleSheets.size(); ++i) {
+        const RuleSet& ruleSet = m_authorStyleSheets[i]->ruleSet();
+        for (unsigned i = 0; i < ruleSet.m_regionSelectorsAndRuleSets.size(); ++i) {
+            ASSERT(ruleSet.m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
+            if (checkRegionSelector(ruleSet.m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
+                return true;
+        }
     }
     return false;
 }
@@ -344,62 +129,8 @@
     }
 }
 
-inline RuleSet* ScopedStyleResolver::atHostRuleSetFor(const ShadowRoot* shadowRoot) const
-{
-    HashMap<const ShadowRoot*, OwnPtr<RuleSet> >::const_iterator it = m_atHostRules.find(shadowRoot);
-    return it != m_atHostRules.end() ? it->value.get() : 0;
-}
-
-void ScopedStyleResolver::matchHostRules(ElementRuleCollector& collector, bool includeEmptyRules)
-{
-    // FIXME: Determine tree position.
-    CascadeScope cascadeScope = ignoreCascadeScope;
-
-    if (m_atHostRules.isEmpty() || !m_scopingNode.isElementNode())
-        return;
-
-    ElementShadow* shadow = toElement(m_scopingNode).shadow();
-    if (!shadow)
-        return;
-
-    collector.clearMatchedRules();
-    collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
-
-    // FIXME(99827): https://bugs.webkit.org/show_bug.cgi?id=99827
-    // add a new flag to ElementShadow and cache whether any @host @-rules are
-    // applied to the element or not. So we can quickly exit this method
-    // by using the flag.
-    ShadowRoot* shadowRoot = shadow->youngestShadowRoot();
-    for (; shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
-        if (!shadowRoot->containsShadowElements())
-            break;
-    // All shadow roots have <shadow>.
-    if (!shadowRoot)
-        shadowRoot = shadow->oldestShadowRoot();
-
-    RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
-    SelectorChecker::BehaviorAtBoundary boundary = 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, boundary, cascadeScope);
-    }
-
-    collector.sortAndTransferMatchedRules();
-}
-
-void ScopedStyleResolver::matchAuthorRules(ElementRuleCollector& collector, bool includeEmptyRules, bool applyAuthorStyles)
-{
-    collector.clearMatchedRules();
-    collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
-    collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, ignoreCascadeScope);
-    collector.sortAndTransferMatchedRules();
-}
-
 void ScopedStyleResolver::collectMatchingAuthorRules(ElementRuleCollector& collector, bool includeEmptyRules, bool applyAuthorStyles, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
 {
-    if (!m_authorStyle)
-        return;
-
     const ContainerNode* scopingNode = &m_scopingNode;
     unsigned behaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary;
 
@@ -411,25 +142,28 @@
         behaviorAtBoundary |= SelectorChecker::ScopeIsShadowHost;
     }
 
-    MatchRequest matchRequest(m_authorStyle.get(), includeEmptyRules, scopingNode, applyAuthorStyles);
     RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
-    collector.collectMatchingRules(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
-    collector.collectMatchingRulesForRegion(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
+    for (size_t i = 0; i < m_authorStyleSheets.size(); ++i) {
+        MatchRequest matchRequest(&m_authorStyleSheets[i]->ruleSet(), includeEmptyRules, scopingNode, applyAuthorStyles, i);
+        collector.collectMatchingRules(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
+        collector.collectMatchingRulesForRegion(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
+    }
 }
 
 void ScopedStyleResolver::matchPageRules(PageRuleCollector& collector)
 {
     // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
     ASSERT(m_scopingNode.isDocumentNode());
-    collector.matchPageRules(m_authorStyle.get());
+    for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
+        collector.matchPageRules(&m_authorStyleSheets[i]->ruleSet());
 }
 
 void ScopedStyleResolver::collectViewportRulesTo(StyleResolver* resolver) const
 {
-    // Only consider the global author RuleSet for @viewport rules.
-    ASSERT(m_scopingNode.isDocumentNode());
-    if (m_authorStyle)
-        resolver->viewportStyleResolver()->collectViewportRules(m_authorStyle.get(), ViewportStyleResolver::AuthorOrigin);
+    if (!m_scopingNode.isDocumentNode())
+        return;
+    for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
+        resolver->viewportStyleResolver()->collectViewportRules(&m_authorStyleSheets[i]->ruleSet(), ViewportStyleResolver::AuthorOrigin);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ScopedStyleResolver.h b/Source/core/css/resolver/ScopedStyleResolver.h
index fee466f..7aa1a1a 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/Source/core/css/resolver/ScopedStyleResolver.h
@@ -27,20 +27,15 @@
 #ifndef ScopedStyleResolver_h
 #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"
-#include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class ElementRuleCollector;
 class MediaQueryEvaluator;
 class PageRuleCollector;
 class ShadowRoot;
@@ -50,119 +45,41 @@
 class ScopedStyleResolver {
     WTF_MAKE_NONCOPYABLE(ScopedStyleResolver); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<ScopedStyleResolver> create(const ContainerNode& scopingNode) { return adoptPtr(new ScopedStyleResolver(scopingNode)); }
+    static PassOwnPtr<ScopedStyleResolver> create(ContainerNode& scopingNode) { return adoptPtr(new ScopedStyleResolver(scopingNode)); }
 
-    static const ContainerNode* scopingNodeFor(const CSSStyleSheet*);
+    static ContainerNode* scopingNodeFor(Document&, const CSSStyleSheet*);
 
     const ContainerNode& scopingNode() const { return m_scopingNode; }
     const TreeScope& treeScope() const { return m_scopingNode.treeScope(); }
-    void prepareEmptyRuleSet() { m_authorStyle = RuleSet::create(); }
     void setParent(ScopedStyleResolver* newParent) { m_parent = newParent; }
     ScopedStyleResolver* parent() { return m_parent; }
 
-    bool hasOnlyEmptyRuleSets() const { return (!m_authorStyle || !m_authorStyle->ruleCount()) && m_atHostRules.isEmpty(); }
-
 public:
     bool checkRegionStyle(Element*);
     const StyleRuleKeyframes* keyframeStylesForAnimation(const StringImpl* animationName);
     void addKeyframeStyle(PassRefPtr<StyleRuleKeyframes>);
 
-    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);
     void collectFeaturesTo(RuleFeatureSet&);
     void resetAuthorStyle();
-    void resetAtHostRules(const ShadowRoot*);
     void collectViewportRulesTo(StyleResolver*) const;
 
 private:
-    explicit ScopedStyleResolver(const ContainerNode& scopingNode) : m_scopingNode(scopingNode), m_parent(0) { }
+    explicit ScopedStyleResolver(ContainerNode& scopingNode) : m_scopingNode(scopingNode), m_parent(0) { }
 
-    RuleSet* ensureAtHostRuleSetFor(const ShadowRoot*);
-    RuleSet* atHostRuleSetFor(const ShadowRoot*) const;
+    RuleSet* ensureAuthorStyle();
 
-    const ContainerNode& m_scopingNode;
+    ContainerNode& m_scopingNode;
     ScopedStyleResolver* m_parent;
 
-    OwnPtr<RuleSet> m_authorStyle;
-    HashMap<const ShadowRoot*, OwnPtr<RuleSet> > m_atHostRules;
+    Vector<StyleSheetContents*> m_authorStyleSheets;
 
     typedef HashMap<const StringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
     KeyframesRuleMap m_keyframesRuleMap;
 };
 
-class ScopedStyleTree {
-    WTF_MAKE_NONCOPYABLE(ScopedStyleTree); WTF_MAKE_FAST_ALLOCATED;
-public:
-    ScopedStyleTree() : m_scopedResolverForDocument(0), m_buildInDocumentOrder(true) { }
-
-    ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode& scopingNode);
-    ScopedStyleResolver* lookupScopedStyleResolverFor(const ContainerNode* scopingNode)
-    {
-        HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.find(scopingNode);
-        return it != m_authorStyles.end() ? it->value.get() : 0;
-    }
-
-    ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode& scopingNode);
-    ScopedStyleResolver* addScopedStyleResolver(const ContainerNode& scopingNode, bool& isNewEntry);
-    void clear();
-
-    // for fast-path.
-    bool hasOnlyScopedResolverForDocument() const { return m_scopedResolverForDocument && m_authorStyles.size() == 1; }
-    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*);
-
-    void remove(const ContainerNode* scopingNode);
-
-    void pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent);
-    void popStyleCache(const ContainerNode& scopingNode);
-
-    void collectFeaturesTo(RuleFeatureSet& features);
-    void setBuildInDocumentOrder(bool enabled) { m_buildInDocumentOrder = enabled; }
-    bool buildInDocumentOrder() const { return m_buildInDocumentOrder; }
-
-private:
-    void setupScopedStylesTree(ScopedStyleResolver* target);
-
-    bool cacheIsValid(const ContainerNode* parent) const { return parent && parent == m_cache.nodeForScopedStyles; }
-    void resolveStyleCache(const ContainerNode* scopingNode);
-    ScopedStyleResolver* enclosingScopedStyleResolverFor(const ContainerNode* scopingNode);
-
-    void reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent);
-
-private:
-    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> > m_authorStyles;
-    ScopedStyleResolver* m_scopedResolverForDocument;
-    bool m_buildInDocumentOrder;
-
-    struct ScopedStyleCache {
-        ScopedStyleResolver* scopedResolver;
-        const ContainerNode* nodeForScopedStyles;
-
-        void clear()
-        {
-            scopedResolver = 0;
-            nodeForScopedStyles = 0;
-        }
-    };
-    ScopedStyleCache m_cache;
-};
-
-inline ScopedStyleResolver* ScopedStyleTree::scopedResolverFor(const Element* element)
-{
-    if (!cacheIsValid(element))
-        resolveStyleCache(element);
-
-    return m_cache.scopedResolver;
-}
-
 } // namespace WebCore
 
 #endif // ScopedStyleResolver_h
diff --git a/Source/core/css/resolver/ScopedStyleTree.cpp b/Source/core/css/resolver/ScopedStyleTree.cpp
new file mode 100644
index 0000000..f1f1906
--- /dev/null
+++ b/Source/core/css/resolver/ScopedStyleTree.cpp
@@ -0,0 +1,220 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * 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 INC. 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 INC. 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/css/resolver/ScopedStyleTree.h"
+
+#include "core/css/RuleFeature.h"
+#include "core/css/resolver/ScopedStyleResolver.h"
+#include "core/dom/Document.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
+
+namespace WebCore {
+
+ScopedStyleResolver* ScopedStyleTree::ensureScopedStyleResolver(ContainerNode& scopingNode)
+{
+    bool isNewEntry;
+    ScopedStyleResolver* scopedStyleResolver = addScopedStyleResolver(scopingNode, isNewEntry);
+    if (isNewEntry)
+        setupScopedStylesTree(scopedStyleResolver);
+    return scopedStyleResolver;
+}
+
+ScopedStyleResolver* ScopedStyleTree::scopedStyleResolverFor(const ContainerNode& scopingNode)
+{
+    if (!scopingNode.hasScopedHTMLStyleChild()
+        && !isShadowHost(&scopingNode)
+        && !scopingNode.isDocumentNode()
+        && !scopingNode.isShadowRoot())
+        return 0;
+    return lookupScopedStyleResolverFor(&scopingNode);
+}
+
+ScopedStyleResolver* ScopedStyleTree::addScopedStyleResolver(ContainerNode& scopingNode, bool& isNewEntry)
+{
+    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::AddResult addResult = m_authorStyles.add(&scopingNode, nullptr);
+
+    if (addResult.isNewEntry) {
+        addResult.iterator->value = ScopedStyleResolver::create(scopingNode);
+        if (scopingNode.isDocumentNode())
+            m_scopedResolverForDocument = addResult.iterator->value.get();
+    }
+    isNewEntry = addResult.isNewEntry;
+    return addResult.iterator->value.get();
+}
+
+void ScopedStyleTree::setupScopedStylesTree(ScopedStyleResolver* target)
+{
+    ASSERT(target);
+
+    const ContainerNode& scopingNode = target->scopingNode();
+
+    // Since StyleResolver creates RuleSets according to styles' document
+    // order, a parent of the given ScopedRuleData has been already
+    // prepared.
+    for (ContainerNode* node = scopingNode.parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
+        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(*node)) {
+            target->setParent(scopedResolver);
+            break;
+        }
+        if (node->isDocumentNode()) {
+            bool dummy;
+            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(*node, dummy);
+            target->setParent(scopedResolver);
+            setupScopedStylesTree(scopedResolver);
+            break;
+        }
+    }
+
+    if (m_buildInDocumentOrder)
+        return;
+
+    // Reparent all nodes whose scoping node is contained by target's one.
+    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+        if (it->value == target)
+            continue;
+        ASSERT(it->key->inDocument());
+        if (it->value->parent() == target->parent() && scopingNode.containsIncludingShadowDOM(it->key))
+            it->value->setParent(target);
+    }
+}
+
+void ScopedStyleTree::clear()
+{
+    m_authorStyles.clear();
+    m_scopedResolverForDocument = 0;
+    m_cache.clear();
+}
+
+void ScopedStyleTree::resolveScopedStyles(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
+{
+    for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent())
+        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();
+    TreeScope& treeScope = element->treeScope();
+    bool applyAuthorStyles = treeScope.applyAuthorStyles();
+
+    for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent()) {
+        if (scopedResolver->treeScope() == treeScope || (applyAuthorStyles && scopedResolver->treeScope() == document))
+            resolvers.append(scopedResolver);
+    }
+}
+
+inline ScopedStyleResolver* ScopedStyleTree::enclosingScopedStyleResolverFor(const ContainerNode* scopingNode)
+{
+    for (; scopingNode; scopingNode = scopingNode->parentOrShadowHostNode()) {
+        if (ScopedStyleResolver* scopedStyleResolver = scopedStyleResolverFor(*scopingNode))
+            return scopedStyleResolver;
+    }
+    return 0;
+}
+
+void ScopedStyleTree::resolveStyleCache(const ContainerNode* scopingNode)
+{
+    m_cache.scopedResolver = enclosingScopedStyleResolverFor(scopingNode);
+    m_cache.nodeForScopedStyles = scopingNode;
+}
+
+void ScopedStyleTree::pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent)
+{
+    if (m_authorStyles.isEmpty())
+        return;
+
+    if (!cacheIsValid(parent)) {
+        resolveStyleCache(&scopingNode);
+        return;
+    }
+
+    ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(scopingNode);
+    if (scopedResolver)
+        m_cache.scopedResolver = scopedResolver;
+    m_cache.nodeForScopedStyles = &scopingNode;
+}
+
+void ScopedStyleTree::popStyleCache(const ContainerNode& scopingNode)
+{
+    if (!cacheIsValid(&scopingNode))
+        return;
+
+    if (m_cache.scopedResolver && m_cache.scopedResolver->scopingNode() == scopingNode)
+        m_cache.scopedResolver = m_cache.scopedResolver->parent();
+    m_cache.nodeForScopedStyles = scopingNode.parentOrShadowHostNode();
+}
+
+void ScopedStyleTree::collectFeaturesTo(RuleFeatureSet& features)
+{
+    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it)
+        it->value->collectFeaturesTo(features);
+}
+
+inline void ScopedStyleTree::reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent)
+{
+    // FIXME: this takes O(N) (N = number of all scoping nodes).
+    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+        if (it->value->parent() == oldParent)
+            it->value->setParent(newParent);
+    }
+}
+
+void ScopedStyleTree::remove(const ContainerNode* scopingNode)
+{
+    if (!scopingNode || scopingNode->isDocumentNode())
+        return;
+
+    ScopedStyleResolver* resolverRemoved = lookupScopedStyleResolverFor(scopingNode);
+    if (!resolverRemoved)
+        return;
+
+    reparentNodes(resolverRemoved, resolverRemoved->parent());
+    if (m_cache.scopedResolver == resolverRemoved)
+        m_cache.clear();
+
+    m_authorStyles.remove(scopingNode);
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/resolver/ScopedStyleTree.h b/Source/core/css/resolver/ScopedStyleTree.h
new file mode 100644
index 0000000..51f68fe
--- /dev/null
+++ b/Source/core/css/resolver/ScopedStyleTree.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * 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 INC. 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 INC. 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.
+ */
+
+#ifndef ScopedStyleTree_h
+#define ScopedStyleTree_h
+
+#include "core/css/resolver/ScopedStyleResolver.h"
+#include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class ScopedStyleTree {
+    WTF_MAKE_NONCOPYABLE(ScopedStyleTree); WTF_MAKE_FAST_ALLOCATED;
+public:
+    ScopedStyleTree() : m_scopedResolverForDocument(0), m_buildInDocumentOrder(true) { }
+
+    ScopedStyleResolver* ensureScopedStyleResolver(ContainerNode& scopingNode);
+    ScopedStyleResolver* lookupScopedStyleResolverFor(const ContainerNode* scopingNode)
+    {
+        HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.find(scopingNode);
+        return it != m_authorStyles.end() ? it->value.get() : 0;
+    }
+
+    ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode& scopingNode);
+    ScopedStyleResolver* addScopedStyleResolver(ContainerNode& scopingNode, bool& isNewEntry);
+    void clear();
+
+    // for fast-path.
+    bool hasOnlyScopedResolverForDocument() const { return m_scopedResolverForDocument && m_authorStyles.size() == 1; }
+    ScopedStyleResolver* scopedStyleResolverForDocument() const { 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*);
+
+    void remove(const ContainerNode* scopingNode);
+
+    void pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent);
+    void popStyleCache(const ContainerNode& scopingNode);
+
+    void collectFeaturesTo(RuleFeatureSet& features);
+    void setBuildInDocumentOrder(bool enabled) { m_buildInDocumentOrder = enabled; }
+    bool buildInDocumentOrder() const { return m_buildInDocumentOrder; }
+
+private:
+    void setupScopedStylesTree(ScopedStyleResolver* target);
+
+    bool cacheIsValid(const ContainerNode* parent) const { return parent && parent == m_cache.nodeForScopedStyles; }
+    void resolveStyleCache(const ContainerNode* scopingNode);
+    ScopedStyleResolver* enclosingScopedStyleResolverFor(const ContainerNode* scopingNode);
+
+    void reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent);
+
+private:
+    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> > m_authorStyles;
+    ScopedStyleResolver* m_scopedResolverForDocument;
+    bool m_buildInDocumentOrder;
+
+    struct ScopedStyleCache {
+        ScopedStyleResolver* scopedResolver;
+        const ContainerNode* nodeForScopedStyles;
+
+        void clear()
+        {
+            scopedResolver = 0;
+            nodeForScopedStyles = 0;
+        }
+    };
+    ScopedStyleCache m_cache;
+};
+
+inline ScopedStyleResolver* ScopedStyleTree::scopedResolverFor(const Element* element)
+{
+    if (!cacheIsValid(element))
+        resolveStyleCache(element);
+
+    return m_cache.scopedResolver;
+}
+
+} // namespace WebCore
+
+#endif // ScopedStyleTree_h
diff --git a/Source/core/css/resolver/SharedStyleFinder.cpp b/Source/core/css/resolver/SharedStyleFinder.cpp
index cfff3f7..1b214a1 100644
--- a/Source/core/css/resolver/SharedStyleFinder.cpp
+++ b/Source/core/css/resolver/SharedStyleFinder.cpp
@@ -32,6 +32,7 @@
 #include "HTMLNames.h"
 #include "XMLNames.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverStats.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
@@ -239,8 +240,8 @@
 
 bool SharedStyleFinder::documentContainsValidCandidate() const
 {
-    for (Element* element = document().documentElement(); element; element = ElementTraversal::next(element)) {
-        if (canShareStyleWithElement(*element))
+    for (Element* element = document().documentElement(); element; element = ElementTraversal::next(*element)) {
+        if (element->supportsStyleSharing() && canShareStyleWithElement(*element))
             return true;
     }
     return false;
@@ -250,17 +251,17 @@
 {
     StyleSharingList& styleSharingList = m_styleResolver.styleSharingList();
     for (StyleSharingList::iterator it = styleSharingList.begin(); it != styleSharingList.end(); ++it) {
-        if (!canShareStyleWithElement(**it))
+        Element& candidate = **it;
+        if (!canShareStyleWithElement(candidate))
             continue;
-        Element* element = it->get();
         if (it != styleSharingList.begin()) {
             // Move the element to the front of the LRU
             styleSharingList.remove(it);
-            styleSharingList.prepend(element);
+            styleSharingList.prepend(&candidate);
         }
-        return element;
+        return &candidate;
     }
-    m_styleResolver.addToStyleSharingList(&element());
+    m_styleResolver.addToStyleSharingList(element());
     return 0;
 }
 
@@ -274,38 +275,40 @@
 
 RenderStyle* SharedStyleFinder::findSharedStyle()
 {
-    STYLE_STATS_ADD_SEARCH();
+    INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleLookups);
 
     if (!element().supportsStyleSharing())
         return 0;
 
-    STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING();
-
     // Cache whether context.element() is affected by any known class selectors.
     m_elementAffectedByClassRules = element().hasClass() && classNamesAffectedByRules(element().classNames());
 
     Element* shareElement = findElementForStyleSharing();
 
-#ifdef STYLE_STATS
-    // FIXME: these stats don't to into account whether or not sibling/attribute
-    // rules prevent these nodes from actually sharing
-    if (shareElement)
-        STYLE_STATS_ADD_SEARCH_FOUND_SIBLING_FOR_SHARING();
-    else if (documentContainsValidCandidate())
-        STYLE_STATS_ADD_SEARCH_MISSED_SHARING();
-#endif
-
-    // If we have exhausted all our budget or our cousins.
-    if (!shareElement)
+    if (!shareElement) {
+        if (m_styleResolver.stats() && m_styleResolver.stats()->printMissedCandidateCount && documentContainsValidCandidate())
+            INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleMissed);
         return 0;
+    }
 
-    // Can't share if sibling or attribute rules apply. This is checked at the end as it should rarely fail.
-    if (matchesRuleSet(m_siblingRuleSet) || matchesRuleSet(m_uncommonAttributeRuleSet))
+    INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleFound);
+
+    if (matchesRuleSet(m_siblingRuleSet)) {
+        INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleRejectedBySiblingRules);
         return 0;
+    }
+
+    if (matchesRuleSet(m_uncommonAttributeRuleSet)) {
+        INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleRejectedByUncommonAttributeRules);
+        return 0;
+    }
+
     // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
-    if (!element().parentElement()->childrenSupportStyleSharing())
+    if (!element().parentElement()->childrenSupportStyleSharing()) {
+        INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleRejectedByParent);
         return 0;
-    STYLE_STATS_ADD_STYLE_SHARED();
+    }
+
     return shareElement->renderStyle();
 }
 
diff --git a/Source/core/css/resolver/StyleAdjuster.cpp b/Source/core/css/resolver/StyleAdjuster.cpp
index c9c70fa..5898dda 100644
--- a/Source/core/css/resolver/StyleAdjuster.cpp
+++ b/Source/core/css/resolver/StyleAdjuster.cpp
@@ -274,6 +274,7 @@
         || style->boxReflect()
         || style->hasFilter()
         || style->hasBlendMode()
+        || style->hasIsolation()
         || style->position() == StickyPosition
         || (style->position() == FixedPosition && e && e->document().settings() && e->document().settings()->fixedPositionCreatesStackingContext())
         || isInTopLayer(e, style)
@@ -383,6 +384,10 @@
         // not be scaled again.
         if (e->hasTagName(SVGNames::foreignObjectTag))
             style->setEffectiveZoom(RenderStyle::initialZoom());
+
+        // SVG text layout code expects us to be a block-level style element.
+        if ((e->hasTagName(SVGNames::foreignObjectTag) || e->hasTagName(SVGNames::textTag)) && style->isDisplayInlineType())
+            style->setDisplay(BLOCK);
     }
 }
 
diff --git a/Source/core/css/resolver/StyleBuilderCustom.cpp b/Source/core/css/resolver/StyleBuilderCustom.cpp
index 8676d8a..a4e8a84 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -49,6 +49,7 @@
 #include "core/css/CSSFontValue.h"
 #include "core/css/CSSFunctionValue.h"
 #include "core/css/CSSGradientValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
 #include "core/css/CSSGridTemplateValue.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSLineBoxContainValue.h"
@@ -91,7 +92,7 @@
 
 static Length clipConvertToLength(StyleResolverState& state, CSSPrimitiveValue* value)
 {
-    return value->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    return value->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
 }
 
 void StyleBuilderFunctions::applyInitialCSSPropertyClip(StyleResolverState& state)
@@ -541,7 +542,7 @@
 
     CSSValueList* valueList = toCSSValueList(value);
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(valueList->itemWithoutBoundsCheck(0));
-    Length lengthOrPercentageValue = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    Length lengthOrPercentageValue = primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
     ASSERT(!lengthOrPercentageValue.isUndefined());
     state.style()->setTextIndent(lengthOrPercentageValue);
 
@@ -564,7 +565,7 @@
     if (primitiveValue->getValueID())
         return state.style()->setVerticalAlign(*primitiveValue);
 
-    state.style()->setVerticalAlignLength(primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom()));
+    state.style()->setVerticalAlignLength(primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom()));
 }
 
 static void resetEffectiveZoom(StyleResolverState& state)
@@ -692,7 +693,7 @@
             break;
         }
     } else {
-        Length marqueeLength = primitiveValue ? primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion>(state.style(), state.rootElementStyle()) : Length(Undefined);
+        Length marqueeLength = primitiveValue ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle()) : Length(Undefined);
         if (!marqueeLength.isUndefined())
             state.style()->setMarqueeIncrement(marqueeLength);
     }
@@ -820,10 +821,18 @@
     state.style()->setTextUnderlinePosition(static_cast<TextUnderlinePosition>(t));
 }
 
+String StyleBuilderConverter::convertFragmentIdentifier(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    if (primitiveValue->isURI())
+        return SVGURIReference::fragmentIdentifierFromIRIString(primitiveValue->getStringValue(), state.document());
+    return String();
+}
+
 Length StyleBuilderConverter::convertLength(StyleResolverState& state, CSSValue* value)
 {
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    Length result = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    Length result = primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
     ASSERT(!result.isUndefined());
     result.setQuirk(primitiveValue->isQuirkValue());
     return result;
@@ -832,7 +841,7 @@
 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());
+    Length result = primitiveValue->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
     ASSERT(!result.isUndefined());
     result.setQuirk(primitiveValue->isQuirkValue());
     return result;
@@ -876,17 +885,26 @@
 {
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
     Pair* pair = primitiveValue->getPairValue();
-    Length x = pair->first()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
-    Length y = pair->second()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    Length x = pair->first()->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    Length y = pair->second()->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
     return LengthPoint(x, y);
 }
 
+float StyleBuilderConverter::convertNumberOrPercentage(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    ASSERT(primitiveValue->isNumber() || primitiveValue->isPercentage());
+    if (primitiveValue->isNumber())
+        return primitiveValue->getFloatValue();
+    return primitiveValue->getFloatValue() / 100.0f;
+}
+
 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());
+    Length radiusWidth = pair->first()->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    Length radiusHeight = pair->second()->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
     float width = radiusWidth.value();
     float height = radiusHeight.value();
     ASSERT(width >= 0 && height >= 0);
@@ -935,6 +953,11 @@
     return primitiveValue->computeLength<float>(state.style(), state.rootElementStyle(), zoom);
 }
 
+SVGLength StyleBuilderConverter::convertSVGLength(StyleResolverState&, CSSValue* value)
+{
+    return SVGLength::fromCSSPrimitiveValue(toCSSPrimitiveValue(value));
+}
+
 
 // Everything below this line is from the old StyleResolver::applyProperty
 // and eventually needs to move into new StyleBuilderFunctions calls intead.
@@ -983,7 +1006,7 @@
         return true;
     }
 
-    workingLength = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    workingLength = primitiveValue->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
     if (workingLength.length().isUndefined())
         return false;
 
@@ -1031,16 +1054,16 @@
     size_t currentNamedGridLine = 0;
     for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
         CSSValue* currValue = i.value();
-        if (currValue->isPrimitiveValue()) {
-            CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(currValue);
-            if (primitiveValue->isString()) {
-                String namedGridLine = primitiveValue->getStringValue();
+        if (currValue->isGridLineNamesValue()) {
+            CSSGridLineNamesValue* lineNamesValue = toCSSGridLineNamesValue(currValue);
+            for (CSSValueListIterator j = lineNamesValue; j.hasMore(); j.advance()) {
+                String namedGridLine = toCSSPrimitiveValue(j.value())->getStringValue();
                 NamedGridLinesMap::AddResult result = namedGridLines.add(namedGridLine, Vector<size_t>());
                 result.iterator->value.append(currentNamedGridLine);
                 OrderedNamedGridLines::AddResult orderedInsertionResult = orderedNamedGridLines.add(currentNamedGridLine, Vector<String>());
                 orderedInsertionResult.iterator->value.append(namedGridLine);
-                continue;
             }
+            continue;
         }
 
         ++currentNamedGridLine;
@@ -1179,35 +1202,6 @@
     return PO_NORMAL;
 }
 
-static bool numberToFloat(const CSSPrimitiveValue* primitiveValue, float& out)
-{
-    if (!primitiveValue)
-        return false;
-    if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
-        return false;
-    out = primitiveValue->getFloatValue();
-    return true;
-}
-
-static bool percentageOrNumberToFloat(const CSSPrimitiveValue* primitiveValue, float& out)
-{
-    if (!primitiveValue)
-        return false;
-    int type = primitiveValue->primitiveType();
-    if (type == CSSPrimitiveValue::CSS_PERCENTAGE) {
-        out = primitiveValue->getFloatValue() / 100.0f;
-        return true;
-    }
-    return numberToFloat(primitiveValue, out);
-}
-
-static String fragmentIdentifier(const CSSPrimitiveValue* primitiveValue, Document& document)
-{
-    if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_URI)
-        return String();
-    return SVGURIReference::fragmentIdentifierFromIRIString(primitiveValue->getStringValue(), document);
-}
-
 static inline bool isValidVisitedLinkProperty(CSSPropertyID id)
 {
     switch (id) {
@@ -1531,7 +1525,7 @@
         RefPtr<StyleReflection> reflection = StyleReflection::create();
         reflection->setDirection(*reflectValue->direction());
         if (reflectValue->offset())
-            reflection->setOffset(reflectValue->offset()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), zoomFactor));
+            reflection->setOffset(reflectValue->offset()->convertToLength<FixedConversion | PercentConversion>(state.style(), state.rootElementStyle(), zoomFactor));
         NinePieceImage mask;
         mask.setMaskDefaults();
         state.styleMap().mapNinePieceImage(state.style(), id, reflectValue->mask(), mask);
@@ -2148,6 +2142,20 @@
     case CSSPropertyTextAnchor:
     case CSSPropertyVectorEffect:
     case CSSPropertyWritingMode:
+    case CSSPropertyClipPath:
+    case CSSPropertyFillOpacity:
+    case CSSPropertyFilter:
+    case CSSPropertyFloodOpacity:
+    case CSSPropertyKerning:
+    case CSSPropertyMarkerEnd:
+    case CSSPropertyMarkerMid:
+    case CSSPropertyMarkerStart:
+    case CSSPropertyMask:
+    case CSSPropertyStopOpacity:
+    case CSSPropertyStrokeDashoffset:
+    case CSSPropertyStrokeMiterlimit:
+    case CSSPropertyStrokeOpacity:
+    case CSSPropertyStrokeWidth:
         ASSERT_NOT_REACHED();
         return;
     // Only used in @viewport rules
@@ -2185,13 +2193,6 @@
 
         break;
     }
-    case CSSPropertyKerning:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(kerning, Kerning);
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setKerning(SVGLength::fromCSSPrimitiveValue(primitiveValue));
-        break;
-    }
     case CSSPropertyColorProfile:
     {
         // Not implemented.
@@ -2234,13 +2235,6 @@
         }
         break;
     }
-    case CSSPropertyStrokeWidth:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(strokeWidth, StrokeWidth)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setStrokeWidth(SVGLength::fromCSSPrimitiveValue(primitiveValue));
-        break;
-    }
     case CSSPropertyStrokeDasharray:
     {
         HANDLE_SVG_INHERIT_AND_INITIAL(strokeDashArray, StrokeDashArray)
@@ -2265,87 +2259,6 @@
         state.style()->accessSVGStyle()->setStrokeDashArray(array);
         break;
     }
-    case CSSPropertyStrokeDashoffset:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(strokeDashOffset, StrokeDashOffset)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setStrokeDashOffset(SVGLength::fromCSSPrimitiveValue(primitiveValue));
-        break;
-    }
-    case CSSPropertyFillOpacity:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(fillOpacity, FillOpacity)
-        float f = 0.0f;
-        if (percentageOrNumberToFloat(primitiveValue, f))
-            state.style()->accessSVGStyle()->setFillOpacity(f);
-        break;
-    }
-    case CSSPropertyStrokeOpacity:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(strokeOpacity, StrokeOpacity)
-        float f = 0.0f;
-        if (percentageOrNumberToFloat(primitiveValue, f))
-            state.style()->accessSVGStyle()->setStrokeOpacity(f);
-        break;
-    }
-    case CSSPropertyStopOpacity:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(stopOpacity, StopOpacity)
-        float f = 0.0f;
-        if (percentageOrNumberToFloat(primitiveValue, f))
-            state.style()->accessSVGStyle()->setStopOpacity(f);
-        break;
-    }
-    case CSSPropertyMarkerStart:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(markerStartResource, MarkerStartResource)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setMarkerStartResource(fragmentIdentifier(primitiveValue, state.document()));
-        break;
-    }
-    case CSSPropertyMarkerMid:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(markerMidResource, MarkerMidResource)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setMarkerMidResource(fragmentIdentifier(primitiveValue, state.document()));
-        break;
-    }
-    case CSSPropertyMarkerEnd:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(markerEndResource, MarkerEndResource)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setMarkerEndResource(fragmentIdentifier(primitiveValue, state.document()));
-        break;
-    }
-    case CSSPropertyStrokeMiterlimit:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(strokeMiterLimit, StrokeMiterLimit)
-        float f = 0.0f;
-        if (numberToFloat(primitiveValue, f))
-            state.style()->accessSVGStyle()->setStrokeMiterLimit(f);
-        break;
-    }
-    case CSSPropertyFilter:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(filterResource, FilterResource)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setFilterResource(fragmentIdentifier(primitiveValue, state.document()));
-        break;
-    }
-    case CSSPropertyMask:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(maskerResource, MaskerResource)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setMaskerResource(fragmentIdentifier(primitiveValue, state.document()));
-        break;
-    }
-    case CSSPropertyClipPath:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(clipperResource, ClipperResource)
-        if (primitiveValue)
-            state.style()->accessSVGStyle()->setClipperResource(fragmentIdentifier(primitiveValue, state.document()));
-        break;
-    }
     case CSSPropertyStopColor:
     {
         HANDLE_SVG_INHERIT_AND_INITIAL(stopColor, StopColor);
@@ -2360,14 +2273,6 @@
             state.style()->accessSVGStyle()->setLightingColor(colorFromSVGColorCSSValue(toSVGColor(value), state.style()->color()));
         break;
     }
-    case CSSPropertyFloodOpacity:
-    {
-        HANDLE_SVG_INHERIT_AND_INITIAL(floodOpacity, FloodOpacity)
-        float f = 0.0f;
-        if (percentageOrNumberToFloat(primitiveValue, f))
-            state.style()->accessSVGStyle()->setFloodOpacity(f);
-        break;
-    }
     case CSSPropertyFloodColor:
     {
         HANDLE_SVG_INHERIT_AND_INITIAL(floodColor, FloodColor);
diff --git a/Source/core/css/resolver/StyleBuilderCustom.h b/Source/core/css/resolver/StyleBuilderCustom.h
index d384c51..006f1c8 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.h
+++ b/Source/core/css/resolver/StyleBuilderCustom.h
@@ -40,6 +40,7 @@
 
 class StyleBuilderConverter {
 public:
+    static String convertFragmentIdentifier(StyleResolverState&, CSSValue*);
     template <typename T> static T convertComputedLength(StyleResolverState&, CSSValue*);
     template <typename T> static T convertLineWidth(StyleResolverState&, CSSValue*);
     static Length convertLength(StyleResolverState&, CSSValue*);
@@ -47,10 +48,12 @@
     static Length convertLengthSizing(StyleResolverState&, CSSValue*);
     static Length convertLengthMaxSizing(StyleResolverState&, CSSValue*);
     static LengthPoint convertLengthPoint(StyleResolverState&, CSSValue*);
+    static float convertNumberOrPercentage(StyleResolverState&, CSSValue*);
     static LengthSize convertRadius(StyleResolverState&, CSSValue*);
     static PassRefPtr<ShadowList> convertShadow(StyleResolverState&, CSSValue*);
     static float convertSpacing(StyleResolverState&, CSSValue*);
     template <CSSValueID IdForNone> static AtomicString convertString(StyleResolverState&, CSSValue*);
+    static SVGLength convertSVGLength(StyleResolverState&, CSSValue*);
 };
 
 template <typename T>
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index 1a74519..927aa52 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -57,12 +57,15 @@
 #include "core/css/PageRuleCollector.h"
 #include "core/css/RuleSet.h"
 #include "core/css/StylePropertySet.h"
+#include "core/css/StyleRuleImport.h"
+#include "core/css/StyleSheetContents.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"
 #include "core/css/resolver/StyleAdjuster.h"
 #include "core/css/resolver/StyleBuilder.h"
+#include "core/css/resolver/StyleResolverStats.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
 #include "core/dom/CSSSelectorWatch.h"
 #include "core/dom/NodeRenderStyle.h"
@@ -89,24 +92,12 @@
 
 using namespace WebCore;
 
-PassRefPtr<TimingFunction> generateTimingFunction(const KeyframeAnimationEffect::KeyframeVector keyframes, const HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions)
+void setAnimationUpdateIfNeeded(StyleResolverState& state, Element& element)
 {
-    // Generate the chained timing function. Note that timing functions apply
-    // from the keyframe in which they're specified to the next keyframe.
-    bool isTimingFunctionLinearThroughout = true;
-    RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
-    for (size_t i = 0; i < keyframes.size() - 1; ++i) {
-        double lowerBound = keyframes[i]->offset();
-        ASSERT(lowerBound >=0 && lowerBound < 1);
-        double upperBound = keyframes[i + 1]->offset();
-        ASSERT(upperBound > 0 && upperBound <= 1);
-        TimingFunction* timingFunction = perKeyframeTimingFunctions.get(lowerBound);
-        isTimingFunctionLinearThroughout &= timingFunction->type() == TimingFunction::LinearFunction;
-        chainedTimingFunction->appendSegment(upperBound, timingFunction);
-    }
-    if (isTimingFunctionLinearThroughout)
-        return LinearTimingFunction::create();
-    return chainedTimingFunction;
+    // If any changes to CSS Animations were detected, stash the update away for application after the
+    // render object is updated if we're in the appropriate scope.
+    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && state.animationUpdate())
+        element.ensureActiveAnimations()->cssAnimations().setPendingUpdate(state.takeAnimationUpdate());
 }
 
 } // namespace
@@ -119,45 +110,47 @@
 
 static StylePropertySet* leftToRightDeclaration()
 {
-    DEFINE_STATIC_LOCAL(RefPtr<MutableStylePropertySet>, leftToRightDecl, (MutableStylePropertySet::create()));
+    DEFINE_STATIC_REF(MutableStylePropertySet, leftToRightDecl, (MutableStylePropertySet::create()));
     if (leftToRightDecl->isEmpty())
         leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
-    return leftToRightDecl.get();
+    return leftToRightDecl;
 }
 
 static StylePropertySet* rightToLeftDeclaration()
 {
-    DEFINE_STATIC_LOCAL(RefPtr<MutableStylePropertySet>, rightToLeftDecl, (MutableStylePropertySet::create()));
+    DEFINE_STATIC_REF(MutableStylePropertySet, rightToLeftDecl, (MutableStylePropertySet::create()));
     if (rightToLeftDecl->isEmpty())
         rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
-    return rightToLeftDecl.get();
+    return rightToLeftDecl;
 }
 
-StyleResolver::StyleResolver(Document& document, bool matchAuthorAndUserStyles)
+StyleResolver::StyleResolver(Document& document)
     : m_document(document)
-    , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
     , m_fontSelector(CSSFontSelector::create(&document))
     , m_viewportStyleResolver(ViewportStyleResolver::create(&document))
+    , m_needCollectFeatures(false)
     , m_styleResourceLoader(document.fetcher())
+    , m_styleResolverStatsSequence(0)
+    , m_accessCount(0)
 {
-    Element* root = document.documentElement();
-
     m_fontSelector->registerForInvalidationCallbacks(this);
 
-    CSSDefaultStyleSheets::initDefaultStyle(root);
+    // FIXME: Why do this here instead of as part of resolving style on the root?
+    CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary();
 
-    // construct document root element default style. this is needed
+    // Construct document root element default style. This is needed
     // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
-    // This is here instead of constructor, because when constructor is run,
-    // document doesn't have documentElement
-    // NOTE: this assumes that element that gets passed to styleForElement -call
-    // is always from the document that owns the style selector
+    // This is here instead of constructor because when constructor is run,
+    // Document doesn't have documentElement.
+    // NOTE: This assumes that element that gets passed to the styleForElement call
+    // is always from the document that owns the StyleResolver.
     FrameView* view = document.view();
     if (view)
         m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
     else
         m_medium = adoptPtr(new MediaQueryEvaluator("all"));
 
+    Element* root = document.documentElement();
     if (root)
         m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
 
@@ -166,8 +159,7 @@
 
     m_styleTree.clear();
 
-    StyleEngine* styleSheetCollection = document.styleEngine();
-    m_ruleSets.initUserStyle(styleSheetCollection, CSSSelectorWatch::from(document).watchedCallbackSelectors(), *m_medium, *this);
+    initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
 
 #if ENABLE(SVG_FONTS)
     if (document.svgExtensions()) {
@@ -178,7 +170,57 @@
     }
 #endif
 
-    styleSheetCollection->appendActiveAuthorStyleSheets(this);
+    document.styleEngine()->appendActiveAuthorStyleSheets(this);
+}
+
+void StyleResolver::initWatchedSelectorRules(const Vector<RefPtr<StyleRule> >& watchedSelectors)
+{
+    if (!watchedSelectors.size())
+        return;
+    m_watchedSelectorsRules = RuleSet::create();
+    for (unsigned i = 0; i < watchedSelectors.size(); ++i)
+        m_watchedSelectorsRules->addStyleRule(watchedSelectors[i].get(), RuleHasNoSpecialState);
+}
+
+void StyleResolver::lazyAppendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
+{
+    unsigned size = styleSheets.size();
+    for (unsigned i = firstNew; i < size; ++i)
+        m_pendingStyleSheets.add(styleSheets[i].get());
+}
+
+void StyleResolver::removePendingAuthorStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
+{
+    for (unsigned i = 0; i < styleSheets.size(); ++i)
+        m_pendingStyleSheets.remove(styleSheets[i].get());
+}
+
+void StyleResolver::appendCSSStyleSheet(CSSStyleSheet* cssSheet)
+{
+    ASSERT(cssSheet);
+    ASSERT(!cssSheet->disabled());
+    if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), &m_viewportDependentMediaQueryResults))
+        return;
+
+    StyleSheetContents* sheet = cssSheet->contents();
+    ContainerNode* scopingNode = ScopedStyleResolver::scopingNodeFor(document(), cssSheet);
+    if (!scopingNode)
+        return;
+
+    ScopedStyleResolver* resolver = ensureScopedStyleResolver(scopingNode);
+    ASSERT(resolver);
+    resolver->addRulesFromSheet(sheet, *m_medium, this);
+    m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
+}
+
+void StyleResolver::appendPendingAuthorStyleSheets()
+{
+    setBuildScopedStyleTreeInDocumentOrder(false);
+    for (ListHashSet<CSSStyleSheet*, 16>::iterator it = m_pendingStyleSheets.begin(); it != m_pendingStyleSheets.end(); ++it)
+        appendCSSStyleSheet(*it);
+
+    m_pendingStyleSheets.clear();
+    finishAppendAuthorStyleSheets();
 }
 
 void StyleResolver::appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
@@ -186,22 +228,8 @@
     // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
     // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
     unsigned size = styleSheets.size();
-    for (unsigned i = firstNew; i < size; ++i) {
-        CSSStyleSheet* cssSheet = styleSheets[i].get();
-        ASSERT(!cssSheet->disabled());
-        if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), &m_viewportDependentMediaQueryResults))
-            continue;
-
-        StyleSheetContents* sheet = cssSheet->contents();
-        const ContainerNode* scopingNode = ScopedStyleResolver::scopingNodeFor(cssSheet);
-        if (!scopingNode && cssSheet->ownerNode() && cssSheet->ownerNode()->isInShadowTree())
-            continue;
-
-        ScopedStyleResolver* resolver = ensureScopedStyleResolver(scopingNode);
-        ASSERT(resolver);
-        resolver->addRulesFromSheet(sheet, *m_medium, this);
-        m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
-    }
+    for (unsigned i = firstNew; i < size; ++i)
+        appendCSSStyleSheet(styleSheets[i].get());
 }
 
 void StyleResolver::finishAppendAuthorStyleSheets()
@@ -212,6 +240,56 @@
         document().renderer()->style()->font().update(fontSelector());
 
     collectViewportRules();
+
+    document().styleEngine()->resetCSSFeatureFlags(m_features);
+}
+
+void StyleResolver::resetRuleFeatures()
+{
+    // Need to recreate RuleFeatureSet.
+    m_features.clear();
+    m_siblingRuleSet.clear();
+    m_uncommonAttributeRuleSet.clear();
+    m_needCollectFeatures = true;
+}
+
+void StyleResolver::addTreeBoundaryCrossingRules(const Vector<MinimalRuleData>& rules, ContainerNode* scope)
+{
+    for (unsigned i = 0; i < rules.size(); ++i) {
+        const MinimalRuleData& info = rules[i];
+        m_treeBoundaryCrossingRules.addRule(info.m_rule, info.m_selectorIndex, scope, info.m_flags);
+    }
+}
+
+void StyleResolver::processScopedRules(const RuleSet& authorRules, const KURL& sheetBaseURL, ContainerNode* scope)
+{
+    const Vector<StyleRuleKeyframes*> keyframesRules = authorRules.keyframesRules();
+    for (unsigned i = 0; i < keyframesRules.size(); ++i)
+        ensureScopedStyleResolver(scope)->addKeyframeStyle(keyframesRules[i]);
+
+    addTreeBoundaryCrossingRules(authorRules.treeBoundaryCrossingRules(), scope);
+
+    // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
+    if (!scope || scope->isDocumentNode()) {
+        const Vector<StyleRuleFontFace*> fontFaceRules = authorRules.fontFaceRules();
+        for (unsigned i = 0; i < fontFaceRules.size(); ++i)
+            fontSelector()->addFontFaceRule(fontFaceRules[i]);
+        if (fontFaceRules.size())
+            invalidateMatchedPropertiesCache();
+    } else {
+        addTreeBoundaryCrossingRules(authorRules.shadowDistributedRules(), scope);
+    }
+}
+
+void StyleResolver::resetFontSelector()
+{
+    ASSERT(m_fontSelector);
+    m_fontSelector->unregisterForInvalidationCallbacks(this);
+    m_fontSelector->clearDocument();
+    invalidateMatchedPropertiesCache();
+
+    m_fontSelector = CSSFontSelector::create(&m_document);
+    m_fontSelector->registerForInvalidationCallbacks(this);
 }
 
 void StyleResolver::resetAuthorStyle(const ContainerNode* scopingNode)
@@ -222,39 +300,16 @@
     if (!resolver)
         return;
 
-    m_ruleSets.treeBoundaryCrossingRules().reset(scopingNode);
+    treeBoundaryCrossingRules().reset(scopingNode);
 
     resolver->resetAuthorStyle();
+    resetRuleFeatures();
     if (!scopingNode)
         return;
 
-    if (scopingNode->isInShadowTree())
-        resetAtHostRules(scopingNode->containingShadowRoot());
-
-    if (!resolver->hasOnlyEmptyRuleSets())
-        return;
-
     m_styleTree.remove(scopingNode);
 }
 
-void StyleResolver::resetAtHostRules(const ShadowRoot* shadowRoot)
-{
-    if (!shadowRoot)
-        return;
-
-    const ContainerNode* shadowHost = shadowRoot->shadowHost();
-    ASSERT(shadowHost);
-    ScopedStyleResolver* resolver = m_styleTree.lookupScopedStyleResolverFor(shadowHost);
-    if (!resolver)
-        return;
-
-    resolver->resetAtHostRules(shadowRoot);
-    if (!resolver->hasOnlyEmptyRuleSets())
-        return;
-
-    m_styleTree.remove(shadowHost);
-}
-
 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<RuleFeature>& rules)
 {
     size_t size = rules.size();
@@ -269,11 +324,25 @@
 void StyleResolver::collectFeatures()
 {
     m_features.clear();
-    m_ruleSets.collectFeaturesTo(m_features, document().isViewSource());
+    // Collect all ids and rules using sibling selectors (:first-child and similar)
+    // in the current set of stylesheets. Style sharing code uses this information to reject
+    // sharing candidates.
+    if (CSSDefaultStyleSheets::defaultStyle)
+        m_features.add(CSSDefaultStyleSheets::defaultStyle->features());
+
+    if (document().isViewSource())
+        m_features.add(CSSDefaultStyleSheets::viewSourceStyle()->features());
+
+    if (m_watchedSelectorsRules)
+        m_features.add(m_watchedSelectorsRules->features());
+
+    m_treeBoundaryCrossingRules.collectFeaturesTo(m_features);
+
     m_styleTree.collectFeaturesTo(m_features);
 
     m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
     m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
+    m_needCollectFeatures = false;
 }
 
 bool StyleResolver::hasRulesForId(const AtomicString& id) const
@@ -281,11 +350,16 @@
     return m_features.idsInRules.contains(id.impl());
 }
 
-void StyleResolver::addToStyleSharingList(Element* element)
+void StyleResolver::addToStyleSharingList(Element& element)
 {
+    // Never add elements to the style sharing list if we're not in a recalcStyle,
+    // otherwise we could leave stale pointers in there.
+    if (!document().inStyleRecalc())
+        return;
+    INCREMENT_STYLE_STATS_COUNTER(*this, sharedStyleCandidates);
     if (m_styleSharingList.size() >= styleSharingListSize)
         m_styleSharingList.remove(--m_styleSharingList.end());
-    m_styleSharingList.prepend(element);
+    m_styleSharingList.prepend(&element);
 }
 
 void StyleResolver::clearStyleSharingList()
@@ -299,10 +373,9 @@
     m_document.setNeedsStyleRecalc();
 }
 
-void StyleResolver::pushParentElement(Element* parent)
+void StyleResolver::pushParentElement(Element& parent)
 {
-    ASSERT(parent);
-    const ContainerNode* parentsParent = parent->parentOrShadowHostElement();
+    const ContainerNode* parentsParent = parent.parentOrShadowHostElement();
 
     // We are not always invoked consistently. For example, script execution can cause us to enter
     // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
@@ -314,18 +387,17 @@
         m_selectorFilter.pushParent(parent);
 
     // Note: We mustn't skip ShadowRoot nodes for the scope stack.
-    m_styleTree.pushStyleCache(*parent, parent->parentOrShadowHostNode());
+    m_styleTree.pushStyleCache(parent, parent.parentOrShadowHostNode());
 }
 
-void StyleResolver::popParentElement(Element* parent)
+void StyleResolver::popParentElement(Element& parent)
 {
-    ASSERT(parent);
     // Note that we may get invoked for some random elements in some wacky cases during style resolve.
     // Pause maintaining the stack in this case.
-    if (m_selectorFilter.parentStackIsConsistent(parent))
+    if (m_selectorFilter.parentStackIsConsistent(&parent))
         m_selectorFilter.popParent();
 
-    m_styleTree.popStyleCache(*parent);
+    m_styleTree.popStyleCache(parent);
 }
 
 void StyleResolver::pushParentShadowRoot(const ShadowRoot& shadowRoot)
@@ -347,40 +419,31 @@
     m_viewportStyleResolver->clearDocument();
 }
 
-inline void StyleResolver::collectTreeBoundaryCrossingRules(ElementRuleCollector& collector, bool includeEmptyRules)
+inline void StyleResolver::collectTreeBoundaryCrossingRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
 {
-    if (m_ruleSets.treeBoundaryCrossingRules().isEmpty())
+    if (m_treeBoundaryCrossingRules.isEmpty())
         return;
 
-    bool previousCanUseFastReject = collector.canUseFastReject();
-    collector.setCanUseFastReject(false);
-
     RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
 
-    TreeBoundaryCrossingRules& rules = m_ruleSets.treeBoundaryCrossingRules();
     CascadeOrder cascadeOrder = 0;
 
-    DocumentOrderedList::iterator it = rules.end();
-    while (it != rules.begin()) {
+    DocumentOrderedList::iterator it = m_treeBoundaryCrossingRules.end();
+    while (it != m_treeBoundaryCrossingRules.begin()) {
         --it;
         const ContainerNode* scopingNode = toContainerNode(*it);
-        RuleSet* ruleSet = rules.ruleSetScopedBy(scopingNode);
+        RuleSet* ruleSet = m_treeBoundaryCrossingRules.ruleSetScopedBy(scopingNode);
         unsigned boundaryBehavior = SelectorChecker::CrossesBoundary | SelectorChecker::ScopeContainsLastMatchedElement;
 
+        // If a given scoping node is a shadow root and a given element is in a descendant tree of tree hosted by
+        // the scoping node's shadow host, we should use ScopeIsShadowHost.
         if (scopingNode && scopingNode->isShadowRoot()) {
-            boundaryBehavior |= SelectorChecker::ScopeIsShadowHost;
+            if (element->isInDescendantTreeOf(toShadowRoot(scopingNode)->host()))
+                boundaryBehavior |= SelectorChecker::ScopeIsShadowHost;
             scopingNode = toShadowRoot(scopingNode)->host();
         }
         collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, scopingNode), ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(boundaryBehavior), ignoreCascadeScope, cascadeOrder++);
     }
-    collector.setCanUseFastReject(previousCanUseFastReject);
-}
-
-void StyleResolver::matchHostRules(Element* element, ScopedStyleResolver* resolver, ElementRuleCollector& collector, bool includeEmptyRules)
-{
-    if (element != &resolver->scopingNode())
-        return;
-    resolver->matchHostRules(collector, includeEmptyRules);
 }
 
 static inline bool applyAuthorStylesOf(const Element* element)
@@ -406,21 +469,19 @@
     for (unsigned i = 0; i < resolvers.size(); ++i)
         resolvers.at(i)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, --cascadeOrder);
 
-    collectTreeBoundaryCrossingRules(collector, includeEmptyRules);
+    collectTreeBoundaryCrossingRules(element, collector, includeEmptyRules);
     collector.sortAndTransferMatchedRules();
-
-    if (!resolvers.isEmpty())
-        matchHostRules(element, resolvers.first(), collector, includeEmptyRules);
 }
 
 void StyleResolver::matchAuthorRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
 {
-    if (m_styleTree.hasOnlyScopedResolverForDocument()) {
-        m_styleTree.scopedStyleResolverForDocument()->matchAuthorRules(collector, includeEmptyRules, applyAuthorStylesOf(element));
+    collector.clearMatchedRules();
+    collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
 
-        collector.clearMatchedRules();
-        collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
-        collectTreeBoundaryCrossingRules(collector, includeEmptyRules);
+    bool applyAuthorStyles = applyAuthorStylesOf(element);
+    if (m_styleTree.hasOnlyScopedResolverForDocument()) {
+        m_styleTree.scopedStyleResolverForDocument()->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, ignoreCascadeScope);
+        collectTreeBoundaryCrossingRules(element, collector, includeEmptyRules);
         collector.sortAndTransferMatchedRules();
         return;
     }
@@ -438,33 +499,27 @@
     if (resolvers.isEmpty())
         return;
 
-    bool applyAuthorStyles = applyAuthorStylesOf(element);
     CascadeScope cascadeScope = 0;
     CascadeOrder cascadeOrder = resolvers.size();
-    collector.clearMatchedRules();
-    collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
-
     for (unsigned i = 0; i < resolvers.size(); ++i, --cascadeOrder) {
         ScopedStyleResolver* resolver = resolvers.at(i);
         // FIXME: Need to clarify how to treat style scoped.
         resolver->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, resolver->treeScope() == element->treeScope() && resolver->scopingNode().isShadowRoot() ? 0 : cascadeOrder);
     }
 
-    collectTreeBoundaryCrossingRules(collector, includeEmptyRules);
+    collectTreeBoundaryCrossingRules(element, collector, includeEmptyRules);
     collector.sortAndTransferMatchedRules();
-
-    matchHostRules(element, resolvers.first(), collector, includeEmptyRules);
 }
 
-void StyleResolver::matchUserRules(ElementRuleCollector& collector, bool includeEmptyRules)
+void StyleResolver::matchWatchSelectorRules(ElementRuleCollector& collector)
 {
-    if (!m_ruleSets.userStyle())
+    if (!m_watchedSelectorsRules)
         return;
 
     collector.clearMatchedRules();
     collector.matchedResult().ranges.lastUserRule = collector.matchedResult().matchedProperties.size() - 1;
 
-    MatchRequest matchRequest(m_ruleSets.userStyle(), includeEmptyRules);
+    MatchRequest matchRequest(m_watchedSelectorsRules.get());
     RuleRange ruleRange = collector.matchedResult().ranges.userRuleRange();
     collector.collectMatchingRules(matchRequest, ruleRange);
     collector.collectMatchingRulesForRegion(matchRequest, ruleRange);
@@ -476,10 +531,6 @@
 {
     collector.setMatchingUARules(true);
 
-    // First we match rules from the user agent sheet.
-    if (CSSDefaultStyleSheets::simpleDefaultStyleSheet)
-        collector.matchedResult().isCacheable = false;
-
     RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
         ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle;
     matchUARules(collector, userAgentStyleSheet);
@@ -493,6 +544,8 @@
         matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle());
 
     collector.setMatchingUARules(false);
+
+    matchWatchSelectorRules(collector);
 }
 
 void StyleResolver::matchUARules(ElementRuleCollector& collector, RuleSet* rules)
@@ -506,14 +559,10 @@
     collector.sortAndTransferMatchedRules();
 }
 
-void StyleResolver::matchAllRules(StyleResolverState& state, ElementRuleCollector& collector, bool matchAuthorAndUserStyles, bool includeSMILProperties)
+void StyleResolver::matchAllRules(StyleResolverState& state, ElementRuleCollector& collector, bool includeSMILProperties)
 {
     matchUARules(collector);
 
-    // Now we check user sheet rules.
-    if (matchAuthorAndUserStyles)
-        matchUserRules(collector, false);
-
     // Now check author rules, beginning first with presentational attributes mapped from HTML.
     if (state.element()->isStyledElement()) {
         collector.addElementStyleProperties(state.element()->presentationAttributeStyle());
@@ -531,26 +580,18 @@
         }
     }
 
-    // Check the rules in author sheets next.
-    if (matchAuthorAndUserStyles)
-        matchAuthorRules(state.element(), collector, false);
+    matchAuthorRules(state.element(), collector, false);
 
     if (state.element()->isStyledElement()) {
-        // Now check our inline style attribute.
-        if (matchAuthorAndUserStyles && state.element()->inlineStyle()) {
+        if (state.element()->inlineStyle()) {
             // Inline style is immutable as long as there is no CSSOM wrapper.
-            // FIXME: Media control shadow trees seem to have problems with caching.
-            bool isInlineStyleCacheable = !state.element()->inlineStyle()->isMutable() && !state.element()->isInShadowTree();
-            // FIXME: Constify.
+            bool isInlineStyleCacheable = !state.element()->inlineStyle()->isMutable();
             collector.addElementStyleProperties(state.element()->inlineStyle(), isInlineStyleCacheable);
         }
 
         // Now check SMIL animation override style.
-        if (includeSMILProperties && matchAuthorAndUserStyles && state.element()->isSVGElement())
+        if (includeSMILProperties && state.element()->isSVGElement())
             collector.addElementStyleProperties(toSVGElement(state.element())->animatedSMILStyleProperties(), false /* isCacheable */);
-
-        if (state.element()->hasActiveAnimations())
-            collector.matchedResult().isCacheable = false;
     }
 }
 
@@ -611,6 +652,8 @@
 {
     ASSERT(document().frame());
     ASSERT(documentSettings());
+    ASSERT(!hasPendingAuthorStyleSheets());
+    ASSERT(!m_needCollectFeatures);
 
     // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
     // will vanish if a style recalc happens during loading.
@@ -624,6 +667,8 @@
         return s_styleNotYetAvailable;
     }
 
+    didAccess();
+
     if (element == document().documentElement())
         resetDirectionAndWritingModeOnDocument(document());
     StyleResolverState state(document(), element, defaultParent, regionForStyling);
@@ -677,9 +722,9 @@
         if (matchingBehavior == MatchOnlyUserAgentRules)
             matchUARules(collector);
         else
-            matchAllRules(state, collector, m_matchAuthorAndUserStyles, matchingBehavior != MatchAllRulesExcludingSMIL);
+            matchAllRules(state, collector, matchingBehavior != MatchAllRulesExcludingSMIL);
 
-        applyMatchedProperties(state, collector.matchedResult());
+        applyMatchedProperties(state, collector.matchedResult(), element);
 
         addContentAttrValuesToFeatures(state.contentAttrValues(), m_features);
     }
@@ -688,25 +733,21 @@
         adjuster.adjustRenderStyle(state.style(), state.parentStyle(), element);
     }
 
-    document().didAccessStyleResolver();
-
     // FIXME: Shouldn't this be on RenderBody::styleDidChange?
     if (element->hasTagName(bodyTag))
         document().textLinkColors().setTextColor(state.style()->visitedDependentColor(CSSPropertyColor));
 
-    // If any changes to CSS Animations were detected, stash the update away for application after the
-    // render object is updated if we're in the appropriate scope.
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && state.animationUpdate())
-        element->ensureActiveAnimations()->cssAnimations().setPendingUpdate(state.takeAnimationUpdate());
+    setAnimationUpdateIfNeeded(state, *element);
 
     // Now return the style.
     return state.takeStyle();
 }
 
-PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* e, const RenderStyle* elementStyle, const StyleKeyframe* keyframe)
+PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* e, const RenderStyle& elementStyle, const StyleKeyframe* keyframe, const AtomicString& animationName)
 {
     ASSERT(document().frame());
     ASSERT(documentSettings());
+    ASSERT(!hasPendingAuthorStyleSheets());
 
     if (e == document().documentElement())
         resetDirectionAndWritingModeOnDocument(document());
@@ -719,9 +760,21 @@
     ASSERT(!state.style());
 
     // Create the style
-    state.setStyle(RenderStyle::clone(elementStyle));
+    state.setStyle(RenderStyle::clone(&elementStyle));
     state.setLineHeightValue(0);
 
+    // Make sure that the CSSAnimationData for the animation to which this
+    // keyframe belongs is first in the list. This makes sure that if the
+    // animation-timing-function property is set for this keyframe, it will be
+    // applied to the correct CSSAnimationData object. Note that objects other
+    // than the first in the list are ignored when reading the timing function
+    // value. See KeyframeValue::timingFunction().
+    CSSAnimationDataList* animations = state.style()->accessAnimations();
+    ASSERT(animations && !animations->isEmpty());
+    while (animations->animation(0)->name() != animationName)
+        animations->remove(0);
+    ASSERT(!animations->isEmpty() && animations->animation(0)->name() == animationName);
+
     state.fontBuilder().initForStyleResolve(state.document(), state.style(), state.useSVGZoomRules());
 
     // We don't need to bother with !important. Since there is only ever one
@@ -750,30 +803,14 @@
 
     // Start loading resources referenced by this style.
     m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+    m_fontSelector->loadPendingFonts();
 
-    document().didAccessStyleResolver();
+    didAccess();
 
     return state.takeStyle();
 }
 
-const StyleRuleKeyframes* StyleResolver::matchScopedKeyframesRule(const Element* e, const StringImpl* animationName)
-{
-    if (m_styleTree.hasOnlyScopedResolverForDocument())
-        return m_styleTree.scopedStyleResolverForDocument()->keyframeStylesForAnimation(animationName);
-
-    Vector<ScopedStyleResolver*, 8> stack;
-    m_styleTree.resolveScopedKeyframesRules(e, stack);
-    if (stack.isEmpty())
-        return 0;
-
-    for (size_t i = 0; i < stack.size(); ++i) {
-        if (const StyleRuleKeyframes* keyframesRule = stack.at(i)->keyframeStylesForAnimation(animationName))
-            return keyframesRule;
-    }
-    return 0;
-}
-
-void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
+void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle& elementStyle, KeyframeList& list)
 {
     ASSERT(!RuntimeEnabledFeatures::webAnimationsCSSEnabled());
     list.clear();
@@ -782,18 +819,20 @@
     if (!e || list.animationName().isEmpty())
         return;
 
-    const StyleRuleKeyframes* keyframesRule = matchScopedKeyframesRule(e, list.animationName().impl());
+    ASSERT(!hasPendingAuthorStyleSheets());
+    const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(this, e, list.animationName().impl());
     if (!keyframesRule)
         return;
 
     // Construct and populate the style for each keyframe
+    const AtomicString& name = list.animationName();
     const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
     for (unsigned i = 0; i < keyframes.size(); ++i) {
         // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
         const StyleKeyframe* keyframe = keyframes[i].get();
 
         KeyframeValue keyframeValue(0, 0);
-        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, keyframe));
+        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, keyframe, name));
         keyframeValue.addProperties(keyframe->properties());
 
         // Add this keyframe style to all the indicated key times
@@ -813,7 +852,7 @@
             zeroPercentKeyframe->setKeyText("0%");
         }
         KeyframeValue keyframeValue(0, 0);
-        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, zeroPercentKeyframe));
+        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, zeroPercentKeyframe, name));
         keyframeValue.addProperties(zeroPercentKeyframe->properties());
         list.insert(keyframeValue);
     }
@@ -826,173 +865,12 @@
             hundredPercentKeyframe->setKeyText("100%");
         }
         KeyframeValue keyframeValue(1, 0);
-        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, hundredPercentKeyframe));
+        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, hundredPercentKeyframe, name));
         keyframeValue.addProperties(hundredPercentKeyframe->properties());
         list.insert(keyframeValue);
     }
 }
 
-void StyleResolver::resolveKeyframes(Element* element, const RenderStyle* style, const AtomicString& name, TimingFunction* defaultTimingFunction, Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > >& keyframesAndTimingFunctions)
-{
-    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-    const StyleRuleKeyframes* keyframesRule = matchScopedKeyframesRule(element, name.impl());
-    if (!keyframesRule)
-        return;
-
-    const Vector<RefPtr<StyleKeyframe> >& styleKeyframes = keyframesRule->keyframes();
-    if (styleKeyframes.isEmpty())
-        return;
-
-    // Construct and populate the style for each keyframe
-    KeyframeAnimationEffect::KeyframeVector keyframes;
-    HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions;
-    for (size_t i = 0; i < styleKeyframes.size(); ++i) {
-        const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
-        RefPtr<RenderStyle> keyframeStyle = styleForKeyframe(element, style, styleKeyframe);
-        RefPtr<Keyframe> keyframe = Keyframe::create();
-        const Vector<double>& offsets = styleKeyframe->keys();
-        ASSERT(!offsets.isEmpty());
-        keyframe->setOffset(offsets[0]);
-        TimingFunction* timingFunction = defaultTimingFunction;
-        const StylePropertySet* properties = styleKeyframe->properties();
-        for (unsigned j = 0; j < properties->propertyCount(); j++) {
-            CSSPropertyID property = properties->propertyAt(j).id();
-            if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction) {
-                // FIXME: This sometimes gets the wrong timing function. See crbug.com/288540.
-                timingFunction = KeyframeValue::timingFunction(keyframeStyle.get(), name);
-            } else if (CSSAnimations::isAnimatableProperty(property)) {
-                keyframe->setPropertyValue(property, CSSAnimatableValueFactory::create(property, keyframeStyle.get()).get());
-            }
-        }
-        keyframes.append(keyframe);
-        // The last keyframe specified at a given offset is used.
-        perKeyframeTimingFunctions.set(offsets[0], timingFunction);
-        for (size_t j = 1; j < offsets.size(); ++j) {
-            keyframes.append(keyframe->cloneWithOffset(offsets[j]));
-            perKeyframeTimingFunctions.set(offsets[j], timingFunction);
-        }
-    }
-    ASSERT(!keyframes.isEmpty());
-
-    if (!perKeyframeTimingFunctions.contains(0))
-        perKeyframeTimingFunctions.set(0, defaultTimingFunction);
-
-    // 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())
-            targetIndex++;
-        if (targetIndex != i)
-            keyframes[targetIndex] = keyframes[i];
-    }
-    keyframes.shrink(targetIndex + 1);
-
-    // Add 0% and 100% keyframes if absent.
-    RefPtr<Keyframe> startKeyframe = keyframes[0];
-    if (startKeyframe->offset()) {
-        startKeyframe = Keyframe::create();
-        startKeyframe->setOffset(0);
-        keyframes.prepend(startKeyframe);
-    }
-    RefPtr<Keyframe> endKeyframe = keyframes[keyframes.size() - 1];
-    if (endKeyframe->offset() != 1) {
-        endKeyframe = Keyframe::create();
-        endKeyframe->setOffset(1);
-        keyframes.append(endKeyframe);
-    }
-    ASSERT(keyframes.size() >= 2);
-    ASSERT(!keyframes.first()->offset());
-    ASSERT(keyframes.last()->offset() == 1);
-
-    // Snapshot current property values for 0% and 100% if missing.
-    PropertySet allProperties;
-    size_t numKeyframes = keyframes.size();
-    for (size_t i = 0; i < numKeyframes; i++) {
-        const PropertySet& keyframeProperties = keyframes[i]->properties();
-        for (PropertySet::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
-            allProperties.add(*iter);
-    }
-    const PropertySet& startKeyframeProperties = startKeyframe->properties();
-    const PropertySet& endKeyframeProperties = endKeyframe->properties();
-    bool missingStartValues = startKeyframeProperties.size() < allProperties.size();
-    bool missingEndValues = endKeyframeProperties.size() < allProperties.size();
-    if (missingStartValues || missingEndValues) {
-        for (PropertySet::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());
-        }
-    }
-    ASSERT(startKeyframe->properties().size() == allProperties.size());
-    ASSERT(endKeyframe->properties().size() == allProperties.size());
-
-    // Determine how many keyframes specify each property. Note that this must
-    // be done after we've filled in end keyframes.
-    typedef HashCountedSet<CSSPropertyID> PropertyCountedSet;
-    PropertyCountedSet propertyCounts;
-    for (size_t i = 0; i < numKeyframes; ++i) {
-        const PropertySet& properties = keyframes[i]->properties();
-        for (PropertySet::const_iterator iter = properties.begin(); iter != properties.end(); ++iter)
-            propertyCounts.add(*iter);
-    }
-
-    // Split keyframes into groups, where each group contains only keyframes
-    // which specify all properties used in that group. Each group is animated
-    // in a separate animation, to allow per-keyframe timing functions to be
-    // applied correctly.
-    for (PropertyCountedSet::const_iterator iter = propertyCounts.begin(); iter != propertyCounts.end(); ++iter) {
-        const CSSPropertyID property = iter->key;
-        const size_t count = iter->value;
-        ASSERT(count <= numKeyframes);
-        if (count == numKeyframes)
-            continue;
-        KeyframeAnimationEffect::KeyframeVector splitOutKeyframes;
-        for (size_t i = 0; i < numKeyframes; i++) {
-            Keyframe* keyframe = keyframes[i].get();
-            if (!keyframe->properties().contains(property)) {
-                ASSERT(i && i != numKeyframes - 1);
-                continue;
-            }
-            RefPtr<Keyframe> clonedKeyframe = Keyframe::create();
-            clonedKeyframe->setOffset(keyframe->offset());
-            clonedKeyframe->setComposite(keyframe->composite());
-            clonedKeyframe->setPropertyValue(property, keyframe->propertyValue(property));
-            splitOutKeyframes.append(clonedKeyframe);
-            // Note that it's OK if this keyframe ends up having no
-            // properties. This can only happen when none of the properties
-            // are specified in all keyframes, in which case we won't animate
-            // anything with these keyframes.
-            keyframe->clearPropertyValue(property);
-        }
-        ASSERT(!splitOutKeyframes.first()->offset());
-        ASSERT(splitOutKeyframes.last()->offset() == 1);
-#ifndef NDEBUG
-        for (size_t j = 0; j < splitOutKeyframes.size(); ++j)
-            ASSERT(splitOutKeyframes[j]->properties().size() == 1);
-#endif
-        keyframesAndTimingFunctions.append(std::make_pair(splitOutKeyframes, generateTimingFunction(splitOutKeyframes, perKeyframeTimingFunctions)));
-    }
-
-    int numPropertiesSpecifiedInAllKeyframes = keyframes.first()->properties().size();
-#ifndef NDEBUG
-    for (size_t i = 1; i < numKeyframes; ++i)
-        ASSERT(keyframes[i]->properties().size() == numPropertiesSpecifiedInAllKeyframes);
-#endif
-
-    // If the animation specifies any keyframes, we always provide at least one
-    // vector of resolved keyframes, even if no properties are animated.
-    if (numPropertiesSpecifiedInAllKeyframes || keyframesAndTimingFunctions.isEmpty())
-        keyframesAndTimingFunctions.append(std::make_pair(keyframes, generateTimingFunction(keyframes, perKeyframeTimingFunctions)));
-}
-
 PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* e, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
 {
     ASSERT(document().frame());
@@ -1022,17 +900,14 @@
         collector.setPseudoStyleRequest(pseudoStyleRequest);
 
         matchUARules(collector);
-        if (m_matchAuthorAndUserStyles) {
-            matchUserRules(collector, false);
-            matchAuthorRules(state.element(), collector, false);
-        }
+        matchAuthorRules(state.element(), collector, false);
 
         if (collector.matchedResult().matchedProperties.isEmpty())
             return 0;
 
         state.style()->setStyleType(pseudoStyleRequest.pseudoId);
 
-        applyMatchedProperties(state, collector.matchedResult());
+        applyMatchedProperties(state, collector.matchedResult(), e->pseudoElement(pseudoStyleRequest.pseudoId));
 
         addContentAttrValuesToFeatures(state.contentAttrValues(), m_features);
     }
@@ -1043,7 +918,10 @@
         adjuster.adjustRenderStyle(state.style(), state.parentStyle(), 0);
     }
 
-    document().didAccessStyleResolver();
+    didAccess();
+
+    if (PseudoElement* pseudoElement = e->pseudoElement(pseudoStyleRequest.pseudoId))
+        setAnimationUpdateIfNeeded(state, *pseudoElement);
 
     // Now return the style.
     return state.takeStyle();
@@ -1051,6 +929,7 @@
 
 PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
 {
+    ASSERT(!hasPendingAuthorStyleSheets());
     resetDirectionAndWritingModeOnDocument(document());
     StyleResolverState state(document(), document().documentElement()); // m_rootElementStyle will be set to the document style.
 
@@ -1064,7 +943,6 @@
     PageRuleCollector collector(rootElementStyle, pageIndex);
 
     collector.matchPageRules(CSSDefaultStyleSheets::defaultPrintStyle);
-    collector.matchPageRules(m_ruleSets.userStyle());
 
     if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
         scopedResolver->matchPageRules(collector);
@@ -1089,8 +967,9 @@
 
     // Start loading resources referenced by this style.
     m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+    m_fontSelector->loadPendingFonts();
 
-    document().didAccessStyleResolver();
+    didAccess();
 
     // Now return the style.
     return state.takeStyle();
@@ -1103,9 +982,6 @@
     if (document().isMobileDocument())
         viewportStyleResolver()->collectViewportRules(CSSDefaultStyleSheets::xhtmlMobileProfileStyle(), ViewportStyleResolver::UserAgentOrigin);
 
-    if (m_ruleSets.userStyle())
-        viewportStyleResolver()->collectViewportRules(m_ruleSets.userStyle(), ViewportStyleResolver::UserAgentOrigin);
-
     if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
         scopedResolver->collectViewportRulesTo(this);
 
@@ -1139,20 +1015,10 @@
 {
     // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
     // so all region rules are global by default. Verify whether that can stand or needs changing.
-
-    if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
+    if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument()) {
         if (scopedResolver->checkRegionStyle(regionElement))
             return true;
-
-    if (m_ruleSets.userStyle()) {
-        unsigned rulesSize = m_ruleSets.userStyle()->m_regionSelectorsAndRuleSets.size();
-        for (unsigned i = 0; i < rulesSize; ++i) {
-            ASSERT(m_ruleSets.userStyle()->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
-            if (checkRegionSelector(m_ruleSets.userStyle()->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
-                return true;
-        }
     }
-
     return false;
 }
 
@@ -1190,19 +1056,11 @@
 {
     collector.setPseudoStyleRequest(PseudoStyleRequest(pseudoId));
 
-    if (rulesToInclude & UAAndUserCSSRules) {
-        // First we match rules from the user agent sheet.
+    if (rulesToInclude & UAAndUserCSSRules)
         matchUARules(collector);
 
-        // Now we check user sheet rules.
-        if (m_matchAuthorAndUserStyles)
-            matchUserRules(collector, rulesToInclude & EmptyCSSRules);
-    }
-
-    if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
+    if (rulesToInclude & AuthorCSSRules) {
         collector.setSameOriginOnly(!(rulesToInclude & CrossOriginCSSRules));
-
-        // Check the rules in author sheets.
         matchAuthorRules(element, collector, rulesToInclude & EmptyCSSRules);
     }
 }
@@ -1210,24 +1068,38 @@
 // -------------------------------------------------------------------------------------
 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
 
+void StyleResolver::applyAnimatedProperties(StyleResolverState& state, Element* animatingElement)
+{
+    // animatingElement may be null, for example if we're calculating the
+    // style for a potential pseudo element that has yet to be created.
+    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || !animatingElement)
+        return;
+    state.setAnimationUpdate(CSSAnimations::calculateUpdate(animatingElement, *state.style(), this));
+    if (!state.animationUpdate())
+        return;
+    const AnimationEffect::CompositableValueMap& compositableValuesForAnimations = state.animationUpdate()->compositableValuesForAnimations();
+    const AnimationEffect::CompositableValueMap& compositableValuesForTransitions = state.animationUpdate()->compositableValuesForTransitions();
+    applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForAnimations);
+    applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForTransitions);
+    applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForAnimations);
+    applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForTransitions);
+}
+
 template <StyleResolver::StyleApplicationPass pass>
-bool StyleResolver::applyAnimatedProperties(StyleResolverState& state, const AnimationEffect::CompositableValueMap& compositableValues)
+void StyleResolver::applyAnimatedProperties(StyleResolverState& state, const AnimationEffect::CompositableValueMap& compositableValues)
 {
     ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
     ASSERT(pass != VariableDefinitions);
     ASSERT(pass != AnimationProperties);
-    bool didApply = false;
 
     for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues.begin(); iter != compositableValues.end(); ++iter) {
         CSSPropertyID property = iter->key;
         if (!isPropertyForPass<pass>(property))
             continue;
-        RELEASE_ASSERT_WITH_MESSAGE(!iter->value->dependsOnUnderlyingValue(), "Web Animations not yet implemented: An interface for compositing onto the underlying value.");
+        ASSERT_WITH_MESSAGE(!iter->value->dependsOnUnderlyingValue(), "Web Animations not yet implemented: An interface for compositing onto the underlying value.");
         RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(0);
         AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
-        didApply = true;
     }
-    return didApply;
 }
 
 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
@@ -1388,11 +1260,12 @@
     m_matchedPropertiesCache.clear();
 }
 
-void StyleResolver::applyMatchedProperties(StyleResolverState& state, const MatchResult& matchResult)
+void StyleResolver::applyMatchedProperties(StyleResolverState& state, const MatchResult& matchResult, Element* animatingElement)
 {
     const Element* element = state.element();
     ASSERT(element);
-    STYLE_STATS_ADD_MATCHED_PROPERTIES_SEARCH();
+
+    INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyApply);
 
     unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
     bool applyInheritedOnly = false;
@@ -1400,13 +1273,13 @@
 
     if (cacheHash && (cachedMatchedProperties = m_matchedPropertiesCache.find(cacheHash, state, matchResult))
         && MatchedPropertiesCache::isCacheable(element, state.style(), state.parentStyle())) {
-        STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT();
+        INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheHit);
         // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
         // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
         // element context. This is fast and saves memory by reusing the style data structures.
         state.style()->copyNonInheritedFrom(cachedMatchedProperties->renderStyle.get());
         if (state.parentStyle()->inheritedDataShared(cachedMatchedProperties->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
-            STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT_SHARED_INHERITED();
+            INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheInheritedHit);
 
             EInsideLink linkStatus = state.style()->insideLink();
             // If the cache item parent style has identical inherited properties to the current parent style then the
@@ -1415,6 +1288,12 @@
 
             // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
             state.style()->setInsideLink(linkStatus);
+
+            if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && animatingElement
+                && (animatingElement->hasActiveAnimations()
+                    || (state.style()->transitions() && !state.style()->transitions()->isEmpty())
+                    || (state.style()->animations() && !state.style()->animations()->isEmpty())))
+                applyAnimatedProperties(state, animatingElement);
             return;
         }
         applyInheritedOnly = true;
@@ -1476,52 +1355,53 @@
     applyMatchedProperties<LowPriorityProperties>(state, matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
     applyMatchedProperties<LowPriorityProperties>(state, matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
 
-    if (RuntimeEnabledFeatures::webAnimationsEnabled()) {
-        state.setAnimationUpdate(CSSAnimations::calculateUpdate(state.element(), state.style(), this));
-        if (state.animationUpdate()) {
-            ASSERT(!applyInheritedOnly);
-            const AnimationEffect::CompositableValueMap& compositableValuesForAnimations = state.animationUpdate()->compositableValuesForAnimations();
-            const AnimationEffect::CompositableValueMap& compositableValuesForTransitions = state.animationUpdate()->compositableValuesForTransitions();
-            // Apply animated properties, then reapply any rules marked important.
-            if (applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForAnimations)) {
-                bool important = true;
-                applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
-                applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
-                applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
-            }
-            applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForTransitions);
-            if (applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForAnimations)) {
-                bool important = true;
-                applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
-                applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
-                applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
-            }
-            applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForTransitions);
-        }
-    }
-
     // Start loading resources referenced by this style.
     m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+    m_fontSelector->loadPendingFonts();
+
+    if (!cachedMatchedProperties && cacheHash && MatchedPropertiesCache::isCacheable(element, state.style(), state.parentStyle())) {
+        INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheAdded);
+        m_matchedPropertiesCache.add(state.style(), state.parentStyle(), cacheHash, matchResult);
+    }
+
+    applyAnimatedProperties(state, animatingElement);
 
     ASSERT(!state.fontBuilder().fontDirty());
-
-#ifdef STYLE_STATS
-    if (!cachedMatchedProperties)
-        STYLE_STATS_ADD_MATCHED_PROPERTIES_TO_CACHE();
-#endif
-
-    if (cachedMatchedProperties || !cacheHash)
-        return;
-    if (!MatchedPropertiesCache::isCacheable(element, state.style(), state.parentStyle()))
-        return;
-    STYLE_STATS_ADD_MATCHED_PROPERTIES_ENTERED_INTO_CACHE();
-    m_matchedPropertiesCache.add(state.style(), state.parentStyle(), cacheHash, matchResult);
 }
 
 CSSPropertyValue::CSSPropertyValue(CSSPropertyID id, const StylePropertySet& propertySet)
     : property(id), value(propertySet.getPropertyCSSValue(id).get())
 { }
 
+void StyleResolver::enableStats(StatsReportType reportType)
+{
+    if (m_styleResolverStats)
+        return;
+    m_styleResolverStats = StyleResolverStats::create();
+    m_styleResolverStatsTotals = StyleResolverStats::create();
+    if (reportType == ReportSlowStats) {
+        m_styleResolverStats->printMissedCandidateCount = true;
+        m_styleResolverStatsTotals->printMissedCandidateCount = true;
+    }
+}
+
+void StyleResolver::disableStats()
+{
+    m_styleResolverStatsSequence = 0;
+    m_styleResolverStats.clear();
+    m_styleResolverStatsTotals.clear();
+}
+
+void StyleResolver::printStats()
+{
+    if (!m_styleResolverStats)
+        return;
+    fprintf(stderr, "=== Style Resolver Stats (resolve #%u) (%s) ===\n", ++m_styleResolverStatsSequence, m_document.url().string().utf8().data());
+    fprintf(stderr, "%s\n", m_styleResolverStats->report().utf8().data());
+    fprintf(stderr, "== Totals ==\n");
+    fprintf(stderr, "%s\n", m_styleResolverStatsTotals->report().utf8().data());
+}
+
 void StyleResolver::applyPropertiesToStyle(const CSSPropertyValue* properties, size_t count, RenderStyle* style)
 {
     StyleResolverState state(document(), document().documentElement(), style);
@@ -1547,49 +1427,19 @@
     }
 }
 
+void StyleResolver::addMediaQueryResults(const MediaQueryResultList& list)
+{
+    for (size_t i = 0; i < list.size(); ++i)
+        m_viewportDependentMediaQueryResults.append(list[i]);
+}
+
 bool StyleResolver::affectedByViewportChange() const
 {
-    unsigned s = m_viewportDependentMediaQueryResults.size();
-    for (unsigned i = 0; i < s; i++) {
+    for (unsigned i = 0; i < m_viewportDependentMediaQueryResults.size(); ++i) {
         if (m_medium->eval(&m_viewportDependentMediaQueryResults[i]->m_expression) != m_viewportDependentMediaQueryResults[i]->m_result)
             return true;
     }
     return false;
 }
 
-#ifdef STYLE_STATS
-StyleSharingStats StyleResolver::m_styleSharingStats;
-
-static void printStyleStats(unsigned searches, unsigned elementsEligibleForSharing, unsigned stylesShared, unsigned searchFoundSiblingForSharing, unsigned searchesMissedSharing,
-    unsigned matchedPropertiesSearches, unsigned matchedPropertiesHit, unsigned matchedPropertiesSharedInheritedHit, unsigned matchedPropertiesToCache, unsigned matchedPropertiesEnteredIntoCache)
-{
-    double percentOfElementsSharingStyle = (stylesShared * 100.0) / searches;
-    double percentOfNodesEligibleForSharing = (elementsEligibleForSharing * 100.0) / searches;
-    double percentOfEligibleSharingRelativesFound = (searchFoundSiblingForSharing * 100.0) / searches;
-    double percentOfMatchedPropertiesHit = (matchedPropertiesHit * 100.0) / matchedPropertiesSearches;
-    double percentOfMatchedPropertiesSharedInheritedHit = (matchedPropertiesSharedInheritedHit * 100.0) / matchedPropertiesSearches;
-    double percentOfMatchedPropertiesEnteredIntoCache = (matchedPropertiesEnteredIntoCache * 100.0) / matchedPropertiesToCache;
-
-    fprintf(stderr, "%u elements checked, %u were eligible for style sharing (%.2f%%).\n", searches, elementsEligibleForSharing, percentOfNodesEligibleForSharing);
-    fprintf(stderr, "%u elements were found to share with, %u were possible (%.2f%%).\n", searchFoundSiblingForSharing, searchesMissedSharing + searchFoundSiblingForSharing, percentOfEligibleSharingRelativesFound);
-    fprintf(stderr, "%u styles were actually shared once sibling and attribute rules were considered (%.2f%%).\n", stylesShared, percentOfElementsSharingStyle);
-    fprintf(stderr, "%u/%u (%.2f%%) matched property lookups hit the cache.\n", matchedPropertiesHit, matchedPropertiesSearches, percentOfMatchedPropertiesHit);
-    fprintf(stderr, "%u/%u (%.2f%%) matched property lookups hit the cache and shared inherited data.\n", matchedPropertiesSharedInheritedHit, matchedPropertiesSearches, percentOfMatchedPropertiesSharedInheritedHit);
-    fprintf(stderr, "%u/%u (%.2f%%) matched properties were cacheable\n", matchedPropertiesEnteredIntoCache, matchedPropertiesToCache, percentOfMatchedPropertiesEnteredIntoCache);
-}
-
-void StyleSharingStats::printStats() const
-{
-    fprintf(stderr, "--------------------------------------------------------------------------------\n");
-    fprintf(stderr, "This recalc style:\n");
-    printStyleStats(m_searches, m_elementsEligibleForSharing, m_stylesShared, m_searchFoundSiblingForSharing, m_searchesMissedSharing,
-        m_matchedPropertiesSearches, m_matchedPropertiesHit, m_matchedPropertiesSharedInheritedHit, m_matchedPropertiesToCache, m_matchedPropertiesEnteredIntoCache);
-
-    fprintf(stderr, "Total:\n");
-    printStyleStats(m_totalSearches, m_totalElementsEligibleForSharing, m_totalStylesShared, m_totalSearchFoundSiblingForSharing, m_totalSearchesMissedSharing,
-        m_totalMatchedPropertiesSearches, m_totalMatchedPropertiesHit, m_totalMatchedPropertiesSharedInheritedHit, m_totalMatchedPropertiesToCache, m_totalMatchedPropertiesEnteredIntoCache);
-    fprintf(stderr, "--------------------------------------------------------------------------------\n");
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index 51d87a6..4ff0797 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -23,7 +23,6 @@
 #define StyleResolver_h
 
 #include "core/animation/KeyframeAnimationEffect.h"
-#include "core/css/DocumentRuleSets.h"
 #include "core/css/InspectorCSSOMWrappers.h"
 #include "core/css/PseudoStyleRequest.h"
 #include "core/css/RuleFeature.h"
@@ -31,8 +30,10 @@
 #include "core/css/SelectorChecker.h"
 #include "core/css/SelectorFilter.h"
 #include "core/css/SiblingTraversalStrategies.h"
+#include "core/css/TreeBoundaryCrossingRules.h"
 #include "core/css/resolver/MatchedPropertiesCache.h"
 #include "core/css/resolver/ScopedStyleResolver.h"
+#include "core/css/resolver/ScopedStyleTree.h"
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/StyleResolverIncludes.h"
 #include "core/css/resolver/StyleResolverState.h"
@@ -40,6 +41,7 @@
 #include "wtf/Deque.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
+#include "wtf/ListHashSet.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
@@ -65,6 +67,7 @@
 class Settings;
 class StyleKeyframe;
 class StylePropertySet;
+class StyleResolverStats;
 class StyleRule;
 class StyleRuleKeyframes;
 class StyleRulePage;
@@ -87,81 +90,7 @@
 };
 
 const unsigned styleSharingListSize = 40;
-typedef WTF::Deque<RefPtr<Element>, styleSharingListSize> StyleSharingList;
-
-#undef STYLE_STATS
-
-#ifdef STYLE_STATS
-struct StyleSharingStats {
-    void addSearch() { ++m_searches; ++m_totalSearches; }
-    void addElementEligibleForSharing() { ++m_elementsEligibleForSharing; ++m_totalElementsEligibleForSharing; }
-    void addStyleShared() { ++m_stylesShared; ++m_totalStylesShared; }
-    void addSearchFoundSiblingForSharing() { ++m_searchFoundSiblingForSharing; ++m_totalSearchFoundSiblingForSharing; }
-    void addSearchMissedSharing() { ++m_searchesMissedSharing; ++m_totalSearchesMissedSharing; }
-    void addMatchedPropertiesSearch() { ++m_matchedPropertiesSearches; ++m_totalMatchedPropertiesSearches; }
-    void addMatchedPropertiesHit() { ++m_matchedPropertiesHit; ++m_totalMatchedPropertiesHit; }
-    void addMatchedPropertiesHitSharedInherited() { ++m_matchedPropertiesSharedInheritedHit; ++m_totalMatchedPropertiesSharedInheritedHit; }
-    void addMatchedPropertiesToCache() { ++m_matchedPropertiesToCache; ++m_totalMatchedPropertiesToCache; }
-    void addMatchedPropertiesEnteredIntoCache() { ++m_matchedPropertiesEnteredIntoCache; ++m_totalMatchedPropertiesEnteredIntoCache; }
-
-    void clear()
-    {
-        m_searches = m_elementsEligibleForSharing = m_stylesShared = m_searchesMissedSharing = m_searchFoundSiblingForSharing =
-            m_matchedPropertiesSearches = m_matchedPropertiesHit = m_matchedPropertiesSharedInheritedHit = m_matchedPropertiesToCache =
-            m_matchedPropertiesEnteredIntoCache = 0;
-    }
-
-    void printStats() const;
-
-    unsigned m_searches;
-    unsigned m_elementsEligibleForSharing;
-    unsigned m_stylesShared;
-    unsigned m_searchFoundSiblingForSharing;
-    unsigned m_searchesMissedSharing;
-    unsigned m_matchedPropertiesSearches;
-    unsigned m_matchedPropertiesHit;
-    unsigned m_matchedPropertiesSharedInheritedHit;
-    unsigned m_matchedPropertiesToCache;
-    unsigned m_matchedPropertiesEnteredIntoCache;
-
-    unsigned m_totalSearches;
-    unsigned m_totalElementsEligibleForSharing;
-    unsigned m_totalStylesShared;
-    unsigned m_totalSearchFoundSiblingForSharing;
-    unsigned m_totalSearchesMissedSharing;
-    unsigned m_totalMatchedPropertiesSearches;
-    unsigned m_totalMatchedPropertiesHit;
-    unsigned m_totalMatchedPropertiesSharedInheritedHit;
-    unsigned m_totalMatchedPropertiesToCache;
-    unsigned m_totalMatchedPropertiesEnteredIntoCache;
-};
-
-#define STYLE_STATS_ADD_SEARCH() StyleResolver::styleSharingStats().addSearch();
-#define STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING() StyleResolver::styleSharingStats().addElementEligibleForSharing();
-#define STYLE_STATS_ADD_STYLE_SHARED() StyleResolver::styleSharingStats().addStyleShared();
-#define STYLE_STATS_ADD_SEARCH_FOUND_SIBLING_FOR_SHARING() StyleResolver::styleSharingStats().addSearchFoundSiblingForSharing();
-#define STYLE_STATS_ADD_SEARCH_MISSED_SHARING() StyleResolver::styleSharingStats().addSearchMissedSharing();
-#define STYLE_STATS_PRINT() StyleResolver::styleSharingStats().printStats();
-#define STYLE_STATS_CLEAR() StyleResolver::styleSharingStats().clear();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_SEARCH() StyleResolver::styleSharingStats().addMatchedPropertiesSearch();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT() StyleResolver::styleSharingStats().addMatchedPropertiesHit();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT_SHARED_INHERITED() StyleResolver::styleSharingStats().addMatchedPropertiesHitSharedInherited();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_TO_CACHE() StyleResolver::styleSharingStats().addMatchedPropertiesToCache();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_ENTERED_INTO_CACHE() StyleResolver::styleSharingStats().addMatchedPropertiesEnteredIntoCache();
-#else
-#define STYLE_STATS_ADD_SEARCH() (void(0));
-#define STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING() (void(0));
-#define STYLE_STATS_ADD_STYLE_SHARED() (void(0));
-#define STYLE_STATS_ADD_SEARCH_FOUND_SIBLING_FOR_SHARING() (void(0));
-#define STYLE_STATS_ADD_SEARCH_MISSED_SHARING() (void(0));
-#define STYLE_STATS_PRINT() (void(0));
-#define STYLE_STATS_CLEAR() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_SEARCH() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT_SHARED_INHERITED() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_TO_CACHE() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_ENTERED_INTO_CACHE() (void(0));
-#endif
+typedef WTF::Deque<Element*, styleSharingListSize> StyleSharingList;
 
 struct CSSPropertyValue {
     CSSPropertyValue(CSSPropertyID property, CSSValue* value)
@@ -176,26 +105,25 @@
 class StyleResolver : public FontSelectorClient {
     WTF_MAKE_NONCOPYABLE(StyleResolver); WTF_MAKE_FAST_ALLOCATED;
 public:
-    StyleResolver(Document&, bool matchAuthorAndUserStyles);
+    explicit StyleResolver(Document&);
     ~StyleResolver();
 
     // FIXME: StyleResolver should not be keeping tree-walk state.
     // These should move to some global tree-walk state, or should be contained in a
     // TreeWalkContext or similar which is passed in to StyleResolver methods when available.
     // Using these during tree walk will allow style selector to optimize child and descendant selector lookups.
-    void pushParentElement(Element*);
-    void popParentElement(Element*);
+    void pushParentElement(Element&);
+    void popParentElement(Element&);
     void pushParentShadowRoot(const ShadowRoot&);
     void popParentShadowRoot(const ShadowRoot&);
 
     PassRefPtr<RenderStyle> styleForElement(Element*, RenderStyle* parentStyle = 0, StyleSharingBehavior = AllowStyleSharing,
         RuleMatchingBehavior = MatchAllRules, RenderRegion* regionForStyling = 0);
 
-    // FIXME: The following logic related to animations and keyframes should be factored out of StyleResolver
-    void resolveKeyframes(Element*, const RenderStyle*, const AtomicString& animationName, TimingFunction* defaultTimingFunction, Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > >&);
-    void keyframeStylesForAnimation(Element*, const RenderStyle*, KeyframeList&);
-    const StyleRuleKeyframes* matchScopedKeyframesRule(const Element*, const StringImpl* animationName);
-    PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle*, const StyleKeyframe*);
+    // FIXME: keyframeStylesForAnimation is only used in the legacy animations implementation
+    // and should be removed when that is replaced by Web Animations.
+    void keyframeStylesForAnimation(Element*, const RenderStyle&, KeyframeList&);
+    PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle&, const StyleKeyframe*, const AtomicString& animationName);
 
     PassRefPtr<RenderStyle> pseudoStyleForElement(Element*, const PseudoStyleRequest&, RenderStyle* parentStyle);
 
@@ -209,23 +137,37 @@
     // their dependency on Document* instead of grabbing one through StyleResolver.
     Document& document() { return m_document; }
 
-    // FIXME: It could be better to call m_ruleSets.appendAuthorStyleSheets() directly after we factor StyleRsolver further.
+    // FIXME: It could be better to call appendAuthorStyleSheets() directly after we factor StyleResolver further.
     // https://bugs.webkit.org/show_bug.cgi?id=108890
     void appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >&);
     void resetAuthorStyle(const ContainerNode*);
-    void resetAtHostRules(const ShadowRoot*);
     void finishAppendAuthorStyleSheets();
+    void resetFontSelector();
 
-    DocumentRuleSets& ruleSets() { return m_ruleSets; }
-    const DocumentRuleSets& ruleSets() const { return m_ruleSets; }
+    TreeBoundaryCrossingRules& treeBoundaryCrossingRules() { return m_treeBoundaryCrossingRules; }
+    void processScopedRules(const RuleSet& authorRules, const KURL&, ContainerNode* scope = 0);
+
+    void lazyAppendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >&);
+    void removePendingAuthorStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
+    void appendPendingAuthorStyleSheets();
+    bool hasPendingAuthorStyleSheets() const { return m_pendingStyleSheets.size() > 0 || m_needCollectFeatures; }
+
     SelectorFilter& selectorFilter() { return m_selectorFilter; }
 
     void setBuildScopedStyleTreeInDocumentOrder(bool enabled) { m_styleTree.setBuildInDocumentOrder(enabled); }
     bool buildScopedStyleTreeInDocumentOrder() const { return m_styleTree.buildInDocumentOrder(); }
+    bool styleTreeHasOnlyScopedResolverForDocument() const { return m_styleTree.hasOnlyScopedResolverForDocument(); }
+    ScopedStyleResolver* styleTreeScopedStyleResolverForDocument() const { return m_styleTree.scopedStyleResolverForDocument(); }
 
-    ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scope)
+    ScopedStyleResolver* ensureScopedStyleResolver(ContainerNode* scope)
     {
-        return m_styleTree.ensureScopedStyleResolver(scope ? *scope : document());
+        ASSERT(scope);
+        return m_styleTree.ensureScopedStyleResolver(*scope);
+    }
+
+    void styleTreeResolveScopedKeyframesRules(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
+    {
+        m_styleTree.resolveScopedKeyframesRules(element, resolvers);
     }
 
     // These methods will give back the set of rules that matched for a given element (or a pseudo-element).
@@ -247,7 +189,7 @@
     CSSFontSelector* fontSelector() const { return m_fontSelector.get(); }
     ViewportStyleResolver* viewportStyleResolver() { return m_viewportStyleResolver.get(); }
 
-    typedef Vector<OwnPtr<MediaQueryResult> > MediaQueryResultList;
+    void addMediaQueryResults(const MediaQueryResultList&);
     MediaQueryResultList* viewportDependentMediaQueryResults() { return &m_viewportDependentMediaQueryResults; }
     bool hasViewportDependentMediaQueries() const { return !m_viewportDependentMediaQueryResults.isEmpty(); }
     bool affectedByViewportChange() const;
@@ -264,41 +206,60 @@
     // FIXME: StyleResolver should not have this member or method.
     InspectorCSSOMWrappers& inspectorCSSOMWrappers() { return m_inspectorCSSOMWrappers; }
 
-    const RuleFeatureSet& ruleFeatureSet() const { return m_features; }
+    const RuleFeatureSet& ensureRuleFeatureSet()
+    {
+        if (hasPendingAuthorStyleSheets())
+            appendPendingAuthorStyleSheets();
+        return m_features;
+    }
 
     StyleSharingList& styleSharingList() { return m_styleSharingList; }
 
     bool hasRulesForId(const AtomicString&) const;
 
-    void addToStyleSharingList(Element*);
+    void addToStyleSharingList(Element&);
     void clearStyleSharingList();
 
-#ifdef STYLE_STATS
-    ALWAYS_INLINE static StyleSharingStats& styleSharingStats() { return m_styleSharingStats; }
-#endif
+    StyleResolverStats* stats() { return m_styleResolverStats.get(); }
+    StyleResolverStats* statsTotals() { return m_styleResolverStatsTotals.get(); }
+    enum StatsReportType { ReportDefaultStats, ReportSlowStats };
+    void enableStats(StatsReportType = ReportDefaultStats);
+    void disableStats();
+    void printStats();
+
+    unsigned accessCount() const { return m_accessCount; }
+    void didAccess() { ++m_accessCount; }
 
 private:
     // FontSelectorClient implementation.
     virtual void fontsNeedUpdate(FontSelector*);
 
 private:
+    void initWatchedSelectorRules(const Vector<RefPtr<StyleRule> >& watchedSelectors);
+
+    void addTreeBoundaryCrossingRules(const Vector<MinimalRuleData>&, ContainerNode* scope);
+
     // FIXME: This should probably go away, folded into FontBuilder.
     void updateFont(StyleResolverState&);
 
+    void appendCSSStyleSheet(CSSStyleSheet*);
+
     void collectPseudoRulesForElement(Element*, ElementRuleCollector&, PseudoId, unsigned rulesToInclude);
     void matchUARules(ElementRuleCollector&, RuleSet*);
     void matchAuthorRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
     void matchAuthorRulesForShadowHost(Element*, ElementRuleCollector&, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree);
-    void matchHostRules(Element*, ScopedStyleResolver*, ElementRuleCollector&, bool includeEmptyRules);
-    void matchAllRules(StyleResolverState&, ElementRuleCollector&, bool matchAuthorAndUserStyles, bool includeSMILProperties);
+    void matchAllRules(StyleResolverState&, ElementRuleCollector&, bool includeSMILProperties);
     void matchUARules(ElementRuleCollector&);
-    void matchUserRules(ElementRuleCollector&, bool includeEmptyRules);
+    // FIXME: watched selectors should be implemented using injected author stylesheets: http://crbug.com/316960
+    void matchWatchSelectorRules(ElementRuleCollector&);
     void collectFeatures();
-    void collectTreeBoundaryCrossingRules(ElementRuleCollector&, bool includeEmptyRules);
+    void collectTreeBoundaryCrossingRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
+    void resetRuleFeatures();
 
     bool fastRejectSelector(const RuleData&) const;
 
-    void applyMatchedProperties(StyleResolverState&, const MatchResult&);
+    void applyMatchedProperties(StyleResolverState&, const MatchResult&, Element* animatingElement);
+    void applyAnimatedProperties(StyleResolverState&, Element* animatingElement);
 
     enum StyleApplicationPass {
         VariableDefinitions,
@@ -313,7 +274,7 @@
     template <StyleApplicationPass pass>
     void applyProperties(StyleResolverState&, const StylePropertySet* properties, StyleRule*, bool isImportant, bool inheritedOnly, PropertyWhitelistType = PropertyWhitelistNone);
     template <StyleApplicationPass pass>
-    bool applyAnimatedProperties(StyleResolverState&, const AnimationEffect::CompositableValueMap&);
+    void applyAnimatedProperties(StyleResolverState&, const AnimationEffect::CompositableValueMap&);
     void matchPageRules(MatchResult&, RuleSet*, bool isLeftPage, bool isFirstPage, const String& pageName);
     void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>&, bool isLeftPage, bool isFirstPage, const String& pageName);
     void collectViewportRules();
@@ -324,8 +285,6 @@
     bool isFirstPage(int pageIndex) const;
     String pageName(int pageIndex) const;
 
-    DocumentRuleSets m_ruleSets;
-
     // FIXME: This likely belongs on RuleSet.
     typedef HashMap<StringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
     KeyframesRuleMap m_keyframesRuleMap;
@@ -344,12 +303,12 @@
     Document& m_document;
     SelectorFilter m_selectorFilter;
 
-    bool m_matchAuthorAndUserStyles;
-
     RefPtr<CSSFontSelector> m_fontSelector;
 
     RefPtr<ViewportStyleResolver> m_viewportStyleResolver;
 
+    ListHashSet<CSSStyleSheet*, 16> m_pendingStyleSheets;
+
     ScopedStyleTree m_styleTree;
 
     // FIXME: The entire logic of collecting features on StyleResolver, as well astransferring them
@@ -358,15 +317,23 @@
     OwnPtr<RuleSet> m_siblingRuleSet;
     OwnPtr<RuleSet> m_uncommonAttributeRuleSet;
 
+    // FIXME: watched selectors should be implemented using injected author stylesheets: http://crbug.com/316960
+    OwnPtr<RuleSet> m_watchedSelectorsRules;
+    TreeBoundaryCrossingRules m_treeBoundaryCrossingRules;
+
+    bool m_needCollectFeatures;
+
     InspectorCSSOMWrappers m_inspectorCSSOMWrappers;
 
     StyleResourceLoader m_styleResourceLoader;
 
     StyleSharingList m_styleSharingList;
 
-#ifdef STYLE_STATS
-    static StyleSharingStats m_styleSharingStats;
-#endif
+    OwnPtr<StyleResolverStats> m_styleResolverStats;
+    OwnPtr<StyleResolverStats> m_styleResolverStatsTotals;
+    unsigned m_styleResolverStatsSequence;
+
+    unsigned m_accessCount;
 };
 
 inline bool checkRegionSelector(const CSSSelector* regionSelector, Element* regionElement)
diff --git a/Source/core/css/resolver/StyleResolverStats.cpp b/Source/core/css/resolver/StyleResolverStats.cpp
new file mode 100644
index 0000000..bb795bf
--- /dev/null
+++ b/Source/core/css/resolver/StyleResolverStats.cpp
@@ -0,0 +1,87 @@
+/*
+ * 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/StyleResolverStats.h"
+
+#include "wtf/text/CString.h"
+#include "wtf/text/StringBuilder.h"
+
+#define PERCENT(x, y) ((!y) ? 0 : (((x) * 100.0) / (y)))
+
+namespace WebCore {
+
+void StyleResolverStats::reset()
+{
+    sharedStyleLookups = 0;
+    sharedStyleCandidates = 0;
+    sharedStyleFound = 0;
+    sharedStyleMissed = 0;
+    sharedStyleRejectedByUncommonAttributeRules = 0;
+    sharedStyleRejectedBySiblingRules = 0;
+    sharedStyleRejectedByParent = 0;
+    matchedPropertyApply = 0;
+    matchedPropertyCacheHit = 0;
+    matchedPropertyCacheInheritedHit = 0;
+    matchedPropertyCacheAdded = 0;
+}
+
+String StyleResolverStats::report() const
+{
+    StringBuilder output;
+
+    unsigned sharedStylesRejected = sharedStyleRejectedByUncommonAttributeRules + sharedStyleRejectedBySiblingRules + sharedStyleRejectedByParent;
+    unsigned sharedStylesUsed = sharedStyleFound - sharedStylesRejected;
+
+    output.append("Style sharing:\n");
+    output.append(String::format("  %u elements were added to the sharing candidate list.\n", sharedStyleCandidates));
+    output.append(String::format("  %u calls were made to findSharedStyle, %u found a candidate to share with (%.2f%%).\n", sharedStyleLookups, sharedStyleFound, PERCENT(sharedStyleFound, sharedStyleLookups)));
+    if (printMissedCandidateCount)
+        output.append(String::format("  %u candidates could have matched but were not in the list when searching (%.2f%%).\n", sharedStyleMissed, PERCENT(sharedStyleMissed, sharedStyleLookups)));
+    output.append(String::format("  %u of found styles were rejected (%.2f%%), %.2f%% by uncommon attribute rules, %.2f%% by sibling rules and %.2f%% by parents disabling sharing.\n",
+        sharedStylesRejected,
+        PERCENT(sharedStylesRejected, sharedStyleFound),
+        PERCENT(sharedStyleRejectedByUncommonAttributeRules, sharedStylesRejected),
+        PERCENT(sharedStyleRejectedBySiblingRules, sharedStylesRejected),
+        PERCENT(sharedStyleRejectedByParent, sharedStylesRejected)));
+    output.append(String::format("  %u of found styles were used for sharing (%.2f%%).\n", sharedStylesUsed, PERCENT(sharedStylesUsed, sharedStyleFound)));
+    output.append(String::format("  %.2f%% of calls to findSharedStyle returned a shared style.\n", PERCENT(sharedStylesUsed, sharedStyleLookups)));
+
+    output.append("\n");
+
+    output.append("Matched property cache:\n");
+    output.append(String::format("  %u calls to applyMatchedProperties, %u hit the cache (%.2f%%).\n", matchedPropertyApply, matchedPropertyCacheHit, PERCENT(matchedPropertyCacheHit, matchedPropertyApply)));
+    output.append(String::format("  %u cache hits also shared the inherited style (%.2f%%).\n", matchedPropertyCacheInheritedHit, PERCENT(matchedPropertyCacheInheritedHit, matchedPropertyCacheHit)));
+    output.append(String::format("  %u styles created in applyMatchedProperties were added to the cache (%.2f%%).\n", matchedPropertyCacheAdded, PERCENT(matchedPropertyCacheAdded, matchedPropertyApply)));
+
+    return output.toString();
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/resolver/StyleResolverStats.h b/Source/core/css/resolver/StyleResolverStats.h
new file mode 100644
index 0000000..084c02d
--- /dev/null
+++ b/Source/core/css/resolver/StyleResolverStats.h
@@ -0,0 +1,77 @@
+/*
+ * 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 StyleResolverStats_h
+#define StyleResolverStats_h
+
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class StyleResolverStats {
+public:
+    static PassOwnPtr<StyleResolverStats> create()
+    {
+        return adoptPtr(new StyleResolverStats);
+    }
+
+    void reset();
+    String report() const;
+
+    unsigned sharedStyleLookups;
+    unsigned sharedStyleCandidates;
+    unsigned sharedStyleFound;
+    unsigned sharedStyleMissed;
+    unsigned sharedStyleRejectedByUncommonAttributeRules;
+    unsigned sharedStyleRejectedBySiblingRules;
+    unsigned sharedStyleRejectedByParent;
+    unsigned matchedPropertyApply;
+    unsigned matchedPropertyCacheHit;
+    unsigned matchedPropertyCacheInheritedHit;
+    unsigned matchedPropertyCacheAdded;
+
+    // We keep a separate flag for this since crawling the entire document to print
+    // the number of missed candidates is very slow.
+    bool printMissedCandidateCount;
+
+private:
+    StyleResolverStats()
+        : printMissedCandidateCount(false)
+    {
+        reset();
+    }
+};
+
+#define INCREMENT_STYLE_STATS_COUNTER(resolver, counter) ((resolver).stats() && ++(resolver).stats()-> counter && (resolver).statsTotals()-> counter ++);
+
+} // namespace WebCore
+
+#endif // StyleResolverStats_h
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
index 3d29773..2def25e 100644
--- a/Source/core/css/resolver/StyleResourceLoader.cpp
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -43,6 +43,7 @@
 #include "core/rendering/style/StyleGeneratedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include "core/rendering/style/StylePendingShader.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
 
 namespace WebCore {
 
@@ -60,8 +61,8 @@
     Vector<RefPtr<FilterOperation> >& filterOperations = renderStyle->mutableFilter().operations();
     for (unsigned i = 0; i < filterOperations.size(); ++i) {
         RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
-        if (filterOperation->getOperationType() == FilterOperation::REFERENCE) {
-            ReferenceFilterOperation* referenceFilter = static_cast<ReferenceFilterOperation*>(filterOperation.get());
+        if (filterOperation->type() == FilterOperation::REFERENCE) {
+            ReferenceFilterOperation* referenceFilter = toReferenceFilterOperation(filterOperation.get());
 
             CSSSVGDocumentValue* value = elementStyleResources.pendingSVGDocuments().get(referenceFilter);
             if (!value)
@@ -71,7 +72,7 @@
                 continue;
 
             // Stash the DocumentResource on the reference filter.
-            referenceFilter->setDocumentResourceReference(adoptPtr(new DocumentResourceReference(resource)));
+            ReferenceFilterBuilder::setDocumentResourceReference(referenceFilter, adoptPtr(new DocumentResourceReference(resource)));
         }
     }
 }
@@ -111,14 +112,13 @@
     if (!image || !image->isPendingImage())
         return;
 
-    StylePendingImage* pendingImage = static_cast<StylePendingImage*>(image);
+    StylePendingImage* pendingImage = toStylePendingImage(image);
     CSSImageValue* cssImageValue =  pendingImage->cssImageValue();
 
     ResourceLoaderOptions options = ResourceFetcher::defaultResourceOptions();
-    options.requestOriginPolicy = PotentiallyCrossOriginEnabled;
     options.allowCredentials = DoNotAllowStoredCredentials;
 
-    shapeValue->setImage(cssImageValue->cachedImage(m_fetcher, options));
+    shapeValue->setImage(cssImageValue->cachedImage(m_fetcher, options, PotentiallyCORSEnabled));
 }
 
 void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementStyleResources& elementStyleResources)
@@ -134,7 +134,7 @@
         case CSSPropertyBackgroundImage: {
             for (FillLayer* backgroundLayer = style->accessBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
                 if (backgroundLayer->image() && backgroundLayer->image()->isPendingImage())
-                    backgroundLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(backgroundLayer->image()), elementStyleResources.deviceScaleFactor()));
+                    backgroundLayer->setImage(loadPendingImage(toStylePendingImage(backgroundLayer->image()), elementStyleResources.deviceScaleFactor()));
             }
             break;
         }
@@ -143,7 +143,7 @@
                 if (contentData->isImage()) {
                     StyleImage* image = static_cast<ImageContentData*>(contentData)->image();
                     if (image->isPendingImage()) {
-                        RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor());
+                        RefPtr<StyleImage> loadedImage = loadPendingImage(toStylePendingImage(image), elementStyleResources.deviceScaleFactor());
                         if (loadedImage)
                             static_cast<ImageContentData*>(contentData)->setImage(loadedImage.release());
                     }
@@ -157,7 +157,7 @@
                     CursorData& currentCursor = cursorList->at(i);
                     if (StyleImage* image = currentCursor.image()) {
                         if (image->isPendingImage())
-                            currentCursor.setImage(loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor()));
+                            currentCursor.setImage(loadPendingImage(toStylePendingImage(image), elementStyleResources.deviceScaleFactor()));
                     }
                 }
             }
@@ -165,19 +165,19 @@
         }
         case CSSPropertyListStyleImage: {
             if (style->listStyleImage() && style->listStyleImage()->isPendingImage())
-                style->setListStyleImage(loadPendingImage(static_cast<StylePendingImage*>(style->listStyleImage()), elementStyleResources.deviceScaleFactor()));
+                style->setListStyleImage(loadPendingImage(toStylePendingImage(style->listStyleImage()), elementStyleResources.deviceScaleFactor()));
             break;
         }
         case CSSPropertyBorderImageSource: {
             if (style->borderImageSource() && style->borderImageSource()->isPendingImage())
-                style->setBorderImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->borderImageSource()), elementStyleResources.deviceScaleFactor()));
+                style->setBorderImageSource(loadPendingImage(toStylePendingImage(style->borderImageSource()), elementStyleResources.deviceScaleFactor()));
             break;
         }
         case CSSPropertyWebkitBoxReflect: {
             if (StyleReflection* reflection = style->boxReflect()) {
                 const NinePieceImage& maskImage = reflection->mask();
                 if (maskImage.image() && maskImage.image()->isPendingImage()) {
-                    RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(maskImage.image()), elementStyleResources.deviceScaleFactor());
+                    RefPtr<StyleImage> loadedImage = loadPendingImage(toStylePendingImage(maskImage.image()), elementStyleResources.deviceScaleFactor());
                     reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
                 }
             }
@@ -185,13 +185,13 @@
         }
         case CSSPropertyWebkitMaskBoxImageSource: {
             if (style->maskBoxImageSource() && style->maskBoxImageSource()->isPendingImage())
-                style->setMaskBoxImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->maskBoxImageSource()), elementStyleResources.deviceScaleFactor()));
+                style->setMaskBoxImageSource(loadPendingImage(toStylePendingImage(style->maskBoxImageSource()), elementStyleResources.deviceScaleFactor()));
             break;
         }
         case CSSPropertyWebkitMaskImage: {
             for (FillLayer* maskLayer = style->accessMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
                 if (maskLayer->image() && maskLayer->image()->isPendingImage())
-                    maskLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(maskLayer->image()), elementStyleResources.deviceScaleFactor()));
+                    maskLayer->setImage(loadPendingImage(toStylePendingImage(maskLayer->image()), elementStyleResources.deviceScaleFactor()));
             }
             break;
         }
@@ -215,8 +215,8 @@
     Vector<RefPtr<FilterOperation> >& filterOperations = style->mutableFilter().operations();
     for (unsigned i = 0; i < filterOperations.size(); ++i) {
         RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
-        if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
-            CustomFilterOperation* customFilter = static_cast<CustomFilterOperation*>(filterOperation.get());
+        if (filterOperation->type() == FilterOperation::CUSTOM) {
+            CustomFilterOperation* customFilter = toCustomFilterOperation(filterOperation.get());
             ASSERT(customFilter->program());
             StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
             // Note that the StylePendingShaders could be already resolved to StyleFetchedShaders. That's because the rule was matched before.
diff --git a/Source/core/css/resolver/TransformBuilder.cpp b/Source/core/css/resolver/TransformBuilder.cpp
index 4538fcd..d6f344c 100644
--- a/Source/core/css/resolver/TransformBuilder.cpp
+++ b/Source/core/css/resolver/TransformBuilder.cpp
@@ -53,7 +53,7 @@
 
 static Length convertToFloatLength(CSSPrimitiveValue* primitiveValue, const RenderStyle* style, const RenderStyle* rootStyle, double multiplier)
 {
-    return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion>(style, rootStyle, multiplier) : Length(Undefined);
+    return primitiveValue ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(style, rootStyle, multiplier) : Length(Undefined);
 }
 
 static TransformOperation::OperationType getTransformOperationType(CSSTransformValue::TransformOperationType type)
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.cpp b/Source/core/css/viewportAndroid.css
similarity index 84%
copy from Source/core/workers/WorkerGlobalScopeProxy.cpp
copy to Source/core/css/viewportAndroid.css
index 06471bb..f406505 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ b/Source/core/css/viewportAndroid.css
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 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,11 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
+/* These styles override other user-agent styles for Chromium on Android. */
 
-namespace WebCore {
-
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
-
-} // namespace WebCore
+@viewport {
+    min-width: 980px;
+}
diff --git a/Source/core/dom/ActiveDOMObject.h b/Source/core/dom/ActiveDOMObject.h
index 67b5e82..1157363 100644
--- a/Source/core/dom/ActiveDOMObject.h
+++ b/Source/core/dom/ActiveDOMObject.h
@@ -44,12 +44,22 @@
     bool suspendIfNeededCalled() const { return m_suspendIfNeededCalled; }
 #endif
 
+    // Should return true if there's any pending asynchronous activity, and so
+    // this object must not be garbage collected.
+    //
+    // Default implementation is that it returns true iff
+    // m_pendingActivityCount is non-zero.
     virtual bool hasPendingActivity() const;
 
+    // These methods have an empty default implementation so that subclasses
+    // which don't need special treatment can skip implementation.
     virtual void suspend();
     virtual void resume();
     virtual void stop();
 
+protected:
+    virtual ~ActiveDOMObject();
+
     template<class T> void setPendingActivity(T* thisObject)
     {
         ASSERT(thisObject == this);
@@ -64,9 +74,6 @@
         thisObject->deref();
     }
 
-protected:
-    virtual ~ActiveDOMObject();
-
 private:
     unsigned m_pendingActivityCount;
 #if !ASSERT_DISABLED
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index 6b0e04e..1ebc4bb 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -31,7 +31,7 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Text.h"
 #include "core/events/ScopedEventQueue.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -91,21 +91,21 @@
     }
 }
 
-void Attr::setPrefix(const AtomicString& prefix, ExceptionState& es)
+void Attr::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
 {
     UseCounter::count(document(), UseCounter::AttributeSetPrefix);
 
-    checkSetPrefix(prefix, es);
-    if (es.hadException())
+    checkSetPrefix(prefix, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     if (prefix == xmlnsAtom && namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
-        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'."));
+        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'."));
         return;
     }
 
     if (this->qualifiedName() == xmlnsAtom) {
-        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'."));
+        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'."));
         return;
     }
 
diff --git a/Source/core/dom/Attr.idl b/Source/core/dom/Attr.idl
index 8494da4..00d9205 100644
--- a/Source/core/dom/Attr.idl
+++ b/Source/core/dom/Attr.idl
@@ -26,7 +26,7 @@
 
     [MeasureAs=AttributeSpecified] readonly attribute boolean specified;
 
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException, CustomElementCallbacks] attribute DOMString value;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter, CustomElementCallbacks] attribute DOMString value;
 
     // DOM Level 2
 
@@ -38,7 +38,7 @@
 
     // DOM 4
 
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException] attribute DOMString prefix;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter] attribute DOMString prefix;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
 };
diff --git a/Source/core/dom/CSSSelectorWatch.cpp b/Source/core/dom/CSSSelectorWatch.cpp
index 4f8b781..074d6b2 100644
--- a/Source/core/dom/CSSSelectorWatch.cpp
+++ b/Source/core/dom/CSSSelectorWatch.cpp
@@ -90,31 +90,24 @@
 
     for (unsigned i = 0; i < removedSelectors.size(); ++i) {
         const String& selector = removedSelectors[i];
-        HashMap<String, int>::iterator count = m_matchingCallbackSelectors.find(selector);
-        if (count == m_matchingCallbackSelectors.end())
+        if (!m_matchingCallbackSelectors.remove(selector))
             continue;
-        --count->value;
-        if (!count->value) {
-            shouldUpdateTimer = true;
 
-            m_matchingCallbackSelectors.remove(count);
-            if (m_addedSelectors.contains(selector))
-                m_addedSelectors.remove(selector);
-            else
-                m_removedSelectors.add(selector);
-        }
+        // Count reached 0.
+        shouldUpdateTimer = true;
+        if (m_addedSelectors.contains(selector))
+            m_addedSelectors.remove(selector);
+        else
+            m_removedSelectors.add(selector);
     }
 
     for (unsigned i = 0; i < addedSelectors.size(); ++i) {
         const String& selector = addedSelectors[i];
-        HashMap<String, int>::iterator count = m_matchingCallbackSelectors.find(selector);
-        if (count != m_matchingCallbackSelectors.end()) {
-            ++count->value;
+        HashCountedSet<String>::AddResult result = m_matchingCallbackSelectors.add(selector);
+        if (!result.isNewEntry)
             continue;
-        }
-        shouldUpdateTimer = true;
 
-        m_matchingCallbackSelectors.set(selector, 1);
+        shouldUpdateTimer = true;
         if (m_removedSelectors.contains(selector))
             m_removedSelectors.remove(selector);
         else
diff --git a/Source/core/dom/CSSSelectorWatch.h b/Source/core/dom/CSSSelectorWatch.h
index 0eb8079..e1cbbed 100644
--- a/Source/core/dom/CSSSelectorWatch.h
+++ b/Source/core/dom/CSSSelectorWatch.h
@@ -34,6 +34,7 @@
 #include "core/css/StyleRule.h"
 #include "core/dom/DocumentSupplementable.h"
 #include "platform/Timer.h"
+#include "wtf/HashCountedSet.h"
 #include "wtf/HashSet.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
@@ -63,7 +64,7 @@
 
     // Maps a CSS selector string with a -webkit-callback property to the number
     // of matching RenderStyle objects in this document.
-    HashMap<String, int> m_matchingCallbackSelectors;
+    HashCountedSet<String> m_matchingCallbackSelectors;
     // Selectors are relative to m_matchingCallbackSelectors's contents at
     // the previous call to selectorMatchChanged.
     HashSet<String> m_addedSelectors;
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index 305cad6..d7f818a 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -58,10 +58,10 @@
     document().didRemoveText(this, 0, oldLength);
 }
 
-String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
+String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& exceptionState)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("substringData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("substringData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return String();
     }
 
@@ -92,10 +92,10 @@
     // FIXME: Should we call textInserted here?
 }
 
-void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
+void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& exceptionState, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return;
     }
 
@@ -107,10 +107,10 @@
     document().didInsertText(this, offset, data.length());
 }
 
-void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
+void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& exceptionState, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return;
     }
 
@@ -128,10 +128,10 @@
     document().didRemoveText(this, offset, realCount);
 }
 
-void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
+void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& exceptionState)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("replaceData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("replaceData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return;
     }
 
diff --git a/Source/core/dom/Clipboard.cpp b/Source/core/dom/Clipboard.cpp
index d00860b..fc3808e 100644
--- a/Source/core/dom/Clipboard.cpp
+++ b/Source/core/dom/Clipboard.cpp
@@ -35,10 +35,10 @@
 #include "core/html/HTMLImageElement.h"
 #include "core/frame/Frame.h"
 #include "core/platform/DragImage.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderObject.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/clipboard/ClipboardMimeTypes.h"
 #include "platform/clipboard/ClipboardUtilities.h"
 
@@ -211,13 +211,13 @@
     return files.release();
 }
 
-void Clipboard::setDragImage(Element* image, int x, int y, ExceptionState& es)
+void Clipboard::setDragImage(Element* image, int x, int y, ExceptionState& exceptionState)
 {
     if (!isForDragAndDrop())
         return;
 
     if (!image) {
-        es.throwTypeError("setDragImage: Invalid first argument");
+        exceptionState.throwTypeError("setDragImage: Invalid first argument");
         return;
     }
     IntPoint location(x, y);
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index efe778d..a352dce 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -51,7 +51,6 @@
 
 static void dispatchChildInsertionEvents(Node&);
 static void dispatchChildRemovalEvents(Node&);
-static void updateTreeAfterInsertion(ContainerNode&, Node&);
 
 ChildNodesLazySnapshot* ChildNodesLazySnapshot::latestSnapshot = 0;
 
@@ -63,12 +62,12 @@
 static const char insertBeforeMethodName[] = "insertBefore";
 static const char replaceChildMethodName[] = "replaceChild";
 
-static void collectChildrenAndRemoveFromOldParent(Node& node, NodeVector& nodes, ExceptionState& es)
+static void collectChildrenAndRemoveFromOldParent(Node& node, NodeVector& nodes, ExceptionState& exceptionState)
 {
-    if (node.nodeType() != Node::DOCUMENT_FRAGMENT_NODE) {
+    if (!node.isDocumentFragment()) {
         nodes.append(&node);
         if (ContainerNode* oldParent = node.parentNode())
-            oldParent->removeChild(&node, es);
+            oldParent->removeChild(&node, exceptionState);
         return;
     }
     getChildNodes(node, nodes);
@@ -100,45 +99,38 @@
     removeDetachedChildren();
 }
 
-static inline bool isChildTypeAllowed(ContainerNode& newParent, Node& child)
+bool ContainerNode::isChildTypeAllowed(const Node& child) const
 {
     if (!child.isDocumentFragment())
-        return newParent.childTypeAllowed(child.nodeType());
+        return childTypeAllowed(child.nodeType());
 
     for (Node* node = child.firstChild(); node; node = node->nextSibling()) {
-        if (!newParent.childTypeAllowed(node->nodeType()))
+        if (!childTypeAllowed(node->nodeType()))
             return false;
     }
     return true;
 }
 
-static inline bool isInTemplateContent(const Node& node)
+bool ContainerNode::containsConsideringHostElements(const Node& newChild) const
 {
-    const Document& document = node.document();
-    return document == document.templateDocument();
+    if (isInShadowTree() || document() == document().templateDocument())
+        return newChild.containsIncludingHostElements(*this);
+    return newChild.contains(this);
 }
 
-static inline bool containsConsideringHostElements(const Node& newChild, const Node& newParent)
-{
-    return (newParent.isInShadowTree() || isInTemplateContent(newParent))
-        ? newChild.containsIncludingHostElements(newParent)
-        : newChild.contains(&newParent);
-}
-
-static inline bool checkAcceptChild(ContainerNode& newParent, Node* newChild, Node* oldChild, const char* method, ExceptionState& es)
+bool ContainerNode::checkAcceptChild(const Node* newChild, const Node* oldChild, const char* method, ExceptionState& exceptionState) const
 {
     // Not mentioned in spec: throw NotFoundError if newChild is null
     if (!newChild) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(method, "Node", "The new child element is null."));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(method, "Node", "The new child element is null."));
         return false;
     }
 
     // Use common case fast path if possible.
-    if ((newChild->isElementNode() || newChild->isTextNode()) && newParent.isElementNode()) {
-        ASSERT(!newParent.isDocumentTypeNode());
-        ASSERT(isChildTypeAllowed(newParent, *newChild));
-        if (containsConsideringHostElements(*newChild, newParent)) {
-            es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
+    if ((newChild->isElementNode() || newChild->isTextNode()) && isElementNode()) {
+        ASSERT(isChildTypeAllowed(*newChild));
+        if (containsConsideringHostElements(*newChild)) {
+            exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
             return false;
         }
         return true;
@@ -147,52 +139,40 @@
     // This should never happen, but also protect release builds from tree corruption.
     ASSERT(!newChild->isPseudoElement());
     if (newChild->isPseudoElement()) {
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element is a pseudo-element."));
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element is a pseudo-element."));
         return false;
     }
 
-    if (containsConsideringHostElements(*newChild, newParent)) {
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
+    if (containsConsideringHostElements(*newChild)) {
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
         return false;
     }
 
-    if (oldChild && newParent.isDocumentNode()) {
-        if (!toDocument(newParent).canReplaceChild(*newChild, *oldChild)) {
+    if (oldChild && isDocumentNode()) {
+        if (!toDocument(this)->canReplaceChild(*newChild, *oldChild)) {
             // FIXME: Adjust 'Document::canReplaceChild' to return some additional detail (or an error message).
-            es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "ContainerNode"));
+            exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "ContainerNode"));
             return false;
         }
-    } else if (!isChildTypeAllowed(newParent, *newChild)) {
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "Nodes of type '" + newChild->nodeName() + "' may not be inserted inside nodes of type '" + newParent.nodeName() + "'."));
+    } else if (!isChildTypeAllowed(*newChild)) {
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "Nodes of type '" + newChild->nodeName() + "' may not be inserted inside nodes of type '" + nodeName() + "'."));
         return false;
     }
 
     return true;
 }
 
-static inline bool checkAcceptChildGuaranteedNodeTypes(ContainerNode& newParent, Node& newChild, const char* method, ExceptionState& es)
+bool ContainerNode::checkAcceptChildGuaranteedNodeTypes(const Node& newChild, const char* method, ExceptionState& exceptionState) const
 {
-    ASSERT(!newParent.isDocumentTypeNode());
-    ASSERT(isChildTypeAllowed(newParent, newChild));
-    if (newChild.contains(&newParent)) {
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
+    ASSERT(isChildTypeAllowed(newChild));
+    if (newChild.contains(this)) {
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
         return false;
     }
-
     return true;
 }
 
-static inline bool checkAddChild(ContainerNode& newParent, Node* newChild, const char* method, ExceptionState& es)
-{
-    return checkAcceptChild(newParent, newChild, 0, method, es);
-}
-
-static inline bool checkReplaceChild(ContainerNode& newParent, Node* newChild, Node& oldChild, const char* method, ExceptionState& es)
-{
-    return checkAcceptChild(newParent, newChild, &oldChild, method, es);
-}
-
-void ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& es)
+void ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& exceptionState)
 {
     // Check that this node is not "floating".
     // If it is, it can be deleted as a side effect of sending mutation events.
@@ -202,18 +182,18 @@
 
     // insertBefore(node, 0) is equivalent to appendChild(node)
     if (!refChild) {
-        appendChild(newChild, es);
+        appendChild(newChild, exceptionState);
         return;
     }
 
     // Make sure adding the new child is OK.
-    if (!checkAddChild(*this, newChild.get(), insertBeforeMethodName, es))
+    if (!checkAcceptChild(newChild.get(), 0, insertBeforeMethodName, exceptionState))
         return;
     ASSERT(newChild);
 
     // NotFoundError: Raised if refChild is not a child of this node
     if (refChild->parentNode() != this) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(insertBeforeMethodName, "Node", "The node before which the new node is to be inserted is not a child of this node."));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(insertBeforeMethodName, "Node", "The node before which the new node is to be inserted is not a child of this node."));
         return;
     }
 
@@ -223,14 +203,14 @@
     RefPtr<Node> next = refChild;
 
     NodeVector targets;
-    collectChildrenAndRemoveFromOldParent(*newChild, targets, es);
-    if (es.hadException())
+    collectChildrenAndRemoveFromOldParent(*newChild, targets, exceptionState);
+    if (exceptionState.hadException())
         return;
     if (targets.isEmpty())
         return;
 
     // We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
-    if (!checkAcceptChildGuaranteedNodeTypes(*this, *newChild, insertBeforeMethodName, es))
+    if (!checkAcceptChildGuaranteedNodeTypes(*newChild, insertBeforeMethodName, exceptionState))
         return;
 
     InspectorInstrumentation::willInsertDOMNode(this);
@@ -253,7 +233,7 @@
 
         insertBeforeCommon(*next, child);
 
-        updateTreeAfterInsertion(*this, child);
+        updateTreeAfterInsertion(child);
     }
 
     dispatchSubtreeModifiedEvent();
@@ -308,7 +288,7 @@
     ChildNodeInsertionNotifier(*this).notify(*newChild);
 }
 
-void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& es)
+void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& exceptionState)
 {
     // Check that this node is not "floating".
     // If it is, it can be deleted as a side effect of sending mutation events.
@@ -320,17 +300,17 @@
         return;
 
     if (!oldChild) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(replaceChildMethodName, "Node", "The node to be replaced is null."));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(replaceChildMethodName, "Node", "The node to be replaced is null."));
         return;
     }
 
     // Make sure replacing the old child with the new is ok
-    if (!checkReplaceChild(*this, newChild.get(), *oldChild, replaceChildMethodName, es))
+    if (!checkAcceptChild(newChild.get(), oldChild, replaceChildMethodName, exceptionState))
         return;
 
     // NotFoundError: Raised if oldChild is not a child of this node.
     if (oldChild->parentNode() != this) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(replaceChildMethodName, "Node", "The node to be replaced is not a child of this node."));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(replaceChildMethodName, "Node", "The node to be replaced is not a child of this node."));
         return;
     }
 
@@ -340,24 +320,24 @@
 
     // Remove the node we're replacing
     RefPtr<Node> removedChild = oldChild;
-    removeChild(oldChild, es);
-    if (es.hadException())
+    removeChild(oldChild, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     if (next && (next->previousSibling() == newChild || next == newChild)) // nothing to do
         return;
 
     // Does this one more time because removeChild() fires a MutationEvent.
-    if (!checkReplaceChild(*this, newChild.get(), *oldChild, replaceChildMethodName, es))
+    if (!checkAcceptChild(newChild.get(), oldChild, replaceChildMethodName, exceptionState))
         return;
 
     NodeVector targets;
-    collectChildrenAndRemoveFromOldParent(*newChild, targets, es);
-    if (es.hadException())
+    collectChildrenAndRemoveFromOldParent(*newChild, targets, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     // Does this yet another check because collectChildrenAndRemoveFromOldParent() fires a MutationEvent.
-    if (!checkReplaceChild(*this, newChild.get(), *oldChild, replaceChildMethodName, es))
+    if (!checkAcceptChild(newChild.get(), oldChild, replaceChildMethodName, exceptionState))
         return;
 
     InspectorInstrumentation::willInsertDOMNode(this);
@@ -387,39 +367,37 @@
                 appendChildToContainer(child, *this);
         }
 
-        updateTreeAfterInsertion(*this, child);
+        updateTreeAfterInsertion(child);
     }
 
     dispatchSubtreeModifiedEvent();
 }
 
-static void willRemoveChild(Node& child)
+void ContainerNode::willRemoveChild(Node& child)
 {
-    ASSERT(child.parentNode());
-    ChildListMutationScope(*child.parentNode()).willRemoveChild(child);
+    ASSERT(child.parentNode() == this);
+    ChildListMutationScope(*this).willRemoveChild(child);
     child.notifyMutationObserversNodeWillDetach();
     dispatchChildRemovalEvents(child);
-    child.document().nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
+    document().nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
     ChildFrameDisconnector(child).disconnect();
 }
 
-static void willRemoveChildren(ContainerNode& container)
+void ContainerNode::willRemoveChildren()
 {
     NodeVector children;
-    getChildNodes(container, children);
+    getChildNodes(*this, children);
 
-    ChildListMutationScope mutation(container);
+    ChildListMutationScope mutation(*this);
     for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
         ASSERT(*it);
         Node& child = **it;
         mutation.willRemoveChild(child);
         child.notifyMutationObserversNodeWillDetach();
-
-        // fire removed from document mutation events.
         dispatchChildRemovalEvents(child);
     }
 
-    ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly);
+    ChildFrameDisconnector(*this).disconnect(ChildFrameDisconnector::DescendantsOnly);
 }
 
 void ContainerNode::disconnectDescendantFrames()
@@ -427,7 +405,7 @@
     ChildFrameDisconnector(*this).disconnect();
 }
 
-void ContainerNode::removeChild(Node* oldChild, ExceptionState& es)
+void ContainerNode::removeChild(Node* oldChild, ExceptionState& exceptionState)
 {
     // Check that this node is not "floating".
     // If it is, it can be deleted as a side effect of sending mutation events.
@@ -437,7 +415,7 @@
 
     // NotFoundError: Raised if oldChild is not a child of this node.
     if (!oldChild || oldChild->parentNode() != this) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is not a child of this node."));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is not a child of this node."));
         return;
     }
 
@@ -451,7 +429,7 @@
     // Events fired when blurring currently focused node might have moved this
     // child into a different parent.
     if (child->parentNode() != this) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is no longer a child of this node. Perhaps it was moved in a 'blur' event handler?"));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is no longer a child of this node. Perhaps it was moved in a 'blur' event handler?"));
         return;
     }
 
@@ -459,7 +437,7 @@
 
     // Mutation events might have moved this child into a different parent.
     if (child->parentNode() != this) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is no longer a child of this node. Perhaps it was moved in response to a mutation?"));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is no longer a child of this node. Perhaps it was moved in response to a mutation?"));
         return;
     }
 
@@ -481,8 +459,7 @@
 
     ASSERT(oldChild.parentNode() == this);
 
-    // Remove from rendering tree
-    if (oldChild.confusingAndOftenMisusedAttached())
+    if (!oldChild.needsAttach())
         oldChild.detach();
 
     if (nextChild)
@@ -535,7 +512,7 @@
 
     // Do any prep work needed before actually starting to detach
     // and remove... e.g. stop loading frames, fire unload events.
-    willRemoveChildren(*this);
+    willRemoveChildren();
 
     {
         // Removing focus can cause frames to load, either via events (focusout, blur)
@@ -574,7 +551,7 @@
     dispatchSubtreeModifiedEvent();
 }
 
-void ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionState& es)
+void ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionState& exceptionState)
 {
     RefPtr<ContainerNode> protect(this);
 
@@ -583,7 +560,7 @@
     ASSERT(refCount() || parentOrShadowHostNode());
 
     // Make sure adding the new child is ok
-    if (!checkAddChild(*this, newChild.get(), appendChildMethodName, es))
+    if (!checkAcceptChild(newChild.get(), 0, appendChildMethodName, exceptionState))
         return;
     ASSERT(newChild);
 
@@ -591,15 +568,15 @@
         return;
 
     NodeVector targets;
-    collectChildrenAndRemoveFromOldParent(*newChild, targets, es);
-    if (es.hadException())
+    collectChildrenAndRemoveFromOldParent(*newChild, targets, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     if (targets.isEmpty())
         return;
 
     // We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
-    if (!checkAcceptChildGuaranteedNodeTypes(*this, *newChild, appendChildMethodName, es))
+    if (!checkAcceptChildGuaranteedNodeTypes(*newChild, appendChildMethodName, exceptionState))
         return;
 
     InspectorInstrumentation::willInsertDOMNode(this);
@@ -624,7 +601,7 @@
             appendChildToContainer(child, *this);
         }
 
-        updateTreeAfterInsertion(*this, child);
+        updateTreeAfterInsertion(child);
     }
 
     dispatchSubtreeModifiedEvent();
@@ -676,13 +653,17 @@
     if (!changedByParser && childCountDelta)
         document().updateRangesAfterChildrenChanged(this);
     invalidateNodeListCachesInAncestors();
+    if (childCountDelta > 0 && inActiveDocument()) {
+        setChildNeedsStyleRecalc();
+        markAncestorsWithChildNeedsStyleRecalc();
+    }
 }
 
 void ContainerNode::cloneChildNodes(ContainerNode *clone)
 {
-    TrackExceptionState es;
-    for (Node* n = firstChild(); n && !es.hadException(); n = n->nextSibling())
-        clone->appendChild(n->cloneNode(true), es);
+    TrackExceptionState exceptionState;
+    for (Node* n = firstChild(); n && !exceptionState.hadException(); n = n->nextSibling())
+        clone->appendChild(n->cloneNode(true), exceptionState);
 }
 
 
@@ -818,6 +799,22 @@
     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
 }
 
+// This is used by FrameSelection to denote when the active-state of the page has changed
+// independent of the focused element changing.
+void ContainerNode::focusStateChanged()
+{
+    // If we're just changing the window's active state and the focused node has no
+    // renderer we can just ignore the state change.
+    if (!renderer())
+        return;
+    // FIXME: This could probably setNeedsStyleRecalc(LocalStyleChange) in the affectedByFocus case
+    // and only setNeedsStyleRecalc(SubtreeStyleChange) in the childrenAffectedByFocus case.
+    if (renderStyle()->affectedByFocus() || (isElementNode() && toElement(this)->childrenAffectedByFocus()))
+        setNeedsStyleRecalc();
+    if (renderer() && renderer()->style()->hasAppearance())
+        RenderTheme::theme().stateChanged(renderer(), FocusState);
+}
+
 void ContainerNode::setFocus(bool received)
 {
     if (focused() == received)
@@ -825,18 +822,20 @@
 
     Node::setFocus(received);
 
-    // note that we need to recalc the style
-    setNeedsStyleRecalc();
+    focusStateChanged();
+    // If :focus sets display: none, we lose focus but still need to recalc our style.
+    if (!renderer() && !received)
+        setNeedsStyleRecalc();
 }
 
-void ContainerNode::setActive(bool down, bool pause)
+void ContainerNode::setActive(bool down)
 {
-    if (down == active()) return;
+    if (down == active())
+        return;
 
     Node::setActive(down);
 
-    // note that we need to recalc the style
-    // FIXME: Move to Element
+    // FIXME: Why does this not need to handle the display: none transition like :hover does?
     if (renderer()) {
         if (renderStyle()->affectedByActive() || (isElementNode() && toElement(this)->childrenAffectedByActive()))
             setNeedsStyleRecalc();
@@ -847,24 +846,18 @@
 
 void ContainerNode::setHovered(bool over)
 {
-    if (over == hovered()) return;
+    if (over == hovered())
+        return;
 
     Node::setHovered(over);
 
+    // If :hover sets display: none we lose our hover but still need to recalc our style.
     if (!renderer()) {
-        // When setting hover to false, the style needs to be recalc'd even when
-        // there's no renderer (imagine setting display:none in the :hover class,
-        // if a nil renderer would prevent this element from recalculating its
-        // style, it would never go back to its normal style and remain
-        // stuck in its hovered style).
         if (!over)
             setNeedsStyleRecalc();
-
         return;
     }
 
-    // note that we need to recalc the style
-    // FIXME: Move to Element
     if (renderer()) {
         if (renderStyle()->affectedByHover() || (isElementNode() && toElement(this)->childrenAffectedByHover()))
             setNeedsStyleRecalc();
@@ -880,7 +873,7 @@
 
 Element* ContainerNode::firstElementChild() const
 {
-    return ElementTraversal::firstWithin(this);
+    return ElementTraversal::firstWithin(*this);
 }
 
 Element* ContainerNode::lastElementChild() const
@@ -935,7 +928,7 @@
 
     // dispatch the DOMNodeInsertedIntoDocument event to all descendants
     if (c->inDocument() && document->hasListenerType(Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER)) {
-        for (; c; c = NodeTraversal::next(c.get(), &child))
+        for (; c; c = NodeTraversal::next(*c, &child))
             c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeInsertedIntoDocument, false));
     }
 }
@@ -963,21 +956,21 @@
     // dispatch the DOMNodeRemovedFromDocument event to all descendants
     if (c->inDocument() && document->hasListenerType(Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER)) {
         NodeChildRemovalTracker scope(child);
-        for (; c; c = NodeTraversal::next(c.get(), &child))
+        for (; c; c = NodeTraversal::next(*c, &child))
             c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeRemovedFromDocument, false));
     }
 }
 
-static void updateTreeAfterInsertion(ContainerNode& parent, Node& child)
+void ContainerNode::updateTreeAfterInsertion(Node& child)
 {
-    ASSERT(parent.refCount());
+    ASSERT(refCount());
     ASSERT(child.refCount());
 
-    ChildListMutationScope(parent).childAdded(child);
+    ChildListMutationScope(*this).childAdded(child);
 
-    parent.childrenChanged(false, child.previousSibling(), child.nextSibling(), 1);
+    childrenChanged(false, child.previousSibling(), child.nextSibling(), 1);
 
-    ChildNodeInsertionNotifier(parent).notify(child);
+    ChildNodeInsertionNotifier(*this).notify(child);
 
     dispatchChildInsertionEvents(child);
 }
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index e7d067c..3b55990 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -117,7 +117,8 @@
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual LayoutRect boundingBox() const OVERRIDE;
     virtual void setFocus(bool) OVERRIDE;
-    virtual void setActive(bool active = true, bool pause = false) OVERRIDE;
+    void focusStateChanged();
+    virtual void setActive(bool = true) OVERRIDE;
     virtual void setHovered(bool = true) OVERRIDE;
 
     // -----------------------------------------------------------------------------
@@ -147,6 +148,14 @@
 private:
     void removeBetween(Node* previousChild, Node* nextChild, Node& oldChild);
     void insertBeforeCommon(Node& nextChild, Node& oldChild);
+    void updateTreeAfterInsertion(Node& child);
+    void willRemoveChildren();
+    void willRemoveChild(Node& child);
+
+    inline bool checkAcceptChildGuaranteedNodeTypes(const Node& newChild, const char* method, ExceptionState&) const;
+    inline bool checkAcceptChild(const Node* newChild, const Node* oldChild, const char* method, ExceptionState&) const;
+    inline bool containsConsideringHostElements(const Node&) const;
+    inline bool isChildTypeAllowed(const Node& child) const;
 
     void attachChildren(const AttachContext& = AttachContext());
     void detachChildren(const AttachContext& = AttachContext());
diff --git a/Source/core/dom/ContainerNodeAlgorithms.h b/Source/core/dom/ContainerNodeAlgorithms.h
index c3cd3bf..b863c25 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.h
+++ b/Source/core/dom/ContainerNodeAlgorithms.h
@@ -224,14 +224,6 @@
     else if (node.isContainerNode())
         notifyNodeInsertedIntoTree(toContainerNode(node));
 
-    // Script runs in didNotifySubtreeInsertions so we should lazy attach before
-    // to ensure that triggering a style recalc in script attaches all nodes that
-    // were inserted.
-    // FIXME: We should merge the lazy attach logic into the tree traversal in
-    // notifyNodeInsertedIntoDocument.
-    if (!node.confusingAndOftenMisusedAttached() && node.parentNode() && node.parentNode()->confusingAndOftenMisusedAttached())
-        node.lazyAttach();
-
     for (size_t i = 0; i < m_postInsertionNotificationTargets.size(); ++i) {
         Node* targetNode = m_postInsertionNotificationTargets[i].get();
         if (targetNode->inDocument())
diff --git a/Source/core/dom/ContextFeatures.cpp b/Source/core/dom/ContextFeatures.cpp
index 47af9c0..86b980e 100644
--- a/Source/core/dom/ContextFeatures.cpp
+++ b/Source/core/dom/ContextFeatures.cpp
@@ -46,8 +46,8 @@
 
 ContextFeatures* ContextFeatures::defaultSwitch()
 {
-    DEFINE_STATIC_LOCAL(RefPtr<ContextFeatures>, instance, (ContextFeatures::create(ContextFeaturesClient::empty())));
-    return instance.get();
+    DEFINE_STATIC_REF(ContextFeatures, instance, (ContextFeatures::create(ContextFeaturesClient::empty())));
+    return instance;
 }
 
 bool ContextFeatures::dialogElementEnabled(Document* document)
diff --git a/Source/core/dom/ContextLifecycleNotifier.cpp b/Source/core/dom/ContextLifecycleNotifier.cpp
index 7b96fbe..048978c 100644
--- a/Source/core/dom/ContextLifecycleNotifier.cpp
+++ b/Source/core/dom/ContextLifecycleNotifier.cpp
@@ -44,7 +44,7 @@
 
 void ContextLifecycleNotifier::addObserver(ContextLifecycleNotifier::Observer* observer)
 {
-    LifecycleNotifier::addObserver(observer);
+    LifecycleNotifier<ExecutionContext>::addObserver(observer);
 
     RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
     if (observer->observerType() == Observer::ActiveDOMObjectType) {
@@ -55,7 +55,7 @@
 
 void ContextLifecycleNotifier::removeObserver(ContextLifecycleNotifier::Observer* observer)
 {
-    LifecycleNotifier::removeObserver(observer);
+    LifecycleNotifier<ExecutionContext>::removeObserver(observer);
 
     RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
     if (observer->observerType() == Observer::ActiveDOMObjectType) {
diff --git a/Source/core/dom/DOMError.idl b/Source/core/dom/DOMError.idl
index 83522fa..b2ea60f 100644
--- a/Source/core/dom/DOMError.idl
+++ b/Source/core/dom/DOMError.idl
@@ -27,7 +27,7 @@
  */
 [
     NoInterfaceObject
-] interface  DOMError {
+] interface DOMError {
     readonly attribute DOMString name;
     readonly attribute DOMString message;
   };
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 756cbb1..83885b3 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -47,13 +47,13 @@
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/MediaPlayer.h"
-#include "core/plugins/PluginData.h"
 #include "core/svg/SVGDocument.h"
 #include "platform/ContentType.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/graphics/media/MediaPlayer.h"
+#include "platform/plugins/PluginData.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/StdLibExtras.h"
 
 namespace WebCore {
@@ -161,7 +161,7 @@
         && svgFeatures.contains(feature.right(feature.length() - 35));
 }
 
-DOMImplementation::DOMImplementation(Document* document)
+DOMImplementation::DOMImplementation(Document& document)
     : m_document(document)
 {
     ScriptWrappable::init(this);
@@ -179,13 +179,13 @@
 }
 
 PassRefPtr<DocumentType> DOMImplementation::createDocumentType(const String& qualifiedName,
-    const String& publicId, const String& systemId, ExceptionState& es)
+    const String& publicId, const String& systemId, ExceptionState& exceptionState)
 {
     String prefix, localName;
-    if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
+    if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
-    return DocumentType::create(m_document, qualifiedName, publicId, systemId);
+    return DocumentType::create(&m_document, qualifiedName, publicId, systemId);
 }
 
 DOMImplementation* DOMImplementation::getInterface(const String& /*feature*/)
@@ -194,25 +194,25 @@
 }
 
 PassRefPtr<Document> DOMImplementation::createDocument(const String& namespaceURI,
-    const String& qualifiedName, DocumentType* doctype, ExceptionState& es)
+    const String& qualifiedName, DocumentType* doctype, ExceptionState& exceptionState)
 {
     RefPtr<Document> doc;
-    DocumentInit init = DocumentInit::fromContext(m_document->contextDocument());
+    DocumentInit init = DocumentInit::fromContext(m_document.contextDocument());
     if (namespaceURI == SVGNames::svgNamespaceURI) {
         doc = SVGDocument::create(init);
     } else if (namespaceURI == HTMLNames::xhtmlNamespaceURI) {
-        doc = Document::createXHTML(init.withRegistrationContext(m_document->registrationContext()));
+        doc = Document::createXHTML(init.withRegistrationContext(m_document.registrationContext()));
     } else {
         doc = Document::create(init);
     }
 
-    doc->setSecurityOrigin(m_document->securityOrigin()->isolatedCopy());
-    doc->setContextFeatures(m_document->contextFeatures());
+    doc->setSecurityOrigin(m_document.securityOrigin()->isolatedCopy());
+    doc->setContextFeatures(m_document.contextFeatures());
 
     RefPtr<Node> documentElement;
     if (!qualifiedName.isEmpty()) {
-        documentElement = doc->createElementNS(namespaceURI, qualifiedName, es);
-        if (es.hadException())
+        documentElement = doc->createElementNS(namespaceURI, qualifiedName, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
 
@@ -307,15 +307,15 @@
 
 PassRefPtr<HTMLDocument> DOMImplementation::createHTMLDocument(const String& title)
 {
-    DocumentInit init = DocumentInit::fromContext(m_document->contextDocument())
-        .withRegistrationContext(m_document->registrationContext());
+    DocumentInit init = DocumentInit::fromContext(m_document.contextDocument())
+        .withRegistrationContext(m_document.registrationContext());
     RefPtr<HTMLDocument> d = HTMLDocument::create(init);
     d->open();
     d->write("<!doctype html><html><body></body></html>");
     if (!title.isNull())
         d->setTitle(title);
-    d->setSecurityOrigin(m_document->securityOrigin()->isolatedCopy());
-    d->setContextFeatures(m_document->contextFeatures());
+    d->setSecurityOrigin(m_document.securityOrigin()->isolatedCopy());
+    d->setContextFeatures(m_document.contextFeatures());
     return d.release();
 }
 
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index 5fb1f51..76852d3 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -42,11 +42,11 @@
 class DOMImplementation : public ScriptWrappable {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<DOMImplementation> create(Document* document) { return adoptPtr(new DOMImplementation(document)); }
+    static PassOwnPtr<DOMImplementation> create(Document& document) { return adoptPtr(new DOMImplementation(document)); }
 
-    void ref() { m_document->ref(); }
-    void deref() { m_document->deref(); }
-    Document* document() { return m_document; }
+    void ref() { m_document.ref(); }
+    void deref() { m_document.deref(); }
+    Document* document() { return &m_document; }
 
     // DOM methods & attributes for DOMImplementation
     static bool hasFeature(const String& feature, const String& version);
@@ -69,9 +69,9 @@
     static bool isTextMIMEType(const String& MIMEType);
 
 private:
-    explicit DOMImplementation(Document*);
+    explicit DOMImplementation(Document&);
 
-    Document* m_document;
+    Document& m_document;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/DOMImplementation.idl b/Source/core/dom/DOMImplementation.idl
index c110cb4..9c42ec0 100644
--- a/Source/core/dom/DOMImplementation.idl
+++ b/Source/core/dom/DOMImplementation.idl
@@ -19,7 +19,7 @@
  */
 
 [
-    GenerateIsReachable=document
+    GenerateVisitDOMWrapper=document,
 ] interface DOMImplementation {
 
     // DOM Level 1
diff --git a/Source/core/dom/DOMNamedFlowCollection.cpp b/Source/core/dom/DOMNamedFlowCollection.cpp
index 0be5818..695bbbc 100644
--- a/Source/core/dom/DOMNamedFlowCollection.cpp
+++ b/Source/core/dom/DOMNamedFlowCollection.cpp
@@ -61,7 +61,7 @@
 
 PassRefPtr<NamedFlow> DOMNamedFlowCollection::namedItem(const AtomicString& name) const
 {
-    DOMNamedFlowSet::const_iterator it = m_namedFlows.find<String, DOMNamedFlowHashTranslator>(name);
+    DOMNamedFlowSet::const_iterator it = m_namedFlows.find<DOMNamedFlowHashTranslator, String>(name);
     if (it != m_namedFlows.end())
         return *it;
     return 0;
diff --git a/Source/core/dom/DOMSettableTokenList.cpp b/Source/core/dom/DOMSettableTokenList.cpp
index 10692ca..2d69533 100644
--- a/Source/core/dom/DOMSettableTokenList.cpp
+++ b/Source/core/dom/DOMSettableTokenList.cpp
@@ -52,9 +52,9 @@
     return m_tokens.contains(token);
 }
 
-void DOMSettableTokenList::add(const Vector<String>& tokens, ExceptionState& es)
+void DOMSettableTokenList::add(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
-    DOMTokenList::add(tokens, es);
+    DOMTokenList::add(tokens, exceptionState);
 
     for (size_t i = 0; i < tokens.size(); ++i) {
         if (m_tokens.isNull())
@@ -73,9 +73,9 @@
         m_tokens.add(token);
 }
 
-void DOMSettableTokenList::remove(const Vector<String>& tokens, ExceptionState& es)
+void DOMSettableTokenList::remove(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
-    DOMTokenList::remove(tokens, es);
+    DOMTokenList::remove(tokens, exceptionState);
     for (size_t i = 0; i < tokens.size(); ++i)
         m_tokens.remove(tokens[i]);
 }
diff --git a/Source/core/dom/DOMStringMap.h b/Source/core/dom/DOMStringMap.h
index cbcc402..22ce974 100644
--- a/Source/core/dom/DOMStringMap.h
+++ b/Source/core/dom/DOMStringMap.h
@@ -49,18 +49,18 @@
     virtual bool contains(const String& name) = 0;
     virtual void setItem(const String& name, const String& value, ExceptionState&) = 0;
     virtual void deleteItem(const String& name, ExceptionState&) = 0;
-    bool anonymousNamedSetter(const String& name, const String& value, ExceptionState& es)
+    bool anonymousNamedSetter(const String& name, const String& value, ExceptionState& exceptionState)
     {
-        setItem(name, value, es);
+        setItem(name, value, exceptionState);
         return true;
     }
     bool anonymousNamedDeleter(const AtomicString& name, ExceptionState&)
     {
         // FIXME: Remove ExceptionState parameter.
 
-        TrackExceptionState es;
-        deleteItem(name, es);
-        bool result = !es.hadException();
+        TrackExceptionState exceptionState;
+        deleteItem(name, exceptionState);
+        bool result = !exceptionState.hadException();
         // DOMStringMap deleter should ignore exception.
         // Behavior of Firefox and Opera are same.
         // delete document.body.dataset["-foo"] // false instead of DOM Exception 12
@@ -73,6 +73,19 @@
     }
     bool namedPropertyQuery(const AtomicString&, ExceptionState&);
 
+    String anonymousIndexedGetter(uint32_t index)
+    {
+        return item(String::number(index));
+    }
+    bool anonymousIndexedSetter(uint32_t index, const String& value, ExceptionState& exceptionState)
+    {
+        return anonymousNamedSetter(String::number(index), value, exceptionState);
+    }
+    bool anonymousIndexedDeleter(uint32_t index, ExceptionState& exceptionState)
+    {
+        return anonymousNamedDeleter(AtomicString::number(index), exceptionState);
+    }
+
     virtual Element* element() = 0;
 
 protected:
diff --git a/Source/core/dom/DOMStringMap.idl b/Source/core/dom/DOMStringMap.idl
index 5b09c33..fcbbf89 100644
--- a/Source/core/dom/DOMStringMap.idl
+++ b/Source/core/dom/DOMStringMap.idl
@@ -24,10 +24,13 @@
  */
 
 [
-    GenerateIsReachable=element
+    GenerateVisitDOMWrapper=element,
 ] interface DOMStringMap {
+    [ImplementedAs=anonymousIndexedGetter, NotEnumerable] getter DOMString (unsigned long index);
+    [ImplementedAs=anonymousIndexedSetter, RaisesException, NotEnumerable] setter DOMString (unsigned long index, DOMString value);
+    [ImplementedAs=anonymousIndexedDeleter, RaisesException, NotEnumerable] deleter boolean (unsigned long index);
     [ImplementedAs=item, OverrideBuiltins] getter DOMString (DOMString name);
-    [ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
     [ImplementedAs=anonymousNamedSetter, RaisesException, OverrideBuiltins] setter DOMString (DOMString name, DOMString value);
+    [ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
 };
 
diff --git a/Source/core/dom/DOMTokenList.cpp b/Source/core/dom/DOMTokenList.cpp
index 68bf91c..fc815ee 100644
--- a/Source/core/dom/DOMTokenList.cpp
+++ b/Source/core/dom/DOMTokenList.cpp
@@ -33,17 +33,17 @@
 
 namespace WebCore {
 
-bool DOMTokenList::validateToken(const AtomicString& token, const char* method, ExceptionState& es)
+bool DOMTokenList::validateToken(const AtomicString& token, const char* method, ExceptionState& exceptionState)
 {
     if (token.isEmpty()) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute(method, "DOMTokenList", "The token provided must not be empty."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute(method, "DOMTokenList", "The token provided must not be empty."));
         return false;
     }
 
     unsigned length = token.length();
     for (unsigned i = 0; i < length; ++i) {
         if (isHTMLSpace<UChar>(token[i])) {
-            es.throwDOMException(InvalidCharacterError, ExceptionMessages::failedToExecute(method, "DOMTokenList", "The token provided ('" + token + "') contains HTML space characters, which are not valid in tokens."));
+            exceptionState.throwDOMException(InvalidCharacterError, ExceptionMessages::failedToExecute(method, "DOMTokenList", "The token provided ('" + token + "') contains HTML space characters, which are not valid in tokens."));
             return false;
         }
     }
@@ -51,36 +51,36 @@
     return true;
 }
 
-bool DOMTokenList::validateTokens(const Vector<String>& tokens, const char* method, ExceptionState& es)
+bool DOMTokenList::validateTokens(const Vector<String>& tokens, const char* method, ExceptionState& exceptionState)
 {
     for (size_t i = 0; i < tokens.size(); ++i) {
-        if (!validateToken(tokens[i], method, es))
+        if (!validateToken(tokens[i], method, exceptionState))
             return false;
     }
 
     return true;
 }
 
-bool DOMTokenList::contains(const AtomicString& token, ExceptionState& es) const
+bool DOMTokenList::contains(const AtomicString& token, ExceptionState& exceptionState) const
 {
-    if (!validateToken(token, "contains", es))
+    if (!validateToken(token, "contains", exceptionState))
         return false;
     return containsInternal(token);
 }
 
-void DOMTokenList::add(const AtomicString& token, ExceptionState& es)
+void DOMTokenList::add(const AtomicString& token, ExceptionState& exceptionState)
 {
     Vector<String> tokens;
     tokens.append(token.string());
-    add(tokens, es);
+    add(tokens, exceptionState);
 }
 
-void DOMTokenList::add(const Vector<String>& tokens, ExceptionState& es)
+void DOMTokenList::add(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
     Vector<String> filteredTokens;
     filteredTokens.reserveCapacity(tokens.size());
     for (size_t i = 0; i < tokens.size(); ++i) {
-        if (!validateToken(tokens[i], "add", es))
+        if (!validateToken(tokens[i], "add", exceptionState))
             return;
         if (containsInternal(tokens[i]))
             continue;
@@ -95,16 +95,16 @@
     setValue(addTokens(value(), filteredTokens));
 }
 
-void DOMTokenList::remove(const AtomicString& token, ExceptionState& es)
+void DOMTokenList::remove(const AtomicString& token, ExceptionState& exceptionState)
 {
     Vector<String> tokens;
     tokens.append(token.string());
-    remove(tokens, es);
+    remove(tokens, exceptionState);
 }
 
-void DOMTokenList::remove(const Vector<String>& tokens, ExceptionState& es)
+void DOMTokenList::remove(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
-    if (!validateTokens(tokens, "remove", es))
+    if (!validateTokens(tokens, "remove", exceptionState))
         return;
 
     // Check using containsInternal first since it is a lot faster than going
@@ -121,9 +121,9 @@
         setValue(removeTokens(value(), tokens));
 }
 
-bool DOMTokenList::toggle(const AtomicString& token, ExceptionState& es)
+bool DOMTokenList::toggle(const AtomicString& token, ExceptionState& exceptionState)
 {
-    if (!validateToken(token, "toggle", es))
+    if (!validateToken(token, "toggle", exceptionState))
         return false;
 
     if (containsInternal(token)) {
@@ -134,9 +134,9 @@
     return true;
 }
 
-bool DOMTokenList::toggle(const AtomicString& token, bool force, ExceptionState& es)
+bool DOMTokenList::toggle(const AtomicString& token, bool force, ExceptionState& exceptionState)
 {
-    if (!validateToken(token, "toggle", es))
+    if (!validateToken(token, "toggle", exceptionState))
         return false;
 
     if (force)
diff --git a/Source/core/dom/DOMTokenList.idl b/Source/core/dom/DOMTokenList.idl
index 9aef382..9830b7e 100644
--- a/Source/core/dom/DOMTokenList.idl
+++ b/Source/core/dom/DOMTokenList.idl
@@ -23,7 +23,7 @@
  */
 
 [
-    GenerateIsReachable=element
+    GenerateVisitDOMWrapper=element,
 ] interface DOMTokenList {
     readonly attribute unsigned long length;
     [TreatReturnedNullStringAs=Null] getter DOMString item(unsigned long index);
diff --git a/Source/core/dom/DOMURL.cpp b/Source/core/dom/DOMURL.cpp
index 0440c0d..a61485e 100644
--- a/Source/core/dom/DOMURL.cpp
+++ b/Source/core/dom/DOMURL.cpp
@@ -35,20 +35,20 @@
 #include "core/fileapi/Blob.h"
 #include "core/html/PublicURLManager.h"
 #include "platform/blob/BlobURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/MainThread.h"
 
 namespace WebCore {
 
-DOMURL::DOMURL(const String& url, const KURL& base, ExceptionState& es)
+DOMURL::DOMURL(const String& url, const KURL& base, ExceptionState& exceptionState)
 {
     ScriptWrappable::init(this);
     if (!base.isValid())
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToConstruct("URL", "Invalid base URL"));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToConstruct("URL", "Invalid base URL"));
 
     m_url = KURL(base, url);
     if (!m_url.isValid())
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToConstruct("URL", "Invalid URL"));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToConstruct("URL", "Invalid URL"));
 }
 
 void DOMURL::setInput(const String& value)
diff --git a/Source/core/dom/DOMURL.h b/Source/core/dom/DOMURL.h
index 1736990..2b112f7 100644
--- a/Source/core/dom/DOMURL.h
+++ b/Source/core/dom/DOMURL.h
@@ -29,7 +29,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/DOMURLUtils.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -45,18 +45,18 @@
 class DOMURL FINAL : public ScriptWrappable, public DOMURLUtils, public RefCounted<DOMURL> {
 
 public:
-    static PassRefPtr<DOMURL> create(const String& url, ExceptionState& es)
+    static PassRefPtr<DOMURL> create(const String& url, ExceptionState& exceptionState)
     {
-        return adoptRef(new DOMURL(url, blankURL(), es));
+        return adoptRef(new DOMURL(url, blankURL(), exceptionState));
     }
-    static PassRefPtr<DOMURL> create(const String& url, const String& base, ExceptionState& es)
+    static PassRefPtr<DOMURL> create(const String& url, const String& base, ExceptionState& exceptionState)
     {
-        return adoptRef(new DOMURL(url, KURL(KURL(), base), es));
+        return adoptRef(new DOMURL(url, KURL(KURL(), base), exceptionState));
     }
-    static PassRefPtr<DOMURL> create(const String& url, PassRefPtr<DOMURL> base, ExceptionState& es)
+    static PassRefPtr<DOMURL> create(const String& url, PassRefPtr<DOMURL> base, ExceptionState& exceptionState)
     {
         ASSERT(base);
-        return adoptRef(new DOMURL(url, base->m_url, es));
+        return adoptRef(new DOMURL(url, base->m_url, exceptionState));
     }
 
     static String createObjectURL(ExecutionContext*, Blob*);
diff --git a/Source/core/dom/DOMURLUtils.cpp b/Source/core/dom/DOMURLUtils.cpp
index 77051f7..7e1fa19 100644
--- a/Source/core/dom/DOMURLUtils.cpp
+++ b/Source/core/dom/DOMURLUtils.cpp
@@ -27,7 +27,7 @@
 #include "config.h"
 #include "core/dom/DOMURLUtils.h"
 
-#include "weborigin/KnownPorts.h"
+#include "platform/weborigin/KnownPorts.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DOMURLUtilsReadOnly.cpp b/Source/core/dom/DOMURLUtilsReadOnly.cpp
index 933d76f..15b1268 100644
--- a/Source/core/dom/DOMURLUtilsReadOnly.cpp
+++ b/Source/core/dom/DOMURLUtilsReadOnly.cpp
@@ -27,8 +27,8 @@
 #include "config.h"
 #include "core/dom/DOMURLUtilsReadOnly.h"
 
-#include "weborigin/KnownPorts.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/KnownPorts.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DOMURLUtilsReadOnly.h b/Source/core/dom/DOMURLUtilsReadOnly.h
index 9ddfd40..36d6085 100644
--- a/Source/core/dom/DOMURLUtilsReadOnly.h
+++ b/Source/core/dom/DOMURLUtilsReadOnly.h
@@ -27,7 +27,7 @@
 #ifndef DOMURLUtilsReadOnly_h
 #define DOMURLUtilsReadOnly_h
 
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/dom/DataTransferItemList.cpp b/Source/core/dom/DataTransferItemList.cpp
index 7e751d3..d4f44d2 100644
--- a/Source/core/dom/DataTransferItemList.cpp
+++ b/Source/core/dom/DataTransferItemList.cpp
@@ -62,10 +62,10 @@
     return DataTransferItem::create(m_clipboard, item);
 }
 
-void DataTransferItemList::deleteItem(unsigned long index, ExceptionState& es)
+void DataTransferItemList::deleteItem(unsigned long index, ExceptionState& exceptionState)
 {
     if (!m_clipboard->canWriteData()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
     m_dataObject->deleteItem(index);
@@ -78,11 +78,11 @@
     m_dataObject->clearAll();
 }
 
-PassRefPtr<DataTransferItem> DataTransferItemList::add(const String& data, const String& type, ExceptionState& es)
+PassRefPtr<DataTransferItem> DataTransferItemList::add(const String& data, const String& type, ExceptionState& exceptionState)
 {
     if (!m_clipboard->canWriteData())
         return 0;
-    RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(data, type, es);
+    RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(data, type, exceptionState);
     if (!item)
         return 0;
     return DataTransferItem::create(m_clipboard, item);
diff --git a/Source/core/dom/DatasetDOMStringMap.cpp b/Source/core/dom/DatasetDOMStringMap.cpp
index 309dabf..9215319 100644
--- a/Source/core/dom/DatasetDOMStringMap.cpp
+++ b/Source/core/dom/DatasetDOMStringMap.cpp
@@ -83,7 +83,7 @@
     unsigned p = 0;
     bool wordBoundary = false;
     while (a < attributeLength && p < propertyLength) {
-        if (attributeName[a] == '-' && a + 1 < attributeLength && attributeName[a + 1] != '-')
+        if (attributeName[a] == '-' && a + 1 < attributeLength && isASCIILower(attributeName[a + 1]))
             wordBoundary = true;
         else {
             if ((wordBoundary ? toASCIIUpper(attributeName[a]) : attributeName[a]) != propertyName[p])
@@ -178,20 +178,20 @@
     return false;
 }
 
-void DatasetDOMStringMap::setItem(const String& name, const String& value, ExceptionState& es)
+void DatasetDOMStringMap::setItem(const String& name, const String& value, ExceptionState& exceptionState)
 {
     if (!isValidPropertyName(name)) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToSet(name, "DOMStringMap", "'" + name + "' is not a valid property name."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet(name, "DOMStringMap", "'" + name + "' is not a valid property name."));
         return;
     }
 
-    m_element->setAttribute(convertPropertyNameToAttributeName(name), value, es);
+    m_element->setAttribute(convertPropertyNameToAttributeName(name), value, exceptionState);
 }
 
-void DatasetDOMStringMap::deleteItem(const String& name, ExceptionState& es)
+void DatasetDOMStringMap::deleteItem(const String& name, ExceptionState& exceptionState)
 {
     if (!isValidPropertyName(name)) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToDelete(name, "DOMStringMap", "'" + name + "' is not a valid property name."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToDelete(name, "DOMStringMap", "'" + name + "' is not a valid property name."));
         return;
     }
 
diff --git a/Source/core/dom/DecodedDataDocumentParser.cpp b/Source/core/dom/DecodedDataDocumentParser.cpp
index c734580..7f3c01f 100644
--- a/Source/core/dom/DecodedDataDocumentParser.cpp
+++ b/Source/core/dom/DecodedDataDocumentParser.cpp
@@ -27,60 +27,86 @@
 #include "core/dom/DecodedDataDocumentParser.h"
 
 #include "core/dom/Document.h"
+#include "core/dom/DocumentEncodingData.h"
 #include "core/fetch/TextResourceDecoder.h"
 
 namespace WebCore {
 
 DecodedDataDocumentParser::DecodedDataDocumentParser(Document* document)
     : DocumentParser(document)
+    , m_hasAppendedData(false)
 {
 }
 
-size_t DecodedDataDocumentParser::appendBytes(const char* data, size_t length)
+DecodedDataDocumentParser::~DecodedDataDocumentParser()
+{
+}
+
+void DecodedDataDocumentParser::setDecoder(PassOwnPtr<TextResourceDecoder> decoder)
+{
+    m_decoder = decoder;
+}
+
+TextResourceDecoder* DecodedDataDocumentParser::decoder()
+{
+    return m_decoder.get();
+}
+
+void DecodedDataDocumentParser::setHasAppendedData()
+{
+    m_hasAppendedData = true;
+}
+
+void DecodedDataDocumentParser::appendBytes(const char* data, size_t length)
 {
     if (!length)
-        return 0;
+        return;
 
     // This should be checking isStopped(), but XMLDocumentParser prematurely
     // stops parsing when handling an XSLT processing instruction and still
     // needs to receive decoded bytes.
     if (isDetached())
-        return 0;
+        return;
 
-    String decoded = document()->decoder()->decode(data, length);
-    document()->setEncoding(document()->decoder()->encoding());
-
-    if (decoded.isEmpty())
-        return 0;
-
-    size_t consumedChars = decoded.length();
-    append(decoded.releaseImpl());
-
-    return consumedChars;
+    String decoded = m_decoder->decode(data, length);
+    updateDocument(decoded);
 }
 
-size_t DecodedDataDocumentParser::flush()
+void DecodedDataDocumentParser::flush()
 {
     // This should be checking isStopped(), but XMLDocumentParser prematurely
     // stops parsing when handling an XSLT processing instruction and still
     // needs to receive decoded bytes.
     if (isDetached())
-        return 0;
+        return;
 
     // null decoder indicates there is no data received.
     // We have nothing to do in that case.
-    TextResourceDecoder* decoder = document()->decoder();
-    if (!decoder)
-        return 0;
-    String remainingData = decoder->flush();
-    document()->setEncoding(document()->decoder()->encoding());
-    if (remainingData.isEmpty())
-        return 0;
+    if (!m_decoder)
+        return;
 
-    size_t consumedChars = remainingData.length();
-    append(remainingData.releaseImpl());
+    String remainingData = m_decoder->flush();
+    updateDocument(remainingData);
+}
 
-    return consumedChars;
+void DecodedDataDocumentParser::updateDocument(String& decodedData)
+{
+    DocumentEncodingData encodingData;
+    encodingData.encoding = m_decoder->encoding();
+    encodingData.wasDetectedHeuristically = m_decoder->encodingWasDetectedHeuristically();
+    encodingData.sawDecodingError = m_decoder->sawError();
+    document()->setEncodingData(encodingData);
+
+    if (decodedData.isEmpty())
+        return;
+
+    append(decodedData.releaseImpl());
+    // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
+    if (!m_hasAppendedData) {
+        m_hasAppendedData = true;
+        if (m_decoder->encoding().usesVisualOrdering())
+            document()->setVisuallyOrdered();
+    }
 }
 
 };
diff --git a/Source/core/dom/DecodedDataDocumentParser.h b/Source/core/dom/DecodedDataDocumentParser.h
index c931c0c..453147d 100644
--- a/Source/core/dom/DecodedDataDocumentParser.h
+++ b/Source/core/dom/DecodedDataDocumentParser.h
@@ -27,8 +27,11 @@
 #define DecodedDataDocumentParser_h
 
 #include "core/dom/DocumentParser.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
+class TextResourceDecoder;
 
 class DecodedDataDocumentParser : public DocumentParser {
 public:
@@ -36,17 +39,26 @@
     // XMLHttpRequest if the responseXML was well formed.
     virtual bool wellFormed() const { return true; }
 
+    // The below functions are used by DocumentWriter (the loader).
+    virtual void appendBytes(const char* bytes, size_t length) OVERRIDE;
+    virtual void flush() OVERRIDE;
+    virtual bool needsDecoder() const OVERRIDE { return !m_decoder; }
+    virtual void setDecoder(PassOwnPtr<TextResourceDecoder>) OVERRIDE;
+    virtual TextResourceDecoder* decoder() OVERRIDE;
+    virtual void setHasAppendedData() OVERRIDE;
+
 protected:
     explicit DecodedDataDocumentParser(Document*);
+    virtual ~DecodedDataDocumentParser();
 
 private:
     // append is used by DocumentWriter::replaceDocument.
     virtual void append(PassRefPtr<StringImpl>) = 0;
 
-    // appendBytes and flush are used by DocumentWriter (the loader).
-    virtual size_t appendBytes(const char* bytes, size_t length) OVERRIDE;
-    virtual size_t flush() OVERRIDE;
-    virtual bool needsDecoder() const OVERRIDE { return true; }
+    void updateDocument(String& decodedData);
+
+    bool m_hasAppendedData;
+    OwnPtr<TextResourceDecoder> m_decoder;
 };
 
 }
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index ddbf569..26e2db8 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -43,6 +43,7 @@
 #include "bindings/v8/ScriptController.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/animation/AnimationClock.h"
+#include "core/animation/DocumentAnimations.h"
 #include "core/animation/DocumentTimeline.h"
 #include "core/animation/css/TransitionTimeline.h"
 #include "core/css/CSSDefaultStyleSheets.h"
@@ -55,6 +56,7 @@
 #include "core/css/StyleSheetList.h"
 #include "core/css/resolver/FontBuilder.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverStats.h"
 #include "core/dom/AddConsoleMessageTask.h"
 #include "core/dom/Attr.h"
 #include "core/dom/CDATASection.h"
@@ -72,6 +74,7 @@
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExecutionContextTask.h"
+#include "core/dom/MainThreadTaskRunner.h"
 #include "core/dom/NamedFlowCollection.h"
 #include "core/dom/NodeChildRemovalTracker.h"
 #include "core/dom/NodeFilter.h"
@@ -99,6 +102,7 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
+#include "core/editing/SpellChecker.h"
 #include "core/events/BeforeUnloadEvent.h"
 #include "core/events/Event.h"
 #include "core/events/EventFactory.h"
@@ -174,9 +178,9 @@
 #include "platform/network/HTTPParsers.h"
 #include "platform/text/PlatformLocale.h"
 #include "platform/text/SegmentedString.h"
-#include "weborigin/OriginAccessEntry.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/OriginAccessEntry.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/HashFunctions.h"
 #include "wtf/MainThread.h"
@@ -374,13 +378,8 @@
 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
     : ContainerNode(0, CreateDocument)
     , TreeScope(this)
-    , m_styleResolverThrowawayTimer(this, &Document::styleResolverThrowawayTimerFired)
-    , m_styleResolverAccessCount(0)
-    , m_lastStyleResolverAccessCount(0)
-    , m_didCalculateStyleResolver(false)
     , m_hasNodesWithPlaceholderStyle(false)
     , m_needsNotifyRemoveAllPendingStylesheet(false)
-    , m_ignorePendingStylesheets(false)
     , m_evaluateMediaQueriesOnStyleRecalc(false)
     , m_pendingSheetLayout(NoLayoutWithPendingSheets)
     , m_frame(initializer.frame())
@@ -443,10 +442,9 @@
     , m_writeRecursionIsTooDeep(false)
     , m_writeRecursionDepth(0)
     , m_lastHandledUserGestureTimestamp(0)
-    , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
+    , m_taskRunner(MainThreadTaskRunner::create(this))
     , m_textAutosizer(TextAutosizer::create(this))
     , m_registrationContext(initializer.registrationContext(this))
-    , m_scheduledTasksAreSuspended(false)
     , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
 #ifndef NDEBUG
     , m_didDispatchViewportPropertiesChanged(false)
@@ -518,8 +516,6 @@
     if (this == topDocument())
         clearAXObjectCache();
 
-    setDecoder(PassRefPtr<TextResourceDecoder>());
-
     if (m_styleSheetList)
         m_styleSheetList->detachFromDocument();
 
@@ -528,13 +524,11 @@
         m_import = 0;
     }
 
-    m_styleEngine.clear();
+    m_styleEngine.clear(); // We need to destory CSSFontSelector before destroying m_fetcher.
 
     if (m_elemSheet)
         m_elemSheet->clearOwnerNode();
 
-    clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_fetcher.
-
     // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
     // load the initial empty document and the SVGDocument with the same DocumentLoader).
     if (m_fetcher->document() == this)
@@ -588,7 +582,7 @@
     // removeDetachedChildren() can access FormController.
     m_formController.clear();
 
-    m_markers->detach();
+    m_markers->clear();
 
     m_cssCanvasElements.clear();
 
@@ -618,6 +612,11 @@
     return *m_mediaQueryMatcher;
 }
 
+void Document::mediaQueryAffectingValueChanged()
+{
+    styleEngine()->clearMediaQueryRuleSetStyleSheets();
+}
+
 void Document::setCompatibilityMode(CompatibilityMode mode)
 {
     if (m_compatibilityModeLocked || mode == m_compatibilityMode)
@@ -626,8 +625,7 @@
     m_compatibilityMode = mode;
     selectorQueryCache().invalidate();
     if (inQuirksMode() != wasInQuirksMode) {
-        // All user stylesheets have to reparse using the different mode.
-        m_styleEngine->clearPageUserSheet();
+        // All injected stylesheets have to reparse using the different mode.
         m_styleEngine->invalidateInjectedStyleSheetCache();
     }
 }
@@ -654,7 +652,7 @@
 DOMImplementation* Document::implementation()
 {
     if (!m_implementation)
-        m_implementation = DOMImplementation::create(this);
+        m_implementation = DOMImplementation::create(*this);
     return m_implementation.get();
 }
 
@@ -675,7 +673,7 @@
 {
     ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
 
-    Element* newDocumentElement = ElementTraversal::firstWithin(this);
+    Element* newDocumentElement = ElementTraversal::firstWithin(*this);
     if (newDocumentElement == m_documentElement)
         return;
     m_documentElement = newDocumentElement;
@@ -683,23 +681,23 @@
     clearStyleResolver();
 }
 
-PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& es)
+PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
 {
     if (!isValidName(name)) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
         return 0;
     }
 
     if (isXHTMLDocument() || isHTMLDocument())
-        return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, isHTMLDocument() ? name.lower() : name, xhtmlNamespaceURI), this, 0, false);
+        return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, document(), 0, false);
 
     return createElement(QualifiedName(nullAtom, name, nullAtom), false);
 }
 
-PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& es)
+PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
 {
     if (!isValidName(localName)) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
         return 0;
     }
 
@@ -708,7 +706,7 @@
     if (RuntimeEnabledFeatures::customElementsEnabled() && CustomElement::isValidName(localName) && registrationContext())
         element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
     else
-        element = createElement(localName, es);
+        element = createElement(localName, exceptionState);
 
     if (RuntimeEnabledFeatures::customElementsEnabled() && !typeExtension.isNull() && !typeExtension.isEmpty())
         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
@@ -716,15 +714,15 @@
     return element;
 }
 
-PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState& es)
+PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
 {
     String prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, es))
+    if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
     QualifiedName qName(prefix, localName, namespaceURI);
     if (!hasValidNamespaceForElements(qName)) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
+        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
         return 0;
     }
 
@@ -732,7 +730,7 @@
     if (CustomElement::isValidName(qName.localName()) && registrationContext())
         element = registrationContext()->createCustomTagElement(*this, qName);
     else
-        element = createElementNS(namespaceURI, qualifiedName, es);
+        element = createElementNS(namespaceURI, qualifiedName, exceptionState);
 
     if (!typeExtension.isNull() && !typeExtension.isEmpty())
         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
@@ -740,20 +738,20 @@
     return element;
 }
 
-ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionState& es)
+ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionState& exceptionState)
 {
-    return registerElement(state, name, Dictionary(), es);
+    return registerElement(state, name, Dictionary(), exceptionState);
 }
 
-ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& es, CustomElement::NameSet validNames)
+ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
 {
     if (!registrationContext()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return ScriptValue();
     }
 
     CustomElementConstructorBuilder constructorBuilder(state, &options);
-    registrationContext()->registerElement(this, &constructorBuilder, name, validNames, es);
+    registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
     return constructorBuilder.bindingsReturnValue();
 }
 
@@ -788,27 +786,27 @@
     return Comment::create(*this, data);
 }
 
-PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& es)
+PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
 {
     if (isHTMLDocument()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     if (data.find("]]>") != WTF::kNotFound) {
-        es.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
+        exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
         return 0;
     }
     return CDATASection::create(*this, data);
 }
 
-PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& es)
+PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
 {
     if (!isValidName(target)) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
         return 0;
     }
     if (isHTMLDocument()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     return ProcessingInstruction::create(*this, target, data);
@@ -824,10 +822,10 @@
     return MutableStylePropertySet::create()->ensureCSSStyleDeclaration();
 }
 
-PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& es)
+PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
 {
     if (!importedNode) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
@@ -835,9 +833,9 @@
     case TEXT_NODE:
         return createTextNode(importedNode->nodeValue());
     case CDATA_SECTION_NODE:
-        return createCDATASection(importedNode->nodeValue(), es);
+        return createCDATASection(importedNode->nodeValue(), exceptionState);
     case PROCESSING_INSTRUCTION_NODE:
-        return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), es);
+        return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
     case COMMENT_NODE:
         return createComment(importedNode->nodeValue());
     case ELEMENT_NODE: {
@@ -845,7 +843,7 @@
         // FIXME: The following check might be unnecessary. Is it possible that
         // oldElement has mismatched prefix/namespace?
         if (!hasValidNamespaceForElements(oldElement->tagQName())) {
-            es.throwUninformativeAndGenericDOMException(NamespaceError);
+            exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
             return 0;
         }
         RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
@@ -854,11 +852,11 @@
 
         if (deep) {
             for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
-                RefPtr<Node> newChild = importNode(oldChild, true, es);
-                if (es.hadException())
+                RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
+                if (exceptionState.hadException())
                     return 0;
-                newElement->appendChild(newChild.release(), es);
-                if (es.hadException())
+                newElement->appendChild(newChild.release(), exceptionState);
+                if (exceptionState.hadException())
                     return 0;
             }
         }
@@ -877,11 +875,11 @@
         RefPtr<DocumentFragment> newFragment = createDocumentFragment();
         if (deep) {
             for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
-                RefPtr<Node> newChild = importNode(oldChild, true, es);
-                if (es.hadException())
+                RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
+                if (exceptionState.hadException())
                     return 0;
-                newFragment->appendChild(newChild.release(), es);
-                if (es.hadException())
+                newFragment->appendChild(newChild.release(), exceptionState);
+                if (exceptionState.hadException())
                     return 0;
             }
         }
@@ -897,14 +895,14 @@
     case XPATH_NAMESPACE_NODE:
         break;
     }
-    es.throwUninformativeAndGenericDOMException(NotSupportedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
     return 0;
 }
 
-PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& es)
+PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
 {
     if (!source) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
@@ -916,31 +914,31 @@
     case DOCUMENT_NODE:
     case DOCUMENT_TYPE_NODE:
     case XPATH_NAMESPACE_NODE:
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     case ATTRIBUTE_NODE: {
         Attr* attr = toAttr(source.get());
         if (attr->ownerElement())
-            attr->ownerElement()->removeAttributeNode(attr, es);
+            attr->ownerElement()->removeAttributeNode(attr, exceptionState);
         break;
     }
     default:
         if (source->isShadowRoot()) {
             // ShadowRoot cannot disconnect itself from the host node.
-            es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
             return 0;
         }
 
         if (source->isFrameOwnerElement()) {
             HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
             if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
-                es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+                exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
                 return 0;
             }
         }
         if (source->parentNode()) {
-            source->parentNode()->removeChild(source.get(), es);
-            if (es.hadException())
+            source->parentNode()->removeChild(source.get(), exceptionState);
+            if (exceptionState.hadException())
                 return 0;
         }
     }
@@ -986,17 +984,19 @@
 
     // FIXME: Use registered namespaces and look up in a hash to find the right factory.
     if (qName.namespaceURI() == xhtmlNamespaceURI)
-        e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
+        e = HTMLElementFactory::createHTMLElement(qName.localName(), document(), 0, createdByParser);
     else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
-        e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
+        e = SVGElementFactory::createSVGElement(qName.localName(), document(), createdByParser);
 
     if (e)
         m_sawElementsInKnownNamespaces = true;
     else
         e = Element::create(qName, &document());
 
-    // <image> uses imgTag so we need a special rule.
-    ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
+    if (e->prefix() != qName.prefix())
+        e->setTagNameForCreateElementNS(qName);
+
+    ASSERT(qName == e->tagQName());
 
     return e.release();
 }
@@ -1006,14 +1006,9 @@
     return settings() && settings()->regionBasedColumnsEnabled();
 }
 
-bool Document::cssCompositingEnabled() const
-{
-    return RuntimeEnabledFeatures::cssCompositingEnabled();
-}
-
 PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
 {
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !isActive())
+    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderView())
         return 0;
 
     updateStyleIfNeeded();
@@ -1029,15 +1024,15 @@
     return m_namedFlows.get();
 }
 
-PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& es)
+PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& exceptionState)
 {
     String prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, es))
+    if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
     QualifiedName qName(prefix, localName, namespaceURI);
     if (!hasValidNamespaceForElements(qName)) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
+        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
         return 0;
     }
 
@@ -1100,7 +1095,7 @@
     // TextEncoding::name() returns a char*, no need to allocate a new
     // String for it each time.
     // FIXME: We should fix TextEncoding to speak AtomicString anyway.
-    return AtomicString(m_encoding.name());
+    return AtomicString(encoding().name());
 }
 
 String Document::defaultCharset() const
@@ -1112,10 +1107,15 @@
 
 void Document::setCharset(const String& charset)
 {
-    if (!decoder())
+    if (DocumentLoader* documentLoader = loader())
+        documentLoader->setUserChosenEncoding(charset);
+    WTF::TextEncoding encoding(charset);
+    // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
+    if (!encoding.isValid())
         return;
-    decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
-    setEncoding(m_decoder->encoding());
+    DocumentEncodingData newEncodingData = m_encodingData;
+    newEncodingData.encoding = encoding;
+    setEncodingData(newEncodingData);
 }
 
 void Document::setContentLanguage(const String& language)
@@ -1128,25 +1128,25 @@
     setNeedsStyleRecalc();
 }
 
-void Document::setXMLVersion(const String& version, ExceptionState& es)
+void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
 {
     if (!implementation()->hasFeature("XML", String())) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
     if (!XMLDocumentParser::supportsXMLVersion(version)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
     m_xmlVersion = version;
 }
 
-void Document::setXMLStandalone(bool standalone, ExceptionState& es)
+void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
 {
     if (!implementation()->hasFeature("XML", String())) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
@@ -1188,7 +1188,7 @@
 
 Element* Document::elementFromPoint(int x, int y) const
 {
-    if (!isActive())
+    if (!renderView())
         return 0;
 
     return TreeScope::elementFromPoint(x, y);
@@ -1196,7 +1196,7 @@
 
 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
 {
-    if (!isActive())
+    if (!renderView())
         return 0;
     LayoutPoint localPoint;
     RenderObject* renderer = rendererFromPoint(this, x, y, &localPoint);
@@ -1350,7 +1350,7 @@
         updateTitle(String());
 }
 
-PageVisibilityState Document::visibilityState() const
+PageVisibilityState Document::pageVisibilityState() const
 {
     // The visibility of the document is inherited from the visibility of the
     // page. If there is no page associated with the document, we will assume
@@ -1361,18 +1361,20 @@
     return m_frame->page()->visibilityState();
 }
 
-String Document::webkitVisibilityState() const
+String Document::visibilityState() const
 {
-    return pageVisibilityStateString(visibilityState());
+    return pageVisibilityStateString(pageVisibilityState());
 }
 
-bool Document::webkitHidden() const
+bool Document::hidden() const
 {
-    return visibilityState() != PageVisibilityStateVisible;
+    return pageVisibilityState() != PageVisibilityStateVisible;
 }
 
 void Document::dispatchVisibilityStateChangeEvent()
 {
+    dispatchEvent(Event::create(EventTypeNames::visibilitychange));
+    // Also send out the deprecated version until it can be removed.
     dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
 }
 
@@ -1434,20 +1436,20 @@
     return Range::create(*this);
 }
 
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& es)
+PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
 {
     // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
 }
 
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& es)
+PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
 {
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
@@ -1455,20 +1457,20 @@
     return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
 }
 
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& es)
+PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
 {
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     // FIXME: Ditto.
     return NodeIterator::create(root, whatToShow, filter);
 }
 
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& es)
+PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& exceptionState)
 {
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     // FIXME: Warn if |expandEntityReferences| is specified. This optional argument is deprecated in DOM4.
@@ -1476,38 +1478,38 @@
     return NodeIterator::create(root, whatToShow, filter);
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& es)
+PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
 {
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& es)
+PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
 {
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& es)
+PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
 {
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     return TreeWalker::create(root, whatToShow, filter);
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& es)
+PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& exceptionState)
 {
     UNUSED_PARAM(expandEntityReferences);
     if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
     return TreeWalker::create(root, whatToShow, filter);
@@ -1592,51 +1594,46 @@
 
     FontBuilder fontBuilder;
     fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
-    RefPtr<CSSFontSelector> selector = m_styleResolver ? m_styleResolver->fontSelector() : 0;
+    RefPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
     fontBuilder.createFontForDocument(selector, documentStyle);
 }
 
 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
 {
-    RenderView* renderView = this->renderView();
-
-    if (!documentElement() || !frame() || !view())
-        return;
+    ASSERT(inStyleRecalc());
+    ASSERT(documentElement());
 
     RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
     if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
         documentElementStyle = styleResolver()->styleForElement(documentElement());
 
-    RefPtr<RenderStyle> bodyStyle = 0;
-    if (body()) {
-        bodyStyle = body()->renderStyle();
-        if (!bodyStyle || body()->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
-            bodyStyle = styleResolver()->styleForElement(body(), documentElementStyle.get());
-    }
-
     WritingMode rootWritingMode = documentElementStyle->writingMode();
     TextDirection rootDirection = documentElementStyle->direction();
+    HTMLElement* body = this->body();
 
-    if (!writingModeSetOnDocumentElement() && body()) {
-        rootWritingMode = bodyStyle->writingMode();
+    if (body) {
+        RefPtr<RenderStyle> bodyStyle = body->renderStyle();
+        if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
+            bodyStyle = styleResolver()->styleForElement(body, documentElementStyle.get());
+        if (!writingModeSetOnDocumentElement())
+            rootWritingMode = bodyStyle->writingMode();
+        if (!directionSetOnDocumentElement())
+            rootDirection = bodyStyle->direction();
     }
 
-    if (!directionSetOnDocumentElement() && body())
-        rootDirection = bodyStyle->direction();
-
-    RefPtr<RenderStyle> documentStyle = renderView->style();
+    RefPtr<RenderStyle> documentStyle = renderView()->style();
     if (documentStyle->writingMode() != rootWritingMode || documentStyle->direction() != rootDirection) {
         RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
         newStyle->setWritingMode(rootWritingMode);
         newStyle->setDirection(rootDirection);
-        renderView->setStyle(newStyle);
+        renderView()->setStyle(newStyle);
         setStyleDependentState(newStyle.get());
     }
 
-    if (body()) {
-        if (RenderStyle* style = body()->renderStyle()) {
+    if (body) {
+        if (RenderStyle* style = body->renderStyle()) {
             if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
-                body()->setNeedsStyleRecalc();
+                body->setNeedsStyleRecalc();
         }
     }
 
@@ -1692,24 +1689,40 @@
         if (styleChangeType() >= SubtreeStyleChange)
             change = Force;
 
+        // FIXME: Cannot access the styleResolver() before calling styleForDocument below because
+        // apparently the StyleResolver's constructor has side effects. We should fix it.
+        // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
+        // mac when accessing the resolver by what appears to be a viewport size difference.
+
         if (change == Force || (change >= Inherit && shouldDisplaySeamlesslyWithParent())) {
             m_hasNodesWithPlaceholderStyle = false;
-            RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
+            RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleEngine->fontSelector());
             StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderView()->style());
             if (localChange != NoChange)
                 renderView()->setStyle(documentStyle.release());
         }
 
-        inheritHtmlAndBodyElementStyles(change);
+        clearNeedsStyleRecalc();
+
+        // Uncomment to enable printing of statistics about style sharing and the matched property cache.
+        // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
+        // entire DOM (where collecting them is very slow).
+        // FIXME: Expose this as a runtime flag.
+        // styleResolver()->enableStats(/*StyleResolver::ReportSlowStats*/);
+
+        if (StyleResolverStats* stats = styleResolver()->stats())
+            stats->reset();
 
         if (Element* documentElement = this->documentElement()) {
+            inheritHtmlAndBodyElementStyles(change);
             if (shouldRecalcStyle(change, documentElement))
                 documentElement->recalcStyle(change);
         }
 
+        styleResolver()->printStats();
+
         view()->updateCompositingLayersAfterStyleChange();
 
-        clearNeedsStyleRecalc();
         clearChildNeedsStyleRecalc();
         unscheduleStyleRecalc();
 
@@ -1718,16 +1731,13 @@
         if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
             setNeedsStyleRecalc();
 
-        if (m_styleResolver) {
+        if (m_styleEngine->hasResolver()) {
             // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
-            m_styleEngine->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
-            m_styleResolver->clearStyleSharingList();
+            m_styleEngine->resetCSSFeatureFlags(m_styleEngine->resolver()->ensureRuleFeatureSet());
+            m_styleEngine->resolver()->clearStyleSharingList();
         }
     }
 
-    STYLE_STATS_PRINT();
-    STYLE_STATS_CLEAR();
-
     InspectorInstrumentation::didRecalculateStyle(cookie);
 
     // As a result of the style recalculation, the currently hovered element might have been
@@ -1747,7 +1757,7 @@
 
     AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : 0);
     recalcStyle(NoChange);
-    m_animationClock->unfreeze();
+    DocumentAnimations::serviceAfterStyleRecalc(*this);
 }
 
 void Document::updateStyleForNodeIfNeeded(Node* node)
@@ -1779,7 +1789,7 @@
     updateStyleIfNeeded();
 
     // Only do a layout if changes have occurred that make it necessary.
-    if (frameView && isActive() && (frameView->layoutPending() || renderView()->needsLayout()))
+    if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
         frameView->layout();
 
     if (frameView)
@@ -1793,32 +1803,33 @@
     // FIXME: Using a Task doesn't look a good idea.
     if (!m_focusedElement || m_didPostCheckFocusedElementTask)
         return;
-    postTask(CheckFocusedElementTask::create());
+    m_taskRunner->postTask(CheckFocusedElementTask::create());
     m_didPostCheckFocusedElementTask = true;
 }
 
 void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
 {
-    TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
-    if (!haveStylesheetsLoaded()) {
-        m_ignorePendingStylesheets = true;
-        // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
-        // Our assumption is that it would be dangerous to try to stop it a second time, after page
-        // content has already been loaded and displayed with accurate style information. (Our
-        // suppression involves blanking the whole page at the moment. If it were more refined, we
-        // might be able to do something better.) It's worth noting though that this entire method
-        // is a hack, since what we really want to do is suspend JS instead of doing a layout with
-        // inaccurate information.
-        HTMLElement* bodyElement = body();
-        if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
-            m_pendingSheetLayout = DidLayoutWithPendingSheets;
-            styleResolverChanged(RecalcStyleImmediately);
-        } else if (m_hasNodesWithPlaceholderStyle) {
-            // If new nodes have been added or style recalc has been done with style sheets still
-            // pending, some nodes may not have had their real style calculated yet. Normally this
-            // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
-            recalcStyle(Force);
-        }
+    ASSERT(m_styleEngine->ignoringPendingStylesheets());
+
+    if (!m_styleEngine->hasPendingSheets())
+        return;
+
+    // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
+    // Our assumption is that it would be dangerous to try to stop it a second time, after page
+    // content has already been loaded and displayed with accurate style information. (Our
+    // suppression involves blanking the whole page at the moment. If it were more refined, we
+    // might be able to do something better.) It's worth noting though that this entire method
+    // is a hack, since what we really want to do is suspend JS instead of doing a layout with
+    // inaccurate information.
+    HTMLElement* bodyElement = body();
+    if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
+        m_pendingSheetLayout = DidLayoutWithPendingSheets;
+        styleResolverChanged(RecalcStyleImmediately);
+    } else if (m_hasNodesWithPlaceholderStyle) {
+        // If new nodes have been added or style recalc has been done with style sheets still
+        // pending, some nodes may not have had their real style calculated yet. Normally this
+        // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
+        recalcStyle(Force);
     }
 }
 
@@ -1828,10 +1839,13 @@
 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
 // lets us get reasonable answers. The long term solution to this problem is
 // to instead suspend JavaScript execution.
-void Document::updateLayoutIgnorePendingStylesheets()
+void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
 {
+    StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
     recalcStyleForLayoutIgnoringPendingStylesheets();
     updateLayout();
+    if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
+        view()->flushAnyPendingPostLayoutTasks();
 }
 
 void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNode)
@@ -1843,7 +1857,7 @@
         return;
     }
 
-    TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
+    StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
     recalcStyleForLayoutIgnoringPendingStylesheets();
 
     if (stopLayoutAtNode) {
@@ -1869,7 +1883,7 @@
 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
 {
     ASSERT_ARG(element, element->document() == this);
-    TemporaryChange<bool> ignoreStyleSheets(m_ignorePendingStylesheets, true);
+    StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
     return styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
 }
 
@@ -1932,18 +1946,19 @@
     didUpdateSecurityOrigin();
 }
 
-void Document::createStyleResolver()
+StyleResolver* Document::styleResolverIfExists() const
 {
-    bool matchAuthorAndUserStyles = true;
-    if (Settings* docSettings = settings())
-        matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
-    m_styleResolver = adoptPtr(new StyleResolver(*this, matchAuthorAndUserStyles));
-    m_styleEngine->combineCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
+    return m_styleEngine->resolverIfExists();
+}
+
+StyleResolver* Document::styleResolver() const
+{
+    return m_styleEngine->resolver();
 }
 
 void Document::clearStyleResolver()
 {
-    m_styleResolver.clear();
+    m_styleEngine->clearResolver();
 }
 
 void Document::attach(const AttachContext& context)
@@ -1958,7 +1973,7 @@
     m_renderView->setStyle(StyleResolver::styleForDocument(*this));
     view()->updateCompositingLayersAfterStyleChange();
 
-    m_styleResolverThrowawayTimer.startRepeating(60);
+    m_styleEngine->didAttach();
 
     ContainerNode::attach(context);
 
@@ -1986,25 +2001,38 @@
     if (svgExtensions())
         accessSVGExtensions()->pauseAnimations();
 
-    m_renderView->setIsInWindow(false);
+    // FIXME: This shouldn't be needed once DOMWindow becomes ExecutionContext.
+    if (m_domWindow)
+        m_domWindow->clearEventQueue();
 
-    // FIXME: How can the frame be null here?
+    RenderView* renderView = m_renderView;
+
+    if (renderView)
+        renderView->setIsInWindow(false);
+
     if (m_frame) {
-        if (FrameView* view = m_frame->view())
+        FrameView* view = m_frame->view();
+        if (view)
             view->detachCustomScrollbars();
     }
 
+    // Indicate destruction mode by setting the renderer to null.
+    // FIXME: Don't do this and use m_lifecycle.state() == Stopping instead.
+    setRenderer(0);
+    m_renderView = 0;
+
     m_hoverNode = 0;
     m_focusedElement = 0;
     m_activeElement = 0;
 
-    m_styleResolverThrowawayTimer.stop();
-
     ContainerNode::detach(context);
 
     unscheduleStyleRecalc();
 
-    clearStyleResolver();
+    m_styleEngine->didDetach();
+
+    if (renderView)
+        renderView->destroy();
 
     if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
         parentDocument()->didRemoveEventTargetNode(this);
@@ -2025,6 +2053,7 @@
 
 void Document::prepareForDestruction()
 {
+    m_markers->prepareForDestruction();
     disconnectDescendantFrames();
 
     // The process of disconnecting descendant frames could have already detached us.
@@ -2042,7 +2071,7 @@
 
     if (DOMWindow* domWindow = this->domWindow())
         domWindow->removeAllEventListeners();
-    for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
+    for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
         node->removeAllEventListeners();
 }
 
@@ -2061,7 +2090,7 @@
 
     // If the renderer is gone then we are in the process of destruction.
     // This method will be called before m_frame = 0.
-    if (!topDocument()->isActive())
+    if (!topDocument()->renderView())
         return 0;
 
     return topDocument()->m_axObjectCache.get();
@@ -2079,7 +2108,7 @@
     Document* topDocument = this->topDocument();
 
     // If the document has already been detached, do not make a new axObjectCache.
-    if (!topDocument->isActive())
+    if (!topDocument->renderView())
         return 0;
 
     ASSERT(topDocument == this || !m_axObjectCache);
@@ -2212,17 +2241,17 @@
     return 0;
 }
 
-void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& es)
+void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
 {
     RefPtr<HTMLElement> newBody = prpNewBody;
 
     if (!newBody || !documentElement()) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return;
     }
 
     if (!newBody->hasTagName(bodyTag) && !newBody->hasTagName(framesetTag)) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return;
     }
 
@@ -2231,9 +2260,9 @@
         return;
 
     if (oldBody)
-        documentElement()->replaceChild(newBody.release(), oldBody, es);
+        documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
     else
-        documentElement()->appendChild(newBody.release(), es);
+        documentElement()->appendChild(newBody.release(), exceptionState);
 }
 
 HTMLHeadElement* Document::head()
@@ -2303,8 +2332,7 @@
     // onLoad event handler, as in Radar 3206524.
     detachParser();
 
-    Frame* f = frame();
-    if (f && f->script().canExecuteScripts(NotAboutToExecuteScript)) {
+    if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
         ImageLoader::dispatchPendingBeforeLoadEvents();
         ImageLoader::dispatchPendingLoadEvents();
         ImageLoader::dispatchPendingErrorEvents();
@@ -2313,6 +2341,9 @@
         HTMLStyleElement::dispatchPendingLoadEvents();
     }
 
+    // JS running below could remove the frame or destroy the RenderView so we call
+    // those two functions repeatedly and don't save them on the stack.
+
     // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
     // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
     // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
@@ -2327,7 +2358,6 @@
         loader()->applicationCacheHost()->stopDeferringEvents();
     }
 
-    // An event handler may have removed the frame
     if (!frame()) {
         m_loadEventProgress = LoadEventCompleted;
         return;
@@ -2345,8 +2375,6 @@
         return;
     }
 
-    RenderView* renderView = this->renderView();
-
     // We used to force a synchronous display and flush here.  This really isn't
     // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
     // (if your platform is syncing flushes and limiting them to 60fps).
@@ -2355,25 +2383,25 @@
         updateStyleIfNeeded();
 
         // Always do a layout after loading if needed.
-        if (view() && renderView && (!renderView->firstChild() || renderView->needsLayout()))
+        if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
             view()->layout();
     }
 
     m_loadEventProgress = LoadEventCompleted;
 
-    if (f && renderView && AXObjectCache::accessibilityEnabled()) {
+    if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
         // The AX cache may have been cleared at this point, but we need to make sure it contains an
         // AX object to send the notification to. getOrCreate will make sure that an valid AX object
         // exists in the cache (we ignore the return value because we don't need it here). This is
         // only safe to call when a layout is not in progress, so it can not be used in postNotification.
         if (AXObjectCache* cache = axObjectCache()) {
-            cache->getOrCreate(renderView);
+            cache->getOrCreate(renderView());
             if (this == topDocument()) {
-                cache->postNotification(renderView, AXObjectCache::AXLoadComplete, true);
+                cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
             } else {
                 // AXLoadComplete can only be posted on the top document, so if it's a document
                 // in an iframe that just finished loading, post AXLayoutComplete instead.
-                cache->postNotification(renderView, AXObjectCache::AXLayoutComplete, true);
+                cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
             }
         }
     }
@@ -2447,7 +2475,6 @@
                 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
             }
         }
-        updateStyleIfNeeded();
         m_loadEventProgress = UnloadEventHandled;
     }
 
@@ -2623,7 +2650,7 @@
     if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
         // Base URL change changes any relative visited links.
         // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
-        for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element)) {
+        for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element)) {
             if (isHTMLAnchorElement(element))
                 toHTMLAnchorElement(element)->invalidateCachedVisitedLinkHash();
         }
@@ -2641,7 +2668,7 @@
     // Find the first href attribute in a base element and the first target attribute in a base element.
     const AtomicString* href = 0;
     const AtomicString* target = 0;
-    for (Element* element = ElementTraversal::firstWithin(this); element && (!href || !target); element = ElementTraversal::next(element)) {
+    for (Element* element = ElementTraversal::firstWithin(*this); element && (!href || !target); element = ElementTraversal::next(*element)) {
         if (element->hasTagName(baseTag)) {
             if (!href) {
                 const AtomicString& value = element->fastGetAttribute(hrefAttr);
@@ -2918,6 +2945,9 @@
 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
 {
     if (viewportDescription.isLegacyViewportType()) {
+        if (settings() && !settings()->viewportMetaEnabled())
+            return;
+
         m_legacyViewportDescription = viewportDescription;
 
         // When no author style for @viewport is present, and a meta tag for defining
@@ -2939,7 +2969,7 @@
 
 void Document::updateViewportDescription()
 {
-    if (page() && page()->mainFrame() == frame()) {
+    if (frame() && frame()->isMainFrame()) {
 #ifndef NDEBUG
         m_didDispatchViewportPropertiesChanged = true;
 #endif
@@ -2963,13 +2993,15 @@
 
 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
 {
+    ASSERT(!renderView() || renderView()->isRenderView());
+
     // RenderView::hitTest causes a layout, and we don't want to hit that until the first
     // layout because until then, there is nothing shown on the screen - the user can't
     // have intentionally clicked on something belonging to this page. Furthermore,
     // mousemove events before the first layout should not lead to a premature layout()
     // happening, which could show a flash of white.
     // See also the similar code in EventHandler::hitTestResultAtPoint.
-    if (!isActive() || !view() || !view()->didFirstLayout())
+    if (!renderView() || !view() || !view()->didFirstLayout())
         return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
 
     HitTestResult result(documentPoint);
@@ -3009,7 +3041,7 @@
     return false;
 }
 
-bool Document::canReplaceChild(Node& newChild, Node& oldChild)
+bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
 {
     if (oldChild.nodeType() == newChild.nodeType())
         return true;
@@ -3108,7 +3140,7 @@
 void Document::cloneDataFromDocument(const Document& other)
 {
     setCompatibilityMode(other.compatibilityMode());
-    setEncoding(other.encoding());
+    setEncodingData(other.m_encodingData);
     setContextFeatures(other.contextFeatures());
     setSecurityOrigin(other.securityOrigin()->isolatedCopy());
 }
@@ -3144,24 +3176,16 @@
 
 void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
 {
-    // Don't bother updating, since we haven't loaded all our style info yet
-    // and haven't calculated the style selector for the first time.
-    if (!isActive() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
-        m_styleResolver.clear();
-        return;
-    }
-    m_didCalculateStyleResolver = true;
+    StyleResolverChange change = m_styleEngine->resolverChanged(updateMode);
 
-    bool needsRecalc = m_styleEngine->updateActiveStyleSheets(updateMode);
-
-    if (didLayoutWithPendingStylesheets() && !m_styleEngine->hasPendingSheets()) {
+    if (change.needsRepaint()) {
         // We need to manually repaint because we avoid doing all repaints in layout or style
         // recalc while sheets are still loading to avoid FOUC.
         m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
         renderView()->repaintViewAndCompositedLayers();
     }
 
-    if (!needsRecalc)
+    if (!change.needsStyleRecalc())
         return;
 
     m_evaluateMediaQueriesOnStyleRecalc = true;
@@ -3207,17 +3231,11 @@
     if (!m_focusedElement)
         return;
 
-    Element* focusedElement = node->treeScope().adjustedFocusedElement();
-    if (!focusedElement)
+    // We can't be focused if we're not in the document.
+    if (!node->inDocument())
         return;
-
-    bool nodeInSubtree = false;
-    if (amongChildrenOnly)
-        nodeInSubtree = focusedElement->isDescendantOf(node);
-    else
-        nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
-
-    if (nodeInSubtree)
+    bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
+    if (contains && (m_focusedElement != node || !amongChildrenOnly))
         setFocusedElement(0);
 }
 
@@ -3372,7 +3390,7 @@
         m_focusedElement->setFocus(true);
 
         if (m_focusedElement->isRootEditableElement())
-            frame()->editor().didBeginEditing(m_focusedElement.get());
+            frame()->spellChecker().didBeginEditing(m_focusedElement.get());
 
         // eww, I suck. set the qt focus correctly
         // ### find a better place in the code for this
@@ -3486,8 +3504,10 @@
             (*it)->nodeWillBeRemoved(*n);
     }
 
-    if (Frame* frame = this->frame()) {
-        for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
+    Frame* frame = this->frame();
+    for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
+        m_markers->nodeWillBeRemoved(*n);
+        if (frame) {
             frame->eventHandler().nodeWillBeRemoved(*n);
             frame->selection().nodeWillBeRemoved(*n);
             frame->page()->dragCaretController().nodeWillBeRemoved(*n);
@@ -3512,6 +3532,8 @@
         frame->selection().nodeWillBeRemoved(n);
         frame->page()->dragCaretController().nodeWillBeRemoved(n);
     }
+
+    m_markers->nodeWillBeRemoved(n);
 }
 
 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
@@ -3591,9 +3613,9 @@
     return m_domWindow->eventQueue();
 }
 
-void Document::scheduleAnimationFrameEvent(PassRefPtr<Event> event)
+void Document::enqueueAnimationFrameEvent(PassRefPtr<Event> event)
 {
-    ensureScriptedAnimationController().scheduleEvent(event);
+    ensureScriptedAnimationController().enqueueEvent(event);
 }
 
 void Document::enqueueScrollEventForNode(Node* target)
@@ -3601,16 +3623,23 @@
     // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
     RefPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
     scrollEvent->setTarget(target);
-    scheduleAnimationFrameEvent(scrollEvent.release());
+    ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
 }
 
-PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionState& es)
+void Document::enqueueResizeEvent()
+{
+    RefPtr<Event> event = Event::create(EventTypeNames::resize);
+    event->setTarget(domWindow());
+    ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
+}
+
+PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
 {
     RefPtr<Event> event = EventFactory::create(eventType);
     if (event)
         return event.release();
 
-    es.throwUninformativeAndGenericDOMException(NotSupportedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
     return 0;
 }
 
@@ -3674,7 +3703,7 @@
     return frame()->ownerElement();
 }
 
-String Document::cookie(ExceptionState& es) const
+String Document::cookie(ExceptionState& exceptionState) const
 {
     if (settings() && !settings()->cookieEnabled())
         return String();
@@ -3686,11 +3715,11 @@
     if (!securityOrigin()->canAccessCookies()) {
         String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
         if (isSandboxed(SandboxOrigin))
-            es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
         else if (url().protocolIs("data"))
-            es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
         else
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError(accessDeniedMessage);
         return String();
     }
 
@@ -3701,7 +3730,7 @@
     return cookies(this, cookieURL);
 }
 
-void Document::setCookie(const String& value, ExceptionState& es)
+void Document::setCookie(const String& value, ExceptionState& exceptionState)
 {
     if (settings() && !settings()->cookieEnabled())
         return;
@@ -3713,11 +3742,11 @@
     if (!securityOrigin()->canAccessCookies()) {
         String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
         if (isSandboxed(SandboxOrigin))
-            es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
         else if (url().protocolIs("data"))
-            es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
         else
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError(accessDeniedMessage);
         return;
     }
 
@@ -3740,23 +3769,31 @@
     return securityOrigin()->domain();
 }
 
-void Document::setDomain(const String& newDomain, ExceptionState& es)
+void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
 {
     if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
-        es.throwSecurityError(ExceptionMessages::failedToSet("domain", "Document", "assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme."));
+        exceptionState.throwSecurityError(ExceptionMessages::failedToSet("domain", "Document", "assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme."));
         return;
     }
 
-    String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is not a suffix of '" + domain() + "'.");
     if (newDomain.isEmpty()) {
-        es.throwSecurityError(exceptionMessage);
+        String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is an empty domain.");
+        exceptionState.throwSecurityError(exceptionMessage);
         return;
     }
 
     OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
     OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
-    if (!accessEntry.matchesOrigin(*securityOrigin())) {
-        es.throwSecurityError(exceptionMessage);
+    OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
+    if (result == OriginAccessEntry::DoesNotMatchOrigin) {
+        String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is not a suffix of '" + domain() + "'.");
+        exceptionState.throwSecurityError(exceptionMessage);
+        return;
+    }
+
+    if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
+        String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is a top-level domain.");
+        exceptionState.throwSecurityError(exceptionMessage);
         return;
     }
 
@@ -3863,7 +3900,7 @@
 }
 
 template<typename CharType>
-static bool parseQualifiedNameInternal(const String& qualifiedName, const CharType* characters, unsigned length, String& prefix, String& localName, ExceptionState& es)
+static bool parseQualifiedNameInternal(const String& qualifiedName, const CharType* characters, unsigned length, String& prefix, String& localName, ExceptionState& exceptionState)
 {
     bool nameStart = true;
     bool sawColon = false;
@@ -3874,7 +3911,7 @@
         U16_NEXT(characters, i, length, c)
         if (c == ':') {
             if (sawColon) {
-                es.throwUninformativeAndGenericDOMException(NamespaceError);
+                exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
                 return false; // multiple colons: not allowed
             }
             nameStart = true;
@@ -3882,13 +3919,13 @@
             colonPos = i - 1;
         } else if (nameStart) {
             if (!isValidNameStart(c)) {
-                es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+                exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
                 return false;
             }
             nameStart = false;
         } else {
             if (!isValidNamePart(c)) {
-                es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+                exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
                 return false;
             }
         }
@@ -3900,45 +3937,36 @@
     } else {
         prefix = qualifiedName.substring(0, colonPos);
         if (prefix.isEmpty()) {
-            es.throwUninformativeAndGenericDOMException(NamespaceError);
+            exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
             return false;
         }
         localName = qualifiedName.substring(colonPos + 1);
     }
 
     if (localName.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
+        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
         return false;
     }
 
     return true;
 }
 
-bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionState& es)
+bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionState& exceptionState)
 {
     unsigned length = qualifiedName.length();
 
     if (!length) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
         return false;
     }
 
     if (qualifiedName.is8Bit())
-        return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, es);
-    return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, es);
+        return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
+    return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
 }
 
-void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
+void Document::setEncodingData(const DocumentEncodingData& newData)
 {
-    m_decoder = decoder;
-    setEncoding(m_decoder ? m_decoder->encoding() : WTF::TextEncoding());
-}
-
-void Document::setEncoding(const WTF::TextEncoding& encoding)
-{
-    if (m_encoding == encoding)
-        return;
-
     // It's possible for the encoding of the document to change while we're decoding
     // data. That can only occur while we're processing the <head> portion of the
     // document. There isn't much user-visible content in the <head>, but there is
@@ -3946,17 +3974,18 @@
     // document's title so that the user doesn't see an incorrectly decoded title
     // in the title bar.
     if (m_titleElement
+        && encoding() != newData.encoding
         && !m_titleElement->firstElementChild()
-        && m_encoding == Latin1Encoding()
+        && encoding() == Latin1Encoding()
         && m_titleElement->textContent().containsOnlyLatin1()) {
 
         CString originalBytes = m_titleElement->textContent().latin1();
-        OwnPtr<TextCodec> codec = newTextCodec(encoding);
+        OwnPtr<TextCodec> codec = newTextCodec(newData.encoding);
         String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), true);
         m_titleElement->setTextContent(correctlyDecodedTitle, IGNORE_EXCEPTION);
     }
 
-    m_encoding = encoding;
+    m_encodingData = newData;
 }
 
 KURL Document::completeURL(const String& url, const KURL& baseURLOverride) const
@@ -3967,9 +3996,9 @@
     if (url.isNull())
         return KURL();
     const KURL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
-    if (!m_decoder)
+    if (!encoding().isValid())
         return KURL(baseURL, url);
-    return KURL(baseURL, url, m_decoder->encoding());
+    return KURL(baseURL, url, encoding());
 }
 
 KURL Document::completeURL(const String& url) const
@@ -4067,7 +4096,7 @@
     ASSERT(!pi->isLoading());
     UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
     RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
-    processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
+    processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
     String resultMIMEType;
     String newSource;
     String resultEncoding;
@@ -4134,21 +4163,21 @@
     return WeakPtr<Document>(0);
 }
 
-PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionState& es)
+PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionState& exceptionState)
 {
-    return createAttributeNS(String(), name, es, true);
+    return createAttributeNS(String(), name, exceptionState, true);
 }
 
-PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& es, bool shouldIgnoreNamespaceChecks)
+PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
 {
     String prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, es))
+    if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
     QualifiedName qName(prefix, localName, namespaceURI);
 
     if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
+        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
         return 0;
     }
 
@@ -4192,12 +4221,6 @@
     return ensureCachedCollection(DocEmbeds);
 }
 
-PassRefPtr<HTMLCollection> Document::plugins()
-{
-    // This is an alias for embeds() required for the JS DOM bindings.
-    return ensureCachedCollection(DocEmbeds);
-}
-
 PassRefPtr<HTMLCollection> Document::scripts()
 {
     return ensureCachedCollection(DocScripts);
@@ -4289,29 +4312,17 @@
     m_sharedObjectPool.clear();
 }
 
-void Document::styleResolverThrowawayTimerFired(Timer<Document>*)
+Vector<IconURL> Document::iconURLs(int iconTypesMask)
 {
-    if (m_styleResolverAccessCount == m_lastStyleResolverAccessCount)
-        clearStyleResolver();
-    m_lastStyleResolverAccessCount = m_styleResolverAccessCount;
-}
+    IconURL firstFavicon;
+    IconURL firstTouchIcon;
+    IconURL firstTouchPrecomposedIcon;
+    Vector<IconURL> secondaryIcons;
 
-const Vector<IconURL>& Document::shortcutIconURLs()
-{
-    // Include any icons where type = link, rel = "shortcut icon".
-    return iconURLs(Favicon);
-}
-
-const Vector<IconURL>& Document::iconURLs(int iconTypesMask)
-{
-    m_iconURLs.clear();
-
-    if (!head() || !(head()->children()))
-        return m_iconURLs;
-
-    RefPtr<HTMLCollection> children = head()->children();
-    unsigned int length = children->length();
-    for (unsigned int i = 0; i < length; ++i) {
+    // Start from the last child node so that icons seen later take precedence as required by the spec.
+    RefPtr<HTMLCollection> children = head() ? head()->children() : 0;
+    unsigned length = children ? children->length() : 0;
+    for (unsigned i = 0; i < length; i++) {
         Node* child = children->item(i);
         if (!child->hasTagName(linkTag))
             continue;
@@ -4320,13 +4331,42 @@
             continue;
         if (linkElement->href().isEmpty())
             continue;
+#if !ENABLE(TOUCH_ICON_LOADING)
+        if (linkElement->iconType() != Favicon)
+            continue;
+#endif
 
-        // Put it at the front to ensure that icons seen later take precedence as required by the spec.
         IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
-        m_iconURLs.prepend(newURL);
+        if (linkElement->iconType() == Favicon) {
+            if (firstFavicon.m_iconType != InvalidIcon)
+                secondaryIcons.append(firstFavicon);
+            firstFavicon = newURL;
+        } else if (linkElement->iconType() == TouchIcon) {
+            if (firstTouchIcon.m_iconType != InvalidIcon)
+                secondaryIcons.append(firstTouchIcon);
+            firstTouchIcon = newURL;
+        } else if (linkElement->iconType() == TouchPrecomposedIcon) {
+            if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
+                secondaryIcons.append(firstTouchPrecomposedIcon);
+            firstTouchPrecomposedIcon = newURL;
+        } else {
+            ASSERT_NOT_REACHED();
+        }
     }
 
-    return m_iconURLs;
+    Vector<IconURL> iconURLs;
+    if (firstFavicon.m_iconType != InvalidIcon)
+        iconURLs.append(firstFavicon);
+    else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
+        iconURLs.append(IconURL::defaultFavicon(m_url));
+
+    if (firstTouchIcon.m_iconType != InvalidIcon)
+        iconURLs.append(firstTouchIcon);
+    if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
+        iconURLs.append(firstTouchPrecomposedIcon);
+    for (int i = secondaryIcons.size() - 1; i >= 0; --i)
+        iconURLs.append(secondaryIcons[i]);
+    return iconURLs;
 }
 
 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
@@ -4575,7 +4615,7 @@
 void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state)
 {
     if (!isContextThread()) {
-        postTask(AddConsoleMessageTask::create(source, level, message));
+        m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
         return;
     }
     Page* page = this->page();
@@ -4597,7 +4637,7 @@
 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
 {
     if (!isContextThread()) {
-        postTask(AddConsoleMessageTask::create(source, level, message));
+        m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
         return;
     }
 
@@ -4605,94 +4645,52 @@
         page->console().addMessage(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
 }
 
-struct PerformTaskContext {
-    WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
-public:
-    PerformTaskContext(WeakPtr<Document> document, PassOwnPtr<ExecutionContextTask> task)
-        : documentReference(document)
-        , task(task)
-    {
-    }
-
-    WeakPtr<Document> documentReference;
-    OwnPtr<ExecutionContextTask> task;
-};
-
-void Document::didReceiveTask(void* untypedContext)
-{
-    ASSERT(isMainThread());
-
-    OwnPtr<PerformTaskContext> context = adoptPtr(static_cast<PerformTaskContext*>(untypedContext));
-    ASSERT(context);
-
-    Document* document = context->documentReference.get();
-    if (!document)
-        return;
-
-    Page* page = document->page();
-    if ((page && page->defersLoading()) || !document->m_pendingTasks.isEmpty()) {
-        document->m_pendingTasks.append(context->task.release());
-        return;
-    }
-
-    context->task->performTask(document);
-}
-
+// FIXME(crbug.com/305497): This should be removed after ExecutionContext-DOMWindow migration.
 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
 {
-    callOnMainThread(didReceiveTask, new PerformTaskContext(m_weakFactory.createWeakPtr(), task));
+    m_taskRunner->postTask(task);
 }
 
-void Document::pendingTasksTimerFired(Timer<Document>*)
+void Document::tasksWereSuspended()
 {
-    while (!m_pendingTasks.isEmpty()) {
-        OwnPtr<ExecutionContextTask> task = m_pendingTasks[0].release();
-        m_pendingTasks.remove(0);
-        task->performTask(this);
-    }
-}
-
-void Document::suspendScheduledTasks()
-{
-    ASSERT(!m_scheduledTasksAreSuspended);
-
-    suspendScriptedAnimationControllerCallbacks();
-    suspendActiveDOMObjects();
     scriptRunner()->suspend();
-    m_pendingTasksTimer.stop();
+
     if (m_parser)
         m_parser->suspendScheduledTasks();
-
-    m_scheduledTasksAreSuspended = true;
-}
-
-void Document::resumeScheduledTasks()
-{
-    ASSERT(m_scheduledTasksAreSuspended);
-
-    if (m_parser)
-        m_parser->resumeScheduledTasks();
-    if (!m_pendingTasks.isEmpty())
-        m_pendingTasksTimer.startOneShot(0);
-    scriptRunner()->resume();
-    resumeActiveDOMObjects();
-    resumeScriptedAnimationControllerCallbacks();
-
-    m_scheduledTasksAreSuspended = false;
-}
-
-void Document::suspendScriptedAnimationControllerCallbacks()
-{
     if (m_scriptedAnimationController)
         m_scriptedAnimationController->suspend();
 }
 
-void Document::resumeScriptedAnimationControllerCallbacks()
+void Document::tasksWereResumed()
 {
+    scriptRunner()->resume();
+
+    if (m_parser)
+        m_parser->resumeScheduledTasks();
     if (m_scriptedAnimationController)
         m_scriptedAnimationController->resume();
 }
 
+// FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
+// should be moved to DOMWindow once it inherits ExecutionContext
+void Document::suspendScheduledTasks()
+{
+    ExecutionContext::suspendScheduledTasks();
+    m_taskRunner->suspend();
+}
+
+void Document::resumeScheduledTasks()
+{
+    ExecutionContext::resumeScheduledTasks();
+    m_taskRunner->resume();
+}
+
+bool Document::tasksNeedSuspension()
+{
+    Page* page = this->page();
+    return page && page->defersLoading();
+}
+
 void Document::addToTopLayer(Element* element, const Element* before)
 {
     if (element->isInTopLayer())
@@ -4923,7 +4921,7 @@
     return node;
 }
 
-void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject* renderer)
+void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
 {
     if (!view())
         return;
@@ -4935,7 +4933,7 @@
     }
 }
 
-void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject* renderer)
+void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
 {
     if (!view())
         return;
@@ -5047,6 +5045,7 @@
 
     // Locate the common ancestor render object for the two renderers.
     RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
+    RefPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
 
     Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
     Vector<RefPtr<Node>, 32> nodesToAddToChain;
@@ -5113,7 +5112,7 @@
     size_t addCount = nodesToAddToChain.size();
     for (size_t i = 0; i < addCount; ++i) {
         // Elements past the common ancestor do not change hover state, but might change active state.
-        if (ancestor && nodesToAddToChain[i] == ancestor->node())
+        if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
             sawCommonAncestor = true;
         if (allowActiveChanges)
             nodesToAddToChain[i]->setActive(true);
@@ -5129,7 +5128,7 @@
 
 bool Document::haveStylesheetsLoaded() const
 {
-    return !m_styleEngine->hasPendingSheets() || m_ignorePendingStylesheets;
+    return m_styleEngine->haveStylesheetsLoaded();
 }
 
 Locale& Document::getCachedLocale(const AtomicString& locale)
@@ -5149,8 +5148,7 @@
         return *const_cast<Document*>(document);
 
     if (isHTMLDocument()) {
-        DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL())
-            .withRegistrationContext(registrationContext());
+        DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL());
         m_templateDocument = HTMLDocument::create(init);
     } else {
         m_templateDocument = Document::create(DocumentInit(blankURL()));
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 00a32b9..65ea92a 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -29,8 +29,10 @@
 #define Document_h
 
 #include "bindings/v8/ScriptValue.h"
+#include "core/animation/css/CSSPendingAnimations.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/DOMTimeStamp.h"
+#include "core/dom/DocumentEncodingData.h"
 #include "core/dom/DocumentInit.h"
 #include "core/dom/DocumentLifecycle.h"
 #include "core/dom/DocumentSupplementable.h"
@@ -49,7 +51,7 @@
 #include "core/page/PageVisibilityState.h"
 #include "core/rendering/HitTestRequest.h"
 #include "platform/Timer.h"
-#include "weborigin/ReferrerPolicy.h"
+#include "platform/weborigin/ReferrerPolicy.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -93,6 +95,7 @@
 class Event;
 class EventListener;
 class ExceptionState;
+class MainThreadTaskRunner;
 class FloatQuad;
 class FloatRect;
 class FormController;
@@ -152,7 +155,6 @@
 class StyleSheetList;
 class Text;
 class TextAutosizer;
-class TextResourceDecoder;
 class Touch;
 class TouchList;
 class TransformSource;
@@ -220,6 +222,8 @@
 
     MediaQueryMatcher& mediaQueryMatcher();
 
+    void mediaQueryAffectingValueChanged();
+
     using ContainerNode::ref;
     using ContainerNode::deref;
     using SecurityContext::securityOrigin;
@@ -292,7 +296,6 @@
     PassRefPtr<Element> createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState&);
     PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
 
-    bool cssCompositingEnabled() const;
     PassRefPtr<DOMNamedFlowCollection> webkitGetNamedFlows();
 
     NamedFlowCollection* namedFlows();
@@ -351,8 +354,8 @@
 
     virtual KURL baseURI() const;
 
-    String webkitVisibilityState() const;
-    bool webkitHidden() const;
+    String visibilityState() const;
+    bool hidden() const;
     void dispatchVisibilityStateChangeEvent();
 
     DOMSecurityPolicy* securityPolicy();
@@ -361,7 +364,6 @@
 
     PassRefPtr<HTMLCollection> images();
     PassRefPtr<HTMLCollection> embeds();
-    PassRefPtr<HTMLCollection> plugins(); // an alias for embeds() required for the JS DOM bindings.
     PassRefPtr<HTMLCollection> applets();
     PassRefPtr<HTMLCollection> links();
     PassRefPtr<HTMLCollection> forms();
@@ -387,20 +389,14 @@
     bool isSrcdocDocument() const { return m_isSrcdocDocument; }
     bool isMobileDocument() const { return m_isMobileDocument; }
 
-    StyleResolver* styleResolverIfExists() const { return m_styleResolver.get(); }
+    StyleResolver* styleResolverIfExists() const;
+    StyleResolver* styleResolver() const;
 
     bool isViewSource() const { return m_isViewSource; }
     void setIsViewSource(bool);
 
     bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
 
-    StyleResolver* styleResolver()
-    {
-        if (!m_styleResolver)
-            createStyleResolver();
-        return m_styleResolver.get();
-    }
-
     void notifyRemovePendingSheetIfNeeded();
 
     bool haveStylesheetsLoaded() const;
@@ -424,8 +420,6 @@
     void modifiedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
     void changedSelectorWatch() { styleResolverChanged(RecalcStyleDeferred); }
 
-    void didAccessStyleResolver() { ++m_styleResolverAccessCount; }
-
     void evaluateMediaQueryList();
 
     // Never returns 0.
@@ -462,7 +456,11 @@
     void updateStyleIfNeeded();
     void updateStyleForNodeIfNeeded(Node*);
     void updateLayout();
-    void updateLayoutIgnorePendingStylesheets();
+    enum RunPostLayoutTasks {
+        RunPostLayoutTasksAsyhnchronously,
+        RunPostLayoutTasksSynchronously,
+    };
+    void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasksAsyhnchronously);
     void partialUpdateLayoutIgnorePendingStylesheets(Node*);
     PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
     PassRefPtr<RenderStyle> styleForPage(int pageIndex);
@@ -485,7 +483,6 @@
     void prepareForDestruction();
 
     RenderView* renderView() const { return m_renderView; }
-    void clearRenderView() { m_renderView = 0; }
 
     AXObjectCache* existingAXObjectCache() const;
     AXObjectCache* axObjectCache() const;
@@ -650,7 +647,7 @@
     void nodeChildrenWillBeRemoved(ContainerNode*);
     // nodeWillBeRemoved is only safe when removing one node at a time.
     void nodeWillBeRemoved(Node&);
-    bool canReplaceChild(Node& newChild, Node& oldChild);
+    bool canReplaceChild(const Node& newChild, const Node& oldChild) const;
 
     void didInsertText(Node*, unsigned offset, unsigned length);
     void didRemoveText(Node*, unsigned offset, unsigned length);
@@ -818,8 +815,7 @@
     bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
     void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
 
-    const Vector<IconURL>& shortcutIconURLs();
-    const Vector<IconURL>& iconURLs(int iconTypesMask);
+    Vector<IconURL> iconURLs(int iconTypesMask);
 
     void setUseSecureKeyboardEntryWhenActive(bool);
     bool useSecureKeyboardEntryWhenActive() const;
@@ -834,18 +830,22 @@
     bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
     void parseDNSPrefetchControlHeader(const String&);
 
-    virtual void postTask(PassOwnPtr<ExecutionContextTask>); // Executes the task on context's thread asynchronously.
+    // FIXME(crbug.com/305497): This should be removed once DOMWindow is an ExecutionContext.
+    virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
 
-    void suspendScriptedAnimationControllerCallbacks();
-    void resumeScriptedAnimationControllerCallbacks();
+    virtual void tasksWereSuspended() OVERRIDE;
+    virtual void tasksWereResumed() OVERRIDE;
+    virtual void suspendScheduledTasks() OVERRIDE;
+    virtual void resumeScheduledTasks() OVERRIDE;
+    virtual bool tasksNeedSuspension() OVERRIDE;
 
     void finishedParsing();
 
-    void setDecoder(PassRefPtr<TextResourceDecoder>);
-    TextResourceDecoder* decoder() const { return m_decoder.get(); }
+    void setEncodingData(const DocumentEncodingData& newData);
+    const WTF::TextEncoding& encoding() const { return m_encodingData.encoding; }
 
-    void setEncoding(const WTF::TextEncoding&);
-    const WTF::TextEncoding& encoding() const { return m_encoding; }
+    bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically; }
+    bool sawDecodingError() const { return m_encodingData.sawDecodingError; }
 
     void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
     bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
@@ -892,8 +892,9 @@
     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
     void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
 
+    void enqueueResizeEvent();
     void enqueueScrollEventForNode(Node*);
-    void scheduleAnimationFrameEvent(PassRefPtr<Event>);
+    void enqueueAnimationFrameEvent(PassRefPtr<Event>);
 
     const QualifiedName& idAttributeName() const { return m_idAttributeName; }
 
@@ -936,9 +937,6 @@
 
     bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
 
-    void suspendScheduledTasks();
-    void resumeScheduledTasks();
-
     IntSize initialViewportSize() const;
 
     TextAutosizer* textAutosizer() { return m_textAutosizer.get(); }
@@ -954,8 +952,8 @@
     bool haveImportsLoaded() const;
     void didLoadAllImports();
 
-    void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject*);
-    void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject*);
+    void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject&);
+    void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject&);
 
     bool hasActiveParser();
     unsigned activeParserCount() { return m_activeParserCount; }
@@ -980,6 +978,7 @@
     AnimationClock& animationClock() { return *m_animationClock; }
     DocumentTimeline* timeline() const { return m_timeline.get(); }
     DocumentTimeline* transitionTimeline() const { return m_transitionTimeline.get(); }
+    CSSPendingAnimations& cssPendingAnimations() { return m_cssPendingAnimations; }
 
     void addToTopLayer(Element*, const Element* before = 0);
     void removeFromTopLayer(Element*);
@@ -1000,7 +999,6 @@
 
     DocumentLifecycleNotifier& lifecycleNotifier();
     bool isActive() const { return m_lifecyle.state() == DocumentLifecycle::Active; }
-    bool isStopping() const { return m_lifecyle.state() == DocumentLifecycle::Stopping; }
     bool isStopped() const { return m_lifecyle.state() == DocumentLifecycle::Stopped; }
 
     enum HttpRefreshType {
@@ -1061,8 +1059,6 @@
     void updateFocusAppearanceTimerFired(Timer<Document>*);
     void updateBaseURL();
 
-    void createStyleResolver();
-
     void executeScriptsWaitingForResourcesIfNeeded();
 
     void seamlessParentUpdatedStylesheets();
@@ -1073,11 +1069,7 @@
 
     void loadEventDelayTimerFired(Timer<Document>*);
 
-    void pendingTasksTimerFired(Timer<Document>*);
-
-    static void didReceiveTask(void*);
-
-    PageVisibilityState visibilityState() const;
+    PageVisibilityState pageVisibilityState() const;
 
     PassRefPtr<HTMLCollection> ensureCachedCollection(CollectionType);
 
@@ -1100,18 +1092,8 @@
 
     DocumentLifecycle m_lifecyle;
 
-    // FIXME: This should probably be handled inside the style resolver itself.
-    Timer<Document> m_styleResolverThrowawayTimer;
-    unsigned m_styleResolverAccessCount;
-    unsigned m_lastStyleResolverAccessCount;
-
-    OwnPtr<StyleResolver> m_styleResolver;
-    bool m_didCalculateStyleResolver;
     bool m_hasNodesWithPlaceholderStyle;
     bool m_needsNotifyRemoveAllPendingStylesheet;
-    // But sometimes you need to ignore pending stylesheet count to
-    // force an immediate layout when requested by JS.
-    bool m_ignorePendingStylesheets;
     bool m_evaluateMediaQueriesOnStyleRecalc;
 
     // If we do ignore the pending stylesheet count, then we need to add a boolean
@@ -1231,8 +1213,7 @@
 
     String m_contentLanguage;
 
-    RefPtr<TextResourceDecoder> m_decoder;
-    WTF::TextEncoding m_encoding;
+    DocumentEncodingData m_encodingData;
 
     InheritedBool m_designMode;
 
@@ -1247,8 +1228,6 @@
 
     HashMap<String, RefPtr<HTMLCanvasElement> > m_cssCanvasElements;
 
-    Vector<IconURL> m_iconURLs;
-
     OwnPtr<SelectorQueryCache> m_selectorQueryCache;
 
     bool m_useSecureKeyboardEntryWhenActive;
@@ -1294,16 +1273,11 @@
     double m_lastHandledUserGestureTimestamp;
 
     RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
-
-    Timer<Document> m_pendingTasksTimer;
-    Vector<OwnPtr<ExecutionContextTask> > m_pendingTasks;
-
+    OwnPtr<MainThreadTaskRunner> m_taskRunner;
     OwnPtr<TextAutosizer> m_textAutosizer;
 
     RefPtr<CustomElementRegistrationContext> m_registrationContext;
 
-    bool m_scheduledTasksAreSuspended;
-
     RefPtr<NamedFlowCollection> m_namedFlows;
 
     RefPtr<DOMSecurityPolicy> m_domSecurityPolicy;
@@ -1323,6 +1297,7 @@
     OwnPtr<AnimationClock> m_animationClock;
     RefPtr<DocumentTimeline> m_timeline;
     RefPtr<DocumentTimeline> m_transitionTimeline;
+    CSSPendingAnimations m_cssPendingAnimations;
 
     RefPtr<Document> m_templateDocument;
     Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index ba1e205..f5f0b83 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;
 
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Element createElement([TreatNullAs=NullString,Default=Undefined] optional DOMString tagName);
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, 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:
 
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Node importNode([Default=Undefined] optional Node importedNode,
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node importNode([Default=Undefined] optional Node importedNode,
                     optional boolean deep);
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                             [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName);
     [RaisesException, MeasureAs=DocumentCreateAttributeNS] Attr createAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                                                   [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName); // Removed from DOM4.
@@ -56,8 +56,8 @@
     [TreatReturnedNullStringAs=Null, MeasureAs=DocumentInputEncoding] readonly attribute DOMString inputEncoding; // Removed from DOM4.
 
     [TreatReturnedNullStringAs=Null, MeasureAs=DocumentXMLEncoding] readonly attribute DOMString xmlEncoding; // Removed from DOM4.
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException, MeasureAs=DocumentXMLVersion] attribute DOMString xmlVersion; // Removed from DOM4.
-    [SetterRaisesException, MeasureAs=DocumentXMLStandalone] attribute boolean xmlStandalone; // Removed from DOM4.
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter, MeasureAs=DocumentXMLVersion] attribute DOMString xmlVersion; // Removed from DOM4.
+    [RaisesException=Setter, MeasureAs=DocumentXMLStandalone] attribute boolean xmlStandalone; // Removed from DOM4.
 
     [RaisesException, CustomElementCallbacks] Node               adoptNode([Default=Undefined] optional Node source);
 
@@ -113,12 +113,12 @@
 
              [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString title;
     readonly attribute DOMString referrer;
-             [TreatNullAs=NullString, SetterRaisesException] attribute DOMString domain;
+             [TreatNullAs=NullString, RaisesException=Setter] attribute DOMString domain;
     readonly attribute DOMString URL;
 
-             [TreatNullAs=NullString, GetterRaisesException, SetterRaisesException] attribute DOMString cookie;
+             [TreatNullAs=NullString, RaisesException] attribute DOMString cookie;
 
-             [SetterRaisesException, CustomElementCallbacks] attribute HTMLElement body;
+             [RaisesException=Setter, CustomElementCallbacks] attribute HTMLElement body;
 
     readonly attribute HTMLHeadElement head;
     readonly attribute HTMLCollection images;
@@ -130,7 +130,7 @@
 
     [PerWorldBindings] NodeList getElementsByName([Default=Undefined] optional DOMString elementName);
 
-    [PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, PutForwards=href] readonly attribute Location location;
+    [PerWorldBindings, ActivityLogging=ForIsolatedWorlds, PutForwards=href] readonly attribute Location location;
 
     // IE extensions
     [MeasureAs=DocumentCharset, TreatReturnedNullStringAs=Undefined, TreatNullAs=NullString] attribute DOMString charset;
@@ -187,7 +187,7 @@
     attribute EventHandler onwebkitfullscreenerror;
     attribute EventHandler onwebkitpointerlockchange;
     attribute EventHandler onwebkitpointerlockerror;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onwheel;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onwheel;
 
     [RuntimeEnabled=Touch] Touch createTouch([Default=Undefined] optional Window window,
                                                [Default=Undefined] optional EventTarget target,
@@ -204,13 +204,19 @@
 
     [DeprecateAs=PrefixedDocumentRegister, RuntimeEnabled=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
     [RuntimeEnabled=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
                             [TreatNullAs=NullString] DOMString typeExtension);
 
     // Page visibility API.
-    readonly attribute DOMString webkitVisibilityState;
-    readonly attribute boolean webkitHidden;
+    readonly attribute DOMString visibilityState;
+    readonly attribute boolean hidden;
+
+    // Deprecated prefixed page visibility API.
+    // TODO(davidben): This is a property so attaching a deprecation warning results in false positives when outputting
+    // document in the console. It's possible http://crbug.com/43394 will resolve this.
+    [MeasureAs=PrefixedPageVisibility, ImplementedAs=visibilityState] readonly attribute DOMString webkitVisibilityState;
+    [MeasureAs=PrefixedPageVisibility, ImplementedAs=hidden] readonly attribute boolean webkitHidden;
 
     // Security Policy API: http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#script-interfaces
     [RuntimeEnabled=ExperimentalContentSecurityPolicyFeatures] readonly attribute SecurityPolicy securityPolicy;
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.cpp b/Source/core/dom/DocumentEncodingData.h
similarity index 79%
copy from Source/core/workers/WorkerGlobalScopeProxy.cpp
copy to Source/core/dom/DocumentEncodingData.h
index 06471bb..d41c078 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ b/Source/core/dom/DocumentEncodingData.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 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,11 +28,23 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
+#ifndef DocumentEncodingData_h
+#define DocumentEncodingData_h
 
 namespace WebCore {
 
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
+struct DocumentEncodingData {
+    DocumentEncodingData()
+        : wasDetectedHeuristically(false)
+        , sawDecodingError(false)
+    {
+    }
+
+    WTF::TextEncoding encoding;
+    bool wasDetectedHeuristically;
+    bool sawDecodingError;
+};
 
 } // namespace WebCore
+
+#endif // DocumentEncodingData_h
diff --git a/Source/core/dom/DocumentInit.h b/Source/core/dom/DocumentInit.h
index 136d400..911d14f 100644
--- a/Source/core/dom/DocumentInit.h
+++ b/Source/core/dom/DocumentInit.h
@@ -30,7 +30,7 @@
 
 #include "core/dom/SandboxFlags.h"
 #include "core/dom/SecurityContext.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 #include "wtf/WeakPtr.h"
diff --git a/Source/core/dom/DocumentMarker.cpp b/Source/core/dom/DocumentMarker.cpp
index 5f3db28..12b9039 100644
--- a/Source/core/dom/DocumentMarker.cpp
+++ b/Source/core/dom/DocumentMarker.cpp
@@ -84,8 +84,8 @@
 
 PassRefPtr<DocumentMarkerTextMatch> DocumentMarkerTextMatch::instanceFor(bool match)
 {
-    DEFINE_STATIC_LOCAL(RefPtr<DocumentMarkerTextMatch>, trueInstance, (adoptRef(new DocumentMarkerTextMatch(true))));
-    DEFINE_STATIC_LOCAL(RefPtr<DocumentMarkerTextMatch>, falseInstance, (adoptRef(new DocumentMarkerTextMatch(false))));
+    DEFINE_STATIC_REF(DocumentMarkerTextMatch, trueInstance, (adoptRef(new DocumentMarkerTextMatch(true))));
+    DEFINE_STATIC_REF(DocumentMarkerTextMatch, falseInstance, (adoptRef(new DocumentMarkerTextMatch(false))));
     return match ? trueInstance : falseInstance;
 }
 
diff --git a/Source/core/dom/DocumentMarkerController.cpp b/Source/core/dom/DocumentMarkerController.cpp
index 554c511..be763b1 100644
--- a/Source/core/dom/DocumentMarkerController.cpp
+++ b/Source/core/dom/DocumentMarkerController.cpp
@@ -75,7 +75,7 @@
 {
 }
 
-void DocumentMarkerController::detach()
+void DocumentMarkerController::clear()
 {
     m_markers.clear();
     m_possiblyExistingMarkerTypes = 0;
@@ -140,6 +140,20 @@
     }
 }
 
+void DocumentMarkerController::nodeWillBeRemoved(const Node& node)
+{
+    if (!possiblyHasMarkers(DocumentMarker::AllMarkers()))
+        return;
+    m_markers.remove(&node);
+    if (m_markers.isEmpty())
+        m_possiblyExistingMarkerTypes = 0;
+}
+
+void DocumentMarkerController::prepareForDestruction()
+{
+    clear();
+}
+
 void DocumentMarkerController::removeMarkers(Range* range, DocumentMarker::MarkerTypes markerTypes, RemovePartiallyOverlappingMarkerOrNot shouldRemovePartiallyOverlappingMarker)
 {
     for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
@@ -439,7 +453,7 @@
     ASSERT(endContainer);
 
     Node* pastLastNode = range->pastLastNode();
-    for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(node)) {
+    for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(*node)) {
         Vector<DocumentMarker*> markers = markersFor(node);
         Vector<DocumentMarker*>::const_iterator end = markers.end();
         for (Vector<DocumentMarker*>::const_iterator it = markers.begin(); it != end; ++it) {
@@ -504,7 +518,7 @@
         return;
     ASSERT(!m_markers.isEmpty());
 
-    Vector<RefPtr<Node> > nodesWithMarkers;
+    Vector<const Node*> nodesWithMarkers;
     copyKeysToVector(m_markers, nodesWithMarkers);
     unsigned size = nodesWithMarkers.size();
     for (unsigned i = 0; i < size; ++i) {
@@ -568,7 +582,7 @@
     // outer loop: process each markered node in the document
     MarkerMap::iterator end = m_markers.end();
     for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
-        Node* node = i->key.get();
+        const Node* node = i->key;
 
         // inner loop: process each marker in the current node
         MarkerLists* markers = i->value.get();
@@ -644,7 +658,7 @@
 
     Node* pastLastNode = range->pastLastNode();
 
-    for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(node)) {
+    for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(*node)) {
         int startOffset = node == startContainer ? range->startOffset() : 0;
         int endOffset = node == endContainer ? range->endOffset() : INT_MAX;
         setMarkersActive(node, startOffset, endOffset, active);
@@ -689,7 +703,7 @@
     ASSERT(endContainer);
 
     Node* pastLastNode = range->pastLastNode();
-    for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(node)) {
+    for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(*node)) {
         Vector<DocumentMarker*> markers = markersFor(node);
         Vector<DocumentMarker*>::const_iterator end = markers.end();
         for (Vector<DocumentMarker*>::const_iterator it = markers.begin(); it != end; ++it) {
@@ -712,7 +726,7 @@
     fprintf(stderr, "%d nodes have markers:\n", m_markers.size());
     MarkerMap::const_iterator end = m_markers.end();
     for (MarkerMap::const_iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
-        Node* node = nodeIterator->key.get();
+        const Node* node = nodeIterator->key;
         fprintf(stderr, "%p", node);
         MarkerLists* markers = m_markers.get(node);
         for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
diff --git a/Source/core/dom/DocumentMarkerController.h b/Source/core/dom/DocumentMarkerController.h
index 97e5d37..bae5e11 100644
--- a/Source/core/dom/DocumentMarkerController.h
+++ b/Source/core/dom/DocumentMarkerController.h
@@ -47,7 +47,7 @@
     DocumentMarkerController();
     ~DocumentMarkerController();
 
-    void detach();
+    void clear();
     void addMarker(Range*, DocumentMarker::MarkerType);
     void addMarker(Range*, DocumentMarker::MarkerType, const String& description);
     void addMarker(Range*, DocumentMarker::MarkerType, const String& description, uint32_t hash);
@@ -58,6 +58,8 @@
     void copyMarkers(Node* srcNode, unsigned startOffset, int length, Node* dstNode, int delta);
     bool hasMarkers(Range*, DocumentMarker::MarkerTypes = DocumentMarker::AllMarkers());
 
+    void nodeWillBeRemoved(const Node&);
+    void prepareForDestruction();
     // When a marker partially overlaps with range, if removePartiallyOverlappingMarkers is true, we completely
     // remove the marker. If the argument is false, we will adjust the span of the marker so that it retains
     // the portion that is outside of the range.
@@ -88,7 +90,7 @@
 
     typedef Vector<RenderedDocumentMarker> MarkerList;
     typedef Vector<OwnPtr<MarkerList>, DocumentMarker::MarkerTypeIndexesCount> MarkerLists;
-    typedef HashMap<RefPtr<Node>, OwnPtr<MarkerLists> > MarkerMap;
+    typedef HashMap<const Node*, OwnPtr<MarkerLists> > MarkerMap;
     void mergeOverlapping(MarkerList*, DocumentMarker&);
     bool possiblyHasMarkers(DocumentMarker::MarkerTypes);
     void removeMarkersFromList(MarkerMap::iterator, DocumentMarker::MarkerTypes);
diff --git a/Source/core/dom/DocumentOrderedMap.cpp b/Source/core/dom/DocumentOrderedMap.cpp
index bd58170..494d266 100644
--- a/Source/core/dom/DocumentOrderedMap.cpp
+++ b/Source/core/dom/DocumentOrderedMap.cpp
@@ -122,7 +122,8 @@
 
     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)) {
+        ASSERT(scope->rootNode());
+        for (element = ElementTraversal::firstWithin(*scope->rootNode()); element; element = ElementTraversal::next(*element)) {
             if (!keyMatches(key, element))
                 continue;
             m_duplicateCounts.remove(key);
diff --git a/Source/core/dom/DocumentParser.cpp b/Source/core/dom/DocumentParser.cpp
index dcafb09..ac2ffa9 100644
--- a/Source/core/dom/DocumentParser.cpp
+++ b/Source/core/dom/DocumentParser.cpp
@@ -25,6 +25,7 @@
 
 #include "config.h"
 #include "core/dom/DocumentParser.h"
+#include "core/fetch/TextResourceDecoder.h"
 
 #include "wtf/Assertions.h"
 
@@ -46,6 +47,16 @@
     ASSERT(!m_document);
 }
 
+void DocumentParser::setDecoder(PassOwnPtr<TextResourceDecoder>)
+{
+    ASSERT_NOT_REACHED();
+}
+
+TextResourceDecoder* DocumentParser::decoder()
+{
+    return 0;
+}
+
 void DocumentParser::startParsing()
 {
     m_state = ParsingState;
diff --git a/Source/core/dom/DocumentParser.h b/Source/core/dom/DocumentParser.h
index 3b3969b..c0b502a 100644
--- a/Source/core/dom/DocumentParser.h
+++ b/Source/core/dom/DocumentParser.h
@@ -26,6 +26,7 @@
 
 #include "wtf/Forward.h"
 #include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
@@ -33,6 +34,7 @@
 class DocumentWriter;
 class SegmentedString;
 class ScriptableDocumentParser;
+class TextResourceDecoder;
 
 class DocumentParser : public RefCounted<DocumentParser> {
 public:
@@ -46,10 +48,13 @@
     // insert is used by document.write.
     virtual void insert(const SegmentedString&) = 0;
 
-    // appendBytes and flush are used by DocumentWriter (the loader).
-    virtual size_t appendBytes(const char* bytes, size_t length) = 0;
-    virtual size_t flush() = 0;
+    // The below functions are used by DocumentWriter (the loader).
+    virtual void appendBytes(const char* bytes, size_t length) = 0;
+    virtual void flush() = 0;
     virtual bool needsDecoder() const { return false; }
+    virtual void setDecoder(PassOwnPtr<TextResourceDecoder>);
+    virtual TextResourceDecoder* decoder();
+    virtual void setHasAppendedData() { }
 
     // pinToMainThread also makes append() not yield before completion of that chunk.
     virtual void pinToMainThread() { }
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index 95d2c79..87a308c 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -52,11 +52,8 @@
     ASSERT(treeScope.rootNode() == treeScope.rootNode()->document());
 }
 
-void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection)
 {
-    if (document()->settings() && !document()->settings()->authorAndUserStylesEnabled())
-        return;
-
     DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
     DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
     for (DocumentOrderedList::iterator it = begin; it != end; ++it) {
@@ -76,7 +73,7 @@
             }
             sheet = pi->sheet();
             if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
-                activeSheet = static_cast<CSSStyleSheet*>(sheet);
+                activeSheet = toCSSStyleSheet(sheet);
         } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))) || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))) {
             Element* e = toElement(n);
             AtomicString title = e->getAttribute(titleAttr);
@@ -87,11 +84,11 @@
                 enabledViaScript = linkElement->isEnabledViaScript();
                 if (!linkElement->isDisabled() && linkElement->styleSheetIsLoading()) {
                     // it is loading but we should still decide which style sheet set to use
-                    if (!enabledViaScript && !title.isEmpty() && collections->preferredStylesheetSetName().isEmpty()) {
+                    if (!enabledViaScript && !title.isEmpty() && engine->preferredStylesheetSetName().isEmpty()) {
                         const AtomicString& rel = e->getAttribute(relAttr);
                         if (!rel.contains("alternate")) {
-                            collections->setPreferredStylesheetSetName(title);
-                            collections->setSelectedStylesheetSetName(title);
+                            engine->setPreferredStylesheetSetName(title);
+                            engine->setSelectedStylesheetSetName(title);
                         }
                     }
 
@@ -107,7 +104,7 @@
             }
 
             if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
-                activeSheet = static_cast<CSSStyleSheet*>(sheet);
+                activeSheet = toCSSStyleSheet(sheet);
 
             // Check to see if this sheet belongs to a styleset
             // (thus making it PREFERRED or ALTERNATE rather than
@@ -115,73 +112,72 @@
             AtomicString rel = e->getAttribute(relAttr);
             if (!enabledViaScript && sheet && !title.isEmpty()) {
                 // Yes, we have a title.
-                if (collections->preferredStylesheetSetName().isEmpty()) {
+                if (engine->preferredStylesheetSetName().isEmpty()) {
                     // No preferred set has been established. If
                     // we are NOT an alternate sheet, then establish
                     // us as the preferred set. Otherwise, just ignore
                     // this sheet.
                     if (e->hasLocalName(styleTag) || !rel.contains("alternate")) {
-                        collections->setPreferredStylesheetSetName(title);
-                        collections->setSelectedStylesheetSetName(title);
+                        engine->setPreferredStylesheetSetName(title);
+                        engine->setSelectedStylesheetSetName(title);
                     }
                 }
-                if (title != collections->preferredStylesheetSetName())
+                if (title != engine->preferredStylesheetSetName())
                     activeSheet = 0;
             }
 
             if (rel.contains("alternate") && title.isEmpty())
                 activeSheet = 0;
         }
+
         if (sheet)
-            styleSheets.append(sheet);
+            collection.appendSheetForList(sheet);
         if (activeSheet)
-            activeSheets.append(activeSheet);
+            collection.appendActiveStyleSheet(activeSheet);
     }
 }
 
-static void collectActiveCSSStyleSheetsFromSeamlessParents(Vector<RefPtr<CSSStyleSheet> >& sheets, Document* document)
+static void collectActiveCSSStyleSheetsFromSeamlessParents(StyleSheetCollectionBase& collection, Document* document)
 {
     HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
     if (!seamlessParentIFrame)
         return;
-    sheets.append(seamlessParentIFrame->document().styleEngine()->activeAuthorStyleSheets());
+    collection.appendActiveStyleSheets(seamlessParentIFrame->document().styleEngine()->activeAuthorStyleSheets());
 }
 
-bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* collections, StyleResolverUpdateMode updateMode)
+bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
 {
-    Vector<RefPtr<StyleSheet> > styleSheets;
-    Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
-    activeCSSStyleSheets.append(collections->injectedAuthorStyleSheets());
-    activeCSSStyleSheets.append(collections->documentAuthorStyleSheets());
-    collectActiveCSSStyleSheetsFromSeamlessParents(activeCSSStyleSheets, document());
-    collectStyleSheets(collections, styleSheets, activeCSSStyleSheets);
+    StyleSheetCollectionBase collection;
+    collection.appendActiveStyleSheets(engine->injectedAuthorStyleSheets());
+    collection.appendActiveStyleSheets(engine->documentAuthorStyleSheets());
+    collectActiveCSSStyleSheetsFromSeamlessParents(collection, document());
+    collectStyleSheets(engine, collection);
 
-    StyleResolverUpdateType styleResolverUpdateType;
-    bool requiresFullStyleRecalc;
-    analyzeStyleSheetChange(updateMode, activeAuthorStyleSheets(), activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
+    StyleSheetChange change;
+    analyzeStyleSheetChange(updateMode, collection, change);
 
-    if (styleResolverUpdateType == Reconstruct) {
-        document()->clearStyleResolver();
-    } else {
-        StyleResolver* styleResolver = document()->styleResolverIfExists();
-        ASSERT(styleResolver);
+    if (change.styleResolverUpdateType == Reconstruct) {
+        engine->clearResolver();
+    } else if (StyleResolver* styleResolver = engine->resolverIfExists()) {
         // FIXME: We might have already had styles in child treescope. In this case, we cannot use buildScopedStyleTreeInDocumentOrder.
         // Need to change "false" to some valid condition.
         styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
-        if (styleResolverUpdateType == Reset) {
+        if (change.styleResolverUpdateType != Additive) {
+            ASSERT(change.styleResolverUpdateType == Reset || change.styleResolverUpdateType == ResetStyleResolverAndFontSelector);
             resetAllRuleSetsInTreeScope(styleResolver);
-            styleResolver->appendAuthorStyleSheets(0, activeCSSStyleSheets);
+            if (change.styleResolverUpdateType == ResetStyleResolverAndFontSelector)
+                styleResolver->resetFontSelector();
+            styleResolver->removePendingAuthorStyleSheets(m_activeAuthorStyleSheets);
+            styleResolver->lazyAppendAuthorStyleSheets(0, collection.activeAuthorStyleSheets());
         } else {
-            ASSERT(styleResolverUpdateType == Additive);
-            styleResolver->appendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), activeCSSStyleSheets);
+            styleResolver->lazyAppendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), collection.activeAuthorStyleSheets());
         }
     }
     m_scopingNodesForStyleScoped.didRemoveScopingNodes();
-    m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
-    m_styleSheetsForStyleSheetList.swap(styleSheets);
+    collection.swap(*this);
     updateUsesRemUnits();
 
-    return requiresFullStyleRecalc;
+    return change.requiresFullStyleRecalc;
 }
 
 }
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index 1a039fb..cefe7da 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -46,7 +46,7 @@
     bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
 
 private:
-    void collectStyleSheets(StyleEngine*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+    void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&);
 };
 
 }
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index 36cdb70..893d1dc 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -64,7 +64,6 @@
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/dom/SelectorQuery.h"
 #include "core/dom/Text.h"
-#include "core/dom/WhitespaceChildList.h"
 #include "core/dom/custom/CustomElement.h"
 #include "core/dom/custom/CustomElementRegistrationContext.h"
 #include "core/dom/shadow/InsertionPoint.h"
@@ -89,11 +88,12 @@
 #include "core/html/HTMLTableRowsCollection.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/FocusController.h"
 #include "core/page/Page.h"
 #include "core/page/PointerLockController.h"
 #include "core/rendering/FlowThreadController.h"
-#include "core/rendering/RenderRegion.h"
+#include "core/rendering/RenderNamedFlowFragment.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "core/svg/SVGDocumentExtensions.h"
@@ -110,7 +110,7 @@
 
 class StyleResolverParentPusher {
 public:
-    StyleResolverParentPusher(Element* parent)
+    explicit StyleResolverParentPusher(Element& parent)
         : m_parent(parent)
         , m_pushedStyleResolver(0)
     {
@@ -119,7 +119,7 @@
     {
         if (m_pushedStyleResolver)
             return;
-        m_pushedStyleResolver = m_parent->document().styleResolver();
+        m_pushedStyleResolver = m_parent.document().styleResolver();
         m_pushedStyleResolver->pushParentElement(m_parent);
     }
     ~StyleResolverParentPusher()
@@ -130,15 +130,15 @@
 
         // This tells us that our pushed style selector is in a bad state,
         // so we should just bail out in that scenario.
-        ASSERT(m_pushedStyleResolver == m_parent->document().styleResolver());
-        if (m_pushedStyleResolver != m_parent->document().styleResolver())
+        ASSERT(m_pushedStyleResolver == m_parent.document().styleResolver());
+        if (m_pushedStyleResolver != m_parent.document().styleResolver())
             return;
 
         m_pushedStyleResolver->popParentElement(m_parent);
     }
 
 private:
-    Element* m_parent;
+    Element& m_parent;
     StyleResolver* m_pushedStyleResolver;
 };
 
@@ -179,11 +179,12 @@
     element->setHasSyntheticAttrChildNodes(false);
 }
 
-static Attr* findAttrNodeInList(AttrNodeList& attrNodeList, const QualifiedName& name)
+static Attr* findAttrNodeInList(const AttrNodeList& attrNodeList, const QualifiedName& name)
 {
-    for (unsigned i = 0; i < attrNodeList.size(); ++i) {
-        if (attrNodeList[i]->qualifiedName() == name)
-            return attrNodeList[i].get();
+    AttrNodeList::const_iterator end = attrNodeList.end();
+    for (AttrNodeList::const_iterator it = attrNodeList.begin(); it != end; ++it) {
+        if ((*it)->qualifiedName() == name)
+            return it->get();
     }
     return 0;
 }
@@ -378,7 +379,7 @@
 
 ActiveAnimations* Element::activeAnimations() const
 {
-    if (hasActiveAnimations())
+    if (hasRareData())
         return elementRareData()->activeAnimations();
     return 0;
 }
@@ -528,16 +529,16 @@
     scrollByUnits(pages, ScrollByPage);
 }
 
-static float localZoomForRenderer(RenderObject* renderer)
+static float localZoomForRenderer(RenderObject& renderer)
 {
     // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
     // other out, but the alternative is that we'd have to crawl up the whole render tree every
     // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
     float zoomFactor = 1;
-    if (renderer->style()->effectiveZoom() != 1) {
+    if (renderer.style()->effectiveZoom() != 1) {
         // Need to find the nearest enclosing RenderObject that set up
         // a differing zoom, and then we divide our result by it to eliminate the zoom.
-        RenderObject* prev = renderer;
+        RenderObject* prev = &renderer;
         for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
             if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
                 zoomFactor = prev->style()->zoom();
@@ -551,7 +552,7 @@
     return zoomFactor;
 }
 
-static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
+static int adjustForLocalZoom(LayoutUnit value, RenderObject& renderer)
 {
     float zoomFactor = localZoomForRenderer(renderer);
     if (zoomFactor == 1)
@@ -563,7 +564,7 @@
 {
     document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
-        return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
+        return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), *renderer);
     return 0;
 }
 
@@ -571,7 +572,7 @@
 {
     document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
-        return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
+        return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), *renderer);
     return 0;
 }
 
@@ -581,12 +582,12 @@
 
     if (RenderBox* renderer = renderBox()) {
         if (renderer->canDetermineWidthWithoutLayout())
-            return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
+            return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), *renderer).round();
     }
 
     document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
-        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
+        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), *renderer).round();
     return 0;
 }
 
@@ -594,7 +595,7 @@
 {
     document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
-        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
+        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), *renderer).round();
     return 0;
 }
 
@@ -648,7 +649,7 @@
     }
 
     if (RenderBox* renderer = renderBox())
-        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
+        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), *renderer).round();
     return 0;
 }
 
@@ -669,7 +670,7 @@
     }
 
     if (RenderBox* renderer = renderBox())
-        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
+        return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), *renderer).round();
     return 0;
 }
 
@@ -677,7 +678,13 @@
 {
     document().updateLayoutIgnorePendingStylesheets();
 
-    if (document().documentElement() == this) {
+    if (document().documentElement() != this) {
+        if (RenderBox* rend = renderBox())
+            return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
+        return 0;
+    }
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
         if (document().inQuirksMode())
             return 0;
 
@@ -687,8 +694,6 @@
         }
     }
 
-    if (RenderBox* rend = renderBox())
-        return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
     return 0;
 }
 
@@ -696,7 +701,13 @@
 {
     document().updateLayoutIgnorePendingStylesheets();
 
-    if (document().documentElement() == this) {
+    if (document().documentElement() != this) {
+        if (RenderBox* rend = renderBox())
+            return adjustForAbsoluteZoom(rend->scrollTop(), rend);
+        return 0;
+    }
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
         if (document().inQuirksMode())
             return 0;
 
@@ -706,8 +717,6 @@
         }
     }
 
-    if (RenderBox* rend = renderBox())
-        return adjustForAbsoluteZoom(rend->scrollTop(), rend);
     return 0;
 }
 
@@ -715,7 +724,13 @@
 {
     document().updateLayoutIgnorePendingStylesheets();
 
-    if (document().documentElement() == this) {
+    if (document().documentElement() != this) {
+        if (RenderBox* rend = renderBox())
+            rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
+        return;
+    }
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
         if (document().inQuirksMode())
             return;
 
@@ -726,24 +741,21 @@
         if (!view)
             return;
 
-        // WHATWG spec says [1]: "If the element is the root element invoke scroll()
-        // with x as first argument and zero as second". Blink intentionally matches
-        // other engine's behaviors here, instead, where the 'y' scroll position is
-        // preversed. See [2].
-        // [1] http://dev.w3.org/csswg/cssom-view/#dom-element-scrollleft
-        // [2] https://www.w3.org/Bugs/Public/show_bug.cgi?id=23448
         view->setScrollPosition(IntPoint(static_cast<int>(newLeft * frame->pageZoomFactor()), view->scrollY()));
     }
-
-    if (RenderBox* rend = renderBox())
-        rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
 }
 
 void Element::setScrollTop(int newTop)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
-    if (document().documentElement() == this) {
+    if (document().documentElement() != this) {
+        if (RenderBox* rend = renderBox())
+            rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
+        return;
+    }
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
         if (document().inQuirksMode())
             return;
 
@@ -754,17 +766,8 @@
         if (!view)
             return;
 
-        // WHATWG spec says [1]: "If the element is the root element invoke scroll()
-        // with zero as first argument and y as second". Blink intentionally
-        // matches other engine's behaviors here, instead, where the 'x' scroll
-        // position is preversed. See [2].
-        // [1] http://dev.w3.org/csswg/cssom-view/#dom-element-scrolltop
-        // [2] https://www.w3.org/Bugs/Public/show_bug.cgi?id=23448
         view->setScrollPosition(IntPoint(view->scrollX(), static_cast<int>(newTop * frame->pageZoomFactor())));
     }
-
-    if (RenderBox* rend = renderBox())
-        rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
 }
 
 int Element::scrollWidth()
@@ -828,7 +831,7 @@
 
     Vector<FloatQuad> quads;
     renderBoxModelObject->absoluteQuads(quads);
-    document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
+    document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, *renderBoxModelObject);
     return ClientRectList::create(quads);
 }
 
@@ -856,7 +859,8 @@
     for (size_t i = 1; i < quads.size(); ++i)
         result.unite(quads[i].boundingBox());
 
-    document().adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
+    ASSERT(renderer());
+    document().adjustFloatRectForScrollAndAbsoluteZoom(result, *renderer());
     return ClientRect::create(result);
 }
 
@@ -883,10 +887,10 @@
     return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
 }
 
-void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& es)
+void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
 {
     if (!Document::isValidName(localName)) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
         return;
     }
 
@@ -911,7 +915,7 @@
     setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
 }
 
-inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
+ALWAYS_INLINE void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
 {
     if (newValue.isNull()) {
         if (index != kNotFound)
@@ -924,12 +928,13 @@
         return;
     }
 
-    QualifiedName existingAttributeName = attributeItem(index)->name();
+    const Attribute* existingAttribute = attributeItem(index);
+    QualifiedName existingAttributeName = existingAttribute->name();
 
     if (!inSynchronizationOfLazyAttribute)
-        willModifyAttribute(existingAttributeName, attributeItem(index)->value(), newValue);
+        willModifyAttribute(existingAttributeName, existingAttribute->value(), newValue);
 
-    if (newValue != attributeItem(index)->value()) {
+    if (newValue != existingAttribute->value()) {
         // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
         // will write into the ElementData.
         // FIXME: Refactor this so it makes some sense.
@@ -987,7 +992,7 @@
         AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
         if (newId != oldId) {
             elementData()->setIdForStyleResolution(newId);
-            shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
+            shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ensureRuleFeatureSet());
         }
     } else if (name == classAttr) {
         classAttributeChanged(newValue);
@@ -1012,7 +1017,7 @@
 inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
 {
     if (name == isAttr)
-        CustomElementRegistrationContext::setTypeExtension(this, newValue, reason == ModifiedDirectly ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
+        CustomElementRegistrationContext::setTypeExtension(this, newValue);
     attributeChanged(name, newValue, reason);
 }
 
@@ -1057,30 +1062,37 @@
 template<typename Checker>
 static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
 {
-    unsigned oldSize = oldClasses.size();
-    if (!oldSize)
+    if (!oldClasses.size())
         return checkSelectorForClassChange(newClasses, checker);
-    BitVector remainingClassBits;
-    remainingClassBits.ensureSize(oldSize);
+
     // Class vectors tend to be very short. This is faster than using a hash table.
-    unsigned newSize = newClasses.size();
-    for (unsigned i = 0; i < newSize; ++i) {
-        for (unsigned j = 0; j < oldSize; ++j) {
+    BitVector remainingClassBits;
+    remainingClassBits.ensureSize(oldClasses.size());
+
+    for (unsigned i = 0; i < newClasses.size(); ++i) {
+        bool found = false;
+        for (unsigned j = 0; j < oldClasses.size(); ++j) {
             if (newClasses[i] == oldClasses[j]) {
+                // Mark each class that is still in the newClasses so we can skip doing
+                // an n^2 search below when looking for removals. We can't break from
+                // this loop early since a class can appear more than once.
                 remainingClassBits.quickSet(j);
-                continue;
+                found = true;
             }
         }
-        if (checker.hasSelectorForClass(newClasses[i]))
+        // Class was added.
+        if (!found && checker.hasSelectorForClass(newClasses[i]))
             return true;
     }
-    for (unsigned i = 0; i < oldSize; ++i) {
-        // If the bit is not set the the corresponding class has been removed.
+
+    for (unsigned i = 0; i < oldClasses.size(); ++i) {
         if (remainingClassBits.quickGet(i))
             continue;
+        // Class was removed.
         if (checker.hasSelectorForClass(oldClasses[i]))
             return true;
     }
+
     return false;
 }
 
@@ -1095,10 +1107,10 @@
         const SpaceSplitString oldClasses = elementData()->classNames();
         elementData()->setClass(newClassString, shouldFoldCase);
         const SpaceSplitString& newClasses = elementData()->classNames();
-        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
+        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ensureRuleFeatureSet());
     } else {
         const SpaceSplitString& oldClasses = elementData()->classNames();
-        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
+        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ensureRuleFeatureSet());
         elementData()->clearClass();
     }
 
@@ -1223,10 +1235,10 @@
     return m_tagName.toString();
 }
 
-void Element::setPrefix(const AtomicString& prefix, ExceptionState& es)
+void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
 {
-    checkSetPrefix(prefix, es);
-    if (es.hadException())
+    checkSetPrefix(prefix, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
@@ -1357,22 +1369,22 @@
 {
     ASSERT(document().inStyleRecalc());
 
-    StyleResolverParentPusher parentPusher(this);
+    StyleResolverParentPusher parentPusher(*this);
 
-    // We've already been through detach when doing a lazyAttach, but we might
+    // We've already been through detach when doing an attach, but we might
     // need to clear any state that's been added since then.
     if (hasRareData() && styleChangeType() == NeedsReattachStyleChange) {
         ElementRareData* data = elementRareData();
         data->clearComputedStyle();
         data->resetDynamicRestyleObservations();
+        // Only clear the style state if we're not going to reuse the style from recalcStyle.
         if (!context.resolvedStyle)
             data->resetStyleState();
     }
 
     NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
 
-    if (RenderStyle* style = renderStyle())
-        updateCallbackSelectors(0, style);
+    addCallbackSelectors();
 
     createPseudoElementIfNeeded(BEFORE);
 
@@ -1380,8 +1392,9 @@
     if (ElementShadow* shadow = this->shadow()) {
         parentPusher.push();
         shadow->attach(context);
-    } else if (firstChild())
+    } else if (firstChild()) {
         parentPusher.push();
+    }
 
     ContainerNode::attach(context);
 
@@ -1411,26 +1424,30 @@
     RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
     unregisterNamedFlowContentNode();
     cancelFocusAppearanceUpdate();
-    if (RenderStyle* style = renderStyle()) {
-        if (!style->callbackSelectors().isEmpty())
-            updateCallbackSelectors(style, 0);
-    }
+    removeCallbackSelectors();
     if (hasRareData()) {
         ElementRareData* data = elementRareData();
         data->setPseudoElement(BEFORE, 0);
         data->setPseudoElement(AFTER, 0);
         data->setPseudoElement(BACKDROP, 0);
-        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)
+        // attach() will perform the below steps for us when inside recalcStyle.
+        if (!document().inStyleRecalc()) {
             data->resetStyleState();
+            data->clearComputedStyle();
+            data->resetDynamicRestyleObservations();
+        }
 
-        if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
-            if (ActiveAnimations* activeAnimations = data->activeAnimations())
-                activeAnimations->cssAnimations().cancel();
+        if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
+            if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
+                if (context.performingReattach) {
+                    // FIXME: restart compositor animations rather than pull back to the main thread
+                    activeAnimations->cancelAnimationOnCompositor();
+                } else {
+                    activeAnimations->cssAnimations().cancel();
+                }
+            }
         }
     }
     if (ElementShadow* shadow = this->shadow())
@@ -1466,7 +1483,7 @@
             newStyle->addCachedPseudoStyle(newPseudoStyle);
             if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
                 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
-                // is needed, but for now just assume a layout will be required.  The diff code
+                // is needed, but for now just assume a layout will be required. The diff code
                 // in RenderObject::setStyle would need to be factored out so that it could be reused.
                 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
             }
@@ -1491,57 +1508,54 @@
     return document().styleResolver()->styleForElement(this);
 }
 
-bool Element::recalcStyle(StyleRecalcChange change)
+void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
 {
     ASSERT(document().inStyleRecalc());
+    ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
 
     if (hasCustomStyleCallbacks())
         willRecalcStyle(change);
 
-    if (hasRareData() && (change > NoChange || needsStyleRecalc())) {
-        ElementRareData* data = elementRareData();
-        data->resetStyleState();
-        data->clearComputedStyle();
+    if (change >= Inherit || needsStyleRecalc()) {
+        if (hasRareData()) {
+            ElementRareData* data = elementRareData();
+            data->resetStyleState();
+            data->clearComputedStyle();
+        }
+        if (parentRenderStyle())
+            change = recalcOwnStyle(change);
+        clearNeedsStyleRecalc();
     }
 
-    // Active InsertionPoints have no renderers so they never need to go through a recalc.
-    if ((change >= Inherit || needsStyleRecalc()) && parentRenderStyle() && !isActiveInsertionPoint(*this))
-        change = recalcOwnStyle(change);
-
     // If we reattached we don't need to recalc the style of our descendants anymore.
-    if (change < Reattach)
+    if ((change >= Inherit && change < Reattach) || childNeedsStyleRecalc())
         recalcChildStyle(change);
-
-    clearNeedsStyleRecalc();
     clearChildNeedsStyleRecalc();
 
     if (hasCustomStyleCallbacks())
         didRecalcStyle(change);
 
-    return change == Reattach;
-}
-
-static bool callbackSelectorsDiffer(RenderStyle* style1, RenderStyle* style2)
-{
-    const Vector<String> emptyVector;
-    const Vector<String>& callbackSelectors1 = style1 ? style1->callbackSelectors() : emptyVector;
-    const Vector<String>& callbackSelectors2 = style2 ? style2->callbackSelectors() : emptyVector;
-    if (callbackSelectors1.isEmpty() && callbackSelectors2.isEmpty()) {
-        // Help the inliner with this common case.
-        return false;
-    }
-    return callbackSelectors1 != callbackSelectors2;
+    if (change == Reattach)
+        reattachWhitespaceSiblings(nextTextSibling);
 }
 
 StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
 {
     ASSERT(document().inStyleRecalc());
+    ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
+    ASSERT(change >= Inherit || needsStyleRecalc());
+    ASSERT(parentRenderStyle());
 
-    CSSAnimationUpdateScope cssAnimationUpdateScope(this);
     RefPtr<RenderStyle> oldStyle = renderStyle();
-    RefPtr<RenderStyle> newStyle = styleForRenderer();
+    RefPtr<RenderStyle> newStyle;
+    {
+        CSSAnimationUpdateScope cssAnimationUpdateScope(this);
+        newStyle = styleForRenderer();
+    }
     StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
 
+    ASSERT(newStyle);
+
     if (localChange == Reattach) {
         AttachContext reattachContext;
         reattachContext.resolvedStyle = newStyle.get();
@@ -1549,13 +1563,15 @@
         return Reattach;
     }
 
+    ASSERT(oldStyle);
+
     InspectorInstrumentation::didRecalculateStyleForElement(this);
 
-    if (localChange != NoChange && callbackSelectorsDiffer(oldStyle.get(), newStyle.get()))
+    if (localChange != NoChange)
         updateCallbackSelectors(oldStyle.get(), newStyle.get());
 
     if (RenderObject* renderer = this->renderer()) {
-        if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
+        if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || shouldNotifyRendererWithIdenticalStyles()) {
             renderer->setAnimatableStyle(newStyle.get());
         } else {
             // Although no change occurred, we use the new style so that the cousin style sharing code won't get
@@ -1568,7 +1584,7 @@
 
     // If "rem" units are used anywhere in the document, and if the document element's font size changes, then go ahead and force font updating
     // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
-    if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle && newStyle && oldStyle->fontSize() != newStyle->fontSize()) {
+    if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle->fontSize() != newStyle->fontSize()) {
         // Cached RenderStyles may depend on the re units.
         document().styleResolver()->invalidateMatchedPropertiesCache();
         return Force;
@@ -1583,8 +1599,10 @@
 void Element::recalcChildStyle(StyleRecalcChange change)
 {
     ASSERT(document().inStyleRecalc());
+    ASSERT(change >= Inherit || childNeedsStyleRecalc());
+    ASSERT(!needsStyleRecalc());
 
-    StyleResolverParentPusher parentPusher(this);
+    StyleResolverParentPusher parentPusher(*this);
 
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         if (shouldRecalcStyle(change, root)) {
@@ -1596,64 +1614,89 @@
     if (shouldRecalcStyle(change, this))
         updatePseudoElement(BEFORE, change);
 
-    bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
-    bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
-    unsigned forceCheckOfNextElementCount = 0;
-    bool forceCheckOfAnyElementSibling = false;
-    if (hasDirectAdjacentRules || hasIndirectAdjacentRules) {
-        for (Node* child = firstChild(); child; child = child->nextSibling()) {
-            if (!child->isElementNode())
-                continue;
-            Element* element = toElement(child);
-            bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
+    if (change < Force && hasRareData() && childNeedsStyleRecalc())
+        checkForChildrenAdjacentRuleChanges();
 
-            if (forceCheckOfNextElementCount || forceCheckOfAnyElementSibling)
-                element->setNeedsStyleRecalc();
-
-            if (forceCheckOfNextElementCount)
-                forceCheckOfNextElementCount--;
-
-            if (childRulesChanged && hasDirectAdjacentRules)
-                forceCheckOfNextElementCount = document().styleEngine()->maxDirectAdjacentSelectors();
-
-            forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
-        }
-    }
     // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
     // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
     // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
-    // Reversing this loop can lead to non-deterministic results in our code to optimize out empty whitespace
-    // RenderTexts. We try to put off recalcing their style until the end to avoid this issue.
     // See crbug.com/288225
-    WhitespaceChildList whitespaceChildList(change);
+    StyleResolver& styleResolver = *document().styleResolver();
+    Text* lastTextNode = 0;
     for (Node* child = lastChild(); child; child = child->previousSibling()) {
         if (child->isTextNode()) {
-            Text* textChild = toText(child);
-            // FIXME: This check is expensive and may negate the performance gained by the optimization of
-            // avoiding whitespace renderers.
-            if (textChild->containsOnlyWhitespace())
-                whitespaceChildList.append(textChild);
-            else
-                textChild->recalcTextStyle(change);
+            toText(child)->recalcTextStyle(change, lastTextNode);
+            lastTextNode = toText(child);
         } else if (child->isElementNode()) {
             Element* element = toElement(child);
             if (shouldRecalcStyle(change, element)) {
                 parentPusher.push();
-                element->recalcStyle(change);
+                element->recalcStyle(change, lastTextNode);
             } else if (element->supportsStyleSharing()) {
-                document().styleResolver()->addToStyleSharingList(element);
+                styleResolver.addToStyleSharingList(*element);
             }
+            if (element->renderer())
+                lastTextNode = 0;
         }
     }
 
-    whitespaceChildList.recalcStyle();
-
     if (shouldRecalcStyle(change, this)) {
         updatePseudoElement(AFTER, change);
         updatePseudoElement(BACKDROP, change);
     }
 }
 
+void Element::checkForChildrenAdjacentRuleChanges()
+{
+    bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
+    bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
+
+    if (!hasDirectAdjacentRules && !hasIndirectAdjacentRules)
+        return;
+
+    unsigned forceCheckOfNextElementCount = 0;
+    bool forceCheckOfAnyElementSibling = false;
+
+    for (Node* child = firstChild(); child; child = child->nextSibling()) {
+        if (!child->isElementNode())
+            continue;
+        Element* element = toElement(child);
+        bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
+
+        if (forceCheckOfNextElementCount || forceCheckOfAnyElementSibling)
+            element->setNeedsStyleRecalc();
+
+        if (forceCheckOfNextElementCount)
+            forceCheckOfNextElementCount--;
+
+        if (childRulesChanged && hasDirectAdjacentRules)
+            forceCheckOfNextElementCount = document().styleEngine()->maxDirectAdjacentSelectors();
+
+        forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
+    }
+}
+
+void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
+{
+    Vector<String> emptyVector;
+    const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
+    const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
+    if (oldCallbackSelectors.isEmpty() && newCallbackSelectors.isEmpty())
+        return;
+    if (oldCallbackSelectors != newCallbackSelectors)
+        CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
+}
+
+void Element::addCallbackSelectors()
+{
+    updateCallbackSelectors(0, renderStyle());
+}
+
+void Element::removeCallbackSelectors()
+{
+    updateCallbackSelectors(renderStyle(), 0);
+}
+
 ElementShadow* Element::shadow() const
 {
     return hasRareData() ? elementRareData()->shadow() : 0;
@@ -1671,22 +1714,22 @@
         elementShadow->didAffectSelector(mask);
 }
 
-PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& es)
+PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
 {
     if (alwaysCreateUserAgentShadowRoot())
         ensureUserAgentShadowRoot();
 
     if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
-        return ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot);
+        return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
 
     // Since some elements recreates shadow root dynamically, multiple shadow
     // subtrees won't work well in that element. Until they are fixed, we disable
     // adding author shadow root for them.
     if (!areAuthorShadowsAllowed()) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return 0;
     }
-    return ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot);
+    return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
 }
 
 ShadowRoot* Element::shadowRoot() const
@@ -1716,11 +1759,11 @@
     return 0;
 }
 
-ShadowRoot* Element::ensureUserAgentShadowRoot()
+ShadowRoot& Element::ensureUserAgentShadowRoot()
 {
     if (ShadowRoot* shadowRoot = userAgentShadowRoot())
-        return shadowRoot;
-    ShadowRoot* shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
+        return *shadowRoot;
+    ShadowRoot& shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
     didAddUserAgentShadowRoot(shadowRoot);
     return shadowRoot;
 }
@@ -1740,25 +1783,26 @@
     return false;
 }
 
-static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
+void Element::checkForEmptyStyleChange(RenderStyle* style)
 {
-    if (!style && !element->styleAffectedByEmpty())
+    if (!style && !styleAffectedByEmpty())
         return;
 
-    if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
-        element->setNeedsStyleRecalc();
+    if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildNodes())))
+        setNeedsStyleRecalc();
 }
 
-static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
-                                        Node* beforeChange, Node* afterChange, int childCountDelta)
+void Element::checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
-    if (!e->inActiveDocument() || e->document().hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
+    if (!inActiveDocument() || document().hasPendingForcedStyleRecalc() || styleChangeType() >= SubtreeStyleChange)
         return;
 
-    // :empty selector.
-    checkForEmptyStyleChange(e, style);
+    RenderStyle* style = renderStyle();
 
-    if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
+    // :empty selector.
+    checkForEmptyStyleChange(style);
+
+    if (!style || (needsStyleRecalc() && childrenAffectedByPositionalRules()))
         return;
 
     // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
@@ -1768,17 +1812,17 @@
     // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
     // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
     // here. recalcStyle will then force a walk of the children when it sees that this has happened.
-    if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
-        e->setNeedsStyleRecalc();
+    if ((childrenAffectedByForwardPositionalRules() && afterChange) || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
+        setNeedsStyleRecalc();
         return;
     }
 
     // :first-child.  In the parser callback case, we don't have to check anything, since we were right the first time.
     // In the DOM case, we only need to do something if |afterChange| is not 0.
     // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
-    if (e->childrenAffectedByFirstChildRules() && afterChange) {
+    if (childrenAffectedByFirstChildRules() && afterChange) {
         // Find our new first child.
-        Node* newFirstChild = e->firstElementChild();
+        Node* newFirstChild = firstElementChild();
         RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
 
         // Find the first element node following |afterChange|
@@ -1796,9 +1840,9 @@
 
     // :last-child.  In the parser callback case, we don't have to check anything, since we were right the first time.
     // In the DOM case, we only need to do something if |afterChange| is not 0.
-    if (e->childrenAffectedByLastChildRules() && beforeChange) {
+    if (childrenAffectedByLastChildRules() && beforeChange) {
         // Find our new last child.
-        Node* newLastChild = e->lastElementChild();
+        Node* newLastChild = lastElementChild();
         RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
 
         // Find the last element node going backwards from |beforeChange|
@@ -1816,7 +1860,7 @@
 
     // The + selector.  We need to invalidate the first element following the insertion point.  It is the only possible element
     // that could be affected by this DOM change.
-    if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
+    if (childrenAffectedByDirectAdjacentRules() && afterChange) {
         if (Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling())
             firstElementAfterInsertion->setNeedsStyleRecalc();
     }
@@ -1826,9 +1870,9 @@
 {
     ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
     if (changedByParser)
-        checkForEmptyStyleChange(this, renderStyle());
+        checkForEmptyStyleChange(renderStyle());
     else
-        checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
+        checkForSiblingStyleChanges(false, beforeChange, afterChange, childCountDelta);
 
     if (ElementShadow* shadow = this->shadow())
         shadow->setNeedsDistributionRecalc();
@@ -1849,9 +1893,7 @@
 void Element::finishParsingChildren()
 {
     setIsParsingChildrenFinished();
-    checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
-    if (isCustomElement())
-        CustomElement::didFinishParsingChildren(this);
+    checkForSiblingStyleChanges(this, lastChild(), 0, 0);
 }
 
 #ifndef NDEBUG
@@ -1888,10 +1930,10 @@
     return *attrNodeListForElement(this);
 }
 
-PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
+PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
 {
     if (!attrNode) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return 0;
     }
 
@@ -1902,7 +1944,7 @@
     // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
     // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
     if (attrNode->ownerElement()) {
-        es.throwUninformativeAndGenericDOMException(InUseAttributeError);
+        exceptionState.throwUninformativeAndGenericDOMException(InUseAttributeError);
         return 0;
     }
 
@@ -1926,19 +1968,19 @@
     return oldAttrNode.release();
 }
 
-PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& es)
+PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& exceptionState)
 {
-    return setAttributeNode(attr, es);
+    return setAttributeNode(attr, exceptionState);
 }
 
-PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
+PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
 {
     if (!attr) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return 0;
     }
     if (attr->ownerElement() != this) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return 0;
     }
 
@@ -1948,7 +1990,7 @@
 
     size_t index = elementData()->getAttrIndex(attr);
     if (index == kNotFound) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return 0;
     }
 
@@ -1957,17 +1999,17 @@
     return guard.release();
 }
 
-bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& es)
+bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
 {
     String prefix, localName;
-    if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
+    if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return false;
-    ASSERT(!es.hadException());
+    ASSERT(!exceptionState.hadException());
 
     QualifiedName qName(prefix, localName, namespaceURI);
 
     if (!Document::hasValidNamespaceForAttributes(qName)) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
+        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
         return false;
     }
 
@@ -1975,10 +2017,10 @@
     return true;
 }
 
-void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& es)
+void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& exceptionState)
 {
     QualifiedName parsedName = anyName;
-    if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, es))
+    if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, exceptionState))
         return;
     setAttribute(parsedName, value);
 }
@@ -2201,38 +2243,38 @@
     return createMarkup(this);
 }
 
-void Element::setInnerHTML(const String& html, ExceptionState& es)
+void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
 {
-    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", es)) {
+    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
         ContainerNode* container = this;
         if (hasTagName(templateTag))
             container = toHTMLTemplateElement(this)->content();
-        replaceChildrenWithFragment(container, fragment.release(), es);
+        replaceChildrenWithFragment(container, fragment.release(), exceptionState);
     }
 }
 
-void Element::setOuterHTML(const String& html, ExceptionState& es)
+void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
 {
     Node* p = parentNode();
     if (!p || !p->isElementNode()) {
-        es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
         return;
     }
     RefPtr<Element> parent = toElement(p);
     RefPtr<Node> prev = previousSibling();
     RefPtr<Node> next = nextSibling();
 
-    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", es);
-    if (es.hadException())
+    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", exceptionState);
+    if (exceptionState.hadException())
         return;
 
-    parent->replaceChild(fragment.release(), this, es);
+    parent->replaceChild(fragment.release(), this, exceptionState);
     RefPtr<Node> node = next ? next->previousSibling() : 0;
-    if (!es.hadException() && node && node->isTextNode())
-        mergeWithNextTextNode(node.release(), es);
+    if (!exceptionState.hadException() && node && node->isTextNode())
+        mergeWithNextTextNode(node.release(), exceptionState);
 
-    if (!es.hadException() && prev && prev->isTextNode())
-        mergeWithNextTextNode(prev.release(), es);
+    if (!exceptionState.hadException() && prev && prev->isTextNode())
+        mergeWithNextTextNode(prev.release(), exceptionState);
 }
 
 String Element::innerText()
@@ -2302,14 +2344,24 @@
     return getAttribute(pseudoAttr);
 }
 
-const AtomicString& Element::part() const
+void Element::setPseudo(const AtomicString& value)
 {
-    return getAttribute(partAttr);
+    setAttribute(pseudoAttr, value);
 }
 
-void Element::setPart(const AtomicString& value)
+bool Element::isInDescendantTreeOf(const Element* shadowHost) const
 {
-    setAttribute(partAttr, value);
+    ASSERT(shadowHost);
+    ASSERT(isShadowHost(shadowHost));
+
+    const ShadowRoot* shadowRoot = containingShadowRoot();
+    while (shadowRoot) {
+        const Element* ancestorShadowHost = shadowRoot->shadowHost();
+        if (ancestorShadowHost == shadowHost)
+            return true;
+        shadowRoot = ancestorShadowHost->containingShadowRoot();
+    }
+    return false;
 }
 
 LayoutSize Element::minimumSizeForResizing() const
@@ -2356,22 +2408,24 @@
     ensureElementRareData().setStyleAffectedByEmpty(true);
 }
 
-void Element::setChildrenAffectedByHover(bool value)
+void Element::setChildrenAffectedByFocus()
 {
-    if (value || hasRareData())
-        ensureElementRareData().setChildrenAffectedByHover(value);
+    ensureElementRareData().setChildrenAffectedByFocus(true);
 }
 
-void Element::setChildrenAffectedByActive(bool value)
+void Element::setChildrenAffectedByHover()
 {
-    if (value || hasRareData())
-        ensureElementRareData().setChildrenAffectedByActive(value);
+    ensureElementRareData().setChildrenAffectedByHover(true);
 }
 
-void Element::setChildrenAffectedByDrag(bool value)
+void Element::setChildrenAffectedByActive()
 {
-    if (value || hasRareData())
-        ensureElementRareData().setChildrenAffectedByDrag(value);
+    ensureElementRareData().setChildrenAffectedByActive(true);
+}
+
+void Element::setChildrenAffectedByDrag()
+{
+    ensureElementRareData().setChildrenAffectedByDrag(true);
 }
 
 void Element::setChildrenAffectedByFirstChildRules()
@@ -2411,7 +2465,8 @@
 {
     if (!hasRareData())
         return true;
-    return !rareDataChildrenAffectedByHover()
+    return !rareDataChildrenAffectedByFocus()
+        && !rareDataChildrenAffectedByHover()
         && !rareDataChildrenAffectedByActive()
         && !rareDataChildrenAffectedByDrag()
         && !rareDataChildrenAffectedByFirstChildRules()
@@ -2427,6 +2482,12 @@
     return elementRareData()->styleAffectedByEmpty();
 }
 
+bool Element::rareDataChildrenAffectedByFocus() const
+{
+    ASSERT(hasRareData());
+    return elementRareData()->childrenAffectedByFocus();
+}
+
 bool Element::rareDataChildrenAffectedByHover() const
 {
     ASSERT(hasRareData());
@@ -2552,15 +2613,6 @@
         document().cancelFocusAppearanceUpdate();
 }
 
-void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
-{
-    const Vector<String> emptyVector;
-    const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
-    const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
-
-    CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
-}
-
 void Element::normalizeAttributes()
 {
     if (!hasAttributes())
@@ -2575,8 +2627,14 @@
 {
     PseudoElement* element = pseudoElement(pseudoId);
     if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
+        // Need to clear the cached style if the PseudoElement wants a recalc so it
+        // computes a new style.
+        if (element->needsStyleRecalc())
+            renderer()->style()->removeCachedPseudoStyle(pseudoId);
+
         // PseudoElement styles hang off their parent element's style so if we needed
         // a style recalc we should Force one on the pseudo.
+        // FIXME: We should figure out the right text sibling to pass.
         element->recalcStyle(needsStyleRecalc() ? Force : change);
 
         // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
@@ -2633,14 +2691,14 @@
     return 0;
 }
 
-bool Element::webkitMatchesSelector(const String& selector, ExceptionState& es)
+bool Element::webkitMatchesSelector(const String& selector, ExceptionState& exceptionState)
 {
     if (selector.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return false;
     }
 
-    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selector, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selector, document(), exceptionState);
     if (!selectorQuery)
         return false;
     return selectorQuery->matches(*this);
@@ -2694,8 +2752,7 @@
 
 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
 {
-    // FIXME: Need an AtomicString version of String::number.
-    setAttribute(attributeName, String::number(value));
+    setAttribute(attributeName, AtomicString::number(value));
 }
 
 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
@@ -2705,8 +2762,17 @@
 
 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
 {
-    // FIXME: Need an AtomicString version of String::number.
-    setAttribute(attributeName, String::number(value));
+    setAttribute(attributeName, AtomicString::number(value));
+}
+
+double Element::getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue) const
+{
+    return parseToDoubleForNumberType(getAttribute(attributeName), fallbackValue);
+}
+
+void Element::setFloatingPointAttribute(const QualifiedName& attributeName, double value)
+{
+    setAttribute(attributeName, AtomicString::number(value));
 }
 
 bool Element::childShouldCreateRenderer(const Node& child) const
@@ -2805,8 +2871,8 @@
 
 RenderRegion* Element::renderRegion() const
 {
-    if (renderer() && renderer()->isRenderRegion())
-        return toRenderRegion(renderer());
+    if (renderer() && renderer()->isRenderNamedFlowFragmentContainer())
+        return toRenderBlockFlow(renderer())->renderNamedFlowFragment();
 
     return 0;
 }
@@ -2829,10 +2895,13 @@
 
 const AtomicString& Element::webkitRegionOverset() const
 {
+    DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
+    if (!RuntimeEnabledFeatures::cssRegionsEnabled())
+        return undefinedState;
+
     document().updateLayoutIgnorePendingStylesheets();
 
-    DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
+    if (!renderRegion())
         return undefinedState;
 
     switch (renderRegion()->regionOversetState()) {
@@ -2858,11 +2927,14 @@
 
 Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
 {
+    Vector<RefPtr<Range> > rangeObjects;
+    if (!RuntimeEnabledFeatures::cssRegionsEnabled())
+        return rangeObjects;
+
     document().updateLayoutIgnorePendingStylesheets();
 
-    Vector<RefPtr<Range> > rangeObjects;
-    if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
-        RenderRegion* region = toRenderRegion(renderer());
+    if (renderer() && renderer()->isRenderNamedFlowFragmentContainer()) {
+        RenderNamedFlowFragment* region = toRenderBlockFlow(renderer())->renderNamedFlowFragment();
         if (region->isValid())
             region->getRanges(rangeObjects);
     }
@@ -2945,7 +3017,7 @@
 
 static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
 {
-    return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
+    return document->styleResolver() && document->styleResolver()->ensureRuleFeatureSet().hasSelectorForAttribute(localName);
 }
 
 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
@@ -3266,11 +3338,10 @@
     if (!inlineStyle) {
         CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
         inlineStyle = MutableStylePropertySet::create(mode);
-    }
-    else if (!inlineStyle->isMutable())
+    } else if (!inlineStyle->isMutable()) {
         inlineStyle = inlineStyle->mutableCopy();
-    ASSERT(inlineStyle->isMutable());
-    return static_cast<MutableStylePropertySet*>(inlineStyle.get());
+    }
+    return toMutableStylePropertySet(inlineStyle);
 }
 
 PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index bcdbf85..dd870be 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -114,6 +114,8 @@
     void setIntegralAttribute(const QualifiedName& attributeName, int value);
     unsigned getUnsignedIntegralAttribute(const QualifiedName& attributeName) const;
     void setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value);
+    double getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue = std::numeric_limits<double>::quiet_NaN()) const;
+    void setFloatingPointAttribute(const QualifiedName& attributeName, double value);
 
     // Call this to get the value of an attribute that is known not to be the style
     // attribute or one of the SVG animatable attributes.
@@ -222,6 +224,9 @@
     String tagName() const { return nodeName(); }
     bool hasTagName(const QualifiedName& tagName) const { return m_tagName.matches(tagName); }
 
+    // Should be called only by Document::createElementNS to fix up m_tagName immediately after construction.
+    void setTagNameForCreateElementNS(const QualifiedName&);
+
     // A fast function for checking the local name against another atomic string.
     bool hasLocalName(const AtomicString& other) const { return m_tagName.localName() == other; }
     bool hasLocalName(const QualifiedName& other) const { return m_tagName.localName() == other.localName(); }
@@ -299,7 +304,7 @@
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool rendererIsNeeded(const RenderStyle&);
-    bool recalcStyle(StyleRecalcChange);
+    void recalcStyle(StyleRecalcChange, Text* nextTextSibling = 0);
     void didAffectSelector(AffectedSelectorMask);
 
     bool supportsStyleSharing() const;
@@ -308,17 +313,20 @@
     ElementShadow& ensureShadow();
     PassRefPtr<ShadowRoot> createShadowRoot(ExceptionState&);
     ShadowRoot* shadowRoot() const;
+    ShadowRoot* youngestShadowRoot() const;
 
     bool hasAuthorShadowRoot() const { return shadowRoot(); }
     virtual void didAddShadowRoot(ShadowRoot&);
     ShadowRoot* userAgentShadowRoot() const;
-    ShadowRoot* ensureUserAgentShadowRoot();
+    ShadowRoot& ensureUserAgentShadowRoot();
     const AtomicString& shadowPseudoId() const;
+    bool isInDescendantTreeOf(const Element* shadowHost) const;
 
     RenderStyle* computedStyle(PseudoId = NOPSEUDO);
 
     // Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.)
     bool styleAffectedByEmpty() const { return hasRareData() && rareDataStyleAffectedByEmpty(); }
+    bool childrenAffectedByFocus() const { return hasRareData() && rareDataChildrenAffectedByFocus(); }
     bool childrenAffectedByHover() const { return hasRareData() && rareDataChildrenAffectedByHover(); }
     bool childrenAffectedByActive() const { return hasRareData() && rareDataChildrenAffectedByActive(); }
     bool childrenAffectedByDrag() const { return hasRareData() && rareDataChildrenAffectedByDrag(); }
@@ -333,9 +341,10 @@
     bool childrenSupportStyleSharing() const;
 
     void setStyleAffectedByEmpty();
-    void setChildrenAffectedByHover(bool);
-    void setChildrenAffectedByActive(bool);
-    void setChildrenAffectedByDrag(bool);
+    void setChildrenAffectedByFocus();
+    void setChildrenAffectedByHover();
+    void setChildrenAffectedByActive();
+    void setChildrenAffectedByDrag();
     void setChildrenAffectedByFirstChildRules();
     void setChildrenAffectedByLastChildRules();
     void setChildrenAffectedByDirectAdjacentRules();
@@ -347,7 +356,7 @@
     bool isInCanvasSubtree() const;
 
     bool isUpgradedCustomElement() { return customElementState() == Upgraded; }
-    bool isUnresolvedCustomElement() { return isCustomElement() && !isUpgradedCustomElement(); }
+    bool isUnresolvedCustomElement() { return customElementState() == WaitingForUpgrade; }
 
     void setIsInsideRegion(bool);
     bool isInsideRegion() const;
@@ -394,9 +403,8 @@
 
     virtual String title() const { return String(); }
 
-    const AtomicString& pseudo() const;
-    virtual const AtomicString& part() const;
-    void setPart(const AtomicString&);
+    virtual const AtomicString& pseudo() const;
+    void setPseudo(const AtomicString&);
 
     LayoutSize minimumSizeForResizing() const;
     void setMinimumSizeForResizing(const LayoutSize&);
@@ -566,6 +574,12 @@
     StyleRecalcChange recalcOwnStyle(StyleRecalcChange);
     void recalcChildStyle(StyleRecalcChange);
 
+    // FIXME: These methods should all be renamed to something better than "check",
+    // since it's not clear that they alter the style bits of siblings and children.
+    void checkForChildrenAdjacentRuleChanges();
+    void checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta);
+    inline void checkForEmptyStyleChange(RenderStyle*);
+
     void updatePseudoElement(PseudoId, StyleRecalcChange);
 
     inline void createPseudoElementIfNeeded(PseudoId);
@@ -574,7 +588,7 @@
 
     // FIXME: Everyone should allow author shadows.
     virtual bool areAuthorShadowsAllowed() const { return true; }
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) { }
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) { }
     virtual bool alwaysCreateUserAgentShadowRoot() const { return false; }
 
     // FIXME: Remove the need for Attr to call willModifyAttribute/didModifyAttribute.
@@ -615,7 +629,9 @@
 
     virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return computedStyle(pseudoElementSpecifier); }
 
-    void updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle);
+    inline void updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle);
+    inline void removeCallbackSelectors();
+    inline void addCallbackSelectors();
 
     // cloneNode is private so that non-virtual cloneElementWithChildren and cloneElementWithoutChildren
     // are used instead.
@@ -624,6 +640,7 @@
 
     QualifiedName m_tagName;
     bool rareDataStyleAffectedByEmpty() const;
+    bool rareDataChildrenAffectedByFocus() const;
     bool rareDataChildrenAffectedByHover() const;
     bool rareDataChildrenAffectedByActive() const;
     bool rareDataChildrenAffectedByDrag() const;
@@ -720,10 +737,6 @@
 
 inline const AtomicString& Element::shadowPseudoId() const
 {
-    // FIXME: We should remove both part() and pseudo(), neither are in the new spec.
-    const AtomicString& part = this->part();
-    if (!part.isEmpty())
-        return part;
     return pseudo();
 }
 
@@ -856,6 +869,14 @@
     return elementData()->presentationAttributeStyle();
 }
 
+inline void Element::setTagNameForCreateElementNS(const QualifiedName& tagName)
+{
+    // We expect this method to be called only to reset the prefix.
+    ASSERT(tagName.localName() == m_tagName.localName());
+    ASSERT(tagName.namespaceURI() == m_tagName.namespaceURI());
+    m_tagName = tagName;
+}
+
 inline bool isShadowHost(const Node* node)
 {
     return node && node->isElementNode() && toElement(node)->shadow();
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 3a8d2ba..d85e326 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -61,7 +61,7 @@
     // Other browsers do this as well. So we don't convert null to JS null.
     [Reflect, TreatNullAs=NullString] attribute DOMString id;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException] attribute DOMString prefix;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter] attribute DOMString prefix;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
 
     // Common extensions
@@ -92,8 +92,8 @@
 
     // HTML 5
     NodeList getElementsByClassName([Default=Undefined] optional DOMString name);
-    [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
-    [TreatNullAs=NullString, CustomElementCallbacks, SetterRaisesException] attribute DOMString outerHTML;
+    [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
+    [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter] attribute DOMString outerHTML;
 
     [Reflect=class, TreatNullAs=NullString, PerWorldBindings] attribute DOMString className;
     [PerWorldBindings] readonly attribute DOMTokenList classList;
@@ -124,10 +124,10 @@
 
     // Mozilla version
     const unsigned short ALLOW_KEYBOARD_INPUT = 1;
-    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=AccessForAllWorlds, MeasureAs=PrefixedElementRequestFullScreen] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
+    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=ForAllWorlds, MeasureAs=PrefixedElementRequestFullScreen] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
 
     // W3C version
-    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=AccessForAllWorlds, MeasureAs=PrefixedElementRequestFullscreen] void webkitRequestFullscreen();
+    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=ForAllWorlds, MeasureAs=PrefixedElementRequestFullscreen] void webkitRequestFullscreen();
 
     void webkitRequestPointerLock();
 
@@ -150,7 +150,7 @@
     [RuntimeEnabled=Touch] attribute EventHandler ontouchstart;
     attribute EventHandler onwebkitfullscreenchange;
     attribute EventHandler onwebkitfullscreenerror;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onwheel;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onwheel;
 };
 
 Element implements ParentNode;
diff --git a/Source/core/dom/ElementData.cpp b/Source/core/dom/ElementData.cpp
index 9248276..73d0c39 100644
--- a/Source/core/dom/ElementData.cpp
+++ b/Source/core/dom/ElementData.cpp
@@ -81,11 +81,8 @@
     // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
 }
 
-void ElementData::deref()
+void ElementData::destroy()
 {
-    if (!derefBase())
-        return;
-
     if (m_isUnique)
         delete static_cast<UniqueElementData*>(this);
     else
@@ -215,17 +212,6 @@
     return adoptRef(new (slot) ShareableElementData(*this));
 }
 
-void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
-{
-    m_attributeVector.append(Attribute(attributeName, value));
-}
-
-void UniqueElementData::removeAttribute(size_t index)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(index < length());
-    m_attributeVector.remove(index);
-}
-
 Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
 {
     for (unsigned i = 0; i < length(); ++i) {
@@ -235,10 +221,4 @@
     return 0;
 }
 
-Attribute* UniqueElementData::attributeItem(unsigned index)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(index < length());
-    return &m_attributeVector.at(index);
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/ElementData.h b/Source/core/dom/ElementData.h
index 50c2879..b7c36f0 100644
--- a/Source/core/dom/ElementData.h
+++ b/Source/core/dom/ElementData.h
@@ -97,6 +97,8 @@
     friend class UniqueElementData;
     friend class SVGElement;
 
+    void destroy();
+
     const Attribute* attributeBase() const;
     const Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
     size_t getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
@@ -144,6 +146,13 @@
     Vector<Attribute, 4> m_attributeVector;
 };
 
+inline void ElementData::deref()
+{
+    if (!derefBase())
+        return;
+    destroy();
+}
+
 inline size_t ElementData::length() const
 {
     if (isUnique())
@@ -225,6 +234,21 @@
     return attributeBase() + index;
 }
 
+inline void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
+{
+    m_attributeVector.append(Attribute(attributeName, value));
+}
+
+inline void UniqueElementData::removeAttribute(size_t index)
+{
+    m_attributeVector.remove(index);
+}
+
+inline Attribute* UniqueElementData::attributeItem(unsigned index)
+{
+    return &m_attributeVector.at(index);
+}
+
 } // namespace WebCore
 
 #endif // ElementData_h
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index ac97c75..a187997 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -75,6 +75,8 @@
     bool isInTopLayer() const { return m_isInTopLayer; }
     void setIsInTopLayer(bool value) { m_isInTopLayer = value; }
 
+    bool childrenAffectedByFocus() const { return m_childrenAffectedByFocus; }
+    void setChildrenAffectedByFocus(bool value) { m_childrenAffectedByFocus = value; }
     bool childrenAffectedByHover() const { return m_childrenAffectedByHover; }
     void setChildrenAffectedByHover(bool value) { m_childrenAffectedByHover = value; }
     bool childrenAffectedByActive() const { return m_childrenAffectedByActive; }
@@ -158,6 +160,7 @@
     unsigned m_containsFullScreenElement : 1;
     unsigned m_isInTopLayer : 1;
     unsigned m_hasPendingResources : 1;
+    unsigned m_childrenAffectedByFocus : 1;
     unsigned m_childrenAffectedByHover : 1;
     unsigned m_childrenAffectedByActive : 1;
     unsigned m_childrenAffectedByDrag : 1;
@@ -207,6 +210,7 @@
     , m_containsFullScreenElement(false)
     , m_isInTopLayer(false)
     , m_hasPendingResources(false)
+    , m_childrenAffectedByFocus(false)
     , m_childrenAffectedByHover(false)
     , m_childrenAffectedByActive(false)
     , m_childrenAffectedByDrag(false)
@@ -273,13 +277,13 @@
 
 inline void ElementRareData::resetStyleState()
 {
-    setComputedStyle(0);
     setStyleAffectedByEmpty(false);
     setChildIndex(0);
 }
 
 inline void ElementRareData::resetDynamicRestyleObservations()
 {
+    setChildrenAffectedByFocus(false);
     setChildrenAffectedByHover(false);
     setChildrenAffectedByActive(false);
     setChildrenAffectedByDrag(false);
diff --git a/Source/core/dom/ElementTraversal.h b/Source/core/dom/ElementTraversal.h
index 0278732..274725d 100644
--- a/Source/core/dom/ElementTraversal.h
+++ b/Source/core/dom/ElementTraversal.h
@@ -33,112 +33,112 @@
 namespace ElementTraversal {
 
 // First element child of the node.
-Element* firstWithin(const Node*);
-Element* firstWithin(const ContainerNode*);
+Element* firstWithin(const Node&);
+Element* firstWithin(const ContainerNode&);
 
 // Pre-order traversal skipping non-element nodes.
-Element* next(const Node*);
-Element* next(const Node*, const Node* stayWithin);
-Element* next(const ContainerNode*);
-Element* next(const ContainerNode*, const Node* stayWithin);
+Element* next(const Node&);
+Element* next(const Node&, const Node* stayWithin);
+Element* next(const ContainerNode&);
+Element* next(const ContainerNode&, const Node* stayWithin);
 
 // Like next, but skips children.
-Element* nextSkippingChildren(const Node*);
-Element* nextSkippingChildren(const Node*, const Node* stayWithin);
-Element* nextSkippingChildren(const ContainerNode*);
-Element* nextSkippingChildren(const ContainerNode*, const Node* stayWithin);
+Element* nextSkippingChildren(const Node&);
+Element* nextSkippingChildren(const Node&, const Node* stayWithin);
+Element* nextSkippingChildren(const ContainerNode&);
+Element* nextSkippingChildren(const ContainerNode&, const Node* stayWithin);
 
 // Pre-order traversal including the pseudo-elements.
-Element* previousIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Element* nextIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Element* nextIncludingPseudoSkippingChildren(const Node*, const Node* stayWithin = 0);
+Element* previousIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Element* nextIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Element* nextIncludingPseudoSkippingChildren(const Node&, const Node* stayWithin = 0);
 
 // Utility function to traverse only the element and pseudo-element siblings of a node.
-Element* pseudoAwarePreviousSibling(const Node*);
+Element* pseudoAwarePreviousSibling(const Node&);
 
 template <class NodeType>
-inline Element* firstElementWithinTemplate(NodeType* current)
+inline Element* firstElementWithinTemplate(NodeType& current)
 {
     // Except for the root containers, only elements can have element children.
-    Node* node = current->firstChild();
+    Node* node = current.firstChild();
     while (node && !node->isElementNode())
         node = node->nextSibling();
     return toElement(node);
 }
-inline Element* firstWithin(const ContainerNode* current) { return firstElementWithinTemplate(current); }
-inline Element* firstWithin(const Node* current) { return firstElementWithinTemplate(current); }
+inline Element* firstWithin(const ContainerNode& current) { return firstElementWithinTemplate(current); }
+inline Element* firstWithin(const Node& current) { return firstElementWithinTemplate(current); }
 
 template <class NodeType>
-inline Element* traverseNextElementTemplate(NodeType* current)
+inline Element* traverseNextElementTemplate(NodeType& current)
 {
     Node* node = NodeTraversal::next(current);
     while (node && !node->isElementNode())
-        node = NodeTraversal::nextSkippingChildren(node);
+        node = NodeTraversal::nextSkippingChildren(*node);
     return toElement(node);
 }
-inline Element* next(const ContainerNode* current) { return traverseNextElementTemplate(current); }
-inline Element* next(const Node* current) { return traverseNextElementTemplate(current); }
+inline Element* next(const ContainerNode& current) { return traverseNextElementTemplate(current); }
+inline Element* next(const Node& current) { return traverseNextElementTemplate(current); }
 
 template <class NodeType>
-inline Element* traverseNextElementTemplate(NodeType* current, const Node* stayWithin)
+inline Element* traverseNextElementTemplate(NodeType& current, const Node* stayWithin)
 {
     Node* node = NodeTraversal::next(current, stayWithin);
     while (node && !node->isElementNode())
-        node = NodeTraversal::nextSkippingChildren(node, stayWithin);
+        node = NodeTraversal::nextSkippingChildren(*node, stayWithin);
     return toElement(node);
 }
-inline Element* next(const ContainerNode* current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
-inline Element* next(const Node* current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
+inline Element* next(const ContainerNode& current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
+inline Element* next(const Node& current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
 
 template <class NodeType>
-inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current)
+inline Element* traverseNextElementSkippingChildrenTemplate(NodeType& current)
 {
     Node* node = NodeTraversal::nextSkippingChildren(current);
     while (node && !node->isElementNode())
-        node = NodeTraversal::nextSkippingChildren(node);
+        node = NodeTraversal::nextSkippingChildren(*node);
     return toElement(node);
 }
-inline Element* nextSkippingChildren(const ContainerNode* current) { return traverseNextElementSkippingChildrenTemplate(current); }
-inline Element* nextSkippingChildren(const Node* current) { return traverseNextElementSkippingChildrenTemplate(current); }
+inline Element* nextSkippingChildren(const ContainerNode& current) { return traverseNextElementSkippingChildrenTemplate(current); }
+inline Element* nextSkippingChildren(const Node& current) { return traverseNextElementSkippingChildrenTemplate(current); }
 
 template <class NodeType>
-inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current, const Node* stayWithin)
+inline Element* traverseNextElementSkippingChildrenTemplate(NodeType& current, const Node* stayWithin)
 {
     Node* node = NodeTraversal::nextSkippingChildren(current, stayWithin);
     while (node && !node->isElementNode())
-        node = NodeTraversal::nextSkippingChildren(node, stayWithin);
+        node = NodeTraversal::nextSkippingChildren(*node, stayWithin);
     return toElement(node);
 }
-inline Element* nextSkippingChildren(const ContainerNode* current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
-inline Element* nextSkippingChildren(const Node* current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
+inline Element* nextSkippingChildren(const ContainerNode& current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
+inline Element* nextSkippingChildren(const Node& current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
 
-inline Element* previousIncludingPseudo(const Node* current, const Node* stayWithin)
+inline Element* previousIncludingPseudo(const Node& current, const Node* stayWithin)
 {
     Node* node = NodeTraversal::previousIncludingPseudo(current, stayWithin);
     while (node && !node->isElementNode())
-        node = NodeTraversal::previousIncludingPseudo(node, stayWithin);
+        node = NodeTraversal::previousIncludingPseudo(*node, stayWithin);
     return toElement(node);
 }
 
-inline Element* nextIncludingPseudo(const Node* current, const Node* stayWithin)
+inline Element* nextIncludingPseudo(const Node& current, const Node* stayWithin)
 {
     Node* node = NodeTraversal::nextIncludingPseudo(current, stayWithin);
     while (node && !node->isElementNode())
-        node = NodeTraversal::nextIncludingPseudo(node, stayWithin);
+        node = NodeTraversal::nextIncludingPseudo(*node, stayWithin);
     return toElement(node);
 }
 
-inline Element* nextIncludingPseudoSkippingChildren(const Node* current, const Node* stayWithin)
+inline Element* nextIncludingPseudoSkippingChildren(const Node& current, const Node* stayWithin)
 {
     Node* node = NodeTraversal::nextIncludingPseudoSkippingChildren(current, stayWithin);
     while (node && !node->isElementNode())
-        node = NodeTraversal::nextIncludingPseudoSkippingChildren(node, stayWithin);
+        node = NodeTraversal::nextIncludingPseudoSkippingChildren(*node, stayWithin);
     return toElement(node);
 }
 
-inline Element* pseudoAwarePreviousSibling(const Node* current)
+inline Element* pseudoAwarePreviousSibling(const Node& current)
 {
-    Node* node = current->pseudoAwarePreviousSibling();
+    Node* node = current.pseudoAwarePreviousSibling();
     while (node && !node->isElementNode())
         node = node->pseudoAwarePreviousSibling();
     return toElement(node);
diff --git a/Source/core/dom/Entity.h b/Source/core/dom/Entity.h
index ee46c2c..e1a7a00 100644
--- a/Source/core/dom/Entity.h
+++ b/Source/core/dom/Entity.h
@@ -28,11 +28,7 @@
 
 class Entity : public ContainerNode {
 private:
-    Entity() : ContainerNode(0)
-    {
-        ASSERT_NOT_REACHED();
-        ScriptWrappable::init(this);
-    }
+    Entity(); // Left unimplemented on purpose.
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/ExecutionContext.cpp b/Source/core/dom/ExecutionContext.cpp
index 321fe69..8481a1e 100644
--- a/Source/core/dom/ExecutionContext.cpp
+++ b/Source/core/dom/ExecutionContext.cpp
@@ -31,7 +31,6 @@
 #include "core/dom/AddConsoleMessageTask.h"
 #include "core/dom/ContextLifecycleNotifier.h"
 #include "core/dom/ExecutionContextTask.h"
-#include "core/dom/MessagePort.h"
 #include "core/events/ErrorEvent.h"
 #include "core/events/EventTarget.h"
 #include "core/frame/DOMTimer.h"
@@ -44,19 +43,6 @@
 
 namespace WebCore {
 
-class ProcessMessagesSoonTask : public ExecutionContextTask {
-public:
-    static PassOwnPtr<ProcessMessagesSoonTask> create()
-    {
-        return adoptPtr(new ProcessMessagesSoonTask);
-    }
-
-    virtual void performTask(ExecutionContext* context)
-    {
-        context->dispatchMessagePortEvents();
-    }
-};
-
 class ExecutionContext::PendingException {
     WTF_MAKE_NONCOPYABLE(PendingException);
 public:
@@ -87,66 +73,11 @@
 
 ExecutionContext::~ExecutionContext()
 {
-    HashSet<MessagePort*>::iterator messagePortsEnd = m_messagePorts.end();
-    for (HashSet<MessagePort*>::iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
-        ASSERT((*iter)->executionContext() == this);
-        (*iter)->contextDestroyed();
-    }
-}
-
-void ExecutionContext::processMessagePortMessagesSoon()
-{
-    postTask(ProcessMessagesSoonTask::create());
-}
-
-void ExecutionContext::dispatchMessagePortEvents()
-{
-    RefPtr<ExecutionContext> protect(this);
-
-    // Make a frozen copy.
-    Vector<MessagePort*> ports;
-    copyToVector(m_messagePorts, ports);
-
-    unsigned portCount = ports.size();
-    for (unsigned i = 0; i < portCount; ++i) {
-        MessagePort* port = ports[i];
-        // The port may be destroyed, and another one created at the same address, but this is safe, as the worst that can happen
-        // as a result is that dispatchMessages() will be called needlessly.
-        if (m_messagePorts.contains(port) && port->started())
-            port->dispatchMessages();
-    }
-}
-
-void ExecutionContext::createdMessagePort(MessagePort* port)
-{
-    ASSERT(port);
-    ASSERT((isDocument() && isMainThread())
-        || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
-
-    m_messagePorts.add(port);
-}
-
-void ExecutionContext::destroyedMessagePort(MessagePort* port)
-{
-    ASSERT(port);
-    ASSERT((isDocument() && isMainThread())
-        || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
-
-    m_messagePorts.remove(port);
 }
 
 bool ExecutionContext::hasPendingActivity()
 {
-    if (lifecycleNotifier().hasPendingActivity())
-        return true;
-
-    HashSet<MessagePort*>::const_iterator messagePortsEnd = m_messagePorts.end();
-    for (HashSet<MessagePort*>::const_iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
-        if ((*iter)->hasPendingActivity())
-            return true;
-    }
-
-    return false;
+    return lifecycleNotifier().hasPendingActivity();
 }
 
 void ExecutionContext::suspendActiveDOMObjects()
@@ -165,8 +96,20 @@
 {
     m_activeDOMObjectsAreStopped = true;
     lifecycleNotifier().notifyStoppingActiveDOMObjects();
-    // Also close MessagePorts. If they were ActiveDOMObjects (they could be) then they could be stopped instead.
-    closeMessagePorts();
+}
+
+void ExecutionContext::suspendScheduledTasks()
+{
+    suspendActiveDOMObjects();
+    if (m_client)
+        m_client->tasksWereSuspended();
+}
+
+void ExecutionContext::resumeScheduledTasks()
+{
+    resumeActiveDOMObjects();
+    if (m_client)
+        m_client->tasksWereResumed();
 }
 
 void ExecutionContext::suspendActiveDOMObjectIfNeeded(ActiveDOMObject* object)
@@ -177,15 +120,6 @@
         object->suspend();
 }
 
-void ExecutionContext::closeMessagePorts()
-{
-    HashSet<MessagePort*>::iterator messagePortsEnd = m_messagePorts.end();
-    for (HashSet<MessagePort*>::iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
-        ASSERT((*iter)->executionContext() == this);
-        (*iter)->close();
-    }
-}
-
 bool ExecutionContext::shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus corsStatus)
 {
     return !(securityOrigin()->canRequest(completeURL(sourceURL)) || corsStatus == SharableCrossOrigin);
@@ -368,6 +302,13 @@
     m_client->postTask(task);
 }
 
+void ExecutionContext::postTask(const Closure& closure)
+{
+    if (!m_client)
+        return;
+    m_client->postTask(CallClosureTask::create(closure));
+}
+
 PassOwnPtr<LifecycleNotifier<ExecutionContext> > ExecutionContext::createLifecycleNotifier()
 {
     return ContextLifecycleNotifier::create(this);
diff --git a/Source/core/dom/ExecutionContext.h b/Source/core/dom/ExecutionContext.h
index ac26fdf..06b6370 100644
--- a/Source/core/dom/ExecutionContext.h
+++ b/Source/core/dom/ExecutionContext.h
@@ -37,8 +37,8 @@
 #include "core/frame/ConsoleTypes.h"
 #include "core/frame/DOMTimer.h"
 #include "platform/LifecycleContext.h"
-#include "weborigin/KURL.h"
-#include "wtf/HashSet.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/Functional.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -54,7 +54,6 @@
 class EventQueue;
 class EventTarget;
 class ExecutionContextTask;
-class MessagePort;
 class PublicURLManager;
 class SecurityOrigin;
 class ScriptCallStack;
@@ -79,6 +78,7 @@
     DOMWindow* executingWindow() const;
     String userAgent(const KURL&) const;
     void postTask(PassOwnPtr<ExecutionContextTask>);
+    void postTask(const Closure&);
     double timerAlignmentInterval() const;
 
     bool shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus);
@@ -96,6 +96,10 @@
     void resumeActiveDOMObjects();
     void stopActiveDOMObjects();
 
+    virtual void suspendScheduledTasks();
+    virtual void resumeScheduledTasks();
+    virtual bool tasksNeedSuspension() { return false; }
+
     bool activeDOMObjectsAreSuspended() const { return m_activeDOMObjectsAreSuspended; }
     bool activeDOMObjectsAreStopped() const { return m_activeDOMObjectsAreStopped; }
     bool isIteratingOverObservers() const;
@@ -103,13 +107,6 @@
     // Called after the construction of an ActiveDOMObject to synchronize suspend state.
     void suspendActiveDOMObjectIfNeeded(ActiveDOMObject*);
 
-    // MessagePort is conceptually a kind of ActiveDOMObject, but it needs to be tracked separately for message dispatch.
-    void processMessagePortMessagesSoon();
-    void dispatchMessagePortEvents();
-    void createdMessagePort(MessagePort*);
-    void destroyedMessagePort(MessagePort*);
-    const HashSet<MessagePort*>& messagePorts() const { return m_messagePorts; }
-
     void ref() { refExecutionContext(); }
     void deref() { derefExecutionContext(); }
 
@@ -135,8 +132,6 @@
 
     bool dispatchErrorEvent(PassRefPtr<ErrorEvent>, AccessControlStatus);
 
-    void closeMessagePorts();
-
     virtual void refExecutionContext() = 0;
     virtual void derefExecutionContext() = 0;
     // LifecycleContext implementation.
@@ -147,7 +142,6 @@
 
     ExecutionContextClient* m_client;
     SandboxFlags m_sandboxFlags;
-    HashSet<MessagePort*> m_messagePorts;
 
     int m_circularSequentialID;
     typedef HashMap<int, OwnPtr<DOMTimer> > TimeoutMap;
diff --git a/Source/core/dom/ExecutionContextClient.h b/Source/core/dom/ExecutionContextClient.h
index f9cd303..4293c74 100644
--- a/Source/core/dom/ExecutionContextClient.h
+++ b/Source/core/dom/ExecutionContextClient.h
@@ -29,7 +29,7 @@
 
 #include "core/frame/ConsoleTypes.h"
 #include "platform/LifecycleNotifier.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/WTFString.h"
@@ -67,6 +67,9 @@
     virtual double timerAlignmentInterval() const = 0;
     virtual void didUpdateSecurityOrigin() = 0;
 
+    virtual void tasksWereSuspended() { }
+    virtual void tasksWereResumed() { }
+
     void addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber) { addMessage(source, level, message, sourceURL, lineNumber, 0); }
     void addConsoleMessage(MessageSource source, MessageLevel level, const String& message, ScriptState* state = 0) { addMessage(source, level, message, String(), 0, state); }
     KURL contextURL() const { return virtualURL(); }
diff --git a/Source/core/dom/ExecutionContextTask.h b/Source/core/dom/ExecutionContextTask.h
index 84da8ce..9d07d75 100644
--- a/Source/core/dom/ExecutionContextTask.h
+++ b/Source/core/dom/ExecutionContextTask.h
@@ -28,7 +28,9 @@
 #define ExecutionContextTask_h
 
 #include "wtf/FastAllocBase.h"
+#include "wtf/Functional.h"
 #include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
@@ -45,6 +47,19 @@
     virtual bool isCleanupTask() const { return false; }
 };
 
+class CallClosureTask : public ExecutionContextTask {
+public:
+    static PassOwnPtr<CallClosureTask> create(const Closure& closure)
+    {
+        return adoptPtr(new CallClosureTask(closure));
+    }
+    virtual void performTask(ExecutionContext*) OVERRIDE { m_closure(); }
+
+private:
+    explicit CallClosureTask(const Closure& closure) : m_closure(closure) { }
+    Closure m_closure;
+};
+
 } // namespace
 
 #endif
diff --git a/Source/core/dom/FullscreenElementStack.cpp b/Source/core/dom/FullscreenElementStack.cpp
index 89c6851..1cb4b79 100644
--- a/Source/core/dom/FullscreenElementStack.cpp
+++ b/Source/core/dom/FullscreenElementStack.cpp
@@ -517,6 +517,10 @@
     if (!m_fullScreenElement)
         return;
 
+    // If the node isn't in a document it can't have a fullscreen'd child.
+    if (!node->inDocument())
+        return;
+
     bool elementInSubtree = false;
     if (amongChildrenOnly)
         elementInSubtree = m_fullScreenElement->isDescendantOf(node);
diff --git a/Source/core/dom/GlobalEventHandlers.idl b/Source/core/dom/GlobalEventHandlers.idl
index 6666780..8800382 100644
--- a/Source/core/dom/GlobalEventHandlers.idl
+++ b/Source/core/dom/GlobalEventHandlers.idl
@@ -36,41 +36,41 @@
     attribute EventHandler oncanplay;
     attribute EventHandler oncanplaythrough;
     attribute EventHandler onchange;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onclick;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onclick;
     attribute EventHandler onclose;
     attribute EventHandler oncontextmenu;
     attribute EventHandler oncuechange;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondblclick;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondrag;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondragend;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondragenter;
-    //[ActivityLogging=SetterForAllWorlds] attribute EventHandler ondragexit;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondragleave;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondragover;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondragstart;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler ondrop;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondrag;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragend;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
+    //[PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragexit;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragover;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondrop;
     attribute EventHandler ondurationchange;
     attribute EventHandler onemptied;
     attribute EventHandler onended;
     attribute EventHandler onerror;
     attribute EventHandler onfocus;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler oninput;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler oninput;
     attribute EventHandler oninvalid;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onkeydown;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onkeypress;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onkeyup;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
     attribute EventHandler onload;
     attribute EventHandler onloadeddata;
     attribute EventHandler onloadedmetadata;
     attribute EventHandler onloadstart;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmousedown;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmouseenter;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmouseleave;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmousemove;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmouseout;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmouseover;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmouseup;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onmousewheel;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
     attribute EventHandler onpause;
     attribute EventHandler onplay;
     attribute EventHandler onplaying;
diff --git a/Source/core/dom/IconURL.cpp b/Source/core/dom/IconURL.cpp
index 97575a2..248835b 100644
--- a/Source/core/dom/IconURL.cpp
+++ b/Source/core/dom/IconURL.cpp
@@ -33,9 +33,18 @@
 
 namespace WebCore {
 
-IconURL IconURL::defaultIconURL(const KURL& url, IconType type)
+IconURL IconURL::defaultFavicon(const KURL& documentURL)
 {
-    IconURL result(url, emptyString(), emptyString(), type);
+    ASSERT(documentURL.protocolIsInHTTPFamily());
+    KURL url;
+    bool couldSetProtocol = url.setProtocol(documentURL.protocol());
+    ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
+    url.setHost(documentURL.host());
+    if (documentURL.hasPort())
+        url.setPort(documentURL.port());
+    url.setPath("/favicon.ico");
+
+    IconURL result(url, emptyString(), emptyString(), Favicon);
     result.m_isDefaultIcon = true;
     return result;
 }
diff --git a/Source/core/dom/IconURL.h b/Source/core/dom/IconURL.h
index e352b7f..adec2a7 100644
--- a/Source/core/dom/IconURL.h
+++ b/Source/core/dom/IconURL.h
@@ -31,7 +31,7 @@
 #ifndef IconURL_h
 #define IconURL_h
 
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 
 namespace WebCore {
 
@@ -70,7 +70,7 @@
     {
     }
 
-    static IconURL defaultIconURL(const KURL&, IconType);
+    static IconURL defaultFavicon(const KURL&);
 };
 
 bool operator==(const IconURL&, const IconURL&);
diff --git a/Source/core/dom/LiveNodeList.h b/Source/core/dom/LiveNodeList.h
index 86e3404..2145b24 100644
--- a/Source/core/dom/LiveNodeList.h
+++ b/Source/core/dom/LiveNodeList.h
@@ -137,8 +137,8 @@
 private:
     Node* itemBeforeOrAfterCachedItem(unsigned offset, ContainerNode* root) const;
     Node* traverseChildNodeListForwardToOffset(unsigned offset, Node* currentNode, unsigned& currentOffset) const;
-    Element* traverseLiveNodeListFirstElement(ContainerNode* root) const;
-    Element* traverseLiveNodeListForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, ContainerNode* root) const;
+    Element* traverseLiveNodeListFirstElement(ContainerNode& root) const;
+    Element* traverseLiveNodeListForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root) const;
     bool isLastItemCloserThanLastOrCachedItem(unsigned offset) const;
     bool isFirstItemCloserThanCachedItem(unsigned offset) const;
     Node* iterateForPreviousNode(Node* current) const;
diff --git a/Source/core/dom/MainThreadTaskRunner.cpp b/Source/core/dom/MainThreadTaskRunner.cpp
new file mode 100644
index 0000000..976d971
--- /dev/null
+++ b/Source/core/dom/MainThreadTaskRunner.cpp
@@ -0,0 +1,116 @@
+/*
+ * 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:
+ * 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/dom/MainThreadTaskRunner.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+struct PerformTaskContext {
+    WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
+public:
+    PerformTaskContext(WeakPtr<MainThreadTaskRunner> runner, PassOwnPtr<ExecutionContextTask> task)
+        : m_runner(runner)
+        , m_task(task)
+    {
+    }
+
+    WeakPtr<MainThreadTaskRunner> m_runner;
+    OwnPtr<ExecutionContextTask> m_task;
+
+    static void didReceiveTask(void* untypedContext);
+};
+
+void PerformTaskContext::didReceiveTask(void* untypedContext)
+{
+    ASSERT(isMainThread());
+
+    OwnPtr<PerformTaskContext> self = adoptPtr(static_cast<PerformTaskContext*>(untypedContext));
+    ASSERT(self);
+
+    MainThreadTaskRunner* runner = self->m_runner.get();
+    if (!runner)
+        return;
+    runner->perform(self->m_task.release());
+}
+
+MainThreadTaskRunner::MainThreadTaskRunner(ExecutionContext* context)
+    : m_context(context)
+    , m_weakFactory(this)
+    , m_pendingTasksTimer(this, &MainThreadTaskRunner::pendingTasksTimerFired)
+    , m_suspended(false)
+{
+}
+
+MainThreadTaskRunner::~MainThreadTaskRunner()
+{
+}
+
+void MainThreadTaskRunner::postTask(PassOwnPtr<ExecutionContextTask> task)
+{
+    callOnMainThread(PerformTaskContext::didReceiveTask, new PerformTaskContext(m_weakFactory.createWeakPtr(), task));
+}
+
+void MainThreadTaskRunner::perform(PassOwnPtr<ExecutionContextTask> task)
+{
+    if (m_context->tasksNeedSuspension() || !m_pendingTasks.isEmpty()) {
+        m_pendingTasks.append(task);
+        return;
+    }
+
+    task->performTask(m_context);
+}
+
+void MainThreadTaskRunner::suspend()
+{
+    ASSERT(!m_suspended);
+    m_pendingTasksTimer.stop();
+    m_suspended = true;
+}
+
+void MainThreadTaskRunner::resume()
+{
+    ASSERT(m_suspended);
+    if (!m_pendingTasks.isEmpty())
+        m_pendingTasksTimer.startOneShot(0);
+
+    m_suspended = false;
+}
+
+void MainThreadTaskRunner::pendingTasksTimerFired(Timer<MainThreadTaskRunner>*)
+{
+    while (!m_pendingTasks.isEmpty()) {
+        OwnPtr<ExecutionContextTask> task = m_pendingTasks[0].release();
+        m_pendingTasks.remove(0);
+        task->performTask(m_context);
+    }
+}
+
+} // namespace
diff --git a/Source/core/dom/MainThreadTaskRunner.h b/Source/core/dom/MainThreadTaskRunner.h
new file mode 100644
index 0000000..a61a226
--- /dev/null
+++ b/Source/core/dom/MainThreadTaskRunner.h
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ *     * 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 MainThreadTaskRunner_h
+#define MainThreadTaskRunner_h
+
+#include "platform/Timer.h"
+
+#include "wtf/FastAllocBase.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/WeakPtr.h"
+
+namespace WebCore {
+
+class ExecutionContext;
+class ExecutionContextTask;
+
+class MainThreadTaskRunner {
+    WTF_MAKE_NONCOPYABLE(MainThreadTaskRunner);
+    WTF_MAKE_FAST_ALLOCATED;
+
+public:
+    static PassOwnPtr<MainThreadTaskRunner> create(ExecutionContext*);
+
+    ~MainThreadTaskRunner();
+
+    void postTask(PassOwnPtr<ExecutionContextTask>); // Executes the task on context's thread asynchronously.
+    void perform(PassOwnPtr<ExecutionContextTask>);
+    void suspend();
+    void resume();
+
+private:
+    explicit MainThreadTaskRunner(ExecutionContext*);
+
+    void pendingTasksTimerFired(Timer<MainThreadTaskRunner>*);
+
+    ExecutionContext* m_context;
+    WeakPtrFactory<MainThreadTaskRunner> m_weakFactory;
+    Timer<MainThreadTaskRunner> m_pendingTasksTimer;
+    Vector<OwnPtr<ExecutionContextTask> > m_pendingTasks;
+    bool m_suspended;
+};
+
+inline PassOwnPtr<MainThreadTaskRunner> MainThreadTaskRunner::create(ExecutionContext* context)
+{
+    return adoptPtr(new MainThreadTaskRunner(context));
+}
+
+} // namespace
+
+#endif
diff --git a/Source/core/dom/MainThreadTaskRunnerTest.cpp b/Source/core/dom/MainThreadTaskRunnerTest.cpp
new file mode 100644
index 0000000..ca17799
--- /dev/null
+++ b/Source/core/dom/MainThreadTaskRunnerTest.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2008 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 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/dom/MainThreadTaskRunner.h"
+
+#include "core/dom/ExecutionContext.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "core/events/EventQueue.h"
+#include "core/testing/UnitTestHelpers.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class NullEventQueue : public EventQueue {
+public:
+    NullEventQueue() { }
+    virtual ~NullEventQueue() { }
+    virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE { return true; }
+    virtual bool cancelEvent(Event*) OVERRIDE { return true; }
+    virtual void close() OVERRIDE { }
+};
+
+class NullExecutionContext : public ExecutionContext, public RefCounted<NullExecutionContext> {
+public:
+    using RefCounted<NullExecutionContext>::ref;
+    using RefCounted<NullExecutionContext>::deref;
+
+    virtual void refExecutionContext() OVERRIDE { ref(); }
+    virtual void derefExecutionContext() OVERRIDE { deref(); }
+    virtual EventQueue* eventQueue() const OVERRIDE { return m_queue.get(); }
+    virtual bool tasksNeedSuspension() { return m_tasksNeedSuspension; }
+
+    void setTasksNeedSuspention(bool flag) { m_tasksNeedSuspension = flag; }
+
+    NullExecutionContext();
+
+private:
+    bool m_tasksNeedSuspension;
+    OwnPtr<EventQueue> m_queue;
+};
+
+NullExecutionContext::NullExecutionContext()
+    : m_tasksNeedSuspension(false)
+    , m_queue(adoptPtr(new NullEventQueue()))
+{
+}
+
+class MarkingBooleanTask FINAL : public ExecutionContextTask {
+public:
+    static PassOwnPtr<MarkingBooleanTask> create(bool* toBeMarked)
+    {
+        return adoptPtr(new MarkingBooleanTask(toBeMarked));
+    }
+
+
+    virtual ~MarkingBooleanTask() { }
+
+private:
+    MarkingBooleanTask(bool* toBeMarked) : m_toBeMarked(toBeMarked) { }
+
+    virtual void performTask(ExecutionContext* context) OVERRIDE
+    {
+        *m_toBeMarked = true;
+    }
+
+    bool* m_toBeMarked;
+};
+
+TEST(MainThreadTaskRunnerTest, PostTask)
+{
+    RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
+    OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
+    bool isMarked = false;
+
+    runner->postTask(MarkingBooleanTask::create(&isMarked));
+    EXPECT_FALSE(isMarked);
+    WebCore::testing::runPendingTasks();
+    EXPECT_TRUE(isMarked);
+}
+
+TEST(MainThreadTaskRunnerTest, SuspendTask)
+{
+    RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
+    OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
+    bool isMarked = false;
+
+    context->setTasksNeedSuspention(true);
+    runner->postTask(MarkingBooleanTask::create(&isMarked));
+    runner->suspend();
+    WebCore::testing::runPendingTasks();
+    EXPECT_FALSE(isMarked);
+
+    context->setTasksNeedSuspention(false);
+    runner->resume();
+    WebCore::testing::runPendingTasks();
+    EXPECT_TRUE(isMarked);
+}
+
+TEST(MainThreadTaskRunnerTest, RemoveRunner)
+{
+    RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
+    OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
+    bool isMarked = false;
+
+    context->setTasksNeedSuspention(true);
+    runner->postTask(MarkingBooleanTask::create(&isMarked));
+    runner.clear();
+    WebCore::testing::runPendingTasks();
+    EXPECT_FALSE(isMarked);
+}
+
+}
diff --git a/Source/core/dom/MessageChannel.cpp b/Source/core/dom/MessageChannel.cpp
index b880fab..20a493d 100644
--- a/Source/core/dom/MessageChannel.cpp
+++ b/Source/core/dom/MessageChannel.cpp
@@ -28,16 +28,32 @@
 #include "core/dom/MessageChannel.h"
 
 #include "core/dom/MessagePort.h"
-#include "core/dom/MessagePortChannel.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebMessagePortChannel.h"
 
 namespace WebCore {
 
+static void createChannel(MessagePort* port1, MessagePort* port2)
+{
+    // Create proxies for each endpoint.
+    OwnPtr<blink::WebMessagePortChannel> channel1 = adoptPtr(blink::Platform::current()->createMessagePortChannel());
+    OwnPtr<blink::WebMessagePortChannel> channel2 = adoptPtr(blink::Platform::current()->createMessagePortChannel());
+
+    // Entangle the two endpoints.
+    channel1->entangle(channel2.get());
+    channel2->entangle(channel1.get());
+
+    // Now entangle the proxies with the appropriate local ports.
+    port1->entangle(channel2.release());
+    port2->entangle(channel1.release());
+}
+
 MessageChannel::MessageChannel(ExecutionContext* context)
     : m_port1(MessagePort::create(*context))
     , m_port2(MessagePort::create(*context))
 {
     ScriptWrappable::init(this);
-    MessagePortChannel::createChannel(m_port1.get(), m_port2.get());
+    createChannel(m_port1.get(), m_port2.get());
 }
 
 MessageChannel::~MessageChannel()
diff --git a/Source/core/dom/MessagePort.cpp b/Source/core/dom/MessagePort.cpp
index 91b6484..f827ccf 100644
--- a/Source/core/dom/MessagePort.cpp
+++ b/Source/core/dom/MessagePort.cpp
@@ -30,39 +30,48 @@
 #include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/SerializedScriptValue.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/dom/ExecutionContext.h"
 #include "core/events/MessageEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/frame/DOMWindow.h"
 #include "core/workers/WorkerGlobalScope.h"
+#include "public/platform/WebMessagePortChannel.h"
+#include "public/platform/WebString.h"
+#include "wtf/Functional.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
+PassRefPtr<MessagePort> MessagePort::create(ExecutionContext& executionContext)
+{
+    RefPtr<MessagePort> port = adoptRef(new MessagePort(executionContext));
+    port->suspendIfNeeded();
+    return port.release();
+}
+
 MessagePort::MessagePort(ExecutionContext& executionContext)
-    : m_started(false)
+    : ActiveDOMObject(&executionContext)
+    , m_started(false)
     , m_closed(false)
-    , m_executionContext(&executionContext)
+    , m_weakFactory(this)
 {
     ScriptWrappable::init(this);
-    m_executionContext->createdMessagePort(this);
-
-    // Don't need to call processMessagePortMessagesSoon() here, because the port will not be opened until start() is invoked.
 }
 
 MessagePort::~MessagePort()
 {
     close();
-    if (m_executionContext)
-        m_executionContext->destroyedMessagePort(this);
 }
 
-void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& es)
+void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
 {
     if (!isEntangled())
         return;
-    ASSERT(m_executionContext);
+    ASSERT(executionContext());
+    ASSERT(m_entangledChannel);
 
     OwnPtr<MessagePortChannelArray> channels;
     // Make sure we aren't connected to any of the passed-in ports.
@@ -70,28 +79,29 @@
         for (unsigned int i = 0; i < ports->size(); ++i) {
             MessagePort* dataPort = (*ports)[i].get();
             if (dataPort == this) {
-                es.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("postMessage", "MessagePort", "Item #" + String::number(i) + " in the array of ports contains the source port."));
+                exceptionState.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("postMessage", "MessagePort", "Item #" + String::number(i) + " in the array of ports contains the source port."));
                 return;
             }
         }
-        channels = MessagePort::disentanglePorts(ports, es);
-        if (es.hadException())
+        channels = MessagePort::disentanglePorts(ports, exceptionState);
+        if (exceptionState.hadException())
             return;
     }
-    m_entangledChannel->postMessageToRemote(message, channels.release());
+
+    blink::WebString messageString = message->toWireString();
+    blink::WebMessagePortChannelArray* webChannels = 0;
+    if (channels && channels->size()) {
+        webChannels = new blink::WebMessagePortChannelArray(channels->size());
+        for (size_t i = 0; i < channels->size(); ++i)
+            (*webChannels)[i] = (*channels)[i].leakPtr();
+    }
+    m_entangledChannel->postMessage(messageString, webChannels);
 }
 
-PassOwnPtr<MessagePortChannel> MessagePort::disentangle()
+PassOwnPtr<blink::WebMessagePortChannel> MessagePort::disentangle()
 {
     ASSERT(m_entangledChannel);
-
-    m_entangledChannel->disentangle();
-
-    // We can't receive any messages or generate any events, so remove ourselves from the list of active ports.
-    ASSERT(m_executionContext);
-    m_executionContext->destroyedMessagePort(this);
-    m_executionContext = 0;
-
+    m_entangledChannel->setClient(0);
     return m_entangledChannel.release();
 }
 
@@ -99,8 +109,8 @@
 // This code may be called from another thread, and so should not call any non-threadsafe APIs (i.e. should not call into the entangled channel or access mutable variables).
 void MessagePort::messageAvailable()
 {
-    ASSERT(m_executionContext);
-    m_executionContext->processMessagePortMessagesSoon();
+    ASSERT(executionContext());
+    executionContext()->postTask(bind(&MessagePort::dispatchMessages, m_weakFactory.createWeakPtr()));
 }
 
 void MessagePort::start()
@@ -109,38 +119,29 @@
     if (!isEntangled())
         return;
 
-    ASSERT(m_executionContext);
+    ASSERT(executionContext());
     if (m_started)
         return;
 
     m_started = true;
-    m_executionContext->processMessagePortMessagesSoon();
+    messageAvailable();
 }
 
 void MessagePort::close()
 {
     if (isEntangled())
-        m_entangledChannel->close();
+        m_entangledChannel->setClient(0);
     m_closed = true;
 }
 
-void MessagePort::entangle(PassOwnPtr<MessagePortChannel> remote)
+void MessagePort::entangle(PassOwnPtr<blink::WebMessagePortChannel> remote)
 {
     // Only invoked to set our initial entanglement.
     ASSERT(!m_entangledChannel);
-    ASSERT(m_executionContext);
+    ASSERT(executionContext());
 
-    remote->entangle(this);
     m_entangledChannel = remote;
-}
-
-void MessagePort::contextDestroyed()
-{
-    ASSERT(m_executionContext);
-    // Must be closed before blowing away the cached context, to ensure that we get no more calls to messageAvailable().
-    // ExecutionContext::closeMessagePorts() takes care of that.
-    ASSERT(m_closed);
-    m_executionContext = 0;
+    m_entangledChannel->setClient(this);
 }
 
 const AtomicString& MessagePort::interfaceName() const
@@ -148,42 +149,53 @@
     return EventTargetNames::MessagePort;
 }
 
-ExecutionContext* MessagePort::executionContext() const
+static bool tryGetMessageFrom(blink::WebMessagePortChannel& webChannel, RefPtr<SerializedScriptValue>& message, OwnPtr<MessagePortChannelArray>& channels)
 {
-    return m_executionContext;
+    blink::WebString messageString;
+    blink::WebMessagePortChannelArray webChannels;
+    if (!webChannel.tryGetMessage(&messageString, webChannels))
+        return false;
+
+    if (webChannels.size()) {
+        channels = adoptPtr(new MessagePortChannelArray(webChannels.size()));
+        for (size_t i = 0; i < webChannels.size(); ++i)
+            (*channels)[i] = adoptPtr(webChannels[i]);
+    }
+    message = SerializedScriptValue::createFromWire(messageString);
+    return true;
 }
 
 void MessagePort::dispatchMessages()
 {
     // Messages for contexts that are not fully active get dispatched too, but JSAbstractEventListener::handleEvent() doesn't call handlers for these.
     // The HTML5 spec specifies that any messages sent to a document that is not fully active should be dropped, so this behavior is OK.
-    ASSERT(started());
+    if (!started())
+        return;
 
     RefPtr<SerializedScriptValue> message;
     OwnPtr<MessagePortChannelArray> channels;
-    while (m_entangledChannel && m_entangledChannel->tryGetMessageFromRemote(message, channels)) {
-
+    while (m_entangledChannel && tryGetMessageFrom(*m_entangledChannel, message, channels)) {
         // close() in Worker onmessage handler should prevent next message from dispatching.
-        if (m_executionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_executionContext)->isClosing())
+        if (executionContext()->isWorkerGlobalScope() && toWorkerGlobalScope(executionContext())->isClosing())
             return;
 
-        OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_executionContext, channels.release());
+        OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*executionContext(), channels.release());
         RefPtr<Event> evt = MessageEvent::create(ports.release(), message.release());
 
         dispatchEvent(evt.release(), ASSERT_NO_EXCEPTION);
     }
 }
 
-bool MessagePort::hasPendingActivity()
+bool MessagePort::hasPendingActivity() const
 {
     // The spec says that entangled message ports should always be treated as if they have a strong reference.
     // We'll also stipulate that the queue needs to be open (if the app drops its reference to the port before start()-ing it, then it's not really entangled as it's unreachable).
-    if (m_started && m_entangledChannel && m_entangledChannel->hasPendingActivity())
+    if (m_started && m_entangledChannel)
         return true;
     return isEntangled();
 }
 
-PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionState& es)
+PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionState& exceptionState)
 {
     if (!ports || !ports->size())
         return nullptr;
@@ -202,7 +214,7 @@
                 type = "already neutered";
             else
                 type = "a duplicate";
-            es.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("disentanglePorts", "MessagePort", "Item #"  + String::number(i) + " in the array of ports is " + type + "."));
+            exceptionState.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("disentanglePorts", "MessagePort", "Item #"  + String::number(i) + " in the array of ports is " + type + "."));
             return nullptr;
         }
         portSet.add(port);
diff --git a/Source/core/dom/MessagePort.h b/Source/core/dom/MessagePort.h
index 4540a9b..c5f78ea 100644
--- a/Source/core/dom/MessagePort.h
+++ b/Source/core/dom/MessagePort.h
@@ -28,15 +28,18 @@
 #define MessagePort_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/ActiveDOMObject.h"
 #include "core/events/EventListener.h"
 #include "core/events/EventTarget.h"
-#include "core/dom/MessagePortChannel.h"
-#include "wtf/Forward.h"
+#include "public/platform/WebMessagePortChannel.h"
+#include "public/platform/WebMessagePortChannelClient.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
@@ -45,14 +48,22 @@
 class Frame;
 class MessagePort;
 class ExecutionContext;
+class SerializedScriptValue;
 
 // The overwhelmingly common case is sending a single port, so handle that efficiently with an inline buffer of size 1.
 typedef Vector<RefPtr<MessagePort>, 1> MessagePortArray;
 
-class MessagePort : public RefCounted<MessagePort>, public ScriptWrappable, public EventTargetWithInlineData {
+// Not to be confused with blink::WebMessagePortChannelArray; this one uses Vector and OwnPtr instead of WebVector and raw pointers.
+typedef Vector<OwnPtr<blink::WebMessagePortChannel>, 1> MessagePortChannelArray;
+
+class MessagePort : public RefCounted<MessagePort>
+    , public ActiveDOMObject
+    , public EventTargetWithInlineData
+    , public ScriptWrappable
+    , public blink::WebMessagePortChannelClient {
     REFCOUNTED_EVENT_TARGET(MessagePort);
 public:
-    static PassRefPtr<MessagePort> create(ExecutionContext& executionContext) { return adoptRef(new MessagePort(executionContext)); }
+    static PassRefPtr<MessagePort> create(ExecutionContext&);
     virtual ~MessagePort();
 
     void postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray*, ExceptionState&);
@@ -60,8 +71,8 @@
     void start();
     void close();
 
-    void entangle(PassOwnPtr<MessagePortChannel>);
-    PassOwnPtr<MessagePortChannel> disentangle();
+    void entangle(PassOwnPtr<blink::WebMessagePortChannel>);
+    PassOwnPtr<blink::WebMessagePortChannel> disentangle();
 
     // Returns 0 if there is an exception, or if the passed-in array is 0/empty.
     static PassOwnPtr<MessagePortChannelArray> disentanglePorts(const MessagePortArray*, ExceptionState&);
@@ -69,18 +80,15 @@
     // Returns 0 if the passed array is 0/empty.
     static PassOwnPtr<MessagePortArray> entanglePorts(ExecutionContext&, PassOwnPtr<MessagePortChannelArray>);
 
-    void messageAvailable();
     bool started() const { return m_started; }
 
-    void contextDestroyed();
-
     virtual const AtomicString& interfaceName() const OVERRIDE;
-    virtual ExecutionContext* executionContext() const OVERRIDE;
+    virtual ExecutionContext* executionContext() const OVERRIDE { return ActiveDOMObject::executionContext(); }
     MessagePort* toMessagePort() OVERRIDE { return this; }
 
-    void dispatchMessages();
-
-    bool hasPendingActivity();
+    // ActiveDOMObject implementation.
+    virtual bool hasPendingActivity() const OVERRIDE;
+    virtual void stop() OVERRIDE { close(); }
 
     void setOnmessage(PassRefPtr<EventListener> listener, DOMWrapperWorld* world)
     {
@@ -90,20 +98,24 @@
     EventListener* onmessage(DOMWrapperWorld* world) { return getAttributeEventListener(EventTypeNames::message, world); }
 
     // A port starts out its life entangled, and remains entangled until it is closed or is cloned.
-    bool isEntangled() { return !m_closed && !isNeutered(); }
+    bool isEntangled() const { return !m_closed && !isNeutered(); }
 
     // A port gets neutered when it is transferred to a new owner via postMessage().
-    bool isNeutered() { return !m_entangledChannel; }
+    bool isNeutered() const { return !m_entangledChannel; }
 
 private:
     explicit MessagePort(ExecutionContext&);
 
-    OwnPtr<MessagePortChannel> m_entangledChannel;
+    // WebMessagePortChannelClient implementation.
+    virtual void messageAvailable() OVERRIDE;
+    void dispatchMessages();
+
+    OwnPtr<blink::WebMessagePortChannel> m_entangledChannel;
 
     bool m_started;
     bool m_closed;
 
-    ExecutionContext* m_executionContext;
+    WeakPtrFactory<MessagePort> m_weakFactory;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/MessagePortChannel.cpp b/Source/core/dom/MessagePortChannel.cpp
deleted file mode 100644
index 8f5cee3..0000000
--- a/Source/core/dom/MessagePortChannel.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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:
- *
- *     * 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/dom/MessagePortChannel.h"
-
-#include "core/dom/MessagePort.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebMessagePortChannel.h"
-#include "public/platform/WebString.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-PassOwnPtr<MessagePortChannel> MessagePortChannel::create(WebKit::WebMessagePortChannel* channel)
-{
-    return adoptPtr(new MessagePortChannel(channel));
-}
-
-void MessagePortChannel::createChannel(MessagePort* port1, MessagePort* port2)
-{
-    // Create proxies for each endpoint.
-    OwnPtr<MessagePortChannel> channel1 = create(WebKit::Platform::current()->createMessagePortChannel());
-    OwnPtr<MessagePortChannel> channel2 = create(WebKit::Platform::current()->createMessagePortChannel());
-
-    // Entangle the two endpoints.
-    channel1->m_webChannel->entangle(channel2->m_webChannel);
-    channel2->m_webChannel->entangle(channel1->m_webChannel);
-
-    // Now entangle the proxies with the appropriate local ports.
-    port1->entangle(channel2.release());
-    port2->entangle(channel1.release());
-}
-
-MessagePortChannel::MessagePortChannel(WebKit::WebMessagePortChannel* channel)
-    : m_localPort(0)
-    , m_webChannel(channel)
-{
-    ASSERT(m_webChannel);
-    m_webChannel->setClient(this);
-}
-
-MessagePortChannel::~MessagePortChannel()
-{
-    if (m_webChannel)
-        m_webChannel->destroy();
-}
-
-void MessagePortChannel::entangle(MessagePort* port)
-{
-    MutexLocker lock(m_mutex);
-    m_localPort = port;
-}
-
-void MessagePortChannel::disentangle()
-{
-    MutexLocker lock(m_mutex);
-    m_localPort = 0;
-}
-
-void MessagePortChannel::postMessageToRemote(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
-{
-    if (!m_localPort || !m_webChannel)
-        return;
-
-    WebKit::WebString messageString = message->toWireString();
-    WebKit::WebMessagePortChannelArray* webChannels = 0;
-    if (channels && channels->size()) {
-        webChannels = new WebKit::WebMessagePortChannelArray(channels->size());
-        for (size_t i = 0; i < channels->size(); ++i)
-            (*webChannels)[i] = (*channels)[i]->webChannelRelease();
-    }
-    m_webChannel->postMessage(messageString, webChannels);
-}
-
-bool MessagePortChannel::tryGetMessageFromRemote(RefPtr<SerializedScriptValue>& serializedMessage, OwnPtr<MessagePortChannelArray>& channels)
-{
-    if (!m_webChannel)
-        return false;
-
-    WebKit::WebString message;
-    WebKit::WebMessagePortChannelArray webChannels;
-    bool rv = m_webChannel->tryGetMessage(&message, webChannels);
-    if (rv) {
-        if (webChannels.size()) {
-            channels = adoptPtr(new MessagePortChannelArray(webChannels.size()));
-            for (size_t i = 0; i < webChannels.size(); ++i)
-                (*channels)[i] = MessagePortChannel::create(webChannels[i]);
-        }
-        serializedMessage = SerializedScriptValue::createFromWire(message);
-    }
-
-    return rv;
-}
-
-void MessagePortChannel::close()
-{
-    MutexLocker lock(m_mutex);
-    // Disentangle ourselves from the other end. We still maintain a reference to m_webChannel,
-    // since previously-existing messages should still be delivered.
-    m_localPort = 0;
-}
-
-bool MessagePortChannel::hasPendingActivity()
-{
-    MutexLocker lock(m_mutex);
-    return m_localPort;
-}
-
-void MessagePortChannel::messageAvailable()
-{
-    MutexLocker lock(m_mutex);
-    if (m_localPort)
-        m_localPort->messageAvailable();
-}
-
-WebKit::WebMessagePortChannel* MessagePortChannel::webChannelRelease()
-{
-    ASSERT(m_webChannel);
-    WebKit::WebMessagePortChannel* webChannel = m_webChannel;
-    m_webChannel = 0;
-    webChannel->setClient(0);
-    return webChannel;
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/MessagePortChannel.h b/Source/core/dom/MessagePortChannel.h
deleted file mode 100644
index 799a6b6..0000000
--- a/Source/core/dom/MessagePortChannel.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * 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:
- *
- *     * 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 MessagePortChannel_h
-#define MessagePortChannel_h
-
-#include "bindings/v8/SerializedScriptValue.h"
-#include "public/platform/WebMessagePortChannelClient.h"
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/ThreadSafeRefCounted.h"
-#include "wtf/ThreadingPrimitives.h"
-
-namespace WebKit {
-class WebMessagePortChannel;
-}
-
-namespace WebCore {
-
-class MessagePort;
-class MessagePortChannel;
-class ExecutionContext;
-class SerializedScriptValue;
-
-// The overwhelmingly common case is sending a single port, so handle that efficiently with an inline buffer of size 1.
-typedef Vector<OwnPtr<MessagePortChannel>, 1> MessagePortChannelArray;
-
-// MessagePortChannel is a platform-independent interface to the remote side of a message channel.
-class MessagePortChannel : public WebKit::WebMessagePortChannelClient {
-    WTF_MAKE_NONCOPYABLE(MessagePortChannel);
-public:
-    static void createChannel(MessagePort*, MessagePort*);
-    static PassOwnPtr<MessagePortChannel> create(WebKit::WebMessagePortChannel*);
-
-    virtual ~MessagePortChannel();
-
-    // Entangles the channel with a port (called when a port has been cloned, after the clone has been marshaled to its new owning thread and is ready to receive messages).
-    void entangle(MessagePort*);
-
-    // Disentangles the channel from a given port so it no longer forwards messages to the port. Called when the port is being cloned and no new owning thread has yet been established.
-    void disentangle();
-
-    // Closes the port (ensures that no further messages can be added to either queue).
-    void close();
-
-    // Returns true if the proxy currently contains messages for this port.
-    bool hasPendingActivity();
-
-    // Sends a message and optional cloned port to the remote port.
-    void postMessageToRemote(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
-
-    // Extracts a message from the message queue for this port.
-    bool tryGetMessageFromRemote(RefPtr<SerializedScriptValue>&, OwnPtr<MessagePortChannelArray>&);
-
-    // Releases ownership of the contained web channel.
-    WebKit::WebMessagePortChannel* webChannelRelease();
-
-private:
-    explicit MessagePortChannel(WebKit::WebMessagePortChannel*);
-
-    // WebKit::WebMessagePortChannelClient implementation
-    virtual void messageAvailable() OVERRIDE;
-
-    // Mutex used to ensure exclusive access to the object internals.
-    Mutex m_mutex;
-
-    // The port we are connected to - this is the port that is notified when new messages arrive.
-    MessagePort* m_localPort;
-
-    WebKit::WebMessagePortChannel* m_webChannel;
-};
-
-} // namespace WebCore
-
-#endif // MessagePortChannel_h
diff --git a/Source/core/dom/MutationObserver.cpp b/Source/core/dom/MutationObserver.cpp
index 5b664c4..ebe5639 100644
--- a/Source/core/dom/MutationObserver.cpp
+++ b/Source/core/dom/MutationObserver.cpp
@@ -74,51 +74,65 @@
     ASSERT(m_registrations.isEmpty());
 }
 
-void MutationObserver::observe(Node* node, const Dictionary& optionsDictionary, ExceptionState& es)
+void MutationObserver::observe(Node* node, const Dictionary& optionsDictionary, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The provided node was null."));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The provided node was null."));
         return;
     }
 
-    static const struct {
-        const char* name;
-        MutationObserverOptions value;
-    } booleanOptions[] = {
-        { "childList", ChildList },
-        { "attributes", Attributes },
-        { "characterData", CharacterData },
-        { "subtree", Subtree },
-        { "attributeOldValue", AttributeOldValue },
-        { "characterDataOldValue", CharacterDataOldValue }
-    };
     MutationObserverOptions options = 0;
-    for (unsigned i = 0; i < sizeof(booleanOptions) / sizeof(booleanOptions[0]); ++i) {
-        bool value = false;
-        if (optionsDictionary.get(booleanOptions[i].name, value) && value)
-            options |= booleanOptions[i].value;
-    }
+
+    bool attributeOldValue = false;
+    bool attributeOldValuePresent = optionsDictionary.get("attributeOldValue", attributeOldValue);
+    if (attributeOldValue)
+        options |= AttributeOldValue;
 
     HashSet<AtomicString> attributeFilter;
-    if (optionsDictionary.get("attributeFilter", attributeFilter))
+    bool attributeFilterPresent = optionsDictionary.get("attributeFilter", attributeFilter);
+    if (attributeFilterPresent)
         options |= AttributeFilter;
 
-    if (!(options & (Attributes | CharacterData | ChildList))) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object must set at least one of 'attributes', 'characterData', or 'childList' to true."));
-        return;
-    }
+    bool attributes = false;
+    bool attributesPresent = optionsDictionary.get("attributes", attributes);
+    if (attributes || (!attributesPresent && (attributeOldValuePresent || attributeFilterPresent)))
+        options |= Attributes;
+
+    bool characterDataOldValue = false;
+    bool characterDataOldValuePresent = optionsDictionary.get("characterDataOldValue", characterDataOldValue);
+    if (characterDataOldValue)
+        options |= CharacterDataOldValue;
+
+    bool characterData = false;
+    bool characterDataPresent = optionsDictionary.get("characterData", characterData);
+    if (characterData || (!characterDataPresent && characterDataOldValuePresent))
+        options |= CharacterData;
+
+    bool childListValue = false;
+    if (optionsDictionary.get("childList", childListValue) && childListValue)
+        options |= ChildList;
+
+    bool subtreeValue = false;
+    if (optionsDictionary.get("subtree", subtreeValue) && subtreeValue)
+        options |= Subtree;
+
     if (!(options & Attributes)) {
         if (options & AttributeOldValue) {
-            es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'attributeOldValue' to true when 'attributes' is also true."));
+            exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'attributeOldValue' to true when 'attributes' is true or not present."));
             return;
         }
         if (options & AttributeFilter) {
-            es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'attributeFilter' when 'attributes' is also true."));
+            exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'attributeFilter' when 'attributes' is true or not present."));
             return;
         }
     }
     if (!((options & CharacterData) || !(options & CharacterDataOldValue))) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'characterDataOldValue' to true when 'characterData' is also true."));
+        exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'characterDataOldValue' to true when 'characterData' is true or not present."));
+        return;
+    }
+
+    if (!(options & (Attributes | CharacterData | ChildList))) {
+        exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object must set at least one of 'attributes', 'characterData', or 'childList' to true."));
         return;
     }
 
diff --git a/Source/core/dom/NamedFlow.cpp b/Source/core/dom/NamedFlow.cpp
index 4f4d204..04f1c08 100644
--- a/Source/core/dom/NamedFlow.cpp
+++ b/Source/core/dom/NamedFlow.cpp
@@ -35,8 +35,8 @@
 #include "core/dom/StaticNodeList.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/events/UIEvent.h"
+#include "core/rendering/RenderNamedFlowFragment.h"
 #include "core/rendering/RenderNamedFlowThread.h"
-#include "core/rendering/RenderRegion.h"
 
 namespace WebCore {
 
@@ -104,11 +104,11 @@
     int countNonPseudoRegions = -1;
     RenderRegionList::const_iterator iter = regionList.begin();
     for (int index = 0; iter != regionList.end(); ++index, ++iter) {
-        const RenderRegion* renderRegion = *iter;
+        const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
         // FIXME: Pseudo-elements are not included in the list.
         // They will be included when we will properly support the Region interface
         // http://dev.w3.org/csswg/css-regions/#the-region-interface
-        if (renderRegion->isPseudoElement())
+        if (!renderRegion->isElementBasedRegion())
             continue;
         countNonPseudoRegions++;
         if (renderRegion->regionOversetState() == RegionEmpty)
@@ -135,13 +135,13 @@
     if (inFlowThread(contentNode->renderer(), m_parentFlowThread)) {
         const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
         for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
-            const RenderRegion* renderRegion = *iter;
+            const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
             // They will be included when we will properly support the Region interface
             // http://dev.w3.org/csswg/css-regions/#the-region-interface
-            if (renderRegion->isPseudoElement())
+            if (!renderRegion->isElementBasedRegion())
                 continue;
             if (m_parentFlowThread->objectInFlowRegion(contentNode->renderer(), renderRegion))
-                regionNodes.append(renderRegion->node());
+                regionNodes.append(renderRegion->nodeForRegion());
         }
     }
 
@@ -162,12 +162,12 @@
 
     const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
     for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
-        const RenderRegion* renderRegion = *iter;
+        const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
         // They will be included when we will properly support the Region interface
         // http://dev.w3.org/csswg/css-regions/#the-region-interface
-        if (renderRegion->isPseudoElement())
+        if (!renderRegion->isElementBasedRegion())
             continue;
-        regionNodes.append(renderRegion->node());
+        regionNodes.append(renderRegion->nodeForRegion());
     }
 
     return StaticNodeList::adopt(regionNodes);
diff --git a/Source/core/dom/NamedFlowCollection.cpp b/Source/core/dom/NamedFlowCollection.cpp
index b9ae4b3..538a88c 100644
--- a/Source/core/dom/NamedFlowCollection.cpp
+++ b/Source/core/dom/NamedFlowCollection.cpp
@@ -62,7 +62,7 @@
 
 NamedFlow* NamedFlowCollection::flowByName(const String& flowName)
 {
-    NamedFlowSet::iterator it = m_namedFlows.find<String, NamedFlowHashTranslator>(flowName);
+    NamedFlowSet::iterator it = m_namedFlows.find<NamedFlowHashTranslator>(flowName);
     if (it == m_namedFlows.end() || (*it)->flowState() == NamedFlow::FlowStateNull)
         return 0;
 
@@ -71,7 +71,7 @@
 
 PassRefPtr<NamedFlow> NamedFlowCollection::ensureFlowWithName(const String& flowName)
 {
-    NamedFlowSet::iterator it = m_namedFlows.find<String, NamedFlowHashTranslator>(flowName);
+    NamedFlowSet::iterator it = m_namedFlows.find<NamedFlowHashTranslator>(flowName);
     if (it != m_namedFlows.end()) {
         NamedFlow* namedFlow = *it;
         ASSERT(namedFlow->flowState() == NamedFlow::FlowStateNull);
diff --git a/Source/core/dom/NamedNodeMap.cpp b/Source/core/dom/NamedNodeMap.cpp
index f75ce65..2265972 100644
--- a/Source/core/dom/NamedNodeMap.cpp
+++ b/Source/core/dom/NamedNodeMap.cpp
@@ -55,45 +55,45 @@
     return m_element->getAttributeNodeNS(namespaceURI, localName);
 }
 
-PassRefPtr<Node> NamedNodeMap::removeNamedItem(const AtomicString& name, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::removeNamedItem(const AtomicString& name, ExceptionState& exceptionState)
 {
     size_t index = m_element->hasAttributes() ? m_element->getAttributeItemIndex(name, m_element->shouldIgnoreAttributeCase()) : kNotFound;
     if (index == kNotFound) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return 0;
     }
     return m_element->detachAttribute(index);
 }
 
-PassRefPtr<Node> NamedNodeMap::removeNamedItemNS(const AtomicString& namespaceURI, const AtomicString& localName, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::removeNamedItemNS(const AtomicString& namespaceURI, const AtomicString& localName, ExceptionState& exceptionState)
 {
     size_t index = m_element->hasAttributes() ? m_element->getAttributeItemIndex(QualifiedName(nullAtom, localName, namespaceURI)) : kNotFound;
     if (index == kNotFound) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return 0;
     }
     return m_element->detachAttribute(index);
 }
 
-PassRefPtr<Node> NamedNodeMap::setNamedItem(Node* node, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::setNamedItem(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return 0;
     }
 
     // Not mentioned in spec: throw a HIERARCHY_REQUEST_ERROR if the user passes in a non-attribute node
     if (!node->isAttributeNode()) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return 0;
     }
 
-    return m_element->setAttributeNode(toAttr(node), es);
+    return m_element->setAttributeNode(toAttr(node), exceptionState);
 }
 
-PassRefPtr<Node> NamedNodeMap::setNamedItemNS(Node* node, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::setNamedItemNS(Node* node, ExceptionState& exceptionState)
 {
-    return setNamedItem(node, es);
+    return setNamedItem(node, exceptionState);
 }
 
 PassRefPtr<Node> NamedNodeMap::item(unsigned index) const
diff --git a/Source/core/dom/NamedNodeMap.idl b/Source/core/dom/NamedNodeMap.idl
index 9c687b7..0f51574 100644
--- a/Source/core/dom/NamedNodeMap.idl
+++ b/Source/core/dom/NamedNodeMap.idl
@@ -19,7 +19,7 @@
  */
 
 [
-    GenerateIsReachable=element
+    GenerateVisitDOMWrapper=element,
 ] interface NamedNodeMap {
 
     Node getNamedItem([Default=Undefined] optional DOMString name);
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 8fdeee7..2cd8dde 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -448,42 +448,42 @@
     return lastChild();
 }
 
-void Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& es)
+void Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& exceptionState)
 {
     if (isContainerNode())
-        toContainerNode(this)->insertBefore(newChild, refChild, es);
+        toContainerNode(this)->insertBefore(newChild, refChild, exceptionState);
     else
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("insertBefore", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("insertBefore", "Node", "This node type does not support this method."));
 }
 
-void Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& es)
+void Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& exceptionState)
 {
     if (isContainerNode())
-        toContainerNode(this)->replaceChild(newChild, oldChild, es);
+        toContainerNode(this)->replaceChild(newChild, oldChild, exceptionState);
     else
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("replaceChild", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("replaceChild", "Node", "This node type does not support this method."));
 }
 
-void Node::removeChild(Node* oldChild, ExceptionState& es)
+void Node::removeChild(Node* oldChild, ExceptionState& exceptionState)
 {
     if (isContainerNode())
-        toContainerNode(this)->removeChild(oldChild, es);
+        toContainerNode(this)->removeChild(oldChild, exceptionState);
     else
-        es.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "This node type does not support this method."));
 }
 
-void Node::appendChild(PassRefPtr<Node> newChild, ExceptionState& es)
+void Node::appendChild(PassRefPtr<Node> newChild, ExceptionState& exceptionState)
 {
     if (isContainerNode())
-        toContainerNode(this)->appendChild(newChild, es);
+        toContainerNode(this)->appendChild(newChild, exceptionState);
     else
-        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("appendChild", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("appendChild", "Node", "This node type does not support this method."));
 }
 
-void Node::remove(ExceptionState& es)
+void Node::remove(ExceptionState& exceptionState)
 {
     if (ContainerNode* parent = parentNode())
-        parent->removeChild(this, es);
+        parent->removeChild(this, exceptionState);
 }
 
 void Node::normalize()
@@ -505,7 +505,7 @@
         if (type == TEXT_NODE)
             node = toText(node)->mergeNextSiblingNodesIfPossible();
         else
-            node = NodeTraversal::nextPostOrder(node.get());
+            node = NodeTraversal::nextPostOrder(*node);
     }
 }
 
@@ -515,12 +515,12 @@
     return nullAtom;
 }
 
-void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionState& es)
+void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionState& exceptionState)
 {
     // The spec says that for nodes other than elements and attributes, prefix is always null.
     // It does not say what to do when the user tries to set the prefix on another type of
     // node, however Mozilla throws a NamespaceError exception.
-    es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "Prefixes are only supported on element and attribute nodes."));
+    exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "Prefixes are only supported on element and attribute nodes."));
 }
 
 const AtomicString& Node::localName() const
@@ -654,6 +654,7 @@
     return false;
 }
 
+#ifndef NDEBUG
 inline static ShadowRoot* oldestShadowRootFor(const Node* node)
 {
     if (!node->isElementNode())
@@ -662,6 +663,7 @@
         return shadow->oldestShadowRoot();
     return 0;
 }
+#endif
 
 void Node::recalcDistribution()
 {
@@ -701,7 +703,7 @@
     m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
 }
 
-inline void Node::markAncestorsWithChildNeedsStyleRecalc()
+void Node::markAncestorsWithChildNeedsStyleRecalc()
 {
     for (ContainerNode* p = parentOrShadowHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrShadowHostNode())
         p->setChildNeedsStyleRecalc();
@@ -732,19 +734,6 @@
     return inDocument() && document().isActive();
 }
 
-void Node::lazyAttach()
-{
-    markAncestorsWithChildNeedsStyleRecalc();
-    for (Node* node = this; node; node = NodeTraversal::next(node, this)) {
-        node->setAttached();
-        node->setStyleChange(NeedsReattachStyleChange);
-        if (node->isContainerNode())
-            node->setChildNeedsStyleRecalc();
-        for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
-            root->lazyAttach();
-    }
-}
-
 Node* Node::focusDelegate()
 {
     return this;
@@ -842,13 +831,13 @@
     rareData()->clearNodeLists();
 }
 
-void Node::checkSetPrefix(const AtomicString& prefix, ExceptionState& es)
+void Node::checkSetPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
 {
     // Perform error checking as required by spec for setting Node.prefix. Used by
     // Element::setPrefix() and Attr::setPrefix()
 
     if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
-        es.throwDOMException(InvalidCharacterError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + prefix + "' is not a valid name."));
+        exceptionState.throwDOMException(InvalidCharacterError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + prefix + "' is not a valid name."));
         return;
     }
 
@@ -856,12 +845,12 @@
 
     const AtomicString& nodeNamespaceURI = namespaceURI();
     if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
-        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "No namespace is set, so a namespace prefix may not be set."));
+        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "No namespace is set, so a namespace prefix may not be set."));
         return;
     }
 
     if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
-        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'."));
+        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'."));
         return;
     }
     // Attribute-specific checks are in Attr::setPrefix().
@@ -931,6 +920,43 @@
     return false;
 }
 
+Node* Node::commonAncestorOverShadowBoundary(const Node& other)
+{
+    if (this == other)
+        return this;
+    if (document() != other.document())
+        return 0;
+    int thisDepth = 0;
+    for (Node* node = this; node; node = node->parentOrShadowHostNode()) {
+        if (node == &other)
+            return node;
+        thisDepth++;
+    }
+    int otherDepth = 0;
+    for (const Node* node = &other; node; node = node->parentOrShadowHostNode()) {
+        if (node == this)
+            return this;
+        otherDepth++;
+    }
+    Node* thisIterator = this;
+    const Node* otherIterator = &other;
+    if (thisDepth > otherDepth) {
+        for (int i = thisDepth; i > otherDepth; --i)
+            thisIterator = thisIterator->parentOrShadowHostNode();
+    } else if (otherDepth > thisDepth) {
+        for (int i = otherDepth; i > thisDepth; --i)
+            otherIterator = otherIterator->parentOrShadowHostNode();
+    }
+    while (thisIterator) {
+        if (thisIterator == otherIterator)
+            return thisIterator;
+        thisIterator = thisIterator->parentOrShadowHostNode();
+        otherIterator = otherIterator->parentOrShadowHostNode();
+    }
+    ASSERT(!otherIterator);
+    return 0;
+}
+
 void Node::reattach(const AttachContext& context)
 {
     AttachContext reattachContext(context);
@@ -948,7 +974,6 @@
     ASSERT(needsAttach());
     ASSERT(!renderer() || (renderer()->style() && (renderer()->parent() || renderer()->isRenderView())));
 
-    setAttached();
     clearNeedsStyleRecalc();
 
     if (Document* doc = documentInternal()) {
@@ -990,13 +1015,31 @@
         }
     }
 
-    clearFlag(IsAttachedFlag);
+    setStyleChange(NeedsReattachStyleChange);
+    setChildNeedsStyleRecalc();
 
 #ifndef NDEBUG
     detachingNode = 0;
 #endif
 }
 
+void Node::reattachWhitespaceSiblings(Text* start)
+{
+    for (Node* sibling = start; sibling; sibling = sibling->nextSibling()) {
+        if (sibling->isTextNode() && toText(sibling)->containsOnlyWhitespace()) {
+            bool hadRenderer = sibling->hasRenderer();
+            sibling->reattach();
+            // If the reattach didn't toggle the visibility of the whitespace we don't
+            // need to continue reattaching siblings since they won't toggle visibility
+            // either.
+            if (hadRenderer == sibling->hasRenderer())
+                return;
+        } else if (sibling->renderer()) {
+            return;
+        }
+    }
+}
+
 // FIXME: This code is used by editing.  Seems like it could move over there and not pollute Node.
 Node *Node::previousNodeConsideringAtomicNodes() const
 {
@@ -1140,6 +1183,13 @@
     return toElement(parent);
 }
 
+ContainerNode* Node::parentOrShadowHostOrTemplateHostNode() const
+{
+    if (isDocumentFragment() && toDocumentFragment(this)->isTemplateContent())
+        return static_cast<const TemplateContentDocumentFragment*>(this)->host();
+    return parentOrShadowHostNode();
+}
+
 bool Node::isBlockFlowElement() const
 {
     return isElementNode() && renderer() && renderer()->isRenderBlockFlow();
@@ -1233,27 +1283,27 @@
     return ensureRareData().ensureNodeLists().addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
 }
 
-PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionState& es)
+PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionState& exceptionState)
 {
     if (selectors.isEmpty()) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("querySelector", "Node", "The provided selector is empty."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("querySelector", "Node", "The provided selector is empty."));
         return 0;
     }
 
-    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
     if (!selectorQuery)
         return 0;
     return selectorQuery->queryFirst(*this);
 }
 
-PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionState& es)
+PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionState& exceptionState)
 {
     if (selectors.isEmpty()) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("querySelectorAll", "Node", "The provided selector is empty."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("querySelectorAll", "Node", "The provided selector is empty."));
         return 0;
     }
 
-    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
     if (!selectorQuery)
         return 0;
     return selectorQuery->queryAll(*this);
@@ -1544,7 +1594,7 @@
     return isNullString ? String() : content.toString();
 }
 
-void Node::setTextContent(const String& text, ExceptionState& es)
+void Node::setTextContent(const String& text, ExceptionState& exceptionState)
 {
     switch (nodeType()) {
         case TEXT_NODE:
@@ -1561,7 +1611,7 @@
             ChildListMutationScope mutation(*this);
             container->removeChildren();
             if (!text.isEmpty())
-                container->appendChild(document().createTextNode(text), es);
+                container->appendChild(document().createTextNode(text), exceptionState);
             return;
         }
         case DOCUMENT_NODE:
@@ -1861,7 +1911,7 @@
 
 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
 {
-    for (const Node* node = rootNode; node; node = NodeTraversal::next(node)) {
+    for (const Node* node = rootNode; node; node = NodeTraversal::next(*node)) {
         if (node == markedNode1)
             fprintf(stderr, "%s", markedLabel1);
         if (node == markedNode2)
@@ -2305,9 +2355,9 @@
     return EventDispatcher::dispatchEvent(this, TouchEventDispatchMediator::create(event));
 }
 
-void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
+void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions)
 {
-    EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions, visualOptions);
+    EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions);
 }
 
 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
@@ -2550,7 +2600,7 @@
     document().userActionElements().setFocused(this, flag);
 }
 
-void Node::setActive(bool flag, bool)
+void Node::setActive(bool flag)
 {
     document().userActionElements().setActive(this, flag);
 }
@@ -2593,22 +2643,18 @@
         ASSERT_NOT_REACHED(); // Everything starts in this state
         return;
 
-    case WaitingForParser:
+    case WaitingForUpgrade:
         ASSERT(NotCustomElement == oldState);
         break;
 
-    case WaitingForUpgrade:
-        ASSERT(NotCustomElement == oldState || WaitingForParser == oldState);
-        break;
-
     case Upgraded:
-        ASSERT(WaitingForParser == oldState || WaitingForUpgrade == oldState);
+        ASSERT(WaitingForUpgrade == oldState);
         break;
     }
 
     ASSERT(isHTMLElement() || isSVGElement());
-    setFlag(newState & 1, CustomElementWaitingForParserOrIsUpgraded);
-    setFlag(newState & 2, CustomElementWaitingForUpgradeOrIsUpgraded);
+    setFlag(CustomElement);
+    setFlag(newState == Upgraded, CustomElementUpgraded);
 
     if (oldState == NotCustomElement || newState == Upgraded)
         setNeedsStyleRecalc(); // :unresolved has changed
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index fe25b60..a139faf 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -36,7 +36,7 @@
 #include "core/inspector/InspectorCounters.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "platform/geometry/LayoutRect.h"
-#include "weborigin/KURLHash.h"
+#include "platform/weborigin/KURLHash.h"
 #include "wtf/Forward.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/text/AtomicString.h"
@@ -63,8 +63,8 @@
 class IntRect;
 class KeyboardEvent;
 class NSResolver;
-class NamedNodeMap;
 class NameNodeList;
+class NamedNodeMap;
 class NodeList;
 class NodeListsNodeData;
 class NodeRareData;
@@ -82,6 +82,7 @@
 class RenderStyle;
 class ShadowRoot;
 class TagNodeList;
+class Text;
 class TouchEvent;
 
 const int nodeStyleChangeShift = 14;
@@ -231,19 +232,23 @@
     bool isAfterPseudoElement() const { return pseudoId() == AFTER; }
     PseudoId pseudoId() const { return (isElementNode() && hasCustomStyleCallbacks()) ? customPseudoId() : NOPSEUDO; }
 
+    bool isCustomElement() const { return getFlag(CustomElement); }
     enum CustomElementState {
-        NotCustomElement,
-        WaitingForParser,
-        WaitingForUpgrade,
-        Upgraded
+        NotCustomElement  = 0,
+        WaitingForUpgrade = 1 << 0,
+        Upgraded          = 1 << 1
     };
-    bool isCustomElement() const { return customElementState() != NotCustomElement; }
-    CustomElementState customElementState() const { return CustomElementState((getFlag(CustomElementWaitingForParserOrIsUpgraded) ? 1 : 0) | (getFlag(CustomElementWaitingForUpgradeOrIsUpgraded) ? 2 : 0)); }
+    CustomElementState customElementState() const
+    {
+        return isCustomElement()
+            ? (getFlag(CustomElementUpgraded) ? Upgraded : WaitingForUpgrade)
+            : NotCustomElement;
+    }
     void setCustomElementState(CustomElementState newState);
 
     virtual bool isMediaControlElement() const { return false; }
     virtual bool isMediaControls() const { return false; }
-    virtual bool isWebVTTElement() const { return false; }
+    virtual bool isVTTElement() const { return false; }
     virtual bool isAttributeNode() const { return false; }
     virtual bool isCharacterDataNode() const { return false; }
     virtual bool isFrameOwnerElement() const { return false; }
@@ -254,7 +259,7 @@
     // if this element can participate in style sharing.
     //
     // FIXME: The only things that ever go through StyleResolver that aren't StyledElements are
-    // PseudoElements and WebVTTElements. It's possible we can just eliminate all the checks
+    // PseudoElements and VTTElements. It's possible we can just eliminate all the checks
     // since those elements will never have class names, inline style, or other things that
     // this apparently guards against.
     bool isStyledElement() const { return isHTMLElement() || isSVGElement(); }
@@ -290,6 +295,9 @@
     void setParentOrShadowHostNode(ContainerNode*);
     Node* highestAncestor() const;
 
+    // Knows about all kinds of hosts.
+    ContainerNode* parentOrShadowHostOrTemplateHostNode() const;
+
     // Use when it's guaranteed to that shadowHost is 0.
     ContainerNode* parentNodeGuaranteedHostFree() const;
     // Returns the parent node, but 0 if the parent node is a ShadowRoot.
@@ -360,11 +368,7 @@
     bool hovered() const { return isUserActionElement() && isUserActionElementHovered(); }
     bool focused() const { return isUserActionElement() && isUserActionElementFocused(); }
 
-    // FIXME: Don't let InsertionPoints attach out of order and remove
-    // childAttachedAllowedWhenAttachingChildren and child->needsAttach() checks.
-    bool needsAttach() const { return !getFlag(IsAttachedFlag) || styleChangeType() == NeedsReattachStyleChange; }
-    bool confusingAndOftenMisusedAttached() const { return getFlag(IsAttachedFlag); }
-    void setAttached() { setFlag(IsAttachedFlag); }
+    bool needsAttach() const { return styleChangeType() == NeedsReattachStyleChange; }
     bool needsStyleRecalc() const { return styleChangeType() != NoStyleChange; }
     StyleChangeType styleChangeType() const { return static_cast<StyleChangeType>(m_nodeFlags & StyleChangeMask); }
     bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
@@ -405,10 +409,8 @@
     bool isV8CollectableDuringMinorGC() const { return getFlag(V8CollectableDuringMinorGCFlag); }
     void setV8CollectableDuringMinorGC(bool flag) { setFlag(flag, V8CollectableDuringMinorGCFlag); }
 
-    void lazyAttach();
-
     virtual void setFocus(bool flag);
-    virtual void setActive(bool flag = true, bool pause = false);
+    virtual void setActive(bool flag = true);
     virtual void setHovered(bool flag = true);
 
     virtual short tabIndex() const;
@@ -501,6 +503,7 @@
     bool contains(const Node*) const;
     bool containsIncludingShadowDOM(const Node*) const;
     bool containsIncludingHostElements(const Node&) const;
+    Node* commonAncestorOverShadowBoundary(const Node&);
 
     // FIXME: Remove this when crbug.com/265716 cleans up contains semantics.
     bool bindingsContains(const Node* node) const { return containsIncludingShadowDOM(node); }
@@ -530,6 +533,7 @@
         else
             m_data.m_renderer = renderer;
     }
+    bool hasRenderer() const { return renderer(); }
 
     // Use these two methods with caution.
     RenderBox* renderBox() const;
@@ -663,7 +667,7 @@
     bool dispatchGestureEvent(const PlatformGestureEvent&);
     bool dispatchTouchEvent(PassRefPtr<TouchEvent>);
 
-    void dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions = SendNoEvents, SimulatedClickVisualOptions = ShowPressedLook);
+    void dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions = SendNoEvents);
 
     virtual bool dispatchBeforeLoadEvent(const String& sourceURL);
     virtual void dispatchChangeEvent();
@@ -707,7 +711,8 @@
         IsElementFlag = 1 << 2,
         IsHTMLFlag = 1 << 3,
         IsSVGFlag = 1 << 4,
-        IsAttachedFlag = 1 << 5,
+
+        ChildNeedsDistributionRecalc = 1 << 5,
         ChildNeedsStyleRecalcFlag = 1 << 6,
         InDocumentFlag = 1 << 7,
         IsLinkFlag = 1 << 8,
@@ -737,16 +742,15 @@
 
         NotifyRendererWithIdenticalStyles = 1 << 26,
 
-        CustomElementWaitingForParserOrIsUpgraded = 1 << 27,
-        CustomElementWaitingForUpgradeOrIsUpgraded = 1 << 28,
+        CustomElement = 1 << 27,
+        CustomElementUpgraded = 1 << 28,
 
-        ChildNeedsDistributionRecalc = 1 << 29,
-        AlreadySpellCheckedFlag = 1 << 30,
+        AlreadySpellCheckedFlag = 1 << 29,
 
-        DefaultNodeFlags = IsParsingChildrenFinishedFlag
+        DefaultNodeFlags = IsParsingChildrenFinishedFlag | ChildNeedsStyleRecalcFlag | NeedsReattachStyleChange
     };
 
-    // 2 bits remaining
+    // 3 bits remaining.
 
     bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
     void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
@@ -759,7 +763,6 @@
         CreateText = DefaultNodeFlags | IsTextFlag,
         CreateContainer = DefaultNodeFlags | IsContainerFlag,
         CreateElement = CreateContainer | IsElementFlag,
-        CreatePseudoElement =  CreateElement | InDocumentFlag,
         CreateShadowRoot = CreateContainer | IsDocumentFragmentFlag | IsInShadowTreeFlag,
         CreateDocumentFragment = CreateContainer | IsDocumentFragmentFlag,
         CreateHTMLElement = CreateElement | IsHTMLFlag,
@@ -791,6 +794,8 @@
 
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const { }
 
+    static void reattachWhitespaceSiblings(Text* start);
+
     void willBeDeletedFromDocument();
 
     bool hasRareData() const { return getFlag(HasRareDataFlag); }
@@ -806,6 +811,8 @@
     Document* documentInternal() const { return treeScope().documentScope(); }
     void setTreeScope(TreeScope* scope) { m_treeScope = scope; }
 
+    void markAncestorsWithChildNeedsStyleRecalc();
+
 private:
     friend class TreeShared<Node>;
 
@@ -829,9 +836,6 @@
 
     void setStyleChange(StyleChangeType);
 
-    // Used to share code between lazyAttach and setNeedsStyleRecalc.
-    void markAncestorsWithChildNeedsStyleRecalc();
-
     virtual RenderStyle* nonRendererStyle() const { return 0; }
 
     virtual RenderStyle* virtualComputedStyle(PseudoId = NOPSEUDO);
@@ -906,7 +910,7 @@
     context.performingReattach = true;
 
     detach(context);
-    lazyAttach();
+    markAncestorsWithChildNeedsStyleRecalc();
 }
 
 inline bool shouldRecalcStyle(StyleRecalcChange change, const Node* node)
@@ -914,6 +918,16 @@
     return change >= Inherit || node->childNeedsStyleRecalc() || node->needsStyleRecalc();
 }
 
+inline bool isTreeScopeRoot(const Node* node)
+{
+    return !node || node->isDocumentNode() || node->isShadowRoot();
+}
+
+inline bool isTreeScopeRoot(const Node& node)
+{
+    return node.isDocumentNode() || node.isShadowRoot();
+}
+
 // Allow equality comparisons of Nodes by reference or pointer, interchangeably.
 inline bool operator==(const Node& a, const Node& b) { return &a == &b; }
 inline bool operator==(const Node& a, const Node* b) { return &a == b; }
diff --git a/Source/core/dom/Node.idl b/Source/core/dom/Node.idl
index 3e3ec70..b066000 100644
--- a/Source/core/dom/Node.idl
+++ b/Source/core/dom/Node.idl
@@ -19,7 +19,7 @@
  */
 
 [
-    CustomToV8,
+    CustomWrap,
     DependentLifetime
 ] interface Node : EventTarget {
     // NodeType
@@ -50,10 +50,10 @@
     [PerWorldBindings] readonly attribute Node             nextSibling;
     [PerWorldBindings] readonly attribute Document         ownerDocument;
 
-    [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Node insertBefore(Node newChild, Node refChild);
-    [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Node replaceChild(Node newChild, Node oldChild);
+    [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node insertBefore(Node newChild, Node refChild);
+    [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node replaceChild(Node newChild, Node oldChild);
     [Custom, CustomElementCallbacks, PerWorldBindings, RaisesException] Node removeChild(Node oldChild);
-    [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] Node appendChild(Node newChild);
+    [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node appendChild(Node newChild);
 
     boolean            hasChildNodes();
     [CustomElementCallbacks, PerWorldBindings]
@@ -65,14 +65,14 @@
                                                     [TreatNullAs=NullString,Default=Undefined] optional DOMString version); // Removed in DOM4.
 
     [TreatReturnedNullStringAs=Null, PerWorldBindings, MeasureAs=NodeNamespaceURI] readonly attribute DOMString namespaceURI; // Moved to Element and Attr in DOM4.
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException, MeasureAs=NodePrefix] attribute DOMString prefix; // Moved to Element and Attr in DOM4.
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter, MeasureAs=NodePrefix] attribute DOMString prefix; // Moved to Element and Attr in DOM4.
     [TreatReturnedNullStringAs=Null, PerWorldBindings, MeasureAs=NodeLocalName] readonly attribute DOMString localName; // Moved to Element and Attr in DOM4.
 
     // Introduced in DOM Level 3:
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString       baseURI;
 
              // FIXME: the spec says this can also raise on retrieval.
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException, CustomElementCallbacks] attribute DOMString       textContent;
+             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter, CustomElementCallbacks] attribute DOMString       textContent;
 
     [MeasureAs=NodeIsSameNode] boolean isSameNode([Default=Undefined] optional Node other); // Removed in DOM4.
     boolean            isEqualNode([Default=Undefined] optional Node other);
diff --git a/Source/core/dom/NodeIterator.cpp b/Source/core/dom/NodeIterator.cpp
index 0770aa1..2643139 100644
--- a/Source/core/dom/NodeIterator.cpp
+++ b/Source/core/dom/NodeIterator.cpp
@@ -58,7 +58,7 @@
         isPointerBeforeNode = false;
         return true;
     }
-    node = NodeTraversal::next(node.get(), root);
+    node = NodeTraversal::next(*node, root);
     return node;
 }
 
@@ -70,7 +70,7 @@
         isPointerBeforeNode = true;
         return true;
     }
-    node = NodeTraversal::previous(node.get(), root);
+    node = NodeTraversal::previous(*node, root);
     return node;
 }
 
@@ -88,10 +88,10 @@
     root()->document().detachNodeIterator(this);
 }
 
-PassRefPtr<Node> NodeIterator::nextNode(ScriptState* state, ExceptionState& es)
+PassRefPtr<Node> NodeIterator::nextNode(ScriptState* state, ExceptionState& exceptionState)
 {
     if (m_detached) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("nextNode", "NodeIterator", "The iterator is detached."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("nextNode", "NodeIterator", "The iterator is detached."));
         return 0;
     }
 
@@ -117,10 +117,10 @@
     return result.release();
 }
 
-PassRefPtr<Node> NodeIterator::previousNode(ScriptState* state, ExceptionState& es)
+PassRefPtr<Node> NodeIterator::previousNode(ScriptState* state, ExceptionState& exceptionState)
 {
     if (m_detached) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("previousNode", "NodeIterator", "The iterator is detached."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("previousNode", "NodeIterator", "The iterator is detached."));
         return 0;
     }
 
@@ -174,22 +174,22 @@
         return;
 
     if (referenceNode.isPointerBeforeNode) {
-        Node* node = NodeTraversal::next(&removedNode, root());
+        Node* node = NodeTraversal::next(removedNode, root());
         if (node) {
             // Move out from under the node being removed if the new reference
             // node is a descendant of the node being removed.
             while (node && node->isDescendantOf(&removedNode))
-                node = NodeTraversal::next(node, root());
+                node = NodeTraversal::next(*node, root());
             if (node)
                 referenceNode.node = node;
         } else {
-            node = NodeTraversal::previous(&removedNode, root());
+            node = NodeTraversal::previous(removedNode, root());
             if (node) {
                 // Move out from under the node being removed if the reference node is
                 // a descendant of the node being removed.
                 if (willRemoveReferenceNodeAncestor) {
                     while (node && node->isDescendantOf(&removedNode))
-                        node = NodeTraversal::previous(node, root());
+                        node = NodeTraversal::previous(*node, root());
                 }
                 if (node) {
                     // Removing last node.
@@ -201,24 +201,24 @@
             }
         }
     } else {
-        Node* node = NodeTraversal::previous(&removedNode, root());
+        Node* node = NodeTraversal::previous(removedNode, root());
         if (node) {
             // Move out from under the node being removed if the reference node is
             // a descendant of the node being removed.
             if (willRemoveReferenceNodeAncestor) {
                 while (node && node->isDescendantOf(&removedNode))
-                    node = NodeTraversal::previous(node, root());
+                    node = NodeTraversal::previous(*node, root());
             }
             if (node)
                 referenceNode.node = node;
         } else {
             // FIXME: This branch doesn't appear to have any LayoutTests.
-            node = NodeTraversal::next(&removedNode, root());
+            node = NodeTraversal::next(removedNode, root());
             // Move out from under the node being removed if the reference node is
             // a descendant of the node being removed.
             if (willRemoveReferenceNodeAncestor) {
                 while (node && node->isDescendantOf(&removedNode))
-                    node = NodeTraversal::previous(node, root());
+                    node = NodeTraversal::previous(*node, root());
             }
             if (node)
                 referenceNode.node = node;
diff --git a/Source/core/dom/NodeList.idl b/Source/core/dom/NodeList.idl
index 794ba11..2e48078 100644
--- a/Source/core/dom/NodeList.idl
+++ b/Source/core/dom/NodeList.idl
@@ -19,7 +19,7 @@
  */
 
 [
-    CustomIsReachable,
+    CustomVisitDOMWrapper,
     DependentLifetime
 ] interface NodeList {
 
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index 6c5d602..f94665c 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -163,7 +163,7 @@
     Element* element = toElement(m_node);
     bool elementInsideRegionNeedsRenderer = false;
     RenderObject* parentRenderer = this->parentRenderer();
-    if ((parentRenderer && !parentRenderer->canHaveChildren() && parentRenderer->isRenderRegion())
+    if ((parentRenderer && !parentRenderer->canHaveChildren() && parentRenderer->isRenderNamedFlowFragmentContainer())
         || (!parentRenderer && element->parentElement() && element->parentElement()->isInsideRegion())) {
 
         if (!m_style)
@@ -206,10 +206,10 @@
     if (!shouldCreateRenderer() && !elementInsideRegionNeedsRenderer())
         return;
 
-    // If m_style is already available, this scope shouldn't attempt to trigger animation updates.
-    CSSAnimationUpdateScope cssAnimationUpdateScope(m_style ? 0 : element);
-    if (!m_style)
+    if (!m_style) {
+        CSSAnimationUpdateScope cssAnimationUpdateScope(element);
         m_style = element->styleForRenderer();
+    }
     ASSERT(m_style);
 
     moveToFlowThreadIfNeeded();
diff --git a/Source/core/dom/NodeRenderingTraversal.cpp b/Source/core/dom/NodeRenderingTraversal.cpp
index d0648bd..b30c66a 100644
--- a/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/Source/core/dom/NodeRenderingTraversal.cpp
@@ -49,10 +49,12 @@
 
 ContainerNode* parent(const Node* node, ParentDetails* details)
 {
+    // FIXME: We should probably ASSERT(!node->document().childNeedsDistributionRecalc()) here, but
+    // a bunch of things use NodeRenderingTraversal::parent in places where that looks like it could
+    // be false.
     ASSERT(node);
     if (isActiveInsertionPoint(*node))
         return 0;
-    // FIXME: Once everything lazy attaches we should assert that we don't need a distribution recalc here.
     ComposedTreeWalker walker(node, ComposedTreeWalker::CanStartFromShadowBoundary);
     return toContainerNode(walker.traverseParent(walker.get(), details));
 }
diff --git a/Source/core/dom/NodeTraversal.cpp b/Source/core/dom/NodeTraversal.cpp
index 11a9661..631a8b9 100644
--- a/Source/core/dom/NodeTraversal.cpp
+++ b/Source/core/dom/NodeTraversal.cpp
@@ -30,142 +30,142 @@
 namespace WebCore {
 namespace NodeTraversal {
 
-Node* previousIncludingPseudo(const Node* current, const Node* stayWithin)
+Node* previousIncludingPseudo(const Node& current, const Node* stayWithin)
 {
     if (current == stayWithin)
         return 0;
-    if (Node* previous = current->pseudoAwarePreviousSibling()) {
+    if (Node* previous = current.pseudoAwarePreviousSibling()) {
         while (previous->pseudoAwareLastChild())
             previous = previous->pseudoAwareLastChild();
         return previous;
     }
-    return current->parentNode();
+    return current.parentNode();
 }
 
-Node* nextIncludingPseudo(const Node* current, const Node* stayWithin)
+Node* nextIncludingPseudo(const Node& current, const Node* stayWithin)
 {
-    if (Node* next = current->pseudoAwareFirstChild())
+    if (Node* next = current.pseudoAwareFirstChild())
         return next;
     if (current == stayWithin)
         return 0;
-    if (Node* next = current->pseudoAwareNextSibling())
+    if (Node* next = current.pseudoAwareNextSibling())
         return next;
-    for (current = current->parentNode(); current; current = current->parentNode()) {
-        if (current == stayWithin)
+    for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+        if (parent == stayWithin)
             return 0;
-        if (Node* next = current->pseudoAwareNextSibling())
+        if (Node* next = parent->pseudoAwareNextSibling())
             return next;
     }
     return 0;
 }
 
-Node* nextIncludingPseudoSkippingChildren(const Node* current, const Node* stayWithin)
+Node* nextIncludingPseudoSkippingChildren(const Node& current, const Node* stayWithin)
 {
     if (current == stayWithin)
         return 0;
-    if (Node* next = current->pseudoAwareNextSibling())
+    if (Node* next = current.pseudoAwareNextSibling())
         return next;
-    for (current = current->parentNode(); current; current = current->parentNode()) {
-        if (current == stayWithin)
+    for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+        if (parent == stayWithin)
             return 0;
-        if (Node* next = current->pseudoAwareNextSibling())
+        if (Node* next = parent->pseudoAwareNextSibling())
             return next;
     }
     return 0;
 }
 
-Node* nextAncestorSibling(const Node* current)
+Node* nextAncestorSibling(const Node& current)
 {
-    ASSERT(!current->nextSibling());
-    for (current = current->parentNode(); current; current = current->parentNode()) {
-        if (current->nextSibling())
-            return current->nextSibling();
+    ASSERT(!current.nextSibling());
+    for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+        if (parent->nextSibling())
+            return parent->nextSibling();
     }
     return 0;
 }
 
-Node* nextAncestorSibling(const Node* current, const Node* stayWithin)
+Node* nextAncestorSibling(const Node& current, const Node* stayWithin)
 {
-    ASSERT(!current->nextSibling());
+    ASSERT(!current.nextSibling());
     ASSERT(current != stayWithin);
-    for (current = current->parentNode(); current; current = current->parentNode()) {
-        if (current == stayWithin)
+    for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+        if (parent == stayWithin)
             return 0;
-        if (current->nextSibling())
-            return current->nextSibling();
+        if (parent->nextSibling())
+            return parent->nextSibling();
     }
     return 0;
 }
 
-Node* previous(const Node* current, const Node* stayWithin)
+Node* previous(const Node& current, const Node* stayWithin)
 {
     if (current == stayWithin)
         return 0;
-    if (current->previousSibling()) {
-        Node* previous = current->previousSibling();
+    if (current.previousSibling()) {
+        Node* previous = current.previousSibling();
         while (previous->lastChild())
             previous = previous->lastChild();
         return previous;
     }
-    return current->parentNode();
+    return current.parentNode();
 }
 
-Node* previousSkippingChildren(const Node* current, const Node* stayWithin)
+Node* previousSkippingChildren(const Node& current, const Node* stayWithin)
 {
     if (current == stayWithin)
         return 0;
-    if (current->previousSibling())
-        return current->previousSibling();
-    for (current = current->parentNode(); current; current = current->parentNode()) {
-        if (current == stayWithin)
+    if (current.previousSibling())
+        return current.previousSibling();
+    for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+        if (parent == stayWithin)
             return 0;
-        if (current->previousSibling())
-            return current->previousSibling();
+        if (parent->previousSibling())
+            return parent->previousSibling();
     }
     return 0;
 }
 
-Node* nextPostOrder(const Node* current, const Node* stayWithin)
+Node* nextPostOrder(const Node& current, const Node* stayWithin)
 {
     if (current == stayWithin)
         return 0;
-    if (!current->nextSibling())
-        return current->parentNode();
-    Node* next = current->nextSibling();
+    if (!current.nextSibling())
+        return current.parentNode();
+    Node* next = current.nextSibling();
     while (next->firstChild())
         next = next->firstChild();
     return next;
 }
 
-static Node* previousAncestorSiblingPostOrder(const Node* current, const Node* stayWithin)
+static Node* previousAncestorSiblingPostOrder(const Node& current, const Node* stayWithin)
 {
-    ASSERT(!current->previousSibling());
-    for (current = current->parentNode(); current; current = current->parentNode()) {
-        if (current == stayWithin)
+    ASSERT(!current.previousSibling());
+    for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+        if (parent == stayWithin)
             return 0;
-        if (current->previousSibling())
-            return current->previousSibling();
+        if (parent->previousSibling())
+            return parent->previousSibling();
     }
     return 0;
 }
 
-Node* previousPostOrder(const Node* current, const Node* stayWithin)
+Node* previousPostOrder(const Node& current, const Node* stayWithin)
 {
-    if (current->lastChild())
-        return current->lastChild();
+    if (current.lastChild())
+        return current.lastChild();
     if (current == stayWithin)
         return 0;
-    if (current->previousSibling())
-        return current->previousSibling();
+    if (current.previousSibling())
+        return current.previousSibling();
     return previousAncestorSiblingPostOrder(current, stayWithin);
 }
 
-Node* previousSkippingChildrenPostOrder(const Node* current, const Node* stayWithin)
+Node* previousSkippingChildrenPostOrder(const Node& current, const Node* stayWithin)
 {
     if (current == stayWithin)
         return 0;
-    if (current->previousSibling())
-        return current->previousSibling();
+    if (current.previousSibling())
+        return current.previousSibling();
     return previousAncestorSiblingPostOrder(current, stayWithin);
 }
 
diff --git a/Source/core/dom/NodeTraversal.h b/Source/core/dom/NodeTraversal.h
index c6966a6..438b0c0 100644
--- a/Source/core/dom/NodeTraversal.h
+++ b/Source/core/dom/NodeTraversal.h
@@ -35,85 +35,85 @@
 // This uses the same order that tags appear in the source file. If the stayWithin
 // argument is non-null, the traversal will stop once the specified node is reached.
 // This can be used to restrict traversal to a particular sub-tree.
-Node* next(const Node*);
-Node* next(const Node*, const Node* stayWithin);
-Node* next(const ContainerNode*);
-Node* next(const ContainerNode*, const Node* stayWithin);
+Node* next(const Node&);
+Node* next(const Node&, const Node* stayWithin);
+Node* next(const ContainerNode&);
+Node* next(const ContainerNode&, const Node* stayWithin);
 
 // Like next, but skips children and starts with the next sibling.
-Node* nextSkippingChildren(const Node*);
-Node* nextSkippingChildren(const Node*, const Node* stayWithin);
-Node* nextSkippingChildren(const ContainerNode*);
-Node* nextSkippingChildren(const ContainerNode*, const Node* stayWithin);
+Node* nextSkippingChildren(const Node&);
+Node* nextSkippingChildren(const Node&, const Node* stayWithin);
+Node* nextSkippingChildren(const ContainerNode&);
+Node* nextSkippingChildren(const ContainerNode&, const Node* stayWithin);
 
 // Does a reverse pre-order traversal to find the node that comes before the current one in document order
-Node* previous(const Node*, const Node* stayWithin = 0);
+Node* previous(const Node&, const Node* stayWithin = 0);
 
 // Like previous, but skips children and starts with the next sibling.
-Node* previousSkippingChildren(const Node*, const Node* stayWithin = 0);
+Node* previousSkippingChildren(const Node&, const Node* stayWithin = 0);
 
 // Like next, but visits parents after their children.
-Node* nextPostOrder(const Node*, const Node* stayWithin = 0);
+Node* nextPostOrder(const Node&, const Node* stayWithin = 0);
 
 // Like previous/previousSkippingChildren, but visits parents before their children.
-Node* previousPostOrder(const Node*, const Node* stayWithin = 0);
-Node* previousSkippingChildrenPostOrder(const Node*, const Node* stayWithin = 0);
+Node* previousPostOrder(const Node&, const Node* stayWithin = 0);
+Node* previousSkippingChildrenPostOrder(const Node&, const Node* stayWithin = 0);
 
 // Pre-order traversal including the pseudo-elements.
-Node* previousIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Node* nextIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Node* nextIncludingPseudoSkippingChildren(const Node*, const Node* stayWithin = 0);
+Node* previousIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Node* nextIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Node* nextIncludingPseudoSkippingChildren(const Node&, const Node* stayWithin = 0);
 
-Node* nextAncestorSibling(const Node*);
-Node* nextAncestorSibling(const Node*, const Node* stayWithin);
+Node* nextAncestorSibling(const Node&);
+Node* nextAncestorSibling(const Node&, const Node* stayWithin);
 
 template <class NodeType>
-inline Node* traverseNextTemplate(NodeType* current)
+inline Node* traverseNextTemplate(NodeType& current)
 {
-    if (current->firstChild())
-        return current->firstChild();
-    if (current->nextSibling())
-        return current->nextSibling();
+    if (current.firstChild())
+        return current.firstChild();
+    if (current.nextSibling())
+        return current.nextSibling();
     return nextAncestorSibling(current);
 }
-inline Node* next(const Node* current) { return traverseNextTemplate(current); }
-inline Node* next(const ContainerNode* current) { return traverseNextTemplate(current); }
+inline Node* next(const Node& current) { return traverseNextTemplate(current); }
+inline Node* next(const ContainerNode& current) { return traverseNextTemplate(current); }
 
 template <class NodeType>
-inline Node* traverseNextTemplate(NodeType* current, const Node* stayWithin)
+inline Node* traverseNextTemplate(NodeType& current, const Node* stayWithin)
 {
-    if (current->firstChild())
-        return current->firstChild();
+    if (current.firstChild())
+        return current.firstChild();
     if (current == stayWithin)
         return 0;
-    if (current->nextSibling())
-        return current->nextSibling();
+    if (current.nextSibling())
+        return current.nextSibling();
     return nextAncestorSibling(current, stayWithin);
 }
-inline Node* next(const Node* current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
-inline Node* next(const ContainerNode* current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
+inline Node* next(const Node& current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
+inline Node* next(const ContainerNode& current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
 
 template <class NodeType>
-inline Node* traverseNextSkippingChildrenTemplate(NodeType* current)
+inline Node* traverseNextSkippingChildrenTemplate(NodeType& current)
 {
-    if (current->nextSibling())
-        return current->nextSibling();
+    if (current.nextSibling())
+        return current.nextSibling();
     return nextAncestorSibling(current);
 }
-inline Node* nextSkippingChildren(const Node* current) { return traverseNextSkippingChildrenTemplate(current); }
-inline Node* nextSkippingChildren(const ContainerNode* current) { return traverseNextSkippingChildrenTemplate(current); }
+inline Node* nextSkippingChildren(const Node& current) { return traverseNextSkippingChildrenTemplate(current); }
+inline Node* nextSkippingChildren(const ContainerNode& current) { return traverseNextSkippingChildrenTemplate(current); }
 
 template <class NodeType>
-inline Node* traverseNextSkippingChildrenTemplate(NodeType* current, const Node* stayWithin)
+inline Node* traverseNextSkippingChildrenTemplate(NodeType& current, const Node* stayWithin)
 {
     if (current == stayWithin)
         return 0;
-    if (current->nextSibling())
-        return current->nextSibling();
+    if (current.nextSibling())
+        return current.nextSibling();
     return nextAncestorSibling(current, stayWithin);
 }
-inline Node* nextSkippingChildren(const Node* current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
-inline Node* nextSkippingChildren(const ContainerNode* current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
+inline Node* nextSkippingChildren(const Node& current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
+inline Node* nextSkippingChildren(const ContainerNode& current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
 
 }
 
diff --git a/Source/core/dom/PresentationAttributeStyle.cpp b/Source/core/dom/PresentationAttributeStyle.cpp
index 8adfd77..e9ced65 100644
--- a/Source/core/dom/PresentationAttributeStyle.cpp
+++ b/Source/core/dom/PresentationAttributeStyle.cpp
@@ -92,7 +92,7 @@
 
 private:
     static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
-    static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
+    static const unsigned minimumPresentationAttributeCacheSizeForCleaning = 100;
     static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
 
     void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
@@ -181,7 +181,7 @@
         unsigned size = element.attributeCount();
         for (unsigned i = 0; i < size; ++i) {
             const Attribute* attribute = element.attributeItem(i);
-            element.collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
+            element.collectStyleForPresentationAttribute(attribute->name(), attribute->value(), toMutableStylePropertySet(style));
         }
     }
 
@@ -192,7 +192,7 @@
     newEntry->key = cacheKey;
     newEntry->value = style;
 
-    static const int presentationAttributeCacheMaximumSize = 4096;
+    static const unsigned presentationAttributeCacheMaximumSize = 4096;
     if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
         // FIXME: Discarding the entire cache when it gets too big is probably bad
         // since it creates a perf "cliff". Perhaps we should use an LRU?
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index f838b25..2cc8386 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -210,9 +210,9 @@
 void ProcessingInstruction::parseStyleSheet(const String& sheet)
 {
     if (m_isCSS)
-        static_cast<CSSStyleSheet*>(m_sheet.get())->contents()->parseString(sheet);
+        toCSSStyleSheet(m_sheet.get())->contents()->parseString(sheet);
     else if (m_isXSL)
-        static_cast<XSLStyleSheet*>(m_sheet.get())->parseString(sheet);
+        toXSLStyleSheet(m_sheet.get())->parseString(sheet);
 
     if (m_resource)
         m_resource->removeClient(this);
@@ -221,9 +221,9 @@
     m_loading = false;
 
     if (m_isCSS)
-        static_cast<CSSStyleSheet*>(m_sheet.get())->contents()->checkLoaded();
+        toCSSStyleSheet(m_sheet.get())->contents()->checkLoaded();
     else if (m_isXSL)
-        static_cast<XSLStyleSheet*>(m_sheet.get())->checkLoaded();
+        toXSLStyleSheet(m_sheet.get())->checkLoaded();
 }
 
 void ProcessingInstruction::setCSSStyleSheet(PassRefPtr<CSSStyleSheet> sheet)
diff --git a/Source/core/dom/PseudoElement.cpp b/Source/core/dom/PseudoElement.cpp
index 3900d2f..9512d82 100644
--- a/Source/core/dom/PseudoElement.cpp
+++ b/Source/core/dom/PseudoElement.cpp
@@ -55,7 +55,7 @@
 }
 
 PseudoElement::PseudoElement(Element* parent, PseudoId pseudoId)
-    : Element(pseudoElementTagName(), &parent->document(), CreatePseudoElement)
+    : Element(pseudoElementTagName(), &parent->document(), CreateElement)
     , m_pseudoId(pseudoId)
 {
     ASSERT(pseudoId != NOPSEUDO);
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index 5b2d161..e8355a0 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -128,50 +128,50 @@
     m_ownerDocument->attachRange(this);
 }
 
-Node* Range::startContainer(ExceptionState& es) const
+Node* Range::startContainer(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("startContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("startContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     return m_start.container();
 }
 
-int Range::startOffset(ExceptionState& es) const
+int Range::startOffset(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("startOffset", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("startOffset", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     return m_start.offset();
 }
 
-Node* Range::endContainer(ExceptionState& es) const
+Node* Range::endContainer(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("endContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("endContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     return m_end.container();
 }
 
-int Range::endOffset(ExceptionState& es) const
+int Range::endOffset(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("endOffset", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("endOffset", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     return m_end.offset();
 }
 
-Node* Range::commonAncestorContainer(ExceptionState& es) const
+Node* Range::commonAncestorContainer(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("commonAncestorContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("commonAncestorContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
@@ -189,10 +189,10 @@
     return 0;
 }
 
-bool Range::collapsed(ExceptionState& es) const
+bool Range::collapsed(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapsed", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapsed", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
@@ -211,15 +211,15 @@
     return startRootContainer != endRootContainer || (Range::compareBoundaryPoints(start, end, ASSERT_NO_EXCEPTION) > 0);
 }
 
-void Range::setStart(PassRefPtr<Node> refNode, int offset, ExceptionState& es)
+void Range::setStart(PassRefPtr<Node> refNode, int offset, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setStart", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setStart", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
 
@@ -229,25 +229,25 @@
         didMoveDocument = true;
     }
 
-    Node* childNode = checkNodeWOffset(refNode.get(), offset, es);
-    if (es.hadException())
+    Node* childNode = checkNodeWOffset(refNode.get(), offset, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     m_start.set(refNode, offset, childNode);
 
     if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end))
-        collapse(true, es);
+        collapse(true, exceptionState);
 }
 
-void Range::setEnd(PassRefPtr<Node> refNode, int offset, ExceptionState& es)
+void Range::setEnd(PassRefPtr<Node> refNode, int offset, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setEnd", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setEnd", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
 
@@ -257,32 +257,32 @@
         didMoveDocument = true;
     }
 
-    Node* childNode = checkNodeWOffset(refNode.get(), offset, es);
-    if (es.hadException())
+    Node* childNode = checkNodeWOffset(refNode.get(), offset, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     m_end.set(refNode, offset, childNode);
 
     if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end))
-        collapse(false, es);
+        collapse(false, exceptionState);
 }
 
-void Range::setStart(const Position& start, ExceptionState& es)
+void Range::setStart(const Position& start, ExceptionState& exceptionState)
 {
     Position parentAnchored = start.parentAnchoredEquivalent();
-    setStart(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), es);
+    setStart(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), exceptionState);
 }
 
-void Range::setEnd(const Position& end, ExceptionState& es)
+void Range::setEnd(const Position& end, ExceptionState& exceptionState)
 {
     Position parentAnchored = end.parentAnchoredEquivalent();
-    setEnd(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), es);
+    setEnd(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), exceptionState);
 }
 
-void Range::collapse(bool toStart, ExceptionState& es)
+void Range::collapse(bool toStart, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapse", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapse", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
@@ -292,15 +292,15 @@
         m_start = m_end;
 }
 
-bool Range::isPointInRange(Node* refNode, int offset, ExceptionState& es)
+bool Range::isPointInRange(Node* refNode, int offset, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("isPointInRange", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("isPointInRange", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return false;
     }
 
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return false;
     }
 
@@ -308,67 +308,67 @@
         return false;
     }
 
-    checkNodeWOffset(refNode, offset, es);
-    if (es.hadException())
+    checkNodeWOffset(refNode, offset, exceptionState);
+    if (exceptionState.hadException())
         return false;
 
-    return compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), es) >= 0 && !es.hadException()
-        && compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), es) <= 0 && !es.hadException();
+    return compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), exceptionState) >= 0 && !exceptionState.hadException()
+        && compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), exceptionState) <= 0 && !exceptionState.hadException();
 }
 
-short Range::comparePoint(Node* refNode, int offset, ExceptionState& es) const
+short Range::comparePoint(Node* refNode, int offset, ExceptionState& exceptionState) const
 {
     // http://developer.mozilla.org/en/docs/DOM:range.comparePoint
     // This method returns -1, 0 or 1 depending on if the point described by the
     // refNode node and an offset within the node is before, same as, or after the range respectively.
 
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("comparePoint", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("comparePoint", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return 0;
     }
 
     if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
-        es.throwUninformativeAndGenericDOMException(WrongDocumentError);
+        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
         return 0;
     }
 
-    checkNodeWOffset(refNode, offset, es);
-    if (es.hadException())
+    checkNodeWOffset(refNode, offset, exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     // compare to start, and point comes before
-    if (compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), es) < 0)
+    if (compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), exceptionState) < 0)
         return -1;
 
-    if (es.hadException())
+    if (exceptionState.hadException())
         return 0;
 
     // compare to end, and point comes after
-    if (compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), es) > 0 && !es.hadException())
+    if (compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), exceptionState) > 0 && !exceptionState.hadException())
         return 1;
 
     // point is in the middle of this range, or on the boundary points
     return 0;
 }
 
-Range::CompareResults Range::compareNode(Node* refNode, ExceptionState& es) const
+Range::CompareResults Range::compareNode(Node* refNode, ExceptionState& exceptionState) const
 {
     // http://developer.mozilla.org/en/docs/DOM:range.compareNode
     // This method returns 0, 1, 2, or 3 based on if the node is before, after,
     // before and after(surrounds), or inside the range, respectively
 
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return NODE_BEFORE;
     }
 
     if (!m_start.container() && refNode->inActiveDocument()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return NODE_BEFORE;
     }
 
@@ -388,42 +388,42 @@
     if (!parentNode) {
         // if the node is the top document we should return NODE_BEFORE_AND_AFTER
         // but we throw to match firefox behavior
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return NODE_BEFORE;
     }
 
-    if (comparePoint(parentNode, nodeIndex, es) < 0) { // starts before
-        if (comparePoint(parentNode, nodeIndex + 1, es) > 0) // ends after the range
+    if (comparePoint(parentNode, nodeIndex, exceptionState) < 0) { // starts before
+        if (comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) // ends after the range
             return NODE_BEFORE_AND_AFTER;
         return NODE_BEFORE; // ends before or in the range
     }
     // starts at or after the range start
-    if (comparePoint(parentNode, nodeIndex + 1, es) > 0) // ends after the range
+    if (comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) // ends after the range
         return NODE_AFTER;
     return NODE_INSIDE; // ends inside the range
 }
 
-short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, ExceptionState& es) const
+short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("compareBoundaryPoints", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("compareBoundaryPoints", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     if (!sourceRange) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return 0;
     }
 
-    Node* thisCont = commonAncestorContainer(es);
-    if (es.hadException())
+    Node* thisCont = commonAncestorContainer(exceptionState);
+    if (exceptionState.hadException())
         return 0;
-    Node* sourceCont = sourceRange->commonAncestorContainer(es);
-    if (es.hadException())
+    Node* sourceCont = sourceRange->commonAncestorContainer(exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     if (thisCont->document() != sourceCont->document()) {
-        es.throwUninformativeAndGenericDOMException(WrongDocumentError);
+        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
         return 0;
     }
 
@@ -434,26 +434,26 @@
     while (sourceTop->parentNode())
         sourceTop = sourceTop->parentNode();
     if (thisTop != sourceTop) { // in different DocumentFragments
-        es.throwUninformativeAndGenericDOMException(WrongDocumentError);
+        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
         return 0;
     }
 
     switch (how) {
         case START_TO_START:
-            return compareBoundaryPoints(m_start, sourceRange->m_start, es);
+            return compareBoundaryPoints(m_start, sourceRange->m_start, exceptionState);
         case START_TO_END:
-            return compareBoundaryPoints(m_end, sourceRange->m_start, es);
+            return compareBoundaryPoints(m_end, sourceRange->m_start, exceptionState);
         case END_TO_END:
-            return compareBoundaryPoints(m_end, sourceRange->m_end, es);
+            return compareBoundaryPoints(m_end, sourceRange->m_end, exceptionState);
         case END_TO_START:
-            return compareBoundaryPoints(m_start, sourceRange->m_end, es);
+            return compareBoundaryPoints(m_start, sourceRange->m_end, exceptionState);
     }
 
-    es.throwUninformativeAndGenericDOMException(SyntaxError);
+    exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
     return 0;
 }
 
-short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containerB, int offsetB, ExceptionState& es)
+short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containerB, int offsetB, ExceptionState& exceptionState)
 {
     ASSERT(containerA);
     ASSERT(containerB);
@@ -515,7 +515,7 @@
     // ### we need to do a traversal here instead
     Node* commonAncestor = commonAncestorContainer(containerA, containerB);
     if (!commonAncestor) {
-        es.throwUninformativeAndGenericDOMException(WrongDocumentError);
+        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
         return 0;
     }
     Node* childA = containerA;
@@ -546,38 +546,38 @@
     return 0;
 }
 
-short Range::compareBoundaryPoints(const RangeBoundaryPoint& boundaryA, const RangeBoundaryPoint& boundaryB, ExceptionState& es)
+short Range::compareBoundaryPoints(const RangeBoundaryPoint& boundaryA, const RangeBoundaryPoint& boundaryB, ExceptionState& exceptionState)
 {
-    return compareBoundaryPoints(boundaryA.container(), boundaryA.offset(), boundaryB.container(), boundaryB.offset(), es);
+    return compareBoundaryPoints(boundaryA.container(), boundaryA.offset(), boundaryB.container(), boundaryB.offset(), exceptionState);
 }
 
 bool Range::boundaryPointsValid() const
 {
-    TrackExceptionState es;
-    return m_start.container() && compareBoundaryPoints(m_start, m_end, es) <= 0 && !es.hadException();
+    TrackExceptionState exceptionState;
+    return m_start.container() && compareBoundaryPoints(m_start, m_end, exceptionState) <= 0 && !exceptionState.hadException();
 }
 
-void Range::deleteContents(ExceptionState& es)
+void Range::deleteContents(ExceptionState& exceptionState)
 {
-    checkDeleteExtract("deleteContents", es);
-    if (es.hadException())
+    checkDeleteExtract("deleteContents", exceptionState);
+    if (exceptionState.hadException())
         return;
 
-    processContents(DELETE_CONTENTS, es);
+    processContents(DELETE_CONTENTS, exceptionState);
 }
 
-bool Range::intersectsNode(Node* refNode, ExceptionState& es)
+bool Range::intersectsNode(Node* refNode, ExceptionState& exceptionState)
 {
     // http://developer.mozilla.org/en/docs/DOM:range.intersectsNode
     // Returns a bool if the node intersects the range.
 
     // Throw exception if the range is already detached.
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("intersectsNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("intersectsNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return false;
     }
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
@@ -592,17 +592,17 @@
     if (!parentNode) {
         // if the node is the top document we should return NODE_BEFORE_AND_AFTER
         // but we throw to match firefox behavior
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
-    if (comparePoint(parentNode, nodeIndex, es) < 0 // starts before start
-        && comparePoint(parentNode, nodeIndex + 1, es) < 0) { // ends before start
+    if (comparePoint(parentNode, nodeIndex, exceptionState) < 0 // starts before start
+        && comparePoint(parentNode, nodeIndex + 1, exceptionState) < 0) { // ends before start
         return false;
     }
 
-    if (comparePoint(parentNode, nodeIndex, es) > 0 // starts after end
-        && comparePoint(parentNode, nodeIndex + 1, es) > 0) { // ends after end
+    if (comparePoint(parentNode, nodeIndex, exceptionState) > 0 // starts after end
+        && comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) { // ends after end
         return false;
     }
 
@@ -666,7 +666,7 @@
     return 0;
 }
 
-PassRefPtr<DocumentFragment> Range::processContents(ActionType action, ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::processContents(ActionType action, ExceptionState& exceptionState)
 {
     typedef Vector<RefPtr<Node> > NodeVector;
 
@@ -674,18 +674,18 @@
     if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS)
         fragment = DocumentFragment::create(*m_ownerDocument.get());
 
-    if (collapsed(es))
+    if (collapsed(exceptionState))
         return fragment.release();
-    if (es.hadException())
+    if (exceptionState.hadException())
         return 0;
 
-    RefPtr<Node> commonRoot = commonAncestorContainer(es);
-    if (es.hadException())
+    RefPtr<Node> commonRoot = commonAncestorContainer(exceptionState);
+    if (exceptionState.hadException())
         return 0;
     ASSERT(commonRoot);
 
     if (m_start.container() == m_end.container()) {
-        processContentsBetweenOffsets(action, fragment, m_start.container(), m_start.offset(), m_end.offset(), es);
+        processContentsBetweenOffsets(action, fragment, m_start.container(), m_start.offset(), m_end.offset(), exceptionState);
         return fragment;
     }
 
@@ -719,14 +719,14 @@
 
     RefPtr<Node> leftContents;
     if (originalStart.container() != commonRoot && commonRoot->contains(originalStart.container())) {
-        leftContents = processContentsBetweenOffsets(action, 0, originalStart.container(), originalStart.offset(), lengthOfContentsInNode(originalStart.container()), es);
-        leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), es);
+        leftContents = processContentsBetweenOffsets(action, 0, originalStart.container(), originalStart.offset(), lengthOfContentsInNode(originalStart.container()), exceptionState);
+        leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), exceptionState);
     }
 
     RefPtr<Node> rightContents;
     if (m_end.container() != commonRoot && commonRoot->contains(originalEnd.container())) {
-        rightContents = processContentsBetweenOffsets(action, 0, originalEnd.container(), 0, originalEnd.offset(), es);
-        rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), es);
+        rightContents = processContentsBetweenOffsets(action, 0, originalEnd.container(), 0, originalEnd.offset(), exceptionState);
+        rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), exceptionState);
     }
 
     // delete all children of commonRoot between the start and end container
@@ -739,14 +739,14 @@
     if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) {
         if (partialStart && commonRoot->contains(partialStart.get())) {
             // FIXME: We should not continue if we have an earlier error.
-            es.clearException();
-            setStart(partialStart->parentNode(), partialStart->nodeIndex() + 1, es);
+            exceptionState.clearException();
+            setStart(partialStart->parentNode(), partialStart->nodeIndex() + 1, exceptionState);
         } else if (partialEnd && commonRoot->contains(partialEnd.get())) {
             // FIXME: We should not continue if we have an earlier error.
-            es.clearException();
-            setStart(partialEnd->parentNode(), partialEnd->nodeIndex(), es);
+            exceptionState.clearException();
+            setStart(partialEnd->parentNode(), partialEnd->nodeIndex(), exceptionState);
         }
-        if (es.hadException())
+        if (exceptionState.hadException())
             return 0;
         m_end = m_start;
     }
@@ -758,31 +758,31 @@
     // (or just delete the stuff in between)
 
     if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && leftContents)
-        fragment->appendChild(leftContents, es);
+        fragment->appendChild(leftContents, exceptionState);
 
     if (processStart) {
         NodeVector nodes;
         for (Node* n = processStart.get(); n && n != processEnd; n = n->nextSibling())
             nodes.append(n);
-        processNodes(action, nodes, commonRoot, fragment, es);
+        processNodes(action, nodes, commonRoot, fragment, exceptionState);
     }
 
     if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && rightContents)
-        fragment->appendChild(rightContents, es);
+        fragment->appendChild(rightContents, exceptionState);
 
     return fragment.release();
 }
 
-static inline void deleteCharacterData(PassRefPtr<CharacterData> data, unsigned startOffset, unsigned endOffset, ExceptionState& es)
+static inline void deleteCharacterData(PassRefPtr<CharacterData> data, unsigned startOffset, unsigned endOffset, ExceptionState& exceptionState)
 {
     if (data->length() - endOffset)
-        data->deleteData(endOffset, data->length() - endOffset, es);
+        data->deleteData(endOffset, data->length() - endOffset, exceptionState);
     if (startOffset)
-        data->deleteData(0, startOffset, es);
+        data->deleteData(0, startOffset, exceptionState);
 }
 
 PassRefPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRefPtr<DocumentFragment> fragment,
-    Node* container, unsigned startOffset, unsigned endOffset, ExceptionState& es)
+    Node* container, unsigned startOffset, unsigned endOffset, ExceptionState& exceptionState)
 {
     ASSERT(container);
     ASSERT(startOffset <= endOffset);
@@ -796,15 +796,15 @@
         endOffset = std::min(endOffset, toCharacterData(container)->length());
         if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
             RefPtr<CharacterData> c = static_pointer_cast<CharacterData>(container->cloneNode(true));
-            deleteCharacterData(c, startOffset, endOffset, es);
+            deleteCharacterData(c, startOffset, endOffset, exceptionState);
             if (fragment) {
                 result = fragment;
-                result->appendChild(c.release(), es);
+                result->appendChild(c.release(), exceptionState);
             } else
                 result = c.release();
         }
         if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS)
-            toCharacterData(container)->deleteData(startOffset, endOffset - startOffset, es);
+            toCharacterData(container)->deleteData(startOffset, endOffset - startOffset, exceptionState);
         break;
     case Node::PROCESSING_INSTRUCTION_NODE:
         endOffset = std::min(endOffset, toProcessingInstruction(container)->data().length());
@@ -813,7 +813,7 @@
             c->setData(c->data().substring(startOffset, endOffset - startOffset));
             if (fragment) {
                 result = fragment;
-                result->appendChild(c.release(), es);
+                result->appendChild(c.release(), exceptionState);
             } else
                 result = c.release();
         }
@@ -847,31 +847,31 @@
         for (unsigned i = startOffset; n && i < endOffset; i++, n = n->nextSibling())
             nodes.append(n);
 
-        processNodes(action, nodes, container, result, es);
+        processNodes(action, nodes, container, result, exceptionState);
         break;
     }
 
     return result.release();
 }
 
-void Range::processNodes(ActionType action, Vector<RefPtr<Node> >& nodes, PassRefPtr<Node> oldContainer, PassRefPtr<Node> newContainer, ExceptionState& es)
+void Range::processNodes(ActionType action, Vector<RefPtr<Node> >& nodes, PassRefPtr<Node> oldContainer, PassRefPtr<Node> newContainer, ExceptionState& exceptionState)
 {
     for (unsigned i = 0; i < nodes.size(); i++) {
         switch (action) {
         case DELETE_CONTENTS:
-            oldContainer->removeChild(nodes[i].get(), es);
+            oldContainer->removeChild(nodes[i].get(), exceptionState);
             break;
         case EXTRACT_CONTENTS:
-            newContainer->appendChild(nodes[i].release(), es); // will remove n from its parent
+            newContainer->appendChild(nodes[i].release(), exceptionState); // will remove n from its parent
             break;
         case CLONE_CONTENTS:
-            newContainer->appendChild(nodes[i]->cloneNode(true), es);
+            newContainer->appendChild(nodes[i]->cloneNode(true), exceptionState);
             break;
         }
     }
 }
 
-PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node* container, ContentsProcessDirection direction, PassRefPtr<Node> passedClonedContainer, Node* commonRoot, ExceptionState& es)
+PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node* container, ContentsProcessDirection direction, PassRefPtr<Node> passedClonedContainer, Node* commonRoot, ExceptionState& exceptionState)
 {
     typedef Vector<RefPtr<Node> > NodeVector;
 
@@ -885,7 +885,7 @@
         RefPtr<Node> ancestor = *it;
         if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
             if (RefPtr<Node> clonedAncestor = ancestor->cloneNode(false)) { // Might have been removed already during mutation event.
-                clonedAncestor->appendChild(clonedContainer, es);
+                clonedAncestor->appendChild(clonedContainer, exceptionState);
                 clonedContainer = clonedAncestor;
             }
         }
@@ -904,19 +904,19 @@
             Node* child = it->get();
             switch (action) {
             case DELETE_CONTENTS:
-                ancestor->removeChild(child, es);
+                ancestor->removeChild(child, exceptionState);
                 break;
             case EXTRACT_CONTENTS: // will remove child from ancestor
                 if (direction == ProcessContentsForward)
-                    clonedContainer->appendChild(child, es);
+                    clonedContainer->appendChild(child, exceptionState);
                 else
-                    clonedContainer->insertBefore(child, clonedContainer->firstChild(), es);
+                    clonedContainer->insertBefore(child, clonedContainer->firstChild(), exceptionState);
                 break;
             case CLONE_CONTENTS:
                 if (direction == ProcessContentsForward)
-                    clonedContainer->appendChild(child->cloneNode(true), es);
+                    clonedContainer->appendChild(child->cloneNode(true), exceptionState);
                 else
-                    clonedContainer->insertBefore(child->cloneNode(true), clonedContainer->firstChild(), es);
+                    clonedContainer->insertBefore(child->cloneNode(true), clonedContainer->firstChild(), exceptionState);
                 break;
             }
         }
@@ -926,36 +926,36 @@
     return clonedContainer.release();
 }
 
-PassRefPtr<DocumentFragment> Range::extractContents(ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::extractContents(ExceptionState& exceptionState)
 {
-    checkDeleteExtract("extractContents", es);
-    if (es.hadException())
+    checkDeleteExtract("extractContents", exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
-    return processContents(EXTRACT_CONTENTS, es);
+    return processContents(EXTRACT_CONTENTS, exceptionState);
 }
 
-PassRefPtr<DocumentFragment> Range::cloneContents(ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::cloneContents(ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("cloneContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("cloneContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
-    return processContents(CLONE_CONTENTS, es);
+    return processContents(CLONE_CONTENTS, exceptionState);
 }
 
-void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
+void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& exceptionState)
 {
     RefPtr<Node> newNode = prpNewNode;
 
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("insertNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("insertNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
     if (!newNode) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
 
@@ -965,7 +965,7 @@
     // an extra one here - if a text node is going to split, it must have a parent to insert into
     bool startIsText = m_start.container()->isTextNode();
     if (startIsText && !m_start.container()->parentNode()) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return;
     }
 
@@ -984,7 +984,7 @@
         numNewChildren = 0;
         for (Node* c = newNode->firstChild(); c; c = c->nextSibling()) {
             if (!checkAgainst->childTypeAllowed(c->nodeType())) {
-                es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+                exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
                 return;
             }
             ++numNewChildren;
@@ -992,14 +992,14 @@
     } else {
         numNewChildren = 1;
         if (!checkAgainst->childTypeAllowed(newNodeType)) {
-            es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
             return;
         }
     }
 
     for (Node* n = m_start.container(); n; n = n->parentNode()) {
         if (n == newNode) {
-            es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
             return;
         }
     }
@@ -1010,11 +1010,11 @@
     case Node::ENTITY_NODE:
     case Node::NOTATION_NODE:
     case Node::DOCUMENT_NODE:
-        es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
         return;
     default:
         if (newNode->isShadowRoot()) {
-            es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
             return;
         }
         break;
@@ -1025,13 +1025,13 @@
     RefPtr<Node> container;
     if (startIsText) {
         container = m_start.container();
-        RefPtr<Text> newText = toText(container)->splitText(m_start.offset(), es);
-        if (es.hadException())
+        RefPtr<Text> newText = toText(container)->splitText(m_start.offset(), exceptionState);
+        if (exceptionState.hadException())
             return;
 
         container = m_start.container();
-        container->parentNode()->insertBefore(newNode.release(), newText.get(), es);
-        if (es.hadException())
+        container->parentNode()->insertBefore(newNode.release(), newText.get(), exceptionState);
+        if (exceptionState.hadException())
             return;
 
         if (collapsed)
@@ -1048,8 +1048,8 @@
         }
 
         container = m_start.container();
-        container->insertBefore(newNode.release(), container->childNode(m_start.offset()), es);
-        if (es.hadException())
+        container->insertBefore(newNode.release(), container->childNode(m_start.offset()), exceptionState);
+        if (exceptionState.hadException())
             return;
 
         // Note that m_start.offset() may have changed as a result of container->insertBefore,
@@ -1059,17 +1059,17 @@
     }
 }
 
-String Range::toString(ExceptionState& es) const
+String Range::toString(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("toString", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("toString", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return String();
     }
 
     StringBuilder builder;
 
     Node* pastLast = pastLastNode();
-    for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(n)) {
+    for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) {
         if (n->nodeType() == Node::TEXT_NODE || n->nodeType() == Node::CDATA_SECTION_NODE) {
             String data = toCharacterData(n)->data();
             int length = data.length();
@@ -1099,20 +1099,20 @@
     return plainText(this);
 }
 
-PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode();
     if (!element || !element->isHTMLElement()) {
-        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container must be an HTML element."));
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container must be an HTML element."));
         return 0;
     }
 
-    RefPtr<DocumentFragment> fragment = WebCore::createContextualFragment(markup, toHTMLElement(element), AllowScriptingContentAndDoNotMarkAlreadyStarted, es);
+    RefPtr<DocumentFragment> fragment = WebCore::createContextualFragment(markup, toHTMLElement(element), AllowScriptingContentAndDoNotMarkAlreadyStarted, exceptionState);
     if (!fragment)
         return 0;
 
@@ -1120,11 +1120,11 @@
 }
 
 
-void Range::detach(ExceptionState& es)
+void Range::detach(ExceptionState& exceptionState)
 {
     // Check first to see if we've already detached:
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("detach", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("detach", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
@@ -1134,23 +1134,23 @@
     m_end.clear();
 }
 
-Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionState& es) const
+Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionState& exceptionState) const
 {
     switch (n->nodeType()) {
         case Node::DOCUMENT_TYPE_NODE:
         case Node::ENTITY_NODE:
         case Node::NOTATION_NODE:
-            es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
             return 0;
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
         case Node::TEXT_NODE:
             if (static_cast<unsigned>(offset) > toCharacterData(n)->length())
-                es.throwUninformativeAndGenericDOMException(IndexSizeError);
+                exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return 0;
         case Node::PROCESSING_INSTRUCTION_NODE:
             if (static_cast<unsigned>(offset) > toProcessingInstruction(n)->data().length())
-                es.throwUninformativeAndGenericDOMException(IndexSizeError);
+                exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return 0;
         case Node::ATTRIBUTE_NODE:
         case Node::DOCUMENT_FRAGMENT_NODE:
@@ -1161,7 +1161,7 @@
                 return 0;
             Node* childBefore = n->childNode(offset - 1);
             if (!childBefore)
-                es.throwUninformativeAndGenericDOMException(IndexSizeError);
+                exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return childBefore;
         }
     }
@@ -1169,15 +1169,15 @@
     return 0;
 }
 
-void Range::checkNodeBA(Node* n, const String& methodName, ExceptionState& es) const
+void Range::checkNodeBA(Node* n, const String& methodName, ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute(methodName, "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute(methodName, "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
     if (!n) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
 
@@ -1186,7 +1186,7 @@
     // or if refNode is a Document, DocumentFragment, ShadowRoot, Attr, Entity, or Notation node.
 
     if (!n->parentNode()) {
-        es.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute(methodName, "Range", "the given Node has no parent."));
+        exceptionState.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute(methodName, "Range", "the given Node has no parent."));
         return;
     }
 
@@ -1196,7 +1196,7 @@
         case Node::DOCUMENT_NODE:
         case Node::ENTITY_NODE:
         case Node::NOTATION_NODE:
-            es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
             return;
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
@@ -1226,62 +1226,62 @@
         case Node::PROCESSING_INSTRUCTION_NODE:
         case Node::TEXT_NODE:
         case Node::XPATH_NAMESPACE_NODE:
-            es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
             return;
     }
 }
 
-PassRefPtr<Range> Range::cloneRange(ExceptionState& es) const
+PassRefPtr<Range> Range::cloneRange(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("cloneRange", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("cloneRange", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return 0;
     }
 
     return Range::create(*m_ownerDocument.get(), m_start.container(), m_start.offset(), m_end.container(), m_end.offset());
 }
 
-void Range::setStartAfter(Node* refNode, ExceptionState& es)
+void Range::setStartAfter(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setStartAfter", es);
-    if (es.hadException())
+    checkNodeBA(refNode, "setStartAfter", exceptionState);
+    if (exceptionState.hadException())
         return;
 
-    setStart(refNode->parentNode(), refNode->nodeIndex() + 1, es);
+    setStart(refNode->parentNode(), refNode->nodeIndex() + 1, exceptionState);
 }
 
-void Range::setEndBefore(Node* refNode, ExceptionState& es)
+void Range::setEndBefore(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setEndBefore", es);
-    if (es.hadException())
+    checkNodeBA(refNode, "setEndBefore", exceptionState);
+    if (exceptionState.hadException())
         return;
 
-    setEnd(refNode->parentNode(), refNode->nodeIndex(), es);
+    setEnd(refNode->parentNode(), refNode->nodeIndex(), exceptionState);
 }
 
-void Range::setEndAfter(Node* refNode, ExceptionState& es)
+void Range::setEndAfter(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setEndAfter", es);
-    if (es.hadException())
+    checkNodeBA(refNode, "setEndAfter", exceptionState);
+    if (exceptionState.hadException())
         return;
 
-    setEnd(refNode->parentNode(), refNode->nodeIndex() + 1, es);
+    setEnd(refNode->parentNode(), refNode->nodeIndex() + 1, exceptionState);
 }
 
-void Range::selectNode(Node* refNode, ExceptionState& es)
+void Range::selectNode(Node* refNode, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("selectNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("selectNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
 
     if (!refNode->parentNode()) {
-        es.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute("selectNode", "Range", "the given Node has no parent."));
+        exceptionState.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute("selectNode", "Range", "the given Node has no parent."));
         return;
     }
 
@@ -1303,7 +1303,7 @@
             case Node::DOCUMENT_TYPE_NODE:
             case Node::ENTITY_NODE:
             case Node::NOTATION_NODE:
-                es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+                exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
                 return;
         }
     }
@@ -1322,7 +1322,7 @@
         case Node::DOCUMENT_NODE:
         case Node::ENTITY_NODE:
         case Node::NOTATION_NODE:
-            es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
             return;
     }
 
@@ -1333,15 +1333,15 @@
     setEndAfter(refNode);
 }
 
-void Range::selectNodeContents(Node* refNode, ExceptionState& es)
+void Range::selectNodeContents(Node* refNode, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("selectNodeContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("selectNodeContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
     if (!refNode) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
 
@@ -1362,7 +1362,7 @@
             case Node::DOCUMENT_TYPE_NODE:
             case Node::ENTITY_NODE:
             case Node::NOTATION_NODE:
-                es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+                exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
                 return;
         }
     }
@@ -1374,17 +1374,17 @@
     m_end.setToEndOfNode(refNode);
 }
 
-void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionState& es)
+void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionState& exceptionState)
 {
     RefPtr<Node> newParent = passNewParent;
 
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("surroundContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("surroundContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
     if (!newParent) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return;
     }
 
@@ -1397,7 +1397,7 @@
         case Node::DOCUMENT_TYPE_NODE:
         case Node::ENTITY_NODE:
         case Node::NOTATION_NODE:
-            es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
             return;
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
@@ -1417,12 +1417,12 @@
     if (parentOfNewParent->isCharacterDataNode())
         parentOfNewParent = parentOfNewParent->parentNode();
     if (!parentOfNewParent || !parentOfNewParent->childTypeAllowed(newParent->nodeType())) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return;
     }
 
     if (newParent->contains(m_start.container())) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return;
     }
 
@@ -1437,50 +1437,50 @@
     if (endNonTextContainer->nodeType() == Node::TEXT_NODE)
         endNonTextContainer = endNonTextContainer->parentNode();
     if (startNonTextContainer != endNonTextContainer) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
     while (Node* n = newParent->firstChild()) {
-        toContainerNode(newParent)->removeChild(n, es);
-        if (es.hadException())
+        toContainerNode(newParent)->removeChild(n, exceptionState);
+        if (exceptionState.hadException())
             return;
     }
-    RefPtr<DocumentFragment> fragment = extractContents(es);
-    if (es.hadException())
+    RefPtr<DocumentFragment> fragment = extractContents(exceptionState);
+    if (exceptionState.hadException())
         return;
-    insertNode(newParent, es);
-    if (es.hadException())
+    insertNode(newParent, exceptionState);
+    if (exceptionState.hadException())
         return;
-    newParent->appendChild(fragment.release(), es);
-    if (es.hadException())
+    newParent->appendChild(fragment.release(), exceptionState);
+    if (exceptionState.hadException())
         return;
-    selectNode(newParent.get(), es);
+    selectNode(newParent.get(), exceptionState);
 }
 
-void Range::setStartBefore(Node* refNode, ExceptionState& es)
+void Range::setStartBefore(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setStartBefore", es);
-    if (es.hadException())
+    checkNodeBA(refNode, "setStartBefore", exceptionState);
+    if (exceptionState.hadException())
         return;
 
-    setStart(refNode->parentNode(), refNode->nodeIndex(), es);
+    setStart(refNode->parentNode(), refNode->nodeIndex(), exceptionState);
 }
 
-void Range::checkDeleteExtract(const String& methodName, ExceptionState& es)
+void Range::checkDeleteExtract(const String& methodName, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute(methodName, "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute(methodName, "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
         return;
     }
 
-    if (!commonAncestorContainer(es) || es.hadException())
+    if (!commonAncestorContainer(exceptionState) || exceptionState.hadException())
         return;
 
     Node* pastLast = pastLastNode();
-    for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(n)) {
+    for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) {
         if (n->nodeType() == Node::DOCUMENT_TYPE_NODE) {
-            es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
             return;
         }
     }
@@ -1496,7 +1496,7 @@
         return child;
     if (!m_start.offset())
         return m_start.container();
-    return NodeTraversal::nextSkippingChildren(m_start.container());
+    return NodeTraversal::nextSkippingChildren(*m_start.container());
 }
 
 ShadowRoot* Range::shadowRoot() const
@@ -1509,10 +1509,10 @@
     if (!m_start.container() || !m_end.container())
         return 0;
     if (m_end.container()->offsetInCharacters())
-        return NodeTraversal::nextSkippingChildren(m_end.container());
+        return NodeTraversal::nextSkippingChildren(*m_end.container());
     if (Node* child = m_end.container()->childNode(m_end.offset()))
         return child;
-    return NodeTraversal::nextSkippingChildren(m_end.container());
+    return NodeTraversal::nextSkippingChildren(*m_end.container());
 }
 
 IntRect Range::boundingBox() const
@@ -1541,7 +1541,7 @@
     bool someFixed = false;
 
     Node* stopNode = pastLastNode();
-    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
         RenderObject* r = node->renderer();
         if (!r || !r->isText())
             continue;
@@ -1573,7 +1573,7 @@
     bool someFixed = false;
 
     Node* stopNode = pastLastNode();
-    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
         RenderObject* r = node->renderer();
         if (!r || !r->isText())
             continue;
@@ -1803,7 +1803,7 @@
     boundaryTextNodeSplit(m_end, oldNode);
 }
 
-void Range::expand(const String& unit, ExceptionState& es)
+void Range::expand(const String& unit, ExceptionState& exceptionState)
 {
     VisiblePosition start(startPosition());
     VisiblePosition end(endPosition());
@@ -1821,8 +1821,8 @@
         end = endOfDocument(end);
     } else
         return;
-    setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), es);
-    setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), es);
+    setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
+    setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
 }
 
 PassRefPtr<ClientRectList> Range::getClientRects() const
@@ -1850,30 +1850,30 @@
     Node* stopNode = pastLastNode();
 
     HashSet<Node*> nodeSet;
-    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
         if (node->isElementNode())
             nodeSet.add(node);
     }
 
-    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+    for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
         if (node->isElementNode()) {
             if (!nodeSet.contains(node->parentNode())) {
                 if (RenderBoxModelObject* renderBoxModelObject = toElement(node)->renderBoxModelObject()) {
                     Vector<FloatQuad> elementQuads;
                     renderBoxModelObject->absoluteQuads(elementQuads);
-                    m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(elementQuads, renderBoxModelObject);
+                    m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(elementQuads, *renderBoxModelObject);
 
                     quads.append(elementQuads);
                 }
             }
         } else if (node->isTextNode()) {
             if (RenderObject* renderer = toText(node)->renderer()) {
-                RenderText* renderText = toRenderText(renderer);
+                RenderText& renderText = toRenderText(*renderer);
                 int startOffset = (node == startContainer) ? m_start.offset() : 0;
                 int endOffset = (node == endContainer) ? m_end.offset() : INT_MAX;
 
                 Vector<FloatQuad> textQuads;
-                renderText->absoluteQuadsForRange(textQuads, startOffset, endOffset);
+                renderText.absoluteQuadsForRange(textQuads, startOffset, endOffset);
                 m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(textQuads, renderText);
 
                 quads.append(textQuads);
diff --git a/Source/core/dom/Range.idl b/Source/core/dom/Range.idl
index 42ca334..4b8a5ee 100644
--- a/Source/core/dom/Range.idl
+++ b/Source/core/dom/Range.idl
@@ -24,12 +24,12 @@
     ConstructorCallWith=Document
 ] interface Range {
 
-    [GetterRaisesException] readonly attribute Node startContainer;
-    [GetterRaisesException] readonly attribute long startOffset;
-    [GetterRaisesException] readonly attribute Node endContainer;
-    [GetterRaisesException] readonly attribute long endOffset;
-    [GetterRaisesException] readonly attribute boolean collapsed;
-    [GetterRaisesException] readonly attribute Node commonAncestorContainer;
+    [RaisesException=Getter] readonly attribute Node startContainer;
+    [RaisesException=Getter] readonly attribute long startOffset;
+    [RaisesException=Getter] readonly attribute Node endContainer;
+    [RaisesException=Getter] readonly attribute long endOffset;
+    [RaisesException=Getter] readonly attribute boolean collapsed;
+    [RaisesException=Getter] readonly attribute Node commonAncestorContainer;
 
      [RaisesException] void setStart([Default=Undefined] optional Node refNode,
                                  [Default=Undefined] optional long offset);
diff --git a/Source/core/dom/RawDataDocumentParser.h b/Source/core/dom/RawDataDocumentParser.h
index 343842d..f2adeed 100644
--- a/Source/core/dom/RawDataDocumentParser.h
+++ b/Source/core/dom/RawDataDocumentParser.h
@@ -45,11 +45,10 @@
     }
 
 private:
-    virtual size_t flush() OVERRIDE
+    virtual void flush() OVERRIDE
     {
         // Make sure appendBytes is called at least once.
         appendBytes(0, 0);
-        return 0;
     }
 
     virtual void insert(const SegmentedString&)
diff --git a/Source/core/dom/ScriptLoader.cpp b/Source/core/dom/ScriptLoader.cpp
index d90456f..68e9302 100644
--- a/Source/core/dom/ScriptLoader.cpp
+++ b/Source/core/dom/ScriptLoader.cpp
@@ -43,9 +43,9 @@
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/Frame.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/svg/SVGScriptElement.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/text/StringHash.h"
@@ -66,6 +66,7 @@
     , m_willExecuteWhenDocumentFinishedParsing(false)
     , m_forceAsync(!parserInserted)
     , m_willExecuteInOrder(false)
+    , m_isPotentiallyCORSEnabled(false)
 {
     ASSERT(m_element);
     if (parserInserted && element->document().scriptableDocumentParser() && !element->document().isInDocumentWrite())
@@ -241,7 +242,8 @@
         // Reset line numbering for nested writes.
         TextPosition position = elementDocument.isInDocumentWrite() ? TextPosition() : scriptStartPosition;
         KURL scriptURL = (!elementDocument.isInDocumentWrite() && m_parserInserted) ? elementDocument.url() : KURL();
-        executeScript(ScriptSourceCode(scriptContent(), scriptURL, position));
+        if (!executePotentiallyCrossOriginScript(ScriptSourceCode(scriptContent(), scriptURL, position)))
+            return false;
     }
 
     return true;
@@ -264,7 +266,8 @@
         String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
         if (!crossOriginMode.isNull()) {
             StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-            request.setPotentiallyCrossOriginEnabled(elementDocument->securityOrigin(), allowCredentials);
+            request.setCrossOriginAccessControl(elementDocument->securityOrigin(), allowCredentials);
+            m_isPotentiallyCORSEnabled = true;
         }
         request.setCharset(scriptCharset());
 
@@ -276,9 +279,8 @@
         m_isExternalScript = true;
     }
 
-    if (m_resource) {
+    if (m_resource)
         return true;
-    }
 
     dispatchErrorEvent();
     return false;
@@ -362,6 +364,18 @@
     resource->removeClient(this);
 }
 
+bool ScriptLoader::executePotentiallyCrossOriginScript(const ScriptSourceCode& sourceCode)
+{
+    if (sourceCode.resource()
+        && isPotentiallyCORSEnabled()
+        && !m_element->document().fetcher()->canAccess(sourceCode.resource(), PotentiallyCORSEnabled)) {
+        dispatchErrorEvent();
+        return false;
+    }
+    executeScript(sourceCode);
+    return true;
+}
+
 void ScriptLoader::notifyFinished(Resource* resource)
 {
     ASSERT(!m_willBeParserExecuted);
@@ -378,7 +392,8 @@
     ASSERT_UNUSED(resource, resource == m_resource);
     if (!m_resource)
         return;
-    if (!elementDocument->fetcher()->canAccess(m_resource.get())) {
+    CORSEnabled corsEnabled = isPotentiallyCORSEnabled() ? PotentiallyCORSEnabled : NotCORSEnabled;
+    if (!elementDocument->fetcher()->canAccess(m_resource.get(), corsEnabled)) {
         dispatchErrorEvent();
         return;
     }
diff --git a/Source/core/dom/ScriptLoader.h b/Source/core/dom/ScriptLoader.h
index e6ba8d3..72f5197 100644
--- a/Source/core/dom/ScriptLoader.h
+++ b/Source/core/dom/ScriptLoader.h
@@ -50,6 +50,12 @@
     void executeScript(const ScriptSourceCode&);
     void execute(ScriptResource*);
 
+    // Check if potentially cross-origin enabled script is accessible
+    // prior to execution. Returns 'false' if not accessible, signalling
+    // that callers must not dispatch load events as the cross-origin
+    // fetch failed.
+    bool executePotentiallyCrossOriginScript(const ScriptSourceCode&);
+
     // XML parser calls these
     void dispatchLoadEvent();
     void dispatchErrorEvent();
@@ -65,6 +71,7 @@
     bool isParserInserted() const { return m_parserInserted; }
     bool alreadyStarted() const { return m_alreadyStarted; }
     bool forceAsync() const { return m_forceAsync; }
+    bool isPotentiallyCORSEnabled() const { return m_isPotentiallyCORSEnabled; }
 
     // Helper functions used by our parent classes.
     void didNotifySubtreeInsertionsToDocument();
@@ -98,6 +105,7 @@
     bool m_willExecuteWhenDocumentFinishedParsing : 1;
     bool m_forceAsync : 1;
     bool m_willExecuteInOrder : 1;
+    bool m_isPotentiallyCORSEnabled : 1;
     String m_characterEncoding;
     String m_fallbackCharacterEncoding;
 };
diff --git a/Source/core/dom/ScriptRunner.cpp b/Source/core/dom/ScriptRunner.cpp
index f63ab50..6cf96ae 100644
--- a/Source/core/dom/ScriptRunner.cpp
+++ b/Source/core/dom/ScriptRunner.cpp
@@ -47,7 +47,7 @@
         m_document->decrementLoadEventDelayCount();
     for (size_t i = 0; i < m_scriptsToExecuteInOrder.size(); ++i)
         m_document->decrementLoadEventDelayCount();
-    for (int i = 0; i < m_pendingAsyncScripts.size(); ++i)
+    for (size_t i = 0; i < m_pendingAsyncScripts.size(); ++i)
         m_document->decrementLoadEventDelayCount();
 }
 
diff --git a/Source/core/dom/ScriptedAnimationController.cpp b/Source/core/dom/ScriptedAnimationController.cpp
index 6438e51..33446c8 100644
--- a/Source/core/dom/ScriptedAnimationController.cpp
+++ b/Source/core/dom/ScriptedAnimationController.cpp
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-std::pair<EventTarget*, StringImpl*> scheduledEventTargetKey(const Event* event)
+std::pair<EventTarget*, StringImpl*> eventTargetKey(const Event* event)
 {
     return std::make_pair(event->target(), event->type().impl());
 }
@@ -95,11 +95,13 @@
 {
     Vector<RefPtr<Event> > events;
     events.swap(m_eventQueue);
-    m_scheduledEventTargets.clear();
+    m_perFrameEvents.clear();
 
     for (size_t i = 0; i < events.size(); ++i) {
         EventTarget* eventTarget = events[i]->target();
-        // FIXME: we should figure out how to make dispatchEvent properly virtual to avoid this.
+        // FIXME: we should figure out how to make dispatchEvent properly virtual to avoid
+        // special casting window.
+        // FIXME: We should not fire events for nodes that are no longer in the tree.
         if (DOMWindow* window = eventTarget->toDOMWindow())
             window->dispatchEvent(events[i], 0);
         else
@@ -158,14 +160,19 @@
     scheduleAnimationIfNeeded();
 }
 
-void ScriptedAnimationController::scheduleEvent(PassRefPtr<Event> event)
+void ScriptedAnimationController::enqueueEvent(PassRefPtr<Event> event)
 {
-    if (!m_scheduledEventTargets.add(scheduledEventTargetKey(event.get())).isNewEntry)
-        return;
     m_eventQueue.append(event);
     scheduleAnimationIfNeeded();
 }
 
+void ScriptedAnimationController::enqueuePerFrameEvent(PassRefPtr<Event> event)
+{
+    if (!m_perFrameEvents.add(eventTargetKey(event.get())).isNewEntry)
+        return;
+    enqueueEvent(event);
+}
+
 void ScriptedAnimationController::scheduleAnimationIfNeeded()
 {
     if (!m_document)
diff --git a/Source/core/dom/ScriptedAnimationController.h b/Source/core/dom/ScriptedAnimationController.h
index 1d32c5a..7c83094 100644
--- a/Source/core/dom/ScriptedAnimationController.h
+++ b/Source/core/dom/ScriptedAnimationController.h
@@ -54,7 +54,8 @@
     void cancelCallback(CallbackId);
     void serviceScriptedAnimations(double monotonicTimeNow);
 
-    void scheduleEvent(PassRefPtr<Event>);
+    void enqueueEvent(PassRefPtr<Event>);
+    void enqueuePerFrameEvent(PassRefPtr<Event>);
 
     void suspend();
     void resume();
@@ -74,7 +75,7 @@
     CallbackId m_nextCallbackId;
     int m_suspendCount;
     Vector<RefPtr<Event> > m_eventQueue;
-    ListHashSet<std::pair<const EventTarget*, const StringImpl*> > m_scheduledEventTargets;
+    ListHashSet<std::pair<const EventTarget*, const StringImpl*> > m_perFrameEvents;
 };
 
 }
diff --git a/Source/core/dom/SecurityContext.cpp b/Source/core/dom/SecurityContext.cpp
index aaab839..d0c3530 100644
--- a/Source/core/dom/SecurityContext.cpp
+++ b/Source/core/dom/SecurityContext.cpp
@@ -28,7 +28,7 @@
 #include "core/dom/SecurityContext.h"
 
 #include "core/frame/ContentSecurityPolicy.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/SelectorQuery.cpp b/Source/core/dom/SelectorQuery.cpp
index d1f90af..50113c5 100644
--- a/Source/core/dom/SelectorQuery.cpp
+++ b/Source/core/dom/SelectorQuery.cpp
@@ -34,6 +34,7 @@
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/dom/Document.h"
 #include "core/dom/ElementTraversal.h"
+#include "core/dom/Node.h"
 #include "core/dom/StaticNodeList.h"
 
 namespace WebCore {
@@ -64,7 +65,7 @@
 
 class ClassRootNodeList : public SimpleNodeList {
 public:
-    ClassRootNodeList(Node* rootNode, const AtomicString& className)
+    ClassRootNodeList(Node& rootNode, const AtomicString& className)
         : m_className(className)
         , m_rootNode(rootNode)
         , m_currentElement(nextInternal(ElementTraversal::firstWithin(m_rootNode))) { }
@@ -75,14 +76,14 @@
     {
         Node* current = m_currentElement;
         ASSERT(current);
-        m_currentElement = nextInternal(ElementTraversal::nextSkippingChildren(m_currentElement, m_rootNode));
+        m_currentElement = nextInternal(ElementTraversal::nextSkippingChildren(*m_currentElement, &m_rootNode));
         return current;
     }
 
 private:
     Element* nextInternal(Element* element)
     {
-        for (; element; element = ElementTraversal::next(element, m_rootNode)) {
+        for (; element; element = ElementTraversal::next(*element, &m_rootNode)) {
             if (element->hasClass() && element->classNames().contains(m_className))
                 return element;
         }
@@ -90,13 +91,13 @@
     }
 
     const AtomicString& m_className;
-    Node* m_rootNode;
+    Node& m_rootNode;
     Element* m_currentElement;
 };
 
 class ClassElementList : public SimpleNodeList {
 public:
-    ClassElementList(Node* rootNode, const AtomicString& className)
+    ClassElementList(Node& rootNode, const AtomicString& className)
         : m_className(className)
         , m_rootNode(rootNode)
         , m_currentElement(nextInternal(ElementTraversal::firstWithin(rootNode))) { }
@@ -107,14 +108,14 @@
     {
         Node* current = m_currentElement;
         ASSERT(current);
-        m_currentElement = nextInternal(ElementTraversal::next(m_currentElement, m_rootNode));
+        m_currentElement = nextInternal(ElementTraversal::next(*m_currentElement, &m_rootNode));
         return current;
     }
 
 private:
     Element* nextInternal(Element* element)
     {
-        for (; element; element = ElementTraversal::next(element, m_rootNode)) {
+        for (; element; element = ElementTraversal::next(*element, &m_rootNode)) {
             if (element->hasClass() && element->classNames().contains(m_className))
                 return element;
         }
@@ -122,7 +123,7 @@
     }
 
     const AtomicString& m_className;
-    Node* m_rootNode;
+    Node& m_rootNode;
     Element* m_currentElement;
 };
 
@@ -179,15 +180,9 @@
     return executeQueryFirst(rootNode);
 }
 
-static inline bool isTreeScopeRoot(Node* node)
-{
-    ASSERT(node);
-    return node->isDocumentNode() || node->isShadowRoot();
-}
-
 void SelectorDataList::collectElementsByClassName(Node& rootNode, const AtomicString& className, Vector<RefPtr<Node> >& traversalRoots) const
 {
-    for (Element* element = ElementTraversal::firstWithin(&rootNode); element; element = ElementTraversal::next(element, &rootNode)) {
+    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
         if (element->hasClass() && element->classNames().contains(className))
             traversalRoots.append(element);
     }
@@ -195,7 +190,7 @@
 
 void SelectorDataList::collectElementsByTagName(Node& rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >& traversalRoots) const
 {
-    for (Element* element = ElementTraversal::firstWithin(&rootNode); element; element = ElementTraversal::next(element, &rootNode)) {
+    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
         if (SelectorChecker::tagMatches(*element, tagName))
             traversalRoots.append(element);
     }
@@ -203,7 +198,7 @@
 
 Element* SelectorDataList::findElementByClassName(Node& rootNode, const AtomicString& className) const
 {
-    for (Element* element = ElementTraversal::firstWithin(&rootNode); element; element = ElementTraversal::next(element, &rootNode)) {
+    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
         if (element->hasClass() && element->classNames().contains(className))
             return element;
     }
@@ -212,7 +207,7 @@
 
 Element* SelectorDataList::findElementByTagName(Node& rootNode, const QualifiedName& tagName) const
 {
-    for (Element* element = ElementTraversal::firstWithin(&rootNode); element; element = ElementTraversal::next(element, &rootNode)) {
+    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
         if (SelectorChecker::tagMatches(*element, tagName))
             return element;
     }
@@ -224,12 +219,12 @@
     return m_selectors.size() == 1 && rootNode.inDocument() && !rootNode.document().inQuirksMode();
 }
 
-inline bool ancestorHasClassName(Node* rootNode, const AtomicString& className)
+inline bool ancestorHasClassName(Node& rootNode, const AtomicString& className)
 {
-    if (!rootNode->isElementNode())
+    if (!rootNode.isElementNode())
         return false;
 
-    for (Element* element = toElement(rootNode); element; element = element->parentElement()) {
+    for (Element* element = &toElement(rootNode); element; element = element->parentElement()) {
         if (element->hasClass() && element->classNames().contains(className))
             return true;
     }
@@ -244,11 +239,10 @@
 //
 // The travseralRoots may be empty, regardless of the returned bool value, if this method finds that the selectors won't
 // match any element.
-PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node* rootNode, bool& matchTraverseRoots) const
+PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node& rootNode, bool& matchTraverseRoots) const
 {
     // We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches
     // we would need to sort the results. For now, just traverse the document in that case.
-    ASSERT(rootNode);
     ASSERT(m_selectors.size() == 1);
     ASSERT(m_selectors[0].selector);
 
@@ -256,21 +250,22 @@
     bool startFromParent = false;
 
     for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
-        if (selector->m_match == CSSSelector::Id && !rootNode->document().containsMultipleElementsWithId(selector->value())) {
-            Element* element = rootNode->treeScope().getElementById(selector->value());
-            if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
-                rootNode = element;
+        if (selector->m_match == CSSSelector::Id && !rootNode.document().containsMultipleElementsWithId(selector->value())) {
+            Element* element = rootNode.treeScope().getElementById(selector->value());
+            Node* adjustedNode = &rootNode;
+            if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
+                adjustedNode = element;
             else if (!element || isRightmostSelector)
-                rootNode = 0;
+                adjustedNode = 0;
             if (isRightmostSelector) {
                 matchTraverseRoots = true;
-                return adoptPtr(new SingleNodeList(rootNode));
+                return adoptPtr(new SingleNodeList(adjustedNode));
             }
-            if (startFromParent && rootNode)
-                rootNode = rootNode->parentNode();
+            if (startFromParent && adjustedNode)
+                adjustedNode = adjustedNode->parentNode();
 
             matchTraverseRoots = false;
-            return adoptPtr(new SingleNodeList(rootNode));
+            return adoptPtr(new SingleNodeList(adjustedNode));
         }
 
         // If we have both CSSSelector::Id and CSSSelector::Class at the same time, we should use Id
@@ -283,7 +278,7 @@
             matchTraverseRoots = false;
             // Since there exists some ancestor element which has the class name, we need to see all children of rootNode.
             if (ancestorHasClassName(rootNode, selector->value()))
-                return adoptPtr(new SingleNodeList(rootNode));
+                return adoptPtr(new SingleNodeList(&rootNode));
 
             return adoptPtr(new ClassRootNodeList(rootNode, selector->value()));
         }
@@ -298,12 +293,12 @@
     }
 
     matchTraverseRoots = false;
-    return adoptPtr(new SingleNodeList(rootNode));
+    return adoptPtr(new SingleNodeList(&rootNode));
 }
 
 void SelectorDataList::executeSlowQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const
 {
-    for (Element* element = ElementTraversal::firstWithin(&rootNode); element; element = ElementTraversal::next(element, &rootNode)) {
+    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
         for (unsigned i = 0; i < m_selectors.size(); ++i) {
             if (selectorMatches(m_selectors[i], *element, rootNode)) {
                 matchedElements.append(element);
@@ -347,7 +342,7 @@
     }
 
     bool matchTraverseRoots;
-    OwnPtr<SimpleNodeList> traverseRoots = findTraverseRoots(&rootNode, matchTraverseRoots);
+    OwnPtr<SimpleNodeList> traverseRoots = findTraverseRoots(rootNode, matchTraverseRoots);
     if (traverseRoots->isEmpty())
         return;
 
@@ -364,7 +359,8 @@
 
     while (!traverseRoots->isEmpty()) {
         Node* traverseRoot = traverseRoots->next();
-        for (Element* element = ElementTraversal::firstWithin(traverseRoot); element; element = ElementTraversal::next(element, traverseRoot)) {
+        ASSERT(traverseRoot);
+        for (Element* element = ElementTraversal::firstWithin(*traverseRoot); element; element = ElementTraversal::next(*element, traverseRoot)) {
             if (selectorMatches(selector, *element, rootNode))
                 matchedElements.append(element);
         }
@@ -418,7 +414,7 @@
 
 Element* SelectorDataList::executeSlowQueryFirst(Node& rootNode) const
 {
-    for (Element* element = ElementTraversal::firstWithin(&rootNode); element; element = ElementTraversal::next(element, &rootNode)) {
+    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
         for (unsigned i = 0; i < m_selectors.size(); ++i) {
             if (selectorMatches(m_selectors[i], *element, rootNode))
                 return element;
@@ -467,7 +463,7 @@
         return selectorMatches(m_selectors[0], element, rootNode) ? &element : 0;
     }
 
-    for (Element* element = ElementTraversal::firstWithin(traverseRootNode); element; element = ElementTraversal::next(element, traverseRootNode)) {
+    for (Element* element = ElementTraversal::firstWithin(*traverseRootNode); element; element = ElementTraversal::next(*element, traverseRootNode)) {
         if (selectorMatches(m_selectors[0], *element, rootNode))
             return element;
     }
@@ -495,7 +491,7 @@
     return m_selectors.queryFirst(rootNode);
 }
 
-SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, const Document& document, ExceptionState& es)
+SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, const Document& document, ExceptionState& exceptionState)
 {
     HashMap<AtomicString, OwnPtr<SelectorQuery> >::iterator it = m_entries.find(selectors);
     if (it != m_entries.end())
@@ -506,17 +502,17 @@
     parser.parseSelector(selectors, selectorList);
 
     if (!selectorList.first()) {
-        es.throwDOMException(SyntaxError, "Failed to execute query: '" + selectors + "' is not a valid selector.");
+        exceptionState.throwDOMException(SyntaxError, "Failed to execute query: '" + selectors + "' is not a valid selector.");
         return 0;
     }
 
     // throw a NamespaceError if the selector includes any namespace prefixes.
     if (selectorList.selectorsNeedNamespaceResolution()) {
-        es.throwDOMException(NamespaceError, "Failed to execute query: '" + selectors + "' contains namespaces, which are not supported.");
+        exceptionState.throwDOMException(NamespaceError, "Failed to execute query: '" + selectors + "' contains namespaces, which are not supported.");
         return 0;
     }
 
-    const int maximumSelectorQueryCacheSize = 256;
+    const unsigned maximumSelectorQueryCacheSize = 256;
     if (m_entries.size() == maximumSelectorQueryCacheSize)
         m_entries.remove(m_entries.begin());
 
diff --git a/Source/core/dom/SelectorQuery.h b/Source/core/dom/SelectorQuery.h
index bbe607c..fb787ab 100644
--- a/Source/core/dom/SelectorQuery.h
+++ b/Source/core/dom/SelectorQuery.h
@@ -62,7 +62,7 @@
     Element* findElementByClassName(Node& rootNode, const AtomicString& className) const;
     void collectElementsByTagName(Node& rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >&) const;
     Element* findElementByTagName(Node& rootNode, const QualifiedName& tagName) const;
-    PassOwnPtr<SimpleNodeList> findTraverseRoots(Node* rootNode, bool& matchTraverseRoots) const;
+    PassOwnPtr<SimpleNodeList> findTraverseRoots(Node& rootNode, bool& matchTraverseRoots) const;
     void executeSlowQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const;
     void executeQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const;
     Node* findTraverseRoot(Node& rootNode, bool& matchTraverseRoot) const;
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
index f77ff81..d0ae20a 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
@@ -30,7 +30,6 @@
 #include "HTMLNames.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/StyleEngine.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -46,11 +45,8 @@
 {
 }
 
-void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection)
 {
-    if (document()->settings() && !document()->settings()->authorAndUserStylesEnabled())
-        return;
-
     DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
     DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
     for (DocumentOrderedList::iterator it = begin; it != end; ++it) {
@@ -67,20 +63,20 @@
 
         sheet = toHTMLStyleElement(node)->sheet();
         if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
-            activeSheet = static_cast<CSSStyleSheet*>(sheet);
+            activeSheet = toCSSStyleSheet(sheet);
 
         // FIXME: clarify how PREFERRED or ALTERNATE works in shadow trees.
         // Should we set preferred/selected stylesheets name in shadow trees and
         // use the name in document?
         AtomicString rel = element->getAttribute(relAttr);
         if (!enabledViaScript && sheet && !title.isEmpty()) {
-            if (collections->preferredStylesheetSetName().isEmpty()) {
+            if (engine->preferredStylesheetSetName().isEmpty()) {
                 if (element->hasLocalName(styleTag) || !rel.contains("alternate")) {
-                    collections->setPreferredStylesheetSetName(title);
-                    collections->setSelectedStylesheetSetName(title);
+                    engine->setPreferredStylesheetSetName(title);
+                    engine->setSelectedStylesheetSetName(title);
                 }
             }
-            if (title != collections->preferredStylesheetSetName())
+            if (title != engine->preferredStylesheetSetName())
                 activeSheet = 0;
         }
 
@@ -88,46 +84,42 @@
             activeSheet = 0;
 
         if (sheet)
-            styleSheets.append(sheet);
+            collection.appendSheetForList(sheet);
         if (activeSheet)
-            activeSheets.append(activeSheet);
+            collection.appendActiveStyleSheet(activeSheet);
     }
 }
 
-bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(StyleEngine* collections, StyleResolverUpdateMode updateMode)
+bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
 {
-    Vector<RefPtr<StyleSheet> > styleSheets;
-    Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
-    collectStyleSheets(collections, styleSheets, activeCSSStyleSheets);
+    StyleSheetCollectionBase collection;
+    collectStyleSheets(engine, collection);
 
-    bool requiresFullStyleRecalc = true;
+    StyleSheetChange change;
+    analyzeStyleSheetChange(updateMode, collection, change);
 
-    StyleResolverUpdateType styleResolverUpdateType;
-    analyzeStyleSheetChange(updateMode, activeAuthorStyleSheets(), activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
-
-    if (StyleResolver* styleResolver = document()->styleResolverIfExists()) {
+    if (StyleResolver* styleResolver = engine->resolverIfExists()) {
         // FIXME: We might have already had styles in child treescope. In this case, we cannot use buildScopedStyleTreeInDocumentOrder.
         // Need to change "false" to some valid condition.
         styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
-        if (styleResolverUpdateType == Reset || styleResolverUpdateType == Reconstruct) {
+        if (change.styleResolverUpdateType != Additive) {
             // We should not destroy StyleResolver when we find any stylesheet update in a shadow tree.
             // In this case, we will reset rulesets created from style elements in the shadow tree.
             resetAllRuleSetsInTreeScope(styleResolver);
-            styleResolver->appendAuthorStyleSheets(0, activeCSSStyleSheets);
+            styleResolver->removePendingAuthorStyleSheets(m_activeAuthorStyleSheets);
+            styleResolver->lazyAppendAuthorStyleSheets(0, collection.activeAuthorStyleSheets());
         } else {
-            ASSERT(styleResolverUpdateType == Additive);
-            styleResolver->appendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), activeCSSStyleSheets);
+            styleResolver->lazyAppendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), collection.activeAuthorStyleSheets());
         }
     }
-    if (requiresFullStyleRecalc)
+    if (change.requiresFullStyleRecalc)
         toShadowRoot(m_treeScope.rootNode())->host()->setNeedsStyleRecalc();
 
     m_scopingNodesForStyleScoped.didRemoveScopingNodes();
-    m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
-    m_styleSheetsForStyleSheetList.swap(styleSheets);
+    collection.swap(*this);
     updateUsesRemUnits();
 
-    return requiresFullStyleRecalc;
+    return change.requiresFullStyleRecalc;
 }
 
 }
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.h b/Source/core/dom/ShadowTreeStyleSheetCollection.h
index 253ad63..b7c13cb 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.h
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.h
@@ -46,7 +46,7 @@
     bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
 
 private:
-    void collectStyleSheets(StyleEngine*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+    void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&);
 };
 
 }
diff --git a/Source/core/dom/SimulatedClickOptions.h b/Source/core/dom/SimulatedClickOptions.h
index a49ed74..8feefed 100644
--- a/Source/core/dom/SimulatedClickOptions.h
+++ b/Source/core/dom/SimulatedClickOptions.h
@@ -29,11 +29,6 @@
     SendMouseOverUpDownEvents
 };
 
-enum SimulatedClickVisualOptions {
-    DoNotShowPressedLook,
-    ShowPressedLook
-};
-
 } // namespace WebCore
 
 #endif // SimulatedClickOptions_h
diff --git a/Source/core/dom/StyleEngine.cpp b/Source/core/dom/StyleEngine.cpp
index 7c908b9..8a1d0c8 100644
--- a/Source/core/dom/StyleEngine.cpp
+++ b/Source/core/dom/StyleEngine.cpp
@@ -33,7 +33,6 @@
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StyleInvalidationAnalysis.h"
 #include "core/css/StyleSheetContents.h"
-#include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
@@ -42,6 +41,7 @@
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Page.h"
 #include "core/page/PageGroup.h"
 #include "core/page/Settings.h"
@@ -58,24 +58,24 @@
     , m_injectedStyleSheetCacheValid(false)
     , m_needsUpdateActiveStylesheetsOnStyleRecalc(false)
     , m_documentStyleSheetCollection(document)
-    , m_needsDocumentStyleSheetsUpdate(true)
+    , m_dirtyTreeScopes(document)
     , m_usesSiblingRules(false)
     , m_usesSiblingRulesOverride(false)
     , m_usesFirstLineRules(false)
     , m_usesFirstLetterRules(false)
     , m_usesRemUnits(false)
     , m_maxDirectAdjacentSelectors(0)
+    , m_ignorePendingStylesheets(false)
+    , m_didCalculateResolver(false)
+    , m_lastResolverAccessCount(0)
+    , m_resolverThrowawayTimer(this, &StyleEngine::resolverThrowawayTimerFired)
 {
 }
 
 StyleEngine::~StyleEngine()
 {
-    if (m_pageUserSheet)
-        m_pageUserSheet->clearOwnerNode();
     for (unsigned i = 0; i < m_injectedAuthorStyleSheets.size(); ++i)
         m_injectedAuthorStyleSheets[i]->clearOwnerNode();
-    for (unsigned i = 0; i < m_userStyleSheets.size(); ++i)
-        m_userStyleSheets[i]->clearOwnerNode();
     for (unsigned i = 0; i < m_authorStyleSheets.size(); ++i)
         m_authorStyleSheets[i]->clearOwnerNode();
 }
@@ -170,43 +170,6 @@
     m_maxDirectAdjacentSelectors = features.maxDirectAdjacentSelectors();
 }
 
-CSSStyleSheet* StyleEngine::pageUserSheet()
-{
-    if (m_pageUserSheet)
-        return m_pageUserSheet.get();
-
-    Page* owningPage = m_document.page();
-    if (!owningPage)
-        return 0;
-
-    String userSheetText = owningPage->userStyleSheet();
-    if (userSheetText.isEmpty())
-        return 0;
-
-    // Parse the sheet and cache it.
-    m_pageUserSheet = CSSStyleSheet::createInline(&m_document, m_document.settings()->userStyleSheetLocation());
-    m_pageUserSheet->contents()->setIsUserStyleSheet(true);
-    m_pageUserSheet->contents()->parseString(userSheetText);
-    return m_pageUserSheet.get();
-}
-
-void StyleEngine::clearPageUserSheet()
-{
-    if (m_pageUserSheet) {
-        RefPtr<StyleSheet> removedSheet = m_pageUserSheet;
-        m_pageUserSheet = 0;
-        m_document.removedStyleSheet(removedSheet.get());
-    }
-}
-
-void StyleEngine::updatePageUserSheet()
-{
-    clearPageUserSheet();
-    // FIXME: Why is this immediately and not defer?
-    if (StyleSheet* addedSheet = pageUserSheet())
-        m_document.addedStyleSheet(addedSheet, RecalcStyleImmediately);
-}
-
 const Vector<RefPtr<CSSStyleSheet> >& StyleEngine::injectedAuthorStyleSheets() const
 {
     updateInjectedStyleSheetCache();
@@ -234,7 +197,6 @@
             continue;
         RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(&m_document), KURL());
         m_injectedAuthorStyleSheets.append(groupSheet);
-        groupSheet->contents()->setIsUserStyleSheet(false);
         groupSheet->contents()->parseString(sheet->source());
     }
 }
@@ -242,7 +204,7 @@
 void StyleEngine::invalidateInjectedStyleSheetCache()
 {
     m_injectedStyleSheetCacheValid = false;
-    m_needsDocumentStyleSheetsUpdate = true;
+    m_dirtyTreeScopes.markDocument();
     // FIXME: updateInjectedStyleSheetCache is called inside StyleSheetCollection::updateActiveStyleSheets
     // and batch updates lots of sheets so we can't call addedStyleSheet() or removedStyleSheet().
     m_document.styleResolverChanged(RecalcStyleDeferred);
@@ -250,18 +212,9 @@
 
 void StyleEngine::addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet)
 {
-    ASSERT(!authorSheet->isUserStyleSheet());
     m_authorStyleSheets.append(CSSStyleSheet::create(authorSheet, &m_document));
     m_document.addedStyleSheet(m_authorStyleSheets.last().get(), RecalcStyleImmediately);
-    m_needsDocumentStyleSheetsUpdate = true;
-}
-
-void StyleEngine::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
-{
-    ASSERT(userSheet->isUserStyleSheet());
-    m_userStyleSheets.append(CSSStyleSheet::create(userSheet, &m_document));
-    m_document.addedStyleSheet(m_userStyleSheets.last().get(), RecalcStyleImmediately);
-    m_needsDocumentStyleSheetsUpdate = true;
+    m_dirtyTreeScopes.markDocument();
 }
 
 // This method is called whenever a top-level stylesheet has finished loading.
@@ -273,10 +226,8 @@
     m_pendingStylesheets--;
 
     TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : &m_document;
-    if (treeScope == m_document)
-        m_needsDocumentStyleSheetsUpdate = true;
-    else
-        m_dirtyTreeScopes.add(treeScope);
+
+    m_dirtyTreeScopes.mark(*treeScope);
 
     if (m_pendingStylesheets)
         return;
@@ -303,11 +254,8 @@
     TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
     ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
 
-    if (treeScope == m_document) {
-        m_needsDocumentStyleSheetsUpdate = true;
-        return;
-    }
-    m_dirtyTreeScopes.add(&treeScope);
+
+    m_dirtyTreeScopes.mark(treeScope);
 }
 
 void StyleEngine::addStyleSheetCandidateNode(Node* node, bool createdByParser)
@@ -322,13 +270,9 @@
     ASSERT(collection);
     collection->addStyleSheetCandidateNode(node, createdByParser);
 
-    if (treeScope == m_document) {
-        m_needsDocumentStyleSheetsUpdate = true;
-        return;
-    }
-
-    insertTreeScopeInDocumentOrder(m_activeTreeScopes, &treeScope);
-    m_dirtyTreeScopes.add(&treeScope);
+    m_dirtyTreeScopes.mark(treeScope);
+    if (treeScope != m_document)
+        insertTreeScopeInDocumentOrder(m_activeTreeScopes, &treeScope);
 }
 
 void StyleEngine::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
@@ -340,11 +284,7 @@
     ASSERT(collection);
     collection->removeStyleSheetCandidateNode(node, scopingNode);
 
-    if (treeScope == m_document) {
-        m_needsDocumentStyleSheetsUpdate = true;
-        return;
-    }
-    m_dirtyTreeScopes.add(&treeScope);
+    m_dirtyTreeScopes.mark(treeScope);
     m_activeTreeScopes.remove(&treeScope);
 }
 
@@ -355,16 +295,30 @@
 
     TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
     ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
-    if (treeScope == m_document) {
-        m_needsDocumentStyleSheetsUpdate = true;
-        return;
-    }
-    m_dirtyTreeScopes.add(&treeScope);
+    m_dirtyTreeScopes.mark(treeScope);
 }
 
 bool StyleEngine::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode updateMode)
 {
-    return !m_dirtyTreeScopes.isEmpty() || updateMode == FullStyleUpdate;
+    return !m_dirtyTreeScopes.isSubscopeMarked() || updateMode == FullStyleUpdate;
+}
+
+void StyleEngine::clearMediaQueryRuleSetOnTreeScopeStyleSheets(TreeScopeSet treeScopes)
+{
+    for (TreeScopeSet::iterator it = treeScopes.begin(); it != treeScopes.end(); ++it) {
+        TreeScope& treeScope = **it;
+        ASSERT(treeScope != m_document);
+        ShadowTreeStyleSheetCollection* collection = static_cast<ShadowTreeStyleSheetCollection*>(styleSheetCollectionFor(treeScope));
+        ASSERT(collection);
+        collection->clearMediaQueryRuleSetStyleSheets();
+    }
+}
+
+void StyleEngine::clearMediaQueryRuleSetStyleSheets()
+{
+    m_documentStyleSheetCollection.clearMediaQueryRuleSetStyleSheets();
+    clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_activeTreeScopes);
+    clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_dirtyTreeScopes.subscope());
 }
 
 bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
@@ -381,11 +335,11 @@
         return false;
 
     bool requiresFullStyleRecalc = false;
-    if (m_needsDocumentStyleSheetsUpdate || updateMode == FullStyleUpdate)
+    if (m_dirtyTreeScopes.isDocumentMarked() || updateMode == FullStyleUpdate)
         requiresFullStyleRecalc = m_documentStyleSheetCollection.updateActiveStyleSheets(this, updateMode);
 
     if (shouldUpdateShadowTreeStyleSheetCollection(updateMode)) {
-        TreeScopeSet treeScopes = updateMode == FullStyleUpdate ? m_activeTreeScopes : m_dirtyTreeScopes;
+        TreeScopeSet treeScopes = updateMode == FullStyleUpdate ? m_activeTreeScopes : m_dirtyTreeScopes.subscope();
         HashSet<TreeScope*> treeScopesRemoved;
 
         for (TreeScopeSet::iterator it = treeScopes.begin(); it != treeScopes.end(); ++it) {
@@ -400,22 +354,15 @@
         if (!treeScopesRemoved.isEmpty())
             for (HashSet<TreeScope*>::iterator it = treeScopesRemoved.begin(); it != treeScopesRemoved.end(); ++it)
                 m_activeTreeScopes.remove(*it);
-        m_dirtyTreeScopes.clear();
     }
-
-    if (StyleResolver* styleResolver = m_document.styleResolverIfExists()) {
-        styleResolver->finishAppendAuthorStyleSheets();
-        resetCSSFeatureFlags(styleResolver->ruleFeatureSet());
-    }
-
     m_needsUpdateActiveStylesheetsOnStyleRecalc = false;
     activeStyleSheetsUpdatedForInspector();
     m_usesRemUnits = m_documentStyleSheetCollection.usesRemUnits();
 
-    if (m_needsDocumentStyleSheetsUpdate || updateMode == FullStyleUpdate) {
+    if (m_dirtyTreeScopes.isDocumentMarked() || updateMode == FullStyleUpdate)
         m_document.notifySeamlessChildDocumentsOfStylesheetUpdate();
-        m_needsDocumentStyleSheetsUpdate = false;
-    }
+
+    m_dirtyTreeScopes.clear();
 
     return requiresFullStyleRecalc;
 }
@@ -467,4 +414,76 @@
     styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
 }
 
+void StyleEngine::createResolver()
+{
+    // It is a programming error to attempt to resolve style on a Document
+    // which is not in a frame. Code which hits this should have checked
+    // Document::isActive() before calling into code which could get here.
+
+    ASSERT(m_document.frame());
+
+    m_resolver = adoptPtr(new StyleResolver(m_document));
+    combineCSSFeatureFlags(m_resolver->ensureRuleFeatureSet());
+}
+
+void StyleEngine::clearResolver()
+{
+    ASSERT(!m_document.inStyleRecalc());
+    m_resolver.clear();
+}
+
+unsigned StyleEngine::resolverAccessCount() const
+{
+    return m_resolver ? m_resolver->accessCount() : 0;
+}
+
+void StyleEngine::resolverThrowawayTimerFired(Timer<StyleEngine>*)
+{
+    if (resolverAccessCount() == m_lastResolverAccessCount)
+        clearResolver();
+    m_lastResolverAccessCount = resolverAccessCount();
+}
+
+CSSFontSelector* StyleEngine::fontSelector()
+{
+    return m_resolver ? m_resolver->fontSelector() : 0;
+}
+
+void StyleEngine::didAttach()
+{
+    m_resolverThrowawayTimer.startRepeating(60);
+}
+
+void StyleEngine::didDetach()
+{
+    m_resolverThrowawayTimer.stop();
+    clearResolver();
+}
+
+bool StyleEngine::shouldClearResolver() const
+{
+    return !m_didCalculateResolver && !haveStylesheetsLoaded();
+}
+
+StyleResolverChange StyleEngine::resolverChanged(StyleResolverUpdateMode mode)
+{
+    StyleResolverChange change;
+
+    // Don't bother updating, since we haven't loaded all our style info yet
+    // and haven't calculated the style selector for the first time.
+    if (!m_document.isActive() || shouldClearResolver()) {
+        clearResolver();
+        return change;
+    }
+
+    m_didCalculateResolver = true;
+    if (m_document.didLayoutWithPendingStylesheets() && !hasPendingSheets())
+        change.setNeedsRepaint();
+
+    if (updateActiveStyleSheets(mode))
+        change.setNeedsStyleRecalc();
+
+    return change;
+}
+
 }
diff --git a/Source/core/dom/StyleEngine.h b/Source/core/dom/StyleEngine.h
index 0df22e4..1c1b6fc 100644
--- a/Source/core/dom/StyleEngine.h
+++ b/Source/core/dom/StyleEngine.h
@@ -28,29 +28,63 @@
 #ifndef StyleEngine_h
 #define StyleEngine_h
 
+#include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentOrderedList.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
+#include "core/dom/StyleTreeScopeTracker.h"
 #include "wtf/FastAllocBase.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/RefPtr.h"
+#include "wtf/TemporaryChange.h"
 #include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
+class CSSFontSelector;
 class CSSStyleSheet;
+class FontSelector;
 class Node;
 class RuleFeatureSet;
 class ShadowTreeStyleSheetCollection;
+class StyleResolver;
 class StyleSheet;
 class StyleSheetCollection;
 class StyleSheetContents;
 class StyleSheetList;
 
+class StyleResolverChange {
+public:
+    StyleResolverChange()
+        : m_needsRepaint(false)
+        , m_needsStyleRecalc(false)
+    { }
+
+    bool needsRepaint() const { return m_needsRepaint; }
+    bool needsStyleRecalc() const { return m_needsStyleRecalc; }
+    void setNeedsRepaint() { m_needsRepaint = true; }
+    void setNeedsStyleRecalc() { m_needsStyleRecalc = true; }
+
+private:
+    bool m_needsRepaint;
+    bool m_needsStyleRecalc;
+};
+
 class StyleEngine {
     WTF_MAKE_FAST_ALLOCATED;
 public:
+
+    class IgnoringPendingStylesheet : public TemporaryChange<bool> {
+    public:
+        IgnoringPendingStylesheet(StyleEngine* engine)
+            : TemporaryChange<bool>(engine->m_ignorePendingStylesheets, true)
+        {
+        }
+    };
+
+    friend class IgnoringPendingStylesheet;
+
     static PassOwnPtr<StyleEngine> create(Document& document) { return adoptPtr(new StyleEngine(document)); }
 
     ~StyleEngine();
@@ -58,8 +92,6 @@
     const Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList(TreeScope&);
     const Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() const;
 
-    CSSStyleSheet* pageUserSheet();
-    const Vector<RefPtr<CSSStyleSheet> >& documentUserStyleSheets() const { return m_userStyleSheets; }
     const Vector<RefPtr<CSSStyleSheet> >& documentAuthorStyleSheets() const { return m_authorStyleSheets; }
     const Vector<RefPtr<CSSStyleSheet> >& injectedAuthorStyleSheets() const;
 
@@ -68,16 +100,14 @@
     void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode = 0);
     void modifiedStyleSheetCandidateNode(Node*);
 
-    void clearPageUserSheet();
-    void updatePageUserSheet();
     void invalidateInjectedStyleSheetCache();
     void updateInjectedStyleSheetCache() const;
 
     void addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet);
-    void addUserSheet(PassRefPtr<StyleSheetContents> userSheet);
 
     bool needsUpdateActiveStylesheetsOnStyleRecalc() const { return m_needsUpdateActiveStylesheetsOnStyleRecalc; }
 
+    void clearMediaQueryRuleSetStyleSheets();
     bool updateActiveStyleSheets(StyleResolverUpdateMode);
 
     String preferredStylesheetSetName() const { return m_preferredStylesheetSetName; }
@@ -93,6 +123,8 @@
     void removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
 
     bool hasPendingSheets() const { return m_pendingStylesheets > 0; }
+    bool haveStylesheetsLoaded() const { return !hasPendingSheets() || m_ignorePendingStylesheets; }
+    bool ignoringPendingStylesheets() const { return m_ignorePendingStylesheets; }
 
     unsigned maxDirectAdjacentSelectors() const { return m_maxDirectAdjacentSelectors; }
     bool usesSiblingRules() const { return m_usesSiblingRules || m_usesSiblingRulesOverride; }
@@ -107,11 +139,36 @@
     void combineCSSFeatureFlags(const RuleFeatureSet&);
     void resetCSSFeatureFlags(const RuleFeatureSet&);
 
-    void didModifySeamlessParentStyleSheet() { m_needsDocumentStyleSheetsUpdate = true; }
+    void didModifySeamlessParentStyleSheet() { m_dirtyTreeScopes.markDocument(); }
     void didRemoveShadowRoot(ShadowRoot*);
     void appendActiveAuthorStyleSheets(StyleResolver*);
     void getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const;
 
+    StyleResolver* resolverIfExists() const
+    {
+        return m_resolver.get();
+    }
+
+    StyleResolver* resolver()
+    {
+        if (!m_resolver) {
+            createResolver();
+        } else if (m_resolver->hasPendingAuthorStyleSheets()) {
+            m_resolver->appendPendingAuthorStyleSheets();
+        }
+        return m_resolver.get();
+    }
+
+    bool hasResolver() const { return m_resolver.get(); }
+    void clearResolver();
+
+    CSSFontSelector* fontSelector();
+    void didAttach();
+    void didDetach();
+    bool shouldClearResolver() const;
+    StyleResolverChange resolverChanged(StyleResolverUpdateMode);
+    unsigned resolverAccessCount() const;
+
 private:
     StyleEngine(Document&);
 
@@ -119,9 +176,13 @@
     StyleSheetCollection* styleSheetCollectionFor(TreeScope&);
     void activeStyleSheetsUpdatedForInspector();
     bool shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode);
+    void resolverThrowawayTimerFired(Timer<StyleEngine>*);
 
     typedef ListHashSet<TreeScope*, 16> TreeScopeSet;
     static void insertTreeScopeInDocumentOrder(TreeScopeSet&, TreeScope*);
+    void clearMediaQueryRuleSetOnTreeScopeStyleSheets(TreeScopeSet treeScopes);
+
+    void createResolver();
 
     Document& m_document;
 
@@ -131,12 +192,9 @@
     // elements and when it is safe to execute scripts.
     int m_pendingStylesheets;
 
-    RefPtr<CSSStyleSheet> m_pageUserSheet;
-
     mutable Vector<RefPtr<CSSStyleSheet> > m_injectedAuthorStyleSheets;
     mutable bool m_injectedStyleSheetCacheValid;
 
-    Vector<RefPtr<CSSStyleSheet> > m_userStyleSheets;
     Vector<RefPtr<CSSStyleSheet> > m_authorStyleSheets;
 
     bool m_needsUpdateActiveStylesheetsOnStyleRecalc;
@@ -144,9 +202,8 @@
     DocumentStyleSheetCollection m_documentStyleSheetCollection;
     HashMap<TreeScope*, OwnPtr<StyleSheetCollection> > m_styleSheetCollectionMap;
 
-    TreeScopeSet m_dirtyTreeScopes;
+    StyleTreeScopeTracker m_dirtyTreeScopes;
     TreeScopeSet m_activeTreeScopes;
-    bool m_needsDocumentStyleSheetsUpdate;
 
     String m_preferredStylesheetSetName;
     String m_selectedStylesheetSetName;
@@ -157,6 +214,12 @@
     bool m_usesFirstLetterRules;
     bool m_usesRemUnits;
     unsigned m_maxDirectAdjacentSelectors;
+
+    bool m_ignorePendingStylesheets;
+    bool m_didCalculateResolver;
+    unsigned m_lastResolverAccessCount;
+    Timer<StyleEngine> m_resolverThrowawayTimer;
+    OwnPtr<StyleResolver> m_resolver;
 };
 
 }
diff --git a/Source/core/dom/StyleSheetCollection.cpp b/Source/core/dom/StyleSheetCollection.cpp
index ff87dd8..e2f3f3f 100644
--- a/Source/core/dom/StyleSheetCollection.cpp
+++ b/Source/core/dom/StyleSheetCollection.cpp
@@ -29,6 +29,7 @@
 
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StyleInvalidationAnalysis.h"
+#include "core/css/StyleRuleImport.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
@@ -39,9 +40,40 @@
 
 namespace WebCore {
 
+StyleSheetCollectionBase::StyleSheetCollectionBase()
+{
+}
+
+StyleSheetCollectionBase::~StyleSheetCollectionBase()
+{
+}
+
+void StyleSheetCollectionBase::swap(StyleSheetCollectionBase& other)
+{
+    m_styleSheetsForStyleSheetList.swap(other.m_styleSheetsForStyleSheetList);
+    m_activeAuthorStyleSheets.swap(other.m_activeAuthorStyleSheets);
+}
+
+void StyleSheetCollectionBase::appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets)
+{
+    m_activeAuthorStyleSheets.append(sheets);
+}
+
+void StyleSheetCollectionBase::appendActiveStyleSheet(CSSStyleSheet* sheet)
+{
+    m_activeAuthorStyleSheets.append(sheet);
+}
+
+void StyleSheetCollectionBase::appendSheetForList(StyleSheet* sheet)
+{
+    m_styleSheetsForStyleSheetList.append(sheet);
+}
+
+
 StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope)
     : m_treeScope(treeScope)
     , m_hadActiveLoadingStylesheet(false)
+    , m_usesRemUnits(false)
 {
 }
 
@@ -77,24 +109,25 @@
 
 StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
 {
-    unsigned newStylesheetCount = newStylesheets.size();
-    unsigned oldStylesheetCount = oldStyleSheets.size();
-    ASSERT(newStylesheetCount >= oldStylesheetCount);
+    unsigned newStyleSheetCount = newStylesheets.size();
+    unsigned oldStyleSheetCount = oldStyleSheets.size();
+    ASSERT(newStyleSheetCount >= oldStyleSheetCount);
+
+    if (!newStyleSheetCount)
+        return Reconstruct;
 
     unsigned newIndex = 0;
-    for (unsigned oldIndex = 0; oldIndex < oldStylesheetCount; ++oldIndex) {
-        if (newIndex >= newStylesheetCount)
-            return Reconstruct;
+    for (unsigned oldIndex = 0; oldIndex < oldStyleSheetCount; ++oldIndex) {
         while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
             addedSheets.append(newStylesheets[newIndex]->contents());
-            ++newIndex;
-            if (newIndex == newStylesheetCount)
+            if (++newIndex == newStyleSheetCount)
                 return Reconstruct;
         }
-        ++newIndex;
+        if (++newIndex == newStyleSheetCount)
+            return Reconstruct;
     }
     bool hasInsertions = !addedSheets.isEmpty();
-    while (newIndex < newStylesheetCount) {
+    while (newIndex < newStyleSheetCount) {
         addedSheets.append(newStylesheets[newIndex]->contents());
         ++newIndex;
     }
@@ -120,30 +153,65 @@
     return false;
 }
 
-void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
+static bool styleSheetContentsHasFontFaceRule(Vector<StyleSheetContents*> sheets)
 {
-    styleResolverUpdateType = Reconstruct;
-    requiresFullStyleRecalc = true;
+    for (unsigned i = 0; i < sheets.size(); ++i) {
+        ASSERT(sheets[i]);
+        if (sheets[i]->hasFontFaceRule())
+            return true;
+    }
+    return false;
+}
 
-    if (activeLoadingStyleSheetLoaded(newStyleSheets))
+static bool cssStyleSheetHasFontFaceRule(const Vector<RefPtr<CSSStyleSheet> > sheets)
+{
+    for (unsigned i = 0; i < sheets.size(); ++i) {
+        ASSERT(sheets[i]);
+        if (sheets[i]->contents()->hasFontFaceRule())
+            return true;
+    }
+    return false;
+}
+
+void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const StyleSheetCollectionBase& newCollection, StyleSheetChange& change)
+{
+    // No point in doing the analysis work if we're just going to recalc the whole document anyways.
+    if (document()->hasPendingForcedStyleRecalc())
+        return;
+
+    if (activeLoadingStyleSheetLoaded(newCollection.activeAuthorStyleSheets()))
         return;
 
     if (updateMode != AnalyzedStyleUpdate)
         return;
-    if (!document()->styleResolverIfExists())
-        return;
 
     // Find out which stylesheets are new.
     Vector<StyleSheetContents*> addedSheets;
-    if (oldStyleSheets.size() <= newStyleSheets.size()) {
-        styleResolverUpdateType = compareStyleSheets(oldStyleSheets, newStyleSheets, addedSheets);
+    if (m_activeAuthorStyleSheets.size() <= newCollection.activeAuthorStyleSheets().size()) {
+        change.styleResolverUpdateType = compareStyleSheets(m_activeAuthorStyleSheets, newCollection.activeAuthorStyleSheets(), addedSheets);
     } else {
-        StyleResolverUpdateType updateType = compareStyleSheets(newStyleSheets, oldStyleSheets, addedSheets);
-        styleResolverUpdateType = updateType != Additive ? updateType : Reset;
+        StyleResolverUpdateType updateType = compareStyleSheets(newCollection.activeAuthorStyleSheets(), m_activeAuthorStyleSheets, addedSheets);
+        if (updateType != Additive) {
+            change.styleResolverUpdateType = updateType;
+        } else {
+            if (styleSheetContentsHasFontFaceRule(addedSheets)) {
+                change.styleResolverUpdateType = ResetStyleResolverAndFontSelector;
+                return;
+            }
+            // FIXME: since currently all stylesheets are re-added after reseting styleresolver,
+            // fontSelector should be always reset. After creating RuleSet for each StyleSheetContents,
+            // we can avoid appending all stylesheetcontents in reset case.
+            // So we can remove "styleSheetContentsHasFontFaceRule(newSheets)".
+            if (cssStyleSheetHasFontFaceRule(newCollection.activeAuthorStyleSheets()))
+                change.styleResolverUpdateType = ResetStyleResolverAndFontSelector;
+            else
+                change.styleResolverUpdateType = Reset;
+        }
     }
 
-    // FIXME: If styleResolverUpdateType is still Reconstruct, we could return early here
-    // as destroying the StyleResolver will recalc the whole document anyway?
+    // FIXME: If styleResolverUpdateType is Reconstruct, we should return early here since
+    // we need to recalc the whole document. It's wrong to use StyleInvalidationAnalysis since
+    // it only looks at the addedSheets.
 
     // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
     if (!document()->body() || document()->hasNodesWithPlaceholderStyle())
@@ -151,8 +219,18 @@
     StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
     if (invalidationAnalysis.dirtiesAllStyle())
         return;
-    invalidationAnalysis.invalidateStyle(document());
-    requiresFullStyleRecalc = false;
+    invalidationAnalysis.invalidateStyle(*document());
+    change.requiresFullStyleRecalc = false;
+    return;
+}
+
+void StyleSheetCollection::clearMediaQueryRuleSetStyleSheets()
+{
+    for (size_t i = 0; i < m_activeAuthorStyleSheets.size(); ++i) {
+        StyleSheetContents* contents = m_activeAuthorStyleSheets[i]->contents();
+        if (contents->hasMediaQueries())
+            contents->clearRuleSet();
+    }
 }
 
 void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver)
diff --git a/Source/core/dom/StyleSheetCollection.h b/Source/core/dom/StyleSheetCollection.h
index 6519617..9c90233 100644
--- a/Source/core/dom/StyleSheetCollection.h
+++ b/Source/core/dom/StyleSheetCollection.h
@@ -49,24 +49,47 @@
 class StyleSheetContents;
 class StyleSheetList;
 
-class StyleSheetCollection {
-    WTF_MAKE_NONCOPYABLE(StyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
+// FIXME: Should be in separate file and be renamed like:
+// - StyleSheetCollectionBase -> StyleSheetCollection
+// - StyleSheetCollection -> ScopeStyleSheetCollection
+//
+class StyleSheetCollectionBase {
+    WTF_MAKE_NONCOPYABLE(StyleSheetCollectionBase); WTF_MAKE_FAST_ALLOCATED;
 public:
-    void addStyleSheetCandidateNode(Node*, bool createdByParser);
-    void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
-    bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
+    StyleSheetCollectionBase();
+    ~StyleSheetCollectionBase();
 
     Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() { return m_activeAuthorStyleSheets; }
     Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList() { return m_styleSheetsForStyleSheetList; }
     const Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() const { return m_activeAuthorStyleSheets; }
     const Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList() const { return m_styleSheetsForStyleSheetList; }
 
+    void swap(StyleSheetCollectionBase&);
+    void appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
+    void appendActiveStyleSheet(CSSStyleSheet*);
+    void appendSheetForList(StyleSheet*);
+
+protected:
+    Vector<RefPtr<StyleSheet> > m_styleSheetsForStyleSheetList;
+    Vector<RefPtr<CSSStyleSheet> > m_activeAuthorStyleSheets;
+};
+
+
+class StyleSheetCollection : public StyleSheetCollectionBase {
+public:
+    void addStyleSheetCandidateNode(Node*, bool createdByParser);
+    void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
+    bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
+
+
     bool usesRemUnits() const { return m_usesRemUnits; }
 
     DocumentOrderedList& styleSheetCandidateNodes() { return m_styleSheetCandidateNodes; }
     DocumentOrderedList* scopingNodesForStyleScoped() { return m_scopingNodesForStyleScoped.scopingNodes(); }
     ListHashSet<Node*, 4>* scopingNodesRemoved() { return m_scopingNodesForStyleScoped.scopingNodesRemoved(); }
 
+    void clearMediaQueryRuleSetStyleSheets();
+
 protected:
     explicit StyleSheetCollection(TreeScope&);
 
@@ -75,20 +98,28 @@
     enum StyleResolverUpdateType {
         Reconstruct,
         Reset,
-        Additive
+        Additive,
+        ResetStyleResolverAndFontSelector
     };
-    void analyzeStyleSheetChange(StyleResolverUpdateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
+
+    struct StyleSheetChange {
+        StyleResolverUpdateType styleResolverUpdateType;
+        bool requiresFullStyleRecalc;
+
+        StyleSheetChange()
+            : styleResolverUpdateType(Reconstruct)
+            , requiresFullStyleRecalc(true) { }
+    };
+
+    void analyzeStyleSheetChange(StyleResolverUpdateMode, const StyleSheetCollectionBase&, StyleSheetChange&);
     void resetAllRuleSetsInTreeScope(StyleResolver*);
     void updateUsesRemUnits();
 
 private:
-    StyleResolverUpdateType compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets);
+    static StyleResolverUpdateType compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets);
     bool activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets);
 
 protected:
-    Vector<RefPtr<StyleSheet> > m_styleSheetsForStyleSheetList;
-    Vector<RefPtr<CSSStyleSheet> > m_activeAuthorStyleSheets;
-
     TreeScope& m_treeScope;
     bool m_hadActiveLoadingStylesheet;
     bool m_usesRemUnits;
diff --git a/Source/core/dom/StyleSheetScopingNodeList.cpp b/Source/core/dom/StyleSheetScopingNodeList.cpp
index e2a5b3d..5d809e0 100644
--- a/Source/core/dom/StyleSheetScopingNodeList.cpp
+++ b/Source/core/dom/StyleSheetScopingNodeList.cpp
@@ -29,6 +29,7 @@
 #include "core/dom/StyleSheetScopingNodeList.h"
 
 #include "core/dom/Document.h"
+#include "core/dom/Node.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/StyleSheetScopingNodeList.h b/Source/core/dom/StyleSheetScopingNodeList.h
index 790be13..e6f61ec 100644
--- a/Source/core/dom/StyleSheetScopingNodeList.h
+++ b/Source/core/dom/StyleSheetScopingNodeList.h
@@ -34,16 +34,6 @@
 
 namespace WebCore {
 
-inline bool isTreeScopeRoot(const Node* node)
-{
-    return !node || node->isDocumentNode() || node->isShadowRoot();
-}
-
-inline bool isTreeScopeRoot(const Node& node)
-{
-    return node.isDocumentNode() || node.isShadowRoot();
-}
-
 class StyleSheetScopingNodeList {
     WTF_MAKE_NONCOPYABLE(StyleSheetScopingNodeList); WTF_MAKE_FAST_ALLOCATED;
 public:
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.cpp b/Source/core/dom/StyleTreeScopeTracker.cpp
similarity index 71%
copy from Source/core/workers/WorkerGlobalScopeProxy.cpp
copy to Source/core/dom/StyleTreeScopeTracker.cpp
index 06471bb..87f56ac 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ b/Source/core/dom/StyleTreeScopeTracker.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 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
@@ -7,10 +7,6 @@
  *
  *     * 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.
@@ -29,10 +25,32 @@
  */
 
 #include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
+#include "core/dom/StyleTreeScopeTracker.h"
+
+#include "core/dom/Document.h"
 
 namespace WebCore {
 
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
+StyleTreeScopeTracker::StyleTreeScopeTracker(Document& document)
+    : m_document(document)
+    , m_isDocumentMarked(true)
+{
+}
 
-} // namespace WebCore
+void StyleTreeScopeTracker::mark(TreeScope& scope)
+{
+    if (scope == m_document) {
+        markDocument();
+        return;
+    }
+
+    m_set.add(&scope);
+}
+
+void StyleTreeScopeTracker::clear()
+{
+    m_set.clear();
+    m_isDocumentMarked = false;
+}
+
+}
diff --git a/Source/core/rendering/RenderingConfiguration.cpp b/Source/core/dom/StyleTreeScopeTracker.h
similarity index 66%
copy from Source/core/rendering/RenderingConfiguration.cpp
copy to Source/core/dom/StyleTreeScopeTracker.h
index 77060a3..7dbd886 100644
--- a/Source/core/rendering/RenderingConfiguration.cpp
+++ b/Source/core/dom/StyleTreeScopeTracker.h
@@ -7,10 +7,6 @@
  *
  *     * 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.
@@ -28,29 +24,35 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/rendering/RenderingConfiguration.h"
+#ifndef StyleTreeScopeTracker_h
+#define StyleTreeScopeTracker_h
 
-#include "core/dom/Document.h"
+#include "wtf/ListHashSet.h"
 
 namespace WebCore {
 
-RenderingConfiguration::RenderingConfiguration()
-    : m_inQuirksMode(false)
-    , m_paginated(false)
-    , m_printing(false)
-{
-}
+class Document;
+class TreeScope;
 
-RenderingConfiguration::~RenderingConfiguration()
-{
-}
+class StyleTreeScopeTracker {
+public:
+    typedef ListHashSet<TreeScope*, 16> TreeScopeSet;
 
-void RenderingConfiguration::update(Document& document)
-{
-    m_inQuirksMode = document.inQuirksMode();
-    m_paginated = document.paginated();
-    m_printing = document.printing();
-}
+    explicit StyleTreeScopeTracker(Document&);
+
+    void mark(TreeScope&);
+    void markDocument() { m_isDocumentMarked = true; }
+    bool isSubscopeMarked() const { return m_set.isEmpty(); }
+    bool isDocumentMarked() const { return m_isDocumentMarked; }
+    void clear();
+    TreeScopeSet& subscope() { return m_set; }
+
+private:
+    Document& m_document;
+    bool m_isDocumentMarked;
+    TreeScopeSet m_set;
+};
 
 }
+
+#endif
diff --git a/Source/core/dom/TemplateContentDocumentFragment.h b/Source/core/dom/TemplateContentDocumentFragment.h
index 6c44e60..380e8fa 100644
--- a/Source/core/dom/TemplateContentDocumentFragment.h
+++ b/Source/core/dom/TemplateContentDocumentFragment.h
@@ -33,16 +33,16 @@
 
 class TemplateContentDocumentFragment FINAL : public DocumentFragment {
 public:
-    static PassRefPtr<TemplateContentDocumentFragment> create(Document& document, const Element* host)
+    static PassRefPtr<TemplateContentDocumentFragment> create(Document& document, Element* host)
     {
         return adoptRef(new TemplateContentDocumentFragment(document, host));
     }
 
-    const Element* host() const { return m_host; }
+    Element* host() const { return m_host; }
     void clearHost() { m_host = 0; }
 
 private:
-    TemplateContentDocumentFragment(Document& document, const Element* host)
+    TemplateContentDocumentFragment(Document& document, Element* host)
         : DocumentFragment(&document, CreateDocumentFragment)
         , m_host(host)
     {
@@ -50,7 +50,7 @@
 
     virtual bool isTemplateContent() const OVERRIDE { return true; }
 
-    const Element* m_host;
+    Element* m_host;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index 2d5d6d3..6cbbeba 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -60,7 +60,7 @@
     // Remove empty text nodes.
     if (!length()) {
         // Care must be taken to get the next node before removing the current node.
-        RefPtr<Node> nextNode(NodeTraversal::nextPostOrder(this));
+        RefPtr<Node> nextNode(NodeTraversal::nextPostOrder(*this));
         remove(IGNORE_EXCEPTION);
         return nextNode.release();
     }
@@ -84,25 +84,31 @@
         String oldTextData = data();
         setDataWithoutUpdate(data() + nextTextData);
         updateTextRenderer(oldTextData.length(), 0);
+
         // Empty nextText for layout update.
         nextText->setDataWithoutUpdate(emptyString());
+        nextText->updateTextRenderer(0, nextTextData.length());
+
         document().didMergeTextNodes(nextText.get(), offset);
+
         // Restore nextText for mutation event.
         nextText->setDataWithoutUpdate(nextTextData);
+        nextText->updateTextRenderer(0, 0);
+
         document().incDOMTreeVersion();
         didModifyData(oldTextData);
         nextText->remove(IGNORE_EXCEPTION);
     }
 
-    return NodeTraversal::nextPostOrder(this);
+    return NodeTraversal::nextPostOrder(*this);
 }
 
-PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionState& es)
+PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionState& exceptionState)
 {
     // IndexSizeError: Raised if the specified offset is negative or greater than
     // the number of 16-bit units in data.
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("splitText", "Text", "The offset " + String::number(offset) + " is larger than the Text node's length."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("splitText", "Text", "The offset " + String::number(offset) + " is larger than the Text node's length."));
         return 0;
     }
 
@@ -114,8 +120,8 @@
     didModifyData(oldStr);
 
     if (parentNode())
-        parentNode()->insertBefore(newText.get(), nextSibling(), es);
-    if (es.hadException())
+        parentNode()->insertBefore(newText.get(), nextSibling(), exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     if (renderer())
@@ -305,7 +311,7 @@
     CharacterData::attach(context);
 }
 
-bool Text::recalcTextStyle(StyleRecalcChange change)
+void Text::recalcTextStyle(StyleRecalcChange change, Text* nextTextSibling)
 {
     if (RenderText* renderer = toRenderText(this->renderer())) {
         if (change != NoChange || needsStyleRecalc())
@@ -315,9 +321,8 @@
         clearNeedsStyleRecalc();
     } else if (needsStyleRecalc() || needsWhitespaceRenderer()) {
         reattach();
-        return true;
+        reattachWhitespaceSiblings(nextTextSibling);
     }
-    return false;
 }
 
 // If a whitespace node had no renderer and goes through a recalcStyle it may
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index ee66dab..603a018 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -48,7 +48,7 @@
     String wholeText() const;
     PassRefPtr<Text> replaceWholeText(const String&);
 
-    bool recalcTextStyle(StyleRecalcChange);
+    void recalcTextStyle(StyleRecalcChange, Text* nextTextSibling);
     bool textRendererIsNeeded(const NodeRenderingContext&);
     virtual RenderText* createTextRenderer(RenderStyle*);
     void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior = DoNotRecalcStyle);
diff --git a/Source/core/dom/Text.idl b/Source/core/dom/Text.idl
index 0ee791b..d6e2f18 100644
--- a/Source/core/dom/Text.idl
+++ b/Source/core/dom/Text.idl
@@ -19,7 +19,7 @@
 [
     Constructor([Default=NullString] optional DOMString data),
     ConstructorCallWith=Document,
-    CustomToV8
+    CustomWrap,
 ] interface Text : CharacterData {
 
     // DOM Level 1
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 46fe4ca..c624f9d 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -277,7 +277,8 @@
     if (!m_labelsByForAttribute) {
         // Populate the map on first access.
         m_labelsByForAttribute = adoptPtr(new DocumentOrderedMap);
-        for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::next(element)) {
+        ASSERT(rootNode());
+        for (Element* element = ElementTraversal::firstWithin(*rootNode()); element; element = ElementTraversal::next(*element)) {
             if (isHTMLLabelElement(element)) {
                 HTMLLabelElement* label = toHTMLLabelElement(element);
                 const AtomicString& forValue = label->fastGetAttribute(forAttr);
@@ -311,7 +312,8 @@
         return 0;
     if (Element* element = getElementById(name))
         return element;
-    for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::next(element)) {
+    ASSERT(rootNode());
+    for (Element* element = ElementTraversal::firstWithin(*rootNode()); element; element = ElementTraversal::next(*element)) {
         if (isHTMLAnchorElement(element)) {
             HTMLAnchorElement* anchor = toHTMLAnchorElement(element);
             if (rootNode()->document().inQuirksMode()) {
@@ -352,7 +354,7 @@
     return 0;
 }
 
-Element* TreeScope::adjustedFocusedElement()
+Element* TreeScope::adjustedFocusedElement() const
 {
     Document& document = rootNode()->document();
     Element* element = document.focusedElement();
@@ -485,7 +487,8 @@
         return 0;
     Element* result = 0;
     Node* root = rootNode();
-    for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(element, root)) {
+    ASSERT(root);
+    for (Element* element = ElementTraversal::firstWithin(*root); element; element = ElementTraversal::next(*element, root)) {
         if (equalIgnoringCase(element->fastGetAttribute(accesskeyAttr), key))
             result = element;
         for (ShadowRoot* shadowRoot = element->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
diff --git a/Source/core/dom/TreeScope.h b/Source/core/dom/TreeScope.h
index 664db15..26154da 100644
--- a/Source/core/dom/TreeScope.h
+++ b/Source/core/dom/TreeScope.h
@@ -55,7 +55,7 @@
     TreeScope* parentTreeScope() const { return m_parentTreeScope; }
     void setParentTreeScope(TreeScope*);
 
-    Element* adjustedFocusedElement();
+    Element* adjustedFocusedElement() const;
     Element* getElementById(const AtomicString&) const;
     bool hasElementWithId(StringImpl* id) const;
     bool containsMultipleElementsWithId(const AtomicString& id) const;
diff --git a/Source/core/dom/TreeScopeAdopter.cpp b/Source/core/dom/TreeScopeAdopter.cpp
index 6561b09..366b4af 100644
--- a/Source/core/dom/TreeScopeAdopter.cpp
+++ b/Source/core/dom/TreeScopeAdopter.cpp
@@ -51,7 +51,7 @@
     if (willMoveToNewDocument)
         oldDocument->incDOMTreeVersion();
 
-    for (Node* node = &root; node; node = NodeTraversal::next(node, &root)) {
+    for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
         updateTreeScope(*node);
 
         if (willMoveToNewDocument)
@@ -83,7 +83,7 @@
 
 void TreeScopeAdopter::moveTreeToNewDocument(Node& root, Document& oldDocument, Document* newDocument) const
 {
-    for (Node* node = &root; node; node = NodeTraversal::next(node, &root)) {
+    for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
         moveNodeToNewDocument(*node, oldDocument, newDocument);
         for (ShadowRoot* shadow = node->youngestShadowRoot(); shadow; shadow = shadow->olderShadowRoot())
             moveTreeToNewDocument(*shadow, oldDocument, newDocument);
diff --git a/Source/core/dom/TreeWalker.cpp b/Source/core/dom/TreeWalker.cpp
index bec5c19..2d58281 100644
--- a/Source/core/dom/TreeWalker.cpp
+++ b/Source/core/dom/TreeWalker.cpp
@@ -43,10 +43,10 @@
     ScriptWrappable::init(this);
 }
 
-void TreeWalker::setCurrentNode(PassRefPtr<Node> node, ExceptionState& es)
+void TreeWalker::setCurrentNode(PassRefPtr<Node> node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("setCurrentNode", "TreeWalker", "The Node provided is invalid."));
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("setCurrentNode", "TreeWalker", "The Node provided is invalid."));
         return;
     }
     m_current = node;
@@ -267,7 +267,7 @@
         if (acceptNodeResult == NodeFilter::FILTER_REJECT)
             break;
     }
-    while (Node* nextSibling = NodeTraversal::nextSkippingChildren(node.get(), root())) {
+    while (Node* nextSibling = NodeTraversal::nextSkippingChildren(*node, root())) {
         node = nextSibling;
         short acceptNodeResult = acceptNode(state, node.get());
         if (state && state->hadException())
diff --git a/Source/core/dom/TreeWalker.idl b/Source/core/dom/TreeWalker.idl
index ac04ba0..6a92eb0 100644
--- a/Source/core/dom/TreeWalker.idl
+++ b/Source/core/dom/TreeWalker.idl
@@ -26,7 +26,7 @@
     readonly attribute unsigned long whatToShow;
     readonly attribute NodeFilter filter;
     readonly attribute boolean expandEntityReferences;
-             [SetterRaisesException] attribute Node currentNode;
+             [RaisesException=Setter] attribute Node currentNode;
 
     [CallWith=ScriptState] Node parentNode();
     [CallWith=ScriptState] Node firstChild();
diff --git a/Source/core/dom/URL.idl b/Source/core/dom/URL.idl
index 37e2a90..ff323dd 100644
--- a/Source/core/dom/URL.idl
+++ b/Source/core/dom/URL.idl
@@ -26,7 +26,7 @@
 
 [
     GlobalContext=Window&WorkerGlobalScope,
-    ConstructorRaisesException,
+    RaisesException=Constructor,
     Constructor(DOMString url),
     Constructor(DOMString url, URL base),
     Constructor(DOMString url, DOMString base),
diff --git a/Source/core/dom/VisitedLinkState.cpp b/Source/core/dom/VisitedLinkState.cpp
index 521d0ab..f715a3d 100644
--- a/Source/core/dom/VisitedLinkState.cpp
+++ b/Source/core/dom/VisitedLinkState.cpp
@@ -63,7 +63,7 @@
 {
     if (m_linksCheckedForVisitedState.isEmpty())
         return;
-    for (Element* element = ElementTraversal::firstWithin(&m_document); element; element = ElementTraversal::next(element)) {
+    for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(*element)) {
         if (element->isLink())
             element->setNeedsStyleRecalc();
     }
@@ -73,7 +73,7 @@
 {
     if (!m_linksCheckedForVisitedState.contains(linkHash))
         return;
-    for (Element* element = ElementTraversal::firstWithin(&m_document); element; element = ElementTraversal::next(element)) {
+    for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(*element)) {
         if (element->isLink() && linkHashForElement(*element) == linkHash)
             element->setNeedsStyleRecalc();
     }
@@ -99,7 +99,7 @@
 
     if (LinkHash hash = linkHashForElement(element, attribute)) {
         m_linksCheckedForVisitedState.add(hash);
-        if (WebKit::Platform::current()->isLinkVisited(hash))
+        if (blink::Platform::current()->isLinkVisited(hash))
             return InsideVisitedLink;
     }
 
diff --git a/Source/core/dom/WebKitNamedFlow.idl b/Source/core/dom/WebKitNamedFlow.idl
index f1185b4..800e26d 100644
--- a/Source/core/dom/WebKitNamedFlow.idl
+++ b/Source/core/dom/WebKitNamedFlow.idl
@@ -28,10 +28,10 @@
  */
 
 [
+    GenerateVisitDOMWrapper=ownerNode,
+    ImplementedAs=NamedFlow,
     NoInterfaceObject,
     RuntimeEnabled=CSSRegions,
-    ImplementedAs=NamedFlow,
-    GenerateIsReachable=ownerNode
 ] interface WebKitNamedFlow : EventTarget {
     readonly attribute DOMString name;
     readonly attribute boolean overset;
diff --git a/Source/core/dom/WhitespaceChildList.h b/Source/core/dom/WhitespaceChildList.h
deleted file mode 100644
index b5a4fb1..0000000
--- a/Source/core/dom/WhitespaceChildList.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.
- *     * 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 WhitespaceChildList_h
-#define WhitespaceChildList_h
-
-#include "core/dom/Text.h"
-#include "core/rendering/style/RenderStyleConstants.h"
-
-namespace WebCore {
-
-class Text;
-
-// Tracks a limited number of whitespace text children during style recalc
-// to postpone their style recalc as part of optimization to avoid creating
-// unnecessary whitespace text renderers. If we hit the limit, it recalcs
-// the whitespace text's style and clears the list.
-class WhitespaceChildList {
-public:
-    WhitespaceChildList(StyleRecalcChange change)
-        : m_change(change)
-    { }
-
-    void append(Text* textChild)
-    {
-        ASSERT(textChild->containsOnlyWhitespace());
-        if (m_list.size() == maxWhitespaceChildrenToDefer) {
-            recalcStyle();
-            m_list.clear();
-        }
-        m_list.append(textChild);
-    }
-
-    void recalcStyle() const
-    {
-        for (unsigned i = 0; i < m_list.size(); ++i)
-            m_list[i]->recalcTextStyle(m_change);
-    }
-private:
-    StyleRecalcChange m_change;
-
-    static const unsigned maxWhitespaceChildrenToDefer = 10;
-    Vector<Text*, maxWhitespaceChildrenToDefer> m_list;
-};
-
-} // namespace WebCore
-
-#endif // WhitespaceChildList_h
diff --git a/Source/core/dom/custom/CustomElement.cpp b/Source/core/dom/custom/CustomElement.cpp
index 39dd599..eea313c 100644
--- a/Source/core/dom/custom/CustomElement.cpp
+++ b/Source/core/dom/custom/CustomElement.cpp
@@ -99,10 +99,6 @@
         ASSERT_NOT_REACHED();
         break;
 
-    case Element::WaitingForParser:
-        definitions().add(element, definition);
-        break;
-
     case Element::WaitingForUpgrade:
         definitions().add(element, definition);
         CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
@@ -117,17 +113,6 @@
     return definition;
 }
 
-void CustomElement::didFinishParsingChildren(Element* element)
-{
-    ASSERT(element->customElementState() == Element::WaitingForParser);
-    element->setCustomElementState(Element::WaitingForUpgrade);
-
-    CustomElementObserver::notifyElementDidFinishParsingChildren(element);
-
-    if (CustomElementDefinition* definition = definitions().get(element))
-        CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
-}
-
 void CustomElement::attributeDidChange(Element* element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
 {
     ASSERT(element->customElementState() == Element::Upgraded);
@@ -157,7 +142,6 @@
         ASSERT_NOT_REACHED();
         break;
 
-    case Element::WaitingForParser:
     case Element::WaitingForUpgrade:
     case Element::Upgraded:
         definitions().remove(element);
diff --git a/Source/core/dom/custom/CustomElementException.cpp b/Source/core/dom/custom/CustomElementException.cpp
index f240c86..78a01f1 100644
--- a/Source/core/dom/custom/CustomElementException.cpp
+++ b/Source/core/dom/custom/CustomElementException.cpp
@@ -41,51 +41,51 @@
     return "Failed to call 'register' on 'Document' for type '" + type + "': ";
 }
 
-void CustomElementException::throwException(Reason reason, const AtomicString& type, ExceptionState& es)
+void CustomElementException::throwException(Reason reason, const AtomicString& type, ExceptionState& exceptionState)
 {
     switch (reason) {
     case CannotRegisterFromExtension:
-        es.throwDOMException(NotSupportedError, preamble(type) + "elements cannot be registered from extensions.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "elements cannot be registered from extensions.");
         return;
 
     case ConstructorPropertyNotConfigurable:
-        es.throwDOMException(NotSupportedError, preamble(type) + "prototype constructor property is not configurable.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "prototype constructor property is not configurable.");
         return;
 
     case ContextDestroyedCheckingPrototype:
-        es.throwDOMException(InvalidStateError, preamble(type) + "the context is no longer valid.");
+        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "the context is no longer valid.");
         return;
 
     case ContextDestroyedCreatingCallbacks:
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
 
     case ContextDestroyedRegisteringDefinition:
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
 
     case ExtendsIsInvalidName:
-        es.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is not a valid tag name.");
+        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is not a valid tag name.");
         return;
 
     case ExtendsIsCustomElementName:
-        es.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is a custom element name. Use inheritance instead.");
+        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is a custom element name. Use inheritance instead.");
         return;
 
     case InvalidName:
-        es.throwDOMException(InvalidCharacterError, preamble(type) + ": '" + type + "' is not a valid name.");
+        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + ": '" + type + "' is not a valid name.");
         return;
 
     case PrototypeInUse:
-        es.throwDOMException(NotSupportedError, preamble(type) + "prototype is already in-use as an interface prototype object.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "prototype is already in-use as an interface prototype object.");
         return;
 
     case PrototypeNotAnObject:
-        es.throwDOMException(InvalidStateError, preamble(type) + "the prototype option is not an object.");
+        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "the prototype option is not an object.");
         return;
 
     case TypeAlreadyRegistered:
-        es.throwDOMException(InvalidStateError, preamble(type) + "a type with that name is already registered.");
+        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "a type with that name is already registered.");
         return;
     }
 
diff --git a/Source/core/dom/custom/CustomElementRegistrationContext.cpp b/Source/core/dom/custom/CustomElementRegistrationContext.cpp
index 44ed913..e248ab7 100644
--- a/Source/core/dom/custom/CustomElementRegistrationContext.cpp
+++ b/Source/core/dom/custom/CustomElementRegistrationContext.cpp
@@ -45,9 +45,9 @@
 
 namespace WebCore {
 
-void CustomElementRegistrationContext::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState& es)
+void CustomElementRegistrationContext::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState& exceptionState)
 {
-    CustomElementDefinition* definition = m_registry.registerElement(document, constructorBuilder, type, validNames, es);
+    CustomElementDefinition* definition = m_registry.registerElement(document, constructorBuilder, type, validNames, exceptionState);
 
     if (!definition)
         return;
@@ -58,7 +58,7 @@
         didResolveElement(definition, *it);
 }
 
-PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document& document, const QualifiedName& tagName, CreationMode mode)
+PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document& document, const QualifiedName& tagName)
 {
     ASSERT(CustomElement::isValidName(tagName.localName()));
 
@@ -73,7 +73,7 @@
         return Element::create(tagName, &document);
     }
 
-    element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
+    element->setCustomElementState(Element::WaitingForUpgrade);
     resolve(element.get(), nullAtom);
     return element.release();
 }
@@ -107,7 +107,7 @@
 
 void CustomElementRegistrationContext::didCreateUnresolvedElement(const CustomElementDescriptor& descriptor, Element* element)
 {
-    ASSERT(element->customElementState() == Element::WaitingForParser || element->customElementState() == Element::WaitingForUpgrade);
+    ASSERT(element->customElementState() == Element::WaitingForUpgrade);
     m_candidates.add(descriptor, element);
 }
 
@@ -124,7 +124,7 @@
     setTypeExtension(element, type);
 }
 
-void CustomElementRegistrationContext::setTypeExtension(Element* element, const AtomicString& type, CreationMode mode)
+void CustomElementRegistrationContext::setTypeExtension(Element* element, const AtomicString& type)
 {
     if (!element->isHTMLElement() && !element->isSVGElement())
         return;
@@ -141,7 +141,7 @@
     // Custom tags take precedence over type extensions
     ASSERT(!CustomElement::isValidName(element->localName()));
 
-    element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
+    element->setCustomElementState(Element::WaitingForUpgrade);
 
     if (CustomElementRegistrationContext* context = element->document().registrationContext())
         context->didGiveTypeExtension(element, type);
diff --git a/Source/core/dom/custom/CustomElementRegistrationContext.h b/Source/core/dom/custom/CustomElementRegistrationContext.h
index 1c933bb..97dbc5f 100644
--- a/Source/core/dom/custom/CustomElementRegistrationContext.h
+++ b/Source/core/dom/custom/CustomElementRegistrationContext.h
@@ -56,15 +56,9 @@
     // Definitions
     void registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState&);
 
-    // Instance creation
-    enum CreationMode {
-        CreatedByParser,
-        NotCreatedByParser
-    };
-
-    PassRefPtr<Element> createCustomTagElement(Document&, const QualifiedName&, CreationMode = NotCreatedByParser);
+    PassRefPtr<Element> createCustomTagElement(Document&, const QualifiedName&);
     static void setIsAttributeAndTypeExtension(Element*, const AtomicString& type);
-    static void setTypeExtension(Element*, const AtomicString& type, CreationMode = NotCreatedByParser);
+    static void setTypeExtension(Element*, const AtomicString& type);
 
 protected:
     CustomElementRegistrationContext() { }
diff --git a/Source/core/dom/custom/CustomElementRegistry.cpp b/Source/core/dom/custom/CustomElementRegistry.cpp
index acf7e0c..cbbbf64 100644
--- a/Source/core/dom/custom/CustomElementRegistry.cpp
+++ b/Source/core/dom/custom/CustomElementRegistry.cpp
@@ -58,7 +58,7 @@
     bool m_wentAway;
 };
 
-CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, CustomElement::NameSet validNames, ExceptionState& es)
+CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, CustomElement::NameSet validNames, ExceptionState& exceptionState)
 {
     // FIXME: In every instance except one it is the
     // CustomElementConstructorBuilder that observes document
@@ -69,24 +69,24 @@
     AtomicString type = userSuppliedName.lower();
 
     if (!constructorBuilder->isFeatureAllowed()) {
-        CustomElementException::throwException(CustomElementException::CannotRegisterFromExtension, type, es);
+        CustomElementException::throwException(CustomElementException::CannotRegisterFromExtension, type, exceptionState);
         return 0;
     }
 
     if (!CustomElement::isValidName(type, validNames)) {
-        CustomElementException::throwException(CustomElementException::InvalidName, type, es);
+        CustomElementException::throwException(CustomElementException::InvalidName, type, exceptionState);
         return 0;
     }
 
     QualifiedName tagName = nullQName();
-    if (!constructorBuilder->validateOptions(type, tagName, es))
+    if (!constructorBuilder->validateOptions(type, tagName, exceptionState))
         return 0;
 
     ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
 
     // FIXME: This should be done earlier in validateOptions.
     if (m_registeredTypeNames.contains(type)) {
-        CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, es);
+        CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, exceptionState);
         return 0;
     }
 
@@ -97,21 +97,21 @@
     // Consulting the constructor builder could execute script and
     // kill the document.
     if (observer.registrationContextWentAway()) {
-        CustomElementException::throwException(CustomElementException::ContextDestroyedCreatingCallbacks, type, es);
+        CustomElementException::throwException(CustomElementException::ContextDestroyedCreatingCallbacks, type, exceptionState);
         return 0;
     }
 
     const CustomElementDescriptor descriptor(type, tagName.namespaceURI(), tagName.localName());
     RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(descriptor, lifecycleCallbacks);
 
-    if (!constructorBuilder->createConstructor(document, definition.get(), es))
+    if (!constructorBuilder->createConstructor(document, definition.get(), exceptionState))
         return 0;
 
     m_definitions.add(descriptor, definition);
     m_registeredTypeNames.add(descriptor.type());
 
     if (!constructorBuilder->didRegisterDefinition(definition.get())) {
-        CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, type, es);
+        CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, type, exceptionState);
         return 0;
     }
 
diff --git a/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp b/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
index df2033f..b7ea628 100644
--- a/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
+++ b/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
@@ -70,10 +70,10 @@
 void CustomElementUpgradeCandidateMap::removeCommon(Element* element)
 {
     UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
-    ASSERT(candidate != m_upgradeCandidates.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(candidate != m_upgradeCandidates.end());
 
     UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
-    ASSERT(elements != m_unresolvedDefinitions.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(elements != m_unresolvedDefinitions.end());
     elements->value.remove(element);
     m_upgradeCandidates.remove(candidate);
 }
@@ -88,10 +88,10 @@
 void CustomElementUpgradeCandidateMap::moveToEnd(Element* element)
 {
     UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
-    ASSERT(candidate != m_upgradeCandidates.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(candidate != m_upgradeCandidates.end());
 
     UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
-    ASSERT(elements != m_unresolvedDefinitions.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(elements != m_unresolvedDefinitions.end());
     elements->value.appendOrMoveToLast(element);
 }
 
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.cpp b/Source/core/dom/shadow/ComposedTreeWalker.cpp
index b321d06..0b9dc04 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedTreeWalker.cpp
@@ -31,6 +31,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
+#include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 
 namespace WebCore {
@@ -73,7 +74,8 @@
     const InsertionPoint* insertionPoint = toInsertionPoint(node);
     if (Node* found = traverseDistributedNodes(direction == TraversalDirectionForward ? insertionPoint->first() : insertionPoint->last(), insertionPoint, direction))
         return found;
-    return traverseLightChildren(node, direction);
+    ASSERT(isHTMLShadowElement(node) || (isHTMLContentElement(node) && !node->hasChildNodes()));
+    return 0;
 }
 
 Node* ComposedTreeWalker::traverseDistributedNodes(const Node* node, const InsertionPoint* insertionPoint, TraversalDirection direction)
@@ -139,32 +141,27 @@
             // The node is distributed. But the distribution was stopped at this insertion point.
             if (shadowWhereNodeCanBeDistributed(*insertionPoint))
                 return 0;
-            return traverseParentInCurrentTree(insertionPoint, details);
+            return traverseParentOrHost(insertionPoint, details);
         }
         return 0;
     }
-    return traverseParentInCurrentTree(node, details);
+    return traverseParentOrHost(node, details);
 }
 
-inline Node* ComposedTreeWalker::traverseParentInCurrentTree(const Node* node, ParentTraversalDetails* details) const
+inline Node* ComposedTreeWalker::traverseParentOrHost(const Node* node, ParentTraversalDetails* details) const
 {
-    if (Node* parent = node->parentNode())
-        return parent->isShadowRoot() ? traverseParentBackToYoungerShadowRootOrHost(toShadowRoot(parent), details) : parent;
-    return 0;
-}
-
-Node* ComposedTreeWalker::traverseParentBackToYoungerShadowRootOrHost(const ShadowRoot* shadowRoot, ParentTraversalDetails* details) const
-{
-    ASSERT(shadowRoot);
+    Node* parent = node->parentNode();
+    if (!parent)
+        return 0;
+    if (!parent->isShadowRoot())
+        return parent;
+    ShadowRoot* shadowRoot = toShadowRoot(parent);
     ASSERT(!shadowRoot->shadowInsertionPointOfYoungerShadowRoot());
-
-    if (shadowRoot->isYoungest()) {
-        if (details)
-            details->didTraverseShadowRoot(shadowRoot);
-        return shadowRoot->host();
-    }
-
-    return 0;
+    if (!shadowRoot->isYoungest())
+        return 0;
+    if (details)
+        details->didTraverseShadowRoot(shadowRoot);
+    return shadowRoot->host();
 }
 
 } // namespace
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.h b/Source/core/dom/shadow/ComposedTreeWalker.h
index 2754913..0b1b4f0 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.h
+++ b/Source/core/dom/shadow/ComposedTreeWalker.h
@@ -107,8 +107,7 @@
 
     static Node* traverseBackToYoungerShadowRoot(const Node*, TraversalDirection);
 
-    Node* traverseParentInCurrentTree(const Node*, ParentTraversalDetails* = 0) const;
-    Node* traverseParentBackToYoungerShadowRootOrHost(const ShadowRoot*, ParentTraversalDetails* = 0) const;
+    Node* traverseParentOrHost(const Node*, ParentTraversalDetails* = 0) const;
 
     const Node* m_node;
 };
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 158addd..c4c7a68 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -40,26 +40,34 @@
 
 class DistributionPool {
 public:
-    explicit DistributionPool(const ContainerNode*);
+    explicit DistributionPool(const ContainerNode&);
+    void clear();
     ~DistributionPool();
     void distributeTo(InsertionPoint*, ElementShadow*);
+    void populateChildren(const ContainerNode&);
 
 private:
-    void populateChildren(const ContainerNode*);
     void detachNonDistributedNodes();
     Vector<Node*, 32> m_nodes;
     Vector<bool, 32> m_distributed;
 };
 
-inline DistributionPool::DistributionPool(const ContainerNode* parent)
+inline DistributionPool::DistributionPool(const ContainerNode& parent)
 {
-    if (parent)
-        populateChildren(parent);
+    populateChildren(parent);
 }
 
-inline void DistributionPool::populateChildren(const ContainerNode* parent)
+inline void DistributionPool::clear()
 {
-    for (Node* child = parent->firstChild(); child; child = child->nextSibling()) {
+    detachNonDistributedNodes();
+    m_nodes.clear();
+    m_distributed.clear();
+}
+
+inline void DistributionPool::populateChildren(const ContainerNode& parent)
+{
+    clear();
+    for (Node* child = parent.firstChild(); child; child = child->nextSibling()) {
         if (isActiveInsertionPoint(*child)) {
             InsertionPoint* insertionPoint = toInsertionPoint(child);
             for (size_t i = 0; i < insertionPoint->size(); ++i)
@@ -131,16 +139,18 @@
     removeAllShadowRoots();
 }
 
-ShadowRoot* ElementShadow::addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType type)
+ShadowRoot& ElementShadow::addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType type)
 {
     RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(&shadowHost.document(), type);
 
+    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot())
+        root->lazyReattachIfAttached();
+
     shadowRoot->setParentOrShadowHostNode(&shadowHost);
     shadowRoot->setParentTreeScope(&shadowHost.treeScope());
     m_shadowRoots.push(shadowRoot.get());
     ChildNodeInsertionNotifier(shadowHost).notify(*shadowRoot);
     setNeedsDistributionRecalc();
-    shadowHost.lazyReattachIfAttached();
 
     // 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.
@@ -149,7 +159,9 @@
     shadowHost.didAddShadowRoot(*shadowRoot);
     InspectorInstrumentation::didPushShadowRoot(&shadowHost, shadowRoot.get());
 
-    return shadowRoot.get();
+    ASSERT(m_shadowRoots.head());
+    ASSERT(shadowRoot.get() == m_shadowRoots.head());
+    return *m_shadowRoots.head();
 }
 
 void ElementShadow::removeAllShadowRoots()
@@ -193,7 +205,7 @@
 void ElementShadow::removeAllEventListeners()
 {
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
-        for (Node* node = root; node; node = NodeTraversal::next(node))
+        for (Node* node = root; node; node = NodeTraversal::next(*node))
             node->removeAllEventListeners();
     }
 }
@@ -255,13 +267,10 @@
 void ElementShadow::distribute()
 {
     host()->setNeedsStyleRecalc();
-
-    const ContainerNode* poolContainer = host();
-
     Vector<HTMLShadowElement*, 32> shadowInsertionPoints;
-    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
-        DistributionPool pool(poolContainer);
+    DistributionPool pool(*host());
 
+    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         HTMLShadowElement* shadowInsertionPoint = 0;
         const Vector<RefPtr<InsertionPoint> >& insertionPoints = root->descendantInsertionPoints();
         for (size_t i = 0; i < insertionPoints.size(); ++i) {
@@ -277,23 +286,27 @@
                     shadow->setNeedsDistributionRecalc();
             }
         }
-        if (shadowInsertionPoint)
+        if (shadowInsertionPoint) {
             shadowInsertionPoints.append(shadowInsertionPoint);
-        poolContainer = shadowInsertionPoint;
+            if (shadowInsertionPoint->hasChildNodes())
+                pool.populateChildren(*shadowInsertionPoint);
+        } else {
+            pool.clear();
+        }
     }
 
     for (size_t i = shadowInsertionPoints.size(); i > 0; --i) {
         HTMLShadowElement* shadowInsertionPoint = shadowInsertionPoints[i - 1];
         ShadowRoot* root = shadowInsertionPoint->containingShadowRoot();
         ASSERT(root);
-        if (root->olderShadowRoot() && root->olderShadowRoot()->type() == root->type()) {
+        if (root->isOldest()) {
+            pool.distributeTo(shadowInsertionPoint, this);
+        } else if (root->olderShadowRoot()->type() == root->type()) {
             // Only allow reprojecting older shadow roots between the same type to
             // disallow reprojecting UA elements into author shadows.
-            distributeNodeChildrenTo(shadowInsertionPoint, root->olderShadowRoot());
+            DistributionPool olderShadowRootPool(*root->olderShadowRoot());
+            olderShadowRootPool.distributeTo(shadowInsertionPoint, this);
             root->olderShadowRoot()->setShadowInsertionPointOfYoungerShadowRoot(shadowInsertionPoint);
-        } else if (root->isOldest()) {
-            DistributionPool pool(shadowInsertionPoint);
-            pool.distributeTo(shadowInsertionPoint, this);
         }
         if (ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*shadowInsertionPoint))
             shadow->setNeedsDistributionRecalc();
@@ -306,12 +319,6 @@
     result.iterator->value.append(insertionPoint);
 }
 
-void ElementShadow::distributeNodeChildrenTo(InsertionPoint* insertionPoint, ContainerNode* containerNode)
-{
-    DistributionPool pool(containerNode);
-    pool.distributeTo(insertionPoint, this);
-}
-
 const SelectRuleFeatureSet& ElementShadow::ensureSelectFeatureSet()
 {
     if (!m_needsSelectFeatureSet)
@@ -319,17 +326,17 @@
 
     m_selectFeatures.clear();
     for (ShadowRoot* root = oldestShadowRoot(); root; root = root->youngerShadowRoot())
-        collectSelectFeatureSetFrom(root);
+        collectSelectFeatureSetFrom(*root);
     m_needsSelectFeatureSet = false;
     return m_selectFeatures;
 }
 
-void ElementShadow::collectSelectFeatureSetFrom(ShadowRoot* root)
+void ElementShadow::collectSelectFeatureSetFrom(ShadowRoot& root)
 {
-    if (!root->containsShadowRoots() && !root->containsContentElements())
+    if (!root.containsShadowRoots() && !root.containsContentElements())
         return;
 
-    for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(element, root)) {
+    for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(*element, &root)) {
         if (ElementShadow* shadow = element->shadow())
             m_selectFeatures.add(shadow->ensureSelectFeatureSet());
         if (!isHTMLContentElement(element))
diff --git a/Source/core/dom/shadow/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
index bab1c23..9017ddc 100644
--- a/Source/core/dom/shadow/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -50,7 +50,7 @@
     ShadowRoot* oldestShadowRoot() const { return m_shadowRoots.tail(); }
     ElementShadow* containingShadow() const;
 
-    ShadowRoot* addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType);
+    ShadowRoot& addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType);
 
     bool applyAuthorStyles() const { return m_applyAuthorStyles; }
     bool didAffectApplyAuthorStyles();
@@ -82,7 +82,7 @@
     void distribute();
     void clearDistribution();
 
-    void collectSelectFeatureSetFrom(ShadowRoot*);
+    void collectSelectFeatureSetFrom(ShadowRoot&);
     void distributeNodeChildrenTo(InsertionPoint*, ContainerNode*);
 
     bool needsSelectFeatureSet() const { return m_needsSelectFeatureSet; }
@@ -106,9 +106,14 @@
 
 inline ShadowRoot* Node::youngestShadowRoot() const
 {
-    if (!this->isElementNode())
+    if (!isElementNode())
         return 0;
-    if (ElementShadow* shadow = toElement(this)->shadow())
+    return toElement(this)->youngestShadowRoot();
+}
+
+inline ShadowRoot* Element::youngestShadowRoot() const
+{
+    if (ElementShadow* shadow = this->shadow())
         return shadow->youngestShadowRoot();
     return 0;
 }
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index a1bb7db..f671b91 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -100,8 +100,10 @@
 
 void InsertionPoint::attach(const AttachContext& context)
 {
-    // FIXME: This loop shouldn't be needed since the distributed nodes should
-    // never be detached, we can probably remove it.
+    // We need to attach the distribution here so that they're inserted in the right order
+    // otherwise the n^2 protection inside NodeRenderingContext will cause them to be
+    // inserted in the wrong place later. This also lets distributed nodes benefit from
+    // the n^2 protection.
     for (size_t i = 0; i < m_distribution.size(); ++i) {
         if (m_distribution.at(i)->needsAttach())
             m_distribution.at(i)->attach(context);
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index 95865b8..58d6823 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -34,7 +34,6 @@
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/StyleEngine.h"
 #include "core/dom/Text.h"
-#include "core/dom/WhitespaceChildList.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRootRareData.h"
@@ -66,14 +65,14 @@
     , m_resetStyleInheritance(false)
     , m_type(type)
     , m_registeredWithParentShadowRoot(false)
-    , m_childInsertionPointsIsValid(false)
+    , m_descendantInsertionPointsIsValid(false)
 {
     ASSERT(document);
     ScriptWrappable::init(this);
 
     if (type == ShadowRoot::AuthorShadowRoot) {
         ShadowRootUsageOriginType usageType = document->url().protocolIsInHTTPFamily() ? ShadowRootUsageOriginWeb : ShadowRootUsageOriginNotWeb;
-        WebKit::Platform::current()->histogramEnumeration("WebCore.ShadowRoot.constructor", usageType, ShadowRootUsageOriginMax);
+        blink::Platform::current()->histogramEnumeration("WebCore.ShadowRoot.constructor", usageType, ShadowRootUsageOriginMax);
     }
 }
 
@@ -127,9 +126,9 @@
     return true;
 }
 
-PassRefPtr<Node> ShadowRoot::cloneNode(bool, ExceptionState& es)
+PassRefPtr<Node> ShadowRoot::cloneNode(bool, ExceptionState& exceptionState)
 {
-    es.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("cloneNode", "ShadowRoot", "ShadowRoot nodes are not clonable."));
+    exceptionState.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("cloneNode", "ShadowRoot", "ShadowRoot nodes are not clonable."));
     return 0;
 }
 
@@ -138,15 +137,15 @@
     return createMarkup(this, ChildrenOnly);
 }
 
-void ShadowRoot::setInnerHTML(const String& markup, ExceptionState& es)
+void ShadowRoot::setInnerHTML(const String& markup, ExceptionState& exceptionState)
 {
     if (isOrphan()) {
-        es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("setInnerHTML", "ShadowRoot", "The ShadowRoot does not have a host."));
+        exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("setInnerHTML", "ShadowRoot", "The ShadowRoot does not have a host."));
         return;
     }
 
-    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), AllowScriptingContent, "innerHTML", es))
-        replaceChildrenWithFragment(this, fragment.release(), es);
+    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), AllowScriptingContent, "innerHTML", exceptionState))
+        replaceChildrenWithFragment(this, fragment.release(), exceptionState);
 }
 
 bool ShadowRoot::childTypeAllowed(NodeType type) const
@@ -171,32 +170,29 @@
     StyleResolver* styleResolver = document().styleResolver();
     styleResolver->pushParentShadowRoot(*this);
 
-    // When we're set to lazyAttach we'll have a SubtreeStyleChange and we'll need
-    // to promote the change to a Force for all our descendants so they get a
-    // recalc and will attach.
     if (styleChangeType() >= SubtreeStyleChange)
         change = Force;
 
+    // There's no style to update so just calling recalcStyle means we're updated.
+    clearNeedsStyleRecalc();
+
     // FIXME: This doesn't handle :hover + div properly like Element::recalcStyle does.
-    WhitespaceChildList whitespaceChildList(change);
+    Text* lastTextNode = 0;
     for (Node* child = lastChild(); child; child = child->previousSibling()) {
         if (child->isTextNode()) {
-            Text* textChild = toText(child);
-            if (textChild->containsOnlyWhitespace())
-                whitespaceChildList.append(textChild);
-            else
-                textChild->recalcTextStyle(change);
-        } else if (child->isElementNode() && shouldRecalcStyle(change, child)) {
-            toElement(child)->recalcStyle(change);
+            toText(child)->recalcTextStyle(change, lastTextNode);
+            lastTextNode = toText(child);
+        } else if (child->isElementNode()) {
+            if (shouldRecalcStyle(change, child))
+                toElement(child)->recalcStyle(change, lastTextNode);
+            if (child->renderer())
+                lastTextNode = 0;
         }
     }
 
-    whitespaceChildList.recalcStyle();
-
     styleResolver->popParentShadowRoot(*this);
-    clearNeedsStyleRecalc();
+
     clearChildNeedsStyleRecalc();
-    setAttached();
 }
 
 bool ShadowRoot::isActive() const
@@ -212,7 +208,7 @@
     if (isOrphan())
         return;
 
-    if (m_applyAuthorStyles == value)
+    if (applyAuthorStyles() == value)
         return;
 
     m_applyAuthorStyles = value;
@@ -238,7 +234,7 @@
     if (isOrphan())
         return;
 
-    if (value == m_resetStyleInheritance)
+    if (value == resetStyleInheritance())
         return;
 
     m_resetStyleInheritance = value;
@@ -357,13 +353,13 @@
 void ShadowRoot::didAddInsertionPoint(InsertionPoint* insertionPoint)
 {
     ensureShadowRootRareData()->didAddInsertionPoint(insertionPoint);
-    invalidateChildInsertionPoints();
+    invalidateDescendantInsertionPoints();
 }
 
 void ShadowRoot::didRemoveInsertionPoint(InsertionPoint* insertionPoint)
 {
     m_shadowRootRareData->didRemoveInsertionPoint(insertionPoint);
-    invalidateChildInsertionPoints();
+    invalidateDescendantInsertionPoints();
 }
 
 void ShadowRoot::addChildShadowRoot()
@@ -384,9 +380,9 @@
     return m_shadowRootRareData ? m_shadowRootRareData->childShadowRootCount() : 0;
 }
 
-void ShadowRoot::invalidateChildInsertionPoints()
+void ShadowRoot::invalidateDescendantInsertionPoints()
 {
-    m_childInsertionPointsIsValid = false;
+    m_descendantInsertionPointsIsValid = false;
     m_shadowRootRareData->clearDescendantInsertionPoints();
 }
 
@@ -394,16 +390,16 @@
 {
     DEFINE_STATIC_LOCAL(const Vector<RefPtr<InsertionPoint> >, emptyList, ());
 
-    if (m_shadowRootRareData && m_childInsertionPointsIsValid)
+    if (m_shadowRootRareData && m_descendantInsertionPointsIsValid)
         return m_shadowRootRareData->descendantInsertionPoints();
 
-    m_childInsertionPointsIsValid = true;
+    m_descendantInsertionPointsIsValid = true;
 
     if (!containsInsertionPoints())
         return emptyList;
 
     Vector<RefPtr<InsertionPoint> > insertionPoints;
-    for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element, this)) {
+    for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element, this)) {
         if (element->isInsertionPoint())
             insertionPoints.append(toInsertionPoint(element));
     }
diff --git a/Source/core/dom/shadow/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
index 876dcbf..768f78b 100644
--- a/Source/core/dom/shadow/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -115,7 +115,7 @@
     void setInnerHTML(const String&, ExceptionState&);
 
     PassRefPtr<Node> cloneNode(bool, ExceptionState&);
-    PassRefPtr<Node> cloneNode(ExceptionState& es) { return cloneNode(true, es); }
+    PassRefPtr<Node> cloneNode(ExceptionState& exceptionState) { return cloneNode(true, exceptionState); }
 
     StyleSheetList* styleSheets();
 
@@ -131,7 +131,7 @@
 
     void addChildShadowRoot();
     void removeChildShadowRoot();
-    void invalidateChildInsertionPoints();
+    void invalidateDescendantInsertionPoints();
 
     // ShadowRoots should never be cloned.
     virtual PassRefPtr<Node> cloneNode(bool) OVERRIDE { return 0; }
@@ -148,14 +148,12 @@
     unsigned m_resetStyleInheritance : 1;
     unsigned m_type : 1;
     unsigned m_registeredWithParentShadowRoot : 1;
-    unsigned m_childInsertionPointsIsValid : 1;
+    unsigned m_descendantInsertionPointsIsValid : 1;
 };
 
 inline Element* ShadowRoot::activeElement() const
 {
-    if (Element* element = treeScope().adjustedFocusedElement())
-        return element;
-    return 0;
+    return adjustedFocusedElement();
 }
 
 inline const ShadowRoot* toShadowRoot(const Node* node)
diff --git a/Source/core/dom/shadow/ShadowRoot.idl b/Source/core/dom/shadow/ShadowRoot.idl
index fd06913..c84d177 100644
--- a/Source/core/dom/shadow/ShadowRoot.idl
+++ b/Source/core/dom/shadow/ShadowRoot.idl
@@ -32,7 +32,7 @@
     attribute boolean resetStyleInheritance;
     [RuntimeEnabled=ShadowDOM, ImplementedAs=bindingsOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
 
-    [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
+    [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
 
     [RaisesException] Node cloneNode([Default=Undefined] optional boolean deep);
     Selection getSelection();
diff --git a/Source/core/editing/ApplyBlockElementCommand.cpp b/Source/core/editing/ApplyBlockElementCommand.cpp
index 5c4166d..9eada42 100644
--- a/Source/core/editing/ApplyBlockElementCommand.cpp
+++ b/Source/core/editing/ApplyBlockElementCommand.cpp
@@ -159,9 +159,9 @@
     if (!textNode || !textNode->isTextNode() || offset < 0 || offset >= textNode->maxCharacterOffset())
         return false;
 
-    TrackExceptionState es;
-    String textAtPosition = toText(textNode)->substringData(offset, 1, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    String textAtPosition = toText(textNode)->substringData(offset, 1, exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     return textAtPosition[0] == '\n';
diff --git a/Source/core/editing/ApplyStyleCommand.cpp b/Source/core/editing/ApplyStyleCommand.cpp
index f221f34..bdb2dec 100644
--- a/Source/core/editing/ApplyStyleCommand.cpp
+++ b/Source/core/editing/ApplyStyleCommand.cpp
@@ -351,26 +351,27 @@
     // an ancestor of the start node), we gather nodes up to the next sibling of the end node
     Node *beyondEnd;
     if (start.deprecatedNode()->isDescendantOf(end.deprecatedNode()))
-        beyondEnd = NodeTraversal::nextSkippingChildren(end.deprecatedNode());
+        beyondEnd = NodeTraversal::nextSkippingChildren(*end.deprecatedNode());
     else
-        beyondEnd = NodeTraversal::next(end.deprecatedNode());
+        beyondEnd = NodeTraversal::next(*end.deprecatedNode());
 
     start = start.upstream(); // Move upstream to ensure we do not add redundant spans.
     Node* startNode = start.deprecatedNode();
+    ASSERT(startNode);
     if (startNode->isTextNode() && start.deprecatedEditingOffset() >= caretMaxOffset(startNode)) // Move out of text node if range does not include its characters.
-        startNode = NodeTraversal::next(startNode);
+        startNode = NodeTraversal::next(*startNode);
 
     // Store away font size before making any changes to the document.
     // This ensures that changes to one node won't effect another.
     HashMap<Node*, float> startingFontSizes;
-    for (Node *node = startNode; node != beyondEnd; node = NodeTraversal::next(node))
+    for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(*node))
         startingFontSizes.set(node, computedFontSize(node));
 
     // These spans were added by us. If empty after font size changes, they can be removed.
     Vector<RefPtr<HTMLElement> > unstyledSpans;
 
     Node* lastStyledNode = 0;
-    for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(node)) {
+    for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(*node)) {
         RefPtr<HTMLElement> element;
         if (node->isHTMLElement()) {
             // Only work on fully selected nodes.
@@ -435,7 +436,6 @@
         next = node->nextSibling();
         if (isSpanWithoutAttributesOrUnstyledStyleSpan(node))
             removeNodePreservingChildren(node);
-        node = next;
     }
 }
 
@@ -672,21 +672,22 @@
 void ApplyStyleCommand::fixRangeAndApplyInlineStyle(EditingStyle* style, const Position& start, const Position& end)
 {
     Node* startNode = start.deprecatedNode();
+    ASSERT(startNode);
 
     if (start.deprecatedEditingOffset() >= caretMaxOffset(start.deprecatedNode())) {
-        startNode = NodeTraversal::next(startNode);
+        startNode = NodeTraversal::next(*startNode);
         if (!startNode || comparePositions(end, firstPositionInOrBeforeNode(startNode)) < 0)
             return;
     }
 
     Node* pastEndNode = end.deprecatedNode();
     if (end.deprecatedEditingOffset() >= caretMaxOffset(end.deprecatedNode()))
-        pastEndNode = NodeTraversal::nextSkippingChildren(end.deprecatedNode());
+        pastEndNode = NodeTraversal::nextSkippingChildren(*end.deprecatedNode());
 
     // FIXME: Callers should perform this operation on a Range that includes the br
     // if they want style applied to the empty line.
     if (start == end && start.deprecatedNode()->hasTagName(brTag))
-        pastEndNode = NodeTraversal::next(start.deprecatedNode());
+        pastEndNode = NodeTraversal::next(*start.deprecatedNode());
 
     // Start from the highest fully selected ancestor so that we can modify the fully selected node.
     // e.g. When applying font-size: large on <font color="blue">hello</font>, we need to include the font element in our run
@@ -701,13 +702,13 @@
     applyInlineStyleToNodeRange(style, startNode, pastEndNode);
 }
 
-static bool containsNonEditableRegion(Node* node)
+static bool containsNonEditableRegion(Node& node)
 {
-    if (!node->rendererIsEditable())
+    if (!node.rendererIsEditable())
         return true;
 
     Node* sibling = NodeTraversal::nextSkippingChildren(node);
-    for (Node* descendent = node->firstChild(); descendent && descendent != sibling; descendent = NodeTraversal::next(descendent)) {
+    for (Node* descendent = node.firstChild(); descendent && descendent != sibling; descendent = NodeTraversal::next(*descendent)) {
         if (!descendent->rendererIsEditable())
             return true;
     }
@@ -747,7 +748,7 @@
     Vector<InlineRunToApplyStyle> runs;
     RefPtr<Node> node = startNode;
     for (RefPtr<Node> next; node && node != pastEndNode; node = next) {
-        next = NodeTraversal::next(node.get());
+        next = NodeTraversal::next(*node);
 
         if (!node->renderer() || !node->rendererIsEditable())
             continue;
@@ -760,7 +761,7 @@
                 break;
             // Add to this element's inline style and skip over its contents.
             HTMLElement* element = toHTMLElement(node);
-            next = NodeTraversal::nextSkippingChildren(node.get());
+            next = NodeTraversal::nextSkippingChildren(*node);
             if (!style->style())
                 continue;
             RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
@@ -773,10 +774,10 @@
             continue;
 
         if (node->childNodeCount()) {
-            if (node->contains(pastEndNode.get()) || containsNonEditableRegion(node.get()) || !node->parentNode()->rendererIsEditable())
+            if (node->contains(pastEndNode.get()) || containsNonEditableRegion(*node) || !node->parentNode()->rendererIsEditable())
                 continue;
             if (editingIgnoresContent(node.get())) {
-                next = NodeTraversal::nextSkippingChildren(node.get());
+                next = NodeTraversal::nextSkippingChildren(*node);
                 continue;
             }
         }
@@ -785,14 +786,15 @@
         Node* runEnd = node.get();
         Node* sibling = node->nextSibling();
         while (sibling && sibling != pastEndNode && !sibling->contains(pastEndNode.get())
-               && (!isBlock(sibling) || sibling->hasTagName(brTag))
-               && !containsNonEditableRegion(sibling)) {
+            && (!isBlock(sibling) || sibling->hasTagName(brTag))
+            && !containsNonEditableRegion(*sibling)) {
             runEnd = sibling;
             sibling = runEnd->nextSibling();
         }
-        next = NodeTraversal::nextSkippingChildren(runEnd);
+        ASSERT(runEnd);
+        next = NodeTraversal::nextSkippingChildren(*runEnd);
 
-        Node* pastEndNode = NodeTraversal::nextSkippingChildren(runEnd);
+        Node* pastEndNode = NodeTraversal::nextSkippingChildren(*runEnd);
         if (!shouldApplyInlineStyleToRun(style, runStart, pastEndNode))
             continue;
 
@@ -828,7 +830,7 @@
 {
     ASSERT(style && runStart);
 
-    for (Node* node = runStart; node && node != pastEndNode; node = NodeTraversal::next(node)) {
+    for (Node* node = runStart; node && node != pastEndNode; node = NodeTraversal::next(*node)) {
         if (node->childNodeCount())
             continue;
         // We don't consider m_isInlineElementToRemoveFunction here because we never apply style when m_isInlineElementToRemoveFunction is specified
@@ -847,9 +849,10 @@
     for (RefPtr<Node> node = next; node && node->inDocument() && node != pastEndNode; node = next) {
         if (editingIgnoresContent(node.get())) {
             ASSERT(!node->contains(pastEndNode.get()));
-            next = NodeTraversal::nextSkippingChildren(node.get());
-        } else
-            next = NodeTraversal::next(node.get());
+            next = NodeTraversal::nextSkippingChildren(*node);
+        } else {
+            next = NodeTraversal::next(*node);
+        }
         if (!node->isHTMLElement())
             continue;
 
@@ -1106,14 +1109,14 @@
         RefPtr<Node> next;
         if (editingIgnoresContent(node.get())) {
             ASSERT(node == end.deprecatedNode() || !node->contains(end.deprecatedNode()));
-            next = NodeTraversal::nextSkippingChildren(node.get());
+            next = NodeTraversal::nextSkippingChildren(*node);
         } else {
-            next = NodeTraversal::next(node.get());
+            next = NodeTraversal::next(*node);
         }
         if (node->isHTMLElement() && nodeFullySelected(node.get(), start, end)) {
             RefPtr<HTMLElement> elem = toHTMLElement(node);
-            RefPtr<Node> prev = NodeTraversal::previousPostOrder(elem.get());
-            RefPtr<Node> next = NodeTraversal::next(elem.get());
+            RefPtr<Node> prev = NodeTraversal::previousPostOrder(*elem);
+            RefPtr<Node> next = NodeTraversal::next(*elem);
             RefPtr<EditingStyle> styleToPushDown;
             RefPtr<Node> childNode;
             if (isStyledInlineElementToRemove(elem.get())) {
diff --git a/Source/core/editing/BreakBlockquoteCommand.cpp b/Source/core/editing/BreakBlockquoteCommand.cpp
index 9064923..73f09d9 100644
--- a/Source/core/editing/BreakBlockquoteCommand.cpp
+++ b/Source/core/editing/BreakBlockquoteCommand.cpp
@@ -105,18 +105,19 @@
 
     // startNode is the first node that we need to move to the new blockquote.
     Node* startNode = pos.deprecatedNode();
+    ASSERT(startNode);
 
     // Split at pos if in the middle of a text node.
     if (startNode->isTextNode()) {
         Text* textNode = toText(startNode);
         if ((unsigned)pos.deprecatedEditingOffset() >= textNode->length()) {
-            startNode = NodeTraversal::next(startNode);
+            startNode = NodeTraversal::next(*startNode);
             ASSERT(startNode);
         } else if (pos.deprecatedEditingOffset() > 0)
             splitTextNode(textNode, pos.deprecatedEditingOffset());
     } else if (pos.deprecatedEditingOffset() > 0) {
         Node* childAtOffset = startNode->childNode(pos.deprecatedEditingOffset());
-        startNode = childAtOffset ? childAtOffset : NodeTraversal::next(startNode);
+        startNode = childAtOffset ? childAtOffset : NodeTraversal::next(*startNode);
         ASSERT(startNode);
     }
 
@@ -150,7 +151,7 @@
             while (listChildNode && !listChildNode->hasTagName(liTag))
                 listChildNode = listChildNode->nextSibling();
             if (listChildNode && listChildNode->renderer() && listChildNode->renderer()->isListItem())
-                setNodeAttribute(clonedChild, startAttr, String::number(toRenderListItem(listChildNode->renderer())->value()));
+                setNodeAttribute(clonedChild, startAttr, AtomicString::number(toRenderListItem(listChildNode->renderer())->value()));
         }
 
         appendNode(clonedChild.get(), clonedAncestor.get());
diff --git a/Source/core/editing/Caret.cpp b/Source/core/editing/Caret.cpp
index 21de4d2..4501cc8 100644
--- a/Source/core/editing/Caret.cpp
+++ b/Source/core/editing/Caret.cpp
@@ -35,11 +35,6 @@
 
 namespace WebCore {
 
-static inline LayoutUnit NoXPosForVerticalArrowNavigation()
-{
-    return LayoutUnit::min();
-}
-
 CaretBase::CaretBase(CaretVisibility visibility)
     : m_caretRectNeedsUpdate(true)
     , m_caretVisibility(visibility)
@@ -93,23 +88,15 @@
     return element.containsIncludingShadowDOM(position.anchorNode());
 }
 
-static void clearRenderViewSelection(const Position& position)
-{
-    RefPtr<Document> document = position.document();
-    document->updateStyleIfNeeded();
-    if (RenderView* view = document->renderView())
-        view->clearSelection();
-}
-
 void DragCaretController::nodeWillBeRemoved(Node& node)
 {
-    if (!hasCaret() || !node.inDocument())
+    if (!hasCaret() || !node.inActiveDocument())
         return;
 
     if (!removingNodeRemovesPosition(node, m_position.deepEquivalent()))
         return;
 
-    clearRenderViewSelection(m_position.deepEquivalent());
+    m_position.deepEquivalent().document()->renderView()->clearSelection();
     clear();
 }
 
@@ -120,7 +107,7 @@
 
 static inline bool caretRendersInsideNode(Node* node)
 {
-    return node && !isTableElement(node) && !editingIgnoresContent(node);
+    return node && !isRenderedTable(node) && !editingIgnoresContent(node);
 }
 
 RenderObject* CaretBase::caretRenderer(Node* node)
diff --git a/Source/core/editing/CompositeEditCommand.cpp b/Source/core/editing/CompositeEditCommand.cpp
index ae7cebf..b70cb53 100644
--- a/Source/core/editing/CompositeEditCommand.cpp
+++ b/Source/core/editing/CompositeEditCommand.cpp
@@ -73,6 +73,24 @@
 
 using namespace HTMLNames;
 
+namespace {
+class ReentrancyGuard {
+public:
+    static bool isRecursiveCall() { return s_nestingCounter; }
+
+    class Scope {
+    public:
+        Scope() { ++s_nestingCounter; }
+        ~Scope() { --s_nestingCounter; }
+    };
+    friend class Scope;
+
+private:
+    static int s_nestingCounter;
+};
+int ReentrancyGuard::s_nestingCounter;
+}
+
 PassRefPtr<EditCommandComposition> EditCommandComposition::create(Document* document,
     const VisibleSelection& startingSelection, const VisibleSelection& endingSelection, EditAction editAction)
 {
@@ -158,6 +176,14 @@
 
 void CompositeEditCommand::apply()
 {
+    // We don't allow recusrive |apply()| to protect against attack code.
+    // Recursive call of |apply()| could be happened by moving iframe
+    // with script triggered by insertion, e.g. <iframe src="javascript:...">
+    // <iframe onload="...">. This usage is valid as of the specification
+    // although, it isn't common use case, rather it is used as attack code.
+    if (ReentrancyGuard::isRecursiveCall())
+        return;
+
     if (!endingSelection().isContentRichlyEditable()) {
         switch (editingAction()) {
         case EditActionTyping:
@@ -182,7 +208,8 @@
     Frame* frame = document().frame();
     ASSERT(frame);
     {
-        EventQueueScope scope;
+        EventQueueScope eventQueueScope;
+        ReentrancyGuard::Scope reentrancyGuardScope;
         doApply();
     }
 
@@ -797,7 +824,7 @@
         return;
 
     Vector<RefPtr<Text> > nodes;
-    for (Node* node = start.deprecatedNode(); node; node = NodeTraversal::next(node)) {
+    for (Node* node = start.deprecatedNode(); node; node = NodeTraversal::next(*node)) {
         if (node->isTextNode())
             nodes.append(toText(node));
         if (node == end.deprecatedNode())
@@ -981,7 +1008,7 @@
         appendNode(lastNode, blockElement);
     }
 
-    if (start.deprecatedNode() != outerNode && lastNode->isElementNode()) {
+    if (start.anchorNode() != outerNode && lastNode->isElementNode() && start.anchorNode()->isDescendantOf(outerNode.get())) {
         Vector<RefPtr<Node> > ancestors;
 
         // Insert each node from innerNode to outerNode (excluded) in a list.
@@ -998,6 +1025,11 @@
         }
     }
 
+    // Scripts specified in javascript protocol may remove |outerNode|
+    // during insertion, e.g. <iframe src="javascript:...">
+    if (!outerNode->inDocument())
+        return;
+
     // Handle the case of paragraphs with more than one node,
     // cloning all the siblings until end.deprecatedNode() is reached.
 
@@ -1010,7 +1042,7 @@
         }
 
         RefPtr<Node> startNode = start.deprecatedNode();
-        for (RefPtr<Node> node = NodeTraversal::nextSkippingChildren(startNode.get(), outerNode.get()); node; node = NodeTraversal::nextSkippingChildren(node.get(), outerNode.get())) {
+        for (RefPtr<Node> node = NodeTraversal::nextSkippingChildren(*startNode, outerNode.get()); node; node = NodeTraversal::nextSkippingChildren(*node, outerNode.get())) {
             // Move lastNode up in the tree as much as node was moved up in the
             // tree by NodeTraversal::nextSkippingChildren, so that the relative depth between
             // node and the original start node is maintained in the clone.
@@ -1117,7 +1149,7 @@
     beforeParagraph = VisiblePosition(beforeParagraph.deepEquivalent());
     afterParagraph = VisiblePosition(afterParagraph.deepEquivalent());
 
-    if (beforeParagraph.isNotNull() && !isTableElement(beforeParagraph.deepEquivalent().deprecatedNode())
+    if (beforeParagraph.isNotNull() && !isRenderedTable(beforeParagraph.deepEquivalent().deprecatedNode())
         && ((!isEndOfParagraph(beforeParagraph) && !isStartOfParagraph(beforeParagraph)) || beforeParagraph == afterParagraph)) {
         // FIXME: Trim text between beforeParagraph and afterParagraph if they aren't equal.
         insertNodeAt(createBreakElement(document()), beforeParagraph.deepEquivalent());
diff --git a/Source/core/editing/DeleteFromTextNodeCommand.cpp b/Source/core/editing/DeleteFromTextNodeCommand.cpp
index 2ca40f0..bbecace 100644
--- a/Source/core/editing/DeleteFromTextNodeCommand.cpp
+++ b/Source/core/editing/DeleteFromTextNodeCommand.cpp
@@ -51,12 +51,12 @@
     if (!m_node->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable))
         return;
 
-    TrackExceptionState es;
-    m_text = m_node->substringData(m_offset, m_count, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    m_text = m_node->substringData(m_offset, m_count, exceptionState);
+    if (exceptionState.hadException())
         return;
 
-    m_node->deleteData(m_offset, m_count, es, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
+    m_node->deleteData(m_offset, m_count, exceptionState, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 }
 
 void DeleteFromTextNodeCommand::doUnapply()
diff --git a/Source/core/editing/DeleteSelectionCommand.cpp b/Source/core/editing/DeleteSelectionCommand.cpp
index 8b07307..ce27bb7 100644
--- a/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/Source/core/editing/DeleteSelectionCommand.cpp
@@ -337,7 +337,7 @@
     ASSERT(node);
     Node* next = node;
     while (next && !next->rendererIsEditable())
-        next = NodeTraversal::next(next, node);
+        next = NodeTraversal::next(*next, node);
     return next ? firstPositionInOrBeforeNode(next) : Position();
 }
 
@@ -429,9 +429,9 @@
     RefPtr<Range> range = m_selectionToDelete.toNormalizedRange();
     RefPtr<Node> node = range->firstNode();
     while (node && node != range->pastLastNode()) {
-        RefPtr<Node> nextNode = NodeTraversal::next(node.get());
+        RefPtr<Node> nextNode = NodeTraversal::next(*node);
         if ((node->hasTagName(styleTag) && !(toElement(node)->hasAttribute(scopedAttr))) || node->hasTagName(linkTag)) {
-            nextNode = NodeTraversal::nextSkippingChildren(node.get());
+            nextNode = NodeTraversal::nextSkippingChildren(*node);
             RefPtr<ContainerNode> rootEditableElement = node->rootEditableElement();
             if (rootEditableElement.get()) {
                 removeNode(node);
@@ -449,13 +449,14 @@
 
     int startOffset = m_upstreamStart.deprecatedEditingOffset();
     Node* startNode = m_upstreamStart.deprecatedNode();
+    ASSERT(startNode);
 
     makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss();
 
     // Never remove the start block unless it's a table, in which case we won't merge content in.
     if (startNode->isSameNode(m_startBlock.get()) && !startOffset && canHaveChildrenForEditing(startNode) && !isHTMLTableElement(startNode)) {
         startOffset = 0;
-        startNode = NodeTraversal::next(startNode);
+        startNode = NodeTraversal::next(*startNode);
         if (!startNode)
             return;
     }
@@ -467,7 +468,7 @@
     }
 
     if (startOffset >= lastOffsetForEditing(startNode)) {
-        startNode = NodeTraversal::nextSkippingChildren(startNode);
+        startNode = NodeTraversal::nextSkippingChildren(*startNode);
         startOffset = 0;
     }
 
@@ -501,7 +502,7 @@
                 // in a text node that needs to be trimmed
                 Text* text = toText(node);
                 deleteTextFromNode(text, startOffset, text->length() - startOffset);
-                node = NodeTraversal::next(node.get());
+                node = NodeTraversal::next(*node);
             } else {
                 node = startNode->childNode(startOffset);
             }
@@ -516,7 +517,7 @@
                 // NodeTraversal::nextSkippingChildren just blew past the end position, so stop deleting
                 node = 0;
             } else if (!m_downstreamEnd.deprecatedNode()->isDescendantOf(node.get())) {
-                RefPtr<Node> nextNode = NodeTraversal::nextSkippingChildren(node.get());
+                RefPtr<Node> nextNode = NodeTraversal::nextSkippingChildren(*node);
                 // if we just removed a node from the end container, update end position so the
                 // check above will work
                 updatePositionForNodeRemoval(m_downstreamEnd, node.get());
@@ -527,8 +528,9 @@
                 if (m_downstreamEnd.deprecatedNode() == n && m_downstreamEnd.deprecatedEditingOffset() >= caretMaxOffset(&n)) {
                     removeNode(node.get());
                     node = 0;
-                } else
-                    node = NodeTraversal::next(node.get());
+                } else {
+                    node = NodeTraversal::next(*node);
+                }
             }
         }
 
diff --git a/Source/core/editing/EditingBehavior.h b/Source/core/editing/EditingBehavior.h
index 395ebe6..ec1a775 100644
--- a/Source/core/editing/EditingBehavior.h
+++ b/Source/core/editing/EditingBehavior.h
@@ -83,6 +83,13 @@
     // should not be selected and the cursor should be placed where the deletion started.
     bool shouldUndoOfDeleteSelectText() const { return m_type == EditingMacBehavior; }
 
+    // Support for global selections, used on platforms like the X Window
+    // System that treat selection as a type of clipboard.
+    bool supportsGlobalSelection() const
+    {
+        return m_type != EditingWindowsBehavior && m_type != EditingMacBehavior;
+    }
+
 private:
     EditingBehaviorType m_type;
 };
diff --git a/Source/core/editing/EditingStyle.cpp b/Source/core/editing/EditingStyle.cpp
index 3588196..57b2332 100644
--- a/Source/core/editing/EditingStyle.cpp
+++ b/Source/core/editing/EditingStyle.cpp
@@ -712,7 +712,7 @@
 
     TriState state = FalseTriState;
     bool nodeIsStart = true;
-    for (Node* node = selection.start().deprecatedNode(); node; node = NodeTraversal::next(node)) {
+    for (Node* node = selection.start().deprecatedNode(); node; node = NodeTraversal::next(*node)) {
         if (node->renderer() && node->rendererIsEditable()) {
             RefPtr<CSSComputedStyleDeclaration> nodeStyle = CSSComputedStyleDeclaration::create(node);
             if (nodeStyle) {
@@ -1091,14 +1091,14 @@
 
 static void mergeTextDecorationValues(CSSValueList* mergedValue, const CSSValueList* valueToMerge)
 {
-    DEFINE_STATIC_LOCAL(const RefPtr<CSSPrimitiveValue>, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
-    DEFINE_STATIC_LOCAL(const RefPtr<CSSPrimitiveValue>, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
+    DEFINE_STATIC_REF(CSSPrimitiveValue, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
+    DEFINE_STATIC_REF(CSSPrimitiveValue, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
 
-    if (valueToMerge->hasValue(underline.get()) && !mergedValue->hasValue(underline.get()))
-        mergedValue->append(underline.get());
+    if (valueToMerge->hasValue(underline) && !mergedValue->hasValue(underline))
+        mergedValue->append(underline);
 
-    if (valueToMerge->hasValue(lineThrough.get()) && !mergedValue->hasValue(lineThrough.get()))
-        mergedValue->append(lineThrough.get());
+    if (valueToMerge->hasValue(lineThrough) && !mergedValue->hasValue(lineThrough))
+        mergedValue->append(lineThrough);
 }
 
 void EditingStyle::mergeStyle(const StylePropertySet* style, CSSPropertyOverrideMode mode)
@@ -1300,7 +1300,7 @@
 
         ASSERT(end.document());
         Node* pastLast = Range::create(*end.document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode();
-        for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(n)) {
+        for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(*n)) {
             if (!n->isStyledElement())
                 continue;
 
@@ -1447,13 +1447,13 @@
     // Furthermore, text-decoration: none has been trimmed so that text-decoration property is always a CSSValueList.
     RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(textDecorationPropertyForEditing());
     if (textDecoration && textDecoration->isValueList()) {
-        DEFINE_STATIC_LOCAL(RefPtr<CSSPrimitiveValue>, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
-        DEFINE_STATIC_LOCAL(RefPtr<CSSPrimitiveValue>, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
+        DEFINE_STATIC_REF(CSSPrimitiveValue, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
+        DEFINE_STATIC_REF(CSSPrimitiveValue, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
 
         RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
-        if (newTextDecoration->removeAll(underline.get()))
+        if (newTextDecoration->removeAll(underline))
             m_applyUnderline = true;
-        if (newTextDecoration->removeAll(lineThrough.get()))
+        if (newTextDecoration->removeAll(lineThrough))
             m_applyLineThrough = true;
 
         // If trimTextDecorations, delete underline and line-through
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index bb5ffec..daa77e4 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -53,6 +53,7 @@
 #include "core/editing/SpellChecker.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/TypingCommand.h"
+#include "core/editing/UndoStack.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
@@ -73,10 +74,10 @@
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/KillRing.h"
 #include "core/platform/Pasteboard.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
 #include "core/rendering/HitTestResult.h"
+#include "platform/KillRing.h"
 #include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
@@ -140,9 +141,11 @@
     return emptyEditorClient();
 }
 
-void Editor::handleKeyboardEvent(KeyboardEvent* event)
+UndoStack* Editor::undoStack() const
 {
-    client().handleKeyboardEvent(event);
+    if (Page* page = m_frame.page())
+        return &page->undoStack();
+    return 0;
 }
 
 bool Editor::handleTextEvent(TextEvent* event)
@@ -263,19 +266,23 @@
     return true;
 }
 
-bool Editor::smartInsertDeleteEnabled()
+bool Editor::smartInsertDeleteEnabled() const
 {
-    return client().smartInsertDeleteEnabled();
+    if (Settings* settings = m_frame.settings())
+        return settings->smartInsertDeleteEnabled();
+    return false;
 }
 
-bool Editor::canSmartCopyOrDelete()
+bool Editor::canSmartCopyOrDelete() const
 {
-    return client().smartInsertDeleteEnabled() && m_frame.selection().granularity() == WordGranularity;
+    return smartInsertDeleteEnabled() && m_frame.selection().granularity() == WordGranularity;
 }
 
-bool Editor::isSelectTrailingWhitespaceEnabled()
+bool Editor::isSelectTrailingWhitespaceEnabled() const
 {
-    return client().isSelectTrailingWhitespaceEnabled();
+    if (Settings* settings = m_frame.settings())
+        return settings->selectTrailingWhitespaceEnabled();
+    return false;
 }
 
 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
@@ -405,6 +412,13 @@
         pasteAsFragment(fragment, canSmartReplaceWithPasteboard(pasteboard), chosePlainText);
 }
 
+void Editor::writeSelectionToPasteboard(Pasteboard* pasteboard, Range* selectedRange, const String& plainText)
+{
+    String html = createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs);
+    KURL url = selectedRange->startContainer()->document().url();
+    pasteboard->writeHTML(html, url, plainText, canSmartCopyOrDelete());
+}
+
 // Returns whether caller should continue with "the default processing", which is the same as
 // the event handler NOT setting the return value to false
 bool Editor::dispatchCPPEvent(const AtomicString &eventType, ClipboardAccessPolicy policy, PasteMode pasteMode)
@@ -436,7 +450,7 @@
 
 bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard)
 {
-    return client().smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
+    return smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
 }
 
 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
@@ -455,7 +469,7 @@
     ReplaceSelectionCommand::create(*m_frame.document(), fragment, options, EditActionPaste)->apply();
     revealSelectionAfterEditingOperation();
 
-    if (m_frame.selection().isInPasswordField() || !isContinuousSpellCheckingEnabled())
+    if (m_frame.selection().isInPasswordField() || !spellChecker().isContinuousSpellCheckingEnabled())
         return;
     spellChecker().chunkAndMarkAllMisspellingsAndBadGrammar(m_frame.selection().rootEditableElement());
 }
@@ -480,7 +494,7 @@
 
 void Editor::notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
 {
-    client().respondToChangedSelection(&m_frame);
+    client().respondToChangedSelection(m_frame.selection().selectionType());
     setStartNewKillRingSequence(true);
 }
 
@@ -619,8 +633,6 @@
     Node* target = selection.start().element();
     if (!target)
         target = m_frame.document()->body();
-    if (!target)
-        return 0;
 
     return target;
 }
@@ -633,13 +645,13 @@
 void Editor::applyStyle(StylePropertySet* style, EditAction editingAction)
 {
     switch (m_frame.selection().selectionType()) {
-    case VisibleSelection::NoSelection:
+    case NoSelection:
         // do nothing
         break;
-    case VisibleSelection::CaretSelection:
+    case CaretSelection:
         computeAndSetTypingStyle(style, editingAction);
         break;
-    case VisibleSelection::RangeSelection:
+    case RangeSelection:
         if (style) {
             ASSERT(m_frame.document());
             ApplyStyleCommand::create(*m_frame.document(), EditingStyle::create(style).get(), editingAction)->apply();
@@ -650,18 +662,10 @@
 
 void Editor::applyParagraphStyle(StylePropertySet* style, EditAction editingAction)
 {
-    switch (m_frame.selection().selectionType()) {
-    case VisibleSelection::NoSelection:
-        // do nothing
-        break;
-    case VisibleSelection::CaretSelection:
-    case VisibleSelection::RangeSelection:
-        if (style) {
-            ASSERT(m_frame.document());
-            ApplyStyleCommand::create(*m_frame.document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties)->apply();
-        }
-        break;
-    }
+    if (m_frame.selection().isNone() || !style)
+        return;
+    ASSERT(m_frame.document());
+    ApplyStyleCommand::create(*m_frame.document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties)->apply();
 }
 
 void Editor::applyStyleToSelection(StylePropertySet* style, EditAction editingAction)
@@ -746,7 +750,8 @@
         // Only register a new undo command if the command passed in is
         // different from the last command
         m_lastEditCommand = cmd;
-        client().registerUndoStep(m_lastEditCommand->ensureComposition());
+        if (UndoStack* undoStack = this->undoStack())
+            undoStack->registerUndoStep(m_lastEditCommand->ensureComposition());
     }
 
     respondToChangedContents(newSelection);
@@ -763,7 +768,8 @@
     changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
 
     m_lastEditCommand = 0;
-    client().registerRedoStep(cmd);
+    if (UndoStack* undoStack = this->undoStack())
+        undoStack->registerRedoStep(cmd);
     respondToChangedContents(newSelection);
 }
 
@@ -778,7 +784,8 @@
     changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
 
     m_lastEditCommand = 0;
-    client().registerUndoStep(cmd);
+    if (UndoStack* undoStack = this->undoStack())
+        undoStack->registerUndoStep(cmd);
     respondToChangedContents(newSelection);
 }
 
@@ -826,8 +833,7 @@
         return false;
     RefPtr<Range> range = selection.toNormalizedRange();
 
-    if (!text.isEmpty())
-        spellChecker().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
+    spellChecker().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
 
     // Get the selection to use for the event that triggered this insertText.
     // If the event handler changed the selection, we may want to use a different selection
@@ -899,7 +905,7 @@
             Pasteboard::generalPasteboard()->writePlainText(plainText,
                 canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
         } else {
-            Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), plainText);
+            writeSelectionToPasteboard(Pasteboard::generalPasteboard(), selection.get(), plainText);
         }
         deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
     }
@@ -919,7 +925,7 @@
         if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
             Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
         else
-            Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame.selectedTextForClipboard());
+            writeSelectionToPasteboard(Pasteboard::generalPasteboard(), selectedRange().get(), m_frame.selectedTextForClipboard());
     }
 }
 
@@ -961,25 +967,6 @@
     setStartNewKillRingSequence(false);
 }
 
-void Editor::simplifyMarkup(Node* startNode, Node* endNode)
-{
-    if (!startNode)
-        return;
-    if (endNode) {
-        if (startNode->document() != endNode->document())
-            return;
-        // check if start node is before endNode
-        Node* node = startNode;
-        while (node && node != endNode)
-            node = NodeTraversal::next(node);
-        if (!node)
-            return;
-    }
-
-    ASSERT(m_frame.document());
-    SimplifyMarkupCommand::create(*m_frame.document(), startNode, endNode ? NodeTraversal::next(endNode) : 0)->apply();
-}
-
 void Editor::copyImage(const HitTestResult& result)
 {
     KURL url = result.absoluteLinkURL();
@@ -991,32 +978,34 @@
 
 void Editor::clearUndoRedoOperations()
 {
-    client().clearUndoRedoOperations();
+    if (UndoStack* undoStack = this->undoStack())
+        undoStack->clearUndoRedoOperations();
 }
 
 bool Editor::canUndo()
 {
-    return client().canUndo();
+    if (UndoStack* undoStack = this->undoStack())
+        return undoStack->canUndo();
+    return false;
 }
 
 void Editor::undo()
 {
-    client().undo();
+    if (UndoStack* undoStack = this->undoStack())
+        undoStack->undo();
 }
 
 bool Editor::canRedo()
 {
-    return client().canRedo();
+    if (UndoStack* undoStack = this->undoStack())
+        return undoStack->canRedo();
+    return false;
 }
 
 void Editor::redo()
 {
-    client().redo();
-}
-
-void Editor::didBeginEditing(Element* rootEditableElement)
-{
-    spellChecker().didBeginEditing(rootEditableElement);
+    if (UndoStack* undoStack = this->undoStack())
+        undoStack->redo();
 }
 
 void Editor::setBaseWritingDirection(WritingDirection direction)
@@ -1036,23 +1025,6 @@
     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
 }
 
-PassRefPtr<Range> Editor::rangeForPoint(const IntPoint& windowPoint)
-{
-    Document* document = m_frame.documentAtPoint(windowPoint);
-    if (!document)
-        return 0;
-
-    Frame* frame = document->frame();
-    ASSERT(frame);
-    FrameView* frameView = frame->view();
-    if (!frameView)
-        return 0;
-    IntPoint framePoint = frameView->windowToContents(windowPoint);
-    VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
-
-    return selection.toNormalizedRange().get();
-}
-
 void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
 {
     if (m_preventRevealSelection)
@@ -1101,13 +1073,13 @@
 void Editor::addToKillRing(Range* range, bool prepend)
 {
     if (m_shouldStartNewKillRingSequence)
-        killRing()->startNewSequence();
+        killRing().startNewSequence();
 
     String text = plainText(range);
     if (prepend)
-        killRing()->prepend(text);
+        killRing().prepend(text);
     else
-        killRing()->append(text);
+        killRing().append(text);
     m_shouldStartNewKillRingSequence = false;
 }
 
@@ -1129,7 +1101,7 @@
     // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
     // starts a new kill ring sequence, but we want to do these things (matches AppKit).
     if (selectionDidNotChangeDOMPosition)
-        client().respondToChangedSelection(&m_frame);
+        client().respondToChangedSelection(m_frame.selection().selectionType());
 }
 
 IntRect Editor::firstRectForRange(Range* range) const
@@ -1190,27 +1162,6 @@
     m_frame.selection().setTypingStyle(typingStyle);
 }
 
-void Editor::textAreaOrTextFieldDidBeginEditing(Element* e)
-{
-    spellChecker().didBeginEditing(e);
-}
-
-void Editor::textFieldDidEndEditing(Element* e)
-{
-    spellChecker().didEndEditingOnTextField(e);
-    client().textFieldDidEndEditing(e);
-}
-
-void Editor::textDidChangeInTextField(Element* e)
-{
-    client().textDidChangeInTextField(e);
-}
-
-bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
-{
-    return client().doTextFieldCommandFromEvent(e, ke);
-}
-
 bool Editor::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection)
 {
     FindOptions options = (forward ? 0 : Backwards) | (caseFlag ? 0 : CaseInsensitive) | (wrapFlag ? WrapAround : 0) | (startInSelection ? StartInSelection : 0);
@@ -1335,11 +1286,6 @@
     return m_frame.spellChecker();
 }
 
-bool Editor::isContinuousSpellCheckingEnabled() const
-{
-    return spellChecker().isContinuousSpellCheckingEnabled();
-}
-
 void Editor::toggleOverwriteModeEnabled()
 {
     m_overwriteModeEnabled = !m_overwriteModeEnabled;
diff --git a/Source/core/editing/Editor.h b/Source/core/editing/Editor.h
index 99ea868..26b698b 100644
--- a/Source/core/editing/Editor.h
+++ b/Source/core/editing/Editor.h
@@ -57,6 +57,7 @@
 class StylePropertySet;
 class Text;
 class TextEvent;
+class UndoStack;
 
 enum EditorCommandSource { CommandFromMenuOrKeyBinding, CommandFromDOM, CommandFromDOMWithUserInterface };
 enum EditorParagraphSeparator { EditorParagraphSeparatorIsDiv, EditorParagraphSeparatorIsP };
@@ -87,7 +88,7 @@
     bool canCopy() const;
     bool canPaste() const;
     bool canDelete() const;
-    bool canSmartCopyOrDelete();
+    bool canSmartCopyOrDelete() const;
 
     void cut();
     void copy();
@@ -127,9 +128,6 @@
     bool deleteWithDirection(SelectionDirection, TextGranularity, bool killRing, bool isTypingAction);
     void deleteSelectionWithSmartDelete(bool smartDelete);
 
-    Node* removedAnchor() const { return m_removedAnchor.get(); }
-    void setRemovedAnchor(PassRefPtr<Node> n) { m_removedAnchor = n; }
-
     void applyStyle(StylePropertySet*, EditAction = EditActionUnspecified);
     void applyParagraphStyle(StylePropertySet*, EditAction = EditActionUnspecified);
     void applyStyleToSelection(StylePropertySet*, EditAction);
@@ -181,26 +179,22 @@
     bool canRedo();
     void redo();
 
-    void didBeginEditing(Element*);
-
     void setBaseWritingDirection(WritingDirection);
 
     // smartInsertDeleteEnabled and selectTrailingWhitespaceEnabled are
     // mutually exclusive, meaning that enabling one will disable the other.
-    bool smartInsertDeleteEnabled();
-    bool isSelectTrailingWhitespaceEnabled();
+    bool smartInsertDeleteEnabled() const;
+    bool isSelectTrailingWhitespaceEnabled() const;
 
     bool preventRevealSelection() const { return m_preventRevealSelection; }
 
     void setStartNewKillRingSequence(bool);
 
-    PassRefPtr<Range> rangeForPoint(const IntPoint& windowPoint);
-
     void clear();
 
     VisibleSelection selectionForCommand(Event*);
 
-    KillRing* killRing() const { return m_killRing.get(); }
+    KillRing& killRing() const { return *m_killRing; }
 
     EditingBehavior behavior() const;
 
@@ -217,7 +211,6 @@
     // FIXME: Switch callers over to the FindOptions version and retire this one.
     bool findString(const String&, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection);
 
-    PassRefPtr<Range> rangeOfString(const String&, Range*, FindOptions);
     PassRefPtr<Range> findStringAndScrollToVisible(const String&, Range*, FindOptions);
 
     const VisibleSelection& mark() const; // Mark, to be used as emacs uses it.
@@ -232,16 +225,9 @@
     bool markedTextMatchesAreHighlighted() const;
     void setMarkedTextMatchesAreHighlighted(bool);
 
-    void textAreaOrTextFieldDidBeginEditing(Element*);
-    void textFieldDidEndEditing(Element*);
-    void textDidChangeInTextField(Element*);
-    bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*);
-
     void replaceSelectionWithFragment(PassRefPtr<DocumentFragment>, bool selectReplacement, bool smartReplace, bool matchStyle);
     void replaceSelectionWithText(const String&, bool selectReplacement, bool smartReplace);
 
-    void simplifyMarkup(Node* startNode, Node* endNode);
-
     EditorParagraphSeparator defaultParagraphSeparator() const { return m_defaultParagraphSeparator; }
     void setDefaultParagraphSeparator(EditorParagraphSeparator separator) { m_defaultParagraphSeparator = separator; }
 
@@ -255,14 +241,16 @@
     };
     friend class RevealSelectionScope;
 
+    // Export interpretKeyEvent only for testing
+    static const char* interpretKeyEvent(const WebCore::KeyboardEvent*);
+
 private:
     Frame& m_frame;
     RefPtr<CompositeEditCommand> m_lastEditCommand;
-    RefPtr<Node> m_removedAnchor;
     int m_preventRevealSelection;
     bool m_shouldStartNewKillRingSequence;
     bool m_shouldStyleWithCSS;
-    OwnPtr<KillRing> m_killRing;
+    const OwnPtr<KillRing> m_killRing;
     VisibleSelection m_mark;
     bool m_areMarkedTextMatchesHighlighted;
     EditorParagraphSeparator m_defaultParagraphSeparator;
@@ -272,6 +260,8 @@
 
     bool canDeleteRange(Range*) const;
 
+    UndoStack* undoStack() const;
+
     bool tryDHTMLCopy();
     bool tryDHTMLCut();
     bool tryDHTMLPaste(PasteMode);
@@ -279,6 +269,7 @@
     bool canSmartReplaceWithPasteboard(Pasteboard*);
     void pasteAsPlainTextWithPasteboard(Pasteboard*);
     void pasteWithPasteboard(Pasteboard*);
+    void writeSelectionToPasteboard(Pasteboard*, Range*, const String& plainText);
     bool dispatchCPPEvent(const AtomicString&, ClipboardAccessPolicy, PasteMode = AllMimeTypes);
 
     void revealSelectionAfterEditingOperation(const ScrollAlignment& = ScrollAlignment::alignCenterIfNeeded, RevealExtentOption = DoNotRevealExtent);
@@ -287,8 +278,11 @@
 
     Node* findEventTargetFromSelection() const;
 
+    PassRefPtr<Range> rangeOfString(const String&, Range*, FindOptions);
+
     SpellChecker& spellChecker() const;
-    bool isContinuousSpellCheckingEnabled() const;
+
+    bool handleEditingKeyboardEvent(WebCore::KeyboardEvent*);
 };
 
 inline void Editor::setStartNewKillRingSequence(bool flag)
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index 9661fa2..1b19dd3 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -56,10 +56,10 @@
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/KillRing.h"
 #include "core/platform/Pasteboard.h"
 #include "core/platform/Scrollbar.h"
 #include "core/rendering/RenderBox.h"
+#include "platform/KillRing.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
@@ -200,9 +200,9 @@
 {
     ASSERT(frame.document());
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(*frame.document());
-    TrackExceptionState es;
-    fragment->appendChild(content, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    fragment->appendChild(content, exceptionState);
+    if (exceptionState.hadException())
         return false;
     return executeInsertFragment(frame, fragment.release());
 }
@@ -935,7 +935,7 @@
 
 static bool executePasteGlobalSelection(Frame& frame, Event*, EditorCommandSource source, const String&)
 {
-    if (!frame.editor().client().supportsGlobalSelection())
+    if (!frame.editor().behavior().supportsGlobalSelection())
         return false;
     ASSERT_UNUSED(source, source == CommandFromMenuOrKeyBinding);
 
@@ -1132,15 +1132,15 @@
 
 static bool executeYank(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing()->yank(), false, 0);
-    frame.editor().killRing()->setToYankedState();
+    frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing().yank(), false, 0);
+    frame.editor().killRing().setToYankedState();
     return true;
 }
 
 static bool executeYankAndSelect(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing()->yank(), true, 0);
-    frame.editor().killRing()->setToYankedState();
+    frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing().yank(), true, 0);
+    frame.editor().killRing().setToYankedState();
     return true;
 }
 
diff --git a/Source/core/editing/EditorKeyBindings.cpp b/Source/core/editing/EditorKeyBindings.cpp
new file mode 100644
index 0000000..48295ec
--- /dev/null
+++ b/Source/core/editing/EditorKeyBindings.cpp
@@ -0,0 +1,307 @@
+/*
+ * Copyright (C) 2006, 2007 Apple, Inc.  All rights reserved.
+ * 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 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/Editor.h"
+
+#include "core/events/KeyboardEvent.h"
+#include "core/frame/Frame.h"
+#include "core/page/EditorClient.h"
+#include "core/platform/chromium/KeyboardCodes.h"
+#include "platform/PlatformKeyboardEvent.h"
+
+namespace WebCore {
+
+//
+// The below code was adapted from the WebKit file webview.cpp
+//
+
+static const unsigned CtrlKey = 1 << 0;
+static const unsigned AltKey = 1 << 1;
+static const unsigned ShiftKey = 1 << 2;
+static const unsigned MetaKey = 1 << 3;
+#if OS(MACOSX)
+// Aliases for the generic key defintions to make kbd shortcuts definitions more
+// readable on OS X.
+static const unsigned OptionKey  = AltKey;
+
+// Do not use this constant for anything but cursor movement commands. Keys
+// with cmd set have their |isSystemKey| bit set, so chances are the shortcut
+// will not be executed. Another, less important, reason is that shortcuts
+// defined in the renderer do not blink the menu item that they triggered. See
+// http://crbug.com/25856 and the bugs linked from there for details.
+static const unsigned CommandKey = MetaKey;
+#endif
+
+// Keys with special meaning. These will be delegated to the editor using
+// the execCommand() method
+struct KeyDownEntry {
+    unsigned virtualKey;
+    unsigned modifiers;
+    const char* name;
+};
+
+struct KeyPressEntry {
+    unsigned charCode;
+    unsigned modifiers;
+    const char* name;
+};
+
+// Key bindings with command key on Mac and alt key on other platforms are
+// marked as system key events and will be ignored (with the exception
+// of Command-B and Command-I) so they shouldn't be added here.
+static const KeyDownEntry keyDownEntries[] = {
+    { VKEY_LEFT,   0,                  "MoveLeft"                             },
+    { VKEY_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"           },
+#if OS(MACOSX)
+    { VKEY_LEFT,   OptionKey,          "MoveWordLeft"                         },
+    { VKEY_LEFT,   OptionKey | ShiftKey,
+        "MoveWordLeftAndModifySelection"                                      },
+#else
+    { VKEY_LEFT,   CtrlKey,            "MoveWordLeft"                         },
+    { VKEY_LEFT,   CtrlKey | ShiftKey,
+        "MoveWordLeftAndModifySelection"                                      },
+#endif
+    { VKEY_RIGHT,  0,                  "MoveRight"                            },
+    { VKEY_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"          },
+#if OS(MACOSX)
+    { VKEY_RIGHT,  OptionKey,          "MoveWordRight"                        },
+    { VKEY_RIGHT,  OptionKey | ShiftKey, "MoveWordRightAndModifySelection"    },
+#else
+    { VKEY_RIGHT,  CtrlKey,            "MoveWordRight"                        },
+    { VKEY_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"      },
+#endif
+    { VKEY_UP,     0,                  "MoveUp"                               },
+    { VKEY_UP,     ShiftKey,           "MoveUpAndModifySelection"             },
+    { VKEY_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"         },
+    { VKEY_DOWN,   0,                  "MoveDown"                             },
+    { VKEY_DOWN,   ShiftKey,           "MoveDownAndModifySelection"           },
+    { VKEY_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"       },
+#if !OS(MACOSX)
+    { VKEY_UP,     CtrlKey,            "MoveParagraphBackward"                },
+    { VKEY_UP,     CtrlKey | ShiftKey, "MoveParagraphBackwardAndModifySelection" },
+    { VKEY_DOWN,   CtrlKey,            "MoveParagraphForward"                },
+    { VKEY_DOWN,   CtrlKey | ShiftKey, "MoveParagraphForwardAndModifySelection" },
+    { VKEY_PRIOR,  0,                  "MovePageUp"                           },
+    { VKEY_NEXT,   0,                  "MovePageDown"                         },
+#endif
+    { VKEY_HOME,   0,                  "MoveToBeginningOfLine"                },
+    { VKEY_HOME,   ShiftKey,
+        "MoveToBeginningOfLineAndModifySelection"                             },
+#if OS(MACOSX)
+    { VKEY_PRIOR,  OptionKey,          "MovePageUp"                           },
+    { VKEY_NEXT,   OptionKey,          "MovePageDown"                         },
+#endif
+#if !OS(MACOSX)
+    { VKEY_HOME,   CtrlKey,            "MoveToBeginningOfDocument"            },
+    { VKEY_HOME,   CtrlKey | ShiftKey,
+        "MoveToBeginningOfDocumentAndModifySelection"                         },
+#endif
+    { VKEY_END,    0,                  "MoveToEndOfLine"                      },
+    { VKEY_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"    },
+#if !OS(MACOSX)
+    { VKEY_END,    CtrlKey,            "MoveToEndOfDocument"                  },
+    { VKEY_END,    CtrlKey | ShiftKey,
+        "MoveToEndOfDocumentAndModifySelection"                               },
+#endif
+    { VKEY_BACK,   0,                  "DeleteBackward"                       },
+    { VKEY_BACK,   ShiftKey,           "DeleteBackward"                       },
+    { VKEY_DELETE, 0,                  "DeleteForward"                        },
+#if OS(MACOSX)
+    { VKEY_BACK,   OptionKey,          "DeleteWordBackward"                   },
+    { VKEY_DELETE, OptionKey,          "DeleteWordForward"                    },
+#else
+    { VKEY_BACK,   CtrlKey,            "DeleteWordBackward"                   },
+    { VKEY_DELETE, CtrlKey,            "DeleteWordForward"                    },
+#endif
+#if OS(MACOSX)
+    { 'B',         CommandKey,         "ToggleBold"                           },
+    { 'I',         CommandKey,         "ToggleItalic"                         },
+#else
+    { 'B',         CtrlKey,            "ToggleBold"                           },
+    { 'I',         CtrlKey,            "ToggleItalic"                         },
+#endif
+    { 'U',         CtrlKey,            "ToggleUnderline"                      },
+    { VKEY_ESCAPE, 0,                  "Cancel"                               },
+    { VKEY_OEM_PERIOD, CtrlKey,        "Cancel"                               },
+    { VKEY_TAB,    0,                  "InsertTab"                            },
+    { VKEY_TAB,    ShiftKey,           "InsertBacktab"                        },
+    { VKEY_RETURN, 0,                  "InsertNewline"                        },
+    { VKEY_RETURN, CtrlKey,            "InsertNewline"                        },
+    { VKEY_RETURN, AltKey,             "InsertNewline"                        },
+    { VKEY_RETURN, AltKey | ShiftKey,  "InsertNewline"                        },
+    { VKEY_RETURN, ShiftKey,           "InsertLineBreak"                      },
+    { VKEY_INSERT, CtrlKey,            "Copy"                                 },
+    { VKEY_INSERT, ShiftKey,           "Paste"                                },
+    { VKEY_DELETE, ShiftKey,           "Cut"                                  },
+#if !OS(MACOSX)
+    // On OS X, we pipe these back to the browser, so that it can do menu item
+    // blinking.
+    { 'C',         CtrlKey,            "Copy"                                 },
+    { 'V',         CtrlKey,            "Paste"                                },
+    { 'V',         CtrlKey | ShiftKey, "PasteAndMatchStyle"                   },
+    { 'X',         CtrlKey,            "Cut"                                  },
+    { 'A',         CtrlKey,            "SelectAll"                            },
+    { 'Z',         CtrlKey,            "Undo"                                 },
+    { 'Z',         CtrlKey | ShiftKey, "Redo"                                 },
+    { 'Y',         CtrlKey,            "Redo"                                 },
+#endif
+    { VKEY_INSERT, 0,                  "OverWrite"                            },
+};
+
+static const KeyPressEntry keyPressEntries[] = {
+    { '\t',   0,                  "InsertTab"                                 },
+    { '\t',   ShiftKey,           "InsertBacktab"                             },
+    { '\r',   0,                  "InsertNewline"                             },
+    { '\r',   CtrlKey,            "InsertNewline"                             },
+    { '\r',   ShiftKey,           "InsertLineBreak"                           },
+    { '\r',   AltKey,             "InsertNewline"                             },
+    { '\r',   AltKey | ShiftKey,  "InsertNewline"                             },
+};
+
+const char* Editor::interpretKeyEvent(const KeyboardEvent* evt)
+{
+    const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
+    if (!keyEvent)
+        return "";
+
+    static HashMap<int, const char*>* keyDownCommandsMap = 0;
+    static HashMap<int, const char*>* keyPressCommandsMap = 0;
+
+    if (!keyDownCommandsMap) {
+        keyDownCommandsMap = new HashMap<int, const char*>;
+        keyPressCommandsMap = new HashMap<int, const char*>;
+
+        for (unsigned i = 0; i < arraysize(keyDownEntries); i++) {
+            keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
+        }
+
+        for (unsigned i = 0; i < arraysize(keyPressEntries); i++) {
+            keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
+        }
+    }
+
+    unsigned modifiers = 0;
+    if (keyEvent->shiftKey())
+        modifiers |= ShiftKey;
+    if (keyEvent->altKey())
+        modifiers |= AltKey;
+    if (keyEvent->ctrlKey())
+        modifiers |= CtrlKey;
+    if (keyEvent->metaKey())
+        modifiers |= MetaKey;
+
+    if (keyEvent->type() == PlatformEvent::RawKeyDown) {
+        int mapKey = modifiers << 16 | evt->keyCode();
+        return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
+    }
+
+    int mapKey = modifiers << 16 | evt->charCode();
+    return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
+}
+
+bool Editor::handleEditingKeyboardEvent(KeyboardEvent* evt)
+{
+    const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
+    // do not treat this as text input if it's a system key event
+    if (!keyEvent || keyEvent->isSystemKey())
+        return false;
+
+    String commandName = interpretKeyEvent(evt);
+    Command command = this->command(commandName);
+
+    if (keyEvent->type() == PlatformEvent::RawKeyDown) {
+        // WebKit doesn't have enough information about mode to decide how
+        // commands that just insert text if executed via Editor should be treated,
+        // so we leave it upon WebCore to either handle them immediately
+        // (e.g. Tab that changes focus) or let a keypress event be generated
+        // (e.g. Tab that inserts a Tab character, or Enter).
+        if (command.isTextInsertion() || commandName.isEmpty())
+            return false;
+        if (command.execute(evt)) {
+            client().didExecuteCommand(commandName);
+            return true;
+        }
+        return false;
+    }
+
+    if (command.execute(evt)) {
+        client().didExecuteCommand(commandName);
+        return true;
+    }
+
+    // Here we need to filter key events.
+    // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
+    // In Webkit, EditorClient::handleKeyboardEvent in
+    // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
+    // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
+    // These key events should not emit text insert event.
+    // Alt key would be used to insert alternative character, so we should let
+    // through. Also note that Ctrl-Alt combination equals to AltGr key which is
+    // also used to insert alternative character.
+    // http://code.google.com/p/chromium/issues/detail?id=10846
+    // Windows sets both alt and meta are on when "Alt" key pressed.
+    // http://code.google.com/p/chromium/issues/detail?id=2215
+    // Also, we should not rely on an assumption that keyboards don't
+    // send ASCII characters when pressing a control key on Windows,
+    // which may be configured to do it so by user.
+    // See also http://en.wikipedia.org/wiki/Keyboard_Layout
+    // FIXME(ukai): investigate more detail for various keyboard layout.
+    if (evt->keyEvent()->text().length() == 1) {
+        UChar ch = evt->keyEvent()->text()[0U];
+
+        // Don't insert null or control characters as they can result in
+        // unexpected behaviour
+        if (ch < ' ')
+            return false;
+#if !OS(WIN)
+        // Don't insert ASCII character if ctrl w/o alt or meta is on.
+        // On Mac, we should ignore events when meta is on (Command-<x>).
+        if (ch < 0x80) {
+            if (evt->keyEvent()->ctrlKey() && !evt->keyEvent()->altKey())
+                return false;
+#if OS(MACOSX)
+            if (evt->keyEvent()->metaKey())
+            return false;
+#endif
+        }
+#endif
+    }
+
+    if (!canEdit())
+        return false;
+
+    return insertText(evt->keyEvent()->text(), evt);
+}
+
+void Editor::handleKeyboardEvent(KeyboardEvent* evt)
+{
+    // Give the embedder a chance to handle the keyboard event.
+    if (client().handleKeyboardEvent() || handleEditingKeyboardEvent(evt))
+        evt->setDefaultHandled();
+}
+
+} // namesace WebCore
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 4177bbf..2469353 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -197,11 +197,12 @@
 
     VisiblePosition base = m_originalBase.isNotNull() ? m_originalBase : newSelection.visibleBase();
     VisiblePosition newBase = base;
-    VisiblePosition newExtent = newSelection.visibleExtent();
+    VisiblePosition extent = newSelection.visibleExtent();
+    VisiblePosition newExtent = extent;
     if (endpointsAdjustmentMode == AdjustEndpointsAtBidiBoundary)
         adjustEndpointsAtBidiBoundary(newBase, newExtent);
 
-    if (newBase != base || newExtent != newSelection.visibleExtent()) {
+    if (newBase != base || newExtent != extent) {
         m_originalBase = base;
         newSelection.setBase(newBase);
         newSelection.setExtent(newExtent);
@@ -313,19 +314,11 @@
     return element.containsIncludingShadowDOM(position.anchorNode());
 }
 
-static void clearRenderViewSelection(const Position& position)
-{
-    RefPtr<Document> document = position.document();
-    document->updateStyleIfNeeded();
-    if (RenderView* view = document->renderView())
-        view->clearSelection();
-}
-
 void FrameSelection::nodeWillBeRemoved(Node& node)
 {
     // There can't be a selection inside a fragment, so if a fragment's node is being removed,
     // the selection in the document that created the fragment needs no adjustment.
-    if (isNone() || !node.inDocument())
+    if (isNone() || !node.inActiveDocument())
         return;
 
     respondToNodeModification(node, removingNodeRemovesPosition(node, m_selection.base()), removingNodeRemovesPosition(node, m_selection.extent()),
@@ -334,6 +327,8 @@
 
 void FrameSelection::respondToNodeModification(Node& node, bool baseRemoved, bool extentRemoved, bool startRemoved, bool endRemoved)
 {
+    ASSERT(node.document().isActive());
+
     bool clearRenderTreeSelection = false;
     bool clearDOMTreeSelection = false;
 
@@ -364,9 +359,9 @@
         else
             m_selection.setWithoutValidation(m_selection.end(), m_selection.start());
     } else if (RefPtr<Range> range = m_selection.firstRange()) {
-        TrackExceptionState es;
-        Range::CompareResults compareResult = range->compareNode(&node, es);
-        if (!es.hadException() && (compareResult == Range::NODE_BEFORE_AND_AFTER || compareResult == Range::NODE_INSIDE)) {
+        TrackExceptionState exceptionState;
+        Range::CompareResults compareResult = range->compareNode(&node, exceptionState);
+        if (!exceptionState.hadException() && (compareResult == Range::NODE_BEFORE_AND_AFTER || compareResult == Range::NODE_INSIDE)) {
             // If we did nothing here, when this node's renderer was destroyed, the rect that it
             // occupied would be invalidated, but, selection gaps that change as a result of
             // the removal wouldn't be invalidated.
@@ -376,7 +371,7 @@
     }
 
     if (clearRenderTreeSelection)
-        clearRenderViewSelection(m_selection.start());
+        m_selection.start().document()->renderView()->clearSelection();
 
     if (clearDOMTreeSelection)
         setSelection(VisibleSelection(), DoNotSetFocus);
@@ -1432,9 +1427,9 @@
 
     // Non-collapsed ranges are not allowed to start at the end of a line that is wrapped,
     // they start at the beginning of the next line instead
-    TrackExceptionState es;
-    bool collapsed = range->collapsed(es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    bool collapsed = range->collapsed(exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     // FIXME: Can we provide extentAffinity?
@@ -1481,16 +1476,10 @@
     // Update for caps lock state
     m_frame->eventHandler().capsLockStateMayHaveChanged();
 
-    // Because StyleResolver::checkOneSelector() and
-    // RenderTheme::isFocused() check if the frame is active, we have to
-    // update style and theme state that depended on those.
-    if (Element* element = document->focusedElement()) {
-        element->setNeedsStyleRecalc();
-        if (RenderObject* renderer = element->renderer()) {
-            if (renderer && renderer->style()->hasAppearance())
-                RenderTheme::theme().stateChanged(renderer, FocusState);
-        }
-    }
+    // We may have lost active status even though the focusElement hasn't changed
+    // give the element a chance to recalc style if its affected by focus.
+    if (Element* element = document->focusedElement())
+        element->focusStateChanged();
 
     // Secure keyboard entry is set by the active frame.
     if (document->useSecureKeyboardEntryWhenActive())
@@ -1747,8 +1736,8 @@
 {
     if (!start)
         return 0;
-    Element* element = start->isElementNode() ? toElement(start) : ElementTraversal::next(start);
-    for (; element; element = ElementTraversal::next(element)) {
+    Element* element = start->isElementNode() ? toElement(start) : ElementTraversal::next(*start);
+    for (; element; element = ElementTraversal::next(*element)) {
         if (element->hasTagName(formTag))
             return toHTMLFormElement(element);
         if (element->isHTMLElement() && toHTMLElement(element)->isFormControlElement())
@@ -1788,12 +1777,12 @@
     LayoutRect rect;
 
     switch (selectionType()) {
-    case VisibleSelection::NoSelection:
+    case NoSelection:
         return;
-    case VisibleSelection::CaretSelection:
+    case CaretSelection:
         rect = absoluteCaretBounds();
         break;
-    case VisibleSelection::RangeSelection:
+    case RangeSelection:
         rect = revealExtentOption == RevealExtent ? VisiblePosition(extent()).absoluteCaretBounds() : enclosingIntRect(bounds(false));
         break;
     }
@@ -1821,7 +1810,7 @@
 
     Node* node = document->documentElement();
     while (node && !node->hasTagName(bodyTag))
-        node = NodeTraversal::next(node);
+        node = NodeTraversal::next(*node);
     if (node)
         setSelection(VisibleSelection(firstPositionInOrBeforeNode(node), DOWNSTREAM));
 }
diff --git a/Source/core/editing/FrameSelection.h b/Source/core/editing/FrameSelection.h
index 5c34ff6..04b6599 100644
--- a/Source/core/editing/FrameSelection.h
+++ b/Source/core/editing/FrameSelection.h
@@ -106,7 +106,7 @@
 
     bool contains(const LayoutPoint&);
 
-    VisibleSelection::SelectionType selectionType() const { return m_selection.selectionType(); }
+    SelectionType selectionType() const { return m_selection.selectionType(); }
 
     EAffinity affinity() const { return m_selection.affinity(); }
 
diff --git a/Source/core/editing/IndentOutdentCommand.cpp b/Source/core/editing/IndentOutdentCommand.cpp
index 9348405..940f54b 100644
--- a/Source/core/editing/IndentOutdentCommand.cpp
+++ b/Source/core/editing/IndentOutdentCommand.cpp
@@ -72,13 +72,18 @@
     // We should calculate visible range in list item because inserting new
     // list element will change visibility of list item, e.g. :first-child
     // CSS selector.
-    VisiblePosition startOfMove(start);
-    VisiblePosition endOfMove(end);
-
     RefPtr<Element> newList = document().createElement(listNode->tagQName(), false);
     insertNodeBefore(newList, selectedListItem.get());
 
-    moveParagraphWithClones(startOfMove, endOfMove, newList.get(), selectedListItem.get());
+    // We should clone all the children of the list item for indenting purposes. However, in case the current
+    // selection does not encompass all its children, we need to explicitally handle the same. The original
+    // list item too would require proper deletion in that case.
+    if (end.anchorNode() == selectedListItem.get() || end.anchorNode()->isDescendantOf(selectedListItem->lastChild())) {
+        moveParagraphWithClones(start, end, newList.get(), selectedListItem.get());
+    } else {
+        moveParagraphWithClones(start, positionAfterNode(selectedListItem->lastChild()), newList.get(), selectedListItem.get());
+        removeNode(selectedListItem.get());
+    }
 
     if (canMergeLists(previousList.get(), newList.get()))
         mergeIdenticalElements(previousList.get(), newList.get());
diff --git a/Source/core/editing/InputMethodController.cpp b/Source/core/editing/InputMethodController.cpp
index daf2226..92eb55a 100644
--- a/Source/core/editing/InputMethodController.cpp
+++ b/Source/core/editing/InputMethodController.cpp
@@ -35,7 +35,8 @@
 #include "core/editing/Editor.h"
 #include "core/editing/TypingCommand.h"
 #include "core/html/HTMLTextAreaElement.h"
-#include "core/page/EditorClient.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/RenderObject.h"
@@ -81,11 +82,6 @@
     return m_frame.editor();
 }
 
-inline EditorClient& InputMethodController::editorClient() const
-{
-    return editor().client();
-}
-
 void InputMethodController::clear()
 {
     m_compositionNode = 0;
@@ -148,8 +144,8 @@
     if (!hasComposition())
         return;
 
-    // EditorClient::willSetInputMethodState() resets input method and the composition string is committed.
-    editorClient().willSetInputMethodState();
+    // ChromeClient::willSetInputMethodState() resets input method and the composition string is committed.
+    m_frame.chromeClient().willSetInputMethodState();
 }
 
 void InputMethodController::cancelComposition()
@@ -172,7 +168,7 @@
         return;
 
     cancelComposition();
-    editorClient().didCancelCompositionOnSelectionChange();
+    m_frame.chromeClient().didCancelCompositionOnSelectionChange();
 }
 
 bool InputMethodController::finishComposition(const String& text, FinishCompositionMode mode)
diff --git a/Source/core/editing/InputMethodController.h b/Source/core/editing/InputMethodController.h
index 7b49c4f..843cd8a 100644
--- a/Source/core/editing/InputMethodController.h
+++ b/Source/core/editing/InputMethodController.h
@@ -105,7 +105,6 @@
 
     explicit InputMethodController(Frame&);
     Editor& editor() const;
-    EditorClient& editorClient() const;
     bool insertTextForConfirmedComposition(const String& text);
     void selectComposition() const;
     enum FinishCompositionMode { ConfirmComposition, CancelComposition };
diff --git a/Source/core/editing/InsertParagraphSeparatorCommand.cpp b/Source/core/editing/InsertParagraphSeparatorCommand.cpp
index 5c12948..ddfe1d2 100644
--- a/Source/core/editing/InsertParagraphSeparatorCommand.cpp
+++ b/Source/core/editing/InsertParagraphSeparatorCommand.cpp
@@ -395,7 +395,7 @@
         else {
             Node* splitTo = insertionPosition.containerNode();
             if (splitTo->isTextNode() && insertionPosition.offsetInContainerNode() >= caretMaxOffset(splitTo))
-                splitTo = NodeTraversal::next(splitTo, startBlock.get());
+                splitTo = NodeTraversal::next(*splitTo, startBlock.get());
             ASSERT(splitTo);
             splitTreeToNode(splitTo, startBlock.get());
 
diff --git a/Source/core/editing/InsertTextCommand.cpp b/Source/core/editing/InsertTextCommand.cpp
index 00ba6a7..8a48940 100644
--- a/Source/core/editing/InsertTextCommand.cpp
+++ b/Source/core/editing/InsertTextCommand.cpp
@@ -174,7 +174,7 @@
     // It is possible for the node that contains startPosition to contain only unrendered whitespace,
     // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
     Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.containerNode()));
-    deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
+    deleteInsignificantText(startPosition, startPosition.downstream());
     if (!startPosition.inDocument())
         startPosition = positionBeforeStartNode;
     if (!startPosition.isCandidate())
diff --git a/Source/core/editing/MarkupAccumulator.cpp b/Source/core/editing/MarkupAccumulator.cpp
index 1ccbc83..9d5b975 100644
--- a/Source/core/editing/MarkupAccumulator.cpp
+++ b/Source/core/editing/MarkupAccumulator.cpp
@@ -39,7 +39,7 @@
 #include "core/editing/Editor.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLTemplateElement.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
@@ -303,14 +303,16 @@
 
 EntityMask MarkupAccumulator::entityMaskForText(Text* text) const
 {
+    if (!text->document().isHTMLDocument())
+        return EntityMaskInPCDATA;
+
     const QualifiedName* parentName = 0;
     if (text->parentElement())
         parentName = &(text->parentElement())->tagQName();
 
     if (parentName && (*parentName == scriptTag || *parentName == styleTag || *parentName == xmpTag))
         return EntityMaskInCDATA;
-
-    return text->document().isHTMLDocument() ? EntityMaskInHTMLPCDATA : EntityMaskInPCDATA;
+    return EntityMaskInHTMLPCDATA;
 }
 
 void MarkupAccumulator::appendText(StringBuilder& result, Text* text)
diff --git a/Source/core/editing/MergeIdenticalElementsCommand.cpp b/Source/core/editing/MergeIdenticalElementsCommand.cpp
index 2ae2dbb..e512319 100644
--- a/Source/core/editing/MergeIdenticalElementsCommand.cpp
+++ b/Source/core/editing/MergeIdenticalElementsCommand.cpp
@@ -71,10 +71,10 @@
     if (!parent || !parent->rendererIsEditable())
         return;
 
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
 
-    parent->insertBefore(m_element1.get(), m_element2.get(), es);
-    if (es.hadException())
+    parent->insertBefore(m_element1.get(), m_element2.get(), exceptionState);
+    if (exceptionState.hadException())
         return;
 
     Vector<RefPtr<Node> > children;
@@ -83,7 +83,7 @@
 
     size_t size = children.size();
     for (size_t i = 0; i < size; ++i)
-        m_element1->appendChild(children[i].release(), es);
+        m_element1->appendChild(children[i].release(), exceptionState);
 }
 
 } // namespace WebCore
diff --git a/Source/core/editing/ReplaceSelectionCommand.cpp b/Source/core/editing/ReplaceSelectionCommand.cpp
index a77d2b0..c58c10f 100644
--- a/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -272,7 +272,7 @@
 {
     Vector<RefPtr<Node> > unrendered;
 
-    for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(node, holder))
+    for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(*node, holder))
         if (!isNodeRendered(node) && !isTableStructureNode(node))
             unrendered.append(node);
 
@@ -313,51 +313,49 @@
 
     node = container->firstChild();
     while (node) {
-        RefPtr<Node> next = NodeTraversal::next(node);
+        RefPtr<Node> next = NodeTraversal::next(*node);
         if (isInterchangeConvertedSpaceSpan(node)) {
-            next = NodeTraversal::nextSkippingChildren(node);
+            next = NodeTraversal::nextSkippingChildren(*node);
             removeNodePreservingChildren(node);
         }
         node = next.get();
     }
 }
 
-inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node* node)
+inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node& node)
 {
-    if (!node)
-        return;
-
     if (!m_firstNodeInserted)
-        m_firstNodeInserted = node;
+        m_firstNodeInserted = &node;
 
-    m_lastNodeInserted = node;
+    m_lastNodeInserted = &node;
 }
 
-inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node* node)
+inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node& node)
 {
     if (m_firstNodeInserted == node)
         m_firstNodeInserted = NodeTraversal::next(node);
     if (m_lastNodeInserted == node)
-        m_lastNodeInserted = node->lastChild() ? node->lastChild() : NodeTraversal::nextSkippingChildren(node);
+        m_lastNodeInserted = node.lastChild() ? node.lastChild() : NodeTraversal::nextSkippingChildren(node);
 }
 
-inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node* node)
+inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node& node)
 {
     if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
         m_firstNodeInserted = 0;
         m_lastNodeInserted = 0;
-    } else if (m_firstNodeInserted == node)
-        m_firstNodeInserted = NodeTraversal::nextSkippingChildren(m_firstNodeInserted.get());
-    else if (m_lastNodeInserted == node)
-        m_lastNodeInserted = NodeTraversal::previousSkippingChildren(m_lastNodeInserted.get());
+    } else if (m_firstNodeInserted == node) {
+        m_firstNodeInserted = NodeTraversal::nextSkippingChildren(*m_firstNodeInserted);
+    } else if (m_lastNodeInserted == node) {
+        m_lastNodeInserted = NodeTraversal::previousSkippingChildren(*m_lastNodeInserted);
+    }
 }
 
-inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node* node, Node* newNode)
+inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node& node, Node& newNode)
 {
     if (m_firstNodeInserted == node)
-        m_firstNodeInserted = newNode;
+        m_firstNodeInserted = &newNode;
     if (m_lastNodeInserted == node)
-        m_lastNodeInserted = newNode;
+        m_lastNodeInserted = &newNode;
 }
 
 ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
@@ -471,7 +469,7 @@
     for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
         // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
 
-        next = NodeTraversal::next(node.get());
+        next = NodeTraversal::next(*node);
         if (!node->isStyledElement())
             continue;
 
@@ -483,12 +481,13 @@
             if (element->isHTMLElement()) {
                 Vector<QualifiedName> attributes;
                 HTMLElement* htmlElement = toHTMLElement(element);
+                ASSERT(htmlElement);
 
                 if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
                     // e.g. <b style="font-weight: normal;"> is converted to <span style="font-weight: normal;">
                     node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
                     element = toElement(node);
-                    insertedNodes.didReplaceNode(htmlElement, node.get());
+                    insertedNodes.didReplaceNode(*htmlElement, *node);
                 } else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
                     EditingStyle::DoNotExtractMatchingStyle)) {
                     // e.g. <font size="3" style="font-size: 20px;"> is converted to <font style="font-size: 20px;">
@@ -510,7 +509,7 @@
 
         if (!inlineStyle || newInlineStyle->isEmpty()) {
             if (isStyleSpanOrSpanWithOnlyStyleAttribute(element) || isEmptyFontTag(element, AllowNonEmptyStyleAttribute)) {
-                insertedNodes.willRemoveNodePreservingChildren(element);
+                insertedNodes.willRemoveNodePreservingChildren(*element);
                 removeNodePreservingChildren(element);
                 continue;
             }
@@ -522,7 +521,7 @@
         if (isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
             && VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
             && VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
-            insertedNodes.willRemoveNodePreservingChildren(element);
+            insertedNodes.willRemoveNodePreservingChildren(*element);
             removeNodePreservingChildren(element);
             continue;
         }
@@ -534,7 +533,7 @@
         // Keep this code around for backward compatibility
         if (isLegacyAppleStyleSpan(element)) {
             if (!element->firstChild()) {
-                insertedNodes.willRemoveNodePreservingChildren(element);
+                insertedNodes.willRemoveNodePreservingChildren(*element);
                 removeNodePreservingChildren(element);
                 continue;
             }
@@ -616,7 +615,7 @@
     RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
     RefPtr<Node> next;
     for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
-        next = NodeTraversal::next(node.get());
+        next = NodeTraversal::next(*node);
 
         if (!node->isHTMLElement())
             continue;
@@ -671,7 +670,7 @@
     if (lastLeafInserted.isTextNode() && !nodeHasVisibleRenderText(toText(lastLeafInserted))
         && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), selectTag)
         && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), scriptTag)) {
-        insertedNodes.willRemoveNode(&lastLeafInserted);
+        insertedNodes.willRemoveNode(lastLeafInserted);
         removeNode(&lastLeafInserted);
     }
 
@@ -679,7 +678,7 @@
     // it is a top level node in the fragment and the user can't insert into those elements.
     Node* firstNodeInserted = insertedNodes.firstNodeInserted();
     if (firstNodeInserted && firstNodeInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*firstNodeInserted))) {
-        insertedNodes.willRemoveNode(firstNodeInserted);
+        insertedNodes.willRemoveNode(*firstNodeInserted);
         removeNode(firstNodeInserted);
     }
 }
@@ -705,10 +704,11 @@
             || node->hasTagName(metaTag)
             || node->hasTagName(styleTag)
             || isHTMLTitleElement(node)) {
-            next = NodeTraversal::nextSkippingChildren(node);
+            next = NodeTraversal::nextSkippingChildren(*node);
             fragment.removeNode(node);
-        } else
-            next = NodeTraversal::next(node);
+        } else {
+            next = NodeTraversal::next(*node);
+        }
     }
 }
 
@@ -755,7 +755,7 @@
     // The style span that contains the source document's default style should be at
     // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
     // so search for the top level style span instead of assuming it's at the top.
-    for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(node)) {
+    for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(*node)) {
         if (isLegacyAppleStyleSpan(node)) {
             wrappingStyleSpan = toHTMLElement(node);
             break;
@@ -787,7 +787,7 @@
     style->removeBlockProperties();
 
     if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
-        insertedNodes.willRemoveNodePreservingChildren(wrappingStyleSpan);
+        insertedNodes.willRemoveNodePreservingChildren(*wrappingStyleSpan);
         removeNodePreservingChildren(wrappingStyleSpan);
     } else
         setNodeAttribute(wrappingStyleSpan, styleAttr, style->style()->asText());
@@ -992,17 +992,17 @@
     if (endBR)
         originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR), DOWNSTREAM).previous();
 
-    startBlock = enclosingBlock(insertionPos.deprecatedNode());
+    RefPtr<Node> insertionBlock = enclosingBlock(insertionPos.deprecatedNode());
 
     // Adjust insertionPos to prevent nesting.
     // If the start was in a Mail blockquote, we will have already handled adjusting insertionPos above.
-    if (m_preventNesting && startBlock && !isTableCell(startBlock) && !startIsInsideMailBlockquote) {
-        ASSERT(startBlock != currentRoot);
+    if (m_preventNesting && insertionBlock && !isTableCell(insertionBlock.get()) && !startIsInsideMailBlockquote) {
+        ASSERT(insertionBlock != currentRoot);
         VisiblePosition visibleInsertionPos(insertionPos);
         if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
-            insertionPos = positionInParentAfterNode(startBlock);
+            insertionPos = positionInParentAfterNode(insertionBlock.get());
         else if (isStartOfBlock(visibleInsertionPos))
-            insertionPos = positionInParentBeforeNode(startBlock);
+            insertionPos = positionInParentBeforeNode(insertionBlock.get());
     }
 
     // Paste at start or end of link goes outside of link.
@@ -1067,6 +1067,7 @@
 
     InsertedNodes insertedNodes;
     RefPtr<Node> refNode = fragment.firstChild();
+    ASSERT(refNode);
     RefPtr<Node> node = refNode->nextSibling();
 
     fragment.removeNode(refNode);
@@ -1077,7 +1078,7 @@
         refNode = insertAsListItems(toHTMLElement(refNode), blockStart, insertionPos, insertedNodes);
     else {
         insertNodeAt(refNode, insertionPos);
-        insertedNodes.respondToNodeInsertion(refNode.get());
+        insertedNodes.respondToNodeInsertion(*refNode);
     }
 
     // Mutation events (bug 22634) may have already removed the inserted content
@@ -1089,8 +1090,8 @@
     while (node) {
         RefPtr<Node> next = node->nextSibling();
         fragment.removeNode(node.get());
-        insertNodeAfter(node, refNode.get());
-        insertedNodes.respondToNodeInsertion(node.get());
+        insertNodeAfter(node, refNode);
+        insertedNodes.respondToNodeInsertion(*node);
 
         // Mutation events (bug 22634) may have already removed the inserted content
         if (!node->inDocument())
@@ -1111,19 +1112,24 @@
     if (!insertedNodes.firstNodeInserted() || !insertedNodes.firstNodeInserted()->inDocument())
         return;
 
+    // Scripts specified in javascript protocol may remove |insertionBlock|
+    // during insertion, e.g. <iframe src="javascript:...">
+    if (insertionBlock && !insertionBlock->inDocument())
+        insertionBlock = 0;
+
     VisiblePosition startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
 
-    // We inserted before the startBlock to prevent nesting, and the content before the startBlock wasn't in its own block and
+    // We inserted before the insertionBlock to prevent nesting, and the content before the insertionBlock wasn't in its own block and
     // didn't have a br after it, so the inserted content ended up in the same paragraph.
-    if (startBlock && insertionPos.deprecatedNode() == startBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < startBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
+    if (insertionBlock && insertionPos.deprecatedNode() == insertionBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < insertionBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
         insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
 
     if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))) {
         RefPtr<Node> parent = endBR->parentNode();
-        insertedNodes.willRemoveNode(endBR);
+        insertedNodes.willRemoveNode(*endBR);
         removeNode(endBR);
         if (Node* nodeToRemove = highestNodeToRemoveInPruning(parent.get())) {
-            insertedNodes.willRemoveNode(nodeToRemove);
+            insertedNodes.willRemoveNode(*nodeToRemove);
             removeNode(nodeToRemove);
         }
     }
@@ -1432,10 +1438,10 @@
         listElement->removeChild(listItem.get(), ASSERT_NO_EXCEPTION);
         if (isStart || isMiddle) {
             insertNodeBefore(listItem, lastNode);
-            insertedNodes.respondToNodeInsertion(listItem.get());
+            insertedNodes.respondToNodeInsertion(*listItem);
         } else if (isEnd) {
             insertNodeAfter(listItem, lastNode);
-            insertedNodes.respondToNodeInsertion(listItem.get());
+            insertedNodes.respondToNodeInsertion(*listItem);
             lastNode = listItem.get();
         } else
             ASSERT_NOT_REACHED();
diff --git a/Source/core/editing/ReplaceSelectionCommand.h b/Source/core/editing/ReplaceSelectionCommand.h
index b9f5da6..ee3879b 100644
--- a/Source/core/editing/ReplaceSelectionCommand.h
+++ b/Source/core/editing/ReplaceSelectionCommand.h
@@ -60,14 +60,14 @@
 
     class InsertedNodes {
     public:
-        void respondToNodeInsertion(Node*);
-        void willRemoveNodePreservingChildren(Node*);
-        void willRemoveNode(Node*);
-        void didReplaceNode(Node*, Node* newNode);
+        void respondToNodeInsertion(Node&);
+        void willRemoveNodePreservingChildren(Node&);
+        void willRemoveNode(Node&);
+        void didReplaceNode(Node&, Node& newNode);
 
         Node* firstNodeInserted() const { return m_firstNodeInserted.get(); }
         Node& lastLeafInserted() const { ASSERT(m_lastNodeInserted); return m_lastNodeInserted->lastDescendant(); }
-        Node* pastLastLeaf() const { return m_lastNodeInserted ? NodeTraversal::next(&lastLeafInserted()) : 0; }
+        Node* pastLastLeaf() const { return m_lastNodeInserted ? NodeTraversal::next(lastLeafInserted()) : 0; }
 
     private:
         RefPtr<Node> m_firstNodeInserted;
diff --git a/Source/core/platform/MIMETypeFromURL.h b/Source/core/editing/SelectionType.h
similarity index 81%
rename from Source/core/platform/MIMETypeFromURL.h
rename to Source/core/editing/SelectionType.h
index 50af6c2..1d5a606 100644
--- a/Source/core/platform/MIMETypeFromURL.h
+++ b/Source/core/editing/SelectionType.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2004 Apple Computer, Inc.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,18 +23,13 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MIMETypeFromURL_h
-#define MIMETypeFromURL_h
-
-#include "wtf/Forward.h"
+#ifndef SelectionType_h
+#define SelectionType_h
 
 namespace WebCore {
 
-class KURL;
-
-String mimeTypeFromDataURL(const String& url);
-String mimeTypeFromURL(const KURL&);
+enum SelectionType { NoSelection, CaretSelection, RangeSelection };
 
 } // namespace WebCore
 
-#endif // MIMETypeFromURL_h
+#endif // SelectionType_h
diff --git a/Source/core/editing/SimplifyMarkupCommand.cpp b/Source/core/editing/SimplifyMarkupCommand.cpp
index 4e5fdf7..8d13312 100644
--- a/Source/core/editing/SimplifyMarkupCommand.cpp
+++ b/Source/core/editing/SimplifyMarkupCommand.cpp
@@ -48,7 +48,7 @@
     // without affecting the style. The goal is to produce leaner markup even when starting
     // from a verbose fragment.
     // We look at inline elements as well as non top level divs that don't have attributes.
-    for (Node* node = m_firstNode.get(); node && node != m_nodeAfterLast; node = NodeTraversal::next(node)) {
+    for (Node* node = m_firstNode.get(); node && node != m_nodeAfterLast; node = NodeTraversal::next(*node)) {
         if (node->firstChild() || (node->isTextNode() && node->nextSibling()))
             continue;
 
diff --git a/Source/core/editing/SpellChecker.cpp b/Source/core/editing/SpellChecker.cpp
index ea460e7..f13d855 100644
--- a/Source/core/editing/SpellChecker.cpp
+++ b/Source/core/editing/SpellChecker.cpp
@@ -38,11 +38,12 @@
 #include "core/editing/TextCheckingHelper.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
-#include "core/html/HTMLInputElement.h"
-#include "core/page/EditorClient.h"
 #include "core/frame/Frame.h"
+#include "core/html/HTMLInputElement.h"
+#include "core/loader/EmptyClients.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
+#include "core/page/SpellCheckerClient.h"
 #include "core/rendering/RenderTextControl.h"
 #include "platform/text/TextCheckerClient.h"
 
@@ -65,14 +66,22 @@
     return adoptPtr(new SpellChecker(frame));
 }
 
-EditorClient& SpellChecker::editorClient() const
+static SpellCheckerClient& emptySpellCheckerClient()
 {
-    return m_frame.editor().client();
+    DEFINE_STATIC_LOCAL(EmptySpellCheckerClient, client, ());
+    return client;
+}
+
+SpellCheckerClient& SpellChecker::spellCheckerClient() const
+{
+    if (Page* page = m_frame.page())
+        return page->spellCheckerClient();
+    return emptySpellCheckerClient();
 }
 
 TextCheckerClient& SpellChecker::textChecker() const
 {
-    return editorClient().textChecker();
+    return spellCheckerClient().textChecker();
 }
 
 SpellChecker::SpellChecker(Frame& frame)
@@ -87,16 +96,16 @@
 
 bool SpellChecker::isContinuousSpellCheckingEnabled() const
 {
-    return editorClient().isContinuousSpellCheckingEnabled();
+    return spellCheckerClient().isContinuousSpellCheckingEnabled();
 }
 
 void SpellChecker::toggleContinuousSpellChecking()
 {
-    editorClient().toggleContinuousSpellChecking();
+    spellCheckerClient().toggleContinuousSpellChecking();
     if (isContinuousSpellCheckingEnabled())
         return;
     for (Frame* frame = m_frame.page()->mainFrame(); frame && frame->document(); frame = frame->tree().traverseNext()) {
-        for (Node* node = frame->document()->rootNode(); node; node = NodeTraversal::next(node)) {
+        for (Node* node = frame->document()->rootNode(); node; node = NodeTraversal::next(*node)) {
             node->setAlreadySpellChecked(false);
         }
     }
@@ -104,7 +113,7 @@
 
 bool SpellChecker::isGrammarCheckingEnabled()
 {
-    return editorClient().isGrammarCheckingEnabled();
+    return spellCheckerClient().isGrammarCheckingEnabled();
 }
 
 void SpellChecker::didBeginEditing(Element* element)
@@ -215,7 +224,7 @@
     RefPtr<Range> firstMisspellingRange;
     if (unifiedTextCheckerEnabled()) {
         grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
-        foundItem = TextCheckingHelper(editorClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
+        foundItem = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
         if (isSpelling) {
             misspelledWord = foundItem;
             misspellingOffset = foundOffset;
@@ -224,7 +233,7 @@
             grammarPhraseOffset = foundOffset;
         }
     } else {
-        misspelledWord = TextCheckingHelper(editorClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
+        misspelledWord = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
         grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
         if (!misspelledWord.isEmpty()) {
             // Stop looking at start of next misspelled word
@@ -234,7 +243,7 @@
         }
 
         if (isGrammarCheckingEnabled())
-            badGrammarPhrase = TextCheckingHelper(editorClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
+            badGrammarPhrase = TextCheckingHelper(spellCheckerClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
     }
 
     // If we found neither bad grammar nor a misspelled word, wrap and try again (but don't bother if we started at the beginning of the
@@ -246,7 +255,7 @@
 
         if (unifiedTextCheckerEnabled()) {
             grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
-            foundItem = TextCheckingHelper(editorClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
+            foundItem = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
             if (isSpelling) {
                 misspelledWord = foundItem;
                 misspellingOffset = foundOffset;
@@ -255,7 +264,7 @@
                 grammarPhraseOffset = foundOffset;
             }
         } else {
-            misspelledWord = TextCheckingHelper(editorClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
+            misspelledWord = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
             grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
             if (!misspelledWord.isEmpty()) {
                 // Stop looking at start of next misspelled word
@@ -265,7 +274,7 @@
             }
 
             if (isGrammarCheckingEnabled())
-                badGrammarPhrase = TextCheckingHelper(editorClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
+                badGrammarPhrase = TextCheckingHelper(spellCheckerClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
         }
     }
 
@@ -291,7 +300,7 @@
         m_frame.selection().setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
         m_frame.selection().revealSelection();
 
-        editorClient().updateSpellingUIWithMisspelledWord(misspelledWord);
+        spellCheckerClient().updateSpellingUIWithMisspelledWord(misspelledWord);
         m_frame.document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
     }
 }
@@ -328,13 +337,13 @@
 
 void SpellChecker::showSpellingGuessPanel()
 {
-    if (editorClient().spellingUIIsShowing()) {
-        editorClient().showSpellingUI(false);
+    if (spellCheckerClient().spellingUIIsShowing()) {
+        spellCheckerClient().showSpellingUI(false);
         return;
     }
 
     advanceToNextMisspelling(true);
-    editorClient().showSpellingUI(true);
+    spellCheckerClient().showSpellingUI(true);
 }
 
 void SpellChecker::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
@@ -431,7 +440,7 @@
     if (!isSpellCheckingEnabledFor(editableNode))
         return;
 
-    TextCheckingHelper checker(editorClient(), searchRange);
+    TextCheckingHelper checker(spellCheckerClient(), searchRange);
     if (checkSpelling)
         checker.markAllMisspellings(firstMisspellingRange);
     else if (isGrammarCheckingEnabled())
@@ -564,7 +573,7 @@
     bool adjustSelectionForParagraphBoundaries = false;
 
     if (shouldMarkSpelling) {
-        if (m_frame.selection().selectionType() == VisibleSelection::CaretSelection) {
+        if (m_frame.selection().isCaret()) {
             // Attempt to save the caret position so we can restore it later if needed
             Position caretPosition = m_frame.selection().end();
             selectionOffset = paragraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
@@ -726,7 +735,7 @@
     DocumentMarker::MarkerTypes markerTypes(DocumentMarker::Spelling);
     if (isGrammarCheckingEnabled() || unifiedTextCheckerEnabled())
         markerTypes.add(DocumentMarker::Grammar);
-    for (Node* node = innerText; node; node = NodeTraversal::next(node, innerText)) {
+    for (Node* node = innerText; node; node = NodeTraversal::next(*node, innerText)) {
         m_frame.document()->markers()->removeMarkers(node, markerTypes);
     }
 }
diff --git a/Source/core/editing/SpellChecker.h b/Source/core/editing/SpellChecker.h
index bf54744..009cca1 100644
--- a/Source/core/editing/SpellChecker.h
+++ b/Source/core/editing/SpellChecker.h
@@ -34,8 +34,8 @@
 
 namespace WebCore {
 
-class EditorClient;
 class Frame;
+class SpellCheckerClient;
 class SpellCheckRequest;
 class SpellCheckRequester;
 class TextCheckerClient;
@@ -49,7 +49,7 @@
 
     ~SpellChecker();
 
-    EditorClient& editorClient() const;
+    SpellCheckerClient& spellCheckerClient() const;
     TextCheckerClient& textChecker() const;
 
     bool isContinuousSpellCheckingEnabled() const;
diff --git a/Source/core/editing/SplitElementCommand.cpp b/Source/core/editing/SplitElementCommand.cpp
index e4227ca..128c370 100644
--- a/Source/core/editing/SplitElementCommand.cpp
+++ b/Source/core/editing/SplitElementCommand.cpp
@@ -53,13 +53,13 @@
     for (Node* node = m_element2->firstChild(); node != m_atChild; node = node->nextSibling())
         children.append(node);
 
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
 
     ContainerNode* parent = m_element2->parentNode();
     if (!parent || !parent->rendererIsEditable())
         return;
-    parent->insertBefore(m_element1.get(), m_element2.get(), es);
-    if (es.hadException())
+    parent->insertBefore(m_element1.get(), m_element2.get(), exceptionState);
+    if (exceptionState.hadException())
         return;
 
     // Delete id attribute from the second element because the same id cannot be used for more than one element
@@ -67,7 +67,7 @@
 
     size_t size = children.size();
     for (size_t i = 0; i < size; ++i)
-        m_element1->appendChild(children[i], es);
+        m_element1->appendChild(children[i], exceptionState);
 }
 
 void SplitElementCommand::doApply()
diff --git a/Source/core/editing/SplitTextNodeCommand.cpp b/Source/core/editing/SplitTextNodeCommand.cpp
index c8550cf..3408659 100644
--- a/Source/core/editing/SplitTextNodeCommand.cpp
+++ b/Source/core/editing/SplitTextNodeCommand.cpp
@@ -96,11 +96,11 @@
 
 void SplitTextNodeCommand::insertText1AndTrimText2()
 {
-    TrackExceptionState es;
-    m_text2->parentNode()->insertBefore(m_text1.get(), m_text2.get(), es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    m_text2->parentNode()->insertBefore(m_text1.get(), m_text2.get(), exceptionState);
+    if (exceptionState.hadException())
         return;
-    m_text2->deleteData(0, m_offset, es, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
+    m_text2->deleteData(0, m_offset, exceptionState, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 }
 
 } // namespace WebCore
diff --git a/Source/core/editing/TextCheckingHelper.cpp b/Source/core/editing/TextCheckingHelper.cpp
index 201b06d..41247b0 100644
--- a/Source/core/editing/TextCheckingHelper.cpp
+++ b/Source/core/editing/TextCheckingHelper.cpp
@@ -37,6 +37,7 @@
 #include "core/editing/VisibleUnits.h"
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
+#include "core/page/SpellCheckerClient.h"
 #include "platform/text/TextBreakIterator.h"
 #include "platform/text/TextCheckerClient.h"
 
@@ -160,12 +161,12 @@
     return TextIterator::subrange(paragraphRange().get(), characterOffset, characterCount);
 }
 
-int TextCheckingParagraph::offsetTo(const Position& position, ExceptionState& es) const
+int TextCheckingParagraph::offsetTo(const Position& position, ExceptionState& exceptionState) const
 {
     ASSERT(m_checkingRange);
     RefPtr<Range> range = offsetAsRange()->cloneRange(ASSERT_NO_EXCEPTION);
-    range->setEnd(position.containerNode(), position.computeOffsetInContainerNode(), es);
-    if (es.hadException())
+    range->setEnd(position.containerNode(), position.computeOffsetInContainerNode(), exceptionState);
+    if (exceptionState.hadException())
         return 0;
     return TextIterator::rangeLength(range.get());
 }
@@ -218,7 +219,7 @@
     return m_checkingLength;
 }
 
-TextCheckingHelper::TextCheckingHelper(EditorClient& client, PassRefPtr<Range> range)
+TextCheckingHelper::TextCheckingHelper(SpellCheckerClient& client, PassRefPtr<Range> range)
     : m_client(&client)
     , m_range(range)
 {
diff --git a/Source/core/editing/TextCheckingHelper.h b/Source/core/editing/TextCheckingHelper.h
index a458524..a69116e 100644
--- a/Source/core/editing/TextCheckingHelper.h
+++ b/Source/core/editing/TextCheckingHelper.h
@@ -21,15 +21,17 @@
 #ifndef TextCheckingHelper_h
 #define TextCheckingHelper_h
 
-#include "core/page/EditorClient.h"
 #include "platform/text/TextChecking.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 class ExceptionState;
+class Frame;
 class Range;
 class Position;
+class SpellCheckerClient;
+class TextCheckerClient;
 struct TextCheckingResult;
 
 class TextCheckingParagraph {
@@ -77,7 +79,7 @@
 class TextCheckingHelper {
     WTF_MAKE_NONCOPYABLE(TextCheckingHelper);
 public:
-    TextCheckingHelper(EditorClient&, PassRefPtr<Range>);
+    TextCheckingHelper(SpellCheckerClient&, PassRefPtr<Range>);
     ~TextCheckingHelper();
 
     String findFirstMisspelling(int& firstMisspellingOffset, bool markAll, RefPtr<Range>& firstMisspellingRange);
@@ -87,7 +89,7 @@
     void markAllBadGrammar();
 
 private:
-    EditorClient* m_client;
+    SpellCheckerClient* m_client;
     RefPtr<Range> m_range;
 
     int findFirstGrammarDetail(const Vector<GrammarDetail>& grammarDetails, int badGrammarPhraseLocation, int startOffset, int endOffset, bool markAll) const;
diff --git a/Source/core/editing/TextIterator.cpp b/Source/core/editing/TextIterator.cpp
index 6707368..275111a 100644
--- a/Source/core/editing/TextIterator.cpp
+++ b/Source/core/editing/TextIterator.cpp
@@ -244,7 +244,6 @@
     , m_emitsOriginalText(behavior & TextIteratorEmitsOriginalText)
     , m_handledFirstLetter(false)
     , m_ignoresStyleVisibility(behavior & TextIteratorIgnoresStyleVisibility)
-    , m_emitsObjectReplacementCharacters(behavior & TextIteratorEmitsObjectReplacementCharacters)
     , m_stopsOnFormControls(behavior & TextIteratorStopsOnFormControls)
     , m_shouldStop(false)
     , m_emitsImageAltText(behavior & TextIteratorEmitsImageAltText)
@@ -386,7 +385,7 @@
         if (!next) {
             next = m_node->nextSibling();
             if (!next) {
-                bool pastEnd = NodeTraversal::next(m_node) == m_pastEndNode;
+                bool pastEnd = NodeTraversal::next(*m_node) == m_pastEndNode;
                 Node* parentNode = m_node->parentOrShadowHostNode();
                 while (!next && parentNode) {
                     if ((pastEnd && parentNode == m_endContainer) || m_endContainer->isDescendantOf(parentNode))
@@ -440,7 +439,7 @@
 
 String TextIterator::substring(unsigned position, unsigned length) const
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(position < static_cast<unsigned>(this->length()));
+    ASSERT_WITH_SECURITY_IMPLICATION(position <= static_cast<unsigned>(this->length()));
     ASSERT_WITH_SECURITY_IMPLICATION(position + length <= static_cast<unsigned>(this->length()));
     if (!length)
         return emptyString();
@@ -678,11 +677,6 @@
 
     m_hasEmitted = true;
 
-    if (m_emitsObjectReplacementCharacters && renderer && renderer->isReplaced()) {
-        emitCharacter(objectReplacementCharacter, m_node->parentNode(), m_node, 0, 1);
-        return true;
-    }
-
     if (m_emitsCharactersBetweenAllVisiblePositions) {
         // We want replaced elements to behave like punctuation for boundary
         // finding, and to simply take up space for the selection preservation
@@ -747,36 +741,36 @@
     return emitsOriginalText || !(node->isInShadowTree() && node->shadowHost()->hasTagName(inputTag));
 }
 
-static bool shouldEmitNewlinesBeforeAndAfterNode(Node* node)
+static bool shouldEmitNewlinesBeforeAndAfterNode(Node& node)
 {
     // Block flow (versus inline flow) is represented by having
     // a newline both before and after the element.
-    RenderObject* r = node->renderer();
+    RenderObject* r = node.renderer();
     if (!r) {
-        return (node->hasTagName(blockquoteTag)
-            || node->hasTagName(ddTag)
-            || node->hasTagName(divTag)
-            || node->hasTagName(dlTag)
-            || node->hasTagName(dtTag)
-            || node->hasTagName(h1Tag)
-            || node->hasTagName(h2Tag)
-            || node->hasTagName(h3Tag)
-            || node->hasTagName(h4Tag)
-            || node->hasTagName(h5Tag)
-            || node->hasTagName(h6Tag)
-            || node->hasTagName(hrTag)
-            || node->hasTagName(liTag)
-            || node->hasTagName(listingTag)
-            || node->hasTagName(olTag)
-            || node->hasTagName(pTag)
-            || node->hasTagName(preTag)
-            || node->hasTagName(trTag)
-            || node->hasTagName(ulTag));
+        return (node.hasTagName(blockquoteTag)
+            || node.hasTagName(ddTag)
+            || node.hasTagName(divTag)
+            || node.hasTagName(dlTag)
+            || node.hasTagName(dtTag)
+            || node.hasTagName(h1Tag)
+            || node.hasTagName(h2Tag)
+            || node.hasTagName(h3Tag)
+            || node.hasTagName(h4Tag)
+            || node.hasTagName(h5Tag)
+            || node.hasTagName(h6Tag)
+            || node.hasTagName(hrTag)
+            || node.hasTagName(liTag)
+            || node.hasTagName(listingTag)
+            || node.hasTagName(olTag)
+            || node.hasTagName(pTag)
+            || node.hasTagName(preTag)
+            || node.hasTagName(trTag)
+            || node.hasTagName(ulTag));
     }
 
     // Need to make an exception for table cells, because they are blocks, but we
     // want them tab-delimited rather than having newlines before and after.
-    if (isTableCell(node))
+    if (isTableCell(&node))
         return false;
 
     // Need to make an exception for table row elements, because they are neither
@@ -791,21 +785,22 @@
         && !r->isFloatingOrOutOfFlowPositioned() && !r->isBody() && !r->isRubyText();
 }
 
-static bool shouldEmitNewlineAfterNode(Node* node)
+static bool shouldEmitNewlineAfterNode(Node& node)
 {
     // FIXME: It should be better but slower to create a VisiblePosition here.
     if (!shouldEmitNewlinesBeforeAndAfterNode(node))
         return false;
     // Check if this is the very last renderer in the document.
     // If so, then we should not emit a newline.
-    while ((node = NodeTraversal::nextSkippingChildren(node))) {
-        if (node->renderer())
+    Node* next = &node;
+    while ((next = NodeTraversal::nextSkippingChildren(*next))) {
+        if (next->renderer())
             return true;
     }
     return false;
 }
 
-static bool shouldEmitNewlineBeforeNode(Node* node)
+static bool shouldEmitNewlineBeforeNode(Node& node)
 {
     return shouldEmitNewlinesBeforeAndAfterNode(node);
 }
@@ -936,7 +931,7 @@
     if (shouldEmitTabBeforeNode(m_node)) {
         if (shouldRepresentNodeOffsetZero())
             emitCharacter('\t', m_node->parentNode(), m_node, 0, 0);
-    } else if (shouldEmitNewlineBeforeNode(m_node)) {
+    } else if (shouldEmitNewlineBeforeNode(*m_node)) {
         if (shouldRepresentNodeOffsetZero())
             emitCharacter('\n', m_node->parentNode(), m_node, 0, 0);
     } else if (shouldEmitSpaceBeforeAndAfterNode(m_node)) {
@@ -974,7 +969,7 @@
     // the logic in _web_attributedStringFromRange match. We'll get that for free when we switch to use
     // TextIterator in _web_attributedStringFromRange.
     // See <rdar://problem/5428427> for an example of how this mismatch will cause problems.
-    if (m_lastTextNode && shouldEmitNewlineAfterNode(m_node)) {
+    if (m_lastTextNode && shouldEmitNewlineAfterNode(*m_node)) {
         // use extra newline to represent margin bottom, as needed
         bool addNewline = shouldEmitExtraNewlineForNode(m_node);
 
@@ -1313,7 +1308,7 @@
 {
     // We can use a linefeed in place of a tab because this simple iterator is only used to
     // find boundaries, not actual content. A linefeed breaks words, sentences, and paragraphs.
-    if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineAfterNode(m_node) || shouldEmitTabBeforeNode(m_node)) {
+    if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineAfterNode(*m_node) || shouldEmitTabBeforeNode(m_node)) {
         unsigned index = m_node->nodeIndex();
         // The start of this emitted range is wrong. Ensuring correctness would require
         // VisiblePositions and so would be slow. previousBoundary expects this.
@@ -1324,7 +1319,7 @@
 
 void SimplifiedBackwardsTextIterator::exitNode()
 {
-    if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineBeforeNode(m_node) || shouldEmitTabBeforeNode(m_node)) {
+    if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineBeforeNode(*m_node) || shouldEmitTabBeforeNode(m_node)) {
         // The start of this emitted range is wrong. Ensuring correctness would require
         // VisiblePositions and so would be slow. previousBoundary expects this.
         emitCharacter('\n', m_node, 0, 0);
diff --git a/Source/core/editing/TextIterator.h b/Source/core/editing/TextIterator.h
index 2e2d2cc..54db7cc 100644
--- a/Source/core/editing/TextIterator.h
+++ b/Source/core/editing/TextIterator.h
@@ -41,10 +41,9 @@
     TextIteratorEmitsCharactersBetweenAllVisiblePositions = 1 << 0,
     TextIteratorEntersTextControls = 1 << 1,
     TextIteratorIgnoresStyleVisibility = 1 << 2,
-    TextIteratorEmitsObjectReplacementCharacters = 1 << 3,
-    TextIteratorEmitsOriginalText = 1 << 4,
-    TextIteratorStopsOnFormControls = 1 << 5,
-    TextIteratorEmitsImageAltText = 1 << 6,
+    TextIteratorEmitsOriginalText = 1 << 3,
+    TextIteratorStopsOnFormControls = 1 << 4,
+    TextIteratorEmitsImageAltText = 1 << 5,
 };
 
 // FIXME: Can't really answer this question correctly without knowing the white-space mode.
@@ -197,8 +196,6 @@
     bool m_handledFirstLetter;
     // Used when the visibility of the style should not affect text gathering.
     bool m_ignoresStyleVisibility;
-    // Used when emitting the special 0xFFFC character is required.
-    bool m_emitsObjectReplacementCharacters;
     // Used when the iteration should stop if form controls are reached.
     bool m_stopsOnFormControls;
     // Used when m_stopsOnFormControls is set to determine if the iterator should keep advancing.
diff --git a/Source/core/editing/TextIteratorTest.cpp b/Source/core/editing/TextIteratorTest.cpp
new file mode 100644
index 0000000..8da44d3
--- /dev/null
+++ b/Source/core/editing/TextIteratorTest.cpp
@@ -0,0 +1,251 @@
+/*
+ * 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/editing/TextIterator.h"
+
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/Node.h"
+#include "core/dom/Range.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/frame/FrameView.h"
+#include "core/html/HTMLDocument.h"
+#include "core/html/HTMLElement.h"
+#include "core/testing/DummyPageHolder.h"
+#include "platform/geometry/IntSize.h"
+#include "wtf/Compiler.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
+#include "wtf/testing/WTFTestHelpers.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class TextIteratorTest : public ::testing::Test {
+protected:
+    virtual void SetUp() OVERRIDE;
+
+    HTMLDocument& document() const;
+
+    Vector<String> iterate(TextIteratorBehavior = TextIteratorDefaultBehavior);
+
+    void setBodyInnerHTML(const char*);
+    PassRefPtr<Range> getBodyRange() const;
+
+private:
+    OwnPtr<DummyPageHolder> m_dummyPageHolder;
+
+    HTMLDocument* m_document;
+};
+
+void TextIteratorTest::SetUp()
+{
+    m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+    m_document = toHTMLDocument(&m_dummyPageHolder->document());
+    ASSERT(m_document);
+}
+
+Vector<String> TextIteratorTest::iterate(TextIteratorBehavior iteratorBehavior)
+{
+    document().view()->updateLayoutAndStyleIfNeededRecursive(); // Force renderers to be created; TextIterator needs them.
+
+    RefPtr<Range> range = getBodyRange();
+    TextIterator textIterator(range.get(), iteratorBehavior);
+    Vector<String> textChunks;
+    while (!textIterator.atEnd()) {
+        textChunks.append(textIterator.substring(0, textIterator.length()));
+        textIterator.advance();
+    }
+    return textChunks;
+}
+
+HTMLDocument& TextIteratorTest::document() const
+{
+    return *m_document;
+}
+
+void TextIteratorTest::setBodyInnerHTML(const char* bodyContent)
+{
+    document().body()->setInnerHTML(String::fromUTF8(bodyContent), ASSERT_NO_EXCEPTION);
+}
+
+PassRefPtr<Range> TextIteratorTest::getBodyRange() const
+{
+    RefPtr<Range> range(Range::create(document()));
+    range->selectNode(document().body());
+    return range.release();
+}
+
+TEST_F(TextIteratorTest, BasicIteration)
+{
+    static const char* input = "<p>Hello, \ntext</p><p>iterator.</p>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        "text",
+        "\n",
+        "\n",
+        "iterator."
+    };
+    Vector<String> expectedTextChunks;
+    expectedTextChunks.append(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(input);
+    Vector<String> actualTextChunks = iterate();
+    EXPECT_EQ(expectedTextChunks, actualTextChunks);
+}
+
+TEST_F(TextIteratorTest, NotEnteringTextControls)
+{
+    static const char* input = "<p>Hello <input type=\"text\" value=\"input\">!</p>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello ",
+        "",
+        "!",
+    };
+    Vector<String> expectedTextChunks;
+    expectedTextChunks.append(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(input);
+    Vector<String> actualTextChunks = iterate();
+    EXPECT_EQ(expectedTextChunks, actualTextChunks);
+}
+
+TEST_F(TextIteratorTest, EnteringTextControlsWithOption)
+{
+    static const char* input = "<p>Hello <input type=\"text\" value=\"input\">!</p>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello ",
+        "\n",
+        "input",
+        "!",
+    };
+    Vector<String> expectedTextChunks;
+    expectedTextChunks.append(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(input);
+    Vector<String> actualTextChunks = iterate(TextIteratorEntersTextControls);
+    EXPECT_EQ(expectedTextChunks, actualTextChunks);
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTree)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+    static const char* shadowContent = "<span>shadow</span>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ", // TextIterator doesn't emit "text" since its renderer is not created. The shadow tree is ignored.
+        " iterator."
+    };
+    Vector<String> expectedTextChunks;
+    expectedTextChunks.append(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    RefPtr<ShadowRoot> shadowRoot = document().getElementById(AtomicString::fromUTF8("host"))->createShadowRoot(ASSERT_NO_EXCEPTION);
+    shadowRoot->setInnerHTML(String::fromUTF8(shadowContent), ASSERT_NO_EXCEPTION);
+
+    Vector<String> actualTextChunks = iterate();
+    EXPECT_EQ(expectedTextChunks, actualTextChunks);
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTreeWithMultipleShadowTrees)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+    static const char* shadowContent1 = "<span>first shadow</span>";
+    static const char* shadowContent2 = "<span>second shadow</span>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        " iterator."
+    };
+    Vector<String> expectedTextChunks;
+    expectedTextChunks.append(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    Element& host = *document().getElementById(AtomicString::fromUTF8("host"));
+    RefPtr<ShadowRoot> shadowRoot1 = host.createShadowRoot(ASSERT_NO_EXCEPTION);
+    shadowRoot1->setInnerHTML(String::fromUTF8(shadowContent1), ASSERT_NO_EXCEPTION);
+    RefPtr<ShadowRoot> shadowRoot2 = host.createShadowRoot(ASSERT_NO_EXCEPTION);
+    shadowRoot2->setInnerHTML(String::fromUTF8(shadowContent2), ASSERT_NO_EXCEPTION);
+
+    Vector<String> actualTextChunks = iterate();
+    EXPECT_EQ(expectedTextChunks, actualTextChunks);
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTreeWithNestedShadowTrees)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host-in-document\">text</span> iterator.</div>";
+    static const char* shadowContent1 = "<span>first <span id=\"host-in-shadow\">shadow</span></span>";
+    static const char* shadowContent2 = "<span>second shadow</span>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        " iterator."
+    };
+    Vector<String> expectedTextChunks;
+    expectedTextChunks.append(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    Element& hostInDocument = *document().getElementById(AtomicString::fromUTF8("host-in-document"));
+    RefPtr<ShadowRoot> shadowRoot1 = hostInDocument.createShadowRoot(ASSERT_NO_EXCEPTION);
+    shadowRoot1->setInnerHTML(String::fromUTF8(shadowContent1), ASSERT_NO_EXCEPTION);
+    Element& hostInShadow = *shadowRoot1->getElementById(AtomicString::fromUTF8("host-in-shadow"));
+    RefPtr<ShadowRoot> shadowRoot2 = hostInShadow.createShadowRoot(ASSERT_NO_EXCEPTION);
+    shadowRoot2->setInnerHTML(String::fromUTF8(shadowContent2), ASSERT_NO_EXCEPTION);
+
+    Vector<String> actualTextChunks = iterate();
+    EXPECT_EQ(expectedTextChunks, actualTextChunks);
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTreeWithContentInsertionPoint)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+    static const char* shadowContent = "<span>shadow <content>content</content></span>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        "text", // In this case a renderer for "text" is created, so it shows up here.
+        " iterator."
+    };
+    Vector<String> expectedTextChunks;
+    expectedTextChunks.append(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    Element& host = *document().getElementById(AtomicString::fromUTF8("host"));
+    RefPtr<ShadowRoot> shadowRoot = host.createShadowRoot(ASSERT_NO_EXCEPTION);
+    shadowRoot->setInnerHTML(String::fromUTF8(shadowContent), ASSERT_NO_EXCEPTION);
+
+    Vector<String> actualTextChunks = iterate();
+    EXPECT_EQ(expectedTextChunks, actualTextChunks);
+}
+
+}
diff --git a/Source/core/editing/TypingCommand.cpp b/Source/core/editing/TypingCommand.cpp
index 042d0a8..c68ecda 100644
--- a/Source/core/editing/TypingCommand.cpp
+++ b/Source/core/editing/TypingCommand.cpp
@@ -402,11 +402,11 @@
     VisibleSelection selectionAfterUndo;
 
     switch (endingSelection().selectionType()) {
-    case VisibleSelection::RangeSelection:
+    case RangeSelection:
         selectionToDelete = endingSelection();
         selectionAfterUndo = selectionToDelete;
         break;
-    case VisibleSelection::CaretSelection: {
+    case CaretSelection: {
         // After breaking out of an empty mail blockquote, we still want continue with the deletion
         // so actual content will get deleted, and not just the quote style.
         if (breakOutOfEmptyMailBlockquotedParagraph())
@@ -470,7 +470,7 @@
             selectionAfterUndo.setWithoutValidation(startingSelection().end(), selectionToDelete.extent());
         break;
     }
-    case VisibleSelection::NoSelection:
+    case NoSelection:
         ASSERT_NOT_REACHED();
         break;
     }
@@ -506,11 +506,11 @@
     VisibleSelection selectionAfterUndo;
 
     switch (endingSelection().selectionType()) {
-    case VisibleSelection::RangeSelection:
+    case RangeSelection:
         selectionToDelete = endingSelection();
         selectionAfterUndo = selectionToDelete;
         break;
-    case VisibleSelection::CaretSelection: {
+    case CaretSelection: {
         m_smartDelete = false;
 
         // Handle delete at beginning-of-block case.
@@ -563,7 +563,7 @@
         }
         break;
     }
-    case VisibleSelection::NoSelection:
+    case NoSelection:
         ASSERT_NOT_REACHED();
         break;
     }
diff --git a/Source/core/editing/UndoStack.cpp b/Source/core/editing/UndoStack.cpp
new file mode 100644
index 0000000..953c077
--- /dev/null
+++ b/Source/core/editing/UndoStack.cpp
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2006, 2007 Apple, Inc.  All rights reserved.
+ * 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 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 "UndoStack.h"
+
+#include "core/dom/ContainerNode.h"
+#include "core/editing/UndoStep.h"
+#include "wtf/TemporaryChange.h"
+
+namespace WebCore {
+
+// Arbitrary depth limit for the undo stack, to keep it from using
+// unbounded memory. This is the maximum number of distinct undoable
+// actions -- unbroken stretches of typed characters are coalesced
+// into a single action.
+static const size_t maximumUndoStackDepth = 1000;
+
+UndoStack::UndoStack()
+    : m_inRedo(false)
+{
+}
+
+UndoStack::~UndoStack()
+{
+}
+
+PassOwnPtr<UndoStack> UndoStack::create()
+{
+    return adoptPtr(new UndoStack());
+}
+
+void UndoStack::registerUndoStep(PassRefPtr<UndoStep> step)
+{
+    if (m_undoStack.size() == maximumUndoStackDepth)
+        m_undoStack.removeFirst(); // drop oldest item off the far end
+    if (!m_inRedo)
+        m_redoStack.clear();
+    m_undoStack.append(step);
+}
+
+void UndoStack::registerRedoStep(PassRefPtr<UndoStep> step)
+{
+    m_redoStack.append(step);
+}
+
+void UndoStack::clearUndoRedoOperations()
+{
+    NoEventDispatchAssertion assertNoEventDispatch;
+    m_undoStack.clear();
+    m_redoStack.clear();
+}
+
+bool UndoStack::canUndo() const
+{
+    return !m_undoStack.isEmpty();
+}
+
+bool UndoStack::canRedo() const
+{
+    return !m_redoStack.isEmpty();
+}
+
+void UndoStack::undo()
+{
+    if (canUndo()) {
+        UndoManagerStack::iterator back = --m_undoStack.end();
+        RefPtr<UndoStep> step(*back);
+        m_undoStack.remove(back);
+        step->unapply();
+        // unapply will call us back to push this command onto the redo stack.
+    }
+}
+
+void UndoStack::redo()
+{
+    if (canRedo()) {
+        UndoManagerStack::iterator back = --m_redoStack.end();
+        RefPtr<UndoStep> step(*back);
+        m_redoStack.remove(back);
+
+        ASSERT(!m_inRedo);
+        TemporaryChange<bool> redoScope(m_inRedo, true);
+        step->reapply();
+        // reapply will call us back to push this command onto the undo stack.
+    }
+}
+
+} // namesace WebCore
diff --git a/Source/core/rendering/RenderingConfiguration.h b/Source/core/editing/UndoStack.h
similarity index 70%
copy from Source/core/rendering/RenderingConfiguration.h
copy to Source/core/editing/UndoStack.h
index dc1af6d..4d5e286 100644
--- a/Source/core/rendering/RenderingConfiguration.h
+++ b/Source/core/editing/UndoStack.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google 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
@@ -28,33 +28,40 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderingConfiguration_h
-#define RenderingConfiguration_h
+#ifndef UndoStack_h
+#define UndoStack_h
 
-#include "wtf/Noncopyable.h"
+#include "wtf/Deque.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
-class Document;
+class UndoStep;
 
-class RenderingConfiguration {
-    WTF_MAKE_NONCOPYABLE(RenderingConfiguration);
+class UndoStack {
 public:
-    RenderingConfiguration();
-    ~RenderingConfiguration();
+    static PassOwnPtr<UndoStack> create();
 
-    void update(Document&);
+    ~UndoStack();
 
-    bool inQuirksMode() const { return m_inQuirksMode; }
-    bool paginated() const { return m_paginated; }
-    bool printing() const { return m_printing; }
+    void registerUndoStep(PassRefPtr<UndoStep>);
+    void registerRedoStep(PassRefPtr<UndoStep>);
+    void clearUndoRedoOperations();
+    bool canUndo() const;
+    bool canRedo() const;
+    void undo();
+    void redo();
 
 private:
-    bool m_inQuirksMode;
-    bool m_paginated;
-    bool m_printing;
+    UndoStack();
+
+    bool m_inRedo;
+
+    typedef Deque<RefPtr<UndoStep> > UndoManagerStack;
+    UndoManagerStack m_undoStack;
+    UndoManagerStack m_redoStack;
 };
 
-}
+} // namespace WebCore
 
-#endif // RenderingConfiguration_h
+#endif
diff --git a/Source/core/editing/VisiblePosition.cpp b/Source/core/editing/VisiblePosition.cpp
index 1d1b6f6..b158125 100644
--- a/Source/core/editing/VisiblePosition.cpp
+++ b/Source/core/editing/VisiblePosition.cpp
@@ -749,9 +749,9 @@
     if (!r)
         return false;
     Position p = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
-    TrackExceptionState es;
-    r->setStart(p.containerNode(), p.offsetInContainerNode(), es);
-    return !es.hadException();
+    TrackExceptionState exceptionState;
+    r->setStart(p.containerNode(), p.offsetInContainerNode(), exceptionState);
+    return !exceptionState.hadException();
 }
 
 bool setEnd(Range *r, const VisiblePosition &visiblePosition)
@@ -759,9 +759,9 @@
     if (!r)
         return false;
     Position p = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
-    TrackExceptionState es;
-    r->setEnd(p.containerNode(), p.offsetInContainerNode(), es);
-    return !es.hadException();
+    TrackExceptionState exceptionState;
+    r->setEnd(p.containerNode(), p.offsetInContainerNode(), exceptionState);
+    return !exceptionState.hadException();
 }
 
 Element* enclosingBlockFlowElement(const VisiblePosition &visiblePosition)
diff --git a/Source/core/editing/VisibleSelection.cpp b/Source/core/editing/VisibleSelection.cpp
index 22ed2e3..22bb977 100644
--- a/Source/core/editing/VisibleSelection.cpp
+++ b/Source/core/editing/VisibleSelection.cpp
@@ -218,14 +218,14 @@
         return 0;
 
     RefPtr<Range> searchRange(Range::create(d));
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
 
     Position start(pos.parentAnchoredEquivalent());
-    searchRange->selectNodeContents(boundary, es);
-    searchRange->setStart(start.containerNode(), start.offsetInContainerNode(), es);
+    searchRange->selectNodeContents(boundary, exceptionState);
+    searchRange->setStart(start.containerNode(), start.offsetInContainerNode(), exceptionState);
 
-    ASSERT(!es.hadException());
-    if (es.hadException())
+    ASSERT(!exceptionState.hadException());
+    if (exceptionState.hadException())
         return 0;
 
     return searchRange.release();
diff --git a/Source/core/editing/VisibleSelection.h b/Source/core/editing/VisibleSelection.h
index 5e515f8..e5e9dd0 100644
--- a/Source/core/editing/VisibleSelection.h
+++ b/Source/core/editing/VisibleSelection.h
@@ -26,6 +26,7 @@
 #ifndef VisibleSelection_h
 #define VisibleSelection_h
 
+#include "core/editing/SelectionType.h"
 #include "core/editing/TextGranularity.h"
 #include "core/editing/VisiblePosition.h"
 
@@ -39,8 +40,6 @@
 
 class VisibleSelection {
 public:
-    enum SelectionType { NoSelection, CaretSelection, RangeSelection };
-
     VisibleSelection();
 
     VisibleSelection(const Position&, EAffinity, bool isDirectional = false);
diff --git a/Source/core/editing/VisibleUnits.cpp b/Source/core/editing/VisibleUnits.cpp
index 6041d27..600242c 100644
--- a/Source/core/editing/VisibleUnits.cpp
+++ b/Source/core/editing/VisibleUnits.cpp
@@ -40,7 +40,7 @@
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/htmlediting.h"
 #include "core/rendering/InlineTextBox.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderObject.h"
 #include "platform/text/TextBoundaries.h"
 
@@ -460,11 +460,11 @@
     Vector<UChar, 1024> string;
     unsigned suffixLength = 0;
 
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
     if (requiresContextForWordBoundary(c.characterBefore())) {
         RefPtr<Range> forwardsScanRange(d.createRange());
-        forwardsScanRange->setEndAfter(boundary, es);
-        forwardsScanRange->setStart(end.deprecatedNode(), end.deprecatedEditingOffset(), es);
+        forwardsScanRange->setEndAfter(boundary, exceptionState);
+        forwardsScanRange->setStart(end.deprecatedNode(), end.deprecatedEditingOffset(), exceptionState);
         TextIterator forwardsIterator(forwardsScanRange.get());
         while (!forwardsIterator.atEnd()) {
             Vector<UChar, 1024> characters;
@@ -478,11 +478,11 @@
         }
     }
 
-    searchRange->setStart(start.deprecatedNode(), start.deprecatedEditingOffset(), es);
-    searchRange->setEnd(end.deprecatedNode(), end.deprecatedEditingOffset(), es);
+    searchRange->setStart(start.deprecatedNode(), start.deprecatedEditingOffset(), exceptionState);
+    searchRange->setEnd(end.deprecatedNode(), end.deprecatedEditingOffset(), exceptionState);
 
-    ASSERT(!es.hadException());
-    if (es.hadException())
+    ASSERT(!exceptionState.hadException());
+    if (exceptionState.hadException())
         return VisiblePosition();
 
     SimplifiedBackwardsTextIterator it(searchRange.get());
@@ -913,7 +913,7 @@
 static inline IntPoint absoluteLineDirectionPointToLocalPointInBlock(RootInlineBox* root, int lineDirectionPoint)
 {
     ASSERT(root);
-    RenderBlock* containingBlock = root->block();
+    RenderBlockFlow* containingBlock = root->block();
     FloatPoint absoluteBlockPoint = containingBlock->localToAbsolute(FloatPoint());
     if (containingBlock->hasOverflowClip())
         absoluteBlockPoint -= containingBlock->scrolledContentOffset();
@@ -1115,18 +1115,18 @@
             break;
         if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
             while (n && n->rendererIsEditable() != startNode->rendererIsEditable())
-                n = NodeTraversal::previousPostOrder(n, startBlock);
+                n = NodeTraversal::previousPostOrder(*n, startBlock);
             if (!n || !n->isDescendantOf(highestRoot))
                 break;
         }
         RenderObject* r = n->renderer();
         if (!r) {
-            n = NodeTraversal::previousPostOrder(n, startBlock);
+            n = NodeTraversal::previousPostOrder(*n, startBlock);
             continue;
         }
         RenderStyle* style = r->style();
         if (style->visibility() != VISIBLE) {
-            n = NodeTraversal::previousPostOrder(n, startBlock);
+            n = NodeTraversal::previousPostOrder(*n, startBlock);
             continue;
         }
 
@@ -1149,13 +1149,14 @@
             }
             node = n;
             offset = 0;
-            n = NodeTraversal::previousPostOrder(n, startBlock);
-        } else if (editingIgnoresContent(n) || isTableElement(n)) {
+            n = NodeTraversal::previousPostOrder(*n, startBlock);
+        } else if (editingIgnoresContent(n) || isRenderedTable(n)) {
             node = n;
             type = Position::PositionIsBeforeAnchor;
-            n = n->previousSibling() ? n->previousSibling() : NodeTraversal::previousPostOrder(n, startBlock);
-        } else
-            n = NodeTraversal::previousPostOrder(n, startBlock);
+            n = n->previousSibling() ? n->previousSibling() : NodeTraversal::previousPostOrder(*n, startBlock);
+        } else {
+            n = NodeTraversal::previousPostOrder(*n, startBlock);
+        }
     }
 
     if (type == Position::PositionIsOffsetInAnchor) {
@@ -1191,19 +1192,19 @@
             break;
         if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
             while (n && n->rendererIsEditable() != startNode->rendererIsEditable())
-                n = NodeTraversal::next(n, stayInsideBlock);
+                n = NodeTraversal::next(*n, stayInsideBlock);
             if (!n || !n->isDescendantOf(highestRoot))
                 break;
         }
 
         RenderObject* r = n->renderer();
         if (!r) {
-            n = NodeTraversal::next(n, stayInsideBlock);
+            n = NodeTraversal::next(*n, stayInsideBlock);
             continue;
         }
         RenderStyle* style = r->style();
         if (style->visibility() != VISIBLE) {
-            n = NodeTraversal::next(n, stayInsideBlock);
+            n = NodeTraversal::next(*n, stayInsideBlock);
             continue;
         }
 
@@ -1225,13 +1226,14 @@
             }
             node = n;
             offset = r->caretMaxOffset();
-            n = NodeTraversal::next(n, stayInsideBlock);
-        } else if (editingIgnoresContent(n) || isTableElement(n)) {
+            n = NodeTraversal::next(*n, stayInsideBlock);
+        } else if (editingIgnoresContent(n) || isRenderedTable(n)) {
             node = n;
             type = Position::PositionIsAfterAnchor;
-            n = NodeTraversal::nextSkippingChildren(n, stayInsideBlock);
-        } else
-            n = NodeTraversal::next(n, stayInsideBlock);
+            n = NodeTraversal::nextSkippingChildren(*n, stayInsideBlock);
+        } else {
+            n = NodeTraversal::next(*n, stayInsideBlock);
+        }
     }
 
     if (type == Position::PositionIsOffsetInAnchor)
diff --git a/Source/core/editing/htmlediting.cpp b/Source/core/editing/htmlediting.cpp
index ce132c1..fe77574 100644
--- a/Source/core/editing/htmlediting.cpp
+++ b/Source/core/editing/htmlediting.cpp
@@ -160,7 +160,7 @@
     else
         ASSERT(updateStyle == DoNotUpdateStyle);
 
-    if (node->renderer() && node->renderer()->isTable())
+    if (isTableElement(node))
         node = node->parentNode();
 
     return node->rendererIsEditable(editableType);
@@ -179,7 +179,7 @@
     if (!node)
         return false;
 
-    if (node->renderer() && node->renderer()->isTable())
+    if (isTableElement(node))
         node = node->parentNode();
 
     return node->rendererIsRichlyEditable(editableType);
@@ -191,7 +191,7 @@
     if (!node)
         return 0;
 
-    if (node->renderer() && node->renderer()->isTable())
+    if (isTableElement(node))
         node = node->parentNode();
 
     return node->rootEditableElement(editableType);
@@ -434,7 +434,7 @@
         if (isSpecialElement(n)) {
             VisiblePosition vPos = VisiblePosition(pos, DOWNSTREAM);
             VisiblePosition firstInElement = VisiblePosition(firstPositionInOrBeforeNode(n), DOWNSTREAM);
-            if (isTableElement(n) && vPos == firstInElement.next())
+            if (isRenderedTable(n) && vPos == firstInElement.next())
                 return n;
             if (vPos == firstInElement)
                 return n;
@@ -449,7 +449,7 @@
         if (isSpecialElement(n)) {
             VisiblePosition vPos = VisiblePosition(pos, DOWNSTREAM);
             VisiblePosition lastInElement = VisiblePosition(lastPositionInOrAfterNode(n), DOWNSTREAM);
-            if (isTableElement(n) && vPos == lastInElement.previous())
+            if (isRenderedTable(n) && vPos == lastInElement.previous())
                 return n;
             if (vPos == lastInElement)
                 return n;
@@ -526,12 +526,12 @@
 // Create a range object with two visible positions, start and end.
 // create(Document*, const Position&, const Position&); will use deprecatedEditingOffset
 // Use this function instead of create a regular range object (avoiding editing offset).
-PassRefPtr<Range> createRange(Document& document, const VisiblePosition& start, const VisiblePosition& end, ExceptionState& es)
+PassRefPtr<Range> createRange(Document& document, const VisiblePosition& start, const VisiblePosition& end, ExceptionState& exceptionState)
 {
     RefPtr<Range> selectedRange = Range::create(document);
-    selectedRange->setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), es);
-    if (!es.hadException())
-        selectedRange->setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), es);
+    selectedRange->setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
+    if (!exceptionState.hadException())
+        selectedRange->setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
     return selectedRange.release();
 }
 
@@ -605,12 +605,12 @@
 {
     for (Node* n = node->firstChild(); n;) {
         if (n == excludedNode) {
-            n = NodeTraversal::nextSkippingChildren(n, node);
+            n = NodeTraversal::nextSkippingChildren(*n, node);
             continue;
         }
         if (n->renderer())
             return true;
-        n = NodeTraversal::next(n, node);
+        n = NodeTraversal::next(*n, node);
     }
     return false;
 }
@@ -752,14 +752,21 @@
     // Make sure there is no visible content between this li and the previous list
 }
 
-// FIXME: do not require renderer, so that this can be used within fragments, or rename to isRenderedTable()
-bool isTableElement(Node* n)
+bool isTableElement(const Node* node)
 {
-    if (!n || !n->isElementNode())
+    if (!node || !node->isElementNode())
         return false;
 
-    RenderObject* renderer = n->renderer();
-    return (renderer && (renderer->style()->display() == TABLE || renderer->style()->display() == INLINE_TABLE));
+    return node->hasTagName(tableTag);
+}
+
+bool isRenderedTable(const Node* node)
+{
+    if (!node || !node->isElementNode())
+        return false;
+
+    RenderObject* renderer = node->renderer();
+    return (renderer && renderer->isTable());
 }
 
 bool isTableCell(const Node* node)
@@ -839,12 +846,12 @@
 
 PassRefPtr<HTMLElement> createHTMLElement(Document& document, const QualifiedName& name)
 {
-    return HTMLElementFactory::createHTMLElement(name, &document, 0, false);
+    return createHTMLElement(document, name.localName());
 }
 
 PassRefPtr<HTMLElement> createHTMLElement(Document& document, const AtomicString& tagName)
 {
-    return createHTMLElement(document, QualifiedName(nullAtom, tagName, xhtmlNamespaceURI));
+    return HTMLElementFactory::createHTMLElement(tagName, document, 0, false);
 }
 
 bool isTabSpanNode(const Node *node)
diff --git a/Source/core/editing/htmlediting.h b/Source/core/editing/htmlediting.h
index fa03d45..1d7e52c 100644
--- a/Source/core/editing/htmlediting.h
+++ b/Source/core/editing/htmlediting.h
@@ -101,7 +101,8 @@
 bool isTabSpanNode(const Node*);
 bool isTabSpanTextNode(const Node*);
 bool isMailBlockquote(const Node*);
-bool isTableElement(Node*);
+bool isRenderedTable(const Node*);
+bool isTableElement(const Node*);
 bool isTableCell(const Node*);
 bool isEmptyTableCell(const Node*);
 bool isTableStructureNode(const Node*);
diff --git a/Source/core/editing/markup.cpp b/Source/core/editing/markup.cpp
index 2a644be..abf6797 100644
--- a/Source/core/editing/markup.cpp
+++ b/Source/core/editing/markup.cpp
@@ -58,7 +58,7 @@
 #include "core/html/HTMLTextFormControlElement.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/RenderObject.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -93,13 +93,13 @@
     String m_value;
 };
 
-static void completeURLs(DocumentFragment* fragment, const String& baseURL)
+static void completeURLs(DocumentFragment& fragment, const String& baseURL)
 {
     Vector<AttributeChange> changes;
 
     KURL parsedBaseURL(ParsedURLString, baseURL);
 
-    for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(element, fragment)) {
+    for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(*element, &fragment)) {
         if (!element->hasAttributes())
             continue;
         unsigned length = element->attributeCount();
@@ -355,7 +355,7 @@
         if (!n)
             break;
 
-        next = NodeTraversal::next(n);
+        next = NodeTraversal::next(*n);
         bool openedTag = false;
 
         if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
@@ -363,7 +363,7 @@
             continue;
 
         if (!n->renderer() && !enclosingNodeWithTag(firstPositionInOrBeforeNode(n), selectTag)) {
-            next = NodeTraversal::nextSkippingChildren(n);
+            next = NodeTraversal::nextSkippingChildren(*n);
             // Don't skip over pastEnd.
             if (pastEnd && pastEnd->isDescendantOf(n))
                 next = pastEnd;
@@ -648,7 +648,7 @@
     fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
 
     if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
-        completeURLs(fragment.get(), baseURL);
+        completeURLs(*fragment, baseURL);
 
     return fragment.release();
 }
@@ -657,7 +657,7 @@
 
 static bool findNodesSurroundingContext(Document* document, RefPtr<Node>& nodeBeforeContext, RefPtr<Node>& nodeAfterContext)
 {
-    for (Node* node = document->firstChild(); node; node = NodeTraversal::next(node)) {
+    for (Node* node = document->firstChild(); node; node = NodeTraversal::next(*node)) {
         if (node->nodeType() == Node::COMMENT_NODE && toCharacterData(node)->data() == fragmentMarkerTag) {
             if (!nodeBeforeContext)
                 nodeBeforeContext = node;
@@ -675,10 +675,10 @@
     RefPtr<Node> next;
     for (RefPtr<Node> node = fragment->firstChild(); node; node = next) {
         if (nodeBeforeContext->isDescendantOf(node.get())) {
-            next = NodeTraversal::next(node.get());
+            next = NodeTraversal::next(*node);
             continue;
         }
-        next = NodeTraversal::nextSkippingChildren(node.get());
+        next = NodeTraversal::nextSkippingChildren(*node);
         ASSERT(!node->contains(nodeAfterContext));
         node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
         if (nodeBeforeContext == node)
@@ -687,7 +687,7 @@
 
     ASSERT(nodeAfterContext->parentNode());
     for (RefPtr<Node> node = nodeAfterContext; node; node = next) {
-        next = NodeTraversal::nextSkippingChildren(node.get());
+        next = NodeTraversal::nextSkippingChildren(*node);
         node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
     }
 }
@@ -943,7 +943,7 @@
     return markup.toString();
 }
 
-PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& es)
+PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& exceptionState)
 {
     Document& document = contextElement->hasTagName(templateTag) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
@@ -955,7 +955,7 @@
 
     bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
     if (!wasValid) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute(method, "Node", "The provided markup is invalid XML, and therefore cannot be inserted into an XML document."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute(method, "Node", "The provided markup is invalid XML, and therefore cannot be inserted into an XML document."));
         return 0;
     }
     return fragment.release();
@@ -996,16 +996,16 @@
     fragment->removeChild(element);
 }
 
-PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& es)
+PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& exceptionState)
 {
     ASSERT(element);
     if (element->ieForbidsInsertHTML() || element->hasLocalName(colTag) || element->hasLocalName(colgroupTag) || element->hasLocalName(framesetTag)
         || element->hasLocalName(headTag) || element->hasLocalName(styleTag) || element->hasLocalName(titleTag)) {
-        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container is '" + element->localName() + "', which is not supported."));
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container is '" + element->localName() + "', which is not supported."));
         return 0;
     }
 
-    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", es);
+    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", exceptionState);
     if (!fragment)
         return 0;
 
@@ -1026,7 +1026,7 @@
     return fragment.release();
 }
 
-void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& es)
+void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& exceptionState)
 {
     ASSERT(container);
     RefPtr<ContainerNode> containerNode(container);
@@ -1044,15 +1044,15 @@
     }
 
     if (containerNode->hasOneChild()) {
-        containerNode->replaceChild(fragment, containerNode->firstChild(), es);
+        containerNode->replaceChild(fragment, containerNode->firstChild(), exceptionState);
         return;
     }
 
     containerNode->removeChildren();
-    containerNode->appendChild(fragment, es);
+    containerNode->appendChild(fragment, exceptionState);
 }
 
-void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& es)
+void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& exceptionState)
 {
     ASSERT(container);
     RefPtr<ContainerNode> containerNode(container);
@@ -1067,15 +1067,15 @@
     RefPtr<Text> textNode = Text::create(containerNode->document(), text);
 
     if (containerNode->hasOneChild()) {
-        containerNode->replaceChild(textNode.release(), containerNode->firstChild(), es);
+        containerNode->replaceChild(textNode.release(), containerNode->firstChild(), exceptionState);
         return;
     }
 
     containerNode->removeChildren();
-    containerNode->appendChild(textNode.release(), es);
+    containerNode->appendChild(textNode.release(), exceptionState);
 }
 
-void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& es)
+void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& exceptionState)
 {
     ASSERT(node && node->isTextNode());
     Node* next = node->nextSibling();
@@ -1086,7 +1086,7 @@
     RefPtr<Text> textNext = toText(next);
     textNode->appendData(textNext->data());
     if (textNext->parentNode()) // Might have been removed by mutation event.
-        textNext->remove(es);
+        textNext->remove(exceptionState);
 }
 
 }
diff --git a/Source/core/events/CustomEvent.idl b/Source/core/events/CustomEvent.idl
index 0afe8fe..bb29521 100644
--- a/Source/core/events/CustomEvent.idl
+++ b/Source/core/events/CustomEvent.idl
@@ -26,7 +26,7 @@
 [
     ConstructorTemplate=Event
 ] interface CustomEvent : Event {
-    [CustomGetter, InitializedByEventConstructor] readonly attribute any detail;
+    [Custom=Getter, InitializedByEventConstructor] readonly attribute any detail;
 
     [Custom] void initCustomEvent([Default=Undefined] optional DOMString typeArg,
                                   [Default=Undefined] optional boolean canBubbleArg,
diff --git a/Source/core/events/ErrorEvent.idl b/Source/core/events/ErrorEvent.idl
index 1a5d21a..8106592 100644
--- a/Source/core/events/ErrorEvent.idl
+++ b/Source/core/events/ErrorEvent.idl
@@ -35,6 +35,6 @@
     [InitializedByEventConstructor] readonly attribute DOMString filename;
     [InitializedByEventConstructor] readonly attribute unsigned long lineno;
     [InitializedByEventConstructor] readonly attribute unsigned long colno;
-    [CustomGetter, InitializedByEventConstructor, Unserializable] readonly attribute any error;
+    [Custom=Getter, InitializedByEventConstructor, Unserializable] readonly attribute any error;
 };
 
diff --git a/Source/core/events/Event.idl b/Source/core/events/Event.idl
index 49b4914..50eaf86 100644
--- a/Source/core/events/Event.idl
+++ b/Source/core/events/Event.idl
@@ -20,9 +20,8 @@
 
 // Introduced in DOM Level 2:
 [
-    CustomToV8,
-    ConstructorTemplate=Event
-
+    CustomWrap,
+    ConstructorTemplate=Event,
 ] interface Event {
 
     // DOM PhaseType
@@ -74,5 +73,5 @@
 
     [RuntimeEnabled=ShadowDOM] readonly attribute NodeList path;
 
-    [CustomGetter] readonly attribute Clipboard clipboardData;
+    [Custom=Getter] readonly attribute Clipboard clipboardData;
 };
diff --git a/Source/core/events/EventDispatcher.cpp b/Source/core/events/EventDispatcher.cpp
index a3d74a6..77d3793 100644
--- a/Source/core/events/EventDispatcher.cpp
+++ b/Source/core/events/EventDispatcher.cpp
@@ -71,7 +71,7 @@
     ScopedEventQueue::instance()->enqueueEventDispatchMediator(mediator);
 }
 
-void EventDispatcher::dispatchSimulatedClick(Node* node, Event* underlyingEvent, SimulatedClickMouseEventOptions mouseEventOptions, SimulatedClickVisualOptions visualOptions)
+void EventDispatcher::dispatchSimulatedClick(Node* node, Event* underlyingEvent, SimulatedClickMouseEventOptions mouseEventOptions)
 {
     if (isDisabledFormControl(node))
         return;
@@ -88,7 +88,7 @@
 
     if (mouseEventOptions != SendNoEvents)
         EventDispatcher(node, SimulatedMouseEvent::create(EventTypeNames::mousedown, node->document().domWindow(), underlyingEvent)).dispatch();
-    node->setActive(true, visualOptions == ShowPressedLook);
+    node->setActive(true);
     if (mouseEventOptions != SendNoEvents)
         EventDispatcher(node, SimulatedMouseEvent::create(EventTypeNames::mouseup, node->document().domWindow(), underlyingEvent)).dispatch();
     node->setActive(false);
diff --git a/Source/core/events/EventDispatcher.h b/Source/core/events/EventDispatcher.h
index 6607627..aae65a2 100644
--- a/Source/core/events/EventDispatcher.h
+++ b/Source/core/events/EventDispatcher.h
@@ -54,7 +54,7 @@
     static bool dispatchEvent(Node*, PassRefPtr<EventDispatchMediator>);
     static void dispatchScopedEvent(Node*, PassRefPtr<EventDispatchMediator>);
 
-    static void dispatchSimulatedClick(Node*, Event* underlyingEvent, SimulatedClickMouseEventOptions, SimulatedClickVisualOptions);
+    static void dispatchSimulatedClick(Node*, Event* underlyingEvent, SimulatedClickMouseEventOptions);
 
     bool dispatch();
     Node* node() const { return m_node.get(); }
diff --git a/Source/core/events/EventPath.cpp b/Source/core/events/EventPath.cpp
index 086d53c..954ef21 100644
--- a/Source/core/events/EventPath.cpp
+++ b/Source/core/events/EventPath.cpp
@@ -204,28 +204,28 @@
 }
 
 #ifndef NDEBUG
-static inline bool movedFromChildToParent(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
-{
-    return lastTreeScope.parentTreeScope() == &currentTreeScope;
-}
-
 static inline bool movedFromOlderToYounger(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
 {
     Node* rootNode = lastTreeScope.rootNode();
     return rootNode->isShadowRoot() && toShadowRoot(rootNode)->youngerShadowRoot() == currentTreeScope.rootNode();
 }
-#endif
-
-static inline bool movedFromParentToChild(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
-{
-    return currentTreeScope.parentTreeScope() == &lastTreeScope;
-}
 
 static inline bool movedFromYoungerToOlder(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
 {
     Node* rootNode = lastTreeScope.rootNode();
     return rootNode->isShadowRoot() && toShadowRoot(rootNode)->olderShadowRoot() == currentTreeScope.rootNode();
 }
+#endif
+
+static inline bool movedFromChildToParent(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
+{
+    return lastTreeScope.parentTreeScope() == &currentTreeScope;
+}
+
+static inline bool movedFromParentToChild(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
+{
+    return currentTreeScope.parentTreeScope() == &lastTreeScope;
+}
 
 void EventPath::calculateAdjustedTargets()
 {
@@ -239,14 +239,21 @@
         if (targetStack.isEmpty()) {
             targetStack.append(current);
         } else if (*lastTreeScope != currentTreeScope && !isSVGElement) {
-            if (movedFromParentToChild(*lastTreeScope, currentTreeScope) || movedFromYoungerToOlder(*lastTreeScope, currentTreeScope)) {
+            if (movedFromParentToChild(*lastTreeScope, currentTreeScope)) {
                 targetStack.append(targetStack.last());
-            } else {
-                ASSERT(movedFromChildToParent(*lastTreeScope, currentTreeScope) || movedFromOlderToYounger(*lastTreeScope, currentTreeScope));
+            } else if (movedFromChildToParent(*lastTreeScope, currentTreeScope)) {
                 ASSERT(!targetStack.isEmpty());
                 targetStack.removeLast();
                 if (targetStack.isEmpty())
                     targetStack.append(current);
+            } else {
+                ASSERT(movedFromYoungerToOlder(*lastTreeScope, currentTreeScope) || movedFromOlderToYounger(*lastTreeScope, currentTreeScope));
+                ASSERT(!targetStack.isEmpty());
+                targetStack.removeLast();
+                if (targetStack.isEmpty())
+                    targetStack.append(current);
+                else
+                    targetStack.append(targetStack.last());
             }
         }
         at(i).setTarget(eventTargetRespectingTargetRules(targetStack.last()));
diff --git a/Source/core/events/EventTarget.cpp b/Source/core/events/EventTarget.cpp
index 0c93217..56c3fbe 100644
--- a/Source/core/events/EventTarget.cpp
+++ b/Source/core/events/EventTarget.cpp
@@ -155,18 +155,18 @@
     return removeEventListener(eventType, listener, false);
 }
 
-bool EventTarget::dispatchEvent(PassRefPtr<Event> event, ExceptionState& es)
+bool EventTarget::dispatchEvent(PassRefPtr<Event> event, ExceptionState& exceptionState)
 {
     if (!event) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event provided is null."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event provided is null."));
         return false;
     }
     if (event->type().isEmpty()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event provided is uninitialized."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event provided is uninitialized."));
         return false;
     }
     if (event->isBeingDispatched()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event is already being dispatched."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event is already being dispatched."));
         return false;
     }
 
@@ -299,7 +299,11 @@
         if (DOMWindow* executingWindow = this->executingWindow()) {
             if (executingWindow->top())
                 UseCounter::count(executingWindow, UseCounter::SubFrameBeforeUnloadFired);
+            UseCounter::count(executingWindow, UseCounter::DocumentBeforeUnloadFired);
         }
+    } else if (event->type() == EventTypeNames::unload) {
+        if (DOMWindow* executingWindow = this->executingWindow())
+            UseCounter::count(executingWindow, UseCounter::DocumentUnloadFired);
     }
 
     bool userEventWasHandled = false;
diff --git a/Source/core/events/EventTarget.idl b/Source/core/events/EventTarget.idl
index 7c87036..ce9dac4 100644
--- a/Source/core/events/EventTarget.idl
+++ b/Source/core/events/EventTarget.idl
@@ -20,7 +20,6 @@
 
 [
     CustomToV8,
-    DoNotGenerateWrap
 ] interface EventTarget {
     void addEventListener(DOMString type,
                           EventListener listener,
diff --git a/Source/core/events/EventTargetFactory.in b/Source/core/events/EventTargetFactory.in
index a69ca1d..2f36e12 100644
--- a/Source/core/events/EventTargetFactory.in
+++ b/Source/core/events/EventTargetFactory.in
@@ -38,6 +38,7 @@
 modules/mediastream/RTCDataChannel
 modules/mediastream/RTCPeerConnection
 modules/notifications/Notification
+modules/serviceworkers/ServiceWorkerGlobalScope
 modules/speech/SpeechRecognition
 modules/speech/SpeechSynthesisUtterance
 modules/webaudio/AudioContext Conditional=WEB_AUDIO
diff --git a/Source/core/events/EventTypeNames.in b/Source/core/events/EventTypeNames.in
index 8863a45..4241c2a 100644
--- a/Source/core/events/EventTypeNames.in
+++ b/Source/core/events/EventTypeNames.in
@@ -11,6 +11,7 @@
 DOMNodeRemovedFromDocument
 DOMSubtreeModified
 abort
+activate
 addsourcebuffer
 addstream
 addtrack
@@ -75,6 +76,7 @@
 enter
 error
 exit
+fetch
 focus
 focusin
 focusout
@@ -89,6 +91,7 @@
 icecandidate
 iceconnectionstatechange
 input
+install
 invalid
 keydown
 keypress
@@ -180,6 +183,7 @@
 updatestart
 upgradeneeded
 versionchange
+visibilitychange
 voiceschanged
 volumechange
 waiting
diff --git a/Source/core/events/GenericEventQueue.cpp b/Source/core/events/GenericEventQueue.cpp
index 7c47fb4..b35f85c 100644
--- a/Source/core/events/GenericEventQueue.cpp
+++ b/Source/core/events/GenericEventQueue.cpp
@@ -89,11 +89,11 @@
     m_pendingEvents.swap(pendingEvents);
 
     RefPtr<EventTarget> protect(m_owner);
-    for (unsigned i = 0; i < pendingEvents.size(); ++i) {
+    for (size_t i = 0; i < pendingEvents.size(); ++i) {
         Event* event = pendingEvents[i].get();
         EventTarget* target = event->target() ? event->target() : m_owner;
         CString type(event->type().string().ascii());
-        TRACE_EVENT_ASYNC_STEP1("event", "GenericEventQueue:enqueueEvent", event, "dispatch", "type", type);
+        TRACE_EVENT_ASYNC_STEP_INTO1("event", "GenericEventQueue:enqueueEvent", event, "dispatch", "type", type);
         target->dispatchEvent(pendingEvents[i].release());
         TRACE_EVENT_ASYNC_END1("event", "GenericEventQueue:enqueueEvent", event, "type", type);
     }
@@ -102,14 +102,17 @@
 void GenericEventQueue::close()
 {
     m_isClosed = true;
-
-    m_timer.stop();
-    m_pendingEvents.clear();
+    cancelAllEvents();
 }
 
 void GenericEventQueue::cancelAllEvents()
 {
     m_timer.stop();
+
+    for (size_t i = 0; i < m_pendingEvents.size(); ++i) {
+        Event* event = m_pendingEvents[i].get();
+        TRACE_EVENT_ASYNC_END2("event", "GenericEventQueue:enqueueEvent", event, "type", event->type().string().ascii(), "status", "cancelled");
+    }
     m_pendingEvents.clear();
 }
 
diff --git a/Source/core/events/KeyboardEvent.cpp b/Source/core/events/KeyboardEvent.cpp
index 2255e72..c03712e 100644
--- a/Source/core/events/KeyboardEvent.cpp
+++ b/Source/core/events/KeyboardEvent.cpp
@@ -24,8 +24,8 @@
 #include "core/events/KeyboardEvent.h"
 
 #include "core/events/ThreadLocalEventNames.h"
-#include "core/platform/WindowsKeyboardCodes.h"
 #include "platform/PlatformKeyboardEvent.h"
+#include "platform/WindowsKeyboardCodes.h"
 
 namespace WebCore {
 
diff --git a/Source/core/events/MessageEvent.idl b/Source/core/events/MessageEvent.idl
index 33d1c33..417e2b6 100644
--- a/Source/core/events/MessageEvent.idl
+++ b/Source/core/events/MessageEvent.idl
@@ -32,7 +32,7 @@
     [InitializedByEventConstructor] readonly attribute DOMString origin;
     [InitializedByEventConstructor] readonly attribute DOMString lastEventId;
     [InitializedByEventConstructor] readonly attribute EventTarget source; // May be a Window or a MessagePort
-    [InitializedByEventConstructor, CustomGetter] readonly attribute any data;
+    [InitializedByEventConstructor, Custom=Getter] readonly attribute any data;
     [InitializedByEventConstructor] readonly attribute MessagePort[] ports;
 
     [Custom] void initMessageEvent([Default=Undefined] optional DOMString typeArg,
diff --git a/Source/core/events/PopStateEvent.idl b/Source/core/events/PopStateEvent.idl
index 20ddbaa..b5a7f73 100644
--- a/Source/core/events/PopStateEvent.idl
+++ b/Source/core/events/PopStateEvent.idl
@@ -27,5 +27,5 @@
 [
     ConstructorTemplate=Event
 ] interface PopStateEvent : Event {
-    [InitializedByEventConstructor, CustomGetter] readonly attribute any state;
+    [InitializedByEventConstructor, Custom=Getter] readonly attribute any state;
 };
diff --git a/Source/core/fetch/CSSStyleSheetResource.h b/Source/core/fetch/CSSStyleSheetResource.h
index 3ecf34b..986e991 100644
--- a/Source/core/fetch/CSSStyleSheetResource.h
+++ b/Source/core/fetch/CSSStyleSheetResource.h
@@ -26,14 +26,14 @@
 #ifndef CSSStyleSheetResource_h
 #define CSSStyleSheetResource_h
 
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 
+class CSSParserContext;
 class ResourceClient;
 class StyleSheetContents;
 class TextResourceDecoder;
-struct CSSParserContext;
 
 class CSSStyleSheetResource : public Resource {
 public:
@@ -56,12 +56,14 @@
 protected:
     virtual void checkNotify();
 
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
     String m_decodedSheetText;
 
     RefPtr<StyleSheetContents> m_parsedStyleSheetCache;
 };
 
+DEFINE_RESOURCE_TYPE_CASTS(CSSStyleSheet);
+
 }
 
 #endif
diff --git a/Source/core/fetch/CrossOriginAccessControl.cpp b/Source/core/fetch/CrossOriginAccessControl.cpp
index feb858e..401254c 100644
--- a/Source/core/fetch/CrossOriginAccessControl.cpp
+++ b/Source/core/fetch/CrossOriginAccessControl.cpp
@@ -30,7 +30,7 @@
 #include "platform/network/HTTPParsers.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Threading.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/StringBuilder.h"
diff --git a/Source/core/fetch/DocumentResource.h b/Source/core/fetch/DocumentResource.h
index efa77d9..f05d171 100644
--- a/Source/core/fetch/DocumentResource.h
+++ b/Source/core/fetch/DocumentResource.h
@@ -47,9 +47,12 @@
     PassRefPtr<Document> createDocument(const KURL&);
 
     RefPtr<Document> m_document;
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
 };
 
+DEFINE_TYPE_CASTS(DocumentResource, Resource, resource, resource->type() == Resource::SVGDocument, resource.type() == Resource::SVGDocument); \
+inline DocumentResource* toDocumentResource(const ResourcePtr<Resource>& ptr) { return toDocumentResource(ptr.get()); }
+
 class DocumentResourceClient : public ResourceClient {
 public:
     virtual ~DocumentResourceClient() { }
diff --git a/Source/core/fetch/FetchRequest.cpp b/Source/core/fetch/FetchRequest.cpp
index d8d9512..ef7ca22 100644
--- a/Source/core/fetch/FetchRequest.cpp
+++ b/Source/core/fetch/FetchRequest.cpp
@@ -40,6 +40,7 @@
     , m_priority(priority)
     , m_forPreload(false)
     , m_defer(NoDefer)
+    , m_originRestriction(UseDefaultOriginRestrictionForType)
 {
     m_options.initiatorInfo.name = initiator;
 }
@@ -50,6 +51,7 @@
     , m_priority(ResourceLoadPriorityUnresolved)
     , m_forPreload(false)
     , m_defer(NoDefer)
+    , m_originRestriction(UseDefaultOriginRestrictionForType)
 {
     m_options.initiatorInfo.name = initiator;
 }
@@ -60,6 +62,7 @@
     , m_priority(ResourceLoadPriorityUnresolved)
     , m_forPreload(false)
     , m_defer(NoDefer)
+    , m_originRestriction(UseDefaultOriginRestrictionForType)
 {
     m_options.initiatorInfo = initiator;
 }
@@ -68,11 +71,9 @@
 {
 }
 
-void FetchRequest::setPotentiallyCrossOriginEnabled(SecurityOrigin* origin, StoredCredentials allowCredentials)
+void FetchRequest::setCrossOriginAccessControl(SecurityOrigin* origin, StoredCredentials allowCredentials)
 {
     updateRequestForAccessControl(m_resourceRequest, origin, allowCredentials);
-    ASSERT(m_options.requestOriginPolicy == UseDefaultOriginRestrictionsForType); // Allows only tightening from the default value.
-    m_options.requestOriginPolicy = PotentiallyCrossOriginEnabled;
 }
 
 } // namespace WebCore
diff --git a/Source/core/fetch/FetchRequest.h b/Source/core/fetch/FetchRequest.h
index f913937..1954ced 100644
--- a/Source/core/fetch/FetchRequest.h
+++ b/Source/core/fetch/FetchRequest.h
@@ -39,6 +39,7 @@
 class FetchRequest {
 public:
     enum DeferOption { NoDefer, DeferredByClient };
+    enum OriginRestriction { UseDefaultOriginRestrictionForType, RestrictToSameOrigin };
 
     explicit FetchRequest(const ResourceRequest&, const AtomicString& initiator, const String& charset = String(), ResourceLoadPriority = ResourceLoadPriorityUnresolved);
     FetchRequest(const ResourceRequest&, const AtomicString& initiator, const ResourceLoaderOptions&);
@@ -58,7 +59,9 @@
     DeferOption defer() const { return m_defer; }
     void setDefer(DeferOption defer) { m_defer = defer; }
     void setContentSecurityCheck(ContentSecurityPolicyCheck contentSecurityPolicyOption) { m_options.contentSecurityPolicyOption = contentSecurityPolicyOption; }
-    void setPotentiallyCrossOriginEnabled(SecurityOrigin*, StoredCredentials);
+    void setCrossOriginAccessControl(SecurityOrigin*, StoredCredentials);
+    OriginRestriction originRestriction() const { return m_originRestriction; }
+    void setOriginRestriction(OriginRestriction restriction) { m_originRestriction = restriction; }
 
 private:
     ResourceRequest m_resourceRequest;
@@ -67,6 +70,7 @@
     ResourceLoadPriority m_priority;
     bool m_forPreload;
     DeferOption m_defer;
+    OriginRestriction m_originRestriction;
 };
 
 } // namespace WebCore
diff --git a/Source/core/fetch/FontResource.cpp b/Source/core/fetch/FontResource.cpp
index 8e4cf13..22ff2c5 100644
--- a/Source/core/fetch/FontResource.cpp
+++ b/Source/core/fetch/FontResource.cpp
@@ -79,7 +79,6 @@
         ResourceClientWalker<FontResourceClient> walker(m_clients);
         while (FontResourceClient* client = walker.next())
             client->didStartFontLoad(this);
-        m_histograms.loadStarted();
     }
 }
 
@@ -109,7 +108,7 @@
     if (!m_externalSVGDocument && !errorOccurred() && !isLoading() && m_data) {
         m_externalSVGDocument = SVGDocument::create();
 
-        RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
+        OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
         String svgSource = decoder->decode(m_data->data(), m_data->size());
         svgSource.append(decoder->flush());
 
@@ -165,36 +164,4 @@
         c->fontLoaded(this);
 }
 
-void FontResource::willUseFontData()
-{
-    if (!isLoaded())
-        m_histograms.willUseFontData();
-}
-
-FontResource::FontResourceHistograms::~FontResourceHistograms()
-{
-    if (m_styledTime > 0)
-        WebKit::Platform::current()->histogramEnumeration("WebFont.Resource.UsageType", StyledButNotUsed, UsageTypeMax);
-}
-
-void FontResource::FontResourceHistograms::willUseFontData()
-{
-    if (!m_styledTime)
-        m_styledTime = currentTimeMS();
-}
-
-void FontResource::FontResourceHistograms::loadStarted()
-{
-    if (m_styledTime < 0)
-        return;
-    if (!m_styledTime) {
-        WebKit::Platform::current()->histogramEnumeration("WebFont.Resource.UsageType", NotStyledButUsed, UsageTypeMax);
-    } else {
-        int duration = static_cast<int>(currentTimeMS() - m_styledTime);
-        WebKit::Platform::current()->histogramCustomCounts("WebFont.Resource.StyleRecalcToDownloadLatency", duration, 0, 10000, 50);
-        WebKit::Platform::current()->histogramEnumeration("WebFont.Resource.UsageType", StyledAndUsed, UsageTypeMax);
-    }
-    m_styledTime = -1;
-}
-
 }
diff --git a/Source/core/fetch/FontResource.h b/Source/core/fetch/FontResource.h
index 4666820..8d700ba 100644
--- a/Source/core/fetch/FontResource.h
+++ b/Source/core/fetch/FontResource.h
@@ -26,8 +26,8 @@
 #ifndef FontResource_h
 #define FontResource_h
 
-#include "core/fetch/Resource.h"
 #include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "platform/fonts/FontOrientation.h"
 #include "platform/fonts/FontWidthVariant.h"
 #include "wtf/OwnPtr.h"
@@ -50,7 +50,6 @@
     virtual void didAddClient(ResourceClient*);
 
     virtual void allClientsRemoved();
-    void willUseFontData();
     void beginLoadIfNeeded(ResourceFetcher* dl);
     bool stillNeedsLoad() const { return !m_loadInitiated; }
 
@@ -70,26 +69,12 @@
 #if ENABLE(SVG_FONTS)
     RefPtr<WebCore::SVGDocument> m_externalSVGDocument;
 #endif
-    class FontResourceHistograms {
-    public:
-        enum UsageType {
-            StyledAndUsed,
-            StyledButNotUsed,
-            NotStyledButUsed,
-            UsageTypeMax
-        };
-        FontResourceHistograms() : m_styledTime(0) { }
-        ~FontResourceHistograms();
-        void willUseFontData();
-        void loadStarted();
-    private:
-        double m_styledTime;
-    };
-    FontResourceHistograms m_histograms;
 
     friend class MemoryCache;
 };
 
+DEFINE_RESOURCE_TYPE_CASTS(Font);
+
 class FontResourceClient : public ResourceClient {
 public:
     virtual ~FontResourceClient() { }
diff --git a/Source/core/fetch/ImageResource.cpp b/Source/core/fetch/ImageResource.cpp
index 4827b2e..9a8a71d 100644
--- a/Source/core/fetch/ImageResource.cpp
+++ b/Source/core/fetch/ImageResource.cpp
@@ -113,7 +113,7 @@
         for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
             switchContainerSizeRequests.set(it->key, it->value);
         Resource::switchClientsToRevalidatedResource();
-        ImageResource* revalidatedImageResource = static_cast<ImageResource*>(resourceToRevalidate());
+        ImageResource* revalidatedImageResource = toImageResource(resourceToRevalidate());
         for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
             revalidatedImageResource->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
         return;
@@ -133,12 +133,12 @@
 pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
 {
     if (deviceScaleFactor >= 2) {
-        DEFINE_STATIC_LOCAL(RefPtr<WebCore::Image>, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
-        return std::make_pair(brokenImageHiRes.get(), 2);
+        DEFINE_STATIC_REF(WebCore::Image, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
+        return std::make_pair(brokenImageHiRes, 2);
     }
 
-    DEFINE_STATIC_LOCAL(RefPtr<WebCore::Image>, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
-    return std::make_pair(brokenImageLoRes.get(), 1);
+    DEFINE_STATIC_REF(WebCore::Image, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
+    return std::make_pair(brokenImageLoRes, 1);
 }
 
 bool ImageResource::willPaintBrokenImage() const
diff --git a/Source/core/fetch/ImageResource.h b/Source/core/fetch/ImageResource.h
index 2092d9f..01e0747 100644
--- a/Source/core/fetch/ImageResource.h
+++ b/Source/core/fetch/ImageResource.h
@@ -23,12 +23,12 @@
 #ifndef ImageResource_h
 #define ImageResource_h
 
-#include "core/fetch/Resource.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "core/platform/graphics/IntSizeHash.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/svg/graphics/SVGImageCache.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/geometry/IntSizeHash.h"
 #include "platform/geometry/LayoutSize.h"
+#include "platform/graphics/ImageObserver.h"
 #include "wtf/HashMap.h"
 
 namespace WebCore {
@@ -127,6 +127,8 @@
     bool m_hasDevicePixelRatioHeaderValue;
 };
 
+DEFINE_RESOURCE_TYPE_CASTS(Image);
+
 }
 
 #endif
diff --git a/Source/core/fetch/ImageResourceTest.cpp b/Source/core/fetch/ImageResourceTest.cpp
index 2949e32..c54767e 100644
--- a/Source/core/fetch/ImageResourceTest.cpp
+++ b/Source/core/fetch/ImageResourceTest.cpp
@@ -37,13 +37,10 @@
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/loader/EmptyClients.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
-#include "core/page/Page.h"
+#include "core/testing/DummyPageHolder.h"
+#include "core/testing/UnitTestHelpers.h"
 #include "platform/SharedBuffer.h"
 #include "public/platform/Platform.h"
-#include "public/platform/WebThread.h"
 #include "public/platform/WebURL.h"
 #include "public/platform/WebURLResponse.h"
 #include "public/platform/WebUnitTestSupport.h"
@@ -52,20 +49,6 @@
 
 namespace {
 
-class QuitTask : public WebKit::WebThread::Task {
-public:
-    virtual void run()
-    {
-        WebKit::Platform::current()->currentThread()->exitRunLoop();
-    }
-};
-
-void runPendingTasks()
-{
-    WebKit::Platform::current()->currentThread()->postTask(new QuitTask);
-    WebKit::Platform::current()->currentThread()->enterRunLoop();
-}
-
 TEST(ImageResourceTest, MultipartImage)
 {
     ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest());
@@ -114,23 +97,17 @@
 {
     KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html");
 
-    WebKit::WebURLResponse response;
+    blink::WebURLResponse response;
     response.initialize();
     response.setMIMEType("text/html");
-    WTF::String localPath = WebKit::Platform::current()->unitTestSupport()->webKitRootDir();
+    WTF::String localPath = blink::Platform::current()->unitTestSupport()->webKitRootDir();
     localPath.append("/Source/web/tests/data/cancelTest.html");
-    WebKit::Platform::current()->unitTestSupport()->registerMockedURL(testURL, response, localPath);
+    blink::Platform::current()->unitTestSupport()->registerMockedURL(testURL, response, localPath);
 
     // Create enough of a mocked world to get a functioning ResourceLoader.
-    Page::PageClients pageClients;
-    fillWithEmptyClients(pageClients);
-    EmptyFrameLoaderClient frameLoaderClient;
-    Page page(pageClients);
-    RefPtr<Frame> frame = Frame::create(FrameInit::create(0, &page, &frameLoaderClient));
-    frame->setView(FrameView::create(frame.get()));
-    frame->init();
+    OwnPtr<DummyPageHolder> dummyPageHolder = DummyPageHolder::create();
     RefPtr<DocumentLoader> documentLoader = DocumentLoader::create(ResourceRequest(testURL), SubstituteData());
-    documentLoader->setFrame(frame.get());
+    documentLoader->setFrame(&dummyPageHolder->frame());
 
     // Emulate starting a real load.
     ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest(testURL));
@@ -147,11 +124,11 @@
     EXPECT_NE(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL));
 
     // Trigger the cancel timer, ensure the load was cancelled and the resource was evicted from the cache.
-    runPendingTasks();
+    WebCore::testing::runPendingTasks();
     EXPECT_EQ(Resource::LoadError, cachedImage->status());
     EXPECT_EQ(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL));
 
-    WebKit::Platform::current()->unitTestSupport()->unregisterMockedURL(testURL);
+    blink::Platform::current()->unitTestSupport()->unregisterMockedURL(testURL);
 }
 
 } // namespace
diff --git a/Source/core/fetch/MemoryCache.cpp b/Source/core/fetch/MemoryCache.cpp
index 22ce954..b82e4fb 100644
--- a/Source/core/fetch/MemoryCache.cpp
+++ b/Source/core/fetch/MemoryCache.cpp
@@ -33,9 +33,9 @@
 #include "core/workers/WorkerThread.h"
 #include "platform/Logging.h"
 #include "platform/TraceEvent.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOriginHash.h"
 #include "public/platform/Platform.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityOriginHash.h"
 #include "wtf/Assertions.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MathExtras.h"
@@ -92,7 +92,7 @@
 MemoryCache::~MemoryCache()
 {
     if (m_prunePending)
-        WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
+        blink::Platform::current()->currentThread()->removeTaskObserver(this);
 }
 
 KURL MemoryCache::removeFragmentIdentifierIfNeeded(const KURL& originalURL)
@@ -595,7 +595,7 @@
             pruneNow(currentTime); // Delay exceeded, prune now.
         } else {
             // Defer.
-            WebKit::Platform::current()->currentThread()->addTaskObserver(this);
+            blink::Platform::current()->currentThread()->addTaskObserver(this);
             m_prunePending = true;
         }
     }
@@ -630,7 +630,7 @@
 {
     if (m_prunePending) {
         m_prunePending = false;
-        WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
+        blink::Platform::current()->currentThread()->removeTaskObserver(this);
     }
 
     TemporaryChange<bool> reentrancyProtector(m_inPruneResources, true);
diff --git a/Source/core/fetch/MemoryCache.h b/Source/core/fetch/MemoryCache.h
index ba1d2ca..178680c 100644
--- a/Source/core/fetch/MemoryCache.h
+++ b/Source/core/fetch/MemoryCache.h
@@ -59,7 +59,7 @@
 // Enable this macro to periodically log information about the memory cache.
 #undef MEMORY_CACHE_STATS
 
-class MemoryCache : public WebKit::WebThread::TaskObserver {
+class MemoryCache : public blink::WebThread::TaskObserver {
     WTF_MAKE_NONCOPYABLE(MemoryCache); WTF_MAKE_FAST_ALLOCATED;
 public:
     MemoryCache();
diff --git a/Source/core/fetch/MemoryCacheTest.cpp b/Source/core/fetch/MemoryCacheTest.cpp
index 9432f9e..21962b1 100644
--- a/Source/core/fetch/MemoryCacheTest.cpp
+++ b/Source/core/fetch/MemoryCacheTest.cpp
@@ -149,7 +149,7 @@
     cachedLiveResource->addClient(&client);
     cachedLiveResource->appendData(data, 4);
 
-    class Task1 : public WebKit::WebThread::Task {
+    class Task1 : public blink::WebThread::Task {
     public:
         Task1(const ResourcePtr<Resource>& live, const ResourcePtr<Resource>& dead)
             : m_live(live)
@@ -183,7 +183,7 @@
         ResourcePtr<Resource> m_live, m_dead;
     };
 
-    class Task2 : public WebKit::WebThread::Task {
+    class Task2 : public blink::WebThread::Task {
     public:
         Task2(unsigned liveSizeWithoutDecode)
             : m_liveSizeWithoutDecode(liveSizeWithoutDecode) { }
@@ -193,7 +193,7 @@
             // Next task: now, the live resource was evicted.
             ASSERT_EQ(0u, memoryCache()->deadSize());
             ASSERT_EQ(m_liveSizeWithoutDecode, memoryCache()->liveSize());
-            WebKit::Platform::current()->currentThread()->exitRunLoop();
+            blink::Platform::current()->currentThread()->exitRunLoop();
         }
 
     private:
@@ -201,9 +201,9 @@
     };
 
 
-    WebKit::Platform::current()->currentThread()->postTask(new Task1(cachedLiveResource, cachedDeadResource));
-    WebKit::Platform::current()->currentThread()->postTask(new Task2(cachedLiveResource->encodedSize() + cachedLiveResource->overheadSize()));
-    WebKit::Platform::current()->currentThread()->enterRunLoop();
+    blink::Platform::current()->currentThread()->postTask(new Task1(cachedLiveResource, cachedDeadResource));
+    blink::Platform::current()->currentThread()->postTask(new Task2(cachedLiveResource->encodedSize() + cachedLiveResource->overheadSize()));
+    blink::Platform::current()->currentThread()->enterRunLoop();
     cachedLiveResource->removeClient(&client);
 }
 
diff --git a/Source/core/fetch/RawResource.cpp b/Source/core/fetch/RawResource.cpp
index 2cfda84..9df4f4e 100644
--- a/Source/core/fetch/RawResource.cpp
+++ b/Source/core/fetch/RawResource.cpp
@@ -131,7 +131,6 @@
     // FIXME: This list of headers that don't affect cache policy almost certainly isn't complete.
     DEFINE_STATIC_LOCAL(HashSet<AtomicString>, m_headers, ());
     if (m_headers.isEmpty()) {
-        m_headers.add("Accept");
         m_headers.add("Cache-Control");
         m_headers.add("If-Modified-Since");
         m_headers.add("If-None-Match");
diff --git a/Source/core/fetch/RawResource.h b/Source/core/fetch/RawResource.h
index 0ed0bc0..1cdbddd 100644
--- a/Source/core/fetch/RawResource.h
+++ b/Source/core/fetch/RawResource.h
@@ -23,8 +23,8 @@
 #ifndef RawResource_h
 #define RawResource_h
 
-#include "core/fetch/Resource.h"
 #include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 class RawResourceCallback;
@@ -71,6 +71,18 @@
     Vector<RedirectPair> m_redirectChain;
 };
 
+#ifdef SECURITY_ASSERT_ENABLED
+inline bool isRawResource(const Resource& resource)
+{
+    Resource::Type type = resource.type();
+    return type == Resource::MainResource || type == Resource::Raw || type == Resource::TextTrack || type == Resource::ImportResource;
+}
+#endif
+inline RawResource* toRawResource(const ResourcePtr<Resource>& resource)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!resource || isRawResource(*resource.get()));
+    return static_cast<RawResource*>(resource.get());
+}
 
 class RawResourceClient : public ResourceClient {
 public:
diff --git a/Source/core/rendering/RenderingConfiguration.cpp b/Source/core/fetch/RawResourceTest.cpp
similarity index 60%
copy from Source/core/rendering/RenderingConfiguration.cpp
copy to Source/core/fetch/RawResourceTest.cpp
index 77060a3..b61c7e6 100644
--- a/Source/core/rendering/RenderingConfiguration.cpp
+++ b/Source/core/fetch/RawResourceTest.cpp
@@ -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
@@ -29,28 +29,37 @@
  */
 
 #include "config.h"
-#include "core/rendering/RenderingConfiguration.h"
+#include "core/fetch/RawResource.h"
 
-#include "core/dom/Document.h"
+#include "core/fetch/ImageResourceClient.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/MockImageResourceClient.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/testing/DummyPageHolder.h"
+#include "core/testing/UnitTestHelpers.h"
+#include "platform/SharedBuffer.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebURL.h"
+#include "public/platform/WebURLResponse.h"
+#include "public/platform/WebUnitTestSupport.h"
 
-namespace WebCore {
+using namespace WebCore;
 
-RenderingConfiguration::RenderingConfiguration()
-    : m_inQuirksMode(false)
-    , m_paginated(false)
-    , m_printing(false)
+namespace {
+
+TEST(RawResourceTest, DontIgnoreAcceptForCacheReuse)
 {
+    ResourceRequest jpegRequest;
+    jpegRequest.setHTTPAccept("image/jpeg");
+
+    RawResource jpegResource(jpegRequest, Resource::Raw);
+
+    ResourceRequest pngRequest;
+    pngRequest.setHTTPAccept("image/png");
+
+    ASSERT_FALSE(jpegResource.canReuse(pngRequest));
 }
 
-RenderingConfiguration::~RenderingConfiguration()
-{
-}
-
-void RenderingConfiguration::update(Document& document)
-{
-    m_inQuirksMode = document.inQuirksMode();
-    m_paginated = document.paginated();
-    m_printing = document.printing();
-}
-
-}
+} // namespace
diff --git a/Source/core/fetch/Resource.cpp b/Source/core/fetch/Resource.cpp
index f3b012a..bd61fe3 100644
--- a/Source/core/fetch/Resource.cpp
+++ b/Source/core/fetch/Resource.cpp
@@ -36,8 +36,8 @@
 #include "platform/Logging.h"
 #include "platform/PurgeableBuffer.h"
 #include "platform/SharedBuffer.h"
+#include "platform/weborigin/KURL.h"
 #include "public/platform/Platform.h"
-#include "weborigin/KURL.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MathExtras.h"
 #include "wtf/RefCountedLeakCounter.h"
@@ -351,7 +351,7 @@
 
     m_cachedMetadata = CachedMetadata::create(dataTypeID, data, size);
     const Vector<char>& serializedData = m_cachedMetadata->serialize();
-    WebKit::Platform::current()->cacheMetadata(m_response.url(), m_response.responseTime(), serializedData.data(), serializedData.size());
+    blink::Platform::current()->cacheMetadata(m_response.url(), m_response.responseTime(), serializedData.data(), serializedData.size());
 }
 
 CachedMetadata* Resource::cachedMetadata(unsigned dataTypeID) const
@@ -363,7 +363,7 @@
 
 void Resource::setCacheLiveResourcePriority(CacheLiveResourcePriority priority)
 {
-    if (inCache() && m_inLiveDecodedResourcesList && m_cacheLiveResourcePriority != priority) {
+    if (inCache() && m_inLiveDecodedResourcesList && cacheLiveResourcePriority() != static_cast<unsigned>(priority)) {
         memoryCache()->removeFromLiveDecodedResourcesList(this);
         m_cacheLiveResourcePriority = priority;
         memoryCache()->insertInLiveDecodedResourcesList(this);
diff --git a/Source/core/fetch/Resource.h b/Source/core/fetch/Resource.h
index dfb7825..d5bbd7a 100644
--- a/Source/core/fetch/Resource.h
+++ b/Source/core/fetch/Resource.h
@@ -364,6 +364,10 @@
 const char* ResourceTypeName(Resource::Type);
 #endif
 
+#define DEFINE_RESOURCE_TYPE_CASTS(typeName) \
+    DEFINE_TYPE_CASTS(typeName##Resource, Resource, resource, resource->type() == Resource::typeName, resource.type() == Resource::typeName); \
+    inline typeName##Resource* to##typeName##Resource(const ResourcePtr<Resource>& ptr) { return to##typeName##Resource(ptr.get()); }
+
 }
 
 #endif
diff --git a/Source/core/fetch/ResourceFetcher.cpp b/Source/core/fetch/ResourceFetcher.cpp
index 651050f..e224698 100644
--- a/Source/core/fetch/ResourceFetcher.cpp
+++ b/Source/core/fetch/ResourceFetcher.cpp
@@ -61,10 +61,10 @@
 #include "core/page/Settings.h"
 #include "platform/Logging.h"
 #include "platform/TraceEvent.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/WTFString.h"
 
@@ -146,9 +146,9 @@
     const KURL& url = request.url();
     ASSERT(url.protocolIsData());
 
-    WebKit::WebString mimetype;
-    WebKit::WebString charset;
-    RefPtr<SharedBuffer> data = PassRefPtr<SharedBuffer>(WebKit::Platform::current()->parseDataURL(url, mimetype, charset));
+    blink::WebString mimetype;
+    blink::WebString charset;
+    RefPtr<SharedBuffer> data = PassRefPtr<SharedBuffer>(blink::Platform::current()->parseDataURL(url, mimetype, charset));
     if (!data)
         return 0;
     ResourceResponse response(url, mimetype, data->size(), charset, String());
@@ -278,7 +278,7 @@
     if (Frame* f = frame()) {
         if (f->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal) {
             KURL requestURL = request.resourceRequest().url();
-            if (requestURL.isValid() && canRequest(Resource::Image, requestURL, request.options(), request.forPreload()))
+            if (requestURL.isValid() && canRequest(Resource::Image, requestURL, request.options(), request.forPreload(), request.originRestriction()))
                 PingLoader::loadImage(f, requestURL);
             return 0;
         }
@@ -288,7 +288,7 @@
         preCacheDataURIImage(request);
 
     request.setDefer(clientDefersImage(request.resourceRequest().url()) ? FetchRequest::DeferredByClient : FetchRequest::NoDefer);
-    return static_cast<ImageResource*>(requestResource(Resource::Image, request).get());
+    return toImageResource(requestResource(Resource::Image, request));
 }
 
 void ResourceFetcher::preCacheDataURIImage(const FetchRequest& request)
@@ -305,22 +305,22 @@
 
 ResourcePtr<FontResource> ResourceFetcher::fetchFont(FetchRequest& request)
 {
-    return static_cast<FontResource*>(requestResource(Resource::Font, request).get());
+    return toFontResource(requestResource(Resource::Font, request));
 }
 
 ResourcePtr<ShaderResource> ResourceFetcher::fetchShader(FetchRequest& request)
 {
-    return static_cast<ShaderResource*>(requestResource(Resource::Shader, request).get());
+    return toShaderResource(requestResource(Resource::Shader, request));
 }
 
 ResourcePtr<RawResource> ResourceFetcher::fetchImport(FetchRequest& request)
 {
-    return static_cast<RawResource*>(requestResource(Resource::ImportResource, request).get());
+    return toRawResource(requestResource(Resource::ImportResource, request));
 }
 
 ResourcePtr<CSSStyleSheetResource> ResourceFetcher::fetchCSSStyleSheet(FetchRequest& request)
 {
-    return static_cast<CSSStyleSheetResource*>(requestResource(Resource::CSSStyleSheet, request).get());
+    return toCSSStyleSheetResource(requestResource(Resource::CSSStyleSheet, request));
 }
 
 ResourcePtr<CSSStyleSheetResource> ResourceFetcher::fetchUserCSSStyleSheet(FetchRequest& request)
@@ -329,28 +329,28 @@
 
     if (Resource* existing = memoryCache()->resourceForURL(url)) {
         if (existing->type() == Resource::CSSStyleSheet)
-            return static_cast<CSSStyleSheetResource*>(existing);
+            return toCSSStyleSheetResource(existing);
         memoryCache()->remove(existing);
     }
 
-    request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType, DocumentContext));
-    return static_cast<CSSStyleSheetResource*>(requestResource(Resource::CSSStyleSheet, request).get());
+    request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
+    return toCSSStyleSheetResource(requestResource(Resource::CSSStyleSheet, request));
 }
 
 ResourcePtr<ScriptResource> ResourceFetcher::fetchScript(FetchRequest& request)
 {
-    return static_cast<ScriptResource*>(requestResource(Resource::Script, request).get());
+    return toScriptResource(requestResource(Resource::Script, request));
 }
 
 ResourcePtr<XSLStyleSheetResource> ResourceFetcher::fetchXSLStyleSheet(FetchRequest& request)
 {
     ASSERT(RuntimeEnabledFeatures::xsltEnabled());
-    return static_cast<XSLStyleSheetResource*>(requestResource(Resource::XSLStyleSheet, request).get());
+    return toXSLStyleSheetResource(requestResource(Resource::XSLStyleSheet, request));
 }
 
 ResourcePtr<DocumentResource> ResourceFetcher::fetchSVGDocument(FetchRequest& request)
 {
-    return static_cast<DocumentResource*>(requestResource(Resource::SVGDocument, request).get());
+    return toDocumentResource(requestResource(Resource::SVGDocument, request));
 }
 
 ResourcePtr<Resource> ResourceFetcher::fetchLinkResource(Resource::Type type, FetchRequest& request)
@@ -362,12 +362,12 @@
 
 ResourcePtr<RawResource> ResourceFetcher::fetchRawResource(FetchRequest& request)
 {
-    return static_cast<RawResource*>(requestResource(Resource::Raw, request).get());
+    return toRawResource(requestResource(Resource::Raw, request));
 }
 
 ResourcePtr<RawResource> ResourceFetcher::fetchMainResource(FetchRequest& request)
 {
-    return static_cast<RawResource*>(requestResource(Resource::MainResource, request).get());
+    return toRawResource(requestResource(Resource::MainResource, request));
 }
 
 bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url, MixedContentBlockingTreatment treatment) const
@@ -422,7 +422,7 @@
     return true;
 }
 
-bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload)
+bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload, FetchRequest::OriginRestriction originRestriction)
 {
     if (document() && !document()->securityOrigin()->canDisplay(url)) {
         if (!forPreload)
@@ -451,7 +451,7 @@
     case Resource::ImportResource:
         // By default these types of resources can be loaded from any origin.
         // FIXME: Are we sure about Resource::Font?
-        if (options.requestOriginPolicy == RestrictToSameOrigin && !m_document->securityOrigin()->canRequest(url)) {
+        if (originRestriction == FetchRequest::RestrictToSameOrigin && !m_document->securityOrigin()->canRequest(url)) {
             printAccessDeniedMessage(url);
             return false;
         }
@@ -523,17 +523,17 @@
     return true;
 }
 
-bool ResourceFetcher::canAccess(Resource* resource)
+bool ResourceFetcher::canAccess(Resource* resource, CORSEnabled corsEnabled, FetchRequest::OriginRestriction originRestriction)
 {
     // Redirects can change the response URL different from one of request.
-    if (!canRequest(resource->type(), resource->response().url(), resource->options(), false))
+    if (!canRequest(resource->type(), resource->response().url(), resource->options(), false, originRestriction))
         return false;
 
     String error;
     switch (resource->type()) {
     case Resource::Script:
     case Resource::ImportResource:
-        if (resource->options().requestOriginPolicy == PotentiallyCrossOriginEnabled
+        if (corsEnabled == PotentiallyCORSEnabled
             && !m_document->securityOrigin()->canRequest(resource->response().url())
             && !resource->passesAccessControlCheck(m_document->securityOrigin(), error)) {
             if (frame() && frame()->document())
@@ -584,7 +584,7 @@
     if (!url.isValid())
         return 0;
 
-    if (!canRequest(type, url, request.options(), request.forPreload()))
+    if (!canRequest(type, url, request.options(), request.forPreload(), request.originRestriction()))
         return 0;
 
     if (Frame* f = frame())
@@ -860,8 +860,9 @@
         return Reload;
     }
 
-    // During the initial load, avoid loading the same resource multiple times for a single document, even if the cache policies would tell us to.
-    if (document() && !document()->loadEventFinished() && m_validatedURLs.contains(existingResource->url()))
+    // During the initial load, avoid loading the same resource multiple times for a single document,
+    // even if the cache policies would tell us to. Raw resources are exempted.
+    if (type != Resource::Raw && document() && !document()->loadEventFinished() && m_validatedURLs.contains(existingResource->url()))
         return Use;
 
     // CachePolicyReload always reloads
@@ -1081,7 +1082,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");
+    TRACE_EVENT_ASYNC_STEP_INTO0("net", "Resource", resource.get(), "Preload");
     resource->increasePreloadCount();
 
     if (!m_preloads)
@@ -1149,7 +1150,7 @@
 
 void ResourceFetcher::didChangeLoadingPriority(const Resource* resource, ResourceLoadPriority loadPriority)
 {
-    TRACE_EVENT_ASYNC_STEP1("net", "Resource", resource, "ChangePriority", "priority", loadPriority);
+    TRACE_EVENT_ASYNC_STEP_INTO1("net", "Resource", resource, "ChangePriority", "priority", loadPriority);
     context().dispatchDidChangeResourcePriority(resource->identifier(), loadPriority);
 }
 
@@ -1254,7 +1255,7 @@
 
 bool ResourceFetcher::shouldRequest(Resource* resource, const ResourceRequest& request, const ResourceLoaderOptions& options)
 {
-    if (!canRequest(resource->type(), request.url(), options))
+    if (!canRequest(resource->type(), request.url(), options, false, FetchRequest::UseDefaultOriginRestrictionForType))
         return false;
     if (resource->type() == Resource::Image && shouldDeferImageLoad(request.url()))
         return false;
@@ -1322,7 +1323,7 @@
 
 const ResourceLoaderOptions& ResourceFetcher::defaultResourceOptions()
 {
-    DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, DoSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType, DocumentContext));
+    DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, DoSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
     return options;
 }
 
diff --git a/Source/core/fetch/ResourceFetcher.h b/Source/core/fetch/ResourceFetcher.h
index 979c632..6437801 100644
--- a/Source/core/fetch/ResourceFetcher.h
+++ b/Source/core/fetch/ResourceFetcher.h
@@ -60,6 +60,11 @@
 class ResourceTimingInfo;
 class ResourceLoaderSet;
 
+enum CORSEnabled {
+    NotCORSEnabled,
+    PotentiallyCORSEnabled // Indicates "potentially CORS-enabled fetch" in HTML standard.
+};
+
 // The ResourceFetcher provides a per-context interface to the MemoryCache
 // and enforces a bunch of security checks and rules for resource revalidation.
 // Its lifetime is roughly per-DocumentLoader, in that it is generally created
@@ -128,7 +133,7 @@
     void preload(Resource::Type, FetchRequest&, const String& charset);
     void checkForPendingPreloads();
     void printPreloadStats();
-    bool canAccess(Resource*);
+    bool canAccess(Resource*, CORSEnabled, FetchRequest::OriginRestriction = FetchRequest::UseDefaultOriginRestrictionForType);
 
     void setDefersLoading(bool);
     void stopFetching();
@@ -176,7 +181,7 @@
     ResourceRequestCachePolicy resourceRequestCachePolicy(const ResourceRequest&, Resource::Type);
     void addAdditionalRequestHeaders(ResourceRequest&, Resource::Type);
 
-    bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload = false);
+    bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload, FetchRequest::OriginRestriction);
     bool checkInsecureContent(Resource::Type, const KURL&, MixedContentBlockingTreatment) const;
 
     static bool resourceNeedsLoad(Resource*, const FetchRequest&, RevalidationPolicy);
diff --git a/Source/core/fetch/ResourceLoader.cpp b/Source/core/fetch/ResourceLoader.cpp
index f361a58..2ecf81d 100644
--- a/Source/core/fetch/ResourceLoader.cpp
+++ b/Source/core/fetch/ResourceLoader.cpp
@@ -148,9 +148,9 @@
     RELEASE_ASSERT(m_connectionState == ConnectionStateNew);
     m_connectionState = ConnectionStateStarted;
 
-    m_loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
+    m_loader = adoptPtr(blink::Platform::current()->createURLLoader());
     ASSERT(m_loader);
-    WebKit::WrappedResourceRequest wrappedRequest(m_request);
+    blink::WrappedResourceRequest wrappedRequest(m_request);
     wrappedRequest.setAllowStoredCredentials(m_options.allowCredentials == AllowStoredCredentials);
     m_loader->loadAsynchronously(wrappedRequest, this);
 }
@@ -161,6 +161,7 @@
     ASSERT(m_loader);
     m_loader->cancel();
     m_loader.clear();
+    m_request.setPriority(ResourceLoadPriorityHighest);
     m_connectionState = ConnectionStateNew;
     requestSynchronously();
 }
@@ -177,7 +178,7 @@
     }
 }
 
-void ResourceLoader::didDownloadData(WebKit::WebURLLoader*, int length, int encodedDataLength)
+void ResourceLoader::didDownloadData(blink::WebURLLoader*, int length, int encodedDataLength)
 {
     RefPtr<ResourceLoader> protect(this);
     RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse);
@@ -201,7 +202,7 @@
 {
     if (m_loader) {
         m_host->didChangeLoadingPriority(m_resource, loadPriority);
-        m_loader->didChangePriority(static_cast<WebKit::WebURLRequest::Priority>(loadPriority));
+        m_loader->didChangePriority(static_cast<blink::WebURLRequest::Priority>(loadPriority));
     }
 }
 
@@ -252,7 +253,7 @@
         releaseResources();
 }
 
-void ResourceLoader::willSendRequest(WebKit::WebURLLoader*, WebKit::WebURLRequest& passedRequest, const WebKit::WebURLResponse& passedRedirectResponse)
+void ResourceLoader::willSendRequest(blink::WebURLLoader*, blink::WebURLRequest& passedRequest, const blink::WebURLResponse& passedRedirectResponse)
 {
     RefPtr<ResourceLoader> protect(this);
 
@@ -275,21 +276,21 @@
     m_request = request;
 }
 
-void ResourceLoader::didReceiveCachedMetadata(WebKit::WebURLLoader*, const char* data, int length)
+void ResourceLoader::didReceiveCachedMetadata(blink::WebURLLoader*, const char* data, int length)
 {
     RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse || m_connectionState == ConnectionStateReceivingData);
     ASSERT(m_state == Initialized);
     m_resource->setSerializedCachedMetadata(data, length);
 }
 
-void ResourceLoader::didSendData(WebKit::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+void ResourceLoader::didSendData(blink::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
     ASSERT(m_state == Initialized);
     RefPtr<ResourceLoader> protect(this);
     m_resource->didSendData(bytesSent, totalBytesToBeSent);
 }
 
-void ResourceLoader::didReceiveResponse(WebKit::WebURLLoader*, const WebKit::WebURLResponse& response)
+void ResourceLoader::didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse& response)
 {
     ASSERT(!response.isNull());
     ASSERT(m_state == Initialized);
@@ -330,7 +331,7 @@
     cancel();
 }
 
-void ResourceLoader::didReceiveData(WebKit::WebURLLoader*, const char* data, int length, int encodedDataLength)
+void ResourceLoader::didReceiveData(blink::WebURLLoader*, const char* data, int length, int encodedDataLength)
 {
     RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse || m_connectionState == ConnectionStateReceivingData);
     m_connectionState = ConnectionStateReceivingData;
@@ -352,7 +353,7 @@
     m_resource->appendData(data, length);
 }
 
-void ResourceLoader::didFinishLoading(WebKit::WebURLLoader*, double finishTime)
+void ResourceLoader::didFinishLoading(blink::WebURLLoader*, double finishTime)
 {
     RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse || m_connectionState == ConnectionStateReceivingData);
     m_connectionState = ConnectionStateFinishedLoading;
@@ -374,7 +375,7 @@
     releaseResources();
 }
 
-void ResourceLoader::didFail(WebKit::WebURLLoader*, const WebKit::WebURLError& error)
+void ResourceLoader::didFail(blink::WebURLLoader*, const blink::WebURLError& error)
 {
     m_connectionState = ConnectionStateFailed;
     ASSERT(m_state != Terminated);
@@ -405,7 +406,7 @@
 
 void ResourceLoader::requestSynchronously()
 {
-    OwnPtr<WebKit::WebURLLoader> loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
+    OwnPtr<blink::WebURLLoader> loader = adoptPtr(blink::Platform::current()->createURLLoader());
     ASSERT(loader);
 
     RefPtr<ResourceLoader> protect(this);
@@ -415,12 +416,12 @@
     RELEASE_ASSERT(m_connectionState == ConnectionStateNew);
     m_connectionState = ConnectionStateStarted;
 
-    WebKit::WrappedResourceRequest requestIn(m_request);
+    blink::WrappedResourceRequest requestIn(m_request);
     requestIn.setAllowStoredCredentials(m_options.allowCredentials == AllowStoredCredentials);
-    WebKit::WebURLResponse responseOut;
+    blink::WebURLResponse responseOut;
     responseOut.initialize();
-    WebKit::WebURLError errorOut;
-    WebKit::WebData dataOut;
+    blink::WebURLError errorOut;
+    blink::WebData dataOut;
     loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut);
     if (errorOut.reason) {
         didFail(0, errorOut);
diff --git a/Source/core/fetch/ResourceLoader.h b/Source/core/fetch/ResourceLoader.h
index d7c90a5..814cecf 100644
--- a/Source/core/fetch/ResourceLoader.h
+++ b/Source/core/fetch/ResourceLoader.h
@@ -44,7 +44,7 @@
 class ResourceResponse;
 class ResourceLoaderHost;
 
-class ResourceLoader : public RefCounted<ResourceLoader>, protected WebKit::WebURLLoaderClient {
+class ResourceLoader : public RefCounted<ResourceLoader>, protected blink::WebURLLoaderClient {
 public:
     static PassRefPtr<ResourceLoader> create(ResourceLoaderHost*, Resource*, const ResourceRequest&, const ResourceLoaderOptions&);
     virtual ~ResourceLoader();
@@ -67,14 +67,14 @@
     void didChangePriority(ResourceLoadPriority);
 
     // WebURLLoaderClient
-    virtual void willSendRequest(WebKit::WebURLLoader*, WebKit::WebURLRequest&, const WebKit::WebURLResponse& redirectResponse) OVERRIDE;
-    virtual void didSendData(WebKit::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
-    virtual void didReceiveResponse(WebKit::WebURLLoader*, const WebKit::WebURLResponse&) OVERRIDE;
-    virtual void didReceiveData(WebKit::WebURLLoader*, const char*, int, int encodedDataLength) OVERRIDE;
-    virtual void didReceiveCachedMetadata(WebKit::WebURLLoader*, const char* data, int length) OVERRIDE;
-    virtual void didFinishLoading(WebKit::WebURLLoader*, double finishTime) OVERRIDE;
-    virtual void didFail(WebKit::WebURLLoader*, const WebKit::WebURLError&) OVERRIDE;
-    virtual void didDownloadData(WebKit::WebURLLoader*, int, int) OVERRIDE;
+    virtual void willSendRequest(blink::WebURLLoader*, blink::WebURLRequest&, const blink::WebURLResponse& redirectResponse) OVERRIDE;
+    virtual void didSendData(blink::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
+    virtual void didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&) OVERRIDE;
+    virtual void didReceiveData(blink::WebURLLoader*, const char*, int, int encodedDataLength) OVERRIDE;
+    virtual void didReceiveCachedMetadata(blink::WebURLLoader*, const char* data, int length) OVERRIDE;
+    virtual void didFinishLoading(blink::WebURLLoader*, double finishTime) OVERRIDE;
+    virtual void didFail(blink::WebURLLoader*, const blink::WebURLError&) OVERRIDE;
+    virtual void didDownloadData(blink::WebURLLoader*, int, int) OVERRIDE;
 
     const KURL& url() const { return m_request.url(); }
     bool shouldSendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
@@ -92,7 +92,7 @@
 
     void didFinishLoadingOnePart(double finishTime);
 
-    OwnPtr<WebKit::WebURLLoader> m_loader;
+    OwnPtr<blink::WebURLLoader> m_loader;
     RefPtr<ResourceLoaderHost> m_host;
 
     ResourceRequest m_request;
diff --git a/Source/core/fetch/ResourceLoaderOptions.h b/Source/core/fetch/ResourceLoaderOptions.h
index 124b7d5..cc6bf74 100644
--- a/Source/core/fetch/ResourceLoaderOptions.h
+++ b/Source/core/fetch/ResourceLoaderOptions.h
@@ -65,12 +65,6 @@
     DoNotCheckContentSecurityPolicy
 };
 
-enum RequestOriginPolicy {
-    UseDefaultOriginRestrictionsForType,
-    RestrictToSameOrigin,
-    PotentiallyCrossOriginEnabled // Indicates "potentially CORS-enabled fetch" in HTML standard.
-};
-
 enum RequestInitiatorContext {
     DocumentContext,
     WorkerContext,
@@ -112,7 +106,6 @@
         , crossOriginCredentialPolicy(DoNotAskClientForCrossOriginCredentials)
         , securityCheck(DoSecurityCheck)
         , contentSecurityPolicyOption(CheckContentSecurityPolicy)
-        , requestOriginPolicy(UseDefaultOriginRestrictionsForType)
         , requestInitiatorContext(DocumentContext)
         , mixedContentBlockingTreatment(TreatAsDefaultForType)
         , synchronousPolicy(RequestAsynchronously)
@@ -128,7 +121,6 @@
         ClientCrossOriginCredentialPolicy crossOriginCredentialPolicy,
         SecurityCheckPolicy securityCheck,
         ContentSecurityPolicyCheck contentSecurityPolicyOption,
-        RequestOriginPolicy requestOriginPolicy,
         RequestInitiatorContext requestInitiatorContext)
         : sendLoadCallbacks(sendLoadCallbacks)
         , sniffContent(sniffContent)
@@ -138,7 +130,6 @@
         , crossOriginCredentialPolicy(crossOriginCredentialPolicy)
         , securityCheck(securityCheck)
         , contentSecurityPolicyOption(contentSecurityPolicyOption)
-        , requestOriginPolicy(requestOriginPolicy)
         , requestInitiatorContext(requestInitiatorContext)
         , mixedContentBlockingTreatment(TreatAsDefaultForType)
         , synchronousPolicy(RequestAsynchronously)
@@ -154,7 +145,6 @@
     SecurityCheckPolicy securityCheck;
     ContentSecurityPolicyCheck contentSecurityPolicyOption;
     FetchInitiatorInfo initiatorInfo;
-    RequestOriginPolicy requestOriginPolicy;
     RequestInitiatorContext requestInitiatorContext;
     MixedContentBlockingTreatment mixedContentBlockingTreatment;
     SynchronousPolicy synchronousPolicy;
diff --git a/Source/core/fetch/ScriptResource.cpp b/Source/core/fetch/ScriptResource.cpp
index 52bfa54..5002371 100644
--- a/Source/core/fetch/ScriptResource.cpp
+++ b/Source/core/fetch/ScriptResource.cpp
@@ -28,7 +28,7 @@
 #include "core/fetch/ScriptResource.h"
 
 #include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/MIMETypeRegistry.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/SharedBuffer.h"
 #include "platform/network/HTTPParsers.h"
 
diff --git a/Source/core/fetch/ScriptResource.h b/Source/core/fetch/ScriptResource.h
index 441a3b0..56385a3 100644
--- a/Source/core/fetch/ScriptResource.h
+++ b/Source/core/fetch/ScriptResource.h
@@ -26,7 +26,7 @@
 #ifndef ScriptResource_h
 #define ScriptResource_h
 
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 
@@ -48,8 +48,11 @@
 
 private:
     AtomicString m_script;
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
 };
+
+DEFINE_RESOURCE_TYPE_CASTS(Script);
+
 }
 
 #endif
diff --git a/Source/core/fetch/ShaderResource.h b/Source/core/fetch/ShaderResource.h
index 9485663..0363c67 100644
--- a/Source/core/fetch/ShaderResource.h
+++ b/Source/core/fetch/ShaderResource.h
@@ -30,7 +30,7 @@
 #ifndef ShaderResource_h
 #define ShaderResource_h
 
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 
@@ -44,10 +44,12 @@
     const String& shaderString();
 
 private:
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
     String m_shaderString;
 };
 
+DEFINE_RESOURCE_TYPE_CASTS(Shader);
+
 }
 
 
diff --git a/Source/core/fetch/StyleSheetResourceClient.h b/Source/core/fetch/StyleSheetResourceClient.h
index 6c12bf3..4e46c2a 100644
--- a/Source/core/fetch/StyleSheetResourceClient.h
+++ b/Source/core/fetch/StyleSheetResourceClient.h
@@ -27,7 +27,7 @@
 #define StyleSheetResourceClient_h
 
 #include "core/fetch/ResourceClient.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
diff --git a/Source/core/fetch/TextResourceDecoder.cpp b/Source/core/fetch/TextResourceDecoder.cpp
index 3dd24e2..df1279d 100644
--- a/Source/core/fetch/TextResourceDecoder.cpp
+++ b/Source/core/fetch/TextResourceDecoder.cpp
@@ -38,16 +38,6 @@
 
 using namespace HTMLNames;
 
-static inline bool bytesEqual(const char* p, char b0, char b1)
-{
-    return p[0] == b0 && p[1] == b1;
-}
-
-static inline bool bytesEqual(const char* p, char b0, char b1, char b2)
-{
-    return p[0] == b0 && p[1] == b1 && p[2] == b2;
-}
-
 static inline bool bytesEqual(const char* p, char b0, char b1, char b2, char b3, char b4)
 {
     return p[0] == b0 && p[1] == b1 && p[2] == b2 && p[3] == b3 && p[4] == b4;
@@ -199,14 +189,6 @@
     return pos;
 }
 
-// true if there is more to parse
-static inline bool skipWhitespace(const char*& pos, const char* dataEnd)
-{
-    while (pos < dataEnd && (*pos == '\t' || *pos == ' '))
-        ++pos;
-    return pos != dataEnd;
-}
-
 size_t TextResourceDecoder::checkForBOM(const char* data, size_t len)
 {
     // Check for UTF-16/32 or UTF-8 BOM mark at the beginning, which is a sure sign of a Unicode encoding.
diff --git a/Source/core/fetch/TextResourceDecoder.h b/Source/core/fetch/TextResourceDecoder.h
index 14baa35..4c77347 100644
--- a/Source/core/fetch/TextResourceDecoder.h
+++ b/Source/core/fetch/TextResourceDecoder.h
@@ -30,7 +30,7 @@
 
 class HTMLMetaCharsetParser;
 
-class TextResourceDecoder : public RefCounted<TextResourceDecoder> {
+class TextResourceDecoder {
 public:
     enum EncodingSource {
         DefaultEncoding,
@@ -44,24 +44,26 @@
         EncodingFromParentFrame
     };
 
-    static PassRefPtr<TextResourceDecoder> create(const String& mimeType, const WTF::TextEncoding& defaultEncoding = WTF::TextEncoding(), bool usesEncodingDetector = false)
+    static PassOwnPtr<TextResourceDecoder> create(const String& mimeType, const WTF::TextEncoding& defaultEncoding = WTF::TextEncoding(), bool usesEncodingDetector = false)
     {
-        return adoptRef(new TextResourceDecoder(mimeType, defaultEncoding, usesEncodingDetector));
+        return adoptPtr(new TextResourceDecoder(mimeType, defaultEncoding, usesEncodingDetector));
     }
     ~TextResourceDecoder();
 
     void setEncoding(const WTF::TextEncoding&, EncodingSource);
     const WTF::TextEncoding& encoding() const { return m_encoding; }
+    bool encodingWasDetectedHeuristically() const
+    {
+        return m_source == AutoDetectedEncoding
+            || m_source == EncodingFromContentSniffing;
+    }
 
     String decode(const char* data, size_t length);
     String flush();
 
-    void setHintEncoding(const TextResourceDecoder* hintDecoder)
+    void setHintEncoding(const WTF::TextEncoding& encoding)
     {
-        // hintEncoding is for use with autodetection, which should be
-        // only invoked when hintEncoding comes from auto-detection.
-        if (hintDecoder && hintDecoder->wasDetectedHueristically())
-            m_hintEncoding = hintDecoder->encoding().name();
+        m_hintEncoding = encoding.name();
     }
 
     void useLenientXMLDecoding() { m_useLenientXMLDecoding = true; }
@@ -74,8 +76,6 @@
     static ContentType determineContentType(const String& mimeType);
     static const WTF::TextEncoding& defaultEncoding(ContentType, const WTF::TextEncoding& defaultEncoding);
 
-    bool wasDetectedHueristically() const { return m_source == AutoDetectedEncoding || m_source == EncodingFromContentSniffing; }
-
     size_t checkForBOM(const char*, size_t);
     bool checkForCSSCharset(const char*, size_t, bool& movedDataToBuffer);
     bool checkForXMLCharset(const char*, size_t, bool& movedDataToBuffer);
diff --git a/Source/core/fetch/XSLStyleSheetResource.h b/Source/core/fetch/XSLStyleSheetResource.h
index 52e6814..1dea634 100644
--- a/Source/core/fetch/XSLStyleSheetResource.h
+++ b/Source/core/fetch/XSLStyleSheetResource.h
@@ -26,7 +26,7 @@
 #ifndef XSLStyleSheetResource_h
 #define XSLStyleSheetResource_h
 
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 
@@ -47,9 +47,11 @@
     virtual void checkNotify();
 
     String m_sheet;
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
 };
 
+DEFINE_RESOURCE_TYPE_CASTS(XSLStyleSheet);
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/fileapi/Blob.cpp b/Source/core/fileapi/Blob.cpp
index 5fda7d84..def1ae0 100644
--- a/Source/core/fileapi/Blob.cpp
+++ b/Source/core/fileapi/Blob.cpp
@@ -82,7 +82,7 @@
     // The modification time will be used to verify if the file has been changed or not, when the underlying data are accessed.
     long long size;
     double modificationTime;
-    if (isFile()) {
+    if (hasBackingFile()) {
         // FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
         toFile(this)->captureSnapshot(size, modificationTime);
     } else {
@@ -112,7 +112,7 @@
     long long length = end - start;
     OwnPtr<BlobData> blobData = BlobData::create();
     blobData->setContentType(contentType);
-    if (isFile()) {
+    if (hasBackingFile()) {
         if (!toFile(this)->fileSystemURL().isEmpty())
             blobData->appendFileSystemURL(toFile(this)->fileSystemURL(), start, length, modificationTime);
         else
diff --git a/Source/core/fileapi/Blob.h b/Source/core/fileapi/Blob.h
index 58006c8..6a72155 100644
--- a/Source/core/fileapi/Blob.h
+++ b/Source/core/fileapi/Blob.h
@@ -60,7 +60,10 @@
     String uuid() const { return m_blobDataHandle->uuid(); }
     String type() const {  return m_blobDataHandle->type(); }
     virtual unsigned long long size() const { return m_blobDataHandle->size(); }
+    // True for all File instances, including the user-built ones.
     virtual bool isFile() const { return false; }
+    // Only true for File instances that are backed by platform files.
+    virtual bool hasBackingFile() const { return false; }
     PassRefPtr<BlobDataHandle> blobDataHandle() const { return m_blobDataHandle; }
     PassRefPtr<Blob> slice(long long start = 0, long long end = std::numeric_limits<long long>::max(), const String& contentType = String()) const;
 
diff --git a/Source/core/fileapi/BlobBuilder.cpp b/Source/core/fileapi/BlobBuilder.cpp
index 8be60c1..70583af 100644
--- a/Source/core/fileapi/BlobBuilder.cpp
+++ b/Source/core/fileapi/BlobBuilder.cpp
@@ -94,7 +94,7 @@
 {
     if (!blob)
         return;
-    if (blob->isFile()) {
+    if (blob->hasBackingFile()) {
         File* file = toFile(blob);
         // If the blob is file that is not snapshoted, capture the snapshot now.
         // FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
@@ -122,7 +122,7 @@
     m_size += buffer.size() - oldSize;
 }
 
-PassRefPtr<Blob> BlobBuilder::getBlob(const String& contentType)
+PassRefPtr<Blob> BlobBuilder::createBlob(const String& contentType)
 {
     OwnPtr<BlobData> blobData = BlobData::create();
     blobData->setContentType(contentType);
@@ -134,7 +134,22 @@
     // Instead, we only need to keep a reference to the blob data just created.
     m_items.append(BlobDataItem(blob->blobDataHandle(), 0, m_size));
 
-    return blob;
+    return blob.release();
+}
+
+PassRefPtr<File> BlobBuilder::createFile(const String& contentType, const String& fileName, double modificationTime)
+{
+    OwnPtr<BlobData> blobData = BlobData::create();
+    blobData->setContentType(contentType);
+    blobData->swapItems(m_items);
+
+    RefPtr<File> file = File::create(fileName, modificationTime, BlobDataHandle::create(blobData.release(), m_size));
+
+    // After creating a file from the current blob data, we do not need to keep the data around any more.
+    // Instead, we only need to keep a reference to the blob data just created.
+    m_items.append(BlobDataItem(file->blobDataHandle(), 0, m_size));
+
+    return file.release();
 }
 
 } // namespace WebCore
diff --git a/Source/core/fileapi/BlobBuilder.h b/Source/core/fileapi/BlobBuilder.h
index 560a79c..cdf3cc5 100644
--- a/Source/core/fileapi/BlobBuilder.h
+++ b/Source/core/fileapi/BlobBuilder.h
@@ -34,15 +34,10 @@
 #include "platform/blob/BlobData.h"
 #include "wtf/Forward.h"
 
-namespace WTF{
-class TextEncoding;
-}
-
 namespace WebCore {
 
 class Blob;
-
-typedef int ExceptionCode;
+class File;
 
 class BlobBuilder {
 public:
@@ -53,7 +48,8 @@
     void append(ArrayBuffer*);
     void append(ArrayBufferView*);
 
-    PassRefPtr<Blob> getBlob(const String& contentType);
+    PassRefPtr<Blob> createBlob(const String& contentType);
+    PassRefPtr<File> createFile(const String& contentType, const String& fileName, double modificationTime);
 
 private:
     void appendBytesData(const void*, size_t);
diff --git a/Source/core/fileapi/File.cpp b/Source/core/fileapi/File.cpp
index c578ada..6842161 100644
--- a/Source/core/fileapi/File.cpp
+++ b/Source/core/fileapi/File.cpp
@@ -26,8 +26,8 @@
 #include "config.h"
 #include "core/fileapi/File.h"
 
-#include "core/platform/MIMETypeRegistry.h"
 #include "platform/FileMetadata.h"
+#include "platform/MIMETypeRegistry.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebFileUtilities.h"
 #include "wtf/CurrentTime.h"
@@ -94,8 +94,9 @@
 
 File::File(const String& path, ContentTypeLookupPolicy policy)
     : Blob(BlobDataHandle::create(createBlobDataForFile(path, policy), -1))
+    , m_hasBackingFile(true)
     , m_path(path)
-    , m_name(WebKit::Platform::current()->fileUtilities()->baseName(path))
+    , m_name(blink::Platform::current()->fileUtilities()->baseName(path))
     , m_snapshotSize(-1)
     , m_snapshotModificationTime(invalidFileTime())
 {
@@ -104,6 +105,7 @@
 
 File::File(const String& path, const String& name, ContentTypeLookupPolicy policy)
     : Blob(BlobDataHandle::create(createBlobDataForFileWithName(path, name, policy), -1))
+    , m_hasBackingFile(true)
     , m_path(path)
     , m_name(name)
     , m_snapshotSize(-1)
@@ -114,8 +116,9 @@
 
 File::File(const String& path, PassRefPtr<BlobDataHandle> blobDataHandle)
     : Blob(blobDataHandle)
+    , m_hasBackingFile(true)
     , m_path(path)
-    , m_name(WebKit::Platform::current()->fileUtilities()->baseName(path))
+    , m_name(blink::Platform::current()->fileUtilities()->baseName(path))
     , m_snapshotSize(-1)
     , m_snapshotModificationTime(invalidFileTime())
 {
@@ -125,8 +128,19 @@
     // See SerializedScriptValue.cpp.
 }
 
+File::File(const String& name, double modificationTime, PassRefPtr<BlobDataHandle> blobDataHandle)
+    : Blob(blobDataHandle)
+    , m_hasBackingFile(false)
+    , m_name(name)
+    , m_snapshotSize(Blob::size())
+    , m_snapshotModificationTime(modificationTime)
+{
+    ScriptWrappable::init(this);
+}
+
 File::File(const String& name, const FileMetadata& metadata)
     : Blob(BlobDataHandle::create(createBlobDataForFileWithMetadata(name, metadata),  metadata.length))
+    , m_hasBackingFile(true)
     , m_path(metadata.platformPath)
     , m_name(name)
     , m_snapshotSize(metadata.length)
@@ -137,6 +151,7 @@
 
 File::File(const KURL& fileSystemURL, const FileMetadata& metadata)
     : Blob(BlobDataHandle::create(createBlobDataForFileSystemURL(fileSystemURL, metadata), metadata.length))
+    , m_hasBackingFile(true)
     , m_fileSystemURL(fileSystemURL)
     , m_snapshotSize(metadata.length)
     , m_snapshotModificationTime(metadata.modificationTime)
diff --git a/Source/core/fileapi/File.h b/Source/core/fileapi/File.h
index c6d8db4..f9c87b4 100644
--- a/Source/core/fileapi/File.h
+++ b/Source/core/fileapi/File.h
@@ -49,6 +49,11 @@
         return adoptRef(new File(path, policy));
     }
 
+    static PassRefPtr<File> create(const String& name, double modificationTime, PassRefPtr<BlobDataHandle> blobDataHandle)
+    {
+        return adoptRef(new File(name, modificationTime, blobDataHandle));
+    }
+
     // For deserialization.
     static PassRefPtr<File> create(const String& path, PassRefPtr<BlobDataHandle> blobDataHandle)
     {
@@ -70,7 +75,7 @@
         return adoptRef(new File(url, metadata));
     }
 
-    KURL fileSystemURL() const { return m_fileSystemURL; }
+    KURL fileSystemURL() const { ASSERT(m_hasBackingFile); return m_fileSystemURL; }
 
     // Create a file with a name exposed to the author (via File.name and associated DOM properties) that differs from the one provided in the path.
     static PassRefPtr<File> createWithName(const String& path, const String& name, ContentTypeLookupPolicy policy = WellKnownContentTypes)
@@ -80,10 +85,11 @@
         return adoptRef(new File(path, name, policy));
     }
 
-    virtual unsigned long long size() const;
-    virtual bool isFile() const { return true; }
+    virtual unsigned long long size() const OVERRIDE;
+    virtual bool isFile() const OVERRIDE { return true; }
+    virtual bool hasBackingFile() const OVERRIDE { return m_hasBackingFile; }
 
-    const String& path() const { return m_path; }
+    const String& path() const { ASSERT(m_hasBackingFile); return m_path; }
     const String& name() const { return m_name; }
 
     // This returns the current date and time if the file's last modifiecation date is not known (per spec: http://www.w3.org/TR/FileAPI/#dfn-lastModifiedDate).
@@ -99,12 +105,14 @@
     File(const String& path, ContentTypeLookupPolicy);
     File(const String& path, const String& name, ContentTypeLookupPolicy);
     File(const String& path, PassRefPtr<BlobDataHandle>);
+    File(const String& name, double modificationTime, PassRefPtr<BlobDataHandle>);
     File(const String& name, const FileMetadata&);
     File(const KURL& fileSystemURL, const FileMetadata&);
 
     // Returns true if this has a valid snapshot metadata (i.e. m_snapshotSize >= 0).
     bool hasValidSnapshotMetadata() const { return m_snapshotSize >= 0; }
 
+    bool m_hasBackingFile;
     String m_path;
     String m_name;
 
diff --git a/Source/core/fileapi/File.idl b/Source/core/fileapi/File.idl
index 56be7fc..fdbe18d 100644
--- a/Source/core/fileapi/File.idl
+++ b/Source/core/fileapi/File.idl
@@ -23,7 +23,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface File : Blob {
+[
+    GlobalContext=Window&WorkerGlobalScope,
+    CustomConstructor(sequence<any> blobParts, DOMString fileName, optional BlobPropertyBag options)
+] interface File : Blob {
     readonly attribute DOMString name;
     readonly attribute Date lastModifiedDate;
     [RuntimeEnabled=DirectoryUpload] readonly attribute DOMString webkitRelativePath;
diff --git a/Source/core/fileapi/FileError.cpp b/Source/core/fileapi/FileError.cpp
index 2fa8576..693b52c 100644
--- a/Source/core/fileapi/FileError.cpp
+++ b/Source/core/fileapi/FileError.cpp
@@ -123,18 +123,18 @@
 
 } // namespace
 
-void FileError::throwDOMException(ExceptionState& es, ErrorCode code)
+void FileError::throwDOMException(ExceptionState& exceptionState, ErrorCode code)
 {
     if (code == FileError::OK)
         return;
 
     // SecurityError is special-cased, as we want to route those exceptions through ExceptionState::throwSecurityError.
     if (code == FileError::SECURITY_ERR) {
-        es.throwSecurityError(FileError::securityErrorMessage);
+        exceptionState.throwSecurityError(FileError::securityErrorMessage);
         return;
     }
 
-    es.throwDOMException(errorCodeToExceptionCode(code), errorCodeToMessage(code));
+    exceptionState.throwDOMException(errorCodeToExceptionCode(code), errorCodeToMessage(code));
 }
 
 FileError::FileError(ErrorCode code)
diff --git a/Source/core/fileapi/FileReader.cpp b/Source/core/fileapi/FileReader.cpp
index 060c406..5332ebd 100644
--- a/Source/core/fileapi/FileReader.cpp
+++ b/Source/core/fileapi/FileReader.cpp
@@ -46,6 +46,7 @@
 
 namespace {
 
+#if !LOG_DISABLED
 const CString utf8BlobUUID(Blob* blob)
 {
     return blob->uuid().utf8();
@@ -53,8 +54,9 @@
 
 const CString utf8FilePath(Blob* blob)
 {
-    return blob->isFile() ? toFile(blob)->path().utf8() : "";
+    return blob->hasBackingFile() ? toFile(blob)->path().utf8() : "";
 }
+#endif
 
 } // namespace
 
@@ -92,27 +94,27 @@
     terminate();
 }
 
-void FileReader::readAsArrayBuffer(Blob* blob, ExceptionState& es)
+void FileReader::readAsArrayBuffer(Blob* blob, ExceptionState& exceptionState)
 {
     if (!blob)
         return;
 
     LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
-    readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, es);
+    readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, exceptionState);
 }
 
-void FileReader::readAsBinaryString(Blob* blob, ExceptionState& es)
+void FileReader::readAsBinaryString(Blob* blob, ExceptionState& exceptionState)
 {
     if (!blob)
         return;
 
     LOG(FileAPI, "FileReader: reading as binary: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
-    readInternal(blob, FileReaderLoader::ReadAsBinaryString, es);
+    readInternal(blob, FileReaderLoader::ReadAsBinaryString, exceptionState);
 }
 
-void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionState& es)
+void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionState& exceptionState)
 {
     if (!blob)
         return;
@@ -120,29 +122,29 @@
     LOG(FileAPI, "FileReader: reading as text: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
     m_encoding = encoding;
-    readInternal(blob, FileReaderLoader::ReadAsText, es);
+    readInternal(blob, FileReaderLoader::ReadAsText, exceptionState);
 }
 
-void FileReader::readAsText(Blob* blob, ExceptionState& es)
+void FileReader::readAsText(Blob* blob, ExceptionState& exceptionState)
 {
-    readAsText(blob, String(), es);
+    readAsText(blob, String(), exceptionState);
 }
 
-void FileReader::readAsDataURL(Blob* blob, ExceptionState& es)
+void FileReader::readAsDataURL(Blob* blob, ExceptionState& exceptionState)
 {
     if (!blob)
         return;
 
     LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
-    readInternal(blob, FileReaderLoader::ReadAsDataURL, es);
+    readInternal(blob, FileReaderLoader::ReadAsDataURL, exceptionState);
 }
 
-void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionState& es)
+void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionState& exceptionState)
 {
     // If multiple concurrent read methods are called on the same FileReader, InvalidStateError should be thrown when the state is LOADING.
     if (m_state == LOADING) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
diff --git a/Source/core/fileapi/FileReader.idl b/Source/core/fileapi/FileReader.idl
index eb26da7..05e5b3f 100644
--- a/Source/core/fileapi/FileReader.idl
+++ b/Source/core/fileapi/FileReader.idl
@@ -50,7 +50,7 @@
     void abort();
 
     // file data
-    [CustomGetter] readonly attribute any result;
+    [Custom=Getter] readonly attribute object result;
 
     readonly attribute FileError error;
 
diff --git a/Source/core/fileapi/FileReaderLoader.cpp b/Source/core/fileapi/FileReaderLoader.cpp
index 001257b..b4a07e7 100644
--- a/Source/core/fileapi/FileReaderLoader.cpp
+++ b/Source/core/fileapi/FileReaderLoader.cpp
@@ -163,7 +163,7 @@
         m_rawData.clear();
         m_stringResult = "";
         m_isRawDataConverted = true;
-        m_decoder = 0;
+        m_decoder.clear();
     }
 }
 
diff --git a/Source/core/fileapi/FileReaderLoader.h b/Source/core/fileapi/FileReaderLoader.h
index 264b587..6bb4459 100644
--- a/Source/core/fileapi/FileReaderLoader.h
+++ b/Source/core/fileapi/FileReaderLoader.h
@@ -33,7 +33,7 @@
 
 #include "core/fileapi/FileError.h"
 #include "core/loader/ThreadableLoaderClient.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/ArrayBuffer.h"
 #include "wtf/ArrayBufferBuilder.h"
 #include "wtf/Forward.h"
@@ -124,7 +124,7 @@
     String m_stringResult;
 
     // The decoder used to decode the text data.
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
 
     bool m_finishedLoading;
     long long m_bytesLoaded;
diff --git a/Source/core/fileapi/FileReaderSync.cpp b/Source/core/fileapi/FileReaderSync.cpp
index 80222cf..cbef4c1 100644
--- a/Source/core/fileapi/FileReaderSync.cpp
+++ b/Source/core/fileapi/FileReaderSync.cpp
@@ -46,62 +46,62 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<ArrayBuffer> FileReaderSync::readAsArrayBuffer(ExecutionContext* executionContext, Blob* blob, ExceptionState& es)
+PassRefPtr<ArrayBuffer> FileReaderSync::readAsArrayBuffer(ExecutionContext* executionContext, Blob* blob, ExceptionState& exceptionState)
 {
     if (!blob) {
-        es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+        exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
         return 0;
     }
 
     FileReaderLoader loader(FileReaderLoader::ReadAsArrayBuffer, 0);
-    startLoading(executionContext, loader, *blob, es);
+    startLoading(executionContext, loader, *blob, exceptionState);
 
     return loader.arrayBufferResult();
 }
 
-String FileReaderSync::readAsBinaryString(ExecutionContext* executionContext, Blob* blob, ExceptionState& es)
+String FileReaderSync::readAsBinaryString(ExecutionContext* executionContext, Blob* blob, ExceptionState& exceptionState)
 {
     if (!blob) {
-        es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+        exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
         return String();
     }
 
     FileReaderLoader loader(FileReaderLoader::ReadAsBinaryString, 0);
-    startLoading(executionContext, loader, *blob, es);
+    startLoading(executionContext, loader, *blob, exceptionState);
     return loader.stringResult();
 }
 
-String FileReaderSync::readAsText(ExecutionContext* executionContext, Blob* blob, const String& encoding, ExceptionState& es)
+String FileReaderSync::readAsText(ExecutionContext* executionContext, Blob* blob, const String& encoding, ExceptionState& exceptionState)
 {
     if (!blob) {
-        es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+        exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
         return String();
     }
 
     FileReaderLoader loader(FileReaderLoader::ReadAsText, 0);
     loader.setEncoding(encoding);
-    startLoading(executionContext, loader, *blob, es);
+    startLoading(executionContext, loader, *blob, exceptionState);
     return loader.stringResult();
 }
 
-String FileReaderSync::readAsDataURL(ExecutionContext* executionContext, Blob* blob, ExceptionState& es)
+String FileReaderSync::readAsDataURL(ExecutionContext* executionContext, Blob* blob, ExceptionState& exceptionState)
 {
     if (!blob) {
-        es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+        exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
         return String();
     }
 
     FileReaderLoader loader(FileReaderLoader::ReadAsDataURL, 0);
     loader.setDataType(blob->type());
-    startLoading(executionContext, loader, *blob, es);
+    startLoading(executionContext, loader, *blob, exceptionState);
     return loader.stringResult();
 }
 
-void FileReaderSync::startLoading(ExecutionContext* executionContext, FileReaderLoader& loader, const Blob& blob, ExceptionState& es)
+void FileReaderSync::startLoading(ExecutionContext* executionContext, FileReaderLoader& loader, const Blob& blob, ExceptionState& exceptionState)
 {
     loader.start(executionContext, blob.blobDataHandle());
     if (loader.errorCode())
-        FileError::throwDOMException(es, loader.errorCode());
+        FileError::throwDOMException(exceptionState, loader.errorCode());
 }
 
 } // namespace WebCore
diff --git a/Source/core/fileapi/Stream.h b/Source/core/fileapi/Stream.h
index 379a154..3e9b3e0 100644
--- a/Source/core/fileapi/Stream.h
+++ b/Source/core/fileapi/Stream.h
@@ -33,7 +33,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/ActiveDOMObject.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/frame/ConsoleBase.idl b/Source/core/frame/ConsoleBase.idl
index 542610f..8c6c401 100644
--- a/Source/core/frame/ConsoleBase.idl
+++ b/Source/core/frame/ConsoleBase.idl
@@ -28,9 +28,8 @@
  */
 
 [
-    CustomToV8,
-    DoNotGenerateWrap,
-    NoInterfaceObject
+    NoInterfaceObject,
+    DoNotGenerateToV8,
 ] interface ConsoleBase {
     [CallWith=ScriptArguments&ScriptState] void debug();
     [CallWith=ScriptArguments&ScriptState] void error();
diff --git a/Source/core/frame/ContentSecurityPolicy.cpp b/Source/core/frame/ContentSecurityPolicy.cpp
index bc17809..6ac550b 100644
--- a/Source/core/frame/ContentSecurityPolicy.cpp
+++ b/Source/core/frame/ContentSecurityPolicy.cpp
@@ -40,16 +40,16 @@
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/PingLoader.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "platform/JSONValues.h"
 #include "platform/NotImplemented.h"
 #include "platform/ParsingUtilities.h"
 #include "platform/network/FormData.h"
 #include "platform/network/ResourceResponse.h"
-#include "weborigin/KURL.h"
-#include "weborigin/KnownPorts.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/KnownPorts.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/HashSet.h"
 #include "wtf/SHA1.h"
 #include "wtf/StringHasher.h"
diff --git a/Source/core/frame/DOMWindow.cpp b/Source/core/frame/DOMWindow.cpp
index 15a499e..b47293e 100644
--- a/Source/core/frame/DOMWindow.cpp
+++ b/Source/core/frame/DOMWindow.cpp
@@ -89,19 +89,18 @@
 #include "core/page/WindowFeatures.h"
 #include "core/page/WindowFocusAllowedIndicator.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/graphics/MediaPlayer.h"
 #include "core/storage/Storage.h"
 #include "core/storage/StorageArea.h"
 #include "core/storage/StorageNamespace.h"
 #include "core/timing/Performance.h"
-#include "modules/device_orientation/NewDeviceOrientationController.h"
 #include "platform/PlatformScreen.h"
 #include "platform/UserGestureIndicator.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/graphics/media/MediaPlayer.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
 #include "public/platform/Platform.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
 #include "wtf/MainThread.h"
 #include "wtf/MathExtras.h"
 #include "wtf/text/WTFString.h"
@@ -150,12 +149,12 @@
 
 static void disableSuddenTermination()
 {
-    WebKit::Platform::current()->suddenTerminationChanged(false);
+    blink::Platform::current()->suddenTerminationChanged(false);
 }
 
 static void enableSuddenTermination()
 {
-    WebKit::Platform::current()->suddenTerminationChanged(true);
+    blink::Platform::current()->suddenTerminationChanged(true);
 }
 
 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
@@ -238,10 +237,7 @@
     Frame* frame = window->frame();
     if (!frame)
         return false;
-    Page* page = frame->page();
-    if (!page)
-        return false;
-    return frame == page->mainFrame();
+    return frame->isMainFrame();
 }
 
 unsigned DOMWindow::pendingUnloadEventListeners() const
@@ -353,15 +349,23 @@
         // depends on this detach() call, so it seems like there's some room
         // for cleanup.
         m_document->detach();
-        m_eventQueue->close();
     }
 
-    m_eventQueue.clear();
+    // FIXME: This should be part of ActiveDOM Object shutdown
+    clearEventQueue();
 
     m_document->clearDOMWindow();
     m_document = 0;
 }
 
+void DOMWindow::clearEventQueue()
+{
+    if (!m_eventQueue)
+        return;
+    m_eventQueue->close();
+    m_eventQueue.clear();
+}
+
 PassRefPtr<Document> DOMWindow::createDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
 {
     RefPtr<Document> document;
@@ -403,7 +407,7 @@
 
     m_frame->selection().updateSecureKeyboardEntryIfActive();
 
-    if (m_frame->page() && m_frame->page()->mainFrame() == m_frame) {
+    if (m_frame->isMainFrame()) {
         m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
         if (m_document->hasTouchEventHandlers())
             m_frame->page()->chrome().client().needTouchEvents(true);
@@ -419,12 +423,16 @@
 
 void DOMWindow::enqueueWindowEvent(PassRefPtr<Event> event)
 {
+    if (!m_eventQueue)
+        return;
     event->setTarget(this);
     m_eventQueue->enqueueEvent(event);
 }
 
 void DOMWindow::enqueueDocumentEvent(PassRefPtr<Event> event)
 {
+    if (!m_eventQueue)
+        return;
     event->setTarget(m_document);
     m_eventQueue->enqueueEvent(event);
 }
@@ -536,10 +544,6 @@
 void DOMWindow::willDetachPage()
 {
     InspectorInstrumentation::frameWindowDiscarded(m_frame, this);
-    // FIXME: Once DeviceOrientationController is a ExecutionContext
-    // Supplement, this will no longer be needed.
-    if (NewDeviceOrientationController* controller = NewDeviceOrientationController::from(document()))
-        controller->stopUpdating();
 }
 
 void DOMWindow::willDestroyDocumentInFrame()
@@ -745,7 +749,7 @@
     return m_location.get();
 }
 
-Storage* DOMWindow::sessionStorage(ExceptionState& es) const
+Storage* DOMWindow::sessionStorage(ExceptionState& exceptionState) const
 {
     if (!isCurrentlyDisplayedInFrame())
         return 0;
@@ -757,17 +761,17 @@
     String accessDeniedMessage = "Access to 'sessionStorage' is denied for this document.";
     if (!document->securityOrigin()->canAccessLocalStorage()) {
         if (document->isSandboxed(SandboxOrigin))
-            es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
         else if (document->url().protocolIs("data"))
-            es.throwSecurityError(accessDeniedMessage + " Storage is disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " Storage is disabled inside 'data:' URLs.");
         else
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
     if (m_sessionStorage) {
         if (!m_sessionStorage->area()->canAccessStorage(m_frame)) {
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError(accessDeniedMessage);
             return 0;
         }
         return m_sessionStorage.get();
@@ -779,7 +783,7 @@
 
     OwnPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
-        es.throwSecurityError(accessDeniedMessage);
+        exceptionState.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
@@ -787,7 +791,7 @@
     return m_sessionStorage.get();
 }
 
-Storage* DOMWindow::localStorage(ExceptionState& es) const
+Storage* DOMWindow::localStorage(ExceptionState& exceptionState) const
 {
     if (!isCurrentlyDisplayedInFrame())
         return 0;
@@ -799,17 +803,17 @@
     String accessDeniedMessage = "Access to 'localStorage' is denied for this document.";
     if (!document->securityOrigin()->canAccessLocalStorage()) {
         if (document->isSandboxed(SandboxOrigin))
-            es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
         else if (document->url().protocolIs("data"))
-            es.throwSecurityError(accessDeniedMessage + " Storage is disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError(accessDeniedMessage + " Storage is disabled inside 'data:' URLs.");
         else
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
     if (m_localStorage) {
         if (!m_localStorage->area()->canAccessStorage(m_frame)) {
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError(accessDeniedMessage);
             return 0;
         }
         return m_localStorage.get();
@@ -824,7 +828,7 @@
 
     OwnPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
-        es.throwSecurityError(accessDeniedMessage);
+        exceptionState.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
@@ -832,7 +836,7 @@
     return m_localStorage.get();
 }
 
-void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionState& es)
+void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionState& exceptionState)
 {
     if (!isCurrentlyDisplayedInFrame())
         return;
@@ -851,13 +855,13 @@
         // It doesn't make sense target a postMessage at a unique origin
         // because there's no way to represent a unique origin in a string.
         if (target->isUnique()) {
-            es.throwDOMException(SyntaxError, "Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
+            exceptionState.throwDOMException(SyntaxError, "Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
             return;
         }
     }
 
-    OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, es);
-    if (es.hadException())
+    OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     // Capture the source of the message.  We need to do this synchronously
@@ -943,7 +947,7 @@
     }
 
     // If we're a top level window, bring the window to the front.
-    if (m_frame == page->mainFrame() && allowFocus)
+    if (m_frame->isMainFrame() && allowFocus)
         page->chrome().focus();
 
     if (!m_frame)
@@ -1440,11 +1444,8 @@
     if (m_frame != page->mainFrame())
         return;
 
-    FloatRect fr = page->chrome().windowRect();
-    FloatRect sr = screenAvailableRect(page->mainFrame()->view());
-    fr.setLocation(sr.location());
-    FloatRect update = fr;
-    update.move(x, y);
+    FloatRect update = page->chrome().windowRect();
+    update.setLocation(FloatPoint(x, y));
     // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
     page->chrome().setWindowRect(adjustWindowRect(page, update));
 }
@@ -1540,8 +1541,10 @@
     lifecycleNotifier().notifyAddEventListener(this, eventType);
 
     if (eventType == EventTypeNames::unload) {
+        UseCounter::count(this, UseCounter::DocumentUnloadRegistered);
         addUnloadEventListener(this);
     } else if (eventType == EventTypeNames::beforeunload) {
+        UseCounter::count(this, UseCounter::DocumentBeforeUnloadRegistered);
         if (allowsBeforeUnloadListeners(this)) {
             // This is confusingly named. It doesn't actually add the listener. It just increments a count
             // so that we know we have listeners registered for the purposes of determining if we can
@@ -1687,6 +1690,9 @@
 // http://crbug.com/17325
 String DOMWindow::sanitizedCrossDomainAccessErrorMessage(DOMWindow* activeWindow)
 {
+    if (!activeWindow || !activeWindow->document())
+        return String();
+
     const KURL& activeWindowURL = activeWindow->document()->url();
     if (activeWindowURL.isNull())
         return String();
@@ -1703,6 +1709,9 @@
 
 String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
 {
+    if (!activeWindow || !activeWindow->document())
+        return String();
+
     const KURL& activeWindowURL = activeWindow->document()->url();
     if (activeWindowURL.isNull())
         return String();
@@ -1864,7 +1873,7 @@
 
 DOMWindowLifecycleNotifier& DOMWindow::lifecycleNotifier()
 {
-    return static_cast<DOMWindowLifecycleNotifier&>(LifecycleContext::lifecycleNotifier());
+    return static_cast<DOMWindowLifecycleNotifier&>(LifecycleContext<DOMWindow>::lifecycleNotifier());
 }
 
 PassOwnPtr<LifecycleNotifier<DOMWindow> > DOMWindow::createLifecycleNotifier()
diff --git a/Source/core/frame/DOMWindow.h b/Source/core/frame/DOMWindow.h
index 9632a7f..8753367 100644
--- a/Source/core/frame/DOMWindow.h
+++ b/Source/core/frame/DOMWindow.h
@@ -186,10 +186,6 @@
         String defaultStatus() const;
         void setDefaultStatus(const String&);
 
-        // This attribute is an alias of defaultStatus and is necessary for legacy uses.
-        String defaultstatus() const { return defaultStatus(); }
-        void setDefaultstatus(const String& status) { setDefaultStatus(status); }
-
         // Self-referential attributes
 
         DOMWindow* self() const;
@@ -326,6 +322,10 @@
         void dispatchWindowLoadEvent();
         void documentWasClosed();
         void statePopped(PassRefPtr<SerializedScriptValue>);
+
+        // FIXME: This shouldn't be public once DOMWindow becomes ExecutionContext.
+        void clearEventQueue();
+
     protected:
         DOMWindowLifecycleNotifier& lifecycleNotifier();
 
diff --git a/Source/core/frame/DOMWindowBase64.cpp b/Source/core/frame/DOMWindowBase64.cpp
index d2c1787..2d2e1f7 100644
--- a/Source/core/frame/DOMWindowBase64.cpp
+++ b/Source/core/frame/DOMWindowBase64.cpp
@@ -35,38 +35,38 @@
 
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/html/parser/HTMLParserIdioms.h"
 #include "wtf/text/Base64.h"
 
 namespace WebCore {
 
 namespace DOMWindowBase64 {
 
-String btoa(void*, const String& stringToEncode, ExceptionState& es)
+String btoa(void*, const String& stringToEncode, ExceptionState& exceptionState)
 {
     if (stringToEncode.isNull())
         return String();
 
     if (!stringToEncode.containsOnlyLatin1()) {
-        es.throwDOMException(InvalidCharacterError, "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
+        exceptionState.throwDOMException(InvalidCharacterError, "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
         return String();
     }
 
     return base64Encode(stringToEncode.latin1());
 }
 
-String atob(void*, const String& encodedString, ExceptionState& es)
+String atob(void*, const String& encodedString, ExceptionState& exceptionState)
 {
     if (encodedString.isNull())
         return String();
 
     if (!encodedString.containsOnlyLatin1()) {
-        es.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded contains characters outside of the Latin1 range.");
+        exceptionState.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, Base64FailOnInvalidCharacterOrExcessPadding)) {
-        es.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded is not correctly encoded.");
+    if (!base64Decode(encodedString, out, isHTMLSpace<UChar>, Base64ValidatePadding)) {
+        exceptionState.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded is not correctly encoded.");
         return String();
     }
 
diff --git a/Source/core/frame/DOMWindowLifecycleNotifier.cpp b/Source/core/frame/DOMWindowLifecycleNotifier.cpp
index 0ecb796..92fafea 100644
--- a/Source/core/frame/DOMWindowLifecycleNotifier.cpp
+++ b/Source/core/frame/DOMWindowLifecycleNotifier.cpp
@@ -30,7 +30,7 @@
 namespace WebCore {
 
 DOMWindowLifecycleNotifier::DOMWindowLifecycleNotifier(DOMWindow* context)
-    : LifecycleNotifier(context)
+    : LifecycleNotifier<DOMWindow>(context)
 {
 }
 
@@ -41,7 +41,7 @@
         m_windowObservers.add(static_cast<DOMWindowLifecycleObserver*>(observer));
     }
 
-    LifecycleNotifier::addObserver(observer);
+    LifecycleNotifier<DOMWindow>::addObserver(observer);
 }
 
 void DOMWindowLifecycleNotifier::removeObserver(DOMWindowLifecycleNotifier::Observer* observer)
@@ -51,7 +51,7 @@
         m_windowObservers.remove(static_cast<DOMWindowLifecycleObserver*>(observer));
     }
 
-    LifecycleNotifier::removeObserver(observer);
+    LifecycleNotifier<DOMWindow>::removeObserver(observer);
 }
 
 PassOwnPtr<DOMWindowLifecycleNotifier> DOMWindowLifecycleNotifier::create(DOMWindow* context)
diff --git a/Source/core/frame/DOMWindowLifecycleObserver.cpp b/Source/core/frame/DOMWindowLifecycleObserver.cpp
index ad17f84..aa4f97b 100644
--- a/Source/core/frame/DOMWindowLifecycleObserver.cpp
+++ b/Source/core/frame/DOMWindowLifecycleObserver.cpp
@@ -42,7 +42,7 @@
 }
 
 DOMWindowLifecycleObserver::DOMWindowLifecycleObserver(DOMWindow* window)
-    : LifecycleObserver(window, DOMWindowLifecycleObserverType)
+    : LifecycleObserver<DOMWindow>(window, DOMWindowLifecycleObserverType)
 {
 }
 
diff --git a/Source/core/frame/Frame.cpp b/Source/core/frame/Frame.cpp
index 252af45..869c7b0 100644
--- a/Source/core/frame/Frame.cpp
+++ b/Source/core/frame/Frame.cpp
@@ -44,6 +44,7 @@
 #include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/inspector/InspectorInstrumentation.h"
+#include "core/loader/EmptyClients.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/Chrome.h"
@@ -204,7 +205,7 @@
 
     m_view = view;
 
-    if (m_view && m_page && m_page->mainFrame() == this)
+    if (m_view && isMainFrame())
         m_view->setVisibleContentScaleFactor(m_page->pageScaleFactor());
 }
 
@@ -277,6 +278,19 @@
     m_domWindow = domWindow;
 }
 
+static ChromeClient& emptyChromeClient()
+{
+    DEFINE_STATIC_LOCAL(EmptyChromeClient, client, ());
+    return client;
+}
+
+ChromeClient& Frame::chromeClient() const
+{
+    if (Page* page = this->page())
+        return page->chrome().client();
+    return emptyChromeClient();
+}
+
 Document* Frame::document() const
 {
     return m_domWindow ? m_domWindow->document() : 0;
@@ -358,6 +372,11 @@
     m_frameInit->setOwnerElement(0);
 }
 
+bool Frame::isMainFrame() const
+{
+    return m_page && this == m_page->mainFrame();
+}
+
 String Frame::documentTypeString() const
 {
     if (DocumentType* doctype = document()->doctype())
@@ -435,7 +454,7 @@
     ASSERT(this);
     ASSERT(m_page);
 
-    bool isMainFrame = this == m_page->mainFrame();
+    bool isMainFrame = this->isMainFrame();
 
     if (isMainFrame && view())
         view()->setParentVisible(false);
@@ -540,6 +559,7 @@
 
 void Frame::deviceOrPageScaleFactorChanged()
 {
+    document()->mediaQueryAffectingValueChanged();
     for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
         child->deviceOrPageScaleFactorChanged();
 }
@@ -547,7 +567,7 @@
 void Frame::notifyChromeClientWheelEventHandlerCountChanged() const
 {
     // Ensure that this method is being called on the main frame of the page.
-    ASSERT(m_page && m_page->mainFrame() == this);
+    ASSERT(isMainFrame());
 
     unsigned count = 0;
     for (const Frame* frame = this; frame; frame = frame->tree().traverseNext()) {
diff --git a/Source/core/frame/Frame.h b/Source/core/frame/Frame.h
index 5aeadb9..6c38bce 100644
--- a/Source/core/frame/Frame.h
+++ b/Source/core/frame/Frame.h
@@ -40,6 +40,7 @@
 namespace WebCore {
 
     class AnimationController;
+    class ChromeClient;
     class Color;
     class DOMWindow;
     class Document;
@@ -124,12 +125,14 @@
 
         Page* page() const;
         HTMLFrameOwnerElement* ownerElement() const;
+        bool isMainFrame() const;
 
         void setDOMWindow(PassRefPtr<DOMWindow>);
         DOMWindow* domWindow() const;
         Document* document() const;
         FrameView* view() const;
 
+        ChromeClient& chromeClient() const;
         Editor& editor() const;
         EventHandler& eventHandler() const;
         FrameLoader& loader() const;
diff --git a/Source/core/frame/FrameView.cpp b/Source/core/frame/FrameView.cpp
index cd4781a..85d4b0d 100644
--- a/Source/core/frame/FrameView.cpp
+++ b/Source/core/frame/FrameView.cpp
@@ -30,8 +30,7 @@
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/accessibility/AXObjectCache.h"
-#include "core/animation/AnimationClock.h"
-#include "core/animation/DocumentTimeline.h"
+#include "core/animation/DocumentAnimations.h"
 #include "core/css/FontFaceSet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/DocumentMarkerController.h"
@@ -171,10 +170,10 @@
     , m_layoutRoot(0)
     , m_inSynchronousPostLayout(false)
     , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
+    , m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
     , m_isTransparent(false)
     , m_baseBackgroundColor(Color::white)
     , m_mediaType("screen")
-    , m_overflowEventSuspendCount(0)
     , m_overflowStatusDirty(true)
     , m_viewportRenderer(0)
     , m_wasScrolledByUser(false)
@@ -224,10 +223,8 @@
 
 FrameView::~FrameView()
 {
-    if (m_postLayoutTasksTimer.isActive()) {
+    if (m_postLayoutTasksTimer.isActive())
         m_postLayoutTasksTimer.stop();
-        m_overflowEventQueue.clear();
-    }
 
     removeFromAXObjectCache();
     resetScrollbars();
@@ -240,7 +237,6 @@
     setHasVerticalScrollbar(false);
 
     ASSERT(!m_scrollCorner);
-    ASSERT(m_overflowEventQueue.isEmpty());
 
     ASSERT(m_frame);
     ASSERT(m_frame->view() != this || !m_frame->contentRenderer());
@@ -267,6 +263,7 @@
     m_layoutCount = 0;
     m_nestedLayoutCount = 0;
     m_postLayoutTasksTimer.stop();
+    m_updateWidgetsTimer.stop();
     m_firstLayout = true;
     m_firstLayoutCallbackPending = false;
     m_wasScrolledByUser = false;
@@ -289,6 +286,7 @@
     m_firstVisuallyNonEmptyLayoutCallbackPending = true;
     m_maintainScrollPositionAnchor = 0;
     m_partialLayout.reset();
+    m_viewportConstrainedObjects.clear();
 }
 
 void FrameView::removeFromAXObjectCache()
@@ -585,7 +583,7 @@
     }
 
     bool ignoreOverflowHidden = false;
-    if (m_frame->settings()->ignoreMainFrameOverflowHiddenQuirk() && m_frame->page()->mainFrame() == m_frame)
+    if (m_frame->settings()->ignoreMainFrameOverflowHiddenQuirk() && m_frame->isMainFrame())
         ignoreOverflowHidden = true;
 
     switch (overflowX) {
@@ -863,6 +861,8 @@
     Document* document = m_frame->document();
     if (!document->styleResolverIfExists() || document->styleResolverIfExists()->affectedByViewportChange()) {
         document->styleResolverChanged(RecalcStyleDeferred);
+        document->mediaQueryAffectingValueChanged();
+
         // FIXME: This instrumentation event is not strictly accurate since cached media query results
         //        do not persist across StyleResolver rebuilds.
         InspectorInstrumentation::mediaQueryResultChanged(document);
@@ -899,7 +899,6 @@
         m_inLayout = true;
 
         forceLayoutParentViewIfNeeded();
-        renderView()->updateConfiguration();
 
         // Text Autosizing requires two-pass layout which is incompatible with partial layout.
         // If enabled, only do partial layout for the second layout.
@@ -925,10 +924,8 @@
 
 void FrameView::scheduleOrPerformPostLayoutTasks()
 {
-    if (m_postLayoutTasksTimer.isActive()) {
-        resumeOverflowEvents();
+    if (m_postLayoutTasksTimer.isActive())
         return;
-    }
 
     // Partial layouts should not happen with synchronous post layouts.
     ASSERT(!(m_inSynchronousPostLayout && partialLayout().isStopping()));
@@ -951,10 +948,8 @@
         // can make us need to update again, and we can get stuck in a nasty cycle unless
         // we call it through the timer here.
         m_postLayoutTasksTimer.startOneShot(0);
-        if (!partialLayout().isStopping() && needsLayout()) {
-            suspendOverflowEvents();
+        if (!partialLayout().isStopping() && needsLayout())
             layout();
-        }
     }
 }
 
@@ -1086,9 +1081,8 @@
 
         layer = rootForThisLayout->enclosingLayer();
 
-        suspendOverflowEvents();
-
         performLayout(rootForThisLayout, inSubtreeLayout);
+
         m_layoutRoot = 0;
     } // Reset m_layoutSchedulingEnabled to its previous value.
 
@@ -1108,6 +1102,9 @@
             // the visibleContentRect(). It just happens to work out most of the time,
             // since first layouts and printing don't have you scrolled anywhere.
             rootForThisLayout->view()->repaint();
+
+        } else if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && !partialLayout().isStopping()) {
+            repaintTree(rootForThisLayout);
         }
 
         layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, inSubtreeLayout, m_doFullRepaint));
@@ -1154,6 +1151,27 @@
         frame().page()->chrome().client().layoutUpdated(m_frame.get());
 }
 
+// The plan is to move to compositor-queried repainting, in which case this
+// method would setNeedsRedraw on the GraphicsLayers with invalidations and
+// let the compositor pick which to actually draw.
+// See http://crbug.com/306706
+void FrameView::repaintTree(RenderObject* root)
+{
+    ASSERT(RuntimeEnabledFeatures::repaintAfterLayoutEnabled());
+    ASSERT(!root->needsLayout());
+
+    for (RenderObject* renderer = root; renderer; renderer = renderer->nextInPreOrder()) {
+        const LayoutRect& oldRect = renderer->oldRepaintRect();
+        const LayoutRect& newRect = renderer->newRepaintRect();
+
+        if (oldRect != newRect) {
+            // FIXME: do repaint here.
+        }
+
+        renderer->clearRepaintRects();
+    }
+}
+
 RenderBox* FrameView::embeddedContentBox() const
 {
     RenderView* renderView = this->renderView();
@@ -1194,6 +1212,8 @@
 
 void FrameView::setMediaType(const AtomicString& mediaType)
 {
+    ASSERT(m_frame->document());
+    m_frame->document()->mediaQueryAffectingValueChanged();
     m_mediaType = mediaType;
 }
 
@@ -2025,15 +2045,8 @@
         frame->view()->serviceScrollAnimations();
         if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
             frame->animation().serviceAnimations();
-        if (RuntimeEnabledFeatures::webAnimationsEnabled()) {
-            frame->document()->animationClock().updateTime(monotonicAnimationStartTime);
-            bool didTriggerStyleRecalc = frame->document()->timeline()->serviceAnimations();
-            didTriggerStyleRecalc |= frame->document()->transitionTimeline()->serviceAnimations();
-            if (!didTriggerStyleRecalc)
-                frame->document()->animationClock().unfreeze();
-            frame->document()->timeline()->dispatchEvents();
-            frame->document()->transitionTimeline()->dispatchEvents();
-        }
+
+        DocumentAnimations::serviceOnAnimationFrame(*frame->document(), monotonicAnimationStartTime);
     }
 
     Vector<RefPtr<Document> > documents;
@@ -2052,7 +2065,7 @@
 void FrameView::setTransparent(bool isTransparent)
 {
     m_isTransparent = isTransparent;
-    if (renderView() && renderView()->layer()->compositedLayerMapping())
+    if (renderView() && renderView()->layer()->hasCompositedLayerMapping())
         renderView()->layer()->compositedLayerMapping()->updateContentsOpaque();
 }
 
@@ -2073,7 +2086,8 @@
     else
         m_baseBackgroundColor = backgroundColor;
 
-    if (CompositedLayerMapping* compositedLayerMapping = renderView() ? renderView()->layer()->compositedLayerMapping() : 0) {
+    if (renderView() && renderView()->layer()->hasCompositedLayerMapping()) {
+        CompositedLayerMappingPtr compositedLayerMapping = renderView()->layer()->compositedLayerMapping();
         compositedLayerMapping->updateContentsOpaque();
         if (compositedLayerMapping->mainGraphicsLayer())
             compositedLayerMapping->mainGraphicsLayer()->setNeedsDisplay();
@@ -2108,34 +2122,6 @@
     return true;
 }
 
-void FrameView::suspendOverflowEvents()
-{
-    ++m_overflowEventSuspendCount;
-}
-
-void FrameView::resumeOverflowEvents()
-{
-    // FIXME: We should assert here but it makes several tests fail. See http://crbug.com/299788
-    // ASSERT(m_overflowEventSuspendCount > 0);
-
-    if (--m_overflowEventSuspendCount)
-        return;
-
-    Vector<RefPtr<OverflowEvent> > events;
-    m_overflowEventQueue.swap(events);
-
-    for (Vector<RefPtr<OverflowEvent> >::iterator it = events.begin(); it != events.end(); ++it) {
-        Node* target = (*it)->target()->toNode();
-        if (target->inDocument())
-            target->dispatchEvent(*it, IGNORE_EXCEPTION);
-    }
-}
-
-void FrameView::scheduleOverflowEvent(PassRefPtr<OverflowEvent> event)
-{
-    m_overflowEventQueue.append(event);
-}
-
 void FrameView::scrollToAnchor()
 {
     RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
@@ -2229,18 +2215,29 @@
     return m_widgetUpdateSet->isEmpty();
 }
 
+void FrameView::updateWidgetsTimerFired(Timer<FrameView>*)
+{
+    RefPtr<FrameView> protect(this);
+    m_updateWidgetsTimer.stop();
+    for (unsigned i = 0; i < maxUpdateWidgetsIterations; ++i) {
+        if (updateWidgets())
+            return;
+    }
+}
+
 void FrameView::flushAnyPendingPostLayoutTasks()
 {
-    if (!m_postLayoutTasksTimer.isActive())
-        return;
-
-    performPostLayoutTasks();
+    if (m_postLayoutTasksTimer.isActive())
+        performPostLayoutTasks();
+    if (m_updateWidgetsTimer.isActive())
+        updateWidgetsTimerFired(0);
 }
 
 void FrameView::performPostLayoutTasks()
 {
     TRACE_EVENT0("webkit", "FrameView::performPostLayoutTasks");
-    // updateWidgets() call below can blow us away from underneath.
+    // FontFaceSet::didLayout() calls below can blow us away from underneath.
+    // FIXME: We should not run any JavaScript code in this function.
     RefPtr<FrameView> protect(this);
 
     m_postLayoutTasksTimer.stop();
@@ -2273,10 +2270,7 @@
     if (renderView)
         renderView->updateWidgetPositions();
 
-    for (unsigned i = 0; i < maxUpdateWidgetsIterations; i++) {
-        if (updateWidgets())
-            break;
-    }
+    m_updateWidgetsTimer.startOneShot(0);
 
     if (Page* page = m_frame->page()) {
         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
@@ -2285,8 +2279,6 @@
 
     scrollToAnchor();
 
-    resumeOverflowEvents();
-
     sendResizeEventIfNeeded();
 }
 
@@ -2309,7 +2301,7 @@
     if (!shouldSendResizeEvent)
         return;
 
-    m_frame->eventHandler().sendResizeEvent();
+    m_frame->document()->enqueueResizeEvent();
 
     if (isMainFrame())
         InspectorInstrumentation::didResizeMainFrame(m_frame->page());
@@ -2452,7 +2444,7 @@
 
         RefPtr<OverflowEvent> event = OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow, verticalOverflowChanged, verticalOverflow);
         event->setTarget(m_viewportRenderer->node());
-        scheduleOverflowEvent(event);
+        m_frame->document()->enqueueAnimationFrameEvent(event.release());
     }
 
 }
@@ -2990,7 +2982,7 @@
         s_inPaintContents = false;
     }
 
-    InspectorInstrumentation::didPaint(renderView, p, rect);
+    InspectorInstrumentation::didPaint(renderView, 0, p, rect);
 }
 
 void FrameView::setPaintBehavior(PaintBehavior behavior)
@@ -3453,7 +3445,7 @@
 
 bool FrameView::isMainFrame() const
 {
-    return m_frame->page() && m_frame->page()->mainFrame() == m_frame;
+    return m_frame->isMainFrame();
 }
 
 void FrameView::frameRectsChanged()
@@ -3473,4 +3465,20 @@
     contentsResized();
 }
 
+void FrameView::didAddScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
+{
+    ScrollableArea::didAddScrollbar(scrollbar, orientation);
+    if (AXObjectCache* cache = axObjectCache())
+        cache->handleScrollbarUpdate(this);
+}
+
+void FrameView::willRemoveScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
+{
+    ScrollableArea::willRemoveScrollbar(scrollbar, orientation);
+    if (AXObjectCache* cache = axObjectCache()) {
+        cache->remove(scrollbar);
+        cache->handleScrollbarUpdate(this);
+    }
+}
+
 } // namespace WebCore
diff --git a/Source/core/frame/FrameView.h b/Source/core/frame/FrameView.h
index bd44f62..315ea8d 100644
--- a/Source/core/frame/FrameView.h
+++ b/Source/core/frame/FrameView.h
@@ -38,12 +38,12 @@
 
 namespace WebCore {
 
+class AXObjectCache;
 class Element;
 class FloatSize;
 class Frame;
 class KURL;
 class Node;
-class OverflowEvent;
 class Page;
 class RenderBox;
 class RenderEmbeddedObject;
@@ -206,10 +206,6 @@
 
     void restoreScrollbar();
 
-    void suspendOverflowEvents();
-    void resumeOverflowEvents();
-    void scheduleOverflowEvent(PassRefPtr<OverflowEvent>);
-
     void postLayoutTimerFired(Timer<FrameView>*);
 
     bool wasScrolledByUser() const;
@@ -343,6 +339,10 @@
 
     PartialLayoutState& partialLayout() { return m_partialLayout; }
 
+    // Override scrollbar notifications to update the AXObject cache.
+    virtual void didAddScrollbar(Scrollbar*, ScrollbarOrientation) OVERRIDE;
+    virtual void willRemoveScrollbar(Scrollbar*, ScrollbarOrientation) OVERRIDE;
+
     class DeferredRepaintScope {
     public:
         DeferredRepaintScope(FrameView&);
@@ -393,6 +393,8 @@
     void scheduleOrPerformPostLayoutTasks();
     void performPostLayoutTasks();
 
+    void repaintTree(RenderObject* root);
+
     virtual void repaintContentRectangle(const IntRect&);
     virtual void contentsResized() OVERRIDE;
     virtual void scrollbarExistenceDidChange();
@@ -429,6 +431,7 @@
     void updateDeferredRepaintDelayAfterRepaint();
     double adjustedDeferredRepaintDelay() const;
 
+    void updateWidgetsTimerFired(Timer<FrameView>*);
     bool updateWidgets();
     void updateWidget(RenderObject*);
     void scrollToAnchor();
@@ -478,6 +481,7 @@
     int m_layoutCount;
     unsigned m_nestedLayoutCount;
     Timer<FrameView> m_postLayoutTasksTimer;
+    Timer<FrameView> m_updateWidgetsTimer;
     bool m_firstLayoutCallbackPending;
 
     bool m_firstLayout;
@@ -489,9 +493,6 @@
     AtomicString m_mediaType;
     AtomicString m_mediaTypeWhenNotPrinting;
 
-    unsigned m_overflowEventSuspendCount;
-    Vector<RefPtr<OverflowEvent> > m_overflowEventQueue;
-
     bool m_overflowStatusDirty;
     bool m_horizontalOverflow;
     bool m_verticalOverflow;
@@ -587,13 +588,13 @@
 
 inline FrameView* toFrameView(Widget* widget)
 {
-    ASSERT(!widget || widget->isFrameView());
+    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isFrameView());
     return static_cast<FrameView*>(widget);
 }
 
 inline const FrameView* toFrameView(const Widget* widget)
 {
-    ASSERT(!widget || widget->isFrameView());
+    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isFrameView());
     return static_cast<const FrameView*>(widget);
 }
 
diff --git a/Source/core/frame/History.cpp b/Source/core/frame/History.cpp
index 2529ced..eccbff0 100644
--- a/Source/core/frame/History.cpp
+++ b/Source/core/frame/History.cpp
@@ -37,8 +37,8 @@
 #include "core/frame/Frame.h"
 #include "core/page/BackForwardClient.h"
 #include "core/page/Page.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/MainThread.h"
 
 namespace WebCore {
@@ -70,7 +70,7 @@
     if (!m_frame)
         return 0;
 
-    if (HistoryItem* historyItem = m_frame->loader().history()->currentItem())
+    if (HistoryItem* historyItem = m_frame->loader().currentItem())
         return historyItem->stateObject();
 
     return 0;
@@ -142,7 +142,7 @@
     return KURL(document->baseURL(), urlString);
 }
 
-void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& /* title */, const String& urlString, SameDocumentNavigationSource sameDocumentNavigationSource, ExceptionState& es)
+void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& /* title */, const String& urlString, SameDocumentNavigationSource sameDocumentNavigationSource, ExceptionState& exceptionState)
 {
     if (!m_frame || !m_frame->page())
         return;
@@ -150,7 +150,7 @@
     KURL fullURL = urlForState(urlString);
     if (!fullURL.isValid() || !m_frame->document()->securityOrigin()->canRequest(fullURL)) {
         // We can safely expose the URL to JavaScript, as a) no redirection takes place: JavaScript already had this URL, b) JavaScript can only access a same-origin History object.
-        es.throwSecurityError("A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
+        exceptionState.throwSecurityError("A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
         return;
     }
     m_frame->loader().updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, FrameLoader::DoNotUpdateBackForwardList);
diff --git a/Source/core/frame/History.idl b/Source/core/frame/History.idl
index 2b8cce4..6bd6439 100644
--- a/Source/core/frame/History.idl
+++ b/Source/core/frame/History.idl
@@ -25,7 +25,7 @@
 
 interface History {
     readonly attribute unsigned long length;
-    [CustomGetter] readonly attribute SerializedScriptValue state;
+    [Custom=Getter] readonly attribute SerializedScriptValue state;
 
     [CallWith=ExecutionContext] void back();
     [CallWith=ExecutionContext] void forward();
diff --git a/Source/core/frame/ImageBitmap.idl b/Source/core/frame/ImageBitmap.idl
index b7eec85..903a2d7 100644
--- a/Source/core/frame/ImageBitmap.idl
+++ b/Source/core/frame/ImageBitmap.idl
@@ -6,4 +6,4 @@
 ] interface ImageBitmap {
     readonly attribute long width;
     readonly attribute long height;
-};
\ No newline at end of file
+};
diff --git a/Source/core/frame/ImageBitmapTest.cpp b/Source/core/frame/ImageBitmapTest.cpp
index 5656195..f7eb002 100644
--- a/Source/core/frame/ImageBitmapTest.cpp
+++ b/Source/core/frame/ImageBitmapTest.cpp
@@ -202,8 +202,8 @@
         imageBitmapDerived = ImageBitmap::create(imageBitmapFromCanvas.get(), IntRect(0, 0, 20, 20));
     }
     CanvasRenderingContext* context = canvasElement->getContext("2d");
-    TrackExceptionState es;
-    static_cast<CanvasRenderingContext2D*>(context)->drawImage(imageBitmapDerived.get(), 0, 0, es);
+    TrackExceptionState exceptionState;
+    static_cast<CanvasRenderingContext2D*>(context)->drawImage(imageBitmapDerived.get(), 0, 0, exceptionState);
 }
 
 } // namespace
diff --git a/Source/core/frame/Location.cpp b/Source/core/frame/Location.cpp
index bb7e5e7..9a8195a 100644
--- a/Source/core/frame/Location.cpp
+++ b/Source/core/frame/Location.cpp
@@ -37,8 +37,8 @@
 #include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
 #include "core/loader/FrameLoader.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
@@ -141,13 +141,13 @@
     setLocation(url, activeWindow, firstWindow);
 }
 
-void Location::setProtocol(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& protocol, ExceptionState& es)
+void Location::setProtocol(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& protocol, ExceptionState& exceptionState)
 {
     if (!m_frame)
         return;
     KURL url = m_frame->document()->url();
     if (!url.setProtocol(protocol)) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("protocol", "Location", "'" + protocol + "' is an invalid protocol."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("protocol", "Location", "'" + protocol + "' is an invalid protocol."));
         return;
     }
     setLocation(url.string(), activeWindow, firstWindow);
diff --git a/Source/core/frame/Location.idl b/Source/core/frame/Location.idl
index 1d1c893..da81ecf 100644
--- a/Source/core/frame/Location.idl
+++ b/Source/core/frame/Location.idl
@@ -27,16 +27,21 @@
  */
 
 [
-    CheckSecurity
+    CheckSecurity=Frame,
 ] interface Location {
-    [SetterCallWith=ActiveWindow&FirstWindow, DoNotCheckSecurityOnSetter, Unforgeable] attribute DOMString href;
+    // |assign|, |replace|, and *writing* |href| do not require a security
+    // check, as they *change* the page, and thus these do not change any
+    // property of an *existing* document at a different origin.
+    // However, *reading* |href|, or accessing any component, is a security
+    // problem, since that allows tracking navigation.
+    [SetterCallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity=Setter, Unforgeable] attribute DOMString href;
 
-    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds] void assign([Default=Undefined] optional DOMString url);
-    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds] void replace([Default=Undefined] optional DOMString url);
+    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void assign([Default=Undefined] optional DOMString url);
+    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void replace([Default=Undefined] optional DOMString url);
     [CallWith=ActiveWindow, Unforgeable, ReadOnly] void reload();
 
     // URI decomposition attributes
-    [SetterCallWith=ActiveWindow&FirstWindow, SetterRaisesException] attribute DOMString protocol;
+    [SetterCallWith=ActiveWindow&FirstWindow, RaisesException=Setter] attribute DOMString protocol;
     [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString host;
     [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString hostname;
     [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString port;
diff --git a/Source/core/page/UseCounter.cpp b/Source/core/frame/UseCounter.cpp
similarity index 96%
rename from Source/core/page/UseCounter.cpp
rename to Source/core/frame/UseCounter.cpp
index 0353938..720d049 100644
--- a/Source/core/page/UseCounter.cpp
+++ b/Source/core/frame/UseCounter.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StyleSheetContents.h"
@@ -527,19 +527,19 @@
 UseCounter::~UseCounter()
 {
     // We always log PageDestruction so that we have a scale for the rest of the features.
-    WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageDestruction, NumberOfFeatures);
+    blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageDestruction, NumberOfFeatures);
 
     updateMeasurements();
 }
 
 void UseCounter::updateMeasurements()
 {
-    WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageVisits, NumberOfFeatures);
+    blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageVisits, NumberOfFeatures);
 
     if (m_countBits) {
         for (unsigned i = 0; i < NumberOfFeatures; ++i) {
             if (m_countBits->quickGet(i))
-                WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", i, NumberOfFeatures);
+                blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", i, NumberOfFeatures);
         }
         // Clearing count bits is timing sensitive.
         m_countBits->clearAll();
@@ -552,13 +552,13 @@
     for (int i = firstCSSProperty; i <= lastCSSProperty; ++i) {
         if (m_CSSFeatureBits.quickGet(i)) {
             int cssSampleId = mapCSSPropertyIdToCSSSampleIdForHistogram(i);
-            WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", cssSampleId, maximumCSSSampleId());
+            blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", cssSampleId, maximumCSSSampleId());
             needsPagesMeasuredUpdate = true;
         }
     }
 
     if (needsPagesMeasuredUpdate)
-        WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", totalPagesMeasuredCSSSampleId(), maximumCSSSampleId());
+        blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", totalPagesMeasuredCSSSampleId(), maximumCSSSampleId());
 
     m_CSSFeatureBits.clearAll();
 }
@@ -682,6 +682,9 @@
     case ShowModalDialog:
         return "Chromium is considering deprecating showModalDialog. Please use window.open and postMessage instead.";
 
+    case CSSStyleSheetInsertRuleOptionalArg:
+        return "Calling CSSStyleSheet.insertRule() with one argument is deprecated. Please pass the index argument as well: insertRule(x, 0).";
+
     // Features that aren't deprecated don't have a deprecation message.
     default:
         return String();
@@ -694,7 +697,7 @@
     ASSERT(feature <= lastCSSProperty);
     ASSERT(!isInternalProperty(feature));
 
-    if (!isUseCounterEnabledForMode(context.mode))
+    if (!isUseCounterEnabledForMode(context.mode()))
         return;
 
     m_CSSFeatureBits.quickSet(feature);
@@ -724,7 +727,7 @@
 {
     // FIXME: We may want to handle stylesheets that have multiple owners
     //        http://crbug.com/242125
-    if (sheetContents && !sheetContents->isUserStyleSheet() && sheetContents->hasSingleOwnerNode())
+    if (sheetContents && sheetContents->hasSingleOwnerNode())
         return getFrom(sheetContents->singleOwnerDocument());
     return 0;
 }
diff --git a/Source/core/page/UseCounter.h b/Source/core/frame/UseCounter.h
similarity index 96%
rename from Source/core/page/UseCounter.h
rename to Source/core/frame/UseCounter.h
index dd21b79..9b337eb 100644
--- a/Source/core/page/UseCounter.h
+++ b/Source/core/frame/UseCounter.h
@@ -255,6 +255,14 @@
         InputTypePasswordMaxLength,
         SVGInstanceRoot,
         ShowModalDialog,
+        PrefixedPageVisibility,
+        HTMLFrameElementLocation,
+        CSSStyleSheetInsertRuleOptionalArg, // Inconsistent with the specification and other browsers.
+        CSSWebkitRegionAtRule, // @region rule changed to ::region()
+        DocumentBeforeUnloadRegistered,
+        DocumentBeforeUnloadFired,
+        DocumentUnloadRegistered,
+        DocumentUnloadFired,
         // 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/frame/Window.idl b/Source/core/frame/Window.idl
index 86dd8e0..c6de6c3 100644
--- a/Source/core/frame/Window.idl
+++ b/Source/core/frame/Window.idl
@@ -26,11 +26,11 @@
 
 // HTML 5 draft spec:
 // http://www.w3.org/html/wg/drafts/html/master/browsers.html#window
+// FIXME: explain all uses of [DoNotCheckSecurity]
 [
-    CheckSecurity,
+    CheckSecurity=Frame,
     CustomToV8,
-    DoNotGenerateWrap,
-    ImplementedAs=DOMWindow
+    ImplementedAs=DOMWindow,
 ] interface Window : EventTarget {
     // DOM Level 0
     [Replaceable] readonly attribute Screen screen;
@@ -43,12 +43,12 @@
     [Replaceable] readonly attribute BarProp toolbar;
     [Replaceable, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds] readonly attribute Navigator navigator;
     [Replaceable] readonly attribute Navigator clientInformation;
-    [DoNotCheckSecurity, Unforgeable, Replaceable, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, PutForwards=href] readonly attribute Location location;
+    [DoNotCheckSecurity, Unforgeable, Replaceable, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, PutForwards=href] readonly attribute Location location;
     [Custom, MeasureAs=WindowEvent, NotEnumerable] attribute Event event;
 
     Selection getSelection();
 
-    [CheckSecurityForNode] readonly attribute Element frameElement;
+    [CheckSecurity=Node, Custom=Getter] readonly attribute Element frameElement;
 
     [DoNotCheckSecurity, CallWith=ExecutionContext] void focus();
     [DoNotCheckSecurity] void blur();
@@ -93,9 +93,9 @@
     readonly attribute long pageXOffset;
     readonly attribute long pageYOffset;
 
-    void scrollBy([Default=Undefined] optional long x, [Default=Undefined] optional long y);
-    void scrollTo([Default=Undefined] optional long x, [Default=Undefined] optional long y);
-    void scroll([Default=Undefined] optional long x, [Default=Undefined] optional long y);
+    void scrollBy(long x, long y);
+    void scrollTo(long x, long y);
+    void scroll(long x, long y);
     void moveBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
     void moveTo([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
     void resizeBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
@@ -103,23 +103,23 @@
 
     [DoNotCheckSecurity] readonly attribute boolean closed;
 
-    [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute unsigned long length;
+    [Replaceable, DoNotCheckSecurity] readonly attribute unsigned long length;
 
     attribute DOMString name;
 
     attribute DOMString status;
     attribute DOMString defaultStatus;
     // This attribute is an alias of defaultStatus and is necessary for legacy uses.
-    attribute DOMString defaultstatus;
+    [ImplementedAs=defaultStatus] attribute DOMString defaultstatus;
 
     // Self referential attributes
-    [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute Window self;
+    [Replaceable, DoNotCheckSecurity] readonly attribute Window self;
     [DoNotCheckSecurity, Unforgeable] readonly attribute Window window;
-    [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute  Window frames;
+    [Replaceable, DoNotCheckSecurity] readonly attribute  Window frames;
 
-    [DoNotCheckSecurityOnGetter, CustomSetter] attribute Window opener;
-    [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute Window parent;
-    [DoNotCheckSecurityOnGetter, Unforgeable] readonly attribute Window top;
+    [DoNotCheckSecurity, Custom=Setter] attribute Window opener;
+    [Replaceable, DoNotCheckSecurity] readonly attribute Window parent;
+    [DoNotCheckSecurity, Unforgeable] readonly attribute Window top;
 
     // DOM Level 2 AbstractView Interface
     readonly attribute Document document;
@@ -147,8 +147,8 @@
 
     [RuntimeEnabled=ApplicationCache, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds] readonly attribute ApplicationCache applicationCache;
 
-    [RuntimeEnabled=SessionStorage, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage sessionStorage;
-    [RuntimeEnabled=LocalStorage, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage localStorage;
+    [RuntimeEnabled=SessionStorage, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds, RaisesException=Getter] readonly attribute Storage sessionStorage;
+    [RuntimeEnabled=LocalStorage, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds, RaisesException=Getter] readonly attribute Storage localStorage;
 
     // This is the interface orientation in degrees. Some examples are:
     //  0 is straight up; -90 is when the device is rotated 90 clockwise;
@@ -187,7 +187,7 @@
     attribute EventHandler onwebkitanimationiteration;
     attribute EventHandler onwebkitanimationstart;
     attribute EventHandler onwebkittransitionend;
-    [ActivityLogging=SetterForAllWorlds] attribute EventHandler onwheel;
+    [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onwheel;
 
     [DeprecateAs=CaptureEvents] void captureEvents();
     [DeprecateAs=ReleaseEvents] void releaseEvents();
diff --git a/Source/core/frame/animation/AnimationBase.cpp b/Source/core/frame/animation/AnimationBase.cpp
index 20af331..c638f8f 100644
--- a/Source/core/frame/animation/AnimationBase.cpp
+++ b/Source/core/frame/animation/AnimationBase.cpp
@@ -40,7 +40,7 @@
 
 namespace WebCore {
 
-AnimationBase::AnimationBase(const CSSAnimationData* transition, RenderObject* renderer, CompositeAnimation* compAnim)
+AnimationBase::AnimationBase(const CSSAnimationData* transition, RenderObject& renderer, CompositeAnimation* compAnim)
     : m_animState(AnimationStateNew)
     , m_isAccelerated(false)
     , m_transformFunctionListValid(false)
@@ -50,7 +50,7 @@
     , m_requestedStartTime(0)
     , m_totalDuration(-1)
     , m_nextIterationDuration(-1)
-    , m_object(renderer)
+    , m_object(&renderer)
     , m_animation(const_cast<CSSAnimationData*>(transition))
     , m_compAnim(compAnim)
 {
@@ -518,7 +518,7 @@
 
     if (m_totalDuration < 0 || nextIterationTime < m_totalDuration) {
         // We are not at the end yet
-        ASSERT(nextIterationTime > 0);
+        ASSERT(m_totalDuration < 0 || nextIterationTime > 0);
         isLooping = true;
     } else {
         // We are at the end
diff --git a/Source/core/frame/animation/AnimationBase.h b/Source/core/frame/animation/AnimationBase.h
index ac28753..6ab1d58 100644
--- a/Source/core/frame/animation/AnimationBase.h
+++ b/Source/core/frame/animation/AnimationBase.h
@@ -50,7 +50,7 @@
     friend class CSSPropertyAnimation;
 
 public:
-    AnimationBase(const CSSAnimationData* transition, RenderObject* renderer, CompositeAnimation* compAnim);
+    AnimationBase(const CSSAnimationData* transition, RenderObject& renderer, CompositeAnimation* compAnim);
     virtual ~AnimationBase() { }
 
     RenderObject* renderer() const { return m_object; }
diff --git a/Source/core/frame/animation/AnimationController.cpp b/Source/core/frame/animation/AnimationController.cpp
index 152fa96..defa4e5 100644
--- a/Source/core/frame/animation/AnimationController.cpp
+++ b/Source/core/frame/animation/AnimationController.cpp
@@ -62,12 +62,12 @@
 {
 }
 
-PassRefPtr<CompositeAnimation> AnimationControllerPrivate::accessCompositeAnimation(RenderObject* renderer)
+PassRefPtr<CompositeAnimation> AnimationControllerPrivate::accessCompositeAnimation(RenderObject& renderer)
 {
-    RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
+    RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(&renderer);
     if (!animation) {
         animation = CompositeAnimation::create(this);
-        m_compositeAnimations.set(renderer, animation);
+        m_compositeAnimations.set(&renderer, animation);
     }
     return animation;
 }
@@ -118,12 +118,12 @@
     timeToNextEvent = minTimeToNextEvent;
 }
 
-void AnimationControllerPrivate::scheduleServiceForRenderer(RenderObject* renderer)
+void AnimationControllerPrivate::scheduleServiceForRenderer(RenderObject& renderer)
 {
     double timeToNextService = -1;
     double timeToNextEvent = -1;
 
-    RefPtr<CompositeAnimation> compAnim = m_compositeAnimations.get(renderer);
+    RefPtr<CompositeAnimation> compAnim = m_compositeAnimations.get(&renderer);
     if (compAnim->hasAnimations()) {
         timeToNextService = compAnim->timeToNextService();
         timeToNextEvent = compAnim->timeToNextEvent();
@@ -265,7 +265,7 @@
     return animation->isAnimatingProperty(property, false, isRunningNow);
 }
 
-bool AnimationControllerPrivate::isRunningAcceleratableAnimationOnRenderer(RenderObject *renderer) const
+bool AnimationControllerPrivate::isRunningAcceleratableAnimationOnRenderer(RenderObject *renderer, bool isOpacityAcceleratable) const
 {
     RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
     if (!animation)
@@ -273,7 +273,7 @@
 
     bool acceleratedOnly = false;
     bool isRunningNow = true;
-    return animation->isAnimatingProperty(CSSPropertyOpacity, acceleratedOnly, isRunningNow)
+    return (isOpacityAcceleratable && animation->isAnimatingProperty(CSSPropertyOpacity, acceleratedOnly, isRunningNow))
         || animation->isAnimatingProperty(CSSPropertyWebkitTransform, acceleratedOnly, isRunningNow)
         || animation->isAnimatingProperty(CSSPropertyWebkitFilter, acceleratedOnly, isRunningNow);
 }
@@ -443,16 +443,16 @@
     }
 }
 
-PassRefPtr<RenderStyle> AnimationController::updateAnimations(RenderObject* renderer, RenderStyle* newStyle)
+PassRefPtr<RenderStyle> AnimationController::updateAnimations(RenderObject& renderer, RenderStyle& newStyle)
 {
-    RenderStyle* oldStyle = renderer->style();
+    RenderStyle* oldStyle = renderer.style();
 
-    if ((!oldStyle || (!oldStyle->animations() && !oldStyle->transitions())) && (!newStyle->animations() && !newStyle->transitions()))
-        return newStyle;
+    if ((!oldStyle || (!oldStyle->animations() && !oldStyle->transitions())) && (!newStyle.animations() && !newStyle.transitions()))
+        return PassRefPtr<RenderStyle>(newStyle);
 
     // Don't run transitions when printing.
-    if (renderer->view()->document().printing())
-        return newStyle;
+    if (renderer.view()->document().printing())
+        return PassRefPtr<RenderStyle>(newStyle);
 
     // Fetch our current set of implicit animations from a hashtable.  We then compare them
     // against the animations in the style and make sure we're in sync.  If destination values
@@ -460,16 +460,16 @@
     // a new style.
 
     // We don't support anonymous pseudo elements like :first-line or :first-letter.
-    ASSERT(renderer->node());
+    ASSERT(renderer.node());
 
     RefPtr<CompositeAnimation> rendererAnimations = m_data->accessCompositeAnimation(renderer);
     RefPtr<RenderStyle> blendedStyle = rendererAnimations->animate(renderer, oldStyle, newStyle);
 
-    if (renderer->parent() || newStyle->animations() || (oldStyle && oldStyle->animations())) {
+    if (renderer.parent() || newStyle.animations() || (oldStyle && oldStyle->animations())) {
         m_data->scheduleServiceForRenderer(renderer);
     }
 
-    if (blendedStyle != newStyle) {
+    if (blendedStyle != &newStyle) {
         // If the animations/transitions change opacity or transform, we need to update
         // the style to impose the stacking rules. Note that this is also
         // done in StyleResolver::adjustRenderStyle().
@@ -504,9 +504,9 @@
     return m_data->isRunningAnimationOnRenderer(renderer, property, isRunningNow);
 }
 
-bool AnimationController::isRunningAcceleratableAnimationOnRenderer(RenderObject* renderer) const
+bool AnimationController::isRunningAcceleratableAnimationOnRenderer(RenderObject* renderer, bool isOpacityAcceleratable) const
 {
-    return m_data->isRunningAcceleratableAnimationOnRenderer(renderer);
+    return m_data->isRunningAcceleratableAnimationOnRenderer(renderer, isOpacityAcceleratable);
 }
 
 bool AnimationController::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
diff --git a/Source/core/frame/animation/AnimationController.h b/Source/core/frame/animation/AnimationController.h
index 2f5564a..0713254 100644
--- a/Source/core/frame/animation/AnimationController.h
+++ b/Source/core/frame/animation/AnimationController.h
@@ -50,7 +50,7 @@
     ~AnimationController();
 
     void cancelAnimations(RenderObject*);
-    PassRefPtr<RenderStyle> updateAnimations(RenderObject*, RenderStyle* newStyle);
+    PassRefPtr<RenderStyle> updateAnimations(RenderObject&, RenderStyle& newStyle);
     PassRefPtr<RenderStyle> getAnimatedStyleForRenderer(RenderObject*);
 
     // This is called when an accelerated animation or transition has actually started to animate.
@@ -60,7 +60,7 @@
     unsigned numberOfActiveAnimations(Document*) const; // To be used only for testing
 
     bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
-    bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
+    bool isRunningAcceleratableAnimationOnRenderer(RenderObject*, bool isOpacityAcceleratable) const;
     bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
 
     void serviceAnimations();
diff --git a/Source/core/frame/animation/AnimationControllerPrivate.h b/Source/core/frame/animation/AnimationControllerPrivate.h
index 94a0ec3..aa69d2f 100644
--- a/Source/core/frame/animation/AnimationControllerPrivate.h
+++ b/Source/core/frame/animation/AnimationControllerPrivate.h
@@ -64,7 +64,7 @@
     void updateAnimations(double& timeToNextService, double& timeToNextEvent, SetNeedsStyleRecalc callSetNeedsStyleRecalc = DoNotCallSetNeedsStyleRecalc);
     void scheduleService();
 
-    PassRefPtr<CompositeAnimation> accessCompositeAnimation(RenderObject*);
+    PassRefPtr<CompositeAnimation> accessCompositeAnimation(RenderObject&);
     bool clear(RenderObject*);
 
     void updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*);
@@ -77,7 +77,7 @@
     void serviceAnimations();
 
     bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
-    bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
+    bool isRunningAcceleratableAnimationOnRenderer(RenderObject*, bool isOpacityAcceleratable) const;
     bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
 
     void pauseAnimationsForTesting(double t);
@@ -98,7 +98,7 @@
 
     void animationWillBeRemoved(AnimationBase*);
 
-    void scheduleServiceForRenderer(RenderObject*);
+    void scheduleServiceForRenderer(RenderObject&);
 
 private:
     void animationTimerFired(Timer<AnimationControllerPrivate>*);
diff --git a/Source/core/frame/animation/CSSPropertyAnimation.cpp b/Source/core/frame/animation/CSSPropertyAnimation.cpp
index db32502..a3c2608 100644
--- a/Source/core/frame/animation/CSSPropertyAnimation.cpp
+++ b/Source/core/frame/animation/CSSPropertyAnimation.cpp
@@ -71,10 +71,34 @@
     return to.blend(from, progress, ValueRangeAll);
 }
 
+static inline BorderImageLength blendFunc(const AnimationBase* anim, const BorderImageLength& from, const BorderImageLength& to, double progress)
+{
+    if (from.isNumber() && to.isNumber())
+        return BorderImageLength(blendFunc(anim, from.number(), to.number(), progress));
+
+    if (from.isLength() && to.isLength())
+        return BorderImageLength(blendFunc(anim, from.length(), to.length(), progress));
+
+    // FIXME: Converting numbers to lengths using the computed border
+    // width would make it possible to interpolate between numbers and
+    // lengths.
+    // https://code.google.com/p/chromium/issues/detail?id=316164
+    return to;
+}
+
+static inline BorderImageLengthBox blendFunc(const AnimationBase* anim, const BorderImageLengthBox& from,
+    const BorderImageLengthBox& to, double progress)
+{
+    return BorderImageLengthBox(blendFunc(anim, from.top(), to.top(), progress),
+        blendFunc(anim, from.right(), to.right(), progress),
+        blendFunc(anim, from.bottom(), to.bottom(), progress),
+        blendFunc(anim, from.left(), to.left(), progress));
+}
+
 static inline LengthSize blendFunc(const AnimationBase* anim, const LengthSize& from, const LengthSize& to, double progress)
 {
     return LengthSize(blendFunc(anim, from.width(), to.width(), progress),
-                      blendFunc(anim, from.height(), to.height(), progress));
+        blendFunc(anim, from.height(), to.height(), progress));
 }
 
 static inline LengthPoint blendFunc(const AnimationBase* anim, const LengthPoint& from, const LengthPoint& to, double progress)
@@ -82,12 +106,6 @@
     return LengthPoint(blendFunc(anim, from.x(), to.x(), progress), blendFunc(anim, from.y(), to.y(), progress));
 }
 
-static inline IntSize blendFunc(const AnimationBase* anim, const IntSize& from, const IntSize& to, double progress)
-{
-    return IntSize(blendFunc(anim, from.width(), to.width(), progress),
-                   blendFunc(anim, from.height(), to.height(), progress));
-}
-
 static inline TransformOperations blendFunc(const AnimationBase* anim, const TransformOperations& from, const TransformOperations& to, double progress)
 {
     if (anim->isTransformFunctionListValid())
@@ -98,11 +116,11 @@
 static inline PassRefPtr<ClipPathOperation> blendFunc(const AnimationBase*, ClipPathOperation* from, ClipPathOperation* to, double progress)
 {
     // Other clip-path operations than BasicShapes can not be animated.
-    if (from->getOperationType() != ClipPathOperation::SHAPE || to->getOperationType() != ClipPathOperation::SHAPE)
+    if (!from || !to || from->type() != ClipPathOperation::SHAPE || to->type() != ClipPathOperation::SHAPE)
         return to;
 
-    const BasicShape* fromShape = static_cast<ShapeClipPathOperation*>(from)->basicShape();
-    const BasicShape* toShape = static_cast<ShapeClipPathOperation*>(to)->basicShape();
+    const BasicShape* fromShape = toShapeClipPathOperation(from)->basicShape();
+    const BasicShape* toShape = toShapeClipPathOperation(to)->basicShape();
 
     if (!fromShape->canBlend(toShape))
         return to;
@@ -113,7 +131,7 @@
 static inline PassRefPtr<ShapeValue> blendFunc(const AnimationBase*, ShapeValue* from, ShapeValue* to, double progress)
 {
     // FIXME Bug 102723: Shape-inside should be able to animate a value of 'outside-shape' when shape-outside is set to a BasicShape
-    if (from->type() != ShapeValue::Shape || to->type() != ShapeValue::Shape)
+    if (!from || !to || from->type() != ShapeValue::Shape || to->type() != ShapeValue::Shape)
         return to;
 
     const BasicShape* fromShape = from->shape();
@@ -236,31 +254,13 @@
         return to;
 
     if (from->isImageResource() && to->isImageResource())
-        return crossfadeBlend(anim, static_cast<StyleFetchedImage*>(from), static_cast<StyleFetchedImage*>(to), progress);
+        return crossfadeBlend(anim, toStyleFetchedImage(from), toStyleFetchedImage(to), progress);
 
     // FIXME: Support transitioning generated images as well. (gradients, etc.)
 
     return to;
 }
 
-static inline NinePieceImage blendFunc(const AnimationBase* anim, const NinePieceImage& from, const NinePieceImage& to, double progress)
-{
-    if (!from.hasImage() || !to.hasImage())
-        return to;
-
-    // FIXME (74112): Support transitioning between NinePieceImages that differ by more than image content.
-
-    if (from.imageSlices() != to.imageSlices() || from.borderSlices() != to.borderSlices() || from.outset() != to.outset() || from.fill() != to.fill() || from.horizontalRule() != to.horizontalRule() || from.verticalRule() != to.verticalRule())
-        return to;
-
-    if (from.image()->imageSize(anim->renderer(), 1.0) != to.image()->imageSize(anim->renderer(), 1.0))
-        return to;
-
-    RefPtr<StyleImage> newContentImage = blendFunc(anim, from.image(), to.image(), progress);
-
-    return NinePieceImage(newContentImage, from.imageSlices(), from.fill(), from.borderSlices(), from.outset(), from.horizontalRule(), from.verticalRule());
-}
-
 class AnimationPropertyWrapperBase {
     WTF_MAKE_NONCOPYABLE(AnimationPropertyWrapperBase);
     WTF_MAKE_FAST_ALLOCATED;
@@ -965,11 +965,13 @@
 
     gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyBorderImageSource, &RenderStyle::borderImageSource, &RenderStyle::setBorderImageSource));
     gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageSlice, &RenderStyle::borderImageSlices, &RenderStyle::setBorderImageSlices));
-    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageWidth, &RenderStyle::borderImageWidth, &RenderStyle::setBorderImageWidth));
-    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageOutset, &RenderStyle::borderImageOutset, &RenderStyle::setBorderImageOutset));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageWidth, &RenderStyle::borderImageWidth, &RenderStyle::setBorderImageWidth));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageOutset, &RenderStyle::borderImageOutset, &RenderStyle::setBorderImageOutset));
 
     gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskBoxImageSource, &RenderStyle::maskBoxImageSource, &RenderStyle::setMaskBoxImageSource));
-    gPropertyWrappers->append(new PropertyWrapper<const NinePieceImage&>(CSSPropertyWebkitMaskBoxImage, &RenderStyle::maskBoxImage, &RenderStyle::setMaskBoxImage));
+    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyWebkitMaskBoxImageSlice, &RenderStyle::maskBoxImageSlices, &RenderStyle::setMaskBoxImageSlices));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageWidth, &RenderStyle::maskBoxImageWidth, &RenderStyle::setMaskBoxImageWidth));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageOutset, &RenderStyle::maskBoxImageOutset, &RenderStyle::setMaskBoxImageOutset));
 
     gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionX, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
     gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionY, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
@@ -1029,6 +1031,7 @@
     gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyShapeInside, &RenderStyle::shapeInside, &RenderStyle::setShapeInside));
     gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyShapeOutside, &RenderStyle::shapeOutside, &RenderStyle::setShapeOutside));
     gPropertyWrappers->append(new NonNegativeLengthWrapper(CSSPropertyShapeMargin, &RenderStyle::shapeMargin, &RenderStyle::setShapeMargin));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyShapeImageThreshold, &RenderStyle::shapeImageThreshold, &RenderStyle::setShapeImageThreshold));
 
     gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitColumnRuleColor, MaybeInvalidColor, &RenderStyle::columnRuleColor, &RenderStyle::setColumnRuleColor, &RenderStyle::visitedLinkColumnRuleColor, &RenderStyle::setVisitedLinkColumnRuleColor));
     gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitTextStrokeColor, MaybeInvalidColor, &RenderStyle::textStrokeColor, &RenderStyle::setTextStrokeColor, &RenderStyle::visitedLinkTextStrokeColor, &RenderStyle::setVisitedLinkTextStrokeColor));
diff --git a/Source/core/frame/animation/CompositeAnimation.cpp b/Source/core/frame/animation/CompositeAnimation.cpp
index d796e72..f3c52db 100644
--- a/Source/core/frame/animation/CompositeAnimation.cpp
+++ b/Source/core/frame/animation/CompositeAnimation.cpp
@@ -70,10 +70,10 @@
     }
 }
 
-void CompositeAnimation::updateTransitions(RenderObject* renderer, RenderStyle* currentStyle, RenderStyle* targetStyle)
+void CompositeAnimation::updateTransitions(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
 {
     // If currentStyle is null or there are no old or new transitions, just skip it
-    if (!currentStyle || (!targetStyle->transitions() && m_transitions.isEmpty()))
+    if (!currentStyle || (!targetStyle.transitions() && m_transitions.isEmpty()))
         return;
 
     // Mark all existing transitions as no longer active. We will mark the still active ones
@@ -85,9 +85,9 @@
     RefPtr<RenderStyle> modifiedCurrentStyle;
 
     // Check to see if we need to update the active transitions
-    if (targetStyle->transitions()) {
-        for (size_t i = 0; i < targetStyle->transitions()->size(); ++i) {
-            const CSSAnimationData* anim = targetStyle->transitions()->animation(i);
+    if (targetStyle.transitions()) {
+        for (size_t i = 0; i < targetStyle.transitions()->size(); ++i) {
+            const CSSAnimationData* anim = targetStyle.transitions()->animation(i);
             bool isActiveTransition = anim->duration() || anim->delay() > 0;
 
             CSSAnimationData::AnimationMode mode = anim->animationMode();
@@ -137,7 +137,7 @@
                     // you have both an explicit transition-property and 'all' in the same
                     // list. In this case, the latter one overrides the earlier one, so we
                     // behave as though this is a running animation being replaced.
-                    if (!implAnim->isTargetPropertyEqual(prop, targetStyle)) {
+                    if (!implAnim->isTargetPropertyEqual(prop, &targetStyle)) {
                         // For accelerated animations we need to return a new RenderStyle with the _current_ value
                         // of the property, so that restarted transitions use the correct starting point.
                         if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(prop) && implAnim->isAccelerated()) {
@@ -152,7 +152,7 @@
                     }
                 } else {
                     // We need to start a transition if it is active and the properties don't match
-                    equal = !isActiveTransition || CSSPropertyAnimation::propertiesEqual(prop, fromStyle, targetStyle);
+                    equal = !isActiveTransition || CSSPropertyAnimation::propertiesEqual(prop, fromStyle, &targetStyle);
                 }
 
                 // We can be in this loop with an inactive transition (!isActiveTransition). We need
@@ -187,15 +187,15 @@
         m_transitions.remove(toBeRemoved[j]);
 }
 
-void CompositeAnimation::updateKeyframeAnimations(RenderObject* renderer, RenderStyle* currentStyle, RenderStyle* targetStyle)
+void CompositeAnimation::updateKeyframeAnimations(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
 {
     // Nothing to do if we don't have any animations, and didn't have any before
-    if (m_keyframeAnimations.isEmpty() && !targetStyle->hasAnimations())
+    if (m_keyframeAnimations.isEmpty() && !targetStyle.hasAnimations())
         return;
 
     AnimationNameMap::const_iterator kfend = m_keyframeAnimations.end();
 
-    if (currentStyle && currentStyle->hasAnimations() && targetStyle->hasAnimations() && *(currentStyle->animations()) == *(targetStyle->animations())) {
+    if (currentStyle && currentStyle->hasAnimations() && targetStyle.hasAnimations() && *(currentStyle->animations()) == *(targetStyle.animations())) {
         // The current and target animations are the same so we just need to toss any
         // animation which is finished (postActive).
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it) {
@@ -213,10 +213,10 @@
         DEFINE_STATIC_LOCAL(const AtomicString, none, ("none", AtomicString::ConstructFromLiteral));
 
         // Now mark any still active animations as active and add any new animations.
-        if (targetStyle->animations()) {
-            int numAnims = targetStyle->animations()->size();
+        if (targetStyle.animations()) {
+            int numAnims = targetStyle.animations()->size();
             for (int i = 0; i < numAnims; ++i) {
-                const CSSAnimationData* anim = targetStyle->animations()->animation(i);
+                const CSSAnimationData* anim = targetStyle.animations()->animation(i);
                 if (!anim->isValidAnimation())
                     continue;
 
@@ -276,7 +276,7 @@
     }
 }
 
-PassRefPtr<RenderStyle> CompositeAnimation::animate(RenderObject* renderer, RenderStyle* currentStyle, RenderStyle* targetStyle)
+PassRefPtr<RenderStyle> CompositeAnimation::animate(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
 {
     RefPtr<RenderStyle> resultStyle;
 
@@ -291,7 +291,7 @@
             CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
             for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
                 if (ImplicitAnimation* anim = it->value.get())
-                    anim->animate(this, renderer, currentStyle, targetStyle, resultStyle);
+                    anim->animate(this, &renderer, currentStyle, &targetStyle, resultStyle);
             }
         }
     }
@@ -301,10 +301,10 @@
     for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
         RefPtr<KeyframeAnimation> keyframeAnim = m_keyframeAnimations.get(*it);
         ASSERT(keyframeAnim);
-        keyframeAnim->animate(this, renderer, currentStyle, targetStyle, resultStyle);
+        keyframeAnim->animate(this, &renderer, currentStyle, &targetStyle, resultStyle);
     }
 
-    return resultStyle ? resultStyle.release() : targetStyle;
+    return resultStyle ? resultStyle.release() : PassRefPtr<RenderStyle>(targetStyle);
 }
 
 PassRefPtr<RenderStyle> CompositeAnimation::getAnimatedStyle() const
diff --git a/Source/core/frame/animation/CompositeAnimation.h b/Source/core/frame/animation/CompositeAnimation.h
index bc43b90..ee0bd46 100644
--- a/Source/core/frame/animation/CompositeAnimation.h
+++ b/Source/core/frame/animation/CompositeAnimation.h
@@ -53,7 +53,7 @@
 
     void clearRenderer();
 
-    PassRefPtr<RenderStyle> animate(RenderObject*, RenderStyle* currentStyle, RenderStyle* targetStyle);
+    PassRefPtr<RenderStyle> animate(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
     PassRefPtr<RenderStyle> getAnimatedStyle() const;
 
     double timeToNextService() const;
@@ -79,8 +79,8 @@
     {
     }
 
-    void updateTransitions(RenderObject*, RenderStyle* currentStyle, RenderStyle* targetStyle);
-    void updateKeyframeAnimations(RenderObject*, RenderStyle* currentStyle, RenderStyle* targetStyle);
+    void updateTransitions(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
+    void updateKeyframeAnimations(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
 
     typedef HashMap<int, RefPtr<ImplicitAnimation> > CSSPropertyTransitionsMap;
     typedef HashMap<AtomicString, RefPtr<KeyframeAnimation> > AnimationNameMap;
diff --git a/Source/core/frame/animation/ImplicitAnimation.cpp b/Source/core/frame/animation/ImplicitAnimation.cpp
index bd9eb6b..2cf82b6 100644
--- a/Source/core/frame/animation/ImplicitAnimation.cpp
+++ b/Source/core/frame/animation/ImplicitAnimation.cpp
@@ -29,7 +29,7 @@
 #include "config.h"
 
 #include "core/events/ThreadLocalEventNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/frame/animation/AnimationControllerPrivate.h"
 #include "core/frame/animation/CSSPropertyAnimation.h"
 #include "core/frame/animation/CompositeAnimation.h"
@@ -40,7 +40,7 @@
 
 namespace WebCore {
 
-ImplicitAnimation::ImplicitAnimation(const CSSAnimationData* transition, CSSPropertyID animatingProperty, RenderObject* renderer, CompositeAnimation* compAnim, RenderStyle* fromStyle)
+ImplicitAnimation::ImplicitAnimation(const CSSAnimationData* transition, CSSPropertyID animatingProperty, RenderObject& renderer, CompositeAnimation* compAnim, RenderStyle* fromStyle)
     : AnimationBase(transition, renderer, compAnim)
     , m_transitionProperty(transition->property())
     , m_animatingProperty(animatingProperty)
@@ -49,7 +49,7 @@
     , m_fromStyle(fromStyle)
 {
     ASSERT(animatingProperty != CSSPropertyInvalid);
-    WebKit::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(m_animatingProperty));
+    blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(m_animatingProperty));
 }
 
 ImplicitAnimation::~ImplicitAnimation()
diff --git a/Source/core/frame/animation/ImplicitAnimation.h b/Source/core/frame/animation/ImplicitAnimation.h
index 573bf1c..c531b36 100644
--- a/Source/core/frame/animation/ImplicitAnimation.h
+++ b/Source/core/frame/animation/ImplicitAnimation.h
@@ -39,7 +39,7 @@
 // for a single RenderObject.
 class ImplicitAnimation : public AnimationBase {
 public:
-    static PassRefPtr<ImplicitAnimation> create(const CSSAnimationData* animation, CSSPropertyID animatingProperty, RenderObject* renderer, CompositeAnimation* compositeAnimation, RenderStyle* fromStyle)
+    static PassRefPtr<ImplicitAnimation> create(const CSSAnimationData* animation, CSSPropertyID animatingProperty, RenderObject& renderer, CompositeAnimation* compositeAnimation, RenderStyle* fromStyle)
     {
         return adoptRef(new ImplicitAnimation(animation, animatingProperty, renderer, compositeAnimation, fromStyle));
     };
@@ -80,7 +80,7 @@
     void checkForMatchingFilterFunctionLists();
 
 private:
-    ImplicitAnimation(const CSSAnimationData*, CSSPropertyID, RenderObject*, CompositeAnimation*, RenderStyle*);
+    ImplicitAnimation(const CSSAnimationData*, CSSPropertyID, RenderObject&, CompositeAnimation*, RenderStyle*);
     virtual ~ImplicitAnimation();
 
     CSSPropertyID m_transitionProperty; // Transition property as specified in the RenderStyle.
diff --git a/Source/core/frame/animation/KeyframeAnimation.cpp b/Source/core/frame/animation/KeyframeAnimation.cpp
index 8ef47df..616981f 100644
--- a/Source/core/frame/animation/KeyframeAnimation.cpp
+++ b/Source/core/frame/animation/KeyframeAnimation.cpp
@@ -32,7 +32,7 @@
 #include "CSSPropertyNames.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/events/ThreadLocalEventNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/frame/animation/AnimationControllerPrivate.h"
 #include "core/frame/animation/CSSPropertyAnimation.h"
 #include "core/frame/animation/CompositeAnimation.h"
@@ -44,7 +44,7 @@
 
 namespace WebCore {
 
-KeyframeAnimation::KeyframeAnimation(const CSSAnimationData* animation, RenderObject* renderer, int index, CompositeAnimation* compAnim, RenderStyle* unanimatedStyle)
+KeyframeAnimation::KeyframeAnimation(const CSSAnimationData* animation, RenderObject& renderer, int index, CompositeAnimation* compAnim, RenderStyle& unanimatedStyle)
     : AnimationBase(animation, renderer, compAnim)
     , m_keyframes(renderer, animation->name())
     , m_index(index)
@@ -60,7 +60,7 @@
     checkForMatchingFilterFunctionLists();
     HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
     for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it)
-        WebKit::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(*it));
+        blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(*it));
 }
 
 KeyframeAnimation::~KeyframeAnimation()
@@ -147,9 +147,7 @@
     // A scale of infinity is handled in AnimationBase::fractionalTime().
     ASSERT(scale >= 0 && (!std::isinf(scale) || prevIndex == nextIndex));
 
-    // FIXME: This sometimes gets the wrong timing function. See crbug.com/288540.
-    const TimingFunction* timingFunction = KeyframeValue::timingFunction(prevKeyframe.style(), name());
-    prog = progress(scale, offset, timingFunction);
+    prog = progress(scale, offset, KeyframeValue::timingFunction(*prevKeyframe.style()));
 }
 
 void KeyframeAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
diff --git a/Source/core/frame/animation/KeyframeAnimation.h b/Source/core/frame/animation/KeyframeAnimation.h
index 82c198a..93334d9 100644
--- a/Source/core/frame/animation/KeyframeAnimation.h
+++ b/Source/core/frame/animation/KeyframeAnimation.h
@@ -41,7 +41,7 @@
 // for a single RenderObject.
 class KeyframeAnimation : public AnimationBase {
 public:
-    static PassRefPtr<KeyframeAnimation> create(const CSSAnimationData* animation, RenderObject* renderer, int index, CompositeAnimation* compositeAnimation, RenderStyle* unanimatedStyle)
+    static PassRefPtr<KeyframeAnimation> create(const CSSAnimationData* animation, RenderObject& renderer, int index, CompositeAnimation* compositeAnimation, RenderStyle& unanimatedStyle)
     {
         return adoptRef(new KeyframeAnimation(animation, renderer, index, compositeAnimation, unanimatedStyle));
     };
@@ -80,7 +80,7 @@
     void checkForMatchingFilterFunctionLists();
 
 private:
-    KeyframeAnimation(const CSSAnimationData* animation, RenderObject*, int index, CompositeAnimation*, RenderStyle* unanimatedStyle);
+    KeyframeAnimation(const CSSAnimationData*, RenderObject&, int index, CompositeAnimation*, RenderStyle& unanimatedStyle);
     virtual ~KeyframeAnimation();
 
     // Get the styles for the given property surrounding the current animation time and the progress between them.
diff --git a/Source/core/history/HistoryItem.cpp b/Source/core/history/HistoryItem.cpp
index 4c48804..93b9dc8 100644
--- a/Source/core/history/HistoryItem.cpp
+++ b/Source/core/history/HistoryItem.cpp
@@ -66,6 +66,7 @@
     , m_target(item.m_target)
     , m_scrollPoint(item.m_scrollPoint)
     , m_pageScaleFactor(item.m_pageScaleFactor)
+    , m_documentState(item.m_documentState)
     , m_itemSequenceNumber(item.m_itemSequenceNumber)
     , m_documentSequenceNumber(item.m_documentSequenceNumber)
     , m_targetFrameID(item.m_targetFrameID)
@@ -208,42 +209,9 @@
 
 void HistoryItem::addChildItem(PassRefPtr<HistoryItem> child)
 {
-    ASSERT(!childItemWithTarget(child->target()));
     m_children.append(child);
 }
 
-void HistoryItem::setChildItem(PassRefPtr<HistoryItem> child)
-{
-    unsigned size = m_children.size();
-    for (unsigned i = 0; i < size; ++i)  {
-        if (m_children[i]->target() == child->target()) {
-            m_children[i] = child;
-            return;
-        }
-    }
-    m_children.append(child);
-}
-
-HistoryItem* HistoryItem::childItemWithTarget(const String& target) const
-{
-    unsigned size = m_children.size();
-    for (unsigned i = 0; i < size; ++i) {
-        if (m_children[i]->target() == target)
-            return m_children[i].get();
-    }
-    return 0;
-}
-
-HistoryItem* HistoryItem::childItemWithDocumentSequenceNumber(long long number) const
-{
-    unsigned size = m_children.size();
-    for (unsigned i = 0; i < size; ++i) {
-        if (m_children[i]->documentSequenceNumber() == number)
-            return m_children[i].get();
-    }
-    return 0;
-}
-
 const HistoryItemVector& HistoryItem::children() const
 {
     return m_children;
@@ -254,61 +222,6 @@
     m_children.clear();
 }
 
-// We do same-document navigation if going to a different item and if either of the following is true:
-// - The other item corresponds to the same document (for history entries created via pushState or fragment changes).
-// - The other item corresponds to the same set of documents, including frames (for history entries created via regular navigation)
-bool HistoryItem::shouldDoSameDocumentNavigationTo(HistoryItem* otherItem) const
-{
-    if (this == otherItem)
-        return false;
-
-    if (stateObject() || otherItem->stateObject())
-        return documentSequenceNumber() == otherItem->documentSequenceNumber();
-
-    if ((url().hasFragmentIdentifier() || otherItem->url().hasFragmentIdentifier()) && equalIgnoringFragmentIdentifier(url(), otherItem->url()))
-        return documentSequenceNumber() == otherItem->documentSequenceNumber();
-
-    return hasSameDocumentTree(otherItem);
-}
-
-// Does a recursive check that this item and its descendants have the same
-// document sequence numbers as the other item.
-bool HistoryItem::hasSameDocumentTree(HistoryItem* otherItem) const
-{
-    if (documentSequenceNumber() != otherItem->documentSequenceNumber())
-        return false;
-
-    if (children().size() != otherItem->children().size())
-        return false;
-
-    for (size_t i = 0; i < children().size(); i++) {
-        HistoryItem* child = children()[i].get();
-        HistoryItem* otherChild = otherItem->childItemWithDocumentSequenceNumber(child->documentSequenceNumber());
-        if (!otherChild || !child->hasSameDocumentTree(otherChild))
-            return false;
-    }
-
-    return true;
-}
-
-// Does a non-recursive check that this item and its immediate children have the
-// same frames as the other item.
-bool HistoryItem::hasSameFrames(HistoryItem* otherItem) const
-{
-    if (target() != otherItem->target())
-        return false;
-
-    if (children().size() != otherItem->children().size())
-        return false;
-
-    for (size_t i = 0; i < children().size(); i++) {
-        if (!otherItem->childItemWithTarget(children()[i]->target()))
-            return false;
-    }
-
-    return true;
-}
-
 String HistoryItem::formContentType() const
 {
     return m_formContentType;
@@ -350,37 +263,5 @@
     return equalIgnoringFragmentIdentifier(url(), doc->url());
 }
 
-#ifndef NDEBUG
-
-int HistoryItem::showTree() const
-{
-    return showTreeWithIndent(0);
-}
-
-int HistoryItem::showTreeWithIndent(unsigned indentLevel) const
-{
-    Vector<char> prefix;
-    for (unsigned i = 0; i < indentLevel; ++i)
-        prefix.append("  ", 2);
-    prefix.append("\0", 1);
-
-    fprintf(stderr, "%s+-%s (%p)\n", prefix.data(), m_urlString.utf8().data(), this);
-
-    int totalSubItems = 0;
-    for (unsigned i = 0; i < m_children.size(); ++i)
-        totalSubItems += m_children[i]->showTreeWithIndent(indentLevel + 1);
-    return totalSubItems + 1;
-}
-
-#endif
-
 } // namespace WebCore
 
-#ifndef NDEBUG
-
-int showTree(const WebCore::HistoryItem* item)
-{
-    return item->showTree();
-}
-
-#endif
diff --git a/Source/core/history/HistoryItem.h b/Source/core/history/HistoryItem.h
index 4bd3524..68e34f9 100644
--- a/Source/core/history/HistoryItem.h
+++ b/Source/core/history/HistoryItem.h
@@ -99,28 +99,15 @@
     void setFormContentType(const String&);
 
     void addChildItem(PassRefPtr<HistoryItem>);
-    void setChildItem(PassRefPtr<HistoryItem>);
-    HistoryItem* childItemWithTarget(const String&) const;
-    HistoryItem* childItemWithDocumentSequenceNumber(long long number) const;
     const HistoryItemVector& children() const;
     void clearChildren();
 
-    bool shouldDoSameDocumentNavigationTo(HistoryItem* otherItem) const;
-    bool hasSameFrames(HistoryItem* otherItem) const;
-
     bool isCurrentDocument(Document*) const;
 
-#ifndef NDEBUG
-    int showTree() const;
-    int showTreeWithIndent(unsigned indentLevel) const;
-#endif
-
 private:
     HistoryItem();
     explicit HistoryItem(const HistoryItem&);
 
-    bool hasSameDocumentTree(HistoryItem* otherItem) const;
-
     String m_urlString;
     String m_originalURLString;
     String m_referrer;
@@ -156,9 +143,4 @@
 
 } //namespace WebCore
 
-#ifndef NDEBUG
-// Outside the WebCore namespace for ease of invocation from gdb.
-extern "C" int showTree(const WebCore::HistoryItem*);
-#endif
-
 #endif // HISTORYITEM_H
diff --git a/Source/core/html/FormAssociatedElement.cpp b/Source/core/html/FormAssociatedElement.cpp
index b1de0fc..5b45b8b 100644
--- a/Source/core/html/FormAssociatedElement.cpp
+++ b/Source/core/html/FormAssociatedElement.cpp
@@ -135,7 +135,7 @@
         m_form->removeFormElement(this);
     m_form = newForm;
     if (m_form)
-        m_form->registerFormElement(this);
+        m_form->registerFormElement(*this);
     didChangeForm();
 }
 
@@ -274,19 +274,30 @@
     return false;
 }
 
-const HTMLElement* toHTMLElement(const FormAssociatedElement* associatedElement)
+const HTMLElement& toHTMLElement(const FormAssociatedElement& associatedElement)
 {
-    if (associatedElement->isFormControlElement())
+    if (associatedElement.isFormControlElement())
         return toHTMLFormControlElement(associatedElement);
     // Assumes the element is an HTMLObjectElement
     return toHTMLObjectElement(associatedElement);
 }
 
+const HTMLElement* toHTMLElement(const FormAssociatedElement* associatedElement)
+{
+    ASSERT(associatedElement);
+    return &toHTMLElement(*associatedElement);
+}
+
 HTMLElement* toHTMLElement(FormAssociatedElement* associatedElement)
 {
     return const_cast<HTMLElement*>(toHTMLElement(static_cast<const FormAssociatedElement*>(associatedElement)));
 }
 
+HTMLElement& toHTMLElement(FormAssociatedElement& associatedElement)
+{
+    return const_cast<HTMLElement&>(toHTMLElement(static_cast<const FormAssociatedElement&>(associatedElement)));
+}
+
 PassOwnPtr<FormAttributeTargetObserver> FormAttributeTargetObserver::create(const AtomicString& id, FormAssociatedElement* element)
 {
     return adoptPtr(new FormAttributeTargetObserver(id, element));
diff --git a/Source/core/html/FormAssociatedElement.h b/Source/core/html/FormAssociatedElement.h
index e7d994b..15f2fa1 100644
--- a/Source/core/html/FormAssociatedElement.h
+++ b/Source/core/html/FormAssociatedElement.h
@@ -119,7 +119,9 @@
 };
 
 HTMLElement* toHTMLElement(FormAssociatedElement*);
+HTMLElement& toHTMLElement(FormAssociatedElement&);
 const HTMLElement* toHTMLElement(const FormAssociatedElement*);
+const HTMLElement& toHTMLElement(const FormAssociatedElement&);
 
 } // namespace
 
diff --git a/Source/core/html/FormData.idl b/Source/core/html/FormData.idl
index 0391d3a..73dcbfb 100644
--- a/Source/core/html/FormData.idl
+++ b/Source/core/html/FormData.idl
@@ -29,7 +29,7 @@
  */
 
 [
-    CustomConstructor(optional HTMLFormElement form),
+    Constructor([Default=Undefined] optional HTMLFormElement form),
     ImplementedAs=DOMFormData
 ] interface FormData {
     // void append(DOMString name, DOMString value);
diff --git a/Source/core/html/FormDataList.cpp b/Source/core/html/FormDataList.cpp
index f490596..b564d2c 100644
--- a/Source/core/html/FormDataList.cpp
+++ b/Source/core/html/FormDataList.cpp
@@ -115,7 +115,7 @@
             // Append body
             formData->appendData(header.data(), header.size());
             if (value.blob()) {
-                if (value.blob()->isFile()) {
+                if (value.blob()->hasBackingFile()) {
                     File* file = toFile(value.blob());
                     // Do not add the file if the path is empty.
                     if (!file->path().isEmpty())
diff --git a/Source/core/html/HTMLAllCollection.idl b/Source/core/html/HTMLAllCollection.idl
index 9f87dd4..8206871 100644
--- a/Source/core/html/HTMLAllCollection.idl
+++ b/Source/core/html/HTMLAllCollection.idl
@@ -25,9 +25,9 @@
 
 [
     CustomLegacyCall,
+    DependentLifetime,
+    GenerateVisitDOMWrapper=ownerNode,
     MasqueradesAsUndefined,
-    GenerateIsReachable=ownerNode,
-    DependentLifetime
 ] interface HTMLAllCollection {
     readonly attribute unsigned long length;
     [ImplementedAs=item] getter Node (unsigned long index);
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index 5c6b6c7..143b3c5 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -48,21 +48,21 @@
 #include "platform/PlatformMouseEvent.h"
 #include "platform/network/DNS.h"
 #include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/KnownPorts.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebPrescientNetworking.h"
 #include "public/platform/WebURL.h"
-#include "weborigin/KnownPorts.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
 namespace {
 
-void preconnectToURL(const KURL& url, WebKit::WebPreconnectMotivation motivation)
+void preconnectToURL(const KURL& url, blink::WebPreconnectMotivation motivation)
 {
-    WebKit::WebPrescientNetworking* prescientNetworking = WebKit::Platform::current()->prescientNetworking();
+    blink::WebPrescientNetworking* prescientNetworking = blink::Platform::current()->prescientNetworking();
     if (!prescientNetworking)
         return;
 
@@ -95,7 +95,7 @@
     void handleClick(Event* event);
 
     bool shouldPrefetch(const KURL&);
-    void prefetch(WebKit::WebPreconnectMotivation);
+    void prefetch(blink::WebPreconnectMotivation);
 
     HTMLAnchorElement* m_anchorElement;
     double m_mouseOverTimestamp;
@@ -230,7 +230,7 @@
     HTMLElement::defaultEventHandler(event);
 }
 
-void HTMLAnchorElement::setActive(bool down, bool pause)
+void HTMLAnchorElement::setActive(bool down)
 {
     if (rendererIsEditable()) {
         EditableLinkBehavior editableLinkBehavior = EditableLinkDefaultBehavior;
@@ -259,7 +259,7 @@
 
     }
 
-    ContainerNode::setActive(down, pause);
+    ContainerNode::setActive(down);
 }
 
 void HTMLAnchorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -577,9 +577,9 @@
     if (m_mouseOverTimestamp == 0.0) {
         m_mouseOverTimestamp = event->timeStamp();
 
-        WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseOvers", 0, 2);
+        blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseOvers", 0, 2);
 
-        prefetch(WebKit::WebPreconnectMotivationLinkMouseOver);
+        prefetch(blink::WebPreconnectMotivationLinkMouseOver);
     }
 }
 
@@ -587,7 +587,7 @@
 {
     if (m_mouseOverTimestamp > 0.0) {
         double mouseOverDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseOverTimestamp);
-        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_NoClick", mouseOverDuration * 1000, 0, 10000, 100);
+        blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_NoClick", mouseOverDuration * 1000, 0, 10000, 100);
 
         m_mouseOverTimestamp = 0.0;
     }
@@ -597,27 +597,27 @@
 {
     m_mouseDownTimestamp = event->timeStamp();
 
-    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDowns", 0, 2);
+    blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDowns", 0, 2);
 
-    prefetch(WebKit::WebPreconnectMotivationLinkMouseDown);
+    prefetch(blink::WebPreconnectMotivationLinkMouseDown);
 }
 
 void HTMLAnchorElement::PrefetchEventHandler::handleGestureTapUnconfirmed(Event* event)
 {
     m_hadTapUnconfirmed = true;
 
-    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapUnconfirmeds", 0, 2);
+    blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapUnconfirmeds", 0, 2);
 
-    prefetch(WebKit::WebPreconnectMotivationLinkTapUnconfirmed);
+    prefetch(blink::WebPreconnectMotivationLinkTapUnconfirmed);
 }
 
 void HTMLAnchorElement::PrefetchEventHandler::handleGestureShowPress(Event* event)
 {
     m_tapDownTimestamp = event->timeStamp();
 
-    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapDowns", 0, 2);
+    blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapDowns", 0, 2);
 
-    prefetch(WebKit::WebPreconnectMotivationLinkTapDown);
+    prefetch(blink::WebPreconnectMotivationLinkTapDown);
 }
 
 void HTMLAnchorElement::PrefetchEventHandler::handleClick(Event* event)
@@ -626,27 +626,27 @@
     if (capturedMouseOver) {
         double mouseOverDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseOverTimestamp);
 
-        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_Click", mouseOverDuration * 1000, 0, 10000, 100);
+        blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_Click", mouseOverDuration * 1000, 0, 10000, 100);
     }
 
     bool capturedMouseDown = (m_mouseDownTimestamp > 0.0);
-    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDownFollowedByClick", capturedMouseDown, 2);
+    blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDownFollowedByClick", capturedMouseDown, 2);
 
     if (capturedMouseDown) {
         double mouseDownDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseDownTimestamp);
 
-        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseDownDuration_Click", mouseDownDuration * 1000, 0, 10000, 100);
+        blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseDownDuration_Click", mouseDownDuration * 1000, 0, 10000, 100);
     }
 
     bool capturedTapDown = (m_tapDownTimestamp > 0.0);
     if (capturedTapDown) {
         double tapDownDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_tapDownTimestamp);
 
-        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.TapDownDuration_Click", tapDownDuration * 1000, 0, 10000, 100);
+        blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.TapDownDuration_Click", tapDownDuration * 1000, 0, 10000, 100);
     }
 
     int flags = (m_hadTapUnconfirmed ? 2 : 0) | (capturedTapDown ? 1 : 0);
-    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.PreTapEventsFollowedByClick", flags, 4);
+    blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.PreTapEventsFollowedByClick", flags, 4);
 }
 
 bool HTMLAnchorElement::PrefetchEventHandler::shouldPrefetch(const KURL& url)
@@ -679,7 +679,7 @@
     return true;
 }
 
-void HTMLAnchorElement::PrefetchEventHandler::prefetch(WebKit::WebPreconnectMotivation motivation)
+void HTMLAnchorElement::PrefetchEventHandler::prefetch(blink::WebPreconnectMotivation motivation)
 {
     const KURL& url = m_anchorElement->href();
 
@@ -687,7 +687,7 @@
         return;
 
     // The precision of current MouseOver trigger is too low to actually trigger preconnects.
-    if (motivation == WebKit::WebPreconnectMotivationLinkMouseOver)
+    if (motivation == blink::WebPreconnectMotivationLinkMouseOver)
         return;
 
     preconnectToURL(url, motivation);
diff --git a/Source/core/html/HTMLAnchorElement.h b/Source/core/html/HTMLAnchorElement.h
index b79fc69..bfb0d63 100644
--- a/Source/core/html/HTMLAnchorElement.h
+++ b/Source/core/html/HTMLAnchorElement.h
@@ -94,7 +94,7 @@
     virtual bool isMouseFocusable() const;
     virtual bool isKeyboardFocusable() const OVERRIDE;
     virtual void defaultEventHandler(Event*);
-    virtual void setActive(bool active = true, bool pause = false);
+    virtual void setActive(bool = true) OVERRIDE FINAL;
     virtual void accessKeyAction(bool sendMouseEvents);
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
     virtual bool canStartSelection() const;
diff --git a/Source/core/html/HTMLAnchorElement.idl b/Source/core/html/HTMLAnchorElement.idl
index 88cf2d4..116f7dc 100644
--- a/Source/core/html/HTMLAnchorElement.idl
+++ b/Source/core/html/HTMLAnchorElement.idl
@@ -19,17 +19,17 @@
  */
 
 interface HTMLAnchorElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString charset;
-    [Reflect, TreatNullAs=NullString] attribute DOMString coords;
-    [Reflect, TreatNullAs=NullString] attribute DOMString download;
-    [Reflect, TreatNullAs=NullString] attribute DOMString hreflang;
-    [Reflect, TreatNullAs=NullString] attribute DOMString name;
-    [Reflect, TreatNullAs=NullString] attribute DOMString ping;
-    [Reflect, TreatNullAs=NullString] attribute DOMString rel;
-    [Reflect, TreatNullAs=NullString] attribute DOMString rev;
-    [Reflect, TreatNullAs=NullString] attribute DOMString shape;
-    [Reflect, TreatNullAs=NullString] attribute DOMString target;
-    [Reflect, TreatNullAs=NullString] attribute DOMString type;
+    [Reflect] attribute DOMString charset;
+    [Reflect] attribute DOMString coords;
+    [Reflect] attribute DOMString download;
+    [Reflect] attribute DOMString hreflang;
+    [Reflect] attribute DOMString name;
+    [Reflect] attribute DOMString ping;
+    [Reflect] attribute DOMString rel;
+    [Reflect] attribute DOMString rev;
+    [Reflect] attribute DOMString shape;
+    [Reflect] attribute DOMString target;
+    [Reflect] attribute DOMString type;
 
     readonly attribute DOMString text;
 };
diff --git a/Source/core/html/HTMLAppletElement.cpp b/Source/core/html/HTMLAppletElement.cpp
index cf79feb..8173f2b 100644
--- a/Source/core/html/HTMLAppletElement.cpp
+++ b/Source/core/html/HTMLAppletElement.cpp
@@ -33,24 +33,23 @@
 #include "core/page/Settings.h"
 #include "core/rendering/RenderApplet.h"
 #include "platform/Widget.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLPlugInElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
+HTMLAppletElement::HTMLAppletElement(Document& document, bool createdByParser)
+    : HTMLPlugInElement(appletTag, document, createdByParser, ShouldNotPreferPlugInsForImages)
 {
-    ASSERT(hasTagName(appletTag));
     ScriptWrappable::init(this);
 
     m_serviceType = "application/x-java-applet";
 }
 
-PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(Document& document, bool createdByParser)
 {
-    return adoptRef(new HTMLAppletElement(tagName, document, createdByParser));
+    return adoptRef(new HTMLAppletElement(document, createdByParser));
 }
 
 void HTMLAppletElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -68,6 +67,12 @@
     HTMLPlugInElement::parseAttribute(name, value);
 }
 
+bool HTMLAppletElement::isURLAttribute(const Attribute& attribute) const
+{
+    return attribute.name() == codebaseAttr || attribute.name() == objectAttr
+        || HTMLPlugInElement::isURLAttribute(attribute);
+}
+
 bool HTMLAppletElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (!fastHasAttribute(codeAttr))
diff --git a/Source/core/html/HTMLAppletElement.h b/Source/core/html/HTMLAppletElement.h
index c709b8f..4e1e266 100644
--- a/Source/core/html/HTMLAppletElement.h
+++ b/Source/core/html/HTMLAppletElement.h
@@ -29,15 +29,16 @@
 
 class HTMLAppletElement FINAL : public HTMLPlugInElement {
 public:
-    static PassRefPtr<HTMLAppletElement> create(const QualifiedName&, Document&, bool createdByParser);
+    static PassRefPtr<HTMLAppletElement> create(Document&, bool createdByParser);
 
 protected:
     virtual RenderWidget* renderWidgetForJSBindings() const OVERRIDE;
 
 private:
-    HTMLAppletElement(const QualifiedName&, Document&, bool createdByParser);
+    HTMLAppletElement(Document&, bool createdByParser);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
+    virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
diff --git a/Source/core/html/HTMLAppletElement.idl b/Source/core/html/HTMLAppletElement.idl
index 655cd07..a509178 100644
--- a/Source/core/html/HTMLAppletElement.idl
+++ b/Source/core/html/HTMLAppletElement.idl
@@ -21,20 +21,19 @@
 [
     CustomLegacyCall
 ] interface HTMLAppletElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString align;
-    [Reflect, TreatNullAs=NullString] attribute DOMString alt;
-    [Reflect, TreatNullAs=NullString] attribute DOMString archive;
-    [Reflect, TreatNullAs=NullString] attribute DOMString code;
-    [Reflect, TreatNullAs=NullString] attribute DOMString codeBase;
-    [Reflect, TreatNullAs=NullString] attribute DOMString height;
-    [Reflect, TreatNullAs=NullString] attribute DOMString hspace;
-    [Reflect, TreatNullAs=NullString] attribute DOMString name;
-    [Reflect, TreatNullAs=NullString] attribute DOMString _object;  // "object" is a reserved word
-    [Reflect, TreatNullAs=NullString] attribute DOMString vspace;
-    [Reflect, TreatNullAs=NullString] attribute DOMString width;
+    [Reflect] attribute DOMString align;
+    [Reflect] attribute DOMString alt;
+    [Reflect] attribute DOMString archive;
+    [Reflect] attribute DOMString code;
+    [Reflect, URL] attribute DOMString codeBase;
+    [Reflect] attribute DOMString height;
+    [Reflect] attribute unsigned long hspace;
+    [Reflect] attribute DOMString name;
+    [Reflect, URL] attribute DOMString _object;  // "object" is a reserved word
+    [Reflect] attribute unsigned long vspace;
+    [Reflect] attribute DOMString width;
     [Custom, NotEnumerable] getter boolean (unsigned long index);
     [Custom] setter boolean (unsigned long index, Node value);
     [Custom, NotEnumerable] getter Node (DOMString name);
     [Custom] setter Node (DOMString name, Node value);
 };
-
diff --git a/Source/core/html/HTMLAreaElement.cpp b/Source/core/html/HTMLAreaElement.cpp
index 437c28f..45ca132 100644
--- a/Source/core/html/HTMLAreaElement.cpp
+++ b/Source/core/html/HTMLAreaElement.cpp
@@ -37,18 +37,17 @@
 
 using namespace HTMLNames;
 
-inline HTMLAreaElement::HTMLAreaElement(const QualifiedName& tagName, Document& document)
-    : HTMLAnchorElement(tagName, document)
+inline HTMLAreaElement::HTMLAreaElement(Document& document)
+    : HTMLAnchorElement(areaTag, document)
     , m_lastSize(-1, -1)
     , m_shape(Unknown)
 {
-    ASSERT(hasTagName(areaTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLAreaElement> HTMLAreaElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLAreaElement> HTMLAreaElement::create(Document& document)
 {
-    return adoptRef(new HTMLAreaElement(tagName, document));
+    return adoptRef(new HTMLAreaElement(document));
 }
 
 void HTMLAreaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/html/HTMLAreaElement.h b/Source/core/html/HTMLAreaElement.h
index 67c7a58..35f3438 100644
--- a/Source/core/html/HTMLAreaElement.h
+++ b/Source/core/html/HTMLAreaElement.h
@@ -34,7 +34,7 @@
 
 class HTMLAreaElement FINAL : public HTMLAnchorElement {
 public:
-    static PassRefPtr<HTMLAreaElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLAreaElement> create(Document&);
 
     bool isDefault() const { return m_shape == Default; }
 
@@ -47,7 +47,7 @@
     HTMLImageElement* imageElement() const;
 
 private:
-    HTMLAreaElement(const QualifiedName&, Document&);
+    explicit HTMLAreaElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool supportsFocus() const;
diff --git a/Source/core/html/HTMLAreaElement.idl b/Source/core/html/HTMLAreaElement.idl
index 1175ec1..ff59b8c 100644
--- a/Source/core/html/HTMLAreaElement.idl
+++ b/Source/core/html/HTMLAreaElement.idl
@@ -19,12 +19,12 @@
  */
 
 interface HTMLAreaElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString alt;
-    [Reflect, TreatNullAs=NullString] attribute DOMString coords;
+    [Reflect] attribute DOMString alt;
+    [Reflect] attribute DOMString coords;
     [Reflect] attribute boolean noHref;
-    [Reflect, TreatNullAs=NullString] attribute DOMString ping;
-    [Reflect, TreatNullAs=NullString] attribute DOMString shape;
-    [Reflect, TreatNullAs=NullString] attribute DOMString target;
+    [Reflect] attribute DOMString ping;
+    [Reflect] attribute DOMString shape;
+    [Reflect] attribute DOMString target;
 };
 
 // Force rebuild: crbug.com/307023
diff --git a/Source/core/html/HTMLAttributeNames.in b/Source/core/html/HTMLAttributeNames.in
index b80a4ad..4ae7745 100644
--- a/Source/core/html/HTMLAttributeNames.in
+++ b/Source/core/html/HTMLAttributeNames.in
@@ -276,7 +276,6 @@
 onwheel
 open
 optimum
-part
 pattern
 placeholder
 pluginspage
diff --git a/Source/core/html/HTMLAudioElement.cpp b/Source/core/html/HTMLAudioElement.cpp
index e30c85a..a11d77b 100644
--- a/Source/core/html/HTMLAudioElement.cpp
+++ b/Source/core/html/HTMLAudioElement.cpp
@@ -32,23 +32,22 @@
 
 using namespace HTMLNames;
 
-HTMLAudioElement::HTMLAudioElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLMediaElement(tagName, document, createdByParser)
+HTMLAudioElement::HTMLAudioElement(Document& document, bool createdByParser)
+    : HTMLMediaElement(audioTag, document, createdByParser)
 {
-    ASSERT(hasTagName(audioTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(Document& document, bool createdByParser)
 {
-    RefPtr<HTMLAudioElement> audioElement(adoptRef(new HTMLAudioElement(tagName, document, createdByParser)));
+    RefPtr<HTMLAudioElement> audioElement(adoptRef(new HTMLAudioElement(document, createdByParser)));
     audioElement->suspendIfNeeded();
     return audioElement.release();
 }
 
 PassRefPtr<HTMLAudioElement> HTMLAudioElement::createForJSConstructor(Document& document, const String& src)
 {
-    RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(audioTag, document, false));
+    RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(document, false));
     audio->setPreload("auto");
     if (!src.isNull())
         audio->setSrc(src);
diff --git a/Source/core/html/HTMLAudioElement.h b/Source/core/html/HTMLAudioElement.h
index fc3996b..ff3e6a5 100644
--- a/Source/core/html/HTMLAudioElement.h
+++ b/Source/core/html/HTMLAudioElement.h
@@ -35,11 +35,11 @@
 
 class HTMLAudioElement FINAL : public HTMLMediaElement {
 public:
-    static PassRefPtr<HTMLAudioElement> create(const QualifiedName&, Document&, bool);
+    static PassRefPtr<HTMLAudioElement> create(Document&, bool);
     static PassRefPtr<HTMLAudioElement> createForJSConstructor(Document&, const String& src);
 
 private:
-    HTMLAudioElement(const QualifiedName&, Document&, bool);
+    HTMLAudioElement(Document&, bool);
 
     virtual bool isVideo() const OVERRIDE { return false; }
 };
diff --git a/Source/core/html/HTMLBDIElement.h b/Source/core/html/HTMLBDIElement.h
index d72e4a0..b5050a6 100644
--- a/Source/core/html/HTMLBDIElement.h
+++ b/Source/core/html/HTMLBDIElement.h
@@ -27,14 +27,14 @@
 
 class HTMLBDIElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLBDIElement> create(const QualifiedName& name, Document& document)
+    static PassRefPtr<HTMLBDIElement> create(Document& document)
     {
-        return adoptRef(new HTMLBDIElement(name, document));
+        return adoptRef(new HTMLBDIElement(document));
     }
 
 private:
-    HTMLBDIElement(const QualifiedName& name, Document& document)
-        : HTMLElement(name, document)
+    explicit HTMLBDIElement(Document& document)
+        : HTMLElement(HTMLNames::bdiTag, document)
     {
         // FIXME: Rename setSelfOrAncestorHasDirAutoAttribute to reflect the fact bdi also uses this flag.
         setSelfOrAncestorHasDirAutoAttribute(true);
diff --git a/Source/core/html/HTMLBRElement.cpp b/Source/core/html/HTMLBRElement.cpp
index d92ac0c..19b3aa9 100644
--- a/Source/core/html/HTMLBRElement.cpp
+++ b/Source/core/html/HTMLBRElement.cpp
@@ -32,21 +32,15 @@
 
 using namespace HTMLNames;
 
-HTMLBRElement::HTMLBRElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLBRElement::HTMLBRElement(Document& document)
+    : HTMLElement(brTag, document)
 {
-    ASSERT(hasTagName(brTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLBRElement> HTMLBRElement::create(Document& document)
 {
-    return adoptRef(new HTMLBRElement(brTag, document));
-}
-
-PassRefPtr<HTMLBRElement> HTMLBRElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLBRElement(tagName, document));
+    return adoptRef(new HTMLBRElement(document));
 }
 
 bool HTMLBRElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLBRElement.h b/Source/core/html/HTMLBRElement.h
index fc6d5c4..0188c71 100644
--- a/Source/core/html/HTMLBRElement.h
+++ b/Source/core/html/HTMLBRElement.h
@@ -31,12 +31,11 @@
 class HTMLBRElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLBRElement> create(Document&);
-    static PassRefPtr<HTMLBRElement> create(const QualifiedName&, Document&);
 
     virtual bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLBRElement(const QualifiedName&, Document&);
+    explicit HTMLBRElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLBRElement.idl b/Source/core/html/HTMLBRElement.idl
index 7c31dfb..c909dc1 100644
--- a/Source/core/html/HTMLBRElement.idl
+++ b/Source/core/html/HTMLBRElement.idl
@@ -18,6 +18,6 @@
  */
 
 interface HTMLBRElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString clear;
+    [Reflect] attribute DOMString clear;
 };
 
diff --git a/Source/core/html/HTMLBaseElement.cpp b/Source/core/html/HTMLBaseElement.cpp
index 34e5de2..6ec6654 100644
--- a/Source/core/html/HTMLBaseElement.cpp
+++ b/Source/core/html/HTMLBaseElement.cpp
@@ -33,16 +33,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLBaseElement::HTMLBaseElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLBaseElement::HTMLBaseElement(Document& document)
+    : HTMLElement(baseTag, document)
 {
-    ASSERT(hasTagName(baseTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLBaseElement> HTMLBaseElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLBaseElement> HTMLBaseElement::create(Document& document)
 {
-    return adoptRef(new HTMLBaseElement(tagName, document));
+    return adoptRef(new HTMLBaseElement(document));
 }
 
 void HTMLBaseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/html/HTMLBaseElement.h b/Source/core/html/HTMLBaseElement.h
index 7a52c37..39c8bfe 100644
--- a/Source/core/html/HTMLBaseElement.h
+++ b/Source/core/html/HTMLBaseElement.h
@@ -29,13 +29,13 @@
 
 class HTMLBaseElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLBaseElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLBaseElement> create(Document&);
 
     KURL href() const;
     void setHref(const AtomicString&);
 
 private:
-    HTMLBaseElement(const QualifiedName&, Document&);
+    explicit HTMLBaseElement(Document&);
 
     virtual String target() const;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
diff --git a/Source/core/html/HTMLBaseElement.idl b/Source/core/html/HTMLBaseElement.idl
index 408e129..87e614f 100644
--- a/Source/core/html/HTMLBaseElement.idl
+++ b/Source/core/html/HTMLBaseElement.idl
@@ -18,6 +18,6 @@
  */
 
 interface HTMLBaseElement : HTMLElement {
-    [TreatNullAs=NullString] attribute DOMString href;
-    [Reflect, TreatNullAs=NullString] attribute DOMString target;
+    attribute DOMString href;
+    [Reflect] attribute DOMString target;
 };
diff --git a/Source/core/html/HTMLBaseFontElement.cpp b/Source/core/html/HTMLBaseFontElement.cpp
deleted file mode 100644
index a12f10f..0000000
--- a/Source/core/html/HTMLBaseFontElement.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2009, 2010 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.
- *
- */
-
-#include "config.h"
-#include "core/html/HTMLBaseFontElement.h"
-
-#include "HTMLNames.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-inline HTMLBaseFontElement::HTMLBaseFontElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
-{
-    ASSERT(hasTagName(basefontTag));
-    ScriptWrappable::init(this);
-}
-
-PassRefPtr<HTMLBaseFontElement> HTMLBaseFontElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLBaseFontElement(tagName, document));
-}
-
-}
diff --git a/Source/core/html/HTMLBaseFontElement.h b/Source/core/html/HTMLBaseFontElement.h
deleted file mode 100644
index e66cc11..0000000
--- a/Source/core/html/HTMLBaseFontElement.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2009, 2010 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.
- *
- */
-
-#ifndef HTMLBaseFontElement_h
-#define HTMLBaseFontElement_h
-
-#include "core/html/HTMLElement.h"
-
-namespace WebCore {
-
-class HTMLBaseFontElement FINAL : public HTMLElement {
-public:
-    static PassRefPtr<HTMLBaseFontElement> create(const QualifiedName&, Document&);
-
-private:
-    HTMLBaseFontElement(const QualifiedName&, Document&);
-};
-
-} // namespace
-
-#endif
diff --git a/Source/core/html/HTMLBaseFontElement.idl b/Source/core/html/HTMLBaseFontElement.idl
deleted file mode 100644
index a4910e8..0000000
--- a/Source/core/html/HTMLBaseFontElement.idl
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2006, 2009, 2010 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.
- */
-
-interface HTMLBaseFontElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString color;
-    [Reflect, TreatNullAs=NullString] attribute DOMString face;
-    [Reflect] attribute long size;
-};
diff --git a/Source/core/html/HTMLBodyElement.cpp b/Source/core/html/HTMLBodyElement.cpp
index ad0cbb2..44a1572 100644
--- a/Source/core/html/HTMLBodyElement.cpp
+++ b/Source/core/html/HTMLBodyElement.cpp
@@ -41,21 +41,15 @@
 
 using namespace HTMLNames;
 
-HTMLBodyElement::HTMLBodyElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLBodyElement::HTMLBodyElement(Document& document)
+    : HTMLElement(bodyTag, document)
 {
-    ASSERT(hasTagName(bodyTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(Document& document)
 {
-    return adoptRef(new HTMLBodyElement(bodyTag, document));
-}
-
-PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLBodyElement(tagName, document));
+    return adoptRef(new HTMLBodyElement(document));
 }
 
 HTMLBodyElement::~HTMLBodyElement()
@@ -172,10 +166,10 @@
             HTMLFrameElementBase* ownerFrameElement = toHTMLFrameElementBase(ownerElement);
             int marginWidth = ownerFrameElement->marginWidth();
             if (marginWidth != -1)
-                setAttribute(marginwidthAttr, String::number(marginWidth));
+                setIntegralAttribute(marginwidthAttr, marginWidth);
             int marginHeight = ownerFrameElement->marginHeight();
             if (marginHeight != -1)
-                setAttribute(marginheightAttr, String::number(marginHeight));
+                setIntegralAttribute(marginheightAttr, marginHeight);
         }
     }
     return InsertionDone;
@@ -205,18 +199,21 @@
     return static_cast<int>(value / zoomFactor);
 }
 
+// FIXME: There are cases where body.scrollLeft is allowed to return
+// non-zero values in both quirks and strict mode. It happens when
+// <body> has an overflow that is not the Frame overflow.
+// http://dev.w3.org/csswg/cssom-view/#dom-element-scrollleft
+// http://code.google.com/p/chromium/issues/detail?id=312435
 int HTMLBodyElement::scrollLeft()
 {
     Document& document = this->document();
-
-    // FIXME: There are cases where body.scrollLeft is allowed to return
-    // non-zero values in both quirks and strict mode. It happens when
-    // <body> has an overflow that is not the Frame overflow.
-    // http://dev.w3.org/csswg/cssom-view/#dom-element-scrollleft
-    if (!document.inQuirksMode())
-        UseCounter::countDeprecation(&document, UseCounter::ScrollLeftBodyNotQuirksMode);
-
     document.updateLayoutIgnorePendingStylesheets();
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        if (!document.inQuirksMode())
+            return 0;
+    }
+
     FrameView* view = document.view();
     return view ? adjustForZoom(view->scrollX(), &document) : 0;
 }
@@ -224,11 +221,13 @@
 void HTMLBodyElement::setScrollLeft(int scrollLeft)
 {
     Document& document = this->document();
-
-    if (!document.inQuirksMode())
-        UseCounter::countDeprecation(&document, UseCounter::ScrollLeftBodyNotQuirksMode);
-
     document.updateLayoutIgnorePendingStylesheets();
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        if (!document.inQuirksMode())
+            return;
+    }
+
     Frame* frame = document.frame();
     if (!frame)
         return;
@@ -241,15 +240,13 @@
 int HTMLBodyElement::scrollTop()
 {
     Document& document = this->document();
-
-    // FIXME: There are cases where body.scrollTop is allowed to return
-    // non-zero values in both quirks and strict mode. It happens when
-    // body has a overflow that is not the Frame overflow.
-    // http://dev.w3.org/csswg/cssom-view/#dom-element-scrolltop
-    if (!document.inQuirksMode())
-        UseCounter::countDeprecation(&document, UseCounter::ScrollTopBodyNotQuirksMode);
-
     document.updateLayoutIgnorePendingStylesheets();
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        if (!document.inQuirksMode())
+            return 0;
+    }
+
     FrameView* view = document.view();
     return view ? adjustForZoom(view->scrollY(), &document) : 0;
 }
@@ -257,11 +254,13 @@
 void HTMLBodyElement::setScrollTop(int scrollTop)
 {
     Document& document = this->document();
-
-    if (!document.inQuirksMode())
-        UseCounter::countDeprecation(&document, UseCounter::ScrollTopBodyNotQuirksMode);
-
     document.updateLayoutIgnorePendingStylesheets();
+
+    if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        if (!document.inQuirksMode())
+            return;
+    }
+
     Frame* frame = document.frame();
     if (!frame)
         return;
diff --git a/Source/core/html/HTMLBodyElement.h b/Source/core/html/HTMLBodyElement.h
index 14da8fb..d7a5c45 100644
--- a/Source/core/html/HTMLBodyElement.h
+++ b/Source/core/html/HTMLBodyElement.h
@@ -33,7 +33,6 @@
 class HTMLBodyElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLBodyElement> create(Document&);
-    static PassRefPtr<HTMLBodyElement> create(const QualifiedName&, Document&);
     virtual ~HTMLBodyElement();
 
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur);
@@ -47,7 +46,7 @@
 #endif
 
 private:
-    HTMLBodyElement(const QualifiedName&, Document&);
+    explicit HTMLBodyElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLBodyElement.idl b/Source/core/html/HTMLBodyElement.idl
index 3ce7850..139b34a 100644
--- a/Source/core/html/HTMLBodyElement.idl
+++ b/Source/core/html/HTMLBodyElement.idl
@@ -20,7 +20,7 @@
 
 interface HTMLBodyElement : HTMLElement {
     [Reflect, TreatNullAs=NullString] attribute DOMString aLink;
-    [Reflect, TreatNullAs=NullString] attribute DOMString background;
+    [Reflect] attribute DOMString background;
     [Reflect, TreatNullAs=NullString] attribute DOMString bgColor;
     [Reflect, TreatNullAs=NullString] attribute DOMString link;
     [Reflect, TreatNullAs=NullString] attribute DOMString text;
diff --git a/Source/core/html/HTMLButtonElement.cpp b/Source/core/html/HTMLButtonElement.cpp
index 9218ab0..d70626f 100644
--- a/Source/core/html/HTMLButtonElement.cpp
+++ b/Source/core/html/HTMLButtonElement.cpp
@@ -39,18 +39,17 @@
 
 using namespace HTMLNames;
 
-inline HTMLButtonElement::HTMLButtonElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
-    : HTMLFormControlElement(tagName, document, form)
+inline HTMLButtonElement::HTMLButtonElement(Document& document, HTMLFormElement* form)
+    : HTMLFormControlElement(buttonTag, document, form)
     , m_type(SUBMIT)
     , m_isActivatedSubmit(false)
 {
-    ASSERT(hasTagName(buttonTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLButtonElement> HTMLButtonElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLButtonElement> HTMLButtonElement::create(Document& document, HTMLFormElement* form)
 {
-    return adoptRef(new HTMLButtonElement(tagName, document, form));
+    return adoptRef(new HTMLButtonElement(document, form));
 }
 
 void HTMLButtonElement::setType(const AtomicString& type)
@@ -126,7 +125,7 @@
 
     if (event->isKeyboardEvent()) {
         if (event->type() == EventTypeNames::keydown && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
-            setActive(true, true);
+            setActive(true);
             // No setDefaultHandled() - IE dispatches a keypress in this case.
             return;
         }
@@ -160,11 +159,9 @@
     return HTMLFormControlElement::willRespondToMouseClickEvents();
 }
 
-bool HTMLButtonElement::isSuccessfulSubmitButton() const
+bool HTMLButtonElement::canBeSuccessfulSubmitButton() const
 {
-    // HTML spec says that buttons must have names to be considered successful.
-    // However, other browsers do not impose this constraint.
-    return m_type == SUBMIT && !isDisabledFormControl();
+    return m_type == SUBMIT;
 }
 
 bool HTMLButtonElement::isActivatedSubmit() const
diff --git a/Source/core/html/HTMLButtonElement.h b/Source/core/html/HTMLButtonElement.h
index 8d31893..b70cd7f 100644
--- a/Source/core/html/HTMLButtonElement.h
+++ b/Source/core/html/HTMLButtonElement.h
@@ -30,7 +30,7 @@
 
 class HTMLButtonElement FINAL : public HTMLFormControlElement {
 public:
-    static PassRefPtr<HTMLButtonElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+    static PassRefPtr<HTMLButtonElement> create(Document&, HTMLFormElement*);
 
     void setType(const AtomicString&);
 
@@ -39,7 +39,7 @@
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    HTMLButtonElement(const QualifiedName& tagName, Document&, HTMLFormElement*);
+    HTMLButtonElement(Document&, HTMLFormElement*);
 
     enum Type { SUBMIT, RESET, BUTTON };
 
@@ -60,7 +60,7 @@
     virtual bool supportLabels() const OVERRIDE { return true; }
     virtual bool isInteractiveContent() const OVERRIDE;
 
-    virtual bool isSuccessfulSubmitButton() const;
+    virtual bool canBeSuccessfulSubmitButton() const OVERRIDE;
     virtual bool isActivatedSubmit() const;
     virtual void setActivatedSubmit(bool flag);
 
diff --git a/Source/core/html/HTMLButtonElement.idl b/Source/core/html/HTMLButtonElement.idl
index 0fef161..db8c147 100644
--- a/Source/core/html/HTMLButtonElement.idl
+++ b/Source/core/html/HTMLButtonElement.idl
@@ -22,14 +22,14 @@
     [Reflect] attribute boolean autofocus;
     [Reflect] attribute boolean disabled;
     readonly attribute HTMLFormElement form;
-    [Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString formAction;
-    [TreatNullAs=NullString] attribute DOMString formEnctype;
-    [TreatNullAs=NullString] attribute DOMString formMethod;
+    [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString formAction;
+    attribute DOMString formEnctype;
+    attribute DOMString formMethod;
     [Reflect] attribute boolean formNoValidate;
-    [Reflect, TreatNullAs=NullString] attribute DOMString formTarget;
-    [Reflect, TreatNullAs=NullString] attribute DOMString name;
-    [TreatNullAs=NullString] attribute DOMString type;
-    [Reflect, TreatNullAs=NullString] attribute DOMString value;
+    [Reflect] attribute DOMString formTarget;
+    [Reflect] attribute DOMString name;
+    attribute DOMString type;
+    [Reflect] attribute DOMString value;
 
     readonly attribute boolean willValidate;
     readonly attribute ValidityState validity;
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index e94c050..54152ab 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -43,10 +43,10 @@
 #include "core/html/canvas/WebGLRenderingContext.h"
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/rendering/RenderHTMLCanvas.h"
+#include "platform/MIMETypeRegistry.h"
 #include "public/platform/Platform.h"
 
 namespace WebCore {
@@ -65,8 +65,8 @@
 //In Skia, we will also limit width/height to 32767.
 static const int MaxSkiaDim = 32767; // Maximum width/height in CSS pixels.
 
-HTMLCanvasElement::HTMLCanvasElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLCanvasElement::HTMLCanvasElement(Document& document)
+    : HTMLElement(canvasTag, document)
     , m_size(DefaultWidth, DefaultHeight)
     , m_rendererIsCanvas(false)
     , m_ignoreReset(false)
@@ -74,21 +74,15 @@
     , m_externallyAllocatedMemory(0)
     , m_deviceScaleFactor(1)
     , m_originClean(true)
-    , m_hasCreatedImageBuffer(false)
+    , m_didFailToCreateImageBuffer(false)
     , m_didClearImageBuffer(false)
 {
-    ASSERT(hasTagName(canvasTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(Document& document)
 {
-    return adoptRef(new HTMLCanvasElement(canvasTag, document));
-}
-
-PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLCanvasElement(tagName, document));
+    return adoptRef(new HTMLCanvasElement(document));
 }
 
 HTMLCanvasElement::~HTMLCanvasElement()
@@ -138,12 +132,12 @@
 
 void HTMLCanvasElement::setHeight(int value)
 {
-    setAttribute(heightAttr, String::number(value));
+    setIntegralAttribute(heightAttr, value);
 }
 
 void HTMLCanvasElement::setWidth(int value)
 {
-    setAttribute(widthAttr, String::number(value));
+    setIntegralAttribute(widthAttr, value);
 }
 
 CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, CanvasContextAttributes* attrs)
@@ -168,7 +162,7 @@
         if (m_context && !m_context->is2d())
             return 0;
         if (!m_context) {
-            WebKit::Platform::current()->histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
+            blink::Platform::current()->histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
             m_context = CanvasRenderingContext2D::create(this, static_cast<Canvas2DContextAttributes*>(attrs), document().inQuirksMode());
             if (m_context)
                 scheduleLayerUpdate();
@@ -195,7 +189,7 @@
             if (m_context && !m_context->is3d())
                 return 0;
             if (!m_context) {
-                WebKit::Platform::current()->histogramEnumeration("Canvas.ContextType", contextType, ContextTypeCount);
+                blink::Platform::current()->histogramEnumeration("Canvas.ContextType", contextType, ContextTypeCount);
                 m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
                 if (m_context)
                     scheduleLayerUpdate();
@@ -237,7 +231,7 @@
         return;
 
     bool ok;
-    bool hadImageBuffer = hasCreatedImageBuffer();
+    bool hadImageBuffer = hasImageBuffer();
 
     int w = getAttribute(widthAttr).toInt(&ok);
     if (!ok || w < 0)
@@ -264,7 +258,7 @@
 
     // If the size of an existing buffer matches, we can just clear it instead of reallocating.
     // This optimization is only done for 2D canvases for now.
-    if (m_hasCreatedImageBuffer && oldSize == newSize && m_deviceScaleFactor == newDeviceScaleFactor && m_context && m_context->is2d()) {
+    if (hadImageBuffer && oldSize == newSize && m_deviceScaleFactor == newDeviceScaleFactor && m_context && m_context->is2d()) {
         if (!m_didClearImageBuffer)
             clearImageBuffer();
         return;
@@ -322,7 +316,7 @@
         m_context->paintRenderingResultsToCanvas();
     }
 
-    if (hasCreatedImageBuffer()) {
+    if (hasImageBuffer()) {
         ImageBuffer* imageBuffer = buffer();
         if (imageBuffer) {
             CompositeOperator compositeOperator = !m_context || m_context->hasAlpha() ? CompositeSourceOver : CompositeCopy;
@@ -358,7 +352,7 @@
 void HTMLCanvasElement::setSurfaceSize(const IntSize& size)
 {
     m_size = size;
-    m_hasCreatedImageBuffer = false;
+    m_didFailToCreateImageBuffer = false;
     m_contextStateSaver.clear();
     m_imageBuffer.clear();
     setExternallyAllocatedMemory(0);
@@ -376,10 +370,10 @@
     return lowercaseMimeType;
 }
 
-String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionState& es)
+String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionState& exceptionState)
 {
     if (!m_originClean) {
-        es.throwSecurityError(ExceptionMessages::failedToExecute("toDataURL", "HTMLCanvasElement", "tainted canvases may not be exported."));
+        exceptionState.throwSecurityError(ExceptionMessages::failedToExecute("toDataURL", "HTMLCanvasElement", "tainted canvases may not be exported."));
         return String();
     }
 
@@ -392,7 +386,7 @@
     RefPtr<ImageData> imageData = getImageData();
 
     if (imageData)
-        return ImageDataToDataURL(*imageData, encodingMimeType, quality);
+        return ImageDataToDataURL(ImageDataBuffer(imageData->size(), imageData->data()), encodingMimeType, quality);
 
     if (m_context)
         m_context->paintRenderingResultsToCanvas();
@@ -412,9 +406,8 @@
 
 IntSize HTMLCanvasElement::convertLogicalToDevice(const IntSize& logicalSize) const
 {
-    float width = ceilf(logicalSize.width() * m_deviceScaleFactor);
-    float height = ceilf(logicalSize.height() * m_deviceScaleFactor);
-    return IntSize(width, height);
+    FloatSize deviceSize = logicalSize * m_deviceScaleFactor;
+    return expandedIntSize(deviceSize);
 }
 
 SecurityOrigin* HTMLCanvasElement::securityOrigin() const
@@ -443,7 +436,7 @@
     if (size.width() * size.height() < settings->minimumAccelerated2dCanvasSize())
         return false;
 
-    if (!WebKit::Platform::current()->canAccelerate2dCanvas())
+    if (!blink::Platform::current()->canAccelerate2dCanvas())
         return false;
 
     return true;
@@ -453,7 +446,7 @@
 {
     ASSERT(!m_imageBuffer);
 
-    m_hasCreatedImageBuffer = true;
+    m_didFailToCreateImageBuffer = true;
     m_didClearImageBuffer = true;
 
     IntSize deviceSize = convertLogicalToDevice(size());
@@ -466,18 +459,22 @@
     if (!deviceSize.width() || !deviceSize.height())
         return;
 
-    RenderingMode renderingMode = shouldAccelerate(deviceSize) ? Accelerated : UnacceleratedNonPlatformBuffer;
+    RenderingMode renderingMode = is3D() ? TextureBacked : (shouldAccelerate(deviceSize) ? Accelerated : UnacceleratedNonPlatformBuffer);
     int msaaSampleCount = 0;
-    if (renderingMode == Accelerated && document().settings()->antialiased2dCanvasEnabled())
+    if (document().settings())
         msaaSampleCount = document().settings()->accelerated2dCanvasMSAASampleCount();
     OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;
     m_imageBuffer = ImageBuffer::create(size(), m_deviceScaleFactor, renderingMode, opacityMode, msaaSampleCount);
     if (!m_imageBuffer)
         return;
+    m_didFailToCreateImageBuffer = false;
     setExternallyAllocatedMemory(4 * width() * height());
     m_imageBuffer->context()->setShouldClampToSourceRect(false);
     m_imageBuffer->context()->setImageInterpolationQuality(DefaultInterpolationQuality);
-    if (document().settings() && !document().settings()->antialiased2dCanvasEnabled())
+    // Enabling MSAA overrides a request to disable antialiasing. This is true regardless of whether the
+    // rendering mode is accelerated or not. For consistency, we don't want to apply AA in accelerated
+    // canvases but not in unaccelerated canvases.
+    if (!msaaSampleCount && document().settings() && !document().settings()->antialiased2dCanvasEnabled())
         m_imageBuffer->context()->setShouldAntialias(false);
     // GraphicsContext's defaults don't always agree with the 2d canvas spec.
     // See CanvasRenderingContext2D::State::State() for more information.
@@ -503,15 +500,17 @@
 
 GraphicsContext* HTMLCanvasElement::existingDrawingContext() const
 {
-    if (!m_hasCreatedImageBuffer)
+    if (m_didFailToCreateImageBuffer) {
+        ASSERT(!hasImageBuffer());
         return 0;
+    }
 
     return drawingContext();
 }
 
 ImageBuffer* HTMLCanvasElement::buffer() const
 {
-    if (!m_hasCreatedImageBuffer)
+    if (!hasImageBuffer() && !m_didFailToCreateImageBuffer)
         const_cast<HTMLCanvasElement*>(this)->createImageBuffer();
     return m_imageBuffer.get();
 }
@@ -528,7 +527,7 @@
 
 void HTMLCanvasElement::clearImageBuffer()
 {
-    ASSERT(m_hasCreatedImageBuffer);
+    ASSERT(hasImageBuffer() && !m_didFailToCreateImageBuffer);
     ASSERT(!m_didClearImageBuffer);
     ASSERT(m_context);
 
@@ -549,7 +548,7 @@
 
 AffineTransform HTMLCanvasElement::baseTransform() const
 {
-    ASSERT(m_hasCreatedImageBuffer);
+    ASSERT(hasImageBuffer() && !m_didFailToCreateImageBuffer);
     IntSize unscaledSize = size();
     IntSize size = convertLogicalToDevice(unscaledSize);
     AffineTransform transform;
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index 2691bcd..6887641 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -59,7 +59,6 @@
 class HTMLCanvasElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLCanvasElement> create(Document&);
-    static PassRefPtr<HTMLCanvasElement> create(const QualifiedName&, Document&);
     virtual ~HTMLCanvasElement();
 
     void addObserver(CanvasObserver*);
@@ -91,7 +90,7 @@
 
     static String toEncodingMimeType(const String& mimeType);
     String toDataURL(const String& mimeType, const double* quality, ExceptionState&);
-    String toDataURL(const String& mimeType, ExceptionState& es) { return toDataURL(mimeType, 0, es); }
+    String toDataURL(const String& mimeType, ExceptionState& exceptionState) { return toDataURL(mimeType, 0, exceptionState); }
 
     // Used for rendering
     void didDraw(const FloatRect&);
@@ -121,7 +120,7 @@
 
     bool is3D() const;
 
-    bool hasCreatedImageBuffer() const { return m_hasCreatedImageBuffer; }
+    bool hasImageBuffer() const { return m_imageBuffer.get(); }
 
     bool shouldAccelerate(const IntSize&) const;
 
@@ -130,7 +129,7 @@
     InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
 private:
-    HTMLCanvasElement(const QualifiedName&, Document&);
+    explicit HTMLCanvasElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*);
@@ -165,8 +164,9 @@
     float m_deviceScaleFactor; // FIXME: This is always 1 and should probable be deleted
     bool m_originClean;
 
-    // m_createdImageBuffer means we tried to malloc the buffer.  We didn't necessarily get it.
-    mutable bool m_hasCreatedImageBuffer;
+    // It prevents HTMLCanvasElement::buffer() from continuously re-attempting to allocate an imageBuffer
+    // after the first attempt failed.
+    mutable bool m_didFailToCreateImageBuffer;
     mutable bool m_didClearImageBuffer;
     OwnPtr<ImageBuffer> m_imageBuffer;
     mutable OwnPtr<GraphicsContextStateSaver> m_contextStateSaver;
diff --git a/Source/core/html/HTMLCanvasElement.idl b/Source/core/html/HTMLCanvasElement.idl
index 78ada4d..0bee59f 100644
--- a/Source/core/html/HTMLCanvasElement.idl
+++ b/Source/core/html/HTMLCanvasElement.idl
@@ -32,6 +32,6 @@
     [Custom, RaisesException] DOMString toDataURL([TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString type);
 
     // The custom binding is needed to handle context creation attributes.
-    [Custom, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds] any getContext([Default=Undefined] optional DOMString contextId);
+    [Custom, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] any getContext([Default=Undefined] optional DOMString contextId);
 };
 
diff --git a/Source/core/html/HTMLCollection.cpp b/Source/core/html/HTMLCollection.cpp
index a6faa86..a0edbbc 100644
--- a/Source/core/html/HTMLCollection.cpp
+++ b/Source/core/html/HTMLCollection.cpp
@@ -255,7 +255,7 @@
 
 static Node* previousNode(Node& base, Node& previous, bool onlyIncludeDirectChildren)
 {
-    return onlyIncludeDirectChildren ? previous.previousSibling() : NodeTraversal::previous(&previous, &base);
+    return onlyIncludeDirectChildren ? previous.previousSibling() : NodeTraversal::previous(previous, &base);
 }
 
 static inline Node* lastDescendent(Node& node)
@@ -302,30 +302,32 @@
 }
 
 template <class NodeListType>
-inline Element* firstMatchingElement(const NodeListType* nodeList, ContainerNode* root)
+inline Element* firstMatchingElement(const NodeListType* nodeList, ContainerNode& root)
 {
     Element* element = ElementTraversal::firstWithin(root);
     while (element && !isMatchingElement(nodeList, element))
-        element = ElementTraversal::next(element, root);
+        element = ElementTraversal::next(*element, &root);
     return element;
 }
 
 template <class NodeListType>
-inline Element* nextMatchingElement(const NodeListType* nodeList, Element* current, ContainerNode* root)
+inline Element* nextMatchingElement(const NodeListType* nodeList, Element& current, ContainerNode* root)
 {
+    Element* next = &current;
     do {
-        current = ElementTraversal::next(current, root);
-    } while (current && !isMatchingElement(nodeList, current));
-    return current;
+        next = ElementTraversal::next(*next, root);
+    } while (next && !isMatchingElement(nodeList, next));
+    return next;
 }
 
 template <class NodeListType>
-inline Element* traverseMatchingElementsForwardToOffset(const NodeListType* nodeList, unsigned offset, Element* currentElement, unsigned& currentOffset, ContainerNode* root)
+inline Element* traverseMatchingElementsForwardToOffset(const NodeListType* nodeList, unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root)
 {
     ASSERT(currentOffset < offset);
-    while ((currentElement = nextMatchingElement(nodeList, currentElement, root))) {
+    Element* next = &currentElement;
+    while ((next = nextMatchingElement(nodeList, *next, root))) {
         if (++currentOffset == offset)
-            return currentElement;
+            return next;
     }
     return 0;
 }
@@ -343,7 +345,7 @@
 }
 
 // FIXME: This should be in LiveNodeList
-inline Element* LiveNodeListBase::traverseLiveNodeListFirstElement(ContainerNode* root) const
+inline Element* LiveNodeListBase::traverseLiveNodeListFirstElement(ContainerNode& root) const
 {
     ASSERT(isNodeList(type()));
     ASSERT(type() != ChildNodeListType);
@@ -355,7 +357,7 @@
 }
 
 // FIXME: This should be in LiveNodeList
-inline Element* LiveNodeListBase::traverseLiveNodeListForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, ContainerNode* root) const
+inline Element* LiveNodeListBase::traverseLiveNodeListForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root) const
 {
     ASSERT(isNodeList(type()));
     ASSERT(type() != ChildNodeListType);
@@ -433,9 +435,9 @@
         if (type() == ChildNodeListType)
             firstItem = root->firstChild();
         else if (isNodeList(type()))
-            firstItem = traverseLiveNodeListFirstElement(root);
+            firstItem = traverseLiveNodeListFirstElement(*root);
         else
-            firstItem = static_cast<const HTMLCollection*>(this)->traverseFirstElement(offsetInArray, root);
+            firstItem = static_cast<const HTMLCollection*>(this)->traverseFirstElement(offsetInArray, *root);
 
         if (!firstItem) {
             setLengthCache(0);
@@ -476,9 +478,9 @@
     if (type() == ChildNodeListType)
         currentItem = traverseChildNodeListForwardToOffset(offset, currentItem, currentOffset);
     else if (isNodeList(type()))
-        currentItem = traverseLiveNodeListForwardToOffset(offset, toElement(currentItem), currentOffset, root);
+        currentItem = traverseLiveNodeListForwardToOffset(offset, toElement(*currentItem), currentOffset, root);
     else
-        currentItem = static_cast<const HTMLCollection*>(this)->traverseForwardToOffset(offset, toElement(currentItem), currentOffset, offsetInArray, root);
+        currentItem = static_cast<const HTMLCollection*>(this)->traverseForwardToOffset(offset, toElement(*currentItem), currentOffset, offsetInArray, root);
 
     if (!currentItem) {
         // Did not find the item. On plus side, we now know the length.
@@ -523,23 +525,24 @@
     return e->getNameAttribute() == name && e->getIdAttribute() != name;
 }
 
-inline Element* firstMatchingChildElement(const HTMLCollection* nodeList, ContainerNode* root)
+inline Element* firstMatchingChildElement(const HTMLCollection* nodeList, ContainerNode& root)
 {
     Element* element = ElementTraversal::firstWithin(root);
     while (element && !isMatchingElement(nodeList, element))
-        element = ElementTraversal::nextSkippingChildren(element, root);
+        element = ElementTraversal::nextSkippingChildren(*element, &root);
     return element;
 }
 
-inline Element* nextMatchingChildElement(const HTMLCollection* nodeList, Element* current, ContainerNode* root)
+inline Element* nextMatchingChildElement(const HTMLCollection* nodeList, Element& current, ContainerNode* root)
 {
+    Element* next = &current;
     do {
-        current = ElementTraversal::nextSkippingChildren(current, root);
-    } while (current && !isMatchingElement(nodeList, current));
-    return current;
+        next = ElementTraversal::nextSkippingChildren(*next, root);
+    } while (next && !isMatchingElement(nodeList, next));
+    return next;
 }
 
-inline Element* HTMLCollection::traverseFirstElement(unsigned& offsetInArray, ContainerNode* root) const
+inline Element* HTMLCollection::traverseFirstElement(unsigned& offsetInArray, ContainerNode& root) const
 {
     if (overridesItemAfter())
         return virtualItemAfter(offsetInArray, 0);
@@ -549,31 +552,33 @@
     return firstMatchingElement(static_cast<const HTMLCollection*>(this), root);
 }
 
-inline Element* HTMLCollection::traverseNextElement(unsigned& offsetInArray, Element* previous, ContainerNode* root) const
+inline Element* HTMLCollection::traverseNextElement(unsigned& offsetInArray, Element& previous, ContainerNode* root) const
 {
     if (overridesItemAfter())
-        return virtualItemAfter(offsetInArray, previous);
+        return virtualItemAfter(offsetInArray, &previous);
     ASSERT(!offsetInArray);
     if (shouldOnlyIncludeDirectChildren())
         return nextMatchingChildElement(this, previous, root);
     return nextMatchingElement(this, previous, root);
 }
 
-inline Element* HTMLCollection::traverseForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const
+inline Element* HTMLCollection::traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const
 {
     ASSERT(currentOffset < offset);
     if (overridesItemAfter()) {
         offsetInArray = m_cachedElementsArrayOffset;
-        while ((currentElement = virtualItemAfter(offsetInArray, currentElement))) {
+        Element* next = &currentElement;
+        while ((next = virtualItemAfter(offsetInArray, next))) {
             if (++currentOffset == offset)
-                return currentElement;
+                return next;
         }
         return 0;
     }
     if (shouldOnlyIncludeDirectChildren()) {
-        while ((currentElement = nextMatchingChildElement(this, currentElement, root))) {
+        Element* next = &currentElement;
+        while ((next = nextMatchingChildElement(this, *next, root))) {
             if (++currentOffset == offset)
-                return currentElement;
+                return next;
         }
         return 0;
     }
@@ -594,7 +599,7 @@
 
     unsigned arrayOffset = 0;
     unsigned i = 0;
-    for (Element* element = traverseFirstElement(arrayOffset, root); element; element = traverseNextElement(arrayOffset, element, root)) {
+    for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
         if (checkForNameMatch(element, /* checkName */ false, name)) {
             setItemCache(element, i, arrayOffset);
             return element;
@@ -603,7 +608,7 @@
     }
 
     i = 0;
-    for (Element* element = traverseFirstElement(arrayOffset, root); element; element = traverseNextElement(arrayOffset, element, root)) {
+    for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
         if (checkForNameMatch(element, /* checkName */ true, name)) {
             setItemCache(element, i, arrayOffset);
             return element;
@@ -624,7 +629,7 @@
         return;
 
     unsigned arrayOffset = 0;
-    for (Element* element = traverseFirstElement(arrayOffset, root); element; element = traverseNextElement(arrayOffset, element, root)) {
+    for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
         const AtomicString& idAttrVal = element->getIdAttribute();
         if (!idAttrVal.isEmpty())
             appendIdCache(idAttrVal, element);
diff --git a/Source/core/html/HTMLCollection.h b/Source/core/html/HTMLCollection.h
index 4ff5e71..967b247 100644
--- a/Source/core/html/HTMLCollection.h
+++ b/Source/core/html/HTMLCollection.h
@@ -61,8 +61,8 @@
 
     virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const;
 
-    Element* traverseFirstElement(unsigned& offsetInArray, ContainerNode* root) const;
-    Element* traverseForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const;
+    Element* traverseFirstElement(unsigned& offsetInArray, ContainerNode& root) const;
+    Element* traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const;
 
 protected:
     HTMLCollection(Node* base, CollectionType, ItemAfterOverrideType);
@@ -77,7 +77,7 @@
 
 private:
     bool checkForNameMatch(Element*, bool checkName, const AtomicString& name) const;
-    Element* traverseNextElement(unsigned& offsetInArray, Element* previous, ContainerNode* root) const;
+    Element* traverseNextElement(unsigned& offsetInArray, Element& previous, ContainerNode* root) const;
 
     virtual bool isLiveNodeList() const OVERRIDE { ASSERT_NOT_REACHED(); return true; }
 
diff --git a/Source/core/html/HTMLCollection.idl b/Source/core/html/HTMLCollection.idl
index 319d878..2b9245e 100644
--- a/Source/core/html/HTMLCollection.idl
+++ b/Source/core/html/HTMLCollection.idl
@@ -19,9 +19,9 @@
  */
 
 [
-    CustomToV8,
-    GenerateIsReachable=ownerNode,
-    DependentLifetime
+    CustomWrap,
+    DependentLifetime,
+    GenerateVisitDOMWrapper=ownerNode,
 ] interface HTMLCollection {
     readonly attribute unsigned long length;
     getter Node item([Default=Undefined] optional unsigned long index);
diff --git a/Source/core/html/HTMLDListElement.cpp b/Source/core/html/HTMLDListElement.cpp
index 4b14c69..7196698 100644
--- a/Source/core/html/HTMLDListElement.cpp
+++ b/Source/core/html/HTMLDListElement.cpp
@@ -29,16 +29,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLDListElement::HTMLDListElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLDListElement::HTMLDListElement(Document& document)
+    : HTMLElement(dlTag, document)
 {
-    ASSERT(hasTagName(dlTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDListElement> HTMLDListElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDListElement> HTMLDListElement::create(Document& document)
 {
-    return adoptRef(new HTMLDListElement(tagName, document));
+    return adoptRef(new HTMLDListElement(document));
 }
 
 }
diff --git a/Source/core/html/HTMLDListElement.h b/Source/core/html/HTMLDListElement.h
index 1909af6..24aeb81 100644
--- a/Source/core/html/HTMLDListElement.h
+++ b/Source/core/html/HTMLDListElement.h
@@ -29,10 +29,10 @@
 
 class HTMLDListElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDListElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLDListElement> create(Document&);
 
 private:
-    HTMLDListElement(const QualifiedName&, Document&);
+    explicit HTMLDListElement(Document&);
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLDataListElement.cpp b/Source/core/html/HTMLDataListElement.cpp
index 2c609c3..fbac9e9 100644
--- a/Source/core/html/HTMLDataListElement.cpp
+++ b/Source/core/html/HTMLDataListElement.cpp
@@ -32,21 +32,22 @@
 #include "config.h"
 #include "core/html/HTMLDataListElement.h"
 
+#include "HTMLNames.h"
 #include "core/dom/IdTargetObserverRegistry.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 
 namespace WebCore {
 
-inline HTMLDataListElement::HTMLDataListElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLDataListElement::HTMLDataListElement(Document& document)
+    : HTMLElement(HTMLNames::datalistTag, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDataListElement> HTMLDataListElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDataListElement> HTMLDataListElement::create(Document& document)
 {
     UseCounter::count(document, UseCounter::DataListElement);
-    return adoptRef(new HTMLDataListElement(tagName, document));
+    return adoptRef(new HTMLDataListElement(document));
 }
 
 PassRefPtr<HTMLCollection> HTMLDataListElement::options()
diff --git a/Source/core/html/HTMLDataListElement.h b/Source/core/html/HTMLDataListElement.h
index e882fe3..e41a0e8 100644
--- a/Source/core/html/HTMLDataListElement.h
+++ b/Source/core/html/HTMLDataListElement.h
@@ -39,14 +39,14 @@
 
 class HTMLDataListElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDataListElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLDataListElement> create(Document&);
 
     PassRefPtr<HTMLCollection> options();
 
     void optionElementChildrenChanged();
 
 private:
-    HTMLDataListElement(const QualifiedName&, Document&);
+    HTMLDataListElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLDataListElement, hasTagName(HTMLNames::datalistTag));
diff --git a/Source/core/html/HTMLDetailsElement.cpp b/Source/core/html/HTMLDetailsElement.cpp
index b0ee16b..f3220bc 100644
--- a/Source/core/html/HTMLDetailsElement.cpp
+++ b/Source/core/html/HTMLDetailsElement.cpp
@@ -34,18 +34,17 @@
 
 using namespace HTMLNames;
 
-PassRefPtr<HTMLDetailsElement> HTMLDetailsElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDetailsElement> HTMLDetailsElement::create(Document& document)
 {
-    RefPtr<HTMLDetailsElement> details = adoptRef(new HTMLDetailsElement(tagName, document));
+    RefPtr<HTMLDetailsElement> details = adoptRef(new HTMLDetailsElement(document));
     details->ensureUserAgentShadowRoot();
     return details.release();
 }
 
-HTMLDetailsElement::HTMLDetailsElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLDetailsElement::HTMLDetailsElement(Document& document)
+    : HTMLElement(detailsTag, document)
     , m_isOpen(false)
 {
-    ASSERT(hasTagName(detailsTag));
     ScriptWrappable::init(this);
 }
 
@@ -54,19 +53,19 @@
     return new RenderBlockFlow(this);
 }
 
-void HTMLDetailsElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLDetailsElement::didAddUserAgentShadowRoot(ShadowRoot& root)
 {
     DEFINE_STATIC_LOCAL(AtomicString, summarySelector, ("summary:first-of-type", AtomicString::ConstructFromLiteral));
 
-    RefPtr<HTMLSummaryElement> defaultSummary = HTMLSummaryElement::create(summaryTag, document());
-    defaultSummary->appendChild(Text::create(document(), locale().queryString(WebKit::WebLocalizedString::DetailsLabel)));
+    RefPtr<HTMLSummaryElement> defaultSummary = HTMLSummaryElement::create(document());
+    defaultSummary->appendChild(Text::create(document(), locale().queryString(blink::WebLocalizedString::DetailsLabel)));
 
     RefPtr<HTMLContentElement> content = HTMLContentElement::create(document());
     content->setAttribute(selectAttr, summarySelector);
     content->appendChild(defaultSummary);
 
-    root->appendChild(content);
-    root->appendChild(HTMLContentElement::create(document()));
+    root.appendChild(content);
+    root.appendChild(HTMLContentElement::create(document()));
 }
 
 Element* HTMLDetailsElement::findMainSummary() const
diff --git a/Source/core/html/HTMLDetailsElement.h b/Source/core/html/HTMLDetailsElement.h
index 55cc956..d5a6b4a 100644
--- a/Source/core/html/HTMLDetailsElement.h
+++ b/Source/core/html/HTMLDetailsElement.h
@@ -27,18 +27,18 @@
 
 class HTMLDetailsElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDetailsElement> create(const QualifiedName& tagName, Document&);
+    static PassRefPtr<HTMLDetailsElement> create(Document&);
     void toggleOpen();
 
     Element* findMainSummary() const;
 
 private:
-    HTMLDetailsElement(const QualifiedName&, Document&);
+    explicit HTMLDetailsElement(Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
     virtual bool isInteractiveContent() const OVERRIDE;
 
     bool m_isOpen;
diff --git a/Source/core/html/HTMLDialogElement.cpp b/Source/core/html/HTMLDialogElement.cpp
index b264572..82496b1 100644
--- a/Source/core/html/HTMLDialogElement.cpp
+++ b/Source/core/html/HTMLDialogElement.cpp
@@ -26,7 +26,9 @@
 #include "config.h"
 #include "core/html/HTMLDialogElement.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
+#include "core/accessibility/AXObjectCache.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLFormControlElement.h"
@@ -51,31 +53,42 @@
             }
         }
         if (node->hasTagName(dialogTag))
-            next = NodeTraversal::nextSkippingChildren(node, dialog);
+            next = NodeTraversal::nextSkippingChildren(*node, dialog);
         else
-            next = NodeTraversal::next(node, dialog);
+            next = NodeTraversal::next(*node, dialog);
     }
 }
 
-HTMLDialogElement::HTMLDialogElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+static void inertSubtreesChanged(Document& document)
+{
+    // When a modal dialog opens or closes, nodes all over the accessibility
+    // tree can change inertness which means they must be added or removed from
+    // the tree. The most foolproof way is to clear the entire tree and rebuild
+    // it, though a more clever way is probably possible.
+    Document* topDocument = document.topDocument();
+    topDocument->clearAXObjectCache();
+    if (AXObjectCache* cache = topDocument->axObjectCache())
+        cache->childrenChanged(cache->getOrCreate(topDocument));
+}
+
+HTMLDialogElement::HTMLDialogElement(Document& document)
+    : HTMLElement(dialogTag, document)
     , m_centeringMode(Uninitialized)
     , m_centeredPosition(0)
     , m_returnValue("")
 {
-    ASSERT(hasTagName(dialogTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDialogElement> HTMLDialogElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDialogElement> HTMLDialogElement::create(Document& document)
 {
-    return adoptRef(new HTMLDialogElement(tagName, document));
+    return adoptRef(new HTMLDialogElement(document));
 }
 
-void HTMLDialogElement::close(const String& returnValue, ExceptionState& es)
+void HTMLDialogElement::close(const String& returnValue, ExceptionState& exceptionState)
 {
     if (!fastHasAttribute(openAttr)) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("close", "HTMLDialogElement", "The element does not have an 'open' attribute, and therefore cannot be closed."));
         return;
     }
     closeDialog(returnValue);
@@ -86,7 +99,11 @@
     if (!fastHasAttribute(openAttr))
         return;
     setBooleanAttribute(openAttr, false);
+
+    HTMLDialogElement* activeModalDialog = document().activeModalDialog();
     document().removeFromTopLayer(this);
+    if (activeModalDialog == this)
+        inertSubtreesChanged(document());
 
     if (!returnValue.isNull())
         m_returnValue = returnValue;
@@ -110,17 +127,23 @@
     forceLayoutForCentering();
 }
 
-void HTMLDialogElement::showModal(ExceptionState& es)
+void HTMLDialogElement::showModal(ExceptionState& exceptionState)
 {
-    if (fastHasAttribute(openAttr) || !inDocument()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+    if (fastHasAttribute(openAttr)) {
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("showModal", "HTMLDialogElement", "The element already has an 'open' attribute, and therefore cannot be opened modally."));
         return;
     }
+    if (!inDocument()) {
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("showModal", "HTMLDialogElement", "The element is not in a Document."));
+        return;
+    }
+
     document().addToTopLayer(this);
     setBooleanAttribute(openAttr, true);
 
     runAutofocus(this);
     forceLayoutForCentering();
+    inertSubtreesChanged(document());
 }
 
 void HTMLDialogElement::setCentered(LayoutUnit centeredPosition)
diff --git a/Source/core/html/HTMLDialogElement.h b/Source/core/html/HTMLDialogElement.h
index c78bd88..248044e 100644
--- a/Source/core/html/HTMLDialogElement.h
+++ b/Source/core/html/HTMLDialogElement.h
@@ -37,7 +37,7 @@
 
 class HTMLDialogElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDialogElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLDialogElement> create(Document&);
 
     void close(const String& returnValue, ExceptionState&);
     void closeDialog(const String& returnValue = String());
@@ -58,7 +58,7 @@
     void setReturnValue(const String& returnValue) { m_returnValue = returnValue; }
 
 private:
-    HTMLDialogElement(const QualifiedName&, Document&);
+    explicit HTMLDialogElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
diff --git a/Source/core/html/HTMLDirectoryElement.cpp b/Source/core/html/HTMLDirectoryElement.cpp
index 0068dfa..2010c5a 100644
--- a/Source/core/html/HTMLDirectoryElement.cpp
+++ b/Source/core/html/HTMLDirectoryElement.cpp
@@ -29,16 +29,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLDirectoryElement::HTMLDirectoryElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLDirectoryElement::HTMLDirectoryElement(Document& document)
+    : HTMLElement(dirTag, document)
 {
-    ASSERT(hasTagName(dirTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDirectoryElement> HTMLDirectoryElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDirectoryElement> HTMLDirectoryElement::create(Document& document)
 {
-    return adoptRef(new HTMLDirectoryElement(tagName, document));
+    return adoptRef(new HTMLDirectoryElement(document));
 }
 
 }
diff --git a/Source/core/html/HTMLDirectoryElement.h b/Source/core/html/HTMLDirectoryElement.h
index 99efc0d..7c0dcaa 100644
--- a/Source/core/html/HTMLDirectoryElement.h
+++ b/Source/core/html/HTMLDirectoryElement.h
@@ -29,10 +29,10 @@
 
 class HTMLDirectoryElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDirectoryElement> create(const QualifiedName& tagName, Document&);
+    static PassRefPtr<HTMLDirectoryElement> create(Document&);
 
 private:
-    HTMLDirectoryElement(const QualifiedName&, Document&);
+    explicit HTMLDirectoryElement(Document&);
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLDivElement.cpp b/Source/core/html/HTMLDivElement.cpp
index 8ed60f1..af3d893 100644
--- a/Source/core/html/HTMLDivElement.cpp
+++ b/Source/core/html/HTMLDivElement.cpp
@@ -31,21 +31,15 @@
 
 using namespace HTMLNames;
 
-HTMLDivElement::HTMLDivElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLDivElement::HTMLDivElement(Document& document)
+    : HTMLElement(divTag, document)
 {
-    ASSERT(hasTagName(divTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLDivElement> HTMLDivElement::create(Document& document)
 {
-    return adoptRef(new HTMLDivElement(divTag, document));
-}
-
-PassRefPtr<HTMLDivElement> HTMLDivElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLDivElement(tagName, document));
+    return adoptRef(new HTMLDivElement(document));
 }
 
 bool HTMLDivElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLDivElement.h b/Source/core/html/HTMLDivElement.h
index e326c6e..12e2300 100644
--- a/Source/core/html/HTMLDivElement.h
+++ b/Source/core/html/HTMLDivElement.h
@@ -30,10 +30,9 @@
 class HTMLDivElement : public HTMLElement {
 public:
     static PassRefPtr<HTMLDivElement> create(Document&);
-    static PassRefPtr<HTMLDivElement> create(const QualifiedName&, Document&);
 
 protected:
-    HTMLDivElement(const QualifiedName&, Document&);
+    explicit HTMLDivElement(Document&);
 
 private:
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLDivElement.idl b/Source/core/html/HTMLDivElement.idl
index b2eeb3d..f8ab122 100644
--- a/Source/core/html/HTMLDivElement.idl
+++ b/Source/core/html/HTMLDivElement.idl
@@ -17,8 +17,6 @@
  * Boston, MA 02110-1301, USA.
  */
 
-[
-] interface HTMLDivElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString align;
+interface HTMLDivElement : HTMLElement {
+    [Reflect] attribute DOMString align;
 };
-
diff --git a/Source/core/html/HTMLDocument.cpp b/Source/core/html/HTMLDocument.cpp
index 39952ae..ee9cb24 100644
--- a/Source/core/html/HTMLDocument.cpp
+++ b/Source/core/html/HTMLDocument.cpp
@@ -55,12 +55,14 @@
 
 #include "HTMLNames.h"
 #include "bindings/v8/ScriptController.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
 #include "core/html/HTMLBodyElement.h"
 #include "core/page/FocusController.h"
-#include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
-#include "core/frame/FrameView.h"
 #include "core/page/Page.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -326,4 +328,22 @@
     // But I do see it in the documentation for Mozilla.
 }
 
+void HTMLDocument::write(DOMWindow* activeWindow, const Vector<String>& text)
+{
+    ASSERT(activeWindow);
+    StringBuilder builder;
+    for (size_t i = 0; i < text.size(); ++i)
+        builder.append(text[i]);
+    write(builder.toString(), activeWindow->document());
+}
+
+void HTMLDocument::writeln(DOMWindow* activeWindow, const Vector<String>& text)
+{
+    ASSERT(activeWindow);
+    StringBuilder builder;
+    for (size_t i = 0; i < text.size(); ++i)
+        builder.append(text[i]);
+    writeln(builder.toString(), activeWindow->document());
+}
+
 }
diff --git a/Source/core/html/HTMLDocument.h b/Source/core/html/HTMLDocument.h
index bc3b9a7..58e624f 100644
--- a/Source/core/html/HTMLDocument.h
+++ b/Source/core/html/HTMLDocument.h
@@ -74,6 +74,11 @@
     void removeExtraNamedItem(const AtomicString& name);
     bool hasExtraNamedItem(const AtomicString& name);
 
+    using Document::write;
+    using Document::writeln;
+    void write(DOMWindow*, const Vector<String>& text);
+    void writeln(DOMWindow*, const Vector<String>& text);
+
     static bool isCaseSensitiveAttribute(const QualifiedName&);
 
     virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
diff --git a/Source/core/html/HTMLDocument.idl b/Source/core/html/HTMLDocument.idl
index 764f1af..84328c8 100644
--- a/Source/core/html/HTMLDocument.idl
+++ b/Source/core/html/HTMLDocument.idl
@@ -21,11 +21,15 @@
 interface HTMLDocument : Document {
     [Custom, CustomElementCallbacks] void open();
     void close();
-    [Custom, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, CustomElementCallbacks] void write([Default=Undefined] optional DOMString text);
-    [Custom, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, CustomElementCallbacks] void writeln([Default=Undefined] optional DOMString text);
+
+    // We support multiple DOMString arguments to match FF / IE, e.g.:
+    // document.write("a", "b", "c") --> document.write("abc")
+    // document.write() --> document.write("")
+    [CallWith=ActiveWindow, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, CustomElementCallbacks] void write(DOMString... text);
+    [CallWith=ActiveWindow, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, CustomElementCallbacks] void writeln(DOMString... text);
 
     readonly attribute HTMLCollection embeds;
-    readonly attribute HTMLCollection plugins;
+    [ImplementedAs=embeds] readonly attribute HTMLCollection plugins;
     readonly attribute HTMLCollection scripts;
 
     // Extensions
diff --git a/Source/core/html/HTMLElement.cpp b/Source/core/html/HTMLElement.cpp
index 2500b8a..180a074 100644
--- a/Source/core/html/HTMLElement.cpp
+++ b/Source/core/html/HTMLElement.cpp
@@ -29,6 +29,7 @@
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "XMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptController.h"
 #include "bindings/v8/ScriptEventListener.h"
@@ -325,7 +326,7 @@
     }
 }
 
-PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& es)
+PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& exceptionState)
 {
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
     unsigned int i, length = text.length();
@@ -339,13 +340,13 @@
               break;
         }
 
-        fragment->appendChild(Text::create(document(), text.substring(start, i - start)), es);
-        if (es.hadException())
+        fragment->appendChild(Text::create(document(), text.substring(start, i - start)), exceptionState);
+        if (exceptionState.hadException())
             return 0;
 
         if (c == '\r' || c == '\n') {
-            fragment->appendChild(HTMLBRElement::create(document()), es);
-            if (es.hadException())
+            fragment->appendChild(HTMLBRElement::create(document()), exceptionState);
+            if (exceptionState.hadException())
                 return 0;
             // Make sure \r\n doesn't result in two line breaks.
             if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
@@ -358,17 +359,17 @@
     return fragment;
 }
 
-void HTMLElement::setInnerText(const String& text, ExceptionState& es)
+void HTMLElement::setInnerText(const String& text, ExceptionState& exceptionState)
 {
     if (ieForbidsInsertHTML()) {
-        es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+        exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::failedToSet("innerText", "HTMLElement", "The '" + localName() + "' element does not support text insertion."));
         return;
     }
     if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
         hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
         hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
         hasLocalName(trTag)) {
-        es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+        exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::failedToSet("innerText", "HTMLElement", "The '" + localName() + "' element does not support text insertion."));
         return;
     }
 
@@ -379,7 +380,7 @@
             removeChildren();
             return;
         }
-        replaceChildrenWithText(this, text, es);
+        replaceChildrenWithText(this, text, exceptionState);
         return;
     }
 
@@ -389,39 +390,39 @@
     RenderObject* r = renderer();
     if (r && r->style()->preserveNewline()) {
         if (!text.contains('\r')) {
-            replaceChildrenWithText(this, text, es);
+            replaceChildrenWithText(this, text, exceptionState);
             return;
         }
         String textWithConsistentLineBreaks = text;
         textWithConsistentLineBreaks.replace("\r\n", "\n");
         textWithConsistentLineBreaks.replace('\r', '\n');
-        replaceChildrenWithText(this, textWithConsistentLineBreaks, es);
+        replaceChildrenWithText(this, textWithConsistentLineBreaks, exceptionState);
         return;
     }
 
     // Add text nodes and <br> elements.
-    RefPtr<DocumentFragment> fragment = textToFragment(text, es);
-    if (!es.hadException())
-        replaceChildrenWithFragment(this, fragment.release(), es);
+    RefPtr<DocumentFragment> fragment = textToFragment(text, exceptionState);
+    if (!exceptionState.hadException())
+        replaceChildrenWithFragment(this, fragment.release(), exceptionState);
 }
 
-void HTMLElement::setOuterText(const String &text, ExceptionState& es)
+void HTMLElement::setOuterText(const String &text, ExceptionState& exceptionState)
 {
     if (ieForbidsInsertHTML()) {
-        es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+        exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::failedToSet("outerText", "HTMLElement", "The '" + localName() + "' element does not support text insertion."));
         return;
     }
     if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
         hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
         hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
         hasLocalName(trTag)) {
-        es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+        exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::failedToSet("outerText", "HTMLElement", "The '" + localName() + "' element does not support text insertion."));
         return;
     }
 
     ContainerNode* parent = parentNode();
     if (!parent) {
-        es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+        exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::failedToSet("outerText", "HTMLElement", "The element has no parent."));
         return;
     }
 
@@ -431,25 +432,28 @@
 
     // Convert text to fragment with <br> tags instead of linebreaks if needed.
     if (text.contains('\r') || text.contains('\n'))
-        newChild = textToFragment(text, es);
+        newChild = textToFragment(text, exceptionState);
     else
         newChild = Text::create(document(), text);
 
+    // textToFragment might cause mutation events.
     if (!this || !parentNode())
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
-    if (es.hadException())
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToSet("outerText", "HTMLElement", "The element has no parent."));
+
+    if (exceptionState.hadException())
         return;
-    parent->replaceChild(newChild.release(), this, es);
+
+    parent->replaceChild(newChild.release(), this, exceptionState);
 
     RefPtr<Node> node = next ? next->previousSibling() : 0;
-    if (!es.hadException() && node && node->isTextNode())
-        mergeWithNextTextNode(node.release(), es);
+    if (!exceptionState.hadException() && node && node->isTextNode())
+        mergeWithNextTextNode(node.release(), exceptionState);
 
-    if (!es.hadException() && prev && prev->isTextNode())
-        mergeWithNextTextNode(prev.release(), es);
+    if (!exceptionState.hadException() && prev && prev->isTextNode())
+        mergeWithNextTextNode(prev.release(), exceptionState);
 }
 
-Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionState& es)
+Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
 {
     // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
     // a document fragment is created and the elements appended in the correct order. This document
@@ -460,82 +464,82 @@
 
     if (equalIgnoringCase(where, "beforeBegin")) {
         if (ContainerNode* parent = this->parentNode()) {
-            parent->insertBefore(newChild, this, es);
-            if (!es.hadException())
+            parent->insertBefore(newChild, this, exceptionState);
+            if (!exceptionState.hadException())
                 return newChild;
         }
         return 0;
     }
 
     if (equalIgnoringCase(where, "afterBegin")) {
-        insertBefore(newChild, firstChild(), es);
-        return es.hadException() ? 0 : newChild;
+        insertBefore(newChild, firstChild(), exceptionState);
+        return exceptionState.hadException() ? 0 : newChild;
     }
 
     if (equalIgnoringCase(where, "beforeEnd")) {
-        appendChild(newChild, es);
-        return es.hadException() ? 0 : newChild;
+        appendChild(newChild, exceptionState);
+        return exceptionState.hadException() ? 0 : newChild;
     }
 
     if (equalIgnoringCase(where, "afterEnd")) {
         if (ContainerNode* parent = this->parentNode()) {
-            parent->insertBefore(newChild, nextSibling(), es);
-            if (!es.hadException())
+            parent->insertBefore(newChild, nextSibling(), exceptionState);
+            if (!exceptionState.hadException())
                 return newChild;
         }
         return 0;
     }
 
     // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
-    es.throwUninformativeAndGenericDOMException(NotSupportedError);
+    exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("insertAdjacent", "HTMLElement", "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'."));
     return 0;
 }
 
-Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& es)
+Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
 {
     if (!newChild) {
         // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwTypeError(ExceptionMessages::failedToExecute("insertAdjacentElement", "HTMLElement", "The node provided is null."));
         return 0;
     }
 
-    Node* returnValue = insertAdjacent(where, newChild, es);
+    Node* returnValue = insertAdjacent(where, newChild, exceptionState);
     return toElement(returnValue);
 }
 
 // Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
-static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& es)
+static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
 {
     if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
         ContainerNode* parent = element->parentNode();
         if (parent && !parent->isElementNode()) {
-            es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+            exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::failedToExecute("insertAdjacentHTML", "HTMLElement", "The element has no parent."));
             return 0;
         }
         return toElement(parent);
     }
     if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
         return element;
-    es.throwUninformativeAndGenericDOMException(SyntaxError);
+    exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("insertAdjacentHTML", "HTMLElement", "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'."));
     return 0;
 }
 
-void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& es)
+void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
 {
-    Element* contextElement = contextElementForInsertion(where, this, es);
+    RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
     if (!contextElement)
         return;
 
-    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement, AllowScriptingContent, "insertAdjacentHTML", es);
+    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
     if (!fragment)
         return;
-    insertAdjacent(where, fragment.get(), es);
+    insertAdjacent(where, fragment.get(), exceptionState);
 }
 
-void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionState& es)
+void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
 {
     RefPtr<Text> textNode = document().createTextNode(text);
-    insertAdjacent(where, textNode.get(), es);
+    insertAdjacent(where, textNode.get(), exceptionState);
 }
 
 void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStylePropertySet* style)
@@ -621,7 +625,7 @@
     return "inherit";
 }
 
-void HTMLElement::setContentEditable(const String& enabled, ExceptionState& es)
+void HTMLElement::setContentEditable(const String& enabled, ExceptionState& exceptionState)
 {
     if (equalIgnoringCase(enabled, "true"))
         setAttribute(contenteditableAttr, "true");
@@ -632,7 +636,7 @@
     else if (equalIgnoringCase(enabled, "inherit"))
         removeAttribute(contenteditableAttr);
     else
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("contentEditable", "HTMLElement", "The value provided ('" + enabled + "') is not one of 'true', 'false', 'plaintext-only', or 'inherit'."));
 }
 
 bool HTMLElement::draggable() const
@@ -658,7 +662,7 @@
 
 void HTMLElement::click()
 {
-    dispatchSimulatedClick(0, SendNoEvents, DoNotShowPressedLook);
+    dispatchSimulatedClick(0, SendNoEvents);
 }
 
 void HTMLElement::accessKeyAction(bool sendMouseEvents)
@@ -680,7 +684,7 @@
 
 void HTMLElement::setTabIndex(int value)
 {
-    setAttribute(tabindexAttr, String::number(value));
+    setIntegralAttribute(tabindexAttr, value);
 }
 
 TranslateAttributeMode HTMLElement::translateAttributeMode() const
@@ -771,13 +775,13 @@
         if (elementAffectsDirectionality(node)) {
             if (node == lastNode)
                 return;
-            node = NodeTraversal::nextSkippingChildren(node, firstNode);
+            node = NodeTraversal::nextSkippingChildren(*node, firstNode);
             continue;
         }
         node->setSelfOrAncestorHasDirAutoAttribute(flag);
         if (node == lastNode)
             return;
-        node = NodeTraversal::next(node, firstNode);
+        node = NodeTraversal::next(*node, firstNode);
     }
 }
 
@@ -829,7 +833,7 @@
         // Skip bdi, script, style and text form controls.
         if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)
             || (node->isElementNode() && toElement(node)->isTextFormControl())) {
-            node = NodeTraversal::nextSkippingChildren(node, this);
+            node = NodeTraversal::nextSkippingChildren(*node, this);
             continue;
         }
 
@@ -837,7 +841,7 @@
         if (node->isElementNode()) {
             AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
             if (isValidDirAttribute(dirAttributeValue)) {
-                node = NodeTraversal::nextSkippingChildren(node, this);
+                node = NodeTraversal::nextSkippingChildren(*node, this);
                 continue;
             }
         }
@@ -851,7 +855,7 @@
                 return textDirection;
             }
         }
-        node = NodeTraversal::next(node, this);
+        node = NodeTraversal::next(*node, this);
     }
     if (strongDirectionalityTextNode)
         *strongDirectionalityTextNode = 0;
@@ -898,8 +902,8 @@
 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
 {
     if (document().renderer() && childCountDelta < 0) {
-        Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(beforeChange) : 0;
-        for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(node)) {
+        Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
+        for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(*node)) {
             if (elementAffectsDirectionality(node))
                 continue;
 
@@ -910,9 +914,9 @@
     if (!selfOrAncestorHasDirAutoAttribute())
         return;
 
-    Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(beforeChange) : 0;
+    Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
     while (oldMarkedNode && elementAffectsDirectionality(oldMarkedNode))
-        oldMarkedNode = NodeTraversal::nextSkippingChildren(oldMarkedNode, this);
+        oldMarkedNode = NodeTraversal::nextSkippingChildren(*oldMarkedNode, this);
     if (oldMarkedNode)
         setHasDirAutoFlagRecursively(oldMarkedNode, false);
 
diff --git a/Source/core/html/HTMLElement.idl b/Source/core/html/HTMLElement.idl
index c5640d5..e20b341 100644
--- a/Source/core/html/HTMLElement.idl
+++ b/Source/core/html/HTMLElement.idl
@@ -19,7 +19,7 @@
  */
 
 [
-    CustomToV8
+    CustomWrap,
 ] interface HTMLElement : Element {
     [Reflect, TreatNullAs=NullString] attribute DOMString title;
     [Reflect, TreatNullAs=NullString] attribute DOMString lang;
@@ -33,8 +33,8 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString accessKey;
 
     // Extensions
-    [TreatNullAs=NullString, CustomElementCallbacks, SetterRaisesException] attribute DOMString innerText;
-    [TreatNullAs=NullString, CustomElementCallbacks, SetterRaisesException] attribute DOMString outerText;
+    [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter] attribute DOMString innerText;
+    [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter] attribute DOMString outerText;
 
     [RaisesException, CustomElementCallbacks, MeasureAs=InsertAdjacentElement] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
                                   [Default=Undefined] optional Element element);
@@ -45,7 +45,7 @@
 
     [RuntimeEnabled=IMEAPI] readonly attribute InputMethodContext inputMethodContext;
 
-    [TreatNullAs=NullString, CustomElementCallbacks, SetterRaisesException] attribute DOMString contentEditable;
+    [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter] attribute DOMString contentEditable;
     readonly attribute boolean isContentEditable;
 
              attribute boolean spellcheck;
diff --git a/Source/core/html/HTMLEmbedElement.cpp b/Source/core/html/HTMLEmbedElement.cpp
index 09b3b7b..cb1fe1d 100644
--- a/Source/core/html/HTMLEmbedElement.cpp
+++ b/Source/core/html/HTMLEmbedElement.cpp
@@ -38,21 +38,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLEmbedElement::HTMLEmbedElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLPlugInElement(tagName, document, createdByParser, ShouldPreferPlugInsForImages)
+inline HTMLEmbedElement::HTMLEmbedElement(Document& document, bool createdByParser)
+    : HTMLPlugInElement(embedTag, document, createdByParser, ShouldPreferPlugInsForImages)
 {
-    ASSERT(hasTagName(embedTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(Document& document, bool createdByParser)
 {
-    return adoptRef(new HTMLEmbedElement(tagName, document, createdByParser));
-}
-
-PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(Document& document)
-{
-    return create(embedTag, document, false);
+    return adoptRef(new HTMLEmbedElement(document, createdByParser));
 }
 
 static inline RenderWidget* findWidgetRenderer(const Node* n)
diff --git a/Source/core/html/HTMLEmbedElement.h b/Source/core/html/HTMLEmbedElement.h
index 023344a..06a1ef4 100644
--- a/Source/core/html/HTMLEmbedElement.h
+++ b/Source/core/html/HTMLEmbedElement.h
@@ -29,11 +29,10 @@
 
 class HTMLEmbedElement FINAL : public HTMLPlugInElement {
 public:
-    static PassRefPtr<HTMLEmbedElement> create(Document&);
-    static PassRefPtr<HTMLEmbedElement> create(const QualifiedName&, Document&, bool createdByParser);
+    static PassRefPtr<HTMLEmbedElement> create(Document&, bool createdByParser = false);
 
 private:
-    HTMLEmbedElement(const QualifiedName&, Document&, bool createdByParser);
+    HTMLEmbedElement(Document&, bool createdByParser);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLEmbedElement.idl b/Source/core/html/HTMLEmbedElement.idl
index 163ce7d..aad4db3 100644
--- a/Source/core/html/HTMLEmbedElement.idl
+++ b/Source/core/html/HTMLEmbedElement.idl
@@ -21,17 +21,16 @@
 [
     CustomLegacyCall,
 ] interface HTMLEmbedElement : HTMLElement {
-[Reflect, TreatNullAs=NullString] attribute DOMString align;
-[Reflect, TreatNullAs=NullString] attribute DOMString height;
-[Reflect, TreatNullAs=NullString] attribute DOMString name;
-[Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
-[Reflect, TreatNullAs=NullString] attribute DOMString type;
-[Reflect, TreatNullAs=NullString] attribute DOMString width;
-[Custom, NotEnumerable] getter boolean (unsigned long index);
-[Custom] setter boolean (unsigned long index, Node value);
-[Custom, NotEnumerable] getter Node (DOMString name);
-[Custom] setter Node (DOMString name, Node value);
+    [Reflect] attribute DOMString align;
+    [Reflect] attribute DOMString height;
+    [Reflect] attribute DOMString name;
+    [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
+    [Reflect] attribute DOMString type;
+    [Reflect] attribute DOMString width;
+    [Custom, NotEnumerable] getter boolean (unsigned long index);
+    [Custom] setter boolean (unsigned long index, Node value);
+    [Custom, NotEnumerable] getter Node (DOMString name);
+    [Custom] setter Node (DOMString name, Node value);
 
-[CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
 };
-
diff --git a/Source/core/html/HTMLFieldSetElement.cpp b/Source/core/html/HTMLFieldSetElement.cpp
index 66ef537..bf568d1 100644
--- a/Source/core/html/HTMLFieldSetElement.cpp
+++ b/Source/core/html/HTMLFieldSetElement.cpp
@@ -37,22 +37,21 @@
 
 using namespace HTMLNames;
 
-inline HTMLFieldSetElement::HTMLFieldSetElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
-    : HTMLFormControlElement(tagName, document, form)
+inline HTMLFieldSetElement::HTMLFieldSetElement(Document& document, HTMLFormElement* form)
+    : HTMLFormControlElement(fieldsetTag, document, form)
     , m_documentVersion(0)
 {
-    ASSERT(hasTagName(fieldsetTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFieldSetElement> HTMLFieldSetElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLFieldSetElement> HTMLFieldSetElement::create(Document& document, HTMLFormElement* form)
 {
-    return adoptRef(new HTMLFieldSetElement(tagName, document, form));
+    return adoptRef(new HTMLFieldSetElement(document, form));
 }
 
-void HTMLFieldSetElement::invalidateDisabledStateUnder(Element* base)
+void HTMLFieldSetElement::invalidateDisabledStateUnder(Element& base)
 {
-    for (Element* element = ElementTraversal::firstWithin(base); element; element = ElementTraversal::next(element, base)) {
+    for (Element* element = ElementTraversal::firstWithin(base); element; element = ElementTraversal::next(*element, &base)) {
         if (element->isFormControlElement())
             toHTMLFormControlElement(element)->ancestorDisabledStateWasChanged();
     }
@@ -62,15 +61,15 @@
 {
     // This element must be updated before the style of nodes in its subtree gets recalculated.
     HTMLFormControlElement::disabledAttributeChanged();
-    invalidateDisabledStateUnder(this);
+    invalidateDisabledStateUnder(*this);
 }
 
 void HTMLFieldSetElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
     HTMLFormControlElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
-    for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::nextSkippingChildren(element, this)) {
+    for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::nextSkippingChildren(*element, this)) {
         if (element->hasTagName(legendTag))
-            invalidateDisabledStateUnder(element);
+            invalidateDisabledStateUnder(*element);
     }
 }
 
@@ -92,7 +91,7 @@
 
 HTMLLegendElement* HTMLFieldSetElement::legend() const
 {
-    for (Element* child = ElementTraversal::firstWithin(this); child; child = ElementTraversal::nextSkippingChildren(child, this)) {
+    for (Element* child = ElementTraversal::firstWithin(*this); child; child = ElementTraversal::nextSkippingChildren(*child, this)) {
         if (child->hasTagName(legendTag))
             return toHTMLLegendElement(child);
     }
@@ -114,7 +113,7 @@
 
     m_associatedElements.clear();
 
-    for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element, this)) {
+    for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element, this)) {
         if (element->hasTagName(objectTag)) {
             m_associatedElements.append(toHTMLObjectElement(element));
             continue;
diff --git a/Source/core/html/HTMLFieldSetElement.h b/Source/core/html/HTMLFieldSetElement.h
index 8b41cdc..e083544 100644
--- a/Source/core/html/HTMLFieldSetElement.h
+++ b/Source/core/html/HTMLFieldSetElement.h
@@ -33,7 +33,7 @@
 
 class HTMLFieldSetElement FINAL : public HTMLFormControlElement {
 public:
-    static PassRefPtr<HTMLFieldSetElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+    static PassRefPtr<HTMLFieldSetElement> create(Document&, HTMLFormElement*);
     HTMLLegendElement* legend() const;
 
     PassRefPtr<HTMLCollection> elements();
@@ -45,7 +45,7 @@
     virtual void disabledAttributeChanged() OVERRIDE;
 
 private:
-    HTMLFieldSetElement(const QualifiedName&, Document&, HTMLFormElement*);
+    HTMLFieldSetElement(Document&, HTMLFormElement*);
 
     virtual bool isEnumeratable() const { return true; }
     virtual bool supportsFocus() const;
@@ -55,7 +55,7 @@
     virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
-    static void invalidateDisabledStateUnder(Element*);
+    static void invalidateDisabledStateUnder(Element&);
     void refreshElementsIfNeeded() const;
 
     mutable Vector<FormAssociatedElement*> m_associatedElements;
diff --git a/Source/core/html/HTMLFieldSetElement.idl b/Source/core/html/HTMLFieldSetElement.idl
index 4fc3409..4e77da9 100644
--- a/Source/core/html/HTMLFieldSetElement.idl
+++ b/Source/core/html/HTMLFieldSetElement.idl
@@ -20,7 +20,7 @@
 interface HTMLFieldSetElement : HTMLElement {
     [Reflect] attribute boolean disabled;
     readonly attribute HTMLFormElement form;
-    [Reflect, TreatNullAs=NullString] attribute DOMString name;
+    [Reflect] attribute DOMString name;
 
     readonly attribute DOMString type;
 
diff --git a/Source/core/html/HTMLFontElement.cpp b/Source/core/html/HTMLFontElement.cpp
index 928b1e9..853eae4 100644
--- a/Source/core/html/HTMLFontElement.cpp
+++ b/Source/core/html/HTMLFontElement.cpp
@@ -38,16 +38,15 @@
 
 using namespace HTMLNames;
 
-HTMLFontElement::HTMLFontElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLFontElement::HTMLFontElement(Document& document)
+    : HTMLElement(fontTag, document)
 {
-    ASSERT(hasTagName(fontTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFontElement> HTMLFontElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLFontElement> HTMLFontElement::create(Document& document)
 {
-    return adoptRef(new HTMLFontElement(tagName, document));
+    return adoptRef(new HTMLFontElement(document));
 }
 
 // http://www.whatwg.org/specs/web-apps/current-work/multipage/rendering.html#fonts-and-colors
diff --git a/Source/core/html/HTMLFontElement.h b/Source/core/html/HTMLFontElement.h
index 7c85f6f..229c5c9 100644
--- a/Source/core/html/HTMLFontElement.h
+++ b/Source/core/html/HTMLFontElement.h
@@ -30,12 +30,12 @@
 
 class HTMLFontElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLFontElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLFontElement> create(Document&);
 
     static bool cssValueFromFontSizeNumber(const String&, CSSValueID&);
 
 private:
-    HTMLFontElement(const QualifiedName&, Document&);
+    explicit HTMLFontElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLFontElement.idl b/Source/core/html/HTMLFontElement.idl
index cdfd429..c0c56d4 100644
--- a/Source/core/html/HTMLFontElement.idl
+++ b/Source/core/html/HTMLFontElement.idl
@@ -19,7 +19,6 @@
 
 interface HTMLFontElement : HTMLElement {
     [Reflect, TreatNullAs=NullString] attribute DOMString color;
-    [Reflect, TreatNullAs=NullString] attribute DOMString face;
-    [Reflect, TreatNullAs=NullString] attribute DOMString size;
+    [Reflect] attribute DOMString face;
+    [Reflect] attribute DOMString size;
 };
-
diff --git a/Source/core/html/HTMLFormControlElement.cpp b/Source/core/html/HTMLFormControlElement.cpp
index 8f1a1d3..b296b84 100644
--- a/Source/core/html/HTMLFormControlElement.cpp
+++ b/Source/core/html/HTMLFormControlElement.cpp
@@ -35,7 +35,7 @@
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/html/ValidityState.h"
 #include "core/html/forms/ValidationMessage.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderTheme.h"
 #include "wtf/Vector.h"
@@ -503,6 +503,11 @@
     return FormAssociatedElement::form();
 }
 
+bool HTMLFormControlElement::isSuccessfulSubmitButton() const
+{
+    return canBeSuccessfulSubmitButton() && !isDisabledFormControl();
+}
+
 bool HTMLFormControlElement::isDefaultButtonForForm() const
 {
     return isSuccessfulSubmitButton() && form() && form()->defaultButton() == this;
diff --git a/Source/core/html/HTMLFormControlElement.h b/Source/core/html/HTMLFormControlElement.h
index e5d6047..c5c24eb 100644
--- a/Source/core/html/HTMLFormControlElement.h
+++ b/Source/core/html/HTMLFormControlElement.h
@@ -81,7 +81,8 @@
     virtual bool appendFormData(FormDataList&, bool) { return false; }
     virtual String resultForDialogSubmit();
 
-    virtual bool isSuccessfulSubmitButton() const { return false; }
+    virtual bool canBeSuccessfulSubmitButton() const { return false; }
+    bool isSuccessfulSubmitButton() const;
     virtual bool isActivatedSubmit() const { return false; }
     virtual void setActivatedSubmit(bool) { }
 
@@ -203,6 +204,12 @@
     return static_cast<const HTMLFormControlElement*>(control);
 }
 
+inline const HTMLFormControlElement& toHTMLFormControlElement(const FormAssociatedElement& control)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(control.isFormControlElement());
+    return static_cast<const HTMLFormControlElement&>(control);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/html/HTMLFormControlsCollection.idl b/Source/core/html/HTMLFormControlsCollection.idl
index e7b757e..f483a67 100644
--- a/Source/core/html/HTMLFormControlsCollection.idl
+++ b/Source/core/html/HTMLFormControlsCollection.idl
@@ -19,8 +19,8 @@
  */
 
 [
-    GenerateIsReachable=ownerNode,
-    DependentLifetime
+    DependentLifetime,
+    GenerateVisitDOMWrapper=ownerNode,
 ] interface HTMLFormControlsCollection : HTMLCollection {
     [ImplementedAs=item] getter Node(unsigned long index);
     [Custom] Node namedItem([Default=Undefined] optional DOMString name);
diff --git a/Source/core/html/HTMLFormElement.cpp b/Source/core/html/HTMLFormElement.cpp
index 585ad3c..296bb55 100644
--- a/Source/core/html/HTMLFormElement.cpp
+++ b/Source/core/html/HTMLFormElement.cpp
@@ -48,8 +48,9 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/rendering/RenderTextControl.h"
 #include "platform/UserGestureIndicator.h"
 
@@ -59,8 +60,8 @@
 
 using namespace HTMLNames;
 
-HTMLFormElement::HTMLFormElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLFormElement::HTMLFormElement(Document& document)
+    : HTMLElement(formTag, document)
     , m_associatedElementsBeforeIndex(0)
     , m_associatedElementsAfterIndex(0)
     , m_wasUserSubmitted(false)
@@ -70,20 +71,13 @@
     , m_wasDemoted(false)
     , m_requestAutocompleteTimer(this, &HTMLFormElement::requestAutocompleteTimerFired)
 {
-    ASSERT(hasTagName(formTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLFormElement> HTMLFormElement::create(Document& document)
 {
     UseCounter::count(document, UseCounter::FormElement);
-    return adoptRef(new HTMLFormElement(formTag, document));
-}
-
-PassRefPtr<HTMLFormElement> HTMLFormElement::create(const QualifiedName& tagName, Document& document)
-{
-    UseCounter::count(document, UseCounter::FormElement);
-    return adoptRef(new HTMLFormElement(tagName, document));
+    return adoptRef(new HTMLFormElement(document));
 }
 
 HTMLFormElement::~HTMLFormElement()
@@ -180,18 +174,27 @@
 void HTMLFormElement::submitImplicitly(Event* event, bool fromImplicitSubmissionTrigger)
 {
     int submissionTriggerCount = 0;
+    bool seenDefaultButton = false;
     for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
         FormAssociatedElement* formAssociatedElement = m_associatedElements[i];
         if (!formAssociatedElement->isFormControlElement())
             continue;
         HTMLFormControlElement* control = toHTMLFormControlElement(formAssociatedElement);
-        if (control->isSuccessfulSubmitButton()) {
-            if (control->renderer()) {
-                control->dispatchSimulatedClick(event);
+        if (!seenDefaultButton && control->canBeSuccessfulSubmitButton()) {
+            if (fromImplicitSubmissionTrigger)
+                seenDefaultButton = true;
+            if (control->isSuccessfulSubmitButton()) {
+                if (control->renderer()) {
+                    control->dispatchSimulatedClick(event);
+                    return;
+                }
+            } else if (fromImplicitSubmissionTrigger) {
+                // Default (submit) button is not activated; no implicit submission.
                 return;
             }
-        } else if (control->canTriggerImplicitSubmission())
+        } else if (control->canTriggerImplicitSubmission()) {
             ++submissionTriggerCount;
+        }
     }
     if (fromImplicitSubmissionTrigger && submissionTriggerCount == 1)
         prepareForSubmission(event);
@@ -398,10 +401,22 @@
         document().frame()->script().executeScriptIfJavaScriptURL(submission->action());
         return;
     }
+
+    Frame* targetFrame = document().frame()->loader().findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
+    if (!targetFrame) {
+        if (!DOMWindow::allowPopUp(document().frame()) && !UserGestureIndicator::processingUserGesture())
+            return;
+        targetFrame = document().frame();
+    } else {
+        submission->clearTarget();
+    }
+    if (!targetFrame->page())
+        return;
+
     submission->setReferrer(document().frame()->loader().outgoingReferrer());
     submission->setOrigin(document().frame()->loader().outgoingOrigin());
 
-    document().frame()->navigationScheduler().scheduleFormSubmission(submission);
+    targetFrame->navigationScheduler().scheduleFormSubmission(submission);
 }
 
 void HTMLFormElement::reset()
@@ -533,20 +548,20 @@
     return left + 1;
 }
 
-unsigned HTMLFormElement::formElementIndex(FormAssociatedElement* associatedElement)
+unsigned HTMLFormElement::formElementIndex(FormAssociatedElement& associatedElement)
 {
-    HTMLElement* associatedHTMLElement = toHTMLElement(associatedElement);
+    HTMLElement& associatedHTMLElement = toHTMLElement(associatedElement);
     // Treats separately the case where this element has the form attribute
     // for performance consideration.
-    if (associatedHTMLElement->fastHasAttribute(formAttr)) {
-        unsigned short position = compareDocumentPosition(associatedHTMLElement);
+    if (associatedHTMLElement.fastHasAttribute(formAttr)) {
+        unsigned short position = compareDocumentPosition(&associatedHTMLElement);
         if (position & DOCUMENT_POSITION_PRECEDING) {
             ++m_associatedElementsBeforeIndex;
             ++m_associatedElementsAfterIndex;
-            return HTMLFormElement::formElementIndexWithFormAttribute(associatedHTMLElement, 0, m_associatedElementsBeforeIndex - 1);
+            return HTMLFormElement::formElementIndexWithFormAttribute(&associatedHTMLElement, 0, m_associatedElementsBeforeIndex - 1);
         }
         if (position & DOCUMENT_POSITION_FOLLOWING && !(position & DOCUMENT_POSITION_CONTAINED_BY))
-            return HTMLFormElement::formElementIndexWithFormAttribute(associatedHTMLElement, m_associatedElementsAfterIndex, m_associatedElements.size());
+            return HTMLFormElement::formElementIndexWithFormAttribute(&associatedHTMLElement, m_associatedElementsAfterIndex, m_associatedElements.size());
     }
 
     // Check for the special case where this element is the very last thing in
@@ -555,7 +570,7 @@
     // that says "add this form element to the end of the array".
     if (ElementTraversal::next(associatedHTMLElement, this)) {
         unsigned i = m_associatedElementsBeforeIndex;
-        for (Element* element = this; element; element = ElementTraversal::next(element, this)) {
+        for (Element* element = this; element; element = ElementTraversal::next(*element, this)) {
             if (element == associatedHTMLElement) {
                 ++m_associatedElementsAfterIndex;
                 return i;
@@ -570,9 +585,9 @@
     return m_associatedElementsAfterIndex++;
 }
 
-void HTMLFormElement::registerFormElement(FormAssociatedElement* e)
+void HTMLFormElement::registerFormElement(FormAssociatedElement& e)
 {
-    m_associatedElements.insert(formElementIndex(e), e);
+    m_associatedElements.insert(formElementIndex(e), &e);
 }
 
 void HTMLFormElement::removeFormElement(FormAssociatedElement* e)
diff --git a/Source/core/html/HTMLFormElement.h b/Source/core/html/HTMLFormElement.h
index b547e58..f9e7695 100644
--- a/Source/core/html/HTMLFormElement.h
+++ b/Source/core/html/HTMLFormElement.h
@@ -47,7 +47,6 @@
 class HTMLFormElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLFormElement> create(Document&);
-    static PassRefPtr<HTMLFormElement> create(const QualifiedName&, Document&);
     virtual ~HTMLFormElement();
 
     PassRefPtr<HTMLCollection> elements();
@@ -65,7 +64,7 @@
     bool shouldAutocomplete() const;
 
     // FIXME: Should rename these two functions to say "form control" or "form-associated element" instead of "form element".
-    void registerFormElement(FormAssociatedElement*);
+    void registerFormElement(FormAssociatedElement&);
     void removeFormElement(FormAssociatedElement*);
 
     void registerImgElement(HTMLImageElement*);
@@ -125,7 +124,7 @@
     void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Node>&);
 
 private:
-    HTMLFormElement(const QualifiedName&, Document&);
+    explicit HTMLFormElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&);
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
@@ -147,7 +146,7 @@
     void scheduleFormSubmission(PassRefPtr<FormSubmission>);
 
     unsigned formElementIndexWithFormAttribute(Element*, unsigned rangeStart, unsigned rangeEnd);
-    unsigned formElementIndex(FormAssociatedElement*);
+    unsigned formElementIndex(FormAssociatedElement&);
 
     // Returns true if the submission should proceed.
     bool validateInteractively(Event*);
diff --git a/Source/core/html/HTMLFormElement.idl b/Source/core/html/HTMLFormElement.idl
index 29a319e..6ba5f41 100644
--- a/Source/core/html/HTMLFormElement.idl
+++ b/Source/core/html/HTMLFormElement.idl
@@ -19,15 +19,15 @@
  */
 
 interface HTMLFormElement : HTMLElement {
-    [Reflect=accept_charset, TreatNullAs=NullString] attribute DOMString acceptCharset;
-    [Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString action;
-    [Reflect, TreatNullAs=NullString] attribute DOMString autocomplete;
-    [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString enctype;
-    [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString encoding;
-    [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString method;
-    [Reflect, TreatNullAs=NullString] attribute DOMString name;
+    [Reflect=accept_charset] attribute DOMString acceptCharset;
+    [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString action;
+    [Reflect] attribute DOMString autocomplete;
+    [CustomElementCallbacks] attribute DOMString enctype;
+    [CustomElementCallbacks] attribute DOMString encoding;
+    [CustomElementCallbacks] attribute DOMString method;
+    [Reflect] attribute DOMString name;
     [Reflect] attribute boolean noValidate;
-    [Reflect, TreatNullAs=NullString] attribute DOMString target;
+    [Reflect] attribute DOMString target;
 
     readonly attribute HTMLCollection elements;
     readonly attribute long length;
diff --git a/Source/core/html/HTMLFrameElement.cpp b/Source/core/html/HTMLFrameElement.cpp
index 38e82ca..218a221 100644
--- a/Source/core/html/HTMLFrameElement.cpp
+++ b/Source/core/html/HTMLFrameElement.cpp
@@ -32,18 +32,17 @@
 
 using namespace HTMLNames;
 
-inline HTMLFrameElement::HTMLFrameElement(const QualifiedName& tagName, Document& document)
-    : HTMLFrameElementBase(tagName, document)
+inline HTMLFrameElement::HTMLFrameElement(Document& document)
+    : HTMLFrameElementBase(frameTag, document)
     , m_frameBorder(true)
     , m_frameBorderSet(false)
 {
-    ASSERT(hasTagName(frameTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFrameElement> HTMLFrameElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLFrameElement> HTMLFrameElement::create(Document& document)
 {
-    return adoptRef(new HTMLFrameElement(tagName, document));
+    return adoptRef(new HTMLFrameElement(document));
 }
 
 bool HTMLFrameElement::rendererIsNeeded(const RenderStyle&)
diff --git a/Source/core/html/HTMLFrameElement.h b/Source/core/html/HTMLFrameElement.h
index 78392b3..72ca103 100644
--- a/Source/core/html/HTMLFrameElement.h
+++ b/Source/core/html/HTMLFrameElement.h
@@ -30,14 +30,14 @@
 
 class HTMLFrameElement FINAL : public HTMLFrameElementBase {
 public:
-    static PassRefPtr<HTMLFrameElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLFrameElement> create(Document&);
 
     bool hasFrameBorder() const { return m_frameBorder; }
 
     bool noResize() const;
 
 private:
-    HTMLFrameElement(const QualifiedName&, Document&);
+    explicit HTMLFrameElement(Document&);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
diff --git a/Source/core/html/HTMLFrameElement.idl b/Source/core/html/HTMLFrameElement.idl
index ff93b07..1ab494c 100644
--- a/Source/core/html/HTMLFrameElement.idl
+++ b/Source/core/html/HTMLFrameElement.idl
@@ -20,27 +20,25 @@
 
 interface HTMLFrameElement : HTMLElement {
 
-    [Reflect, TreatNullAs=NullString] attribute DOMString frameBorder;
-    [Reflect, TreatNullAs=NullString] attribute DOMString longDesc;
+    [Reflect] attribute DOMString frameBorder;
+    [Reflect, URL] attribute DOMString longDesc;
     [Reflect, TreatNullAs=NullString] attribute DOMString marginHeight;
     [Reflect, TreatNullAs=NullString] attribute DOMString marginWidth;
-    [Reflect, TreatNullAs=NullString] attribute DOMString name;
+    [Reflect] attribute DOMString name;
     [Reflect] attribute boolean noResize;
-    [Reflect, TreatNullAs=NullString] attribute DOMString scrolling;
-    [Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
+    [Reflect] attribute DOMString scrolling;
+    [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
 
     // Introduced in DOM Level 2:
-    [CheckSecurityForNode] readonly attribute Document contentDocument;
+    [CheckSecurity=Node] readonly attribute Document contentDocument;
 
     // Extensions
     readonly attribute Window contentWindow;
 
-    [CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
 
-    [TreatNullAs=NullString, CustomSetter] attribute DOMString location;
+    [TreatNullAs=NullString, Custom=Setter, MeasureAs=HTMLFrameElementLocation] attribute DOMString location;
 
     readonly attribute long width;
     readonly attribute long height;
-
 };
-
diff --git a/Source/core/html/HTMLFrameElementBase.cpp b/Source/core/html/HTMLFrameElementBase.cpp
index be9512e..fc6bfb9 100644
--- a/Source/core/html/HTMLFrameElementBase.cpp
+++ b/Source/core/html/HTMLFrameElementBase.cpp
@@ -202,7 +202,8 @@
 
 bool HTMLFrameElementBase::isURLAttribute(const Attribute& attribute) const
 {
-    return attribute.name() == srcAttr || HTMLFrameOwnerElement::isURLAttribute(attribute);
+    return attribute.name() == longdescAttr || attribute.name() == srcAttr
+        || HTMLFrameOwnerElement::isURLAttribute(attribute);
 }
 
 bool HTMLFrameElementBase::isHTMLContentAttribute(const Attribute& attribute) const
diff --git a/Source/core/html/HTMLFrameOwnerElement.cpp b/Source/core/html/HTMLFrameOwnerElement.cpp
index 45e8831..20774db 100644
--- a/Source/core/html/HTMLFrameOwnerElement.cpp
+++ b/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -21,6 +21,7 @@
 #include "config.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/loader/FrameLoader.h"
@@ -29,8 +30,8 @@
 #include "core/frame/FrameView.h"
 #include "core/rendering/RenderPart.h"
 #include "core/svg/SVGDocument.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
 
 namespace WebCore {
 
@@ -112,13 +113,11 @@
     return m_contentFrame && HTMLElement::isKeyboardFocusable();
 }
 
-SVGDocument* HTMLFrameOwnerElement::getSVGDocument(ExceptionState& es) const
+SVGDocument* HTMLFrameOwnerElement::getSVGDocument(ExceptionState& exceptionState) const
 {
     Document* doc = contentDocument();
     if (doc && doc->isSVGDocument())
         return toSVGDocument(doc);
-    // Spec: http://www.w3.org/TR/SVG/struct.html#InterfaceGetSVGDocument
-    es.throwUninformativeAndGenericDOMException(NotSupportedError);
     return 0;
 }
 
diff --git a/Source/core/html/HTMLFrameSetElement.cpp b/Source/core/html/HTMLFrameSetElement.cpp
index e699491..b35a5bb 100644
--- a/Source/core/html/HTMLFrameSetElement.cpp
+++ b/Source/core/html/HTMLFrameSetElement.cpp
@@ -42,8 +42,8 @@
 
 using namespace HTMLNames;
 
-HTMLFrameSetElement::HTMLFrameSetElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLFrameSetElement::HTMLFrameSetElement(Document& document)
+    : HTMLElement(framesetTag, document)
     , m_border(6)
     , m_borderSet(false)
     , m_borderColorSet(false)
@@ -51,14 +51,13 @@
     , m_frameborderSet(false)
     , m_noresize(false)
 {
-    ASSERT(hasTagName(framesetTag));
     ScriptWrappable::init(this);
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<HTMLFrameSetElement> HTMLFrameSetElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLFrameSetElement> HTMLFrameSetElement::create(Document& document)
 {
-    return adoptRef(new HTMLFrameSetElement(tagName, document));
+    return adoptRef(new HTMLFrameSetElement(document));
 }
 
 bool HTMLFrameSetElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLFrameSetElement.h b/Source/core/html/HTMLFrameSetElement.h
index 2815c1a..3138495 100644
--- a/Source/core/html/HTMLFrameSetElement.h
+++ b/Source/core/html/HTMLFrameSetElement.h
@@ -31,7 +31,7 @@
 
 class HTMLFrameSetElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLFrameSetElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLFrameSetElement> create(Document&);
 
     bool hasFrameBorder() const { return m_frameborder; }
     bool noResize() const { return m_noresize; }
@@ -58,7 +58,7 @@
 #endif
 
 private:
-    HTMLFrameSetElement(const QualifiedName&, Document&);
+    explicit HTMLFrameSetElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLFrameSetElement.idl b/Source/core/html/HTMLFrameSetElement.idl
index b1ec56f..38a5f21 100644
--- a/Source/core/html/HTMLFrameSetElement.idl
+++ b/Source/core/html/HTMLFrameSetElement.idl
@@ -20,8 +20,8 @@
 
 interface HTMLFrameSetElement : HTMLElement {
     [ImplementedAs=anonymousNamedGetter, OverrideBuiltins, NotEnumerable] getter Window (DOMString name);
-    [Reflect, TreatNullAs=NullString] attribute DOMString cols;
-    [Reflect, TreatNullAs=NullString] attribute DOMString rows;
+    [Reflect] attribute DOMString cols;
+    [Reflect] attribute DOMString rows;
 
     [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
 
diff --git a/Source/core/html/HTMLHRElement.cpp b/Source/core/html/HTMLHRElement.cpp
index a71a4d3..7a6edf8 100644
--- a/Source/core/html/HTMLHRElement.cpp
+++ b/Source/core/html/HTMLHRElement.cpp
@@ -33,21 +33,15 @@
 
 using namespace HTMLNames;
 
-HTMLHRElement::HTMLHRElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLHRElement::HTMLHRElement(Document& document)
+    : HTMLElement(hrTag, document)
 {
-    ASSERT(hasTagName(hrTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLHRElement> HTMLHRElement::create(Document& document)
 {
-    return adoptRef(new HTMLHRElement(hrTag, document));
-}
-
-PassRefPtr<HTMLHRElement> HTMLHRElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLHRElement(tagName, document));
+    return adoptRef(new HTMLHRElement(document));
 }
 
 bool HTMLHRElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLHRElement.h b/Source/core/html/HTMLHRElement.h
index 7fc185d..ec5bcb0 100644
--- a/Source/core/html/HTMLHRElement.h
+++ b/Source/core/html/HTMLHRElement.h
@@ -30,12 +30,11 @@
 class HTMLHRElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLHRElement> create(Document&);
-    static PassRefPtr<HTMLHRElement> create(const QualifiedName&, Document&);
 
     virtual bool canContainRangeEndPoint() const { return hasChildNodes(); }
 
 private:
-    HTMLHRElement(const QualifiedName&, Document&);
+    explicit HTMLHRElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLHeadElement.cpp b/Source/core/html/HTMLHeadElement.cpp
index a0afa30..8a25aa6 100644
--- a/Source/core/html/HTMLHeadElement.cpp
+++ b/Source/core/html/HTMLHeadElement.cpp
@@ -30,21 +30,15 @@
 
 using namespace HTMLNames;
 
-HTMLHeadElement::HTMLHeadElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLHeadElement::HTMLHeadElement(Document& document)
+    : HTMLElement(headTag, document)
 {
-    ASSERT(hasTagName(headTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(Document& document)
 {
-    return adoptRef(new HTMLHeadElement(headTag, document));
-}
-
-PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLHeadElement(tagName, document));
+    return adoptRef(new HTMLHeadElement(document));
 }
 
 }
diff --git a/Source/core/html/HTMLHeadElement.h b/Source/core/html/HTMLHeadElement.h
index 2330124..7abcac7 100644
--- a/Source/core/html/HTMLHeadElement.h
+++ b/Source/core/html/HTMLHeadElement.h
@@ -31,10 +31,9 @@
 class HTMLHeadElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLHeadElement> create(Document&);
-    static PassRefPtr<HTMLHeadElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLHeadElement(const QualifiedName&, Document&);
+    explicit HTMLHeadElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLHeadElement, hasTagName(HTMLNames::headTag));
diff --git a/Source/core/html/HTMLHtmlElement.cpp b/Source/core/html/HTMLHtmlElement.cpp
index fe9f0ac..e4a56c9 100644
--- a/Source/core/html/HTMLHtmlElement.cpp
+++ b/Source/core/html/HTMLHtmlElement.cpp
@@ -36,21 +36,15 @@
 
 using namespace HTMLNames;
 
-HTMLHtmlElement::HTMLHtmlElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLHtmlElement::HTMLHtmlElement(Document& document)
+    : HTMLElement(htmlTag, document)
 {
-    ASSERT(hasTagName(htmlTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(Document& document)
 {
-    return adoptRef(new HTMLHtmlElement(htmlTag, document));
-}
-
-PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLHtmlElement(tagName, document));
+    return adoptRef(new HTMLHtmlElement(document));
 }
 
 bool HTMLHtmlElement::isURLAttribute(const Attribute& attribute) const
diff --git a/Source/core/html/HTMLHtmlElement.h b/Source/core/html/HTMLHtmlElement.h
index 196cd55..4976aac 100644
--- a/Source/core/html/HTMLHtmlElement.h
+++ b/Source/core/html/HTMLHtmlElement.h
@@ -31,12 +31,11 @@
 class HTMLHtmlElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLHtmlElement> create(Document&);
-    static PassRefPtr<HTMLHtmlElement> create(const QualifiedName&, Document&);
 
     void insertedByParser();
 
 private:
-    HTMLHtmlElement(const QualifiedName&, Document&);
+    explicit HTMLHtmlElement(Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 };
diff --git a/Source/core/html/HTMLIFrameElement.cpp b/Source/core/html/HTMLIFrameElement.cpp
index 2137e76..016fba4 100644
--- a/Source/core/html/HTMLIFrameElement.cpp
+++ b/Source/core/html/HTMLIFrameElement.cpp
@@ -34,18 +34,17 @@
 
 using namespace HTMLNames;
 
-inline HTMLIFrameElement::HTMLIFrameElement(const QualifiedName& tagName, Document& document)
-    : HTMLFrameElementBase(tagName, document)
+inline HTMLIFrameElement::HTMLIFrameElement(Document& document)
+    : HTMLFrameElementBase(iframeTag, document)
     , m_didLoadNonEmptyDocument(false)
 {
-    ASSERT(hasTagName(iframeTag));
     ScriptWrappable::init(this);
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<HTMLIFrameElement> HTMLIFrameElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLIFrameElement> HTMLIFrameElement::create(Document& document)
 {
-    return adoptRef(new HTMLIFrameElement(tagName, document));
+    return adoptRef(new HTMLIFrameElement(document));
 }
 
 bool HTMLIFrameElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLIFrameElement.h b/Source/core/html/HTMLIFrameElement.h
index 3ce7371..eab2678 100644
--- a/Source/core/html/HTMLIFrameElement.h
+++ b/Source/core/html/HTMLIFrameElement.h
@@ -30,12 +30,12 @@
 
 class HTMLIFrameElement FINAL : public HTMLFrameElementBase {
 public:
-    static PassRefPtr<HTMLIFrameElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLIFrameElement> create(Document&);
 
     bool shouldDisplaySeamlessly() const;
 
 private:
-    HTMLIFrameElement(const QualifiedName&, Document&);
+    explicit HTMLIFrameElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLIFrameElement.idl b/Source/core/html/HTMLIFrameElement.idl
index 9fcf3a9..d8a8a8e 100644
--- a/Source/core/html/HTMLIFrameElement.idl
+++ b/Source/core/html/HTMLIFrameElement.idl
@@ -19,26 +19,25 @@
  */
 
 interface HTMLIFrameElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString align;
-    [Reflect, TreatNullAs=NullString] attribute DOMString frameBorder;
-    [Reflect, TreatNullAs=NullString] attribute DOMString height;
-    [Reflect, TreatNullAs=NullString] attribute DOMString longDesc;
+    [Reflect] attribute DOMString align;
+    [Reflect] attribute DOMString frameBorder;
+    [Reflect] attribute DOMString height;
+    [Reflect, URL] attribute DOMString longDesc;
     [Reflect, TreatNullAs=NullString] attribute DOMString marginHeight;
     [Reflect, TreatNullAs=NullString] attribute DOMString marginWidth;
-    [Reflect, TreatNullAs=NullString] attribute DOMString name;
+    [Reflect] attribute DOMString name;
     [Reflect, TreatNullAs=NullString] attribute DOMString sandbox;
     [Reflect, RuntimeEnabled=SeamlessIFrames] attribute boolean seamless;
-    [Reflect, TreatNullAs=NullString] attribute DOMString scrolling;
-    [Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
-    [Reflect, TreatNullAs=NullString] attribute DOMString srcdoc;
-    [Reflect, TreatNullAs=NullString] attribute DOMString width;
+    [Reflect] attribute DOMString scrolling;
+    [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
+    [Reflect] attribute DOMString srcdoc;
+    [Reflect] attribute DOMString width;
 
     // Introduced in DOM Level 2:
-    [CheckSecurityForNode] readonly attribute Document contentDocument;
+    [CheckSecurity=Node] readonly attribute Document contentDocument;
 
     // Extensions
     readonly attribute Window contentWindow;
 
-    [CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
 };
-
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index 6a96bc1..97bb101 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -42,14 +42,13 @@
 
 using namespace HTMLNames;
 
-HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
-    : HTMLElement(tagName, document)
+HTMLImageElement::HTMLImageElement(Document& document, HTMLFormElement* form)
+    : HTMLElement(imgTag, document)
     , m_imageLoader(this)
     , m_form(form)
     , m_compositeOperator(CompositeSourceOver)
     , m_imageDevicePixelRatio(1.0f)
 {
-    ASSERT(hasTagName(imgTag));
     ScriptWrappable::init(this);
     if (form)
         form->registerImgElement(this);
@@ -57,12 +56,12 @@
 
 PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document& document)
 {
-    return adoptRef(new HTMLImageElement(imgTag, document));
+    return adoptRef(new HTMLImageElement(document));
 }
 
-PassRefPtr<HTMLImageElement> HTMLImageElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document& document, HTMLFormElement* form)
 {
-    return adoptRef(new HTMLImageElement(tagName, document, form));
+    return adoptRef(new HTMLImageElement(document, form));
 }
 
 HTMLImageElement::~HTMLImageElement()
@@ -73,7 +72,7 @@
 
 PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document& document, int width, int height)
 {
-    RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(imgTag, document));
+    RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(document));
     if (width)
         image->setWidth(width);
     if (height)
@@ -310,7 +309,7 @@
 
 void HTMLImageElement::setHeight(int value)
 {
-    setAttribute(heightAttr, String::number(value));
+    setIntegralAttribute(heightAttr, value);
 }
 
 KURL HTMLImageElement::src() const
@@ -325,7 +324,7 @@
 
 void HTMLImageElement::setWidth(int value)
 {
-    setAttribute(widthAttr, String::number(value));
+    setIntegralAttribute(widthAttr, value);
 }
 
 int HTMLImageElement::x() const
diff --git a/Source/core/html/HTMLImageElement.h b/Source/core/html/HTMLImageElement.h
index 6ae7f62..d39fb54 100644
--- a/Source/core/html/HTMLImageElement.h
+++ b/Source/core/html/HTMLImageElement.h
@@ -36,7 +36,7 @@
     friend class HTMLFormElement;
 public:
     static PassRefPtr<HTMLImageElement> create(Document&);
-    static PassRefPtr<HTMLImageElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+    static PassRefPtr<HTMLImageElement> create(Document&, HTMLFormElement*);
     static PassRefPtr<HTMLImageElement> createForJSConstructor(Document&, int width, int height);
 
     virtual ~HTMLImageElement();
@@ -82,7 +82,7 @@
     virtual const AtomicString imageSourceURL() const OVERRIDE;
 
 protected:
-    HTMLImageElement(const QualifiedName&, Document&, HTMLFormElement* = 0);
+    explicit HTMLImageElement(Document&, HTMLFormElement* = 0);
 
     virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
 
diff --git a/Source/core/html/HTMLImport.cpp b/Source/core/html/HTMLImport.cpp
index 9b1230d..7859d6d 100644
--- a/Source/core/html/HTMLImport.cpp
+++ b/Source/core/html/HTMLImport.cpp
@@ -52,19 +52,16 @@
 
 void HTMLImport::appendChild(HTMLImport* child)
 {
-    ASSERT(child->parent() == this);
-    ASSERT(!child->hasChildren());
-
     if (isBlocked())
         child->block();
-    m_children.append(child);
+    TreeNode<HTMLImport>::appendChild(child);
     blockAfter(child);
 }
 
 bool HTMLImport::areChilrenLoaded() const
 {
-    for (size_t i = 0; i < m_children.size(); ++i) {
-        if (!m_children[i]->isLoaded())
+    for (HTMLImport* child = firstChild(); child; child = child->next()) {
+        if (!child->isLoaded())
             return false;
     }
 
@@ -77,8 +74,7 @@
     if (!parent)
         return true;
 
-    for (size_t i = 0; i < parent->m_children.size(); ++i) {
-        HTMLImport* sibling = parent->m_children[i];
+    for (HTMLImport* sibling = parent->firstChild(); sibling; sibling = sibling->next()) {
         if (sibling == this)
             break;
         if (!sibling->isLoaded())
@@ -117,8 +113,8 @@
     ASSERT(import->isBlocked() || import->areChilrenLoaded());
 
     if (import->isBlocked()) {
-        for (size_t i = 0; i < import->m_children.size(); ++i) {
-            if (!unblock(import->m_children[i]))
+        for (HTMLImport* child = import->firstChild(); child; child = child->next()) {
+            if (!unblock(child))
                 return false;
         }
     }
@@ -129,17 +125,15 @@
 
 void HTMLImport::block(HTMLImport* import)
 {
-    import->block();
-    for (size_t i = 0; i < import->m_children.size(); ++i)
-        block(import->m_children[i]);
+    for (HTMLImport* child = import; child; child = traverseNext(child, import))
+        child->block();
 }
 
 void HTMLImport::blockAfter(HTMLImport* child)
 {
     ASSERT(child->parent() == this);
 
-    for (size_t i = 0; i < m_children.size(); ++i) {
-        HTMLImport* sibling = m_children[m_children.size() - i - 1];
+    for (HTMLImport* sibling = lastChild(); sibling; sibling = sibling->previous()) {
         if (sibling == child)
             break;
         HTMLImport::block(sibling);
diff --git a/Source/core/html/HTMLImport.h b/Source/core/html/HTMLImport.h
index 215dad9..d6f9837 100644
--- a/Source/core/html/HTMLImport.h
+++ b/Source/core/html/HTMLImport.h
@@ -31,6 +31,7 @@
 #ifndef HTMLImport_h
 #define HTMLImport_h
 
+#include "wtf/TreeNode.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -41,7 +42,7 @@
 class HTMLImportRoot;
 class HTMLImportsController;
 
-class HTMLImport {
+class HTMLImport : public TreeNode<HTMLImport> {
 public:
     static bool unblock(HTMLImport*);
 
@@ -56,7 +57,6 @@
     void appendChild(HTMLImport*);
 
     virtual HTMLImportRoot* root() = 0;
-    virtual HTMLImport* parent() const = 0;
     virtual Document* document() const = 0;
     virtual void wasDetachedFromDocument() = 0;
     virtual void didFinishParsing() = 0;
@@ -77,9 +77,7 @@
 
     bool arePredecessorsLoaded() const;
     bool areChilrenLoaded() const;
-    bool hasChildren() const { return !m_children.isEmpty(); }
 
-    Vector<HTMLImport*> m_children;
     bool m_blocked; // If any of decendants or predecessors is in processing, it is blocked.
 };
 
diff --git a/Source/core/html/HTMLImportLoader.cpp b/Source/core/html/HTMLImportLoader.cpp
index 3f8ca2f..cfb103e 100644
--- a/Source/core/html/HTMLImportLoader.cpp
+++ b/Source/core/html/HTMLImportLoader.cpp
@@ -41,9 +41,8 @@
 
 namespace WebCore {
 
-HTMLImportLoader::HTMLImportLoader(HTMLImport* parent, const KURL& url)
-    : m_parent(parent)
-    , m_state(StateLoading)
+HTMLImportLoader::HTMLImportLoader(const KURL& url)
+    : m_state(StateLoading)
     , m_url(url)
 {
 }
@@ -51,7 +50,6 @@
 HTMLImportLoader::~HTMLImportLoader()
 {
     // importDestroyed() should be called before the destruction.
-    ASSERT(!m_parent);
     ASSERT(!m_importedDocument);
     if (m_resource)
         m_resource->removeClient(this);
@@ -113,7 +111,7 @@
 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()))
+    if (!parent()->document()->fetcher()->canAccess(m_resource.get(), PotentiallyCORSEnabled))
         return StateError;
 
     DocumentInit init = DocumentInit(response.url(), 0, root()->document()->contextDocument(), this)
@@ -127,7 +125,7 @@
 
 HTMLImportLoader::State HTMLImportLoader::finishWriting()
 {
-    if (!m_parent)
+    if (!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.
@@ -139,7 +137,7 @@
 
 HTMLImportLoader::State HTMLImportLoader::finishParsing()
 {
-    if (!m_parent)
+    if (!parent())
         return StateError;
     return StateReady;
 }
@@ -167,19 +165,15 @@
 
 void HTMLImportLoader::importDestroyed()
 {
-    m_parent = 0;
+    if (parent())
+        parent()->removeChild(this);
     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;
+    return parent() ? parent()->root() : 0;
 }
 
 Document* HTMLImportLoader::document() const
diff --git a/Source/core/html/HTMLImportLoader.h b/Source/core/html/HTMLImportLoader.h
index 5406049..53aca45 100644
--- a/Source/core/html/HTMLImportLoader.h
+++ b/Source/core/html/HTMLImportLoader.h
@@ -34,7 +34,7 @@
 #include "core/fetch/RawResource.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/html/HTMLImport.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
@@ -52,7 +52,7 @@
         StateReady
     };
 
-    HTMLImportLoader(HTMLImport*, const KURL&);
+    HTMLImportLoader(const KURL&);
     virtual ~HTMLImportLoader();
 
     Document* importedDocument() const;
@@ -67,7 +67,6 @@
 
     // HTMLImport
     virtual HTMLImportRoot* root() OVERRIDE;
-    virtual HTMLImport* parent() const OVERRIDE;
     virtual Document* document() const OVERRIDE;
     virtual void wasDetachedFromDocument() OVERRIDE;
     virtual void didFinishParsing() OVERRIDE;
@@ -87,7 +86,6 @@
     void setState(State);
     void didFinish();
 
-    HTMLImport* m_parent;
     Vector<HTMLImportLoaderClient*> m_clients;
     State m_state;
     KURL m_url;
diff --git a/Source/core/html/HTMLImportsController.cpp b/Source/core/html/HTMLImportsController.cpp
index 121e71a..a2aae84 100644
--- a/Source/core/html/HTMLImportsController.cpp
+++ b/Source/core/html/HTMLImportsController.cpp
@@ -73,12 +73,12 @@
     if (RefPtr<HTMLImportLoader> found = findLinkFor(request.url()))
         return found.release();
 
-    request.setPotentiallyCrossOriginEnabled(securityOrigin(), DoNotAllowStoredCredentials);
+    request.setCrossOriginAccessControl(securityOrigin(), DoNotAllowStoredCredentials);
     ResourcePtr<RawResource> resource = parent->document()->fetcher()->fetchImport(request);
     if (!resource)
         return 0;
 
-    RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(parent, request.url()));
+    RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(request.url()));
     parent->appendChild(loader.get());
     m_imports.append(loader);
 
@@ -119,11 +119,6 @@
     return this;
 }
 
-HTMLImport* HTMLImportsController::parent() const
-{
-    return 0;
-}
-
 Document* HTMLImportsController::document() const
 {
     return m_master;
diff --git a/Source/core/html/HTMLImportsController.h b/Source/core/html/HTMLImportsController.h
index c11ebed..7cf22c7 100644
--- a/Source/core/html/HTMLImportsController.h
+++ b/Source/core/html/HTMLImportsController.h
@@ -58,7 +58,6 @@
 
     // HTMLImport
     virtual HTMLImportRoot* root() OVERRIDE;
-    virtual HTMLImport* parent() const OVERRIDE;
     virtual Document* document() const OVERRIDE;
     virtual void wasDetachedFromDocument() OVERRIDE;
     virtual void didFinishParsing() OVERRIDE;
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index cf8ff23..d467376 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -32,6 +32,7 @@
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/accessibility/AXObjectCache.h"
@@ -41,8 +42,8 @@
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
+#include "core/editing/SpellChecker.h"
 #include "core/events/BeforeTextInsertedEvent.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/events/MouseEvent.h"
@@ -64,7 +65,10 @@
 #include "core/html/forms/SearchInputType.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/ShadowElementNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/page/Page.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderTheme.h"
 #include "platform/DateTimeChooser.h"
@@ -99,8 +103,8 @@
 const int defaultSize = 20;
 const int maxSavedResults = 256;
 
-HTMLInputElement::HTMLInputElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
-    : HTMLTextFormControlElement(tagName, document, form)
+HTMLInputElement::HTMLInputElement(Document& document, HTMLFormElement* form, bool createdByParser)
+    : HTMLTextFormControlElement(inputTag, document, form)
     , m_size(defaultSize)
     , m_maxLength(maximumLength)
     , m_maxResults(-1)
@@ -120,16 +124,15 @@
     , m_inputType(InputType::createText(*this))
     , m_inputTypeView(m_inputType)
 {
-    ASSERT(hasTagName(inputTag) || hasTagName(isindexTag));
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     setHasCustomStyleCallbacks();
 #endif
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLInputElement> HTMLInputElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLInputElement> HTMLInputElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
 {
-    RefPtr<HTMLInputElement> inputElement = adoptRef(new HTMLInputElement(tagName, document, form, createdByParser));
+    RefPtr<HTMLInputElement> inputElement = adoptRef(new HTMLInputElement(document, form, createdByParser));
     inputElement->ensureUserAgentShadowRoot();
     return inputElement.release();
 }
@@ -141,16 +144,18 @@
     return m_imageLoader.get();
 }
 
-void HTMLInputElement::didAddUserAgentShadowRoot(ShadowRoot*)
+void HTMLInputElement::didAddUserAgentShadowRoot(ShadowRoot&)
 {
-    m_inputType->createShadowSubtree();
+    m_inputTypeView->createShadowSubtree();
 }
 
 void HTMLInputElement::didAddShadowRoot(ShadowRoot& root)
 {
     if (!root.isOldestAuthorShadowRoot())
         return;
+    m_inputTypeView->destroyShadowSubtree();
     m_inputTypeView = InputTypeView::create(*this);
+    lazyReattachIfAttached();
 }
 
 HTMLInputElement::~HTMLInputElement()
@@ -297,14 +302,14 @@
     return m_inputType->findClosestTickMarkValue(value);
 }
 
-void HTMLInputElement::stepUp(int n, ExceptionState& es)
+void HTMLInputElement::stepUp(int n, ExceptionState& exceptionState)
 {
-    m_inputType->stepUp(n, es);
+    m_inputType->stepUp(n, exceptionState);
 }
 
-void HTMLInputElement::stepDown(int n, ExceptionState& es)
+void HTMLInputElement::stepDown(int n, ExceptionState& exceptionState)
 {
-    m_inputType->stepUp(-n, es);
+    m_inputType->stepUp(-n, exceptionState);
 }
 
 void HTMLInputElement::blur()
@@ -351,7 +356,7 @@
         return;
 
     if (Frame* frame = document().frame())
-        frame->editor().textAreaOrTextFieldDidBeginEditing(this);
+        frame->spellChecker().didBeginEditing(this);
 }
 
 void HTMLInputElement::endEditing()
@@ -359,8 +364,11 @@
     if (!isTextField())
         return;
 
-    if (Frame* frame = document().frame())
-        frame->editor().textFieldDidEndEditing(this);
+    if (Frame* frame = document().frame()) {
+        frame->spellChecker().didEndEditingOnTextField(this);
+        if (Page* page = frame->page())
+            page->chrome().client().didEndEditingOnTextField(*this);
+    }
 }
 
 bool HTMLInputElement::shouldUseInputMethod()
@@ -413,7 +421,7 @@
     bool didStoreValue = m_inputType->storesValueSeparateFromAttribute();
     bool didRespectHeightAndWidth = m_inputType->shouldRespectHeightAndWidthAttributes();
 
-    m_inputType->destroyShadowSubtree();
+    m_inputTypeView->destroyShadowSubtree();
     lazyReattachIfAttached();
 
     m_inputType = newType.release();
@@ -421,7 +429,7 @@
         m_inputTypeView = InputTypeView::create(*this);
     else
         m_inputTypeView = m_inputType;
-    m_inputType->createShadowSubtree();
+    m_inputTypeView->createShadowSubtree();
 
     bool hasTouchEventHandler = m_inputTypeView->hasTouchEventHandler();
     if (hasTouchEventHandler != m_hasTouchEventHandler) {
@@ -447,7 +455,7 @@
         updateValueIfNeeded();
 
     setFormControlValueMatchesRenderer(false);
-    m_inputType->updateInnerTextValue();
+    m_inputTypeView->updateView();
 
     m_wasModifiedByUser = false;
 
@@ -514,73 +522,73 @@
     return isTextField();
 }
 
-int HTMLInputElement::selectionStartForBinding(ExceptionState& es) const
+int HTMLInputElement::selectionStartForBinding(ExceptionState& exceptionState) const
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("selectionStart", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return 0;
     }
     return HTMLTextFormControlElement::selectionStart();
 }
 
-int HTMLInputElement::selectionEndForBinding(ExceptionState& es) const
+int HTMLInputElement::selectionEndForBinding(ExceptionState& exceptionState) const
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("selectionEnd", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return 0;
     }
     return HTMLTextFormControlElement::selectionEnd();
 }
 
-String HTMLInputElement::selectionDirectionForBinding(ExceptionState& es) const
+String HTMLInputElement::selectionDirectionForBinding(ExceptionState& exceptionState) const
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("selectionDirection", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return String();
     }
     return HTMLTextFormControlElement::selectionDirection();
 }
 
-void HTMLInputElement::setSelectionStartForBinding(int start, ExceptionState& es)
+void HTMLInputElement::setSelectionStartForBinding(int start, ExceptionState& exceptionState)
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("selectionStart", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return;
     }
     HTMLTextFormControlElement::setSelectionStart(start);
 }
 
-void HTMLInputElement::setSelectionEndForBinding(int end, ExceptionState& es)
+void HTMLInputElement::setSelectionEndForBinding(int end, ExceptionState& exceptionState)
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("selectionEnd", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return;
     }
     HTMLTextFormControlElement::setSelectionEnd(end);
 }
 
-void HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& es)
+void HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& exceptionState)
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("selectionDirection", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return;
     }
     HTMLTextFormControlElement::setSelectionDirection(direction);
 }
 
-void HTMLInputElement::setSelectionRangeForBinding(int start, int end, ExceptionState& es)
+void HTMLInputElement::setSelectionRangeForBinding(int start, int end, ExceptionState& exceptionState)
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("selectionRange", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return;
     }
     HTMLTextFormControlElement::setSelectionRange(start, end);
 }
 
-void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState& es)
+void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState& exceptionState)
 {
     if (!canHaveSelection()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("selectionRange", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return;
     }
     HTMLTextFormControlElement::setSelectionRange(start, end, direction);
@@ -730,9 +738,9 @@
             // styles depending on whether the speech button is visible or
             // not. So we reset the whole thing and recreate to get the right
             // styles and layout.
-            m_inputType->destroyShadowSubtree();
+            m_inputTypeView->destroyShadowSubtree();
             lazyReattachIfAttached();
-            m_inputType->createShadowSubtree();
+            m_inputTypeView->createShadowSubtree();
             setFormControlValueMatchesRenderer(false);
         }
         UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
@@ -777,7 +785,7 @@
 
     HTMLTextFormControlElement::attach(context);
 
-    m_inputTypeView->attach();
+    m_inputTypeView->startResourceLoading();
     m_inputType->countUsage();
 
     if (document().focusedElement() == this)
@@ -788,7 +796,7 @@
 {
     HTMLTextFormControlElement::detach(context);
     setFormControlValueMatchesRenderer(false);
-    m_inputType->detach();
+    m_inputTypeView->closePopupView();
 }
 
 String HTMLInputElement::altText() const
@@ -803,15 +811,13 @@
     if (alt.isNull())
         alt = getAttribute(valueAttr);
     if (alt.isEmpty())
-        alt = locale().queryString(WebKit::WebLocalizedString::InputElementAltText);
+        alt = locale().queryString(blink::WebLocalizedString::InputElementAltText);
     return alt;
 }
 
-bool HTMLInputElement::isSuccessfulSubmitButton() const
+bool HTMLInputElement::canBeSuccessfulSubmitButton() const
 {
-    // HTML spec says that buttons must have names to be considered successful.
-    // However, other browsers do not impose this constraint. So we do not.
-    return !isDisabledFormControl() && m_inputType->canBeSuccessfulSubmitButton();
+    return m_inputType->canBeSuccessfulSubmitButton();
 }
 
 bool HTMLInputElement::isActivatedSubmit() const
@@ -926,7 +932,7 @@
     HTMLTextFormControlElement::copyNonAttributePropertiesFromElement(source);
 
     setFormControlValueMatchesRenderer(false);
-    m_inputTypeView->updateInnerTextValue();
+    m_inputTypeView->updateView();
 }
 
 String HTMLInputElement::value() const
@@ -974,7 +980,7 @@
     setFormControlValueMatchesRenderer(false);
     m_suggestedValue = sanitizeValue(value);
     setNeedsStyleRecalc();
-    m_inputType->updateInnerTextValue();
+    m_inputTypeView->updateView();
 }
 
 void HTMLInputElement::setEditingValue(const String& value)
@@ -993,10 +999,10 @@
     dispatchInputEvent();
 }
 
-void HTMLInputElement::setValue(const String& value, ExceptionState& es, TextFieldEventBehavior eventBehavior)
+void HTMLInputElement::setValue(const String& value, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
 {
     if (isFileUpload() && !value.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("value", "HTMLInputElement", "This input element accepts a filename, which may only be programatically set to the empty string."));
         return;
     }
     setValue(value, eventBehavior);
@@ -1039,9 +1045,9 @@
     return m_inputType->valueAsDate();
 }
 
-void HTMLInputElement::setValueAsDate(double value, ExceptionState& es)
+void HTMLInputElement::setValueAsDate(double value, ExceptionState& exceptionState)
 {
-    m_inputType->setValueAsDate(value, es);
+    m_inputType->setValueAsDate(value, exceptionState);
 }
 
 double HTMLInputElement::valueAsNumber() const
@@ -1049,13 +1055,13 @@
     return m_inputType->valueAsDouble();
 }
 
-void HTMLInputElement::setValueAsNumber(double newValue, ExceptionState& es, TextFieldEventBehavior eventBehavior)
+void HTMLInputElement::setValueAsNumber(double newValue, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
 {
     if (!std::isfinite(newValue)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("valueAsNumber", "HTMLInputElement", ExceptionMessages::notAFiniteNumber(newValue)));
         return;
     }
-    m_inputType->setValueAsDouble(newValue, eventBehavior, es);
+    m_inputType->setValueAsDouble(newValue, eventBehavior, exceptionState);
 }
 
 void HTMLInputElement::setValueFromRenderer(const String& value)
@@ -1284,12 +1290,12 @@
     return m_maxLength;
 }
 
-void HTMLInputElement::setMaxLength(int maxLength, ExceptionState& es)
+void HTMLInputElement::setMaxLength(int maxLength, ExceptionState& exceptionState)
 {
     if (maxLength < 0)
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("maxLength", "HTMLInputElement", "The value provided (" + String::number(maxLength) + ") is negative."));
     else
-        setAttribute(maxlengthAttr, String::number(maxLength));
+        setIntegralAttribute(maxlengthAttr, maxLength);
 }
 
 bool HTMLInputElement::multiple() const
@@ -1299,13 +1305,13 @@
 
 void HTMLInputElement::setSize(unsigned size)
 {
-    setAttribute(sizeAttr, String::number(size));
+    setUnsignedIntegralAttribute(sizeAttr, size);
 }
 
-void HTMLInputElement::setSize(unsigned size, ExceptionState& es)
+void HTMLInputElement::setSize(unsigned size, ExceptionState& exceptionState)
 {
     if (!size)
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("size", "HTMLInputElement", "The value provided is 0, which is an invalid size."));
     else
         setSize(size);
 }
@@ -1761,12 +1767,12 @@
 
 void HTMLInputElement::setHeight(unsigned height)
 {
-    setAttribute(heightAttr, String::number(height));
+    setUnsignedIntegralAttribute(heightAttr, height);
 }
 
 void HTMLInputElement::setWidth(unsigned width)
 {
-    setAttribute(widthAttr, String::number(width));
+    setUnsignedIntegralAttribute(widthAttr, width);
 }
 
 PassOwnPtr<ListAttributeTargetObserver> ListAttributeTargetObserver::create(const AtomicString& id, HTMLInputElement* element)
@@ -1785,24 +1791,24 @@
     m_element->listAttributeTargetChanged();
 }
 
-void HTMLInputElement::setRangeText(const String& replacement, ExceptionState& es)
+void HTMLInputElement::setRangeText(const String& replacement, ExceptionState& exceptionState)
 {
     if (!m_inputType->supportsSelectionAPI()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setRangeText", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return;
     }
 
-    HTMLTextFormControlElement::setRangeText(replacement, es);
+    HTMLTextFormControlElement::setRangeText(replacement, exceptionState);
 }
 
-void HTMLInputElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& es)
+void HTMLInputElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& exceptionState)
 {
     if (!m_inputType->supportsSelectionAPI()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setRangeText", "HTMLInputElement", "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."));
         return;
     }
 
-    HTMLTextFormControlElement::setRangeText(replacement, start, end, selectionMode, es);
+    HTMLTextFormControlElement::setRangeText(replacement, start, end, selectionMode, exceptionState);
 }
 
 bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
@@ -1832,6 +1838,7 @@
 
     parameters.anchorRectInRootView = document().view()->contentsToRootView(pixelSnappedBoundingBox());
     parameters.currentValue = value();
+    parameters.doubleValue = m_inputType->valueAsDouble();
     parameters.isAnchorElementRTL = computedStyle()->direction() == RTL;
     if (RuntimeEnabledFeatures::dataListElementEnabled()) {
         if (HTMLDataListElement* dataList = this->dataList()) {
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index e34f871..f0d363d 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -47,7 +47,7 @@
 
 class HTMLInputElement : public HTMLTextFormControlElement {
 public:
-    static PassRefPtr<HTMLInputElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+    static PassRefPtr<HTMLInputElement> create(Document&, HTMLFormElement*, bool createdByParser);
     virtual ~HTMLInputElement();
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitspeechchange);
@@ -80,8 +80,8 @@
     // Implementations of HTMLInputElement::stepUp() and stepDown().
     void stepUp(int, ExceptionState&);
     void stepDown(int, ExceptionState&);
-    void stepUp(ExceptionState& es) { stepUp(1, es); }
-    void stepDown(ExceptionState& es) { stepDown(1, es); }
+    void stepUp(ExceptionState& exceptionState) { stepUp(1, exceptionState); }
+    void stepDown(ExceptionState& exceptionState) { stepDown(1, exceptionState); }
     // stepUp()/stepDown() for user-interaction.
     bool isSteppable() const;
 
@@ -280,14 +280,14 @@
     bool supportsInputModeAttribute() const;
 
 protected:
-    HTMLInputElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+    HTMLInputElement(Document&, HTMLFormElement*, bool createdByParser);
 
     virtual void defaultEventHandler(Event*);
 
 private:
     enum AutoCompleteSetting { Uninitialized, On, Off };
 
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
     virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE;
 
     virtual void willChangeForm() OVERRIDE;
@@ -331,7 +331,7 @@
     virtual bool appendFormData(FormDataList&, bool) OVERRIDE;
     virtual String resultForDialogSubmit() OVERRIDE;
 
-    virtual bool isSuccessfulSubmitButton() const;
+    virtual bool canBeSuccessfulSubmitButton() const OVERRIDE;
 
     virtual void resetImpl() OVERRIDE;
 
diff --git a/Source/core/html/HTMLInputElement.idl b/Source/core/html/HTMLInputElement.idl
index 9782e01..29cc909 100644
--- a/Source/core/html/HTMLInputElement.idl
+++ b/Source/core/html/HTMLInputElement.idl
@@ -42,7 +42,7 @@
     attribute boolean indeterminate;
     [RuntimeEnabled=DataListElement] readonly attribute HTMLElement list;
     [Reflect, TreatNullAs=NullString] attribute DOMString max;
-    [SetterRaisesException, CustomElementCallbacks] attribute long maxLength;
+    [RaisesException=Setter, CustomElementCallbacks] attribute long maxLength;
     [Reflect, TreatNullAs=NullString] attribute DOMString min;
     [Reflect] attribute boolean multiple;
     [Reflect, TreatNullAs=NullString] attribute DOMString name;
@@ -50,15 +50,15 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString placeholder;
     [Reflect] attribute boolean readOnly;
     [Reflect] attribute boolean required;
-    [SetterRaisesException, CustomElementCallbacks] attribute unsigned long size; // Changed string -> long -> unsigned long
+    [RaisesException=Setter, CustomElementCallbacks] attribute unsigned long size; // Changed string -> long -> unsigned long
     [Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
     [Reflect, TreatNullAs=NullString] attribute DOMString step;
     [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString type; // readonly dropped as part of DOM level 2
     [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString defaultValue;
     // See the discussion in https://bugs.webkit.org/show_bug.cgi?id=100085
-    [TreatNullAs=NullString, SetterRaisesException, CustomElementCallbacks] attribute DOMString value;
-    [SetterRaisesException, CustomElementCallbacks] attribute Date valueAsDate;
-    [SetterRaisesException, CustomElementCallbacks] attribute double valueAsNumber;
+    [TreatNullAs=NullString, RaisesException=Setter, CustomElementCallbacks] attribute DOMString value;
+    [RaisesException=Setter, CustomElementCallbacks] attribute Date valueAsDate;
+    [RaisesException=Setter, CustomElementCallbacks] attribute double valueAsNumber;
     [RuntimeEnabled=InputModeAttribute, Reflect, TreatNullAs=NullString] attribute DOMString inputMode;
 
     [RaisesException, CustomElementCallbacks] void stepUp(optional long n);
diff --git a/Source/core/html/HTMLKeygenElement.cpp b/Source/core/html/HTMLKeygenElement.cpp
index 4b20d87..e6c80d0 100644
--- a/Source/core/html/HTMLKeygenElement.cpp
+++ b/Source/core/html/HTMLKeygenElement.cpp
@@ -42,15 +42,14 @@
 
 using namespace HTMLNames;
 
-HTMLKeygenElement::HTMLKeygenElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
-    : HTMLFormControlElementWithState(tagName, document, form)
+HTMLKeygenElement::HTMLKeygenElement(Document& document, HTMLFormElement* form)
+    : HTMLFormControlElementWithState(keygenTag, document, form)
 {
-    ASSERT(hasTagName(keygenTag));
     ScriptWrappable::init(this);
     ensureUserAgentShadowRoot();
 }
 
-void HTMLKeygenElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLKeygenElement::didAddUserAgentShadowRoot(ShadowRoot& root)
 {
     DEFINE_STATIC_LOCAL(AtomicString, keygenSelectPseudoId, ("-webkit-keygen-select", AtomicString::ConstructFromLiteral));
 
@@ -59,14 +58,14 @@
 
     // Create a select element with one option element for each key size.
     RefPtr<HTMLSelectElement> select = HTMLSelectElement::create(document());
-    select->setPart(keygenSelectPseudoId);
+    select->setPseudo(keygenSelectPseudoId);
     for (size_t i = 0; i < keys.size(); ++i) {
         RefPtr<HTMLOptionElement> option = HTMLOptionElement::create(document());
         option->appendChild(Text::create(document(), keys[i]));
         select->appendChild(option);
     }
 
-    root->appendChild(select);
+    root.appendChild(select);
 }
 
 void HTMLKeygenElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/html/HTMLKeygenElement.h b/Source/core/html/HTMLKeygenElement.h
index 8195376..292a78e 100644
--- a/Source/core/html/HTMLKeygenElement.h
+++ b/Source/core/html/HTMLKeygenElement.h
@@ -32,15 +32,15 @@
 
 class HTMLKeygenElement FINAL : public HTMLFormControlElementWithState {
 public:
-    static PassRefPtr<HTMLKeygenElement> create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+    static PassRefPtr<HTMLKeygenElement> create(Document& document, HTMLFormElement* form)
     {
-        return adoptRef(new HTMLKeygenElement(tagName, document, form));
+        return adoptRef(new HTMLKeygenElement(document, form));
     }
 
     virtual bool willValidate() const OVERRIDE { return false; }
 
 private:
-    HTMLKeygenElement(const QualifiedName&, Document&, HTMLFormElement*);
+    HTMLKeygenElement(Document&, HTMLFormElement*);
 
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
@@ -59,7 +59,7 @@
     virtual void resetImpl() OVERRIDE;
     virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE { return false; }
 
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
 
     HTMLSelectElement* shadowSelect() const;
 };
diff --git a/Source/core/html/HTMLLIElement.cpp b/Source/core/html/HTMLLIElement.cpp
index b6da138..d5a7896 100644
--- a/Source/core/html/HTMLLIElement.cpp
+++ b/Source/core/html/HTMLLIElement.cpp
@@ -32,21 +32,15 @@
 
 using namespace HTMLNames;
 
-HTMLLIElement::HTMLLIElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLLIElement::HTMLLIElement(Document& document)
+    : HTMLElement(liTag, document)
 {
-    ASSERT(hasTagName(liTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLLIElement> HTMLLIElement::create(Document& document)
 {
-    return adoptRef(new HTMLLIElement(liTag, document));
-}
-
-PassRefPtr<HTMLLIElement> HTMLLIElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLLIElement(tagName, document));
+    return adoptRef(new HTMLLIElement(document));
 }
 
 bool HTMLLIElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLLIElement.h b/Source/core/html/HTMLLIElement.h
index 969a938..a16f4b0 100644
--- a/Source/core/html/HTMLLIElement.h
+++ b/Source/core/html/HTMLLIElement.h
@@ -30,10 +30,9 @@
 class HTMLLIElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLLIElement> create(Document&);
-    static PassRefPtr<HTMLLIElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLLIElement(const QualifiedName&, Document&);
+    explicit HTMLLIElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLLIElement.idl b/Source/core/html/HTMLLIElement.idl
index 9d03749..43b242f 100644
--- a/Source/core/html/HTMLLIElement.idl
+++ b/Source/core/html/HTMLLIElement.idl
@@ -18,7 +18,6 @@
  */
 
 interface HTMLLIElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString type;
+    [Reflect] attribute DOMString type;
     [Reflect] attribute long value;
 };
-
diff --git a/Source/core/html/HTMLLabelElement.cpp b/Source/core/html/HTMLLabelElement.cpp
index e5b985e..67cf619 100644
--- a/Source/core/html/HTMLLabelElement.cpp
+++ b/Source/core/html/HTMLLabelElement.cpp
@@ -44,16 +44,15 @@
     return toLabelableElement(element)->supportLabels();
 }
 
-inline HTMLLabelElement::HTMLLabelElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLLabelElement::HTMLLabelElement(Document& document)
+    : HTMLElement(labelTag, document)
 {
-    ASSERT(hasTagName(labelTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLLabelElement> HTMLLabelElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLLabelElement> HTMLLabelElement::create(Document& document)
 {
-    return adoptRef(new HTMLLabelElement(tagName, document));
+    return adoptRef(new HTMLLabelElement(document));
 }
 
 bool HTMLLabelElement::rendererIsFocusable() const
@@ -70,7 +69,7 @@
         // per http://dev.w3.org/html5/spec/Overview.html#the-label-element
         // the form element must be "labelable form-associated element".
         Element* element = this;
-        while ((element = ElementTraversal::next(element, this))) {
+        while ((element = ElementTraversal::next(*element, this))) {
             if (!supportsLabels(element))
                 continue;
             return toLabelableElement(element);
@@ -91,17 +90,17 @@
     return FormAssociatedElement::findAssociatedForm(this, 0);
 }
 
-void HTMLLabelElement::setActive(bool down, bool pause)
+void HTMLLabelElement::setActive(bool down)
 {
     if (down == active())
         return;
 
     // Update our status first.
-    HTMLElement::setActive(down, pause);
+    HTMLElement::setActive(down);
 
     // Also update our corresponding control.
     if (HTMLElement* element = control())
-        element->setActive(down, pause);
+        element->setActive(down);
 }
 
 void HTMLLabelElement::setHovered(bool over)
diff --git a/Source/core/html/HTMLLabelElement.h b/Source/core/html/HTMLLabelElement.h
index a71af43..275b077 100644
--- a/Source/core/html/HTMLLabelElement.h
+++ b/Source/core/html/HTMLLabelElement.h
@@ -31,7 +31,7 @@
 
 class HTMLLabelElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLLabelElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLLabelElement> create(Document&);
 
     LabelableElement* control();
     HTMLFormElement* form() const;
@@ -39,7 +39,7 @@
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    HTMLLabelElement(const QualifiedName&, Document&);
+    explicit HTMLLabelElement(Document&);
     bool isInInteractiveContent(Node*) const;
 
     virtual bool rendererIsFocusable() const OVERRIDE;
@@ -47,8 +47,8 @@
     virtual void accessKeyAction(bool sendMouseEvents);
 
     // Overridden to update the hover/active state of the corresponding control.
-    virtual void setActive(bool = true, bool pause = false);
-    virtual void setHovered(bool = true);
+    virtual void setActive(bool = true) OVERRIDE;
+    virtual void setHovered(bool = true) OVERRIDE;
 
     // Overridden to either click() or focus() the corresponding control.
     virtual void defaultEventHandler(Event*);
diff --git a/Source/core/html/HTMLLegendElement.cpp b/Source/core/html/HTMLLegendElement.cpp
index 5159326..0e711ef 100644
--- a/Source/core/html/HTMLLegendElement.cpp
+++ b/Source/core/html/HTMLLegendElement.cpp
@@ -35,16 +35,15 @@
 using namespace HTMLNames;
 
 
-inline HTMLLegendElement::HTMLLegendElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLLegendElement::HTMLLegendElement(Document& document)
+    : HTMLElement(legendTag, document)
 {
-    ASSERT(hasTagName(legendTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLLegendElement> HTMLLegendElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLLegendElement> HTMLLegendElement::create(Document& document)
 {
-    return adoptRef(new HTMLLegendElement(tagName, document));
+    return adoptRef(new HTMLLegendElement(document));
 }
 
 HTMLFormControlElement* HTMLLegendElement::associatedControl()
@@ -59,7 +58,7 @@
     // Find first form element inside the fieldset that is not a legend element.
     // FIXME: Should we consider tabindex?
     Element* element = fieldset;
-    while ((element = ElementTraversal::next(element, fieldset))) {
+    while ((element = ElementTraversal::next(*element, fieldset))) {
         if (element->isFormControlElement())
             return toHTMLFormControlElement(element);
     }
diff --git a/Source/core/html/HTMLLegendElement.h b/Source/core/html/HTMLLegendElement.h
index dded0f7..4a8c2fa 100644
--- a/Source/core/html/HTMLLegendElement.h
+++ b/Source/core/html/HTMLLegendElement.h
@@ -32,10 +32,10 @@
 
 class HTMLLegendElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLLegendElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLLegendElement> create(Document&);
 
 private:
-    HTMLLegendElement(const QualifiedName&, Document&);
+    explicit HTMLLegendElement(Document&);
 
     // Control in the legend's fieldset that gets focus and access key.
     HTMLFormControlElement* associatedControl();
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index 5e40e35..3ffd373 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -58,21 +58,20 @@
     return sharedLoadEventSender;
 }
 
-inline HTMLLinkElement::HTMLLinkElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLElement(tagName, document)
+inline HTMLLinkElement::HTMLLinkElement(Document& document, bool createdByParser)
+    : HTMLElement(linkTag, document)
     , m_linkLoader(this)
     , m_sizes(DOMSettableTokenList::create())
     , m_createdByParser(createdByParser)
     , m_isInShadowTree(false)
     , m_beforeLoadRecurseCount(0)
 {
-    ASSERT(hasTagName(linkTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLLinkElement> HTMLLinkElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLLinkElement> HTMLLinkElement::create(Document& document, bool createdByParser)
 {
-    return adoptRef(new HTMLLinkElement(tagName, document, createdByParser));
+    return adoptRef(new HTMLLinkElement(document, createdByParser));
 }
 
 HTMLLinkElement::~HTMLLinkElement()
diff --git a/Source/core/html/HTMLLinkElement.h b/Source/core/html/HTMLLinkElement.h
index 71a0cf1..ba8f41c 100644
--- a/Source/core/html/HTMLLinkElement.h
+++ b/Source/core/html/HTMLLinkElement.h
@@ -120,7 +120,7 @@
 
 class HTMLLinkElement FINAL : public HTMLElement, public LinkLoaderClient {
 public:
-    static PassRefPtr<HTMLLinkElement> create(const QualifiedName&, Document&, bool createdByParser);
+    static PassRefPtr<HTMLLinkElement> create(Document&, bool createdByParser);
     virtual ~HTMLLinkElement();
 
     KURL href() const;
@@ -188,7 +188,7 @@
     virtual void didSendDOMContentLoadedForLinkPrerender() OVERRIDE;
 
 private:
-    HTMLLinkElement(const QualifiedName&, Document&, bool createdByParser);
+    HTMLLinkElement(Document&, bool createdByParser);
 
     RefPtr<LinkResource> m_link;
     LinkLoader m_linkLoader;
diff --git a/Source/core/html/HTMLMapElement.cpp b/Source/core/html/HTMLMapElement.cpp
index bdded68..d1f055a 100644
--- a/Source/core/html/HTMLMapElement.cpp
+++ b/Source/core/html/HTMLMapElement.cpp
@@ -36,21 +36,15 @@
 
 using namespace HTMLNames;
 
-HTMLMapElement::HTMLMapElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLMapElement::HTMLMapElement(Document& document)
+    : HTMLElement(mapTag, document)
 {
-    ASSERT(hasTagName(mapTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLMapElement> HTMLMapElement::create(Document& document)
 {
-    return adoptRef(new HTMLMapElement(mapTag, document));
-}
-
-PassRefPtr<HTMLMapElement> HTMLMapElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLMapElement(tagName, document));
+    return adoptRef(new HTMLMapElement(document));
 }
 
 HTMLMapElement::~HTMLMapElement()
@@ -61,7 +55,7 @@
 {
     HTMLAreaElement* defaultArea = 0;
     Element* element = this;
-    while ((element = ElementTraversal::next(element, this))) {
+    while ((element = ElementTraversal::next(*element, this))) {
         if (isHTMLAreaElement(element)) {
             HTMLAreaElement* areaElt = toHTMLAreaElement(element);
             if (areaElt->isDefault()) {
diff --git a/Source/core/html/HTMLMapElement.h b/Source/core/html/HTMLMapElement.h
index 369de11..cdd5c76 100644
--- a/Source/core/html/HTMLMapElement.h
+++ b/Source/core/html/HTMLMapElement.h
@@ -33,7 +33,6 @@
 class HTMLMapElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLMapElement> create(Document&);
-    static PassRefPtr<HTMLMapElement> create(const QualifiedName&, Document&);
     virtual ~HTMLMapElement();
 
     const AtomicString& getName() const { return m_name; }
@@ -44,7 +43,7 @@
     PassRefPtr<HTMLCollection> areas();
 
 private:
-    HTMLMapElement(const QualifiedName&, Document&);
+    explicit HTMLMapElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/html/HTMLMarqueeElement.cpp b/Source/core/html/HTMLMarqueeElement.cpp
index 2f5078e..e06c90a 100644
--- a/Source/core/html/HTMLMarqueeElement.cpp
+++ b/Source/core/html/HTMLMarqueeElement.cpp
@@ -26,6 +26,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/rendering/RenderMarquee.h"
@@ -34,17 +35,16 @@
 
 using namespace HTMLNames;
 
-inline HTMLMarqueeElement::HTMLMarqueeElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLMarqueeElement::HTMLMarqueeElement(Document& document)
+    : HTMLElement(marqueeTag, document)
     , ActiveDOMObject(&document)
 {
-    ASSERT(hasTagName(marqueeTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLMarqueeElement> HTMLMarqueeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLMarqueeElement> HTMLMarqueeElement::create(Document& document)
 {
-    RefPtr<HTMLMarqueeElement> marqueeElement(adoptRef(new HTMLMarqueeElement(tagName, document)));
+    RefPtr<HTMLMarqueeElement> marqueeElement(adoptRef(new HTMLMarqueeElement(document)));
     marqueeElement->suspendIfNeeded();
     return marqueeElement.release();
 }
@@ -128,10 +128,10 @@
     return ok && scrollAmount >= 0 ? scrollAmount : RenderStyle::initialMarqueeIncrement().intValue();
 }
 
-void HTMLMarqueeElement::setScrollAmount(int scrollAmount, ExceptionState& es)
+void HTMLMarqueeElement::setScrollAmount(int scrollAmount, ExceptionState& exceptionState)
 {
     if (scrollAmount < 0)
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("scrollAmount", "HTMLMarqueeElement", "The provided value (" + String::number(scrollAmount) + ") is negative."));
     else
         setIntegralAttribute(scrollamountAttr, scrollAmount);
 }
@@ -143,10 +143,10 @@
     return ok && scrollDelay >= 0 ? scrollDelay : RenderStyle::initialMarqueeSpeed();
 }
 
-void HTMLMarqueeElement::setScrollDelay(int scrollDelay, ExceptionState& es)
+void HTMLMarqueeElement::setScrollDelay(int scrollDelay, ExceptionState& exceptionState)
 {
     if (scrollDelay < 0)
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("scrollDelay", "HTMLMarqueeElement", "The provided value (" + String::number(scrollDelay) + ") is negative."));
     else
         setIntegralAttribute(scrolldelayAttr, scrollDelay);
 }
@@ -158,10 +158,10 @@
     return ok && loopValue > 0 ? loopValue : -1;
 }
 
-void HTMLMarqueeElement::setLoop(int loop, ExceptionState& es)
+void HTMLMarqueeElement::setLoop(int loop, ExceptionState& exceptionState)
 {
     if (loop <= 0 && loop != -1)
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("loop", "HTMLMarqueeElement", "The provided value (" + String::number(loop) + ") is neither positive nor -1."));
     else
         setIntegralAttribute(loopAttr, loop);
 }
diff --git a/Source/core/html/HTMLMarqueeElement.h b/Source/core/html/HTMLMarqueeElement.h
index 284e3c9..0a58595 100644
--- a/Source/core/html/HTMLMarqueeElement.h
+++ b/Source/core/html/HTMLMarqueeElement.h
@@ -33,7 +33,7 @@
 
 class HTMLMarqueeElement FINAL : public HTMLElement, private ActiveDOMObject {
 public:
-    static PassRefPtr<HTMLMarqueeElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLMarqueeElement> create(Document&);
 
     int minimumDelay() const;
 
@@ -52,7 +52,7 @@
     void setLoop(int, ExceptionState&);
 
 private:
-    HTMLMarqueeElement(const QualifiedName&, Document&);
+    explicit HTMLMarqueeElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLMarqueeElement.idl b/Source/core/html/HTMLMarqueeElement.idl
index 827da3e..cc585fc 100644
--- a/Source/core/html/HTMLMarqueeElement.idl
+++ b/Source/core/html/HTMLMarqueeElement.idl
@@ -26,9 +26,9 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString direction;
     [Reflect, TreatNullAs=NullString] attribute DOMString height;
     [Reflect] attribute unsigned long hspace;
-    [SetterRaisesException] attribute long loop;
-    [SetterRaisesException] attribute long scrollAmount;
-    [SetterRaisesException] attribute long scrollDelay;
+    [RaisesException=Setter] attribute long loop;
+    [RaisesException=Setter] attribute long scrollAmount;
+    [RaisesException=Setter] attribute long scrollDelay;
     [Reflect] attribute boolean trueSpeed;
     [Reflect] attribute unsigned long vspace;
     [Reflect, TreatNullAs=NullString] attribute DOMString width;
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index 5a0227c..1ec0575 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -59,10 +59,6 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/graphics/InbandTextTrackPrivate.h"
-#include "core/platform/graphics/MediaPlayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/RenderView.h"
@@ -70,10 +66,14 @@
 #include "platform/ContentType.h"
 #include "platform/Language.h"
 #include "platform/Logging.h"
+#include "platform/MIMETypeFromURL.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/NotImplemented.h"
 #include "platform/UserGestureIndicator.h"
+#include "platform/graphics/media/MediaPlayer.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "public/platform/Platform.h"
-#include "weborigin/SecurityOrigin.h"
+#include "public/platform/WebInbandTextTrack.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MathExtras.h"
 #include "wtf/NonCopyingSort.h"
@@ -92,7 +92,8 @@
 #endif
 
 using namespace std;
-using WebKit::WebMimeRegistry;
+using blink::WebInbandTextTrack;
+using blink::WebMimeRegistry;
 
 namespace WebCore {
 
@@ -154,16 +155,19 @@
         map.add(document, set);
 }
 
-static void throwExceptionForMediaKeyException(MediaPlayer::MediaKeyException exception, ExceptionState& es)
+static void throwExceptionForMediaKeyException(MediaPlayer::MediaKeyException exception, ExceptionState& exceptionState)
 {
     switch (exception) {
     case MediaPlayer::NoError:
         return;
     case MediaPlayer::InvalidPlayerState:
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     case MediaPlayer::KeySystemNotSupported:
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        return;
+    case MediaPlayer::InvalidAccess:
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
@@ -209,7 +213,7 @@
     // when used with parameters, e.g. "application/octet-stream;codecs=theora", is a type that the user agent knows
     // it cannot render.
     if (contentMIMEType != "application/octet-stream" || contentTypeCodecs.isEmpty()) {
-        WebMimeRegistry::SupportsType supported = WebKit::Platform::current()->mimeRegistry()->supportsMediaMIMEType(contentMIMEType, contentTypeCodecs, keySystem.lower());
+        WebMimeRegistry::SupportsType supported = blink::Platform::current()->mimeRegistry()->supportsMediaMIMEType(contentMIMEType, contentTypeCodecs, keySystem.lower());
         return supported > WebMimeRegistry::IsNotSupported;
     }
 
@@ -237,7 +241,7 @@
     if (type == "application/octet-stream")
         return WebMimeRegistry::IsNotSupported;
 
-    return WebKit::Platform::current()->mimeRegistry()->supportsMediaMIMEType(type, typeCodecs, system);
+    return blink::Platform::current()->mimeRegistry()->supportsMediaMIMEType(type, typeCodecs, system);
 }
 
 HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& document, bool createdByParser)
@@ -616,6 +620,9 @@
 
     LOG(Media, "HTMLMediaElement::load()");
 
+    if (document().settings() && !document().settings()->mediaEnabled())
+        return;
+
     if (userGestureRequiredForLoad() && !UserGestureIndicator::processingUserGesture())
         return;
 
@@ -1797,7 +1804,7 @@
     m_player->prepareToPlay();
 }
 
-void HTMLMediaElement::seek(double time, ExceptionState& es)
+void HTMLMediaElement::seek(double time, ExceptionState& exceptionState)
 {
     LOG(Media, "HTMLMediaElement::seek(%f)", time);
 
@@ -1805,7 +1812,7 @@
 
     // 1 - If the media element's readyState is HAVE_NOTHING, then raise an InvalidStateError exception.
     if (m_readyState == HAVE_NOTHING || !m_player) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
@@ -1971,13 +1978,13 @@
     return m_cachedTime;
 }
 
-void HTMLMediaElement::setCurrentTime(double time, ExceptionState& es)
+void HTMLMediaElement::setCurrentTime(double time, ExceptionState& exceptionState)
 {
     if (m_mediaController) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
-    seek(time, es);
+    seek(time, exceptionState);
 }
 
 double HTMLMediaElement::duration() const
@@ -2163,15 +2170,15 @@
     m_mediaSource = 0;
 }
 
-void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& es)
+void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& exceptionState)
 {
     if (keySystem.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
     if (!m_player) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
@@ -2183,33 +2190,33 @@
     }
 
     MediaPlayer::MediaKeyException result = m_player->generateKeyRequest(keySystem, initDataPointer, initDataLength);
-    throwExceptionForMediaKeyException(result, es);
+    throwExceptionForMediaKeyException(result, exceptionState);
 }
 
-void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, ExceptionState& es)
+void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, ExceptionState& exceptionState)
 {
-    webkitGenerateKeyRequest(keySystem, Uint8Array::create(0), es);
+    webkitGenerateKeyRequest(keySystem, Uint8Array::create(0), exceptionState);
 }
 
-void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& es)
+void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& exceptionState)
 {
     if (keySystem.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
     if (!key) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
     if (!key->length()) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
 
     if (!m_player) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
@@ -2221,28 +2228,28 @@
     }
 
     MediaPlayer::MediaKeyException result = m_player->addKey(keySystem, key->data(), key->length(), initDataPointer, initDataLength, sessionId);
-    throwExceptionForMediaKeyException(result, es);
+    throwExceptionForMediaKeyException(result, exceptionState);
 }
 
-void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, ExceptionState& es)
+void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, ExceptionState& exceptionState)
 {
-    webkitAddKey(keySystem, key, Uint8Array::create(0), String(), es);
+    webkitAddKey(keySystem, key, Uint8Array::create(0), String(), exceptionState);
 }
 
-void HTMLMediaElement::webkitCancelKeyRequest(const String& keySystem, const String& sessionId, ExceptionState& es)
+void HTMLMediaElement::webkitCancelKeyRequest(const String& keySystem, const String& sessionId, ExceptionState& exceptionState)
 {
     if (keySystem.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
     if (!m_player) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
     MediaPlayer::MediaKeyException result = m_player->cancelKeyRequest(keySystem, sessionId);
-    throwExceptionForMediaKeyException(result, es);
+    throwExceptionForMediaKeyException(result, exceptionState);
 }
 
 bool HTMLMediaElement::loop() const
@@ -2282,12 +2289,12 @@
     return m_volume;
 }
 
-void HTMLMediaElement::setVolume(double vol, ExceptionState& es)
+void HTMLMediaElement::setVolume(double vol, ExceptionState& exceptionState)
 {
     LOG(Media, "HTMLMediaElement::setVolume(%f)", vol);
 
     if (vol < 0.0f || vol > 1.0f) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
@@ -2439,14 +2446,14 @@
     return buffered / duration;
 }
 
-void HTMLMediaElement::mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate> prpTrack)
+void HTMLMediaElement::mediaPlayerDidAddTrack(WebInbandTextTrack* webTrack)
 {
     if (!RuntimeEnabledFeatures::videoTrackEnabled())
         return;
 
     // 4.8.10.12.2 Sourcing in-band text tracks
     // 1. Associate the relevant data with a new text track and its corresponding new TextTrack object.
-    RefPtr<InbandTextTrack> textTrack = InbandTextTrack::create(document(), this, prpTrack);
+    RefPtr<InbandTextTrack> textTrack = InbandTextTrack::create(document(), this, webTrack);
 
     // 2. Set the new text track's kind, label, and language based on the semantics of the relevant data,
     // as defined by the relevant specification. If there is no label in that data, then the label must
@@ -2474,7 +2481,7 @@
     addTrack(textTrack.get());
 }
 
-void HTMLMediaElement::mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPrivate> prpTrack)
+void HTMLMediaElement::mediaPlayerDidRemoveTrack(WebInbandTextTrack* webTrack)
 {
     if (!RuntimeEnabledFeatures::videoTrackEnabled())
         return;
@@ -2482,9 +2489,9 @@
     if (!m_textTracks)
         return;
 
-    // This cast is safe because we created the InbandTextTrack with the InbandTextTrackPrivate
+    // This cast is safe because we created the InbandTextTrack with the WebInbandTextTrack
     // passed to mediaPlayerDidAddTrack.
-    RefPtr<InbandTextTrack> textTrack = static_cast<InbandTextTrack*>(prpTrack->client());
+    RefPtr<InbandTextTrack> textTrack = static_cast<InbandTextTrack*>(webTrack->client());
     if (!textTrack)
         return;
 
@@ -2529,17 +2536,16 @@
     }
 }
 
-PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const String& kind, const String& label, const String& language, ExceptionState& es)
+PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const String& kind, const String& label, const String& language, ExceptionState& exceptionState)
 {
-    if (!RuntimeEnabledFeatures::videoTrackEnabled())
-        return 0;
+    ASSERT(RuntimeEnabledFeatures::videoTrackEnabled());
 
     // 4.8.10.12.4 Text track API
     // The addTextTrack(kind, label, language) method of media elements, when invoked, must run the following steps:
 
     // 1. If kind is not one of the following strings, then throw a SyntaxError exception and abort these steps
     if (!TextTrack::isValidKindKeyword(kind)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return 0;
     }
 
@@ -2568,8 +2574,7 @@
 
 TextTrackList* HTMLMediaElement::textTracks()
 {
-    if (!RuntimeEnabledFeatures::videoTrackEnabled())
-        return 0;
+    ASSERT(RuntimeEnabledFeatures::videoTrackEnabled());
 
     if (!m_textTracks)
         m_textTracks = TextTrackList::create(this);
@@ -3172,8 +3177,12 @@
 
 PassRefPtr<TimeRanges> HTMLMediaElement::seekable() const
 {
-    double maxSeekable = maxTimeSeekable();
-    return maxSeekable ? TimeRanges::create(0, maxSeekable) : TimeRanges::create();
+    if (m_player) {
+        double maxTimeSeekable = m_player->maxTimeSeekable();
+        if (maxTimeSeekable)
+            return TimeRanges::create(0, maxTimeSeekable);
+    }
+    return TimeRanges::create();
 }
 
 bool HTMLMediaElement::potentiallyPlaying() const
@@ -3235,16 +3244,6 @@
     return false;
 }
 
-double HTMLMediaElement::minTimeSeekable() const
-{
-    return 0;
-}
-
-double HTMLMediaElement::maxTimeSeekable() const
-{
-    return m_player ? m_player->maxTimeSeekable() : 0;
-}
-
 void HTMLMediaElement::updateVolume()
 {
     if (!m_player)
@@ -3474,7 +3473,7 @@
         document().renderView()->compositor()->setCompositingLayersNeedRebuild(true);
 }
 
-WebKit::WebLayer* HTMLMediaElement::platformLayer() const
+blink::WebLayer* HTMLMediaElement::platformLayer() const
 {
     return m_player ? m_player->platformLayer() : 0;
 }
@@ -3591,7 +3590,7 @@
     if (isFullscreen())
         mediaControls->enteredFullscreen();
 
-    ensureUserAgentShadowRoot()->appendChild(mediaControls);
+    ensureUserAgentShadowRoot().appendChild(mediaControls);
 
     if (!controls() || !inDocument())
         mediaControls->hide();
@@ -3720,22 +3719,18 @@
 }
 #endif
 
-const String& HTMLMediaElement::mediaGroup() const
+const AtomicString& HTMLMediaElement::mediaGroup() const
 {
-    return m_mediaGroup;
+    return fastGetAttribute(mediagroupAttr);
 }
 
-void HTMLMediaElement::setMediaGroup(const String& group)
+void HTMLMediaElement::setMediaGroup(const AtomicString& group)
 {
-    if (m_mediaGroup == group)
-        return;
-    m_mediaGroup = group;
-
     // When a media element is created with a mediagroup attribute, and when a media element's mediagroup
     // attribute is set, changed, or removed, the user agent must run the following steps:
     // 1. Let m [this] be the media element in question.
     // 2. Let m have no current media controller, if it currently has one.
-    setController(0);
+    setControllerInternal(0);
 
     // 3. If m's mediagroup attribute is being removed, then abort these steps.
     if (group.isNull() || group.isEmpty())
@@ -3752,13 +3747,13 @@
         // the new value of m's mediagroup attribute,
         if ((*i)->mediaGroup() == group) {
             //  then let controller be that media element's current media controller.
-            setController((*i)->controller());
+            setControllerInternal((*i)->controller());
             return;
         }
     }
 
     // Otherwise, let controller be a newly created MediaController.
-    setController(MediaController::create(Node::executionContext()));
+    setControllerInternal(MediaController::create(Node::executionContext()));
 }
 
 MediaController* HTMLMediaElement::controller() const
@@ -3768,6 +3763,15 @@
 
 void HTMLMediaElement::setController(PassRefPtr<MediaController> controller)
 {
+    // 4.8.10.11.2 Media controllers: controller attribute.
+    // On setting, it must first remove the element's mediagroup attribute, if any,
+    removeAttribute(mediagroupAttr);
+    // and then set the current media controller to the given value.
+    setControllerInternal(controller);
+}
+
+void HTMLMediaElement::setControllerInternal(PassRefPtr<MediaController> controller)
+{
     if (m_mediaController)
         m_mediaController->removeMediaElement(this);
 
@@ -3852,9 +3856,9 @@
 
 MediaPlayerClient::CORSMode HTMLMediaElement::mediaPlayerCORSMode() const
 {
-    if (!fastHasAttribute(HTMLNames::crossoriginAttr))
+    if (!fastHasAttribute(crossoriginAttr))
         return Unspecified;
-    if (equalIgnoringCase(fastGetAttribute(HTMLNames::crossoriginAttr), "use-credentials"))
+    if (equalIgnoringCase(fastGetAttribute(crossoriginAttr), "use-credentials"))
         return UseCredentials;
     return Anonymous;
 }
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index e3a870b..4f6b07a 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -32,11 +32,15 @@
 #include "core/html/MediaControllerInterface.h"
 #include "core/html/track/TextTrack.h"
 #include "core/html/track/TextTrackCue.h"
-#include "core/platform/graphics/MediaPlayer.h"
+#include "core/html/track/vtt/VTTCue.h"
 #include "platform/PODIntervalTree.h"
+#include "platform/graphics/media/MediaPlayer.h"
 #include "public/platform/WebMimeRegistry.h"
 
-namespace WebKit { class WebLayer; }
+namespace blink {
+class WebInbandTextTrack;
+class WebLayer;
+}
 
 namespace WebCore {
 
@@ -60,8 +64,6 @@
 class MediaKeys;
 #endif
 
-class InbandTextTrackPrivate;
-
 typedef PODIntervalTree<double, TextTrackCue*> CueIntervalTree;
 typedef CueIntervalTree::IntervalType CueInterval;
 typedef Vector<CueInterval> CueList;
@@ -74,7 +76,7 @@
     , private TextTrackClient
 {
 public:
-    static WebKit::WebMimeRegistry::SupportsType supportsType(const ContentType&, const String& keySystem = String());
+    static blink::WebMimeRegistry::SupportsType supportsType(const ContentType&, const String& keySystem = String());
 
     MediaPlayer* player() const { return m_player.get(); }
 
@@ -87,7 +89,7 @@
 
     bool supportsSave() const;
 
-    WebKit::WebLayer* platformLayer() const;
+    blink::WebLayer* platformLayer() const;
 
     enum DelayedActionType {
         LoadMediaResource = 1 << 0,
@@ -180,8 +182,8 @@
     double percentLoaded() const;
 
     PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, const String& language, ExceptionState&);
-    PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, ExceptionState& es) { return addTextTrack(kind, label, emptyString(), es); }
-    PassRefPtr<TextTrack> addTextTrack(const String& kind, ExceptionState& es) { return addTextTrack(kind, emptyString(), emptyString(), es); }
+    PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, ExceptionState& exceptionState) { return addTextTrack(kind, label, emptyString(), exceptionState); }
+    PassRefPtr<TextTrack> addTextTrack(const String& kind, ExceptionState& exceptionState) { return addTextTrack(kind, emptyString(), emptyString(), exceptionState); }
 
     TextTrackList* textTracks();
     CueList currentlyActiveCues() const { return m_currentlyActiveCues; }
@@ -195,8 +197,8 @@
     void didAddTrack(HTMLTrackElement*);
     void didRemoveTrack(HTMLTrackElement*);
 
-    virtual void mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate>) OVERRIDE;
-    virtual void mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPrivate>) OVERRIDE;
+    virtual void mediaPlayerDidAddTrack(blink::WebInbandTextTrack*) OVERRIDE;
+    virtual void mediaPlayerDidRemoveTrack(blink::WebInbandTextTrack*) OVERRIDE;
 
     struct TrackGroup {
         enum GroupKind { CaptionsAndSubtitles, Description, Chapter, Metadata, Other };
@@ -275,11 +277,8 @@
     enum InvalidURLAction { DoNothing, Complain };
     bool isSafeToLoadURL(const KURL&, InvalidURLAction);
 
-    const String& mediaGroup() const;
-    void setMediaGroup(const String&);
-
     MediaController* controller() const;
-    void setController(PassRefPtr<MediaController>);
+    void setController(PassRefPtr<MediaController>); // Resets the MediaGroup and sets the MediaController.
 
 protected:
     HTMLMediaElement(const QualifiedName&, Document&, bool);
@@ -298,6 +297,8 @@
 
     virtual bool isMediaElement() const OVERRIDE { return true; }
 
+    void setControllerInternal(PassRefPtr<MediaController>);
+
     // Restrictions to change default behaviors.
     enum BehaviorRestrictionFlags {
         NoRestrictions = 0,
@@ -426,9 +427,6 @@
     bool pausedForUserInteraction() const;
     bool couldPlayIfEnoughData() const;
 
-    double minTimeSeekable() const;
-    double maxTimeSeekable() const;
-
     // Pauses playback without changing any states or generating events
     void setPausedInternal(bool);
 
@@ -451,6 +449,8 @@
 
     void removeBehaviorsRestrictionsAfterFirstUserGesture();
 
+    const AtomicString& mediaGroup() const;
+    void setMediaGroup(const AtomicString&);
     void updateMediaController();
     bool isBlocked() const;
     bool isBlockedOnMediaController() const;
@@ -558,7 +558,6 @@
     MediaElementAudioSourceNode* m_audioSourceNode;
 #endif
 
-    String m_mediaGroup;
     friend class MediaController;
     RefPtr<MediaController> m_mediaController;
 
@@ -583,7 +582,7 @@
 struct ValueToString<TextTrackCue*> {
     static String string(TextTrackCue* const& cue)
     {
-        return String::format("%p id=%s interval=%f-->%f cue=%s)", cue, cue->id().utf8().data(), cue->startTime(), cue->endTime(), cue->text().utf8().data());
+        return cue->toString();
     }
 };
 #endif
diff --git a/Source/core/html/HTMLMediaElement.idl b/Source/core/html/HTMLMediaElement.idl
index a30598b..a868b53 100644
--- a/Source/core/html/HTMLMediaElement.idl
+++ b/Source/core/html/HTMLMediaElement.idl
@@ -34,6 +34,7 @@
     // network state
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
     [URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] readonly attribute DOMString currentSrc;
+    [Reflect] attribute DOMString crossOrigin;
 
     const unsigned short NETWORK_EMPTY = 0;
     const unsigned short NETWORK_IDLE = 1;
@@ -56,7 +57,7 @@
     readonly attribute boolean seeking;
 
     // playback state
-    [SetterRaisesException] attribute double currentTime;
+    [RaisesException=Setter] attribute double currentTime;
     readonly attribute double duration;
     readonly attribute boolean paused;
     attribute double defaultPlaybackRate;
@@ -71,11 +72,11 @@
 
     // media controller
     [Reflect] attribute DOMString mediaGroup;
-    [CustomSetter] attribute MediaController controller;
+    [StrictTypeChecking] attribute MediaController controller;
 
     // controls
     attribute boolean controls;
-    [SetterRaisesException] attribute double volume;
+    [RaisesException=Setter] attribute double volume;
     attribute boolean muted;
     [Reflect=muted] attribute boolean defaultMuted;
 
diff --git a/Source/core/html/HTMLMediaSource.h b/Source/core/html/HTMLMediaSource.h
index ddf0aef..f40206c 100644
--- a/Source/core/html/HTMLMediaSource.h
+++ b/Source/core/html/HTMLMediaSource.h
@@ -35,9 +35,12 @@
 #include "core/html/URLRegistry.h"
 #include "wtf/Forward.h"
 
+namespace blink {
+class WebMediaSource;
+}
+
 namespace WebCore {
 
-class MediaSourcePrivate;
 class TimeRanges;
 
 class HTMLMediaSource : public URLRegistrable {
@@ -56,7 +59,7 @@
     // 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 setWebMediaSourceAndOpen(PassOwnPtr<blink::WebMediaSource>) = 0;
     virtual void close() = 0;
     virtual bool isClosed() const = 0;
     virtual double duration() const = 0;
diff --git a/Source/core/html/HTMLMenuElement.cpp b/Source/core/html/HTMLMenuElement.cpp
index dd110d4..2783c04 100644
--- a/Source/core/html/HTMLMenuElement.cpp
+++ b/Source/core/html/HTMLMenuElement.cpp
@@ -29,16 +29,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLMenuElement::HTMLMenuElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLMenuElement::HTMLMenuElement(Document& document)
+    : HTMLElement(menuTag, document)
 {
-    ASSERT(hasTagName(menuTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLMenuElement> HTMLMenuElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLMenuElement> HTMLMenuElement::create(Document& document)
 {
-    return adoptRef(new HTMLMenuElement(tagName, document));
+    return adoptRef(new HTMLMenuElement(document));
 }
 
 }
diff --git a/Source/core/html/HTMLMenuElement.h b/Source/core/html/HTMLMenuElement.h
index af7070d..b1fdab6 100644
--- a/Source/core/html/HTMLMenuElement.h
+++ b/Source/core/html/HTMLMenuElement.h
@@ -29,10 +29,10 @@
 
 class HTMLMenuElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLMenuElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLMenuElement> create(Document&);
 
 private:
-    HTMLMenuElement(const QualifiedName&, Document&);
+    explicit HTMLMenuElement(Document&);
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLMetaElement-in.cpp b/Source/core/html/HTMLMetaElement-in.cpp
index 8dd4340..18697f4 100644
--- a/Source/core/html/HTMLMetaElement-in.cpp
+++ b/Source/core/html/HTMLMetaElement-in.cpp
@@ -45,21 +45,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLMetaElement::HTMLMetaElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLMetaElement::HTMLMetaElement(Document& document)
+    : HTMLElement(metaTag, document)
 {
-    ASSERT(hasTagName(metaTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(Document& document)
 {
-    return adoptRef(new HTMLMetaElement(metaTag, document));
-}
-
-PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLMetaElement(tagName, document));
+    return adoptRef(new HTMLMetaElement(document));
 }
 
 static bool isInvalidSeparator(UChar c)
@@ -195,13 +189,6 @@
     if (value < 0)
         return Length(); // auto
 
-    if (!value && document().settings() && document().settings()->viewportMetaZeroValuesQuirk()) {
-        if (keyString == "width")
-            return Length(100, ViewportPercentageWidth);
-        if (keyString == "height")
-            return Length(100, ViewportPercentageHeight);
-    }
-
     return Length(clampLengthValue(value), Fixed);
 }
 
diff --git a/Source/core/html/HTMLMetaElement.h b/Source/core/html/HTMLMetaElement.h
index 2c2590b..2ec32c2 100644
--- a/Source/core/html/HTMLMetaElement.h
+++ b/Source/core/html/HTMLMetaElement.h
@@ -38,14 +38,13 @@
 class HTMLMetaElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLMetaElement> create(Document&);
-    static PassRefPtr<HTMLMetaElement> create(const QualifiedName&, Document&);
 
     String content() const;
     String httpEquiv() const;
     String name() const;
 
 private:
-    HTMLMetaElement(const QualifiedName&, Document&);
+    explicit HTMLMetaElement(Document&);
 
     typedef void (HTMLMetaElement::*KeyValuePairCallback)(const String& key, const String& value, void* data);
     void processViewportKeyValuePair(const String& key, const String& value, void* data);
diff --git a/Source/core/html/HTMLMeterElement.cpp b/Source/core/html/HTMLMeterElement.cpp
index 8f77d5f..24aab19 100644
--- a/Source/core/html/HTMLMeterElement.cpp
+++ b/Source/core/html/HTMLMeterElement.cpp
@@ -23,6 +23,7 @@
 #include "core/html/HTMLMeterElement.h"
 
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ExceptionCode.h"
@@ -37,10 +38,9 @@
 
 using namespace HTMLNames;
 
-HTMLMeterElement::HTMLMeterElement(const QualifiedName& tagName, Document& document)
-    : LabelableElement(tagName, document)
+HTMLMeterElement::HTMLMeterElement(Document& document)
+    : LabelableElement(meterTag, document)
 {
-    ASSERT(hasTagName(meterTag));
     ScriptWrappable::init(this);
 }
 
@@ -48,9 +48,9 @@
 {
 }
 
-PassRefPtr<HTMLMeterElement> HTMLMeterElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLMeterElement> HTMLMeterElement::create(Document& document)
 {
-    RefPtr<HTMLMeterElement> meter = adoptRef(new HTMLMeterElement(tagName, document));
+    RefPtr<HTMLMeterElement> meter = adoptRef(new HTMLMeterElement(document));
     meter->ensureUserAgentShadowRoot();
     return meter;
 }
@@ -73,90 +73,90 @@
 
 double HTMLMeterElement::min() const
 {
-    return parseToDoubleForNumberType(getAttribute(minAttr), 0);
+    return getFloatingPointAttribute(minAttr, 0);
 }
 
-void HTMLMeterElement::setMin(double min, ExceptionState& es)
+void HTMLMeterElement::setMin(double min, ExceptionState& exceptionState)
 {
     if (!std::isfinite(min)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("min", "HTMLMeterElement", ExceptionMessages::notAFiniteNumber(min)));
         return;
     }
-    setAttribute(minAttr, String::number(min));
+    setFloatingPointAttribute(minAttr, min);
 }
 
 double HTMLMeterElement::max() const
 {
-    return std::max(parseToDoubleForNumberType(getAttribute(maxAttr), std::max(1.0, min())), min());
+    return std::max(getFloatingPointAttribute(maxAttr, std::max(1.0, min())), min());
 }
 
-void HTMLMeterElement::setMax(double max, ExceptionState& es)
+void HTMLMeterElement::setMax(double max, ExceptionState& exceptionState)
 {
     if (!std::isfinite(max)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("max", "HTMLMeterElement", ExceptionMessages::notAFiniteNumber(max)));
         return;
     }
-    setAttribute(maxAttr, String::number(max));
+    setFloatingPointAttribute(maxAttr, max);
 }
 
 double HTMLMeterElement::value() const
 {
-    double value = parseToDoubleForNumberType(getAttribute(valueAttr), 0);
+    double value = getFloatingPointAttribute(valueAttr, 0);
     return std::min(std::max(value, min()), max());
 }
 
-void HTMLMeterElement::setValue(double value, ExceptionState& es)
+void HTMLMeterElement::setValue(double value, ExceptionState& exceptionState)
 {
     if (!std::isfinite(value)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("value", "HTMLMeterElement", ExceptionMessages::notAFiniteNumber(value)));
         return;
     }
-    setAttribute(valueAttr, String::number(value));
+    setFloatingPointAttribute(valueAttr, value);
 }
 
 double HTMLMeterElement::low() const
 {
-    double low = parseToDoubleForNumberType(getAttribute(lowAttr), min());
+    double low = getFloatingPointAttribute(lowAttr, min());
     return std::min(std::max(low, min()), max());
 }
 
-void HTMLMeterElement::setLow(double low, ExceptionState& es)
+void HTMLMeterElement::setLow(double low, ExceptionState& exceptionState)
 {
     if (!std::isfinite(low)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("low", "HTMLMeterElement", ExceptionMessages::notAFiniteNumber(low)));
         return;
     }
-    setAttribute(lowAttr, String::number(low));
+    setFloatingPointAttribute(lowAttr, low);
 }
 
 double HTMLMeterElement::high() const
 {
-    double high = parseToDoubleForNumberType(getAttribute(highAttr), max());
+    double high = getFloatingPointAttribute(highAttr, max());
     return std::min(std::max(high, low()), max());
 }
 
-void HTMLMeterElement::setHigh(double high, ExceptionState& es)
+void HTMLMeterElement::setHigh(double high, ExceptionState& exceptionState)
 {
     if (!std::isfinite(high)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("high", "HTMLMeterElement", ExceptionMessages::notAFiniteNumber(high)));
         return;
     }
-    setAttribute(highAttr, String::number(high));
+    setFloatingPointAttribute(highAttr, high);
 }
 
 double HTMLMeterElement::optimum() const
 {
-    double optimum = parseToDoubleForNumberType(getAttribute(optimumAttr), (max() + min()) / 2);
+    double optimum = getFloatingPointAttribute(optimumAttr, (max() + min()) / 2);
     return std::min(std::max(optimum, min()), max());
 }
 
-void HTMLMeterElement::setOptimum(double optimum, ExceptionState& es)
+void HTMLMeterElement::setOptimum(double optimum, ExceptionState& exceptionState)
 {
     if (!std::isfinite(optimum)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("optimum", "HTMLMeterElement", ExceptionMessages::notAFiniteNumber(optimum)));
         return;
     }
-    setAttribute(optimumAttr, String::number(optimum));
+    setFloatingPointAttribute(optimumAttr, optimum);
 }
 
 HTMLMeterElement::GaugeRegion HTMLMeterElement::gaugeRegion() const
@@ -217,16 +217,15 @@
         return toRenderMeter(renderer());
 
     RenderObject* renderObject = userAgentShadowRoot()->firstChild()->renderer();
-    ASSERT(!renderObject || renderObject->isMeter());
     return toRenderMeter(renderObject);
 }
 
-void HTMLMeterElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLMeterElement::didAddUserAgentShadowRoot(ShadowRoot& root)
 {
     ASSERT(!m_value);
 
     RefPtr<MeterInnerElement> inner = MeterInnerElement::create(document());
-    root->appendChild(inner);
+    root.appendChild(inner);
 
     RefPtr<MeterBarElement> bar = MeterBarElement::create(document());
     m_value = MeterValueElement::create(document());
diff --git a/Source/core/html/HTMLMeterElement.h b/Source/core/html/HTMLMeterElement.h
index cfdbaf4..e815e60 100644
--- a/Source/core/html/HTMLMeterElement.h
+++ b/Source/core/html/HTMLMeterElement.h
@@ -31,7 +31,7 @@
 
 class HTMLMeterElement FINAL : public LabelableElement {
 public:
-    static PassRefPtr<HTMLMeterElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLMeterElement> create(Document&);
 
     enum GaugeRegion {
         GaugeRegionOptimum,
@@ -63,7 +63,7 @@
     bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLMeterElement(const QualifiedName&, Document&);
+    explicit HTMLMeterElement(Document&);
     virtual ~HTMLMeterElement();
 
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
@@ -76,7 +76,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
     void didElementStateChange();
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
 
     RefPtr<MeterValueElement> m_value;
 };
diff --git a/Source/core/html/HTMLMeterElement.idl b/Source/core/html/HTMLMeterElement.idl
index 12f067a..fde8591 100644
--- a/Source/core/html/HTMLMeterElement.idl
+++ b/Source/core/html/HTMLMeterElement.idl
@@ -18,11 +18,11 @@
  */
 
 interface HTMLMeterElement : HTMLElement {
-             [SetterRaisesException] attribute double value;
-             [SetterRaisesException] attribute double min;
-             [SetterRaisesException] attribute double max;
-             [SetterRaisesException] attribute double low;
-             [SetterRaisesException] attribute double high;
-             [SetterRaisesException] attribute double optimum;
+             [RaisesException=Setter] attribute double value;
+             [RaisesException=Setter] attribute double min;
+             [RaisesException=Setter] attribute double max;
+             [RaisesException=Setter] attribute double low;
+             [RaisesException=Setter] attribute double high;
+             [RaisesException=Setter] attribute double optimum;
     readonly attribute NodeList labels;
 };
diff --git a/Source/core/html/HTMLNameCollection.cpp b/Source/core/html/HTMLNameCollection.cpp
index 0706e81..b11ca18 100644
--- a/Source/core/html/HTMLNameCollection.cpp
+++ b/Source/core/html/HTMLNameCollection.cpp
@@ -27,6 +27,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeRareData.h"
+#include "core/html/HTMLObjectElement.h"
 
 namespace WebCore {
 
@@ -54,11 +55,11 @@
 
     Element* current;
     if (!previous)
-        current = ElementTraversal::firstWithin(ownerNode());
+        current = ElementTraversal::firstWithin(*ownerNode());
     else
-        current = ElementTraversal::next(previous, ownerNode());
+        current = ElementTraversal::next(*previous, ownerNode());
 
-    for (; current; current = ElementTraversal::next(current, ownerNode())) {
+    for (; current; current = ElementTraversal::next(*current, ownerNode())) {
         switch (type()) {
         case WindowNamedItems:
             // find only images, forms, applets, embeds and objects by name,
@@ -81,9 +82,13 @@
             if (current->hasTagName(formTag) || current->hasTagName(embedTag) || current->hasTagName(iframeTag)) {
                 if (current->getNameAttribute() == m_name)
                     return current;
-            } else if (current->hasTagName(appletTag) || current->hasTagName(objectTag)) {
+            } else if (current->hasTagName(appletTag)) {
                 if (current->getNameAttribute() == m_name || current->getIdAttribute() == m_name)
                     return current;
+            } else if (current->hasTagName(objectTag)) {
+                if ((current->getNameAttribute() == m_name || current->getIdAttribute() == m_name)
+                    && toHTMLObjectElement(current)->isDocNamedItem())
+                    return current;
             } else if (current->hasTagName(imgTag)) {
                 if (current->getNameAttribute() == m_name || (current->getIdAttribute() == m_name && current->hasName()))
                     return current;
diff --git a/Source/core/html/HTMLOListElement.cpp b/Source/core/html/HTMLOListElement.cpp
index 8ad5bbb..0367551 100644
--- a/Source/core/html/HTMLOListElement.cpp
+++ b/Source/core/html/HTMLOListElement.cpp
@@ -32,26 +32,20 @@
 
 using namespace HTMLNames;
 
-HTMLOListElement::HTMLOListElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLOListElement::HTMLOListElement(Document& document)
+    : HTMLElement(olTag, document)
     , m_start(0xBADBEEF)
     , m_itemCount(0)
     , m_hasExplicitStart(false)
     , m_isReversed(false)
     , m_shouldRecalculateItemCount(false)
 {
-    ASSERT(hasTagName(olTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLOListElement> HTMLOListElement::create(Document& document)
 {
-    return adoptRef(new HTMLOListElement(olTag, document));
-}
-
-PassRefPtr<HTMLOListElement> HTMLOListElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLOListElement(tagName, document));
+    return adoptRef(new HTMLOListElement(document));
 }
 
 bool HTMLOListElement::isPresentationAttribute(const QualifiedName& name) const
@@ -101,7 +95,7 @@
 
 void HTMLOListElement::setStart(int start)
 {
-    setAttribute(startAttr, String::number(start));
+    setIntegralAttribute(startAttr, start);
 }
 
 void HTMLOListElement::updateItemValues()
diff --git a/Source/core/html/HTMLOListElement.h b/Source/core/html/HTMLOListElement.h
index d3dd1a2..0da2e2c 100644
--- a/Source/core/html/HTMLOListElement.h
+++ b/Source/core/html/HTMLOListElement.h
@@ -30,7 +30,6 @@
 class HTMLOListElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLOListElement> create(Document&);
-    static PassRefPtr<HTMLOListElement> create(const QualifiedName&, Document&);
 
     int start() const { return m_hasExplicitStart ? m_start : (m_isReversed ? itemCount() : 1); }
     void setStart(int);
@@ -40,7 +39,7 @@
     void itemCountChanged() { m_shouldRecalculateItemCount = true; }
 
 private:
-    HTMLOListElement(const QualifiedName&, Document&);
+    explicit HTMLOListElement(Document&);
 
     void updateItemValues();
 
diff --git a/Source/core/html/HTMLOListElement.idl b/Source/core/html/HTMLOListElement.idl
index 0168f6d..01cbabd 100644
--- a/Source/core/html/HTMLOListElement.idl
+++ b/Source/core/html/HTMLOListElement.idl
@@ -21,6 +21,5 @@
     [Reflect] attribute boolean compact;
     attribute long start;
     [Reflect] attribute boolean reversed;
-    [Reflect, TreatNullAs=NullString] attribute DOMString type;
+    [Reflect] attribute DOMString type;
 };
-
diff --git a/Source/core/html/HTMLObjectElement.cpp b/Source/core/html/HTMLObjectElement.cpp
index e3b43d9..e6f66a8 100644
--- a/Source/core/html/HTMLObjectElement.cpp
+++ b/Source/core/html/HTMLObjectElement.cpp
@@ -39,20 +39,20 @@
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/page/Settings.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/RenderEmbeddedObject.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/Widget.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-inline HTMLObjectElement::HTMLObjectElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
-    : HTMLPlugInElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
+inline HTMLObjectElement::HTMLObjectElement(Document& document, HTMLFormElement* form, bool createdByParser)
+    : HTMLPlugInElement(objectTag, document, createdByParser, ShouldNotPreferPlugInsForImages)
+    , m_docNamedItem(true)
     , m_useFallbackContent(false)
 {
-    ASSERT(hasTagName(objectTag));
     setForm(form ? form : findFormAncestor());
     ScriptWrappable::init(this);
 }
@@ -62,9 +62,9 @@
     setForm(0);
 }
 
-PassRefPtr<HTMLObjectElement> HTMLObjectElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLObjectElement> HTMLObjectElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
 {
-    return adoptRef(new HTMLObjectElement(tagName, document, form, createdByParser));
+    return adoptRef(new HTMLObjectElement(document, form, createdByParser));
 }
 
 RenderWidget* HTMLObjectElement::existingRenderWidget() const
@@ -334,6 +334,7 @@
 
 void HTMLObjectElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
+    updateDocNamedItem();
     if (inDocument() && !useFallbackContent()) {
         setNeedsWidgetUpdate(true);
         setNeedsStyleRecalc();
@@ -387,12 +388,72 @@
     reattachFallbackContent();
 }
 
+// FIXME: This should be removed, all callers are almost certainly wrong.
+static bool isRecognizedTagName(const QualifiedName& tagName)
+{
+    DEFINE_STATIC_LOCAL(HashSet<StringImpl*>, tagList, ());
+    if (tagList.isEmpty()) {
+        const QualifiedName* const* tags = HTMLNames::getHTMLTags();
+        for (size_t i = 0; i < HTMLNames::HTMLTagsCount; i++) {
+            if (*tags[i] == bgsoundTag
+                || *tags[i] == commandTag
+                || *tags[i] == detailsTag
+                || *tags[i] == figcaptionTag
+                || *tags[i] == figureTag
+                || *tags[i] == summaryTag
+                || *tags[i] == trackTag) {
+                // Even though we have atoms for these tags, we don't want to
+                // treat them as "recognized tags" for the purpose of parsing
+                // because that changes how we parse documents.
+                continue;
+            }
+            tagList.add(tags[i]->localName().impl());
+        }
+    }
+    return tagList.contains(tagName.localName().impl());
+}
+
+void HTMLObjectElement::updateDocNamedItem()
+{
+    // The rule is "<object> elements with no children other than
+    // <param> elements, unknown elements and whitespace can be
+    // found by name in a document, and other <object> elements cannot."
+    bool wasNamedItem = m_docNamedItem;
+    bool isNamedItem = true;
+    Node* child = firstChild();
+    while (child && isNamedItem) {
+        if (child->isElementNode()) {
+            Element* element = toElement(child);
+            // FIXME: Use of isRecognizedTagName is almost certainly wrong here.
+            if (isRecognizedTagName(element->tagQName()) && !element->hasTagName(paramTag))
+                isNamedItem = false;
+        } else if (child->isTextNode()) {
+            if (!toText(child)->containsOnlyWhitespace())
+                isNamedItem = false;
+        } else {
+            isNamedItem = false;
+        }
+        child = child->nextSibling();
+    }
+    if (isNamedItem != wasNamedItem && document().isHTMLDocument()) {
+        HTMLDocument& document = toHTMLDocument(this->document());
+        if (isNamedItem) {
+            document.addNamedItem(getNameAttribute());
+            document.addExtraNamedItem(getIdAttribute());
+        } else {
+            document.removeNamedItem(getNameAttribute());
+            document.removeExtraNamedItem(getIdAttribute());
+        }
+    }
+    m_docNamedItem = isNamedItem;
+}
+
 bool HTMLObjectElement::containsJavaApplet() const
 {
     if (MIMETypeRegistry::isJavaAppletMIMEType(getAttribute(typeAttr)))
         return true;
 
-    for (Element* child = ElementTraversal::firstWithin(this); child; child = ElementTraversal::nextSkippingChildren(child, this)) {
+    for (Element* child = ElementTraversal::firstWithin(*this); child; child = ElementTraversal::nextSkippingChildren(*child, this)) {
         if (child->hasTagName(paramTag)
                 && equalIgnoringCase(child->getNameAttribute(), "type")
                 && MIMETypeRegistry::isJavaAppletMIMEType(child->getAttribute(valueAttr).string()))
diff --git a/Source/core/html/HTMLObjectElement.h b/Source/core/html/HTMLObjectElement.h
index e0a0026..049cdfe 100644
--- a/Source/core/html/HTMLObjectElement.h
+++ b/Source/core/html/HTMLObjectElement.h
@@ -32,9 +32,11 @@
 
 class HTMLObjectElement FINAL : public HTMLPlugInElement, public FormAssociatedElement {
 public:
-    static PassRefPtr<HTMLObjectElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+    static PassRefPtr<HTMLObjectElement> create(Document&, HTMLFormElement*, bool createdByParser);
     virtual ~HTMLObjectElement();
 
+    bool isDocNamedItem() const { return m_docNamedItem; }
+
     const String& classId() const { return m_classId; }
 
     bool containsJavaApplet() const;
@@ -65,7 +67,7 @@
     virtual bool canContainRangeEndPoint() const { return useFallbackContent(); }
 
 private:
-    HTMLObjectElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+    HTMLObjectElement(Document&, HTMLFormElement*, bool createdByParser);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -87,6 +89,7 @@
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 
     virtual void updateWidget(PluginCreationOption);
+    void updateDocNamedItem();
 
     void reattachFallbackContent();
 
@@ -103,10 +106,11 @@
     virtual void derefFormAssociatedElement() { deref(); }
     virtual HTMLFormElement* virtualForm() const;
 
-    virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return true; }
-    virtual bool shouldRegisterAsExtraNamedItem() const OVERRIDE { return true; }
+    virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return isDocNamedItem(); }
+    virtual bool shouldRegisterAsExtraNamedItem() const OVERRIDE { return isDocNamedItem(); }
 
     String m_classId;
+    bool m_docNamedItem : 1;
     bool m_useFallbackContent : 1;
 };
 
@@ -122,6 +126,16 @@
     return objectElement;
 }
 
+inline const HTMLObjectElement& toHTMLObjectElement(const FormAssociatedElement& element)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!element.isFormControlElement());
+    const HTMLObjectElement& objectElement = static_cast<const HTMLObjectElement&>(element);
+    // We need to assert after the cast because FormAssociatedElement doesn't
+    // have hasTagName.
+    ASSERT_WITH_SECURITY_IMPLICATION(objectElement.hasTagName(HTMLNames::objectTag));
+    return objectElement;
+}
+
 }
 
 #endif
diff --git a/Source/core/html/HTMLObjectElement.idl b/Source/core/html/HTMLObjectElement.idl
index 02b1a80..11ef0dd 100644
--- a/Source/core/html/HTMLObjectElement.idl
+++ b/Source/core/html/HTMLObjectElement.idl
@@ -45,12 +45,12 @@
     void setCustomValidity([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString error);
 
     // Introduced in DOM Level 2:
-    [CheckSecurityForNode] readonly attribute Document contentDocument;
+    [CheckSecurity=Node] readonly attribute Document contentDocument;
     [Custom, NotEnumerable] getter boolean (unsigned long index);
     [Custom] setter boolean (unsigned long index, Node value);
     [Custom, NotEnumerable] getter Node (DOMString name);
     [Custom] setter Node (DOMString name, Node value);
 
-    [CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
 };
 
diff --git a/Source/core/html/HTMLOptGroupElement.cpp b/Source/core/html/HTMLOptGroupElement.cpp
index 5bd6874..c9963b0 100644
--- a/Source/core/html/HTMLOptGroupElement.cpp
+++ b/Source/core/html/HTMLOptGroupElement.cpp
@@ -35,17 +35,16 @@
 
 using namespace HTMLNames;
 
-inline HTMLOptGroupElement::HTMLOptGroupElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLOptGroupElement::HTMLOptGroupElement(Document& document)
+    : HTMLElement(optgroupTag, document)
 {
-    ASSERT(hasTagName(optgroupTag));
     setHasCustomStyleCallbacks();
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLOptGroupElement> HTMLOptGroupElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLOptGroupElement> HTMLOptGroupElement::create(Document& document)
 {
-    return adoptRef(new HTMLOptGroupElement(tagName, document));
+    return adoptRef(new HTMLOptGroupElement(document));
 }
 
 bool HTMLOptGroupElement::isDisabledFormControl() const
diff --git a/Source/core/html/HTMLOptGroupElement.h b/Source/core/html/HTMLOptGroupElement.h
index 383bebe..54ed7b5 100644
--- a/Source/core/html/HTMLOptGroupElement.h
+++ b/Source/core/html/HTMLOptGroupElement.h
@@ -32,7 +32,7 @@
 
 class HTMLOptGroupElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLOptGroupElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLOptGroupElement> create(Document&);
 
     virtual bool isDisabledFormControl() const OVERRIDE;
     HTMLSelectElement* ownerSelectElement() const;
@@ -40,7 +40,7 @@
     String groupLabelText() const;
 
 private:
-    HTMLOptGroupElement(const QualifiedName&, Document&);
+    explicit HTMLOptGroupElement(Document&);
 
     virtual const AtomicString& formControlType() const;
     virtual bool rendererIsFocusable() const OVERRIDE;
diff --git a/Source/core/html/HTMLOptionElement.cpp b/Source/core/html/HTMLOptionElement.cpp
index 85dffe1..614e9cc 100644
--- a/Source/core/html/HTMLOptionElement.cpp
+++ b/Source/core/html/HTMLOptionElement.cpp
@@ -46,35 +46,29 @@
 
 using namespace HTMLNames;
 
-HTMLOptionElement::HTMLOptionElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLOptionElement::HTMLOptionElement(Document& document)
+    : HTMLElement(optionTag, document)
     , m_disabled(false)
     , m_isSelected(false)
 {
-    ASSERT(hasTagName(optionTag));
     setHasCustomStyleCallbacks();
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(Document& document)
 {
-    return adoptRef(new HTMLOptionElement(optionTag, document));
-}
-
-PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLOptionElement(tagName, document));
+    return adoptRef(new HTMLOptionElement(document));
 }
 
 PassRefPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document& document, const String& data, const String& value,
-    bool defaultSelected, bool selected, ExceptionState& es)
+    bool defaultSelected, bool selected, ExceptionState& exceptionState)
 {
-    RefPtr<HTMLOptionElement> element = adoptRef(new HTMLOptionElement(optionTag, document));
+    RefPtr<HTMLOptionElement> element = adoptRef(new HTMLOptionElement(document));
 
     RefPtr<Text> text = Text::create(document, data.isNull() ? "" : data);
 
-    element->appendChild(text.release(), es);
-    if (es.hadException())
+    element->appendChild(text.release(), exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     if (!value.isNull())
@@ -126,7 +120,7 @@
     return text.stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
 }
 
-void HTMLOptionElement::setText(const String &text, ExceptionState& es)
+void HTMLOptionElement::setText(const String &text, ExceptionState& exceptionState)
 {
     RefPtr<Node> protectFromMutationEvents(this);
 
@@ -143,7 +137,7 @@
         toText(child)->setData(text);
     else {
         removeChildren();
-        appendChild(Text::create(document(), text), es);
+        appendChild(Text::create(document(), text), exceptionState);
     }
 
     if (selectIsMenuList && select->selectedIndex() != oldSelectedIndex)
@@ -365,9 +359,9 @@
             text.append(node->nodeValue());
         // Text nodes inside script elements are not part of the option text.
         if (node->isElementNode() && toScriptLoaderIfPossible(toElement(node)))
-            node = NodeTraversal::nextSkippingChildren(node, this);
+            node = NodeTraversal::nextSkippingChildren(*node, this);
         else
-            node = NodeTraversal::next(node, this);
+            node = NodeTraversal::next(*node, this);
     }
     return text.toString();
 }
diff --git a/Source/core/html/HTMLOptionElement.h b/Source/core/html/HTMLOptionElement.h
index e3fdad4..f4a8906 100644
--- a/Source/core/html/HTMLOptionElement.h
+++ b/Source/core/html/HTMLOptionElement.h
@@ -36,7 +36,6 @@
 class HTMLOptionElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLOptionElement> create(Document&);
-    static PassRefPtr<HTMLOptionElement> create(const QualifiedName&, Document&);
     static PassRefPtr<HTMLOptionElement> createForJSConstructor(Document&, const String& data, const String& value,
         bool defaultSelected, bool selected, ExceptionState&);
 
@@ -66,7 +65,7 @@
     void setSelectedState(bool);
 
 private:
-    HTMLOptionElement(const QualifiedName&, Document&);
+    explicit HTMLOptionElement(Document&);
 
     virtual bool rendererIsFocusable() const OVERRIDE;
     virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
diff --git a/Source/core/html/HTMLOptionElement.idl b/Source/core/html/HTMLOptionElement.idl
index d315551..41c6592 100644
--- a/Source/core/html/HTMLOptionElement.idl
+++ b/Source/core/html/HTMLOptionElement.idl
@@ -20,7 +20,7 @@
 
 [
     NamedConstructor=Option([Default=NullString] optional DOMString data, [Default=NullString] optional DOMString value, [Default=Undefined] optional boolean defaultSelected, [Default=Undefined] optional boolean selected),
-    ConstructorRaisesException
+    RaisesException=Constructor
 ] interface HTMLOptionElement : HTMLElement {
     [Reflect] attribute boolean disabled;
     readonly attribute HTMLFormElement form;
@@ -29,6 +29,6 @@
     attribute boolean selected;
     attribute DOMString value;
 
-    [SetterRaisesException] attribute DOMString text;
+    [RaisesException=Setter] attribute DOMString text;
     readonly attribute long index;
 };
diff --git a/Source/core/html/HTMLOptionsCollection.cpp b/Source/core/html/HTMLOptionsCollection.cpp
index 94c808c..34154a0 100644
--- a/Source/core/html/HTMLOptionsCollection.cpp
+++ b/Source/core/html/HTMLOptionsCollection.cpp
@@ -21,6 +21,7 @@
 #include "config.h"
 #include "core/html/HTMLOptionsCollection.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/NamedNodesCollection.h"
@@ -41,33 +42,33 @@
     return adoptRef(new HTMLOptionsCollection(select));
 }
 
-void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, ExceptionState& es)
+void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, ExceptionState& exceptionState)
 {
-    add(element, length(), es);
+    add(element, length(), exceptionState);
 }
 
-void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, int index, ExceptionState& es)
+void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, int index, ExceptionState& exceptionState)
 {
     HTMLOptionElement* newOption = element.get();
 
     if (!newOption) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::failedToExecute("add", "HTMLOptionsCollection", "The element provided was not an HTMLOptionElement."));
         return;
     }
 
     if (index < -1) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("add", "HTMLOptionsCollection", "The index provided (" + String::number(index) + ") is less than -1."));
         return;
     }
 
     HTMLSelectElement* select = toHTMLSelectElement(ownerNode());
 
     if (index == -1 || unsigned(index) >= length())
-        select->add(newOption, 0, es);
+        select->add(newOption, 0, exceptionState);
     else
-        select->add(newOption, toHTMLOptionElement(item(index)), es);
+        select->add(newOption, toHTMLOptionElement(item(index)), exceptionState);
 
-    ASSERT(!es.hadException());
+    ASSERT(!exceptionState.hadException());
 }
 
 void HTMLOptionsCollection::remove(int index)
@@ -90,9 +91,9 @@
     toHTMLSelectElement(ownerNode())->setSelectedIndex(index);
 }
 
-void HTMLOptionsCollection::setLength(unsigned length, ExceptionState& es)
+void HTMLOptionsCollection::setLength(unsigned length, ExceptionState& exceptionState)
 {
-    toHTMLSelectElement(ownerNode())->setLength(length, es);
+    toHTMLSelectElement(ownerNode())->setLength(length, exceptionState);
 }
 
 void HTMLOptionsCollection::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Node>& returnValue1)
@@ -113,21 +114,21 @@
     returnValue0 = NamedNodesCollection::create(namedItems);
 }
 
-bool HTMLOptionsCollection::anonymousIndexedSetterRemove(unsigned index, ExceptionState& es)
+bool HTMLOptionsCollection::anonymousIndexedSetterRemove(unsigned index, ExceptionState& exceptionState)
 {
     HTMLSelectElement* base = toHTMLSelectElement(ownerNode());
     base->remove(index);
     return true;
 }
 
-bool HTMLOptionsCollection::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& es)
+bool HTMLOptionsCollection::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& exceptionState)
 {
     HTMLSelectElement* base = toHTMLSelectElement(ownerNode());
     if (!value) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::failedToSet(String::number(index), "HTMLOptionsCollection", "The element provided was not an HTMLOptionElement."));
         return true;
     }
-    base->setOption(index, value.get(), es);
+    base->setOption(index, value.get(), exceptionState);
     return true;
 }
 
diff --git a/Source/core/html/HTMLOptionsCollection.idl b/Source/core/html/HTMLOptionsCollection.idl
index aa47617..32c4147 100644
--- a/Source/core/html/HTMLOptionsCollection.idl
+++ b/Source/core/html/HTMLOptionsCollection.idl
@@ -20,11 +20,11 @@
  */
 
 [
-    GenerateIsReachable=ownerNode,
-    DependentLifetime
+    DependentLifetime,
+    GenerateVisitDOMWrapper=ownerNode,
 ] interface HTMLOptionsCollection : HTMLCollection {
     attribute long selectedIndex;
-    [CustomSetter, SetterRaisesException] attribute unsigned long length;
+    [Custom=Setter, RaisesException=Setter] attribute unsigned long length;
     [ImplementedAs=item] getter Node(unsigned long index);
     [ImplementedAs=anonymousIndexedSetter, RaisesException] setter HTMLOptionElement (unsigned long index, [TreatNullAs=anonymousIndexedSetterRemove, TreatUndefinedAs=anonymousIndexedSetterRemove] HTMLOptionElement value);
     [ImplementedAs=anonymousNamedGetter, NotEnumerable] getter (NodeList or Node)(DOMString name);
diff --git a/Source/core/html/HTMLOutputElement.cpp b/Source/core/html/HTMLOutputElement.cpp
index 38de4bf..b0e9e03 100644
--- a/Source/core/html/HTMLOutputElement.cpp
+++ b/Source/core/html/HTMLOutputElement.cpp
@@ -36,8 +36,8 @@
 
 namespace WebCore {
 
-inline HTMLOutputElement::HTMLOutputElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
-    : HTMLFormControlElement(tagName, document, form)
+inline HTMLOutputElement::HTMLOutputElement(Document& document, HTMLFormElement* form)
+    : HTMLFormControlElement(HTMLNames::outputTag, document, form)
     , m_isDefaultValueMode(true)
     , m_isSetTextContentInProgress(false)
     , m_defaultValue("")
@@ -46,9 +46,9 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLOutputElement> HTMLOutputElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLOutputElement> HTMLOutputElement::create(Document& document, HTMLFormElement* form)
 {
-    return adoptRef(new HTMLOutputElement(tagName, document, form));
+    return adoptRef(new HTMLOutputElement(document, form));
 }
 
 const AtomicString& HTMLOutputElement::formControlType() const
diff --git a/Source/core/html/HTMLOutputElement.h b/Source/core/html/HTMLOutputElement.h
index 75ac553..bf1e469 100644
--- a/Source/core/html/HTMLOutputElement.h
+++ b/Source/core/html/HTMLOutputElement.h
@@ -38,7 +38,7 @@
 
 class HTMLOutputElement FINAL : public HTMLFormControlElement {
 public:
-    static PassRefPtr<HTMLOutputElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+    static PassRefPtr<HTMLOutputElement> create(Document&, HTMLFormElement*);
 
     virtual bool willValidate() const { return false; }
 
@@ -52,7 +52,7 @@
     virtual bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLOutputElement(const QualifiedName&, Document&, HTMLFormElement*);
+    HTMLOutputElement(Document&, HTMLFormElement*);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual const AtomicString& formControlType() const;
diff --git a/Source/core/html/HTMLParagraphElement.cpp b/Source/core/html/HTMLParagraphElement.cpp
index 626e8d5..4598008 100644
--- a/Source/core/html/HTMLParagraphElement.cpp
+++ b/Source/core/html/HTMLParagraphElement.cpp
@@ -31,21 +31,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLParagraphElement::HTMLParagraphElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLParagraphElement::HTMLParagraphElement(Document& document)
+    : HTMLElement(pTag, document)
 {
-    ASSERT(hasTagName(pTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(Document& document)
 {
-    return adoptRef(new HTMLParagraphElement(pTag, document));
-}
-
-PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLParagraphElement(tagName, document));
+    return adoptRef(new HTMLParagraphElement(document));
 }
 
 bool HTMLParagraphElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLParagraphElement.h b/Source/core/html/HTMLParagraphElement.h
index 9e80fda..4bfbbf6 100644
--- a/Source/core/html/HTMLParagraphElement.h
+++ b/Source/core/html/HTMLParagraphElement.h
@@ -30,10 +30,9 @@
 class HTMLParagraphElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLParagraphElement> create(Document&);
-    static PassRefPtr<HTMLParagraphElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLParagraphElement(const QualifiedName&, Document&);
+    explicit HTMLParagraphElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLParagraphElement.idl b/Source/core/html/HTMLParagraphElement.idl
index 55787c3..83242a1 100644
--- a/Source/core/html/HTMLParagraphElement.idl
+++ b/Source/core/html/HTMLParagraphElement.idl
@@ -18,6 +18,5 @@
  */
 
 interface HTMLParagraphElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString] attribute DOMString align;
+    [Reflect] attribute DOMString align;
 };
-
diff --git a/Source/core/html/HTMLParamElement.cpp b/Source/core/html/HTMLParamElement.cpp
index cf55848..d1e1cdd 100644
--- a/Source/core/html/HTMLParamElement.cpp
+++ b/Source/core/html/HTMLParamElement.cpp
@@ -31,16 +31,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLParamElement::HTMLParamElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLParamElement::HTMLParamElement(Document& document)
+    : HTMLElement(paramTag, document)
 {
-    ASSERT(hasTagName(paramTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLParamElement> HTMLParamElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLParamElement> HTMLParamElement::create(Document& document)
 {
-    return adoptRef(new HTMLParamElement(tagName, document));
+    return adoptRef(new HTMLParamElement(document));
 }
 
 String HTMLParamElement::name() const
diff --git a/Source/core/html/HTMLParamElement.h b/Source/core/html/HTMLParamElement.h
index a5d07e2..ece3544 100644
--- a/Source/core/html/HTMLParamElement.h
+++ b/Source/core/html/HTMLParamElement.h
@@ -29,7 +29,7 @@
 
 class HTMLParamElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLParamElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLParamElement> create(Document&);
 
     String name() const;
     String value() const;
@@ -37,7 +37,7 @@
     static bool isURLParameter(const String&);
 
 private:
-    HTMLParamElement(const QualifiedName&, Document&);
+    explicit HTMLParamElement(Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
diff --git a/Source/core/html/HTMLPlugInElement.cpp b/Source/core/html/HTMLPlugInElement.cpp
index fb74f0f..ebbbdd8 100644
--- a/Source/core/html/HTMLPlugInElement.cpp
+++ b/Source/core/html/HTMLPlugInElement.cpp
@@ -38,15 +38,15 @@
 #include "core/page/EventHandler.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/plugins/PluginData.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderWidget.h"
 #include "platform/Logging.h"
+#include "platform/MIMETypeFromURL.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/Widget.h"
+#include "platform/plugins/PluginData.h"
 #include "wtf/UnusedParam.h"
 
 
@@ -306,7 +306,10 @@
 
 RenderWidget* HTMLPlugInElement::renderWidgetForJSBindings() const
 {
-    document().updateLayoutIgnorePendingStylesheets();
+    // Needs to load the plugin immediatedly because this function is called
+    // when JavaScript code accesses the plugin.
+    // FIXME: Check if dispatching events here is safe.
+    document().updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasksSynchronously);
     return existingRenderWidget();
 }
 
diff --git a/Source/core/html/HTMLProgressElement.cpp b/Source/core/html/HTMLProgressElement.cpp
index 1798437..46df763 100644
--- a/Source/core/html/HTMLProgressElement.cpp
+++ b/Source/core/html/HTMLProgressElement.cpp
@@ -23,6 +23,7 @@
 #include "core/html/HTMLProgressElement.h"
 
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ExceptionCode.h"
@@ -38,11 +39,10 @@
 const double HTMLProgressElement::IndeterminatePosition = -1;
 const double HTMLProgressElement::InvalidPosition = -2;
 
-HTMLProgressElement::HTMLProgressElement(const QualifiedName& tagName, Document& document)
-    : LabelableElement(tagName, document)
+HTMLProgressElement::HTMLProgressElement(Document& document)
+    : LabelableElement(progressTag, document)
     , m_value(0)
 {
-    ASSERT(hasTagName(progressTag));
     ScriptWrappable::init(this);
 }
 
@@ -50,9 +50,9 @@
 {
 }
 
-PassRefPtr<HTMLProgressElement> HTMLProgressElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLProgressElement> HTMLProgressElement::create(Document& document)
 {
-    RefPtr<HTMLProgressElement> progress = adoptRef(new HTMLProgressElement(tagName, document));
+    RefPtr<HTMLProgressElement> progress = adoptRef(new HTMLProgressElement(document));
     progress->ensureUserAgentShadowRoot();
     return progress.release();
 }
@@ -94,32 +94,33 @@
 
 double HTMLProgressElement::value() const
 {
-    double value = parseToDoubleForNumberType(fastGetAttribute(valueAttr));
+    double value = getFloatingPointAttribute(valueAttr);
     return !std::isfinite(value) || value < 0 ? 0 : std::min(value, max());
 }
 
-void HTMLProgressElement::setValue(double value, ExceptionState& es)
+void HTMLProgressElement::setValue(double value, ExceptionState& exceptionState)
 {
     if (!std::isfinite(value)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("value", "HTMLProgressElement", ExceptionMessages::notAFiniteNumber(value)));
         return;
     }
-    setAttribute(valueAttr, String::number(value >= 0 ? value : 0));
+    setFloatingPointAttribute(valueAttr, std::max(value, 0.));
 }
 
 double HTMLProgressElement::max() const
 {
-    double max = parseToDoubleForNumberType(getAttribute(maxAttr));
+    double max = getFloatingPointAttribute(maxAttr);
     return !std::isfinite(max) || max <= 0 ? 1 : max;
 }
 
-void HTMLProgressElement::setMax(double max, ExceptionState& es)
+void HTMLProgressElement::setMax(double max, ExceptionState& exceptionState)
 {
     if (!std::isfinite(max)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToSet("max", "HTMLProgressElement", ExceptionMessages::notAFiniteNumber(max)));
         return;
     }
-    setAttribute(maxAttr, String::number(max > 0 ? max : 1));
+    // FIXME: The specification says we should ignore the input value if it is inferior or equal to 0.
+    setFloatingPointAttribute(maxAttr, max > 0 ? max : 1);
 }
 
 double HTMLProgressElement::position() const
@@ -145,19 +146,19 @@
     }
 }
 
-void HTMLProgressElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLProgressElement::didAddUserAgentShadowRoot(ShadowRoot& root)
 {
     ASSERT(!m_value);
 
     RefPtr<ProgressInnerElement> inner = ProgressInnerElement::create(document());
-    inner->setPart(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
-    root->appendChild(inner);
+    inner->setPseudo(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
+    root.appendChild(inner);
 
     RefPtr<ProgressBarElement> bar = ProgressBarElement::create(document());
-    bar->setPart(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
+    bar->setPseudo(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
     RefPtr<ProgressValueElement> value = ProgressValueElement::create(document());
     m_value = value.get();
-    m_value->setPart(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
+    m_value->setPseudo(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
     m_value->setWidthPercentage(HTMLProgressElement::IndeterminatePosition * 100);
     bar->appendChild(m_value);
 
diff --git a/Source/core/html/HTMLProgressElement.h b/Source/core/html/HTMLProgressElement.h
index abb82aa..6162ded 100644
--- a/Source/core/html/HTMLProgressElement.h
+++ b/Source/core/html/HTMLProgressElement.h
@@ -34,7 +34,7 @@
     static const double IndeterminatePosition;
     static const double InvalidPosition;
 
-    static PassRefPtr<HTMLProgressElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLProgressElement> create(Document&);
 
     double value() const;
     void setValue(double, ExceptionState&);
@@ -47,7 +47,7 @@
     virtual bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLProgressElement(const QualifiedName&, Document&);
+    explicit HTMLProgressElement(Document&);
     virtual ~HTMLProgressElement();
 
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
@@ -62,7 +62,7 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
     void didElementStateChange();
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
     bool isDeterminate() const;
 
     ProgressValueElement* m_value;
diff --git a/Source/core/html/HTMLProgressElement.idl b/Source/core/html/HTMLProgressElement.idl
index a2f3f32..b2f5a9c 100644
--- a/Source/core/html/HTMLProgressElement.idl
+++ b/Source/core/html/HTMLProgressElement.idl
@@ -18,8 +18,8 @@
  */
 
 interface HTMLProgressElement : HTMLElement {
-             [SetterRaisesException] attribute  double                value;
-             [SetterRaisesException] attribute  double                max;
+             [RaisesException=Setter] attribute  double                value;
+             [RaisesException=Setter] attribute  double                max;
     readonly attribute  double                position;
     readonly attribute  NodeList              labels;
 };
diff --git a/Source/core/html/HTMLQuoteElement.idl b/Source/core/html/HTMLQuoteElement.idl
index 464fd0a..93a2aff 100644
--- a/Source/core/html/HTMLQuoteElement.idl
+++ b/Source/core/html/HTMLQuoteElement.idl
@@ -18,5 +18,5 @@
  */
 
 interface HTMLQuoteElement : HTMLElement {
-    [Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString cite;
+    [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString cite;
 };
diff --git a/Source/core/html/HTMLScriptElement.cpp b/Source/core/html/HTMLScriptElement.cpp
index 712f224..fd54cc2 100644
--- a/Source/core/html/HTMLScriptElement.cpp
+++ b/Source/core/html/HTMLScriptElement.cpp
@@ -37,17 +37,16 @@
 
 using namespace HTMLNames;
 
-inline HTMLScriptElement::HTMLScriptElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
-    : HTMLElement(tagName, document)
+inline HTMLScriptElement::HTMLScriptElement(Document& document, bool wasInsertedByParser, bool alreadyStarted)
+    : HTMLElement(scriptTag, document)
     , m_loader(ScriptLoader::create(this, wasInsertedByParser, alreadyStarted))
 {
-    ASSERT(hasTagName(scriptTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLScriptElement> HTMLScriptElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
+PassRefPtr<HTMLScriptElement> HTMLScriptElement::create(Document& document, bool wasInsertedByParser, bool alreadyStarted)
 {
-    return adoptRef(new HTMLScriptElement(tagName, document, wasInsertedByParser, alreadyStarted));
+    return adoptRef(new HTMLScriptElement(document, wasInsertedByParser, alreadyStarted));
 }
 
 bool HTMLScriptElement::isURLAttribute(const Attribute& attribute) const
@@ -173,7 +172,7 @@
 
 PassRefPtr<Element> HTMLScriptElement::cloneElementWithoutAttributesAndChildren()
 {
-    return adoptRef(new HTMLScriptElement(tagQName(), document(), false, m_loader->alreadyStarted()));
+    return adoptRef(new HTMLScriptElement(document(), false, m_loader->alreadyStarted()));
 }
 
 }
diff --git a/Source/core/html/HTMLScriptElement.h b/Source/core/html/HTMLScriptElement.h
index 325bc31..d4e0efd 100644
--- a/Source/core/html/HTMLScriptElement.h
+++ b/Source/core/html/HTMLScriptElement.h
@@ -33,7 +33,7 @@
 
 class HTMLScriptElement FINAL : public HTMLElement, public ScriptLoaderClient {
 public:
-    static PassRefPtr<HTMLScriptElement> create(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted = false);
+    static PassRefPtr<HTMLScriptElement> create(Document&, bool wasInsertedByParser, bool alreadyStarted = false);
 
     String text() { return textFromChildren(); }
     void setText(const String&);
@@ -46,7 +46,7 @@
     ScriptLoader* loader() const { return m_loader.get(); }
 
 private:
-    HTMLScriptElement(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted);
+    HTMLScriptElement(Document&, bool wasInsertedByParser, bool alreadyStarted);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index 327da68..7f7980a 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -29,6 +29,7 @@
 #include "core/html/HTMLSelectElement.h"
 
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
@@ -64,8 +65,8 @@
 // Upper limit agreed upon with representatives of Opera and Mozilla.
 static const unsigned maxSelectItems = 10000;
 
-HTMLSelectElement::HTMLSelectElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
-    : HTMLFormControlElementWithState(tagName, document, form)
+HTMLSelectElement::HTMLSelectElement(Document& document, HTMLFormElement* form, bool createdByParser)
+    : HTMLFormControlElementWithState(selectTag, document, form)
     , m_typeAhead(this)
     , m_size(0)
     , m_lastOnChangeIndex(-1)
@@ -77,19 +78,17 @@
     , m_shouldRecalcListItems(false)
     , m_isParsingInProgress(createdByParser)
 {
-    ASSERT(hasTagName(selectTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document)
 {
-    return adoptRef(new HTMLSelectElement(selectTag, document, 0, false));
+    return adoptRef(new HTMLSelectElement(document, 0, false));
 }
 
-PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
 {
-    ASSERT(tagName.matches(selectTag));
-    return adoptRef(new HTMLSelectElement(tagName, document, form, createdByParser));
+    return adoptRef(new HTMLSelectElement(document, form, createdByParser));
 }
 
 const AtomicString& HTMLSelectElement::formControlType() const
@@ -157,7 +156,7 @@
     if (customError())
         return customValidationMessage();
     if (valueMissing())
-        return locale().queryString(WebKit::WebLocalizedString::ValidationValueMissingForSelect);
+        return locale().queryString(blink::WebLocalizedString::ValidationValueMissingForSelect);
     return String();
 }
 
@@ -209,7 +208,7 @@
     return lastSelectedListIndex();
 }
 
-void HTMLSelectElement::add(HTMLElement* element, HTMLElement* before, ExceptionState& es)
+void HTMLSelectElement::add(HTMLElement* element, HTMLElement* before, ExceptionState& exceptionState)
 {
     // Make sure the element is ref'd and deref'd so we don't leak it.
     RefPtr<HTMLElement> protectNewChild(element);
@@ -217,7 +216,7 @@
     if (!element || !(element->hasLocalName(optionTag) || element->hasLocalName(hrTag)))
         return;
 
-    insertBefore(element, before, es);
+    insertBefore(element, before, exceptionState);
     setNeedsValidityCheck();
 }
 
@@ -290,7 +289,7 @@
         // Set the attribute value to a number.
         // This is important since the style rules for this attribute can determine the appearance property.
         int size = value.toInt();
-        String attrSize = String::number(size);
+        AtomicString attrSize = AtomicString::number(size);
         if (attrSize != value) {
             // FIXME: This is horribly factored.
             if (Attribute* sizeAttribute = ensureUniqueElementData()->getAttributeItem(sizeAttr))
@@ -402,7 +401,7 @@
 
 void HTMLSelectElement::setSize(int size)
 {
-    setAttribute(sizeAttr, String::number(size));
+    setIntegralAttribute(sizeAttr, size);
 }
 
 Node* HTMLSelectElement::namedItem(const AtomicString& name)
@@ -415,7 +414,7 @@
     return options()->item(index);
 }
 
-void HTMLSelectElement::setOption(unsigned index, HTMLOptionElement* option, ExceptionState& es)
+void HTMLSelectElement::setOption(unsigned index, HTMLOptionElement* option, ExceptionState& exceptionState)
 {
     if (index > maxSelectItems - 1)
         index = maxSelectItems - 1;
@@ -423,21 +422,21 @@
     RefPtr<HTMLElement> before = 0;
     // Out of array bounds? First insert empty dummies.
     if (diff > 0) {
-        setLength(index, es);
+        setLength(index, exceptionState);
         // Replace an existing entry?
     } else if (diff < 0) {
         before = toHTMLElement(options()->item(index+1));
         remove(index);
     }
     // Finally add the new element.
-    if (!es.hadException()) {
-        add(option, before.get(), es);
+    if (!exceptionState.hadException()) {
+        add(option, before.get(), exceptionState);
         if (diff >= 0 && option->selected())
             optionSelectionStateChanged(option, true);
     }
 }
 
-void HTMLSelectElement::setLength(unsigned newLen, ExceptionState& es)
+void HTMLSelectElement::setLength(unsigned newLen, ExceptionState& exceptionState)
 {
     if (newLen > maxSelectItems)
         newLen = maxSelectItems;
@@ -447,8 +446,8 @@
         do {
             RefPtr<Element> option = document().createElement(optionTag, false);
             ASSERT(option);
-            add(toHTMLElement(option), 0, es);
-            if (es.hadException())
+            add(toHTMLElement(option), 0, exceptionState);
+            if (exceptionState.hadException())
                 break;
         } while (++diff);
     } else {
@@ -469,7 +468,7 @@
         for (size_t i = 0; i < itemsToRemove.size(); ++i) {
             Element* item = itemsToRemove[i].get();
             if (item->parentNode())
-                item->parentNode()->removeChild(item, es);
+                item->parentNode()->removeChild(item, exceptionState);
         }
     }
     setNeedsValidityCheck();
@@ -736,44 +735,44 @@
 
     HTMLOptionElement* foundSelected = 0;
     HTMLOptionElement* firstOption = 0;
-    for (Element* currentElement = ElementTraversal::firstWithin(this); currentElement; ) {
+    for (Element* currentElement = ElementTraversal::firstWithin(*this); currentElement; ) {
         if (!currentElement->isHTMLElement()) {
-            currentElement = ElementTraversal::nextSkippingChildren(currentElement, this);
+            currentElement = ElementTraversal::nextSkippingChildren(*currentElement, this);
             continue;
         }
-        HTMLElement* current = toHTMLElement(currentElement);
+        HTMLElement& current = toHTMLElement(*currentElement);
 
         // optgroup tags may not nest. However, both FireFox and IE will
         // flatten the tree automatically, so we follow suit.
         // (http://www.w3.org/TR/html401/interact/forms.html#h-17.6)
         if (isHTMLOptGroupElement(current)) {
-            m_listItems.append(current);
+            m_listItems.append(&current);
             if (Element* nextElement = ElementTraversal::firstWithin(current)) {
                 currentElement = nextElement;
                 continue;
             }
         }
 
-        if (current->hasTagName(optionTag)) {
-            m_listItems.append(current);
+        if (current.hasTagName(optionTag)) {
+            m_listItems.append(&current);
 
             if (updateSelectedStates && !m_multiple) {
-                HTMLOptionElement* option = toHTMLOptionElement(current);
+                HTMLOptionElement& option = toHTMLOptionElement(current);
                 if (!firstOption)
-                    firstOption = option;
-                if (option->selected()) {
+                    firstOption = &option;
+                if (option.selected()) {
                     if (foundSelected)
                         foundSelected->setSelectedState(false);
-                    foundSelected = option;
-                } else if (m_size <= 1 && !foundSelected && !option->isDisabledFormControl()) {
-                    foundSelected = option;
+                    foundSelected = &option;
+                } else if (m_size <= 1 && !foundSelected && !option.isDisabledFormControl()) {
+                    foundSelected = &option;
                     foundSelected->setSelectedState(true);
                 }
             }
         }
 
-        if (current->hasTagName(hrTag))
-            m_listItems.append(current);
+        if (current.hasTagName(hrTag))
+            m_listItems.append(&current);
 
         // In conforming HTML code, only <optgroup> and <option> will be found
         // within a <select>. We call NodeTraversal::nextSkippingChildren so that we only step
@@ -781,7 +780,7 @@
         // with the case where odd tags like a <div> have been added but we
         // handle this because such tags have already been removed from the
         // <select>'s subtree at this point.
-        currentElement = ElementTraversal::nextSkippingChildren(currentElement, this);
+        currentElement = ElementTraversal::nextSkippingChildren(*currentElement, this);
     }
 
     if (!foundSelected && m_size <= 1 && firstOption && !firstOption->selected())
@@ -1565,17 +1564,17 @@
     updateListItemSelectedStates();
 }
 
-bool HTMLSelectElement::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& es)
+bool HTMLSelectElement::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& exceptionState)
 {
     if (!value) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwTypeError(ExceptionMessages::failedToSet(String::number(index), "HTMLSelectElement", "The value provided was not an HTMLOptionElement."));
         return false;
     }
-    setOption(index, value.get(), es);
+    setOption(index, value.get(), exceptionState);
     return true;
 }
 
-bool HTMLSelectElement::anonymousIndexedSetterRemove(unsigned index, ExceptionState& es)
+bool HTMLSelectElement::anonymousIndexedSetterRemove(unsigned index, ExceptionState& exceptionState)
 {
     remove(index);
     return true;
diff --git a/Source/core/html/HTMLSelectElement.h b/Source/core/html/HTMLSelectElement.h
index 6670342..7564360 100644
--- a/Source/core/html/HTMLSelectElement.h
+++ b/Source/core/html/HTMLSelectElement.h
@@ -40,7 +40,7 @@
 class HTMLSelectElement FINAL : public HTMLFormControlElementWithState, public TypeAheadDataSource {
 public:
     static PassRefPtr<HTMLSelectElement> create(Document&);
-    static PassRefPtr<HTMLSelectElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+    static PassRefPtr<HTMLSelectElement> create(Document&, HTMLFormElement*, bool createdByParser);
 
     int selectedIndex() const;
     void setSelectedIndex(int);
@@ -115,7 +115,7 @@
     bool anonymousIndexedSetterRemove(unsigned, ExceptionState&);
 
 protected:
-    HTMLSelectElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+    HTMLSelectElement(Document&, HTMLFormElement*, bool createdByParser);
 
 private:
     virtual const AtomicString& formControlType() const;
diff --git a/Source/core/html/HTMLSelectElement.idl b/Source/core/html/HTMLSelectElement.idl
index 477af63..76e5fc4 100644
--- a/Source/core/html/HTMLSelectElement.idl
+++ b/Source/core/html/HTMLSelectElement.idl
@@ -31,7 +31,7 @@
     readonly attribute DOMString type;
 
     readonly attribute HTMLOptionsCollection options;
-    [SetterRaisesException] attribute unsigned long length;
+    [RaisesException=Setter] attribute unsigned long length;
 
     getter Node item(unsigned long index);
     [ImplementedAs=anonymousIndexedSetter, RaisesException] setter HTMLOptionElement (unsigned long index, [TreatNullAs=anonymousIndexedSetterRemove, TreatUndefinedAs=anonymousIndexedSetterRemove] HTMLOptionElement value);
diff --git a/Source/core/html/HTMLSourceElement.cpp b/Source/core/html/HTMLSourceElement.cpp
index b060275..ec37846 100644
--- a/Source/core/html/HTMLSourceElement.cpp
+++ b/Source/core/html/HTMLSourceElement.cpp
@@ -38,18 +38,17 @@
 
 using namespace HTMLNames;
 
-inline HTMLSourceElement::HTMLSourceElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLSourceElement::HTMLSourceElement(Document& document)
+    : HTMLElement(sourceTag, document)
     , m_errorEventTimer(this, &HTMLSourceElement::errorEventTimerFired)
 {
     LOG(Media, "HTMLSourceElement::HTMLSourceElement - %p", this);
-    ASSERT(hasTagName(sourceTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLSourceElement> HTMLSourceElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLSourceElement> HTMLSourceElement::create(Document& document)
 {
-    return adoptRef(new HTMLSourceElement(tagName, document));
+    return adoptRef(new HTMLSourceElement(document));
 }
 
 Node::InsertionNotificationRequest HTMLSourceElement::insertedInto(ContainerNode* insertionPoint)
diff --git a/Source/core/html/HTMLSourceElement.h b/Source/core/html/HTMLSourceElement.h
index 2009427..21f9777 100644
--- a/Source/core/html/HTMLSourceElement.h
+++ b/Source/core/html/HTMLSourceElement.h
@@ -33,8 +33,7 @@
 
 class HTMLSourceElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLSourceElement> create(Document& document) { return create(HTMLNames::sourceTag, document); }
-    static PassRefPtr<HTMLSourceElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLSourceElement> create(Document&);
 
     String media() const;
     String type() const;
@@ -46,7 +45,7 @@
     void cancelPendingErrorEvent();
 
 private:
-    HTMLSourceElement(const QualifiedName&, Document&);
+    explicit HTMLSourceElement(Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/html/HTMLSpanElement.cpp b/Source/core/html/HTMLSpanElement.cpp
index ae275d3..193c659 100644
--- a/Source/core/html/HTMLSpanElement.cpp
+++ b/Source/core/html/HTMLSpanElement.cpp
@@ -32,21 +32,15 @@
 
 using namespace HTMLNames;
 
-HTMLSpanElement::HTMLSpanElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLSpanElement::HTMLSpanElement(Document& document)
+    : HTMLElement(spanTag, document)
 {
-    ASSERT(hasTagName(spanTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLSpanElement> HTMLSpanElement::create(Document& document)
 {
-    return adoptRef(new HTMLSpanElement(spanTag, document));
-}
-
-PassRefPtr<HTMLSpanElement> HTMLSpanElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLSpanElement(tagName, document));
+    return adoptRef(new HTMLSpanElement(document));
 }
 
 }
diff --git a/Source/core/html/HTMLSpanElement.h b/Source/core/html/HTMLSpanElement.h
index 8318479..ca77b86 100644
--- a/Source/core/html/HTMLSpanElement.h
+++ b/Source/core/html/HTMLSpanElement.h
@@ -33,10 +33,9 @@
 class HTMLSpanElement : public HTMLElement {
 public:
     static PassRefPtr<HTMLSpanElement> create(Document&);
-    static PassRefPtr<HTMLSpanElement> create(const QualifiedName&, Document&);
 
 protected:
-    HTMLSpanElement(const QualifiedName&, Document&);
+    explicit HTMLSpanElement(Document&);
 };
 
 }
diff --git a/Source/core/html/HTMLStyleElement.cpp b/Source/core/html/HTMLStyleElement.cpp
index 31f0e18..c3d7e1c 100644
--- a/Source/core/html/HTMLStyleElement.cpp
+++ b/Source/core/html/HTMLStyleElement.cpp
@@ -44,14 +44,13 @@
     return sharedLoadEventSender;
 }
 
-inline HTMLStyleElement::HTMLStyleElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLElement(tagName, document)
+inline HTMLStyleElement::HTMLStyleElement(Document& document, bool createdByParser)
+    : HTMLElement(styleTag, document)
     , StyleElement(&document, createdByParser)
     , m_firedLoad(false)
     , m_loadedSheet(false)
     , m_scopedStyleRegistrationState(NotRegistered)
 {
-    ASSERT(hasTagName(styleTag));
     ScriptWrappable::init(this);
 }
 
@@ -64,9 +63,9 @@
     styleLoadEventSender().cancelEvent(this);
 }
 
-PassRefPtr<HTMLStyleElement> HTMLStyleElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLStyleElement> HTMLStyleElement::create(Document& document, bool createdByParser)
 {
-    return adoptRef(new HTMLStyleElement(tagName, document, createdByParser));
+    return adoptRef(new HTMLStyleElement(document, createdByParser));
 }
 
 void HTMLStyleElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -115,8 +114,8 @@
     if (m_scopedStyleRegistrationState != RegisteredAsScoped)
         return;
 
-    document().styleEngine()->removeStyleSheetCandidateNode(this, parentNode());
     unregisterWithScopingNode(parentNode());
+    document().styleEngine()->removeStyleSheetCandidateNode(this, parentNode());
 
     // As any <style> in a shadow tree is treated as "scoped",
     // need to add the <style> to its shadow root.
diff --git a/Source/core/html/HTMLStyleElement.h b/Source/core/html/HTMLStyleElement.h
index 48a0937..3ab95c6 100644
--- a/Source/core/html/HTMLStyleElement.h
+++ b/Source/core/html/HTMLStyleElement.h
@@ -36,7 +36,7 @@
 
 class HTMLStyleElement FINAL : public HTMLElement, private StyleElement {
 public:
-    static PassRefPtr<HTMLStyleElement> create(const QualifiedName&, Document&, bool createdByParser);
+    static PassRefPtr<HTMLStyleElement> create(Document&, bool createdByParser);
     virtual ~HTMLStyleElement();
 
     void setType(const AtomicString&);
@@ -67,7 +67,7 @@
     static void dispatchPendingLoadEvents();
 
 private:
-    HTMLStyleElement(const QualifiedName&, Document&, bool createdByParser);
+    HTMLStyleElement(Document&, bool createdByParser);
 
     // overload from HTMLElement
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/html/HTMLSummaryElement.cpp b/Source/core/html/HTMLSummaryElement.cpp
index 379b4a5..7f13462 100644
--- a/Source/core/html/HTMLSummaryElement.cpp
+++ b/Source/core/html/HTMLSummaryElement.cpp
@@ -35,17 +35,16 @@
 
 using namespace HTMLNames;
 
-PassRefPtr<HTMLSummaryElement> HTMLSummaryElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLSummaryElement> HTMLSummaryElement::create(Document& document)
 {
-    RefPtr<HTMLSummaryElement> summary = adoptRef(new HTMLSummaryElement(tagName, document));
+    RefPtr<HTMLSummaryElement> summary = adoptRef(new HTMLSummaryElement(document));
     summary->ensureUserAgentShadowRoot();
     return summary.release();
 }
 
-HTMLSummaryElement::HTMLSummaryElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLSummaryElement::HTMLSummaryElement(Document& document)
+    : HTMLElement(summaryTag, document)
 {
-    ASSERT(hasTagName(summaryTag));
 }
 
 RenderObject* HTMLSummaryElement::createRenderer(RenderStyle*)
@@ -53,10 +52,10 @@
     return new RenderBlockFlow(this);
 }
 
-void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot& root)
 {
-    root->appendChild(DetailsMarkerControl::create(document()));
-    root->appendChild(HTMLContentElement::create(document()));
+    root.appendChild(DetailsMarkerControl::create(document()));
+    root.appendChild(HTMLContentElement::create(document()));
 }
 
 HTMLDetailsElement* HTMLSummaryElement::detailsElement() const
@@ -103,7 +102,7 @@
 
         if (event->isKeyboardEvent()) {
             if (event->type() == EventTypeNames::keydown && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
-                setActive(true, true);
+                setActive(true);
                 // No setDefaultHandled() - IE dispatches a keypress in this case.
                 return;
             }
diff --git a/Source/core/html/HTMLSummaryElement.h b/Source/core/html/HTMLSummaryElement.h
index 780a30f..45f1463 100644
--- a/Source/core/html/HTMLSummaryElement.h
+++ b/Source/core/html/HTMLSummaryElement.h
@@ -29,16 +29,16 @@
 
 class HTMLSummaryElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLSummaryElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLSummaryElement> create(Document&);
     bool isMainSummary() const;
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    HTMLSummaryElement(const QualifiedName&, Document&);
+    explicit HTMLSummaryElement(Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual void defaultEventHandler(Event*);
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
     HTMLDetailsElement* detailsElement() const;
 
     bool supportsFocus() const OVERRIDE;
diff --git a/Source/core/html/HTMLTableCaptionElement.cpp b/Source/core/html/HTMLTableCaptionElement.cpp
index 870d7b4..0212e32 100644
--- a/Source/core/html/HTMLTableCaptionElement.cpp
+++ b/Source/core/html/HTMLTableCaptionElement.cpp
@@ -32,16 +32,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLTableCaptionElement::HTMLTableCaptionElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLTableCaptionElement::HTMLTableCaptionElement(Document& document)
+    : HTMLElement(captionTag, document)
 {
-    ASSERT(hasTagName(captionTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTableCaptionElement> HTMLTableCaptionElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTableCaptionElement> HTMLTableCaptionElement::create(Document& document)
 {
-    return adoptRef(new HTMLTableCaptionElement(tagName, document));
+    return adoptRef(new HTMLTableCaptionElement(document));
 }
 
 bool HTMLTableCaptionElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLTableCaptionElement.h b/Source/core/html/HTMLTableCaptionElement.h
index ae7f98c..33315ac 100644
--- a/Source/core/html/HTMLTableCaptionElement.h
+++ b/Source/core/html/HTMLTableCaptionElement.h
@@ -32,10 +32,10 @@
 
 class HTMLTableCaptionElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLTableCaptionElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLTableCaptionElement> create(Document&);
 
 private:
-    HTMLTableCaptionElement(const QualifiedName&, Document&);
+    HTMLTableCaptionElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLTableCellElement.cpp b/Source/core/html/HTMLTableCellElement.cpp
index 34f7bad..a6c5b1e 100644
--- a/Source/core/html/HTMLTableCellElement.cpp
+++ b/Source/core/html/HTMLTableCellElement.cpp
@@ -142,7 +142,7 @@
 
 void HTMLTableCellElement::setColSpan(int n)
 {
-    setAttribute(colspanAttr, String::number(n));
+    setIntegralAttribute(colspanAttr, n);
 }
 
 String HTMLTableCellElement::headers() const
@@ -152,7 +152,7 @@
 
 void HTMLTableCellElement::setRowSpan(int n)
 {
-    setAttribute(rowspanAttr, String::number(n));
+    setIntegralAttribute(rowspanAttr, n);
 }
 
 String HTMLTableCellElement::scope() const
diff --git a/Source/core/html/HTMLTableColElement.cpp b/Source/core/html/HTMLTableColElement.cpp
index bf46d4d..d7d99b1 100644
--- a/Source/core/html/HTMLTableColElement.cpp
+++ b/Source/core/html/HTMLTableColElement.cpp
@@ -91,7 +91,7 @@
 
 void HTMLTableColElement::setSpan(int n)
 {
-    setAttribute(spanAttr, String::number(n));
+    setIntegralAttribute(spanAttr, n);
 }
 
 String HTMLTableColElement::width() const
diff --git a/Source/core/html/HTMLTableElement.cpp b/Source/core/html/HTMLTableElement.cpp
index 7cc5939..1c46269 100644
--- a/Source/core/html/HTMLTableElement.cpp
+++ b/Source/core/html/HTMLTableElement.cpp
@@ -28,6 +28,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/css/CSSImageValue.h"
@@ -41,31 +42,26 @@
 #include "core/html/HTMLTableSectionElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/rendering/RenderTable.h"
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-HTMLTableElement::HTMLTableElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLTableElement::HTMLTableElement(Document& document)
+    : HTMLElement(tableTag, document)
     , m_borderAttr(false)
     , m_borderColorAttr(false)
     , m_frameAttr(false)
     , m_rulesAttr(UnsetRules)
     , m_padding(1)
 {
-    ASSERT(hasTagName(tableTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLTableElement> HTMLTableElement::create(Document& document)
 {
-    return adoptRef(new HTMLTableElement(tableTag, document));
-}
-
-PassRefPtr<HTMLTableElement> HTMLTableElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLTableElement(tagName, document));
+    return adoptRef(new HTMLTableElement(document));
 }
 
 HTMLTableCaptionElement* HTMLTableElement::caption() const
@@ -77,10 +73,10 @@
     return 0;
 }
 
-void HTMLTableElement::setCaption(PassRefPtr<HTMLTableCaptionElement> newCaption, ExceptionState& es)
+void HTMLTableElement::setCaption(PassRefPtr<HTMLTableCaptionElement> newCaption, ExceptionState& exceptionState)
 {
     deleteCaption();
-    insertBefore(newCaption, firstChild(), es);
+    insertBefore(newCaption, firstChild(), exceptionState);
 }
 
 HTMLTableSectionElement* HTMLTableElement::tHead() const
@@ -92,7 +88,7 @@
     return 0;
 }
 
-void HTMLTableElement::setTHead(PassRefPtr<HTMLTableSectionElement> newHead, ExceptionState& es)
+void HTMLTableElement::setTHead(PassRefPtr<HTMLTableSectionElement> newHead, ExceptionState& exceptionState)
 {
     deleteTHead();
 
@@ -101,7 +97,7 @@
         if (child->isElementNode() && !child->hasTagName(captionTag) && !child->hasTagName(colgroupTag))
             break;
 
-    insertBefore(newHead, child, es);
+    insertBefore(newHead, child, exceptionState);
 }
 
 HTMLTableSectionElement* HTMLTableElement::tFoot() const
@@ -113,7 +109,7 @@
     return 0;
 }
 
-void HTMLTableElement::setTFoot(PassRefPtr<HTMLTableSectionElement> newFoot, ExceptionState& es)
+void HTMLTableElement::setTFoot(PassRefPtr<HTMLTableSectionElement> newFoot, ExceptionState& exceptionState)
 {
     deleteTFoot();
 
@@ -122,7 +118,7 @@
         if (child->isElementNode() && !child->hasTagName(captionTag) && !child->hasTagName(colgroupTag) && !child->hasTagName(theadTag))
             break;
 
-    insertBefore(newFoot, child, es);
+    insertBefore(newFoot, child, exceptionState);
 }
 
 PassRefPtr<HTMLElement> HTMLTableElement::createTHead()
@@ -166,7 +162,7 @@
 {
     if (HTMLTableCaptionElement* existingCaption = caption())
         return existingCaption;
-    RefPtr<HTMLTableCaptionElement> caption = HTMLTableCaptionElement::create(captionTag, document());
+    RefPtr<HTMLTableCaptionElement> caption = HTMLTableCaptionElement::create(document());
     setCaption(caption, IGNORE_EXCEPTION);
     return caption.release();
 }
@@ -185,10 +181,10 @@
     return 0;
 }
 
-PassRefPtr<HTMLElement> HTMLTableElement::insertRow(int index, ExceptionState& es)
+PassRefPtr<HTMLElement> HTMLTableElement::insertRow(int index, ExceptionState& exceptionState)
 {
     if (index < -1) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertRow", "HTMLTableElement", "The index provided (" + String::number(index) + ") is less than -1."));
         return 0;
     }
 
@@ -203,7 +199,7 @@
             row = HTMLTableRowsCollection::rowAfter(this, lastRow.get());
             if (!row) {
                 if (i != index) {
-                    es.throwUninformativeAndGenericDOMException(IndexSizeError);
+                    exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertRow", "HTMLTableElement", "The index provided (" + String::number(index) + ") is greater than the number of rows in the table (" + String::number(i) + ")."));
                     return 0;
                 }
                 break;
@@ -220,34 +216,40 @@
         if (!parent) {
             RefPtr<HTMLTableSectionElement> newBody = HTMLTableSectionElement::create(tbodyTag, document());
             RefPtr<HTMLTableRowElement> newRow = HTMLTableRowElement::create(document());
-            newBody->appendChild(newRow, es);
-            appendChild(newBody.release(), es);
+            newBody->appendChild(newRow, exceptionState);
+            appendChild(newBody.release(), exceptionState);
             return newRow.release();
         }
     }
 
     RefPtr<HTMLTableRowElement> newRow = HTMLTableRowElement::create(document());
-    parent->insertBefore(newRow, row.get(), es);
+    parent->insertBefore(newRow, row.get(), exceptionState);
     return newRow.release();
 }
 
-void HTMLTableElement::deleteRow(int index, ExceptionState& es)
+void HTMLTableElement::deleteRow(int index, ExceptionState& exceptionState)
 {
+    if (index < -1) {
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteRow", "HTMLTableElement", "The index provided (" + String::number(index) + ") is less than -1."));
+        return;
+    }
+
     HTMLTableRowElement* row = 0;
+    int i = 0;
     if (index == -1)
         row = HTMLTableRowsCollection::lastRow(this);
     else {
-        for (int i = 0; i <= index; ++i) {
+        for (i = 0; i <= index; ++i) {
             row = HTMLTableRowsCollection::rowAfter(this, row);
             if (!row)
                 break;
         }
     }
     if (!row) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteRow", "HTMLTableElement", "The index provided (" + String::number(index) + ") is greater than the number of rows in the table (" + String::number(i) + ")."));
         return;
     }
-    row->remove(es);
+    row->remove(exceptionState);
 }
 
 static inline bool isTableCellAncestor(Node* n)
@@ -414,14 +416,14 @@
     }
 }
 
-static StylePropertySet* leakBorderStyle(CSSValueID value)
+static PassRefPtr<StylePropertySet> createBorderStyle(CSSValueID value)
 {
     RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(CSSPropertyBorderTopStyle, value);
     style->setProperty(CSSPropertyBorderBottomStyle, value);
     style->setProperty(CSSPropertyBorderLeftStyle, value);
     style->setProperty(CSSPropertyBorderRightStyle, value);
-    return style.release().leakRef();
+    return style.release();
 }
 
 const StylePropertySet* HTMLTableElement::additionalPresentationAttributeStyle()
@@ -433,17 +435,17 @@
         // Setting the border to 'hidden' allows it to win over any border
         // set on the table's cells during border-conflict resolution.
         if (m_rulesAttr != UnsetRules) {
-            static StylePropertySet* solidBorderStyle = leakBorderStyle(CSSValueHidden);
+            DEFINE_STATIC_REF(StylePropertySet, solidBorderStyle, (createBorderStyle(CSSValueHidden)));
             return solidBorderStyle;
         }
         return 0;
     }
 
     if (m_borderColorAttr) {
-        static StylePropertySet* solidBorderStyle = leakBorderStyle(CSSValueSolid);
+        DEFINE_STATIC_REF(StylePropertySet, solidBorderStyle, (createBorderStyle(CSSValueSolid)));
         return solidBorderStyle;
     }
-    static StylePropertySet* outsetBorderStyle = leakBorderStyle(CSSValueOutset);
+    DEFINE_STATIC_REF(StylePropertySet, outsetBorderStyle, (createBorderStyle(CSSValueOutset)));
     return outsetBorderStyle;
 }
 
@@ -517,7 +519,7 @@
     return m_sharedCellStyle.get();
 }
 
-static StylePropertySet* leakGroupBorderStyle(int rows)
+static PassRefPtr<StylePropertySet> createGroupBorderStyle(int rows)
 {
     RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     if (rows) {
@@ -531,7 +533,7 @@
         style->setProperty(CSSPropertyBorderLeftStyle, CSSValueSolid);
         style->setProperty(CSSPropertyBorderRightStyle, CSSValueSolid);
     }
-    return style.release().leakRef();
+    return style.release();
 }
 
 const StylePropertySet* HTMLTableElement::additionalGroupStyle(bool rows)
@@ -540,10 +542,10 @@
         return 0;
 
     if (rows) {
-        static StylePropertySet* rowBorderStyle = leakGroupBorderStyle(true);
+        DEFINE_STATIC_REF(StylePropertySet, rowBorderStyle, (createGroupBorderStyle(true)));
         return rowBorderStyle;
     }
-    static StylePropertySet* columnBorderStyle = leakGroupBorderStyle(false);
+    DEFINE_STATIC_REF(StylePropertySet, columnBorderStyle, (createGroupBorderStyle(false)));
     return columnBorderStyle;
 }
 
diff --git a/Source/core/html/HTMLTableElement.h b/Source/core/html/HTMLTableElement.h
index c1b4918..e2c0897 100644
--- a/Source/core/html/HTMLTableElement.h
+++ b/Source/core/html/HTMLTableElement.h
@@ -39,7 +39,6 @@
 class HTMLTableElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLTableElement> create(Document&);
-    static PassRefPtr<HTMLTableElement> create(const QualifiedName&, Document&);
 
     HTMLTableCaptionElement* caption() const;
     void setCaption(PassRefPtr<HTMLTableCaptionElement>, ExceptionState&);
@@ -70,7 +69,7 @@
     const StylePropertySet* additionalGroupStyle(bool rows);
 
 private:
-    HTMLTableElement(const QualifiedName&, Document&);
+    explicit HTMLTableElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLTableElement.idl b/Source/core/html/HTMLTableElement.idl
index cd247d6..e31e703 100644
--- a/Source/core/html/HTMLTableElement.idl
+++ b/Source/core/html/HTMLTableElement.idl
@@ -19,9 +19,9 @@
  */
 
 interface HTMLTableElement : HTMLElement {
-    [SetterRaisesException] attribute HTMLTableCaptionElement caption;
-    [SetterRaisesException] attribute HTMLTableSectionElement tHead;
-    [SetterRaisesException] attribute HTMLTableSectionElement tFoot;
+    [RaisesException=Setter] attribute HTMLTableCaptionElement caption;
+    [RaisesException=Setter] attribute HTMLTableSectionElement tHead;
+    [RaisesException=Setter] attribute HTMLTableSectionElement tFoot;
 
     readonly attribute HTMLCollection rows;
     readonly attribute HTMLCollection tBodies;
diff --git a/Source/core/html/HTMLTableRowElement.cpp b/Source/core/html/HTMLTableRowElement.cpp
index 7a1bd70..5b4e068 100644
--- a/Source/core/html/HTMLTableRowElement.cpp
+++ b/Source/core/html/HTMLTableRowElement.cpp
@@ -26,6 +26,7 @@
 #include "core/html/HTMLTableRowElement.h"
 
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/html/HTMLCollection.h"
@@ -37,21 +38,15 @@
 
 using namespace HTMLNames;
 
-HTMLTableRowElement::HTMLTableRowElement(const QualifiedName& tagName, Document& document)
-    : HTMLTablePartElement(tagName, document)
+HTMLTableRowElement::HTMLTableRowElement(Document& document)
+    : HTMLTablePartElement(trTag, document)
 {
-    ASSERT(hasTagName(trTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(Document& document)
 {
-    return adoptRef(new HTMLTableRowElement(trTag, document));
-}
-
-PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLTableRowElement(tagName, document));
+    return adoptRef(new HTMLTableRowElement(document));
 }
 
 int HTMLTableRowElement::rowIndex() const
@@ -118,30 +113,30 @@
     return rIndex;
 }
 
-PassRefPtr<HTMLElement> HTMLTableRowElement::insertCell(int index, ExceptionState& es)
+PassRefPtr<HTMLElement> HTMLTableRowElement::insertCell(int index, ExceptionState& exceptionState)
 {
     RefPtr<HTMLCollection> children = cells();
     int numCells = children ? children->length() : 0;
     if (index < -1 || index > numCells) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertCell", "HTMLTableRowElement", "The value provided (" + String::number(index) + ") is outside the range [-1, " + String::number(numCells) + "]."));
         return 0;
     }
 
     RefPtr<HTMLTableCellElement> cell = HTMLTableCellElement::create(tdTag, document());
     if (index < 0 || index >= numCells)
-        appendChild(cell, es);
+        appendChild(cell, exceptionState);
     else {
         Node* n;
         if (index < 1)
             n = firstChild();
         else
             n = children->item(index);
-        insertBefore(cell, n, es);
+        insertBefore(cell, n, exceptionState);
     }
     return cell.release();
 }
 
-void HTMLTableRowElement::deleteCell(int index, ExceptionState& es)
+void HTMLTableRowElement::deleteCell(int index, ExceptionState& exceptionState)
 {
     RefPtr<HTMLCollection> children = cells();
     int numCells = children ? children->length() : 0;
@@ -149,9 +144,9 @@
         index = numCells-1;
     if (index >= 0 && index < numCells) {
         RefPtr<Node> cell = children->item(index);
-        HTMLElement::removeChild(cell.get(), es);
+        HTMLElement::removeChild(cell.get(), exceptionState);
     } else {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteCell", "HTMLTableRowElement", "The value provided (" + String::number(index) + ") is outside the range [0, " + String::number(numCells) + ")."));
     }
 }
 
@@ -160,9 +155,4 @@
     return ensureCachedHTMLCollection(TRCells);
 }
 
-void HTMLTableRowElement::setCells(HTMLCollection*, ExceptionState& es)
-{
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
-}
-
 }
diff --git a/Source/core/html/HTMLTableRowElement.h b/Source/core/html/HTMLTableRowElement.h
index 9483642..1fe3867 100644
--- a/Source/core/html/HTMLTableRowElement.h
+++ b/Source/core/html/HTMLTableRowElement.h
@@ -35,22 +35,18 @@
 class HTMLTableRowElement FINAL : public HTMLTablePartElement {
 public:
     static PassRefPtr<HTMLTableRowElement> create(Document&);
-    static PassRefPtr<HTMLTableRowElement> create(const QualifiedName&, Document&);
 
     int rowIndex() const;
-    void setRowIndex(int);
 
     int sectionRowIndex() const;
-    void setSectionRowIndex(int);
 
     PassRefPtr<HTMLElement> insertCell(int index, ExceptionState&);
     void deleteCell(int index, ExceptionState&);
 
     PassRefPtr<HTMLCollection> cells();
-    void setCells(HTMLCollection *, ExceptionState&);
 
 private:
-    HTMLTableRowElement(const QualifiedName&, Document&);
+    explicit HTMLTableRowElement(Document&);
 };
 
 inline bool isHTMLTableRowElement(const Node* node)
diff --git a/Source/core/html/HTMLTableSectionElement.cpp b/Source/core/html/HTMLTableSectionElement.cpp
index 65be611..e78dfab 100644
--- a/Source/core/html/HTMLTableSectionElement.cpp
+++ b/Source/core/html/HTMLTableSectionElement.cpp
@@ -56,30 +56,30 @@
 
 // these functions are rather slow, since we need to get the row at
 // the index... but they aren't used during usual HTML parsing anyway
-PassRefPtr<HTMLElement> HTMLTableSectionElement::insertRow(int index, ExceptionState& es)
+PassRefPtr<HTMLElement> HTMLTableSectionElement::insertRow(int index, ExceptionState& exceptionState)
 {
     RefPtr<HTMLTableRowElement> row;
     RefPtr<HTMLCollection> children = rows();
     int numRows = children ? (int)children->length() : 0;
     if (index < -1 || index > numRows)
-        es.throwUninformativeAndGenericDOMException(IndexSizeError); // per the DOM
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError); // per the DOM
     else {
-        row = HTMLTableRowElement::create(trTag, document());
+        row = HTMLTableRowElement::create(document());
         if (numRows == index || index == -1)
-            appendChild(row, es);
+            appendChild(row, exceptionState);
         else {
             Node* n;
             if (index < 1)
                 n = firstChild();
             else
                 n = children->item(index);
-            insertBefore(row, n, es);
+            insertBefore(row, n, exceptionState);
         }
     }
     return row.release();
 }
 
-void HTMLTableSectionElement::deleteRow(int index, ExceptionState& es)
+void HTMLTableSectionElement::deleteRow(int index, ExceptionState& exceptionState)
 {
     RefPtr<HTMLCollection> children = rows();
     int numRows = children ? (int)children->length() : 0;
@@ -87,9 +87,9 @@
         index = numRows - 1;
     if (index >= 0 && index < numRows) {
         RefPtr<Node> row = children->item(index);
-        HTMLElement::removeChild(row.get(), es);
+        HTMLElement::removeChild(row.get(), exceptionState);
     } else {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
     }
 }
 
diff --git a/Source/core/html/HTMLTagNames.in b/Source/core/html/HTMLTagNames.in
index 7ba6094..ee8c92f 100644
--- a/Source/core/html/HTMLTagNames.in
+++ b/Source/core/html/HTMLTagNames.in
@@ -11,7 +11,7 @@
 area
 article interfaceName=HTMLElement
 aside interfaceName=HTMLElement
-audio wrapperOnlyIfMediaIsAvailable, constructorNeedsCreatedByParser
+audio runtimeEnabled=media, constructorNeedsCreatedByParser
 b interfaceName=HTMLElement
 base
 basefont interfaceName=HTMLElement
@@ -32,7 +32,6 @@
 colgroup interfaceName=HTMLTableColElement
 command interfaceName=HTMLElement
 content interfaceName=HTMLContentElement
-webkitShadowContent interfaceName=HTMLElement, noConstructor
 datalist interfaceName=HTMLDataListElement
 dd interfaceName=HTMLElement
 del interfaceName=HTMLModElement
@@ -112,7 +111,7 @@
 section interfaceName=HTMLElement
 select constructorNeedsFormElement, constructorNeedsCreatedByParser
 small interfaceName=HTMLElement
-source wrapperOnlyIfMediaIsAvailable
+source runtimeEnabled=media
 span
 strike interfaceName=HTMLElement
 strong interfaceName=HTMLElement
@@ -130,12 +129,12 @@
 thead interfaceName=HTMLTableSectionElement
 title
 tr interfaceName=HTMLTableRowElement
-track wrapperOnlyIfMediaIsAvailable
+track runtimeEnabled=videoTrack
 tt interfaceName=HTMLElement
 u interfaceName=HTMLElement
 ul interfaceName=HTMLUListElement
 var interfaceName=HTMLElement
-video wrapperOnlyIfMediaIsAvailable, constructorNeedsCreatedByParser
+video runtimeEnabled=media, constructorNeedsCreatedByParser
 wbr interfaceName=HTMLElement
 xmp interfaceName=HTMLPreElement
 noscript interfaceName=HTMLElement
diff --git a/Source/core/html/HTMLTemplateElement.cpp b/Source/core/html/HTMLTemplateElement.cpp
index f2793ec..2990838 100644
--- a/Source/core/html/HTMLTemplateElement.cpp
+++ b/Source/core/html/HTMLTemplateElement.cpp
@@ -39,8 +39,8 @@
 
 using namespace HTMLNames;
 
-inline HTMLTemplateElement::HTMLTemplateElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLTemplateElement::HTMLTemplateElement(Document& document)
+    : HTMLElement(templateTag, document)
 {
     ScriptWrappable::init(this);
 }
@@ -51,15 +51,15 @@
         m_content->clearHost();
 }
 
-PassRefPtr<HTMLTemplateElement> HTMLTemplateElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTemplateElement> HTMLTemplateElement::create(Document& document)
 {
-    return adoptRef(new HTMLTemplateElement(tagName, document));
+    return adoptRef(new HTMLTemplateElement(document));
 }
 
 DocumentFragment* HTMLTemplateElement::content() const
 {
     if (!m_content)
-        m_content = TemplateContentDocumentFragment::create(document().ensureTemplateDocument(), this);
+        m_content = TemplateContentDocumentFragment::create(document().ensureTemplateDocument(), const_cast<HTMLTemplateElement*>(this));
 
     return m_content.get();
 }
diff --git a/Source/core/html/HTMLTemplateElement.h b/Source/core/html/HTMLTemplateElement.h
index 883e85c..6b2ebd6 100644
--- a/Source/core/html/HTMLTemplateElement.h
+++ b/Source/core/html/HTMLTemplateElement.h
@@ -40,7 +40,7 @@
 
 class HTMLTemplateElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLTemplateElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLTemplateElement> create(Document&);
     virtual ~HTMLTemplateElement();
 
     DocumentFragment* content() const;
@@ -49,7 +49,7 @@
     virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE;
     virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
 
-    HTMLTemplateElement(const QualifiedName&, Document&);
+    explicit HTMLTemplateElement(Document&);
 
     mutable RefPtr<TemplateContentDocumentFragment> m_content;
 };
diff --git a/Source/core/html/HTMLTemplateElement.idl b/Source/core/html/HTMLTemplateElement.idl
index 46c6696..e950fce 100644
--- a/Source/core/html/HTMLTemplateElement.idl
+++ b/Source/core/html/HTMLTemplateElement.idl
@@ -29,6 +29,6 @@
  */
 
 interface HTMLTemplateElement : HTMLElement {
-    [KeepAttributeAliveForGC] readonly attribute DocumentFragment content;
+    readonly attribute DocumentFragment content;
 };
 
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index 51cd2be..a5600e5 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -28,14 +28,15 @@
 
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
+#include "core/editing/SpellChecker.h"
 #include "core/editing/TextIterator.h"
 #include "core/events/BeforeTextInsertedEvent.h"
 #include "core/events/Event.h"
@@ -59,11 +60,6 @@
 
 // On submission, LF characters are converted into CRLF.
 // This function returns number of characters considering this.
-static inline unsigned computeLengthForSubmission(const String& text, unsigned numberOfLineBreaks)
-{
-    return text.length() + numberOfLineBreaks;
-}
-
 static unsigned numberOfLineBreaks(const String& text)
 {
     unsigned length = text.length();
@@ -80,29 +76,28 @@
     return text.length() + numberOfLineBreaks(text);
 }
 
-HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
-    : HTMLTextFormControlElement(tagName, document, form)
+HTMLTextAreaElement::HTMLTextAreaElement(Document& document, HTMLFormElement* form)
+    : HTMLTextFormControlElement(textareaTag, document, form)
     , m_rows(defaultRows)
     , m_cols(defaultCols)
     , m_wrap(SoftWrap)
     , m_isDirty(false)
     , m_wasModifiedByUser(false)
 {
-    ASSERT(hasTagName(textareaTag));
     setFormControlValueMatchesRenderer(true);
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(Document& document, HTMLFormElement* form)
 {
-    RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(tagName, document, form));
+    RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(document, form));
     textArea->ensureUserAgentShadowRoot();
     return textArea.release();
 }
 
-void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot& root)
 {
-    root->appendChild(TextControlInnerTextElement::create(document()));
+    root.appendChild(TextControlInnerTextElement::create(document()));
 }
 
 const AtomicString& HTMLTextAreaElement::formControlType() const
@@ -270,7 +265,7 @@
 void HTMLTextAreaElement::handleFocusEvent(Element*, FocusDirection)
 {
     if (Frame* frame = document().frame())
-        frame->editor().textAreaOrTextFieldDidBeginEditing(this);
+        frame->spellChecker().didBeginEditing(this);
 }
 
 void HTMLTextAreaElement::subtreeHasChanged()
@@ -434,12 +429,12 @@
     return ok && value >= 0 ? value : -1;
 }
 
-void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& es)
+void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& exceptionState)
 {
     if (newValue < 0)
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("maxLength", "HTMLTextAreaElement", "The value provided (" + String::number(newValue) + ") is not positive or 0."));
     else
-        setAttribute(maxlengthAttr, String::number(newValue));
+        setIntegralAttribute(maxlengthAttr, newValue);
 }
 
 String HTMLTextAreaElement::validationMessage() const
@@ -451,7 +446,7 @@
         return customValidationMessage();
 
     if (valueMissing())
-        return locale().queryString(WebKit::WebLocalizedString::ValidationValueMissing);
+        return locale().queryString(blink::WebLocalizedString::ValidationValueMissing);
 
     if (tooLong())
         return locale().validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
@@ -494,12 +489,12 @@
 
 void HTMLTextAreaElement::setCols(int cols)
 {
-    setAttribute(colsAttr, String::number(cols));
+    setIntegralAttribute(colsAttr, cols);
 }
 
 void HTMLTextAreaElement::setRows(int rows)
 {
-    setAttribute(rowsAttr, String::number(rows));
+    setIntegralAttribute(rowsAttr, rows);
 }
 
 bool HTMLTextAreaElement::shouldUseInputMethod()
@@ -529,7 +524,7 @@
     if (!placeholder) {
         RefPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
         placeholder = newElement.get();
-        placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
         userAgentShadowRoot()->insertBefore(placeholder, innerTextElement()->nextSibling());
     }
diff --git a/Source/core/html/HTMLTextAreaElement.h b/Source/core/html/HTMLTextAreaElement.h
index 1b8dd6b..6dadb01 100644
--- a/Source/core/html/HTMLTextAreaElement.h
+++ b/Source/core/html/HTMLTextAreaElement.h
@@ -34,7 +34,7 @@
 
 class HTMLTextAreaElement FINAL : public HTMLTextFormControlElement {
 public:
-    static PassRefPtr<HTMLTextAreaElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+    static PassRefPtr<HTMLTextAreaElement> create(Document&, HTMLFormElement*);
 
     int cols() const { return m_cols; }
     int rows() const { return m_rows; }
@@ -60,11 +60,11 @@
     void setRows(int);
 
 private:
-    HTMLTextAreaElement(const QualifiedName&, Document&, HTMLFormElement*);
+    HTMLTextAreaElement(Document&, HTMLFormElement*);
 
     enum WrapMethod { NoWrap, SoftWrap, HardWrap };
 
-    virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
     // FIXME: Author shadows should be allowed
     // https://bugs.webkit.org/show_bug.cgi?id=92608
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
diff --git a/Source/core/html/HTMLTextAreaElement.idl b/Source/core/html/HTMLTextAreaElement.idl
index fc3b1ff..a0bd100 100644
--- a/Source/core/html/HTMLTextAreaElement.idl
+++ b/Source/core/html/HTMLTextAreaElement.idl
@@ -25,7 +25,7 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString dirName;
     [Reflect] attribute boolean disabled;
     readonly attribute HTMLFormElement form;
-    [SetterRaisesException] attribute long maxLength;
+    [RaisesException=Setter] attribute long maxLength;
     [Reflect, TreatNullAs=NullString] attribute DOMString name;
     [Reflect, TreatNullAs=NullString] attribute DOMString placeholder;
     [Reflect] attribute boolean readOnly;
diff --git a/Source/core/html/HTMLTextFormControlElement.cpp b/Source/core/html/HTMLTextFormControlElement.cpp
index 24859e6..548200c 100644
--- a/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/Source/core/html/HTMLTextFormControlElement.cpp
@@ -26,6 +26,7 @@
 #include "core/html/HTMLTextFormControlElement.h"
 
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
@@ -40,7 +41,7 @@
 #include "core/html/HTMLBRElement.h"
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/frame/Frame.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderTheme.h"
 #include "wtf/text/StringBuilder.h"
@@ -205,15 +206,15 @@
 }
 
 
-void HTMLTextFormControlElement::setRangeText(const String& replacement, ExceptionState& es)
+void HTMLTextFormControlElement::setRangeText(const String& replacement, ExceptionState& exceptionState)
 {
-    setRangeText(replacement, selectionStart(), selectionEnd(), String(), es);
+    setRangeText(replacement, selectionStart(), selectionEnd(), String(), exceptionState);
 }
 
-void HTMLTextFormControlElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& es)
+void HTMLTextFormControlElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& exceptionState)
 {
     if (start > end) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setRangeText", "HTMLElement", "The provided start value (" + String::number(start) + ") is larger than the provided end value (" + String::number(end) + ")."));
         return;
     }
 
@@ -445,7 +446,7 @@
     int offset = 0;
     Node* startNode = 0;
     Node* endNode = 0;
-    for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(node, innerText)) {
+    for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(*node, innerText)) {
         ASSERT(!node->firstChild());
         ASSERT(node->isTextNode() || node->hasTagName(brTag));
         int length = node->isTextNode() ? lastOffsetInNode(node) : 1;
@@ -538,7 +539,7 @@
         return emptyString();
 
     StringBuilder result;
-    for (Node* node = innerText; node; node = NodeTraversal::next(node, innerText)) {
+    for (Node* node = innerText; node; node = NodeTraversal::next(*node, innerText)) {
         if (node->hasTagName(brTag))
             result.append(newlineCharacter);
         else if (node->isTextNode())
@@ -585,7 +586,7 @@
     getNextSoftBreak(line, breakNode, breakOffset);
 
     StringBuilder result;
-    for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(node, innerText)) {
+    for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(*node, innerText)) {
         if (node->hasTagName(brTag))
             result.append(newlineCharacter);
         else if (node->isTextNode()) {
diff --git a/Source/core/html/HTMLTitleElement.cpp b/Source/core/html/HTMLTitleElement.cpp
index 48ed56e..c9fdaed 100644
--- a/Source/core/html/HTMLTitleElement.cpp
+++ b/Source/core/html/HTMLTitleElement.cpp
@@ -35,17 +35,16 @@
 
 using namespace HTMLNames;
 
-inline HTMLTitleElement::HTMLTitleElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLTitleElement::HTMLTitleElement(Document& document)
+    : HTMLElement(titleTag, document)
 {
-    ASSERT(hasTagName(titleTag));
     setHasCustomStyleCallbacks();
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(Document& document)
 {
-    return adoptRef(new HTMLTitleElement(tagName, document));
+    return adoptRef(new HTMLTitleElement(document));
 }
 
 Node::InsertionNotificationRequest HTMLTitleElement::insertedInto(ContainerNode* insertionPoint)
diff --git a/Source/core/html/HTMLTitleElement.h b/Source/core/html/HTMLTitleElement.h
index 5eab749..988f77a 100644
--- a/Source/core/html/HTMLTitleElement.h
+++ b/Source/core/html/HTMLTitleElement.h
@@ -28,13 +28,13 @@
 
 class HTMLTitleElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLTitleElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLTitleElement> create(Document&);
 
     String text() const;
     void setText(const String&);
 
 private:
-    HTMLTitleElement(const QualifiedName&, Document&);
+    explicit HTMLTitleElement(Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/html/HTMLTrackElement.cpp b/Source/core/html/HTMLTrackElement.cpp
index 0023137..06ba479 100644
--- a/Source/core/html/HTMLTrackElement.cpp
+++ b/Source/core/html/HTMLTrackElement.cpp
@@ -31,7 +31,6 @@
 #include "core/events/Event.h"
 #include "core/html/HTMLMediaElement.h"
 #include "core/frame/ContentSecurityPolicy.h"
-#include "RuntimeEnabledFeatures.h"
 #include "platform/Logging.h"
 
 using namespace std;
@@ -51,12 +50,11 @@
 }
 #endif
 
-inline HTMLTrackElement::HTMLTrackElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+inline HTMLTrackElement::HTMLTrackElement(Document& document)
+    : HTMLElement(trackTag, document)
     , m_loadTimer(this, &HTMLTrackElement::loadTimerFired)
 {
     LOG(Media, "HTMLTrackElement::HTMLTrackElement - %p", this);
-    ASSERT(hasTagName(trackTag));
     ScriptWrappable::init(this);
 }
 
@@ -66,9 +64,9 @@
         m_track->clearClient();
 }
 
-PassRefPtr<HTMLTrackElement> HTMLTrackElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTrackElement> HTMLTrackElement::create(Document& document)
 {
-    return adoptRef(new HTMLTrackElement(tagName, document));
+    return adoptRef(new HTMLTrackElement(document));
 }
 
 Node::InsertionNotificationRequest HTMLTrackElement::insertedInto(ContainerNode* insertionPoint)
@@ -94,23 +92,22 @@
 
 void HTMLTrackElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
-    if (RuntimeEnabledFeatures::videoTrackEnabled()) {
-        if (name == srcAttr) {
-            if (!value.isEmpty())
-                scheduleLoad();
-            else if (m_track)
-                m_track->removeAllCues();
+    if (name == srcAttr) {
+        if (!value.isEmpty())
+            scheduleLoad();
+        else if (m_track)
+            m_track->removeAllCues();
 
-        // 4.8.10.12.3 Sourcing out-of-band text tracks
-        // As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly...
-        } else if (name == kindAttr)
-            track()->setKind(value.lower());
-        else if (name == labelAttr)
-            track()->setLabel(value);
-        else if (name == srclangAttr)
-            track()->setLanguage(value);
-        else if (name == defaultAttr)
-            track()->setIsDefault(!value.isNull());
+    // 4.8.10.12.3 Sourcing out-of-band text tracks
+    // As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly...
+    } else if (name == kindAttr) {
+        track()->setKind(value.lower());
+    } else if (name == labelAttr) {
+        track()->setLabel(value);
+    } else if (name == srclangAttr) {
+        track()->setLanguage(value);
+    } else if (name == defaultAttr) {
+        track()->setIsDefault(!value.isNull());
     }
 
     HTMLElement::parseAttribute(name, value);
@@ -126,44 +123,11 @@
     setAttribute(kindAttr, kind);
 }
 
-String HTMLTrackElement::srclang() const
-{
-    return getAttribute(srclangAttr);
-}
-
-void HTMLTrackElement::setSrclang(const String& srclang)
-{
-    setAttribute(srclangAttr, srclang);
-}
-
-String HTMLTrackElement::label() const
-{
-    return getAttribute(labelAttr);
-}
-
-void HTMLTrackElement::setLabel(const String& label)
-{
-    setAttribute(labelAttr, label);
-}
-
-bool HTMLTrackElement::isDefault() const
-{
-    return fastHasAttribute(defaultAttr);
-}
-
-void HTMLTrackElement::setIsDefault(bool isDefault)
-{
-    setBooleanAttribute(defaultAttr, isDefault);
-}
-
 LoadableTextTrack* HTMLTrackElement::ensureTrack()
 {
     if (!m_track) {
-        // The kind attribute is an enumerated attribute, limited only to know values. It defaults to 'subtitles' if missing or invalid.
-        String kind = getAttribute(kindAttr).lower();
-        if (!TextTrack::isValidKindKeyword(kind))
-            kind = TextTrack::subtitlesKeyword();
-        m_track = LoadableTextTrack::create(this, kind, label(), srclang());
+        // kind, label and language are updated by parseAttribute
+        m_track = LoadableTextTrack::create(this);
     }
     return m_track.get();
 }
@@ -187,9 +151,6 @@
     if (m_loadTimer.isActive())
         return;
 
-    if (!RuntimeEnabledFeatures::videoTrackEnabled())
-        return;
-
     // 2. If the text track's text track mode is not set to one of hidden or showing, abort these steps.
     if (ensureTrack()->mode() != TextTrack::hiddenKeyword() && ensureTrack()->mode() != TextTrack::showingKeyword())
         return;
@@ -227,9 +188,6 @@
 
 bool HTMLTrackElement::canLoadUrl(const KURL& url)
 {
-    if (!RuntimeEnabledFeatures::videoTrackEnabled())
-        return false;
-
     HTMLMediaElement* parent = mediaElement();
     if (!parent)
         return false;
diff --git a/Source/core/html/HTMLTrackElement.h b/Source/core/html/HTMLTrackElement.h
index 942fd8b..e2bd973 100644
--- a/Source/core/html/HTMLTrackElement.h
+++ b/Source/core/html/HTMLTrackElement.h
@@ -36,20 +36,11 @@
 
 class HTMLTrackElement FINAL : public HTMLElement, public TextTrackClient {
 public:
-    static PassRefPtr<HTMLTrackElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLTrackElement> create(Document&);
 
     String kind();
     void setKind(const String&);
 
-    String srclang() const;
-    void setSrclang(const String&);
-
-    String label() const;
-    void setLabel(const String&);
-
-    bool isDefault() const;
-    void setIsDefault(bool);
-
     enum ReadyState { NONE = 0, LOADING = 1, LOADED = 2, TRACK_ERROR = 3 };
     ReadyState readyState();
     void setReadyState(ReadyState);
@@ -64,7 +55,7 @@
     const AtomicString& mediaElementCrossOriginAttribute() const;
 
 private:
-    HTMLTrackElement(const QualifiedName&, Document&);
+    explicit HTMLTrackElement(Document&);
     virtual ~HTMLTrackElement();
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/html/HTMLTrackElement.idl b/Source/core/html/HTMLTrackElement.idl
index 4127db6..da7e22e 100644
--- a/Source/core/html/HTMLTrackElement.idl
+++ b/Source/core/html/HTMLTrackElement.idl
@@ -28,8 +28,8 @@
 ] interface HTMLTrackElement : HTMLElement {
     attribute DOMString kind;
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
-    attribute DOMString srclang;
-    attribute DOMString label;
+    [Reflect] attribute DOMString srclang;
+    [Reflect] attribute DOMString label;
     [Reflect] attribute boolean default;
 
     const unsigned short NONE = 0;
diff --git a/Source/core/html/HTMLUListElement.cpp b/Source/core/html/HTMLUListElement.cpp
index e5b804c..9eb6e55 100644
--- a/Source/core/html/HTMLUListElement.cpp
+++ b/Source/core/html/HTMLUListElement.cpp
@@ -30,21 +30,15 @@
 
 using namespace HTMLNames;
 
-HTMLUListElement::HTMLUListElement(const QualifiedName& tagName, Document& document)
-    : HTMLElement(tagName, document)
+HTMLUListElement::HTMLUListElement(Document& document)
+    : HTMLElement(ulTag, document)
 {
-    ASSERT(hasTagName(ulTag));
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLUListElement> HTMLUListElement::create(Document& document)
 {
-    return adoptRef(new HTMLUListElement(ulTag, document));
-}
-
-PassRefPtr<HTMLUListElement> HTMLUListElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLUListElement(tagName, document));
+    return adoptRef(new HTMLUListElement(document));
 }
 
 bool HTMLUListElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/Source/core/html/HTMLUListElement.h b/Source/core/html/HTMLUListElement.h
index 5954ed4..899467c 100644
--- a/Source/core/html/HTMLUListElement.h
+++ b/Source/core/html/HTMLUListElement.h
@@ -30,10 +30,9 @@
 class HTMLUListElement FINAL : public HTMLElement {
 public:
     static PassRefPtr<HTMLUListElement> create(Document&);
-    static PassRefPtr<HTMLUListElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLUListElement(const QualifiedName&, Document&);
+    explicit HTMLUListElement(Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLUListElement.idl b/Source/core/html/HTMLUListElement.idl
index 1dc6b6d..d7d123a 100644
--- a/Source/core/html/HTMLUListElement.idl
+++ b/Source/core/html/HTMLUListElement.idl
@@ -19,6 +19,5 @@
 
 interface HTMLUListElement : HTMLElement {
     [Reflect] attribute boolean compact;
-    [Reflect, TreatNullAs=NullString] attribute DOMString type;
+    [Reflect] attribute DOMString type;
 };
-
diff --git a/Source/core/html/HTMLVideoElement.cpp b/Source/core/html/HTMLVideoElement.cpp
index 0c1c5b3..2d88a66 100644
--- a/Source/core/html/HTMLVideoElement.cpp
+++ b/Source/core/html/HTMLVideoElement.cpp
@@ -28,6 +28,7 @@
 
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
@@ -43,18 +44,17 @@
 
 using namespace HTMLNames;
 
-inline HTMLVideoElement::HTMLVideoElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLMediaElement(tagName, document, createdByParser)
+inline HTMLVideoElement::HTMLVideoElement(Document& document, bool createdByParser)
+    : HTMLMediaElement(videoTag, document, createdByParser)
 {
-    ASSERT(hasTagName(videoTag));
     ScriptWrappable::init(this);
     if (document.settings())
         m_defaultPosterURL = document.settings()->defaultVideoPosterURL();
 }
 
-PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document, bool createdByParser)
 {
-    RefPtr<HTMLVideoElement> videoElement(adoptRef(new HTMLVideoElement(tagName, document, createdByParser)));
+    RefPtr<HTMLVideoElement> videoElement(adoptRef(new HTMLVideoElement(document, createdByParser)));
     videoElement->suspendIfNeeded();
     return videoElement.release();
 }
@@ -205,15 +205,19 @@
     return player()->hasVideo() && player()->readyState() >= MediaPlayer::HaveCurrentData;
 }
 
-void HTMLVideoElement::webkitEnterFullscreen(ExceptionState& es)
+void HTMLVideoElement::webkitEnterFullscreen(ExceptionState& exceptionState)
 {
     if (isFullscreen())
         return;
 
     // Generate an exception if this isn't called in response to a user gesture, or if the
     // element does not support fullscreen.
-    if ((userGestureRequiredForFullscreen() && !UserGestureIndicator::processingUserGesture()) || !supportsFullscreen()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+    if (userGestureRequiredForFullscreen() && !UserGestureIndicator::processingUserGesture()) {
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("enterFullscreen", "HTMLVideoElement", "This element may only enter fullscreen mode in response to a user gesture ('click', for example)."));
+        return;
+    }
+    if (!supportsFullscreen()) {
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("enterFullscreen", "HTMLVideoElement", "This element does not support fullscreen mode."));
         return;
     }
 
diff --git a/Source/core/html/HTMLVideoElement.h b/Source/core/html/HTMLVideoElement.h
index 0c72fab..4d729f3 100644
--- a/Source/core/html/HTMLVideoElement.h
+++ b/Source/core/html/HTMLVideoElement.h
@@ -35,8 +35,7 @@
 
 class HTMLVideoElement FINAL : public HTMLMediaElement {
 public:
-    static PassRefPtr<HTMLVideoElement> create(Document& document) { return create(HTMLNames::videoTag, document, false); }
-    static PassRefPtr<HTMLVideoElement> create(const QualifiedName&, Document&, bool);
+    static PassRefPtr<HTMLVideoElement> create(Document&, bool createdByParser = false);
 
     unsigned videoWidth() const;
     unsigned videoHeight() const;
@@ -63,7 +62,7 @@
     KURL posterImageURL() const;
 
 private:
-    HTMLVideoElement(const QualifiedName&, Document&, bool);
+    HTMLVideoElement(Document&, bool);
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
diff --git a/Source/core/html/HTMLVideoElement.idl b/Source/core/html/HTMLVideoElement.idl
index 96fc5bf..4448cd2 100644
--- a/Source/core/html/HTMLVideoElement.idl
+++ b/Source/core/html/HTMLVideoElement.idl
@@ -35,11 +35,11 @@
     [MeasureAs=PrefixedVideoSupportsFullscreen] readonly attribute boolean webkitSupportsFullscreen;
     [MeasureAs=PrefixedVideoDisplayingFullscreen] readonly attribute boolean webkitDisplayingFullscreen;
 
-    [MeasureAs=PrefixedVideoEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=AccessForAllWorlds] void webkitEnterFullscreen();
+    [MeasureAs=PrefixedVideoEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullscreen();
     [MeasureAs=PrefixedVideoExitFullscreen] void webkitExitFullscreen();
 
     // Note the different capitalization of the "S" in FullScreen.
-    [MeasureAs=PrefixedVideoEnterFullScreen, ImplementedAs=webkitEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=AccessForAllWorlds] void webkitEnterFullScreen();
+    [MeasureAs=PrefixedVideoEnterFullScreen, ImplementedAs=webkitEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullScreen();
     [MeasureAs=PrefixedVideoExitFullScreen, ImplementedAs=webkitExitFullscreen] void webkitExitFullScreen();
 
     // The number of frames that have been decoded and made available for
diff --git a/Source/core/html/HTMLViewSourceDocument.cpp b/Source/core/html/HTMLViewSourceDocument.cpp
index c04f475..4a55226 100644
--- a/Source/core/html/HTMLViewSourceDocument.cpp
+++ b/Source/core/html/HTMLViewSourceDocument.cpp
@@ -197,7 +197,7 @@
     // Create a cell that will hold the line number (it is generated in the stylesheet using counters).
     RefPtr<HTMLTableCellElement> td = HTMLTableCellElement::create(tdTag, *this);
     td->setAttribute(classAttr, "webkit-line-number");
-    td->setAttribute(valueAttr, String::number(++m_lineNumber));
+    td->setIntegralAttribute(valueAttr, ++m_lineNumber);
     trow->parserAppendChild(td);
 
     // Create a second cell for the line contents
@@ -270,7 +270,7 @@
 
 PassRefPtr<Element> HTMLViewSourceDocument::addBase(const AtomicString& href)
 {
-    RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(baseTag, *this);
+    RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(*this);
     base->setAttribute(hrefAttr, href);
     m_current->parserAppendChild(base);
     return base.release();
diff --git a/Source/core/html/ImageData.idl b/Source/core/html/ImageData.idl
index ca7d61c..64d53e9 100644
--- a/Source/core/html/ImageData.idl
+++ b/Source/core/html/ImageData.idl
@@ -27,7 +27,7 @@
  */
 
 [
-    CustomToV8
+    CustomWrap,
 ] interface ImageData {
     readonly attribute long width;
     readonly attribute long height;
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 31c91ee..350fa9e 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -94,7 +94,7 @@
     {
     }
 
-    virtual size_t appendBytes(const char*, size_t) OVERRIDE;
+    virtual void appendBytes(const char*, size_t) OVERRIDE;
     virtual void finish();
 };
 
@@ -120,19 +120,18 @@
     return result.toString();
 }
 
-size_t ImageDocumentParser::appendBytes(const char* data, size_t length)
+void ImageDocumentParser::appendBytes(const char* data, size_t length)
 {
     if (!length)
-        return 0;
+        return;
 
     Frame* frame = document()->frame();
     Settings* settings = frame->settings();
     if (!frame->loader().client()->allowImage(!settings || settings->areImagesEnabled(), document()->url()))
-        return 0;
+        return;
 
     document()->cachedImage()->appendData(data, length);
     document()->imageUpdated();
-    return 0;
 }
 
 void ImageDocumentParser::finish()
@@ -362,7 +361,7 @@
 
 bool ImageDocument::shouldShrinkToFit() const
 {
-    return frame()->settings()->shrinksStandaloneImagesToFit() && frame()->page()->mainFrame() == frame();
+    return frame()->settings()->shrinksStandaloneImagesToFit() && frame()->isMainFrame();
 }
 
 void ImageDocument::dispose()
diff --git a/Source/core/html/LinkResource.h b/Source/core/html/LinkResource.h
index b4eeb3d..4771bfb 100644
--- a/Source/core/html/LinkResource.h
+++ b/Source/core/html/LinkResource.h
@@ -32,7 +32,7 @@
 #define LinkResource_h
 
 #include "core/fetch/FetchRequest.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/html/MediaController.cpp b/Source/core/html/MediaController.cpp
index 5d26a40..e93bbc1 100644
--- a/Source/core/html/MediaController.cpp
+++ b/Source/core/html/MediaController.cpp
@@ -26,6 +26,7 @@
 #include "config.h"
 #include "core/html/MediaController.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ExceptionCode.h"
@@ -158,7 +159,7 @@
     return m_position;
 }
 
-void MediaController::setCurrentTime(double time, ExceptionState& es)
+void MediaController::setCurrentTime(double time, ExceptionState& exceptionState)
 {
     // When the user agent is to seek the media controller to a particular new playback position,
     // it must follow these steps:
@@ -174,7 +175,7 @@
 
     // Seek each slaved media element to the new playback position relative to the media element timeline.
     for (size_t index = 0; index < m_mediaElements.size(); ++index)
-        m_mediaElements[index]->seek(time, es);
+        m_mediaElements[index]->seek(time, exceptionState);
 
     scheduleTimeupdateEvent();
 }
@@ -252,7 +253,7 @@
     scheduleEvent(EventTypeNames::ratechange);
 }
 
-void MediaController::setVolume(double level, ExceptionState& es)
+void MediaController::setVolume(double level, ExceptionState& exceptionState)
 {
     if (m_volume == level)
         return;
@@ -260,7 +261,7 @@
     // If the new value is outside the range 0.0 to 1.0 inclusive, then, on setting, an
     // IndexSizeError exception must be raised instead.
     if (level < 0 || level > 1) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("volume", "MediaController", "The value provided (" + String::number(level) + ") is not in the range [0.0, 1.0]."));
         return;
     }
 
diff --git a/Source/core/html/MediaController.idl b/Source/core/html/MediaController.idl
index 254bbc2..76364f0 100644
--- a/Source/core/html/MediaController.idl
+++ b/Source/core/html/MediaController.idl
@@ -32,7 +32,7 @@
     readonly attribute TimeRanges seekable;
 
     readonly attribute double duration;
-    [SetterRaisesException] attribute double currentTime;
+    [RaisesException=Setter] attribute double currentTime;
 
     readonly attribute boolean paused;
     readonly attribute TimeRanges played;
@@ -44,6 +44,6 @@
     attribute double defaultPlaybackRate;
     attribute double playbackRate;
 
-    [SetterRaisesException] attribute double volume;
+    [RaisesException=Setter] attribute double volume;
     attribute boolean muted;
 };
diff --git a/Source/core/html/MediaDocument.cpp b/Source/core/html/MediaDocument.cpp
index 14d8d99..65af26d 100644
--- a/Source/core/html/MediaDocument.cpp
+++ b/Source/core/html/MediaDocument.cpp
@@ -63,7 +63,7 @@
     {
     }
 
-    virtual size_t appendBytes(const char*, size_t) OVERRIDE;
+    virtual void appendBytes(const char*, size_t) OVERRIDE;
 
     void createDocumentStructure();
 
@@ -108,14 +108,13 @@
     m_didBuildDocumentStructure = true;
 }
 
-size_t MediaDocumentParser::appendBytes(const char*, size_t)
+void MediaDocumentParser::appendBytes(const char*, size_t)
 {
     if (m_didBuildDocumentStructure)
-        return 0;
+        return;
 
     createDocumentStructure();
     finish();
-    return 0;
 }
 
 MediaDocument::MediaDocument(const DocumentInit& initializer)
@@ -134,7 +133,7 @@
 {
     ASSERT(root);
 
-    for (Node* node = root; node; node = NodeTraversal::next(node, root)) {
+    for (Node* node = root; node; node = NodeTraversal::next(*node, root)) {
         if (isHTMLVideoElement(node))
             return toHTMLVideoElement(node);
     }
diff --git a/Source/core/html/MediaFragmentURIParser.cpp b/Source/core/html/MediaFragmentURIParser.cpp
index c377581..f887a05 100644
--- a/Source/core/html/MediaFragmentURIParser.cpp
+++ b/Source/core/html/MediaFragmentURIParser.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/html/MediaFragmentURIParser.h"
 
-#include "core/platform/graphics/MediaPlayer.h"
+#include "platform/graphics/media/MediaPlayer.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/html/MediaFragmentURIParser.h b/Source/core/html/MediaFragmentURIParser.h
index 9348be0..df43c07 100644
--- a/Source/core/html/MediaFragmentURIParser.h
+++ b/Source/core/html/MediaFragmentURIParser.h
@@ -26,7 +26,7 @@
 #ifndef MediaFragmentURIParser_h
 #define MediaFragmentURIParser_h
 
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
diff --git a/Source/core/html/PluginDocument.cpp b/Source/core/html/PluginDocument.cpp
index e36e8d8..b132b9f 100644
--- a/Source/core/html/PluginDocument.cpp
+++ b/Source/core/html/PluginDocument.cpp
@@ -58,7 +58,7 @@
     {
     }
 
-    virtual size_t appendBytes(const char*, size_t) OVERRIDE;
+    virtual void appendBytes(const char*, size_t) OVERRIDE;
 
     virtual void finish() OVERRIDE;
 
@@ -115,17 +115,15 @@
         view->didReceiveResponse(document()->loader()->response());
 }
 
-size_t PluginDocumentParser::appendBytes(const char* data, size_t length)
+void PluginDocumentParser::appendBytes(const char* data, size_t length)
 {
     if (!m_embedElement)
         createDocumentStructure();
 
     if (!length)
-        return 0;
+        return;
     if (PluginView* view = pluginView())
         view->didReceiveData(data, length);
-
-    return 0;
 }
 
 void PluginDocumentParser::finish()
diff --git a/Source/core/html/PublicURLManager.cpp b/Source/core/html/PublicURLManager.cpp
index 77d8da9..09157de 100644
--- a/Source/core/html/PublicURLManager.cpp
+++ b/Source/core/html/PublicURLManager.cpp
@@ -28,7 +28,7 @@
 #include "core/html/PublicURLManager.h"
 
 #include "core/html/URLRegistry.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/text/StringHash.h"
 
 namespace WebCore {
diff --git a/Source/core/html/TimeRanges.cpp b/Source/core/html/TimeRanges.cpp
index 71fd4fd..219af3a 100644
--- a/Source/core/html/TimeRanges.cpp
+++ b/Source/core/html/TimeRanges.cpp
@@ -26,6 +26,7 @@
 #include "config.h"
 #include "core/html/TimeRanges.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ExceptionCode.h"
@@ -40,6 +41,17 @@
     add(start, end);
 }
 
+PassRefPtr<TimeRanges> TimeRanges::create(const blink::WebTimeRanges& webRanges)
+{
+    RefPtr<TimeRanges> ranges = TimeRanges::create();
+
+    unsigned size = webRanges.size();
+    for (unsigned i = 0; i < size; ++i)
+        ranges->add(webRanges[i].start, webRanges[i].end);
+
+    return ranges.release();
+}
+
 PassRefPtr<TimeRanges> TimeRanges::copy() const
 {
     RefPtr<TimeRanges> newSession = TimeRanges::create();
@@ -102,19 +114,19 @@
     m_ranges.swap(unioned->m_ranges);
 }
 
-double TimeRanges::start(unsigned index, ExceptionState& es) const
+double TimeRanges::start(unsigned index, ExceptionState& exceptionState) const
 {
     if (index >= length()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("start", "TimeRanges", "The index provided (" + String::number(index) + ") is not less than the object's length (" + String::number(length()) + ")."));
         return 0;
     }
     return m_ranges[index].m_start;
 }
 
-double TimeRanges::end(unsigned index, ExceptionState& es) const
+double TimeRanges::end(unsigned index, ExceptionState& exceptionState) const
 {
     if (index >= length()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("end", "TimeRanges", "The index provided (" + String::number(index) + ") is not less than the object's length (" + String::number(length()) + ")."));
         return 0;
     }
     return m_ranges[index].m_end;
diff --git a/Source/core/html/TimeRanges.h b/Source/core/html/TimeRanges.h
index 39a16d3..a3c82e5 100644
--- a/Source/core/html/TimeRanges.h
+++ b/Source/core/html/TimeRanges.h
@@ -27,6 +27,7 @@
 #define TimeRanges_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "public/platform/WebTimeRange.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
@@ -47,6 +48,7 @@
     {
         return adoptRef(new TimeRanges(start, end));
     }
+    static PassRefPtr<TimeRanges> create(const blink::WebTimeRanges&);
 
     PassRefPtr<TimeRanges> copy() const;
     void intersectWith(const TimeRanges*);
diff --git a/Source/core/html/TimeRangesTest.cpp b/Source/core/html/TimeRangesTest.cpp
index 9c92149..584761c 100644
--- a/Source/core/html/TimeRangesTest.cpp
+++ b/Source/core/html/TimeRangesTest.cpp
@@ -61,6 +61,16 @@
     ASSERT_RANGE("{ [1,2) }", TimeRanges::create(1, 2));
 }
 
+TEST(TimeRanges, CreateFromWebTimeRanges)
+{
+    blink::WebTimeRanges webRanges(static_cast<size_t>(2));
+    webRanges[0].start = 0;
+    webRanges[0].end = 1;
+    webRanges[1].start = 2;
+    webRanges[1].end = 3;
+    ASSERT_RANGE("{ [0,1) [2,3) }", TimeRanges::create(webRanges));
+}
+
 TEST(TimeRanges, AddOrder)
 {
     RefPtr<TimeRanges> rangeA = TimeRanges::create();
diff --git a/Source/core/html/canvas/ArrayBufferView.idl b/Source/core/html/canvas/ArrayBufferView.idl
index 5545731..241435c 100644
--- a/Source/core/html/canvas/ArrayBufferView.idl
+++ b/Source/core/html/canvas/ArrayBufferView.idl
@@ -25,7 +25,7 @@
 
 [
     NoInterfaceObject,
-    CustomToV8
+    CustomWrap,
 ] interface ArrayBufferView {
     readonly attribute ArrayBuffer buffer;
     readonly attribute unsigned long byteOffset;
diff --git a/Source/core/html/canvas/CanvasGradient.cpp b/Source/core/html/canvas/CanvasGradient.cpp
index a54df39..07e62a0 100644
--- a/Source/core/html/canvas/CanvasGradient.cpp
+++ b/Source/core/html/canvas/CanvasGradient.cpp
@@ -46,16 +46,16 @@
     ScriptWrappable::init(this);
 }
 
-void CanvasGradient::addColorStop(float value, const String& color, ExceptionState& es)
+void CanvasGradient::addColorStop(float value, const String& color, ExceptionState& exceptionState)
 {
     if (!(value >= 0 && value <= 1.0f)) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
     RGBA32 rgba = 0;
     if (!parseColorOrCurrentColor(rgba, color, 0 /*canvas*/)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
diff --git a/Source/core/html/canvas/CanvasPathMethods.cpp b/Source/core/html/canvas/CanvasPathMethods.cpp
index c7144f6..9d76556 100644
--- a/Source/core/html/canvas/CanvasPathMethods.cpp
+++ b/Source/core/html/canvas/CanvasPathMethods.cpp
@@ -107,13 +107,13 @@
         m_path.addBezierCurveTo(cp1, cp2, p1);
 }
 
-void CanvasPathMethods::arcTo(float x1, float y1, float x2, float y2, float r, ExceptionState& es)
+void CanvasPathMethods::arcTo(float x1, float y1, float x2, float y2, float r, ExceptionState& exceptionState)
 {
     if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(x2) || !std::isfinite(y2) || !std::isfinite(r))
         return;
 
     if (r < 0) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
@@ -253,13 +253,13 @@
 
 } // namespace
 
-void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, float endAngle, bool anticlockwise, ExceptionState& es)
+void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, float endAngle, bool anticlockwise, ExceptionState& exceptionState)
 {
     if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radius) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
         return;
 
     if (radius < 0) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
@@ -277,13 +277,13 @@
     m_path.addArc(FloatPoint(x, y), radius, startAngle, adjustedEndAngle, anticlockwise);
 }
 
-void CanvasPathMethods::ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise, ExceptionState& es)
+void CanvasPathMethods::ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise, ExceptionState& exceptionState)
 {
     if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radiusX) || !std::isfinite(radiusY) || !std::isfinite(rotation) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
         return;
 
     if (radiusX < 0 || radiusY < 0) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
diff --git a/Source/core/html/canvas/CanvasPattern.cpp b/Source/core/html/canvas/CanvasPattern.cpp
index 3a59f71..f7ee0da 100644
--- a/Source/core/html/canvas/CanvasPattern.cpp
+++ b/Source/core/html/canvas/CanvasPattern.cpp
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 
-void CanvasPattern::parseRepetitionType(const String& type, bool& repeatX, bool& repeatY, ExceptionState& es)
+void CanvasPattern::parseRepetitionType(const String& type, bool& repeatX, bool& repeatY, ExceptionState& exceptionState)
 {
     if (type.isEmpty() || type == "repeat") {
         repeatX = true;
@@ -54,7 +54,7 @@
         repeatY = true;
         return;
     }
-    es.throwUninformativeAndGenericDOMException(SyntaxError);
+    exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
 }
 
 CanvasPattern::CanvasPattern(PassRefPtr<Image> image, bool repeatX, bool repeatY, bool originClean)
diff --git a/Source/core/html/canvas/CanvasRenderingContext.cpp b/Source/core/html/canvas/CanvasRenderingContext.cpp
index 7d259a4..3ed7d1c 100644
--- a/Source/core/html/canvas/CanvasRenderingContext.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext.cpp
@@ -31,7 +31,7 @@
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/canvas/CanvasPattern.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/CanvasRenderingContext.h b/Source/core/html/canvas/CanvasRenderingContext.h
index a7cefa3..2f5cd63 100644
--- a/Source/core/html/canvas/CanvasRenderingContext.h
+++ b/Source/core/html/canvas/CanvasRenderingContext.h
@@ -32,7 +32,7 @@
 #include "wtf/Noncopyable.h"
 #include "wtf/text/StringHash.h"
 
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
 
 namespace WebCore {
 
@@ -59,7 +59,7 @@
 
     virtual void paintRenderingResultsToCanvas() {}
 
-    virtual WebKit::WebLayer* platformLayer() const { return 0; }
+    virtual blink::WebLayer* platformLayer() const { return 0; }
 
 protected:
     CanvasRenderingContext(HTMLCanvasElement*);
diff --git a/Source/core/html/canvas/CanvasRenderingContext.idl b/Source/core/html/canvas/CanvasRenderingContext.idl
index 36a7911..edb1d5f 100644
--- a/Source/core/html/canvas/CanvasRenderingContext.idl
+++ b/Source/core/html/canvas/CanvasRenderingContext.idl
@@ -25,7 +25,7 @@
 
 [
     NoInterfaceObject,
-    CustomToV8
+    CustomWrap,
 ] interface CanvasRenderingContext {
     readonly attribute HTMLCanvasElement canvas;
 };
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index 065f8ea..7daf195 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -65,7 +65,7 @@
 #include "platform/graphics/DrawLooper.h"
 #include "platform/graphics/TextRun.h"
 #include "platform/transforms/AffineTransform.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/CheckedArithmetic.h"
 #include "wtf/MathExtras.h"
 #include "wtf/OwnPtr.h"
@@ -112,7 +112,7 @@
 
 bool CanvasRenderingContext2D::isAccelerated() const
 {
-    if (!canvas()->hasCreatedImageBuffer())
+    if (!canvas()->hasImageBuffer())
         return false;
     GraphicsContext* context = drawingContext();
     return context && context->isAccelerated();
@@ -725,7 +725,7 @@
     c->setCTM(canvas()->baseTransform());
 
     if (invertibleCTM)
-        m_path.transform(ctm.inverse());
+        m_path.transform(ctm);
     // When else, do nothing because all transform methods didn't update m_path when CTM became non-invertible.
     // It means that resetTransform() restores m_path just before CTM became non-invertible.
 }
@@ -1289,34 +1289,34 @@
     }
 }
 
-void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap, float x, float y, ExceptionState& exceptionState)
 {
     if (!bitmap) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
-    drawImage(bitmap, x, y, bitmap->width(), bitmap->height(), es);
+    drawImage(bitmap, x, y, bitmap->width(), bitmap->height(), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap,
-    float x, float y, float width, float height, ExceptionState& es)
+    float x, float y, float width, float height, ExceptionState& exceptionState)
 {
     if (!bitmap) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
     if (!bitmap->bitmapRect().width() || !bitmap->bitmapRect().height())
         return;
 
-    drawImage(bitmap, 0, 0, bitmap->width(), bitmap->height(), x, y, width, height, es);
+    drawImage(bitmap, 0, 0, bitmap->width(), bitmap->height(), x, y, width, height, exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap,
     float sx, float sy, float sw, float sh,
-    float dx, float dy, float dw, float dh, ExceptionState& es)
+    float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
 {
     if (!bitmap) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
 
@@ -1331,7 +1331,7 @@
     if (!dstRect.width() || !dstRect.height())
         return;
     if (!srcRect.width() || !srcRect.height()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
@@ -1364,43 +1364,43 @@
     drawImageInternal(imageForRendering.get(), actualSrcRect, actualDstRect, state().m_globalComposite, state().m_globalBlend);
 }
 
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, float x, float y, ExceptionState& exceptionState)
 {
     if (!image) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
     LayoutSize destRectSize = sizeFor(image, ImageSizeAfterDevicePixelRatio);
-    drawImage(image, x, y, destRectSize.width(), destRectSize.height(), es);
+    drawImage(image, x, y, destRectSize.width(), destRectSize.height(), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
-    float x, float y, float width, float height, ExceptionState& es)
+    float x, float y, float width, float height, ExceptionState& exceptionState)
 {
     if (!image) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
     LayoutSize sourceRectSize = sizeFor(image, ImageSizeBeforeDevicePixelRatio);
-    drawImage(image, FloatRect(0, 0, sourceRectSize.width(), sourceRectSize.height()), FloatRect(x, y, width, height), es);
+    drawImage(image, FloatRect(0, 0, sourceRectSize.width(), sourceRectSize.height()), FloatRect(x, y, width, height), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
     float sx, float sy, float sw, float sh,
-    float dx, float dy, float dw, float dh, ExceptionState& es)
+    float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
 {
-    drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), es);
+    drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), exceptionState);
 }
 
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& exceptionState)
 {
-    drawImage(image, srcRect, dstRect, state().m_globalComposite, state().m_globalBlend, es);
+    drawImage(image, srcRect, dstRect, state().m_globalComposite, state().m_globalBlend, exceptionState);
 }
 
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const BlendMode& blendMode, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const BlendMode& blendMode, ExceptionState& exceptionState)
 {
     if (!image) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
 
@@ -1414,7 +1414,7 @@
 
     LayoutSize size = sizeFor(image, ImageSizeBeforeDevicePixelRatio);
     if (!size.width() || !size.height()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
@@ -1426,7 +1426,7 @@
 
     FloatRect imageRect = FloatRect(FloatPoint(), size);
     if (!srcRect.width() || !srcRect.height()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
     if (!imageRect.intersects(normalizedSrcRect))
@@ -1447,41 +1447,41 @@
     drawImageInternal(imageForRendering, normalizedSrcRect, normalizedDstRect, op, blendMode);
 }
 
-void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, float x, float y, ExceptionState& exceptionState)
 {
-    drawImage(sourceCanvas, 0, 0, sourceCanvas->width(), sourceCanvas->height(), x, y, sourceCanvas->width(), sourceCanvas->height(), es);
+    drawImage(sourceCanvas, 0, 0, sourceCanvas->width(), sourceCanvas->height(), x, y, sourceCanvas->width(), sourceCanvas->height(), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas,
-    float x, float y, float width, float height, ExceptionState& es)
+    float x, float y, float width, float height, ExceptionState& exceptionState)
 {
-    drawImage(sourceCanvas, FloatRect(0, 0, sourceCanvas->width(), sourceCanvas->height()), FloatRect(x, y, width, height), es);
+    drawImage(sourceCanvas, FloatRect(0, 0, sourceCanvas->width(), sourceCanvas->height()), FloatRect(x, y, width, height), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas,
     float sx, float sy, float sw, float sh,
-    float dx, float dy, float dw, float dh, ExceptionState& es)
+    float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
 {
-    drawImage(sourceCanvas, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), es);
+    drawImage(sourceCanvas, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, const FloatRect& srcRect,
-    const FloatRect& dstRect, ExceptionState& es)
+    const FloatRect& dstRect, ExceptionState& exceptionState)
 {
     if (!sourceCanvas) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
 
     FloatRect srcCanvasRect = FloatRect(FloatPoint(), sourceCanvas->size());
 
     if (!srcCanvasRect.width() || !srcCanvasRect.height()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
     if (!srcRect.width() || !srcRect.height()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
@@ -1536,38 +1536,38 @@
     }
 }
 
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, float x, float y, ExceptionState& exceptionState)
 {
     if (!video) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
     IntSize size = sizeFor(video);
-    drawImage(video, x, y, size.width(), size.height(), es);
+    drawImage(video, x, y, size.width(), size.height(), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
-    float x, float y, float width, float height, ExceptionState& es)
+    float x, float y, float width, float height, ExceptionState& exceptionState)
 {
     if (!video) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
     IntSize size = sizeFor(video);
-    drawImage(video, FloatRect(0, 0, size.width(), size.height()), FloatRect(x, y, width, height), es);
+    drawImage(video, FloatRect(0, 0, size.width(), size.height()), FloatRect(x, y, width, height), exceptionState);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
     float sx, float sy, float sw, float sh,
-    float dx, float dy, float dw, float dh, ExceptionState& es)
+    float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
 {
-    drawImage(video, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), es);
+    drawImage(video, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), exceptionState);
 }
 
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& exceptionState)
 {
     if (!video) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
 
@@ -1576,7 +1576,7 @@
 
     FloatRect videoRect = FloatRect(FloatPoint(), sizeFor(video));
     if (!srcRect.width() || !srcRect.height()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
@@ -1697,10 +1697,10 @@
     c->endLayer();
 }
 
-PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1, ExceptionState& es)
+PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1, ExceptionState& exceptionState)
 {
     if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
@@ -1708,15 +1708,15 @@
     return gradient.release();
 }
 
-PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionState& es)
+PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionState& exceptionState)
 {
     if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(r0) || !std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(r1)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     if (r0 < 0 || r1 < 0) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return 0;
     }
 
@@ -1725,15 +1725,15 @@
 }
 
 PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLImageElement* image,
-    const String& repetitionType, ExceptionState& es)
+    const String& repetitionType, ExceptionState& exceptionState)
 {
     if (!image) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return 0;
     }
     bool repeatX, repeatY;
-    CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, es);
-    if (es.hadException())
+    CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     if (!image->complete())
@@ -1753,20 +1753,20 @@
 }
 
 PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLCanvasElement* canvas,
-    const String& repetitionType, ExceptionState& es)
+    const String& repetitionType, ExceptionState& exceptionState)
 {
     if (!canvas) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return 0;
     }
     if (!canvas->width() || !canvas->height()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return 0;
     }
 
     bool repeatX, repeatY;
-    CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, es);
-    if (es.hadException())
+    CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, exceptionState);
+    if (exceptionState.hadException())
         return 0;
     return CanvasPattern::create(canvas->copiedImage(), repeatX, repeatY, canvas->originClean());
 }
@@ -1837,24 +1837,24 @@
     return data.release();
 }
 
-PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtr<ImageData> imageData, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtr<ImageData> imageData, ExceptionState& exceptionState) const
 {
     if (!imageData) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     return createEmptyImageData(imageData->size());
 }
 
-PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionState& exceptionState) const
 {
     if (!sw || !sh) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return 0;
     }
     if (!std::isfinite(sw) || !std::isfinite(sh)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
@@ -1871,29 +1871,29 @@
     return createEmptyImageData(size);
 }
 
-PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
 {
-    return getImageData(ImageBuffer::LogicalCoordinateSystem, sx, sy, sw, sh, es);
+    return getImageData(ImageBuffer::LogicalCoordinateSystem, sx, sy, sw, sh, exceptionState);
 }
 
-PassRefPtr<ImageData> CanvasRenderingContext2D::webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
 {
-    return getImageData(ImageBuffer::BackingStoreCoordinateSystem, sx, sy, sw, sh, es);
+    return getImageData(ImageBuffer::BackingStoreCoordinateSystem, sx, sy, sw, sh, exceptionState);
 }
 
-PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::CoordinateSystem coordinateSystem, float sx, float sy, float sw, float sh, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::CoordinateSystem coordinateSystem, float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
 {
     if (!canvas()->originClean()) {
-        es.throwSecurityError(ExceptionMessages::failedToExecute("getImageData", "CanvasRenderingContext2D", "the canvas has been tainted by cross-origin data."));
+        exceptionState.throwSecurityError(ExceptionMessages::failedToExecute("getImageData", "CanvasRenderingContext2D", "the canvas has been tainted by cross-origin data."));
         return 0;
     }
 
     if (!sw || !sh) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return 0;
     }
     if (!std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
@@ -1926,44 +1926,44 @@
     return ImageData::create(imageDataRect.size(), byteArray.release());
 }
 
-void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, ExceptionState& es)
+void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, ExceptionState& exceptionState)
 {
     if (!data) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
-    putImageData(data, dx, dy, 0, 0, data->width(), data->height(), es);
+    putImageData(data, dx, dy, 0, 0, data->width(), data->height(), exceptionState);
 }
 
-void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, ExceptionState& es)
+void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, ExceptionState& exceptionState)
 {
     if (!data) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
-    webkitPutImageDataHD(data, dx, dy, 0, 0, data->width(), data->height(), es);
+    webkitPutImageDataHD(data, dx, dy, 0, 0, data->width(), data->height(), exceptionState);
 }
 
 void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, float dirtyX, float dirtyY,
-    float dirtyWidth, float dirtyHeight, ExceptionState& es)
+    float dirtyWidth, float dirtyHeight, ExceptionState& exceptionState)
 {
-    putImageData(data, ImageBuffer::LogicalCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, es);
+    putImageData(data, ImageBuffer::LogicalCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, exceptionState);
 }
 
-void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionState& es)
+void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionState& exceptionState)
 {
-    putImageData(data, ImageBuffer::BackingStoreCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, es);
+    putImageData(data, ImageBuffer::BackingStoreCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, exceptionState);
 }
 
 void CanvasRenderingContext2D::putImageData(ImageData* data, ImageBuffer::CoordinateSystem coordinateSystem, float dx, float dy, float dirtyX, float dirtyY,
-    float dirtyWidth, float dirtyHeight, ExceptionState& es)
+    float dirtyWidth, float dirtyHeight, ExceptionState& exceptionState)
 {
     if (!data) {
-        es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
         return;
     }
     if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dirtyX) || !std::isfinite(dirtyY) || !std::isfinite(dirtyWidth) || !std::isfinite(dirtyHeight)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
@@ -2310,7 +2310,7 @@
     return state().m_font;
 }
 
-WebKit::WebLayer* CanvasRenderingContext2D::platformLayer() const
+blink::WebLayer* CanvasRenderingContext2D::platformLayer() const
 {
     return canvas()->buffer() ? canvas()->buffer()->platformLayer() : 0;
 }
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.h b/Source/core/html/canvas/CanvasRenderingContext2D.h
index 31f474e..880127b 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -41,7 +41,7 @@
 #include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
 
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
 
 namespace WebCore {
 
@@ -330,7 +330,7 @@
 
     virtual bool isTransformInvertible() const { return state().m_invertibleCTM; }
 
-    virtual WebKit::WebLayer* platformLayer() const OVERRIDE;
+    virtual blink::WebLayer* platformLayer() const OVERRIDE;
 
     Vector<State, 1> m_stateStack;
     unsigned m_unrealizedSaveCount;
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.idl b/Source/core/html/canvas/CanvasRenderingContext2D.idl
index 52b20e2..1c243a6 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.idl
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.idl
@@ -154,8 +154,8 @@
     [RaisesException] ImageData createImageData(ImageData? imagedata);
     [RaisesException] ImageData createImageData(float sw, float sh);
 
-    [Custom] attribute custom strokeStyle;
-    [Custom] attribute custom fillStyle;
+    [Custom] attribute object strokeStyle;
+    [Custom] attribute object fillStyle;
 
     // pixel manipulation
     [RaisesException] ImageData getImageData(float sx, float sy, float sw, float sh);
diff --git a/Source/core/html/canvas/DataView.cpp b/Source/core/html/canvas/DataView.cpp
index 6a2856c..5a28161 100644
--- a/Source/core/html/canvas/DataView.cpp
+++ b/Source/core/html/canvas/DataView.cpp
@@ -130,10 +130,10 @@
 }
 
 template<typename T>
-T DataView::getData(unsigned byteOffset, bool littleEndian, ExceptionState& es) const
+T DataView::getData(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState) const
 {
     if (beyondRange<T>(byteOffset)) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return 0;
     }
 
@@ -145,10 +145,10 @@
 }
 
 template<typename T>
-void DataView::setData(unsigned byteOffset, T value, bool littleEndian, ExceptionState& es)
+void DataView::setData(unsigned byteOffset, T value, bool littleEndian, ExceptionState& exceptionState)
 {
     if (beyondRange<T>(byteOffset)) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
@@ -159,84 +159,84 @@
     memcpy(static_cast<char*>(m_baseAddress) + byteOffset, tempValue.bytes, sizeof(T));
 }
 
-int8_t DataView::getInt8(unsigned byteOffset, ExceptionState& es)
+int8_t DataView::getInt8(unsigned byteOffset, ExceptionState& exceptionState)
 {
-    return getData<int8_t>(byteOffset, false, es);
+    return getData<int8_t>(byteOffset, false, exceptionState);
 }
 
-uint8_t DataView::getUint8(unsigned byteOffset, ExceptionState& es)
+uint8_t DataView::getUint8(unsigned byteOffset, ExceptionState& exceptionState)
 {
-    return getData<uint8_t>(byteOffset, false, es);
+    return getData<uint8_t>(byteOffset, false, exceptionState);
 }
 
-int16_t DataView::getInt16(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+int16_t DataView::getInt16(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
 {
-    return getData<int16_t>(byteOffset, littleEndian, es);
+    return getData<int16_t>(byteOffset, littleEndian, exceptionState);
 }
 
-uint16_t DataView::getUint16(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+uint16_t DataView::getUint16(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
 {
-    return getData<uint16_t>(byteOffset, littleEndian, es);
+    return getData<uint16_t>(byteOffset, littleEndian, exceptionState);
 }
 
-int32_t DataView::getInt32(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+int32_t DataView::getInt32(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
 {
-    return getData<int32_t>(byteOffset, littleEndian, es);
+    return getData<int32_t>(byteOffset, littleEndian, exceptionState);
 }
 
-uint32_t DataView::getUint32(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+uint32_t DataView::getUint32(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
 {
-    return getData<uint32_t>(byteOffset, littleEndian, es);
+    return getData<uint32_t>(byteOffset, littleEndian, exceptionState);
 }
 
-float DataView::getFloat32(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+float DataView::getFloat32(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
 {
-    return getData<float>(byteOffset, littleEndian, es);
+    return getData<float>(byteOffset, littleEndian, exceptionState);
 }
 
-double DataView::getFloat64(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+double DataView::getFloat64(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
 {
-    return getData<double>(byteOffset, littleEndian, es);
+    return getData<double>(byteOffset, littleEndian, exceptionState);
 }
 
-void DataView::setInt8(unsigned byteOffset, int8_t value, ExceptionState& es)
+void DataView::setInt8(unsigned byteOffset, int8_t value, ExceptionState& exceptionState)
 {
-    setData<int8_t>(byteOffset, value, false, es);
+    setData<int8_t>(byteOffset, value, false, exceptionState);
 }
 
-void DataView::setUint8(unsigned byteOffset, uint8_t value, ExceptionState& es)
+void DataView::setUint8(unsigned byteOffset, uint8_t value, ExceptionState& exceptionState)
 {
-    setData<uint8_t>(byteOffset, value, false, es);
+    setData<uint8_t>(byteOffset, value, false, exceptionState);
 }
 
-void DataView::setInt16(unsigned byteOffset, short value, bool littleEndian, ExceptionState& es)
+void DataView::setInt16(unsigned byteOffset, short value, bool littleEndian, ExceptionState& exceptionState)
 {
-    setData<int16_t>(byteOffset, value, littleEndian, es);
+    setData<int16_t>(byteOffset, value, littleEndian, exceptionState);
 }
 
-void DataView::setUint16(unsigned byteOffset, uint16_t value, bool littleEndian, ExceptionState& es)
+void DataView::setUint16(unsigned byteOffset, uint16_t value, bool littleEndian, ExceptionState& exceptionState)
 {
-    setData<uint16_t>(byteOffset, value, littleEndian, es);
+    setData<uint16_t>(byteOffset, value, littleEndian, exceptionState);
 }
 
-void DataView::setInt32(unsigned byteOffset, int32_t value, bool littleEndian, ExceptionState& es)
+void DataView::setInt32(unsigned byteOffset, int32_t value, bool littleEndian, ExceptionState& exceptionState)
 {
-    setData<int32_t>(byteOffset, value, littleEndian, es);
+    setData<int32_t>(byteOffset, value, littleEndian, exceptionState);
 }
 
-void DataView::setUint32(unsigned byteOffset, uint32_t value, bool littleEndian, ExceptionState& es)
+void DataView::setUint32(unsigned byteOffset, uint32_t value, bool littleEndian, ExceptionState& exceptionState)
 {
-    setData<uint32_t>(byteOffset, value, littleEndian, es);
+    setData<uint32_t>(byteOffset, value, littleEndian, exceptionState);
 }
 
-void DataView::setFloat32(unsigned byteOffset, float value, bool littleEndian, ExceptionState& es)
+void DataView::setFloat32(unsigned byteOffset, float value, bool littleEndian, ExceptionState& exceptionState)
 {
-    setData<float>(byteOffset, value, littleEndian, es);
+    setData<float>(byteOffset, value, littleEndian, exceptionState);
 }
 
-void DataView::setFloat64(unsigned byteOffset, double value, bool littleEndian, ExceptionState& es)
+void DataView::setFloat64(unsigned byteOffset, double value, bool littleEndian, ExceptionState& exceptionState)
 {
-    setData<double>(byteOffset, value, littleEndian, es);
+    setData<double>(byteOffset, value, littleEndian, exceptionState);
 }
 
 void DataView::neuter()
diff --git a/Source/core/html/canvas/DataView.idl b/Source/core/html/canvas/DataView.idl
index 5847f9c..0575067 100644
--- a/Source/core/html/canvas/DataView.idl
+++ b/Source/core/html/canvas/DataView.idl
@@ -26,7 +26,7 @@
 [
     GlobalContext=Window&WorkerGlobalScope,
     CustomConstructor(ArrayBuffer buffer, optional unsigned long byteOffset, optional unsigned long byteLength),
-    CustomToV8
+    CustomWrap,
 ] interface DataView : ArrayBufferView {
     // All these methods raise an exception if they would read or write beyond the end of the view.
 
diff --git a/Source/core/html/canvas/WebGLContextAttributes.cpp b/Source/core/html/canvas/WebGLContextAttributes.cpp
index a28e4cf..cb26556 100644
--- a/Source/core/html/canvas/WebGLContextAttributes.cpp
+++ b/Source/core/html/canvas/WebGLContextAttributes.cpp
@@ -117,6 +117,16 @@
     m_attrs.preserveDrawingBuffer = preserveDrawingBuffer;
 }
 
+bool WebGLContextAttributes::failIfMajorPerformanceCaveat() const
+{
+    return m_attrs.failIfMajorPerformanceCaveat;
+}
+
+void WebGLContextAttributes::setFailIfMajorPerformanceCaveat(bool failIfMajorPerformanceCaveat)
+{
+    m_attrs.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;
+}
+
 GraphicsContext3D::Attributes WebGLContextAttributes::attributes() const
 {
     return m_attrs;
diff --git a/Source/core/html/canvas/WebGLContextAttributes.h b/Source/core/html/canvas/WebGLContextAttributes.h
index d609920..f690351 100644
--- a/Source/core/html/canvas/WebGLContextAttributes.h
+++ b/Source/core/html/canvas/WebGLContextAttributes.h
@@ -71,6 +71,11 @@
     bool preserveDrawingBuffer() const;
     void setPreserveDrawingBuffer(bool);
 
+    // Whether or not to fail context creation if performance will be
+    // significantly degraded compared to a native GL context; default=false
+    bool failIfMajorPerformanceCaveat() const;
+    void setFailIfMajorPerformanceCaveat(bool);
+
     // Fetches a copy of the attributes stored in this object in a
     // form that can be used to initialize a GraphicsContext3D.
     GraphicsContext3D::Attributes attributes() const;
diff --git a/Source/core/html/canvas/WebGLContextAttributes.idl b/Source/core/html/canvas/WebGLContextAttributes.idl
index d971644..0fe4662 100644
--- a/Source/core/html/canvas/WebGLContextAttributes.idl
+++ b/Source/core/html/canvas/WebGLContextAttributes.idl
@@ -33,4 +33,5 @@
     attribute boolean antialias;
     attribute boolean premultipliedAlpha;
     attribute boolean preserveDrawingBuffer;
+    attribute boolean failIfMajorPerformanceCaveat;
 };
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index 54a25b8..21b3fe5 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -237,31 +237,6 @@
         return object ? object->object() : 0;
     }
 
-    void clip1D(GC3Dint start, GC3Dsizei range, GC3Dsizei sourceRange, GC3Dint* clippedStart, GC3Dsizei* clippedRange)
-    {
-        ASSERT(clippedStart && clippedRange);
-        if (start < 0) {
-            range += start;
-            start = 0;
-        }
-        GC3Dint end = start + range;
-        if (end > sourceRange)
-            range -= end - sourceRange;
-        *clippedStart = start;
-        *clippedRange = range;
-    }
-
-    // Returns false if no clipping is necessary, i.e., x, y, width, height stay the same.
-    bool clip2D(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height,
-                GC3Dsizei sourceWidth, GC3Dsizei sourceHeight,
-                GC3Dint* clippedX, GC3Dint* clippedY, GC3Dsizei* clippedWidth, GC3Dsizei*clippedHeight)
-    {
-        ASSERT(clippedX && clippedY && clippedWidth && clippedHeight);
-        clip1D(x, width, sourceWidth, clippedX, clippedWidth);
-        clip1D(y, height, sourceHeight, clippedY, clippedHeight);
-        return (*clippedX != x || *clippedY != y || *clippedWidth != width || *clippedHeight != height);
-    }
-
     GC3Dint clamp(GC3Dint value, GC3Dint min, GC3Dint max)
     {
         if (value < min)
@@ -925,7 +900,8 @@
     m_markedCanvasDirty = false;
 
     m_drawingBuffer->commit();
-    m_context->paintRenderingResultsToCanvas(canvas()->buffer(), m_drawingBuffer.get());
+    if (!(canvas()->buffer())->copyRenderingResultsFromDrawingBuffer(m_drawingBuffer.get()))
+        m_context->paintRenderingResultsToCanvas(canvas()->buffer(), m_drawingBuffer.get());
 
     if (m_framebufferBinding)
         m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
@@ -940,14 +916,17 @@
 
     clearIfComposited();
     m_drawingBuffer->commit();
-    RefPtr<ImageData> imageData = m_context->paintRenderingResultsToImageData(m_drawingBuffer.get());
+    int width, height;
+    RefPtr<Uint8ClampedArray> imageDataPixels = m_context->paintRenderingResultsToImageData(m_drawingBuffer.get(), width, height);
+    if (!imageDataPixels)
+        return 0;
 
     if (m_framebufferBinding)
         m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
     else
         m_drawingBuffer->bind();
 
-    return imageData;
+    return ImageData::create(IntSize(width, height), imageDataPixels);
 }
 
 void WebGLRenderingContext::reshape(int width, int height)
@@ -3293,7 +3272,7 @@
     m_context->stencilOpSeparate(face, fail, zfail, zpass);
 }
 
-void WebGLRenderingContext::texImage2DBase(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& es)
+void WebGLRenderingContext::texImage2DBase(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& exceptionState)
 {
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     // FIXME: Handle errors.
@@ -3307,7 +3286,7 @@
     tex->setLevelInfo(target, level, internalformat, width, height, type);
 }
 
-void WebGLRenderingContext::texImage2DImpl(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& es)
+void WebGLRenderingContext::texImage2DImpl(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
 {
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     Vector<uint8_t> data;
@@ -3332,7 +3311,7 @@
 
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
-    texImage2DBase(target, level, internalformat, image->width(), image->height(), 0, format, type, needConversion ? data.data() : imagePixelData, es);
+    texImage2DBase(target, level, internalformat, image->width(), image->height(), 0, format, type, needConversion ? data.data() : imagePixelData, exceptionState);
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
 }
@@ -3398,7 +3377,7 @@
 
 void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
     GC3Dsizei width, GC3Dsizei height, GC3Dint border,
-    GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& es)
+    GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateTexFuncData("texImage2D", level, width, height, format, type, pixels, NullAllowed)
         || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceArrayBufferView, target, level, internalformat, width, height, border, format, type, 0, 0))
@@ -3418,13 +3397,13 @@
     }
     if (changeUnpackAlignment)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
-    texImage2DBase(target, level, internalformat, width, height, border, format, type, data, es);
+    texImage2DBase(target, level, internalformat, width, height, border, format, type, data, exceptionState);
     if (changeUnpackAlignment)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
 void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& es)
+    GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !pixels || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceImageData, target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, 0, 0))
         return;
@@ -3435,22 +3414,22 @@
     if (!m_unpackFlipY && !m_unpackPremultiplyAlpha && format == GraphicsContext3D::RGBA && type == GraphicsContext3D::UNSIGNED_BYTE)
         needConversion = false;
     else {
-        if (!m_context->extractImageData(pixels, format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
+        if (!m_context->extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
             synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "bad image data");
             return;
         }
     }
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
-    texImage2DBase(target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, needConversion ? data.data() : pixels->data()->data(), es);
+    texImage2DBase(target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, needConversion ? data.data() : pixels->data()->data(), exceptionState);
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
 void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& es)
+    GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& exceptionState)
 {
-    if (isContextLost() || !validateHTMLImageElement("texImage2D", image, es))
+    if (isContextLost() || !validateHTMLImageElement("texImage2D", image, exceptionState))
         return;
 
     RefPtr<Image> imageForRender = image->cachedImage()->imageForRenderer(image->renderer());
@@ -3460,13 +3439,13 @@
     if (!imageForRender || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLImageElement, target, level, internalformat, imageForRender->width(), imageForRender->height(), 0, format, type, 0, 0))
         return;
 
-    texImage2DImpl(target, level, internalformat, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+    texImage2DImpl(target, level, internalformat, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
 void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& es)
+    GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
 {
-    if (isContextLost() || !validateHTMLCanvasElement("texImage2D", canvas, es) || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLCanvasElement, target, level, internalformat, canvas->width(), canvas->height(), 0, format, type, 0, 0))
+    if (isContextLost() || !validateHTMLCanvasElement("texImage2D", canvas, exceptionState) || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLCanvasElement, target, level, internalformat, canvas->width(), canvas->height(), 0, format, type, 0, 0))
         return;
 
     WebGLTexture* texture = validateTextureBinding("texImage2D", target, true);
@@ -3492,9 +3471,9 @@
 
     RefPtr<ImageData> imageData = canvas->getImageData();
     if (imageData)
-        texImage2D(target, level, internalformat, format, type, imageData.get(), es);
+        texImage2D(target, level, internalformat, format, type, imageData.get(), exceptionState);
     else
-        texImage2DImpl(target, level, internalformat, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+        texImage2DImpl(target, level, internalformat, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
 PassRefPtr<Image> WebGLRenderingContext::videoFrameToImage(HTMLVideoElement* video, BackingStoreCopy backingStoreCopy)
@@ -3512,9 +3491,9 @@
 }
 
 void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& es)
+    GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& exceptionState)
 {
-    if (isContextLost() || !validateHTMLVideoElement("texImage2D", video, es)
+    if (isContextLost() || !validateHTMLVideoElement("texImage2D", video, exceptionState)
         || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, 0, 0))
         return;
 
@@ -3532,7 +3511,7 @@
     RefPtr<Image> image = videoFrameToImage(video, ImageBuffer::fastCopyImageMode());
     if (!image)
         return;
-    texImage2DImpl(target, level, internalformat, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+    texImage2DImpl(target, level, internalformat, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
 void WebGLRenderingContext::texParameter(GC3Denum target, GC3Denum pname, GC3Dfloat paramf, GC3Dint parami, bool isFloat)
@@ -3583,7 +3562,7 @@
     texParameter(target, pname, 0, param, false);
 }
 
-void WebGLRenderingContext::texSubImage2DBase(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& es)
+void WebGLRenderingContext::texSubImage2DBase(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& exceptionState)
 {
     // FIXME: Handle errors.
     ASSERT(!isContextLost());
@@ -3604,7 +3583,7 @@
     m_context->texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
 }
 
-void WebGLRenderingContext::texSubImage2DImpl(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& es)
+void WebGLRenderingContext::texSubImage2DImpl(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
 {
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     Vector<uint8_t> data;
@@ -3629,14 +3608,14 @@
 
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
-    texSubImage2DBase(target, level, xoffset, yoffset, image->width(), image->height(), format, type,  needConversion ? data.data() : imagePixelData, es);
+    texSubImage2DBase(target, level, xoffset, yoffset, image->width(), image->height(), format, type,  needConversion ? data.data() : imagePixelData, exceptionState);
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
 void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
     GC3Dsizei width, GC3Dsizei height,
-    GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& es)
+    GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateTexFuncData("texSubImage2D", level, width, height, format, type, pixels, NullNotAllowed)
         || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceArrayBufferView, target, level, format, width, height, 0, format, type, xoffset, yoffset))
@@ -3656,13 +3635,13 @@
     }
     if (changeUnpackAlignment)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
-    texSubImage2DBase(target, level, xoffset, yoffset, width, height, format, type, data, es);
+    texSubImage2DBase(target, level, xoffset, yoffset, width, height, format, type, data, exceptionState);
     if (changeUnpackAlignment)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
 void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& es)
+    GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !pixels || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceImageData, target, level, format,  pixels->width(), pixels->height(), 0, format, type, xoffset, yoffset))
         return;
@@ -3674,22 +3653,22 @@
     if (format == GraphicsContext3D::RGBA && type == GraphicsContext3D::UNSIGNED_BYTE && !m_unpackFlipY && !m_unpackPremultiplyAlpha)
         needConversion = false;
     else {
-        if (!m_context->extractImageData(pixels, format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
+        if (!m_context->extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
             synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texSubImage2D", "bad image data");
             return;
         }
     }
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
-    texSubImage2DBase(target, level, xoffset, yoffset, pixels->width(), pixels->height(), format, type, needConversion ? data.data() : pixels->data()->data(), es);
+    texSubImage2DBase(target, level, xoffset, yoffset, pixels->width(), pixels->height(), format, type, needConversion ? data.data() : pixels->data()->data(), exceptionState);
     if (m_unpackAlignment != 1)
         m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
 void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& es)
+    GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& exceptionState)
 {
-    if (isContextLost() || !validateHTMLImageElement("texSubImage2D", image, es))
+    if (isContextLost() || !validateHTMLImageElement("texSubImage2D", image, exceptionState))
         return;
 
     RefPtr<Image> imageForRender = image->cachedImage()->imageForRenderer(image->renderer());
@@ -3699,34 +3678,34 @@
     if (!imageForRender || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLImageElement, target, level, format, imageForRender->width(), imageForRender->height(), 0, format, type, xoffset, yoffset))
         return;
 
-    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
 void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& es)
+    GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
 {
-    if (isContextLost() || !validateHTMLCanvasElement("texSubImage2D", canvas, es)
+    if (isContextLost() || !validateHTMLCanvasElement("texSubImage2D", canvas, exceptionState)
         || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLCanvasElement, target, level, format, canvas->width(), canvas->height(), 0, format, type, xoffset, yoffset))
         return;
 
     RefPtr<ImageData> imageData = canvas->getImageData();
     if (imageData)
-        texSubImage2D(target, level, xoffset, yoffset, format, type, imageData.get(), es);
+        texSubImage2D(target, level, xoffset, yoffset, format, type, imageData.get(), exceptionState);
     else
-        texSubImage2DImpl(target, level, xoffset, yoffset, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+        texSubImage2DImpl(target, level, xoffset, yoffset, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
 void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& es)
+    GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& exceptionState)
 {
-    if (isContextLost() || !validateHTMLVideoElement("texSubImage2D", video, es)
+    if (isContextLost() || !validateHTMLVideoElement("texSubImage2D", video, exceptionState)
         || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLVideoElement, target, level, format, video->videoWidth(), video->videoHeight(), 0, format, type, xoffset, yoffset))
         return;
 
     RefPtr<Image> image = videoFrameToImage(video, ImageBuffer::fastCopyImageMode());
     if (!image)
         return;
-    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
 void WebGLRenderingContext::uniform1f(const WebGLUniformLocation* location, GC3Dfloat x)
@@ -4228,7 +4207,7 @@
         m_restoreTimer.startOneShot(0);
 }
 
-WebKit::WebLayer* WebGLRenderingContext::platformLayer() const
+blink::WebLayer* WebGLRenderingContext::platformLayer() const
 {
     return m_drawingBuffer->platformLayer();
 }
@@ -5158,7 +5137,7 @@
     return 0;
 }
 
-bool WebGLRenderingContext::validateHTMLImageElement(const char* functionName, HTMLImageElement* image, ExceptionState& es)
+bool WebGLRenderingContext::validateHTMLImageElement(const char* functionName, HTMLImageElement* image, ExceptionState& exceptionState)
 {
     if (!image || !image->cachedImage()) {
         synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no image");
@@ -5170,33 +5149,33 @@
         return false;
     }
     if (wouldTaintOrigin(image)) {
-        es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the cross-origin image at " + url.elidedString() + " may not be loaded."));
+        exceptionState.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the cross-origin image at " + url.elidedString() + " may not be loaded."));
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateHTMLCanvasElement(const char* functionName, HTMLCanvasElement* canvas, ExceptionState& es)
+bool WebGLRenderingContext::validateHTMLCanvasElement(const char* functionName, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
 {
     if (!canvas || !canvas->buffer()) {
         synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no canvas");
         return false;
     }
     if (wouldTaintOrigin(canvas)) {
-        es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "tainted canvases may not be loded."));
+        exceptionState.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "tainted canvases may not be loaded."));
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateHTMLVideoElement(const char* functionName, HTMLVideoElement* video, ExceptionState& es)
+bool WebGLRenderingContext::validateHTMLVideoElement(const char* functionName, HTMLVideoElement* video, ExceptionState& exceptionState)
 {
     if (!video || !video->videoWidth() || !video->videoHeight()) {
         synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no video");
         return false;
     }
     if (wouldTaintOrigin(video)) {
-        es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the video element contains cross-origin data, and may not be loaded."));
+        exceptionState.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the video element contains cross-origin data, and may not be loaded."));
         return false;
     }
     return true;
diff --git a/Source/core/html/canvas/WebGLRenderingContext.h b/Source/core/html/canvas/WebGLRenderingContext.h
index c55146f..233270b 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.h
+++ b/Source/core/html/canvas/WebGLRenderingContext.h
@@ -39,7 +39,7 @@
 #include "wtf/OwnPtr.h"
 #include "wtf/text/WTFString.h"
 
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
 
 namespace WebCore {
 
@@ -315,7 +315,7 @@
 
     GraphicsContext3D* graphicsContext3D() const { return m_context.get(); }
     WebGLContextGroup* contextGroup() const { return m_contextGroup.get(); }
-    virtual WebKit::WebLayer* platformLayer() const;
+    virtual blink::WebLayer* platformLayer() const;
 
     void reshape(int width, int height);
 
diff --git a/Source/core/html/forms/BaseCheckableInputType.cpp b/Source/core/html/forms/BaseCheckableInputType.cpp
index 7c2d8d9..0b1e739 100644
--- a/Source/core/html/forms/BaseCheckableInputType.cpp
+++ b/Source/core/html/forms/BaseCheckableInputType.cpp
@@ -64,7 +64,7 @@
 {
     const String& key = event->keyIdentifier();
     if (key == "U+0020") {
-        element().setActive(true, true);
+        element().setActive(true);
         // No setDefaultHandled(), because IE dispatches a keypress in this case
         // and the caller will only dispatch a keypress if we don't call setDefaultHandled().
     }
diff --git a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
index 21d39a3..5ed613d 100644
--- a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/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->setPart(valueContainerPseudo);
+    valueContainer->setPseudo(valueContainerPseudo);
     element().userAgentShadowRoot()->appendChild(valueContainer.get());
     updateAppearance();
 }
@@ -87,7 +87,7 @@
         updateAppearance();
 }
 
-void BaseChooserOnlyDateAndTimeInputType::detach()
+void BaseChooserOnlyDateAndTimeInputType::closePopupView()
 {
     closeDateTimeChooser();
 }
@@ -97,6 +97,15 @@
     element().setValue(value, DispatchInputAndChangeEvent);
 }
 
+void BaseChooserOnlyDateAndTimeInputType::didChooseValue(double value)
+{
+    ASSERT(std::isfinite(value) || std::isnan(value));
+    if (std::isnan(value))
+        element().setValue(emptyString(), DispatchInputAndChangeEvent);
+    else
+        element().setValueAsNumber(value, ASSERT_NO_EXCEPTION, DispatchInputAndChangeEvent);
+}
+
 void BaseChooserOnlyDateAndTimeInputType::didEndChooser()
 {
     m_dateTimeChooser.clear();
diff --git a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
index 69f3b85..4ba1f87 100644
--- a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
+++ b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
@@ -45,7 +45,7 @@
 
     // InputType functions:
     virtual void createShadowSubtree() OVERRIDE;
-    virtual void detach() OVERRIDE;
+    virtual void closePopupView() OVERRIDE;
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
     virtual void handleDOMActivateEvent(Event*) OVERRIDE;
     virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
@@ -55,6 +55,7 @@
 
     // DateTimeChooserClient functions:
     virtual void didChooseValue(const String&) OVERRIDE;
+    virtual void didChooseValue(double) OVERRIDE;
     virtual void didEndChooser() OVERRIDE;
 
     RefPtr<DateTimeChooser> m_dateTimeChooser;
diff --git a/Source/core/html/forms/BaseClickableWithKeyInputType.cpp b/Source/core/html/forms/BaseClickableWithKeyInputType.cpp
index 21823ba..98ab9b1 100644
--- a/Source/core/html/forms/BaseClickableWithKeyInputType.cpp
+++ b/Source/core/html/forms/BaseClickableWithKeyInputType.cpp
@@ -43,7 +43,7 @@
 {
     const String& key = event->keyIdentifier();
     if (key == "U+0020") {
-        element.setActive(true, true);
+        element.setActive(true);
         // No setDefaultHandled(), because IE dispatches a keypress in this case
         // and the caller will only dispatch a keypress if we don't call setDefaultHandled().
     }
diff --git a/Source/core/html/forms/BaseDateAndTimeInputType.cpp b/Source/core/html/forms/BaseDateAndTimeInputType.cpp
index 05f27a3..bf87e94 100644
--- a/Source/core/html/forms/BaseDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/BaseDateAndTimeInputType.cpp
@@ -41,7 +41,7 @@
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace HTMLNames;
 using namespace std;
 
diff --git a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
index e595534..8dce884 100644
--- a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -262,6 +262,15 @@
         edit->setOnlyYearMonthDay(date);
 }
 
+void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(double value)
+{
+    ASSERT(std::isfinite(value) || std::isnan(value));
+    if (std::isnan(value))
+        element().setValue(emptyString(), DispatchInputAndChangeEvent);
+    else
+        element().setValueAsNumber(value, ASSERT_NO_EXCEPTION, DispatchInputAndChangeEvent);
+}
+
 bool BaseMultipleFieldsDateAndTimeInputType::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
 {
     return element().setupDateTimeChooserParameters(parameters);
@@ -289,7 +298,7 @@
 
 String BaseMultipleFieldsDateAndTimeInputType::badInputText() const
 {
-    return locale().queryString(WebKit::WebLocalizedString::ValidationBadInputForDateTime);
+    return locale().queryString(blink::WebLocalizedString::ValidationBadInputForDateTime);
 }
 
 void BaseMultipleFieldsDateAndTimeInputType::blur()
@@ -331,7 +340,7 @@
     ContainerNode* container = element().userAgentShadowRoot();
 
     container->appendChild(DateTimeEditElement::create(document, *this));
-    updateInnerTextValue();
+    updateView();
     container->appendChild(ClearButtonElement::create(document, *this));
     container->appendChild(SpinButtonElement::create(document, *this));
 
@@ -437,7 +446,7 @@
 
 void BaseMultipleFieldsDateAndTimeInputType::minOrMaxAttributeChanged()
 {
-    updateInnerTextValue();
+    updateView();
 }
 
 void BaseMultipleFieldsDateAndTimeInputType::readonlyAttributeChanged()
@@ -471,7 +480,7 @@
     InputType::setValue(sanitizedValue, valueChanged, eventBehavior);
     DateTimeEditElement* edit = dateTimeEditElement();
     if (valueChanged || (sanitizedValue.isEmpty() && edit && edit->anyEditableFieldsHaveValues())) {
-        updateInnerTextValue();
+        updateView();
         element().setNeedsValidityCheck();
     }
 }
@@ -483,10 +492,10 @@
 
 void BaseMultipleFieldsDateAndTimeInputType::stepAttributeChanged()
 {
-    updateInnerTextValue();
+    updateView();
 }
 
-void BaseMultipleFieldsDateAndTimeInputType::updateInnerTextValue()
+void BaseMultipleFieldsDateAndTimeInputType::updateView()
 {
     DateTimeEditElement* edit = dateTimeEditElement();
     if (!edit)
@@ -518,7 +527,7 @@
 void BaseMultipleFieldsDateAndTimeInputType::valueAttributeChanged()
 {
     if (!element().hasDirtyValue())
-        updateInnerTextValue();
+        updateView();
 }
 
 void BaseMultipleFieldsDateAndTimeInputType::listAttributeTargetChanged()
diff --git a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
index 86631dd..14a0a2c 100644
--- a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
+++ b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
@@ -78,6 +78,7 @@
     // PickerIndicatorElement::PickerIndicatorOwner functions
     virtual bool isPickerIndicatorOwnerDisabledOrReadOnly() const OVERRIDE FINAL;
     virtual void pickerIndicatorChooseValue(const String&) OVERRIDE FINAL;
+    virtual void pickerIndicatorChooseValue(double) OVERRIDE FINAL;
     virtual bool setupDateTimeChooserParameters(DateTimeChooserParameters&) OVERRIDE FINAL;
 
     // ClearButtonElement::ClearButtonOwner functions.
@@ -105,7 +106,7 @@
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE FINAL;
     virtual bool shouldUseInputMethod() const OVERRIDE FINAL;
     virtual void stepAttributeChanged() OVERRIDE FINAL;
-    virtual void updateInnerTextValue() OVERRIDE FINAL;
+    virtual void updateView() OVERRIDE FINAL;
     virtual void valueAttributeChanged() OVERRIDE;
     virtual void listAttributeTargetChanged() OVERRIDE FINAL;
     virtual void updateClearButtonVisibility() OVERRIDE FINAL;
diff --git a/Source/core/html/forms/ButtonInputType.cpp b/Source/core/html/forms/ButtonInputType.cpp
index b56ac9a..39e112c 100644
--- a/Source/core/html/forms/ButtonInputType.cpp
+++ b/Source/core/html/forms/ButtonInputType.cpp
@@ -31,7 +31,7 @@
 #include "config.h"
 #include "core/html/forms/ButtonInputType.h"
 
-#include "core/html/forms/InputTypeNames.h"
+#include "InputTypeNames.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
@@ -43,7 +43,7 @@
 
 const AtomicString& ButtonInputType::formControlType() const
 {
-    return InputTypeNames::button();
+    return InputTypeNames::button;
 }
 
 bool ButtonInputType::supportsValidation() const
diff --git a/Source/core/html/forms/CheckboxInputType.cpp b/Source/core/html/forms/CheckboxInputType.cpp
index 19df75f..738f9d5 100644
--- a/Source/core/html/forms/CheckboxInputType.cpp
+++ b/Source/core/html/forms/CheckboxInputType.cpp
@@ -32,9 +32,9 @@
 #include "config.h"
 #include "core/html/forms/CheckboxInputType.h"
 
+#include "InputTypeNames.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -47,7 +47,7 @@
 
 const AtomicString& CheckboxInputType::formControlType() const
 {
-    return InputTypeNames::checkbox();
+    return InputTypeNames::checkbox;
 }
 
 bool CheckboxInputType::valueMissing(const String&) const
@@ -57,7 +57,7 @@
 
 String CheckboxInputType::valueMissingText() const
 {
-    return locale().queryString(WebKit::WebLocalizedString::ValidationValueMissingForCheckbox);
+    return locale().queryString(blink::WebLocalizedString::ValidationValueMissingForCheckbox);
 }
 
 void CheckboxInputType::handleKeyupEvent(KeyboardEvent* event)
diff --git a/Source/core/html/forms/ColorInputType.cpp b/Source/core/html/forms/ColorInputType.cpp
index 5485568..304504b 100644
--- a/Source/core/html/forms/ColorInputType.cpp
+++ b/Source/core/html/forms/ColorInputType.cpp
@@ -32,6 +32,7 @@
 #include "core/html/forms/ColorInputType.h"
 
 #include "CSSPropertyNames.h"
+#include "InputTypeNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "bindings/v8/ScriptController.h"
@@ -41,7 +42,6 @@
 #include "core/html/HTMLDivElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLOptionElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/page/Chrome.h"
 #include "core/rendering/RenderView.h"
 #include "platform/UserGestureIndicator.h"
@@ -53,6 +53,11 @@
 
 using namespace HTMLNames;
 
+// Upper limit of number of datalist suggestions shown.
+static const unsigned maxSuggestions = 1000;
+// Upper limit for the length of the labels for datalist suggestions.
+static const unsigned maxSuggestionLabelLength = 1000;
+
 static bool isValidColorString(const String& value)
 {
     if (value.isEmpty())
@@ -89,7 +94,7 @@
 
 const AtomicString& ColorInputType::formControlType() const
 {
-    return InputTypeNames::color();
+    return InputTypeNames::color;
 }
 
 bool ColorInputType::supportsRequired() const
@@ -121,9 +126,9 @@
 
     Document& document = element().document();
     RefPtr<HTMLDivElement> wrapperElement = HTMLDivElement::create(document);
-    wrapperElement->setPart(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
+    wrapperElement->setPseudo(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
     RefPtr<HTMLDivElement> colorSwatch = HTMLDivElement::create(document);
-    colorSwatch->setPart(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
+    colorSwatch->setPseudo(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
     wrapperElement->appendChild(colorSwatch.release());
     element().userAgentShadowRoot()->appendChild(wrapperElement.release());
 
@@ -157,7 +162,7 @@
     event->setDefaultHandled();
 }
 
-void ColorInputType::detach()
+void ColorInputType::closePopupView()
 {
     endColorChooser();
 }
@@ -225,9 +230,9 @@
     return false;
 }
 
-Vector<Color> ColorInputType::suggestions() const
+Vector<ColorSuggestion> ColorInputType::suggestions() const
 {
-    Vector<Color> suggestions;
+    Vector<ColorSuggestion> suggestions;
     if (RuntimeEnabledFeatures::dataListElementEnabled()) {
         HTMLDataListElement* dataList = element().dataList();
         if (dataList) {
@@ -238,7 +243,10 @@
                 Color color(option->value());
                 if (!color.isValid())
                     continue;
-                suggestions.append(color);
+                ColorSuggestion suggestion(color, option->label().left(maxSuggestionLabelLength));
+                suggestions.append(suggestion);
+                if (suggestions.size() >= maxSuggestions)
+                    break;
             }
         }
     }
diff --git a/Source/core/html/forms/ColorInputType.h b/Source/core/html/forms/ColorInputType.h
index 2d1d3f3..b0f7ba3 100644
--- a/Source/core/html/forms/ColorInputType.h
+++ b/Source/core/html/forms/ColorInputType.h
@@ -47,7 +47,7 @@
     virtual IntRect elementRectRelativeToRootView() const OVERRIDE;
     virtual Color currentColor() OVERRIDE;
     virtual bool shouldShowSuggestions() const OVERRIDE;
-    virtual Vector<Color> suggestions() const OVERRIDE;
+    virtual Vector<ColorSuggestion> suggestions() const OVERRIDE;
 
 private:
     ColorInputType(HTMLInputElement& element) : BaseClickableWithKeyInputType(element) { }
@@ -60,7 +60,7 @@
     virtual void createShadowSubtree() OVERRIDE;
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
     virtual void handleDOMActivateEvent(Event*) OVERRIDE;
-    virtual void detach() OVERRIDE;
+    virtual void closePopupView() OVERRIDE;
     virtual bool shouldRespectListAttribute() OVERRIDE;
     virtual bool typeMismatchFor(const String&) const OVERRIDE;
 
diff --git a/Source/core/html/forms/DateInputType.cpp b/Source/core/html/forms/DateInputType.cpp
index b37f0d8..668ddde 100644
--- a/Source/core/html/forms/DateInputType.cpp
+++ b/Source/core/html/forms/DateInputType.cpp
@@ -32,16 +32,16 @@
 #include "core/html/forms/DateInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/DateComponents.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace HTMLNames;
 
 static const int dateDefaultStep = 1;
@@ -65,7 +65,7 @@
 
 const AtomicString& DateInputType::formControlType() const
 {
-    return InputTypeNames::date();
+    return InputTypeNames::date;
 }
 
 DateComponents::Type DateInputType::dateType() const
diff --git a/Source/core/html/forms/DateTimeLocalInputType.cpp b/Source/core/html/forms/DateTimeLocalInputType.cpp
index 1f3317d..ff8b667 100644
--- a/Source/core/html/forms/DateTimeLocalInputType.cpp
+++ b/Source/core/html/forms/DateTimeLocalInputType.cpp
@@ -32,10 +32,10 @@
 #include "core/html/forms/DateTimeLocalInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/DateComponents.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
@@ -43,7 +43,7 @@
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace HTMLNames;
 
 static const int dateTimeLocalDefaultStep = 60;
@@ -62,7 +62,7 @@
 
 const AtomicString& DateTimeLocalInputType::formControlType() const
 {
-    return InputTypeNames::datetimelocal();
+    return InputTypeNames::datetime_local;
 }
 
 DateComponents::Type DateTimeLocalInputType::dateType() const
@@ -76,10 +76,10 @@
     return DateComponents::invalidMilliseconds();
 }
 
-void DateTimeLocalInputType::setValueAsDate(double value, ExceptionState& es) const
+void DateTimeLocalInputType::setValueAsDate(double value, ExceptionState& exceptionState) const
 {
     // valueAsDate doesn't work for the datetime-local type according to the standard.
-    InputType::setValueAsDate(value, es);
+    InputType::setValueAsDate(value, exceptionState);
 }
 
 StepRange DateTimeLocalInputType::createStepRange(AnyStepHandling anyStepHandling) const
diff --git a/Source/core/html/forms/EmailInputType.cpp b/Source/core/html/forms/EmailInputType.cpp
index 7259900..30c8876 100644
--- a/Source/core/html/forms/EmailInputType.cpp
+++ b/Source/core/html/forms/EmailInputType.cpp
@@ -24,9 +24,8 @@
 #include "config.h"
 #include "core/html/forms/EmailInputType.h"
 
-#include <unicode/uidna.h>
+#include "InputTypeNames.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
@@ -35,10 +34,11 @@
 #include "public/platform/Platform.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/StringBuilder.h"
+#include <unicode/uidna.h>
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 
 // http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
 static const char localPartCharacters[] = "abcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+/=?^_`{|}~.-";
@@ -88,7 +88,7 @@
         return address;
 
     String languages = chrome()->client().acceptLanguages();
-    String unicodeHost = WebKit::Platform::current()->convertIDNToUnicode(address.substring(atPosition + 1), languages);
+    String unicodeHost = blink::Platform::current()->convertIDNToUnicode(address.substring(atPosition + 1), languages);
     StringBuilder builder;
     builder.append(address, 0, atPosition + 1);
     builder.append(unicodeHost);
@@ -153,7 +153,7 @@
 
 const AtomicString& EmailInputType::formControlType() const
 {
-    return InputTypeNames::email();
+    return InputTypeNames::email;
 }
 
 // The return value is an invalid email address string if the specified string
diff --git a/Source/core/html/forms/FileInputType.cpp b/Source/core/html/forms/FileInputType.cpp
index 2a2be02..64338a6 100644
--- a/Source/core/html/forms/FileInputType.cpp
+++ b/Source/core/html/forms/FileInputType.cpp
@@ -23,6 +23,7 @@
 #include "core/html/forms/FileInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -32,9 +33,8 @@
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/FormController.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/page/Chrome.h"
-#include "core/platform/DragData.h"
+#include "core/page/DragData.h"
 #include "core/rendering/RenderFileUploadControl.h"
 #include "platform/FileMetadata.h"
 #include "platform/UserGestureIndicator.h"
@@ -45,7 +45,7 @@
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace HTMLNames;
 
 inline FileInputType::FileInputType(HTMLInputElement& element)
@@ -73,7 +73,7 @@
 
 const AtomicString& FileInputType::formControlType() const
 {
-    return InputTypeNames::file();
+    return InputTypeNames::file;
 }
 
 FormControlState FileInputType::saveFormControlState() const
@@ -247,10 +247,10 @@
 void FileInputType::createShadowSubtree()
 {
     ASSERT(element().shadow());
-    RefPtr<HTMLInputElement> button = HTMLInputElement::create(inputTag, element().document(), 0, false);
-    button->setType(InputTypeNames::button());
+    RefPtr<HTMLInputElement> button = HTMLInputElement::create(element().document(), 0, false);
+    button->setType(InputTypeNames::button);
     button->setAttribute(valueAttr, locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel));
-    button->setPart(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
+    button->setPseudo(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
     element().userAgentShadowRoot()->appendChild(button.release());
 }
 
diff --git a/Source/core/html/forms/HiddenInputType.cpp b/Source/core/html/forms/HiddenInputType.cpp
index 2a9a0ea..5ce1c5d 100644
--- a/Source/core/html/forms/HiddenInputType.cpp
+++ b/Source/core/html/forms/HiddenInputType.cpp
@@ -33,10 +33,10 @@
 #include "core/html/forms/HiddenInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/FormController.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
@@ -50,7 +50,7 @@
 
 const AtomicString& HiddenInputType::formControlType() const
 {
-    return InputTypeNames::hidden();
+    return InputTypeNames::hidden;
 }
 
 FormControlState HiddenInputType::saveFormControlState() const
diff --git a/Source/core/html/forms/ImageInputType.cpp b/Source/core/html/forms/ImageInputType.cpp
index 7ffeee2..a8a8d51 100644
--- a/Source/core/html/forms/ImageInputType.cpp
+++ b/Source/core/html/forms/ImageInputType.cpp
@@ -24,13 +24,13 @@
 #include "core/html/forms/ImageInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "core/events/MouseEvent.h"
 #include "core/fetch/ImageResource.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/rendering/RenderImage.h"
 #include "wtf/PassOwnPtr.h"
@@ -52,7 +52,7 @@
 
 const AtomicString& ImageInputType::formControlType() const
 {
-    return InputTypeNames::image();
+    return InputTypeNames::image;
 }
 
 bool ImageInputType::isFormDataAppendable() const
@@ -139,9 +139,9 @@
     element().imageLoader()->updateFromElementIgnoringPreviousError();
 }
 
-void ImageInputType::attach()
+void ImageInputType::startResourceLoading()
 {
-    BaseButtonInputType::attach();
+    BaseButtonInputType::startResourceLoading();
 
     HTMLImageLoader* imageLoader = element().imageLoader();
     imageLoader->updateFromElement();
diff --git a/Source/core/html/forms/ImageInputType.h b/Source/core/html/forms/ImageInputType.h
index e1f967d..d033e2a 100644
--- a/Source/core/html/forms/ImageInputType.h
+++ b/Source/core/html/forms/ImageInputType.h
@@ -53,7 +53,7 @@
     virtual void handleDOMActivateEvent(Event*) OVERRIDE;
     virtual void altAttributeChanged() OVERRIDE;
     virtual void srcAttributeChanged() OVERRIDE;
-    virtual void attach() OVERRIDE;
+    virtual void startResourceLoading() OVERRIDE;
     virtual bool shouldRespectAlignAttribute() OVERRIDE;
     virtual bool canBeSuccessfulSubmitButton() OVERRIDE;
     virtual bool isImageButton() const OVERRIDE;
diff --git a/Source/core/html/forms/InputType.cpp b/Source/core/html/forms/InputType.cpp
index ff98bc8..eabbbe9 100644
--- a/Source/core/html/forms/InputType.cpp
+++ b/Source/core/html/forms/InputType.cpp
@@ -28,10 +28,10 @@
 #include "config.h"
 #include "core/html/forms/InputType.h"
 
+#include "InputTypeNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/shadow/ShadowRoot.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/events/ScopedEventQueue.h"
 #include "core/fileapi/FileList.h"
@@ -47,7 +47,6 @@
 #include "core/html/forms/FormController.h"
 #include "core/html/forms/HiddenInputType.h"
 #include "core/html/forms/ImageInputType.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/forms/MonthInputType.h"
 #include "core/html/forms/NumberInputType.h"
 #include "core/html/forms/PasswordInputType.h"
@@ -70,7 +69,7 @@
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace HTMLNames;
 using namespace std;
 
@@ -80,29 +79,29 @@
 static PassOwnPtr<InputTypeFactoryMap> createInputTypeFactoryMap()
 {
     OwnPtr<InputTypeFactoryMap> map = adoptPtr(new InputTypeFactoryMap);
-    map->add(InputTypeNames::button(), ButtonInputType::create);
-    map->add(InputTypeNames::checkbox(), CheckboxInputType::create);
+    map->add(InputTypeNames::button, ButtonInputType::create);
+    map->add(InputTypeNames::checkbox, CheckboxInputType::create);
     if (RuntimeEnabledFeatures::inputTypeColorEnabled())
-        map->add(InputTypeNames::color(), ColorInputType::create);
-    map->add(InputTypeNames::date(), DateInputType::create);
-    map->add(InputTypeNames::datetimelocal(), DateTimeLocalInputType::create);
-    map->add(InputTypeNames::email(), EmailInputType::create);
-    map->add(InputTypeNames::file(), FileInputType::create);
-    map->add(InputTypeNames::hidden(), HiddenInputType::create);
-    map->add(InputTypeNames::image(), ImageInputType::create);
-    map->add(InputTypeNames::month(), MonthInputType::create);
-    map->add(InputTypeNames::number(), NumberInputType::create);
-    map->add(InputTypeNames::password(), PasswordInputType::create);
-    map->add(InputTypeNames::radio(), RadioInputType::create);
-    map->add(InputTypeNames::range(), RangeInputType::create);
-    map->add(InputTypeNames::reset(), ResetInputType::create);
-    map->add(InputTypeNames::search(), SearchInputType::create);
-    map->add(InputTypeNames::submit(), SubmitInputType::create);
-    map->add(InputTypeNames::telephone(), TelephoneInputType::create);
-    map->add(InputTypeNames::time(), TimeInputType::create);
-    map->add(InputTypeNames::url(), URLInputType::create);
+        map->add(InputTypeNames::color, ColorInputType::create);
+    map->add(InputTypeNames::date, DateInputType::create);
+    map->add(InputTypeNames::datetime_local, DateTimeLocalInputType::create);
+    map->add(InputTypeNames::email, EmailInputType::create);
+    map->add(InputTypeNames::file, FileInputType::create);
+    map->add(InputTypeNames::hidden, HiddenInputType::create);
+    map->add(InputTypeNames::image, ImageInputType::create);
+    map->add(InputTypeNames::month, MonthInputType::create);
+    map->add(InputTypeNames::number, NumberInputType::create);
+    map->add(InputTypeNames::password, PasswordInputType::create);
+    map->add(InputTypeNames::radio, RadioInputType::create);
+    map->add(InputTypeNames::range, RangeInputType::create);
+    map->add(InputTypeNames::reset, ResetInputType::create);
+    map->add(InputTypeNames::search, SearchInputType::create);
+    map->add(InputTypeNames::submit, SubmitInputType::create);
+    map->add(InputTypeNames::tel, TelephoneInputType::create);
+    map->add(InputTypeNames::time, TimeInputType::create);
+    map->add(InputTypeNames::url, URLInputType::create);
     if (RuntimeEnabledFeatures::inputTypeWeekEnabled())
-        map->add(InputTypeNames::week(), WeekInputType::create);
+        map->add(InputTypeNames::week, WeekInputType::create);
     // No need to register "text" because it is the default type.
     return map.release();
 }
@@ -129,9 +128,9 @@
 const AtomicString& InputType::normalizeTypeName(const AtomicString& typeName)
 {
     if (typeName.isEmpty())
-        return InputTypeNames::text();
+        return InputTypeNames::text;
     InputTypeFactoryMap::const_iterator it = factoryMap()->find(typeName);
-    return it == factoryMap()->end() ? InputTypeNames::text() : it->key;
+    return it == factoryMap()->end() ? InputTypeNames::text : it->key;
 }
 
 bool InputType::canChangeFromAnotherType(const AtomicString& normalizedTypeName)
@@ -141,7 +140,7 @@
     // field's value to something like /etc/passwd and then change it to a file
     // input. I don't think this would actually occur in Blink, but this rule
     // still may be important for compatibility.
-    return normalizedTypeName != InputTypeNames::file();
+    return normalizedTypeName != InputTypeNames::file;
 }
 
 InputType::~InputType()
@@ -209,9 +208,9 @@
     return DateComponents::invalidMilliseconds();
 }
 
-void InputType::setValueAsDate(double, ExceptionState& es) const
+void InputType::setValueAsDate(double, ExceptionState& exceptionState) const
 {
-    es.throwUninformativeAndGenericDOMException(InvalidStateError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
 }
 
 double InputType::valueAsDouble() const
@@ -219,14 +218,14 @@
     return numeric_limits<double>::quiet_NaN();
 }
 
-void InputType::setValueAsDouble(double doubleValue, TextFieldEventBehavior eventBehavior, ExceptionState& es) const
+void InputType::setValueAsDouble(double doubleValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
 {
-    setValueAsDecimal(Decimal::fromDouble(doubleValue), eventBehavior, es);
+    setValueAsDecimal(Decimal::fromDouble(doubleValue), eventBehavior, exceptionState);
 }
 
-void InputType::setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState& es) const
+void InputType::setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState& exceptionState) const
 {
-    es.throwUninformativeAndGenericDOMException(InvalidStateError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
 }
 
 bool InputType::supportsValidation() const
@@ -427,16 +426,6 @@
     return event->isKeyboardEvent() && event->type() == EventTypeNames::keypress && toKeyboardEvent(event)->charCode() == '\r';
 }
 
-void InputType::createShadowSubtree()
-{
-}
-
-void InputType::destroyShadowSubtree()
-{
-    if (ShadowRoot* root = element().userAgentShadowRoot())
-        root->removeChildren();
-}
-
 Decimal InputType::parseToNumber(const String&, const Decimal& defaultValue) const
 {
     ASSERT_NOT_REACHED();
@@ -517,10 +506,6 @@
     element().focus(false);
 }
 
-void InputType::detach()
-{
-}
-
 void InputType::countUsage()
 {
 }
@@ -823,28 +808,28 @@
     return 0;
 }
 
-void InputType::applyStep(int count, AnyStepHandling anyStepHandling, TextFieldEventBehavior eventBehavior, ExceptionState& es)
+void InputType::applyStep(int count, AnyStepHandling anyStepHandling, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState)
 {
     StepRange stepRange(createStepRange(anyStepHandling));
     if (!stepRange.hasStep()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
     const Decimal current = parseToNumberOrNaN(element().value());
     if (!current.isFinite()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
     Decimal newValue = current + stepRange.step() * count;
     if (!newValue.isFinite()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
 
     const Decimal acceptableErrorValue = stepRange.acceptableError();
     if (newValue - stepRange.minimum() < -acceptableErrorValue) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
     if (newValue < stepRange.minimum())
@@ -855,13 +840,13 @@
         newValue = stepRange.alignValueForStep(current, newValue);
 
     if (newValue - stepRange.maximum() > acceptableErrorValue) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
     if (newValue > stepRange.maximum())
         newValue = stepRange.maximum();
 
-    setValueAsDecimal(newValue, eventBehavior, es);
+    setValueAsDecimal(newValue, eventBehavior, exceptionState);
 
     if (AXObjectCache* cache = element().document().existingAXObjectCache())
         cache->postNotification(&element(), AXObjectCache::AXValueChanged, true);
@@ -880,13 +865,13 @@
     return StepRange();
 }
 
-void InputType::stepUp(int n, ExceptionState& es)
+void InputType::stepUp(int n, ExceptionState& exceptionState)
 {
     if (!isSteppable()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         return;
     }
-    applyStep(n, RejectAny, DispatchNoEvent, es);
+    applyStep(n, RejectAny, DispatchNoEvent, exceptionState);
 }
 
 void InputType::stepUpFromRenderer(int n)
diff --git a/Source/core/html/forms/InputType.h b/Source/core/html/forms/InputType.h
index d0a6a4c..94ddda8 100644
--- a/Source/core/html/forms/InputType.h
+++ b/Source/core/html/forms/InputType.h
@@ -36,7 +36,7 @@
 #include "core/html/HTMLTextFormControlElement.h"
 #include "core/html/forms/InputTypeView.h"
 #include "core/html/forms/StepRange.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 
 namespace WebCore {
 
@@ -165,15 +165,9 @@
     virtual void accessKeyAction(bool sendMouseEvents);
     virtual bool canBeSuccessfulSubmitButton();
 
-    // Shadow tree handling
-
-    virtual void createShadowSubtree();
-    virtual void destroyShadowSubtree();
-
     // Miscellaneous functions
 
     virtual bool rendererIsNeeded();
-    virtual void detach();
     virtual void countUsage();
     virtual void sanitizeValueInResponseToMinOrMaxAttributeChange();
     virtual bool shouldRespectAlignAttribute();
diff --git a/Source/core/html/forms/InputTypeNames.cpp b/Source/core/html/forms/InputTypeNames.cpp
deleted file mode 100644
index e4fa55a..0000000
--- a/Source/core/html/forms/InputTypeNames.cpp
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2010, 2012 Google 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.
- *
- */
-
-#include "config.h"
-#include "core/html/forms/InputTypeNames.h"
-
-namespace WebCore {
-
-namespace InputTypeNames {
-
-// The type names must be lowercased because they will be the return values of
-// input.type and input.type must be lowercase according to DOM Level 2.
-
-const AtomicString& button()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("button", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& checkbox()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("checkbox", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& color()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("color", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& date()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("date", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& datetime()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& datetimelocal()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime-local", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& email()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("email", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& file()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("file", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& hidden()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("hidden", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& image()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("image", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& month()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("month", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& number()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("number", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& password()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("password", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& radio()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("radio", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& range()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("range", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& reset()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("reset", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& search()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("search", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& submit()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("submit", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& telephone()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("tel", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& text()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("text", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& time()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("time", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& url()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("url", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-const AtomicString& week()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, name, ("week", AtomicString::ConstructFromLiteral));
-    return name;
-}
-
-} // namespace WebCore::InputTypeNames
-
-} // namespace WebCore
diff --git a/Source/core/html/forms/InputTypeNames.h b/Source/core/html/forms/InputTypeNames.h
deleted file mode 100644
index bb84f3e..0000000
--- a/Source/core/html/forms/InputTypeNames.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2010, 2012 Google 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.
- *
- */
-
-
-#ifndef InputTypeNames_h
-#define InputTypeNames_h
-
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-namespace InputTypeNames {
-
-const AtomicString& button();
-const AtomicString& checkbox();
-const AtomicString& color();
-const AtomicString& date();
-const AtomicString& datetime();
-const AtomicString& datetimelocal();
-const AtomicString& email();
-const AtomicString& file();
-const AtomicString& hidden();
-const AtomicString& image();
-const AtomicString& month();
-const AtomicString& number();
-const AtomicString& password();
-const AtomicString& radio();
-const AtomicString& range();
-const AtomicString& reset();
-const AtomicString& search();
-const AtomicString& submit();
-const AtomicString& telephone();
-const AtomicString& text();
-const AtomicString& time();
-const AtomicString& url();
-const AtomicString& week();
-
-}
-
-} // namespace WebCore
-
-#endif // InputTypeNames_h
diff --git a/Source/core/html/forms/InputTypeNames.in b/Source/core/html/forms/InputTypeNames.in
new file mode 100644
index 0000000..57abbfe
--- /dev/null
+++ b/Source/core/html/forms/InputTypeNames.in
@@ -0,0 +1,25 @@
+namespace="InputType"
+
+button
+checkbox
+color
+date
+datetime
+datetime-local
+email
+file
+hidden
+image
+month
+number
+password
+radio
+range
+reset
+search
+submit
+tel
+text
+time
+url
+week
diff --git a/Source/core/html/forms/InputTypeView.cpp b/Source/core/html/forms/InputTypeView.cpp
index accadf5..d8c4939 100644
--- a/Source/core/html/forms/InputTypeView.cpp
+++ b/Source/core/html/forms/InputTypeView.cpp
@@ -28,6 +28,7 @@
 #include "config.h"
 #include "core/html/forms/InputTypeView.h"
 
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/rendering/RenderObject.h"
@@ -119,10 +120,24 @@
 {
 }
 
-void InputTypeView::attach()
+void InputTypeView::startResourceLoading()
 {
 }
 
+void InputTypeView::closePopupView()
+{
+}
+
+void InputTypeView::createShadowSubtree()
+{
+}
+
+void InputTypeView::destroyShadowSubtree()
+{
+    if (ShadowRoot* root = element().userAgentShadowRoot())
+        root->removeChildren();
+}
+
 void InputTypeView::altAttributeChanged()
 {
 }
@@ -148,7 +163,7 @@
 {
 }
 
-void InputTypeView::updateInnerTextValue()
+void InputTypeView::updateView()
 {
 }
 
diff --git a/Source/core/html/forms/InputTypeView.h b/Source/core/html/forms/InputTypeView.h
index 43528cb..1e4aec4 100644
--- a/Source/core/html/forms/InputTypeView.h
+++ b/Source/core/html/forms/InputTypeView.h
@@ -94,12 +94,15 @@
     virtual void blur();
     virtual RenderObject* createRenderer(RenderStyle*) const;
     virtual PassRefPtr<RenderStyle> customStyleForRenderer(PassRefPtr<RenderStyle>);
-    virtual void attach();
+    virtual void startResourceLoading();
+    virtual void closePopupView();
+    virtual void createShadowSubtree();
+    virtual void destroyShadowSubtree();
     virtual void minOrMaxAttributeChanged();
     virtual void stepAttributeChanged();
     virtual void altAttributeChanged();
     virtual void srcAttributeChanged();
-    virtual void updateInnerTextValue();
+    virtual void updateView();
     virtual void attributeChanged();
     virtual void multipleAttributeChanged();
     virtual void disabledAttributeChanged();
diff --git a/Source/core/html/forms/MonthInputType.cpp b/Source/core/html/forms/MonthInputType.cpp
index 1652dff..3003558 100644
--- a/Source/core/html/forms/MonthInputType.cpp
+++ b/Source/core/html/forms/MonthInputType.cpp
@@ -32,9 +32,9 @@
 #include "core/html/forms/MonthInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/DateComponents.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/CurrentTime.h"
@@ -63,7 +63,7 @@
 
 const AtomicString& MonthInputType::formControlType() const
 {
-    return InputTypeNames::month();
+    return InputTypeNames::month;
 }
 
 DateComponents::Type MonthInputType::dateType() const
diff --git a/Source/core/html/forms/NumberInputType.cpp b/Source/core/html/forms/NumberInputType.cpp
index a91d21a..8559a5d 100644
--- a/Source/core/html/forms/NumberInputType.cpp
+++ b/Source/core/html/forms/NumberInputType.cpp
@@ -32,22 +32,23 @@
 #include "config.h"
 #include "core/html/forms/NumberInputType.h"
 
-#include <limits>
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/rendering/RenderTextControl.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/MathExtras.h"
 #include "wtf/PassOwnPtr.h"
+#include <limits>
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 using namespace HTMLNames;
 using namespace std;
 
@@ -106,13 +107,13 @@
 
 const AtomicString& NumberInputType::formControlType() const
 {
-    return InputTypeNames::number();
+    return InputTypeNames::number;
 }
 
 void NumberInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
 {
     if (!valueChanged && sanitizedValue.isEmpty() && !element().innerTextValue().isEmpty())
-        updateInnerTextValue();
+        updateView();
     TextFieldInputType::setValue(sanitizedValue, valueChanged, eventBehavior);
 }
 
@@ -121,31 +122,23 @@
     return parseToDoubleForNumberType(element().value());
 }
 
-void NumberInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& es) const
+void NumberInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
 {
     // FIXME: We should use numeric_limits<double>::max for number input type.
     const double floatMax = numeric_limits<float>::max();
-    if (newValue < -floatMax) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return;
-    }
-    if (newValue > floatMax) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+    if (newValue < -floatMax || newValue > floatMax) {
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("valueAsNumber", "HTMLInputElement", "The value provided (" + String::number(newValue) + ") is outside the range (" + String::number(-floatMax) + ", " + String::number(floatMax) + ")."));
         return;
     }
     element().setValue(serializeForNumberType(newValue), eventBehavior);
 }
 
-void NumberInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState& es) const
+void NumberInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
 {
     // FIXME: We should use numeric_limits<double>::max for number input type.
     const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
-    if (newValue < -floatMax) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return;
-    }
-    if (newValue > floatMax) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+    if (newValue < -floatMax || newValue > floatMax) {
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("valueAsNumber", "HTMLInputElement", "The value provided (" + newValue.toString() + ") is outside the range (-" + floatMax.toString() + ", " + floatMax.toString() + ")."));
         return;
     }
     element().setValue(serializeForNumberType(newValue), eventBehavior);
diff --git a/Source/core/html/forms/PasswordInputType.cpp b/Source/core/html/forms/PasswordInputType.cpp
index 74557b0..7350aa8 100644
--- a/Source/core/html/forms/PasswordInputType.cpp
+++ b/Source/core/html/forms/PasswordInputType.cpp
@@ -34,10 +34,10 @@
 
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
+#include "InputTypeNames.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/FormController.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/Page.h"
@@ -93,7 +93,7 @@
 
 const AtomicString& PasswordInputType::formControlType() const
 {
-    return InputTypeNames::password();
+    return InputTypeNames::password;
 }
 
 bool PasswordInputType::shouldSaveAndRestoreFormControlState() const
diff --git a/Source/core/html/forms/RadioInputType.cpp b/Source/core/html/forms/RadioInputType.cpp
index f851b6d..fc6da49 100644
--- a/Source/core/html/forms/RadioInputType.cpp
+++ b/Source/core/html/forms/RadioInputType.cpp
@@ -23,11 +23,11 @@
 #include "core/html/forms/RadioInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/events/MouseEvent.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/page/SpatialNavigation.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
@@ -43,7 +43,7 @@
 
 const AtomicString& RadioInputType::formControlType() const
 {
-    return InputTypeNames::radio();
+    return InputTypeNames::radio;
 }
 
 bool RadioInputType::valueMissing(const String&) const
@@ -53,7 +53,7 @@
 
 String RadioInputType::valueMissingText() const
 {
-    return locale().queryString(WebKit::WebLocalizedString::ValidationValueMissingForRadio);
+    return locale().queryString(blink::WebLocalizedString::ValidationValueMissingForRadio);
 }
 
 void RadioInputType::handleClickEvent(MouseEvent* event)
@@ -84,7 +84,7 @@
     // We can only stay within the form's children if the form hasn't been demoted to a leaf because
     // of malformed HTML.
     Node* node = &element();
-    while ((node = (forward ? NodeTraversal::next(node) : NodeTraversal::previous(node)))) {
+    while ((node = (forward ? NodeTraversal::next(*node) : NodeTraversal::previous(*node)))) {
         // Once we encounter a form element, we know we're through.
         if (node->hasTagName(formTag))
             break;
@@ -97,7 +97,7 @@
         if (inputElement->isRadioButton() && inputElement->name() == element().name() && inputElement->isFocusable()) {
             RefPtr<HTMLInputElement> protector(inputElement);
             document.setFocusedElement(inputElement);
-            inputElement->dispatchSimulatedClick(event, SendNoEvents, DoNotShowPressedLook);
+            inputElement->dispatchSimulatedClick(event, SendNoEvents);
             event->setDefaultHandled();
             return;
         }
diff --git a/Source/core/html/forms/RangeInputType.cpp b/Source/core/html/forms/RangeInputType.cpp
index 8827e4b..5f98457 100644
--- a/Source/core/html/forms/RangeInputType.cpp
+++ b/Source/core/html/forms/RangeInputType.cpp
@@ -33,6 +33,7 @@
 #include "core/html/forms/RangeInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/events/KeyboardEvent.h"
@@ -46,7 +47,6 @@
 #include "core/html/HTMLDivElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLOptionElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/forms/StepRange.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/ShadowElementNames.h"
@@ -97,7 +97,7 @@
 
 const AtomicString& RangeInputType::formControlType() const
 {
-    return InputTypeNames::range();
+    return InputTypeNames::range;
 }
 
 double RangeInputType::valueAsDouble() const
@@ -246,7 +246,7 @@
 
     Document& document = element().document();
     RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
-    track->setPart(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
+    track->setPseudo(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
     track->setAttribute(idAttr, ShadowElementNames::sliderTrack());
     track->appendChild(SliderThumbElement::create(document));
     RefPtr<HTMLElement> container = SliderContainerElement::create(document);
diff --git a/Source/core/html/forms/ResetInputType.cpp b/Source/core/html/forms/ResetInputType.cpp
index d1e07e5..6175a6c 100644
--- a/Source/core/html/forms/ResetInputType.cpp
+++ b/Source/core/html/forms/ResetInputType.cpp
@@ -32,10 +32,10 @@
 #include "config.h"
 #include "core/html/forms/ResetInputType.h"
 
+#include "InputTypeNames.h"
 #include "core/events/Event.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -48,7 +48,7 @@
 
 const AtomicString& ResetInputType::formControlType() const
 {
-    return InputTypeNames::reset();
+    return InputTypeNames::reset;
 }
 
 bool ResetInputType::supportsValidation() const
@@ -66,7 +66,7 @@
 
 String ResetInputType::defaultValue() const
 {
-    return locale().queryString(WebKit::WebLocalizedString::ResetButtonDefaultLabel);
+    return locale().queryString(blink::WebLocalizedString::ResetButtonDefaultLabel);
 }
 
 bool ResetInputType::isTextButton() const
diff --git a/Source/core/html/forms/SearchInputType.cpp b/Source/core/html/forms/SearchInputType.cpp
index 7bd4126..8b83268 100644
--- a/Source/core/html/forms/SearchInputType.cpp
+++ b/Source/core/html/forms/SearchInputType.cpp
@@ -32,11 +32,11 @@
 #include "core/html/forms/SearchInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/TextControlInnerElements.h"
 #include "core/rendering/RenderSearchField.h"
@@ -69,7 +69,7 @@
 
 const AtomicString& SearchInputType::formControlType() const
 {
-    return InputTypeNames::search();
+    return InputTypeNames::search;
 }
 
 bool SearchInputType::shouldRespectSpeechAttribute()
@@ -159,9 +159,9 @@
     TextFieldInputType::didSetValueByUserEdit(state);
 }
 
-void SearchInputType::updateInnerTextValue()
+void SearchInputType::updateView()
 {
-    BaseTextInputType::updateInnerTextValue();
+    BaseTextInputType::updateView();
     updateCancelButtonVisibility();
 }
 
diff --git a/Source/core/html/forms/SearchInputType.h b/Source/core/html/forms/SearchInputType.h
index 66c2294..d13c0f9 100644
--- a/Source/core/html/forms/SearchInputType.h
+++ b/Source/core/html/forms/SearchInputType.h
@@ -57,7 +57,7 @@
     virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
     virtual void didSetValueByUserEdit(ValueChangeState) OVERRIDE;
     virtual bool supportsInputModeAttribute() const OVERRIDE;
-    virtual void updateInnerTextValue() OVERRIDE;
+    virtual void updateView() OVERRIDE;
 
     void searchEventTimerFired(Timer<SearchInputType>*);
     bool searchEventsShouldBeDispatched() const;
diff --git a/Source/core/html/forms/SubmitInputType.cpp b/Source/core/html/forms/SubmitInputType.cpp
index cda83bf..3b25b46 100644
--- a/Source/core/html/forms/SubmitInputType.cpp
+++ b/Source/core/html/forms/SubmitInputType.cpp
@@ -32,11 +32,11 @@
 #include "config.h"
 #include "core/html/forms/SubmitInputType.h"
 
+#include "InputTypeNames.h"
 #include "core/events/Event.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -49,7 +49,7 @@
 
 const AtomicString& SubmitInputType::formControlType() const
 {
-    return InputTypeNames::submit();
+    return InputTypeNames::submit;
 }
 
 bool SubmitInputType::appendFormData(FormDataList& encoding, bool) const
@@ -83,7 +83,7 @@
 
 String SubmitInputType::defaultValue() const
 {
-    return locale().queryString(WebKit::WebLocalizedString::SubmitButtonDefaultLabel);
+    return locale().queryString(blink::WebLocalizedString::SubmitButtonDefaultLabel);
 }
 
 bool SubmitInputType::isSubmitButton() const
diff --git a/Source/core/html/forms/TelephoneInputType.cpp b/Source/core/html/forms/TelephoneInputType.cpp
index 44bb48a..4b5e2ed 100644
--- a/Source/core/html/forms/TelephoneInputType.cpp
+++ b/Source/core/html/forms/TelephoneInputType.cpp
@@ -31,7 +31,7 @@
 #include "config.h"
 #include "core/html/forms/TelephoneInputType.h"
 
-#include "core/html/forms/InputTypeNames.h"
+#include "InputTypeNames.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
@@ -48,7 +48,7 @@
 
 const AtomicString& TelephoneInputType::formControlType() const
 {
-    return InputTypeNames::telephone();
+    return InputTypeNames::tel;
 }
 
 bool TelephoneInputType::shouldRespectSpeechAttribute()
diff --git a/Source/core/html/forms/TextFieldInputType.cpp b/Source/core/html/forms/TextFieldInputType.cpp
index 5e71ae5..59d39e3 100644
--- a/Source/core/html/forms/TextFieldInputType.cpp
+++ b/Source/core/html/forms/TextFieldInputType.cpp
@@ -39,7 +39,6 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/events/TextEvent.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/TextIterator.h"
 #include "core/html/FormDataList.h"
@@ -47,6 +46,8 @@
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/TextControlInnerElements.h"
 #include "core/frame/Frame.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/rendering/RenderLayer.h"
@@ -114,7 +115,7 @@
     InputType::setValue(sanitizedValue, valueChanged, DispatchNoEvent);
 
     if (valueChanged)
-        updateInnerTextValue();
+        updateView();
 
     unsigned max = visibleValue().length();
     if (input->focused())
@@ -153,9 +154,10 @@
 {
     if (!element().focused())
         return;
-    Frame* frame = element().document().frame();
-    if (!frame || !frame->editor().doTextFieldCommandFromEvent(&element(), event))
+    if (Chrome* chrome = this->chrome()) {
+        chrome->client().handleKeyboardEventOnTextField(element(), *event);
         return;
+    }
     event->setDefaultHandled();
 }
 
@@ -255,7 +257,7 @@
     }
 
     RefPtr<TextControlInnerContainer> container = TextControlInnerContainer::create(document);
-    container->setPart(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
+    container->setPseudo(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
     shadowRoot->appendChild(container);
 
     RefPtr<EditingViewPortElement> editingViewPort = EditingViewPortElement::create(document);
@@ -285,9 +287,9 @@
 
 void TextFieldInputType::attributeChanged()
 {
-    // FIXME: Updating the inner text on any attribute update should
-    // be unnecessary. We should figure out what attributes affect.
-    updateInnerTextValue();
+    // FIXME: Updating on any attribute update should be unnecessary. We should
+    // figure out what attributes affect.
+    updateView();
 }
 
 void TextFieldInputType::disabledAttributeChanged()
@@ -395,7 +397,7 @@
     if (!placeholder) {
         RefPtr<HTMLElement> newElement = HTMLDivElement::create(element().document());
         placeholder = newElement.get();
-        placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
         Element* container = containerElement();
         Node* previous = container ? container : element().innerTextElement();
@@ -442,8 +444,8 @@
 {
     if (!element().focused())
         return;
-    if (Frame* frame = element().document().frame())
-        frame->editor().textDidChangeInTextField(&element());
+    if (Chrome* chrome = this->chrome())
+        chrome->client().didChangeValueInTextField(element());
 }
 
 void TextFieldInputType::spinButtonStepDown()
@@ -456,7 +458,7 @@
     stepUpFromRenderer(1);
 }
 
-void TextFieldInputType::updateInnerTextValue()
+void TextFieldInputType::updateView()
 {
     if (!element().suggestedValue().isNull()) {
         element().setInnerTextValue(element().suggestedValue());
diff --git a/Source/core/html/forms/TextFieldInputType.h b/Source/core/html/forms/TextFieldInputType.h
index f260eba..a124ea1 100644
--- a/Source/core/html/forms/TextFieldInputType.h
+++ b/Source/core/html/forms/TextFieldInputType.h
@@ -60,7 +60,7 @@
     virtual void handleFocusEvent(Element* oldFocusedNode, FocusDirection) OVERRIDE;
     virtual void handleBlurEvent() OVERRIDE;
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
-    virtual void updateInnerTextValue() OVERRIDE;
+    virtual void updateView() OVERRIDE;
 
     virtual String convertFromVisibleValue(const String&) const;
     enum ValueChangeState {
diff --git a/Source/core/html/forms/TextInputType.cpp b/Source/core/html/forms/TextInputType.cpp
index c90ace4..a5e9db1 100644
--- a/Source/core/html/forms/TextInputType.cpp
+++ b/Source/core/html/forms/TextInputType.cpp
@@ -31,8 +31,8 @@
 #include "config.h"
 #include "core/html/forms/TextInputType.h"
 
+#include "InputTypeNames.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
@@ -50,15 +50,15 @@
     if (element().fastHasAttribute(maxlengthAttr))
         countUsageIfVisible(UseCounter::InputTypeTextMaxLength);
     const AtomicString& type = element().fastGetAttribute(typeAttr);
-    if (equalIgnoringCase(type, InputTypeNames::datetime()))
+    if (equalIgnoringCase(type, InputTypeNames::datetime))
         countUsageIfVisible(UseCounter::InputTypeDateTimeFallback);
-    else if (equalIgnoringCase(type, InputTypeNames::week()))
+    else if (equalIgnoringCase(type, InputTypeNames::week))
         countUsageIfVisible(UseCounter::InputTypeWeekFallback);
 }
 
 const AtomicString& TextInputType::formControlType() const
 {
-    return InputTypeNames::text();
+    return InputTypeNames::text;
 }
 
 bool TextInputType::shouldRespectSpeechAttribute()
diff --git a/Source/core/html/forms/TimeInputType.cpp b/Source/core/html/forms/TimeInputType.cpp
index 83a3fba..cc135bd 100644
--- a/Source/core/html/forms/TimeInputType.cpp
+++ b/Source/core/html/forms/TimeInputType.cpp
@@ -32,9 +32,9 @@
 #include "core/html/forms/TimeInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/DateComponents.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/CurrentTime.h"
@@ -68,7 +68,7 @@
 
 const AtomicString& TimeInputType::formControlType() const
 {
-    return InputTypeNames::time();
+    return InputTypeNames::time;
 }
 
 DateComponents::Type TimeInputType::dateType() const
diff --git a/Source/core/html/forms/URLInputType.cpp b/Source/core/html/forms/URLInputType.cpp
index 404906a..33017eb 100644
--- a/Source/core/html/forms/URLInputType.cpp
+++ b/Source/core/html/forms/URLInputType.cpp
@@ -31,8 +31,8 @@
 #include "config.h"
 #include "core/html/forms/URLInputType.h"
 
+#include "InputTypeNames.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -50,7 +50,7 @@
 
 const AtomicString& URLInputType::formControlType() const
 {
-    return InputTypeNames::url();
+    return InputTypeNames::url;
 }
 
 bool URLInputType::typeMismatchFor(const String& value) const
@@ -65,7 +65,7 @@
 
 String URLInputType::typeMismatchText() const
 {
-    return locale().queryString(WebKit::WebLocalizedString::ValidationTypeMismatchForURL);
+    return locale().queryString(blink::WebLocalizedString::ValidationTypeMismatchForURL);
 }
 
 bool URLInputType::isURLField() const
diff --git a/Source/core/html/forms/WeekInputType.cpp b/Source/core/html/forms/WeekInputType.cpp
index 84d8542..d164ff2 100644
--- a/Source/core/html/forms/WeekInputType.cpp
+++ b/Source/core/html/forms/WeekInputType.cpp
@@ -32,9 +32,9 @@
 #include "core/html/forms/WeekInputType.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "platform/DateComponents.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/PassOwnPtr.h"
@@ -60,7 +60,7 @@
 
 const AtomicString& WeekInputType::formControlType() const
 {
-    return InputTypeNames::week();
+    return InputTypeNames::week;
 }
 
 DateComponents::Type WeekInputType::dateType() const
diff --git a/Source/core/html/parser/AtomicHTMLToken.h b/Source/core/html/parser/AtomicHTMLToken.h
index 2d74f8e..4bc8aa4 100644
--- a/Source/core/html/parser/AtomicHTMLToken.h
+++ b/Source/core/html/parser/AtomicHTMLToken.h
@@ -26,6 +26,7 @@
 #ifndef AtomicHTMLToken_h
 #define AtomicHTMLToken_h
 
+#include "HTMLElementLookupTrie.h"
 #include "core/dom/Attribute.h"
 #include "core/html/parser/CompactHTMLToken.h"
 #include "core/html/parser/HTMLToken.h"
@@ -124,7 +125,10 @@
         case HTMLToken::StartTag:
         case HTMLToken::EndTag: {
             m_selfClosing = token.selfClosing();
-            m_name = AtomicString(token.name());
+            if (StringImpl* tagName = lookupHTMLTag(token.name().data(), token.name().size()))
+                m_name = AtomicString(tagName);
+            else
+                m_name = AtomicString(token.name());
             initializeAttributes(token.attributes());
             break;
         }
diff --git a/Source/core/html/parser/HTMLConstructionSite.cpp b/Source/core/html/parser/HTMLConstructionSite.cpp
index f0ac5ad..96dc248 100644
--- a/Source/core/html/parser/HTMLConstructionSite.cpp
+++ b/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -119,6 +119,27 @@
         task.child->finishParsingChildren();
 }
 
+static inline void executeInsertTextTask(HTMLConstructionSiteTask& task)
+{
+    ASSERT(task.operation == HTMLConstructionSiteTask::InsertText);
+    ASSERT(task.child->isTextNode());
+
+    // Merge text nodes into previous ones if possible:
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#insert-a-character
+    Text* newText = toText(task.child.get());
+    Node* previousChild = task.nextChild ? task.nextChild->previousSibling() : task.parent->lastChild();
+    if (previousChild && previousChild->isTextNode()) {
+        Text* previousText = toText(previousChild);
+        unsigned lengthLimit = textLengthLimitForContainer(task.parent.get());
+        if (previousText->length() + newText->length() < lengthLimit) {
+            previousText->parserAppendData(newText->data());
+            return;
+        }
+    }
+
+    insert(task);
+}
+
 static inline void executeReparentTask(HTMLConstructionSiteTask& task)
 {
     ASSERT(task.operation == HTMLConstructionSiteTask::Reparent);
@@ -149,6 +170,9 @@
     if (task.operation == HTMLConstructionSiteTask::Insert)
         return executeInsertTask(task);
 
+    if (task.operation == HTMLConstructionSiteTask::InsertText)
+        return executeInsertTextTask(task);
+
     // All the cases below this point are only used by the adoption agency.
 
     if (task.operation == HTMLConstructionSiteTask::InsertAlreadyParsedChild)
@@ -166,7 +190,7 @@
 // This is only needed for TextDocuments where we might have text nodes
 // approaching the default length limit (~64k) and we don't want to
 // break a text node in the middle of a combining character.
-static unsigned findBreakIndexBetween(const String& string, unsigned currentPosition, unsigned proposedBreakIndex)
+static unsigned findBreakIndexBetween(const StringBuilder& string, unsigned currentPosition, unsigned proposedBreakIndex)
 {
     ASSERT(currentPosition < proposedBreakIndex);
     ASSERT(proposedBreakIndex <= string.length());
@@ -202,8 +226,46 @@
     return string;
 }
 
+void HTMLConstructionSite::flushPendingText()
+{
+    if (m_pendingText.isEmpty())
+        return;
+
+    PendingText pendingText;
+    // Hold onto the current pending text on the stack so that queueTask doesn't recurse infinitely.
+    m_pendingText.swap(pendingText);
+    ASSERT(m_pendingText.isEmpty());
+
+    // Splitting text nodes into smaller chunks contradicts HTML5 spec, but is necessary
+    // for performance, see: https://bugs.webkit.org/show_bug.cgi?id=55898
+    unsigned lengthLimit = textLengthLimitForContainer(pendingText.parent.get());
+
+    unsigned currentPosition = 0;
+    const StringBuilder& string = pendingText.stringBuilder;
+    while (currentPosition < string.length()) {
+        unsigned proposedBreakIndex = std::min(currentPosition + lengthLimit, string.length());
+        unsigned breakIndex = findBreakIndexBetween(string, currentPosition, proposedBreakIndex);
+        ASSERT(breakIndex <= string.length());
+        String substring = string.substring(currentPosition, breakIndex - currentPosition);
+        substring = atomizeIfAllWhitespace(substring, pendingText.whitespaceMode);
+
+        HTMLConstructionSiteTask task(HTMLConstructionSiteTask::InsertText);
+        task.parent = pendingText.parent;
+        task.nextChild = pendingText.nextChild;
+        task.child = Text::create(task.parent->document(), substring);
+        queueTask(task);
+
+        ASSERT(breakIndex > currentPosition);
+        ASSERT(breakIndex - currentPosition == substring.length());
+        ASSERT(toText(task.child.get())->length() == substring.length());
+        currentPosition = breakIndex;
+    }
+}
+
 void HTMLConstructionSite::queueTask(const HTMLConstructionSiteTask& task)
 {
+    flushPendingText();
+    ASSERT(m_pendingText.isEmpty());
     m_taskQueue.append(task);
 }
 
@@ -232,6 +294,8 @@
 
 void HTMLConstructionSite::executeQueuedTasks()
 {
+    // This has no affect on pendingText, and we may have pendingText
+    // remaining after executing all other queued tasks.
     const size_t size = m_taskQueue.size();
     if (!size)
         return;
@@ -274,10 +338,17 @@
     // Depending on why we're being destroyed it might be OK
     // to forget queued tasks, but currently we don't expect to.
     ASSERT(m_taskQueue.isEmpty());
+    // Currently we assume that text will never be the last token in the
+    // document and that we'll always queue some additional task to cause it to flush.
+    ASSERT(m_pendingText.isEmpty());
 }
 
 void HTMLConstructionSite::detach()
 {
+    // FIXME: We'd like to ASSERT here that we're canceling and not just discarding
+    // text that really should have made it into the DOM earlier, but there
+    // doesn't seem to be a nice way to do that.
+    m_pendingText.discard();
     m_document = 0;
     m_attachmentRoot = 0;
 }
@@ -447,12 +518,15 @@
 void HTMLConstructionSite::processEndOfFile()
 {
     ASSERT(currentNode());
+    flush();
     openElements()->popAll();
 }
 
 void HTMLConstructionSite::finishedParsing()
 {
+    // We shouldn't have any queued tasks but we might have pending text which we need to promote to tasks and execute.
     ASSERT(m_taskQueue.isEmpty());
+    flush();
     m_document->finishedParsing();
 }
 
@@ -565,7 +639,7 @@
     // those flags or effects thereof.
     const bool parserInserted = m_parserContentPolicy != AllowScriptingContentAndDoNotMarkAlreadyStarted;
     const bool alreadyStarted = m_isParsingFragment && parserInserted;
-    RefPtr<HTMLScriptElement> element = HTMLScriptElement::create(scriptTag, ownerDocumentForCurrentNode(), parserInserted, alreadyStarted);
+    RefPtr<HTMLScriptElement> element = HTMLScriptElement::create(ownerDocumentForCurrentNode(), parserInserted, alreadyStarted);
     setAttributes(element.get(), token, m_parserContentPolicy);
     if (scriptingContentIsAllowed(m_parserContentPolicy))
         attachLater(currentNode(), element);
@@ -586,63 +660,22 @@
 
 void HTMLConstructionSite::insertTextNode(const String& string, WhitespaceMode whitespaceMode)
 {
-    HTMLConstructionSiteTask protoTask(HTMLConstructionSiteTask::Insert);
-    protoTask.parent = currentNode();
+    HTMLConstructionSiteTask dummyTask(HTMLConstructionSiteTask::Insert);
+    dummyTask.parent = currentNode();
 
     if (shouldFosterParent())
-        findFosterSite(protoTask);
+        findFosterSite(dummyTask);
 
     // FIXME: This probably doesn't need to be done both here and in insert(Task).
-    if (protoTask.parent->hasTagName(templateTag))
-        protoTask.parent = toHTMLTemplateElement(protoTask.parent.get())->content();
+    if (dummyTask.parent->hasTagName(templateTag))
+        dummyTask.parent = toHTMLTemplateElement(dummyTask.parent.get())->content();
 
-    // Splitting text nodes into smaller chunks contradicts HTML5 spec, but is necessary
-    // for performance, see: https://bugs.webkit.org/show_bug.cgi?id=55898
-    unsigned lengthLimit = textLengthLimitForContainer(protoTask.parent.get());
-    unsigned currentPosition = 0;
-
-    // Merge text nodes into previous ones if possible:
-    // http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#insert-a-character
-    Node* previousChild = protoTask.nextChild ? protoTask.nextChild->previousSibling() : protoTask.parent->lastChild();
-    if (previousChild && previousChild->isTextNode()) {
-        Text* previousText = toText(previousChild);
-        unsigned appendLengthLimit = lengthLimit - previousText->length();
-
-        unsigned proposedBreakIndex = std::min(currentPosition + appendLengthLimit, string.length());
-        unsigned breakIndex = findBreakIndexBetween(string, currentPosition, proposedBreakIndex);
-        ASSERT(breakIndex <= string.length());
-        // If we didn't find a breable piece to append, forget it.
-        if (breakIndex) {
-            String substring = string.substring(currentPosition, breakIndex - currentPosition);
-            substring = atomizeIfAllWhitespace(substring, whitespaceMode);
-            previousText->parserAppendData(substring);
-            currentPosition += substring.length();
-        }
-    }
-
-    while (currentPosition < string.length()) {
-        unsigned proposedBreakIndex = std::min(currentPosition + lengthLimit, string.length());
-        unsigned breakIndex = findBreakIndexBetween(string, currentPosition, proposedBreakIndex);
-        // We failed to find a breakable boudary between the minimum and the proposed, just give up and break at the proposed index.
-        // We could go searching after the proposed index, but current callers are attempting to break after 65k chars!
-        // 65k of unbreakable characters isn't worth trying to handle "correctly".
-        if (!breakIndex)
-            breakIndex = proposedBreakIndex;
-        ASSERT(breakIndex <= string.length());
-        String substring = string.substring(currentPosition, breakIndex - currentPosition);
-        substring = atomizeIfAllWhitespace(substring, whitespaceMode);
-
-        HTMLConstructionSiteTask task(HTMLConstructionSiteTask::Insert);
-        task.parent = protoTask.parent;
-        task.nextChild = protoTask.nextChild;
-        task.child = Text::create(task.parent->document(), substring);
-        queueTask(task);
-
-        ASSERT(breakIndex > currentPosition);
-        ASSERT(breakIndex - currentPosition == substring.length());
-        ASSERT(toText(task.child)->length() == substring.length());
-        currentPosition = breakIndex;
-    }
+    // Unclear when parent != case occurs. Somehow we insert text into two separate nodes while processing the same Token.
+    // The nextChild != dummy.nextChild case occurs whenever foster parenting happened and we hit a new text node "<table>a</table>b"
+    // In either case we have to flush the pending text into the task queue before making more.
+    if (!m_pendingText.isEmpty() && (m_pendingText.parent != dummyTask.parent ||  m_pendingText.nextChild != dummyTask.nextChild))
+        flushPendingText();
+    m_pendingText.append(dummyTask.parent, dummyTask.nextChild, string, whitespaceMode);
 }
 
 void HTMLConstructionSite::reparent(HTMLElementStack::ElementRecord* newParent, HTMLElementStack::ElementRecord* child)
@@ -699,7 +732,6 @@
 
 PassRefPtr<Element> HTMLConstructionSite::createHTMLElement(AtomicHTMLToken* token)
 {
-    QualifiedName tagName(nullAtom, token->name(), xhtmlNamespaceURI);
     Document& document = ownerDocumentForCurrentNode();
     // Only associate the element with the current form if we're creating the new element
     // in a document with a browsing context (rather than in <template> contents).
@@ -707,7 +739,7 @@
     // FIXME: This can't use HTMLConstructionSite::createElement because we
     // have to pass the current form element.  We should rework form association
     // to occur after construction to allow better code sharing here.
-    RefPtr<Element> element = HTMLElementFactory::createHTMLElement(tagName, &document, form, true);
+    RefPtr<Element> element = HTMLElementFactory::createHTMLElement(token->name(), document, form, true);
     setAttributes(element.get(), token, m_parserContentPolicy);
     ASSERT(element->isHTMLElement());
     return element.release();
diff --git a/Source/core/html/parser/HTMLConstructionSite.h b/Source/core/html/parser/HTMLConstructionSite.h
index cac778c..d4d812e 100644
--- a/Source/core/html/parser/HTMLConstructionSite.h
+++ b/Source/core/html/parser/HTMLConstructionSite.h
@@ -41,6 +41,7 @@
 struct HTMLConstructionSiteTask {
     enum Operation {
         Insert,
+        InsertText, // Handles possible merging of text nodes.
         InsertAlreadyParsedChild, // Insert w/o calling begin/end parsing.
         Reparent,
         TakeAllChildren,
@@ -96,8 +97,29 @@
     ~HTMLConstructionSite();
 
     void detach();
+
+    // executeQueuedTasks empties the queue but does not flush pending text.
+    // NOTE: Possible reentrancy via JavaScript execution.
     void executeQueuedTasks();
 
+    // flushPendingText turns pending text into queued Text insertions, but does not execute them.
+    void flushPendingText();
+
+    // Called before every token in HTMLTreeBuilder::processToken, thus inlined:
+    void flush()
+    {
+        if (!hasPendingTasks())
+            return;
+        flushPendingText();
+        executeQueuedTasks(); // NOTE: Possible reentrancy via JavaScript execution.
+        ASSERT(!hasPendingTasks());
+    }
+
+    bool hasPendingTasks()
+    {
+        return !m_pendingText.isEmpty() || !m_taskQueue.isEmpty();
+    }
+
     void setDefaultCompatibilityMode();
     void processEndOfFile();
     void finishedParsing();
@@ -216,6 +238,53 @@
 
     TaskQueue m_taskQueue;
 
+    struct PendingText {
+        PendingText()
+            : whitespaceMode(WhitespaceUnknown)
+        {
+        }
+
+        void append(PassRefPtr<ContainerNode> newParent, PassRefPtr<Node> newNextChild, const String& newString, WhitespaceMode newWhitespaceMode)
+        {
+            ASSERT(!parent || parent == newParent);
+            parent = newParent;
+            ASSERT(!nextChild || nextChild == newNextChild);
+            nextChild = newNextChild;
+            stringBuilder.append(newString);
+            whitespaceMode = std::min(whitespaceMode, newWhitespaceMode);
+        }
+
+        void swap(PendingText& other)
+        {
+            std::swap(whitespaceMode, other.whitespaceMode);
+            parent.swap(other.parent);
+            nextChild.swap(other.nextChild);
+            stringBuilder.swap(other.stringBuilder);
+        }
+
+        void discard()
+        {
+            PendingText discardedText;
+            swap(discardedText);
+        }
+
+        bool isEmpty()
+        {
+            // When the stringbuilder is empty, the parent and whitespace should also be "empty".
+            ASSERT(stringBuilder.isEmpty() == !parent);
+            ASSERT(!stringBuilder.isEmpty() || !nextChild);
+            ASSERT(!stringBuilder.isEmpty() || (whitespaceMode == WhitespaceUnknown));
+            return stringBuilder.isEmpty();
+        }
+
+        RefPtr<ContainerNode> parent;
+        RefPtr<Node> nextChild;
+        StringBuilder stringBuilder;
+        WhitespaceMode whitespaceMode;
+    };
+
+    PendingText m_pendingText;
+
     ParserContentPolicy m_parserContentPolicy;
     bool m_isParsingFragment;
 
diff --git a/Source/core/html/parser/HTMLDocumentParser.cpp b/Source/core/html/parser/HTMLDocumentParser.cpp
index e0dfa89..f3a7f49 100644
--- a/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -557,6 +557,12 @@
     if (isStopped())
         return;
 
+    // There should only be PendingText left since the tree-builder always flushes
+    // the task queue before returning. In case that ever changes, crash.
+    if (mode == ForceSynchronous)
+        m_treeBuilder->flush();
+    RELEASE_ASSERT(!isStopped());
+
     if (session.needsYield)
         m_parserScheduler->scheduleForResume();
 
diff --git a/Source/core/html/parser/HTMLParserIdioms.cpp b/Source/core/html/parser/HTMLParserIdioms.cpp
index b635e62..d488067 100644
--- a/Source/core/html/parser/HTMLParserIdioms.cpp
+++ b/Source/core/html/parser/HTMLParserIdioms.cpp
@@ -28,7 +28,6 @@
 #include <limits>
 #include "core/dom/QualifiedName.h"
 #include "core/html/parser/HTMLIdentifier.h"
-#include "platform/Decimal.h"
 #include "wtf/MathExtras.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/StringBuilder.h"
@@ -115,11 +114,6 @@
     return value.isZero() ? Decimal(0) : value;
 }
 
-Decimal parseToDecimalForNumberType(const String& string)
-{
-    return parseToDecimalForNumberType(string, Decimal::nan());
-}
-
 double parseToDoubleForNumberType(const String& string, double fallbackValue)
 {
     // See HTML5 2.5.4.3 `Real numbers.'
@@ -147,11 +141,6 @@
     return value ? value : 0;
 }
 
-double parseToDoubleForNumberType(const String& string)
-{
-    return parseToDoubleForNumberType(string, std::numeric_limits<double>::quiet_NaN());
-}
-
 template <typename CharacterType>
 static bool parseHTMLIntegerInternal(const CharacterType* position, const CharacterType* end, int& value)
 {
diff --git a/Source/core/html/parser/HTMLParserIdioms.h b/Source/core/html/parser/HTMLParserIdioms.h
index 5c3e9df..903ca5a 100644
--- a/Source/core/html/parser/HTMLParserIdioms.h
+++ b/Source/core/html/parser/HTMLParserIdioms.h
@@ -27,13 +27,12 @@
 
 #include "core/dom/QualifiedName.h"
 #include "core/html/parser/HTMLIdentifier.h"
+#include "platform/Decimal.h"
 #include "wtf/Forward.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class Decimal;
-
 // Space characters as defined by the HTML specification.
 bool isHTMLSpace(UChar);
 bool isHTMLLineBreak(UChar);
@@ -54,10 +53,8 @@
 // Convert the specified string to a decimal/double. If the conversion fails, the return value is fallback value or NaN if not specified.
 // Leading or trailing illegal characters cause failure, as does passing an empty string.
 // The double* parameter may be 0 to check if the string can be parsed without getting the result.
-Decimal parseToDecimalForNumberType(const String&);
-Decimal parseToDecimalForNumberType(const String&, const Decimal& fallbackValue);
-double parseToDoubleForNumberType(const String&);
-double parseToDoubleForNumberType(const String&, double fallbackValue);
+Decimal parseToDecimalForNumberType(const String&, const Decimal& fallbackValue = Decimal::nan());
+double parseToDoubleForNumberType(const String&, double fallbackValue = std::numeric_limits<double>::quiet_NaN());
 
 // http://www.whatwg.org/specs/web-apps/current-work/#rules-for-parsing-integers
 bool parseHTMLInteger(const String&, int&);
diff --git a/Source/core/html/parser/HTMLParserThread.cpp b/Source/core/html/parser/HTMLParserThread.cpp
index 182d2a7..5a0e30c 100644
--- a/Source/core/html/parser/HTMLParserThread.cpp
+++ b/Source/core/html/parser/HTMLParserThread.cpp
@@ -38,7 +38,7 @@
 namespace WebCore {
 
 HTMLParserThread::HTMLParserThread()
-    : m_thread(adoptPtr(WebKit::Platform::current()->createThread("HTMLParserThread")))
+    : m_thread(adoptPtr(blink::Platform::current()->createThread("HTMLParserThread")))
 {
 }
 
diff --git a/Source/core/html/parser/HTMLParserThread.h b/Source/core/html/parser/HTMLParserThread.h
index 9e687de..e0b85f9 100644
--- a/Source/core/html/parser/HTMLParserThread.h
+++ b/Source/core/html/parser/HTMLParserThread.h
@@ -46,7 +46,7 @@
     HTMLParserThread();
     ~HTMLParserThread();
 
-    OwnPtr<WebKit::WebThread> m_thread;
+    OwnPtr<blink::WebThread> m_thread;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/parser/HTMLPreloadScanner.cpp b/Source/core/html/parser/HTMLPreloadScanner.cpp
index a6c98ea..895d6a0 100644
--- a/Source/core/html/parser/HTMLPreloadScanner.cpp
+++ b/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -29,9 +29,9 @@
 #include "core/html/parser/HTMLPreloadScanner.h"
 
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/html/LinkRelAttribute.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/HTMLSrcsetParser.h"
 #include "core/html/parser/HTMLTokenizer.h"
@@ -179,7 +179,7 @@
             if (match(attributeName, srcAttr))
                 setUrlToLoad(attributeValue, DisallowURLReplacement);
             else if (match(attributeName, typeAttr))
-                m_inputIsImage = equalIgnoringCase(attributeValue, InputTypeNames::image());
+                m_inputIsImage = equalIgnoringCase(attributeValue, InputTypeNames::image);
         }
     }
 
diff --git a/Source/core/html/parser/HTMLResourcePreloader.cpp b/Source/core/html/parser/HTMLResourcePreloader.cpp
index 95f3f14..6adba83 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.cpp
+++ b/Source/core/html/parser/HTMLResourcePreloader.cpp
@@ -93,7 +93,7 @@
         return;
 
     FetchRequest request = preload->resourceRequest(m_document);
-    WebKit::Platform::current()->histogramCustomCounts("WebCore.PreloadDelayMs", static_cast<int>(1000 * (monotonicallyIncreasingTime() - preload->discoveryTime())), 0, 2000, 20);
+    blink::Platform::current()->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/HTMLScriptRunner.cpp b/Source/core/html/parser/HTMLScriptRunner.cpp
index c8b9c6c..1cb6555 100644
--- a/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -137,8 +137,8 @@
             scriptLoader->dispatchErrorEvent();
         else {
             ASSERT(isExecutingScript());
-            scriptLoader->executeScript(sourceCode);
-            element->dispatchEvent(createScriptLoadEvent());
+            if (scriptLoader->executePotentiallyCrossOriginScript(sourceCode))
+                element->dispatchEvent(createScriptLoadEvent());
         }
     }
     ASSERT(!isExecutingScript());
diff --git a/Source/core/html/parser/HTMLTreeBuilder.cpp b/Source/core/html/parser/HTMLTreeBuilder.cpp
index f419b65..77d6d24 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.cpp
+++ b/Source/core/html/parser/HTMLTreeBuilder.cpp
@@ -340,15 +340,14 @@
 
 HTMLTreeBuilder::FragmentParsingContext::FragmentParsingContext()
     : m_fragment(0)
-    , m_contextElement(0)
 {
 }
 
 HTMLTreeBuilder::FragmentParsingContext::FragmentParsingContext(DocumentFragment* fragment, Element* contextElement)
     : m_fragment(fragment)
-    , m_contextElement(contextElement)
 {
     ASSERT(!fragment->hasChildNodes());
+    m_contextElementStackItem = HTMLStackItem::create(contextElement, HTMLStackItem::ItemForContextElement);
 }
 
 HTMLTreeBuilder::FragmentParsingContext::~FragmentParsingContext()
@@ -358,6 +357,7 @@
 PassRefPtr<Element> HTMLTreeBuilder::takeScriptToProcess(TextPosition& scriptStartPosition)
 {
     ASSERT(m_scriptToProcess);
+    ASSERT(!m_tree.hasPendingTasks());
     // Unpause ourselves, callers may pause us again when processing the script.
     // The HTML5 spec is written as though scripts are executed inside the tree
     // builder.  We pause the parser to exit the tree builder, and then resume
@@ -377,10 +377,10 @@
     if (m_parser->tokenizer()) {
         bool inForeignContent = false;
         if (!m_tree.isEmpty()) {
-            RefPtr<HTMLStackItem> adjustedCurrentNode = adjustedCurrentStackItem();
+            HTMLStackItem* adjustedCurrentNode = adjustedCurrentStackItem();
             inForeignContent = !adjustedCurrentNode->isInHTMLNamespace()
-                && !HTMLElementStack::isHTMLIntegrationPoint(adjustedCurrentNode.get())
-                && !HTMLElementStack::isMathMLTextIntegrationPoint(adjustedCurrentNode.get());
+                && !HTMLElementStack::isHTMLIntegrationPoint(adjustedCurrentNode)
+                && !HTMLElementStack::isMathMLTextIntegrationPoint(adjustedCurrentNode);
         }
 
         m_parser->tokenizer()->setForceNullCharacterReplacement(m_insertionMode == TextMode || inForeignContent);
@@ -398,6 +398,9 @@
         return;
     }
 
+    // Any non-character token needs to cause us to flush any pending text immediately.
+    // NOTE: flush() can cause any queued tasks to execute, possibly re-entering the parser.
+    m_tree.flush();
     m_shouldSkipLeadingNewline = false;
 
     switch (token->type()) {
@@ -504,7 +507,7 @@
     if (promptAttribute)
         processFakeCharacters(promptAttribute->value());
     else
-        processFakeCharacters(Locale::defaultLocale().queryString(WebKit::WebLocalizedString::SearchableIndexIntroduction));
+        processFakeCharacters(Locale::defaultLocale().queryString(blink::WebLocalizedString::SearchableIndexIntroduction));
     processFakeStartTag(inputTag, attributesForIsindexInput(token));
     notImplemented(); // This second set of characters may be needed by non-english locales.
     processFakeEndTag(labelTag);
@@ -999,11 +1002,11 @@
 }
 
 // http://www.whatwg.org/specs/web-apps/current-work/#adjusted-current-node
-PassRefPtr<HTMLStackItem> HTMLTreeBuilder::adjustedCurrentStackItem() const
+HTMLStackItem* HTMLTreeBuilder::adjustedCurrentStackItem() const
 {
     ASSERT(!m_tree.isEmpty());
     if (isParsingFragment() && m_tree.openElements()->hasOnlyOneElement())
-        return HTMLStackItem::create(m_fragmentContext.contextElement(), HTMLStackItem::ItemForContextElement);
+        return m_fragmentContext.contextElementStackItem();
 
     return m_tree.currentStackItem();
 }
@@ -1620,7 +1623,7 @@
         if (item->node() == m_tree.openElements()->rootNode()) {
             last = true;
             if (isParsingFragment())
-                item = HTMLStackItem::create(m_fragmentContext.contextElement(), HTMLStackItem::ItemForContextElement);
+                item = m_fragmentContext.contextElementStackItem();
         }
         if (item->hasTagName(templateTag))
             return setInsertionMode(m_templateInsertionModes.last());
@@ -2688,11 +2691,11 @@
 {
     if (m_tree.isEmpty())
         return false;
-    RefPtr<HTMLStackItem> adjustedCurrentNode = adjustedCurrentStackItem();
+    HTMLStackItem* adjustedCurrentNode = adjustedCurrentStackItem();
 
     if (adjustedCurrentNode->isInHTMLNamespace())
         return false;
-    if (HTMLElementStack::isMathMLTextIntegrationPoint(adjustedCurrentNode.get())) {
+    if (HTMLElementStack::isMathMLTextIntegrationPoint(adjustedCurrentNode)) {
         if (token->type() == HTMLToken::StartTag
             && token->name() != MathMLNames::mglyphTag
             && token->name() != MathMLNames::malignmarkTag)
@@ -2704,7 +2707,7 @@
         && token->type() == HTMLToken::StartTag
         && token->name() == SVGNames::svgTag)
         return false;
-    if (HTMLElementStack::isHTMLIntegrationPoint(adjustedCurrentNode.get())) {
+    if (HTMLElementStack::isHTMLIntegrationPoint(adjustedCurrentNode)) {
         if (token->type() == HTMLToken::StartTag)
             return false;
         if (token->type() == HTMLToken::Character)
@@ -2717,7 +2720,16 @@
 
 void HTMLTreeBuilder::processTokenInForeignContent(AtomicHTMLToken* token)
 {
-    RefPtr<HTMLStackItem> adjustedCurrentNode = adjustedCurrentStackItem();
+    if (token->type() == HTMLToken::Character) {
+        const String& characters = token->characters();
+        m_tree.insertTextNode(characters);
+        if (m_framesetOk && !isAllWhitespaceOrReplacementCharacters(characters))
+            m_framesetOk = false;
+        return;
+    }
+
+    m_tree.flush();
+    HTMLStackItem* adjustedCurrentNode = adjustedCurrentStackItem();
 
     switch (token->type()) {
     case HTMLToken::Uninitialized:
@@ -2815,14 +2827,8 @@
     }
     case HTMLToken::Comment:
         m_tree.insertComment(token);
-        return;
-    case HTMLToken::Character: {
-        const String& characters = token->characters();
-        m_tree.insertTextNode(characters);
-        if (m_framesetOk && !isAllWhitespaceOrReplacementCharacters(characters))
-            m_framesetOk = false;
         break;
-    }
+    case HTMLToken::Character:
     case HTMLToken::EndOfFile:
         ASSERT_NOT_REACHED();
         break;
diff --git a/Source/core/html/parser/HTMLTreeBuilder.h b/Source/core/html/parser/HTMLTreeBuilder.h
index 2c05af5..60ead95 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.h
+++ b/Source/core/html/parser/HTMLTreeBuilder.h
@@ -80,6 +80,9 @@
     // Done, close any open tags, etc.
     void finished();
 
+    // Synchronously empty any queues, possibly creating more DOM nodes.
+    void flush() { m_tree.flush(); }
+
     void setShouldSkipLeadingNewline(bool shouldSkip) { m_shouldSkipLeadingNewline = shouldSkip; }
 
 private:
@@ -166,7 +169,7 @@
     void defaultForAfterHead();
     void defaultForInTableText();
 
-    inline PassRefPtr<HTMLStackItem> adjustedCurrentStackItem() const;
+    inline HTMLStackItem* adjustedCurrentStackItem() const;
     inline bool shouldProcessTokenInForeignContent(AtomicHTMLToken*);
     void processTokenInForeignContent(AtomicHTMLToken*);
 
@@ -198,11 +201,12 @@
         ~FragmentParsingContext();
 
         DocumentFragment* fragment() const { return m_fragment; }
-        Element* contextElement() const { ASSERT(m_fragment); return m_contextElement; }
+        Element* contextElement() const { ASSERT(m_fragment); return m_contextElementStackItem->element(); }
+        HTMLStackItem* contextElementStackItem() const { ASSERT(m_fragment); return m_contextElementStackItem.get(); }
 
     private:
         DocumentFragment* m_fragment;
-        Element* m_contextElement;
+        RefPtr<HTMLStackItem> m_contextElementStackItem;
     };
 
     bool m_framesetOk;
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index 972c0e7..b7565af 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -43,7 +43,7 @@
 #include "platform/JSONValues.h"
 #include "platform/network/FormData.h"
 #include "platform/text/DecodeEscapeSequences.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/MainThread.h"
 #include "wtf/text/TextEncoding.h"
 
diff --git a/Source/core/html/parser/XSSAuditor.h b/Source/core/html/parser/XSSAuditor.h
index f2f4ae2..db2655f 100644
--- a/Source/core/html/parser/XSSAuditor.h
+++ b/Source/core/html/parser/XSSAuditor.h
@@ -29,7 +29,7 @@
 #include "core/html/parser/HTMLToken.h"
 #include "platform/network/HTTPParsers.h"
 #include "platform/text/SuffixTree.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/TextEncoding.h"
 
diff --git a/Source/core/html/parser/XSSAuditorDelegate.cpp b/Source/core/html/parser/XSSAuditorDelegate.cpp
index b676bc9..f7f8bfd 100644
--- a/Source/core/html/parser/XSSAuditorDelegate.cpp
+++ b/Source/core/html/parser/XSSAuditorDelegate.cpp
@@ -34,7 +34,7 @@
 #include "core/loader/PingLoader.h"
 #include "platform/JSONValues.h"
 #include "platform/network/FormData.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
diff --git a/Source/core/html/parser/XSSAuditorDelegate.h b/Source/core/html/parser/XSSAuditorDelegate.h
index fbd0577..1fbfb20 100644
--- a/Source/core/html/parser/XSSAuditorDelegate.h
+++ b/Source/core/html/parser/XSSAuditorDelegate.h
@@ -26,7 +26,7 @@
 #ifndef XSSAuditorDelegate_h
 #define XSSAuditorDelegate_h
 
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
diff --git a/Source/core/html/shadow/ClearButtonElement.cpp b/Source/core/html/shadow/ClearButtonElement.cpp
index 96b3760..cb928e8 100644
--- a/Source/core/html/shadow/ClearButtonElement.cpp
+++ b/Source/core/html/shadow/ClearButtonElement.cpp
@@ -37,7 +37,7 @@
 using namespace HTMLNames;
 
 inline ClearButtonElement::ClearButtonElement(Document& document, ClearButtonOwner& clearButtonOwner)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
     , m_clearButtonOwner(&clearButtonOwner)
     , m_capturing(false)
 {
@@ -46,7 +46,7 @@
 PassRefPtr<ClearButtonElement> ClearButtonElement::create(Document& document, ClearButtonOwner& clearButtonOwner)
 {
     RefPtr<ClearButtonElement> element = adoptRef(new ClearButtonElement(document, clearButtonOwner));
-    element->setPart(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
+    element->setPseudo(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 909402c..fe6afc7 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->setPart(textPseudoId);
+    element->setPseudo(textPseudoId);
     if (m_parameters.locale.isRTL() && text.length()) {
         Direction dir = direction(text[0]);
         if (dir == SegmentSeparator || dir == WhiteSpaceNeutral || dir == OtherNeutral)
@@ -441,7 +441,7 @@
 }
 
 DateTimeEditElement::DateTimeEditElement(Document& document, EditControlOwner& editControlOwner)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
     , m_editControlOwner(&editControlOwner)
 {
     setHasCustomStyleCallbacks();
@@ -485,7 +485,7 @@
 PassRefPtr<DateTimeEditElement> DateTimeEditElement::create(Document& document, EditControlOwner& editControlOwner)
 {
     RefPtr<DateTimeEditElement> container = adoptRef(new DateTimeEditElement(document, editControlOwner));
-    container->setPart(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
+    container->setPseudo(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
     container->setAttribute(idAttr, ShadowElementNames::dateTimeEdit());
     return container.release();
 }
@@ -653,7 +653,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, fieldsWrapperPseudoId, ("-webkit-datetime-edit-fields-wrapper", AtomicString::ConstructFromLiteral));
     if (!firstChild()) {
         RefPtr<HTMLDivElement> element = HTMLDivElement::create(document());
-        element->setPart(fieldsWrapperPseudoId);
+        element->setPseudo(fieldsWrapperPseudoId);
         appendChild(element.get());
     }
     Element* fieldsWrapper = fieldsWrapperElement();
diff --git a/Source/core/html/shadow/DateTimeFieldElement.cpp b/Source/core/html/shadow/DateTimeFieldElement.cpp
index dc8c3b4..31cdb06 100644
--- a/Source/core/html/shadow/DateTimeFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElement.cpp
@@ -39,7 +39,7 @@
 
 static String emptyValueAXText()
 {
-    return Locale::defaultLocale().queryString(WebKit::WebLocalizedString::AXDateTimeFieldEmptyValueText);
+    return Locale::defaultLocale().queryString(blink::WebLocalizedString::AXDateTimeFieldEmptyValueText);
 }
 
 DateTimeFieldElement::FieldOwner::~FieldOwner()
@@ -47,7 +47,7 @@
 }
 
 DateTimeFieldElement::DateTimeFieldElement(Document& document, FieldOwner& fieldOwner)
-    : HTMLSpanElement(spanTag, document)
+    : HTMLSpanElement(document)
     , m_fieldOwner(&fieldOwner)
 {
 }
@@ -157,7 +157,7 @@
     setAttribute(aria_valuemaxAttr, String::number(axMaximum));
 
     setAttribute(aria_helpAttr, axHelpText);
-    setPart(pseudo);
+    setPseudo(pseudo);
     appendChild(Text::create(document(), visibleValue()));
 }
 
diff --git a/Source/core/html/shadow/DateTimeFieldElements.cpp b/Source/core/html/shadow/DateTimeFieldElements.cpp
index 7949218..5353c04 100644
--- a/Source/core/html/shadow/DateTimeFieldElements.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElements.cpp
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
 
 static String queryString(WebLocalizedString::Name name)
 {
diff --git a/Source/core/html/shadow/DetailsMarkerControl.cpp b/Source/core/html/shadow/DetailsMarkerControl.cpp
index 2056e1a..f3f2adb 100644
--- a/Source/core/html/shadow/DetailsMarkerControl.cpp
+++ b/Source/core/html/shadow/DetailsMarkerControl.cpp
@@ -40,7 +40,7 @@
 using namespace HTMLNames;
 
 DetailsMarkerControl::DetailsMarkerControl(Document& document)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
 {
 }
 
diff --git a/Source/core/html/shadow/DetailsMarkerControl.h b/Source/core/html/shadow/DetailsMarkerControl.h
index a86195f..118063e 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->setPart(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
+    element->setPseudo(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 e0845b7..2da1daa 100644
--- a/Source/core/html/shadow/HTMLContentElement.cpp
+++ b/Source/core/html/shadow/HTMLContentElement.cpp
@@ -42,20 +42,14 @@
 
 PassRefPtr<HTMLContentElement> HTMLContentElement::create(Document& document)
 {
-    return adoptRef(new HTMLContentElement(contentTag, document));
+    return adoptRef(new HTMLContentElement(document));
 }
 
-PassRefPtr<HTMLContentElement> HTMLContentElement::create(const QualifiedName& tagName, Document& document)
-{
-    return adoptRef(new HTMLContentElement(tagName, document));
-}
-
-HTMLContentElement::HTMLContentElement(const QualifiedName& name, Document& document)
-    : InsertionPoint(name, document)
+HTMLContentElement::HTMLContentElement(Document& document)
+    : InsertionPoint(contentTag, document)
     , m_shouldParseSelect(false)
     , m_isValidSelector(true)
 {
-    ASSERT(hasTagName(contentTag));
     ScriptWrappable::init(this);
 }
 
diff --git a/Source/core/html/shadow/HTMLContentElement.h b/Source/core/html/shadow/HTMLContentElement.h
index 064f08a..b8f0f4f 100644
--- a/Source/core/html/shadow/HTMLContentElement.h
+++ b/Source/core/html/shadow/HTMLContentElement.h
@@ -38,7 +38,6 @@
 
 class HTMLContentElement FINAL : public InsertionPoint {
 public:
-    static PassRefPtr<HTMLContentElement> create(const QualifiedName&, Document&);
     static PassRefPtr<HTMLContentElement> create(Document&);
 
     virtual ~HTMLContentElement();
@@ -51,7 +50,7 @@
     bool isSelectValid() const;
 
 private:
-    HTMLContentElement(const QualifiedName&, Document&);
+    explicit HTMLContentElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/html/shadow/HTMLShadowElement.cpp b/Source/core/html/shadow/HTMLShadowElement.cpp
index ac51472..edfba07 100644
--- a/Source/core/html/shadow/HTMLShadowElement.cpp
+++ b/Source/core/html/shadow/HTMLShadowElement.cpp
@@ -38,16 +38,15 @@
 
 class Document;
 
-inline HTMLShadowElement::HTMLShadowElement(const QualifiedName& tagName, Document& document)
-    : InsertionPoint(tagName, document)
+inline HTMLShadowElement::HTMLShadowElement(Document& document)
+    : InsertionPoint(HTMLNames::shadowTag, document)
 {
-    ASSERT(hasTagName(HTMLNames::shadowTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLShadowElement> HTMLShadowElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLShadowElement> HTMLShadowElement::create(Document& document)
 {
-    return adoptRef(new HTMLShadowElement(tagName, document));
+    return adoptRef(new HTMLShadowElement(document));
 }
 
 HTMLShadowElement::~HTMLShadowElement()
diff --git a/Source/core/html/shadow/HTMLShadowElement.h b/Source/core/html/shadow/HTMLShadowElement.h
index 24ef4c6..77741ec 100644
--- a/Source/core/html/shadow/HTMLShadowElement.h
+++ b/Source/core/html/shadow/HTMLShadowElement.h
@@ -38,14 +38,14 @@
 
 class HTMLShadowElement FINAL : public InsertionPoint {
 public:
-    static PassRefPtr<HTMLShadowElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLShadowElement> create(Document&);
 
     virtual ~HTMLShadowElement();
 
     ShadowRoot* olderShadowRoot();
 
 private:
-    HTMLShadowElement(const QualifiedName&, Document&);
+    explicit HTMLShadowElement(Document&);
     virtual InsertionNotificationRequest insertedInto(ContainerNode* insertionPoint) OVERRIDE;
 };
 
diff --git a/Source/core/html/shadow/MediaControlElementTypes.cpp b/Source/core/html/shadow/MediaControlElementTypes.cpp
index eca65c9..dc7f986 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.cpp
+++ b/Source/core/html/shadow/MediaControlElementTypes.cpp
@@ -103,7 +103,7 @@
 // ----------------------------
 
 MediaControlDivElement::MediaControlDivElement(Document& document, MediaControlElementType displayType)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
     , MediaControlElement(displayType, this)
 {
 }
@@ -111,7 +111,7 @@
 // ----------------------------
 
 MediaControlInputElement::MediaControlInputElement(Document& document, MediaControlElementType displayType)
-    : HTMLInputElement(inputTag, document, 0, false)
+    : HTMLInputElement(document, 0, false)
     , MediaControlElement(displayType, this)
 {
 }
diff --git a/Source/core/html/shadow/MediaControlElementTypes.h b/Source/core/html/shadow/MediaControlElementTypes.h
index a2304fd..6293e6d 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& part() const = 0;
+    virtual const AtomicString& pseudo() 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 8b8fb4b..89ee3f5 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -34,12 +34,13 @@
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/DOMTokenList.h"
 #include "core/dom/FullscreenElementStack.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/events/MouseEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/shadow/MediaControls.h"
 #include "core/html/track/TextTrack.h"
-#include "core/html/track/VTTRegionList.h"
+#include "core/html/track/vtt/VTTRegionList.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
@@ -74,7 +75,7 @@
     return adoptRef(new MediaControlPanelElement(document));
 }
 
-const AtomicString& MediaControlPanelElement::part() const
+const AtomicString& MediaControlPanelElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-panel", AtomicString::ConstructFromLiteral));
     return id;
@@ -257,7 +258,7 @@
     return adoptRef(new MediaControlPanelEnclosureElement(document));
 }
 
-const AtomicString& MediaControlPanelEnclosureElement::part() const
+const AtomicString& MediaControlPanelEnclosureElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-enclosure", AtomicString::ConstructFromLiteral));
     return id;
@@ -276,7 +277,7 @@
     return adoptRef(new MediaControlOverlayEnclosureElement(document));
 }
 
-const AtomicString& MediaControlOverlayEnclosureElement::part() const
+const AtomicString& MediaControlOverlayEnclosureElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-enclosure", AtomicString::ConstructFromLiteral));
     return id;
@@ -308,7 +309,7 @@
     MediaControlMuteButtonElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlPanelMuteButtonElement::part() const
+const AtomicString& MediaControlPanelMuteButtonElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-mute-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -329,7 +330,7 @@
     return button.release();
 }
 
-const AtomicString& MediaControlVolumeSliderMuteButtonElement::part() const
+const AtomicString& MediaControlVolumeSliderMuteButtonElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider-mute-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -368,7 +369,7 @@
     setDisplayType(mediaController()->canPlay() ? MediaPlayButton : MediaPauseButton);
 }
 
-const AtomicString& MediaControlPlayButtonElement::part() const
+const AtomicString& MediaControlPlayButtonElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-play-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -407,7 +408,7 @@
         hide();
 }
 
-const AtomicString& MediaControlOverlayPlayButtonElement::part() const
+const AtomicString& MediaControlOverlayPlayButtonElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-play-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -452,7 +453,7 @@
     HTMLInputElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlToggleClosedCaptionsButtonElement::part() const
+const AtomicString& MediaControlToggleClosedCaptionsButtonElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-toggle-closed-captions-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -518,11 +519,11 @@
 
 void MediaControlTimelineElement::setDuration(double duration)
 {
-    setAttribute(maxAttr, String::number(std::isfinite(duration) ? duration : 0));
+    setFloatingPointAttribute(maxAttr, std::isfinite(duration) ? duration : 0);
 }
 
 
-const AtomicString& MediaControlTimelineElement::part() const
+const AtomicString& MediaControlTimelineElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-timeline", AtomicString::ConstructFromLiteral));
     return id;
@@ -545,7 +546,7 @@
     return slider.release();
 }
 
-const AtomicString& MediaControlPanelVolumeSliderElement::part() const
+const AtomicString& MediaControlPanelVolumeSliderElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider", AtomicString::ConstructFromLiteral));
     return id;
@@ -587,7 +588,7 @@
     HTMLInputElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlFullscreenButtonElement::part() const
+const AtomicString& MediaControlFullscreenButtonElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-fullscreen-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -616,7 +617,7 @@
     return id;
 }
 
-const AtomicString& MediaControlTimeRemainingDisplayElement::part() const
+const AtomicString& MediaControlTimeRemainingDisplayElement::pseudo() const
 {
     return getMediaControlTimeRemainingDisplayElementShadowPseudoId();
 }
@@ -639,7 +640,7 @@
     return id;
 }
 
-const AtomicString& MediaControlCurrentTimeDisplayElement::part() const
+const AtomicString& MediaControlCurrentTimeDisplayElement::pseudo() const
 {
     return getMediaControlCurrentTimeDisplayElementShadowPseudoId();
 }
@@ -670,7 +671,7 @@
     return id;
 }
 
-const AtomicString& MediaControlTextTrackContainerElement::part() const
+const AtomicString& MediaControlTextTrackContainerElement::pseudo() const
 {
     return textTrackContainerElementShadowPseudoId();
 }
@@ -734,29 +735,7 @@
         if (!cue->track() || !cue->track()->isRendered() || !cue->isActive())
             continue;
 
-        RefPtr<TextTrackCueBox> displayBox = cue->getDisplayTree(m_videoDisplaySize.size());
-        VTTRegion* region = 0;
-        if (cue->track()->regions())
-            region = cue->track()->regions()->getRegionById(cue->regionId());
-
-        if (!region) {
-            // If cue has an empty text track cue region identifier or there is no
-            // WebVTT region whose region identifier is identical to cue's text
-            // track cue region identifier, run the following substeps:
-            if (displayBox->hasChildNodes() && !contains(displayBox.get()))
-                // Note: the display tree of a cue is removed when the active flag of the cue is unset.
-                appendChild(displayBox);
-        } else {
-            // Let region be the WebVTT region whose region identifier
-            // matches the text track cue region identifier of cue.
-            RefPtr<HTMLDivElement> regionNode = region->getDisplayTree(document());
-
-            // Append the region to the viewport, if it was not already.
-            if (!contains(regionNode.get()))
-                appendChild(regionNode);
-
-            region->appendTextTrackCueBox(displayBox);
-        }
+        cue->updateDisplay(m_videoDisplaySize.size(), *this);
     }
 
     // 11. Return output.
diff --git a/Source/core/html/shadow/MediaControlElements.h b/Source/core/html/shadow/MediaControlElements.h
index e53002d..3d631db 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& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     void startDrag(const LayoutPoint& eventLocation);
@@ -84,7 +84,7 @@
 
 private:
     explicit MediaControlPanelEnclosureElement(Document&);
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
 };
 
 // ----------------------------
@@ -95,7 +95,7 @@
 
 private:
     explicit MediaControlOverlayEnclosureElement(Document&);
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
 };
 
 // ----------------------------
@@ -109,7 +109,7 @@
 private:
     explicit MediaControlPanelMuteButtonElement(Document&, MediaControls*);
 
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     MediaControls* m_controls;
@@ -123,7 +123,7 @@
 
 private:
     explicit MediaControlVolumeSliderMuteButtonElement(Document&);
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
 };
 
 
@@ -139,7 +139,7 @@
 private:
     explicit MediaControlPlayButtonElement(Document&);
 
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -154,7 +154,7 @@
 private:
     explicit MediaControlOverlayPlayButtonElement(Document&);
 
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -171,7 +171,7 @@
 private:
     explicit MediaControlToggleClosedCaptionsButtonElement(Document&, MediaControls*);
 
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -189,7 +189,7 @@
 private:
     explicit MediaControlTimelineElement(Document&, MediaControls*);
 
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     MediaControls* m_controls;
@@ -208,7 +208,7 @@
 private:
     explicit MediaControlFullscreenButtonElement(Document&);
 
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -220,7 +220,7 @@
 
 private:
     explicit MediaControlPanelVolumeSliderElement(Document&);
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
 };
 
 // ----------------------------
@@ -231,7 +231,7 @@
 
 private:
     explicit MediaControlTimeRemainingDisplayElement(Document&);
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
 };
 
 // ----------------------------
@@ -242,7 +242,7 @@
 
 private:
     explicit MediaControlCurrentTimeDisplayElement(Document&);
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
 };
 
 // ----------------------------
@@ -257,7 +257,7 @@
 
 private:
     explicit MediaControlTextTrackContainerElement(Document&);
-    virtual const AtomicString& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*);
 
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index 45559d9..0e2fa81 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -34,7 +34,7 @@
 static const double timeWithoutMouseMovementBeforeHidingFullscreenControls = 3;
 
 MediaControls::MediaControls(Document& document)
-    : HTMLDivElement(HTMLNames::divTag, document)
+    : HTMLDivElement(document)
     , m_mediaController(0)
     , m_panel(0)
     , m_textDisplayContainer(0)
@@ -331,7 +331,7 @@
     m_hideFullscreenControlsTimer.stop();
 }
 
-const AtomicString& MediaControls::part() const
+const AtomicString& MediaControls::pseudo() 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 ff7b39d..d5b5884 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& part() const;
+    virtual const AtomicString& pseudo() const;
 };
 
 inline MediaControls* toMediaControls(Node* node)
diff --git a/Source/core/html/shadow/MediaControlsChromium.cpp b/Source/core/html/shadow/MediaControlsChromium.cpp
index d4fadf7..d1d4ccb 100644
--- a/Source/core/html/shadow/MediaControlsChromium.cpp
+++ b/Source/core/html/shadow/MediaControlsChromium.cpp
@@ -69,68 +69,68 @@
 
     RefPtr<MediaControlPanelElement> panel = MediaControlPanelElement::create(document);
 
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
 
     RefPtr<MediaControlPlayButtonElement> playButton = MediaControlPlayButtonElement::create(document);
     m_playButton = playButton.get();
-    panel->appendChild(playButton.release(), es);
-    if (es.hadException())
+    panel->appendChild(playButton.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     RefPtr<MediaControlTimelineElement> timeline = MediaControlTimelineElement::create(document, this);
     m_timeline = timeline.get();
-    panel->appendChild(timeline.release(), es);
-    if (es.hadException())
+    panel->appendChild(timeline.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     RefPtr<MediaControlCurrentTimeDisplayElement> currentTimeDisplay = MediaControlCurrentTimeDisplayElement::create(document);
     m_currentTimeDisplay = currentTimeDisplay.get();
     m_currentTimeDisplay->hide();
-    panel->appendChild(currentTimeDisplay.release(), es);
-    if (es.hadException())
+    panel->appendChild(currentTimeDisplay.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     RefPtr<MediaControlTimeRemainingDisplayElement> durationDisplay = MediaControlTimeRemainingDisplayElement::create(document);
     m_durationDisplay = durationDisplay.get();
-    panel->appendChild(durationDisplay.release(), es);
-    if (es.hadException())
+    panel->appendChild(durationDisplay.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     RefPtr<MediaControlPanelMuteButtonElement> panelMuteButton = MediaControlPanelMuteButtonElement::create(document, this);
     m_panelMuteButton = panelMuteButton.get();
-    panel->appendChild(panelMuteButton.release(), es);
-    if (es.hadException())
+    panel->appendChild(panelMuteButton.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     RefPtr<MediaControlPanelVolumeSliderElement> slider = MediaControlPanelVolumeSliderElement::create(document);
     m_volumeSlider = slider.get();
     m_volumeSlider->setClearMutedOnUserInteraction(true);
-    panel->appendChild(slider.release(), es);
-    if (es.hadException())
+    panel->appendChild(slider.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     if (RenderTheme::theme().supportsClosedCaptioning()) {
         RefPtr<MediaControlToggleClosedCaptionsButtonElement> toggleClosedCaptionsButton = MediaControlToggleClosedCaptionsButtonElement::create(document, this);
         m_toggleClosedCaptionsButton = toggleClosedCaptionsButton.get();
-        panel->appendChild(toggleClosedCaptionsButton.release(), es);
-        if (es.hadException())
+        panel->appendChild(toggleClosedCaptionsButton.release(), exceptionState);
+        if (exceptionState.hadException())
             return false;
     }
 
     RefPtr<MediaControlFullscreenButtonElement> fullscreenButton = MediaControlFullscreenButtonElement::create(document);
     m_fullScreenButton = fullscreenButton.get();
-    panel->appendChild(fullscreenButton.release(), es);
-    if (es.hadException())
+    panel->appendChild(fullscreenButton.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     m_panel = panel.get();
-    enclosure->appendChild(panel.release(), es);
-    if (es.hadException())
+    enclosure->appendChild(panel.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     m_enclosure = enclosure.get();
-    appendChild(enclosure.release(), es);
-    if (es.hadException())
+    appendChild(enclosure.release(), exceptionState);
+    if (exceptionState.hadException())
         return false;
 
     return true;
diff --git a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp b/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
index 1585d86..f81c930 100644
--- a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
+++ b/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
@@ -50,18 +50,18 @@
 
     RefPtr<MediaControlsChromiumAndroid> controls = adoptRef(new MediaControlsChromiumAndroid(document));
 
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
 
     RefPtr<MediaControlOverlayEnclosureElement> overlayEnclosure = MediaControlOverlayEnclosureElement::create(document);
     RefPtr<MediaControlOverlayPlayButtonElement> overlayPlayButton = MediaControlOverlayPlayButtonElement::create(document);
     controls->m_overlayPlayButton = overlayPlayButton.get();
-    overlayEnclosure->appendChild(overlayPlayButton.release(), es);
-    if (es.hadException())
+    overlayEnclosure->appendChild(overlayPlayButton.release(), exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     controls->m_overlayEnclosure = overlayEnclosure.get();
-    controls->appendChild(overlayEnclosure.release(), es);
-    if (es.hadException())
+    controls->appendChild(overlayEnclosure.release(), exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     if (controls->initializeControls(document))
diff --git a/Source/core/html/shadow/MeterShadowElement.cpp b/Source/core/html/shadow/MeterShadowElement.cpp
index 0462983..a39c29c 100644
--- a/Source/core/html/shadow/MeterShadowElement.cpp
+++ b/Source/core/html/shadow/MeterShadowElement.cpp
@@ -43,7 +43,7 @@
 using namespace HTMLNames;
 
 inline MeterShadowElement::MeterShadowElement(Document& document)
-    : HTMLDivElement(HTMLNames::divTag, document)
+    : HTMLDivElement(document)
 {
 }
 
@@ -66,7 +66,7 @@
 PassRefPtr<MeterInnerElement> MeterInnerElement::create(Document& document)
 {
     RefPtr<MeterInnerElement> element = adoptRef(new MeterInnerElement(document));
-    element->setPart(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
+    element->setPseudo(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->setPart(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
+    element->setPseudo(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 30bbd9c..c15bfdc 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() { setPart(valuePseudoId()); }
+    void updatePseudo() { setPseudo(valuePseudoId()); }
 
 private:
     MeterValueElement(Document&);
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
index a71d2a3..ffca7e3 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
@@ -47,7 +47,7 @@
 using namespace HTMLNames;
 
 PasswordGeneratorButtonElement::PasswordGeneratorButtonElement(Document& document)
-    : HTMLDivElement(HTMLNames::divTag, document)
+    : HTMLDivElement(document)
     , m_isInHoverState(false)
 {
     setHasCustomStyleCallbacks();
diff --git a/Source/core/html/shadow/PickerIndicatorElement.cpp b/Source/core/html/shadow/PickerIndicatorElement.cpp
index ffdc6dd..40aec28 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.cpp
+++ b/Source/core/html/shadow/PickerIndicatorElement.cpp
@@ -45,7 +45,7 @@
 using namespace HTMLNames;
 
 inline PickerIndicatorElement::PickerIndicatorElement(Document& document, PickerIndicatorOwner& pickerIndicatorOwner)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
     , m_pickerIndicatorOwner(&pickerIndicatorOwner)
 {
 }
@@ -53,7 +53,7 @@
 PassRefPtr<PickerIndicatorElement> PickerIndicatorElement::create(Document& document, PickerIndicatorOwner& pickerIndicatorOwner)
 {
     RefPtr<PickerIndicatorElement> element = adoptRef(new PickerIndicatorElement(document, pickerIndicatorOwner));
-    element->setPart(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
+    element->setPseudo(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::pickerIndicator());
     return element.release();
 }
@@ -100,6 +100,12 @@
     m_pickerIndicatorOwner->pickerIndicatorChooseValue(value);
 }
 
+void PickerIndicatorElement::didChooseValue(double value)
+{
+    if (m_pickerIndicatorOwner)
+        m_pickerIndicatorOwner->pickerIndicatorChooseValue(value);
+}
+
 void PickerIndicatorElement::didEndChooser()
 {
     m_chooser.clear();
diff --git a/Source/core/html/shadow/PickerIndicatorElement.h b/Source/core/html/shadow/PickerIndicatorElement.h
index 2631c98..4f42297 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.h
+++ b/Source/core/html/shadow/PickerIndicatorElement.h
@@ -49,7 +49,9 @@
     public:
         virtual ~PickerIndicatorOwner() { }
         virtual bool isPickerIndicatorOwnerDisabledOrReadOnly() const = 0;
+        // FIXME: Remove. Deprecated in favor of double version.
         virtual void pickerIndicatorChooseValue(const String&) = 0;
+        virtual void pickerIndicatorChooseValue(double) = 0;
         virtual bool setupDateTimeChooserParameters(DateTimeChooserParameters&) = 0;
     };
 
@@ -62,6 +64,7 @@
 
     // DateTimeChooserClient implementation.
     virtual void didChooseValue(const String&) OVERRIDE;
+    virtual void didChooseValue(double) OVERRIDE;
     virtual void didEndChooser() OVERRIDE;
 
 private:
diff --git a/Source/core/html/shadow/ProgressShadowElement.cpp b/Source/core/html/shadow/ProgressShadowElement.cpp
index 2de1161..50c8d1d 100644
--- a/Source/core/html/shadow/ProgressShadowElement.cpp
+++ b/Source/core/html/shadow/ProgressShadowElement.cpp
@@ -41,7 +41,7 @@
 using namespace HTMLNames;
 
 ProgressShadowElement::ProgressShadowElement(Document& document)
-    : HTMLDivElement(HTMLNames::divTag, document)
+    : HTMLDivElement(document)
 {
 }
 
diff --git a/Source/core/html/shadow/SliderThumbElement.cpp b/Source/core/html/shadow/SliderThumbElement.cpp
index bead464..70dbfb4 100644
--- a/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/Source/core/html/shadow/SliderThumbElement.cpp
@@ -196,7 +196,7 @@
 // --------------------------------
 
 inline SliderThumbElement::SliderThumbElement(Document& document)
-    : HTMLDivElement(HTMLNames::divTag, document)
+    : HTMLDivElement(document)
     , m_inDragMode(false)
 {
 }
@@ -412,7 +412,7 @@
     return mediaSliderThumb;
 }
 
-const AtomicString& SliderThumbElement::part() const
+const AtomicString& SliderThumbElement::pseudo() const
 {
     HTMLInputElement* input = hostInput();
     if (!input)
@@ -435,7 +435,7 @@
 // --------------------------------
 
 inline SliderContainerElement::SliderContainerElement(Document& document)
-    : HTMLDivElement(HTMLNames::divTag, document)
+    : HTMLDivElement(document)
 {
 }
 
@@ -449,7 +449,7 @@
     return new RenderSliderContainer(this);
 }
 
-const AtomicString& SliderContainerElement::part() const
+const AtomicString& SliderContainerElement::pseudo() 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 1c625dd..b1a1561 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& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() const OVERRIDE;
     HTMLInputElement* hostInput() const;
     void setPositionFromPoint(const LayoutPoint&);
 
@@ -105,7 +105,7 @@
 private:
     SliderContainerElement(Document&);
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual const AtomicString& part() const;
+    virtual const AtomicString& pseudo() const;
 };
 
 }
diff --git a/Source/core/html/shadow/SpinButtonElement.cpp b/Source/core/html/shadow/SpinButtonElement.cpp
index c088512..173114f 100644
--- a/Source/core/html/shadow/SpinButtonElement.cpp
+++ b/Source/core/html/shadow/SpinButtonElement.cpp
@@ -44,7 +44,7 @@
 using namespace HTMLNames;
 
 inline SpinButtonElement::SpinButtonElement(Document& document, SpinButtonOwner& spinButtonOwner)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
     , m_spinButtonOwner(&spinButtonOwner)
     , m_capturing(false)
     , m_upDownState(Indeterminate)
@@ -56,7 +56,7 @@
 PassRefPtr<SpinButtonElement> SpinButtonElement::create(Document& document, SpinButtonOwner& spinButtonOwner)
 {
     RefPtr<SpinButtonElement> element = adoptRef(new SpinButtonElement(document, spinButtonOwner));
-    element->setPart(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
+    element->setPseudo(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 93a28d6..a19fef2 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -49,7 +49,7 @@
 using namespace HTMLNames;
 
 TextControlInnerContainer::TextControlInnerContainer(Document& document)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
 {
 }
 
@@ -68,7 +68,7 @@
 // ---------------------------
 
 EditingViewPortElement::EditingViewPortElement(Document& document)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
 {
     setHasCustomStyleCallbacks();
 }
@@ -105,7 +105,7 @@
 // ---------------------------
 
 inline TextControlInnerTextElement::TextControlInnerTextElement(Document& document)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
 {
     setHasCustomStyleCallbacks();
 }
@@ -153,7 +153,7 @@
 // ----------------------------
 
 inline SearchFieldDecorationElement::SearchFieldDecorationElement(Document& document)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
 {
 }
 
@@ -164,7 +164,7 @@
     return element.release();
 }
 
-const AtomicString& SearchFieldDecorationElement::part() const
+const AtomicString& SearchFieldDecorationElement::pseudo() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, resultsDecorationId, ("-webkit-search-results-decoration", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, decorationId, ("-webkit-search-decoration", AtomicString::ConstructFromLiteral));
@@ -201,7 +201,7 @@
 // ----------------------------
 
 inline SearchFieldCancelButtonElement::SearchFieldCancelButtonElement(Document& document)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
     , m_capturing(false)
 {
 }
@@ -209,7 +209,7 @@
 PassRefPtr<SearchFieldCancelButtonElement> SearchFieldCancelButtonElement::create(Document& document)
 {
     RefPtr<SearchFieldCancelButtonElement> element = adoptRef(new SearchFieldCancelButtonElement(document));
-    element->setPart(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
+    element->setPseudo(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::clearButton());
     return element.release();
 }
@@ -278,7 +278,7 @@
 #if ENABLE(INPUT_SPEECH)
 
 inline InputFieldSpeechButtonElement::InputFieldSpeechButtonElement(Document& document)
-    : HTMLDivElement(divTag, document)
+    : HTMLDivElement(document)
     , m_capturing(false)
     , m_state(Idle)
     , m_listenerId(0)
@@ -298,7 +298,7 @@
 PassRefPtr<InputFieldSpeechButtonElement> InputFieldSpeechButtonElement::create(Document& document)
 {
     RefPtr<InputFieldSpeechButtonElement> element = adoptRef(new InputFieldSpeechButtonElement(document));
-    element->setPart(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
+    element->setPseudo(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::speechButton());
     return element.release();
 }
diff --git a/Source/core/html/shadow/TextControlInnerElements.h b/Source/core/html/shadow/TextControlInnerElements.h
index e21f5b7..711f5ef 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& part() const OVERRIDE;
+    virtual const AtomicString& pseudo() 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 bea20e7..bd03d64 100644
--- a/Source/core/html/track/InbandTextTrack.cpp
+++ b/Source/core/html/track/InbandTextTrack.cpp
@@ -27,42 +27,46 @@
 #include "core/html/track/InbandTextTrack.h"
 
 #include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/html/track/TextTrackCue.h"
-#include "core/platform/graphics/InbandTextTrackPrivate.h"
+#include "core/html/track/vtt/VTTCue.h"
 #include "platform/Logging.h"
+#include "public/platform/WebInbandTextTrack.h"
+#include "public/platform/WebString.h"
 #include "wtf/UnusedParam.h"
 #include <math.h>
 
+using blink::WebInbandTextTrack;
+using blink::WebString;
+
 namespace WebCore {
 
-PassRefPtr<InbandTextTrack> InbandTextTrack::create(Document& document, TextTrackClient* client, PassRefPtr<InbandTextTrackPrivate> playerPrivate)
+PassRefPtr<InbandTextTrack> InbandTextTrack::create(Document& document, TextTrackClient* client, WebInbandTextTrack* webTrack)
 {
-    return adoptRef(new InbandTextTrack(document, client, playerPrivate));
+    return adoptRef(new InbandTextTrack(document, client, webTrack));
 }
 
-InbandTextTrack::InbandTextTrack(Document& document, TextTrackClient* client, PassRefPtr<InbandTextTrackPrivate> tracksPrivate)
-    : TextTrack(document, client, emptyString(), tracksPrivate->label(), tracksPrivate->language(), InBand)
-    , m_private(tracksPrivate)
+InbandTextTrack::InbandTextTrack(Document& document, TextTrackClient* client, WebInbandTextTrack* webTrack)
+    : TextTrack(document, client, emptyAtom, webTrack->label(), webTrack->language(), InBand)
+    , m_webTrack(webTrack)
 {
-    m_private->setClient(this);
+    m_webTrack->setClient(this);
 
-    switch (m_private->kind()) {
-    case InbandTextTrackPrivate::Subtitles:
+    switch (m_webTrack->kind()) {
+    case WebInbandTextTrack::KindSubtitles:
         setKind(TextTrack::subtitlesKeyword());
         break;
-    case InbandTextTrackPrivate::Captions:
+    case WebInbandTextTrack::KindCaptions:
         setKind(TextTrack::captionsKeyword());
         break;
-    case InbandTextTrackPrivate::Descriptions:
+    case WebInbandTextTrack::KindDescriptions:
         setKind(TextTrack::descriptionsKeyword());
         break;
-    case InbandTextTrackPrivate::Chapters:
+    case WebInbandTextTrack::KindChapters:
         setKind(TextTrack::chaptersKeyword());
         break;
-    case InbandTextTrackPrivate::Metadata:
+    case WebInbandTextTrack::KindMetadata:
         setKind(TextTrack::metadataKeyword());
         break;
-    case InbandTextTrackPrivate::None:
+    case WebInbandTextTrack::KindNone:
     default:
         ASSERT_NOT_REACHED();
         break;
@@ -71,84 +75,29 @@
 
 InbandTextTrack::~InbandTextTrack()
 {
-    // Make sure m_private was cleared by trackRemoved() before destruction.
-    ASSERT(!m_private);
-}
-
-void InbandTextTrack::setMode(const AtomicString& mode)
-{
-    TextTrack::setMode(mode);
-
-    if (!m_private)
-        return;
-
-    if (mode == TextTrack::disabledKeyword())
-        m_private->setMode(InbandTextTrackPrivate::Disabled);
-    else if (mode == TextTrack::hiddenKeyword())
-        m_private->setMode(InbandTextTrackPrivate::Hidden);
-    else if (mode == TextTrack::showingKeyword())
-        m_private->setMode(InbandTextTrackPrivate::Showing);
-    else
-        ASSERT_NOT_REACHED();
-}
-
-bool InbandTextTrack::isClosedCaptions() const
-{
-    if (!m_private)
-        return false;
-
-    return m_private->isClosedCaptions();
-}
-
-bool InbandTextTrack::containsOnlyForcedSubtitles() const
-{
-    if (!m_private)
-        return false;
-
-    return m_private->containsOnlyForcedSubtitles();
-}
-
-bool InbandTextTrack::isMainProgramContent() const
-{
-    if (!m_private)
-        return false;
-
-    return m_private->isMainProgramContent();
-}
-
-bool InbandTextTrack::isEasyToRead() const
-{
-    if (!m_private)
-        return false;
-
-    return m_private->isEasyToRead();
+    // Make sure m_webTrack was cleared by trackRemoved() before destruction.
+    ASSERT(!m_webTrack);
 }
 
 size_t InbandTextTrack::inbandTrackIndex()
 {
-    ASSERT(m_private);
-    return m_private->textTrackIndex();
+    ASSERT(m_webTrack);
+    return m_webTrack->textTrackIndex();
 }
 
 void InbandTextTrack::trackRemoved()
 {
-    ASSERT(m_private);
-    m_private->setClient(0);
-    m_private = 0;
+    ASSERT(m_webTrack);
+    m_webTrack->setClient(0);
+    m_webTrack = 0;
     clearClient();
 }
 
-void InbandTextTrack::addWebVTTCue(InbandTextTrackPrivate* trackPrivate, double start, double end, const String& id, const String& content, const String& settings)
+void InbandTextTrack::addWebVTTCue(double start, double end, const WebString& id, const WebString& content, const WebString& settings)
 {
-    ASSERT_UNUSED(trackPrivate, trackPrivate == m_private);
-
-    RefPtr<TextTrackCue> cue = TextTrackCue::create(document(), start, end, content);
+    RefPtr<VTTCue> cue = VTTCue::create(document(), start, end, content);
     cue->setId(id);
-    cue->setCueSettings(settings);
-
-    if (hasCue(cue.get()))
-        return;
-
+    cue->parseSettings(settings);
     addCue(cue);
 }
 
diff --git a/Source/core/html/track/InbandTextTrack.h b/Source/core/html/track/InbandTextTrack.h
index 4ae6a1a..83948f0 100644
--- a/Source/core/html/track/InbandTextTrack.h
+++ b/Source/core/html/track/InbandTextTrack.h
@@ -27,35 +27,34 @@
 #define InbandTextTrack_h
 
 #include "core/html/track/TextTrack.h"
-#include "core/platform/graphics/InbandTextTrackPrivateClient.h"
+#include "public/platform/WebInbandTextTrackClient.h"
 #include "wtf/RefPtr.h"
 
+namespace blink {
+class WebInbandTextTrack;
+class WebString;
+}
+
 namespace WebCore {
 
 class Document;
-class InbandTextTrackPrivate;
 class MediaPlayer;
 class TextTrackCue;
 
-class InbandTextTrack : public TextTrack, public InbandTextTrackPrivateClient {
+class InbandTextTrack : public TextTrack, public blink::WebInbandTextTrackClient {
 public:
-    static PassRefPtr<InbandTextTrack> create(Document&, TextTrackClient*, PassRefPtr<InbandTextTrackPrivate>);
+    static PassRefPtr<InbandTextTrack> create(Document&, TextTrackClient*, blink::WebInbandTextTrack*);
     virtual ~InbandTextTrack();
 
-    virtual bool isClosedCaptions() const OVERRIDE;
-    virtual bool containsOnlyForcedSubtitles() const OVERRIDE;
-    virtual bool isMainProgramContent() const OVERRIDE;
-    virtual bool isEasyToRead() const OVERRIDE;
-    virtual void setMode(const AtomicString&) OVERRIDE;
     size_t inbandTrackIndex();
     void trackRemoved();
 
 private:
-    InbandTextTrack(Document&, TextTrackClient*, PassRefPtr<InbandTextTrackPrivate>);
+    InbandTextTrack(Document&, TextTrackClient*, blink::WebInbandTextTrack*);
 
-    virtual void addWebVTTCue(InbandTextTrackPrivate*, double, double, const String&, const String&, const String&) OVERRIDE;
+    virtual void addWebVTTCue(double, double, const blink::WebString&, const blink::WebString&, const blink::WebString&) OVERRIDE;
 
-    RefPtr<InbandTextTrackPrivate> m_private;
+    blink::WebInbandTextTrack* m_webTrack;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/track/LoadableTextTrack.cpp b/Source/core/html/track/LoadableTextTrack.cpp
index f8c7c75..40c4651 100644
--- a/Source/core/html/track/LoadableTextTrack.cpp
+++ b/Source/core/html/track/LoadableTextTrack.cpp
@@ -28,12 +28,12 @@
 
 #include "core/html/HTMLTrackElement.h"
 #include "core/html/track/TextTrackCueList.h"
-#include "core/html/track/VTTRegionList.h"
+#include "core/html/track/vtt/VTTRegionList.h"
 
 namespace WebCore {
 
-LoadableTextTrack::LoadableTextTrack(HTMLTrackElement* track, const String& kind, const String& label, const String& language)
-    : TextTrack(track->document(), track, kind, label, language, TrackElement)
+LoadableTextTrack::LoadableTextTrack(HTMLTrackElement* track)
+    : TextTrack(track->document(), track, emptyAtom, emptyAtom, emptyAtom, TrackElement)
     , m_trackElement(track)
     , m_loadTimer(this, &LoadableTextTrack::loadTimerFired)
     , m_isDefault(false)
@@ -97,7 +97,7 @@
 {
     ASSERT_UNUSED(loader, m_loader == loader);
 
-    Vector<RefPtr<TextTrackCue> > newCues;
+    Vector<RefPtr<VTTCue> > newCues;
     m_loader->getNewCues(newCues);
 
     if (!m_cues)
diff --git a/Source/core/html/track/LoadableTextTrack.h b/Source/core/html/track/LoadableTextTrack.h
index 7289320..487e7ca 100644
--- a/Source/core/html/track/LoadableTextTrack.h
+++ b/Source/core/html/track/LoadableTextTrack.h
@@ -37,9 +37,9 @@
 
 class LoadableTextTrack : public TextTrack, private TextTrackLoaderClient {
 public:
-    static PassRefPtr<LoadableTextTrack> create(HTMLTrackElement* track, const String& kind, const String& label, const String& language)
+    static PassRefPtr<LoadableTextTrack> create(HTMLTrackElement* track)
     {
-        return adoptRef(new LoadableTextTrack(track, kind, label, language));
+        return adoptRef(new LoadableTextTrack(track));
     }
     virtual ~LoadableTextTrack();
 
@@ -60,7 +60,7 @@
     virtual void cueLoadingCompleted(TextTrackLoader*, bool loadingFailed) OVERRIDE;
     virtual void newRegionsAvailable(TextTrackLoader*) OVERRIDE;
 
-    LoadableTextTrack(HTMLTrackElement*, const String& kind, const String& label, const String& language);
+    LoadableTextTrack(HTMLTrackElement*);
 
     void loadTimerFired(Timer<LoadableTextTrack>*);
 
diff --git a/Source/core/html/track/TextTrack.cpp b/Source/core/html/track/TextTrack.cpp
index 0d26419..92d89b7 100644
--- a/Source/core/html/track/TextTrack.cpp
+++ b/Source/core/html/track/TextTrack.cpp
@@ -33,14 +33,16 @@
 #include "core/html/track/TextTrack.h"
 
 #include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/html/HTMLMediaElement.h"
 #include "core/html/track/TextTrackCueList.h"
 #include "core/html/track/TextTrackList.h"
-#include "core/html/track/VTTRegion.h"
-#include "core/html/track/VTTRegionList.h"
+#include "core/html/track/vtt/VTTRegion.h"
+#include "core/html/track/vtt/VTTRegionList.h"
 
 namespace WebCore {
 
@@ -102,7 +104,7 @@
     , m_mediaElement(0)
     , m_label(label)
     , m_language(language)
-    , m_mode(disabledKeyword().string())
+    , m_mode(disabledKeyword())
     , m_client(client)
     , m_trackType(type)
     , m_readinessState(NotLoaded)
@@ -252,7 +254,7 @@
         m_client->textTrackAddCue(this, cue.get());
 }
 
-void TextTrack::removeCue(TextTrackCue* cue, ExceptionState& es)
+void TextTrack::removeCue(TextTrackCue* cue, ExceptionState& exceptionState)
 {
     if (!cue)
         return;
@@ -264,13 +266,13 @@
     // 1. If the given cue is not currently listed in the method's TextTrack
     // object's text track's text track list of cues, then throw a NotFoundError exception.
     if (cue->track() != this) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeCue", "TextTrack", "The specified cue is not listed in the TextTrack's list of cues."));
         return;
     }
 
     // 2. Remove cue from the method's TextTrack object's text track's text track list of cues.
     if (!m_cues || !m_cues->remove(cue)) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("removeCue", "TextTrack", "Failed to remove the specified cue."));
         return;
     }
 
@@ -330,7 +332,7 @@
     regionList->add(region);
 }
 
-void TextTrack::removeRegion(VTTRegion* region, ExceptionState &es)
+void TextTrack::removeRegion(VTTRegion* region, ExceptionState &exceptionState)
 {
     if (!region)
         return;
@@ -338,12 +340,12 @@
     // 1. If the given region is not currently listed in the method's TextTrack
     // object's text track list of regions, then throw a NotFoundError exception.
     if (region->track() != this) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeRegion", "TextTrack", "The specified region is not listed in the TextTrack's list of regions."));
         return;
     }
 
     if (!m_regions || !m_regions->remove(region)) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("removeRegion", "TextTrack", "Failed to remove the specified region."));
         return;
     }
 
@@ -417,73 +419,6 @@
     return m_renderedTrackIndex;
 }
 
-bool TextTrack::hasCue(TextTrackCue* cue)
-{
-    if (cue->startTime() < 0 || cue->endTime() < 0)
-        return false;
-
-    if (!m_cues || !m_cues->length())
-        return false;
-
-    size_t searchStart = 0;
-    size_t searchEnd = m_cues->length();
-
-    while (1) {
-        ASSERT(searchStart <= m_cues->length());
-        ASSERT(searchEnd <= m_cues->length());
-
-        TextTrackCue* existingCue;
-
-        // Cues in the TextTrackCueList are maintained in start time order.
-        if (searchStart == searchEnd) {
-            if (!searchStart)
-                return false;
-
-            // If there is more than one cue with the same start time, back up to first one so we
-            // consider all of them.
-            while (searchStart >= 2 && cue->startTime() == m_cues->item(searchStart - 2)->startTime())
-                --searchStart;
-
-            bool firstCompare = true;
-            while (1) {
-                if (!firstCompare)
-                    ++searchStart;
-                firstCompare = false;
-                if (searchStart > m_cues->length())
-                    return false;
-
-                existingCue = m_cues->item(searchStart - 1);
-                if (!existingCue || cue->startTime() > existingCue->startTime())
-                    return false;
-
-                if (*existingCue != *cue)
-                    continue;
-
-                return true;
-            }
-        }
-
-        size_t index = (searchStart + searchEnd) / 2;
-        existingCue = m_cues->item(index);
-        if (cue->startTime() < existingCue->startTime() || (cue->startTime() == existingCue->startTime() && cue->endTime() > existingCue->endTime()))
-            searchEnd = index;
-        else
-            searchStart = index + 1;
-    }
-
-    ASSERT_NOT_REACHED();
-    return false;
-}
-
-bool TextTrack::isMainProgramContent() const
-{
-    // "Main program" content is intrinsic to the presentation of the media file, regardless of locale. Content such as
-    // directors commentary is not "main program" because it is not essential for the presentation. HTML5 doesn't have
-    // a way to express this in a machine-reable form, it is typically done with the track label, so we assume that caption
-    // tracks are main content and all other track types are not.
-    return m_kind == captionsKeyword();
-}
-
 const AtomicString& TextTrack::interfaceName() const
 {
     return EventTargetNames::TextTrack;
diff --git a/Source/core/html/track/TextTrack.h b/Source/core/html/track/TextTrack.h
index e7e8833..469db02 100644
--- a/Source/core/html/track/TextTrack.h
+++ b/Source/core/html/track/TextTrack.h
@@ -85,7 +85,7 @@
     static const AtomicString& showingKeyword();
 
     AtomicString mode() const { return m_mode; }
-    virtual void setMode(const AtomicString&);
+    void setMode(const AtomicString&);
 
     enum ReadinessState { NotLoaded = 0, Loading = 1, Loaded = 2, FailedToLoad = 3 };
     ReadinessState readinessState() const { return m_readinessState; }
@@ -99,7 +99,6 @@
 
     void addCue(PassRefPtr<TextTrackCue>);
     void removeCue(TextTrackCue*, ExceptionState&);
-    bool hasCue(TextTrackCue*);
 
     VTTRegionList* regions();
     void addRegion(PassRefPtr<VTTRegion>);
@@ -113,12 +112,6 @@
     enum TextTrackType { TrackElement, AddTrack, InBand };
     TextTrackType trackType() const { return m_trackType; }
 
-    virtual bool isClosedCaptions() const { return false; }
-
-    virtual bool containsOnlyForcedSubtitles() const { return false; }
-    virtual bool isMainProgramContent() const;
-    virtual bool isEasyToRead() const { return false; }
-
     int trackIndex();
     void invalidateTrackIndex();
 
diff --git a/Source/core/html/track/TextTrackCue.cpp b/Source/core/html/track/TextTrackCue.cpp
index 1e40ea7..5e46ede 100644
--- a/Source/core/html/track/TextTrackCue.cpp
+++ b/Source/core/html/track/TextTrackCue.cpp
@@ -32,211 +32,48 @@
 #include "config.h"
 #include "core/html/track/TextTrackCue.h"
 
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
-#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/DocumentFragment.h"
 #include "core/events/Event.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLDivElement.h"
 #include "core/html/track/TextTrack.h"
 #include "core/html/track/TextTrackCueList.h"
-#include "core/html/track/VTTRegionList.h"
-#include "core/html/track/WebVTTElement.h"
-#include "core/html/track/WebVTTParser.h"
-#include "core/rendering/RenderTextTrackCue.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
 static const int invalidCueIndex = -1;
-static const int undefinedPosition = -1;
 
-static const CSSValueID displayWritingModeMap[] = {
-    CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
-};
-COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayWritingModeMap) == TextTrackCue::NumberOfWritingDirections,
-    displayWritingModeMap_has_wrong_size);
+// ----------------------------
 
-static const CSSValueID displayAlignmentMap[] = {
-    CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight
-};
-COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayAlignmentMap) == TextTrackCue::NumberOfAlignments,
-    displayAlignmentMap_has_wrong_size);
-
-static const String& startKeyword()
+TextTrackCueBox::TextTrackCueBox(Document& document)
+    : HTMLDivElement(document)
 {
-    DEFINE_STATIC_LOCAL(const String, start, ("start"));
-    return start;
-}
-
-static const String& middleKeyword()
-{
-    DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
-    return middle;
-}
-
-static const String& endKeyword()
-{
-    DEFINE_STATIC_LOCAL(const String, end, ("end"));
-    return end;
-}
-
-static const String& leftKeyword()
-{
-    DEFINE_STATIC_LOCAL(const String, left, ("left"));
-    return left;
-}
-
-static const String& rightKeyword()
-{
-    DEFINE_STATIC_LOCAL(const String, right, ("right"));
-    return right;
-}
-
-static const String& horizontalKeyword()
-{
-    return emptyString();
-}
-
-static const String& verticalGrowingLeftKeyword()
-{
-    DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
-    return verticalrl;
-}
-
-static const String& verticalGrowingRightKeyword()
-{
-    DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
-    return verticallr;
 }
 
 // ----------------------------
 
-TextTrackCueBox::TextTrackCueBox(Document& document, TextTrackCue* cue)
-    : HTMLDivElement(divTag, document)
-    , m_cue(cue)
+bool TextTrackCue::isInfiniteOrNonNumber(double value, const char* method, ExceptionState& exceptionState)
 {
-    setPart(textTrackCueBoxShadowPseudoId());
-}
-
-TextTrackCue* TextTrackCueBox::getCue() const
-{
-    return m_cue;
-}
-
-void TextTrackCueBox::applyCSSProperties(const IntSize&)
-{
-    // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
-    if (!m_cue->regionId().isEmpty()) {
-        setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
-        return;
+    if (!std::isfinite(value)) {
+        exceptionState.throwTypeError(ExceptionMessages::failedToSet(method, "TextTrackCue", ExceptionMessages::notAFiniteNumber(value)));
+        return true;
     }
-
-    // 3.5.1 On the (root) List of WebVTT Node Objects:
-
-    // the 'position' property must be set to 'absolute'
-    setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
-
-    //  the 'unicode-bidi' property must be set to 'plaintext'
-    setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
-
-    // the 'direction' property must be set to direction
-    setInlineStyleProperty(CSSPropertyDirection, m_cue->getCSSWritingDirection());
-
-    // the 'writing-mode' property must be set to writing-mode
-    setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue->getCSSWritingMode());
-
-    std::pair<float, float> position = m_cue->getCSSPosition();
-
-    // the 'top' property must be set to top,
-    setInlineStyleProperty(CSSPropertyTop, position.second, CSSPrimitiveValue::CSS_PERCENTAGE);
-
-    // the 'left' property must be set to left
-    setInlineStyleProperty(CSSPropertyLeft, position.first, CSSPrimitiveValue::CSS_PERCENTAGE);
-
-    // the 'width' property must be set to width, and the 'height' property  must be set to height
-    if (m_cue->vertical() == horizontalKeyword()) {
-        setInlineStyleProperty(CSSPropertyWidth, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
-        setInlineStyleProperty(CSSPropertyHeight, CSSValueAuto);
-    } else {
-        setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
-        setInlineStyleProperty(CSSPropertyHeight, static_cast<double>(m_cue->getCSSSize()),  CSSPrimitiveValue::CSS_PERCENTAGE);
-    }
-
-    // The 'text-align' property on the (root) List of WebVTT Node Objects must
-    // be set to the value in the second cell of the row of the table below
-    // whose first cell is the value of the corresponding cue's text track cue
-    // alignment:
-    setInlineStyleProperty(CSSPropertyTextAlign, m_cue->getCSSAlignment());
-
-    if (!m_cue->snapToLines()) {
-        // 10.13.1 Set up x and y:
-        // Note: x and y are set through the CSS left and top above.
-
-        // 10.13.2 Position the boxes in boxes such that the point x% along the
-        // width of the bounding box of the boxes in boxes is x% of the way
-        // across the width of the video's rendering area, and the point y%
-        // along the height of the bounding box of the boxes in boxes is y%
-        // of the way across the height of the video's rendering area, while
-        // maintaining the relative positions of the boxes in boxes to each
-        // other.
-        setInlineStyleProperty(CSSPropertyWebkitTransform,
-                String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));
-
-        setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
-    }
+    return false;
 }
 
-const AtomicString& TextTrackCueBox::textTrackCueBoxShadowPseudoId()
-{
-    DEFINE_STATIC_LOCAL(const AtomicString, trackDisplayBoxShadowPseudoId, ("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
-    return trackDisplayBoxShadowPseudoId;
-}
-
-RenderObject* TextTrackCueBox::createRenderer(RenderStyle*)
-{
-    return new RenderTextTrackCue(this);
-}
-
-// ----------------------------
-
-TextTrackCue::TextTrackCue(Document& document, double start, double end, const String& content)
+TextTrackCue::TextTrackCue(double start, double end)
     : m_startTime(start)
     , m_endTime(end)
-    , m_content(content)
-    , m_linePosition(undefinedPosition)
-    , m_computedLinePosition(undefinedPosition)
-    , m_textPosition(50)
-    , m_cueSize(100)
     , m_cueIndex(invalidCueIndex)
-    , m_writingDirection(Horizontal)
-    , m_cueAlignment(Middle)
-    , m_webVTTNodeTree(0)
     , m_track(0)
     , m_isActive(false)
     , m_pauseOnExit(false)
-    , m_snapToLines(true)
-    , m_cueBackgroundBox(HTMLDivElement::create(document))
-    , m_displayTreeShouldChange(true)
-    , m_displayDirection(CSSValueLtr)
-    , m_notifyRegion(true)
 {
-    ScriptWrappable::init(this);
 }
 
-TextTrackCue::~TextTrackCue()
+String TextTrackCue::toString() const
 {
-    displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
-}
-
-PassRefPtr<TextTrackCueBox> TextTrackCue::displayTreeInternal()
-{
-    if (!m_displayTree)
-        m_displayTree = TextTrackCueBox::create(document(), this);
-    return m_displayTree;
+    return String::format("%p id=%s interval=%f-->%f)", this, id().utf8().data(), startTime(), endTime());
 }
 
 void TextTrackCue::cueWillChange()
@@ -249,8 +86,6 @@
 {
     if (m_track)
         m_track->cueDidChange(this);
-
-    m_displayTreeShouldChange = true;
 }
 
 TextTrack* TextTrackCue::track() const
@@ -273,13 +108,11 @@
     cueDidChange();
 }
 
-void TextTrackCue::setStartTime(double value, ExceptionState& es)
+void TextTrackCue::setStartTime(double value, ExceptionState& exceptionState)
 {
     // NaN, Infinity and -Infinity values should trigger a TypeError.
-    if (std::isinf(value) || std::isnan(value)) {
-        es.throwUninformativeAndGenericTypeError();
+    if (isInfiniteOrNonNumber(value, "startTime", exceptionState))
         return;
-    }
 
     // TODO(93143): Add spec-compliant behavior for negative time values.
     if (m_startTime == value || value < 0)
@@ -290,13 +123,11 @@
     cueDidChange();
 }
 
-void TextTrackCue::setEndTime(double value, ExceptionState& es)
+void TextTrackCue::setEndTime(double value, ExceptionState& exceptionState)
 {
     // NaN, Infinity and -Infinity values should trigger a TypeError.
-    if (std::isinf(value) || std::isnan(value)) {
-        es.throwUninformativeAndGenericTypeError();
+    if (isInfiniteOrNonNumber(value, "endTime", exceptionState))
         return;
-    }
 
     // TODO(93143): Add spec-compliant behavior for negative time values.
     if (m_endTime == value || value < 0)
@@ -317,177 +148,6 @@
     cueDidChange();
 }
 
-const String& TextTrackCue::vertical() const
-{
-    switch (m_writingDirection) {
-    case Horizontal:
-        return horizontalKeyword();
-    case VerticalGrowingLeft:
-        return verticalGrowingLeftKeyword();
-    case VerticalGrowingRight:
-        return verticalGrowingRightKeyword();
-    default:
-        ASSERT_NOT_REACHED();
-        return emptyString();
-    }
-}
-
-void TextTrackCue::setVertical(const String& value, ExceptionState& es)
-{
-    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-vertical
-    // On setting, the text track cue writing direction must be set to the value given
-    // in the first cell of the row in the table above whose second cell is a
-    // case-sensitive match for the new value, if any. If none of the values match, then
-    // the user agent must instead throw a SyntaxError exception.
-
-    WritingDirection direction = m_writingDirection;
-    if (value == horizontalKeyword())
-        direction = Horizontal;
-    else if (value == verticalGrowingLeftKeyword())
-        direction = VerticalGrowingLeft;
-    else if (value == verticalGrowingRightKeyword())
-        direction = VerticalGrowingRight;
-    else
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
-
-    if (direction == m_writingDirection)
-        return;
-
-    cueWillChange();
-    m_writingDirection = direction;
-    cueDidChange();
-}
-
-void TextTrackCue::setSnapToLines(bool value)
-{
-    if (m_snapToLines == value)
-        return;
-
-    cueWillChange();
-    m_snapToLines = value;
-    cueDidChange();
-}
-
-void TextTrackCue::setLine(int position, ExceptionState& es)
-{
-    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-line
-    // On setting, if the text track cue snap-to-lines flag is not set, and the new
-    // value is negative or greater than 100, then throw an IndexSizeError exception.
-    if (!m_snapToLines && (position < 0 || position > 100)) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
-
-    // Otherwise, set the text track cue line position to the new value.
-    if (m_linePosition == position)
-        return;
-
-    cueWillChange();
-    m_linePosition = position;
-    m_computedLinePosition = calculateComputedLinePosition();
-    cueDidChange();
-}
-
-void TextTrackCue::setPosition(int position, ExceptionState& es)
-{
-    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-position
-    // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError exception.
-    // Otherwise, set the text track cue text position to the new value.
-    if (position < 0 || position > 100) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
-
-    // Otherwise, set the text track cue line position to the new value.
-    if (m_textPosition == position)
-        return;
-
-    cueWillChange();
-    m_textPosition = position;
-    cueDidChange();
-}
-
-void TextTrackCue::setSize(int size, ExceptionState& es)
-{
-    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-size
-    // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError
-    // exception. Otherwise, set the text track cue size to the new value.
-    if (size < 0 || size > 100) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
-
-    // Otherwise, set the text track cue line position to the new value.
-    if (m_cueSize == size)
-        return;
-
-    cueWillChange();
-    m_cueSize = size;
-    cueDidChange();
-}
-
-const String& TextTrackCue::align() const
-{
-    switch (m_cueAlignment) {
-    case Start:
-        return startKeyword();
-    case Middle:
-        return middleKeyword();
-    case End:
-        return endKeyword();
-    case Left:
-        return leftKeyword();
-    case Right:
-        return rightKeyword();
-    default:
-        ASSERT_NOT_REACHED();
-        return emptyString();
-    }
-}
-
-void TextTrackCue::setAlign(const String& value, ExceptionState& es)
-{
-    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-align
-    // On setting, the text track cue alignment must be set to the value given in the
-    // first cell of the row in the table above whose second cell is a case-sensitive
-    // match for the new value, if any. If none of the values match, then the user
-    // agent must instead throw a SyntaxError exception.
-
-    CueAlignment alignment = m_cueAlignment;
-    if (value == startKeyword())
-        alignment = Start;
-    else if (value == middleKeyword())
-        alignment = Middle;
-    else if (value == endKeyword())
-        alignment = End;
-    else if (value == leftKeyword())
-        alignment = Left;
-    else if (value == rightKeyword())
-        alignment = Right;
-    else
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
-
-    if (alignment == m_cueAlignment)
-        return;
-
-    cueWillChange();
-    m_cueAlignment = alignment;
-    cueDidChange();
-}
-
-void TextTrackCue::setText(const String& text)
-{
-    if (m_content == text)
-        return;
-
-    cueWillChange();
-    // Clear the document fragment but don't bother to create it again just yet as we can do that
-    // when it is requested.
-    m_webVTTNodeTree = 0;
-    m_content = text;
-    cueDidChange();
-}
-
 int TextTrackCue::cueIndex()
 {
     if (m_cueIndex == invalidCueIndex)
@@ -501,43 +161,6 @@
     m_cueIndex = invalidCueIndex;
 }
 
-void TextTrackCue::createWebVTTNodeTree()
-{
-    if (!m_webVTTNodeTree)
-        m_webVTTNodeTree = WebVTTParser::createDocumentFragmentFromCueText(document(), m_content);
-}
-
-void TextTrackCue::copyWebVTTNodeToDOMTree(ContainerNode* webVTTNode, ContainerNode* parent)
-{
-    for (Node* node = webVTTNode->firstChild(); node; node = node->nextSibling()) {
-        RefPtr<Node> clonedNode;
-        if (node->isWebVTTElement())
-            clonedNode = toWebVTTElement(node)->createEquivalentHTMLElement(&document());
-        else
-            clonedNode = node->cloneNode(false);
-        parent->appendChild(clonedNode);
-        if (node->isContainerNode())
-            copyWebVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode));
-    }
-}
-
-PassRefPtr<DocumentFragment> TextTrackCue::getCueAsHTML()
-{
-    createWebVTTNodeTree();
-    RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(document());
-    copyWebVTTNodeToDOMTree(m_webVTTNodeTree.get(), clonedFragment.get());
-    return clonedFragment.release();
-}
-
-PassRefPtr<DocumentFragment> TextTrackCue::createCueRenderingTree()
-{
-    RefPtr<DocumentFragment> clonedFragment;
-    createWebVTTNodeTree();
-    clonedFragment = DocumentFragment::create(document());
-    m_webVTTNodeTree->cloneChildNodes(clonedFragment.get());
-    return clonedFragment.release();
-}
-
 bool TextTrackCue::dispatchEvent(PassRefPtr<Event> event)
 {
     // When a TextTrack's mode is disabled: no cues are active, no events fired.
@@ -547,21 +170,6 @@
     return EventTarget::dispatchEvent(event);
 }
 
-void TextTrackCue::setRegionId(const String& regionId)
-{
-    if (m_regionId == regionId)
-        return;
-
-    cueWillChange();
-    m_regionId = regionId;
-    cueDidChange();
-}
-
-void TextTrackCue::notifyRegionWhenRemovingDisplayTree(bool notifyRegion)
-{
-    m_notifyRegion = notifyRegion;
-}
-
 bool TextTrackCue::isActive()
 {
     return m_isActive && track() && track()->mode() != TextTrack::disabledKeyword();
@@ -576,658 +184,9 @@
         removeDisplayTree();
 }
 
-int TextTrackCue::calculateComputedLinePosition()
-{
-    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position
-
-    // If the text track cue line position is numeric, then that is the text
-    // track cue computed line position.
-    if (m_linePosition != undefinedPosition)
-        return m_linePosition;
-
-    // If the text track cue snap-to-lines flag of the text track cue is not
-    // set, the text track cue computed line position is the value 100;
-    if (!m_snapToLines)
-        return 100;
-
-    // Otherwise, it is the value returned by the following algorithm:
-
-    // If cue is not associated with a text track, return -1 and abort these
-    // steps.
-    if (!track())
-        return -1;
-
-    // Let n be the number of text tracks whose text track mode is showing or
-    // showing by default and that are in the media element's list of text
-    // tracks before track.
-    int n = track()->trackIndexRelativeToRenderedTracks();
-
-    // Increment n by one.
-    n++;
-
-    // Negate n.
-    n = -n;
-
-    return n;
-}
-
-static bool isCueParagraphSeparator(UChar character)
-{
-    // Within a cue, paragraph boundaries are only denoted by Type B characters,
-    // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
-    return WTF::Unicode::category(character) & WTF::Unicode::Separator_Paragraph;
-}
-
-void TextTrackCue::determineTextDirection()
-{
-    DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
-    createWebVTTNodeTree();
-
-    // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
-    // concatenation of the values of each WebVTT Text Object in nodes, in a
-    // pre-order, depth-first traversal, excluding WebVTT Ruby Text Objects and
-    // their descendants.
-    StringBuilder paragraphBuilder;
-    for (Node* node = m_webVTTNodeTree->firstChild(); node; node = NodeTraversal::next(node, m_webVTTNodeTree.get())) {
-        if (!node->isTextNode() || node->localName() == rtTag)
-            continue;
-
-        paragraphBuilder.append(node->nodeValue());
-    }
-
-    String paragraph = paragraphBuilder.toString();
-    if (!paragraph.length())
-        return;
-
-    for (size_t i = 0; i < paragraph.length(); ++i) {
-        UChar current = paragraph[i];
-        if (!current || isCueParagraphSeparator(current))
-            return;
-
-        if (UChar current = paragraph[i]) {
-            WTF::Unicode::Direction charDirection = WTF::Unicode::direction(current);
-            if (charDirection == WTF::Unicode::LeftToRight) {
-                m_displayDirection = CSSValueLtr;
-                return;
-            }
-            if (charDirection == WTF::Unicode::RightToLeft
-                || charDirection == WTF::Unicode::RightToLeftArabic) {
-                m_displayDirection = CSSValueRtl;
-                return;
-            }
-        }
-    }
-}
-
-void TextTrackCue::calculateDisplayParameters()
-{
-    // Steps 10.2, 10.3
-    determineTextDirection();
-
-    // 10.4 If the text track cue writing direction is horizontal, then let
-    // block-flow be 'tb'. Otherwise, if the text track cue writing direction is
-    // vertical growing left, then let block-flow be 'lr'. Otherwise, the text
-    // track cue writing direction is vertical growing right; let block-flow be
-    // 'rl'.
-
-    // The above step is done through the writing direction static map.
-
-    // 10.5 Determine the value of maximum size for cue as per the appropriate
-    // rules from the following list:
-    int maximumSize = m_textPosition;
-    if ((m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueLtr)
-            || (m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueRtl)
-            || (m_writingDirection == Horizontal && m_cueAlignment == Left)
-            || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == Start || m_cueAlignment == Left))
-            || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == Start || m_cueAlignment == Left))) {
-        maximumSize = 100 - m_textPosition;
-    } else if ((m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueLtr)
-            || (m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueRtl)
-            || (m_writingDirection == Horizontal && m_cueAlignment == Right)
-            || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == End || m_cueAlignment == Right))
-            || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == End || m_cueAlignment == Right))) {
-        maximumSize = m_textPosition;
-    } else if (m_cueAlignment == Middle) {
-        maximumSize = m_textPosition <= 50 ? m_textPosition : (100 - m_textPosition);
-        maximumSize = maximumSize * 2;
-    } else {
-        ASSERT_NOT_REACHED();
-    }
-
-    // 10.6 If the text track cue size is less than maximum size, then let size
-    // be text track cue size. Otherwise, let size be maximum size.
-    m_displaySize = std::min(m_cueSize, maximumSize);
-
-    // FIXME: Understand why step 10.7 is missing (just a copy/paste error?)
-    // Could be done within a spec implementation check - http://crbug.com/301580
-
-    // 10.8 Determine the value of x-position or y-position for cue as per the
-    // appropriate rules from the following list:
-    if (m_writingDirection == Horizontal) {
-        switch (m_cueAlignment) {
-        case Start:
-            if (m_displayDirection == CSSValueLtr)
-                m_displayPosition.first = m_textPosition;
-            else
-                m_displayPosition.first = 100 - m_textPosition - m_displaySize;
-            break;
-        case End:
-            if (m_displayDirection == CSSValueRtl)
-                m_displayPosition.first = 100 - m_textPosition;
-            else
-                m_displayPosition.first = m_textPosition - m_displaySize;
-            break;
-        case Left:
-            if (m_displayDirection == CSSValueLtr)
-                m_displayPosition.first = m_textPosition;
-            else
-                m_displayPosition.first = 100 - m_textPosition;
-            break;
-        case Right:
-            if (m_displayDirection == CSSValueLtr)
-                m_displayPosition.first = m_textPosition - m_displaySize;
-            else
-                m_displayPosition.first = 100 - m_textPosition - m_displaySize;
-            break;
-        case Middle:
-            if (m_displayDirection == CSSValueLtr)
-                m_displayPosition.first = m_textPosition - m_displaySize / 2;
-            else
-                m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
-            break;
-        case NumberOfAlignments:
-            ASSERT_NOT_REACHED();
-        }
-    } else {
-        // Cases for m_writingDirection being VerticalGrowing{Left|Right}
-        switch (m_cueAlignment) {
-        case Start:
-        case Left:
-            m_displayPosition.second = m_textPosition;
-            break;
-        case End:
-        case Right:
-            m_displayPosition.second = m_textPosition - m_displaySize;
-            break;
-        case Middle:
-            m_displayPosition.second = m_textPosition - m_displaySize / 2;
-            break;
-        case NumberOfAlignments:
-            ASSERT_NOT_REACHED();
-        }
-    }
-
-    // A text track cue has a text track cue computed line position whose value
-    // is defined in terms of the other aspects of the cue.
-    m_computedLinePosition = calculateComputedLinePosition();
-
-    // 10.9 Determine the value of whichever of x-position or y-position is not
-    // yet calculated for cue as per the appropriate rules from the following
-    // list:
-    if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
-        m_displayPosition.second = 0;
-
-    if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
-        m_displayPosition.second = m_computedLinePosition;
-
-    if (m_snapToLines && m_displayPosition.first == undefinedPosition
-            && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
-        m_displayPosition.first = 0;
-
-    if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
-        m_displayPosition.first = m_computedLinePosition;
-}
-
-void TextTrackCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
-{
-    DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
-
-    bool isPastNode = true;
-    double currentTimestamp = previousTimestamp;
-    if (currentTimestamp > movieTime)
-        isPastNode = false;
-
-    for (Node* child = root->firstChild(); child; child = NodeTraversal::next(child, root)) {
-        if (child->nodeName() == timestampTag) {
-            unsigned position = 0;
-            String timestamp = child->nodeValue();
-            double currentTimestamp = WebVTTParser::collectTimeStamp(timestamp, &position);
-            ASSERT(currentTimestamp != -1);
-
-            if (currentTimestamp > movieTime)
-                isPastNode = false;
-        }
-
-        if (child->isWebVTTElement()) {
-            toWebVTTElement(child)->setIsPastNode(isPastNode);
-            // Make an elemenet id match a cue id for style matching purposes.
-            if (!m_id.isEmpty())
-                toElement(child)->setIdAttribute(m_id);
-        }
-    }
-}
-
-void TextTrackCue::updateDisplayTree(double movieTime)
-{
-    // The display tree may contain WebVTT timestamp objects representing
-    // timestamps (processing instructions), along with displayable nodes.
-
-    if (!track()->isRendered())
-      return;
-
-    // Clear the contents of the set.
-    m_cueBackgroundBox->removeChildren();
-
-    // Update the two sets containing past and future WebVTT objects.
-    RefPtr<DocumentFragment> referenceTree = createCueRenderingTree();
-    markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
-    m_cueBackgroundBox->appendChild(referenceTree, ASSERT_NO_EXCEPTION);
-}
-
-PassRefPtr<TextTrackCueBox> TextTrackCue::getDisplayTree(const IntSize& videoSize)
-{
-    RefPtr<TextTrackCueBox> displayTree = displayTreeInternal();
-    if (!m_displayTreeShouldChange || !track()->isRendered())
-        return displayTree;
-
-    // 10.1 - 10.10
-    calculateDisplayParameters();
-
-    // 10.11. Apply the terms of the CSS specifications to nodes within the
-    // following constraints, thus obtaining a set of CSS boxes positioned
-    // relative to an initial containing block:
-    displayTree->removeChildren();
-
-    // The document tree is the tree of WebVTT Node Objects rooted at nodes.
-
-    // The children of the nodes must be wrapped in an anonymous box whose
-    // 'display' property has the value 'inline'. This is the WebVTT cue
-    // background box.
-
-    // Note: This is contained by default in m_cueBackgroundBox.
-    m_cueBackgroundBox->setPart(cueShadowPseudoId());
-    displayTree->appendChild(m_cueBackgroundBox);
-
-    // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
-    // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose
-    // 'display' property has the value 'ruby-base'.
-
-    // FIXME(BUG 79916): Text runs must be wrapped according to the CSS
-    // line-wrapping rules, except that additionally, regardless of the value of
-    // the 'white-space' property, lines must be wrapped at the edge of their
-    // containing blocks, even if doing so requires splitting a word where there
-    // is no line breaking opportunity. (Thus, normally text wraps as needed,
-    // but if there is a particularly long word, it does not overflow as it
-    // normally would in CSS, it is instead forcibly wrapped at the box's edge.)
-    displayTree->applyCSSProperties(videoSize);
-
-    m_displayTreeShouldChange = false;
-
-    // 10.15. Let cue's text track cue display state have the CSS boxes in
-    // boxes.
-    return displayTree;
-}
-
-void TextTrackCue::removeDisplayTree()
-{
-    if (m_notifyRegion && m_track->regions()) {
-        // The region needs to be informed about the cue removal.
-        VTTRegion* region = m_track->regions()->getRegionById(m_regionId);
-        if (region)
-            region->willRemoveTextTrackCueBox(m_displayTree.get());
-    }
-
-    displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
-}
-
-std::pair<double, double> TextTrackCue::getPositionCoordinates() const
-{
-    // This method is used for setting x and y when snap to lines is not set.
-    std::pair<double, double> coordinates;
-
-    if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
-        coordinates.first = m_textPosition;
-        coordinates.second = m_computedLinePosition;
-
-        return coordinates;
-    }
-
-    if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
-        coordinates.first = 100 - m_textPosition;
-        coordinates.second = m_computedLinePosition;
-
-        return coordinates;
-    }
-
-    if (m_writingDirection == VerticalGrowingLeft) {
-        coordinates.first = 100 - m_computedLinePosition;
-        coordinates.second = m_textPosition;
-
-        return coordinates;
-    }
-
-    if (m_writingDirection == VerticalGrowingRight) {
-        coordinates.first = m_computedLinePosition;
-        coordinates.second = m_textPosition;
-
-        return coordinates;
-    }
-
-    ASSERT_NOT_REACHED();
-
-    return coordinates;
-}
-
-TextTrackCue::CueSetting TextTrackCue::settingName(const String& name)
-{
-    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"));
-    DEFINE_STATIC_LOCAL(const String, regionIdKeyword, ("region"));
-
-    if (name == verticalKeyword)
-        return Vertical;
-    else if (name == lineKeyword)
-        return Line;
-    else if (name == positionKeyword)
-        return Position;
-    else if (name == sizeKeyword)
-        return Size;
-    else if (name == alignKeyword)
-        return Align;
-    else if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && name == regionIdKeyword)
-        return RegionId;
-
-    return None;
-}
-
-void TextTrackCue::setCueSettings(const String& input)
-{
-    m_settings = input;
-    unsigned position = 0;
-
-    while (position < input.length()) {
-
-        // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
-        // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
-        while (position < input.length() && WebVTTParser::isValidSettingDelimiter(input[position]))
-            position++;
-        if (position >= input.length())
-            break;
-
-        // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
-        // the user agent must run the following steps:
-        // 1. Let settings be the result of splitting input on spaces.
-        // 2. For each token setting in the list settings, run the following substeps:
-        //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
-        //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
-        unsigned endOfSetting = position;
-        String setting = WebVTTParser::collectWord(input, &endOfSetting);
-        CueSetting name;
-        size_t colonOffset = setting.find(':', 1);
-        if (colonOffset == kNotFound || !colonOffset || colonOffset == setting.length() - 1)
-            goto NextSetting;
-
-        // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
-        name = settingName(setting.substring(0, colonOffset));
-
-        // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
-        position += colonOffset + 1;
-        if (position >= input.length())
-            break;
-
-        // 4. Run the appropriate substeps that apply for the value of name, as follows:
-        switch (name) {
-        case Vertical:
-            {
-            // If name is a case-sensitive match for "vertical"
-            // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
-            //    be vertical growing left.
-            String writingDirection = WebVTTParser::collectWord(input, &position);
-            if (writingDirection == verticalGrowingLeftKeyword())
-                m_writingDirection = VerticalGrowingLeft;
-
-            // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
-            //    direction be vertical growing right.
-            else if (writingDirection == verticalGrowingRightKeyword())
-                m_writingDirection = VerticalGrowingRight;
-            }
-            break;
-        case Line:
-            {
-            // 1-2 - Collect chars that are either '-', '%', or a digit.
-            // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
-            //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
-            //    to the step labeled next setting.
-            StringBuilder linePositionBuilder;
-            while (position < input.length() && (input[position] == '-' || input[position] == '%' || isASCIIDigit(input[position])))
-                linePositionBuilder.append(input[position++]);
-            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
-                break;
-
-            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
-            //    NINE (9), then jump to the step labeled next setting.
-            // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then
-            //    jump to the step labeled next setting.
-            // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
-            //    jump to the step labeled next setting.
-            String linePosition = linePositionBuilder.toString();
-            if (linePosition.find('-', 1) != kNotFound || linePosition.reverseFind("%", linePosition.length() - 2) != kNotFound)
-                break;
-
-            // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
-            //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
-            if (linePosition[0] == '-' && linePosition[linePosition.length() - 1] == '%')
-                break;
-
-            // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
-            //    let number be that number.
-            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
-            bool validNumber;
-            int number = linePosition.toInt(&validNumber);
-            if (!validNumber)
-                break;
-
-            // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
-            //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
-            // 8. Let cue's text track cue line position be number.
-            // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
-            //    snap-to-lines flag be false. Otherwise, let it be true.
-            if (linePosition[linePosition.length() - 1] == '%') {
-                if (number < 0 || number > 100)
-                    break;
-
-                // 10 - If '%' then set snap-to-lines flag to false.
-                m_snapToLines = false;
-            }
-
-            m_linePosition = number;
-            }
-            break;
-        case Position:
-            {
-            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the range
-            //    U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
-            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
-            //    then jump to the step labeled next setting.
-            String textPosition = WebVTTParser::collectDigits(input, &position);
-            if (textPosition.isEmpty())
-                break;
-            if (position >= input.length())
-                break;
-
-            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then jump
-            //    to the step labeled next setting.
-            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step labeled
-            //    next setting.
-            if (input[position++] != '%')
-                break;
-            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
-                break;
-
-            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
-            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
-            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
-            bool validNumber;
-            int number = textPosition.toInt(&validNumber);
-            if (!validNumber)
-                break;
-            if (number < 0 || number > 100)
-              break;
-
-            // 7. Let cue's text track cue text position be number.
-            m_textPosition = number;
-            }
-            break;
-        case Size:
-            {
-            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the
-            //    range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
-            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
-            //    NINE (9), then jump to the step labeled next setting.
-            String cueSize = WebVTTParser::collectDigits(input, &position);
-            if (cueSize.isEmpty())
-                break;
-            if (position >= input.length())
-                break;
-
-            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%),
-            //    then jump to the step labeled next setting.
-            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step
-            //    labeled next setting.
-            if (input[position++] != '%')
-                break;
-            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
-                break;
-
-            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
-            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
-            bool validNumber;
-            int number = cueSize.toInt(&validNumber);
-            if (!validNumber)
-                break;
-            if (number < 0 || number > 100)
-                break;
-
-            // 7. Let cue's text track cue size be number.
-            m_cueSize = number;
-            }
-            break;
-        case Align:
-            {
-            String cueAlignment = WebVTTParser::collectWord(input, &position);
-
-            // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
-            if (cueAlignment == startKeyword())
-                m_cueAlignment = Start;
-
-            // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
-            else if (cueAlignment == middleKeyword())
-                m_cueAlignment = Middle;
-
-            // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
-            else if (cueAlignment == endKeyword())
-                m_cueAlignment = End;
-
-            // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
-            else if (cueAlignment == leftKeyword())
-                m_cueAlignment = Left;
-
-            // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
-            else if (cueAlignment == rightKeyword())
-                m_cueAlignment = Right;
-            }
-            break;
-        case RegionId:
-            m_regionId = WebVTTParser::collectWord(input, &position);
-            break;
-        case None:
-            break;
-        }
-
-NextSetting:
-        position = endOfSetting;
-    }
-
-    // If cue's line position is not auto or cue's size is not 100 or cue's
-    // writing direction is not horizontal, but cue's region identifier is not
-    // the empty string, let cue's region identifier be the empty string.
-    if (m_regionId.isEmpty())
-        return;
-
-    if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
-        m_regionId = emptyString();
-}
-
-CSSValueID TextTrackCue::getCSSAlignment() const
-{
-    return displayAlignmentMap[m_cueAlignment];
-}
-
-CSSValueID TextTrackCue::getCSSWritingDirection() const
-{
-    return m_displayDirection;
-}
-
-CSSValueID TextTrackCue::getCSSWritingMode() const
-{
-    return displayWritingModeMap[m_writingDirection];
-}
-
-int TextTrackCue::getCSSSize() const
-{
-    return m_displaySize;
-}
-
-std::pair<double, double> TextTrackCue::getCSSPosition() const
-{
-    if (!m_snapToLines)
-        return getPositionCoordinates();
-
-    return m_displayPosition;
-}
-
 const AtomicString& TextTrackCue::interfaceName() const
 {
     return EventTargetNames::TextTrackCue;
 }
 
-ExecutionContext* TextTrackCue::executionContext() const
-{
-    ASSERT(m_cueBackgroundBox);
-    return m_cueBackgroundBox->executionContext();
-}
-
-Document& TextTrackCue::document() const
-{
-    ASSERT(m_cueBackgroundBox);
-    return m_cueBackgroundBox->document();
-}
-
-bool TextTrackCue::operator==(const TextTrackCue& cue) const
-{
-    if (m_endTime != cue.endTime())
-        return false;
-    if (m_startTime != cue.startTime())
-        return false;
-    if (m_content != cue.text())
-        return false;
-    if (m_settings != cue.cueSettings())
-        return false;
-    if (m_id != cue.id())
-        return false;
-    if (m_textPosition != cue.position())
-        return false;
-    if (m_linePosition != cue.line())
-        return false;
-    if (m_cueSize != cue.size())
-        return false;
-    if (align() != cue.align())
-        return false;
-
-    return true;
-}
-
 } // namespace WebCore
diff --git a/Source/core/html/track/TextTrackCue.h b/Source/core/html/track/TextTrackCue.h
index 0326da8..5798389 100644
--- a/Source/core/html/track/TextTrackCue.h
+++ b/Source/core/html/track/TextTrackCue.h
@@ -32,53 +32,36 @@
 #ifndef TextTrackCue_h
 #define TextTrackCue_h
 
-#include "bindings/v8/ScriptWrappable.h"
 #include "core/events/EventTarget.h"
 #include "core/html/HTMLDivElement.h"
-#include "core/page/UseCounter.h"
 #include "wtf/RefCounted.h"
 
 namespace WebCore {
 
 class Document;
-class DocumentFragment;
 class ExceptionState;
-class ExecutionContext;
-class TextTrack;
 class TextTrackCue;
 
 // ----------------------------
 
-class TextTrackCueBox FINAL : public HTMLDivElement {
+class TextTrackCueBox : public HTMLDivElement {
 public:
-    static PassRefPtr<TextTrackCueBox> create(Document& document, TextTrackCue* cue)
+    static const AtomicString& textTrackCueBoxShadowPseudoId()
     {
-        return adoptRef(new TextTrackCueBox(document, cue));
+        DEFINE_STATIC_LOCAL(const AtomicString, trackDisplayBoxShadowPseudoId, ("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
+        return trackDisplayBoxShadowPseudoId;
     }
 
-    TextTrackCue* getCue() const;
-    void applyCSSProperties(const IntSize& videoSize);
-
-    static const AtomicString& textTrackCueBoxShadowPseudoId();
-
 protected:
-    TextTrackCueBox(Document&, TextTrackCue*);
-
-    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-
-    TextTrackCue* m_cue;
+    TextTrackCueBox(Document&);
 };
 
 // ----------------------------
 
-class TextTrackCue : public RefCounted<TextTrackCue>, public ScriptWrappable, public EventTargetWithInlineData {
+class TextTrackCue : public RefCounted<TextTrackCue>, public EventTargetWithInlineData {
     REFCOUNTED_EVENT_TARGET(TextTrackCue);
 public:
-    static PassRefPtr<TextTrackCue> create(Document& document, double start, double end, const String& content)
-    {
-        UseCounter::count(document, UseCounter::TextTrackCueConstructor);
-        return adoptRef(new TextTrackCue(document, start, end, content));
-    }
+    static bool isInfiniteOrNonNumber(double value, const char* method, ExceptionState&);
 
     static const AtomicString& cueShadowPseudoId()
     {
@@ -86,7 +69,7 @@
         return cue;
     }
 
-    virtual ~TextTrackCue();
+    virtual ~TextTrackCue() { }
 
     TextTrack* track() const;
     void setTrack(TextTrack*);
@@ -103,157 +86,48 @@
     bool pauseOnExit() const { return m_pauseOnExit; }
     void setPauseOnExit(bool);
 
-    const String& vertical() const;
-    void setVertical(const String&, ExceptionState&);
-
-    bool snapToLines() const { return m_snapToLines; }
-    void setSnapToLines(bool);
-
-    int line() const { return m_linePosition; }
-    void setLine(int, ExceptionState&);
-
-    int position() const { return m_textPosition; }
-    void setPosition(int, ExceptionState&);
-
-    int size() const { return m_cueSize; }
-    void setSize(int, ExceptionState&);
-
-    const String& align() const;
-    void setAlign(const String&, ExceptionState&);
-
-    const String& text() const { return m_content; }
-    void setText(const String&);
-
-    const String& cueSettings() const { return m_settings; }
-    void setCueSettings(const String&);
-
     int cueIndex();
     void invalidateCueIndex();
 
-    PassRefPtr<DocumentFragment> getCueAsHTML();
-    PassRefPtr<DocumentFragment> createCueRenderingTree();
-
     using EventTarget::dispatchEvent;
     virtual bool dispatchEvent(PassRefPtr<Event>) OVERRIDE;
 
-    const String& regionId() const { return m_regionId; }
-    void setRegionId(const String&);
-    void notifyRegionWhenRemovingDisplayTree(bool);
-
     bool isActive();
     void setIsActive(bool);
 
-    bool hasDisplayTree() const { return m_displayTree; }
-    PassRefPtr<TextTrackCueBox> getDisplayTree(const IntSize& videoSize);
-    PassRefPtr<HTMLDivElement> element() const { return m_cueBackgroundBox; }
+    virtual void updateDisplay(const IntSize& videoSize, HTMLDivElement& container) = 0;
 
-    void updateDisplayTree(double);
-    void removeDisplayTree();
-    void markFutureAndPastNodes(ContainerNode*, double, double);
-
-    int calculateComputedLinePosition();
+    // FIXME: Consider refactoring to eliminate or merge the following three members.
+    // https://code.google.com/p/chromium/issues/detail?id=322434
+    virtual void updateDisplayTree(double movieTime) { }
+    virtual void removeDisplayTree() { }
+    virtual void notifyRegionWhenRemovingDisplayTree(bool notifyRegion) { }
 
     virtual const AtomicString& interfaceName() const OVERRIDE;
-    virtual ExecutionContext* executionContext() const OVERRIDE;
-
-    std::pair<double, double> getCSSPosition() const;
-
-    CSSValueID getCSSAlignment() const;
-    int getCSSSize() const;
-    CSSValueID getCSSWritingDirection() const;
-    CSSValueID getCSSWritingMode() const;
-
-    enum WritingDirection {
-        Horizontal = 0,
-        VerticalGrowingLeft,
-        VerticalGrowingRight,
-        NumberOfWritingDirections
-    };
-    WritingDirection getWritingDirection() const { return m_writingDirection; }
-
-    enum CueAlignment {
-        Start = 0,
-        Middle,
-        End,
-        Left,
-        Right,
-        NumberOfAlignments
-    };
-    CueAlignment getAlignment() const { return m_cueAlignment; }
-
-    bool operator==(const TextTrackCue&) const;
-    bool operator!=(const TextTrackCue& cue) const
-    {
-        return !(*this == cue);
-    }
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(enter);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(exit);
 
-private:
-    TextTrackCue(Document&, double start, double end, const String& content);
+    virtual bool isVTTCue() const { return false; }
 
-    Document& document() const;
+    virtual String toString() const;
 
-    PassRefPtr<TextTrackCueBox> displayTreeInternal();
-
-    void createWebVTTNodeTree();
-    void copyWebVTTNodeToDOMTree(ContainerNode* WebVTTNode, ContainerNode* root);
-
-    std::pair<double, double> getPositionCoordinates() const;
-    void parseSettings(const String&);
-
-    void determineTextDirection();
-    void calculateDisplayParameters();
+protected:
+    TextTrackCue(double start, double end);
 
     void cueWillChange();
-    void cueDidChange();
+    virtual void cueDidChange();
 
-    enum CueSetting {
-        None,
-        Vertical,
-        Line,
-        Position,
-        Size,
-        Align,
-        RegionId
-    };
-    CueSetting settingName(const String&);
-
+private:
     String m_id;
     double m_startTime;
     double m_endTime;
-    String m_content;
-    String m_settings;
-    int m_linePosition;
-    int m_computedLinePosition;
-    int m_textPosition;
-    int m_cueSize;
     int m_cueIndex;
 
-    WritingDirection m_writingDirection;
-
-    CueAlignment m_cueAlignment;
-
-    RefPtr<DocumentFragment> m_webVTTNodeTree;
     TextTrack* m_track;
 
     bool m_isActive;
     bool m_pauseOnExit;
-    bool m_snapToLines;
-
-    RefPtr<HTMLDivElement> m_cueBackgroundBox;
-
-    bool m_displayTreeShouldChange;
-    RefPtr<TextTrackCueBox> m_displayTree;
-
-    CSSValueID m_displayDirection;
-
-    int m_displaySize;
-
-    std::pair<float, float> m_displayPosition;
-    String m_regionId;
-    bool m_notifyRegion;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/track/TextTrackCue.idl b/Source/core/html/track/TextTrackCue.idl
index db7112a..4fe101d 100644
--- a/Source/core/html/track/TextTrackCue.idl
+++ b/Source/core/html/track/TextTrackCue.idl
@@ -24,30 +24,17 @@
  */
 
 [
+    CustomConstructor(double startTime, double endTime, DOMString text),
+    CustomToV8,
     RuntimeEnabled=VideoTrack,
-    Constructor(double startTime, double endTime, DOMString text),
-    ConstructorCallWith=Document
 ] interface TextTrackCue : EventTarget {
     readonly attribute TextTrack track;
 
     attribute DOMString id;
-    [SetterRaisesException] attribute double startTime;
-    [SetterRaisesException] attribute double endTime;
+    [RaisesException=Setter] attribute double startTime;
+    [RaisesException=Setter] attribute double endTime;
     attribute boolean pauseOnExit;
 
-    [SetterRaisesException] attribute DOMString vertical;
-    attribute boolean snapToLines;
-    [SetterRaisesException] attribute long line;
-    [SetterRaisesException] attribute long position;
-    [SetterRaisesException] attribute long size;
-    [SetterRaisesException] attribute DOMString align;
-
-    attribute DOMString text;
-    DocumentFragment getCueAsHTML();
-
     attribute EventHandler onenter;
     attribute EventHandler onexit;
-
-    [RuntimeEnabled=WebVTTRegions] attribute DOMString regionId;
 };
-
diff --git a/Source/core/html/track/TextTrackList.idl b/Source/core/html/track/TextTrackList.idl
index 236029e..ff20985 100644
--- a/Source/core/html/track/TextTrackList.idl
+++ b/Source/core/html/track/TextTrackList.idl
@@ -24,8 +24,8 @@
  */
 
 [
+    GenerateVisitDOMWrapper=owner,
     RuntimeEnabled=VideoTrack,
-    GenerateIsReachable=owner
 ] interface TextTrackList : EventTarget {
     readonly attribute unsigned long length;
     getter TextTrack item(unsigned long index);
diff --git a/Source/core/html/track/TrackEvent.idl b/Source/core/html/track/TrackEvent.idl
index 3a164cd..4261208 100644
--- a/Source/core/html/track/TrackEvent.idl
+++ b/Source/core/html/track/TrackEvent.idl
@@ -27,6 +27,6 @@
     RuntimeEnabled=VideoTrack,
     ConstructorTemplate=Event
 ] interface TrackEvent : Event {
-    [InitializedByEventConstructor, CustomGetter] readonly attribute object track;
+    [InitializedByEventConstructor, Custom=Getter] readonly attribute object track;
 };
 
diff --git a/Source/core/html/track/WebVTTParser.cpp b/Source/core/html/track/WebVTTParser.cpp
deleted file mode 100644
index 00d026e..0000000
--- a/Source/core/html/track/WebVTTParser.cpp
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- * 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:
- *
- *     * 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/track/WebVTTParser.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/ProcessingInstruction.h"
-#include "core/dom/Text.h"
-#include "core/html/track/WebVTTElement.h"
-#include "platform/text/SegmentedString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-const double secondsPerHour = 3600;
-const double secondsPerMinute = 60;
-const double secondsPerMillisecond = 0.001;
-const double malformedTime = -1;
-const unsigned fileIdentifierLength = 6;
-
-String WebVTTParser::collectDigits(const String& input, unsigned* position)
-{
-    StringBuilder digits;
-    while (*position < input.length() && isASCIIDigit(input[*position]))
-        digits.append(input[(*position)++]);
-    return digits.toString();
-}
-
-String WebVTTParser::collectWord(const String& input, unsigned* position)
-{
-    StringBuilder string;
-    while (*position < input.length() && !isASpace(input[*position]))
-        string.append(input[(*position)++]);
-    return string.toString();
-}
-
-float WebVTTParser::parseFloatPercentageValue(const String& value, bool& isValidSetting)
-{
-    // '%' must be present and at the end of the setting value.
-    if (value.find('%', 1) != value.length() - 1) {
-        isValidSetting = false;
-        return 0;
-    }
-
-    unsigned position = 0;
-
-    StringBuilder floatNumberAsString;
-    floatNumberAsString.append(WebVTTParser::collectDigits(value, &position));
-
-    if (value[position] == '.') {
-        floatNumberAsString.append(".");
-        position++;
-
-        floatNumberAsString.append(WebVTTParser::collectDigits(value, &position));
-    }
-    float number = floatNumberAsString.toString().toFloat(&isValidSetting);
-
-    if (isValidSetting && (number <= 0 || number >= 100))
-        isValidSetting = false;
-
-    return number;
-}
-
-FloatPoint WebVTTParser::parseFloatPercentageValuePair(const String& value, char delimiter, bool& isValidSetting)
-{
-    // The delimiter can't be the first or second value because a pair of
-    // percentages (x%,y%) implies that at least the first two characters
-    // are the first percentage value.
-    size_t delimiterOffset = value.find(delimiter, 2);
-    if (delimiterOffset == kNotFound || delimiterOffset == value.length() - 1) {
-        isValidSetting = false;
-        return FloatPoint(0, 0);
-    }
-
-    bool isFirstValueValid;
-    float firstCoord = parseFloatPercentageValue(value.substring(0, delimiterOffset), isFirstValueValid);
-
-    bool isSecondValueValid;
-    float secondCoord = parseFloatPercentageValue(value.substring(delimiterOffset + 1, value.length() - 1), isSecondValueValid);
-
-    isValidSetting = isFirstValueValid && isSecondValueValid;
-    return FloatPoint(firstCoord, secondCoord);
-}
-
-WebVTTParser::WebVTTParser(WebVTTParserClient* client, Document& document)
-    : m_document(&document)
-    , m_state(Initial)
-    , m_decoder(TextResourceDecoder::create("text/plain", UTF8Encoding()))
-    , m_currentStartTime(0)
-    , m_currentEndTime(0)
-    , m_client(client)
-{
-}
-
-void WebVTTParser::getNewCues(Vector<RefPtr<TextTrackCue> >& outputCues)
-{
-    outputCues = m_cuelist;
-    m_cuelist.clear();
-}
-
-void WebVTTParser::getNewRegions(Vector<RefPtr<VTTRegion> >& outputRegions)
-{
-    outputRegions = m_regionList;
-    m_regionList.clear();
-}
-
-void WebVTTParser::parseBytes(const char* data, unsigned length)
-{
-    String textData = m_decoder->decode(data, length);
-
-    // 4.8.10.13.3 WHATWG WebVTT Parser algorithm.
-    // 1-3 - Initial setup.
-    unsigned position = 0;
-
-    while (position < textData.length()) {
-        String line = collectNextLine(textData, &position);
-
-        switch (m_state) {
-        case Initial:
-            // 4-12 - Check for a valid WebVTT signature.
-            if (!hasRequiredFileIdentifier(line)) {
-                if (m_client)
-                    m_client->fileFailedToParse();
-                return;
-            }
-
-            m_state = Header;
-            break;
-
-        case Header:
-            collectMetadataHeader(line);
-
-            // 13-18 - Allow a header (comment area) under the WEBVTT line.
-            if (line.isEmpty()) {
-                if (m_client && m_regionList.size())
-                    m_client->newRegionsParsed();
-
-                m_state = Id;
-                break;
-            }
-
-            break;
-
-        case Id:
-            // 19-29 - Allow any number of line terminators, then initialize new cue values.
-            if (line.isEmpty())
-                break;
-            resetCueValues();
-
-            // 30-39 - Check if this line contains an optional identifier or timing data.
-            m_state = collectCueId(line);
-            break;
-
-        case TimingsAndSettings:
-            if (line.isEmpty()) {
-                m_state = Id;
-                break;
-            }
-
-            // 40 - Collect cue timings and settings.
-            m_state = collectTimingsAndSettings(line);
-            break;
-
-        case CueText:
-            // 41-53 - Collect the cue text, create a cue, and add it to the output.
-            m_state = collectCueText(line, position >= textData.length());
-            break;
-
-        case BadCue:
-            // 54-62 - Collect and discard the remaining cue.
-            m_state = ignoreBadCue(line);
-            break;
-        }
-    }
-}
-
-bool WebVTTParser::hasRequiredFileIdentifier(const String& line)
-{
-    // A WebVTT file identifier consists of an optional BOM character,
-    // the string "WEBVTT" followed by an optional space or tab character,
-    // and any number of characters that are not line terminators ...
-    if (!line.startsWith("WEBVTT", fileIdentifierLength))
-        return false;
-    if (line.length() > fileIdentifierLength && !isASpace(line[fileIdentifierLength]))
-        return false;
-
-    return true;
-}
-
-void WebVTTParser::collectMetadataHeader(const String& line)
-{
-    // 4.1 Extension of WebVTT header parsing (11 - 15)
-    DEFINE_STATIC_LOCAL(const AtomicString, regionHeaderName, ("Region", AtomicString::ConstructFromLiteral));
-
-    // 15.4 If line contains the character ":" (A U+003A COLON), then set metadata's
-    // name to the substring of line before the first ":" character and
-    // metadata's value to the substring after this character.
-    if (!RuntimeEnabledFeatures::webVTTRegionsEnabled() || !line.contains(":"))
-        return;
-
-    unsigned colonPosition = line.find(":");
-    m_currentHeaderName = line.substring(0, colonPosition);
-
-    // 15.5 If metadata's name equals "Region":
-    if (m_currentHeaderName == regionHeaderName) {
-        m_currentHeaderValue = line.substring(colonPosition + 1, line.length() - 1);
-        // 15.5.1 - 15.5.8 Region creation: Let region be a new text track region [...]
-        createNewRegion();
-    }
-}
-
-WebVTTParser::ParseState WebVTTParser::collectCueId(const String& line)
-{
-    if (line.contains("-->"))
-        return collectTimingsAndSettings(line);
-    m_currentId = line;
-    return TimingsAndSettings;
-}
-
-WebVTTParser::ParseState WebVTTParser::collectTimingsAndSettings(const String& line)
-{
-    // 4.8.10.13.3 Collect WebVTT cue timings and settings.
-    // 1-3 - Let input be the string being parsed and position be a pointer into input
-    unsigned position = 0;
-    skipWhiteSpace(line, &position);
-
-    // 4-5 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue start time be the collected time.
-    m_currentStartTime = collectTimeStamp(line, &position);
-    if (m_currentStartTime == malformedTime)
-        return BadCue;
-    if (position >= line.length())
-        return BadCue;
-
-    skipWhiteSpace(line, &position);
-
-    // 6-9 - If the next three characters are not "-->", abort and return failure.
-    if (line.find("-->", position) == kNotFound)
-        return BadCue;
-    position += 3;
-    if (position >= line.length())
-        return BadCue;
-
-    skipWhiteSpace(line, &position);
-
-    // 10-11 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue end time be the collected time.
-    m_currentEndTime = collectTimeStamp(line, &position);
-    if (m_currentEndTime == malformedTime)
-        return BadCue;
-    skipWhiteSpace(line, &position);
-
-    // 12 - Parse the WebVTT settings for the cue (conducted in TextTrackCue).
-    m_currentSettings = line.substring(position, line.length()-1);
-    return CueText;
-}
-
-WebVTTParser::ParseState WebVTTParser::collectCueText(const String& line, bool isAtEnd)
-{
-    if (line.isEmpty()) {
-        createNewCue();
-        return Id;
-    }
-    if (!m_currentContent.isEmpty())
-        m_currentContent.append("\n");
-    m_currentContent.append(line);
-
-    if (isAtEnd)
-        createNewCue();
-
-    return CueText;
-}
-
-WebVTTParser::ParseState WebVTTParser::ignoreBadCue(const String& line)
-{
-    if (!line.isEmpty())
-        return BadCue;
-    return Id;
-}
-
-// A helper class for the construction of a "cue fragment" from the cue text.
-class WebVTTTreeBuilder {
-public:
-    WebVTTTreeBuilder(Document& document)
-        : m_document(document) { }
-
-    PassRefPtr<DocumentFragment> buildFromString(const String& cueText);
-
-private:
-    void constructTreeFromToken(Document&);
-
-    WebVTTToken m_token;
-    RefPtr<ContainerNode> m_currentNode;
-    Vector<AtomicString> m_languageStack;
-    Document& m_document;
-};
-
-PassRefPtr<DocumentFragment> WebVTTTreeBuilder::buildFromString(const String& cueText)
-{
-    // Cue text processing based on
-    // 4.8.10.13.4 WebVTT cue text parsing rules and
-    // 4.8.10.13.5 WebVTT cue text DOM construction rules.
-
-    RefPtr<DocumentFragment> fragment = DocumentFragment::create(m_document);
-
-    if (cueText.isEmpty()) {
-        fragment->parserAppendChild(Text::create(m_document, ""));
-        return fragment;
-    }
-
-    m_currentNode = fragment;
-
-    OwnPtr<WebVTTTokenizer> tokenizer(WebVTTTokenizer::create());
-    m_token.clear();
-    m_languageStack.clear();
-
-    SegmentedString content(cueText);
-    while (tokenizer->nextToken(content, m_token))
-        constructTreeFromToken(m_document);
-
-    return fragment.release();
-}
-
-PassRefPtr<DocumentFragment> WebVTTParser::createDocumentFragmentFromCueText(Document& document, const String& cueText)
-{
-    WebVTTTreeBuilder treeBuilder(document);
-    return treeBuilder.buildFromString(cueText);
-}
-
-void WebVTTParser::createNewCue()
-{
-    if (!m_currentContent.length())
-        return;
-
-    RefPtr<TextTrackCue> cue = TextTrackCue::create(*m_document, m_currentStartTime, m_currentEndTime, m_currentContent.toString());
-    cue->setId(m_currentId);
-    cue->setCueSettings(m_currentSettings);
-
-    m_cuelist.append(cue);
-    if (m_client)
-        m_client->newCuesParsed();
-}
-
-void WebVTTParser::resetCueValues()
-{
-    m_currentId = emptyString();
-    m_currentSettings = emptyString();
-    m_currentStartTime = 0;
-    m_currentEndTime = 0;
-    m_currentContent.clear();
-}
-
-void WebVTTParser::createNewRegion()
-{
-    if (!m_currentHeaderValue.length())
-        return;
-
-    RefPtr<VTTRegion> region = VTTRegion::create();
-    region->setRegionSettings(m_currentHeaderValue);
-
-    // 15.5.10 If the text track list of regions regions contains a region
-    // with the same region identifier value as region, remove that region.
-    for (size_t i = 0; i < m_regionList.size(); ++i)
-        if (m_regionList[i]->id() == region->id()) {
-            m_regionList.remove(i);
-            break;
-        }
-
-    m_regionList.append(region);
-}
-
-double WebVTTParser::collectTimeStamp(const String& line, unsigned* position)
-{
-    // 4.8.10.13.3 Collect a WebVTT timestamp.
-    // 1-4 - Initial checks, let most significant units be minutes.
-    enum Mode { minutes, hours };
-    Mode mode = minutes;
-    if (*position >= line.length() || !isASCIIDigit(line[*position]))
-        return malformedTime;
-
-    // 5-6 - Collect a sequence of characters that are 0-9.
-    String digits1 = collectDigits(line, position);
-    int value1 = digits1.toInt();
-
-    // 7 - If not 2 characters or value is greater than 59, interpret as hours.
-    if (digits1.length() != 2 || value1 > 59)
-        mode = hours;
-
-    // 8-12 - Collect the next sequence of 0-9 after ':' (must be 2 chars).
-    if (*position >= line.length() || line[(*position)++] != ':')
-        return malformedTime;
-    if (*position >= line.length() || !isASCIIDigit(line[(*position)]))
-        return malformedTime;
-    String digits2 = collectDigits(line, position);
-    int value2 = digits2.toInt();
-    if (digits2.length() != 2)
-        return malformedTime;
-
-    // 13 - Detect whether this timestamp includes hours.
-    int value3;
-    if (mode == hours || (*position < line.length() && line[*position] == ':')) {
-        if (*position >= line.length() || line[(*position)++] != ':')
-            return malformedTime;
-        if (*position >= line.length() || !isASCIIDigit(line[*position]))
-            return malformedTime;
-        String digits3 = collectDigits(line, position);
-        if (digits3.length() != 2)
-            return malformedTime;
-        value3 = digits3.toInt();
-    } else {
-        value3 = value2;
-        value2 = value1;
-        value1 = 0;
-    }
-
-    // 14-19 - Collect next sequence of 0-9 after '.' (must be 3 chars).
-    if (*position >= line.length() || line[(*position)++] != '.')
-        return malformedTime;
-    if (*position >= line.length() || !isASCIIDigit(line[*position]))
-        return malformedTime;
-    String digits4 = collectDigits(line, position);
-    if (digits4.length() != 3)
-        return malformedTime;
-    int value4 = digits4.toInt();
-    if (value2 > 59 || value3 > 59)
-        return malformedTime;
-
-    // 20-21 - Calculate result.
-    return (value1 * secondsPerHour) + (value2 * secondsPerMinute) + value3 + (value4 * secondsPerMillisecond);
-}
-
-static WebVTTNodeType tokenToNodeType(WebVTTToken& token)
-{
-    switch (token.name().size()) {
-    case 1:
-        if (token.name()[0] == 'c')
-            return WebVTTNodeTypeClass;
-        if (token.name()[0] == 'v')
-            return WebVTTNodeTypeVoice;
-        if (token.name()[0] == 'b')
-            return WebVTTNodeTypeBold;
-        if (token.name()[0] == 'i')
-            return WebVTTNodeTypeItalic;
-        if (token.name()[0] == 'u')
-            return WebVTTNodeTypeUnderline;
-        break;
-    case 2:
-        if (token.name()[0] == 'r' && token.name()[1] == 't')
-            return WebVTTNodeTypeRubyText;
-        break;
-    case 4:
-        if (token.name()[0] == 'r' && token.name()[1] == 'u' && token.name()[2] == 'b' && token.name()[3] == 'y')
-            return WebVTTNodeTypeRuby;
-        if (token.name()[0] == 'l' && token.name()[1] == 'a' && token.name()[2] == 'n' && token.name()[3] == 'g')
-            return WebVTTNodeTypeLanguage;
-        break;
-    }
-    return WebVTTNodeTypeNone;
-}
-
-void WebVTTTreeBuilder::constructTreeFromToken(Document& document)
-{
-    QualifiedName tagName(nullAtom, AtomicString(m_token.name()), xhtmlNamespaceURI);
-
-    // http://dev.w3.org/html5/webvtt/#webvtt-cue-text-dom-construction-rules
-
-    switch (m_token.type()) {
-    case WebVTTTokenTypes::Character: {
-        String content(m_token.characters()); // FIXME: This should be 8bit if possible.
-        RefPtr<Text> child = Text::create(document, content);
-        m_currentNode->parserAppendChild(child);
-        break;
-    }
-    case WebVTTTokenTypes::StartTag: {
-        RefPtr<WebVTTElement> child;
-        WebVTTNodeType nodeType = tokenToNodeType(m_token);
-        if (nodeType != WebVTTNodeTypeNone)
-            child = WebVTTElement::create(nodeType, &document);
-        if (child) {
-            if (m_token.classes().size() > 0)
-                child->setAttribute(classAttr, AtomicString(m_token.classes()));
-
-            if (child->webVTTNodeType() == WebVTTNodeTypeVoice)
-                child->setAttribute(WebVTTElement::voiceAttributeName(), AtomicString(m_token.annotation()));
-            else if (child->webVTTNodeType() == WebVTTNodeTypeLanguage) {
-                m_languageStack.append(AtomicString(m_token.annotation()));
-                child->setAttribute(WebVTTElement::langAttributeName(), m_languageStack.last());
-            }
-            if (!m_languageStack.isEmpty())
-                child->setLanguage(m_languageStack.last());
-            m_currentNode->parserAppendChild(child);
-            m_currentNode = child;
-        }
-        break;
-    }
-    case WebVTTTokenTypes::EndTag: {
-        WebVTTNodeType nodeType = tokenToNodeType(m_token);
-        if (nodeType != WebVTTNodeTypeNone) {
-            if (nodeType == WebVTTNodeTypeLanguage && m_currentNode->isWebVTTElement() && toWebVTTElement(m_currentNode.get())->webVTTNodeType() == WebVTTNodeTypeLanguage)
-                m_languageStack.removeLast();
-            if (m_currentNode->parentNode())
-                m_currentNode = m_currentNode->parentNode();
-        }
-        break;
-    }
-    case WebVTTTokenTypes::TimestampTag: {
-        unsigned position = 0;
-        String charactersString(StringImpl::create8BitIfPossible(m_token.characters()));
-        double time = WebVTTParser::collectTimeStamp(charactersString, &position);
-        if (time != malformedTime)
-            m_currentNode->parserAppendChild(ProcessingInstruction::create(document, "timestamp", charactersString));
-        break;
-    }
-    default:
-        break;
-    }
-    m_token.clear();
-}
-
-void WebVTTParser::skipWhiteSpace(const String& line, unsigned* position)
-{
-    while (*position < line.length() && isASpace(line[*position]))
-        (*position)++;
-}
-
-void WebVTTParser::skipLineTerminator(const String& data, unsigned* position)
-{
-    if (*position >= data.length())
-        return;
-    if (data[*position] == '\r')
-        (*position)++;
-    if (*position >= data.length())
-        return;
-    if (data[*position] == '\n')
-        (*position)++;
-}
-
-String WebVTTParser::collectNextLine(const String& data, unsigned* position)
-{
-    unsigned oldPosition = *position;
-    while (*position < data.length() && data[*position] != '\r' && data[*position] != '\n')
-        (*position)++;
-    String line = data.substring(oldPosition, *position - oldPosition);
-    skipLineTerminator(data, position);
-    return line;
-}
-
-}
-
diff --git a/Source/core/html/track/WebVTTToken.h b/Source/core/html/track/WebVTTToken.h
deleted file mode 100644
index 0111eb8..0000000
--- a/Source/core/html/track/WebVTTToken.h
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * 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:
- *
- *     * 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 WebVTTToken_h
-#define WebVTTToken_h
-
-namespace WebCore {
-
-class WebVTTTokenTypes {
-public:
-    enum Type {
-        Uninitialized,
-        Character,
-        StartTag,
-        EndTag,
-        TimestampTag,
-        EndOfFile,
-    };
-};
-
-class WebVTTToken {
-    WTF_MAKE_NONCOPYABLE(WebVTTToken);
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    typedef WebVTTTokenTypes Type;
-    typedef WTF::Vector<UChar, 1024> DataVector; // FIXME: Is this too large for WebVTT?
-
-    WebVTTToken() { clear(); }
-
-    void appendToName(UChar character)
-    {
-        ASSERT(m_type == WebVTTTokenTypes::StartTag || m_type == WebVTTTokenTypes::EndTag);
-        ASSERT(character);
-        m_data.append(character);
-    }
-
-    Type::Type type() const { return m_type; }
-
-    const DataVector& name() const
-    {
-        return m_data;
-    }
-
-    const DataVector& characters() const
-    {
-        ASSERT(m_type == Type::Character || m_type == Type::TimestampTag);
-        return m_data;
-    }
-
-    // Starting a character token works slightly differently than starting
-    // other types of tokens because we want to save a per-character branch.
-    void ensureIsCharacterToken()
-    {
-        ASSERT(m_type == Type::Uninitialized || m_type == Type::Character);
-        m_type = Type::Character;
-    }
-
-    void appendToCharacter(char character)
-    {
-        ASSERT(m_type == Type::Character);
-        m_data.append(character);
-    }
-
-    void appendToCharacter(UChar character)
-    {
-        ASSERT(m_type == Type::Character);
-        m_data.append(character);
-    }
-
-    void appendToCharacter(const Vector<LChar, 32>& characters)
-    {
-        ASSERT(m_type == Type::Character);
-        m_data.appendVector(characters);
-    }
-
-    void beginEmptyStartTag()
-    {
-        ASSERT(m_type == Type::Uninitialized);
-        m_type = Type::StartTag;
-        m_data.clear();
-    }
-
-    void beginStartTag(UChar character)
-    {
-        ASSERT(character);
-        ASSERT(m_type == Type::Uninitialized);
-        m_type = Type::StartTag;
-        m_data.append(character);
-    }
-
-    void beginEndTag(LChar character)
-    {
-        ASSERT(m_type == Type::Uninitialized);
-        m_type = Type::EndTag;
-        m_data.append(character);
-    }
-
-    void beginTimestampTag(UChar character)
-    {
-        ASSERT(character);
-        ASSERT(m_type == Type::Uninitialized);
-        m_type = Type::TimestampTag;
-        m_data.append(character);
-    }
-
-    void appendToTimestamp(UChar character)
-    {
-        ASSERT(character);
-        ASSERT(m_type == Type::TimestampTag);
-        m_data.append(character);
-    }
-
-    void appendToClass(UChar character)
-    {
-        appendToStartType(character);
-    }
-
-    void addNewClass()
-    {
-        ASSERT(m_type == Type::StartTag);
-        if (!m_classes.isEmpty())
-            m_classes.append(' ');
-        m_classes.append(m_currentBuffer);
-        m_currentBuffer.clear();
-    }
-
-    const DataVector& classes() const
-    {
-        return m_classes;
-    }
-
-    void appendToAnnotation(UChar character)
-    {
-        appendToStartType(character);
-    }
-
-    void addNewAnnotation()
-    {
-        ASSERT(m_type == Type::StartTag);
-        m_annotation.clear();
-        m_annotation.append(m_currentBuffer);
-        m_currentBuffer.clear();
-    }
-
-    const DataVector& annotation() const
-    {
-        return m_annotation;
-    }
-
-    void makeEndOfFile()
-    {
-        ASSERT(m_type == Type::Uninitialized);
-        m_type = Type::EndOfFile;
-    }
-
-    void clear()
-    {
-        m_type = Type::Uninitialized;
-        m_data.clear();
-        m_annotation.clear();
-        m_classes.clear();
-        m_currentBuffer.clear();
-    }
-
-private:
-    void appendToStartType(UChar character)
-    {
-        ASSERT(character);
-        ASSERT(m_type == Type::StartTag);
-        m_currentBuffer.append(character);
-    }
-
-    Type::Type m_type;
-    DataVector m_data;
-    DataVector m_annotation;
-    DataVector m_classes;
-    DataVector m_currentBuffer;
-};
-
-}
-
-#endif
diff --git a/Source/core/html/track/WebVTTTokenizer.cpp b/Source/core/html/track/WebVTTTokenizer.cpp
deleted file mode 100644
index f290cb6..0000000
--- a/Source/core/html/track/WebVTTTokenizer.cpp
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * 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:
- *
- *     * 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/track/WebVTTTokenizer.h"
-
-#include "core/xml/parser/MarkupTokenizerInlines.h"
-
-namespace WebCore {
-
-#define WEBVTT_BEGIN_STATE(stateName) BEGIN_STATE(WebVTTTokenizerState, stateName)
-#define WEBVTT_ADVANCE_TO(stateName) ADVANCE_TO(WebVTTTokenizerState, stateName)
-
-WebVTTTokenizer::WebVTTTokenizer()
-    : m_inputStreamPreprocessor(this)
-{
-    reset();
-}
-
-template <typename CharacterType>
-inline bool vectorEqualsString(const Vector<CharacterType, 32>& vector, const String& string)
-{
-    if (vector.size() != string.length())
-        return false;
-
-    if (!string.length())
-        return true;
-
-    return equal(string.impl(), vector.data(), vector.size());
-}
-
-void WebVTTTokenizer::reset()
-{
-    m_state = WebVTTTokenizerState::DataState;
-    m_token = 0;
-    m_buffer.clear();
-}
-
-bool WebVTTTokenizer::nextToken(SegmentedString& source, WebVTTToken& token)
-{
-    // If we have a token in progress, then we're supposed to be called back
-    // with the same token so we can finish it.
-    ASSERT(!m_token || m_token == &token || token.type() == WebVTTTokenTypes::Uninitialized);
-    m_token = &token;
-
-    if (source.isEmpty() || !m_inputStreamPreprocessor.peek(source))
-        return haveBufferedCharacterToken();
-
-    UChar cc = m_inputStreamPreprocessor.nextInputCharacter();
-
-    // 4.8.10.13.4 WebVTT cue text tokenizer
-    switch (m_state) {
-    WEBVTT_BEGIN_STATE(DataState) {
-        if (cc == '&') {
-            m_buffer.append(static_cast<LChar>(cc));
-            WEBVTT_ADVANCE_TO(EscapeState);
-        } else if (cc == '<') {
-            // FIXME: the explicit Vector conversion copies into a temporary
-            // and is wasteful.
-            if (m_token->type() == WebVTTTokenTypes::Uninitialized
-                || vectorEqualsString<UChar>(Vector<UChar, 32>(m_token->characters()), emptyString()))
-                WEBVTT_ADVANCE_TO(TagState);
-            else
-                return emitAndResumeIn(source, WebVTTTokenizerState::TagState);
-        } else if (cc == kEndOfFileMarker)
-            return emitEndOfFile(source);
-        else {
-            bufferCharacter(cc);
-            WEBVTT_ADVANCE_TO(DataState);
-        }
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(EscapeState) {
-        if (cc == ';') {
-            if (vectorEqualsString(m_buffer, "&amp"))
-                bufferCharacter('&');
-            else if (vectorEqualsString(m_buffer, "&lt"))
-                bufferCharacter('<');
-            else if (vectorEqualsString(m_buffer, "&gt"))
-                bufferCharacter('>');
-            else {
-                m_buffer.append(static_cast<LChar>(cc));
-                m_token->appendToCharacter(m_buffer);
-            }
-            m_buffer.clear();
-            WEBVTT_ADVANCE_TO(DataState);
-        } else if (isASCIIAlphanumeric(cc)) {
-            m_buffer.append(static_cast<LChar>(cc));
-            WEBVTT_ADVANCE_TO(EscapeState);
-        } else if (cc == kEndOfFileMarker) {
-            m_token->appendToCharacter(m_buffer);
-            return emitEndOfFile(source);
-        } else {
-            if (!vectorEqualsString(m_buffer, "&"))
-                m_token->appendToCharacter(m_buffer);
-            m_buffer.clear();
-            WEBVTT_ADVANCE_TO(DataState);
-        }
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(TagState) {
-        if (isTokenizerWhitespace(cc)) {
-            m_token->beginEmptyStartTag();
-            WEBVTT_ADVANCE_TO(StartTagAnnotationState);
-        } else if (cc == '.') {
-            m_token->beginEmptyStartTag();
-            WEBVTT_ADVANCE_TO(StartTagClassState);
-        } else if (cc == '/') {
-            WEBVTT_ADVANCE_TO(EndTagOpenState);
-        } else if (WTF::isASCIIDigit(cc)) {
-            m_token->beginTimestampTag(cc);
-            WEBVTT_ADVANCE_TO(TimestampTagState);
-        } else if (cc == '>' || cc == kEndOfFileMarker) {
-            m_token->beginEmptyStartTag();
-            return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
-        } else {
-            m_token->beginStartTag(cc);
-            WEBVTT_ADVANCE_TO(StartTagState);
-        }
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(StartTagState) {
-        if (isTokenizerWhitespace(cc))
-            WEBVTT_ADVANCE_TO(StartTagAnnotationState);
-        else if (cc == '.')
-            WEBVTT_ADVANCE_TO(StartTagClassState);
-        else if (cc == '>' || cc == kEndOfFileMarker)
-            return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
-        else {
-            m_token->appendToName(cc);
-            WEBVTT_ADVANCE_TO(StartTagState);
-        }
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(StartTagClassState) {
-        if (isTokenizerWhitespace(cc)) {
-            m_token->addNewClass();
-            WEBVTT_ADVANCE_TO(StartTagAnnotationState);
-        } else if (cc == '.') {
-            m_token->addNewClass();
-            WEBVTT_ADVANCE_TO(StartTagClassState);
-        } else if (cc == '>' || cc == kEndOfFileMarker) {
-            m_token->addNewClass();
-            return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
-        } else {
-            m_token->appendToClass(cc);
-            WEBVTT_ADVANCE_TO(StartTagClassState);
-        }
-
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(StartTagAnnotationState) {
-        if (cc == '>' || cc == kEndOfFileMarker) {
-            m_token->addNewAnnotation();
-            return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
-        }
-        m_token->appendToAnnotation(cc);
-        WEBVTT_ADVANCE_TO(StartTagAnnotationState);
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(EndTagOpenState) {
-        if (cc == '>' || cc == kEndOfFileMarker) {
-            m_token->beginEndTag('\0');
-            return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
-        }
-        m_token->beginEndTag(cc);
-        WEBVTT_ADVANCE_TO(EndTagState);
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(EndTagState) {
-        if (cc == '>' || cc == kEndOfFileMarker)
-            return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
-        m_token->appendToName(cc);
-        WEBVTT_ADVANCE_TO(EndTagState);
-    }
-    END_STATE()
-
-    WEBVTT_BEGIN_STATE(TimestampTagState) {
-        if (cc == '>' || cc == kEndOfFileMarker)
-            return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
-        m_token->appendToTimestamp(cc);
-        WEBVTT_ADVANCE_TO(TimestampTagState);
-    }
-    END_STATE()
-
-    }
-
-    ASSERT_NOT_REACHED();
-    return false;
-}
-
-}
-
diff --git a/Source/core/html/track/vtt/BufferedLineReader.cpp b/Source/core/html/track/vtt/BufferedLineReader.cpp
new file mode 100644
index 0000000..3a4aab7
--- /dev/null
+++ b/Source/core/html/track/vtt/BufferedLineReader.cpp
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2013, Opera Software ASA. 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 "BufferedLineReader.h"
+
+#include "wtf/unicode/CharacterNames.h"
+
+namespace WebCore {
+
+bool BufferedLineReader::getLine(String& line)
+{
+    if (m_maybeSkipLF) {
+        // We ran out of data after a CR (U+000D), which means that we may be
+        // in the middle of a CRLF pair. If the next character is a LF (U+000A)
+        // then skip it, and then (unconditionally) return the buffered line.
+        if (!m_buffer.isEmpty()) {
+            scanCharacter(newlineCharacter);
+            m_maybeSkipLF = false;
+        }
+        // If there was no (new) data available, then keep m_maybeSkipLF set,
+        // and fall through all the way down to the EOS check at the end of
+        // the method.
+    }
+
+    bool shouldReturnLine = false;
+    bool checkForLF = false;
+    while (!m_buffer.isEmpty()) {
+        UChar c = m_buffer.currentChar();
+        m_buffer.advance();
+
+        if (c == newlineCharacter || c == carriageReturn) {
+            // We found a line ending. Return the accumulated line.
+            shouldReturnLine = true;
+            checkForLF = (c == carriageReturn);
+            break;
+        }
+
+        // NULs are transformed into U+FFFD (REPLACEMENT CHAR.) in step 1 of
+        // the WebVTT parser algorithm.
+        if (c == '\0')
+            c = replacementCharacter;
+
+        m_lineBuffer.append(c);
+    }
+
+    if (checkForLF) {
+        // May be in the middle of a CRLF pair.
+        if (!m_buffer.isEmpty()) {
+            // Scan a potential newline character.
+            scanCharacter(newlineCharacter);
+        } else {
+            // Check for the LF on the next call (unless we reached EOS, in
+            // which case we'll return the contents of the line buffer, and
+            // reset state for the next line.)
+            m_maybeSkipLF = true;
+        }
+    }
+
+    if (isAtEndOfStream()) {
+        // We've reached the end of the stream proper. Emit a line if the
+        // current line buffer is non-empty. (Note that if shouldReturnLine is
+        // set already, we want to return a line nonetheless.)
+        shouldReturnLine |= !m_lineBuffer.isEmpty();
+    }
+
+    if (shouldReturnLine) {
+        line = m_lineBuffer.toString();
+        m_lineBuffer.clear();
+        return true;
+    }
+
+    ASSERT(m_buffer.isEmpty());
+    return false;
+}
+
+} // namespace WebCore
diff --git a/Source/core/html/track/vtt/BufferedLineReader.h b/Source/core/html/track/vtt/BufferedLineReader.h
new file mode 100644
index 0000000..489eb53
--- /dev/null
+++ b/Source/core/html/track/vtt/BufferedLineReader.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2013, Opera Software ASA. 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 BufferedLineReader_h
+#define BufferedLineReader_h
+
+#include "platform/text/SegmentedString.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+// Line collection helper for the WebVTT Parser.
+//
+// Converts a stream of data (== a sequence of Strings) into a set of
+// lines. CR, LR or CRLF are considered linebreaks. Normalizes NULs (U+0000)
+// to 'REPLACEMENT CHARACTER' (U+FFFD) and does not return the linebreaks as
+// part of the result.
+class BufferedLineReader {
+    WTF_MAKE_NONCOPYABLE(BufferedLineReader);
+public:
+    BufferedLineReader()
+        : m_endOfStream(false)
+        , m_maybeSkipLF(false) { }
+
+    // Append data to the internal buffer.
+    void append(const String& data)
+    {
+        ASSERT(!m_endOfStream);
+        m_buffer.append(SegmentedString(data));
+    }
+
+    // Indicate that no more data will be appended. This will cause any
+    // potentially "unterminated" line to be returned from getLine.
+    void setEndOfStream() { m_endOfStream = true; }
+
+    // Attempt to read a line from the internal buffer (fed via append).
+    // If successful, true is returned and |line| is set to the line that was
+    // read. If no line could be read false is returned.
+    bool getLine(String& line);
+
+    // Returns true if EOS has been reached proper.
+    bool isAtEndOfStream() const { return m_endOfStream && m_buffer.isEmpty(); }
+
+private:
+    // Consume the next character the buffer if it is the character |c|.
+    void scanCharacter(UChar c)
+    {
+        ASSERT(!m_buffer.isEmpty());
+        if (m_buffer.currentChar() == c)
+            m_buffer.advance();
+    }
+
+    SegmentedString m_buffer;
+    StringBuilder m_lineBuffer;
+    bool m_endOfStream;
+    bool m_maybeSkipLF;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/core/html/track/vtt/BufferedLineReaderTest.cpp b/Source/core/html/track/vtt/BufferedLineReaderTest.cpp
new file mode 100644
index 0000000..7bfcd49
--- /dev/null
+++ b/Source/core/html/track/vtt/BufferedLineReaderTest.cpp
@@ -0,0 +1,292 @@
+/*
+ * Copyright (C) 2013, Opera Software ASA. 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/track/vtt/BufferedLineReader.h"
+
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
+#include "wtf/unicode/CharacterNames.h"
+
+#include <gtest/gtest.h>
+
+using WebCore::BufferedLineReader;
+
+namespace {
+
+TEST(BufferedLineReader, Constructor)
+{
+    BufferedLineReader reader;
+    ASSERT_FALSE(reader.isAtEndOfStream());
+    String line;
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, EOSNoInput)
+{
+    BufferedLineReader reader;
+    String line;
+    ASSERT_FALSE(reader.getLine(line));
+    reader.setEndOfStream();
+    // No input observed, so still no line.
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, EOSInput)
+{
+    BufferedLineReader reader;
+    reader.append("A");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "A");
+}
+
+TEST(BufferedLineReader, EOSMultipleReads_1)
+{
+    BufferedLineReader reader;
+    reader.append("A");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "A");
+    // No more lines returned.
+    ASSERT_FALSE(reader.getLine(line));
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, EOSMultipleReads_2)
+{
+    BufferedLineReader reader;
+    reader.append("A\n");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "A");
+    // No more lines returned.
+    ASSERT_FALSE(reader.getLine(line));
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, LineEndingCR)
+{
+    BufferedLineReader reader;
+    reader.append("X\rY");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, LineEndingCR_EOS)
+{
+    BufferedLineReader reader;
+    reader.append("X\r");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, LineEndingLF)
+{
+    BufferedLineReader reader;
+    reader.append("X\nY");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, LineEndingLF_EOS)
+{
+    BufferedLineReader reader;
+    reader.append("X\n");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, LineEndingCRLF)
+{
+    BufferedLineReader reader;
+    reader.append("X\r\nY");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, LineEndingCRLF_EOS)
+{
+    BufferedLineReader reader;
+    reader.append("X\r\n");
+    reader.setEndOfStream();
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+enum LineBreakType {
+    Cr,
+    Lf,
+    CrLf
+};
+
+String LineBreakString(LineBreakType type)
+{
+    static const char breakStrings[] = "\r\n";
+    return String(type == Lf ? breakStrings + 1 : breakStrings, type == CrLf ? 2 : 1);
+}
+
+String MakeTestData(const char** lines, const LineBreakType* breaks, int count)
+{
+    StringBuilder builder;
+    for (int i = 0; i < count; ++i) {
+        builder.append(lines[i]);
+        builder.append(LineBreakString(breaks[i]));
+    }
+    return builder.toString();
+}
+
+const size_t blockSizes[] = { 64, 32, 16, 8, 4, 2, 1, 3, 5, 7, 9, 11, 13, 17, 19, 23 };
+
+TEST(BufferedLineReader, BufferSizes)
+{
+    const char* lines[] = {
+        "aaaaaaaaaaaaaaaa",
+        "bbbbbbbbbb",
+        "ccccccccccccc",
+        "",
+        "dddddd",
+        "",
+        "eeeeeeeeee"
+    };
+    const LineBreakType breaks[] = { Lf, Lf, Lf, Lf, Lf, Lf, Lf };
+    const size_t numTestLines = WTF_ARRAY_LENGTH(lines);
+    COMPILE_ASSERT(numTestLines == WTF_ARRAY_LENGTH(breaks), DifferentLengths_lines_and_breaks);
+    String data = MakeTestData(lines, breaks, numTestLines);
+
+    for (size_t k = 0; k < WTF_ARRAY_LENGTH(blockSizes); ++k) {
+        size_t lineCount = 0;
+        BufferedLineReader reader;
+        size_t blockSize = blockSizes[k];
+        for (size_t i = 0; i < data.length(); i += blockSize) {
+            reader.append(data.substring(i, blockSize));
+
+            String line;
+            while (reader.getLine(line)) {
+                ASSERT_LT(lineCount, numTestLines);
+                ASSERT_EQ(line, lines[lineCount++]);
+            }
+        }
+        ASSERT_EQ(lineCount, numTestLines);
+    }
+}
+
+TEST(BufferedLineReader, BufferSizesMixedEndings)
+{
+    const char* lines[] = {
+        "aaaaaaaaaaaaaaaa",
+        "bbbbbbbbbb",
+        "ccccccccccccc",
+        "",
+        "dddddd",
+        "eeeeeeeeee",
+        "fffffffffffffffffff"
+    };
+    const LineBreakType breaks[] = { Cr, Lf, CrLf, Cr, Lf, CrLf, Lf };
+    const size_t numTestLines = WTF_ARRAY_LENGTH(lines);
+    COMPILE_ASSERT(numTestLines == WTF_ARRAY_LENGTH(breaks), DifferentLengths_lines_and_breaks);
+    String data = MakeTestData(lines, breaks, numTestLines);
+
+    for (size_t k = 0; k < WTF_ARRAY_LENGTH(blockSizes); ++k) {
+        size_t lineCount = 0;
+        BufferedLineReader reader;
+        size_t blockSize = blockSizes[k];
+        for (size_t i = 0; i < data.length(); i += blockSize) {
+            reader.append(data.substring(i, blockSize));
+
+            String line;
+            while (reader.getLine(line)) {
+                ASSERT_LT(lineCount, numTestLines);
+                ASSERT_EQ(line, lines[lineCount++]);
+            }
+        }
+        ASSERT_EQ(lineCount, numTestLines);
+    }
+}
+
+TEST(BufferedLineReader, BufferBoundaryInCRLF_1)
+{
+    BufferedLineReader reader;
+    reader.append("X\r");
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    reader.append("\n");
+    ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, BufferBoundaryInCRLF_2)
+{
+    BufferedLineReader reader;
+    reader.append("X\r");
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "X");
+    ASSERT_FALSE(reader.getLine(line));
+    reader.append("\n");
+    ASSERT_FALSE(reader.getLine(line));
+    reader.append("Y\n");
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, NormalizedNUL)
+{
+    BufferedLineReader reader;
+    reader.append(String("X\0Y\n", 4));
+    String line;
+    ASSERT_TRUE(reader.getLine(line));
+    ASSERT_EQ(line[1], WTF::Unicode::replacementCharacter);
+}
+
+} // namespace
diff --git a/Source/core/html/track/vtt/VTTCue.cpp b/Source/core/html/track/vtt/VTTCue.cpp
new file mode 100644
index 0000000..14c2e7e
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTCue.cpp
@@ -0,0 +1,1117 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA 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 HOLDER 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/track/vtt/VTTCue.h"
+
+#include "CSSPropertyNames.h"
+#include "CSSValueKeywords.h"
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/DocumentFragment.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/events/Event.h"
+#include "core/html/HTMLDivElement.h"
+#include "core/html/track/TextTrack.h"
+#include "core/html/track/TextTrackCueList.h"
+#include "core/html/track/vtt/VTTElement.h"
+#include "core/html/track/vtt/VTTParser.h"
+#include "core/html/track/vtt/VTTRegionList.h"
+#include "core/rendering/RenderVTTCue.h"
+#include "wtf/MathExtras.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+static const int undefinedPosition = -1;
+
+static const CSSValueID displayWritingModeMap[] = {
+    CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
+};
+COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayWritingModeMap) == VTTCue::NumberOfWritingDirections,
+    displayWritingModeMap_has_wrong_size);
+
+static const CSSValueID displayAlignmentMap[] = {
+    CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight
+};
+COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayAlignmentMap) == VTTCue::NumberOfAlignments,
+    displayAlignmentMap_has_wrong_size);
+
+static const String& startKeyword()
+{
+    DEFINE_STATIC_LOCAL(const String, start, ("start"));
+    return start;
+}
+
+static const String& middleKeyword()
+{
+    DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
+    return middle;
+}
+
+static const String& endKeyword()
+{
+    DEFINE_STATIC_LOCAL(const String, end, ("end"));
+    return end;
+}
+
+static const String& leftKeyword()
+{
+    DEFINE_STATIC_LOCAL(const String, left, ("left"));
+    return left;
+}
+
+static const String& rightKeyword()
+{
+    DEFINE_STATIC_LOCAL(const String, right, ("right"));
+    return right;
+}
+
+static const String& horizontalKeyword()
+{
+    return emptyString();
+}
+
+static const String& verticalGrowingLeftKeyword()
+{
+    DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
+    return verticalrl;
+}
+
+static const String& verticalGrowingRightKeyword()
+{
+    DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
+    return verticallr;
+}
+
+static bool isInvalidPercentage(double value, const char* method, ExceptionState& exceptionState)
+{
+    if (TextTrackCue::isInfiniteOrNonNumber(value, method, exceptionState))
+        return true;
+    if (value < 0 || value > 100) {
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet(method, "TextTrackCue", "The value provided (" + String::number(value) + ") is not between 0 and 100."));
+        return true;
+    }
+    return false;
+}
+
+// ----------------------------
+
+VTTCueBox::VTTCueBox(Document& document, VTTCue* cue)
+    : TextTrackCueBox(document)
+    , m_cue(cue)
+{
+    setPseudo(textTrackCueBoxShadowPseudoId());
+}
+
+void VTTCueBox::applyCSSProperties(const IntSize&)
+{
+    // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
+    if (!m_cue->regionId().isEmpty()) {
+        setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
+        return;
+    }
+
+    // 3.5.1 On the (root) List of WebVTT Node Objects:
+
+    // the 'position' property must be set to 'absolute'
+    setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
+
+    //  the 'unicode-bidi' property must be set to 'plaintext'
+    setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
+
+    // the 'direction' property must be set to direction
+    setInlineStyleProperty(CSSPropertyDirection, m_cue->getCSSWritingDirection());
+
+    // the 'writing-mode' property must be set to writing-mode
+    setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue->getCSSWritingMode());
+
+    std::pair<float, float> position = m_cue->getCSSPosition();
+
+    // the 'top' property must be set to top,
+    setInlineStyleProperty(CSSPropertyTop, position.second, CSSPrimitiveValue::CSS_PERCENTAGE);
+
+    // the 'left' property must be set to left
+    setInlineStyleProperty(CSSPropertyLeft, position.first, CSSPrimitiveValue::CSS_PERCENTAGE);
+
+    // the 'width' property must be set to width, and the 'height' property  must be set to height
+    if (m_cue->vertical() == horizontalKeyword()) {
+        setInlineStyleProperty(CSSPropertyWidth, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
+        setInlineStyleProperty(CSSPropertyHeight, CSSValueAuto);
+    } else {
+        setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
+        setInlineStyleProperty(CSSPropertyHeight, static_cast<double>(m_cue->getCSSSize()),  CSSPrimitiveValue::CSS_PERCENTAGE);
+    }
+
+    // The 'text-align' property on the (root) List of WebVTT Node Objects must
+    // be set to the value in the second cell of the row of the table below
+    // whose first cell is the value of the corresponding cue's text track cue
+    // alignment:
+    setInlineStyleProperty(CSSPropertyTextAlign, m_cue->getCSSAlignment());
+
+    if (!m_cue->snapToLines()) {
+        // 10.13.1 Set up x and y:
+        // Note: x and y are set through the CSS left and top above.
+
+        // 10.13.2 Position the boxes in boxes such that the point x% along the
+        // width of the bounding box of the boxes in boxes is x% of the way
+        // across the width of the video's rendering area, and the point y%
+        // along the height of the bounding box of the boxes in boxes is y%
+        // of the way across the height of the video's rendering area, while
+        // maintaining the relative positions of the boxes in boxes to each
+        // other.
+        setInlineStyleProperty(CSSPropertyWebkitTransform,
+            String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));
+
+        setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
+    }
+}
+
+RenderObject* VTTCueBox::createRenderer(RenderStyle*)
+{
+    return new RenderVTTCue(this);
+}
+
+// ----------------------------
+
+VTTCue::VTTCue(Document& document, double startTime, double endTime, const String& text)
+    : TextTrackCue(startTime, endTime)
+    , m_text(text)
+    , m_linePosition(undefinedPosition)
+    , m_computedLinePosition(undefinedPosition)
+    , m_textPosition(50)
+    , m_cueSize(100)
+    , m_writingDirection(Horizontal)
+    , m_cueAlignment(Middle)
+    , m_vttNodeTree(0)
+    , m_snapToLines(true)
+    , m_cueBackgroundBox(HTMLDivElement::create(document))
+    , m_displayTreeShouldChange(true)
+    , m_displayDirection(CSSValueLtr)
+    , m_notifyRegion(true)
+{
+    ScriptWrappable::init(this);
+}
+
+VTTCue::~VTTCue()
+{
+    displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
+}
+
+String VTTCue::toString() const
+{
+    return String::format("%p id=%s interval=%f-->%f cue=%s)", this, id().utf8().data(), startTime(), endTime(), text().utf8().data());
+}
+
+PassRefPtr<VTTCueBox> VTTCue::displayTreeInternal()
+{
+    if (!m_displayTree)
+        m_displayTree = VTTCueBox::create(document(), this);
+    return m_displayTree;
+}
+
+void VTTCue::cueDidChange()
+{
+    TextTrackCue::cueDidChange();
+    m_displayTreeShouldChange = true;
+}
+
+const String& VTTCue::vertical() const
+{
+    switch (m_writingDirection) {
+    case Horizontal:
+        return horizontalKeyword();
+    case VerticalGrowingLeft:
+        return verticalGrowingLeftKeyword();
+    case VerticalGrowingRight:
+        return verticalGrowingRightKeyword();
+    default:
+        ASSERT_NOT_REACHED();
+        return emptyString();
+    }
+}
+
+void VTTCue::setVertical(const String& value, ExceptionState& exceptionState)
+{
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-vertical
+    // On setting, the text track cue writing direction must be set to the value given
+    // in the first cell of the row in the table above whose second cell is a
+    // case-sensitive match for the new value, if any. If none of the values match, then
+    // the user agent must instead throw a SyntaxError exception.
+
+    WritingDirection direction = m_writingDirection;
+    if (value == horizontalKeyword())
+        direction = Horizontal;
+    else if (value == verticalGrowingLeftKeyword())
+        direction = VerticalGrowingLeft;
+    else if (value == verticalGrowingRightKeyword())
+        direction = VerticalGrowingRight;
+    else
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("vertical", "TextTrackCue", "The value provided ('" + value + "') is invalid. Only 'rl', 'lr', and the empty string are accepted."));
+
+    if (direction == m_writingDirection)
+        return;
+
+    cueWillChange();
+    m_writingDirection = direction;
+    cueDidChange();
+}
+
+void VTTCue::setSnapToLines(bool value)
+{
+    if (m_snapToLines == value)
+        return;
+
+    cueWillChange();
+    m_snapToLines = value;
+    cueDidChange();
+}
+
+void VTTCue::setLine(int position, ExceptionState& exceptionState)
+{
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-line
+    // On setting, if the text track cue snap-to-lines flag is not set, and the new
+    // value is negative or greater than 100, then throw an IndexSizeError exception.
+    if (!m_snapToLines && (position < 0 || position > 100)) {
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("line", "TextTrackCue", "The snap-to-lines flag is not set, and the value provided (" + String::number(position) + ") is not between 0 and 100."));
+        return;
+    }
+
+    // Otherwise, set the text track cue line position to the new value.
+    if (m_linePosition == position)
+        return;
+
+    cueWillChange();
+    m_linePosition = position;
+    m_computedLinePosition = calculateComputedLinePosition();
+    cueDidChange();
+}
+
+void VTTCue::setPosition(int position, ExceptionState& exceptionState)
+{
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-position
+    // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError exception.
+    // Otherwise, set the text track cue text position to the new value.
+    if (isInvalidPercentage(position, "line", exceptionState))
+        return;
+
+    // Otherwise, set the text track cue line position to the new value.
+    if (m_textPosition == position)
+        return;
+
+    cueWillChange();
+    m_textPosition = position;
+    cueDidChange();
+}
+
+void VTTCue::setSize(int size, ExceptionState& exceptionState)
+{
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-size
+    // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError
+    // exception. Otherwise, set the text track cue size to the new value.
+    if (isInvalidPercentage(size, "line", exceptionState))
+        return;
+
+    // Otherwise, set the text track cue line position to the new value.
+    if (m_cueSize == size)
+        return;
+
+    cueWillChange();
+    m_cueSize = size;
+    cueDidChange();
+}
+
+const String& VTTCue::align() const
+{
+    switch (m_cueAlignment) {
+    case Start:
+        return startKeyword();
+    case Middle:
+        return middleKeyword();
+    case End:
+        return endKeyword();
+    case Left:
+        return leftKeyword();
+    case Right:
+        return rightKeyword();
+    default:
+        ASSERT_NOT_REACHED();
+        return emptyString();
+    }
+}
+
+void VTTCue::setAlign(const String& value, ExceptionState& exceptionState)
+{
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-align
+    // On setting, the text track cue alignment must be set to the value given in the
+    // first cell of the row in the table above whose second cell is a case-sensitive
+    // match for the new value, if any. If none of the values match, then the user
+    // agent must instead throw a SyntaxError exception.
+
+    CueAlignment alignment = m_cueAlignment;
+    if (value == startKeyword())
+        alignment = Start;
+    else if (value == middleKeyword())
+        alignment = Middle;
+    else if (value == endKeyword())
+        alignment = End;
+    else if (value == leftKeyword())
+        alignment = Left;
+    else if (value == rightKeyword())
+        alignment = Right;
+    else
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("align", "TextTrackCue", "The value provided ('" + value + "') is invalid. Only 'start', 'middle', 'end', 'left', and 'right' are accepted."));
+
+    if (alignment == m_cueAlignment)
+        return;
+
+    cueWillChange();
+    m_cueAlignment = alignment;
+    cueDidChange();
+}
+
+void VTTCue::setText(const String& text)
+{
+    if (m_text == text)
+        return;
+
+    cueWillChange();
+    // Clear the document fragment but don't bother to create it again just yet as we can do that
+    // when it is requested.
+    m_vttNodeTree = 0;
+    m_text = text;
+    cueDidChange();
+}
+
+void VTTCue::createVTTNodeTree()
+{
+    if (!m_vttNodeTree)
+        m_vttNodeTree = VTTParser::createDocumentFragmentFromCueText(document(), m_text);
+}
+
+void VTTCue::copyVTTNodeToDOMTree(ContainerNode* vttNode, ContainerNode* parent)
+{
+    for (Node* node = vttNode->firstChild(); node; node = node->nextSibling()) {
+        RefPtr<Node> clonedNode;
+        if (node->isVTTElement())
+            clonedNode = toVTTElement(node)->createEquivalentHTMLElement(document());
+        else
+            clonedNode = node->cloneNode(false);
+        parent->appendChild(clonedNode);
+        if (node->isContainerNode())
+            copyVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode));
+    }
+}
+
+PassRefPtr<DocumentFragment> VTTCue::getCueAsHTML()
+{
+    createVTTNodeTree();
+    RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(document());
+    copyVTTNodeToDOMTree(m_vttNodeTree.get(), clonedFragment.get());
+    return clonedFragment.release();
+}
+
+PassRefPtr<DocumentFragment> VTTCue::createCueRenderingTree()
+{
+    RefPtr<DocumentFragment> clonedFragment;
+    createVTTNodeTree();
+    clonedFragment = DocumentFragment::create(document());
+    m_vttNodeTree->cloneChildNodes(clonedFragment.get());
+    return clonedFragment.release();
+}
+
+void VTTCue::setRegionId(const String& regionId)
+{
+    if (m_regionId == regionId)
+        return;
+
+    cueWillChange();
+    m_regionId = regionId;
+    cueDidChange();
+}
+
+void VTTCue::notifyRegionWhenRemovingDisplayTree(bool notifyRegion)
+{
+    m_notifyRegion = notifyRegion;
+}
+
+int VTTCue::calculateComputedLinePosition()
+{
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position
+
+    // If the text track cue line position is numeric, then that is the text
+    // track cue computed line position.
+    if (m_linePosition != undefinedPosition)
+        return m_linePosition;
+
+    // If the text track cue snap-to-lines flag of the text track cue is not
+    // set, the text track cue computed line position is the value 100;
+    if (!m_snapToLines)
+        return 100;
+
+    // Otherwise, it is the value returned by the following algorithm:
+
+    // If cue is not associated with a text track, return -1 and abort these
+    // steps.
+    if (!track())
+        return -1;
+
+    // Let n be the number of text tracks whose text track mode is showing or
+    // showing by default and that are in the media element's list of text
+    // tracks before track.
+    int n = track()->trackIndexRelativeToRenderedTracks();
+
+    // Increment n by one.
+    n++;
+
+    // Negate n.
+    n = -n;
+
+    return n;
+}
+
+static bool isCueParagraphSeparator(UChar character)
+{
+    // Within a cue, paragraph boundaries are only denoted by Type B characters,
+    // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
+    return WTF::Unicode::category(character) & WTF::Unicode::Separator_Paragraph;
+}
+
+void VTTCue::determineTextDirection()
+{
+    DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
+    createVTTNodeTree();
+
+    // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
+    // concatenation of the values of each WebVTT Text Object in nodes, in a
+    // pre-order, depth-first traversal, excluding WebVTT Ruby Text Objects and
+    // their descendants.
+    StringBuilder paragraphBuilder;
+    for (Node* node = m_vttNodeTree->firstChild(); node; node = NodeTraversal::next(*node, m_vttNodeTree.get())) {
+        if (!node->isTextNode() || node->localName() == rtTag)
+            continue;
+
+        paragraphBuilder.append(node->nodeValue());
+    }
+
+    String paragraph = paragraphBuilder.toString();
+    if (!paragraph.length())
+        return;
+
+    for (size_t i = 0; i < paragraph.length(); ++i) {
+        UChar current = paragraph[i];
+        if (!current || isCueParagraphSeparator(current))
+            return;
+
+        if (UChar current = paragraph[i]) {
+            WTF::Unicode::Direction charDirection = WTF::Unicode::direction(current);
+            if (charDirection == WTF::Unicode::LeftToRight) {
+                m_displayDirection = CSSValueLtr;
+                return;
+            }
+            if (charDirection == WTF::Unicode::RightToLeft
+                || charDirection == WTF::Unicode::RightToLeftArabic) {
+                m_displayDirection = CSSValueRtl;
+                return;
+            }
+        }
+    }
+}
+
+void VTTCue::calculateDisplayParameters()
+{
+    // Steps 10.2, 10.3
+    determineTextDirection();
+
+    // 10.4 If the text track cue writing direction is horizontal, then let
+    // block-flow be 'tb'. Otherwise, if the text track cue writing direction is
+    // vertical growing left, then let block-flow be 'lr'. Otherwise, the text
+    // track cue writing direction is vertical growing right; let block-flow be
+    // 'rl'.
+
+    // The above step is done through the writing direction static map.
+
+    // 10.5 Determine the value of maximum size for cue as per the appropriate
+    // rules from the following list:
+    int maximumSize = m_textPosition;
+    if ((m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueLtr)
+        || (m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueRtl)
+        || (m_writingDirection == Horizontal && m_cueAlignment == Left)
+        || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == Start || m_cueAlignment == Left))
+        || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == Start || m_cueAlignment == Left))) {
+        maximumSize = 100 - m_textPosition;
+    } else if ((m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueLtr)
+        || (m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueRtl)
+        || (m_writingDirection == Horizontal && m_cueAlignment == Right)
+        || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == End || m_cueAlignment == Right))
+        || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == End || m_cueAlignment == Right))) {
+        maximumSize = m_textPosition;
+    } else if (m_cueAlignment == Middle) {
+        maximumSize = m_textPosition <= 50 ? m_textPosition : (100 - m_textPosition);
+        maximumSize = maximumSize * 2;
+    } else {
+        ASSERT_NOT_REACHED();
+    }
+
+    // 10.6 If the text track cue size is less than maximum size, then let size
+    // be text track cue size. Otherwise, let size be maximum size.
+    m_displaySize = std::min(m_cueSize, maximumSize);
+
+    // FIXME: Understand why step 10.7 is missing (just a copy/paste error?)
+    // Could be done within a spec implementation check - http://crbug.com/301580
+
+    // 10.8 Determine the value of x-position or y-position for cue as per the
+    // appropriate rules from the following list:
+    if (m_writingDirection == Horizontal) {
+        switch (m_cueAlignment) {
+        case Start:
+            if (m_displayDirection == CSSValueLtr)
+                m_displayPosition.first = m_textPosition;
+            else
+                m_displayPosition.first = 100 - m_textPosition - m_displaySize;
+            break;
+        case End:
+            if (m_displayDirection == CSSValueRtl)
+                m_displayPosition.first = 100 - m_textPosition;
+            else
+                m_displayPosition.first = m_textPosition - m_displaySize;
+            break;
+        case Left:
+            if (m_displayDirection == CSSValueLtr)
+                m_displayPosition.first = m_textPosition;
+            else
+                m_displayPosition.first = 100 - m_textPosition;
+            break;
+        case Right:
+            if (m_displayDirection == CSSValueLtr)
+                m_displayPosition.first = m_textPosition - m_displaySize;
+            else
+                m_displayPosition.first = 100 - m_textPosition - m_displaySize;
+            break;
+        case Middle:
+            if (m_displayDirection == CSSValueLtr)
+                m_displayPosition.first = m_textPosition - m_displaySize / 2;
+            else
+                m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
+            break;
+        case NumberOfAlignments:
+            ASSERT_NOT_REACHED();
+        }
+    } else {
+        // Cases for m_writingDirection being VerticalGrowing{Left|Right}
+        switch (m_cueAlignment) {
+        case Start:
+        case Left:
+            m_displayPosition.second = m_textPosition;
+            break;
+        case End:
+        case Right:
+            m_displayPosition.second = m_textPosition - m_displaySize;
+            break;
+        case Middle:
+            m_displayPosition.second = m_textPosition - m_displaySize / 2;
+            break;
+        case NumberOfAlignments:
+            ASSERT_NOT_REACHED();
+        }
+    }
+
+    // A text track cue has a text track cue computed line position whose value
+    // is defined in terms of the other aspects of the cue.
+    m_computedLinePosition = calculateComputedLinePosition();
+
+    // 10.9 Determine the value of whichever of x-position or y-position is not
+    // yet calculated for cue as per the appropriate rules from the following
+    // list:
+    if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
+        m_displayPosition.second = 0;
+
+    if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
+        m_displayPosition.second = m_computedLinePosition;
+
+    if (m_snapToLines && m_displayPosition.first == undefinedPosition
+        && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
+        m_displayPosition.first = 0;
+
+    if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
+        m_displayPosition.first = m_computedLinePosition;
+}
+
+void VTTCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
+{
+    DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
+
+    bool isPastNode = true;
+    double currentTimestamp = previousTimestamp;
+    if (currentTimestamp > movieTime)
+        isPastNode = false;
+
+    for (Node* child = root->firstChild(); child; child = NodeTraversal::next(*child, root)) {
+        if (child->nodeName() == timestampTag) {
+            unsigned position = 0;
+            String timestamp = child->nodeValue();
+            double currentTimestamp = VTTParser::collectTimeStamp(timestamp, &position);
+            ASSERT(currentTimestamp != -1);
+
+            if (currentTimestamp > movieTime)
+                isPastNode = false;
+        }
+
+        if (child->isVTTElement()) {
+            toVTTElement(child)->setIsPastNode(isPastNode);
+            // Make an elemenet id match a cue id for style matching purposes.
+            if (!id().isEmpty())
+                toElement(child)->setIdAttribute(id());
+        }
+    }
+}
+
+void VTTCue::updateDisplayTree(double movieTime)
+{
+    // The display tree may contain WebVTT timestamp objects representing
+    // timestamps (processing instructions), along with displayable nodes.
+
+    if (!track()->isRendered())
+        return;
+
+    // Clear the contents of the set.
+    m_cueBackgroundBox->removeChildren();
+
+    // Update the two sets containing past and future WebVTT objects.
+    RefPtr<DocumentFragment> referenceTree = createCueRenderingTree();
+    markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
+    m_cueBackgroundBox->appendChild(referenceTree, ASSERT_NO_EXCEPTION);
+}
+
+PassRefPtr<TextTrackCueBox> VTTCue::getDisplayTree(const IntSize& videoSize)
+{
+    RefPtr<VTTCueBox> displayTree = displayTreeInternal();
+    if (!m_displayTreeShouldChange || !track()->isRendered())
+        return displayTree;
+
+    // 10.1 - 10.10
+    calculateDisplayParameters();
+
+    // 10.11. Apply the terms of the CSS specifications to nodes within the
+    // following constraints, thus obtaining a set of CSS boxes positioned
+    // relative to an initial containing block:
+    displayTree->removeChildren();
+
+    // The document tree is the tree of WebVTT Node Objects rooted at nodes.
+
+    // The children of the nodes must be wrapped in an anonymous box whose
+    // 'display' property has the value 'inline'. This is the WebVTT cue
+    // background box.
+
+    // Note: This is contained by default in m_cueBackgroundBox.
+    m_cueBackgroundBox->setPseudo(cueShadowPseudoId());
+    displayTree->appendChild(m_cueBackgroundBox);
+
+    // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
+    // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose
+    // 'display' property has the value 'ruby-base'.
+
+    // FIXME(BUG 79916): Text runs must be wrapped according to the CSS
+    // line-wrapping rules, except that additionally, regardless of the value of
+    // the 'white-space' property, lines must be wrapped at the edge of their
+    // containing blocks, even if doing so requires splitting a word where there
+    // is no line breaking opportunity. (Thus, normally text wraps as needed,
+    // but if there is a particularly long word, it does not overflow as it
+    // normally would in CSS, it is instead forcibly wrapped at the box's edge.)
+    displayTree->applyCSSProperties(videoSize);
+
+    m_displayTreeShouldChange = false;
+
+    // 10.15. Let cue's text track cue display state have the CSS boxes in
+    // boxes.
+    return displayTree;
+}
+
+void VTTCue::removeDisplayTree()
+{
+    if (m_notifyRegion && track()->regions()) {
+        // The region needs to be informed about the cue removal.
+        VTTRegion* region = track()->regions()->getRegionById(m_regionId);
+        if (region)
+            region->willRemoveTextTrackCueBox(m_displayTree.get());
+    }
+
+    displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
+}
+
+void VTTCue::updateDisplay(const IntSize& videoSize, HTMLDivElement& container)
+{
+    RefPtr<TextTrackCueBox> displayBox = getDisplayTree(videoSize);
+    VTTRegion* region = 0;
+    if (track()->regions())
+        region = track()->regions()->getRegionById(regionId());
+
+    if (!region) {
+        // If cue has an empty text track cue region identifier or there is no
+        // WebVTT region whose region identifier is identical to cue's text
+        // track cue region identifier, run the following substeps:
+        if (displayBox->hasChildNodes() && !container.contains(displayBox.get())) {
+            // Note: the display tree of a cue is removed when the active flag of the cue is unset.
+            container.appendChild(displayBox);
+        }
+    } else {
+        // Let region be the WebVTT region whose region identifier
+        // matches the text track cue region identifier of cue.
+        RefPtr<HTMLDivElement> regionNode = region->getDisplayTree(document());
+
+        // Append the region to the viewport, if it was not already.
+        if (!container.contains(regionNode.get()))
+            container.appendChild(regionNode);
+
+        region->appendTextTrackCueBox(displayBox);
+    }
+}
+
+std::pair<double, double> VTTCue::getPositionCoordinates() const
+{
+    // This method is used for setting x and y when snap to lines is not set.
+    std::pair<double, double> coordinates;
+
+    if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
+        coordinates.first = m_textPosition;
+        coordinates.second = m_computedLinePosition;
+
+        return coordinates;
+    }
+
+    if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
+        coordinates.first = 100 - m_textPosition;
+        coordinates.second = m_computedLinePosition;
+
+        return coordinates;
+    }
+
+    if (m_writingDirection == VerticalGrowingLeft) {
+        coordinates.first = 100 - m_computedLinePosition;
+        coordinates.second = m_textPosition;
+
+        return coordinates;
+    }
+
+    if (m_writingDirection == VerticalGrowingRight) {
+        coordinates.first = m_computedLinePosition;
+        coordinates.second = m_textPosition;
+
+        return coordinates;
+    }
+
+    ASSERT_NOT_REACHED();
+
+    return coordinates;
+}
+
+VTTCue::CueSetting VTTCue::settingName(const String& name)
+{
+    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"));
+    DEFINE_STATIC_LOCAL(const String, regionIdKeyword, ("region"));
+
+    if (name == verticalKeyword)
+        return Vertical;
+    if (name == lineKeyword)
+        return Line;
+    if (name == positionKeyword)
+        return Position;
+    if (name == sizeKeyword)
+        return Size;
+    if (name == alignKeyword)
+        return Align;
+    if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && name == regionIdKeyword)
+        return RegionId;
+
+    return None;
+}
+
+void VTTCue::parseSettings(const String& input)
+{
+    unsigned position = 0;
+
+    while (position < input.length()) {
+
+        // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
+        // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
+        while (position < input.length() && VTTParser::isValidSettingDelimiter(input[position]))
+            position++;
+        if (position >= input.length())
+            break;
+
+        // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
+        // the user agent must run the following steps:
+        // 1. Let settings be the result of splitting input on spaces.
+        // 2. For each token setting in the list settings, run the following substeps:
+        //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
+        //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
+        unsigned endOfSetting = position;
+        String setting = VTTParser::collectWord(input, &endOfSetting);
+        CueSetting name;
+        size_t colonOffset = setting.find(':', 1);
+        if (colonOffset == kNotFound || !colonOffset || colonOffset == setting.length() - 1)
+            goto NextSetting;
+
+        // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
+        name = settingName(setting.substring(0, colonOffset));
+
+        // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
+        position += colonOffset + 1;
+        if (position >= input.length())
+            break;
+
+        // 4. Run the appropriate substeps that apply for the value of name, as follows:
+        switch (name) {
+        case Vertical:
+            {
+            // If name is a case-sensitive match for "vertical"
+            // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
+            //    be vertical growing left.
+            String writingDirection = VTTParser::collectWord(input, &position);
+            if (writingDirection == verticalGrowingLeftKeyword())
+                m_writingDirection = VerticalGrowingLeft;
+
+            // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
+            //    direction be vertical growing right.
+            else if (writingDirection == verticalGrowingRightKeyword())
+                m_writingDirection = VerticalGrowingRight;
+            }
+            break;
+        case Line:
+            {
+            // 1-2 - Collect chars that are either '-', '%', or a digit.
+            // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
+            //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
+            //    to the step labeled next setting.
+            StringBuilder linePositionBuilder;
+            while (position < input.length() && (input[position] == '-' || input[position] == '%' || isASCIIDigit(input[position])))
+                linePositionBuilder.append(input[position++]);
+            if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
+                break;
+
+            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
+            //    NINE (9), then jump to the step labeled next setting.
+            // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then
+            //    jump to the step labeled next setting.
+            // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
+            //    jump to the step labeled next setting.
+            String linePosition = linePositionBuilder.toString();
+            if (linePosition.find('-', 1) != kNotFound || linePosition.reverseFind("%", linePosition.length() - 2) != kNotFound)
+                break;
+
+            // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
+            //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
+            if (linePosition[0] == '-' && linePosition[linePosition.length() - 1] == '%')
+                break;
+
+            // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
+            //    let number be that number.
+            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
+            bool validNumber;
+            int number = linePosition.toInt(&validNumber);
+            if (!validNumber)
+                break;
+
+            // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
+            //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
+            // 8. Let cue's text track cue line position be number.
+            // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
+            //    snap-to-lines flag be false. Otherwise, let it be true.
+            if (linePosition[linePosition.length() - 1] == '%') {
+                if (number < 0 || number > 100)
+                    break;
+
+                // 10 - If '%' then set snap-to-lines flag to false.
+                m_snapToLines = false;
+            }
+
+            m_linePosition = number;
+            }
+            break;
+        case Position:
+            {
+            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the range
+            //    U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
+            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
+            //    then jump to the step labeled next setting.
+            String textPosition = VTTParser::collectDigits(input, &position);
+            if (textPosition.isEmpty())
+                break;
+            if (position >= input.length())
+                break;
+
+            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then jump
+            //    to the step labeled next setting.
+            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step labeled
+            //    next setting.
+            if (input[position++] != '%')
+                break;
+            if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
+                break;
+
+            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
+            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
+            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
+            bool validNumber;
+            int number = textPosition.toInt(&validNumber);
+            if (!validNumber)
+                break;
+            if (number < 0 || number > 100)
+                break;
+
+            // 7. Let cue's text track cue text position be number.
+            m_textPosition = number;
+            }
+            break;
+        case Size:
+            {
+            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the
+            //    range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
+            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
+            //    NINE (9), then jump to the step labeled next setting.
+            String cueSize = VTTParser::collectDigits(input, &position);
+            if (cueSize.isEmpty())
+                break;
+            if (position >= input.length())
+                break;
+
+            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%),
+            //    then jump to the step labeled next setting.
+            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step
+            //    labeled next setting.
+            if (input[position++] != '%')
+                break;
+            if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
+                break;
+
+            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
+            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
+            bool validNumber;
+            int number = cueSize.toInt(&validNumber);
+            if (!validNumber)
+                break;
+            if (number < 0 || number > 100)
+                break;
+
+            // 7. Let cue's text track cue size be number.
+            m_cueSize = number;
+            }
+            break;
+        case Align:
+            {
+            String cueAlignment = VTTParser::collectWord(input, &position);
+
+            // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
+            if (cueAlignment == startKeyword())
+                m_cueAlignment = Start;
+
+            // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
+            else if (cueAlignment == middleKeyword())
+                m_cueAlignment = Middle;
+
+            // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
+            else if (cueAlignment == endKeyword())
+                m_cueAlignment = End;
+
+            // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
+            else if (cueAlignment == leftKeyword())
+                m_cueAlignment = Left;
+
+            // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
+            else if (cueAlignment == rightKeyword())
+                m_cueAlignment = Right;
+            }
+            break;
+        case RegionId:
+            m_regionId = VTTParser::collectWord(input, &position);
+            break;
+        case None:
+            break;
+        }
+
+NextSetting:
+        position = endOfSetting;
+    }
+
+    // If cue's line position is not auto or cue's size is not 100 or cue's
+    // writing direction is not horizontal, but cue's region identifier is not
+    // the empty string, let cue's region identifier be the empty string.
+    if (m_regionId.isEmpty())
+        return;
+
+    if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
+        m_regionId = emptyString();
+}
+
+CSSValueID VTTCue::getCSSAlignment() const
+{
+    return displayAlignmentMap[m_cueAlignment];
+}
+
+CSSValueID VTTCue::getCSSWritingDirection() const
+{
+    return m_displayDirection;
+}
+
+CSSValueID VTTCue::getCSSWritingMode() const
+{
+    return displayWritingModeMap[m_writingDirection];
+}
+
+int VTTCue::getCSSSize() const
+{
+    return m_displaySize;
+}
+
+std::pair<double, double> VTTCue::getCSSPosition() const
+{
+    if (!m_snapToLines)
+        return getPositionCoordinates();
+
+    return m_displayPosition;
+}
+
+ExecutionContext* VTTCue::executionContext() const
+{
+    ASSERT(m_cueBackgroundBox);
+    return m_cueBackgroundBox->executionContext();
+}
+
+Document& VTTCue::document() const
+{
+    ASSERT(m_cueBackgroundBox);
+    return m_cueBackgroundBox->document();
+}
+
+} // namespace WebCore
diff --git a/Source/core/html/track/vtt/VTTCue.h b/Source/core/html/track/vtt/VTTCue.h
new file mode 100644
index 0000000..fc21b8d
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTCue.h
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA 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 HOLDER 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 VTTCue_h
+#define VTTCue_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/html/track/TextTrackCue.h"
+
+namespace WebCore {
+
+class Document;
+class ExecutionContext;
+class VTTCue;
+
+// ----------------------------
+
+class VTTCueBox FINAL : public TextTrackCueBox {
+public:
+    static PassRefPtr<VTTCueBox> create(Document& document, VTTCue* cue)
+    {
+        return adoptRef(new VTTCueBox(document, cue));
+    }
+
+    VTTCue* getCue() const { return m_cue; }
+    void applyCSSProperties(const IntSize& videoSize);
+
+protected:
+    VTTCueBox(Document&, VTTCue*);
+
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+
+    VTTCue* m_cue;
+};
+
+// ----------------------------
+
+class VTTCue FINAL : public TextTrackCue, public ScriptWrappable {
+public:
+    static PassRefPtr<VTTCue> create(Document& document, double startTime, double endTime, const String& text)
+    {
+        return adoptRef(new VTTCue(document, startTime, endTime, text));
+    }
+
+    virtual ~VTTCue();
+
+    virtual bool isVTTCue() const OVERRIDE { return true; }
+
+    const String& vertical() const;
+    void setVertical(const String&, ExceptionState&);
+
+    bool snapToLines() const { return m_snapToLines; }
+    void setSnapToLines(bool);
+
+    int line() const { return m_linePosition; }
+    void setLine(int, ExceptionState&);
+
+    int position() const { return m_textPosition; }
+    void setPosition(int, ExceptionState&);
+
+    int size() const { return m_cueSize; }
+    void setSize(int, ExceptionState&);
+
+    const String& align() const;
+    void setAlign(const String&, ExceptionState&);
+
+    const String& text() const { return m_text; }
+    void setText(const String&);
+
+    void parseSettings(const String&);
+
+    PassRefPtr<DocumentFragment> getCueAsHTML();
+    PassRefPtr<DocumentFragment> createCueRenderingTree();
+
+    const String& regionId() const { return m_regionId; }
+    void setRegionId(const String&);
+
+    virtual void updateDisplay(const IntSize& videoSize, HTMLDivElement& container) OVERRIDE;
+
+    virtual void updateDisplayTree(double movieTime) OVERRIDE;
+    virtual void removeDisplayTree() OVERRIDE;
+    virtual void notifyRegionWhenRemovingDisplayTree(bool notifyRegion) OVERRIDE;
+
+    void markFutureAndPastNodes(ContainerNode*, double previousTimestamp, double movieTime);
+
+    int calculateComputedLinePosition();
+
+    std::pair<double, double> getCSSPosition() const;
+
+    CSSValueID getCSSAlignment() const;
+    int getCSSSize() const;
+    CSSValueID getCSSWritingDirection() const;
+    CSSValueID getCSSWritingMode() const;
+
+    enum WritingDirection {
+        Horizontal = 0,
+        VerticalGrowingLeft,
+        VerticalGrowingRight,
+        NumberOfWritingDirections
+    };
+    WritingDirection getWritingDirection() const { return m_writingDirection; }
+
+    enum CueAlignment {
+        Start = 0,
+        Middle,
+        End,
+        Left,
+        Right,
+        NumberOfAlignments
+    };
+    CueAlignment getAlignment() const { return m_cueAlignment; }
+
+    virtual ExecutionContext* executionContext() const OVERRIDE;
+
+    virtual String toString() const;
+
+private:
+    VTTCue(Document&, double startTime, double endTime, const String& text);
+
+    Document& document() const;
+
+    PassRefPtr<VTTCueBox> displayTreeInternal();
+    PassRefPtr<TextTrackCueBox> getDisplayTree(const IntSize& videoSize);
+
+    virtual void cueDidChange() OVERRIDE;
+
+    void createVTTNodeTree();
+    void copyVTTNodeToDOMTree(ContainerNode* vttNode, ContainerNode* root);
+
+    std::pair<double, double> getPositionCoordinates() const;
+
+    void determineTextDirection();
+    void calculateDisplayParameters();
+
+    enum CueSetting {
+        None,
+        Vertical,
+        Line,
+        Position,
+        Size,
+        Align,
+        RegionId
+    };
+    CueSetting settingName(const String&);
+
+    String m_text;
+    int m_linePosition;
+    int m_computedLinePosition;
+    int m_textPosition;
+    int m_cueSize;
+    WritingDirection m_writingDirection;
+
+    CueAlignment m_cueAlignment;
+
+    RefPtr<DocumentFragment> m_vttNodeTree;
+    bool m_snapToLines;
+
+    RefPtr<HTMLDivElement> m_cueBackgroundBox;
+
+    bool m_displayTreeShouldChange;
+    RefPtr<VTTCueBox> m_displayTree;
+
+    CSSValueID m_displayDirection;
+
+    int m_displaySize;
+
+    std::pair<float, float> m_displayPosition;
+    String m_regionId;
+    bool m_notifyRegion;
+};
+
+inline VTTCue* toVTTCue(TextTrackCue* cue)
+{
+    // VTTCue is currently the only TextTrackCue subclass.
+    return static_cast<VTTCue*>(cue);
+}
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/core/html/track/vtt/VTTCue.idl b/Source/core/html/track/vtt/VTTCue.idl
new file mode 100644
index 0000000..5464248
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTCue.idl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA 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 HOLDER 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.
+ */
+
+[
+    RuntimeEnabled=VideoTrack,
+    Constructor(double startTime, double endTime, DOMString text),
+    ConstructorCallWith=Document
+] interface VTTCue : TextTrackCue {
+    [RuntimeEnabled=WebVTTRegions] attribute DOMString regionId;
+    [RaisesException=Setter] attribute DOMString vertical;
+    attribute boolean snapToLines;
+    [RaisesException=Setter] attribute long line;
+    [RaisesException=Setter] attribute long position;
+    [RaisesException=Setter] attribute long size;
+    [RaisesException=Setter] attribute DOMString align;
+    attribute DOMString text;
+    DocumentFragment getCueAsHTML();
+};
diff --git a/Source/core/html/track/WebVTTElement.cpp b/Source/core/html/track/vtt/VTTElement.cpp
similarity index 72%
rename from Source/core/html/track/WebVTTElement.cpp
rename to Source/core/html/track/vtt/VTTElement.cpp
index c988de0..e9b350a 100644
--- a/Source/core/html/track/WebVTTElement.cpp
+++ b/Source/core/html/track/vtt/VTTElement.cpp
@@ -24,13 +24,13 @@
  */
 
 #include "config.h"
-#include "core/html/track/WebVTTElement.h"
+#include "core/html/track/vtt/VTTElement.h"
 
 #include "HTMLElementFactory.h"
 
 namespace WebCore {
 
-static const QualifiedName& nodeTypeToTagName(WebVTTNodeType nodeType)
+static const QualifiedName& nodeTypeToTagName(VTTNodeType nodeType)
 {
     DEFINE_STATIC_LOCAL(QualifiedName, cTag, (nullAtom, "c", nullAtom));
     DEFINE_STATIC_LOCAL(QualifiedName, vTag, (nullAtom, "v", nullAtom));
@@ -41,73 +41,73 @@
     DEFINE_STATIC_LOCAL(QualifiedName, rubyTag, (nullAtom, "ruby", nullAtom));
     DEFINE_STATIC_LOCAL(QualifiedName, rtTag, (nullAtom, "rt", nullAtom));
     switch (nodeType) {
-    case WebVTTNodeTypeClass:
+    case VTTNodeTypeClass:
         return cTag;
-    case WebVTTNodeTypeItalic:
+    case VTTNodeTypeItalic:
         return iTag;
-    case WebVTTNodeTypeLanguage:
+    case VTTNodeTypeLanguage:
         return langTag;
-    case WebVTTNodeTypeBold:
+    case VTTNodeTypeBold:
         return bTag;
-    case WebVTTNodeTypeUnderline:
+    case VTTNodeTypeUnderline:
         return uTag;
-    case WebVTTNodeTypeRuby:
+    case VTTNodeTypeRuby:
         return rubyTag;
-    case WebVTTNodeTypeRubyText:
+    case VTTNodeTypeRubyText:
         return rtTag;
-    case WebVTTNodeTypeVoice:
+    case VTTNodeTypeVoice:
         return vTag;
-    case WebVTTNodeTypeNone:
+    case VTTNodeTypeNone:
     default:
         ASSERT_NOT_REACHED();
         return cTag; // Make the compiler happy.
     }
 }
 
-WebVTTElement::WebVTTElement(WebVTTNodeType nodeType, Document* document)
+VTTElement::VTTElement(VTTNodeType nodeType, Document* document)
     : Element(nodeTypeToTagName(nodeType), document, CreateElement)
     , m_isPastNode(0)
     , m_webVTTNodeType(nodeType)
 {
 }
 
-PassRefPtr<WebVTTElement> WebVTTElement::create(WebVTTNodeType nodeType, Document* document)
+PassRefPtr<VTTElement> VTTElement::create(VTTNodeType nodeType, Document* document)
 {
-    return adoptRef(new WebVTTElement(nodeType, document));
+    return adoptRef(new VTTElement(nodeType, document));
 }
 
-PassRefPtr<Element> WebVTTElement::cloneElementWithoutAttributesAndChildren()
+PassRefPtr<Element> VTTElement::cloneElementWithoutAttributesAndChildren()
 {
-    RefPtr<WebVTTElement> clone = create(static_cast<WebVTTNodeType>(m_webVTTNodeType), &document());
+    RefPtr<VTTElement> clone = create(static_cast<VTTNodeType>(m_webVTTNodeType), &document());
     clone->setLanguage(m_language);
     return clone;
 }
 
-PassRefPtr<HTMLElement> WebVTTElement::createEquivalentHTMLElement(Document* document)
+PassRefPtr<HTMLElement> VTTElement::createEquivalentHTMLElement(Document& document)
 {
     RefPtr<HTMLElement> htmlElement;
     switch (m_webVTTNodeType) {
-    case WebVTTNodeTypeClass:
-    case WebVTTNodeTypeLanguage:
-    case WebVTTNodeTypeVoice:
-        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::spanTag, document);
+    case VTTNodeTypeClass:
+    case VTTNodeTypeLanguage:
+    case VTTNodeTypeVoice:
+        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::spanTag.localName(), document);
         htmlElement.get()->setAttribute(HTMLNames::titleAttr, getAttribute(voiceAttributeName()));
         htmlElement.get()->setAttribute(HTMLNames::langAttr, getAttribute(langAttributeName()));
         break;
-    case WebVTTNodeTypeItalic:
-        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::iTag, document);
+    case VTTNodeTypeItalic:
+        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::iTag.localName(), document);
         break;
-    case WebVTTNodeTypeBold:
-        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::bTag, document);
+    case VTTNodeTypeBold:
+        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::bTag.localName(), document);
         break;
-    case WebVTTNodeTypeUnderline:
-        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::uTag, document);
+    case VTTNodeTypeUnderline:
+        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::uTag.localName(), document);
         break;
-    case WebVTTNodeTypeRuby:
-        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rubyTag, document);
+    case VTTNodeTypeRuby:
+        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rubyTag.localName(), document);
         break;
-    case WebVTTNodeTypeRubyText:
-        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rtTag, document);
+    case VTTNodeTypeRubyText:
+        htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rtTag.localName(), document);
         break;
     default:
         ASSERT_NOT_REACHED();
diff --git a/Source/core/html/track/WebVTTElement.h b/Source/core/html/track/vtt/VTTElement.h
similarity index 72%
rename from Source/core/html/track/WebVTTElement.h
rename to Source/core/html/track/vtt/VTTElement.h
index b2eb5e5..2fe08c7 100644
--- a/Source/core/html/track/WebVTTElement.h
+++ b/Source/core/html/track/vtt/VTTElement.h
@@ -27,33 +27,33 @@
 
 namespace WebCore {
 
-enum WebVTTNodeType {
-    WebVTTNodeTypeNone = 0,
-    WebVTTNodeTypeClass,
-    WebVTTNodeTypeItalic,
-    WebVTTNodeTypeLanguage,
-    WebVTTNodeTypeBold,
-    WebVTTNodeTypeUnderline,
-    WebVTTNodeTypeRuby,
-    WebVTTNodeTypeRubyText,
-    WebVTTNodeTypeVoice
+enum VTTNodeType {
+    VTTNodeTypeNone = 0,
+    VTTNodeTypeClass,
+    VTTNodeTypeItalic,
+    VTTNodeTypeLanguage,
+    VTTNodeTypeBold,
+    VTTNodeTypeUnderline,
+    VTTNodeTypeRuby,
+    VTTNodeTypeRubyText,
+    VTTNodeTypeVoice
 };
 
-class WebVTTElement FINAL : public Element {
+class VTTElement FINAL : public Element {
 public:
-    static PassRefPtr<WebVTTElement> create(const WebVTTNodeType, Document*);
-    static PassRefPtr<WebVTTElement> create(const QualifiedName&, Document*);
-    PassRefPtr<HTMLElement> createEquivalentHTMLElement(Document*);
+    static PassRefPtr<VTTElement> create(const VTTNodeType, Document*);
+    static PassRefPtr<VTTElement> create(const QualifiedName&, Document*);
+    PassRefPtr<HTMLElement> createEquivalentHTMLElement(Document&);
 
     virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren() OVERRIDE;
 
-    void setWebVTTNodeType(WebVTTNodeType type) { m_webVTTNodeType = static_cast<unsigned>(type); }
-    WebVTTNodeType webVTTNodeType() const { return static_cast<WebVTTNodeType>(m_webVTTNodeType); }
+    void setVTTNodeType(VTTNodeType type) { m_webVTTNodeType = static_cast<unsigned>(type); }
+    VTTNodeType webVTTNodeType() const { return static_cast<VTTNodeType>(m_webVTTNodeType); }
 
     bool isPastNode() const { return m_isPastNode; }
     void setIsPastNode(bool value) { m_isPastNode = value; }
 
-    virtual bool isWebVTTElement() const OVERRIDE { return true; }
+    virtual bool isVTTElement() const OVERRIDE { return true; }
     AtomicString language() const { return m_language; }
     void setLanguage(AtomicString value) { m_language = value; }
 
@@ -70,8 +70,8 @@
     }
 
 private:
-    WebVTTElement(const QualifiedName&, Document*);
-    WebVTTElement(WebVTTNodeType, Document*);
+    VTTElement(const QualifiedName&, Document*);
+    VTTElement(VTTNodeType, Document*);
 
     unsigned m_isPastNode : 1;
     unsigned m_webVTTNodeType : 4;
@@ -79,7 +79,7 @@
     AtomicString m_language;
 };
 
-DEFINE_NODE_TYPE_CASTS(WebVTTElement, isWebVTTElement());
+DEFINE_NODE_TYPE_CASTS(VTTElement, isVTTElement());
 
 } // namespace WebCore
 
diff --git a/Source/core/html/track/vtt/VTTParser.cpp b/Source/core/html/track/vtt/VTTParser.cpp
new file mode 100644
index 0000000..eeb0c9f
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTParser.cpp
@@ -0,0 +1,596 @@
+/*
+ * 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:
+ *
+ *     * 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/track/vtt/VTTParser.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/ProcessingInstruction.h"
+#include "core/dom/Text.h"
+#include "core/html/track/vtt/VTTElement.h"
+#include "platform/text/SegmentedString.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+const double secondsPerHour = 3600;
+const double secondsPerMinute = 60;
+const double secondsPerMillisecond = 0.001;
+const double malformedTime = -1;
+const unsigned fileIdentifierLength = 6;
+
+String VTTParser::collectDigits(const String& input, unsigned* position)
+{
+    StringBuilder digits;
+    while (*position < input.length() && isASCIIDigit(input[*position]))
+        digits.append(input[(*position)++]);
+    return digits.toString();
+}
+
+String VTTParser::collectWord(const String& input, unsigned* position)
+{
+    StringBuilder string;
+    while (*position < input.length() && !isASpace(input[*position]))
+        string.append(input[(*position)++]);
+    return string.toString();
+}
+
+float VTTParser::parseFloatPercentageValue(const String& value, bool& isValidSetting)
+{
+    // '%' must be present and at the end of the setting value.
+    if (value.find('%', 1) != value.length() - 1) {
+        isValidSetting = false;
+        return 0;
+    }
+
+    unsigned position = 0;
+
+    StringBuilder floatNumberAsString;
+    floatNumberAsString.append(VTTParser::collectDigits(value, &position));
+
+    if (value[position] == '.') {
+        floatNumberAsString.append(".");
+        position++;
+
+        floatNumberAsString.append(VTTParser::collectDigits(value, &position));
+    }
+    float number = floatNumberAsString.toString().toFloat(&isValidSetting);
+
+    if (isValidSetting && (number <= 0 || number >= 100))
+        isValidSetting = false;
+
+    return number;
+}
+
+FloatPoint VTTParser::parseFloatPercentageValuePair(const String& value, char delimiter, bool& isValidSetting)
+{
+    // The delimiter can't be the first or second value because a pair of
+    // percentages (x%,y%) implies that at least the first two characters
+    // are the first percentage value.
+    size_t delimiterOffset = value.find(delimiter, 2);
+    if (delimiterOffset == kNotFound || delimiterOffset == value.length() - 1) {
+        isValidSetting = false;
+        return FloatPoint(0, 0);
+    }
+
+    bool isFirstValueValid;
+    float firstCoord = parseFloatPercentageValue(value.substring(0, delimiterOffset), isFirstValueValid);
+
+    bool isSecondValueValid;
+    float secondCoord = parseFloatPercentageValue(value.substring(delimiterOffset + 1, value.length() - 1), isSecondValueValid);
+
+    isValidSetting = isFirstValueValid && isSecondValueValid;
+    return FloatPoint(firstCoord, secondCoord);
+}
+
+VTTParser::VTTParser(VTTParserClient* client, Document& document)
+    : m_document(&document)
+    , m_state(Initial)
+    , m_decoder(TextResourceDecoder::create("text/plain", UTF8Encoding()))
+    , m_currentStartTime(0)
+    , m_currentEndTime(0)
+    , m_client(client)
+{
+}
+
+void VTTParser::getNewCues(Vector<RefPtr<VTTCue> >& outputCues)
+{
+    outputCues = m_cuelist;
+    m_cuelist.clear();
+}
+
+void VTTParser::getNewRegions(Vector<RefPtr<VTTRegion> >& outputRegions)
+{
+    outputRegions = m_regionList;
+    m_regionList.clear();
+}
+
+void VTTParser::parseBytes(const char* data, unsigned length)
+{
+    String textData = m_decoder->decode(data, length);
+    m_lineReader.append(textData);
+    parse();
+}
+
+void VTTParser::flush()
+{
+    String textData = m_decoder->flush();
+    m_lineReader.append(textData);
+    m_lineReader.setEndOfStream();
+    parse();
+    flushPendingCue();
+}
+
+void VTTParser::parse()
+{
+    // WebVTT parser algorithm. (5.1 WebVTT file parsing.)
+    // Steps 1 - 3 - Initial setup.
+
+    String line;
+    while (m_lineReader.getLine(line)) {
+        switch (m_state) {
+        case Initial:
+            // Steps 4 - 9 - Check for a valid WebVTT signature.
+            if (!hasRequiredFileIdentifier(line)) {
+                if (m_client)
+                    m_client->fileFailedToParse();
+                return;
+            }
+
+            m_state = Header;
+            break;
+
+        case Header:
+            // Steps 10 - 14 - Allow a header (comment area) under the WEBVTT line.
+            collectMetadataHeader(line);
+
+            if (line.isEmpty()) {
+                if (m_client && m_regionList.size())
+                    m_client->newRegionsParsed();
+
+                m_state = Id;
+                break;
+            }
+
+            // Step 15 - Break out of header loop if the line could be a timestamp line.
+            if (line.contains("-->"))
+                m_state = recoverCue(line);
+
+            // Step 16 - Line is not the empty string and does not contain "-->".
+            break;
+
+        case Id:
+            // Steps 17 - 20 - Allow any number of line terminators, then initialize new cue values.
+            if (line.isEmpty())
+                break;
+
+            // Step 21 - Cue creation (start a new cue).
+            resetCueValues();
+
+            // Steps 22 - 25 - Check if this line contains an optional identifier or timing data.
+            m_state = collectCueId(line);
+            break;
+
+        case TimingsAndSettings:
+            // Steps 26 - 27 - Discard current cue if the line is empty.
+            if (line.isEmpty()) {
+                m_state = Id;
+                break;
+            }
+
+            // Steps 28 - 29 - Collect cue timings and settings.
+            m_state = collectTimingsAndSettings(line);
+            break;
+
+        case CueText:
+            // Steps 31 - 41 - Collect the cue text, create a cue, and add it to the output.
+            m_state = collectCueText(line);
+            break;
+
+        case BadCue:
+            // Steps 42 - 48 - Discard lines until an empty line or a potential timing line is seen.
+            m_state = ignoreBadCue(line);
+            break;
+        }
+    }
+}
+
+void VTTParser::flushPendingCue()
+{
+    ASSERT(m_lineReader.isAtEndOfStream());
+    // If we're in the CueText state when we run out of data, we emit the pending cue.
+    if (m_state == CueText)
+        createNewCue();
+}
+
+bool VTTParser::hasRequiredFileIdentifier(const String& line)
+{
+    // A WebVTT file identifier consists of an optional BOM character,
+    // the string "WEBVTT" followed by an optional space or tab character,
+    // and any number of characters that are not line terminators ...
+    if (!line.startsWith("WEBVTT", fileIdentifierLength))
+        return false;
+    if (line.length() > fileIdentifierLength && !isASpace(line[fileIdentifierLength]))
+        return false;
+
+    return true;
+}
+
+void VTTParser::collectMetadataHeader(const String& line)
+{
+    // WebVTT header parsing (WebVTT parser algorithm step 12)
+    DEFINE_STATIC_LOCAL(const AtomicString, regionHeaderName, ("Region", AtomicString::ConstructFromLiteral));
+
+    // The only currently supported header is the "Region" header.
+    if (!RuntimeEnabledFeatures::webVTTRegionsEnabled())
+        return;
+
+    // Step 12.4 If line contains the character ":" (A U+003A COLON), then set metadata's
+    // name to the substring of line before the first ":" character and
+    // metadata's value to the substring after this character.
+    size_t colonPosition = line.find(':');
+    if (colonPosition == kNotFound)
+        return;
+
+    String headerName = line.substring(0, colonPosition);
+
+    // Steps 12.5 If metadata's name equals "Region":
+    if (headerName == regionHeaderName) {
+        String headerValue = line.substring(colonPosition + 1);
+        // Steps 12.5.1 - 12.5.11 Region creation: Let region be a new text track region [...]
+        createNewRegion(headerValue);
+    }
+}
+
+VTTParser::ParseState VTTParser::collectCueId(const String& line)
+{
+    if (line.contains("-->"))
+        return collectTimingsAndSettings(line);
+    m_currentId = line;
+    return TimingsAndSettings;
+}
+
+VTTParser::ParseState VTTParser::collectTimingsAndSettings(const String& line)
+{
+    // Collect WebVTT cue timings and settings. (5.3 WebVTT cue timings and settings parsing.)
+    // Steps 1 - 3 - Let input be the string being parsed and position be a pointer into input.
+    unsigned position = 0;
+    skipWhiteSpace(line, &position);
+
+    // Steps 4 - 5 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue start time be the collected time.
+    m_currentStartTime = collectTimeStamp(line, &position);
+    if (m_currentStartTime == malformedTime)
+        return BadCue;
+    if (position >= line.length())
+        return BadCue;
+
+    skipWhiteSpace(line, &position);
+
+    // Steps 6 - 9 - If the next three characters are not "-->", abort and return failure.
+    if (line.find("-->", position) == kNotFound)
+        return BadCue;
+    position += 3;
+    if (position >= line.length())
+        return BadCue;
+
+    skipWhiteSpace(line, &position);
+
+    // Steps 10 - 11 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue end time be the collected time.
+    m_currentEndTime = collectTimeStamp(line, &position);
+    if (m_currentEndTime == malformedTime)
+        return BadCue;
+    skipWhiteSpace(line, &position);
+
+    // Step 12 - Parse the WebVTT settings for the cue (conducted in TextTrackCue).
+    m_currentSettings = line.substring(position, line.length()-1);
+    return CueText;
+}
+
+VTTParser::ParseState VTTParser::collectCueText(const String& line)
+{
+    // Step 34.
+    if (line.isEmpty()) {
+        createNewCue();
+        return Id;
+    }
+    // Step 35.
+    if (line.contains("-->")) {
+        // Step 39-40.
+        createNewCue();
+
+        // Step 41 - New iteration of the cue loop.
+        return recoverCue(line);
+    }
+    if (!m_currentContent.isEmpty())
+        m_currentContent.append("\n");
+    m_currentContent.append(line);
+
+    return CueText;
+}
+
+VTTParser::ParseState VTTParser::recoverCue(const String& line)
+{
+    // Step 17 and 21.
+    resetCueValues();
+
+    // Step 22.
+    return collectTimingsAndSettings(line);
+}
+
+VTTParser::ParseState VTTParser::ignoreBadCue(const String& line)
+{
+    if (line.isEmpty())
+        return Id;
+    if (line.contains("-->"))
+        return recoverCue(line);
+    return BadCue;
+}
+
+// A helper class for the construction of a "cue fragment" from the cue text.
+class VTTTreeBuilder {
+public:
+    VTTTreeBuilder(Document& document)
+        : m_document(document) { }
+
+    PassRefPtr<DocumentFragment> buildFromString(const String& cueText);
+
+private:
+    void constructTreeFromToken(Document&);
+
+    VTTToken m_token;
+    RefPtr<ContainerNode> m_currentNode;
+    Vector<AtomicString> m_languageStack;
+    Document& m_document;
+};
+
+PassRefPtr<DocumentFragment> VTTTreeBuilder::buildFromString(const String& cueText)
+{
+    // Cue text processing based on
+    // 5.4 WebVTT cue text parsing rules, and
+    // 5.5 WebVTT cue text DOM construction rules
+
+    RefPtr<DocumentFragment> fragment = DocumentFragment::create(m_document);
+
+    if (cueText.isEmpty()) {
+        fragment->parserAppendChild(Text::create(m_document, ""));
+        return fragment;
+    }
+
+    m_currentNode = fragment;
+
+    VTTTokenizer tokenizer(cueText);
+    m_languageStack.clear();
+
+    while (tokenizer.nextToken(m_token))
+        constructTreeFromToken(m_document);
+
+    return fragment.release();
+}
+
+PassRefPtr<DocumentFragment> VTTParser::createDocumentFragmentFromCueText(Document& document, const String& cueText)
+{
+    VTTTreeBuilder treeBuilder(document);
+    return treeBuilder.buildFromString(cueText);
+}
+
+void VTTParser::createNewCue()
+{
+    RefPtr<VTTCue> cue = VTTCue::create(*m_document, m_currentStartTime, m_currentEndTime, m_currentContent.toString());
+    cue->setId(m_currentId);
+    cue->parseSettings(m_currentSettings);
+
+    m_cuelist.append(cue);
+    if (m_client)
+        m_client->newCuesParsed();
+}
+
+void VTTParser::resetCueValues()
+{
+    m_currentId = emptyString();
+    m_currentSettings = emptyString();
+    m_currentStartTime = 0;
+    m_currentEndTime = 0;
+    m_currentContent.clear();
+}
+
+void VTTParser::createNewRegion(const String& headerValue)
+{
+    if (headerValue.isEmpty())
+        return;
+
+    // Steps 12.5.1 - 12.5.9 - Construct and initialize a WebVTT Region object.
+    RefPtr<VTTRegion> region = VTTRegion::create();
+    region->setRegionSettings(headerValue);
+
+    // Step 12.5.10 If the text track list of regions regions contains a region
+    // with the same region identifier value as region, remove that region.
+    for (size_t i = 0; i < m_regionList.size(); ++i) {
+        if (m_regionList[i]->id() == region->id()) {
+            m_regionList.remove(i);
+            break;
+        }
+    }
+
+    // Step 12.5.11
+    m_regionList.append(region);
+}
+
+double VTTParser::collectTimeStamp(const String& line, unsigned* position)
+{
+    // Collect a WebVTT timestamp (5.3 WebVTT cue timings and settings parsing.)
+    // Steps 1 - 4 - Initial checks, let most significant units be minutes.
+    enum Mode { Minutes, Hours };
+    Mode mode = Minutes;
+    if (*position >= line.length() || !isASCIIDigit(line[*position]))
+        return malformedTime;
+
+    // Steps 5 - 6 - Collect a sequence of characters that are 0-9.
+    String digits1 = collectDigits(line, position);
+    int value1 = digits1.toInt();
+
+    // Step 7 - If not 2 characters or value is greater than 59, interpret as hours.
+    if (digits1.length() != 2 || value1 > 59)
+        mode = Hours;
+
+    // Steps 8 - 11 - Collect the next sequence of 0-9 after ':' (must be 2 chars).
+    if (*position >= line.length() || line[(*position)++] != ':')
+        return malformedTime;
+    if (*position >= line.length() || !isASCIIDigit(line[(*position)]))
+        return malformedTime;
+    String digits2 = collectDigits(line, position);
+    int value2 = digits2.toInt();
+    if (digits2.length() != 2)
+        return malformedTime;
+
+    // Step 12 - Detect whether this timestamp includes hours.
+    int value3;
+    if (mode == Hours || (*position < line.length() && line[*position] == ':')) {
+        if (*position >= line.length() || line[(*position)++] != ':')
+            return malformedTime;
+        if (*position >= line.length() || !isASCIIDigit(line[*position]))
+            return malformedTime;
+        String digits3 = collectDigits(line, position);
+        if (digits3.length() != 2)
+            return malformedTime;
+        value3 = digits3.toInt();
+    } else {
+        value3 = value2;
+        value2 = value1;
+        value1 = 0;
+    }
+
+    // Steps 13 - 17 - Collect next sequence of 0-9 after '.' (must be 3 chars).
+    if (*position >= line.length() || line[(*position)++] != '.')
+        return malformedTime;
+    if (*position >= line.length() || !isASCIIDigit(line[*position]))
+        return malformedTime;
+    String digits4 = collectDigits(line, position);
+    if (digits4.length() != 3)
+        return malformedTime;
+    int value4 = digits4.toInt();
+    if (value2 > 59 || value3 > 59)
+        return malformedTime;
+
+    // Steps 18 - 19 - Calculate result.
+    return (value1 * secondsPerHour) + (value2 * secondsPerMinute) + value3 + (value4 * secondsPerMillisecond);
+}
+
+static VTTNodeType tokenToNodeType(VTTToken& token)
+{
+    switch (token.name().length()) {
+    case 1:
+        if (token.name()[0] == 'c')
+            return VTTNodeTypeClass;
+        if (token.name()[0] == 'v')
+            return VTTNodeTypeVoice;
+        if (token.name()[0] == 'b')
+            return VTTNodeTypeBold;
+        if (token.name()[0] == 'i')
+            return VTTNodeTypeItalic;
+        if (token.name()[0] == 'u')
+            return VTTNodeTypeUnderline;
+        break;
+    case 2:
+        if (token.name()[0] == 'r' && token.name()[1] == 't')
+            return VTTNodeTypeRubyText;
+        break;
+    case 4:
+        if (token.name()[0] == 'r' && token.name()[1] == 'u' && token.name()[2] == 'b' && token.name()[3] == 'y')
+            return VTTNodeTypeRuby;
+        if (token.name()[0] == 'l' && token.name()[1] == 'a' && token.name()[2] == 'n' && token.name()[3] == 'g')
+            return VTTNodeTypeLanguage;
+        break;
+    }
+    return VTTNodeTypeNone;
+}
+
+void VTTTreeBuilder::constructTreeFromToken(Document& document)
+{
+    // http://dev.w3.org/html5/webvtt/#webvtt-cue-text-dom-construction-rules
+
+    switch (m_token.type()) {
+    case VTTTokenTypes::Character: {
+        RefPtr<Text> child = Text::create(document, m_token.characters());
+        m_currentNode->parserAppendChild(child);
+        break;
+    }
+    case VTTTokenTypes::StartTag: {
+        RefPtr<VTTElement> child;
+        VTTNodeType nodeType = tokenToNodeType(m_token);
+        if (nodeType != VTTNodeTypeNone)
+            child = VTTElement::create(nodeType, &document);
+        if (child) {
+            if (!m_token.classes().isEmpty())
+                child->setAttribute(classAttr, m_token.classes());
+
+            if (child->webVTTNodeType() == VTTNodeTypeVoice) {
+                child->setAttribute(VTTElement::voiceAttributeName(), m_token.annotation());
+            } else if (child->webVTTNodeType() == VTTNodeTypeLanguage) {
+                m_languageStack.append(m_token.annotation());
+                child->setAttribute(VTTElement::langAttributeName(), m_languageStack.last());
+            }
+            if (!m_languageStack.isEmpty())
+                child->setLanguage(m_languageStack.last());
+            m_currentNode->parserAppendChild(child);
+            m_currentNode = child;
+        }
+        break;
+    }
+    case VTTTokenTypes::EndTag: {
+        VTTNodeType nodeType = tokenToNodeType(m_token);
+        if (nodeType != VTTNodeTypeNone) {
+            if (nodeType == VTTNodeTypeLanguage && m_currentNode->isVTTElement() && toVTTElement(m_currentNode.get())->webVTTNodeType() == VTTNodeTypeLanguage)
+                m_languageStack.removeLast();
+            if (m_currentNode->parentNode())
+                m_currentNode = m_currentNode->parentNode();
+        }
+        break;
+    }
+    case VTTTokenTypes::TimestampTag: {
+        unsigned position = 0;
+        String charactersString = m_token.characters();
+        double time = VTTParser::collectTimeStamp(charactersString, &position);
+        if (time != malformedTime)
+            m_currentNode->parserAppendChild(ProcessingInstruction::create(document, "timestamp", charactersString));
+        break;
+    }
+    default:
+        break;
+    }
+}
+
+void VTTParser::skipWhiteSpace(const String& line, unsigned* position)
+{
+    while (*position < line.length() && isASpace(line[*position]))
+        (*position)++;
+}
+
+}
+
diff --git a/Source/core/html/track/WebVTTParser.h b/Source/core/html/track/vtt/VTTParser.h
similarity index 82%
rename from Source/core/html/track/WebVTTParser.h
rename to Source/core/html/track/vtt/VTTParser.h
index 8b89f5d..390ac2f 100644
--- a/Source/core/html/track/WebVTTParser.h
+++ b/Source/core/html/track/vtt/VTTParser.h
@@ -28,16 +28,17 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef WebVTTParser_h
-#define WebVTTParser_h
+#ifndef VTTParser_h
+#define VTTParser_h
 
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/fetch/TextResourceDecoder.h"
-#include "core/html/track/TextTrackCue.h"
-#include "core/html/track/VTTRegion.h"
-#include "core/html/track/WebVTTTokenizer.h"
+#include "core/html/track/vtt/BufferedLineReader.h"
+#include "core/html/track/vtt/VTTCue.h"
+#include "core/html/track/vtt/VTTRegion.h"
+#include "core/html/track/vtt/VTTTokenizer.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -47,16 +48,16 @@
 
 class Document;
 
-class WebVTTParserClient {
+class VTTParserClient {
 public:
-    virtual ~WebVTTParserClient() { }
+    virtual ~VTTParserClient() { }
 
     virtual void newCuesParsed() = 0;
     virtual void newRegionsParsed() = 0;
     virtual void fileFailedToParse() = 0;
 };
 
-class WebVTTParser FINAL {
+class VTTParser FINAL {
 public:
     enum ParseState {
         Initial,
@@ -67,9 +68,9 @@
         BadCue
     };
 
-    static PassOwnPtr<WebVTTParser> create(WebVTTParserClient* client, Document& document)
+    static PassOwnPtr<VTTParser> create(VTTParserClient* client, Document& document)
     {
-        return adoptPtr(new WebVTTParser(client, document));
+        return adoptPtr(new VTTParser(client, document));
     }
 
     static inline bool isRecognizedTag(const AtomicString& tagName)
@@ -105,46 +106,46 @@
 
     // Input data to the parser to parse.
     void parseBytes(const char* data, unsigned length);
+    void flush();
 
     // Transfers ownership of last parsed cues to caller.
-    void getNewCues(Vector<RefPtr<TextTrackCue> >&);
+    void getNewCues(Vector<RefPtr<VTTCue> >&);
     void getNewRegions(Vector<RefPtr<VTTRegion> >&);
 
 private:
-    WebVTTParser(WebVTTParserClient*, Document&);
+    VTTParser(VTTParserClient*, Document&);
 
     Document* m_document;
     ParseState m_state;
 
+    void parse();
+    void flushPendingCue();
     bool hasRequiredFileIdentifier(const String& line);
     ParseState collectCueId(const String&);
     ParseState collectTimingsAndSettings(const String&);
-    ParseState collectCueText(const String&, bool);
+    ParseState collectCueText(const String&);
+    ParseState recoverCue(const String&);
     ParseState ignoreBadCue(const String&);
 
     void createNewCue();
     void resetCueValues();
 
     void collectMetadataHeader(const String&);
-    void createNewRegion();
+    void createNewRegion(const String& headerValue);
 
     void skipWhiteSpace(const String&, unsigned*);
-    static void skipLineTerminator(const String& data, unsigned*);
-    static String collectNextLine(const String& data, unsigned*);
 
-    String m_currentHeaderName;
-    String m_currentHeaderValue;
-
-    RefPtr<TextResourceDecoder> m_decoder;
+    BufferedLineReader m_lineReader;
+    OwnPtr<TextResourceDecoder> m_decoder;
     String m_currentId;
     double m_currentStartTime;
     double m_currentEndTime;
     StringBuilder m_currentContent;
     String m_currentSettings;
 
-    WebVTTParserClient* m_client;
+    VTTParserClient* m_client;
 
-    Vector<RefPtr<TextTrackCue> > m_cuelist;
+    Vector<RefPtr<VTTCue> > m_cuelist;
 
     Vector<RefPtr<VTTRegion> > m_regionList;
 };
diff --git a/Source/core/html/track/VTTRegion.cpp b/Source/core/html/track/vtt/VTTRegion.cpp
similarity index 85%
rename from Source/core/html/track/VTTRegion.cpp
rename to Source/core/html/track/vtt/VTTRegion.cpp
index dcf3472..3e155c2 100644
--- a/Source/core/html/track/VTTRegion.cpp
+++ b/Source/core/html/track/vtt/VTTRegion.cpp
@@ -29,14 +29,14 @@
  */
 
 #include "config.h"
-#include "core/html/track/VTTRegion.h"
+#include "core/html/track/vtt/VTTRegion.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/DOMTokenList.h"
 #include "core/html/HTMLDivElement.h"
-#include "core/html/track/WebVTTParser.h"
+#include "core/html/track/vtt/VTTParser.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderObject.h"
 #include "platform/Logging.h"
@@ -67,6 +67,19 @@
 // Default scrolling animation time period (s).
 static const float scrollTime = 0.433;
 
+static bool isInfiniteOrNonNumberOrNonPercentage(double value, const char* method, ExceptionState& exceptionState)
+{
+    if (!std::isfinite(value)) {
+        exceptionState.throwTypeError(ExceptionMessages::failedToSet(method, "VTTRegion", ExceptionMessages::notAFiniteNumber(value)));
+        return true;
+    }
+    if (value < 0 || value > 100) {
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet(method, "VTTRegion", "The value provided (" + String::number(value) + ") is not between 0 and 100."));
+        return true;
+    }
+    return false;
+}
+
 VTTRegion::VTTRegion()
     : m_id(emptyString())
     , m_width(defaultWidth)
@@ -94,87 +107,52 @@
     m_id = id;
 }
 
-void VTTRegion::setWidth(double value, ExceptionState& es)
+void VTTRegion::setWidth(double value, ExceptionState& exceptionState)
 {
-    if (std::isinf(value) || std::isnan(value)) {
-        es.throwUninformativeAndGenericTypeError();
+    if (isInfiniteOrNonNumberOrNonPercentage(value, "width", exceptionState))
         return;
-    }
-
-    if (value < 0 || value > 100) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     m_width = value;
 }
 
-void VTTRegion::setHeight(long value, ExceptionState& es)
+void VTTRegion::setHeight(long value, ExceptionState& exceptionState)
 {
     if (value < 0) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("height", "VTTRegion", "The height provided (" + String::number(value) + ") is negative."));
         return;
     }
 
     m_heightInLines = value;
 }
 
-void VTTRegion::setRegionAnchorX(double value, ExceptionState& es)
+void VTTRegion::setRegionAnchorX(double value, ExceptionState& exceptionState)
 {
-    if (std::isinf(value) || std::isnan(value)) {
-        es.throwUninformativeAndGenericTypeError();
+    if (isInfiniteOrNonNumberOrNonPercentage(value, "regionAnchorX", exceptionState))
         return;
-    }
-
-    if (value < 0 || value > 100) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     m_regionAnchor.setX(value);
 }
 
-void VTTRegion::setRegionAnchorY(double value, ExceptionState& es)
+void VTTRegion::setRegionAnchorY(double value, ExceptionState& exceptionState)
 {
-    if (std::isinf(value) || std::isnan(value)) {
-        es.throwUninformativeAndGenericTypeError();
+    if (isInfiniteOrNonNumberOrNonPercentage(value, "regionAnchorY", exceptionState))
         return;
-    }
-
-    if (value < 0 || value > 100) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     m_regionAnchor.setY(value);
 }
 
-void VTTRegion::setViewportAnchorX(double value, ExceptionState& es)
+void VTTRegion::setViewportAnchorX(double value, ExceptionState& exceptionState)
 {
-    if (std::isinf(value) || std::isnan(value)) {
-        es.throwUninformativeAndGenericTypeError();
+    if (isInfiniteOrNonNumberOrNonPercentage(value, "viewportAnchorX", exceptionState))
         return;
-    }
-
-    if (value < 0 || value > 100) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     m_viewportAnchor.setX(value);
 }
 
-void VTTRegion::setViewportAnchorY(double value, ExceptionState& es)
+void VTTRegion::setViewportAnchorY(double value, ExceptionState& exceptionState)
 {
-    if (std::isinf(value) || std::isnan(value)) {
-        es.throwUninformativeAndGenericTypeError();
+    if (isInfiniteOrNonNumberOrNonPercentage(value, "viewportAnchorY", exceptionState))
         return;
-    }
-
-    if (value < 0 || value > 100) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     m_viewportAnchor.setY(value);
 }
@@ -189,12 +167,12 @@
     return "";
 }
 
-void VTTRegion::setScroll(const AtomicString& value, ExceptionState& es)
+void VTTRegion::setScroll(const AtomicString& value, ExceptionState& exceptionState)
 {
     DEFINE_STATIC_LOCAL(const AtomicString, upScrollValueKeyword, ("up", AtomicString::ConstructFromLiteral));
 
     if (value != emptyString() && value != upScrollValueKeyword) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("scroll", "VTTRegion", "The value provided ('" + value + "') is invalid. The 'scroll' property must be either the empty string, or 'up'."));
         return;
     }
 
@@ -218,7 +196,7 @@
     unsigned position = 0;
 
     while (position < input.length()) {
-        while (position < input.length() && WebVTTParser::isValidSettingDelimiter(input[position]))
+        while (position < input.length() && VTTParser::isValidSettingDelimiter(input[position]))
             position++;
 
         if (position >= input.length())
@@ -269,7 +247,7 @@
             m_id = value;
         break;
     case Width:
-        number = WebVTTParser::parseFloatPercentageValue(value, isValidSetting);
+        number = VTTParser::parseFloatPercentageValue(value, isValidSetting);
         if (isValidSetting)
             m_width = number;
         else
@@ -278,7 +256,7 @@
     case Height:
         position = 0;
 
-        numberAsString = WebVTTParser::collectDigits(value, &position);
+        numberAsString = VTTParser::collectDigits(value, &position);
         number = value.toInt(&isValidSetting);
 
         if (isValidSetting && number >= 0)
@@ -287,14 +265,14 @@
             LOG(Media, "VTTRegion::parseSettingValue, invalid Height");
         break;
     case RegionAnchor:
-        anchorPosition = WebVTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
+        anchorPosition = VTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
         if (isValidSetting)
             m_regionAnchor = anchorPosition;
         else
             LOG(Media, "VTTRegion::parseSettingValue, invalid RegionAnchor");
         break;
     case ViewportAnchor:
-        anchorPosition = WebVTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
+        anchorPosition = VTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
         if (isValidSetting)
             m_viewportAnchor = anchorPosition;
         else
@@ -313,7 +291,7 @@
 
 void VTTRegion::parseSetting(const String& input, unsigned* position)
 {
-    String setting = WebVTTParser::collectWord(input, position);
+    String setting = VTTParser::collectWord(input, position);
 
     size_t equalOffset = setting.find('=', 1);
     if (equalOffset == kNotFound || !equalOffset || equalOffset == setting.length() - 1)
@@ -466,11 +444,11 @@
         0.0,
         CSSPrimitiveValue::CSS_PX);
 
-    m_cueContainer->setPart(textTrackCueContainerShadowPseudoId());
+    m_cueContainer->setPseudo(textTrackCueContainerShadowPseudoId());
     m_regionDisplayTree->appendChild(m_cueContainer);
 
     // 7.5 Every WebVTT region object is initialised with the following CSS
-    m_regionDisplayTree->setPart(textTrackRegionShadowPseudoId());
+    m_regionDisplayTree->setPseudo(textTrackRegionShadowPseudoId());
 }
 
 void VTTRegion::startTimer()
diff --git a/Source/core/html/track/VTTRegion.h b/Source/core/html/track/vtt/VTTRegion.h
similarity index 100%
rename from Source/core/html/track/VTTRegion.h
rename to Source/core/html/track/vtt/VTTRegion.h
diff --git a/Source/core/html/track/VTTRegion.idl b/Source/core/html/track/vtt/VTTRegion.idl
similarity index 78%
rename from Source/core/html/track/VTTRegion.idl
rename to Source/core/html/track/vtt/VTTRegion.idl
index d3793af..b0348b4 100644
--- a/Source/core/html/track/VTTRegion.idl
+++ b/Source/core/html/track/vtt/VTTRegion.idl
@@ -30,12 +30,12 @@
     readonly attribute TextTrack track;
 
     attribute DOMString id;
-    [SetterRaisesException] attribute double width;
-    [SetterRaisesException] attribute long height;
-    [SetterRaisesException] attribute double regionAnchorX;
-    [SetterRaisesException] attribute double regionAnchorY;
-    [SetterRaisesException] attribute double viewportAnchorX;
-    [SetterRaisesException] attribute double viewportAnchorY;
-    [SetterRaisesException] attribute DOMString scroll;
+    [RaisesException=Setter] attribute double width;
+    [RaisesException=Setter] attribute long height;
+    [RaisesException=Setter] attribute double regionAnchorX;
+    [RaisesException=Setter] attribute double regionAnchorY;
+    [RaisesException=Setter] attribute double viewportAnchorX;
+    [RaisesException=Setter] attribute double viewportAnchorY;
+    [RaisesException=Setter] attribute DOMString scroll;
 };
 
diff --git a/Source/core/html/track/VTTRegionList.cpp b/Source/core/html/track/vtt/VTTRegionList.cpp
similarity index 97%
rename from Source/core/html/track/VTTRegionList.cpp
rename to Source/core/html/track/vtt/VTTRegionList.cpp
index 61d78f6..914da52 100644
--- a/Source/core/html/track/VTTRegionList.cpp
+++ b/Source/core/html/track/vtt/VTTRegionList.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "config.h"
-#include "core/html/track/VTTRegionList.h"
+#include "core/html/track/vtt/VTTRegionList.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/track/VTTRegionList.h b/Source/core/html/track/vtt/VTTRegionList.h
similarity index 97%
rename from Source/core/html/track/VTTRegionList.h
rename to Source/core/html/track/vtt/VTTRegionList.h
index ccca882..35e1b8e 100644
--- a/Source/core/html/track/VTTRegionList.h
+++ b/Source/core/html/track/vtt/VTTRegionList.h
@@ -26,7 +26,7 @@
 #ifndef VTTRegionList_h
 #define VTTRegionList_h
 
-#include "core/html/track/VTTRegion.h"
+#include "core/html/track/vtt/VTTRegion.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
diff --git a/Source/core/html/track/VTTRegionList.idl b/Source/core/html/track/vtt/VTTRegionList.idl
similarity index 100%
rename from Source/core/html/track/VTTRegionList.idl
rename to Source/core/html/track/vtt/VTTRegionList.idl
diff --git a/Source/core/html/track/vtt/VTTToken.h b/Source/core/html/track/vtt/VTTToken.h
new file mode 100644
index 0000000..c95134f
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTToken.h
@@ -0,0 +1,92 @@
+/*
+ * 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:
+ *
+ *     * 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 VTTToken_h
+#define VTTToken_h
+
+namespace WebCore {
+
+class VTTTokenTypes {
+public:
+    enum Type {
+        Uninitialized,
+        Character,
+        StartTag,
+        EndTag,
+        TimestampTag,
+    };
+};
+
+class VTTToken {
+public:
+    typedef VTTTokenTypes Type;
+
+    VTTToken() : m_type(Type::Uninitialized) { }
+
+    static VTTToken StringToken(const String& characterData)
+    {
+        return VTTToken(Type::Character, characterData);
+    }
+    static VTTToken StartTag(const String& tagName, const AtomicString& classes = emptyAtom, const AtomicString& annotation = emptyAtom)
+    {
+        VTTToken token(Type::StartTag, tagName);
+        token.m_classes = classes;
+        token.m_annotation = annotation;
+        return token;
+    }
+    static VTTToken EndTag(const String& tagName)
+    {
+        return VTTToken(Type::EndTag, tagName);
+    }
+    static VTTToken TimestampTag(const String& timestampData)
+    {
+        return VTTToken(Type::TimestampTag, timestampData);
+    }
+
+    Type::Type type() const { return m_type; }
+    const String& name() const { return m_data; }
+    const String& characters() const { return m_data; }
+    const AtomicString& classes() const { return m_classes; }
+    const AtomicString& annotation() const { return m_annotation; }
+
+private:
+    VTTToken(Type::Type type, const String& data)
+        : m_type(type)
+        , m_data(data) { }
+
+    Type::Type m_type;
+    String m_data;
+    AtomicString m_annotation;
+    AtomicString m_classes;
+};
+
+}
+
+#endif
diff --git a/Source/core/html/track/vtt/VTTTokenizer.cpp b/Source/core/html/track/vtt/VTTTokenizer.cpp
new file mode 100644
index 0000000..9c9c3f4
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTTokenizer.cpp
@@ -0,0 +1,244 @@
+/*
+ * 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:
+ *
+ *     * 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/track/vtt/VTTTokenizer.h"
+
+#include "core/xml/parser/MarkupTokenizerInlines.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/unicode/CharacterNames.h"
+
+namespace WebCore {
+
+#define WEBVTT_BEGIN_STATE(stateName) BEGIN_STATE(VTTTokenizerState, stateName)
+#define WEBVTT_ADVANCE_TO(stateName) ADVANCE_TO(VTTTokenizerState, stateName)
+
+template<unsigned charactersCount>
+ALWAYS_INLINE bool equalLiteral(const StringBuilder& s, const char (&characters)[charactersCount])
+{
+    return WTF::equal(s, reinterpret_cast<const LChar*>(characters), charactersCount - 1);
+}
+
+static void addNewClass(StringBuilder& classes, const StringBuilder& newClass)
+{
+    if (!classes.isEmpty())
+        classes.append(' ');
+    classes.append(newClass);
+}
+
+VTTTokenizer::VTTTokenizer(const String& input)
+    : m_input(input)
+    , m_inputStreamPreprocessor(this)
+{
+    reset();
+
+    // Append a EOF marker and close the input "stream".
+    ASSERT(!m_input.isClosed());
+    m_input.append(SegmentedString(String(&kEndOfFileMarker, 1)));
+    m_input.close();
+}
+
+void VTTTokenizer::reset()
+{
+    m_token = 0;
+}
+
+bool VTTTokenizer::nextToken(VTTToken& token)
+{
+    // If we have a token in progress, then we're supposed to be called back
+    // with the same token so we can finish it.
+    ASSERT(!m_token || m_token == &token);
+    m_token = &token;
+
+    if (m_input.isEmpty() || !m_inputStreamPreprocessor.peek(m_input))
+        return haveBufferedCharacterToken();
+
+    UChar cc = m_inputStreamPreprocessor.nextInputCharacter();
+    if (cc == kEndOfFileMarker) {
+        m_inputStreamPreprocessor.advance(m_input);
+        return false;
+    }
+
+    StringBuilder buffer;
+    StringBuilder result;
+    StringBuilder classes;
+    m_state = VTTTokenizerState::DataState;
+
+    // The ADVANCE_TO helper macros expect this name ('source') on the input variable.
+    SegmentedString& source = m_input;
+
+    // 4.8.10.13.4 WebVTT cue text tokenizer
+    switch (m_state) {
+        WEBVTT_BEGIN_STATE(DataState) {
+            if (cc == '&') {
+                buffer.append(static_cast<LChar>(cc));
+                WEBVTT_ADVANCE_TO(EscapeState);
+            } else if (cc == '<') {
+                if (result.isEmpty()) {
+                    WEBVTT_ADVANCE_TO(TagState);
+                } else {
+                    // We don't want to advance input or perform a state transition - just return a (new) token.
+                    // (On the next call to nextToken we will see '<' again, but take the other branch in this if instead.)
+                    return emitToken(VTTToken::StringToken(result.toString()));
+                }
+            } else if (cc == kEndOfFileMarker) {
+                return advanceAndEmitToken(source, VTTToken::StringToken(result.toString()));
+            } else {
+                result.append(cc);
+                WEBVTT_ADVANCE_TO(DataState);
+            }
+        }
+        END_STATE()
+
+        WEBVTT_BEGIN_STATE(EscapeState) {
+            if (cc == ';') {
+                if (equalLiteral(buffer, "&amp")) {
+                    result.append('&');
+                } else if (equalLiteral(buffer, "&lt")) {
+                    result.append('<');
+                } else if (equalLiteral(buffer, "&gt")) {
+                    result.append('>');
+                } else if (equalLiteral(buffer, "&lrm")) {
+                    result.append(leftToRightMark);
+                } else if (equalLiteral(buffer, "&rlm")) {
+                    result.append(rightToLeftMark);
+                } else if (equalLiteral(buffer, "&nbsp")) {
+                    result.append(noBreakSpace);
+                } else {
+                    buffer.append(static_cast<LChar>(cc));
+                    result.append(buffer);
+                }
+                buffer.clear();
+                WEBVTT_ADVANCE_TO(DataState);
+            } else if (isASCIIAlphanumeric(cc)) {
+                buffer.append(static_cast<LChar>(cc));
+                WEBVTT_ADVANCE_TO(EscapeState);
+            } else if (cc == kEndOfFileMarker) {
+                result.append(buffer);
+                return advanceAndEmitToken(source, VTTToken::StringToken(result.toString()));
+            } else {
+                if (!equalLiteral(buffer, "&"))
+                    result.append(buffer);
+                buffer.clear();
+                WEBVTT_ADVANCE_TO(DataState);
+            }
+        }
+        END_STATE()
+
+        WEBVTT_BEGIN_STATE(TagState) {
+            if (isTokenizerWhitespace(cc)) {
+                ASSERT(result.isEmpty());
+                WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+            } else if (cc == '.') {
+                ASSERT(result.isEmpty());
+                WEBVTT_ADVANCE_TO(StartTagClassState);
+            } else if (cc == '/') {
+                WEBVTT_ADVANCE_TO(EndTagState);
+            } else if (WTF::isASCIIDigit(cc)) {
+                result.append(cc);
+                WEBVTT_ADVANCE_TO(TimestampTagState);
+            } else if (cc == '>' || cc == kEndOfFileMarker) {
+                ASSERT(result.isEmpty());
+                return advanceAndEmitToken(source, VTTToken::StartTag(result.toString()));
+            } else {
+                result.append(cc);
+                WEBVTT_ADVANCE_TO(StartTagState);
+            }
+        }
+        END_STATE()
+
+        WEBVTT_BEGIN_STATE(StartTagState) {
+            if (isTokenizerWhitespace(cc)) {
+                WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+            } else if (cc == '.') {
+                WEBVTT_ADVANCE_TO(StartTagClassState);
+            } else if (cc == '>' || cc == kEndOfFileMarker) {
+                return advanceAndEmitToken(source, VTTToken::StartTag(result.toString()));
+            } else {
+                result.append(cc);
+                WEBVTT_ADVANCE_TO(StartTagState);
+            }
+        }
+        END_STATE()
+
+        WEBVTT_BEGIN_STATE(StartTagClassState) {
+            if (isTokenizerWhitespace(cc)) {
+                addNewClass(classes, buffer);
+                buffer.clear();
+                WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+            } else if (cc == '.') {
+                addNewClass(classes, buffer);
+                buffer.clear();
+                WEBVTT_ADVANCE_TO(StartTagClassState);
+            } else if (cc == '>' || cc == kEndOfFileMarker) {
+                addNewClass(classes, buffer);
+                buffer.clear();
+                return advanceAndEmitToken(source, VTTToken::StartTag(result.toString(), classes.toAtomicString()));
+            } else {
+                buffer.append(cc);
+                WEBVTT_ADVANCE_TO(StartTagClassState);
+            }
+        }
+        END_STATE()
+
+        WEBVTT_BEGIN_STATE(StartTagAnnotationState) {
+            if (cc == '>' || cc == kEndOfFileMarker) {
+                return advanceAndEmitToken(source, VTTToken::StartTag(result.toString(), classes.toAtomicString(), buffer.toAtomicString()));
+            }
+            buffer.append(cc);
+            WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+        }
+        END_STATE()
+
+        WEBVTT_BEGIN_STATE(EndTagState) {
+            if (cc == '>' || cc == kEndOfFileMarker)
+                return advanceAndEmitToken(source, VTTToken::EndTag(result.toString()));
+            result.append(cc);
+            WEBVTT_ADVANCE_TO(EndTagState);
+        }
+        END_STATE()
+
+        WEBVTT_BEGIN_STATE(TimestampTagState) {
+            if (cc == '>' || cc == kEndOfFileMarker)
+                return advanceAndEmitToken(source, VTTToken::TimestampTag(result.toString()));
+            result.append(cc);
+            WEBVTT_ADVANCE_TO(TimestampTagState);
+        }
+        END_STATE()
+
+    }
+
+    ASSERT_NOT_REACHED();
+    return false;
+}
+
+}
+
diff --git a/Source/core/html/track/WebVTTTokenizer.h b/Source/core/html/track/vtt/VTTTokenizer.h
similarity index 63%
rename from Source/core/html/track/WebVTTTokenizer.h
rename to Source/core/html/track/vtt/VTTTokenizer.h
index 097f508..a5862b5 100644
--- a/Source/core/html/track/WebVTTTokenizer.h
+++ b/Source/core/html/track/vtt/VTTTokenizer.h
@@ -28,16 +28,16 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef WebVTTTokenizer_h
-#define WebVTTTokenizer_h
+#ifndef VTTTokenizer_h
+#define VTTTokenizer_h
 
 #include "core/html/parser/InputStreamPreprocessor.h"
-#include "core/html/track/WebVTTToken.h"
+#include "core/html/track/vtt/VTTToken.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
-class WebVTTTokenizerState {
+class VTTTokenizerState {
 public:
     enum State {
         DataState,
@@ -47,67 +47,50 @@
         StartTagClassState,
         StartTagAnnotationState,
         EndTagState,
-        EndTagOpenState,
         TimestampTagState,
     };
 };
 
-class WebVTTTokenizer {
-    WTF_MAKE_NONCOPYABLE(WebVTTTokenizer);
-    WTF_MAKE_FAST_ALLOCATED;
+class VTTTokenizer {
+    WTF_MAKE_NONCOPYABLE(VTTTokenizer);
 public:
-    static PassOwnPtr<WebVTTTokenizer> create() { return adoptPtr(new WebVTTTokenizer); }
+    explicit VTTTokenizer(const String& input);
 
-    typedef WebVTTTokenizerState State;
+    typedef VTTTokenizerState State;
 
     void reset();
 
-    bool nextToken(SegmentedString&, WebVTTToken&);
+    bool nextToken(VTTToken&);
 
-    inline bool haveBufferedCharacterToken()
-    {
-        return m_token->type() == WebVTTToken::Type::Character;
-    }
+    inline bool haveBufferedCharacterToken() { return false; }
 
-    inline void bufferCharacter(UChar character)
+    inline bool advanceAndEmitToken(SegmentedString& source, const VTTToken& token)
     {
-        ASSERT(character != kEndOfFileMarker);
-        m_token->ensureIsCharacterToken();
-        m_token->appendToCharacter(character);
-    }
-
-    inline bool emitAndResumeIn(SegmentedString& source, State::State state)
-    {
-        m_state = state;
         source.advanceAndUpdateLineNumber();
-        return true;
+        return emitToken(token);
     }
 
-    inline bool emitEndOfFile(SegmentedString& source)
+    inline bool emitToken(const VTTToken& token)
     {
-        if (haveBufferedCharacterToken())
-            return true;
-        m_state = State::DataState;
-        source.advanceAndUpdateLineNumber();
-        m_token->clear();
-        m_token->makeEndOfFile();
+        *m_token = token;
         return true;
     }
 
     bool shouldSkipNullCharacters() const { return true; }
 
 private:
-    WebVTTTokenizer();
-
     // m_token is owned by the caller. If nextToken is not on the stack,
     // this member might be pointing to unallocated memory.
-    WebVTTToken* m_token;
-    WebVTTTokenizerState::State m_state;
+    VTTToken* m_token;
 
-    Vector<LChar, 32> m_buffer;
+    // This member does not really need to be an instance member - it's only used in nextToken.
+    // The reason it's stored here is because of the use of the ADVANCE_TO state helpers.
+    VTTTokenizerState::State m_state;
+
+    SegmentedString m_input;
 
     // ://www.whatwg.org/specs/web-apps/current-work/#preprocessing-the-input-stream
-    InputStreamPreprocessor<WebVTTTokenizer> m_inputStreamPreprocessor;
+    InputStreamPreprocessor<VTTTokenizer> m_inputStreamPreprocessor;
 };
 
 }
diff --git a/Source/core/inspector/DOMEditor.cpp b/Source/core/inspector/DOMEditor.cpp
index 152d47f..2573e69 100644
--- a/Source/core/inspector/DOMEditor.cpp
+++ b/Source/core/inspector/DOMEditor.cpp
@@ -56,22 +56,22 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
         m_anchorNode = m_node->nextSibling();
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), es);
-        return !es.hadException();
+        m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), exceptionState);
+        return !exceptionState.hadException();
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        m_parentNode->removeChild(m_node.get(), es);
-        return !es.hadException();
+        m_parentNode->removeChild(m_node.get(), exceptionState);
+        return !exceptionState.hadException();
     }
 
 private:
@@ -91,33 +91,33 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
         if (m_node->parentNode()) {
             m_removeChildAction = adoptPtr(new RemoveChildAction(m_node->parentNode(), m_node.get()));
-            if (!m_removeChildAction->perform(es))
+            if (!m_removeChildAction->perform(exceptionState))
                 return false;
         }
-        m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), es);
-        return !es.hadException();
+        m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), exceptionState);
+        return !exceptionState.hadException();
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        m_parentNode->removeChild(m_node.get(), es);
-        if (es.hadException())
+        m_parentNode->removeChild(m_node.get(), exceptionState);
+        if (exceptionState.hadException())
             return false;
         if (m_removeChildAction)
-            return m_removeChildAction->undo(es);
+            return m_removeChildAction->undo(exceptionState);
         return true;
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        if (m_removeChildAction && !m_removeChildAction->redo(es))
+        if (m_removeChildAction && !m_removeChildAction->redo(exceptionState))
             return false;
-        m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), es);
-        return !es.hadException();
+        m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), exceptionState);
+        return !exceptionState.hadException();
     }
 
 private:
@@ -137,15 +137,15 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
         m_value = m_element->getAttribute(m_name);
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        m_element->setAttribute(m_name, m_value, es);
+        m_element->setAttribute(m_name, m_value, exceptionState);
         return true;
     }
 
@@ -173,26 +173,26 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
         m_hadAttribute = m_element->hasAttribute(m_name);
         if (m_hadAttribute)
             m_oldValue = m_element->getAttribute(m_name);
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
         if (m_hadAttribute)
-            m_element->setAttribute(m_name, m_oldValue, es);
+            m_element->setAttribute(m_name, m_oldValue, exceptionState);
         else
             m_element->removeAttribute(m_name);
         return true;
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        m_element->setAttribute(m_name, m_value, es);
+        m_element->setAttribute(m_name, m_value, exceptionState);
         return true;
     }
 
@@ -218,23 +218,23 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
         m_oldHTML = createMarkup(m_node.get());
         ASSERT(m_node->ownerDocument());
         DOMPatchSupport domPatchSupport(m_domEditor.get(), *m_node->ownerDocument());
-        m_newNode = domPatchSupport.patchNode(m_node.get(), m_html, es);
-        return !es.hadException();
+        m_newNode = domPatchSupport.patchNode(m_node.get(), m_html, exceptionState);
+        return !exceptionState.hadException();
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        return m_history->undo(es);
+        return m_history->undo(exceptionState);
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        return m_history->redo(es);
+        return m_history->redo(exceptionState);
     }
 
     Node* newNode()
@@ -262,10 +262,10 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
         m_oldText = m_textNode->wholeText();
-        return redo(es);
+        return redo(exceptionState);
     }
 
     virtual bool undo(ExceptionState&)
@@ -297,21 +297,21 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        m_parentNode->replaceChild(m_oldNode, m_newNode.get(), es);
-        return !es.hadException();
+        m_parentNode->replaceChild(m_oldNode, m_newNode.get(), exceptionState);
+        return !exceptionState.hadException();
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        m_parentNode->replaceChild(m_newNode, m_oldNode.get(), es);
-        return !es.hadException();
+        m_parentNode->replaceChild(m_newNode, m_oldNode.get(), exceptionState);
+        return !exceptionState.hadException();
     }
 
 private:
@@ -358,102 +358,102 @@
 
 DOMEditor::~DOMEditor() { }
 
-bool DOMEditor::insertBefore(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode, ExceptionState& es)
+bool DOMEditor::insertBefore(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new InsertBeforeAction(parentNode, node, anchorNode)), es);
+    return m_history->perform(adoptPtr(new InsertBeforeAction(parentNode, node, anchorNode)), exceptionState);
 }
 
-bool DOMEditor::removeChild(Node* parentNode, Node* node, ExceptionState& es)
+bool DOMEditor::removeChild(Node* parentNode, Node* node, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new RemoveChildAction(parentNode, node)), es);
+    return m_history->perform(adoptPtr(new RemoveChildAction(parentNode, node)), exceptionState);
 }
 
-bool DOMEditor::setAttribute(Element* element, const String& name, const String& value, ExceptionState& es)
+bool DOMEditor::setAttribute(Element* element, const String& name, const String& value, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new SetAttributeAction(element, name, value)), es);
+    return m_history->perform(adoptPtr(new SetAttributeAction(element, name, value)), exceptionState);
 }
 
-bool DOMEditor::removeAttribute(Element* element, const String& name, ExceptionState& es)
+bool DOMEditor::removeAttribute(Element* element, const String& name, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new RemoveAttributeAction(element, name)), es);
+    return m_history->perform(adoptPtr(new RemoveAttributeAction(element, name)), exceptionState);
 }
 
-bool DOMEditor::setOuterHTML(Node* node, const String& html, Node** newNode, ExceptionState& es)
+bool DOMEditor::setOuterHTML(Node* node, const String& html, Node** newNode, ExceptionState& exceptionState)
 {
     OwnPtr<SetOuterHTMLAction> action = adoptPtr(new SetOuterHTMLAction(node, html));
     SetOuterHTMLAction* rawAction = action.get();
-    bool result = m_history->perform(action.release(), es);
+    bool result = m_history->perform(action.release(), exceptionState);
     if (result)
         *newNode = rawAction->newNode();
     return result;
 }
 
-bool DOMEditor::replaceWholeText(Text* textNode, const String& text, ExceptionState& es)
+bool DOMEditor::replaceWholeText(Text* textNode, const String& text, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new ReplaceWholeTextAction(textNode, text)), es);
+    return m_history->perform(adoptPtr(new ReplaceWholeTextAction(textNode, text)), exceptionState);
 }
 
-bool DOMEditor::replaceChild(Node* parentNode, PassRefPtr<Node> newNode, Node* oldNode, ExceptionState& es)
+bool DOMEditor::replaceChild(Node* parentNode, PassRefPtr<Node> newNode, Node* oldNode, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new ReplaceChildNodeAction(parentNode, newNode, oldNode)), es);
+    return m_history->perform(adoptPtr(new ReplaceChildNodeAction(parentNode, newNode, oldNode)), exceptionState);
 }
 
-bool DOMEditor::setNodeValue(Node* node, const String& value, ExceptionState& es)
+bool DOMEditor::setNodeValue(Node* node, const String& value, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new SetNodeValueAction(node, value)), es);
+    return m_history->perform(adoptPtr(new SetNodeValueAction(node, value)), exceptionState);
 }
 
-static void populateErrorString(ExceptionState& es, ErrorString* errorString)
+static void populateErrorString(ExceptionState& exceptionState, ErrorString* errorString)
 {
-    if (es.hadException())
-        *errorString = DOMException::getErrorName(es.code());
+    if (exceptionState.hadException())
+        *errorString = DOMException::getErrorName(exceptionState.code());
 }
 
 bool DOMEditor::insertBefore(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode, ErrorString* errorString)
 {
-    TrackExceptionState es;
-    bool result = insertBefore(parentNode, node, anchorNode, es);
-    populateErrorString(es, errorString);
+    TrackExceptionState exceptionState;
+    bool result = insertBefore(parentNode, node, anchorNode, exceptionState);
+    populateErrorString(exceptionState, errorString);
     return result;
 }
 
 bool DOMEditor::removeChild(Node* parentNode, Node* node, ErrorString* errorString)
 {
-    TrackExceptionState es;
-    bool result = removeChild(parentNode, node, es);
-    populateErrorString(es, errorString);
+    TrackExceptionState exceptionState;
+    bool result = removeChild(parentNode, node, exceptionState);
+    populateErrorString(exceptionState, errorString);
     return result;
 }
 
 bool DOMEditor::setAttribute(Element* element, const String& name, const String& value, ErrorString* errorString)
 {
-    TrackExceptionState es;
-    bool result = setAttribute(element, name, value, es);
-    populateErrorString(es, errorString);
+    TrackExceptionState exceptionState;
+    bool result = setAttribute(element, name, value, exceptionState);
+    populateErrorString(exceptionState, errorString);
     return result;
 }
 
 bool DOMEditor::removeAttribute(Element* element, const String& name, ErrorString* errorString)
 {
-    TrackExceptionState es;
-    bool result = removeAttribute(element, name, es);
-    populateErrorString(es, errorString);
+    TrackExceptionState exceptionState;
+    bool result = removeAttribute(element, name, exceptionState);
+    populateErrorString(exceptionState, errorString);
     return result;
 }
 
 bool DOMEditor::setOuterHTML(Node* node, const String& html, Node** newNode, ErrorString* errorString)
 {
-    TrackExceptionState es;
-    bool result = setOuterHTML(node, html, newNode, es);
-    populateErrorString(es, errorString);
+    TrackExceptionState exceptionState;
+    bool result = setOuterHTML(node, html, newNode, exceptionState);
+    populateErrorString(exceptionState, errorString);
     return result;
 }
 
 bool DOMEditor::replaceWholeText(Text* textNode, const String& text, ErrorString* errorString)
 {
-    TrackExceptionState es;
-    bool result = replaceWholeText(textNode, text, es);
-    populateErrorString(es, errorString);
+    TrackExceptionState exceptionState;
+    bool result = replaceWholeText(textNode, text, exceptionState);
+    populateErrorString(exceptionState, errorString);
     return result;
 }
 
diff --git a/Source/core/inspector/DOMPatchSupport.cpp b/Source/core/inspector/DOMPatchSupport.cpp
index 7dc4de3..d5c7cd5 100644
--- a/Source/core/inspector/DOMPatchSupport.cpp
+++ b/Source/core/inspector/DOMPatchSupport.cpp
@@ -113,7 +113,7 @@
     }
 }
 
-Node* DOMPatchSupport::patchNode(Node* node, const String& markup, ExceptionState& es)
+Node* DOMPatchSupport::patchNode(Node* node, const String& markup, ExceptionState& exceptionState)
 {
     // Don't parse <html> as a fragment.
     if (node->isDocumentNode() || (node->parentNode() && node->parentNode()->isDocumentNode())) {
@@ -150,15 +150,15 @@
     for (Node* child = node->nextSibling(); child; child = child->nextSibling())
         newList.append(createDigest(child, 0));
 
-    if (!innerPatchChildren(parentNode, oldList, newList, es)) {
+    if (!innerPatchChildren(parentNode, oldList, newList, exceptionState)) {
         // Fall back to total replace.
-        if (!m_domEditor->replaceChild(parentNode, fragment.release(), node, es))
+        if (!m_domEditor->replaceChild(parentNode, fragment.release(), node, exceptionState))
             return 0;
     }
     return previousSibling ? previousSibling->nextSibling() : parentNode->firstChild();
 }
 
-bool DOMPatchSupport::innerPatchNode(Digest* oldDigest, Digest* newDigest, ExceptionState& es)
+bool DOMPatchSupport::innerPatchNode(Digest* oldDigest, Digest* newDigest, ExceptionState& exceptionState)
 {
     if (oldDigest->m_sha1 == newDigest->m_sha1)
         return true;
@@ -167,10 +167,10 @@
     Node* newNode = newDigest->m_node;
 
     if (newNode->nodeType() != oldNode->nodeType() || newNode->nodeName() != oldNode->nodeName())
-        return m_domEditor->replaceChild(oldNode->parentNode(), newNode, oldNode, es);
+        return m_domEditor->replaceChild(oldNode->parentNode(), newNode, oldNode, exceptionState);
 
     if (oldNode->nodeValue() != newNode->nodeValue()) {
-        if (!m_domEditor->setNodeValue(oldNode, newNode->nodeValue(), es))
+        if (!m_domEditor->setNodeValue(oldNode, newNode->nodeValue(), exceptionState))
             return false;
     }
 
@@ -185,7 +185,7 @@
         if (oldElement->hasAttributesWithoutUpdate()) {
             while (oldElement->attributeCount()) {
                 const Attribute* attribute = oldElement->attributeItem(0);
-                if (!m_domEditor->removeAttribute(oldElement, attribute->localName(), es))
+                if (!m_domEditor->removeAttribute(oldElement, attribute->localName(), exceptionState))
                     return false;
             }
         }
@@ -195,13 +195,13 @@
             size_t numAttrs = newElement->attributeCount();
             for (size_t i = 0; i < numAttrs; ++i) {
                 const Attribute* attribute = newElement->attributeItem(i);
-                if (!m_domEditor->setAttribute(oldElement, attribute->name().localName(), attribute->value(), es))
+                if (!m_domEditor->setAttribute(oldElement, attribute->name().localName(), attribute->value(), exceptionState))
                     return false;
             }
         }
     }
 
-    bool result = innerPatchChildren(oldElement, oldDigest->m_children, newDigest->m_children, es);
+    bool result = innerPatchChildren(oldElement, oldDigest->m_children, newDigest->m_children, exceptionState);
     m_unusedNodesMap.remove(newDigest->m_sha1);
     return result;
 }
@@ -294,7 +294,7 @@
     return make_pair(oldMap, newMap);
 }
 
-bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector<OwnPtr<Digest> >& oldList, const Vector<OwnPtr<Digest> >& newList, ExceptionState& es)
+bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector<OwnPtr<Digest> >& oldList, const Vector<OwnPtr<Digest> >& newList, ExceptionState& exceptionState)
 {
     pair<ResultMap, ResultMap> resultMaps = diff(oldList, newList);
     ResultMap& oldMap = resultMaps.first;
@@ -332,11 +332,11 @@
             if (anchorAfter - anchorCandidate == 1 && anchorCandidate < newList.size())
                 merges.set(newList[anchorCandidate].get(), oldList[i].get());
             else {
-                if (!removeChildAndMoveToNew(oldList[i].get(), es))
+                if (!removeChildAndMoveToNew(oldList[i].get(), exceptionState))
                     return false;
             }
         } else {
-            if (!removeChildAndMoveToNew(oldList[i].get(), es))
+            if (!removeChildAndMoveToNew(oldList[i].get(), exceptionState))
                 return false;
         }
     }
@@ -369,7 +369,7 @@
 
     // 2. Patch nodes marked for merge.
     for (HashMap<Digest*, Digest*>::iterator it = merges.begin(); it != merges.end(); ++it) {
-        if (!innerPatchNode(it->value, it->key, es))
+        if (!innerPatchNode(it->value, it->key, exceptionState))
             return false;
     }
 
@@ -377,7 +377,7 @@
     for (size_t i = 0; i < newMap.size(); ++i) {
         if (newMap[i].first || merges.contains(newList[i].get()))
             continue;
-        if (!insertBeforeAndMarkAsUsed(parentNode, newList[i].get(), parentNode->childNode(i), es))
+        if (!insertBeforeAndMarkAsUsed(parentNode, newList[i].get(), parentNode->childNode(i), exceptionState))
             return false;
     }
 
@@ -392,7 +392,7 @@
         if (node->hasTagName(bodyTag) || node->hasTagName(headTag))
             continue; // Never move head or body, move the rest of the nodes around them.
 
-        if (!m_domEditor->insertBefore(parentNode, node.release(), anchorNode, es))
+        if (!m_domEditor->insertBefore(parentNode, node.release(), anchorNode, exceptionState))
             return false;
     }
     return true;
@@ -448,17 +448,17 @@
     return adoptPtr(digest);
 }
 
-bool DOMPatchSupport::insertBeforeAndMarkAsUsed(ContainerNode* parentNode, Digest* digest, Node* anchor, ExceptionState& es)
+bool DOMPatchSupport::insertBeforeAndMarkAsUsed(ContainerNode* parentNode, Digest* digest, Node* anchor, ExceptionState& exceptionState)
 {
-    bool result = m_domEditor->insertBefore(parentNode, digest->m_node, anchor, es);
+    bool result = m_domEditor->insertBefore(parentNode, digest->m_node, anchor, exceptionState);
     markNodeAsUsed(digest);
     return result;
 }
 
-bool DOMPatchSupport::removeChildAndMoveToNew(Digest* oldDigest, ExceptionState& es)
+bool DOMPatchSupport::removeChildAndMoveToNew(Digest* oldDigest, ExceptionState& exceptionState)
 {
     RefPtr<Node> oldNode = oldDigest->m_node;
-    if (!m_domEditor->removeChild(oldNode->parentNode(), oldNode.get(), es))
+    if (!m_domEditor->removeChild(oldNode->parentNode(), oldNode.get(), exceptionState))
         return false;
 
     // Diff works within levels. In order not to lose the node identity when user
@@ -470,7 +470,7 @@
     if (it != m_unusedNodesMap.end()) {
         Digest* newDigest = it->value;
         Node* newNode = newDigest->m_node;
-        if (!m_domEditor->replaceChild(newNode->parentNode(), oldNode, newNode, es))
+        if (!m_domEditor->replaceChild(newNode->parentNode(), oldNode, newNode, exceptionState))
             return false;
         newDigest->m_node = oldNode.get();
         markNodeAsUsed(newDigest);
@@ -478,7 +478,7 @@
     }
 
     for (size_t i = 0; i < oldDigest->m_children.size(); ++i) {
-        if (!removeChildAndMoveToNew(oldDigest->m_children[i].get(), es))
+        if (!removeChildAndMoveToNew(oldDigest->m_children[i].get(), exceptionState))
             return false;
     }
     return true;
diff --git a/Source/core/inspector/InjectedScriptBase.cpp b/Source/core/inspector/InjectedScriptBase.cpp
index b625fce..574ce40 100644
--- a/Source/core/inspector/InjectedScriptBase.cpp
+++ b/Source/core/inspector/InjectedScriptBase.cpp
@@ -34,6 +34,7 @@
 #include "core/inspector/InjectedScriptBase.h"
 
 #include "bindings/v8/ScriptFunctionCall.h"
+#include "bindings/v8/ScriptState.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "platform/JSONValues.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/inspector/InjectedScriptCanvasModuleSource.js b/Source/core/inspector/InjectedScriptCanvasModuleSource.js
index 00d50cf..f94ab04 100644
--- a/Source/core/inspector/InjectedScriptCanvasModuleSource.js
+++ b/Source/core/inspector/InjectedScriptCanvasModuleSource.js
@@ -118,6 +118,14 @@
             return result;
         }
 
+        // Try to convert to a primitive value via valueOf().
+        if (typeof obj.valueOf === "function") {
+            var value = obj.valueOf();
+            var valueType = typeof value;
+            if (valueType !== "object" && valueType !== "function")
+                return value;
+        }
+
         console.error("ASSERT_NOT_REACHED: failed to clone object: ", obj);
         return obj;
     },
@@ -2750,6 +2758,7 @@
         var gl = this.wrappedObject();
         var bindingParameter;
         var bindMethodName;
+        target = +target; // Explicitly convert to a number.
         var bindMethodTarget = target;
         switch (target) {
         case gl.ARRAY_BUFFER:
diff --git a/Source/core/inspector/InjectedScriptSource.js b/Source/core/inspector/InjectedScriptSource.js
index 9dcecf2..a5a3aae 100644
--- a/Source/core/inspector/InjectedScriptSource.js
+++ b/Source/core/inspector/InjectedScriptSource.js
@@ -64,6 +64,17 @@
 }
 
 /**
+ * @param {*} obj
+ * @return {string}
+ */
+function toStringDescription(obj)
+{
+    if (typeof obj === "number" && obj === 0 && 1 / obj < 0)
+        return "-0"; // Negative zero.
+    return "" + obj;
+}
+
+/**
  * Please use this bind, not the one from Function.prototype
  * @param {function(...)} func
  * @param {Object} thisObject
@@ -539,10 +550,10 @@
                 throw "Could not find object with given id";
 
             return resolvedArg;
-        } else if ("value" in callArgumentJson)
+        } else if ("value" in callArgumentJson) {
             return callArgumentJson.value;
-        else
-            return undefined;
+        }
+        return undefined;
     },
 
     /**
@@ -574,10 +585,9 @@
     {
         var remoteObject = this._wrapObject(value, objectGroup);
         try {
-            remoteObject.description = toString(value);
+            remoteObject.description = toStringDescription(value);
         } catch (e) {}
-        return { wasThrown: true,
-                 result: remoteObject };
+        return { wasThrown: true, result: remoteObject };
     },
 
     /**
@@ -931,7 +941,7 @@
 
         // Provide user-friendly number values.
         if (this.type === "number")
-            this.description = toString(object);
+            this.description = toStringDescription(object);
         return;
     }
 
@@ -1023,13 +1033,15 @@
                 var type = typeof value;
                 if (!descriptor.enumerable && type === "function")
                     continue;
+                if (type === "undefined" && injectedScript._isHTMLAllCollection(value))
+                    type = "object";
 
                 if (InjectedScript.primitiveTypes[type]) {
                     if (type === "string" && value.length > maxLength) {
                         value = this._abbreviateString(value, maxLength, true);
                         preview.lossless = false;
                     }
-                    this._appendPropertyPreview(preview, { name: name, type: type, value: toString(value) }, propertiesThreshold);
+                    this._appendPropertyPreview(preview, { name: name, type: type, value: toStringDescription(value) }, propertiesThreshold);
                     continue;
                 }
 
@@ -1107,6 +1119,8 @@
     this.location = { scriptId: toString(callFrame.sourceID), lineNumber: callFrame.line, columnNumber: callFrame.column };
     this.scopeChain = this._wrapScopeChain(callFrame);
     this.this = injectedScript._wrapObject(callFrame.thisObject, "backtrace");
+    if (callFrame.isAtReturn)
+        this.returnValue = injectedScript._wrapObject(callFrame.returnValue, "backtrace");
 }
 
 InjectedScript.CallFrameProxy.prototype = {
diff --git a/Source/core/inspector/InspectorAgent.cpp b/Source/core/inspector/InspectorAgent.cpp
index daf14ef..4621e7a 100644
--- a/Source/core/inspector/InspectorAgent.cpp
+++ b/Source/core/inspector/InspectorAgent.cpp
@@ -44,7 +44,7 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "platform/JSONValues.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index 0ee38c8..a1b8865 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -63,6 +63,8 @@
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
+#include "core/page/Page.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/WidthIterator.h"
 #include "core/rendering/InlineTextBox.h"
@@ -97,18 +99,11 @@
 
 class StyleSheetAppender {
 public:
-    StyleSheetAppender(CSSStyleSheetToInspectorStyleSheet& cssStyleSheetToInspectorStyleSheet, Vector<CSSStyleSheet*>& result)
-        : m_cssStyleSheetToInspectorStyleSheet(cssStyleSheetToInspectorStyleSheet)
-        , m_result(result) { }
+    StyleSheetAppender(Vector<CSSStyleSheet*>& result)
+        : m_result(result) { }
 
     void run(CSSStyleSheet* styleSheet)
     {
-        RefPtr<InspectorStyleSheet> inspectorStyleSheet = m_cssStyleSheetToInspectorStyleSheet.get(styleSheet);
-        // Avoid creating m_childRuleCSSOMWrappers in the stylesheet if it is in the process of re-parsing.
-        // Otherwise m_childRuleCSSOMWrappers size will be initialized only for a part of rules, resulting in an ASSERT failure in CSSStyleSheet::item().
-        // Instead, wait for the RuleMutationScope destruction and handle the complete CSSStyleSheet.
-        if (inspectorStyleSheet && inspectorStyleSheet->isReparsing())
-            return;
         m_result.append(styleSheet);
         for (unsigned i = 0, size = styleSheet->length(); i < size; ++i) {
             CSSRule* rule = styleSheet->item(i);
@@ -121,7 +116,6 @@
     }
 
 private:
-    CSSStyleSheetToInspectorStyleSheet& m_cssStyleSheetToInspectorStyleSheet;
     Vector<CSSStyleSheet*>& m_result;
 };
 
@@ -326,25 +320,25 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
         if (!m_styleSheet->getText(&m_oldText))
             return false;
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        if (m_styleSheet->setText(m_oldText, es)) {
+        if (m_styleSheet->setText(m_oldText, exceptionState)) {
             m_styleSheet->reparseStyleSheet(m_oldText);
             return true;
         }
         return false;
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        if (m_styleSheet->setText(m_text, es)) {
+        if (m_styleSheet->setText(m_text, exceptionState)) {
             m_styleSheet->reparseStyleSheet(m_text);
             return true;
         }
@@ -384,20 +378,20 @@
         return mergeId() + ": " + m_oldText + " -> " + m_text;
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
         String placeholder;
-        return m_styleSheet->setStyleText(m_cssId, m_oldText, &placeholder, es);
+        return m_styleSheet->setStyleText(m_cssId, m_oldText, &placeholder, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        return m_styleSheet->setStyleText(m_cssId, m_text, &m_oldText, es);
+        return m_styleSheet->setStyleText(m_cssId, m_text, &m_oldText, exceptionState);
     }
 
     virtual String mergeId()
@@ -436,21 +430,21 @@
         return mergeId() + ": " + m_oldText + " -> " + m_text;
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
         String placeholder;
-        return m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_overwrite ? m_oldText : "", true, &placeholder, es);
+        return m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_overwrite ? m_oldText : "", true, &placeholder, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
         String oldText;
-        bool result = m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_text, m_overwrite, &oldText, es);
+        bool result = m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_text, m_overwrite, &oldText, exceptionState);
         m_oldText = oldText.stripWhiteSpace();
         // FIXME: remove this once the model handles this case.
         if (!m_oldText.endsWith(';'))
@@ -490,19 +484,19 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, !m_disable, es);
+        return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, !m_disable, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, m_disable, es);
+        return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, m_disable, exceptionState);
     }
 
 private:
@@ -521,22 +515,22 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
-        m_oldSelector = m_styleSheet->ruleSelector(m_cssId, es);
-        if (es.hadException())
+        m_oldSelector = m_styleSheet->ruleSelector(m_cssId, exceptionState);
+        if (exceptionState.hadException())
             return false;
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        return m_styleSheet->setRuleSelector(m_cssId, m_oldSelector, es);
+        return m_styleSheet->setRuleSelector(m_cssId, m_oldSelector, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        return m_styleSheet->setRuleSelector(m_cssId, m_selector, es);
+        return m_styleSheet->setRuleSelector(m_cssId, m_selector, exceptionState);
     }
 
 private:
@@ -554,20 +548,20 @@
     {
     }
 
-    virtual bool perform(ExceptionState& es)
+    virtual bool perform(ExceptionState& exceptionState)
     {
-        return redo(es);
+        return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& es)
+    virtual bool undo(ExceptionState& exceptionState)
     {
-        return m_styleSheet->deleteRule(m_newId, es);
+        return m_styleSheet->deleteRule(m_newId, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& es)
+    virtual bool redo(ExceptionState& exceptionState)
     {
-        CSSStyleRule* cssStyleRule = m_styleSheet->addRule(m_selector, es);
-        if (es.hadException())
+        CSSStyleRule* cssStyleRule = m_styleSheet->addRule(m_selector, exceptionState);
+        if (exceptionState.hadException())
             return false;
         m_newId = m_styleSheet->ruleId(cssStyleRule);
         return true;
@@ -622,6 +616,8 @@
     , m_pageAgent(pageAgent)
     , m_resourceAgent(resourceAgent)
     , m_lastStyleSheetId(1)
+    , m_styleSheetsPendingMutation(0)
+    , m_styleDeclarationPendingMutation(false)
     , m_creatingViaInspectorStyleSheet(false)
     , m_isSettingStyleSheetText(false)
 {
@@ -777,6 +773,40 @@
     m_frontend->namedFlowRemoved(documentNodeId, namedFlow->name().string());
 }
 
+void InspectorCSSAgent::willMutateRules()
+{
+    ++m_styleSheetsPendingMutation;
+}
+
+void InspectorCSSAgent::didMutateRules(CSSStyleSheet* styleSheet)
+{
+    --m_styleSheetsPendingMutation;
+    ASSERT(m_styleSheetsPendingMutation >= 0);
+
+    if (!styleSheetEditInProgress()) {
+        Document* owner = styleSheet->ownerDocument();
+        if (owner)
+            owner->modifiedStyleSheet(styleSheet, RecalcStyleDeferred, FullStyleUpdate);
+    }
+}
+
+void InspectorCSSAgent::willMutateStyle()
+{
+    m_styleDeclarationPendingMutation = true;
+}
+
+void InspectorCSSAgent::didMutateStyle(CSSStyleDeclaration* style, bool isInlineStyle)
+{
+    ASSERT(m_styleDeclarationPendingMutation);
+    m_styleDeclarationPendingMutation = false;
+    if (!styleSheetEditInProgress() && !isInlineStyle) {
+        CSSStyleSheet* parentSheet = style->parentStyleSheet();
+        Document* owner = parentSheet ? parentSheet->ownerDocument() : 0;
+        if (owner)
+            owner->modifiedStyleSheet(parentSheet, RecalcStyleDeferred, FullStyleUpdate);
+    }
+}
+
 void InspectorCSSAgent::didUpdateRegionLayout(Document* document, NamedFlow* namedFlow)
 {
     int documentNodeId = documentNodeWithRequestedFlowsId(document);
@@ -823,8 +853,9 @@
 
 void InspectorCSSAgent::activeStyleSheetsUpdated(Document* document, const StyleSheetVector& newSheets)
 {
-    if (m_isSettingStyleSheetText)
+    if (styleSheetEditInProgress())
         return;
+
     HashSet<CSSStyleSheet*> removedSheets;
     for (CSSStyleSheetToInspectorStyleSheet::iterator it = m_cssStyleSheetToInspectorStyleSheet.begin(); it != m_cssStyleSheetToInspectorStyleSheet.end(); ++it) {
         if (it->value->canBind() && (!it->key->ownerDocument() || it->key->ownerDocument() == document))
@@ -835,8 +866,8 @@
     for (size_t i = 0, size = newSheets.size(); i < size; ++i) {
         StyleSheet* newSheet = newSheets.at(i).get();
         if (newSheet->isCSSStyleSheet()) {
-            StyleSheetAppender appender(m_cssStyleSheetToInspectorStyleSheet, newSheetsVector);
-            appender.run(static_cast<CSSStyleSheet*>(newSheet));
+            StyleSheetAppender appender(newSheetsVector);
+            appender.run(toCSSStyleSheet(newSheet));
         }
     }
 
@@ -861,7 +892,7 @@
 
     for (HashSet<CSSStyleSheet*>::iterator it = addedSheets.begin(); it != addedSheets.end(); ++it) {
         if (!m_cssStyleSheetToInspectorStyleSheet.contains(*it)) {
-            InspectorStyleSheet* newStyleSheet = bindStyleSheet(static_cast<CSSStyleSheet*>(*it));
+            InspectorStyleSheet* newStyleSheet = bindStyleSheet(*it);
             if (m_frontend)
                 m_frontend->styleSheetAdded(newStyleSheet->buildObjectForStyleSheetInfo());
         }
@@ -916,8 +947,17 @@
     if (elementPseudoId)
         element = element->parentOrShadowHostElement();
 
+    Document* ownerDocument = element->ownerDocument();
+    // A non-active document has no styles.
+    if (!ownerDocument->isActive())
+        return;
+
+    // FIXME: It's really gross for the inspector to reach in and access StyleResolver
+    // directly here. We need to provide the Inspector better APIs to get this information
+    // without grabbing at internal style classes!
+
     // Matched rules.
-    StyleResolver* styleResolver = element->ownerDocument()->styleResolver();
+    StyleResolver* styleResolver = ownerDocument->styleResolver();
     // FIXME: This code should not pass DoNotIncludeStyleSheetInCSSOMWrapper. All CSSOMWrappers should always have a parent sheet or rule.
     RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoCSSRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
     matchedCSSRules = buildArrayForMatchedRuleList(matchedRules.get(), styleResolver, originalElement);
@@ -987,7 +1027,7 @@
     style = inspectorStyle->buildArrayForComputedStyle();
 }
 
-void InspectorCSSAgent::collectPlatformFontsForRenderer(RenderText* renderer, HashMap<String, int>* fontStats)
+void InspectorCSSAgent::collectPlatformFontsForRenderer(RenderText* renderer, HashCountedSet<String>* fontStats)
 {
     for (InlineTextBox* box = renderer->firstTextBox(); box; box = box->nextTextBox()) {
         RenderStyle* style = renderer->style(box->isFirstLineStyle());
@@ -996,12 +1036,11 @@
         WidthIterator it(&font, run, 0, false);
         GlyphBuffer glyphBuffer;
         it.advance(run.length(), &glyphBuffer);
-        for (int i = 0; i < glyphBuffer.size(); ++i) {
+        for (unsigned i = 0; i < glyphBuffer.size(); ++i) {
             String familyName = glyphBuffer.fontDataAt(i)->platformData().fontFamilyName();
             if (familyName.isNull())
                 familyName = "";
-            int value = fontStats->contains(familyName) ? fontStats->get(familyName) : 0;
-            fontStats->set(familyName, value + 1);
+            fontStats->add(familyName);
         }
     }
 }
@@ -1027,7 +1066,7 @@
         }
     }
 
-    HashMap<String, int> fontStats;
+    HashCountedSet<String> fontStats;
     for (size_t i = 0; i < textNodes.size(); ++i) {
         RenderText* renderer = toRenderText(textNodes[i]->renderer());
         collectPlatformFontsForRenderer(renderer, &fontStats);
@@ -1044,7 +1083,7 @@
     }
 
     platformFonts = TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage>::create();
-    for (HashMap<String, int>::iterator it = fontStats.begin(), end = fontStats.end(); it != end; ++it) {
+    for (HashCountedSet<String>::iterator it = fontStats.begin(), end = fontStats.end(); it != end; ++it) {
         RefPtr<TypeBuilder::CSS::PlatformFontUsage> platformFont = TypeBuilder::CSS::PlatformFontUsage::create()
             .setFamilyName(it->key)
             .setGlyphCount(it->value);
@@ -1095,9 +1134,9 @@
     if (!inspectorStyleSheet)
         return;
 
-    TrackExceptionState es;
-    m_domAgent->history()->perform(adoptPtr(new SetStyleSheetTextAction(inspectorStyleSheet, text)), es);
-    *errorString = InspectorDOMAgent::toErrorString(es);
+    TrackExceptionState exceptionState;
+    m_domAgent->history()->perform(adoptPtr(new SetStyleSheetTextAction(inspectorStyleSheet, text)), exceptionState);
+    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
 void InspectorCSSAgent::setStyleText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
@@ -1109,11 +1148,11 @@
     if (!inspectorStyleSheet)
         return;
 
-    TrackExceptionState es;
-    m_domAgent->history()->perform(adoptPtr(new SetStyleTextAction(inspectorStyleSheet, compoundId, text)), es);
-    if (!es.hadException())
+    TrackExceptionState exceptionState;
+    m_domAgent->history()->perform(adoptPtr(new SetStyleTextAction(inspectorStyleSheet, compoundId, text)), exceptionState);
+    if (!exceptionState.hadException())
         result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
-    *errorString = InspectorDOMAgent::toErrorString(es);
+    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
 void InspectorCSSAgent::setPropertyText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
@@ -1125,11 +1164,11 @@
     if (!inspectorStyleSheet)
         return;
 
-    TrackExceptionState es;
-    bool success = m_domAgent->history()->perform(adoptPtr(new SetPropertyTextAction(inspectorStyleSheet, compoundId, propertyIndex, text, overwrite)), es);
+    TrackExceptionState exceptionState;
+    bool success = m_domAgent->history()->perform(adoptPtr(new SetPropertyTextAction(inspectorStyleSheet, compoundId, propertyIndex, text, overwrite)), exceptionState);
     if (success)
         result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
-    *errorString = InspectorDOMAgent::toErrorString(es);
+    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
 void InspectorCSSAgent::toggleProperty(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
@@ -1141,11 +1180,11 @@
     if (!inspectorStyleSheet)
         return;
 
-    TrackExceptionState es;
-    bool success = m_domAgent->history()->perform(adoptPtr(new TogglePropertyAction(inspectorStyleSheet, compoundId, propertyIndex, disable)), es);
+    TrackExceptionState exceptionState;
+    bool success = m_domAgent->history()->perform(adoptPtr(new TogglePropertyAction(inspectorStyleSheet, compoundId, propertyIndex, disable)), exceptionState);
     if (success)
         result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
-    *errorString = InspectorDOMAgent::toErrorString(es);
+    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
 void InspectorCSSAgent::setRuleSelector(ErrorString* errorString, const RefPtr<JSONObject>& fullRuleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
@@ -1157,14 +1196,14 @@
     if (!inspectorStyleSheet)
         return;
 
-    TrackExceptionState es;
-    bool success = m_domAgent->history()->perform(adoptPtr(new SetRuleSelectorAction(inspectorStyleSheet, compoundId, selector)), es);
+    TrackExceptionState exceptionState;
+    bool success = m_domAgent->history()->perform(adoptPtr(new SetRuleSelectorAction(inspectorStyleSheet, compoundId, selector)), exceptionState);
 
     if (success) {
         CSSStyleRule* rule = inspectorStyleSheet->ruleForId(compoundId);
         result = inspectorStyleSheet->buildObjectForRule(rule, buildMediaListChain(rule));
     }
-    *errorString = InspectorDOMAgent::toErrorString(es);
+    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
 void InspectorCSSAgent::addRule(ErrorString* errorString, const int contextNodeId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
@@ -1179,12 +1218,12 @@
         return;
     }
 
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
     OwnPtr<AddRuleAction> action = adoptPtr(new AddRuleAction(inspectorStyleSheet, selector));
     AddRuleAction* rawAction = action.get();
-    bool success = m_domAgent->history()->perform(action.release(), es);
+    bool success = m_domAgent->history()->perform(action.release(), exceptionState);
     if (!success) {
-        *errorString = InspectorDOMAgent::toErrorString(es);
+        *errorString = InspectorDOMAgent::toErrorString(exceptionState);
         return;
     }
 
@@ -1408,14 +1447,14 @@
         for (unsigned i = 0; i < list->length(); ++i) {
             StyleSheet* styleSheet = list->item(i);
             if (styleSheet->isCSSStyleSheet())
-                collectStyleSheets(static_cast<CSSStyleSheet*>(styleSheet), result);
+                collectStyleSheets(toCSSStyleSheet(styleSheet), result);
         }
     }
 }
 
 void InspectorCSSAgent::collectStyleSheets(CSSStyleSheet* styleSheet, Vector<InspectorStyleSheet*>& result)
 {
-    InspectorStyleSheet* inspectorStyleSheet = bindStyleSheet(static_cast<CSSStyleSheet*>(styleSheet));
+    InspectorStyleSheet* inspectorStyleSheet = bindStyleSheet(styleSheet);
     result.append(inspectorStyleSheet);
     for (unsigned i = 0, size = styleSheet->length(); i < size; ++i) {
         CSSRule* rule = styleSheet->item(i);
@@ -1465,11 +1504,11 @@
     if (inspectorStyleSheet || !createIfAbsent)
         return inspectorStyleSheet.get();
 
-    TrackExceptionState es;
-    RefPtr<Element> styleElement = document->createElement("style", es);
-    if (!es.hadException())
-        styleElement->setAttribute("type", "text/css", es);
-    if (!es.hadException()) {
+    TrackExceptionState exceptionState;
+    RefPtr<Element> styleElement = document->createElement("style", exceptionState);
+    if (!exceptionState.hadException())
+        styleElement->setAttribute("type", "text/css", exceptionState);
+    if (!exceptionState.hadException()) {
         ContainerNode* targetNode;
         // HEAD is absent in ImageDocuments, for example.
         if (document->head())
@@ -1481,12 +1520,12 @@
 
         InlineStyleOverrideScope overrideScope(document);
         m_creatingViaInspectorStyleSheet = true;
-        targetNode->appendChild(styleElement, es);
+        targetNode->appendChild(styleElement, exceptionState);
         // At this point the added stylesheet will get bound through the updateActiveStyleSheets() invocation.
         // We just need to pick the respective InspectorStyleSheet from m_documentToInspectorStyleSheet.
         m_creatingViaInspectorStyleSheet = false;
     }
-    if (es.hadException())
+    if (exceptionState.hadException())
         return 0;
 
     return m_documentToInspectorStyleSheet.get(document);
@@ -1612,8 +1651,7 @@
     if (!attributeStyle)
         return 0;
 
-    ASSERT(attributeStyle->isMutable());
-    MutableStylePropertySet* mutableAttributeStyle = static_cast<MutableStylePropertySet*>(attributeStyle);
+    MutableStylePropertySet* mutableAttributeStyle = toMutableStylePropertySet(attributeStyle);
 
     RefPtr<InspectorStyle> inspectorStyle = InspectorStyle::create(InspectorCSSId(), mutableAttributeStyle->ensureCSSStyleDeclaration(), 0);
     return inspectorStyle->buildObjectForStyle();
diff --git a/Source/core/inspector/InspectorCSSAgent.h b/Source/core/inspector/InspectorCSSAgent.h
index f9c2f92..3c3edbf 100644
--- a/Source/core/inspector/InspectorCSSAgent.h
+++ b/Source/core/inspector/InspectorCSSAgent.h
@@ -32,6 +32,7 @@
 #include "core/inspector/InspectorStyleSheet.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "platform/JSONValues.h"
+#include "wtf/HashCountedSet.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassRefPtr.h"
@@ -56,6 +57,7 @@
 class Node;
 class NodeList;
 class PlatformFontUsage;
+class RenderText;
 class StyleResolver;
 class UpdateRegionLayoutTask;
 
@@ -113,6 +115,10 @@
     void mediaQueryResultChanged();
     void didCreateNamedFlow(Document*, NamedFlow*);
     void willRemoveNamedFlow(Document*, NamedFlow*);
+    void willMutateRules();
+    void didMutateRules(CSSStyleSheet*);
+    void willMutateStyle();
+    void didMutateStyle(CSSStyleDeclaration*, bool);
 
 private:
     void regionLayoutUpdated(NamedFlow*, int documentNodeId);
@@ -170,13 +176,14 @@
     void collectAllStyleSheets(Vector<InspectorStyleSheet*>&);
     void collectStyleSheets(CSSStyleSheet*, Vector<InspectorStyleSheet*>&);
 
-    void collectPlatformFontsForRenderer(RenderText*, HashMap<String, int>*);
+    void collectPlatformFontsForRenderer(RenderText*, HashCountedSet<String>*);
 
     InspectorStyleSheet* bindStyleSheet(CSSStyleSheet*);
     String unbindStyleSheet(InspectorStyleSheet*);
     InspectorStyleSheet* viaInspectorStyleSheet(Document*, bool createIfAbsent);
     InspectorStyleSheet* assertStyleSheetForId(ErrorString*, const String&);
     TypeBuilder::CSS::StyleSheetOrigin::Enum detectOrigin(CSSStyleSheet* pageStyleSheet, Document* ownerDocument);
+    bool styleSheetEditInProgress() const { return m_styleSheetsPendingMutation || m_styleDeclarationPendingMutation || m_isSettingStyleSheetText; }
 
     PassRefPtr<TypeBuilder::CSS::CSSRule> buildObjectForRule(CSSStyleRule*, StyleResolver*);
     PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > buildArrayForRuleList(CSSRuleList*, StyleResolver*);
@@ -190,7 +197,7 @@
     virtual void didRemoveDOMNode(Node*);
     virtual void didModifyDOMAttr(Element*);
 
-    // InspectorCSSAgent::Listener implementation
+    // InspectorStyleSheet::Listener implementation
     virtual void styleSheetChanged(InspectorStyleSheet*) OVERRIDE;
     virtual void willReparseStyleSheet() OVERRIDE;
     virtual void didReparseStyleSheet() OVERRIDE;
@@ -212,6 +219,8 @@
     OwnPtr<ChangeRegionOversetTask> m_changeRegionOversetTask;
 
     int m_lastStyleSheetId;
+    int m_styleSheetsPendingMutation;
+    bool m_styleDeclarationPendingMutation;
     bool m_creatingViaInspectorStyleSheet;
     bool m_isSettingStyleSheetText;
 
diff --git a/Source/core/inspector/InspectorClient.h b/Source/core/inspector/InspectorClient.h
index f2bdcdc..4a69725 100644
--- a/Source/core/inspector/InspectorClient.h
+++ b/Source/core/inspector/InspectorClient.h
@@ -52,6 +52,9 @@
         unsigned char flags, double timestamp);
     virtual void setTraceEventCallback(TraceEventCallback) { }
 
+    virtual void startGPUEventsRecording() { }
+    virtual void stopGPUEventsRecording() { }
+
     virtual void overrideDeviceMetrics(int /*width*/, int /*height*/, float /*deviceScaleFactor*/, bool /*emulateViewport*/, bool /*fitWindow*/) { }
 
     virtual bool overridesShowPaintRects() { return false; }
diff --git a/Source/core/inspector/InspectorConsoleAgent.cpp b/Source/core/inspector/InspectorConsoleAgent.cpp
index 2cb5495..1aa1547 100644
--- a/Source/core/inspector/InspectorConsoleAgent.cpp
+++ b/Source/core/inspector/InspectorConsoleAgent.cpp
@@ -243,18 +243,8 @@
     String identifier = title.isEmpty() ? String(lastCaller.sourceURL() + ':' + String::number(lastCaller.lineNumber()))
                                         : String(title + '@');
 
-    HashMap<String, unsigned>::iterator it = m_counts.find(identifier);
-    int count;
-    if (it == m_counts.end())
-        count = 1;
-    else {
-        count = it->value + 1;
-        m_counts.remove(it);
-    }
-
-    m_counts.add(identifier, count);
-
-    String message = title + ": " + String::number(count);
+    HashCountedSet<String>::AddResult result = m_counts.add(identifier);
+    String message = title + ": " + String::number(result.iterator->value);
     addMessageToConsole(ConsoleAPIMessageSource, LogMessageType, DebugMessageLevel, message, callStack);
 }
 
diff --git a/Source/core/inspector/InspectorConsoleAgent.h b/Source/core/inspector/InspectorConsoleAgent.h
index 3242317..9eda28d 100644
--- a/Source/core/inspector/InspectorConsoleAgent.h
+++ b/Source/core/inspector/InspectorConsoleAgent.h
@@ -32,6 +32,7 @@
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/frame/ConsoleTypes.h"
 #include "wtf/Forward.h"
+#include "wtf/HashCountedSet.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/Vector.h"
@@ -111,7 +112,7 @@
     ConsoleMessage* m_previousMessage;
     Vector<OwnPtr<ConsoleMessage> > m_consoleMessages;
     int m_expiredConsoleMessageCount;
-    HashMap<String, unsigned> m_counts;
+    HashCountedSet<String> m_counts;
     HashMap<String, double> m_times;
     bool m_enabled;
 private:
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index e41f578..336a53b 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -109,7 +109,7 @@
     m_memoryAgent = memoryAgentPtr.get();
     m_agents.append(memoryAgentPtr.release());
 
-    OwnPtr<InspectorTimelineAgent> timelineAgentPtr(InspectorTimelineAgent::create(m_instrumentingAgents.get(), pageAgent, m_memoryAgent, domAgent, m_state.get(),
+    OwnPtr<InspectorTimelineAgent> timelineAgentPtr(InspectorTimelineAgent::create(m_instrumentingAgents.get(), pageAgent, m_memoryAgent, domAgent, m_overlay.get(), m_state.get(),
         InspectorTimelineAgent::PageInspector, inspectorClient));
     m_timelineAgent = timelineAgentPtr.get();
     m_agents.append(timelineAgentPtr.release());
@@ -130,7 +130,7 @@
 
     m_agents.append(InspectorDOMDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), domAgent, debuggerAgent));
 
-    m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent, m_state.get(), m_injectedScriptManager.get()));
+    m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent, m_state.get(), m_injectedScriptManager.get(), m_overlay.get()));
 
     m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
 
@@ -360,6 +360,13 @@
     return false;
 }
 
+bool InspectorController::handleKeyboardEvent(Frame* frame, const PlatformKeyboardEvent& event)
+{
+    // Overlay should not consume events.
+    m_overlay->handleKeyboardEvent(event);
+    return false;
+}
+
 void InspectorController::requestPageScaleFactor(float scale, const IntPoint& origin)
 {
     m_inspectorClient->requestPageScaleFactor(scale, origin);
@@ -430,4 +437,10 @@
         timelineAgent->didComposite();
 }
 
+void InspectorController::processGPUEvent(double timestamp, int phase, bool foreign)
+{
+    if (InspectorTimelineAgent* timelineAgent = m_instrumentingAgents->inspectorTimelineAgent())
+        timelineAgent->processGPUEvent(InspectorTimelineAgent::GPUEvent(timestamp, phase, foreign));
+}
+
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorController.h b/Source/core/inspector/InspectorController.h
index 4190fb3..aa51f43 100644
--- a/Source/core/inspector/InspectorController.h
+++ b/Source/core/inspector/InspectorController.h
@@ -57,6 +57,7 @@
 class IntSize;
 class Page;
 class PlatformGestureEvent;
+class PlatformKeyboardEvent;
 class PlatformMouseEvent;
 class PlatformTouchEvent;
 class PostWorkerNotificationToFrontendTask;
@@ -99,6 +100,7 @@
     bool handleGestureEvent(Frame*, const PlatformGestureEvent&);
     bool handleMouseEvent(Frame*, const PlatformMouseEvent&);
     bool handleTouchEvent(Frame*, const PlatformTouchEvent&);
+    bool handleKeyboardEvent(Frame*, const PlatformKeyboardEvent&);
 
     void requestPageScaleFactor(float scale, const IntPoint& origin);
     bool deviceEmulationEnabled();
@@ -120,6 +122,8 @@
     void willComposite();
     void didComposite();
 
+    void processGPUEvent(double timestamp, int phase, bool foreign);
+
 private:
     InspectorController(Page*, InspectorClient*);
 
diff --git a/Source/core/inspector/InspectorCounters.cpp b/Source/core/inspector/InspectorCounters.cpp
index 54f928a..2e81a98 100644
--- a/Source/core/inspector/InspectorCounters.cpp
+++ b/Source/core/inspector/InspectorCounters.cpp
@@ -31,8 +31,6 @@
 #include "config.h"
 #include "core/inspector/InspectorCounters.h"
 
-#include "core/platform/ThreadGlobalData.h"
-
 namespace WebCore {
 
 int InspectorCounters::s_counters[CounterTypeLength];
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index 74afd22..e5e87b8 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -220,10 +220,10 @@
     m_elements.clear();
 }
 
-String InspectorDOMAgent::toErrorString(ExceptionState& es)
+String InspectorDOMAgent::toErrorString(ExceptionState& exceptionState)
 {
-    if (es.hadException())
-        return DOMException::getErrorName(es.code());
+    if (exceptionState.hadException())
+        return DOMException::getErrorName(exceptionState.code());
     return "";
 }
 
@@ -567,9 +567,9 @@
     if (!node)
         return;
 
-    TrackExceptionState es;
-    RefPtr<Element> element = node->querySelector(selectors, es);
-    if (es.hadException()) {
+    TrackExceptionState exceptionState;
+    RefPtr<Element> element = node->querySelector(selectors, exceptionState);
+    if (exceptionState.hadException()) {
         *errorString = "DOM Error while querying";
         return;
     }
@@ -584,9 +584,9 @@
     if (!node)
         return;
 
-    TrackExceptionState es;
-    RefPtr<NodeList> nodes = node->querySelectorAll(selectors, es);
-    if (es.hadException()) {
+    TrackExceptionState exceptionState;
+    RefPtr<NodeList> nodes = node->querySelectorAll(selectors, exceptionState);
+    if (exceptionState.hadException()) {
         *errorString = "DOM Error while querying";
         return;
     }
@@ -767,9 +767,9 @@
     if (!oldNode || !oldNode->isElementNode())
         return;
 
-    TrackExceptionState es;
-    RefPtr<Element> newElem = oldNode->document().createElement(tagName, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    RefPtr<Element> newElem = oldNode->document().createElement(tagName, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     // Copy over the original node's attributes.
@@ -954,7 +954,7 @@
             continue;
 
         // Manual plain text search.
-        while ((node = NodeTraversal::next(node, document->documentElement()))) {
+        while ((node = NodeTraversal::next(*node, document->documentElement()))) {
             switch (node->nodeType()) {
             case Node::TEXT_NODE:
             case Node::COMMENT_NODE:
@@ -981,11 +981,11 @@
                 for (unsigned i = 0; i < numAttrs; ++i) {
                     // Add attribute pair
                     const Attribute* attribute = element->attributeItem(i);
-                    if (attribute->localName().find(whitespaceTrimmedQuery) != kNotFound) {
+                    if (attribute->localName().find(whitespaceTrimmedQuery, 0, false) != kNotFound) {
                         resultCollector.add(node);
                         break;
                     }
-                    size_t foundPosition = attribute->value().find(attributeQuery);
+                    size_t foundPosition = attribute->value().find(attributeQuery, 0, false);
                     if (foundPosition != kNotFound) {
                         if (!exactAttributeMatch || (!foundPosition && attribute->value().length() == attributeQuery.length())) {
                             resultCollector.add(node);
@@ -1003,15 +1003,15 @@
         // XPath evaluation
         for (Vector<Document*>::iterator it = docs.begin(); it != docs.end(); ++it) {
             Document* document = *it;
-            TrackExceptionState es;
-            RefPtr<XPathResult> result = DocumentXPathEvaluator::evaluate(document, whitespaceTrimmedQuery, document, 0, XPathResult::ORDERED_NODE_SNAPSHOT_TYPE, 0, es);
-            if (es.hadException() || !result)
+            TrackExceptionState exceptionState;
+            RefPtr<XPathResult> result = DocumentXPathEvaluator::evaluate(document, whitespaceTrimmedQuery, document, 0, XPathResult::ORDERED_NODE_SNAPSHOT_TYPE, 0, exceptionState);
+            if (exceptionState.hadException() || !result)
                 continue;
 
-            unsigned long size = result->snapshotLength(es);
-            for (unsigned long i = 0; !es.hadException() && i < size; ++i) {
-                Node* node = result->snapshotItem(i, es);
-                if (es.hadException())
+            unsigned long size = result->snapshotLength(exceptionState);
+            for (unsigned long i = 0; !exceptionState.hadException() && i < size; ++i) {
+                Node* node = result->snapshotItem(i, exceptionState);
+                if (exceptionState.hadException())
                     break;
 
                 if (node->nodeType() == Node::ATTRIBUTE_NODE)
@@ -1023,9 +1023,9 @@
         // Selector evaluation
         for (Vector<Document*>::iterator it = docs.begin(); it != docs.end(); ++it) {
             Document* document = *it;
-            TrackExceptionState es;
-            RefPtr<NodeList> nodeList = document->querySelectorAll(whitespaceTrimmedQuery, es);
-            if (es.hadException() || !nodeList)
+            TrackExceptionState exceptionState;
+            RefPtr<NodeList> nodeList = document->querySelectorAll(whitespaceTrimmedQuery, exceptionState);
+            if (exceptionState.hadException() || !nodeList)
                 continue;
 
             unsigned size = nodeList->length();
@@ -1282,16 +1282,16 @@
 
 void InspectorDOMAgent::undo(ErrorString* errorString)
 {
-    TrackExceptionState es;
-    m_history->undo(es);
-    *errorString = InspectorDOMAgent::toErrorString(es);
+    TrackExceptionState exceptionState;
+    m_history->undo(exceptionState);
+    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
 void InspectorDOMAgent::redo(ErrorString* errorString)
 {
-    TrackExceptionState es;
-    m_history->redo(es);
-    *errorString = InspectorDOMAgent::toErrorString(es);
+    TrackExceptionState exceptionState;
+    m_history->redo(exceptionState);
+    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
 void InspectorDOMAgent::markUndoableState(ErrorString*)
@@ -1437,6 +1437,18 @@
     return document->completeURL("").string();
 }
 
+static TypeBuilder::DOM::ShadowRootType::Enum shadowRootType(ShadowRoot* shadowRoot)
+{
+    switch (shadowRoot->type()) {
+    case ShadowRoot::UserAgentShadowRoot:
+        return TypeBuilder::DOM::ShadowRootType::User_agent;
+    case ShadowRoot::AuthorShadowRoot:
+        return TypeBuilder::DOM::ShadowRootType::Author;
+    }
+    ASSERT_NOT_REACHED();
+    return TypeBuilder::DOM::ShadowRootType::User_agent;
+}
+
 PassRefPtr<TypeBuilder::DOM::Node> InspectorDOMAgent::buildObjectForNode(Node* node, int depth, NodeToIdMap* nodesMap)
 {
     int id = bind(node, nodesMap);
@@ -1529,6 +1541,8 @@
         Attr* attribute = toAttr(node);
         value->setName(attribute->name());
         value->setValue(attribute->value());
+    } else if (node->isShadowRoot()) {
+        value->setShadowRootType(shadowRootType(toShadowRoot(node)));
     }
 
     if (node->isContainerNode()) {
diff --git a/Source/core/inspector/InspectorDOMStorageAgent.cpp b/Source/core/inspector/InspectorDOMStorageAgent.cpp
index 63c9186..e0b092e 100644
--- a/Source/core/inspector/InspectorDOMStorageAgent.cpp
+++ b/Source/core/inspector/InspectorDOMStorageAgent.cpp
@@ -46,7 +46,7 @@
 #include "core/storage/StorageArea.h"
 #include "core/storage/StorageNamespace.h"
 #include "platform/JSONValues.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
@@ -54,12 +54,12 @@
 static const char domStorageAgentEnabled[] = "domStorageAgentEnabled";
 };
 
-static bool hadException(ExceptionState& es, ErrorString* errorString)
+static bool hadException(ExceptionState& exceptionState, ErrorString* errorString)
 {
-    if (!es.hadException())
+    if (!exceptionState.hadException())
         return false;
 
-    switch (es.code()) {
+    switch (exceptionState.code()) {
     case SecurityError:
         *errorString = "Security error";
         return true;
@@ -117,13 +117,13 @@
 
     RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > > storageItems = TypeBuilder::Array<TypeBuilder::Array<String> >::create();
 
-    TrackExceptionState es;
-    for (unsigned i = 0; i < storageArea->length(es, frame); ++i) {
-        String name(storageArea->key(i, es, frame));
-        if (hadException(es, errorString))
+    TrackExceptionState exceptionState;
+    for (unsigned i = 0; i < storageArea->length(exceptionState, frame); ++i) {
+        String name(storageArea->key(i, exceptionState, frame));
+        if (hadException(exceptionState, errorString))
             return;
-        String value(storageArea->getItem(name, es, frame));
-        if (hadException(es, errorString))
+        String value(storageArea->getItem(name, exceptionState, frame));
+        if (hadException(exceptionState, errorString))
             return;
         RefPtr<TypeBuilder::Array<String> > entry = TypeBuilder::Array<String>::create();
         entry->addItem(name);
@@ -133,10 +133,10 @@
     items = storageItems.release();
 }
 
-static String toErrorString(ExceptionState& es)
+static String toErrorString(ExceptionState& exceptionState)
 {
-    if (es.hadException())
-        return DOMException::getErrorName(es.code());
+    if (exceptionState.hadException())
+        return DOMException::getErrorName(exceptionState.code());
     return "";
 }
 
@@ -149,9 +149,9 @@
         return;
     }
 
-    TrackExceptionState es;
-    storageArea->setItem(key, value, es, frame);
-    *errorString = toErrorString(es);
+    TrackExceptionState exceptionState;
+    storageArea->setItem(key, value, exceptionState, frame);
+    *errorString = toErrorString(exceptionState);
 }
 
 void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key)
@@ -163,9 +163,9 @@
         return;
     }
 
-    TrackExceptionState es;
-    storageArea->removeItem(key, es, frame);
-    *errorString = toErrorString(es);
+    TrackExceptionState exceptionState;
+    storageArea->removeItem(key, exceptionState, frame);
+    *errorString = toErrorString(exceptionState);
 }
 
 String InspectorDOMStorageAgent::storageId(Storage* storage)
diff --git a/Source/core/inspector/InspectorDebuggerAgent.cpp b/Source/core/inspector/InspectorDebuggerAgent.cpp
index 539bf17..55d9b72 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -49,7 +49,10 @@
 #include "wtf/text/WTFString.h"
 
 using WebCore::TypeBuilder::Array;
+using WebCore::TypeBuilder::Debugger::BreakpointId;
+using WebCore::TypeBuilder::Debugger::CallFrame;
 using WebCore::TypeBuilder::Debugger::FunctionDetails;
+using WebCore::TypeBuilder::Debugger::Location;
 using WebCore::TypeBuilder::Debugger::ScriptId;
 using WebCore::TypeBuilder::Runtime::RemoteObject;
 
@@ -295,9 +298,9 @@
     return url == pattern;
 }
 
-void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString* errorString, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const String* const optionalCondition, const bool* isAntiBreakpoint, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations)
+void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString* errorString, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const String* const optionalCondition, const bool* isAntiBreakpoint, BreakpointId* outBreakpointId, RefPtr<Array<Location> >& locations)
 {
-    locations = Array<TypeBuilder::Debugger::Location>::create();
+    locations = Array<Location>::create();
     if (!optionalURL == !optionalURLRegex) {
         *errorString = "Either url or urlRegex must be specified.";
         return;
@@ -334,7 +337,7 @@
         for (ScriptsMap::iterator it = m_scripts.begin(); it != m_scripts.end(); ++it) {
             if (!matches(it->value.url, url, isRegex))
                 continue;
-            RefPtr<TypeBuilder::Debugger::Location> location = resolveBreakpoint(breakpointId, it->key, breakpoint, UserBreakpointSource);
+            RefPtr<Location> location = resolveBreakpoint(breakpointId, it->key, breakpoint, UserBreakpointSource);
             if (location)
                 locations->addItem(location);
         }
@@ -354,7 +357,7 @@
     return true;
 }
 
-void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<JSONObject>& location, const String* const optionalCondition, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Debugger::Location>& actualLocation)
+void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<JSONObject>& location, const String* const optionalCondition, BreakpointId* outBreakpointId, RefPtr<Location>& actualLocation)
 {
     String scriptId;
     int lineNumber;
@@ -427,7 +430,7 @@
     resume(errorString);
 }
 
-void InspectorDebuggerAgent::getStepInPositions(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::Location> >& positions)
+void InspectorDebuggerAgent::getStepInPositions(ErrorString* errorString, const String& callFrameId, RefPtr<Array<Location> >& positions)
 {
     if (!isPaused() || m_currentCallStack.isNull()) {
         *errorString = "Attempt to access callframe when debugger is not on pause";
@@ -442,7 +445,7 @@
     injectedScript.getStepInPositions(errorString, m_currentCallStack, callFrameId, positions);
 }
 
-void InspectorDebuggerAgent::getBacktrace(ErrorString* errorString, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& callFrames)
+void InspectorDebuggerAgent::getBacktrace(ErrorString* errorString, RefPtr<Array<CallFrame> >& callFrames)
 {
     if (!assertPaused(errorString))
         return;
@@ -463,19 +466,21 @@
 {
     if (m_skipAllPauses)
         return ScriptDebugListener::Continue;
+    if (!topFrame)
+        return ScriptDebugListener::NoSkip;
 
     String topFrameScriptUrl = scriptURL(topFrame.get());
     if (m_cachedSkipStackRegExp && !topFrameScriptUrl.isEmpty() && m_cachedSkipStackRegExp->match(topFrameScriptUrl) != -1)
         return ScriptDebugListener::Continue;
 
-    // Prepare top frame parameters;
-    int topFrameLineNumber = topFrame->line();
-    int topFrameColumnNumber = topFrame->column();
-
     // Match against breakpoints.
     if (topFrameScriptUrl.isEmpty())
         return ScriptDebugListener::NoSkip;
 
+    // Prepare top frame parameters.
+    int topFrameLineNumber = topFrame->line();
+    int topFrameColumnNumber = topFrame->column();
+
     RefPtr<JSONObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
     for (JSONObject::iterator it = breakpointsCookie->begin(); it != breakpointsCookie->end(); ++it) {
         RefPtr<JSONObject> breakpointObject = it->value->asObject();
@@ -512,6 +517,8 @@
 {
     if (m_skipAllPauses)
         return ScriptDebugListener::Continue;
+    if (!topFrame)
+        return ScriptDebugListener::NoSkip;
     return ScriptDebugListener::NoSkip;
 }
 
@@ -519,6 +526,8 @@
 {
     if (m_skipAllPauses)
         return ScriptDebugListener::Continue;
+    if (!topFrame)
+        return ScriptDebugListener::NoSkip;
 
     if (m_cachedSkipStackRegExp) {
         String scriptUrl = scriptURL(topFrame.get());
@@ -533,7 +542,7 @@
     return ScriptDebugListener::NoSkip;
 }
 
-PassRefPtr<TypeBuilder::Debugger::Location> InspectorDebuggerAgent::resolveBreakpoint(const String& breakpointId, const String& scriptId, const ScriptBreakpoint& breakpoint, BreakpointSource source)
+PassRefPtr<Location> InspectorDebuggerAgent::resolveBreakpoint(const String& breakpointId, const String& scriptId, const ScriptBreakpoint& breakpoint, BreakpointSource source)
 {
     ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId);
     if (scriptIterator == m_scripts.end())
@@ -555,7 +564,7 @@
         debugServerBreakpointIdsIterator = m_breakpointIdToDebugServerBreakpointIds.set(breakpointId, Vector<String>()).iterator;
     debugServerBreakpointIdsIterator->value.append(debugServerBreakpointId);
 
-    RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
+    RefPtr<Location> location = Location::create()
         .setScriptId(scriptId)
         .setLineNumber(actualLineNumber);
     location->setColumnNumber(actualColumnNumber);
@@ -584,7 +593,7 @@
         *error = "No script for id: " + scriptId;
 }
 
-void InspectorDebuggerAgent::setScriptSource(ErrorString* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, const String& scriptId, const String& newContent, const bool* const preview, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
+void InspectorDebuggerAgent::setScriptSource(ErrorString* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, const String& scriptId, const String& newContent, const bool* const preview, RefPtr<Array<CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
 {
     bool previewOnly = preview && *preview;
     ScriptObject resultObject;
@@ -595,7 +604,7 @@
     if (object)
         result = object;
 }
-void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
+void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
 {
     if (!isPaused() || m_currentCallStack.isNull()) {
         *errorString = "Attempt to access callframe when debugger is not on pause";
@@ -621,7 +630,7 @@
         *error = "No script for id: " + scriptId;
 }
 
-void InspectorDebuggerAgent::getFunctionDetails(ErrorString* errorString, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>& details)
+void InspectorDebuggerAgent::getFunctionDetails(ErrorString* errorString, const String& functionId, RefPtr<FunctionDetails>& details)
 {
     InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(functionId);
     if (injectedScript.hasNoValue()) {
@@ -748,7 +757,7 @@
         m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, pauseState);
 }
 
-void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString* errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
+void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString* errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
 {
     if (!isPaused() || m_currentCallStack.isNull()) {
         *errorString = "Attempt to access callframe when debugger is not on pause";
@@ -795,7 +804,7 @@
     *scriptId = scriptIdValue;
 }
 
-void InspectorDebuggerAgent::runScript(ErrorString* errorString, const ScriptId& scriptId, const int* executionContextId, const String* const objectGroup, const bool* const doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
+void InspectorDebuggerAgent::runScript(ErrorString* errorString, const ScriptId& scriptId, const int* executionContextId, const String* const objectGroup, const bool* const doNotPauseOnExceptionsAndMuteConsole, RefPtr<RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
 {
     InjectedScript injectedScript = injectedScriptForEval(errorString, executionContextId);
     if (injectedScript.hasNoValue()) {
@@ -886,14 +895,14 @@
     }
 }
 
-PassRefPtr<Array<TypeBuilder::Debugger::CallFrame> > InspectorDebuggerAgent::currentCallFrames()
+PassRefPtr<Array<CallFrame> > InspectorDebuggerAgent::currentCallFrames()
 {
     if (!m_pausedScriptState)
-        return Array<TypeBuilder::Debugger::CallFrame>::create();
+        return Array<CallFrame>::create();
     InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(m_pausedScriptState);
     if (injectedScript.hasNoValue()) {
         ASSERT_NOT_REACHED();
-        return Array<TypeBuilder::Debugger::CallFrame>::create();
+        return Array<CallFrame>::create();
     }
     return injectedScript.wrapCallFrames(m_currentCallStack);
 }
@@ -957,7 +966,7 @@
         breakpointObject->getNumber(DebuggerAgentState::lineNumber, &breakpoint.lineNumber);
         breakpointObject->getNumber(DebuggerAgentState::columnNumber, &breakpoint.columnNumber);
         breakpointObject->getString(DebuggerAgentState::condition, &breakpoint.condition);
-        RefPtr<TypeBuilder::Debugger::Location> location = resolveBreakpoint(it->key, scriptId, breakpoint, UserBreakpointSource);
+        RefPtr<Location> location = resolveBreakpoint(it->key, scriptId, breakpoint, UserBreakpointSource);
         if (location)
             m_frontend->breakpointResolved(it->key, location);
     }
@@ -1025,6 +1034,8 @@
 
 void InspectorDebuggerAgent::breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data)
 {
+    if (m_skipAllPauses)
+        return;
     m_breakReason = breakReason;
     m_breakAuxData = data;
     scriptDebugServer().breakProgram();
diff --git a/Source/core/inspector/InspectorFileSystemAgent.cpp b/Source/core/inspector/InspectorFileSystemAgent.cpp
index f8bf1ae..a5f9719 100644
--- a/Source/core/inspector/InspectorFileSystemAgent.cpp
+++ b/Source/core/inspector/InspectorFileSystemAgent.cpp
@@ -43,7 +43,6 @@
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
 #include "core/frame/Frame.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "modules/filesystem/DOMFileSystem.h"
 #include "modules/filesystem/DirectoryEntry.h"
 #include "modules/filesystem/DirectoryReader.h"
@@ -57,8 +56,9 @@
 #include "modules/filesystem/LocalFileSystem.h"
 #include "modules/filesystem/Metadata.h"
 #include "modules/filesystem/MetadataCallback.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/ArrayBuffer.h"
 #include "wtf/text/Base64.h"
 #include "wtf/text/TextEncoding.h"
@@ -489,7 +489,7 @@
         return;
     }
 
-    RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create(m_mimeType, m_charset, true);
+    OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create(m_mimeType, m_charset, true);
     String result = decoder->decode(static_cast<char*>(buffer->data()), buffer->byteLength());
     result.append(decoder->flush());
     m_charset = decoder->encoding().name();
diff --git a/Source/core/inspector/InspectorFrontendHost.cpp b/Source/core/inspector/InspectorFrontendHost.cpp
index c4f26ce..20f2160 100644
--- a/Source/core/inspector/InspectorFrontendHost.cpp
+++ b/Source/core/inspector/InspectorFrontendHost.cpp
@@ -31,6 +31,7 @@
 #include "core/inspector/InspectorFrontendHost.h"
 
 #include "bindings/v8/ScriptFunctionCall.h"
+#include "bindings/v8/ScriptState.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/TextResourceDecoder.h"
 #include "core/frame/Frame.h"
@@ -40,11 +41,11 @@
 #include "core/page/ContextMenuController.h"
 #include "core/page/ContextMenuProvider.h"
 #include "core/page/Page.h"
-#include "core/platform/ContextMenu.h"
-#include "core/platform/ContextMenuItem.h"
 #include "core/platform/Pasteboard.h"
 #include "core/rendering/RenderTheme.h"
 #include "modules/filesystem/DOMFileSystem.h"
+#include "platform/ContextMenu.h"
+#include "platform/ContextMenuItem.h"
 #include "platform/JSONValues.h"
 #include "platform/SharedBuffer.h"
 #include "platform/UserGestureIndicator.h"
@@ -135,17 +136,6 @@
     m_frontendPage = 0;
 }
 
-void InspectorFrontendHost::closeWindow()
-{
-    if (m_client) {
-        RefPtr<JSONObject> message = JSONObject::create();
-        message->setNumber("id", 0);
-        message->setString("method", "closeWindow");
-        sendMessageToEmbedder(message->toJSONString());
-        disconnectClient(); // Disconnect from client.
-    }
-}
-
 void InspectorFrontendHost::setZoomFactor(float zoom)
 {
     m_frontendPage->mainFrame()->setPageAndTextZoomFactors(zoom, 1);
@@ -214,6 +204,19 @@
     return DOMFileSystem::create(context, fileSystemName, FileSystemTypeIsolated, KURL(ParsedURLString, rootURL));
 }
 
+void InspectorFrontendHost::upgradeDraggedFileSystemPermissions(DOMFileSystem* domFileSystem)
+{
+    if (!m_client)
+        return;
+    RefPtr<JSONObject> message = JSONObject::create();
+    message->setNumber("id", 0);
+    message->setString("method", "upgradeDraggedFileSystemPermissions");
+    RefPtr<JSONArray> params = JSONArray::create();
+    message->setArray("params", params);
+    params->pushString(domFileSystem->rootURL().string());
+    sendMessageToEmbedder(message->toJSONString());
+}
+
 bool InspectorFrontendHost::isUnderTest()
 {
     return m_client && m_client->isUnderTest();
diff --git a/Source/core/inspector/InspectorFrontendHost.h b/Source/core/inspector/InspectorFrontendHost.h
index 47e8f48..1bccdca 100644
--- a/Source/core/inspector/InspectorFrontendHost.h
+++ b/Source/core/inspector/InspectorFrontendHost.h
@@ -30,7 +30,6 @@
 #define InspectorFrontendHost_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/ContextMenu.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
@@ -54,7 +53,6 @@
     ~InspectorFrontendHost();
     void disconnectClient();
 
-    void closeWindow();
     void setZoomFactor(float);
     void inspectedURLChanged(const String&);
 
@@ -71,6 +69,7 @@
     String getSelectionForegroundColor();
 
     PassRefPtr<DOMFileSystem> isolatedFileSystem(const String& fileSystemName, const String& rootURL);
+    void upgradeDraggedFileSystemPermissions(DOMFileSystem*);
 
     bool isUnderTest();
 
diff --git a/Source/core/inspector/InspectorFrontendHost.idl b/Source/core/inspector/InspectorFrontendHost.idl
index d753646..467e7aa 100644
--- a/Source/core/inspector/InspectorFrontendHost.idl
+++ b/Source/core/inspector/InspectorFrontendHost.idl
@@ -33,7 +33,6 @@
 [
     NoInterfaceObject
 ] interface InspectorFrontendHost {
-    void closeWindow();
     void setZoomFactor(float zoom);
     void inspectedURLChanged(DOMString newURL);
 
@@ -55,6 +54,7 @@
     DOMString getSelectionForegroundColor();
 
     DOMFileSystem isolatedFileSystem(DOMString fileSystemId, DOMString registeredName);
+    void upgradeDraggedFileSystemPermissions(DOMFileSystem domFileSystem);
 
     boolean isUnderTest();
 };
diff --git a/Source/core/inspector/InspectorHeapProfilerAgent.cpp b/Source/core/inspector/InspectorHeapProfilerAgent.cpp
index 6356654..c072616 100644
--- a/Source/core/inspector/InspectorHeapProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorHeapProfilerAgent.cpp
@@ -32,6 +32,7 @@
 #include "core/inspector/InspectorHeapProfilerAgent.h"
 
 #include "bindings/v8/ScriptProfiler.h"
+#include "bindings/v8/ScriptScope.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptHost.h"
 #include "core/inspector/InspectorState.h"
@@ -306,6 +307,7 @@
         return;
     }
     ScriptValue value = injectedScript.findObjectById(objectId);
+    ScriptScope scope(injectedScript.scriptState());
     if (value.hasNoValue() || value.isUndefined()) {
         *errorString = "Object with given id not found";
         return;
diff --git a/Source/core/inspector/InspectorHistory.cpp b/Source/core/inspector/InspectorHistory.cpp
index 1c814e5..e882744 100644
--- a/Source/core/inspector/InspectorHistory.cpp
+++ b/Source/core/inspector/InspectorHistory.cpp
@@ -83,9 +83,9 @@
 
 InspectorHistory::InspectorHistory() : m_afterLastActionIndex(0) { }
 
-bool InspectorHistory::perform(PassOwnPtr<Action> action, ExceptionState& es)
+bool InspectorHistory::perform(PassOwnPtr<Action> action, ExceptionState& exceptionState)
 {
-    if (!action->perform(es))
+    if (!action->perform(exceptionState))
         return false;
 
     if (!action->mergeId().isEmpty() && m_afterLastActionIndex > 0 && action->mergeId() == m_history[m_afterLastActionIndex - 1]->mergeId())
@@ -103,14 +103,14 @@
     perform(adoptPtr(new UndoableStateMark()), IGNORE_EXCEPTION);
 }
 
-bool InspectorHistory::undo(ExceptionState& es)
+bool InspectorHistory::undo(ExceptionState& exceptionState)
 {
     while (m_afterLastActionIndex > 0 && m_history[m_afterLastActionIndex - 1]->isUndoableStateMark())
         --m_afterLastActionIndex;
 
     while (m_afterLastActionIndex > 0) {
         Action* action = m_history[m_afterLastActionIndex - 1].get();
-        if (!action->undo(es)) {
+        if (!action->undo(exceptionState)) {
             reset();
             return false;
         }
@@ -122,14 +122,14 @@
     return true;
 }
 
-bool InspectorHistory::redo(ExceptionState& es)
+bool InspectorHistory::redo(ExceptionState& exceptionState)
 {
     while (m_afterLastActionIndex < m_history.size() && m_history[m_afterLastActionIndex]->isUndoableStateMark())
         ++m_afterLastActionIndex;
 
     while (m_afterLastActionIndex < m_history.size()) {
         Action* action = m_history[m_afterLastActionIndex].get();
-        if (!action->redo(es)) {
+        if (!action->redo(exceptionState)) {
             reset();
             return false;
         }
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
index 3975d15..b5b8618 100644
--- a/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ b/Source/core/inspector/InspectorIndexedDBAgent.cpp
@@ -58,7 +58,7 @@
 #include "modules/indexeddb/IDBRequest.h"
 #include "modules/indexeddb/IDBTransaction.h"
 #include "platform/JSONValues.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Vector.h"
 
 using WebCore::TypeBuilder::Array;
@@ -109,9 +109,9 @@
         }
 
         IDBRequest* idbRequest = static_cast<IDBRequest*>(event->target());
-        TrackExceptionState es;
-        RefPtr<IDBAny> requestResult = idbRequest->result(es);
-        if (es.hadException()) {
+        TrackExceptionState exceptionState;
+        RefPtr<IDBAny> requestResult = idbRequest->result(exceptionState);
+        if (exceptionState.hadException()) {
             m_requestCallback->sendFailure("Could not get result in callback.");
             return;
         }
@@ -171,9 +171,9 @@
         }
 
         IDBOpenDBRequest* idbOpenDBRequest = static_cast<IDBOpenDBRequest*>(event->target());
-        TrackExceptionState es;
-        RefPtr<IDBAny> requestResult = idbOpenDBRequest->result(es);
-        if (es.hadException()) {
+        TrackExceptionState exceptionState;
+        RefPtr<IDBAny> requestResult = idbOpenDBRequest->result(exceptionState);
+        if (exceptionState.hadException()) {
             m_executableWithDatabase->requestCallback()->sendFailure("Could not get result in callback.");
             return;
         }
@@ -198,9 +198,9 @@
 void ExecutableWithDatabase::start(IDBFactory* idbFactory, SecurityOrigin*, const String& databaseName)
 {
     RefPtr<OpenDatabaseCallback> callback = OpenDatabaseCallback::create(this);
-    TrackExceptionState es;
-    RefPtr<IDBOpenDBRequest> idbOpenDBRequest = idbFactory->open(context(), databaseName, es);
-    if (es.hadException()) {
+    TrackExceptionState exceptionState;
+    RefPtr<IDBOpenDBRequest> idbOpenDBRequest = idbFactory->open(context(), databaseName, exceptionState);
+    if (exceptionState.hadException()) {
         requestCallback()->sendFailure("Could not open database.");
         return;
     }
@@ -209,27 +209,27 @@
 
 static PassRefPtr<IDBTransaction> transactionForDatabase(ExecutionContext* executionContext, IDBDatabase* idbDatabase, const String& objectStoreName, const String& mode = IDBTransaction::modeReadOnly())
 {
-    TrackExceptionState es;
-    RefPtr<IDBTransaction> idbTransaction = idbDatabase->transaction(executionContext, objectStoreName, mode, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    RefPtr<IDBTransaction> idbTransaction = idbDatabase->transaction(executionContext, objectStoreName, mode, exceptionState);
+    if (exceptionState.hadException())
         return 0;
     return idbTransaction;
 }
 
 static PassRefPtr<IDBObjectStore> objectStoreForTransaction(IDBTransaction* idbTransaction, const String& objectStoreName)
 {
-    TrackExceptionState es;
-    RefPtr<IDBObjectStore> idbObjectStore = idbTransaction->objectStore(objectStoreName, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    RefPtr<IDBObjectStore> idbObjectStore = idbTransaction->objectStore(objectStoreName, exceptionState);
+    if (exceptionState.hadException())
         return 0;
     return idbObjectStore;
 }
 
 static PassRefPtr<IDBIndex> indexForObjectStore(IDBObjectStore* idbObjectStore, const String& indexName)
 {
-    TrackExceptionState es;
-    RefPtr<IDBIndex> idbIndex = idbObjectStore->index(indexName, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    RefPtr<IDBIndex> idbIndex = idbObjectStore->index(indexName, exceptionState);
+    if (exceptionState.hadException())
         return 0;
     return idbIndex;
 }
@@ -415,9 +415,9 @@
         }
 
         IDBRequest* idbRequest = static_cast<IDBRequest*>(event->target());
-        TrackExceptionState es;
-        RefPtr<IDBAny> requestResult = idbRequest->result(es);
-        if (es.hadException()) {
+        TrackExceptionState exceptionState;
+        RefPtr<IDBAny> requestResult = idbRequest->result(exceptionState);
+        if (exceptionState.hadException()) {
             m_requestCallback->sendFailure("Could not get result in callback.");
             return;
         }
@@ -433,9 +433,9 @@
         RefPtr<IDBCursorWithValue> idbCursor = requestResult->idbCursorWithValue();
 
         if (m_skipCount) {
-            TrackExceptionState es;
-            idbCursor->advance(m_skipCount, es);
-            if (es.hadException())
+            TrackExceptionState exceptionState;
+            idbCursor->advance(m_skipCount, exceptionState);
+            if (exceptionState.hadException())
                 m_requestCallback->sendFailure("Could not advance cursor.");
             m_skipCount = 0;
             return;
@@ -447,8 +447,8 @@
         }
 
         // Continue cursor before making injected script calls, otherwise transaction might be finished.
-        idbCursor->continueFunction(0, es);
-        if (es.hadException()) {
+        idbCursor->continueFunction(0, exceptionState);
+        if (exceptionState.hadException()) {
             m_requestCallback->sendFailure("Could not continue cursor.");
             return;
         }
@@ -623,9 +623,9 @@
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
 
-    TrackExceptionState es;
-    RefPtr<IDBRequest> idbRequest = idbFactory->getDatabaseNames(document, es);
-    if (es.hadException()) {
+    TrackExceptionState exceptionState;
+    RefPtr<IDBRequest> idbRequest = idbFactory->getDatabaseNames(document, exceptionState);
+    if (exceptionState.hadException()) {
         requestCallback->sendFailure("Could not obtain database names.");
         return;
     }
@@ -747,11 +747,11 @@
             return;
         }
 
-        TrackExceptionState es;
-        RefPtr<IDBRequest> idbRequest = idbObjectStore->clear(context(), es);
-        ASSERT(!es.hadException());
-        if (es.hadException()) {
-            ExceptionCode ec = es.code();
+        TrackExceptionState exceptionState;
+        RefPtr<IDBRequest> idbRequest = idbObjectStore->clear(context(), exceptionState);
+        ASSERT(!exceptionState.hadException());
+        if (exceptionState.hadException()) {
+            ExceptionCode ec = exceptionState.code();
             m_requestCallback->sendFailure(String::format("Could not clear object store '%s': %d", m_objectStoreName.utf8().data(), ec));
             return;
         }
diff --git a/Source/core/inspector/InspectorInstrumentation.cpp b/Source/core/inspector/InspectorInstrumentation.cpp
index b2685f8..b709868 100644
--- a/Source/core/inspector/InspectorInstrumentation.cpp
+++ b/Source/core/inspector/InspectorInstrumentation.cpp
@@ -239,7 +239,6 @@
 const char PaintSetup[] = "PaintSetup";
 const char PaintLayer[] = "PaintLayer";
 const char RasterTask[] = "RasterTask";
-const char ImageDecodeTask[] = "ImageDecodeTask";
 const char Paint[] = "Paint";
 const char Layer[] = "Layer";
 const char BeginFrame[] = "BeginFrame";
@@ -251,7 +250,6 @@
 const char LayerTreeId[] = "layerTreeId";
 const char NodeId[] = "nodeId";
 const char PageId[] = "pageId";
-const char PixelRefId[] = "pixelRefId";
 };
 
 InstrumentingAgents* instrumentationForPage(Page* page)
diff --git a/Source/core/inspector/InspectorInstrumentation.h b/Source/core/inspector/InspectorInstrumentation.h
index 2f86c3d..44df7d9 100644
--- a/Source/core/inspector/InspectorInstrumentation.h
+++ b/Source/core/inspector/InspectorInstrumentation.h
@@ -33,6 +33,7 @@
 
 #include "bindings/v8/ScriptString.h"
 #include "core/css/CSSSelector.h"
+#include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/dom/CharacterData.h"
 #include "core/dom/Element.h"
@@ -45,9 +46,9 @@
 #include "core/rendering/RenderImage.h"
 #include "core/storage/StorageArea.h"
 #include "modules/websockets/WebSocketFrame.h"
-#include "modules/websockets/WebSocketHandshakeRequest.h"
-#include "modules/websockets/WebSocketHandshakeResponse.h"
 #include "platform/network/FormData.h"
+#include "platform/network/WebSocketHandshakeRequest.h"
+#include "platform/network/WebSocketHandshakeResponse.h"
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
@@ -58,6 +59,7 @@
 class DeviceOrientationData;
 class GeolocationPosition;
 class GraphicsContext;
+class GraphicsLayer;
 class InspectorTimelineAgent;
 class InstrumentingAgents;
 class RenderLayer;
@@ -123,7 +125,6 @@
 extern const char PaintSetup[];
 extern const char PaintLayer[];
 extern const char RasterTask[];
-extern const char ImageDecodeTask[];
 extern const char Paint[];
 extern const char Layer[];
 extern const char BeginFrame[];
@@ -135,7 +136,6 @@
 extern const char LayerTreeId[];
 extern const char NodeId[];
 extern const char PageId[];
-extern const char PixelRefId[];
 };
 
 namespace InspectorInstrumentation {
@@ -165,11 +165,21 @@
     return document ? instrumentingAgentsFor(*document) : 0;
 }
 
+inline InstrumentingAgents* instrumentingAgentsFor(CSSStyleSheet* styleSheet)
+{
+    return styleSheet ? instrumentingAgentsFor(styleSheet->ownerDocument()) : 0;
+}
+
 inline InstrumentingAgents* instrumentingAgentsFor(Node* node)
 {
     return node ? instrumentingAgentsFor(node->document()) : 0;
 }
 
+inline InstrumentingAgents* instrumentingAgentsFor(CSSStyleDeclaration* declaration)
+{
+    return declaration ? instrumentingAgentsFor(declaration->parentStyleSheet()) : 0;
+}
+
 } // namespace InspectorInstrumentation
 
 InstrumentingAgents* instrumentationForPage(Page*);
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index b333401..cc35564 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -92,6 +92,18 @@
     void didInvalidateStyleAttr([Keep] Node*);
 
     [CSS, Inline=FastReturn]
+    void willMutateRules(CSSStyleSheet*);
+
+    [CSS, Inline=FastReturn]
+    void didMutateRules([Keep] CSSStyleSheet*);
+
+    [CSS, Inline=FastReturn]
+    void willMutateStyle(CSSStyleDeclaration*);
+
+    [CSS, Inline=FastReturn]
+    void didMutateStyle([Keep] CSSStyleDeclaration*, bool);
+
+    [CSS, Inline=FastReturn]
     void activeStyleSheetsUpdated([Keep] Document*, const Vector<RefPtr<StyleSheet> >& newSheets);
 
     [Console]
@@ -224,7 +236,7 @@
     void willPaint([Keep] RenderObject*);
 
     [Timeline, Page, LayerTree, Inline=FastReturn]
-    void didPaint([Keep] RenderObject*, GraphicsContext*, const LayoutRect&);
+    void didPaint([Keep] RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
 
     [Timeline, Inline=FastReturn]
     void willPaintImage([Keep] RenderImage*);
@@ -498,7 +510,7 @@
     GeolocationPosition* overrideGeolocationPosition(Page* page, [DefaultReturn] GeolocationPosition* position);
 
     [Page, Inline=FastReturn]
-    float overrideTextAutosizingFontScaleFactor(Page* page, [DefaultReturn] float fontScaleFactor);
+    float overrideFontScaleFactor(Page* page, [DefaultReturn] float fontScaleFactor);
 
     [Page, Inline=FastReturn]
     bool overrideTextAutosizing(Page* page, [DefaultReturn] bool textAutosizing);
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.cpp b/Source/core/inspector/InspectorLayerTreeAgent.cpp
index 5f4df0d..5193283 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.cpp
+++ b/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -52,7 +52,7 @@
 
 namespace WebCore {
 
-inline String idForLayer(GraphicsLayer* graphicsLayer)
+inline String idForLayer(const GraphicsLayer* graphicsLayer)
 {
     return String::number(graphicsLayer->platformLayer()->id());
 }
@@ -149,14 +149,12 @@
     m_frontend->layerTreeDidChange(buildLayerTree());
 }
 
-void InspectorLayerTreeAgent::didPaint(RenderObject* renderer, GraphicsContext*, const LayoutRect& rect)
+void InspectorLayerTreeAgent::didPaint(RenderObject*, const GraphicsLayer* graphicsLayer, GraphicsContext*, const LayoutRect& rect)
 {
-    RenderLayer* renderLayer = toRenderLayerModelObject(renderer)->layer();
-    CompositedLayerMapping* compositedLayerMapping = renderLayer->compositedLayerMapping();
     // Should only happen for FrameView paints when compositing is off. Consider different instrumentation method for that.
-    if (!compositedLayerMapping)
+    if (!graphicsLayer)
         return;
-    GraphicsLayer* graphicsLayer = compositedLayerMapping->mainGraphicsLayer();
+
     RefPtr<TypeBuilder::DOM::Rect> domRect = TypeBuilder::DOM::Rect::create()
         .setX(rect.x())
         .setY(rect.y())
@@ -179,7 +177,7 @@
 
 void InspectorLayerTreeAgent::buildLayerIdToNodeIdMap(RenderLayer* root, LayerIdToNodeIdMap& layerIdToNodeIdMap)
 {
-    if (root->compositedLayerMapping()) {
+    if (root->hasCompositedLayerMapping()) {
         if (Node* node = root->renderer()->generatingNode()) {
             GraphicsLayer* graphicsLayer = root->compositedLayerMapping()->childForSuperlayers();
             layerIdToNodeIdMap.set(graphicsLayer->platformLayer()->id(), idForNode(node));
@@ -291,7 +289,7 @@
     const GraphicsLayer* graphicsLayer = layerById(errorString, layerId);
     if (!graphicsLayer)
         return;
-    WebKit::WebCompositingReasons reasonsBitmask = graphicsLayer->compositingReasons();
+    blink::WebCompositingReasons reasonsBitmask = graphicsLayer->compositingReasons();
     reasonStrings = TypeBuilder::Array<String>::create();
     for (size_t i = 0; i < WTF_ARRAY_LENGTH(compositingReasonNames); ++i) {
         if (!(reasonsBitmask & compositingReasonNames[i].mask))
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.h b/Source/core/inspector/InspectorLayerTreeAgent.h
index 20c3487..e85e422 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.h
+++ b/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -63,7 +63,7 @@
 
     // Called from InspectorInstrumentation
     void layerTreeDidChange();
-    void didPaint(RenderObject*, GraphicsContext*, const LayoutRect&);
+    void didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
 
     // Called from the front-end.
     virtual void enable(ErrorString*);
diff --git a/Source/core/inspector/InspectorOverlay.cpp b/Source/core/inspector/InspectorOverlay.cpp
index 24866ec..1ade847 100644
--- a/Source/core/inspector/InspectorOverlay.cpp
+++ b/Source/core/inspector/InspectorOverlay.cpp
@@ -252,6 +252,7 @@
     , m_drawViewSize(false)
     , m_drawViewSizeWithGrid(false)
     , m_timer(this, &InspectorOverlay::onTimer)
+    , m_activeProfilerCount(0)
 {
 }
 
@@ -315,6 +316,14 @@
     return overlayPage()->mainFrame()->eventHandler().handleTouchEvent(event);
 }
 
+bool InspectorOverlay::handleKeyboardEvent(const PlatformKeyboardEvent& event)
+{
+    if (isEmpty())
+        return false;
+
+    return overlayPage()->mainFrame()->eventHandler().keyEvent(event);
+}
+
 void InspectorOverlay::drawOutline(GraphicsContext* context, const LayoutRect& rect, const Color& color)
 {
     FloatRect outlineRect = rect;
@@ -389,6 +398,8 @@
 
 bool InspectorOverlay::isEmpty()
 {
+    if (m_activeProfilerCount)
+        return true;
     bool hasAlwaysVisibleElements = m_highlightNode || m_eventTargetNode || m_highlightQuad || !m_size.isEmpty() || m_drawViewSize;
     bool hasInvisibleInInspectModeElements = !m_pausedInDebuggerMessage.isNull();
     return !(hasAlwaysVisibleElements || (hasInvisibleInInspectModeElements && !m_inspectModeEnabled));
@@ -582,7 +593,6 @@
     m_overlayChromeClient = adoptPtr(new InspectorOverlayChromeClient(m_page->chrome().client(), this));
     pageClients.chromeClient = m_overlayChromeClient.get();
     m_overlayPage = adoptPtr(new Page(pageClients));
-    m_overlayPage->setGroupType(Page::InspectorPageGroup);
 
     Settings& settings = m_page->settings();
     Settings& overlaySettings = m_overlayPage->settings();
@@ -676,4 +686,10 @@
     m_timer.stop();
 }
 
+void InspectorOverlay::startedRecordingProfile()
+{
+    if (!m_activeProfilerCount++)
+        freePage();
+}
+
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorOverlay.h b/Source/core/inspector/InspectorOverlay.h
index 988d154..609cf52 100644
--- a/Source/core/inspector/InspectorOverlay.h
+++ b/Source/core/inspector/InspectorOverlay.h
@@ -50,6 +50,7 @@
 class Node;
 class Page;
 class PlatformGestureEvent;
+class PlatformKeyboardEvent;
 class PlatformMouseEvent;
 class PlatformTouchEvent;
 
@@ -122,6 +123,7 @@
     bool handleGestureEvent(const PlatformGestureEvent&);
     bool handleMouseEvent(const PlatformMouseEvent&);
     bool handleTouchEvent(const PlatformTouchEvent&);
+    bool handleKeyboardEvent(const PlatformKeyboardEvent&);
 
     void setPausedInDebuggerMessage(const String*);
     void setInspectModeEnabled(bool);
@@ -138,6 +140,9 @@
 
     InspectorOverlayHost* overlayHost() const { return m_overlayHost.get(); }
 
+    void startedRecordingProfile();
+    void finishedRecordingProfile() { m_activeProfilerCount--; }
+
     // Methods supporting underlying overlay page.
     void invalidate();
 private:
@@ -172,6 +177,7 @@
     bool m_drawViewSize;
     bool m_drawViewSizeWithGrid;
     Timer<InspectorOverlay> m_timer;
+    int m_activeProfilerCount;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorOverlayPage.html b/Source/core/inspector/InspectorOverlayPage.html
index 2eecd21..c10cac7 100644
--- a/Source/core/inspector/InspectorOverlayPage.html
+++ b/Source/core/inspector/InspectorOverlayPage.html
@@ -158,6 +158,7 @@
 
 function drawPausedInDebuggerMessage(message)
 {
+    window._controlsVisible = true;
     document.querySelector(".controls-line").style.visibility = "visible";
     document.getElementById("paused-in-debugger").textContent = message;
     document.body.classList.add("dimmed");
@@ -396,6 +397,7 @@
     window.canvasWidth = viewportSize.width;
     window.canvasHeight = viewportSize.height;
 
+    window._controlsVisible = false;
     document.querySelector(".controls-line").style.visibility = "hidden";
     document.getElementById("element-title").style.visibility = "hidden";
     document.body.classList.remove("dimmed");
@@ -658,15 +660,31 @@
     document.getElementById("step-over-button").addEventListener("click", onStepOverClick);
 }
 
+function eventHasCtrlOrMeta(event)
+{
+    return window.platform == "mac" ? (event.metaKey && !event.ctrlKey) : (event.ctrlKey && !event.metaKey);
+}
+
+function onDocumentKeyDown(event)
+{
+    if (!window._controlsVisible)
+        return;
+    if (event.keyIdentifier == "F8" || eventHasCtrlOrMeta(event) && event.keyCode == 220 /* backslash */)
+        InspectorOverlayHost.resume();
+    else if (event.keyIdentifier == "F10" || eventHasCtrlOrMeta(event) && event.keyCode == 222 /* single quote */)
+        InspectorOverlayHost.stepOver();
+}
+
 window.addEventListener("DOMContentLoaded", onLoaded);
+document.addEventListener("keydown", onDocumentKeyDown);
 
 </script>
 </head>
 <body class="fill">
 <div class="controls-line">
     <div class="message-box"><div id="paused-in-debugger"></div></div>
-    <button id="resume-button" title="Resume script execution"><div class="glyph"></div></button>
-    <button id="step-over-button" title="Step over next function call"><div class="glyph"></div></button>
+    <button id="resume-button" title="Resume script execution (F8)."><div class="glyph"></div></button>
+    <button id="step-over-button" title="Step over next function call (F10)."><div class="glyph"></div></button>
 </div>
 </body>
 <canvas id="canvas" class="fill"></canvas>
diff --git a/Source/core/inspector/InspectorPageAgent.cpp b/Source/core/inspector/InspectorPageAgent.cpp
index 58b5df7..44aaf12 100644
--- a/Source/core/inspector/InspectorPageAgent.cpp
+++ b/Source/core/inspector/InspectorPageAgent.cpp
@@ -64,14 +64,14 @@
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
 #include "core/page/Settings.h"
-#include "core/platform/Cookie.h"
 #include "core/platform/text/RegularExpression.h"
+#include "modules/device_orientation/DeviceOrientationController.h"
 #include "modules/device_orientation/DeviceOrientationData.h"
-#include "modules/device_orientation/NewDeviceOrientationController.h"
 #include "modules/geolocation/GeolocationController.h"
+#include "platform/Cookie.h"
 #include "platform/JSONValues.h"
 #include "platform/UserGestureIndicator.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/Vector.h"
@@ -89,7 +89,7 @@
 static const char pageAgentDeviceScaleFactorOverride[] = "pageAgentDeviceScaleFactorOverride";
 static const char pageAgentEmulateViewport[] = "pageAgentEmulateViewport";
 static const char pageAgentFitWindow[] = "pageAgentFitWindow";
-static const char textAutosizingFontScaleFactorOverride[] = "textAutosizingFontScaleFactorOverride";
+static const char fontScaleFactor[] = "fontScaleFactor";
 static const char pageAgentShowFPSCounter[] = "pageAgentShowFPSCounter";
 static const char pageAgentTextAutosizingOverride[] = "pageAgentTextAutosizingOverride";
 static const char pageAgentContinuousPaintingEnabled[] = "pageAgentContinuousPaintingEnabled";
@@ -158,14 +158,14 @@
     return type == InspectorPageAgent::DocumentResource || type == InspectorPageAgent::StylesheetResource || type == InspectorPageAgent::ScriptResource || type == InspectorPageAgent::XHRResource;
 }
 
-static PassRefPtr<TextResourceDecoder> createXHRTextDecoder(const String& mimeType, const String& textEncodingName)
+static PassOwnPtr<TextResourceDecoder> createXHRTextDecoder(const String& mimeType, const String& textEncodingName)
 {
     if (!textEncodingName.isEmpty())
         return TextResourceDecoder::create("text/plain", textEncodingName);
     if (DOMImplementation::isXMLMIMEType(mimeType.lower())) {
-        RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
+        OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
         decoder->useLenientXMLDecoding();
-        return decoder;
+        return decoder.release();
     }
     if (equalIgnoringCase(mimeType, "text/html"))
         return TextResourceDecoder::create("text/html", "UTF-8");
@@ -198,10 +198,10 @@
     if (cachedResource) {
         switch (cachedResource->type()) {
         case Resource::CSSStyleSheet:
-            *result = static_cast<CSSStyleSheetResource*>(cachedResource)->sheetText(false);
+            *result = toCSSStyleSheetResource(cachedResource)->sheetText(false);
             return true;
         case Resource::Script:
-            *result = static_cast<WebCore::ScriptResource*>(cachedResource)->script();
+            *result = toScriptResource(cachedResource)->script();
             return true;
         case Resource::MainResource:
             return false;
@@ -209,7 +209,7 @@
             SharedBuffer* buffer = cachedResource->resourceBuffer();
             if (!buffer)
                 return false;
-            RefPtr<TextResourceDecoder> decoder = createXHRTextDecoder(cachedResource->response().mimeType(), cachedResource->response().textEncodingName());
+            OwnPtr<TextResourceDecoder> decoder = createXHRTextDecoder(cachedResource->response().mimeType(), cachedResource->response().textEncodingName());
             String content = decoder->decode(buffer->data(), buffer->size());
             *result = content + decoder->flush();
             return true;
@@ -323,7 +323,6 @@
     , m_enabled(false)
     , m_geolocationOverridden(false)
     , m_ignoreScriptsEnabledNotification(false)
-    , m_didForceCompositingMode(false)
     , m_deviceMetricsOverridden(false)
 {
 }
@@ -349,7 +348,7 @@
         bool scriptExecutionDisabled = m_state->getBoolean(PageAgentState::pageAgentScriptExecutionDisabled);
         setScriptExecutionDisabled(0, scriptExecutionDisabled);
         if (m_state->getBoolean(PageAgentState::forceCompositingMode))
-            setForceCompositingMode(0, true);
+            setForceCompositingMode(0);
         bool showPaintRects = m_state->getBoolean(PageAgentState::pageAgentShowPaintRects);
         setShowPaintRects(0, showPaintRects);
         bool showDebugBorders = m_state->getBoolean(PageAgentState::pageAgentShowDebugBorders);
@@ -402,8 +401,6 @@
     setContinuousPaintingEnabled(0, false);
     setShowScrollBottleneckRects(0, false);
     setShowViewportSizeOnResize(0, false, 0);
-    if (m_didForceCompositingMode)
-        setForceCompositingMode(0, false);
 
     if (!deviceMetricsChanged(0, 0, 1, false, false, 1, false))
         return;
@@ -415,7 +412,7 @@
     m_state->setDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, 1);
     m_state->setBoolean(PageAgentState::pageAgentEmulateViewport, false);
     m_state->setBoolean(PageAgentState::pageAgentFitWindow, false);
-    m_state->setDouble(PageAgentState::textAutosizingFontScaleFactorOverride, 1);
+    m_state->setDouble(PageAgentState::fontScaleFactor, 1);
     m_state->setBoolean(PageAgentState::pageAgentTextAutosizingOverride, false);
 }
 
@@ -507,12 +504,12 @@
         switch (cachedResource->type()) {
         case Resource::Image:
             // Skip images that were not auto loaded (images disabled in the user agent).
-            if (static_cast<ImageResource*>(cachedResource)->stillNeedsLoad())
+            if (toImageResource(cachedResource)->stillNeedsLoad())
                 continue;
             break;
         case Resource::Font:
             // Skip fonts that were referenced in CSS but never used/downloaded.
-            if (static_cast<FontResource*>(cachedResource)->stillNeedsLoad())
+            if (toFontResource(cachedResource)->stillNeedsLoad())
                 continue;
             break;
         default:
@@ -679,7 +676,7 @@
     m_state->setDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, deviceScaleFactor);
     m_state->setBoolean(PageAgentState::pageAgentEmulateViewport, emulateViewport);
     m_state->setBoolean(PageAgentState::pageAgentFitWindow, fitWindow);
-    m_state->setDouble(PageAgentState::textAutosizingFontScaleFactorOverride, fontScaleFactor);
+    m_state->setDouble(PageAgentState::fontScaleFactor, fontScaleFactor);
     m_state->setBoolean(PageAgentState::pageAgentTextAutosizingOverride, textAutosizing);
 
     updateViewMetrics(width, height, deviceScaleFactor, emulateViewport, fitWindow);
@@ -693,7 +690,7 @@
     double currentDeviceScaleFactor = m_state->getDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, 1);
     bool currentEmulateViewport = m_state->getBoolean(PageAgentState::pageAgentEmulateViewport);
     bool currentFitWindow = m_state->getBoolean(PageAgentState::pageAgentFitWindow);
-    double currentFontScaleFactor = m_state->getDouble(PageAgentState::textAutosizingFontScaleFactorOverride, 1);
+    double currentFontScaleFactor = m_state->getDouble(PageAgentState::fontScaleFactor, 1);
     bool currentTextAutosizing = m_state->getBoolean(PageAgentState::pageAgentTextAutosizingOverride);
 
     return width != currentWidth || height != currentHeight || deviceScaleFactor != currentDeviceScaleFactor || emulateViewport != currentEmulateViewport || fitWindow != currentFitWindow || fontScaleFactor != currentFontScaleFactor || textAutosizing != currentTextAutosizing;
@@ -800,7 +797,7 @@
 
     m_frontend->domContentEventFired(currentTime());
     if (m_state->getBoolean(PageAgentState::forceCompositingMode))
-        setForceCompositingMode(0, true);
+        setForceCompositingMode(0);
 }
 
 void InspectorPageAgent::loadEventFired(Frame* frame)
@@ -970,7 +967,7 @@
     m_frontend->javascriptDialogClosed();
 }
 
-void InspectorPageAgent::didPaint(RenderObject*, GraphicsContext* context, const LayoutRect& rect)
+void InspectorPageAgent::didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext* context, const LayoutRect& rect)
 {
     if (!m_enabled || m_client->overridesShowPaintRects() || !m_state->getBoolean(PageAgentState::pageAgentShowPaintRects))
         return;
@@ -1082,8 +1079,10 @@
     m_client->overrideDeviceMetrics(width, height, static_cast<float>(deviceScaleFactor), emulateViewport, fitWindow);
 
     Document* document = mainFrame()->document();
-    if (document)
+    if (document) {
         document->styleResolverChanged(RecalcStyleImmediately);
+        document->mediaQueryAffectingValueChanged();
+    }
     InspectorInstrumentation::mediaQueryResultChanged(document);
 
     // FIXME: allow metrics override, fps counter and continuous painting at the same time: crbug.com/299837.
@@ -1144,7 +1143,7 @@
 
 void InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma)
 {
-    NewDeviceOrientationController* controller = NewDeviceOrientationController::from(mainFrame()->document());
+    DeviceOrientationController* controller = DeviceOrientationController::from(mainFrame()->document());
     if (!controller) {
         *error = "Internal error: unable to override device orientation";
         return;
@@ -1165,11 +1164,11 @@
     return m_state->getBoolean(PageAgentState::pageAgentTextAutosizingOverride);
 }
 
-float InspectorPageAgent::overrideTextAutosizingFontScaleFactor(float fontScaleFactor)
+float InspectorPageAgent::overrideFontScaleFactor(float fontScaleFactor)
 {
     if (!m_deviceMetricsOverridden)
         return fontScaleFactor;
-    return static_cast<float>(m_state->getDouble(PageAgentState::textAutosizingFontScaleFactorOverride));
+    return static_cast<float>(m_state->getDouble(PageAgentState::fontScaleFactor));
 }
 
 void InspectorPageAgent::setTouchEmulationEnabled(ErrorString*, bool enabled)
@@ -1190,6 +1189,7 @@
     if (m_page->mainFrame())
         document = m_page->mainFrame()->document();
     if (document) {
+        document->mediaQueryAffectingValueChanged();
         document->styleResolverChanged(RecalcStyleImmediately);
         document->updateLayout();
     }
@@ -1202,26 +1202,25 @@
         *media = emulatedMedia;
 }
 
-void InspectorPageAgent::setForceCompositingMode(ErrorString* errorString, bool force)
+void InspectorPageAgent::setForceCompositingMode(ErrorString* errorString)
 {
     Settings& settings = m_page->settings();
-    if (force && !settings.acceleratedCompositingEnabled()) {
+    if (!settings.acceleratedCompositingEnabled()) {
         if (errorString)
             *errorString = "Compositing mode is not supported";
         return;
     }
-    m_state->setBoolean(PageAgentState::forceCompositingMode, force);
-    if (settings.forceCompositingMode() == force)
+    m_state->setBoolean(PageAgentState::forceCompositingMode, true);
+    if (settings.forceCompositingMode())
         return;
-    m_didForceCompositingMode = force;
-    settings.setForceCompositingMode(force);
+    settings.setForceCompositingMode(true);
     Frame* mainFrame = m_page->mainFrame();
     if (!mainFrame)
         return;
     mainFrame->view()->updateCompositingLayersAfterStyleChange();
 }
 
-void InspectorPageAgent::captureScreenshot(ErrorString*, const String*, const int*, const int*, const int*, String*, double*, double*, RefPtr<TypeBuilder::DOM::Rect>&)
+void InspectorPageAgent::captureScreenshot(ErrorString*, const String*, const int*, const int*, const int*, String*, RefPtr<TypeBuilder::Page::ScreencastFrameMetadata>&)
 {
     // Handled on the browser level.
 }
diff --git a/Source/core/inspector/InspectorPageAgent.h b/Source/core/inspector/InspectorPageAgent.h
index 3c566b0..0703308 100644
--- a/Source/core/inspector/InspectorPageAgent.h
+++ b/Source/core/inspector/InspectorPageAgent.h
@@ -46,6 +46,7 @@
 class DocumentLoader;
 class Frame;
 class GraphicsContext;
+class GraphicsLayer;
 class InjectedScriptManager;
 class InspectorClient;
 class InspectorOverlay;
@@ -113,8 +114,8 @@
     virtual void clearDeviceOrientationOverride(ErrorString*);
     virtual void setTouchEmulationEnabled(ErrorString*, bool);
     virtual void setEmulatedMedia(ErrorString*, const String&);
-    virtual void setForceCompositingMode(ErrorString*, bool force);
-    virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight, String* data, double* deviceScaleFactor, double* pageScaleFactor, RefPtr<TypeBuilder::DOM::Rect>&);
+    virtual void setForceCompositingMode(ErrorString*);
+    virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight, String* data, RefPtr<TypeBuilder::Page::ScreencastFrameMetadata>& out_metadata);
     virtual void canScreencast(ErrorString*, bool*);
     virtual void startScreencast(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight);
     virtual void stopScreencast(ErrorString*);
@@ -124,9 +125,10 @@
     // Geolocation override helper.
     GeolocationPosition* overrideGeolocationPosition(GeolocationPosition*);
 
-    // Text autosizing helpers.
+    // Text autosizing override helpers.
     bool overrideTextAutosizing(bool);
-    float overrideTextAutosizingFontScaleFactor(float);
+    // Note: This is used by Settings::deviceScaleAdjustment to calculate the overridden device scale adjustment.
+    float overrideFontScaleFactor(float);
 
     // InspectorInstrumentation API
     void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
@@ -148,7 +150,7 @@
     void applyScreenHeightOverride(long*);
     bool shouldApplyScreenHeightOverride();
     void applyEmulatedMedia(String*);
-    void didPaint(RenderObject*, GraphicsContext*, const LayoutRect&);
+    void didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
     void didLayout(RenderObject*);
     void didScroll();
     void didResizeMainFrame();
@@ -205,7 +207,6 @@
     bool m_enabled;
     bool m_geolocationOverridden;
     bool m_ignoreScriptsEnabledNotification;
-    bool m_didForceCompositingMode;
     bool m_deviceMetricsOverridden;
     RefPtr<GeolocationPosition> m_geolocationPosition;
     RefPtr<GeolocationPosition> m_platformGeolocationPosition;
diff --git a/Source/core/inspector/InspectorProfilerAgent.cpp b/Source/core/inspector/InspectorProfilerAgent.cpp
index 13e01ae..54f6a46 100644
--- a/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -36,6 +36,7 @@
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptHost.h"
 #include "core/inspector/InspectorConsoleAgent.h"
+#include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorState.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/ScriptCallStack.h"
@@ -54,12 +55,12 @@
 
 static const char CPUProfileType[] = "CPU";
 
-PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
+PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
 {
-    return adoptPtr(new InspectorProfilerAgent(instrumentingAgents, consoleAgent, inspectorState, injectedScriptManager));
+    return adoptPtr(new InspectorProfilerAgent(instrumentingAgents, consoleAgent, inspectorState, injectedScriptManager, overlay));
 }
 
-InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
+InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
     : InspectorBaseAgent<InspectorProfilerAgent>("Profiler", instrumentingAgents, inspectorState)
     , m_consoleAgent(consoleAgent)
     , m_injectedScriptManager(injectedScriptManager)
@@ -69,6 +70,7 @@
     , m_nextUserInitiatedProfileNumber(1)
     , m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
     , m_idleStartTime(0.0)
+    , m_overlay(overlay)
 {
 }
 
@@ -225,6 +227,8 @@
         enable(&error);
     }
     m_recordingCPUProfile = true;
+    if (m_overlay)
+        m_overlay->startedRecordingProfile();
     String title = getCurrentUserInitiatedProfileName(true);
     ScriptProfiler::start(title);
     toggleRecordButton(true);
@@ -244,6 +248,8 @@
         return 0;
     }
     m_recordingCPUProfile = false;
+    if (m_overlay)
+        m_overlay->finishedRecordingProfile();
     String title = getCurrentUserInitiatedProfileName();
     RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
     RefPtr<TypeBuilder::Profiler::ProfileHeader> profileHeader;
diff --git a/Source/core/inspector/InspectorProfilerAgent.h b/Source/core/inspector/InspectorProfilerAgent.h
index 2c0ed70..619b59e 100644
--- a/Source/core/inspector/InspectorProfilerAgent.h
+++ b/Source/core/inspector/InspectorProfilerAgent.h
@@ -43,6 +43,7 @@
 class InjectedScriptManager;
 class InspectorConsoleAgent;
 class InspectorFrontend;
+class InspectorOverlay;
 class InstrumentingAgents;
 class ScriptCallStack;
 class ScriptProfile;
@@ -52,7 +53,7 @@
 class InspectorProfilerAgent : public InspectorBaseAgent<InspectorProfilerAgent>, public InspectorBackendDispatcher::ProfilerCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorProfilerAgent); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<InspectorProfilerAgent> create(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*);
+    static PassOwnPtr<InspectorProfilerAgent> create(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*);
     virtual ~InspectorProfilerAgent();
 
     void addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack>);
@@ -82,7 +83,7 @@
     void didLeaveNestedRunLoop();
 
 private:
-    InspectorProfilerAgent(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*);
+    InspectorProfilerAgent(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*);
 
     void doEnable();
 
@@ -105,6 +106,7 @@
     typedef HashMap<String, double> ProfileNameIdleTimeMap;
     ProfileNameIdleTimeMap* m_profileNameIdleTimeMap;
     double m_idleStartTime;
+    InspectorOverlay* m_overlay;
 
     void idleStarted();
     void idleFinished();
diff --git a/Source/core/inspector/InspectorResourceAgent.cpp b/Source/core/inspector/InspectorResourceAgent.cpp
index 8cdc733..be468bd 100644
--- a/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/Source/core/inspector/InspectorResourceAgent.cpp
@@ -59,14 +59,14 @@
 #include "core/page/Page.h"
 #include "core/xml/XMLHttpRequest.h"
 #include "modules/websockets/WebSocketFrame.h"
-#include "modules/websockets/WebSocketHandshakeRequest.h"
-#include "modules/websockets/WebSocketHandshakeResponse.h"
 #include "platform/JSONValues.h"
 #include "platform/network/HTTPHeaderMap.h"
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
-#include "weborigin/KURL.h"
+#include "platform/network/WebSocketHandshakeRequest.h"
+#include "platform/network/WebSocketHandshakeResponse.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/RefPtr.h"
 
@@ -165,7 +165,7 @@
 
     RefPtr<LoadResourceForFrontendCallback> m_callback;
     RefPtr<ThreadableLoader> m_loader;
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
     ScriptString m_responseText;
     int m_statusCode;
     HTTPHeaderMap m_responseHeaders;
diff --git a/Source/core/inspector/InspectorStyleSheet.cpp b/Source/core/inspector/InspectorStyleSheet.cpp
index d1b88da..36e843f 100644
--- a/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/Source/core/inspector/InspectorStyleSheet.cpp
@@ -30,7 +30,6 @@
 #include "SVGNames.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/css/CSSHostRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSMediaRule.h"
 #include "core/css/CSSParser.h"
@@ -108,8 +107,6 @@
         } else if (data->type == CSSRuleSourceData::MEDIA_RULE) {
             m_sourceData->append(data);
             flattenSourceData(&data->childRules);
-        } else if (data->type == CSSRuleSourceData::HOST_RULE) {
-            flattenSourceData(&data->childRules);
         } else if (data->type == CSSRuleSourceData::SUPPORTS_RULE) {
             flattenSourceData(&data->childRules);
         }
@@ -485,9 +482,6 @@
     if (rule->type() == CSSRule::KEYFRAMES_RULE)
         return static_cast<CSSKeyframesRule*>(rule)->cssRules();
 
-    if (rule->type() == CSSRule::HOST_RULE)
-        return static_cast<CSSHostRule*>(rule)->cssRules();
-
     if (rule->type() == CSSRule::SUPPORTS_RULE)
         return static_cast<CSSSupportsRule*>(rule)->cssRules();
 
@@ -547,13 +541,13 @@
 //
 // The propertyText (if not empty) is checked to be a valid style declaration (containing at least one property). If not,
 // the method returns false (denoting an error).
-bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText, bool overwrite, String* oldText, ExceptionState& es)
+bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText, bool overwrite, String* oldText, ExceptionState& exceptionState)
 {
     ASSERT(m_parentStyleSheet);
     DEFINE_STATIC_LOCAL(String, bogusPropertyName, ("-webkit-boguz-propertee"));
 
     if (!m_parentStyleSheet->ensureParsedDataReady()) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
@@ -568,27 +562,27 @@
 
         // At least one property + the bogus property added just above should be present.
         if (propertyCount < 2) {
-            es.throwUninformativeAndGenericDOMException(SyntaxError);
+            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
             return false;
         }
 
         // Check for the proper propertyText termination (the parser could at least restore to the PROPERTY_NAME state).
         if (propertyData.at(propertyCount - 1).name != bogusPropertyName) {
-            es.throwUninformativeAndGenericDOMException(SyntaxError);
+            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
             return false;
         }
     }
 
     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
     if (!sourceData) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
     String text;
     bool success = styleText(&text);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
@@ -598,7 +592,7 @@
     InspectorStyleTextEditor editor(&allProperties, text, newLineAndWhitespaceDelimiters());
     if (overwrite) {
         if (index >= allProperties.size()) {
-            es.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return false;
         }
         *oldText = allProperties.at(index).rawText;
@@ -609,31 +603,31 @@
     return applyStyleText(editor.styleText());
 }
 
-bool InspectorStyle::toggleProperty(unsigned index, bool disable, ExceptionState& es)
+bool InspectorStyle::toggleProperty(unsigned index, bool disable, ExceptionState& exceptionState)
 {
     ASSERT(m_parentStyleSheet);
     if (!m_parentStyleSheet->ensureParsedDataReady()) {
-        es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
         return false;
     }
 
     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
     if (!sourceData) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
     String text;
     bool success = styleText(&text);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
     Vector<InspectorStyleProperty> allProperties;
     populateAllProperties(allProperties);
     if (index >= allProperties.size()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return false;
     }
 
@@ -990,7 +984,6 @@
     , m_origin(origin)
     , m_documentURL(documentURL)
     , m_isRevalidating(false)
-    , m_isReparsing(false)
     , m_listener(listener)
 {
     m_parsedStyleSheet = new ParsedStyleSheet();
@@ -1019,10 +1012,8 @@
         m_pageStyleSheet->clearChildRuleCSSOMWrappers();
     }
     {
-        m_isReparsing = true;
         CSSStyleSheet::RuleMutationScope mutationScope(m_pageStyleSheet.get());
         m_pageStyleSheet->contents()->parseString(text);
-        m_isReparsing = false;
     }
 
     if (m_listener)
@@ -1031,9 +1022,9 @@
     m_pageStyleSheet->ownerDocument()->styleResolverChanged(RecalcStyleImmediately, FullStyleUpdate);
 }
 
-bool InspectorStyleSheet::setText(const String& text, ExceptionState& es)
+bool InspectorStyleSheet::setText(const String& text, ExceptionState& exceptionState)
 {
-    if (!checkPageStyleSheet(es))
+    if (!checkPageStyleSheet(exceptionState))
         return false;
     if (!m_parsedStyleSheet)
         return false;
@@ -1044,35 +1035,35 @@
     return true;
 }
 
-String InspectorStyleSheet::ruleSelector(const InspectorCSSId& id, ExceptionState& es)
+String InspectorStyleSheet::ruleSelector(const InspectorCSSId& id, ExceptionState& exceptionState)
 {
     CSSStyleRule* rule = ruleForId(id);
     if (!rule) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return "";
     }
     return rule->selectorText();
 }
 
-bool InspectorStyleSheet::setRuleSelector(const InspectorCSSId& id, const String& selector, ExceptionState& es)
+bool InspectorStyleSheet::setRuleSelector(const InspectorCSSId& id, const String& selector, ExceptionState& exceptionState)
 {
-    if (!checkPageStyleSheet(es))
+    if (!checkPageStyleSheet(exceptionState))
         return false;
     CSSStyleRule* rule = ruleForId(id);
     if (!rule) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
     CSSStyleSheet* styleSheet = rule->parentStyleSheet();
     if (!styleSheet || !ensureParsedDataReady()) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
     rule->setSelectorText(selector);
     RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
     if (!sourceData) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
@@ -1090,26 +1081,26 @@
     return selectorList.isValid();
 }
 
-CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionState& es)
+CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionState& exceptionState)
 {
-    if (!checkPageStyleSheet(es))
+    if (!checkPageStyleSheet(exceptionState))
         return 0;
     if (!checkStyleRuleSelector(m_pageStyleSheet->ownerDocument(), selector)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return 0;
     }
 
     String text;
     bool success = getText(&text);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return 0;
     }
     StringBuilder styleSheetText;
     styleSheetText.append(text);
 
-    m_pageStyleSheet->addRule(selector, "", es);
-    if (es.hadException())
+    m_pageStyleSheet->addRule(selector, "", exceptionState);
+    if (exceptionState.hadException())
         return 0;
     ASSERT(m_pageStyleSheet->length());
     unsigned lastRuleIndex = m_pageStyleSheet->length() - 1;
@@ -1121,7 +1112,7 @@
         // What we just added has to be a CSSStyleRule - we cannot handle other types of rules yet.
         // If it is not a style rule, pretend we never touched the stylesheet.
         m_pageStyleSheet->deleteRule(lastRuleIndex, ASSERT_NO_EXCEPTION);
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return 0;
     }
 
@@ -1138,31 +1129,31 @@
     return styleRule;
 }
 
-bool InspectorStyleSheet::deleteRule(const InspectorCSSId& id, ExceptionState& es)
+bool InspectorStyleSheet::deleteRule(const InspectorCSSId& id, ExceptionState& exceptionState)
 {
-    if (!checkPageStyleSheet(es))
+    if (!checkPageStyleSheet(exceptionState))
         return false;
     RefPtr<CSSStyleRule> rule = ruleForId(id);
     if (!rule) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
     CSSStyleSheet* styleSheet = rule->parentStyleSheet();
     if (!styleSheet || !ensureParsedDataReady()) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
     RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
     if (!sourceData) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
-    styleSheet->deleteRule(id.ordinal(), es);
+    styleSheet->deleteRule(id.ordinal(), exceptionState);
     // |rule| MAY NOT be addressed after this line!
 
-    if (es.hadException())
+    if (exceptionState.hadException())
         return false;
 
     String sheetText = m_parsedStyleSheet->text();
@@ -1332,17 +1323,17 @@
     return result.release();
 }
 
-bool InspectorStyleSheet::setStyleText(const InspectorCSSId& id, const String& text, String* oldText, ExceptionState& es)
+bool InspectorStyleSheet::setStyleText(const InspectorCSSId& id, const String& text, String* oldText, ExceptionState& exceptionState)
 {
     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
     if (!inspectorStyle || !inspectorStyle->cssStyle()) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
     bool success = inspectorStyle->styleText(oldText);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
@@ -1350,33 +1341,33 @@
     if (success)
         fireStyleSheetChanged();
     else
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
     return success;
 }
 
-bool InspectorStyleSheet::setPropertyText(const InspectorCSSId& id, unsigned propertyIndex, const String& text, bool overwrite, String* oldText, ExceptionState& es)
+bool InspectorStyleSheet::setPropertyText(const InspectorCSSId& id, unsigned propertyIndex, const String& text, bool overwrite, String* oldText, ExceptionState& exceptionState)
 {
     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
     if (!inspectorStyle) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
-    bool success = inspectorStyle->setPropertyText(propertyIndex, text, overwrite, oldText, es);
+    bool success = inspectorStyle->setPropertyText(propertyIndex, text, overwrite, oldText, exceptionState);
     if (success)
         fireStyleSheetChanged();
     return success;
 }
 
-bool InspectorStyleSheet::toggleProperty(const InspectorCSSId& id, unsigned propertyIndex, bool disable, ExceptionState& es)
+bool InspectorStyleSheet::toggleProperty(const InspectorCSSId& id, unsigned propertyIndex, bool disable, ExceptionState& exceptionState)
 {
     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
     if (!inspectorStyle) {
-        es.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
         return false;
     }
 
-    bool success = inspectorStyle->toggleProperty(propertyIndex, disable, es);
+    bool success = inspectorStyle->toggleProperty(propertyIndex, disable, exceptionState);
     if (success)
         fireStyleSheetChanged();
     return success;
@@ -1543,10 +1534,10 @@
     return index == kNotFound ? UINT_MAX : static_cast<unsigned>(index);
 }
 
-bool InspectorStyleSheet::checkPageStyleSheet(ExceptionState& es) const
+bool InspectorStyleSheet::checkPageStyleSheet(ExceptionState& exceptionState) const
 {
     if (!m_pageStyleSheet) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return false;
     }
     return true;
@@ -1612,12 +1603,12 @@
     if (id.isEmpty())
         return false;
 
-    TrackExceptionState es;
-    style->setCSSText(text, es);
-    if (!es.hadException())
+    TrackExceptionState exceptionState;
+    style->setCSSText(text, exceptionState);
+    if (!exceptionState.hadException())
         m_parsedStyleSheet->setText(patchedStyleSheetText);
 
-    return !es.hadException();
+    return !exceptionState.hadException();
 }
 
 bool InspectorStyleSheet::styleSheetTextWithChangedStyle(CSSStyleDeclaration* style, const String& newStyleText, String* result)
@@ -1738,17 +1729,17 @@
 bool InspectorStyleSheetForInlineStyle::setStyleText(CSSStyleDeclaration* style, const String& text)
 {
     ASSERT_UNUSED(style, style == inlineStyle());
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
 
     {
         InspectorCSSAgent::InlineStyleOverrideScope overrideScope(m_element->ownerDocument());
-        m_element->setAttribute("style", text, es);
+        m_element->setAttribute("style", text, exceptionState);
     }
 
     m_styleText = text;
     m_isStyleTextValid = true;
     m_ruleSourceData.clear();
-    return !es.hadException();
+    return !exceptionState.hadException();
 }
 
 PassOwnPtr<Vector<unsigned> > InspectorStyleSheetForInlineStyle::lineEndings() const
diff --git a/Source/core/inspector/InspectorStyleSheet.h b/Source/core/inspector/InspectorStyleSheet.h
index d5100f3..56a0cca 100644
--- a/Source/core/inspector/InspectorStyleSheet.h
+++ b/Source/core/inspector/InspectorStyleSheet.h
@@ -183,7 +183,6 @@
     virtual Document* ownerDocument() const;
     bool canBind() const { return m_origin != TypeBuilder::CSS::StyleSheetOrigin::User_agent && m_origin != TypeBuilder::CSS::StyleSheetOrigin::User; }
     CSSStyleSheet* pageStyleSheet() const { return m_pageStyleSheet.get(); }
-    bool isReparsing() const { return m_isReparsing; }
     void reparseStyleSheet(const String&);
     bool setText(const String&, ExceptionState&);
     String ruleSelector(const InspectorCSSId&, ExceptionState&);
@@ -249,7 +248,6 @@
     TypeBuilder::CSS::StyleSheetOrigin::Enum m_origin;
     String m_documentURL;
     bool m_isRevalidating;
-    bool m_isReparsing;
     ParsedStyleSheet* m_parsedStyleSheet;
     mutable CSSRuleVector m_flatRules;
     Listener* m_listener;
diff --git a/Source/core/inspector/InspectorTimelineAgent.cpp b/Source/core/inspector/InspectorTimelineAgent.cpp
index 1a3f6e1..5dd0bc6 100644
--- a/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -37,10 +37,12 @@
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/inspector/IdentifiersFactory.h"
+#include "core/inspector/InspectorClient.h"
 #include "core/inspector/InspectorCounters.h"
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/InspectorMemoryAgent.h"
+#include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
 #include "core/inspector/InstrumentingAgents.h"
@@ -49,7 +51,8 @@
 #include "core/inspector/TimelineTraceEventProcessor.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/page/PageConsole.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
+#include "core/platform/graphics/DeferredImageDecoder.h"
+#include "core/platform/graphics/GraphicsLayer.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderView.h"
 #include "core/xml/XMLHttpRequest.h"
@@ -66,6 +69,7 @@
 static const char startedFromProtocol[] = "startedFromProtocol";
 static const char timelineMaxCallStackDepth[] = "timelineMaxCallStackDepth";
 static const char includeDomCounters[] = "includeDomCounters";
+static const char includeGPUEvents[] = "includeGPUEvents";
 static const char bufferEvents[] = "bufferEvents";
 }
 
@@ -125,6 +129,7 @@
 const char DecodeImage[] = "DecodeImage";
 const char Rasterize[] = "Rasterize";
 const char PaintSetup[] = "PaintSetup";
+const char GPUTask[] = "GPUTask";
 }
 
 namespace {
@@ -225,7 +230,7 @@
     m_state->setBoolean(TimelineAgentState::enabled, false);
 }
 
-void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters)
+void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeGPUEvents)
 {
     if (!m_frontend)
         return;
@@ -247,6 +252,7 @@
 
     m_state->setLong(TimelineAgentState::timelineMaxCallStackDepth, m_maxCallStackDepth);
     m_state->setBoolean(TimelineAgentState::includeDomCounters, includeDomCounters && *includeDomCounters);
+    m_state->setBoolean(TimelineAgentState::includeGPUEvents, includeGPUEvents && *includeGPUEvents);
     m_state->setBoolean(TimelineAgentState::bufferEvents, bufferEvents && *bufferEvents);
 
     innerStart();
@@ -261,12 +267,19 @@
 
 void InspectorTimelineAgent::innerStart()
 {
+    if (m_overlay)
+        m_overlay->startedRecordingProfile();
     m_state->setBoolean(TimelineAgentState::started, true);
     m_timeConverter.reset();
     m_instrumentingAgents->setInspectorTimelineAgent(this);
     ScriptGCEvent::addEventListener(this);
-    if (m_client && m_pageAgent)
+    if (m_client && m_pageAgent) {
         m_traceEventProcessor = adoptRef(new TimelineTraceEventProcessor(m_weakFactory.createWeakPtr(), m_client));
+        if (m_state->getBoolean(TimelineAgentState::includeGPUEvents)) {
+            m_pendingGPURecord.clear();
+            m_client->startGPUEventsRecording();
+        }
+    }
 }
 
 void InspectorTimelineAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> >& events)
@@ -291,6 +304,8 @@
         m_traceEventProcessor->shutdown();
         m_traceEventProcessor.clear();
     }
+    if (m_state->getBoolean(TimelineAgentState::includeGPUEvents))
+        m_client->stopGPUEventsRecording();
     m_weakFactory.revokeAll();
     m_instrumentingAgents->setInspectorTimelineAgent(0);
     ScriptGCEvent::removeEventListener(this);
@@ -305,6 +320,9 @@
     m_consoleTimelines.clear();
 
     m_frontend->stopped(&fromConsole);
+
+    if (m_overlay)
+        m_overlay->finishedRecordingProfile();
 }
 
 void InspectorTimelineAgent::didBeginFrame(int frameId)
@@ -449,13 +467,14 @@
     pushCurrentRecord(JSONObject::create(), TimelineRecordType::Paint, true, frame, true);
 }
 
-void InspectorTimelineAgent::didPaint(RenderObject* renderer, GraphicsContext*, const LayoutRect& clipRect)
+void InspectorTimelineAgent::didPaint(RenderObject* renderer, const GraphicsLayer* graphicsLayer, GraphicsContext*, const LayoutRect& clipRect)
 {
     TimelineRecordEntry& entry = m_recordStack.last();
     ASSERT(entry.type == TimelineRecordType::Paint);
     FloatQuad quad;
     localToPageQuad(*renderer, clipRect, &quad);
-    entry.data = TimelineRecordFactory::createPaintData(quad, nodeId(renderer));
+    int graphicsLayerId = graphicsLayer ? graphicsLayer->platformLayer()->id() : 0;
+    entry.data = TimelineRecordFactory::createPaintData(quad, nodeId(renderer), graphicsLayerId);
     didCompleteCurrentRecord(TimelineRecordType::Paint);
 }
 
@@ -690,8 +709,10 @@
     String message = String::format("Timeline '%s' finished.", title.utf8().data());
     appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForExecutionContext(context));
     m_consoleTimelines.remove(index);
-    if (!m_consoleTimelines.size() && isStarted() && !m_state->getBoolean(TimelineAgentState::startedFromProtocol))
+    if (!m_consoleTimelines.size() && isStarted() && !m_state->getBoolean(TimelineAgentState::startedFromProtocol)) {
+        unwindRecordStack();
         innerStop(true);
+    }
     page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
 }
 
@@ -763,6 +784,17 @@
     appendRecord(TimelineRecordFactory::createGenericWebSocketData(identifier), TimelineRecordType::WebSocketDestroy, true, document->frame());
 }
 
+void InspectorTimelineAgent::processGPUEvent(const GPUEvent& event)
+{
+    double timelineTimestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp);
+    if (event.phase == GPUEvent::PhaseBegin) {
+        m_pendingGPURecord = TimelineRecordFactory::createBackgroundRecord(timelineTimestamp, "gpu", TimelineRecordType::GPUTask, TimelineRecordFactory::createGPUTaskData(event.foreign));
+    } else if (m_pendingGPURecord) {
+        m_pendingGPURecord->setNumber("endTime", timelineTimestamp);
+        sendEvent(m_pendingGPURecord.release());
+    }
+}
+
 void InspectorTimelineAgent::addRecordToTimeline(PassRefPtr<JSONObject> record)
 {
     commitFrameRecord();
@@ -772,7 +804,6 @@
 void InspectorTimelineAgent::innerAddRecordToTimeline(PassRefPtr<JSONObject> prpRecord)
 {
     RefPtr<TypeBuilder::Timeline::TimelineEvent> record = TypeBuilder::Timeline::TimelineEvent::runtimeCast(prpRecord);
-
     if (m_recordStack.isEmpty()) {
         sendEvent(record.release());
     } else {
@@ -850,7 +881,15 @@
     }
 }
 
-InspectorTimelineAgent::InspectorTimelineAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
+void InspectorTimelineAgent::unwindRecordStack()
+{
+    while (!m_recordStack.isEmpty()) {
+        TimelineRecordEntry& entry = m_recordStack.last();
+        didCompleteCurrentRecord(entry.type);
+    }
+}
+
+InspectorTimelineAgent::InspectorTimelineAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
     : InspectorBaseAgent<InspectorTimelineAgent>("Timeline", instrumentingAgents, state)
     , m_pageAgent(pageAgent)
     , m_memoryAgent(memoryAgent)
@@ -865,6 +904,7 @@
     , m_styleRecalcElementCounter(0)
     , m_layerTreeId(0)
     , m_imageBeingPainted(0)
+    , m_overlay(overlay)
 {
 }
 
diff --git a/Source/core/inspector/InspectorTimelineAgent.h b/Source/core/inspector/InspectorTimelineAgent.h
index 9a51fd9..0374ac9 100644
--- a/Source/core/inspector/InspectorTimelineAgent.h
+++ b/Source/core/inspector/InspectorTimelineAgent.h
@@ -37,8 +37,8 @@
 #include "core/events/EventPath.h"
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/inspector/ScriptGCEventListener.h"
-#include "core/platform/PlatformInstrumentation.h"
 #include "platform/JSONValues.h"
+#include "platform/PlatformInstrumentation.h"
 #include "platform/geometry/LayoutRect.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
@@ -53,10 +53,12 @@
 class FloatQuad;
 class Frame;
 class GraphicsContext;
+class GraphicsLayer;
 class InspectorClient;
 class InspectorDOMAgent;
 class InspectorFrontend;
 class InspectorMemoryAgent;
+class InspectorOverlay;
 class InspectorPageAgent;
 class InstrumentingAgents;
 class KURL;
@@ -83,6 +85,7 @@
 extern const char DecodeImage[];
 extern const char Rasterize[];
 extern const char PaintSetup[];
+extern const char GPUTask[];
 };
 
 class TimelineTimeConverter {
@@ -107,9 +110,21 @@
 public:
     enum InspectorType { PageInspector, WorkerInspector };
 
-    static PassOwnPtr<InspectorTimelineAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
+    class GPUEvent {
+    public:
+        enum Phase { PhaseBegin, PhaseEnd };
+        GPUEvent(double timestamp, int phase, bool foreign) :
+            timestamp(timestamp),
+            phase(static_cast<Phase>(phase)),
+            foreign(foreign) { }
+        double timestamp;
+        Phase phase;
+        bool foreign;
+    };
+
+    static PassOwnPtr<InspectorTimelineAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
     {
-        return adoptPtr(new InspectorTimelineAgent(instrumentingAgents, pageAgent, memoryAgent, domAgent, state, type, client));
+        return adoptPtr(new InspectorTimelineAgent(instrumentingAgents, pageAgent, memoryAgent, domAgent, overlay, state, type, client));
     }
 
     ~InspectorTimelineAgent();
@@ -120,7 +135,7 @@
 
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
-    virtual void start(ErrorString*, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters);
+    virtual void start(ErrorString*, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeGPUEvents);
     virtual void stop(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> >& events);
 
     void setLayerTreeId(int layerTreeId) { m_layerTreeId = layerTreeId; }
@@ -154,7 +169,7 @@
     void didRecalculateStyleForElement();
 
     void willPaint(RenderObject*);
-    void didPaint(RenderObject*, GraphicsContext*, const LayoutRect&);
+    void didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
 
     void willPaintImage(RenderImage*);
     void didPaintImage();
@@ -212,6 +227,8 @@
     void didReceiveWebSocketHandshakeResponse(Document*, unsigned long identifier, const WebSocketHandshakeResponse&);
     void didCloseWebSocket(Document*, unsigned long identifier);
 
+    void processGPUEvent(const class GPUEvent&);
+
     // ScriptGCEventListener methods.
     virtual void didGC(double, double, size_t);
 
@@ -237,7 +254,7 @@
         size_t usedHeapSizeAtStart;
     };
 
-    InspectorTimelineAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorMemoryAgent*, InspectorDOMAgent*, InspectorCompositeState*, InspectorType, InspectorClient*);
+    InspectorTimelineAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorMemoryAgent*, InspectorDOMAgent*, InspectorOverlay*, InspectorCompositeState*, InspectorType, InspectorClient*);
 
     void didFinishLoadingResource(unsigned long, bool didFail, double finishTime, Frame*);
 
@@ -252,6 +269,7 @@
     void pushGCEventRecords();
 
     void didCompleteCurrentRecord(const String& type);
+    void unwindRecordStack();
 
     void commitFrameRecord();
 
@@ -298,6 +316,7 @@
     int m_maxCallStackDepth;
     unsigned m_platformInstrumentationClientInstalledAtStackDepth;
     RefPtr<JSONObject> m_pendingFrameRecord;
+    RefPtr<JSONObject> m_pendingGPURecord;
     InspectorType m_inspectorType;
     InspectorClient* m_client;
     WeakPtrFactory<InspectorTimelineAgent> m_weakFactory;
@@ -307,6 +326,7 @@
     RenderImage* m_imageBeingPainted;
     Vector<String> m_consoleTimelines;
     RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> > m_bufferedEvents;
+    InspectorOverlay* m_overlay;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorWorkerAgent.cpp b/Source/core/inspector/InspectorWorkerAgent.cpp
index c2cffe3..c4b9191 100644
--- a/Source/core/inspector/InspectorWorkerAgent.cpp
+++ b/Source/core/inspector/InspectorWorkerAgent.cpp
@@ -38,7 +38,7 @@
 #include "core/inspector/JSONParser.h"
 #include "core/workers/WorkerGlobalScopeProxy.h"
 #include "platform/JSONValues.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/inspector/JavaScriptCallFrame.cpp b/Source/core/inspector/JavaScriptCallFrame.cpp
index ffaf8ab..3d05d62 100644
--- a/Source/core/inspector/JavaScriptCallFrame.cpp
+++ b/Source/core/inspector/JavaScriptCallFrame.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/inspector/JavaScriptCallFrame.h"
 
+#include "bindings/v8/ScriptValue.h"
 #include "bindings/v8/V8Binding.h"
 
 namespace WebCore {
@@ -127,6 +128,21 @@
     return toWebCoreStringWithUndefinedOrNullCheck(result);
 }
 
+bool JavaScriptCallFrame::isAtReturn() const
+{
+    v8::HandleScope handleScope(m_isolate);
+    v8::Context::Scope contextScope(m_debuggerContext.newLocal(m_isolate));
+    v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("isAtReturn"));
+    if (result->IsBoolean())
+        return result->BooleanValue();
+    return false;
+}
+
+v8::Handle<v8::Value> JavaScriptCallFrame::returnValue() const
+{
+    return m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("returnValue"));
+}
+
 v8::Handle<v8::Value> JavaScriptCallFrame::evaluate(const String& expression)
 {
     v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
@@ -150,16 +166,16 @@
     return m_callFrame.newLocal(m_isolate);
 }
 
-v8::Handle<v8::Value> JavaScriptCallFrame::setVariableValue(int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue)
+ScriptValue JavaScriptCallFrame::setVariableValue(int scopeNumber, const String& variableName, const ScriptValue& newValue)
 {
     v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
     v8::Handle<v8::Function> setVariableValueFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8::String::NewSymbol("setVariableValue")));
     v8::Handle<v8::Value> argv[] = {
         v8::Handle<v8::Value>(v8::Integer::New(scopeNumber, m_isolate)),
         v8String(variableName, m_isolate),
-        newValue
+        newValue.v8Value()
     };
-    return setVariableValueFunction->Call(callFrame, 3, argv);
+    return ScriptValue(setVariableValueFunction->Call(callFrame, 3, argv), m_isolate);
 }
 
 } // namespace WebCore
diff --git a/Source/core/inspector/JavaScriptCallFrame.h b/Source/core/inspector/JavaScriptCallFrame.h
index 2d6e857..ac0c035 100644
--- a/Source/core/inspector/JavaScriptCallFrame.h
+++ b/Source/core/inspector/JavaScriptCallFrame.h
@@ -40,6 +40,8 @@
 
 namespace WebCore {
 
+class ScriptValue;
+
 class JavaScriptCallFrame : public RefCounted<JavaScriptCallFrame>, public ScriptWrappable {
 public:
     static PassRefPtr<JavaScriptCallFrame> create(v8::Handle<v8::Context> debuggerContext, v8::Handle<v8::Object> callFrame)
@@ -59,10 +61,12 @@
     int scopeType(int scopeIndex) const;
     v8::Handle<v8::Value> thisObject() const;
     String stepInPositions() const;
+    bool isAtReturn() const;
+    v8::Handle<v8::Value> returnValue() const;
 
     v8::Handle<v8::Value> evaluate(const String& expression);
     v8::Handle<v8::Value> restart();
-    v8::Handle<v8::Value> setVariableValue(int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue);
+    ScriptValue setVariableValue(int scopeNumber, const String& variableName, const ScriptValue& newValue);
     v8::Handle<v8::Object> innerCallFrame();
 
 private:
diff --git a/Source/core/inspector/JavaScriptCallFrame.idl b/Source/core/inspector/JavaScriptCallFrame.idl
index fa31924..1afad5a 100644
--- a/Source/core/inspector/JavaScriptCallFrame.idl
+++ b/Source/core/inspector/JavaScriptCallFrame.idl
@@ -39,17 +39,18 @@
     [Custom] any restart();
 
     // Only declarative scope (local, with and catch) is accepted. Returns undefined.
-    [Custom] any setVariableValue(long scopeIndex, DOMString variableName, any newValue);
+    any setVariableValue([Default=Undefined] optional long scopeIndex, [TreatNullAs=NullString, TreatUndefinedAs=NullString, Default=Undefined] optional DOMString variableName, [Default=Undefined] optional any newValue);
 
     readonly attribute JavaScriptCallFrame caller;
     readonly attribute long sourceID;
     readonly attribute long line;
     readonly attribute long column;
-    [CustomGetter] readonly attribute Array scopeChain;
+    [Custom=Getter] readonly attribute object scopeChain;
     [Custom] unsigned short scopeType(long scopeIndex);
-    [CustomGetter] readonly attribute Object thisObject;
+    [Custom=Getter] readonly attribute object thisObject;
     readonly attribute DOMString stepInPositions;
     readonly attribute DOMString functionName;
-    [CustomGetter] readonly attribute DOMString type;
+    [Custom=Getter] readonly attribute DOMString type;
+    readonly attribute boolean isAtReturn;
+    [Custom=Getter] readonly attribute any returnValue;
 };
-
diff --git a/Source/core/inspector/NetworkResourcesData.cpp b/Source/core/inspector/NetworkResourcesData.cpp
index cf9f2c4..9f2bb4f 100644
--- a/Source/core/inspector/NetworkResourcesData.cpp
+++ b/Source/core/inspector/NetworkResourcesData.cpp
@@ -155,9 +155,9 @@
     m_requestIdToResourceDataMap.set(requestId, new ResourceData(requestId, loaderId));
 }
 
-static PassRefPtr<TextResourceDecoder> createOtherResourceTextDecoder(const String& mimeType, const String& textEncodingName)
+static PassOwnPtr<TextResourceDecoder> createOtherResourceTextDecoder(const String& mimeType, const String& textEncodingName)
 {
-    RefPtr<TextResourceDecoder> decoder;
+    OwnPtr<TextResourceDecoder> decoder;
     if (!textEncodingName.isEmpty())
         decoder = TextResourceDecoder::create("text/plain", textEncodingName);
     else if (DOMImplementation::isXMLMIMEType(mimeType.lower())) {
@@ -167,7 +167,7 @@
         decoder = TextResourceDecoder::create("text/html", "UTF-8");
     else if (mimeType == "text/plain")
         decoder = TextResourceDecoder::create("text/plain", "ISO-8859-1");
-    return decoder;
+    return decoder.release();
 }
 
 void NetworkResourcesData::responseReceived(const String& requestId, const String& frameId, const ResourceResponse& response)
diff --git a/Source/core/inspector/NetworkResourcesData.h b/Source/core/inspector/NetworkResourcesData.h
index f7c85e5..4504f33 100644
--- a/Source/core/inspector/NetworkResourcesData.h
+++ b/Source/core/inspector/NetworkResourcesData.h
@@ -32,7 +32,7 @@
 #include "core/fetch/TextResourceDecoder.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "platform/network/HTTPHeaderMap.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Deque.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefCounted.h"
@@ -107,8 +107,8 @@
         String textEncodingName() const { return m_textEncodingName; }
         void setTextEncodingName(const String& textEncodingName) { m_textEncodingName = textEncodingName; }
 
-        PassRefPtr<TextResourceDecoder> decoder() const { return m_decoder; }
-        void setDecoder(PassRefPtr<TextResourceDecoder> decoder) { m_decoder = decoder; }
+        TextResourceDecoder* decoder() const { return m_decoder.get(); }
+        void setDecoder(PassOwnPtr<TextResourceDecoder> decoder) { m_decoder = decoder; }
 
         PassRefPtr<SharedBuffer> buffer() const { return m_buffer; }
         void setBuffer(PassRefPtr<SharedBuffer> buffer) { m_buffer = buffer; }
@@ -138,7 +138,7 @@
         int m_httpStatusCode;
 
         String m_textEncodingName;
-        RefPtr<TextResourceDecoder> m_decoder;
+        OwnPtr<TextResourceDecoder> m_decoder;
 
         RefPtr<SharedBuffer> m_buffer;
         Resource* m_cachedResource;
diff --git a/Source/core/inspector/PageRuntimeAgent.cpp b/Source/core/inspector/PageRuntimeAgent.cpp
index dd62995..78d2bbc 100644
--- a/Source/core/inspector/PageRuntimeAgent.cpp
+++ b/Source/core/inspector/PageRuntimeAgent.cpp
@@ -41,7 +41,7 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 using WebCore::TypeBuilder::Runtime::ExecutionContextDescription;
 
diff --git a/Source/core/inspector/TimelineRecordFactory.cpp b/Source/core/inspector/TimelineRecordFactory.cpp
index a60515b..4651142 100644
--- a/Source/core/inspector/TimelineRecordFactory.cpp
+++ b/Source/core/inspector/TimelineRecordFactory.cpp
@@ -57,11 +57,13 @@
     return record.release();
 }
 
-PassRefPtr<JSONObject> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName)
+PassRefPtr<JSONObject> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName, const String& type, PassRefPtr<JSONObject> data)
 {
     RefPtr<JSONObject> record = JSONObject::create();
     record->setNumber("startTime", startTime);
     record->setString("thread", threadName);
+    record->setString("type", type);
+    record->setObject("data", data ? data : JSONObject::create());
     return record.release();
 }
 
@@ -220,6 +222,13 @@
     return data.release();
 }
 
+PassRefPtr<JSONObject> TimelineRecordFactory::createGPUTaskData(bool foreign)
+{
+    RefPtr<JSONObject> data = JSONObject::create();
+    data->setBoolean("foreign", foreign);
+    return data.release();
+}
+
 static PassRefPtr<JSONArray> createQuad(const FloatQuad& quad)
 {
     RefPtr<JSONArray> array = JSONArray::create();
@@ -247,10 +256,11 @@
     return createNodeData(rootNodeId);
 }
 
-PassRefPtr<JSONObject> TimelineRecordFactory::createPaintData(const FloatQuad& quad, long long layerRootNodeId)
+PassRefPtr<JSONObject> TimelineRecordFactory::createPaintData(const FloatQuad& quad, long long layerRootNodeId, int graphicsLayerId)
 {
     RefPtr<JSONObject> data = TimelineRecordFactory::createLayerData(layerRootNodeId);
     data->setArray("clip", createQuad(quad));
+    data->setNumber("layerId", graphicsLayerId);
     return data.release();
 }
 
diff --git a/Source/core/inspector/TimelineRecordFactory.h b/Source/core/inspector/TimelineRecordFactory.h
index ce1cedf..9cb6dfa 100644
--- a/Source/core/inspector/TimelineRecordFactory.h
+++ b/Source/core/inspector/TimelineRecordFactory.h
@@ -32,7 +32,7 @@
 #define TimelineRecordFactory_h
 
 #include "platform/JSONValues.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 #include "wtf/text/WTFString.h"
 
@@ -48,7 +48,7 @@
     class TimelineRecordFactory {
     public:
         static PassRefPtr<JSONObject> createGenericRecord(double startTime, int maxCallStackDepth, const String& type);
-        static PassRefPtr<JSONObject> createBackgroundRecord(double startTime, const String& thread);
+        static PassRefPtr<JSONObject> createBackgroundRecord(double startTime, const String& thread, const String& type, PassRefPtr<JSONObject> data = 0);
 
         static PassRefPtr<JSONObject> createGCEventData(const size_t usedHeapSizeDelta);
 
@@ -94,10 +94,12 @@
 
         static PassRefPtr<JSONObject> createLayerData(long long layerRootNodeId);
 
-        static PassRefPtr<JSONObject> createPaintData(const FloatQuad&, long long layerRootNodeId);
+        static PassRefPtr<JSONObject> createPaintData(const FloatQuad&, long long layerRootNodeId, int graphicsLayerId);
 
         static PassRefPtr<JSONObject> createFrameData(int frameId);
 
+        static PassRefPtr<JSONObject> createGPUTaskData(bool foreign);
+
         static void appendLayoutRoot(JSONObject* data, const FloatQuad&, long long rootNodeId);
 
         static void appendStyleRecalcDetails(JSONObject* data, unsigned elementCount);
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.cpp b/Source/core/inspector/TimelineTraceEventProcessor.cpp
index 4554d1e..ea0aae2 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.cpp
+++ b/Source/core/inspector/TimelineTraceEventProcessor.cpp
@@ -169,13 +169,13 @@
     registerHandler(InstrumentationEvents::PaintSetup, TRACE_EVENT_PHASE_END, &TimelineTraceEventProcessor::onPaintSetupEnd);
     registerHandler(InstrumentationEvents::RasterTask, TRACE_EVENT_PHASE_BEGIN, &TimelineTraceEventProcessor::onRasterTaskBegin);
     registerHandler(InstrumentationEvents::RasterTask, TRACE_EVENT_PHASE_END, &TimelineTraceEventProcessor::onRasterTaskEnd);
-    registerHandler(InstrumentationEvents::ImageDecodeTask, TRACE_EVENT_PHASE_BEGIN, &TimelineTraceEventProcessor::onImageDecodeTaskBegin);
-    registerHandler(InstrumentationEvents::ImageDecodeTask, TRACE_EVENT_PHASE_END, &TimelineTraceEventProcessor::onImageDecodeTaskEnd);
     registerHandler(InstrumentationEvents::Layer, TRACE_EVENT_PHASE_DELETE_OBJECT, &TimelineTraceEventProcessor::onLayerDeleted);
     registerHandler(InstrumentationEvents::Paint, TRACE_EVENT_PHASE_INSTANT, &TimelineTraceEventProcessor::onPaint);
     registerHandler(PlatformInstrumentation::ImageDecodeEvent, TRACE_EVENT_PHASE_BEGIN, &TimelineTraceEventProcessor::onImageDecodeBegin);
     registerHandler(PlatformInstrumentation::ImageDecodeEvent, TRACE_EVENT_PHASE_END, &TimelineTraceEventProcessor::onImageDecodeEnd);
     registerHandler(PlatformInstrumentation::DrawLazyPixelRefEvent, TRACE_EVENT_PHASE_INSTANT, &TimelineTraceEventProcessor::onDrawLazyPixelRef);
+    registerHandler(PlatformInstrumentation::DecodeLazyPixelRefEvent, TRACE_EVENT_PHASE_BEGIN, &TimelineTraceEventProcessor::onDecodeLazyPixelRefBegin);
+    registerHandler(PlatformInstrumentation::DecodeLazyPixelRefEvent, TRACE_EVENT_PHASE_END, &TimelineTraceEventProcessor::onDecodeLazyPixelRefEnd);
     registerHandler(PlatformInstrumentation::LazyPixelRef, TRACE_EVENT_PHASE_DELETE_OBJECT, &TimelineTraceEventProcessor::onLazyPixelRefDeleted);
 
     TraceEventDispatcher::instance()->addProcessor(this, m_inspectorClient);
@@ -308,7 +308,6 @@
     leaveLayerTask(state);
 }
 
-
 bool TimelineTraceEventProcessor::maybeEnterLayerTask(const TraceEvent& event, TimelineThreadState& threadState)
 {
     unsigned long long layerId = event.asUInt(InstrumentationEventArguments::LayerId);
@@ -324,33 +323,21 @@
     threadState.inKnownLayerTask = false;
 }
 
-void TimelineTraceEventProcessor::onImageDecodeTaskBegin(const TraceEvent& event)
-{
-    TimelineThreadState& state = threadState(event.threadIdentifier());
-    ASSERT(!state.decodedPixelRefId);
-    unsigned long long pixelRefId = event.asUInt(InstrumentationEventArguments::PixelRefId);
-    ASSERT(pixelRefId);
-    if (m_pixelRefToImageInfo.contains(pixelRefId))
-        state.decodedPixelRefId = pixelRefId;
-}
-
-void TimelineTraceEventProcessor::onImageDecodeTaskEnd(const TraceEvent& event)
-{
-    threadState(event.threadIdentifier()).decodedPixelRefId = 0;
-}
-
 void TimelineTraceEventProcessor::onImageDecodeBegin(const TraceEvent& event)
 {
     TimelineThreadState& state = threadState(event.threadIdentifier());
-    if (!state.decodedPixelRefId)
+    if (!state.decodedPixelRefId && !state.inKnownLayerTask)
         return;
-    PixelRefToImageInfoMap::const_iterator it = m_pixelRefToImageInfo.find(state.decodedPixelRefId);
-    if (it == m_pixelRefToImageInfo.end()) {
-        ASSERT_NOT_REACHED();
-        return;
+    ImageInfo imageInfo;
+    if (state.decodedPixelRefId) {
+        PixelRefToImageInfoMap::const_iterator it = m_pixelRefToImageInfo.find(state.decodedPixelRefId);
+        if (it != m_pixelRefToImageInfo.end())
+            imageInfo = it->value;
+        else
+            ASSERT_NOT_REACHED();
     }
     RefPtr<JSONObject> data = JSONObject::create();
-    TimelineRecordFactory::appendImageDetails(data.get(), it->value.backendNodeId, it->value.url);
+    TimelineRecordFactory::appendImageDetails(data.get(), imageInfo.backendNodeId, imageInfo.url);
     state.recordStack.addScopedRecord(createRecord(event, TimelineRecordType::DecodeImage, data));
 }
 
@@ -392,6 +379,21 @@
     }
 }
 
+void TimelineTraceEventProcessor::onDecodeLazyPixelRefBegin(const TraceEvent& event)
+{
+    TimelineThreadState& state = threadState(event.threadIdentifier());
+    ASSERT(!state.decodedPixelRefId);
+    unsigned long long pixelRefId = event.asUInt(PlatformInstrumentation::LazyPixelRef);
+    ASSERT(pixelRefId);
+    if (m_pixelRefToImageInfo.contains(pixelRefId))
+        state.decodedPixelRefId = pixelRefId;
+}
+
+void TimelineTraceEventProcessor::onDecodeLazyPixelRefEnd(const TraceEvent& event)
+{
+    threadState(event.threadIdentifier()).decodedPixelRefId = 0;
+}
+
 void TimelineTraceEventProcessor::onDrawLazyPixelRef(const TraceEvent& event)
 {
     // Only track LazyPixelRefs created while we paint known layers
@@ -420,9 +422,7 @@
 PassRefPtr<JSONObject> TimelineTraceEventProcessor::createRecord(const TraceEvent& event, const String& recordType, PassRefPtr<JSONObject> data)
 {
     double startTime = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
-    RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(startTime, String::number(event.threadIdentifier()));
-    record->setString("type", recordType);
-    record->setObject("data", data ? data : JSONObject::create());
+    RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(startTime, String::number(event.threadIdentifier()), recordType, data);
     return record.release();
 }
 
@@ -441,7 +441,8 @@
     for (size_t i = 0, size = events.size(); i < size; ++i) {
         const TraceEvent& event = events[i];
         HandlersMap::iterator it = m_handlersByType.find(std::make_pair(event.name(), event.phase()));
-        ASSERT(it != m_handlersByType.end() && it->value);
+        ASSERT_WITH_SECURITY_IMPLICATION(it != m_handlersByType.end());
+        ASSERT(it->value);
         (this->*(it->value))(event);
     }
 }
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.h b/Source/core/inspector/TimelineTraceEventProcessor.h
index 8b4d99d..24f9f16 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.h
+++ b/Source/core/inspector/TimelineTraceEventProcessor.h
@@ -212,12 +212,12 @@
     void onRasterTaskBegin(const TraceEvent&);
     void onRasterTaskEnd(const TraceEvent&);
     void onPaint(const TraceEvent&);
-    void onImageDecodeTaskBegin(const TraceEvent&);
-    void onImageDecodeTaskEnd(const TraceEvent&);
     void onImageDecodeBegin(const TraceEvent&);
     void onImageDecodeEnd(const TraceEvent&);
     void onLayerDeleted(const TraceEvent&);
     void onDrawLazyPixelRef(const TraceEvent&);
+    void onDecodeLazyPixelRefBegin(const TraceEvent&);
+    void onDecodeLazyPixelRefEnd(const TraceEvent&);
     void onLazyPixelRefDeleted(const TraceEvent&);
 
     WeakPtr<InspectorTimelineAgent> m_timelineAgent;
@@ -240,12 +240,13 @@
     unsigned long long m_layerId;
     double m_paintSetupStart;
     double m_paintSetupEnd;
+    RefPtr<JSONObject> m_gpuTask;
 
     struct ImageInfo {
         int backendNodeId;
         String url;
 
-        ImageInfo() { }
+        ImageInfo() : backendNodeId(0) { }
         ImageInfo(int backendNodeId, String url) : backendNodeId(backendNodeId), url(url) { }
     };
     typedef HashMap<unsigned long long, ImageInfo> PixelRefToImageInfoMap;
diff --git a/Source/core/inspector/WorkerInspectorController.cpp b/Source/core/inspector/WorkerInspectorController.cpp
index 6761fd7..a33fb16 100644
--- a/Source/core/inspector/WorkerInspectorController.cpp
+++ b/Source/core/inspector/WorkerInspectorController.cpp
@@ -97,11 +97,11 @@
 {
     m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope));
 
-    OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0);
+    OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0);
     OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), timelineAgent.get(), m_state.get(), m_injectedScriptManager.get());
     m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get()));
 
-    m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent.get(), m_state.get(), m_injectedScriptManager.get()));
+    m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent.get(), m_state.get(), m_injectedScriptManager.get(), 0));
     m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
     m_agents.append(timelineAgent.release());
     m_agents.append(consoleAgent.release());
diff --git a/Source/core/loader/CookieJar.cpp b/Source/core/loader/CookieJar.cpp
index df33648..4ba0ca1 100644
--- a/Source/core/loader/CookieJar.cpp
+++ b/Source/core/loader/CookieJar.cpp
@@ -34,7 +34,7 @@
 #include "core/dom/Document.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/frame/Frame.h"
-#include "core/platform/Cookie.h"
+#include "platform/Cookie.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebCookie.h"
 #include "public/platform/WebCookieJar.h"
@@ -43,21 +43,21 @@
 
 namespace WebCore {
 
-static WebKit::WebCookieJar* toCookieJar(const Document* document)
+static blink::WebCookieJar* toCookieJar(const Document* document)
 {
     if (!document || !document->frame())
         return 0;
-    WebKit::WebCookieJar* cookieJar = document->frame()->loader().client()->cookieJar();
+    blink::WebCookieJar* cookieJar = document->frame()->loader().client()->cookieJar();
     // FIXME: DRT depends on being able to get a cookie jar from Platform rather than
     // FrameLoaderClient. Delete this when DRT is deleted.
     if (!cookieJar)
-        cookieJar = WebKit::Platform::current()->cookieJar();
+        cookieJar = blink::Platform::current()->cookieJar();
     return cookieJar;
 }
 
 String cookies(const Document* document, const KURL& url)
 {
-    WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+    blink::WebCookieJar* cookieJar = toCookieJar(document);
     if (!cookieJar)
         return String();
     return cookieJar->cookies(url, document->firstPartyForCookies());
@@ -65,7 +65,7 @@
 
 void setCookies(Document* document, const KURL& url, const String& cookieString)
 {
-    WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+    blink::WebCookieJar* cookieJar = toCookieJar(document);
     if (!cookieJar)
         return;
     cookieJar->setCookie(url, document->firstPartyForCookies(), cookieString);
@@ -73,7 +73,7 @@
 
 bool cookiesEnabled(const Document* document)
 {
-    WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+    blink::WebCookieJar* cookieJar = toCookieJar(document);
     if (!cookieJar)
         return false;
     return cookieJar->cookiesEnabled(document->cookieURL(), document->firstPartyForCookies());
@@ -81,7 +81,7 @@
 
 String cookieRequestHeaderFieldValue(const Document* document, const KURL& url)
 {
-    WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+    blink::WebCookieJar* cookieJar = toCookieJar(document);
     if (!cookieJar)
         return String();
     return cookieJar->cookieRequestHeaderFieldValue(url, document->firstPartyForCookies());
@@ -90,13 +90,13 @@
 bool getRawCookies(const Document* document, const KURL& url, Vector<Cookie>& cookies)
 {
     cookies.clear();
-    WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+    blink::WebCookieJar* cookieJar = toCookieJar(document);
     if (!cookieJar)
         return false;
-    WebKit::WebVector<WebKit::WebCookie> webCookies;
+    blink::WebVector<blink::WebCookie> webCookies;
     cookieJar->rawCookies(url, document->firstPartyForCookies(), webCookies);
     for (unsigned i = 0; i < webCookies.size(); ++i) {
-        const WebKit::WebCookie& webCookie = webCookies[i];
+        const blink::WebCookie& webCookie = webCookies[i];
         cookies.append(Cookie(webCookie.name, webCookie.value, webCookie.domain, webCookie.path,
                               webCookie.expires, webCookie.httpOnly, webCookie.secure, webCookie.session));
     }
@@ -105,7 +105,7 @@
 
 void deleteCookie(const Document* document, const KURL& url, const String& cookieName)
 {
-    WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+    blink::WebCookieJar* cookieJar = toCookieJar(document);
     if (!cookieJar)
         return;
     cookieJar->deleteCookie(url, cookieName);
diff --git a/Source/core/loader/CrossOriginPreflightResultCache.h b/Source/core/loader/CrossOriginPreflightResultCache.h
index 3911a2c..1c65c96 100644
--- a/Source/core/loader/CrossOriginPreflightResultCache.h
+++ b/Source/core/loader/CrossOriginPreflightResultCache.h
@@ -28,7 +28,7 @@
 #define CrossOriginPreflightResultCache_h
 
 #include "core/fetch/ResourceLoaderOptions.h"
-#include "weborigin/KURLHash.h"
+#include "platform/weborigin/KURLHash.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
diff --git a/Source/core/loader/DocumentLoadTiming.cpp b/Source/core/loader/DocumentLoadTiming.cpp
index a9115f0..95c48d9 100644
--- a/Source/core/loader/DocumentLoadTiming.cpp
+++ b/Source/core/loader/DocumentLoadTiming.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/loader/DocumentLoadTiming.h"
 
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index 027bb01..ddefb8e 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -46,21 +46,21 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/loader/archive/ArchiveResourceCollection.h"
-#include "core/loader/archive/MHTMLArchive.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/plugins/PluginData.h"
 #include "platform/Logging.h"
 #include "platform/UserGestureIndicator.h"
+#include "platform/mhtml/ArchiveResourceCollection.h"
+#include "platform/mhtml/MHTMLArchive.h"
+#include "platform/plugins/PluginData.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityPolicy.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebMimeRegistry.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityPolicy.h"
 #include "wtf/Assertions.h"
 #include "wtf/text/WTFString.h"
 
@@ -156,10 +156,15 @@
     return request().url();
 }
 
-void DocumentLoader::replaceRequestURLForSameDocumentNavigation(const KURL& url)
+void DocumentLoader::updateForSameDocumentNavigation(const KURL& newURL)
 {
-    m_originalRequestCopy.setURL(url);
-    m_request.setURL(url);
+    KURL oldURL = m_request.url();
+    m_originalRequestCopy.setURL(newURL);
+    m_request.setURL(newURL);
+    clearRedirectChain();
+    if (m_isClientRedirect)
+        appendRedirect(oldURL);
+    appendRedirect(newURL);
 }
 
 bool DocumentLoader::isURLValidForNewHistoryEntry() const
@@ -377,8 +382,7 @@
     if (m_frame->ownerElement() && !m_frame->ownerElement()->document().contentSecurityPolicy()->allowChildFrameFromSource(request.url()))
         return false;
 
-    NavigationPolicy policy = NavigationPolicyCurrentTab;
-    m_triggeringAction.specifiesNavigationPolicy(&policy);
+    NavigationPolicy policy = m_triggeringAction.policy();
     if (policyCheckLoadType != PolicyCheckFragment)
         policy = frameLoader()->client()->decidePolicyForNavigation(request, this, policy);
     if (policy == NavigationPolicyCurrentTab)
@@ -459,7 +463,7 @@
 
 static bool canShowMIMEType(const String& mimeType, Page* page)
 {
-    if (WebKit::Platform::current()->mimeRegistry()->supportsMIMEType(mimeType) == WebKit::WebMimeRegistry::IsSupported)
+    if (blink::Platform::current()->mimeRegistry()->supportsMIMEType(mimeType) == blink::WebMimeRegistry::IsSupported)
         return true;
     PluginData* pluginData = page->pluginData();
     return !mimeType.isEmpty() && pluginData && pluginData->supportsMimeType(mimeType);
@@ -838,7 +842,7 @@
 
     ResourceRequest request(m_request);
     DEFINE_STATIC_LOCAL(ResourceLoaderOptions, mainResourceLoadOptions,
-        (SendCallbacks, SniffContent, DoNotBufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType, DocumentContext));
+        (SendCallbacks, SniffContent, DoNotBufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
     FetchRequest cachedResourceRequest(request, FetchInitiatorTypeNames::document, mainResourceLoadOptions);
     m_mainResource = m_fetcher->fetchMainResource(cachedResourceRequest);
     if (!m_mainResource) {
@@ -932,6 +936,12 @@
     return m_response.mimeType();
 }
 
+void DocumentLoader::setUserChosenEncoding(const String& charset)
+{
+    if (m_writer)
+        m_writer->setUserChosenEncoding(charset);
+}
+
 // This is only called by ScriptController::executeScriptIfJavaScriptURL
 // and always contains the result of evaluating a javascript: url.
 // This is the <iframe src="javascript:'html'"> case.
diff --git a/Source/core/loader/DocumentLoader.h b/Source/core/loader/DocumentLoader.h
index 4ba5aa8..f63d1b5 100644
--- a/Source/core/loader/DocumentLoader.h
+++ b/Source/core/loader/DocumentLoader.h
@@ -86,6 +86,8 @@
 
         String mimeType() const;
 
+        void setUserChosenEncoding(const String& charset);
+
         const ResourceRequest& originalRequest() const;
         const ResourceRequest& originalRequestCopy() const;
 
@@ -105,7 +107,7 @@
         const KURL& requestURL() const;
         const String& responseMIMEType() const;
 
-        void replaceRequestURLForSameDocumentNavigation(const KURL&);
+        void updateForSameDocumentNavigation(const KURL&);
         void stopLoading();
         void setCommitted(bool committed) { m_committed = committed; }
         bool isCommitted() const { return m_committed; }
diff --git a/Source/core/loader/DocumentThreadableLoader.cpp b/Source/core/loader/DocumentThreadableLoader.cpp
index 97bf370..dd99f26 100644
--- a/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/Source/core/loader/DocumentThreadableLoader.cpp
@@ -48,8 +48,8 @@
 #include "platform/SharedBuffer.h"
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Assertions.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/DocumentWriter.cpp b/Source/core/loader/DocumentWriter.cpp
index 1134cc8..9767ca8 100644
--- a/Source/core/loader/DocumentWriter.cpp
+++ b/Source/core/loader/DocumentWriter.cpp
@@ -38,8 +38,8 @@
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Settings.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
@@ -51,7 +51,6 @@
 
 DocumentWriter::DocumentWriter(Document* document, const String& mimeType, const String& encoding, bool encodingUserChoosen)
     : m_document(document)
-    , m_hasReceivedSomeData(false)
     , m_decoderBuilder(mimeType, encoding, encodingUserChoosen)
     // We grab a reference to the parser so that we'll always send data to the
     // original parser, even if the document acquires a new parser (e.g., via
@@ -70,8 +69,6 @@
 
 void DocumentWriter::appendReplacingData(const String& source)
 {
-    ASSERT(!m_hasReceivedSomeData);
-    m_hasReceivedSomeData = true;
     m_document->setCompatibilityMode(Document::NoQuirksMode);
 
     // FIXME: This should call DocumentParser::appendBytes instead of append
@@ -81,29 +78,20 @@
         // Because we're pinned to the main thread we don't need to worry about
         // passing ownership of the source string.
         parser->append(source.impl());
+        parser->setHasAppendedData();
     }
 }
 
-void DocumentWriter::reportDataReceived()
-{
-    ASSERT(m_decoder);
-    if (m_hasReceivedSomeData)
-        return;
-    m_hasReceivedSomeData = true;
-    if (m_decoder->encoding().usesVisualOrdering())
-        m_document->setVisuallyOrdered();
-}
-
 void DocumentWriter::addData(const char* bytes, size_t length)
 {
     ASSERT(m_parser);
-    if (!m_decoder && m_parser->needsDecoder() && 0 < length)
-        m_decoder = m_decoderBuilder.buildFor(m_document);
+    if (m_parser->needsDecoder() && 0 < length) {
+        OwnPtr<TextResourceDecoder> decoder = m_decoderBuilder.buildFor(m_document);
+        m_parser->setDecoder(decoder.release());
+    }
     // appendBytes() can result replacing DocumentLoader::m_writer.
     RefPtr<DocumentWriter> protectingThis(this);
-    size_t consumedChars = m_parser->appendBytes(bytes, length);
-    if (consumedChars)
-        reportDataReceived();
+    m_parser->appendBytes(bytes, length);
 }
 
 void DocumentWriter::end()
@@ -118,13 +106,14 @@
     if (!m_parser)
         return;
 
-    if (!m_decoder && m_parser->needsDecoder())
-        m_decoder = m_decoderBuilder.buildFor(m_document);
+    if (m_parser->needsDecoder()) {
+        OwnPtr<TextResourceDecoder> decoder = m_decoderBuilder.buildFor(m_document);
+        m_parser->setDecoder(decoder.release());
+    }
     // flush() can result replacing DocumentLoader::m_writer.
     RefPtr<DocumentWriter> protectingThis(this);
-    size_t consumedChars = m_parser->flush();
-    if (consumedChars)
-        reportDataReceived();
+    m_parser->flush();
+
     if (!m_parser)
         return;
 
@@ -133,6 +122,13 @@
     m_document = 0;
 }
 
+void DocumentWriter::setUserChosenEncoding(const String& charset)
+{
+    TextResourceDecoder* decoder = m_parser->decoder();
+    if (decoder)
+        decoder->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
+}
+
 void DocumentWriter::setDocumentWasLoadedAsPartOfNavigation()
 {
     ASSERT(m_parser && !m_parser->isStopped());
diff --git a/Source/core/loader/DocumentWriter.h b/Source/core/loader/DocumentWriter.h
index f3da31f..0f7eb5b 100644
--- a/Source/core/loader/DocumentWriter.h
+++ b/Source/core/loader/DocumentWriter.h
@@ -61,11 +61,11 @@
     const String& encoding() const { return m_decoderBuilder.encoding(); }
     bool encodingWasChosenByUser() const { return m_decoderBuilder.encodingWasChosenByUser(); }
 
-    // Exposed for DocumentParser::appendBytes.
-    void reportDataReceived();
     // Exposed for DocumentLoader::replaceDocument.
     void appendReplacingData(const String&);
 
+    void setUserChosenEncoding(const String& charset);
+
     void setDocumentWasLoadedAsPartOfNavigation();
 
 private:
@@ -74,10 +74,8 @@
     PassRefPtr<Document> createDocument(const KURL&);
 
     Document* m_document;
-    bool m_hasReceivedSomeData;
     TextResourceDecoderBuilder m_decoderBuilder;
 
-    RefPtr<TextResourceDecoder> m_decoder;
     RefPtr<DocumentParser> m_parser;
 };
 
diff --git a/Source/core/loader/EmptyClients.cpp b/Source/core/loader/EmptyClients.cpp
index 53c7ae2..ea196a4 100644
--- a/Source/core/loader/EmptyClients.cpp
+++ b/Source/core/loader/EmptyClients.cpp
@@ -59,6 +59,9 @@
 
     static BackForwardClient* dummyBackForwardClient = adoptPtr(new EmptyBackForwardClient).leakPtr();
     pageClients.backForwardClient = dummyBackForwardClient;
+
+    static SpellCheckerClient* dummySpellCheckerClient = adoptPtr(new EmptySpellCheckerClient).leakPtr();
+    pageClients.spellCheckerClient = dummySpellCheckerClient;
 }
 
 class EmptyPopupMenu : public PopupMenu {
@@ -130,19 +133,11 @@
 {
 }
 
-void EmptyEditorClient::registerUndoStep(PassRefPtr<UndoStep>)
-{
-}
-
-void EmptyEditorClient::registerRedoStep(PassRefPtr<UndoStep>)
-{
-}
-
 void EmptyFrameLoaderClient::didRequestAutocomplete(PassRefPtr<FormState>)
 {
 }
 
-PassOwnPtr<WebKit::WebServiceWorkerProvider> EmptyFrameLoaderClient::createServiceWorkerProvider(PassOwnPtr<WebKit::WebServiceWorkerProviderClient>)
+PassOwnPtr<blink::WebServiceWorkerProvider> EmptyFrameLoaderClient::createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>)
 {
     return nullptr;
 }
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index b8845a7..f56e1ab 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -29,6 +29,7 @@
 #ifndef EmptyClients_h
 #define EmptyClients_h
 
+#include "core/editing/UndoStep.h"
 #include "core/inspector/InspectorClient.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/BackForwardClient.h"
@@ -38,6 +39,7 @@
 #include "core/page/EditorClient.h"
 #include "core/page/FocusDirection.h"
 #include "core/page/Page.h"
+#include "core/page/SpellCheckerClient.h"
 #include "core/platform/DragImage.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/network/ResourceError.h"
@@ -83,7 +85,7 @@
     virtual void takeFocus(FocusDirection) OVERRIDE { }
 
     virtual void focusedNodeChanged(Node*) OVERRIDE { }
-    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy) OVERRIDE { return 0; }
+    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy, ShouldSendReferrer) OVERRIDE { return 0; }
     virtual void show(NavigationPolicy) OVERRIDE { }
 
     virtual bool canRunModal() OVERRIDE { return false; }
@@ -135,7 +137,7 @@
 
     virtual IntPoint screenToRootView(const IntPoint& p) const OVERRIDE { return p; }
     virtual IntRect rootViewToScreen(const IntRect& r) const OVERRIDE { return r; }
-    virtual WebKit::WebScreenInfo screenInfo() const OVERRIDE { return WebKit::WebScreenInfo(); }
+    virtual blink::WebScreenInfo screenInfo() const OVERRIDE { return blink::WebScreenInfo(); }
     virtual void contentsSizeChanged(Frame*, const IntSize&) const OVERRIDE { }
 
     virtual void mouseDidMoveOverElement(const HitTestResult&, unsigned) OVERRIDE { }
@@ -224,7 +226,7 @@
 
     virtual String doNotTrackValue() OVERRIDE { return String(); }
 
-    virtual void transitionToCommittedForNewPage() OVERRIDE { }
+    virtual void transitionToCommittedForNewPage(Frame*) OVERRIDE { }
 
     virtual bool navigateBackForward(int offset) const OVERRIDE { return false; }
     virtual void didDisplayInsecureContent() OVERRIDE { }
@@ -245,10 +247,10 @@
     virtual void willReleaseScriptContext(v8::Handle<v8::Context>, int worldId) OVERRIDE { }
     virtual bool allowScriptExtension(const String& extensionName, int extensionGroup, int worldId) OVERRIDE { return false; }
 
-    virtual WebKit::WebCookieJar* cookieJar() const { return 0; }
+    virtual blink::WebCookieJar* cookieJar() const { return 0; }
 
     virtual void didRequestAutocomplete(PassRefPtr<FormState>) OVERRIDE;
-    virtual PassOwnPtr<WebKit::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<WebKit::WebServiceWorkerProviderClient>) OVERRIDE;
+    virtual PassOwnPtr<blink::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>) OVERRIDE;
 };
 
 class EmptyTextCheckerClient : public TextCheckerClient {
@@ -260,52 +262,42 @@
     virtual void requestCheckingOfString(PassRefPtr<TextCheckingRequest>) OVERRIDE;
 };
 
-class EmptyEditorClient : public EditorClient {
-    WTF_MAKE_NONCOPYABLE(EmptyEditorClient); WTF_MAKE_FAST_ALLOCATED;
+class EmptySpellCheckerClient : public SpellCheckerClient {
+    WTF_MAKE_NONCOPYABLE(EmptySpellCheckerClient); WTF_MAKE_FAST_ALLOCATED;
 public:
-    EmptyEditorClient() { }
-    virtual ~EmptyEditorClient() { }
+    EmptySpellCheckerClient() { }
+    virtual ~EmptySpellCheckerClient() { }
 
-    virtual bool smartInsertDeleteEnabled() OVERRIDE { return false; }
-    virtual bool isSelectTrailingWhitespaceEnabled() OVERRIDE { return false; }
     virtual bool isContinuousSpellCheckingEnabled() OVERRIDE { return false; }
     virtual void toggleContinuousSpellChecking() OVERRIDE { }
     virtual bool isGrammarCheckingEnabled() OVERRIDE { return false; }
 
-    virtual void respondToChangedContents() OVERRIDE { }
-    virtual void respondToChangedSelection(Frame*) OVERRIDE { }
-    virtual void didCancelCompositionOnSelectionChange() OVERRIDE { }
-
-    virtual void registerUndoStep(PassRefPtr<UndoStep>) OVERRIDE;
-    virtual void registerRedoStep(PassRefPtr<UndoStep>) OVERRIDE;
-    virtual void clearUndoRedoOperations() OVERRIDE { }
-
-    virtual bool canCopyCut(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
-    virtual bool canPaste(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
-    virtual bool canUndo() const OVERRIDE { return false; }
-    virtual bool canRedo() const OVERRIDE { return false; }
-
-    virtual void undo() OVERRIDE { }
-    virtual void redo() OVERRIDE { }
-
-    virtual void handleKeyboardEvent(KeyboardEvent*) OVERRIDE { }
-
-    virtual void textFieldDidEndEditing(Element*) OVERRIDE { }
-    virtual void textDidChangeInTextField(Element*) OVERRIDE { }
-    virtual bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*) OVERRIDE { return false; }
-
     TextCheckerClient& textChecker() { return m_textCheckerClient; }
 
     virtual void updateSpellingUIWithMisspelledWord(const String&) OVERRIDE { }
     virtual void showSpellingUI(bool) OVERRIDE { }
     virtual bool spellingUIIsShowing() OVERRIDE { return false; }
 
-    virtual void willSetInputMethodState() OVERRIDE { }
-
 private:
     EmptyTextCheckerClient m_textCheckerClient;
 };
 
+class EmptyEditorClient : public EditorClient {
+    WTF_MAKE_NONCOPYABLE(EmptyEditorClient); WTF_MAKE_FAST_ALLOCATED;
+public:
+    EmptyEditorClient() { }
+    virtual ~EmptyEditorClient() { }
+
+    virtual void respondToChangedContents() OVERRIDE { }
+    virtual void respondToChangedSelection(SelectionType) OVERRIDE { }
+
+    virtual bool canCopyCut(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
+    virtual bool canPaste(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
+
+    virtual void didExecuteCommand(String) OVERRIDE { }
+    virtual bool handleKeyboardEvent() OVERRIDE { return false; }
+};
+
 class EmptyContextMenuClient : public ContextMenuClient {
     WTF_MAKE_NONCOPYABLE(EmptyContextMenuClient); WTF_MAKE_FAST_ALLOCATED;
 public:
diff --git a/Source/core/loader/FormSubmission.h b/Source/core/loader/FormSubmission.h
index 6a537c1..d53b2e6 100644
--- a/Source/core/loader/FormSubmission.h
+++ b/Source/core/loader/FormSubmission.h
@@ -32,7 +32,7 @@
 #define FormSubmission_h
 
 #include "core/loader/FormState.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 
 namespace WTF{
 class TextEncoding;
diff --git a/Source/core/loader/FrameFetchContext.cpp b/Source/core/loader/FrameFetchContext.cpp
index 885d1e8..1454df9 100644
--- a/Source/core/loader/FrameFetchContext.cpp
+++ b/Source/core/loader/FrameFetchContext.cpp
@@ -39,7 +39,7 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/weborigin/SecurityPolicy.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/FrameLoadRequest.h b/Source/core/loader/FrameLoadRequest.h
index 6b12069..fefdd1f 100644
--- a/Source/core/loader/FrameLoadRequest.h
+++ b/Source/core/loader/FrameLoadRequest.h
@@ -31,7 +31,7 @@
 #include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/SubstituteData.h"
 #include "platform/network/ResourceRequest.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 class Frame;
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index 583b9ab..509ce2c 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -66,17 +66,19 @@
 #include "core/loader/FrameFetchContext.h"
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/IconController.h"
 #include "core/loader/ProgressTracker.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
+#include "core/page/BackForwardClient.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
+#include "core/page/CreateWindow.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/page/WindowFeatures.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/ScrollAnimator.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "modules/webdatabase/DatabaseManager.h"
@@ -85,8 +87,8 @@
 #include "platform/geometry/FloatRect.h"
 #include "platform/network/HTTPParsers.h"
 #include "platform/network/ResourceRequest.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
 #include "wtf/TemporaryChange.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/WTFString.h"
@@ -142,8 +144,6 @@
 FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
     : m_frame(frame)
     , m_client(client)
-    , m_history(frame)
-    , m_icon(adoptPtr(new IconController(frame)))
     , m_mixedContentChecker(frame)
     , m_state(FrameStateProvisional)
     , m_loadType(FrameLoadTypeStandard)
@@ -155,7 +155,6 @@
     , m_opener(0)
     , m_didAccessInitialDocument(false)
     , m_didAccessInitialDocumentTimer(this, &FrameLoader::didAccessInitialDocumentTimerFired)
-    , m_suppressOpenerInNewFrame(false)
     , m_forcedSandboxFlags(SandboxNone)
 {
 }
@@ -190,7 +189,6 @@
         m_provisionalDocumentLoader->setDefersLoading(defers);
     if (m_policyDocumentLoader)
         m_policyDocumentLoader->setDefersLoading(defers);
-    history()->setDefersLoading(defers);
 
     if (!defers) {
         m_frame->navigationScheduler().startTimer();
@@ -220,9 +218,35 @@
     m_frame->navigationScheduler().cancel();
 }
 
+void FrameLoader::saveDocumentAndScrollState()
+{
+    if (!m_currentItem)
+        return;
+
+    Document* document = m_frame->document();
+    if (m_currentItem->isCurrentDocument(document) && document->isActive())
+        m_currentItem->setDocumentState(document->formElementsState());
+
+    if (!m_frame->view())
+        return;
+
+    m_currentItem->setScrollPoint(m_frame->view()->scrollPosition());
+    if (m_frame->isMainFrame() && !m_frame->page()->inspectorController().deviceEmulationEnabled())
+        m_currentItem->setPageScaleFactor(m_frame->page()->pageScaleFactor());
+}
+
+void FrameLoader::clearScrollPositionAndViewState()
+{
+    ASSERT(m_frame->isMainFrame());
+    if (!m_currentItem)
+        return;
+    m_currentItem->clearScrollPoint();
+    m_currentItem->setPageScaleFactor(0);
+}
+
 bool FrameLoader::closeURL()
 {
-    history()->saveDocumentAndScrollState();
+    saveDocumentAndScrollState();
 
     // Should only send the pagehide event here if the current document exists.
     if (m_frame->document())
@@ -288,6 +312,8 @@
 
     if (m_stateMachine.isDisplayingInitialEmptyDocument())
         m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
+    else if (!m_stateMachine.committedMultipleRealLoads())
+        m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedMultipleRealLoads);
 }
 
 void FrameLoader::receivedFirstData()
@@ -313,8 +339,8 @@
     m_isComplete = false;
     m_frame->document()->setReadyState(Document::Loading);
 
-    if (history()->currentItem() && m_loadType == FrameLoadTypeBackForward)
-        m_frame->domWindow()->statePopped(history()->currentItem()->stateObject());
+    if (m_currentItem && m_loadType == FrameLoadTypeBackForward)
+        m_frame->domWindow()->statePopped(m_currentItem->stateObject());
 
     if (dispatch)
         dispatchDidClearWindowObjectsInAllWorlds();
@@ -342,7 +368,8 @@
         }
     }
 
-    history()->restoreDocumentState();
+    if (m_currentItem && m_loadType == FrameLoadTypeBackForward)
+        m_frame->document()->setStateForNewFormElements(m_currentItem->documentState());
 }
 
 void FrameLoader::finishedParsing()
@@ -513,25 +540,9 @@
 void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource, PassRefPtr<SerializedScriptValue> data, UpdateBackForwardListPolicy updateBackForwardList)
 {
     // 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);
-
-    // updateBackForwardListForFragmentScroll() must happen after
-    // replaceRequestURLForSameDocumentNavigation(), since we add based on
-    // the current request.
-    if (updateBackForwardList == UpdateBackForwardList)
-        history()->updateBackForwardListForFragmentScroll();
-
-    if (sameDocumentNavigationSource == SameDocumentNavigationDefault)
-        history()->updateForSameDocumentNavigation();
-    else if (sameDocumentNavigationSource == SameDocumentNavigationPushState)
-        history()->pushState(data, newURL.string());
-    else if (sameDocumentNavigationSource == SameDocumentNavigationReplaceState)
-        history()->replaceState(data, newURL.string());
-    else
-        ASSERT_NOT_REACHED();
+    documentLoader()->updateForSameDocumentNavigation(newURL);
 
     // 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.
@@ -539,17 +550,21 @@
     if (m_frame->document()->loadEventFinished())
         m_client->postProgressStartedNotification();
 
-    m_documentLoader->clearRedirectChain();
-    if (m_documentLoader->isClientRedirect())
-        m_documentLoader->appendRedirect(oldURL);
-    m_documentLoader->appendRedirect(newURL);
-
     NavigationHistoryPolicy navigationHistoryPolicy = NavigationReusedHistoryEntry;
     if (updateBackForwardList == UpdateBackForwardList || sameDocumentNavigationSource == SameDocumentNavigationPushState)
         navigationHistoryPolicy = NavigationCreatedHistoryEntry;
     m_client->dispatchDidNavigateWithinPage(navigationHistoryPolicy);
     m_client->dispatchDidReceiveTitle(m_frame->document()->title());
 
+    if (m_currentItem) {
+        m_currentItem->setURL(newURL);
+        if (sameDocumentNavigationSource != SameDocumentNavigationDefault) {
+            m_currentItem->setStateObject(data);
+            m_currentItem->setFormData(0);
+            m_currentItem->setFormContentType(String());
+        }
+    }
+
     if (m_frame->document()->loadEventFinished())
         m_client->postProgressFinishedNotification();
 }
@@ -605,20 +620,6 @@
         frame->loader().m_isComplete = false;
 }
 
-void FrameLoader::prepareForHistoryNavigation()
-{
-    // If there is no currentItem, but we still want to engage in
-    // history navigation we need to manufacture one, and update
-    // the state machine of this frame to impersonate having
-    // loaded it.
-    RefPtr<HistoryItem> currentItem = history()->currentItem();
-    if (!currentItem) {
-        insertDummyHistoryItem();
-        ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
-        stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
-    }
-}
-
 void FrameLoader::setReferrerForFrameRequest(ResourceRequest& request, ShouldSendReferrer shouldSendReferrer)
 {
     if (shouldSendReferrer == NeverSendReferrer) {
@@ -650,7 +651,7 @@
 {
     if (m_frame->tree().parent() && !m_stateMachine.startedFirstRealLoad())
         return FrameLoadTypeInitialInChildFrame;
-    if (!m_frame->tree().parent() && !history()->currentItem())
+    if (!m_frame->tree().parent() && !m_frame->page()->backForward().backForwardListCount())
         return FrameLoadTypeStandard;
     if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
         return FrameLoadTypeReload;
@@ -688,21 +689,8 @@
     return true;
 }
 
-static bool shouldOpenInNewWindow(Frame* targetFrame, const FrameLoadRequest& request, const NavigationAction& action)
-{
-    if (!targetFrame && !request.frameName().isEmpty())
-        return true;
-    if (!request.formState())
-        return false;
-    NavigationPolicy navigationPolicy = NavigationPolicyCurrentTab;
-    if (!action.specifiesNavigationPolicy(&navigationPolicy))
-        return false;
-    return navigationPolicy != NavigationPolicyCurrentTab;
-}
-
 void FrameLoader::load(const FrameLoadRequest& passedRequest)
 {
-    ASSERT(!m_suppressOpenerInNewFrame);
     ASSERT(m_frame->document());
 
     // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
@@ -715,7 +703,7 @@
     if (!prepareRequestForThisFrame(request))
         return;
 
-    RefPtr<Frame> targetFrame = findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
+    RefPtr<Frame> targetFrame = request.formState() ? 0 : findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
     if (targetFrame && targetFrame != m_frame) {
         request.setFrameName("_self");
         targetFrame->loader().load(request);
@@ -726,9 +714,11 @@
 
     FrameLoadType newLoadType = determineFrameLoadType(request);
     NavigationAction action(request.resourceRequest(), newLoadType, request.formState(), request.triggeringEvent());
-    if (shouldOpenInNewWindow(targetFrame.get(), request, action)) {
-        TemporaryChange<bool> changeOpener(m_suppressOpenerInNewFrame, request.shouldSendReferrer() == NeverSendReferrer);
-        checkNewWindowPolicyAndContinue(request.formState(), request.frameName(), action);
+    if ((!targetFrame && !request.frameName().isEmpty()) || action.shouldOpenInNewWindow()) {
+        if (action.policy() == NavigationPolicyDownload)
+            m_client->loadURLExternally(action.resourceRequest(), NavigationPolicyDownload);
+        else
+            createWindowForRequest(request, m_frame, action.policy(), request.shouldSendReferrer());
         return;
     }
 
@@ -737,7 +727,7 @@
         return;
     }
     bool sameURL = shouldTreatURLAsSameAsCurrent(request.resourceRequest().url());
-    loadWithNavigationAction(request.resourceRequest(), action, newLoadType, request.formState(), request.substituteData(), request.clientRedirect());
+    loadWithNavigationAction(action, newLoadType, request.formState(), request.substituteData(), request.clientRedirect());
     // Example of this case are sites that reload the same URL with a different cookie
     // driving the generated content, or a master frame with links that drive a target
     // frame, where the user has clicked on the same link repeatedly.
@@ -770,9 +760,6 @@
     if (!documentLoader)
         return;
 
-    if (m_state == FrameStateProvisional)
-        insertDummyHistoryItem();
-
     ResourceRequest request = documentLoader->request();
     // FIXME: We need to reset cache policy to prevent it from being incorrectly propagted to the reload.
     // Do we need to propagate anything other than the url?
@@ -784,7 +771,7 @@
 
     FrameLoadType type = reloadPolicy == EndToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload;
     NavigationAction action(request, type, request.httpMethod() == "POST");
-    loadWithNavigationAction(request, action, type, 0, SubstituteData(), NotClientRedirect, overrideEncoding);
+    loadWithNavigationAction(action, type, 0, SubstituteData(), NotClientRedirect, overrideEncoding);
 }
 
 void FrameLoader::stopAllLoaders()
@@ -844,8 +831,7 @@
 
 void FrameLoader::notifyIfInitialDocumentAccessed()
 {
-    if (m_didAccessInitialDocumentTimer.isActive()
-        && m_stateMachine.isDisplayingInitialEmptyDocument()) {
+    if (m_didAccessInitialDocumentTimer.isActive()) {
         m_didAccessInitialDocumentTimer.stop();
         didAccessInitialDocumentTimerFired(0);
     }
@@ -891,9 +877,7 @@
     if (isLoadingMainFrame())
         m_frame->page()->chrome().client().needTouchEvents(false);
 
-    history()->updateForCommit();
-    m_client->transitionToCommittedForNewPage();
-
+    m_client->transitionToCommittedForNewPage(m_frame);
     m_frame->navigationScheduler().cancel();
     m_frame->editor().clearLastEditCommand();
 
@@ -922,8 +906,7 @@
 
 bool FrameLoader::isLoadingMainFrame() const
 {
-    Page* page = m_frame->page();
-    return page && m_frame == page->mainFrame();
+    return m_frame->isMainFrame();
 }
 
 bool FrameLoader::subframeIsLoading() const
@@ -1005,10 +988,7 @@
     // the new page is ready.
 
     // If the user had a scroll point, scroll to it, overriding the anchor point if any.
-    if (m_frame->page()) {
-        if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
-            history()->restoreScrollPositionAndViewState();
-    }
+    restoreScrollPositionAndViewState();
 
     if (!m_stateMachine.committedFirstRealDocumentLoad())
         return;
@@ -1023,13 +1003,39 @@
     m_loadType = FrameLoadTypeStandard;
 }
 
-void FrameLoader::didFirstLayout()
+// There is a race condition between the layout and load completion that affects restoring the scroll position.
+// We try to restore the scroll position at both the first layout and upon load completion.
+// 1) If first layout happens before the load completes, we want to restore the scroll position then so that the
+// first time we draw the page is already scrolled to the right place, instead of starting at the top and later
+// jumping down. It is possible that the old scroll position is past the part of the doc laid out so far, in
+// which case the restore silent fails and we will fix it in when we try to restore on doc completion.
+// 2) If the layout happens after the load completes, the attempt to restore at load completion time silently
+// fails. We then successfully restore it when the layout happens.
+void FrameLoader::restoreScrollPositionAndViewState()
 {
-    if (!m_frame->page())
+    if (!isBackForwardLoadType(m_loadType) && m_loadType != FrameLoadTypeReload && m_loadType != FrameLoadTypeReloadFromOrigin)
+        return;
+    if (!m_frame->page() || !m_currentItem || !m_stateMachine.committedFirstRealDocumentLoad())
         return;
 
-    if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
-        history()->restoreScrollPositionAndViewState();
+    if (FrameView* view = m_frame->view()) {
+        if (m_frame->isMainFrame()) {
+            if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator())
+                scrollingCoordinator->frameViewRootLayerDidChange(view);
+        }
+
+        if (!view->wasScrolledByUser()) {
+            if (m_frame->isMainFrame() && m_currentItem->pageScaleFactor())
+                m_frame->page()->setPageScaleFactor(m_currentItem->pageScaleFactor(), m_currentItem->scrollPoint());
+            else
+                view->setScrollPositionNonProgrammatically(m_currentItem->scrollPoint());
+        }
+    }
+}
+
+void FrameLoader::didFirstLayout()
+{
+    restoreScrollPositionAndViewState();
 }
 
 void FrameLoader::detachChildren()
@@ -1236,7 +1242,6 @@
             m_provisionalDocumentLoader->detachFromFrame();
         m_provisionalDocumentLoader = 0;
     }
-    history()->setProvisionalItem(0);
     loadInSameDocument(request.url(), 0, isNewNavigation, clientRedirect);
 }
 
@@ -1305,7 +1310,7 @@
     return shouldClose;
 }
 
-void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, ClientRedirectPolicy clientRedirect, const String& overrideEncoding)
+void FrameLoader::loadWithNavigationAction(const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, ClientRedirectPolicy clientRedirect, const String& overrideEncoding)
 {
     ASSERT(m_client->hasWebView());
     if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
@@ -1315,6 +1320,7 @@
     // 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.
+    const ResourceRequest& request = action.resourceRequest();
     if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame->ownerElement() && !m_frame->ownerElement()->dispatchBeforeLoadEvent(request.url().string()))
         return;
 
@@ -1322,8 +1328,7 @@
         m_stateMachine.advanceTo(FrameLoaderStateMachine::StartedFirstRealLoad);
 
     // The current load should replace the history item if it is the first real
-    // load of the frame. FrameLoadTypeRedirectWithLockedBackForwardList is a
-    // proxy for history()->currentItemShouldBeReplaced().
+    // load of the frame.
     bool replacesCurrentHistoryItem = false;
     if (type == FrameLoadTypeRedirectWithLockedBackForwardList
         || !m_stateMachine.committedFirstRealDocumentLoad()) {
@@ -1379,54 +1384,6 @@
     m_provisionalDocumentLoader->startLoadingMainResource();
 }
 
-void FrameLoader::checkNewWindowPolicyAndContinue(PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action)
-{
-    if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
-        return;
-
-    if (m_frame->document() && m_frame->document()->isSandboxed(SandboxPopups))
-        return;
-
-    if (!DOMWindow::allowPopUp(m_frame))
-        return;
-
-    NavigationPolicy navigationPolicy = NavigationPolicyNewForegroundTab;
-    action.specifiesNavigationPolicy(&navigationPolicy);
-
-    if (navigationPolicy == NavigationPolicyDownload) {
-        m_client->loadURLExternally(action.resourceRequest(), navigationPolicy);
-        return;
-    }
-
-    RefPtr<Frame> frame = m_frame;
-    RefPtr<Frame> mainFrame = m_frame;
-
-    if (!m_frame->settings() || m_frame->settings()->supportsMultipleWindows()) {
-        struct WindowFeatures features;
-        Page* newPage = m_frame->page()->chrome().client().createWindow(m_frame, FrameLoadRequest(m_frame->document()->securityOrigin(), action.resourceRequest()),
-            features, navigationPolicy);
-
-        // createWindow can return null (e.g., popup blocker denies the window).
-        if (!newPage)
-            return;
-        mainFrame = newPage->mainFrame();
-    }
-
-    if (frameName != "_blank")
-        mainFrame->tree().setName(frameName);
-
-    mainFrame->page()->setOpenedByDOM();
-    mainFrame->page()->chrome().show(navigationPolicy);
-    if (!m_suppressOpenerInNewFrame) {
-        mainFrame->loader().setOpener(frame.get());
-        mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
-    }
-
-    // FIXME: We can't just send our NavigationAction to the new FrameLoader's loadWithNavigationAction(), we need to
-    // create a new one with a default NavigationType and no triggering event. We should figure out why.
-    mainFrame->loader().loadWithNavigationAction(action.resourceRequest(), NavigationAction(action.resourceRequest()), FrameLoadTypeStandard, formState, SubstituteData());
-}
-
 void FrameLoader::applyUserAgent(ResourceRequest& request)
 {
     String userAgent = this->userAgent(request.url());
@@ -1453,7 +1410,7 @@
         for (Frame* frame = m_frame->tree().parent(); frame; frame = frame->tree().parent()) {
             if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin())) {
                 UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptionsSameOriginWithBadAncestorChain);
-                return true;
+                break;
             }
         }
         return false;
@@ -1476,9 +1433,9 @@
 
 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
 {
-    if (!history()->currentItem())
+    if (!m_currentItem)
         return false;
-    return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
+    return url == m_currentItem->url() || url == m_currentItem->originalURL();
 }
 
 bool FrameLoader::shouldTreatURLAsSrcdocDocument(const KURL& url) const
@@ -1522,19 +1479,14 @@
     return frame;
 }
 
-void FrameLoader::loadHistoryItem(HistoryItem* item)
+void FrameLoader::loadHistoryItem(HistoryItem* item, HistoryLoadType historyLoadType)
 {
-    HistoryItem* currentItem = history()->currentItem();
-
-    if (currentItem && item->shouldDoSameDocumentNavigationTo(currentItem)) {
-        history()->setCurrentItem(item);
+    if (historyLoadType == HistorySameDocumentLoad) {
+        m_currentItem = item;
         loadInSameDocument(item->url(), item->stateObject(), false, NotClientRedirect);
         return;
     }
 
-    // Remember this item so we can traverse any child items as child frames load
-    history()->setProvisionalItem(item);
-
     RefPtr<FormData> formData = item->formData();
     ResourceRequest request(item->url());
     request.setHTTPReferrer(item->referrer());
@@ -1546,13 +1498,7 @@
         addHTTPOriginIfNeeded(request, securityOrigin->toString());
     }
 
-    loadWithNavigationAction(request, NavigationAction(request, FrameLoadTypeBackForward, formData), FrameLoadTypeBackForward, 0, SubstituteData());
-}
-
-void FrameLoader::insertDummyHistoryItem()
-{
-    RefPtr<HistoryItem> currentItem = HistoryItem::create();
-    history()->setCurrentItem(currentItem.get());
+    loadWithNavigationAction(NavigationAction(request, FrameLoadTypeBackForward, formData), FrameLoadTypeBackForward, 0, SubstituteData());
 }
 
 void FrameLoader::dispatchDocumentElementAvailable()
diff --git a/Source/core/loader/FrameLoader.h b/Source/core/loader/FrameLoader.h
index 35fce11..1d9be6b 100644
--- a/Source/core/loader/FrameLoader.h
+++ b/Source/core/loader/FrameLoader.h
@@ -37,9 +37,9 @@
 #include "core/dom/SecurityContext.h"
 #include "core/fetch/CachePolicy.h"
 #include "core/fetch/ResourceLoaderOptions.h"
+#include "core/history/HistoryItem.h"
 #include "core/loader/FrameLoaderStateMachine.h"
 #include "core/loader/FrameLoaderTypes.h"
-#include "core/loader/HistoryController.h"
 #include "core/loader/MixedContentChecker.h"
 #include "platform/Timer.h"
 #include "wtf/Forward.h"
@@ -82,17 +82,12 @@
 
     Frame* frame() const { return m_frame; }
 
-    HistoryController* history() const { return &m_history; }
-
-    IconController* icon() const { return m_icon.get(); }
     MixedContentChecker* mixedContentChecker() const { return &m_mixedContentChecker; }
 
-    void prepareForHistoryNavigation();
-
     // These functions start a load. All eventually call into loadWithNavigationAction() or loadInSameDocument().
     void load(const FrameLoadRequest&); // The entry point for non-reload, non-history loads.
     void reload(ReloadPolicy = NormalReload, const KURL& overrideURL = KURL(), const String& overrideEncoding = String());
-    void loadHistoryItem(HistoryItem*); // The entry point for all back/forward loads
+    void loadHistoryItem(HistoryItem*, HistoryLoadType = HistoryDifferentDocumentLoad); // The entry point for all back/forward loads
 
     static void reportLocalLoadFailed(Frame*, const String& url);
 
@@ -135,6 +130,7 @@
 
     bool subframeIsLoading() const;
 
+    bool shouldTreatURLAsSameAsCurrent(const KURL&) const;
     bool shouldTreatURLAsSrcdocDocument(const KURL&) const;
 
     FrameLoadType loadType() const;
@@ -197,8 +193,6 @@
 
     bool allAncestorsAreComplete() const; // including this
 
-    bool suppressOpenerInNewFrame() const { return m_suppressOpenerInNewFrame; }
-
     bool shouldClose();
 
     void started();
@@ -211,6 +205,12 @@
     };
     void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, UpdateBackForwardListPolicy);
 
+    void setCurrentItem(HistoryItem* item) { m_currentItem = item; }
+    HistoryItem* currentItem() const { return m_currentItem.get(); }
+    void restoreScrollPositionAndViewState();
+    void saveDocumentAndScrollState();
+    void clearScrollPositionAndViewState();
+
 private:
     bool allChildrenAreComplete() const; // immediate children, not all descendants
 
@@ -219,8 +219,6 @@
     void checkTimerFired(Timer<FrameLoader>*);
     void didAccessInitialDocumentTimerFired(Timer<FrameLoader>*);
 
-    void insertDummyHistoryItem();
-
     bool prepareRequestForThisFrame(FrameLoadRequest&);
     void setReferrerForFrameRequest(ResourceRequest&, ShouldSendReferrer);
     FrameLoadType determineFrameLoadType(const FrameLoadRequest&);
@@ -229,7 +227,6 @@
     SubstituteData defaultSubstituteDataForURL(const KURL&);
 
     void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&, bool isNewNavigation, ClientRedirectPolicy);
-    void checkNewWindowPolicyAndContinue(PassRefPtr<FormState>, const String& frameName, const NavigationAction&);
 
     bool shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType, const KURL&);
     void scrollToFragmentWithParentBoundary(const KURL&);
@@ -239,8 +236,8 @@
     void closeOldDataSources();
 
     // Calls continueLoadAfterNavigationPolicy
-    void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&,
-        FrameLoadType, PassRefPtr<FormState>, const SubstituteData&, ClientRedirectPolicy = NotClientRedirect, const String& overrideEncoding = String());
+    void loadWithNavigationAction(const NavigationAction&, FrameLoadType, PassRefPtr<FormState>,
+        const SubstituteData&, ClientRedirectPolicy = NotClientRedirect, const String& overrideEncoding = String());
 
     void detachChildren();
     void closeAndRemoveChild(Frame*);
@@ -250,17 +247,13 @@
     void scheduleCheckCompleted();
     void startCheckCompleteTimer();
 
-    bool shouldTreatURLAsSameAsCurrent(const KURL&) const;
-
     Frame* m_frame;
     FrameLoaderClient* m_client;
 
     // FIXME: These should be OwnPtr<T> to reduce build times and simplify
     // header dependencies unless performance testing proves otherwise.
     // Some of these could be lazily created for memory savings on devices.
-    mutable HistoryController m_history;
     mutable FrameLoaderStateMachine m_stateMachine;
-    OwnPtr<IconController> m_icon;
     mutable MixedContentChecker m_mixedContentChecker;
 
     class FrameProgressTracker;
@@ -278,6 +271,8 @@
     RefPtr<DocumentLoader> m_policyDocumentLoader;
     OwnPtr<FetchContext> m_fetchContext;
 
+    RefPtr<HistoryItem> m_currentItem;
+
     bool m_inStopAllLoaders;
 
     String m_outgoingReferrer;
@@ -293,7 +288,6 @@
 
     bool m_didAccessInitialDocument;
     Timer<FrameLoader> m_didAccessInitialDocumentTimer;
-    bool m_suppressOpenerInNewFrame;
 
     SandboxFlags m_forcedSandboxFlags;
 };
diff --git a/Source/core/loader/FrameLoaderClient.h b/Source/core/loader/FrameLoaderClient.h
index 6069b0c..3539f7c 100644
--- a/Source/core/loader/FrameLoaderClient.h
+++ b/Source/core/loader/FrameLoaderClient.h
@@ -44,7 +44,7 @@
 template<class T> class Handle;
 }
 
-namespace WebKit {
+namespace blink {
 class WebCookieJar;
 class WebServiceWorkerProvider;
 class WebServiceWorkerProviderClient;
@@ -165,7 +165,7 @@
 
         virtual String doNotTrackValue() = 0;
 
-        virtual void transitionToCommittedForNewPage() = 0;
+        virtual void transitionToCommittedForNewPage(Frame*) = 0;
 
         virtual PassRefPtr<Frame> createFrame(const KURL&, const String& name, const String& referrer, HTMLFrameOwnerElement*) = 0;
         virtual PassRefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement*, const KURL&, const Vector<String>&, const Vector<String>&, const String&, bool loadManually) = 0;
@@ -201,7 +201,7 @@
         // This callback is similar, but for plugins.
         virtual void didNotAllowPlugins() { }
 
-        virtual WebKit::WebCookieJar* cookieJar() const = 0;
+        virtual blink::WebCookieJar* cookieJar() const = 0;
 
         // Returns true if the embedder intercepted the postMessage call
         virtual bool willCheckAndDispatchMessageEvent(SecurityOrigin* /*target*/, MessageEvent*) const { return false; }
@@ -227,7 +227,7 @@
 
         virtual void dispatchDidChangeResourcePriority(unsigned long /*identifier*/, ResourceLoadPriority) { }
 
-        virtual PassOwnPtr<WebKit::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<WebKit::WebServiceWorkerProviderClient>) = 0;
+        virtual PassOwnPtr<blink::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>) = 0;
 
         virtual void didStopAllLoaders() { }
 
diff --git a/Source/core/loader/FrameLoaderStateMachine.cpp b/Source/core/loader/FrameLoaderStateMachine.cpp
index 2ad0e23..61db0ef 100644
--- a/Source/core/loader/FrameLoaderStateMachine.cpp
+++ b/Source/core/loader/FrameLoaderStateMachine.cpp
@@ -46,7 +46,7 @@
 
 bool FrameLoaderStateMachine::committedFirstRealDocumentLoad() const
 {
-    return m_state == CommittedFirstRealLoad;
+    return m_state >= CommittedFirstRealLoad;
 }
 
 bool FrameLoaderStateMachine::creatingInitialEmptyDocument() const
@@ -54,6 +54,11 @@
     return m_state == CreatingInitialEmptyDocument;
 }
 
+bool FrameLoaderStateMachine::committedMultipleRealLoads() const
+{
+    return m_state == CommittedMultipleRealLoads;
+}
+
 bool FrameLoaderStateMachine::isDisplayingInitialEmptyDocument() const
 {
     return m_state >= DisplayingInitialEmptyDocument && m_state < CommittedFirstRealLoad;
diff --git a/Source/core/loader/FrameLoaderStateMachine.h b/Source/core/loader/FrameLoaderStateMachine.h
index e8d1a2a..aa349a5 100644
--- a/Source/core/loader/FrameLoaderStateMachine.h
+++ b/Source/core/loader/FrameLoaderStateMachine.h
@@ -47,13 +47,15 @@
         CreatingInitialEmptyDocument,
         DisplayingInitialEmptyDocument,
         StartedFirstRealLoad,
-        CommittedFirstRealLoad
+        CommittedFirstRealLoad,
+        CommittedMultipleRealLoads
     };
 
     bool startedFirstRealLoad() const;
     bool committedFirstRealDocumentLoad() const;
     bool creatingInitialEmptyDocument() const;
     bool isDisplayingInitialEmptyDocument() const;
+    bool committedMultipleRealLoads() const;
     void advanceTo(State);
 
 private:
diff --git a/Source/core/loader/FrameLoaderTypes.h b/Source/core/loader/FrameLoaderTypes.h
index 5a2a4b7..5fe5d36 100644
--- a/Source/core/loader/FrameLoaderTypes.h
+++ b/Source/core/loader/FrameLoaderTypes.h
@@ -99,6 +99,11 @@
     ClientRedirect
 };
 
+enum HistoryLoadType {
+    HistorySameDocumentLoad,
+    HistoryDifferentDocumentLoad
+};
+
 }
 
 #endif
diff --git a/Source/core/loader/HistoryController.cpp b/Source/core/loader/HistoryController.cpp
index 0ac9450..c9b31b4 100644
--- a/Source/core/loader/HistoryController.cpp
+++ b/Source/core/loader/HistoryController.cpp
@@ -33,24 +33,94 @@
 
 #include "core/dom/Document.h"
 #include "core/history/HistoryItem.h"
-#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorController.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/loader/FrameLoaderStateMachine.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
 #include "platform/Logging.h"
+#include "wtf/Deque.h"
 #include "wtf/text/CString.h"
 
 namespace WebCore {
 
-HistoryController::HistoryController(Frame* frame)
-    : m_frame(frame)
+PassOwnPtr<HistoryNode> HistoryNode::create(HistoryEntry* entry, HistoryItem* value)
+{
+    return adoptPtr(new HistoryNode(entry, value));
+}
+
+HistoryNode* HistoryNode::addChild(PassRefPtr<HistoryItem> item)
+{
+    m_children.append(HistoryNode::create(m_entry, item.get()));
+    return m_children.last().get();
+}
+
+PassOwnPtr<HistoryNode> HistoryNode::cloneAndReplace(HistoryEntry* newEntry, HistoryItem* newItem, HistoryItem* oldItem, bool clipAtTarget, Frame* frame)
+{
+    bool isNodeBeingNavigated = m_value == oldItem;
+    HistoryItem* itemForCreate = isNodeBeingNavigated ? newItem : m_value.get();
+    OwnPtr<HistoryNode> newHistoryNode = create(newEntry, itemForCreate);
+
+    if (!clipAtTarget || !isNodeBeingNavigated) {
+        for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
+            HistoryNode* childHistoryNode = m_entry->m_framesToItems.get(child->frameID());
+            if (!childHistoryNode)
+                continue;
+            newHistoryNode->m_children.append(childHistoryNode->cloneAndReplace(newEntry, newItem, oldItem, clipAtTarget, child));
+        }
+    }
+    return newHistoryNode.release();
+}
+
+HistoryNode::HistoryNode(HistoryEntry* entry, HistoryItem* value)
+    : m_entry(entry)
+    , m_value(value)
+{
+    m_entry->m_framesToItems.add(value->targetFrameID(), this);
+    String target = value->target();
+    if (target.isNull())
+        target = emptyString();
+    m_entry->m_uniqueNamesToItems.add(target, this);
+}
+
+HistoryEntry::HistoryEntry(HistoryItem* root)
+{
+    m_root = HistoryNode::create(this, root);
+}
+
+PassOwnPtr<HistoryEntry> HistoryEntry::create(HistoryItem* root)
+{
+    return adoptPtr(new HistoryEntry(root));
+}
+
+PassOwnPtr<HistoryEntry> HistoryEntry::cloneAndReplace(HistoryItem* newItem, HistoryItem* oldItem, bool clipAtTarget, Page* page)
+{
+    OwnPtr<HistoryEntry> newEntry = adoptPtr(new HistoryEntry());
+    newEntry->m_root = m_root->cloneAndReplace(newEntry.get(), newItem, oldItem, clipAtTarget, page->mainFrame());
+    return newEntry.release();
+}
+
+HistoryNode* HistoryEntry::historyNodeForFrame(Frame* frame)
+{
+    if (HistoryNode* historyNode = m_framesToItems.get(frame->frameID()))
+        return historyNode;
+    String target = frame->tree().uniqueName();
+    if (target.isNull())
+        target = emptyString();
+    return m_uniqueNamesToItems.get(target);
+}
+
+HistoryItem* HistoryEntry::itemForFrame(Frame* frame)
+{
+    if (HistoryNode* historyNode = historyNodeForFrame(frame))
+        return historyNode->value();
+    return 0;
+}
+
+HistoryController::HistoryController(Page* page)
+    : m_page(page)
     , m_defersLoading(false)
 {
 }
@@ -59,116 +129,77 @@
 {
 }
 
-void HistoryController::clearScrollPositionAndViewState()
+void HistoryController::updateBackForwardListForFragmentScroll(Frame* frame)
 {
-    if (!m_currentItem)
-        return;
-
-    m_currentItem->clearScrollPoint();
-    m_currentItem->setPageScaleFactor(0);
+    m_provisionalEntry.clear();
+    createNewBackForwardItem(frame, false);
 }
 
-/*
- There is a race condition between the layout and load completion that affects restoring the scroll position.
- We try to restore the scroll position at both the first layout and upon load completion.
-
- 1) If first layout happens before the load completes, we want to restore the scroll position then so that the
- first time we draw the page is already scrolled to the right place, instead of starting at the top and later
- jumping down.  It is possible that the old scroll position is past the part of the doc laid out so far, in
- which case the restore silent fails and we will fix it in when we try to restore on doc completion.
- 2) If the layout happens after the load completes, the attempt to restore at load completion time silently
- fails.  We then successfully restore it when the layout happens.
-*/
-void HistoryController::restoreScrollPositionAndViewState()
+void HistoryController::goToEntry(PassOwnPtr<HistoryEntry> targetEntry)
 {
-    if (!m_currentItem || !m_frame->loader().stateMachine()->committedFirstRealDocumentLoad())
-        return;
+    ASSERT(m_sameDocumentLoadsInProgress.isEmpty());
+    ASSERT(m_differentDocumentLoadsInProgress.isEmpty());
 
-    if (FrameView* view = m_frame->view()) {
-        Page* page = m_frame->page();
-        if (page && page->mainFrame() == m_frame) {
-            if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-                scrollingCoordinator->frameViewRootLayerDidChange(view);
-        }
+    m_provisionalEntry = targetEntry;
+    recursiveGoToEntry(m_page->mainFrame());
 
-        if (!view->wasScrolledByUser()) {
-            if (page && page->mainFrame() == m_frame && m_currentItem->pageScaleFactor())
-                page->setPageScaleFactor(m_currentItem->pageScaleFactor(), m_currentItem->scrollPoint());
-            else
-                view->setScrollPositionNonProgrammatically(m_currentItem->scrollPoint());
-        }
-    }
-}
-
-void HistoryController::updateBackForwardListForFragmentScroll()
-{
-    createNewBackForwardItem(false);
-}
-
-void HistoryController::saveDocumentAndScrollState()
-{
-    if (!m_currentItem)
-        return;
-
-    Document* document = m_frame->document();
-    ASSERT(document);
-
-    if (m_currentItem->isCurrentDocument(document) && document->isActive()) {
-        LOG(Loading, "WebCoreLoading %s: saving form state to %p", m_frame->tree().uniqueName().string().utf8().data(), m_currentItem.get());
-        m_currentItem->setDocumentState(document->formElementsState());
+    if (m_differentDocumentLoadsInProgress.isEmpty()) {
+        m_previousEntry = m_currentEntry.release();
+        m_currentEntry = m_provisionalEntry.release();
+    } else {
+        m_page->mainFrame()->loader().stopAllLoaders();
     }
 
-    if (!m_frame->view())
+    for (HistoryFrameLoadSet::iterator it = m_sameDocumentLoadsInProgress.begin(); it != m_sameDocumentLoadsInProgress.end(); ++it)
+        it->key->loader().loadHistoryItem(it->value, HistorySameDocumentLoad);
+    for (HistoryFrameLoadSet::iterator it = m_differentDocumentLoadsInProgress.begin(); it != m_differentDocumentLoadsInProgress.end(); ++it)
+        it->key->loader().loadHistoryItem(it->value, HistoryDifferentDocumentLoad);
+    m_sameDocumentLoadsInProgress.clear();
+    m_differentDocumentLoadsInProgress.clear();
+}
+
+void HistoryController::recursiveGoToEntry(Frame* frame)
+{
+    HistoryItem* newItem = m_provisionalEntry->itemForFrame(frame);
+    HistoryItem* oldItem = m_currentEntry ? m_currentEntry->itemForFrame(frame) : 0;
+    if (!newItem)
         return;
 
-    m_currentItem->setScrollPoint(m_frame->view()->scrollPosition());
+    if (!oldItem || (newItem != oldItem && newItem->itemSequenceNumber() != oldItem->itemSequenceNumber())) {
+        if (oldItem && newItem->documentSequenceNumber() == oldItem->documentSequenceNumber())
+            m_sameDocumentLoadsInProgress.set(frame, newItem);
+        else
+            m_differentDocumentLoadsInProgress.set(frame, newItem);
+        return;
+    }
 
-    Page* page = m_frame->page();
-    if (page && page->mainFrame() == m_frame && !page->inspectorController().deviceEmulationEnabled())
-        m_currentItem->setPageScaleFactor(page->pageScaleFactor());
+    for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling())
+        recursiveGoToEntry(child);
 }
 
-void HistoryController::restoreDocumentState()
-{
-    if (m_currentItem && m_frame->loader().loadType() == FrameLoadTypeBackForward)
-        m_frame->document()->setStateForNewFormElements(m_currentItem->documentState());
-}
-
-bool HistoryController::shouldStopLoadingForHistoryItem(HistoryItem* targetItem) const
-{
-    if (!m_currentItem)
-        return false;
-    // Don't abort the current load if we're navigating within the current document.
-    return !m_currentItem->shouldDoSameDocumentNavigationTo(targetItem);
-}
-
-// Main funnel for navigating to a previous location (back/forward, non-search snap-back)
-// This includes recursion to handle loading into framesets properly
 void HistoryController::goToItem(HistoryItem* targetItem)
 {
-    ASSERT(!m_frame->tree().parent());
-
-    // shouldGoToHistoryItem is a private delegate method. This is needed to fix:
-    // <rdar://problem/3951283> can view pages from the back/forward cache that should be disallowed by Parental Controls
-    // Ultimately, history item navigations should go through the policy delegate. That's covered in:
-    // <rdar://problem/3979539> back/forward cache navigations should consult policy delegate
-    Page* page = m_frame->page();
-    if (!page)
-        return;
     if (m_defersLoading) {
         m_deferredItem = targetItem;
         return;
     }
 
-    clearProvisionalItemsInAllFrames();
-
-    // First set the provisional item of any frames that are not actually navigating.
-    // This must be done before trying to navigate the desired frame, because some
-    // navigations can commit immediately (such as about:blank).  We must be sure that
-    // all frames have provisional items set before the commit.
-    recursiveSetProvisionalItem(targetItem, m_currentItem.get());
-    // Now that all other frames have provisional items, do the actual navigation.
-    recursiveGoToItem(targetItem, m_currentItem.get());
+    OwnPtr<HistoryEntry> newEntry = HistoryEntry::create(targetItem);
+    Deque<HistoryNode*> historyNodes;
+    historyNodes.append(newEntry->rootHistoryNode());
+    while (!historyNodes.isEmpty()) {
+        // For each item, read the children (if any) off the HistoryItem,
+        // create a new HistoryNode for each child and attach it,
+        // then clear the children on the HistoryItem.
+        HistoryNode* historyNode = historyNodes.takeFirst();
+        const HistoryItemVector& children = historyNode->value()->children();
+        for (size_t i = 0; i < children.size(); i++) {
+            HistoryNode* childHistoryNode = historyNode->addChild(children[i].get());
+            historyNodes.append(childHistoryNode);
+        }
+        historyNode->value()->clearChildren();
+    }
+    goToEntry(newEntry.release());
 }
 
 void HistoryController::setDefersLoading(bool defer)
@@ -180,154 +211,103 @@
     }
 }
 
-void HistoryController::clearProvisionalItemsInAllFrames()
-{
-    for (RefPtr<Frame> frame = m_frame->page()->mainFrame(); frame; frame = frame->tree().traverseNext())
-        frame->loader().history()->m_provisionalItem = 0;
-}
-
 // There are 2 things you might think of as "history", all of which are handled by these functions.
 //
 //     1) Back/forward: The m_currentItem is part of this mechanism.
 //     2) Global history: Handled by the client.
 //
-void HistoryController::updateForStandardLoad()
+void HistoryController::updateForStandardLoad(Frame* frame)
 {
-    LOG(History, "WebCoreHistory: Updating History for Standard Load in frame %s", m_frame->loader().documentLoader()->url().string().ascii().data());
-    createNewBackForwardItem(true);
+    LOG(History, "WebCoreHistory: Updating History for Standard Load in frame %s", frame->loader().documentLoader()->url().string().ascii().data());
+    createNewBackForwardItem(frame, true);
 }
 
-void HistoryController::updateForInitialLoadInChildFrame()
+void HistoryController::updateForInitialLoadInChildFrame(Frame* frame)
 {
-    Frame* parentFrame = m_frame->tree().parent();
-    if (parentFrame && parentFrame->loader().history()->m_currentItem)
-        parentFrame->loader().history()->m_currentItem->setChildItem(createItem());
+    ASSERT(frame->tree().parent());
+    if (!m_currentEntry)
+        return;
+    if (HistoryNode* existingChildHistoryNode = m_currentEntry->historyNodeForFrame(frame))
+        existingChildHistoryNode->updateValue(createItem(frame));
+    else if (HistoryNode* parentHistoryNode = m_currentEntry->historyNodeForFrame(frame->tree().parent()))
+        parentHistoryNode->addChild(createItem(frame));
 }
 
-void HistoryController::updateForCommit()
+void HistoryController::updateForCommit(Frame* frame)
 {
-    FrameLoader& frameLoader = m_frame->loader();
 #if !LOG_DISABLED
-    if (m_frame->document())
-        LOG(History, "WebCoreHistory: Updating History for commit in frame %s", m_frame->document()->title().utf8().data());
+    if (frame->document())
+        LOG(History, "WebCoreHistory: Updating History for commit in frame %s", frame->document()->title().utf8().data());
 #endif
-    FrameLoadType type = frameLoader.loadType();
+    FrameLoadType type = frame->loader().loadType();
     if (isBackForwardLoadType(type)) {
         // Once committed, we want to use current item for saving DocState, and
         // the provisional item for restoring state.
         // Note previousItem must be set before we close the URL, which will
         // happen when the data source is made non-provisional below
-        m_previousItem = m_currentItem;
-        ASSERT(m_provisionalItem);
-        m_currentItem = m_provisionalItem;
-        m_provisionalItem = 0;
-
-        // Tell all other frames in the tree to commit their provisional items and
-        // restore their scroll position.  We'll avoid this frame (which has already
-        // committed) and its children (which will be replaced).
-        Page* page = m_frame->page();
-        ASSERT(page);
-        page->mainFrame()->loader().history()->recursiveUpdateForCommit();
+        if (m_provisionalEntry) {
+            m_previousEntry = m_currentEntry.release();
+            ASSERT(m_provisionalEntry);
+            m_currentEntry = m_provisionalEntry.release();
+        }
+        frame->loader().setCurrentItem(m_currentEntry->itemForFrame(frame));
     } else if (type != FrameLoadTypeRedirectWithLockedBackForwardList) {
-        m_provisionalItem = 0;
+        m_provisionalEntry.clear();
     }
 
     if (type == FrameLoadTypeStandard)
-        updateForStandardLoad();
+        updateForStandardLoad(frame);
     else if (type == FrameLoadTypeInitialInChildFrame)
-        updateForInitialLoadInChildFrame();
+        updateForInitialLoadInChildFrame(frame);
     else
-        updateWithoutCreatingNewBackForwardItem();
+        updateWithoutCreatingNewBackForwardItem(frame);
 }
 
-void HistoryController::recursiveUpdateForCommit()
+static PassRefPtr<HistoryItem> itemForExport(HistoryNode* historyNode)
 {
-    // The frame that navigated will now have a null provisional item.
-    // Ignore it and its children.
-    if (!m_provisionalItem)
-        return;
-
-    // For each frame that already had the content the item requested (based on
-    // (a matching URL and frame tree snapshot), just restore the scroll position.
-    // Save form state
-    if (m_currentItem && itemsAreClones(m_currentItem.get(), m_provisionalItem.get())) {
-        if (FrameView* view = m_frame->view())
-            view->setWasScrolledByUser(false);
-
-        // Now commit the provisional item
-        m_previousItem = m_currentItem;
-        m_currentItem = m_provisionalItem;
-        m_provisionalItem = 0;
-
-        // Restore the scroll position (we choose to do this rather than going back to the anchor point)
-        restoreScrollPositionAndViewState();
-    }
-
-    // Iterate over the rest of the tree
-    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
-        child->loader().history()->recursiveUpdateForCommit();
+    RefPtr<HistoryItem> item = historyNode->value()->copy();
+    const Vector<OwnPtr<HistoryNode> >& childEntries = historyNode->children();
+    for (size_t i = 0; i < childEntries.size(); i++)
+        item->addChildItem(itemForExport(childEntries[i].get()));
+    return item;
 }
 
-void HistoryController::updateForSameDocumentNavigation()
+PassRefPtr<HistoryItem> HistoryController::currentItemForExport(Frame* frame)
 {
-    if (m_frame->document()->url().isEmpty())
-        return;
-
-    Page* page = m_frame->page();
-    if (!page)
-        return;
-
-    page->mainFrame()->loader().history()->recursiveUpdateForSameDocumentNavigation();
-
-    if (m_currentItem)
-        m_currentItem->setURL(m_frame->document()->url());
+    if (!m_currentEntry)
+        return 0;
+    HistoryNode* historyNode = m_currentEntry->historyNodeForFrame(frame);
+    return historyNode ? itemForExport(historyNode) : 0;
 }
 
-void HistoryController::recursiveUpdateForSameDocumentNavigation()
+PassRefPtr<HistoryItem> HistoryController::previousItemForExport(Frame* frame)
 {
-    // The frame that navigated will now have a null provisional item.
-    // Ignore it and its children.
-    if (!m_provisionalItem)
-        return;
-
-    // The provisional item may represent a different pending navigation.
-    // Don't commit it if it isn't a same document navigation.
-    if (m_currentItem && !m_currentItem->shouldDoSameDocumentNavigationTo(m_provisionalItem.get()))
-        return;
-
-    // Commit the provisional item.
-    m_previousItem = m_currentItem;
-    m_currentItem = m_provisionalItem;
-    m_provisionalItem = 0;
-
-    // Iterate over the rest of the tree.
-    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
-        child->loader().history()->recursiveUpdateForSameDocumentNavigation();
+    if (!m_previousEntry)
+        return 0;
+    HistoryNode* historyNode = m_previousEntry->historyNodeForFrame(frame);
+    return historyNode ? itemForExport(historyNode) : 0;
 }
 
-void HistoryController::setCurrentItem(HistoryItem* item)
+PassRefPtr<HistoryItem> HistoryController::provisionalItemForExport(Frame* frame)
 {
-    m_previousItem = m_currentItem;
-    m_currentItem = item;
+    if (!m_provisionalEntry)
+        return 0;
+    HistoryNode* historyNode = m_provisionalEntry->historyNodeForFrame(frame);
+    return historyNode ? itemForExport(historyNode) : 0;
 }
 
-bool HistoryController::currentItemShouldBeReplaced() const
+HistoryItem* HistoryController::itemForNewChildFrame(Frame* frame) const
 {
-    // From the HTML5 spec for location.assign():
-    //  "If the browsing context's session history contains only one Document,
-    //   and that was the about:blank Document created when the browsing context
-    //   was created, then the navigation must be done with replacement enabled."
-    return m_currentItem && !m_previousItem && equalIgnoringCase(m_currentItem->urlString(), blankURL());
+    Frame* parent = frame->tree().parent();
+    ASSERT(parent);
+    if (!m_currentEntry || !isBackForwardLoadType(parent->loader().loadType()) || parent->document()->loadEventFinished())
+        return 0;
+    return m_currentEntry->itemForFrame(frame);
 }
 
-void HistoryController::setProvisionalItem(HistoryItem* item)
+void HistoryController::initializeItem(HistoryItem* item, Frame* frame)
 {
-    m_provisionalItem = item;
-}
-
-void HistoryController::initializeItem(HistoryItem* item)
-{
-    DocumentLoader* documentLoader = m_frame->loader().documentLoader();
+    DocumentLoader* documentLoader = frame->loader().documentLoader();
     ASSERT(documentLoader);
 
     KURL unreachableURL = documentLoader->unreachableURL();
@@ -353,213 +333,66 @@
     if (originalURL.isEmpty())
         originalURL = blankURL();
 
-    Frame* parentFrame = m_frame->tree().parent();
-    String parent = parentFrame ? parentFrame->tree().uniqueName() : "";
-
     item->setURL(url);
-    item->setTarget(m_frame->tree().uniqueName());
-    item->setTargetFrameID(m_frame->frameID());
+    item->setTarget(frame->tree().uniqueName());
+    item->setTargetFrameID(frame->frameID());
     item->setOriginalURLString(originalURL.string());
 
     // Save form state if this is a POST
     item->setFormInfoFromRequest(documentLoader->request());
 }
 
-PassRefPtr<HistoryItem> HistoryController::createItem()
+PassRefPtr<HistoryItem> HistoryController::createItem(Frame* frame)
 {
     RefPtr<HistoryItem> item = HistoryItem::create();
-    initializeItem(item.get());
-
-    // Set the item for which we will save document state
-    m_previousItem = m_currentItem;
-    m_currentItem = item;
-
+    initializeItem(item.get(), frame);
+    frame->loader().setCurrentItem(item.get());
     return item.release();
 }
 
-PassRefPtr<HistoryItem> HistoryController::createItemTree(Frame* targetFrame, bool clipAtTarget)
+void HistoryController::createItemTree(Frame* targetFrame, bool clipAtTarget)
 {
-    RefPtr<HistoryItem> bfItem = createItem();
-
-    if (!clipAtTarget || m_frame != targetFrame) {
-        // clipAtTarget is false for navigations within the same document, so
-        // we should copy the documentSequenceNumber over to the newly create
-        // item.  Non-target items are just clones, and they should therefore
-        // preserve the same itemSequenceNumber.
-        if (m_previousItem) {
-            if (m_frame != targetFrame)
-                bfItem->setItemSequenceNumber(m_previousItem->itemSequenceNumber());
-            bfItem->setDocumentSequenceNumber(m_previousItem->documentSequenceNumber());
-        }
-
-        for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
-            // If the child is a frame corresponding to an <object> element that never loaded,
-            // we don't want to create a history item, because that causes fallback content
-            // to be ignored on reload.
-            FrameLoader& childLoader = child->loader();
-            if (childLoader.stateMachine()->startedFirstRealLoad() || !child->ownerElement()->isObjectElement())
-                bfItem->addChildItem(childLoader.history()->createItemTree(targetFrame, clipAtTarget));
-        }
-    }
-    return bfItem;
-}
-
-// The general idea here is to traverse the frame tree and the item tree in parallel,
-// tracking whether each frame already has the content the item requests.  If there is
-// a match, we set the provisional item and recurse.  Otherwise we will reload that
-// frame and all its kids in recursiveGoToItem.
-void HistoryController::recursiveSetProvisionalItem(HistoryItem* item, HistoryItem* fromItem)
-{
-    ASSERT(item);
-
-    if (itemsAreClones(item, fromItem)) {
-        // Set provisional item, which will be committed in recursiveUpdateForCommit.
-        m_provisionalItem = item;
-
-        const HistoryItemVector& childItems = item->children();
-
-        int size = childItems.size();
-
-        for (int i = 0; i < size; ++i) {
-            String childFrameName = childItems[i]->target();
-            HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName);
-            ASSERT(fromChildItem);
-            Frame* childFrame = m_frame->tree().child(childFrameName);
-            ASSERT(childFrame);
-            childFrame->loader().history()->recursiveSetProvisionalItem(childItems[i].get(), fromChildItem);
-        }
-    }
-}
-
-// We now traverse the frame tree and item tree a second time, loading frames that
-// do have the content the item requests.
-void HistoryController::recursiveGoToItem(HistoryItem* item, HistoryItem* fromItem)
-{
-    ASSERT(item);
-
-    if (itemsAreClones(item, fromItem)) {
-        // Just iterate over the rest, looking for frames to navigate.
-        const HistoryItemVector& childItems = item->children();
-
-        int size = childItems.size();
-        for (int i = 0; i < size; ++i) {
-            String childFrameName = childItems[i]->target();
-            HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName);
-            ASSERT(fromChildItem);
-            Frame* childFrame = m_frame->tree().child(childFrameName);
-            ASSERT(childFrame);
-            childFrame->loader().history()->recursiveGoToItem(childItems[i].get(), fromChildItem);
-        }
+    RefPtr<HistoryItem> newItem = createItem(targetFrame);
+    if (!m_currentEntry) {
+        m_currentEntry = HistoryEntry::create(newItem.get());
     } else {
-        m_frame->loader().loadHistoryItem(item);
+        HistoryItem* oldItem = m_currentEntry->itemForFrame(targetFrame);
+        if (!clipAtTarget && oldItem)
+            newItem->setDocumentSequenceNumber(oldItem->documentSequenceNumber());
+        m_previousEntry = m_currentEntry.release();
+        m_currentEntry = m_previousEntry->cloneAndReplace(newItem.get(), oldItem, clipAtTarget, m_page);
     }
 }
 
-bool HistoryController::itemsAreClones(HistoryItem* item1, HistoryItem* item2) const
-{
-    // If the item we're going to is a clone of the item we're at, then we do
-    // not need to load it again.  The current frame tree and the frame tree
-    // snapshot in the item have to match.
-    // Note: Some clients treat a navigation to the current history item as
-    // a reload.  Thus, if item1 and item2 are the same, we need to create a
-    // new document and should not consider them clones.
-    // (See http://webkit.org/b/35532 for details.)
-    return item1
-        && item2
-        && item1 != item2
-        && item1->itemSequenceNumber() == item2->itemSequenceNumber()
-        && currentFramesMatchItem(item1)
-        && item2->hasSameFrames(item1);
-}
-
-// Helper method that determines whether the current frame tree matches given history item's.
-bool HistoryController::currentFramesMatchItem(HistoryItem* item) const
-{
-    if ((!m_frame->tree().uniqueName().isEmpty() || !item->target().isEmpty()) && m_frame->tree().uniqueName() != item->target())
-        return false;
-
-    const HistoryItemVector& childItems = item->children();
-    if (childItems.size() != m_frame->tree().childCount())
-        return false;
-
-    unsigned size = childItems.size();
-    for (unsigned i = 0; i < size; ++i) {
-        if (!m_frame->tree().child(childItems[i]->target()))
-            return false;
-    }
-
-    return true;
-}
-
-void HistoryController::createNewBackForwardItem(bool doClip)
+void HistoryController::createNewBackForwardItem(Frame* frame, bool doClip)
 {
     // In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree.
     // The item that was the target of the user's navigation is designated as the "targetItem".
     // When this function is called with doClip=true we're able to create the whole tree except for the target's children,
     // which will be loaded in the future. That part of the tree will be filled out as the child loads are committed.
-
-    Page* page = m_frame->page();
-    if (!page)
+    if (!frame->loader().documentLoader()->isURLValidForNewHistoryEntry())
         return;
-
-    if (!m_frame->loader().documentLoader()->isURLValidForNewHistoryEntry())
-        return;
-
-    Frame* mainFrame = page->mainFrame();
-    ASSERT(mainFrame);
-
-    RefPtr<HistoryItem> topItem = mainFrame->loader().history()->createItemTree(m_frame, doClip);
-    LOG(BackForward, "WebCoreBackForward - Adding backforward item %p for frame %s", topItem.get(), m_frame->loader().documentLoader()->url().string().ascii().data());
+    createItemTree(frame, doClip);
 }
 
-void HistoryController::updateWithoutCreatingNewBackForwardItem()
+void HistoryController::updateWithoutCreatingNewBackForwardItem(Frame* frame)
 {
-    if (!m_currentItem)
+    if (!m_currentEntry || !m_currentEntry->itemForFrame(frame))
         return;
 
-    DocumentLoader* documentLoader = m_frame->loader().documentLoader();
+    DocumentLoader* documentLoader = frame->loader().documentLoader();
 
     if (!documentLoader->unreachableURL().isEmpty())
         return;
 
-    if (m_currentItem->url() != documentLoader->url()) {
-        m_currentItem->reset();
-        initializeItem(m_currentItem.get());
+    HistoryItem* item = m_currentEntry->itemForFrame(frame);
+    if (item->url() != documentLoader->url()) {
+        item->reset();
+        initializeItem(item, frame);
     } else {
         // Even if the final URL didn't change, the form data may have changed.
-        m_currentItem->setFormInfoFromRequest(documentLoader->request());
+        item->setFormInfoFromRequest(documentLoader->request());
     }
 }
 
-void HistoryController::pushState(PassRefPtr<SerializedScriptValue> stateObject, const String& urlString)
-{
-    if (!m_currentItem)
-        return;
-
-    Page* page = m_frame->page();
-    ASSERT(page);
-
-    // Get a HistoryItem tree for the current frame tree.
-    RefPtr<HistoryItem> topItem = page->mainFrame()->loader().history()->createItemTree(m_frame, false);
-
-    // Override data in the current item (created by createItemTree) to reflect
-    // the pushState() arguments.
-    m_currentItem->setStateObject(stateObject);
-    m_currentItem->setURLString(urlString);
-}
-
-void HistoryController::replaceState(PassRefPtr<SerializedScriptValue> stateObject, const String& urlString)
-{
-    if (!m_currentItem)
-        return;
-
-    if (!urlString.isEmpty())
-        m_currentItem->setURLString(urlString);
-    m_currentItem->setStateObject(stateObject);
-    m_currentItem->setFormData(0);
-    m_currentItem->setFormContentType(String());
-
-    ASSERT(m_frame->page());
-}
-
 } // namespace WebCore
diff --git a/Source/core/loader/HistoryController.h b/Source/core/loader/HistoryController.h
index f708408..e963dbf 100644
--- a/Source/core/loader/HistoryController.h
+++ b/Source/core/loader/HistoryController.h
@@ -32,6 +32,7 @@
 
 #include "core/history/HistoryItem.h"
 #include "core/loader/FrameLoaderTypes.h"
+#include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
@@ -39,68 +40,141 @@
 namespace WebCore {
 
 class Frame;
-class SerializedScriptValue;
+class HistoryEntry;
+class Page;
+
+
+// A guide to history state in Blink:
+//
+// HistoryController: Owned by Page, is the entry point for interacting with history.
+//     Handles most of the operations to modify history state, navigate to an existing
+//     back/forward entry, etc.
+// HistoryEntry: Represents a single entry in the back/forward list, encapsulating
+//     all frames in the page it represents. It provides access to each frame's
+//     state via lookups by frame id or frame name.
+// HistoryNode: Represents a single frame in a HistoryEntry. Owned by a HistoryEntry. HistoryNodes
+// form a tree that mirrors the FrameTree in the corresponding page. HistoryNodes represent
+// the structure of the page, but don't hold any per-frame state except a list of child frames.
+// HistoryItem (lives in a separate file): The state for a given frame. Can persist across
+//     navigations. HistoryItem is reference counted, and each HistoryNode holds a reference
+//     to its single corresponding HistoryItem. Can be referenced by multiple HistoryNodes and
+//     can therefore exist in multiple HistoryEntry instances.
+//
+// Suppose we have the following page, foo.com, which embeds foo.com/a in an iframe:
+//
+// HistoryEntry 0:
+//     HistoryNode 0_0 (HistoryItem A (url: foo.com))
+//         HistoryNode 0_1: (HistoryItem B (url: foo.com/a))
+//
+// Now we navigation the top frame to bar.com, which embeds bar.com/b and bar.com/c in iframes,
+// and bar.com/b in turn embeds bar.com/d. We will create a new HistoryEntry with a tree
+// containing 4 new HistoryNodes. The state will be:
+//
+// HistoryEntry 1:
+//     HistoryNode 1_0 (HistoryItem C (url: bar.com))
+//         HistoryNode 1_1: (HistoryItem D (url: bar.com/b))
+//             HistoryNode 1_3: (HistoryItem F (url: bar.com/d))
+//         HistoryNode 1_2: (HistoryItem E (url: bar.com/c))
+//
+//
+// Finally, we navigate the first subframe from bar.com/b to bar.com/e, which embeds bar.com/f.
+// We will create a new HistoryEntry and new HistoryNode for each frame. Any frame that
+// navigates (bar.com/e and its child, bar.com/f) will receive a new HistoryItem. However,
+// 2 frames were not navigated (bar.com and bar.com/c), so those two frames will reuse the
+// existing HistoryItem:
+//
+// HistoryEntry 2:
+//     HistoryNode 2_0 (HistoryItem C (url: bar.com))  *REUSED*
+//         HistoryNode 2_1: (HistoryItem G (url: bar.com/e))
+//            HistoryNode 2_3: (HistoryItem H (url: bar.com/f))
+//         HistoryNode 2_2: (HistoryItem E (url: bar.com/c)) *REUSED*
+//
+
+class HistoryNode {
+public:
+    static PassOwnPtr<HistoryNode> create(HistoryEntry*, HistoryItem*);
+    ~HistoryNode() { }
+
+    HistoryNode* addChild(PassRefPtr<HistoryItem>);
+    PassOwnPtr<HistoryNode> cloneAndReplace(HistoryEntry*, HistoryItem* newItem, HistoryItem* oldItem, bool clipAtTarget, Frame*);
+    HistoryItem* value() { return m_value.get(); }
+    void updateValue(PassRefPtr<HistoryItem> item) { m_value = item; }
+    const Vector<OwnPtr<HistoryNode> >& children() const { return m_children; }
+
+private:
+    HistoryNode(HistoryEntry*, HistoryItem*);
+
+    HistoryEntry* m_entry;
+    Vector<OwnPtr<HistoryNode> > m_children;
+    RefPtr<HistoryItem> m_value;
+};
+
+class HistoryEntry {
+public:
+    static PassOwnPtr<HistoryEntry> create(HistoryItem* root);
+    PassOwnPtr<HistoryEntry> cloneAndReplace(HistoryItem* newItem, HistoryItem* oldItem, bool clipAtTarget, Page*);
+
+    HistoryNode* historyNodeForFrame(Frame*);
+    HistoryItem* itemForFrame(Frame*);
+    HistoryItem* root() const { return m_root->value(); }
+    HistoryNode* rootHistoryNode() const { return m_root.get(); }
+
+private:
+    friend class HistoryNode;
+
+    HistoryEntry() { }
+    explicit HistoryEntry(HistoryItem* root);
+
+    OwnPtr<HistoryNode> m_root;
+    HashMap<uint64_t, HistoryNode*> m_framesToItems;
+    HashMap<String, HistoryNode*> m_uniqueNamesToItems;
+};
 
 class HistoryController {
     WTF_MAKE_NONCOPYABLE(HistoryController);
 public:
-    explicit HistoryController(Frame*);
+    explicit HistoryController(Page*);
     ~HistoryController();
 
-    void clearScrollPositionAndViewState();
-    void restoreScrollPositionAndViewState();
+    // Should only be called by embedder. To request a back/forward
+    // navigation, call FrameLoaderClient::navigateBackForward().
+    void goToItem(HistoryItem*);
 
-    void updateBackForwardListForFragmentScroll();
+    void updateBackForwardListForFragmentScroll(Frame*);
+    void updateForCommit(Frame*);
 
-    void saveDocumentAndScrollState();
-    void restoreDocumentState();
+    PassRefPtr<HistoryItem> currentItemForExport(Frame*);
+    PassRefPtr<HistoryItem> previousItemForExport(Frame*);
+    PassRefPtr<HistoryItem> provisionalItemForExport(Frame*);
+    HistoryItem* itemForNewChildFrame(Frame*) const;
 
-    void updateForCommit();
-    void updateForSameDocumentNavigation();
-
-    HistoryItem* currentItem() const { return m_currentItem.get(); }
-    void setCurrentItem(HistoryItem*);
-    bool currentItemShouldBeReplaced() const;
-
-    HistoryItem* previousItem() const { return m_previousItem.get(); }
-
-    HistoryItem* provisionalItem() const { return m_provisionalItem.get(); }
-    void setProvisionalItem(HistoryItem*);
-
-    void pushState(PassRefPtr<SerializedScriptValue>, const String& url);
-    void replaceState(PassRefPtr<SerializedScriptValue>, const String& url);
+    bool inSameDocumentLoad() const { return !m_sameDocumentLoadsInProgress.isEmpty() && m_differentDocumentLoadsInProgress.isEmpty(); }
 
     void setDefersLoading(bool);
 
 private:
-    friend class Page;
-    bool shouldStopLoadingForHistoryItem(HistoryItem*) const;
-    void goToItem(HistoryItem*);
+    void goToEntry(PassOwnPtr<HistoryEntry>);
+    void recursiveGoToEntry(Frame*);
 
-    void initializeItem(HistoryItem*);
-    PassRefPtr<HistoryItem> createItem();
-    PassRefPtr<HistoryItem> createItemTree(Frame* targetFrame, bool clipAtTarget);
+    void initializeItem(HistoryItem*, Frame*);
+    PassRefPtr<HistoryItem> createItem(Frame*);
+    void createItemTree(Frame* targetFrame, bool clipAtTarget);
 
-    void updateForStandardLoad();
-    void updateForInitialLoadInChildFrame();
+    void updateForStandardLoad(Frame*);
+    void updateForInitialLoadInChildFrame(Frame*);
 
-    void recursiveSetProvisionalItem(HistoryItem*, HistoryItem*);
-    void recursiveGoToItem(HistoryItem*, HistoryItem*);
-    void recursiveUpdateForCommit();
-    void recursiveUpdateForSameDocumentNavigation();
-    bool itemsAreClones(HistoryItem*, HistoryItem*) const;
-    bool currentFramesMatchItem(HistoryItem*) const;
+    void createNewBackForwardItem(Frame*, bool doClip);
+    void updateWithoutCreatingNewBackForwardItem(Frame*);
 
-    void createNewBackForwardItem(bool doClip);
-    void updateWithoutCreatingNewBackForwardItem();
+    Page* m_page;
 
-    void clearProvisionalItemsInAllFrames();
+    OwnPtr<HistoryEntry> m_currentEntry;
+    OwnPtr<HistoryEntry> m_previousEntry;
+    OwnPtr<HistoryEntry> m_provisionalEntry;
 
-    Frame* m_frame;
-
-    RefPtr<HistoryItem> m_currentItem;
-    RefPtr<HistoryItem> m_previousItem;
-    RefPtr<HistoryItem> m_provisionalItem;
+    typedef HashMap<Frame*, HistoryItem*> HistoryFrameLoadSet;
+    HistoryFrameLoadSet m_sameDocumentLoadsInProgress;
+    HistoryFrameLoadSet m_differentDocumentLoadsInProgress;
 
     bool m_defersLoading;
     RefPtr<HistoryItem> m_deferredItem;
diff --git a/Source/core/loader/IconController.cpp b/Source/core/loader/IconController.cpp
deleted file mode 100644
index 9061432..0000000
--- a/Source/core/loader/IconController.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2008 Alp Toker <alp@atoker.com>
- * Copyright (C) Research In Motion Limited 2009. All rights reserved.
- * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
- * 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 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/loader/IconController.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/IconURL.h"
-#include "core/frame/Frame.h"
-
-namespace WebCore {
-
-IconController::IconController(Frame* frame)
-    : m_frame(frame)
-{
-}
-
-IconController::~IconController()
-{
-}
-
-KURL IconController::url()
-{
-    IconURLs iconURLs = urlsForTypes(Favicon);
-    return iconURLs.isEmpty() ? KURL() : iconURLs[0].m_iconURL;
-}
-
-IconURL IconController::iconURL(IconType iconType) const
-{
-    IconURL result;
-    const Vector<IconURL>& iconURLs = m_frame->document()->iconURLs(iconType);
-    Vector<IconURL>::const_iterator iter(iconURLs.begin());
-    for (; iter != iconURLs.end(); ++iter) {
-        if (result.m_iconURL.isEmpty() || !iter->m_mimeType.isEmpty())
-            result = *iter;
-    }
-
-    return result;
-}
-
-IconURLs IconController::urlsForTypes(int iconTypesMask)
-{
-    IconURLs iconURLs;
-    if (m_frame->tree().parent())
-        return iconURLs;
-
-    if (iconTypesMask & Favicon && !appendToIconURLs(Favicon, &iconURLs))
-        iconURLs.append(defaultURL(Favicon));
-
-#if ENABLE(TOUCH_ICON_LOADING)
-    appendToIconURLs(TouchPrecomposedIcon, &iconURLs);
-    appendToIconURLs(TouchIcon, &iconURLs);
-#endif
-
-    // Finally, append all remaining icons of this type.
-    const Vector<IconURL>& allIconURLs = m_frame->document()->iconURLs(iconTypesMask);
-    for (Vector<IconURL>::const_iterator iter = allIconURLs.begin(); iter != allIconURLs.end(); ++iter) {
-        int i;
-        int iconCount = iconURLs.size();
-        for (i = 0; i < iconCount; ++i) {
-            if (*iter == iconURLs.at(i))
-                break;
-        }
-        if (i == iconCount)
-            iconURLs.append(*iter);
-    }
-
-    return iconURLs;
-}
-
-bool IconController::appendToIconURLs(IconType iconType, IconURLs* iconURLs)
-{
-    IconURL faviconURL = iconURL(iconType);
-    if (faviconURL.m_iconURL.isEmpty())
-        return false;
-
-    iconURLs->append(faviconURL);
-    return true;
-}
-
-IconURL IconController::defaultURL(IconType iconType)
-{
-    // Don't return a favicon iconURL unless we're http or https
-    KURL documentURL = m_frame->document()->url();
-    if (!documentURL.protocolIsInHTTPFamily())
-        return IconURL();
-
-    KURL url;
-    bool couldSetProtocol = url.setProtocol(documentURL.protocol());
-    ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
-    url.setHost(documentURL.host());
-    if (documentURL.hasPort())
-        url.setPort(documentURL.port());
-
-    if (iconType == Favicon) {
-        url.setPath("/favicon.ico");
-        return IconURL::defaultIconURL(url, Favicon);
-    }
-    return IconURL();
-}
-
-}
diff --git a/Source/core/loader/IconController.h b/Source/core/loader/IconController.h
deleted file mode 100644
index 87aa799..0000000
--- a/Source/core/loader/IconController.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) Research In Motion Limited 2009. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 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.
- */
-
-#ifndef IconController_h
-#define IconController_h
-
-#include "core/dom/IconURL.h"
-
-namespace WebCore {
-
-class Frame;
-class KURL;
-
-class IconController {
-    WTF_MAKE_NONCOPYABLE(IconController);
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    explicit IconController(Frame*);
-    ~IconController();
-
-    KURL url();
-    IconURLs urlsForTypes(int iconTypesMask);
-    IconURL iconURL(IconType) const;
-
-private:
-    bool appendToIconURLs(IconType, IconURLs*);
-    IconURL defaultURL(IconType);
-
-    Frame* m_frame;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/loader/ImageLoader.cpp b/Source/core/loader/ImageLoader.cpp
index c0b01f4..5be15e9 100644
--- a/Source/core/loader/ImageLoader.cpp
+++ b/Source/core/loader/ImageLoader.cpp
@@ -36,7 +36,7 @@
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/svg/RenderSVGImage.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/MixedContentChecker.cpp b/Source/core/loader/MixedContentChecker.cpp
index 8908cda..0b5f4fb 100644
--- a/Source/core/loader/MixedContentChecker.cpp
+++ b/Source/core/loader/MixedContentChecker.cpp
@@ -34,7 +34,7 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/NavigationAction.cpp b/Source/core/loader/NavigationAction.cpp
index 7e89752..b0cffda 100644
--- a/Source/core/loader/NavigationAction.cpp
+++ b/Source/core/loader/NavigationAction.cpp
@@ -60,19 +60,14 @@
     , m_type(navigationType(frameLoadType, isFormSubmission, event))
     , m_event(event)
 {
-}
-
-bool NavigationAction::specifiesNavigationPolicy(NavigationPolicy* policy) const
-{
-    const MouseEvent* event = 0;
+    const MouseEvent* mouseEvent = 0;
     if (m_type == NavigationTypeLinkClicked && m_event->isMouseEvent())
-        event = toMouseEvent(m_event.get());
+        mouseEvent = toMouseEvent(m_event.get());
     else if (m_type == NavigationTypeFormSubmitted && m_event && m_event->underlyingEvent() && m_event->underlyingEvent()->isMouseEvent())
-        event = toMouseEvent(m_event->underlyingEvent());
+        mouseEvent = toMouseEvent(m_event->underlyingEvent());
 
-    if (!event)
-        return false;
-    return navigationPolicyFromMouseEvent(event->button(), event->ctrlKey(), event->shiftKey(), event->altKey(), event->metaKey(), policy);
+    if (!mouseEvent || !navigationPolicyFromMouseEvent(mouseEvent->button(), mouseEvent->ctrlKey(), mouseEvent->shiftKey(), mouseEvent->altKey(), mouseEvent->metaKey(), &m_policy))
+        m_policy = NavigationPolicyCurrentTab;
 }
 
 }
diff --git a/Source/core/loader/NavigationAction.h b/Source/core/loader/NavigationAction.h
index 1c11cf6..e50716b 100644
--- a/Source/core/loader/NavigationAction.h
+++ b/Source/core/loader/NavigationAction.h
@@ -33,7 +33,7 @@
 #include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/NavigationPolicy.h"
 #include "platform/network/ResourceRequest.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
@@ -46,13 +46,14 @@
         const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
         NavigationType type() const { return m_type; }
         Event* event() const { return m_event.get(); }
-
-        bool specifiesNavigationPolicy(NavigationPolicy*) const;
+        NavigationPolicy policy() const { return m_policy; }
+        bool shouldOpenInNewWindow() const { return m_policy != NavigationPolicyCurrentTab; }
 
     private:
         ResourceRequest m_resourceRequest;
         NavigationType m_type;
         RefPtr<Event> m_event;
+        NavigationPolicy m_policy;
     };
 
 }
diff --git a/Source/core/loader/NavigationScheduler.cpp b/Source/core/loader/NavigationScheduler.cpp
index e374a4e..5c2b2a4 100644
--- a/Source/core/loader/NavigationScheduler.cpp
+++ b/Source/core/loader/NavigationScheduler.cpp
@@ -70,11 +70,9 @@
     virtual void fire(Frame*) = 0;
 
     virtual bool shouldStartTimer(Frame*) { return true; }
-    virtual void didStartTimer(Frame*, Timer<NavigationScheduler>*) { }
 
     double delay() const { return m_delay; }
     bool lockBackForwardList() const { return m_lockBackForwardList; }
-    void setLockBackForwardList(bool lockBackForwardList) { m_lockBackForwardList = lockBackForwardList; }
     bool isLocationChange() const { return m_isLocationChange; }
     PassOwnPtr<UserGestureIndicator> createUserGestureIndicator()
     {
@@ -103,7 +101,6 @@
         , m_securityOrigin(securityOrigin)
         , m_url(url)
         , m_referrer(referrer)
-        , m_haveToldClient(false)
     {
     }
 
@@ -116,17 +113,6 @@
         frame->loader().load(request);
     }
 
-    virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
-    {
-        if (m_haveToldClient)
-            return;
-        m_haveToldClient = true;
-
-        OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        if (frame->loader().history()->currentItemShouldBeReplaced())
-            setLockBackForwardList(true);
-    }
-
     SecurityOrigin* securityOrigin() const { return m_securityOrigin.get(); }
     String url() const { return m_url; }
     String referrer() const { return m_referrer; }
@@ -135,7 +121,6 @@
     RefPtr<SecurityOrigin> m_securityOrigin;
     String m_url;
     String m_referrer;
-    bool m_haveToldClient;
 };
 
 class ScheduledRedirect : public ScheduledURLNavigation {
@@ -217,7 +202,6 @@
     ScheduledFormSubmission(PassRefPtr<FormSubmission> submission, bool lockBackForwardList)
         : ScheduledNavigation(0, lockBackForwardList, true)
         , m_submission(submission)
-        , m_haveToldClient(false)
     {
         ASSERT(m_submission->state());
     }
@@ -233,23 +217,11 @@
         frame->loader().load(frameRequest);
     }
 
-    virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
-    {
-        if (m_haveToldClient)
-            return;
-        m_haveToldClient = true;
-
-        OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        if (frame->loader().history()->currentItemShouldBeReplaced())
-            setLockBackForwardList(true);
-    }
-
     virtual bool isForm() const { return true; }
     FormSubmission* submission() const { return m_submission.get(); }
 
 private:
     RefPtr<FormSubmission> m_submission;
-    bool m_haveToldClient;
 };
 
 NavigationScheduler::NavigationScheduler(Frame* frame)
@@ -273,7 +245,6 @@
         InspectorInstrumentation::frameClearedScheduledNavigation(m_frame);
     m_timer.stop();
     m_redirect.clear();
-    m_additionalFormSubmissions.clear();
 }
 
 inline bool NavigationScheduler::shouldScheduleNavigation() const
@@ -307,6 +278,14 @@
     if (!UserGestureIndicator::processingUserGesture() && !targetFrame->document()->loadEventFinished())
         return true;
 
+    // From the HTML5 spec for location.assign():
+    //  "If the browsing context's session history contains only one Document,
+    //   and that was the about:blank Document created when the browsing context
+    //   was created, then the navigation must be done with replacement enabled."
+    if (!targetFrame->loader().stateMachine()->committedMultipleRealLoads()
+        && equalIgnoringCase(targetFrame->document()->url(), blankURL()))
+        return true;
+
     // Navigation of a subframe during loading of an ancestor frame does not create a new back/forward item.
     // The definition of "during load" is any time before all handlers for the load event have been run.
     // See https://bugs.webkit.org/show_bug.cgi?id=14957 for the original motivation for this.
@@ -343,13 +322,6 @@
 void NavigationScheduler::scheduleFormSubmission(PassRefPtr<FormSubmission> submission)
 {
     ASSERT(m_frame->page());
-    if (m_redirect && m_redirect->isForm()) {
-        if (submission->target() != static_cast<ScheduledFormSubmission*>(m_redirect.get())->submission()->target()) {
-            const String& target = submission->target().isNull() ? "" : submission->target();
-            m_additionalFormSubmissions.add(target, adoptPtr(new ScheduledFormSubmission(submission, mustLockBackForwardList(m_frame))));
-            return;
-        }
-    }
     schedule(adoptPtr(new ScheduledFormSubmission(submission, mustLockBackForwardList(m_frame))));
 }
 
@@ -393,15 +365,7 @@
     RefPtr<Frame> protect(m_frame);
 
     OwnPtr<ScheduledNavigation> redirect(m_redirect.release());
-    HashMap<String, OwnPtr<ScheduledNavigation> > additionalFormSubmissions;
-    additionalFormSubmissions.swap(m_additionalFormSubmissions);
     redirect->fire(m_frame);
-    while (!additionalFormSubmissions.isEmpty()) {
-        HashMap<String, OwnPtr<ScheduledNavigation> >::iterator it = additionalFormSubmissions.begin();
-        OwnPtr<ScheduledNavigation> formSubmission = it->value.release();
-        additionalFormSubmissions.remove(it);
-        formSubmission->fire(m_frame);
-    }
     InspectorInstrumentation::frameClearedScheduledNavigation(m_frame);
 }
 
@@ -425,7 +389,6 @@
         return;
 
     m_timer.startOneShot(m_redirect->delay());
-    m_redirect->didStartTimer(m_frame, &m_timer);
     InspectorInstrumentation::frameScheduledNavigation(m_frame, m_redirect->delay());
 }
 
@@ -435,7 +398,6 @@
         InspectorInstrumentation::frameClearedScheduledNavigation(m_frame);
     m_timer.stop();
     m_redirect.clear();
-    m_additionalFormSubmissions.clear();
 }
 
 } // namespace WebCore
diff --git a/Source/core/loader/NavigationScheduler.h b/Source/core/loader/NavigationScheduler.h
index cc5059a..dbbee95 100644
--- a/Source/core/loader/NavigationScheduler.h
+++ b/Source/core/loader/NavigationScheduler.h
@@ -98,7 +98,6 @@
     Frame* m_frame;
     Timer<NavigationScheduler> m_timer;
     OwnPtr<ScheduledNavigation> m_redirect;
-    HashMap<String, OwnPtr<ScheduledNavigation> > m_additionalFormSubmissions;
 };
 
 } // namespace WebCore
diff --git a/Source/core/loader/PingLoader.cpp b/Source/core/loader/PingLoader.cpp
index ff4bbd2..d382e00 100644
--- a/Source/core/loader/PingLoader.cpp
+++ b/Source/core/loader/PingLoader.cpp
@@ -42,10 +42,10 @@
 #include "platform/network/FormData.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebURLLoader.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/UnusedParam.h"
 
@@ -59,7 +59,7 @@
     }
 
     ResourceRequest request(url);
-    request.setTargetType(ResourceRequest::TargetIsImage);
+    request.setTargetType(ResourceRequest::TargetIsPing);
     request.setHTTPHeaderField("Cache-Control", "max-age=0");
     String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), request.url(), frame->loader().outgoingReferrer());
     if (!referrer.isEmpty())
@@ -76,7 +76,7 @@
 void PingLoader::sendPing(Frame* frame, const KURL& pingURL, const KURL& destinationURL)
 {
     ResourceRequest request(pingURL);
-    request.setTargetType(ResourceRequest::TargetIsSubresource);
+    request.setTargetType(ResourceRequest::TargetIsPing);
     request.setHTTPMethod("POST");
     request.setHTTPContentType("text/ping");
     request.setHTTPBody(FormData::create("PING"));
@@ -127,9 +127,9 @@
     frame->loader().client()->didDispatchPingLoader(request.url());
 
     unsigned long identifier = createUniqueIdentifier();
-    m_loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
+    m_loader = adoptPtr(blink::Platform::current()->createURLLoader());
     ASSERT(m_loader);
-    WebKit::WrappedResourceRequest wrappedRequest(request);
+    blink::WrappedResourceRequest wrappedRequest(request);
     wrappedRequest.setAllowStoredCredentials(credentialsAllowed == AllowStoredCredentials);
     m_loader->loadAsynchronously(wrappedRequest, this);
 
diff --git a/Source/core/loader/PingLoader.h b/Source/core/loader/PingLoader.h
index 45ef227..e22f84c 100644
--- a/Source/core/loader/PingLoader.h
+++ b/Source/core/loader/PingLoader.h
@@ -53,7 +53,7 @@
 // to allow the load to live long enough to ensure the message was actually sent.
 // Therefore, as soon as a callback is received from the ResourceHandle, this class
 // will cancel the load and delete itself.
-class PingLoader : private WebKit::WebURLLoaderClient {
+class PingLoader : private blink::WebURLLoaderClient {
     WTF_MAKE_NONCOPYABLE(PingLoader); WTF_MAKE_FAST_ALLOCATED;
 public:
     enum ViolationReportType {
@@ -70,13 +70,13 @@
 private:
     PingLoader(Frame*, ResourceRequest&, StoredCredentials = AllowStoredCredentials);
 
-    virtual void didReceiveResponse(WebKit::WebURLLoader*, const WebKit::WebURLResponse&) OVERRIDE { delete this; }
-    virtual void didReceiveData(WebKit::WebURLLoader*, const char*, int, int) OVERRIDE { delete this; }
-    virtual void didFinishLoading(WebKit::WebURLLoader*, double) OVERRIDE { delete this; }
-    virtual void didFail(WebKit::WebURLLoader*, const WebKit::WebURLError&) OVERRIDE { delete this; }
+    virtual void didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&) OVERRIDE { delete this; }
+    virtual void didReceiveData(blink::WebURLLoader*, const char*, int, int) OVERRIDE { delete this; }
+    virtual void didFinishLoading(blink::WebURLLoader*, double) OVERRIDE { delete this; }
+    virtual void didFail(blink::WebURLLoader*, const blink::WebURLError&) OVERRIDE { delete this; }
     void timeout(Timer<PingLoader>*) { delete this; }
 
-    OwnPtr<WebKit::WebURLLoader> m_loader;
+    OwnPtr<blink::WebURLLoader> m_loader;
     Timer<PingLoader> m_timeout;
 };
 
diff --git a/Source/core/loader/PrerenderHandle.cpp b/Source/core/loader/PrerenderHandle.cpp
index e68a9b3..b00c785 100644
--- a/Source/core/loader/PrerenderHandle.cpp
+++ b/Source/core/loader/PrerenderHandle.cpp
@@ -36,8 +36,8 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/PrerendererClient.h"
 #include "platform/Prerender.h"
-#include "weborigin/ReferrerPolicy.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/weborigin/ReferrerPolicy.h"
+#include "platform/weborigin/SecurityPolicy.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/PrerenderHandle.h b/Source/core/loader/PrerenderHandle.h
index 1bf5d48..2adc058 100644
--- a/Source/core/loader/PrerenderHandle.h
+++ b/Source/core/loader/PrerenderHandle.h
@@ -32,7 +32,7 @@
 #define PrerenderHandle_h
 
 #include "core/dom/DocumentLifecycleObserver.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
diff --git a/Source/core/loader/SinkDocument.cpp b/Source/core/loader/SinkDocument.cpp
index 11839f7..990b71a 100644
--- a/Source/core/loader/SinkDocument.cpp
+++ b/Source/core/loader/SinkDocument.cpp
@@ -44,7 +44,7 @@
     }
 
     // Ignore all data.
-    virtual size_t appendBytes(const char*, size_t) OVERRIDE { return 0; }
+    virtual void appendBytes(const char*, size_t) OVERRIDE { }
 };
 
 SinkDocument::SinkDocument(const DocumentInit& initializer)
diff --git a/Source/core/loader/SubstituteData.h b/Source/core/loader/SubstituteData.h
index 1fff159..2a8f960 100644
--- a/Source/core/loader/SubstituteData.h
+++ b/Source/core/loader/SubstituteData.h
@@ -27,7 +27,7 @@
 #define SubstituteData_h
 
 #include "platform/SharedBuffer.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/loader/TextResourceDecoderBuilder.cpp b/Source/core/loader/TextResourceDecoderBuilder.cpp
index 0076f61..7ef6da4 100644
--- a/Source/core/loader/TextResourceDecoderBuilder.cpp
+++ b/Source/core/loader/TextResourceDecoderBuilder.cpp
@@ -34,7 +34,7 @@
 #include "core/dom/Document.h"
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
@@ -56,7 +56,7 @@
 }
 
 
-inline PassRefPtr<TextResourceDecoder> TextResourceDecoderBuilder::createDecoderInstance(Document* document)
+inline PassOwnPtr<TextResourceDecoder> TextResourceDecoderBuilder::createDecoderInstance(Document* document)
 {
     if (Frame* frame = document->frame()) {
         if (Settings* settings = frame->settings())
@@ -84,17 +84,18 @@
     // FIXME: This might be too cautious for non-7bit-encodings and
     // we may consider relaxing this later after testing.
     if (frame && canReferToParentFrameEncoding(frame, parentFrame)) {
-        decoder->setHintEncoding(parentFrame->document()->decoder());
+        if (parentFrame->document()->encodingWasDetectedHeuristically())
+            decoder->setHintEncoding(parentFrame->document()->encoding());
+
         if (m_encoding.isEmpty())
             decoder->setEncoding(parentFrame->document()->inputEncoding(), TextResourceDecoder::EncodingFromParentFrame);
     }
 }
 
-PassRefPtr<TextResourceDecoder> TextResourceDecoderBuilder::buildFor(Document* document)
+PassOwnPtr<TextResourceDecoder> TextResourceDecoderBuilder::buildFor(Document* document)
 {
-    RefPtr<TextResourceDecoder> decoder = createDecoderInstance(document);
+    OwnPtr<TextResourceDecoder> decoder = createDecoderInstance(document);
     setupEncoding(decoder.get(), document);
-    document->setDecoder(decoder);
     return decoder.release();
 }
 
diff --git a/Source/core/loader/TextResourceDecoderBuilder.h b/Source/core/loader/TextResourceDecoderBuilder.h
index c2a57b9..c592217 100644
--- a/Source/core/loader/TextResourceDecoderBuilder.h
+++ b/Source/core/loader/TextResourceDecoderBuilder.h
@@ -45,7 +45,7 @@
     TextResourceDecoderBuilder(const String& mimeType, const String& encoding, bool encodingUserChoosen);
     ~TextResourceDecoderBuilder();
 
-    PassRefPtr<TextResourceDecoder> buildFor(Document*);
+    PassOwnPtr<TextResourceDecoder> buildFor(Document*);
 
     const String& mimeType() const { return m_mimeType; }
     const String& encoding() const { return m_encoding; }
@@ -54,7 +54,7 @@
     void clear();
 
 private:
-    PassRefPtr<TextResourceDecoder> createDecoderInstance(Document*);
+    PassOwnPtr<TextResourceDecoder> createDecoderInstance(Document*);
     void setupEncoding(TextResourceDecoder*, Document*);
 
     String m_mimeType;
diff --git a/Source/core/loader/TextTrackLoader.cpp b/Source/core/loader/TextTrackLoader.cpp
index 18528b8..40bd0ff 100644
--- a/Source/core/loader/TextTrackLoader.cpp
+++ b/Source/core/loader/TextTrackLoader.cpp
@@ -32,10 +32,10 @@
 #include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ResourceFetcher.h"
-#include "core/html/track/WebVTTParser.h"
+#include "core/html/track/vtt/VTTParser.h"
 #include "platform/Logging.h"
 #include "platform/SharedBuffer.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
@@ -83,7 +83,7 @@
         return;
 
     if (!m_cueParser)
-        m_cueParser = WebVTTParser::create(this, m_document);
+        m_cueParser = VTTParser::create(this, m_document);
 
     m_cueParser->parseBytes(data, length);
 }
@@ -109,6 +109,9 @@
     if (m_state != Failed)
         m_state = resource->errorOccurred() ? Failed : Finished;
 
+    if (m_state == Finished && m_cueParser)
+        m_cueParser->flush();
+
     if (!m_cueLoadTimer.isActive())
         m_cueLoadTimer.startOneShot(0);
 
@@ -167,7 +170,7 @@
     cancelLoad();
 }
 
-void TextTrackLoader::getNewCues(Vector<RefPtr<TextTrackCue> >& outputCues)
+void TextTrackLoader::getNewCues(Vector<RefPtr<VTTCue> >& outputCues)
 {
     ASSERT(m_cueParser);
     if (m_cueParser)
diff --git a/Source/core/loader/TextTrackLoader.h b/Source/core/loader/TextTrackLoader.h
index 2f4a023..e9bcfcc 100644
--- a/Source/core/loader/TextTrackLoader.h
+++ b/Source/core/loader/TextTrackLoader.h
@@ -28,7 +28,7 @@
 
 #include "core/fetch/RawResource.h"
 #include "core/fetch/ResourcePtr.h"
-#include "core/html/track/WebVTTParser.h"
+#include "core/html/track/vtt/VTTParser.h"
 #include "platform/Timer.h"
 #include "wtf/OwnPtr.h"
 
@@ -46,7 +46,7 @@
     virtual void newRegionsAvailable(TextTrackLoader*) = 0;
 };
 
-class TextTrackLoader : public RawResourceClient, private WebVTTParserClient {
+class TextTrackLoader : public RawResourceClient, private VTTParserClient {
     WTF_MAKE_NONCOPYABLE(TextTrackLoader);
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -62,7 +62,7 @@
     enum State { Idle, Loading, Finished, Failed };
     State loadState() { return m_state; }
 
-    void getNewCues(Vector<RefPtr<TextTrackCue> >& outputCues);
+    void getNewCues(Vector<RefPtr<VTTCue> >& outputCues);
     void getNewRegions(Vector<RefPtr<VTTRegion> >& outputRegions);
 private:
 
@@ -70,7 +70,7 @@
     virtual void dataReceived(Resource*, const char* data, int length) OVERRIDE;
     virtual void notifyFinished(Resource*) OVERRIDE;
 
-    // WebVTTParserClient
+    // VTTParserClient
     virtual void newCuesParsed() OVERRIDE;
     virtual void newRegionsParsed() OVERRIDE;
     virtual void fileFailedToParse() OVERRIDE;
@@ -81,7 +81,7 @@
     void corsPolicyPreventedLoad();
 
     TextTrackLoaderClient& m_client;
-    OwnPtr<WebVTTParser> m_cueParser;
+    OwnPtr<VTTParser> m_cueParser;
     ResourcePtr<RawResource> m_resource;
     // FIXME: Remove this pointer and get the Document from m_client.
     Document& m_document;
diff --git a/Source/core/loader/ThreadableLoader.h b/Source/core/loader/ThreadableLoader.h
index 71316ae..645d85c 100644
--- a/Source/core/loader/ThreadableLoader.h
+++ b/Source/core/loader/ThreadableLoader.h
@@ -32,7 +32,7 @@
 #define ThreadableLoader_h
 
 #include "core/fetch/ResourceLoaderOptions.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/loader/WorkerThreadableLoader.cpp b/Source/core/loader/WorkerThreadableLoader.cpp
index d5b7725..8f4b201 100644
--- a/Source/core/loader/WorkerThreadableLoader.cpp
+++ b/Source/core/loader/WorkerThreadableLoader.cpp
@@ -110,11 +110,11 @@
     OwnPtr<ResourceRequest> request(ResourceRequest::adopt(requestData));
     request->setHTTPReferrer(outgoingReferrer);
     options.requestInitiatorContext = WorkerContext;
-    // FIXME: If the a site requests a local resource, then this will return a non-zero value but the sync path
-    // will return a 0 value.  Either this should return 0 or the other code path should do a callback with
-    // a failure.
     thisPtr->m_mainThreadLoader = DocumentThreadableLoader::create(document, thisPtr, *request, options);
-    ASSERT(thisPtr->m_mainThreadLoader);
+    if (!thisPtr->m_mainThreadLoader) {
+        // DocumentThreadableLoader::create may return 0 when the document loader has been already changed.
+        thisPtr->didFail(ResourceError(errorDomainWebKitInternal, 0, request->url().string(), "Can't create DocumentThreadableLoader"));
+    }
 }
 
 void WorkerThreadableLoader::MainThreadBridge::mainThreadDestroy(ExecutionContext* context, MainThreadBridge* thisPtr)
diff --git a/Source/core/loader/appcache/ApplicationCache.cpp b/Source/core/loader/appcache/ApplicationCache.cpp
index 460605a..3c765a6 100644
--- a/Source/core/loader/appcache/ApplicationCache.cpp
+++ b/Source/core/loader/appcache/ApplicationCache.cpp
@@ -70,18 +70,18 @@
     return cacheHost->status();
 }
 
-void ApplicationCache::update(ExceptionState& es)
+void ApplicationCache::update(ExceptionState& exceptionState)
 {
     ApplicationCacheHost* cacheHost = applicationCacheHost();
     if (!cacheHost || !cacheHost->update())
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("update", "ApplicationCache", "there is no application cache to update."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("update", "ApplicationCache", "there is no application cache to update."));
 }
 
-void ApplicationCache::swapCache(ExceptionState& es)
+void ApplicationCache::swapCache(ExceptionState& exceptionState)
 {
     ApplicationCacheHost* cacheHost = applicationCacheHost();
     if (!cacheHost || !cacheHost->swapCache())
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("swapCache", "ApplicationCache", "there is no newer application cache to swap to."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("swapCache", "ApplicationCache", "there is no newer application cache to swap to."));
 }
 
 void ApplicationCache::abort()
diff --git a/Source/core/loader/appcache/ApplicationCacheHost.h b/Source/core/loader/appcache/ApplicationCacheHost.h
index 8530fc1..1405589 100644
--- a/Source/core/loader/appcache/ApplicationCacheHost.h
+++ b/Source/core/loader/appcache/ApplicationCacheHost.h
@@ -31,7 +31,7 @@
 #ifndef ApplicationCacheHost_h
 #define ApplicationCacheHost_h
 
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Deque.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassRefPtr.h"
diff --git a/Source/core/loader/archive/ArchiveResource.cpp b/Source/core/loader/archive/ArchiveResource.cpp
deleted file mode 100644
index 07e3f1d..0000000
--- a/Source/core/loader/archive/ArchiveResource.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 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/loader/archive/ArchiveResource.h"
-
-#include "platform/SharedBuffer.h"
-
-namespace WebCore {
-
-inline ArchiveResource::ArchiveResource(PassRefPtr<SharedBuffer> data, const KURL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
-    : m_url(url)
-    , m_response(response)
-    , m_data(data)
-    , m_mimeType(mimeType)
-    , m_textEncoding(textEncoding)
-    , m_frameName(frameName)
-{
-    ASSERT(m_data);
-}
-
-PassRefPtr<ArchiveResource> ArchiveResource::create(PassRefPtr<SharedBuffer> data, const KURL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
-{
-    if (!data)
-        return 0;
-    if (response.isNull()) {
-        unsigned dataSize = data->size();
-        return adoptRef(new ArchiveResource(data, url, mimeType, textEncoding, frameName,
-            ResourceResponse(url, mimeType, dataSize, textEncoding, String())));
-    }
-    return adoptRef(new ArchiveResource(data, url, mimeType, textEncoding, frameName, response));
-}
-
-PassRefPtr<ArchiveResource> ArchiveResource::create(PassRefPtr<SharedBuffer> data, const KURL& url, const ResourceResponse& response)
-{
-    return create(data, url, response.mimeType(), response.textEncodingName(), String(), response);
-}
-
-}
diff --git a/Source/core/loader/archive/ArchiveResource.h b/Source/core/loader/archive/ArchiveResource.h
deleted file mode 100644
index 6686ff3..0000000
--- a/Source/core/loader/archive/ArchiveResource.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 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.
- */
-
-#ifndef ArchiveResource_h
-#define ArchiveResource_h
-
-#include "platform/SharedBuffer.h"
-#include "platform/network/ResourceResponse.h"
-#include "weborigin/KURL.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class ArchiveResource : public RefCounted<ArchiveResource> {
-public:
-    static PassRefPtr<ArchiveResource> create(PassRefPtr<SharedBuffer>, const KURL&, const ResourceResponse&);
-    static PassRefPtr<ArchiveResource> create(PassRefPtr<SharedBuffer>, const KURL&,
-        const String& mimeType, const String& textEncoding, const String& frameName,
-        const ResourceResponse& = ResourceResponse());
-
-    const KURL& url() const { return m_url; }
-    const ResourceResponse& response() const { return m_response; }
-    SharedBuffer* data() const { return m_data.get(); }
-    const String& mimeType() const { return m_mimeType; }
-    const String& textEncoding() const { return m_textEncoding; }
-    const String& frameName() const { return m_frameName; }
-
-private:
-    ArchiveResource(PassRefPtr<SharedBuffer>, const KURL&, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse&);
-
-    KURL m_url;
-    ResourceResponse m_response;
-    RefPtr<SharedBuffer> m_data;
-    String m_mimeType;
-    String m_textEncoding;
-    String m_frameName;
-};
-
-}
-
-#endif // ArchiveResource_h
diff --git a/Source/core/loader/archive/ArchiveResourceCollection.cpp b/Source/core/loader/archive/ArchiveResourceCollection.cpp
deleted file mode 100644
index 06b2430..0000000
--- a/Source/core/loader/archive/ArchiveResourceCollection.cpp
+++ /dev/null
@@ -1,95 +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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 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/loader/archive/ArchiveResourceCollection.h"
-
-#include "weborigin/KURL.h"
-
-namespace WebCore {
-
-ArchiveResourceCollection::ArchiveResourceCollection()
-{
-}
-
-void ArchiveResourceCollection::addAllResources(MHTMLArchive* archive)
-{
-    ASSERT(archive);
-    if (!archive)
-        return;
-
-    const Vector<RefPtr<ArchiveResource> >& subresources = archive->subresources();
-    for (Vector<RefPtr<ArchiveResource> >::const_iterator iterator = subresources.begin(); iterator != subresources.end(); ++iterator)
-        m_subresources.set((*iterator)->url(), iterator->get());
-
-    const Vector<RefPtr<MHTMLArchive> >& subframes = archive->subframeArchives();
-    for (Vector<RefPtr<MHTMLArchive> >::const_iterator iterator = subframes.begin(); iterator != subframes.end(); ++iterator) {
-        RefPtr<MHTMLArchive> archive = *iterator;
-        ASSERT(archive->mainResource());
-
-        const String& frameName = archive->mainResource()->frameName();
-        if (!frameName.isNull())
-            m_subframes.set(frameName, archive.get());
-        else {
-            // In the MHTML case, frames don't have a name so we use the URL instead.
-            m_subframes.set(archive->mainResource()->url().string(), archive.get());
-        }
-    }
-}
-
-// FIXME: Adding a resource directly to a DocumentLoader/ArchiveResourceCollection seems like bad design, but is API some apps rely on.
-// Can we change the design in a manner that will let us deprecate that API without reducing functionality of those apps?
-void ArchiveResourceCollection::addResource(PassRefPtr<ArchiveResource> resource)
-{
-    ASSERT(resource);
-    if (!resource)
-        return;
-
-    const KURL& url = resource->url(); // get before passing PassRefPtr (which sets it to 0)
-    m_subresources.set(url, resource);
-}
-
-ArchiveResource* ArchiveResourceCollection::archiveResourceForURL(const KURL& url)
-{
-    ArchiveResource* resource = m_subresources.get(url);
-    if (!resource)
-        return 0;
-
-    return resource;
-}
-
-PassRefPtr<MHTMLArchive> ArchiveResourceCollection::popSubframeArchive(const String& frameName, const KURL& url)
-{
-    RefPtr<MHTMLArchive> archive = m_subframes.take(frameName);
-    if (archive)
-        return archive.release();
-
-    return m_subframes.take(url.string());
-}
-
-}
diff --git a/Source/core/loader/archive/ArchiveResourceCollection.h b/Source/core/loader/archive/ArchiveResourceCollection.h
deleted file mode 100644
index 4b66573..0000000
--- a/Source/core/loader/archive/ArchiveResourceCollection.h
+++ /dev/null
@@ -1,59 +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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 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.
- */
-
-#ifndef ArchiveResourceCollection_h
-#define ArchiveResourceCollection_h
-
-#include "core/loader/archive/ArchiveResource.h"
-#include "core/loader/archive/MHTMLArchive.h"
-#include "wtf/HashMap.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KURL;
-
-class ArchiveResourceCollection {
-    WTF_MAKE_NONCOPYABLE(ArchiveResourceCollection); WTF_MAKE_FAST_ALLOCATED;
-public:
-    ArchiveResourceCollection();
-
-    void addResource(PassRefPtr<ArchiveResource>);
-    void addAllResources(MHTMLArchive*);
-
-    ArchiveResource* archiveResourceForURL(const KURL&);
-    PassRefPtr<MHTMLArchive> popSubframeArchive(const String& frameName, const KURL&);
-
-private:
-    HashMap<String, RefPtr<ArchiveResource> > m_subresources;
-    HashMap<String, RefPtr<MHTMLArchive> > m_subframes;
-};
-
-}
-
-#endif
diff --git a/Source/core/loader/archive/DEPS b/Source/core/loader/archive/DEPS
deleted file mode 100644
index f91aaec..0000000
--- a/Source/core/loader/archive/DEPS
+++ /dev/null
@@ -1,9 +0,0 @@
-# Please run Tools/Scripts/check-blink-deps after modifying this file.
-
-include_rules = [
-    # core/loader/archive should not depend on anything in core,
-    # except for itself and core/platform.
-    "-core",
-    "+core/loader/archive",
-    "+core/platform",
-]
diff --git a/Source/core/loader/archive/MHTMLArchive.cpp b/Source/core/loader/archive/MHTMLArchive.cpp
deleted file mode 100644
index eef48bc..0000000
--- a/Source/core/loader/archive/MHTMLArchive.cpp
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * 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:
- *
- *     * 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/archive/MHTMLArchive.h"
-
-#include "core/loader/archive/MHTMLParser.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "platform/SerializedResource.h"
-#include "platform/SharedBuffer.h"
-#include "platform/text/QuotedPrintable.h"
-#include "weborigin/SchemeRegistry.h"
-#include "wtf/CryptographicallyRandomNumber.h"
-#include "wtf/DateMath.h"
-#include "wtf/GregorianDateTime.h"
-#include "wtf/text/Base64.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-const char* const quotedPrintable = "quoted-printable";
-const char* const base64 = "base64";
-const char* const binary = "binary";
-
-static String generateRandomBoundary()
-{
-    // Trying to generate random boundaries similar to IE/UnMHT (ex: ----=_NextPart_000_001B_01CC157B.96F808A0).
-    const size_t randomValuesLength = 10;
-    char randomValues[randomValuesLength];
-    cryptographicallyRandomValues(&randomValues, randomValuesLength);
-    StringBuilder stringBuilder;
-    stringBuilder.append("----=_NextPart_000_");
-    for (size_t i = 0; i < randomValuesLength; ++i) {
-        if (i == 2)
-            stringBuilder.append('_');
-        else if (i == 6)
-            stringBuilder.append('.');
-        stringBuilder.append(lowerNibbleToASCIIHexDigit(randomValues[i]));
-        stringBuilder.append(upperNibbleToASCIIHexDigit(randomValues[i]));
-    }
-    return stringBuilder.toString();
-}
-
-static String replaceNonPrintableCharacters(const String& text)
-{
-    StringBuilder stringBuilder;
-    for (size_t i = 0; i < text.length(); ++i) {
-        if (isASCIIPrintable(text[i]))
-            stringBuilder.append(text[i]);
-        else
-            stringBuilder.append('?');
-    }
-    return stringBuilder.toString();
-}
-
-MHTMLArchive::MHTMLArchive()
-{
-}
-
-MHTMLArchive::~MHTMLArchive()
-{
-    // Because all frames know about each other we need to perform a deep clearing of the archives graph.
-    clearAllSubframeArchives();
-}
-
-PassRefPtr<MHTMLArchive> MHTMLArchive::create()
-{
-    return adoptRef(new MHTMLArchive);
-}
-
-PassRefPtr<MHTMLArchive> MHTMLArchive::create(const KURL& url, SharedBuffer* data)
-{
-    // For security reasons we only load MHTML pages from local URLs.
-    if (!SchemeRegistry::shouldTreatURLSchemeAsLocal(url.protocol()))
-        return 0;
-
-    MHTMLParser parser(data);
-    RefPtr<MHTMLArchive> mainArchive = parser.parseArchive();
-    if (!mainArchive)
-        return 0; // Invalid MHTML file.
-
-    // Since MHTML is a flat format, we need to make all frames aware of all resources.
-    for (size_t i = 0; i < parser.frameCount(); ++i) {
-        RefPtr<MHTMLArchive> archive = parser.frameAt(i);
-        for (size_t j = 1; j < parser.frameCount(); ++j) {
-            if (i != j)
-                archive->addSubframeArchive(parser.frameAt(j));
-        }
-        for (size_t j = 0; j < parser.subResourceCount(); ++j)
-            archive->addSubresource(parser.subResourceAt(j));
-    }
-    return mainArchive.release();
-}
-
-PassRefPtr<SharedBuffer> MHTMLArchive::generateMHTMLData(const Vector<SerializedResource>& resources, EncodingPolicy encodingPolicy, const String& title, const String& mimeType)
-{
-    String boundary = generateRandomBoundary();
-    String endOfResourceBoundary = "--" + boundary + "\r\n";
-
-    GregorianDateTime now;
-    now.setToCurrentLocalTime();
-    String dateString = makeRFC2822DateString(now.weekDay(), now.monthDay(), now.month(), now.year(), now.hour(), now.minute(), now.second(), now.utcOffset() / 60);
-
-    StringBuilder stringBuilder;
-    stringBuilder.append("From: <Saved by WebKit>\r\n");
-    stringBuilder.append("Subject: ");
-    // We replace non ASCII characters with '?' characters to match IE's behavior.
-    stringBuilder.append(replaceNonPrintableCharacters(title));
-    stringBuilder.append("\r\nDate: ");
-    stringBuilder.append(dateString);
-    stringBuilder.append("\r\nMIME-Version: 1.0\r\n");
-    stringBuilder.append("Content-Type: multipart/related;\r\n");
-    stringBuilder.append("\ttype=\"");
-    stringBuilder.append(mimeType);
-    stringBuilder.append("\";\r\n");
-    stringBuilder.append("\tboundary=\"");
-    stringBuilder.append(boundary);
-    stringBuilder.append("\"\r\n\r\n");
-
-    // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it).
-    ASSERT(stringBuilder.toString().containsOnlyASCII());
-    CString asciiString = stringBuilder.toString().utf8();
-    RefPtr<SharedBuffer> mhtmlData = SharedBuffer::create();
-    mhtmlData->append(asciiString.data(), asciiString.length());
-
-    for (size_t i = 0; i < resources.size(); ++i) {
-        const SerializedResource& resource = resources[i];
-
-        stringBuilder.clear();
-        stringBuilder.append(endOfResourceBoundary);
-        stringBuilder.append("Content-Type: ");
-        stringBuilder.append(resource.mimeType);
-
-        const char* contentEncoding = 0;
-        if (encodingPolicy == UseBinaryEncoding)
-            contentEncoding = binary;
-        else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(resource.mimeType) || MIMETypeRegistry::isSupportedNonImageMIMEType(resource.mimeType))
-            contentEncoding = quotedPrintable;
-        else
-            contentEncoding = base64;
-
-        stringBuilder.append("\r\nContent-Transfer-Encoding: ");
-        stringBuilder.append(contentEncoding);
-        stringBuilder.append("\r\nContent-Location: ");
-        stringBuilder.append(resource.url);
-        stringBuilder.append("\r\n\r\n");
-
-        asciiString = stringBuilder.toString().utf8();
-        mhtmlData->append(asciiString.data(), asciiString.length());
-
-        if (!strcmp(contentEncoding, binary)) {
-            const char* data;
-            size_t position = 0;
-            while (size_t length = resource.data->getSomeData(data, position)) {
-                mhtmlData->append(data, length);
-                position += length;
-            }
-        } else {
-            // FIXME: ideally we would encode the content as a stream without having to fetch it all.
-            const char* data = resource.data->data();
-            size_t dataLength = resource.data->size();
-            Vector<char> encodedData;
-            if (!strcmp(contentEncoding, quotedPrintable)) {
-                quotedPrintableEncode(data, dataLength, encodedData);
-                mhtmlData->append(encodedData.data(), encodedData.size());
-                mhtmlData->append("\r\n", 2);
-            } else {
-                ASSERT(!strcmp(contentEncoding, base64));
-                // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs.
-                base64Encode(data, dataLength, encodedData);
-                const size_t maximumLineLength = 76;
-                size_t index = 0;
-                size_t encodedDataLength = encodedData.size();
-                do {
-                    size_t lineLength = std::min(encodedDataLength - index, maximumLineLength);
-                    mhtmlData->append(encodedData.data() + index, lineLength);
-                    mhtmlData->append("\r\n", 2);
-                    index += maximumLineLength;
-                } while (index < encodedDataLength);
-            }
-        }
-    }
-
-    asciiString = String("--" + boundary + "--\r\n").utf8();
-    mhtmlData->append(asciiString.data(), asciiString.length());
-
-    return mhtmlData.release();
-}
-
-void MHTMLArchive::clearAllSubframeArchives()
-{
-    Vector<RefPtr<MHTMLArchive> > clearedArchives;
-    clearAllSubframeArchivesImpl(&clearedArchives);
-}
-
-void MHTMLArchive::clearAllSubframeArchivesImpl(Vector<RefPtr<MHTMLArchive> >* clearedArchives)
-{
-    for (Vector<RefPtr<MHTMLArchive> >::iterator it = m_subframeArchives.begin(); it != m_subframeArchives.end(); ++it) {
-        if (!clearedArchives->contains(*it)) {
-            clearedArchives->append(*it);
-            (*it)->clearAllSubframeArchivesImpl(clearedArchives);
-        }
-    }
-    m_subframeArchives.clear();
-}
-
-}
diff --git a/Source/core/loader/archive/MHTMLArchive.h b/Source/core/loader/archive/MHTMLArchive.h
deleted file mode 100644
index 60b7dbf..0000000
--- a/Source/core/loader/archive/MHTMLArchive.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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:
- *
- *     * 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 MHTMLArchive_h
-#define MHTMLArchive_h
-
-#include "core/loader/archive/ArchiveResource.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class KURL;
-class MHTMLParser;
-class SharedBuffer;
-
-struct SerializedResource;
-
-class MHTMLArchive FINAL : public RefCounted<MHTMLArchive> {
-public:
-    static PassRefPtr<MHTMLArchive> create();
-    static PassRefPtr<MHTMLArchive> create(const KURL&, SharedBuffer*);
-
-    enum EncodingPolicy {
-        UseDefaultEncoding,
-        UseBinaryEncoding
-    };
-
-    // Binary encoding results in smaller MHTML files but they might not work in other browsers.
-    static PassRefPtr<SharedBuffer> generateMHTMLData(const Vector<SerializedResource>&, EncodingPolicy, const String& title, const String& mimeType);
-
-    ~MHTMLArchive();
-    ArchiveResource* mainResource() { return m_mainResource.get(); }
-    const Vector<RefPtr<ArchiveResource> >& subresources() const { return m_subresources; }
-    const Vector<RefPtr<MHTMLArchive> >& subframeArchives() const { return m_subframeArchives; }
-
-private:
-    friend class MHTMLParser;
-    MHTMLArchive();
-
-    void setMainResource(PassRefPtr<ArchiveResource> mainResource) { m_mainResource = mainResource; }
-    void addSubresource(PassRefPtr<ArchiveResource> subResource) { m_subresources.append(subResource); }
-    void addSubframeArchive(PassRefPtr<MHTMLArchive> subframeArchive) { m_subframeArchives.append(subframeArchive); }
-
-    void clearAllSubframeArchives();
-    void clearAllSubframeArchivesImpl(Vector<RefPtr<MHTMLArchive> >* clearedArchives);
-
-    RefPtr<ArchiveResource> m_mainResource;
-    Vector<RefPtr<ArchiveResource> > m_subresources;
-    Vector<RefPtr<MHTMLArchive> > m_subframeArchives;
-};
-
-}
-
-#endif
diff --git a/Source/core/loader/archive/MHTMLParser.cpp b/Source/core/loader/archive/MHTMLParser.cpp
deleted file mode 100644
index b306165..0000000
--- a/Source/core/loader/archive/MHTMLParser.cpp
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
- * 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:
- *
- *     * 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/archive/MHTMLParser.h"
-
-#include "core/loader/archive/MHTMLArchive.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "platform/SharedBufferChunkReader.h"
-#include "platform/network/ParsedContentType.h"
-#include "platform/text/QuotedPrintable.h"
-#include "wtf/HashMap.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/Base64.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/StringConcatenate.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// This class is a limited MIME parser used to parse the MIME headers of MHTML files.
-class MIMEHeader : public RefCounted<MIMEHeader> {
-public:
-    enum Encoding {
-        QuotedPrintable,
-        Base64,
-        EightBit,
-        SevenBit,
-        Binary,
-        Unknown
-    };
-
-    static PassRefPtr<MIMEHeader> parseHeader(SharedBufferChunkReader* crLFLineReader);
-
-    bool isMultipart() const { return m_contentType.startsWith("multipart/"); }
-
-    String contentType() const { return m_contentType; }
-    String charset() const { return m_charset; }
-    Encoding contentTransferEncoding() const { return m_contentTransferEncoding; }
-    String contentLocation() const { return m_contentLocation; }
-
-    // Multi-part type and boundaries are only valid for multipart MIME headers.
-    String multiPartType() const { return m_multipartType; }
-    String endOfPartBoundary() const { return m_endOfPartBoundary; }
-    String endOfDocumentBoundary() const { return m_endOfDocumentBoundary; }
-
-private:
-    MIMEHeader();
-
-    static Encoding parseContentTransferEncoding(const String&);
-
-    String m_contentType;
-    String m_charset;
-    Encoding m_contentTransferEncoding;
-    String m_contentLocation;
-    String m_multipartType;
-    String m_endOfPartBoundary;
-    String m_endOfDocumentBoundary;
-};
-
-typedef HashMap<String, String> KeyValueMap;
-
-static KeyValueMap retrieveKeyValuePairs(WebCore::SharedBufferChunkReader* buffer)
-{
-    KeyValueMap keyValuePairs;
-    String line;
-    String key;
-    StringBuilder value;
-    while (!(line = buffer->nextChunkAsUTF8StringWithLatin1Fallback()).isNull()) {
-        if (line.isEmpty())
-            break; // Empty line means end of key/value section.
-        if (line[0] == '\t') {
-            ASSERT(!key.isEmpty());
-            value.append(line.substring(1));
-            continue;
-        }
-        // New key/value, store the previous one if any.
-        if (!key.isEmpty()) {
-            if (keyValuePairs.find(key) != keyValuePairs.end())
-                LOG_ERROR("Key duplicate found in MIME header. Key is '%s', previous value replaced.", key.ascii().data());
-            keyValuePairs.add(key, value.toString().stripWhiteSpace());
-            key = String();
-            value.clear();
-        }
-        size_t semiColonIndex = line.find(':');
-        if (semiColonIndex == kNotFound) {
-            // This is not a key value pair, ignore.
-            continue;
-        }
-        key = line.substring(0, semiColonIndex).lower().stripWhiteSpace();
-        value.append(line.substring(semiColonIndex + 1));
-    }
-    // Store the last property if there is one.
-    if (!key.isEmpty())
-        keyValuePairs.set(key, value.toString().stripWhiteSpace());
-    return keyValuePairs;
-}
-
-PassRefPtr<MIMEHeader> MIMEHeader::parseHeader(SharedBufferChunkReader* buffer)
-{
-    RefPtr<MIMEHeader> mimeHeader = adoptRef(new MIMEHeader);
-    KeyValueMap keyValuePairs = retrieveKeyValuePairs(buffer);
-    KeyValueMap::iterator mimeParametersIterator = keyValuePairs.find("content-type");
-    if (mimeParametersIterator != keyValuePairs.end()) {
-        ParsedContentType parsedContentType(mimeParametersIterator->value);
-        mimeHeader->m_contentType = parsedContentType.mimeType();
-        if (!mimeHeader->isMultipart()) {
-            mimeHeader->m_charset = parsedContentType.charset().stripWhiteSpace();
-        } else {
-            mimeHeader->m_multipartType = parsedContentType.parameterValueForName("type");
-            mimeHeader->m_endOfPartBoundary = parsedContentType.parameterValueForName("boundary");
-            if (mimeHeader->m_endOfPartBoundary.isNull()) {
-                LOG_ERROR("No boundary found in multipart MIME header.");
-                return 0;
-            }
-            mimeHeader->m_endOfPartBoundary.insert("--", 0);
-            mimeHeader->m_endOfDocumentBoundary = mimeHeader->m_endOfPartBoundary;
-            mimeHeader->m_endOfDocumentBoundary.append("--");
-        }
-    }
-
-    mimeParametersIterator = keyValuePairs.find("content-transfer-encoding");
-    if (mimeParametersIterator != keyValuePairs.end())
-        mimeHeader->m_contentTransferEncoding = parseContentTransferEncoding(mimeParametersIterator->value);
-
-    mimeParametersIterator = keyValuePairs.find("content-location");
-    if (mimeParametersIterator != keyValuePairs.end())
-        mimeHeader->m_contentLocation = mimeParametersIterator->value;
-
-    return mimeHeader.release();
-}
-
-MIMEHeader::Encoding MIMEHeader::parseContentTransferEncoding(const String& text)
-{
-    String encoding = text.stripWhiteSpace().lower();
-    if (encoding == "base64")
-        return Base64;
-    if (encoding == "quoted-printable")
-        return QuotedPrintable;
-    if (encoding == "8bit")
-        return EightBit;
-    if (encoding == "7bit")
-        return SevenBit;
-    if (encoding == "binary")
-        return Binary;
-    LOG_ERROR("Unknown encoding '%s' found in MIME header.", text.ascii().data());
-    return Unknown;
-}
-
-MIMEHeader::MIMEHeader()
-    : m_contentTransferEncoding(Unknown)
-{
-}
-
-static bool skipLinesUntilBoundaryFound(SharedBufferChunkReader& lineReader, const String& boundary)
-{
-    String line;
-    while (!(line = lineReader.nextChunkAsUTF8StringWithLatin1Fallback()).isNull()) {
-        if (line == boundary)
-            return true;
-    }
-    return false;
-}
-
-MHTMLParser::MHTMLParser(SharedBuffer* data)
-    : m_lineReader(data, "\r\n")
-{
-}
-
-PassRefPtr<MHTMLArchive> MHTMLParser::parseArchive()
-{
-    RefPtr<MIMEHeader> header = MIMEHeader::parseHeader(&m_lineReader);
-    return parseArchiveWithHeader(header.get());
-}
-
-PassRefPtr<MHTMLArchive> MHTMLParser::parseArchiveWithHeader(MIMEHeader* header)
-{
-    if (!header) {
-        LOG_ERROR("Failed to parse MHTML part: no header.");
-        return 0;
-    }
-
-    RefPtr<MHTMLArchive> archive = MHTMLArchive::create();
-    if (!header->isMultipart()) {
-        // With IE a page with no resource is not multi-part.
-        bool endOfArchiveReached = false;
-        RefPtr<ArchiveResource> resource = parseNextPart(*header, String(), String(), endOfArchiveReached);
-        if (!resource)
-            return 0;
-        archive->setMainResource(resource);
-        return archive;
-    }
-
-    // Skip the message content (it's a generic browser specific message).
-    skipLinesUntilBoundaryFound(m_lineReader, header->endOfPartBoundary());
-
-    bool endOfArchive = false;
-    while (!endOfArchive) {
-        RefPtr<MIMEHeader> resourceHeader = MIMEHeader::parseHeader(&m_lineReader);
-        if (!resourceHeader) {
-            LOG_ERROR("Failed to parse MHTML, invalid MIME header.");
-            return 0;
-        }
-        if (resourceHeader->contentType() == "multipart/alternative") {
-            // Ignore IE nesting which makes little sense (IE seems to nest only some of the frames).
-            RefPtr<MHTMLArchive> subframeArchive = parseArchiveWithHeader(resourceHeader.get());
-            if (!subframeArchive) {
-                LOG_ERROR("Failed to parse MHTML subframe.");
-                return 0;
-            }
-            bool endOfPartReached = skipLinesUntilBoundaryFound(m_lineReader, header->endOfPartBoundary());
-            ASSERT_UNUSED(endOfPartReached, endOfPartReached);
-            // The top-frame is the first frame found, regardless of the nesting level.
-            if (subframeArchive->mainResource())
-                addResourceToArchive(subframeArchive->mainResource(), archive.get());
-            archive->addSubframeArchive(subframeArchive);
-            continue;
-        }
-
-        RefPtr<ArchiveResource> resource = parseNextPart(*resourceHeader, header->endOfPartBoundary(), header->endOfDocumentBoundary(), endOfArchive);
-        if (!resource) {
-            LOG_ERROR("Failed to parse MHTML part.");
-            return 0;
-        }
-        addResourceToArchive(resource.get(), archive.get());
-    }
-
-    return archive.release();
-}
-
-void MHTMLParser::addResourceToArchive(ArchiveResource* resource, MHTMLArchive* archive)
-{
-    const String& mimeType = resource->mimeType();
-    if (!MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType) || MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType) || mimeType == "text/css") {
-        m_resources.append(resource);
-        return;
-    }
-
-    // The first document suitable resource is the main frame.
-    if (!archive->mainResource()) {
-        archive->setMainResource(resource);
-        m_frames.append(archive);
-        return;
-    }
-
-    RefPtr<MHTMLArchive> subframe = MHTMLArchive::create();
-    subframe->setMainResource(resource);
-    m_frames.append(subframe);
-}
-
-PassRefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, const String& endOfPartBoundary, const String& endOfDocumentBoundary, bool& endOfArchiveReached)
-{
-    ASSERT(endOfPartBoundary.isEmpty() == endOfDocumentBoundary.isEmpty());
-
-    // If no content transfer encoding is specified, default to binary encoding.
-    MIMEHeader::Encoding contentTransferEncoding = mimeHeader.contentTransferEncoding();
-    if (contentTransferEncoding == MIMEHeader::Unknown)
-        contentTransferEncoding = MIMEHeader::Binary;
-
-    RefPtr<SharedBuffer> content = SharedBuffer::create();
-    const bool checkBoundary = !endOfPartBoundary.isEmpty();
-    bool endOfPartReached = false;
-    if (contentTransferEncoding == MIMEHeader::Binary) {
-        if (!checkBoundary) {
-            LOG_ERROR("Binary contents requires end of part");
-            return 0;
-        }
-        m_lineReader.setSeparator(endOfPartBoundary.utf8().data());
-        Vector<char> part;
-        if (!m_lineReader.nextChunk(part)) {
-            LOG_ERROR("Binary contents requires end of part");
-            return 0;
-         }
-         content->append(part);
-         m_lineReader.setSeparator("\r\n");
-         Vector<char> nextChars;
-         if (m_lineReader.peek(nextChars, 2) != 2) {
-             LOG_ERROR("Invalid seperator.");
-             return 0;
-         }
-         endOfPartReached = true;
-         ASSERT(nextChars.size() == 2);
-         endOfArchiveReached = (nextChars[0] == '-' && nextChars[1] == '-');
-         if (!endOfArchiveReached) {
-             String line = m_lineReader.nextChunkAsUTF8StringWithLatin1Fallback();
-             if (!line.isEmpty()) {
-                 LOG_ERROR("No CRLF at end of binary section.");
-                 return 0;
-             }
-         }
-    } else {
-        String line;
-        while (!(line = m_lineReader.nextChunkAsUTF8StringWithLatin1Fallback()).isNull()) {
-            endOfArchiveReached = (line == endOfDocumentBoundary);
-            if (checkBoundary && (line == endOfPartBoundary || endOfArchiveReached)) {
-                endOfPartReached = true;
-                break;
-            }
-            // Note that we use line.utf8() and not line.ascii() as ascii turns special characters (such as tab, line-feed...) into '?'.
-            content->append(line.utf8().data(), line.length());
-            if (contentTransferEncoding == MIMEHeader::QuotedPrintable) {
-                // The line reader removes the \r\n, but we need them for the content in this case as the QuotedPrintable decoder expects CR-LF terminated lines.
-                content->append("\r\n", 2);
-            }
-        }
-    }
-    if (!endOfPartReached && checkBoundary) {
-        LOG_ERROR("No bounday found for MHTML part.");
-        return 0;
-    }
-
-    Vector<char> data;
-    switch (contentTransferEncoding) {
-    case MIMEHeader::Base64:
-        if (!base64Decode(content->data(), content->size(), data)) {
-            LOG_ERROR("Invalid base64 content for MHTML part.");
-            return 0;
-        }
-        break;
-    case MIMEHeader::QuotedPrintable:
-        quotedPrintableDecode(content->data(), content->size(), data);
-        break;
-    case MIMEHeader::EightBit:
-    case MIMEHeader::SevenBit:
-    case MIMEHeader::Binary:
-        data.append(content->data(), content->size());
-        break;
-    default:
-        LOG_ERROR("Invalid encoding for MHTML part.");
-        return 0;
-    }
-    RefPtr<SharedBuffer> contentBuffer = SharedBuffer::adoptVector(data);
-    // FIXME: the URL in the MIME header could be relative, we should resolve it if it is.
-    // The specs mentions 5 ways to resolve a URL: http://tools.ietf.org/html/rfc2557#section-5
-    // IE and Firefox (UNMht) seem to generate only absolute URLs.
-    KURL location = KURL(KURL(), mimeHeader.contentLocation());
-    return ArchiveResource::create(contentBuffer, location, mimeHeader.contentType(), mimeHeader.charset(), String());
-}
-
-size_t MHTMLParser::frameCount() const
-{
-    return m_frames.size();
-}
-
-MHTMLArchive* MHTMLParser::frameAt(size_t index) const
-{
-    return m_frames[index].get();
-}
-
-size_t MHTMLParser::subResourceCount() const
-{
-    return m_resources.size();
-}
-
-ArchiveResource* MHTMLParser::subResourceAt(size_t index) const
-{
-    return m_resources[index].get();
-}
-
-}
diff --git a/Source/core/loader/archive/MHTMLParser.h b/Source/core/loader/archive/MHTMLParser.h
deleted file mode 100644
index 58333a7..0000000
--- a/Source/core/loader/archive/MHTMLParser.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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:
- *
- *     * 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 MHTMLParser_h
-#define MHTMLParser_h
-
-#include "platform/SharedBufferChunkReader.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class ArchiveResource;
-class MHTMLArchive;
-class MIMEHeader;
-class SharedBuffer;
-
-class MHTMLParser {
-public:
-    explicit MHTMLParser(SharedBuffer*);
-
-    PassRefPtr<MHTMLArchive> parseArchive();
-
-    size_t frameCount() const;
-    MHTMLArchive* frameAt(size_t) const;
-
-    size_t subResourceCount() const;
-    ArchiveResource* subResourceAt(size_t) const;
-
-private:
-    PassRefPtr<MHTMLArchive> parseArchiveWithHeader(MIMEHeader*);
-    PassRefPtr<ArchiveResource> parseNextPart(const MIMEHeader&, const String& endOfPartBoundary, const String& endOfDocumentBoundary, bool& endOfArchiveReached);
-
-    void addResourceToArchive(ArchiveResource*, MHTMLArchive*);
-
-    SharedBufferChunkReader m_lineReader;
-    Vector<RefPtr<ArchiveResource> > m_resources;
-    Vector<RefPtr<MHTMLArchive> > m_frames;
-};
-
-}
-
-#endif
-
diff --git a/Source/core/make_core_derived_sources.target.darwin-arm.mk b/Source/core/make_core_derived_sources.target.darwin-arm.mk
index 232e151..577f545 100644
--- a/Source/core/make_core_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_core_derived_sources.target.darwin-arm.mk
@@ -12,7 +12,8 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
 ### Rules for action "generateV8ArrayBufferViewCustomScript":
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
@@ -61,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -95,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -134,7 +135,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -157,7 +158,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -181,7 +182,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -190,9 +191,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -218,6 +219,17 @@
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
 
+### Rules for action "InputTypeNames":
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
+
 ### Rules for action "XLinkNames":
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -252,12 +264,22 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
 ### Rules for action "MakeTokenMatcher":
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
+
+
+### Rules for action "MakeParser":
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
 
@@ -271,6 +293,17 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
+### Rules for action "HTMLElementLookupTrie":
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
+
 
 
 ### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
@@ -342,14 +375,19 @@
 	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
+	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
 	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
@@ -370,14 +408,15 @@
 MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-fno-tree-sra \
 	-fuse-ld=gold \
 	-Wno-psabi \
@@ -392,10 +431,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
@@ -416,6 +451,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -428,6 +466,8 @@
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Debug := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -438,26 +478,27 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-abi \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 # Flags passed to both C and C++ files.
 MY_CFLAGS_Release := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-fno-tree-sra \
 	-fuse-ld=gold \
 	-Wno-psabi \
@@ -472,10 +513,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
@@ -496,6 +533,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -503,11 +543,14 @@
 	'-DCHROME_BUILD_ID=""' \
 	'-DNDEBUG' \
 	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
+	'-D_FORTIFY_SOURCE=2'
 
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Release := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -518,12 +561,12 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-abi \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
diff --git a/Source/core/make_core_derived_sources.target.darwin-mips.mk b/Source/core/make_core_derived_sources.target.darwin-mips.mk
index af2f092..5c41800 100644
--- a/Source/core/make_core_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_core_derived_sources.target.darwin-mips.mk
@@ -12,7 +12,8 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
 ### Rules for action "generateV8ArrayBufferViewCustomScript":
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
@@ -61,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -95,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -134,7 +135,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -157,7 +158,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -181,7 +182,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -190,9 +191,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -218,6 +219,17 @@
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
 
+### Rules for action "InputTypeNames":
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
+
 ### Rules for action "XLinkNames":
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -252,12 +264,22 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
 ### Rules for action "MakeTokenMatcher":
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
+
+
+### Rules for action "MakeParser":
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
 
@@ -271,6 +293,17 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
+### Rules for action "HTMLElementLookupTrie":
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
+
 
 
 ### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
@@ -342,14 +375,19 @@
 	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
+	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
 	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
@@ -373,12 +411,12 @@
 	 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-EL \
 	-mhard-float \
 	-ffunction-sections \
@@ -392,10 +430,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
@@ -416,6 +450,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -428,6 +465,8 @@
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Debug := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -438,12 +477,12 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-uninitialized \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 # Flags passed to both C and C++ files.
@@ -453,12 +492,12 @@
 	 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-EL \
 	-mhard-float \
 	-ffunction-sections \
@@ -472,10 +511,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
@@ -496,6 +531,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -503,11 +541,14 @@
 	'-DCHROME_BUILD_ID=""' \
 	'-DNDEBUG' \
 	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
+	'-D_FORTIFY_SOURCE=2'
 
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Release := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -518,12 +559,12 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-uninitialized \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
diff --git a/Source/core/make_core_derived_sources.target.darwin-x86.mk b/Source/core/make_core_derived_sources.target.darwin-x86.mk
index 9615d32..7f20990 100644
--- a/Source/core/make_core_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_core_derived_sources.target.darwin-x86.mk
@@ -12,7 +12,8 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
 ### Rules for action "generateV8ArrayBufferViewCustomScript":
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
@@ -61,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -95,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -134,7 +135,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -157,7 +158,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -181,7 +182,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -190,9 +191,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -218,6 +219,17 @@
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
 
+### Rules for action "InputTypeNames":
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
+
 ### Rules for action "XLinkNames":
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -252,12 +264,22 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
 ### Rules for action "MakeTokenMatcher":
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
+
+
+### Rules for action "MakeParser":
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
 
@@ -271,6 +293,17 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
+### Rules for action "HTMLElementLookupTrie":
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
+
 
 
 ### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
@@ -342,14 +375,19 @@
 	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
+	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
 	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
@@ -369,14 +407,15 @@
 # Flags passed to both C and C++ files.
 MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-m32 \
 	-mmmx \
 	-march=pentium4 \
@@ -394,10 +433,6 @@
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
 	-fno-stack-protector \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
@@ -418,6 +453,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -430,6 +468,8 @@
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Debug := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -440,24 +480,25 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 # Flags passed to both C and C++ files.
 MY_CFLAGS_Release := \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-m32 \
 	-mmmx \
 	-march=pentium4 \
@@ -475,10 +516,6 @@
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
 	-fno-stack-protector \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
@@ -501,6 +538,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -508,11 +548,14 @@
 	'-DCHROME_BUILD_ID=""' \
 	'-DNDEBUG' \
 	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
+	'-D_FORTIFY_SOURCE=2'
 
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Release := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -523,11 +566,11 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
diff --git a/Source/core/make_core_derived_sources.target.linux-arm.mk b/Source/core/make_core_derived_sources.target.linux-arm.mk
index 232e151..577f545 100644
--- a/Source/core/make_core_derived_sources.target.linux-arm.mk
+++ b/Source/core/make_core_derived_sources.target.linux-arm.mk
@@ -12,7 +12,8 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
 ### Rules for action "generateV8ArrayBufferViewCustomScript":
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
@@ -61,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -95,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -134,7 +135,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -157,7 +158,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -181,7 +182,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -190,9 +191,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -218,6 +219,17 @@
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
 
+### Rules for action "InputTypeNames":
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
+
 ### Rules for action "XLinkNames":
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -252,12 +264,22 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
 ### Rules for action "MakeTokenMatcher":
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
+
+
+### Rules for action "MakeParser":
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
 
@@ -271,6 +293,17 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
+### Rules for action "HTMLElementLookupTrie":
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
+
 
 
 ### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
@@ -342,14 +375,19 @@
 	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
+	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
 	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
@@ -370,14 +408,15 @@
 MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-fno-tree-sra \
 	-fuse-ld=gold \
 	-Wno-psabi \
@@ -392,10 +431,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
@@ -416,6 +451,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -428,6 +466,8 @@
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Debug := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -438,26 +478,27 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-abi \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 # Flags passed to both C and C++ files.
 MY_CFLAGS_Release := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-fno-tree-sra \
 	-fuse-ld=gold \
 	-Wno-psabi \
@@ -472,10 +513,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
@@ -496,6 +533,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -503,11 +543,14 @@
 	'-DCHROME_BUILD_ID=""' \
 	'-DNDEBUG' \
 	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
+	'-D_FORTIFY_SOURCE=2'
 
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Release := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -518,12 +561,12 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-abi \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
diff --git a/Source/core/make_core_derived_sources.target.linux-mips.mk b/Source/core/make_core_derived_sources.target.linux-mips.mk
index af2f092..5c41800 100644
--- a/Source/core/make_core_derived_sources.target.linux-mips.mk
+++ b/Source/core/make_core_derived_sources.target.linux-mips.mk
@@ -12,7 +12,8 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
 ### Rules for action "generateV8ArrayBufferViewCustomScript":
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
@@ -61,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -95,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -134,7 +135,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -157,7 +158,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -181,7 +182,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -190,9 +191,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -218,6 +219,17 @@
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
 
+### Rules for action "InputTypeNames":
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
+
 ### Rules for action "XLinkNames":
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -252,12 +264,22 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
 ### Rules for action "MakeTokenMatcher":
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
+
+
+### Rules for action "MakeParser":
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
 
@@ -271,6 +293,17 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
+### Rules for action "HTMLElementLookupTrie":
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
+
 
 
 ### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
@@ -342,14 +375,19 @@
 	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
+	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
 	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
@@ -373,12 +411,12 @@
 	 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-EL \
 	-mhard-float \
 	-ffunction-sections \
@@ -392,10 +430,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
@@ -416,6 +450,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -428,6 +465,8 @@
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Debug := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -438,12 +477,12 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-uninitialized \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 # Flags passed to both C and C++ files.
@@ -453,12 +492,12 @@
 	 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-EL \
 	-mhard-float \
 	-ffunction-sections \
@@ -472,10 +511,6 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
@@ -496,6 +531,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -503,11 +541,14 @@
 	'-DCHROME_BUILD_ID=""' \
 	'-DNDEBUG' \
 	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
+	'-D_FORTIFY_SOURCE=2'
 
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Release := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -518,12 +559,12 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-uninitialized \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
diff --git a/Source/core/make_core_derived_sources.target.linux-x86.mk b/Source/core/make_core_derived_sources.target.linux-x86.mk
index 9615d32..7f20990 100644
--- a/Source/core/make_core_derived_sources.target.linux-x86.mk
+++ b/Source/core/make_core_derived_sources.target.linux-x86.mk
@@ -12,7 +12,8 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
 ### Rules for action "generateV8ArrayBufferViewCustomScript":
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
@@ -61,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -95,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -134,7 +135,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -157,7 +158,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -181,7 +182,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -190,9 +191,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -218,6 +219,17 @@
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
 
+### Rules for action "InputTypeNames":
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
+
 ### Rules for action "XLinkNames":
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -252,12 +264,22 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
 ### Rules for action "MakeTokenMatcher":
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
+
+
+### Rules for action "MakeParser":
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
 
@@ -271,6 +293,17 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
+### Rules for action "HTMLElementLookupTrie":
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+
+$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
+
 
 
 ### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
@@ -342,14 +375,19 @@
 	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
+	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
+	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
+	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
 	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
@@ -369,14 +407,15 @@
 # Flags passed to both C and C++ files.
 MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-m32 \
 	-mmmx \
 	-march=pentium4 \
@@ -394,10 +433,6 @@
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
 	-fno-stack-protector \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
@@ -418,6 +453,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -430,6 +468,8 @@
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Debug := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -440,24 +480,25 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 # Flags passed to both C and C++ files.
 MY_CFLAGS_Release := \
 	--param=ssp-buffer-size=4 \
+	-Werror \
 	-fno-exceptions \
 	-fno-strict-aliasing \
+	-Wall \
 	-Wno-unused-parameter \
 	-Wno-missing-field-initializers \
 	-fvisibility=hidden \
 	-pipe \
 	-fPIC \
-	-Wno-format \
 	-m32 \
 	-mmmx \
 	-march=pentium4 \
@@ -475,10 +516,6 @@
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
 	-fno-stack-protector \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
@@ -501,6 +538,9 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
+	'-D__STDC_CONSTANT_MACROS' \
+	'-D__STDC_FORMAT_MACROS' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -508,11 +548,14 @@
 	'-DCHROME_BUILD_ID=""' \
 	'-DNDEBUG' \
 	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
+	'-D_FORTIFY_SOURCE=2'
 
 
 # Include paths placed before CFLAGS/CPPFLAGS
 LOCAL_C_INCLUDES_Release := \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
@@ -523,11 +566,11 @@
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
-	-Wno-deprecated \
+	-Wsign-compare \
+	-Wno-c++0x-compat \
 	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
+	-Wno-sign-promo
 
 
 LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
diff --git a/Source/core/page/AutoscrollController.cpp b/Source/core/page/AutoscrollController.cpp
index 4a5f7cc..6c46028 100644
--- a/Source/core/page/AutoscrollController.cpp
+++ b/Source/core/page/AutoscrollController.cpp
@@ -171,8 +171,7 @@
 #if OS(WIN)
 void AutoscrollController::handleMouseReleaseForPanScrolling(Frame* frame, const PlatformMouseEvent& mouseEvent)
 {
-    Page* page = frame->page();
-    if (!page || page->mainFrame() != frame)
+    if (!frame->isMainFrame())
         return;
     switch (m_autoscrollType) {
     case AutoscrollForPan:
diff --git a/Source/core/page/Chrome.cpp b/Source/core/page/Chrome.cpp
index d5e8867..a7ae353 100644
--- a/Source/core/page/Chrome.cpp
+++ b/Source/core/page/Chrome.cpp
@@ -91,7 +91,7 @@
     return m_client->rootViewToScreen(rect);
 }
 
-WebKit::WebScreenInfo Chrome::screenInfo() const
+blink::WebScreenInfo Chrome::screenInfo() const
 {
     return m_client->screenInfo();
 }
diff --git a/Source/core/page/Chrome.h b/Source/core/page/Chrome.h
index 304f518..2f10b72 100644
--- a/Source/core/page/Chrome.h
+++ b/Source/core/page/Chrome.h
@@ -66,7 +66,7 @@
     virtual void scroll(const IntSize&, const IntRect&, const IntRect&) OVERRIDE;
     virtual IntPoint screenToRootView(const IntPoint&) const OVERRIDE;
     virtual IntRect rootViewToScreen(const IntRect&) const OVERRIDE;
-    virtual WebKit::WebScreenInfo screenInfo() const OVERRIDE;
+    virtual blink::WebScreenInfo screenInfo() const OVERRIDE;
 
     virtual void scheduleAnimation() OVERRIDE;
 
diff --git a/Source/core/page/ChromeClient.h b/Source/core/page/ChromeClient.h
index 14834e8..7c795e0 100644
--- a/Source/core/page/ChromeClient.h
+++ b/Source/core/page/ChromeClient.h
@@ -29,12 +29,12 @@
 #include "core/frame/ConsoleTypes.h"
 #include "core/page/FocusDirection.h"
 #include "core/platform/Cursor.h"
-#include "core/platform/PopupMenu.h"
 #include "core/platform/PopupMenuClient.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "modules/webdatabase/DatabaseDetails.h"
 #include "platform/HostWindow.h"
+#include "platform/PopupMenu.h"
 #include "platform/scroll/ScrollTypes.h"
 #include "wtf/Forward.h"
 #include "wtf/PassOwnPtr.h"
@@ -104,7 +104,7 @@
     // created Page has its show method called.
     // The FrameLoadRequest parameter is only for ChromeClient to check if the
     // request could be fulfilled. The ChromeClient should not load the request.
-    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy = NavigationPolicyIgnore) = 0;
+    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy, ShouldSendReferrer) = 0;
     virtual void show(NavigationPolicy) = 0;
 
     virtual bool canRunModal() = 0;
@@ -148,7 +148,7 @@
     virtual void scroll(const IntSize&, const IntRect&, const IntRect&) = 0;
     virtual IntPoint screenToRootView(const IntPoint&) const = 0;
     virtual IntRect rootViewToScreen(const IntRect&) const = 0;
-    virtual WebKit::WebScreenInfo screenInfo() const = 0;
+    virtual blink::WebScreenInfo screenInfo() const = 0;
     virtual void setCursor(const Cursor&) = 0;
     virtual void scheduleAnimation() = 0;
     // End methods used by HostWindow.
@@ -261,6 +261,13 @@
     virtual bool isChromeClientImpl() const { return false; }
 
     virtual void didAssociateFormControls(const Vector<RefPtr<Element> >&) { };
+    virtual void didChangeValueInTextField(HTMLInputElement&) { }
+    virtual void didEndEditingOnTextField(HTMLInputElement&) { }
+    virtual void handleKeyboardEventOnTextField(HTMLInputElement&, KeyboardEvent&) { }
+
+    // Input mehtod editor related functions.
+    virtual void didCancelCompositionOnSelectionChange() { }
+    virtual void willSetInputMethodState() { }
 
     // Notifies the client of a new popup widget.  The client should place
     // and size the widget with the given bounds, relative to the screen.
diff --git a/Source/core/page/ContextMenuController.cpp b/Source/core/page/ContextMenuController.cpp
index cd6cb8a..104dc4a 100644
--- a/Source/core/page/ContextMenuController.cpp
+++ b/Source/core/page/ContextMenuController.cpp
@@ -35,9 +35,9 @@
 #include "core/page/ContextMenuProvider.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
-#include "core/platform/ContextMenu.h"
-#include "core/platform/ContextMenuItem.h"
 #include "core/rendering/HitTestResult.h"
+#include "platform/ContextMenu.h"
+#include "platform/ContextMenuItem.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/CreateWindow.cpp b/Source/core/page/CreateWindow.cpp
index 0cd7ee0..1a76d57 100644
--- a/Source/core/page/CreateWindow.cpp
+++ b/Source/core/page/CreateWindow.cpp
@@ -36,17 +36,17 @@
 #include "core/page/Settings.h"
 #include "core/page/WindowFeatures.h"
 #include "platform/network/ResourceRequest.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
 
 namespace WebCore {
 
-static Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
+static Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer, bool& created)
 {
     ASSERT(!features.dialog || request.frameName().isEmpty());
 
-    if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
+    if (!request.frameName().isEmpty() && request.frameName() != "_blank" && policy == NavigationPolicyIgnore) {
         if (Frame* frame = lookupFrame->loader().findFrameForNavigation(request.frameName(), openerFrame->document())) {
             if (request.frameName() != "_self") {
                 if (Page* page = frame->page())
@@ -73,7 +73,7 @@
     if (!oldPage)
         return 0;
 
-    Page* page = oldPage->chrome().client().createWindow(openerFrame, request, features);
+    Page* page = oldPage->chrome().client().createWindow(openerFrame, request, features, policy, shouldSendReferrer);
     if (!page)
         return 0;
 
@@ -106,7 +106,7 @@
     FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);
 
     page->chrome().setWindowRect(newWindowRect);
-    page->chrome().show();
+    page->chrome().show(policy);
 
     created = true;
     return frame;
@@ -134,7 +134,7 @@
     // We pass the opener frame for the lookupFrame in case the active frame is different from
     // the opener frame, and the name references a frame relative to the opener frame.
     bool created;
-    Frame* newFrame = createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
+    Frame* newFrame = createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, NavigationPolicyIgnore, MaybeSendReferrer, created);
     if (!newFrame)
         return 0;
 
@@ -156,4 +156,33 @@
     return newFrame;
 }
 
+void createWindowForRequest(const FrameLoadRequest& request, Frame* openerFrame, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer)
+{
+    if (openerFrame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
+        return;
+
+    if (openerFrame->document() && openerFrame->document()->isSandboxed(SandboxPopups))
+        return;
+
+    if (!DOMWindow::allowPopUp(openerFrame))
+        return;
+
+    if (policy == NavigationPolicyCurrentTab)
+        policy = NavigationPolicyNewForegroundTab;
+
+    WindowFeatures features;
+    bool created;
+    Frame* newFrame = createWindow(openerFrame, openerFrame, request, features, policy, shouldSendReferrer, created);
+    if (!newFrame)
+        return;
+    newFrame->page()->setOpenedByDOM();
+    if (shouldSendReferrer == MaybeSendReferrer) {
+        newFrame->loader().setOpener(openerFrame);
+        newFrame->document()->setReferrerPolicy(openerFrame->document()->referrerPolicy());
+    }
+    FrameLoadRequest newRequest(0, request.resourceRequest());
+    newRequest.setFormState(request.formState());
+    newFrame->loader().load(newRequest);
+}
+
 } // namespace WebCore
diff --git a/Source/core/page/CreateWindow.h b/Source/core/page/CreateWindow.h
index a6fe12d..1c2f353 100644
--- a/Source/core/page/CreateWindow.h
+++ b/Source/core/page/CreateWindow.h
@@ -28,15 +28,20 @@
 #define CreateWindow_h
 
 #include "core/frame/DOMWindow.h"
+#include "core/loader/FrameLoaderTypes.h"
+#include "core/loader/NavigationPolicy.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 class Frame;
+struct FrameLoadRequest;
 struct WindowFeatures;
 
 Frame* createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures&,
     DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, DOMWindow::PrepareDialogFunction = 0, void* functionContext = 0);
 
+void createWindowForRequest(const FrameLoadRequest&, Frame* openerFrame, NavigationPolicy, ShouldSendReferrer);
+
 } // namespace WebCore
 
 #endif // CreateWindow_h
diff --git a/Source/core/page/DOMSelection.cpp b/Source/core/page/DOMSelection.cpp
index fbba561..a1d6702 100644
--- a/Source/core/page/DOMSelection.cpp
+++ b/Source/core/page/DOMSelection.cpp
@@ -194,13 +194,13 @@
     return m_frame->selection().isNone() ? 0 : 1;
 }
 
-void DOMSelection::collapse(Node* node, int offset, ExceptionState& es)
+void DOMSelection::collapse(Node* node, int offset, ExceptionState& exceptionState)
 {
     if (!m_frame)
         return;
 
     if (offset < 0) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("collapse", "Selection", String::number(offset) + " is not a valid offset."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("collapse", "Selection", String::number(offset) + " is not a valid offset."));
         return;
     }
 
@@ -211,7 +211,7 @@
     m_frame->selection().moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
 }
 
-void DOMSelection::collapseToEnd(ExceptionState& es)
+void DOMSelection::collapseToEnd(ExceptionState& exceptionState)
 {
     if (!m_frame)
         return;
@@ -219,14 +219,14 @@
     const VisibleSelection& selection = m_frame->selection().selection();
 
     if (selection.isNone()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToEnd", "Selection", "there is no selection."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToEnd", "Selection", "there is no selection."));
         return;
     }
 
     m_frame->selection().moveTo(VisiblePosition(selection.end(), DOWNSTREAM));
 }
 
-void DOMSelection::collapseToStart(ExceptionState& es)
+void DOMSelection::collapseToStart(ExceptionState& exceptionState)
 {
     if (!m_frame)
         return;
@@ -234,7 +234,7 @@
     const VisibleSelection& selection = m_frame->selection().selection();
 
     if (selection.isNone()) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToStart", "Selection", "there is no selection."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToStart", "Selection", "there is no selection."));
         return;
     }
 
@@ -248,18 +248,18 @@
     m_frame->selection().clear();
 }
 
-void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState& es)
+void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState& exceptionState)
 {
     if (!m_frame)
         return;
 
     if (baseOffset < 0) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setBaseAndExtent", "Selection", String::number(baseOffset) + " is not a valid base offset."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setBaseAndExtent", "Selection", String::number(baseOffset) + " is not a valid base offset."));
         return;
     }
 
     if (extentOffset < 0) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setBaseAndExtent", "Selection", String::number(extentOffset) + " is not a valid extent offset."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setBaseAndExtent", "Selection", String::number(extentOffset) + " is not a valid extent offset."));
         return;
     }
 
@@ -273,12 +273,12 @@
     m_frame->selection().moveTo(visibleBase, visibleExtent);
 }
 
-void DOMSelection::setPosition(Node* node, int offset, ExceptionState& es)
+void DOMSelection::setPosition(Node* node, int offset, ExceptionState& exceptionState)
 {
     if (!m_frame)
         return;
     if (offset < 0) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setPosition", "Selection", String::number(offset) + " is not a valid offset."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setPosition", "Selection", String::number(offset) + " is not a valid offset."));
         return;
     }
 
@@ -339,22 +339,22 @@
     m_frame->selection().modify(alter, direction, granularity);
 }
 
-void DOMSelection::extend(Node* node, int offset, ExceptionState& es)
+void DOMSelection::extend(Node* node, int offset, ExceptionState& exceptionState)
 {
     if (!m_frame)
         return;
 
     if (!node) {
-        es.throwDOMException(TypeMismatchError, ExceptionMessages::failedToExecute("extend", "Selection", "The node provided is invalid."));
+        exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::failedToExecute("extend", "Selection", "The node provided is invalid."));
         return;
     }
 
     if (offset < 0) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("extend", "Selection", String::number(offset) + " is not a valid offset."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("extend", "Selection", String::number(offset) + " is not a valid offset."));
         return;
     }
     if (offset > (node->offsetInCharacters() ? caretMaxOffset(node) : (int)node->childNodeCount())) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("extend", "Selection", String::number(offset) + " is larger than the given node's length."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("extend", "Selection", String::number(offset) + " is larger than the given node's length."));
         return;
     }
 
@@ -365,13 +365,13 @@
     m_frame->selection().setExtent(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
 }
 
-PassRefPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& es)
+PassRefPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& exceptionState)
 {
     if (!m_frame)
         return 0;
 
     if (index < 0 || index >= rangeCount()) {
-        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("getRangeAt", "Selection", String::number(index) + " is not a valid index."));
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("getRangeAt", "Selection", String::number(index) + " is not a valid index."));
         return 0;
     }
 
@@ -423,8 +423,8 @@
         }
     } else {
         // We don't support discontiguous selection. We don't do anything if r and range don't intersect.
-        TrackExceptionState es;
-        if (r->compareBoundaryPoints(Range::END_TO_START, range.get(), es) < 1 && !es.hadException()) {
+        TrackExceptionState exceptionState;
+        if (r->compareBoundaryPoints(Range::END_TO_START, range.get(), exceptionState) < 1 && !exceptionState.hadException()) {
             if (r->compareBoundaryPoints(Range::END_TO_END, range.get(), IGNORE_EXCEPTION) == -1) {
                 // The original range contains r.
                 selection.setSelection(VisibleSelection(range.get()));
@@ -475,29 +475,29 @@
     if (!parentNode)
         return false;
 
-    TrackExceptionState es;
-    bool nodeFullySelected = Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->startContainer(), selectedRange->startOffset(), es) >= 0 && !es.hadException()
-        && Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->endContainer(), selectedRange->endOffset(), es) <= 0 && !es.hadException();
-    ASSERT(!es.hadException());
+    TrackExceptionState exceptionState;
+    bool nodeFullySelected = Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->startContainer(), selectedRange->startOffset(), exceptionState) >= 0 && !exceptionState.hadException()
+        && Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->endContainer(), selectedRange->endOffset(), exceptionState) <= 0 && !exceptionState.hadException();
+    ASSERT(!exceptionState.hadException());
     if (nodeFullySelected)
         return true;
 
-    bool nodeFullyUnselected = (Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->endContainer(), selectedRange->endOffset(), es) > 0 && !es.hadException())
-        || (Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->startContainer(), selectedRange->startOffset(), es) < 0 && !es.hadException());
-    ASSERT(!es.hadException());
+    bool nodeFullyUnselected = (Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->endContainer(), selectedRange->endOffset(), exceptionState) > 0 && !exceptionState.hadException())
+        || (Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->startContainer(), selectedRange->startOffset(), exceptionState) < 0 && !exceptionState.hadException());
+    ASSERT(!exceptionState.hadException());
     if (nodeFullyUnselected)
         return false;
 
     return allowPartial || n->isTextNode();
 }
 
-void DOMSelection::selectAllChildren(Node* n, ExceptionState& es)
+void DOMSelection::selectAllChildren(Node* n, ExceptionState& exceptionState)
 {
     if (!n)
         return;
 
     // This doesn't (and shouldn't) select text node characters.
-    setBaseAndExtent(n, 0, n, n->childNodeCount(), es);
+    setBaseAndExtent(n, 0, n, n->childNodeCount(), exceptionState);
 }
 
 String DOMSelection::toString()
diff --git a/Source/core/page/DragActions.h b/Source/core/page/DragActions.h
index d98c9c4..ce42ab7 100644
--- a/Source/core/page/DragActions.h
+++ b/Source/core/page/DragActions.h
@@ -39,13 +39,12 @@
         DragDestinationActionAny     = UINT_MAX
     } DragDestinationAction;
 
-    // WebCoreDragSourceAction should be kept in sync with WebDragSourceAction
     typedef enum {
-        DragSourceActionNone         = 0,
-        DragSourceActionDHTML        = 1,
-        DragSourceActionImage        = 2,
-        DragSourceActionLink         = 4,
-        DragSourceActionSelection    = 8,
+        DragSourceActionNone,
+        DragSourceActionDHTML,
+        DragSourceActionImage,
+        DragSourceActionLink,
+        DragSourceActionSelection,
     } DragSourceAction;
 
     //matches NSDragOperation
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index 3dc03d2..1c97568 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -56,12 +56,12 @@
 #include "core/loader/FrameLoader.h"
 #include "core/page/DragActions.h"
 #include "core/page/DragClient.h"
+#include "core/page/DragData.h"
 #include "core/page/DragSession.h"
 #include "core/page/DragState.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/DragData.h"
 #include "core/platform/DragImage.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
 #include "core/platform/graphics/Image.h"
@@ -73,7 +73,7 @@
 #include "platform/geometry/FloatRect.h"
 #include "platform/graphics/ImageOrientation.h"
 #include "platform/network/ResourceRequest.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -620,45 +620,77 @@
     return true;
 }
 
-Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
+Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, SelectionDragPolicy selectionDragPolicy, DragSourceAction& dragType) const
 {
-    state.m_dragType = (src->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
+    if (src->selection().contains(dragOrigin)) {
+        dragType = DragSourceActionSelection;
+        if (selectionDragPolicy == ImmediateSelectionDragResolution)
+            return startNode;
+    } else {
+        dragType = DragSourceActionNone;
+    }
 
+    Node* node = 0;
+    DragSourceAction candidateDragType = DragSourceActionNone;
     for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
-        Node* node = renderer->nonPseudoNode();
-        if (!node)
+        node = renderer->nonPseudoNode();
+        if (!node) {
             // Anonymous render blocks don't correspond to actual DOM nodes, so we skip over them
             // for the purposes of finding a draggable node.
             continue;
-        if (!(state.m_dragType & DragSourceActionSelection) && node->isTextNode() && node->canStartSelection())
+        }
+        if (dragType != DragSourceActionSelection && node->isTextNode() && node->canStartSelection()) {
             // In this case we have a click in the unselected portion of text. If this text is
             // selectable, we want to start the selection process instead of looking for a parent
             // to try to drag.
             return 0;
+        }
         if (node->isElementNode()) {
             EUserDrag dragMode = renderer->style()->userDrag();
             if (dragMode == DRAG_NONE)
                 continue;
+            // Even if the image is part of a selection, we always only drag the image in this case.
             if (renderer->isImage()
                 && src->settings()
                 && src->settings()->loadsImagesAutomatically()) {
-                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionImage);
+                dragType = DragSourceActionImage;
                 return node;
             }
+            // Other draggable elements are considered unselectable.
             if (isHTMLAnchorElement(node)
                 && toHTMLAnchorElement(node)->isLiveLink()) {
-                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionLink);
-                return node;
+                candidateDragType = DragSourceActionLink;
+                break;
             }
             if (dragMode == DRAG_ELEMENT) {
-                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
-                return node;
+                candidateDragType = DragSourceActionDHTML;
+                break;
             }
         }
     }
 
-    // We either have nothing to drag or we have a selection and we're not over a draggable element.
-    return (state.m_dragType & DragSourceActionSelection) ? startNode : 0;
+    if (candidateDragType == DragSourceActionNone) {
+        // Either:
+        // 1) Nothing under the cursor is considered draggable, so we bail out.
+        // 2) There was a selection under the cursor but selectionDragPolicy is set to
+        //    DelayedSelectionDragResolution and no other draggable element could be found, so bail
+        //    out and allow text selection to start at the cursor instead.
+        return 0;
+    }
+
+    ASSERT(node);
+    if (dragType == DragSourceActionSelection) {
+        // Dragging unselectable elements in a selection has special behavior if selectionDragPolicy
+        // is DelayedSelectionDragResolution and this drag was flagged as a potential selection
+        // drag. In that case, don't allow selection and just drag the entire selection instead.
+        ASSERT(selectionDragPolicy == DelayedSelectionDragResolution);
+        node = startNode;
+    } else {
+        // If the cursor isn't over a selection, then just drag the node we found earlier.
+        ASSERT(dragType == DragSourceActionNone);
+        dragType = candidateDragType;
+    }
+    return node;
 }
 
 static ImageResource* getImageResource(Element* element)
@@ -699,7 +731,7 @@
     if (!src->view() || !src->contentRenderer())
         return false;
 
-    HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
+    HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin);
     // FIXME: Can this even happen? I guess it's possible, but should verify
     // with a layout test.
     if (!state.m_dragSrc->contains(hitTestResult.innerNode())) {
@@ -820,11 +852,12 @@
         return false;
 
     HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin);
-    if (!state.m_dragSrc->contains(hitTestResult.innerNode()))
+    if (!state.m_dragSrc->contains(hitTestResult.innerNode())) {
         // The original node being dragged isn't under the drag origin anymore... maybe it was
         // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
         // something that's not actually under the drag origin.
         return false;
+    }
     const KURL& linkURL = hitTestResult.absoluteLinkURL();
     const KURL& imageURL = hitTestResult.absoluteImageURL();
 
diff --git a/Source/core/page/DragController.h b/Source/core/page/DragController.h
index 1aed97e..f109837 100644
--- a/Source/core/page/DragController.h
+++ b/Source/core/page/DragController.h
@@ -28,7 +28,7 @@
 
 #include "core/page/DragActions.h"
 #include "platform/geometry/IntPoint.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
@@ -63,7 +63,11 @@
         DragSession dragUpdated(DragData*);
         bool performDrag(DragData*);
 
-        Node* draggableNode(const Frame*, Node*, const IntPoint&, DragState&) const;
+        enum SelectionDragPolicy {
+            ImmediateSelectionDragResolution,
+            DelayedSelectionDragResolution,
+        };
+        Node* draggableNode(const Frame*, Node*, const IntPoint&, SelectionDragPolicy, DragSourceAction&) const;
         void dragEnded();
 
         bool populateDragClipboard(Frame* src, const DragState&, const IntPoint& dragOrigin);
diff --git a/Source/core/platform/DragData.cpp b/Source/core/page/DragData.cpp
similarity index 95%
rename from Source/core/platform/DragData.cpp
rename to Source/core/page/DragData.cpp
index ccc049b..79a2257 100644
--- a/Source/core/platform/DragData.cpp
+++ b/Source/core/page/DragData.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/platform/DragData.h"
+#include "core/page/DragData.h"
 
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
@@ -36,12 +36,9 @@
 #include "modules/filesystem/DraggedIsolatedFileSystem.h"
 #include "platform/FileMetadata.h"
 #include "platform/clipboard/ClipboardMimeTypes.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/text/WTFString.h"
 
-#include "public/platform/Platform.h"
-#include "public/platform/WebFileUtilities.h"
-
 namespace WebCore {
 
 DragData::DragData(ChromiumDataObject* data, const IntPoint& clientPosition, const IntPoint& globalPosition,
@@ -81,7 +78,7 @@
     if (m_platformDragData->types().contains(mimeTypeTextURIList))
         m_platformDragData->urlAndTitle(url, title);
     else if (filenamePolicy == ConvertFilenames && containsFiles())
-        url = KURL(WebKit::Platform::current()->fileUtilities()->filePathToURL(m_platformDragData->filenames()[0]));
+        url = filePathToURL(m_platformDragData->filenames()[0]);
     return url;
 }
 
diff --git a/Source/core/platform/DragData.h b/Source/core/page/DragData.h
similarity index 96%
rename from Source/core/platform/DragData.h
rename to Source/core/page/DragData.h
index b69f5c3..33c108c 100644
--- a/Source/core/platform/DragData.h
+++ b/Source/core/page/DragData.h
@@ -67,8 +67,7 @@
     String asURL(FilenameConversionPolicy filenamePolicy = ConvertFilenames, String* title = 0) const;
     String asPlainText() const;
     void asFilenames(Vector<String>&) const;
-    PassRefPtr<DocumentFragment> asFragment(Frame*, PassRefPtr<Range> context,
-                                            bool allowPlainText, bool& chosePlainText) const;
+    PassRefPtr<DocumentFragment> asFragment(Frame*, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText) const;
     bool canSmartReplace() const;
     bool containsFiles() const;
     unsigned numberOfFiles() const;
diff --git a/Source/core/page/EditorClient.h b/Source/core/page/EditorClient.h
index 7be8026..f7664b6 100644
--- a/Source/core/page/EditorClient.h
+++ b/Source/core/page/EditorClient.h
@@ -27,74 +27,27 @@
 #ifndef EditorClient_h
 #define EditorClient_h
 
-#include "core/editing/TextAffinity.h"
-#include "core/editing/UndoStep.h"
-#include "platform/geometry/FloatRect.h"
-#include "platform/text/TextChecking.h"
+#include "core/editing/SelectionType.h"
 #include "wtf/Forward.h"
-#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class ArchiveResource;
-class DocumentFragment;
-class Editor;
 class Element;
 class Frame;
-class HTMLElement;
-class KeyboardEvent;
-class Node;
-class Range;
-class SharedBuffer;
-class StylePropertySet;
-class TextCheckerClient;
-class VisibleSelection;
-class VisiblePosition;
-
-struct GrammarDetail;
+class UndoStep;
 
 class EditorClient {
 public:
-    virtual ~EditorClient() {  }
-
-    virtual bool smartInsertDeleteEnabled() = 0;
-    virtual bool isSelectTrailingWhitespaceEnabled() = 0;
-    virtual bool isContinuousSpellCheckingEnabled() = 0;
-    virtual void toggleContinuousSpellChecking() = 0;
-    virtual bool isGrammarCheckingEnabled() = 0;
+    virtual ~EditorClient() { }
 
     virtual void respondToChangedContents() = 0;
-    virtual void respondToChangedSelection(Frame*) = 0;
-    virtual void didCancelCompositionOnSelectionChange() = 0;
-
-    virtual void registerUndoStep(PassRefPtr<UndoStep>) = 0;
-    virtual void registerRedoStep(PassRefPtr<UndoStep>) = 0;
-    virtual void clearUndoRedoOperations() = 0;
+    virtual void respondToChangedSelection(SelectionType) = 0;
 
     virtual bool canCopyCut(Frame*, bool defaultValue) const = 0;
     virtual bool canPaste(Frame*, bool defaultValue) const = 0;
-    virtual bool canUndo() const = 0;
-    virtual bool canRedo() const = 0;
 
-    virtual void undo() = 0;
-    virtual void redo() = 0;
-
-    virtual void handleKeyboardEvent(KeyboardEvent*) = 0;
-
-    virtual void textFieldDidEndEditing(Element*) = 0;
-    virtual void textDidChangeInTextField(Element*) = 0;
-    virtual bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*) = 0;
-
-    virtual TextCheckerClient& textChecker() = 0;
-
-    virtual void updateSpellingUIWithMisspelledWord(const String&) = 0;
-    virtual void showSpellingUI(bool show) = 0;
-    virtual bool spellingUIIsShowing() = 0;
-    virtual void willSetInputMethodState() = 0;
-
-    // Support for global selections, used on platforms like the X Window System that treat
-    // selection as a type of clipboard.
-    virtual bool supportsGlobalSelection() { return false; }
+    virtual void didExecuteCommand(String) = 0;
+    virtual bool handleKeyboardEvent() = 0;
 };
 
 }
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 5501d94..11e63b3 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -76,7 +76,6 @@
 #include "core/platform/Cursor.h"
 #include "core/platform/ScrollAnimator.h"
 #include "core/platform/Scrollbar.h"
-#include "core/platform/WindowsKeyboardCodes.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
 #include "core/platform/graphics/Image.h"
 #include "core/rendering/HitTestRequest.h"
@@ -93,6 +92,7 @@
 #include "platform/PlatformKeyboardEvent.h"
 #include "platform/PlatformTouchEvent.h"
 #include "platform/PlatformWheelEvent.h"
+#include "platform/WindowsKeyboardCodes.h"
 #include "platform/geometry/FloatPoint.h"
 #include "wtf/Assertions.h"
 #include "wtf/CurrentTime.h"
@@ -135,7 +135,6 @@
 static const double TextDragDelay = 0.0;
 #endif
 
-
 enum NoCursorChangeType { NoCursorChange };
 
 class OptionalCursor {
@@ -259,14 +258,6 @@
     return enclosingBox->scroll(delta < 0 ? negativeDirection : positiveDirection, granularity, absDelta, stopNode);
 }
 
-static inline bool shouldGesturesTriggerActive()
-{
-    // If the platform we're on supports GestureShowPress and GestureTapCancel then we'll
-    // rely on them to set the active state. Unfortunately there's no generic way to
-    // know in advance what event types are supported.
-    return true;
-}
-
 // Refetch the event target node if it is removed or currently is the shadow node inside an <input> element.
 // If a mouse event handler changes the input element type to one that has a widget associated,
 // we'd like to EventHandler::handleMousePressEvent to pass the event to the widget and thus the
@@ -285,7 +276,6 @@
     , m_capturesDragging(false)
     , m_mouseDownMayStartSelect(false)
     , m_mouseDownMayStartDrag(false)
-    , m_dragMayStartSelectionInstead(false)
     , m_mouseDownWasSingleClickInSelection(false)
     , m_selectionInitiationState(HaveNotStartedSelection)
     , m_panScrollButtonPressed(false)
@@ -369,8 +359,15 @@
 
 void EventHandler::nodeWillBeRemoved(Node& nodeToBeRemoved)
 {
-    if (nodeToBeRemoved.contains(m_clickNode.get()))
+    if (!nodeToBeRemoved.containsIncludingShadowDOM(m_clickNode.get()))
+        return;
+    if (nodeToBeRemoved.isInShadowTree()) {
+        m_clickNode = nodeToBeRemoved.parentOrShadowHostNode();
+    } else {
+        // We don't dispatch click events if the mousedown node is removed
+        // before a mouseup event. It is compatible with IE and Firefox.
         m_clickNode = 0;
+    }
 }
 
 static void setSelectionIfNeeded(FrameSelection& selection, const VisibleSelection& newSelection)
@@ -1374,10 +1371,10 @@
 #endif
 
     m_clickCount = mouseEvent.clickCount();
-    m_clickNode = mev.targetNode();
+    m_clickNode = mev.targetNode()->isTextNode() ?  mev.targetNode()->parentOrShadowHostNode() : mev.targetNode();
 
     if (FrameView* view = m_frame->view()) {
-        RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
+        RenderLayer* layer = mev.targetNode()->renderer() ? mev.targetNode()->renderer()->enclosingLayer() : 0;
         IntPoint p = view->windowToContents(mouseEvent.position());
         if (layer && layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(p, ResizerForPointer)) {
             m_resizeScrollableArea = layer->scrollableArea();
@@ -1616,30 +1613,6 @@
     m_clickNode = 0;
 }
 
-inline static bool mouseIsReleasedOnPressedElement(Node* targetNode, Node* clickNode)
-{
-    if (targetNode == clickNode)
-        return true;
-
-    if (!targetNode)
-        return false;
-
-    ShadowRoot* containingShadowRoot = targetNode->containingShadowRoot();
-    if (!containingShadowRoot)
-        return false;
-
-    // FIXME: When an element in UA ShadowDOM (e.g. inner element in <input>) is clicked,
-    // we assume that the host element is clicked. This is necessary for implementing <input type="range"> etc.
-    // However, we should not check ShadowRoot type basically.
-    // https://bugs.webkit.org/show_bug.cgi?id=108047
-    if (containingShadowRoot->type() != ShadowRoot::UserAgentShadowRoot)
-        return false;
-
-    Node* adjustedTargetNode = targetNode->shadowHost();
-    Node* adjustedClickNode = clickNode ? clickNode->shadowHost() : 0;
-    return adjustedTargetNode == adjustedClickNode;
-}
-
 bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
 {
     RefPtr<FrameView> protector(m_frame->view());
@@ -1699,7 +1672,11 @@
         contextMenuEvent = true;
 #endif
 
-    bool swallowClickEvent = m_clickCount > 0 && !contextMenuEvent && mouseIsReleasedOnPressedElement(mev.targetNode(), m_clickNode.get()) && !dispatchMouseEvent(EventTypeNames::click, mev.targetNode(), true, m_clickCount, mouseEvent, true);
+    bool swallowClickEvent = false;
+    if (m_clickCount > 0 && !contextMenuEvent && mev.targetNode() && m_clickNode) {
+        if (Node* clickTargetNode = mev.targetNode()->commonAncestorOverShadowBoundary(*m_clickNode))
+            swallowClickEvent = !dispatchMouseEvent(EventTypeNames::click, clickTargetNode, true, m_clickCount, mouseEvent, true);
+    }
 
     if (m_resizeScrollableArea) {
         m_resizeScrollableArea->setInResizeMode(false);
@@ -1740,7 +1717,7 @@
         return false;
     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())
+    if (m_frame == focusFrame && m_frame->editor().behavior().supportsGlobalSelection())
         return m_frame->editor().command("PasteGlobalSelection").execute();
 
     return false;
@@ -2268,6 +2245,16 @@
 
 bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
 {
+    IntPoint adjustedPoint = gestureEvent.position();
+    if (gestureEvent.type() == PlatformEvent::GestureLongPress
+        || gestureEvent.type() == PlatformEvent::GestureLongTap
+        || gestureEvent.type() == PlatformEvent::GestureTwoFingerTap) {
+        adjustGesturePosition(gestureEvent, adjustedPoint);
+        RefPtr<Frame> subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
+        if (subframe)
+            return subframe->eventHandler().handleGestureEvent(gestureEvent);
+    }
+
     Node* eventTarget = 0;
     Scrollbar* scrollbar = 0;
     if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
@@ -2277,7 +2264,6 @@
         eventTarget = m_scrollGestureHandlingNode.get();
     }
 
-    IntPoint adjustedPoint = gestureEvent.position();
     HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
     if (gestureEvent.type() == PlatformEvent::GestureShowPress
         || gestureEvent.type() == PlatformEvent::GestureTapUnconfirmed) {
@@ -2293,9 +2279,6 @@
     else
         hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
 
-    if (!shouldGesturesTriggerActive())
-        hitType |= HitTestRequest::ReadOnly;
-
     if ((!scrollbar && !eventTarget) || !(hitType & HitTestRequest::ReadOnly)) {
         IntPoint hitTestPoint = m_frame->view()->windowToContents(adjustedPoint);
         HitTestResult result = hitTestResultAtPoint(hitTestPoint, hitType | HitTestRequest::AllowFrameScrollbars);
@@ -2351,11 +2334,11 @@
     case PlatformEvent::GestureShowPress:
         return handleGestureShowPress();
     case PlatformEvent::GestureLongPress:
-        return handleGestureLongPress(gestureEvent);
+        return handleGestureLongPress(gestureEvent, adjustedPoint);
     case PlatformEvent::GestureLongTap:
-        return handleGestureLongTap(gestureEvent);
+        return handleGestureLongTap(gestureEvent, adjustedPoint);
     case PlatformEvent::GestureTwoFingerTap:
-        return handleGestureTwoFingerTap(gestureEvent);
+        return handleGestureTwoFingerTap(gestureEvent, adjustedPoint);
     case PlatformEvent::GestureTapDown:
     case PlatformEvent::GesturePinchBegin:
     case PlatformEvent::GesturePinchEnd:
@@ -2395,14 +2378,8 @@
     return defaultPrevented;
 }
 
-bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
 {
-    IntPoint adjustedPoint = gestureEvent.position();
-    adjustGesturePosition(gestureEvent, adjustedPoint);
-    RefPtr<Frame> subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
-    if (subframe && subframe->eventHandler().handleGestureLongPress(gestureEvent))
-        return true;
-
     m_longTapShouldInvokeContextMenu = false;
     if (m_frame->settings() && m_frame->settings()->touchDragDropEnabled() && m_frame->view()) {
         PlatformMouseEvent mouseDownEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1,
@@ -2444,13 +2421,8 @@
     return sendContextMenuEventForGesture(gestureEvent);
 }
 
-bool EventHandler::handleGestureLongTap(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureLongTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
 {
-    IntPoint adjustedPoint = gestureEvent.position();
-    adjustGesturePosition(gestureEvent, adjustedPoint);
-    RefPtr<Frame> subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
-    if (subframe && subframe->eventHandler().handleGestureLongTap(gestureEvent))
-        return true;
 #if !OS(ANDROID)
     if (m_longTapShouldInvokeContextMenu) {
         m_longTapShouldInvokeContextMenu = false;
@@ -2487,7 +2459,7 @@
     return false;
 }
 
-bool EventHandler::handleGestureTwoFingerTap(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureTwoFingerTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
 {
     return sendContextMenuEventForGesture(gestureEvent);
 }
@@ -3219,13 +3191,9 @@
     return !dispatchDragEvent(eventType, dragState().m_dragSrc.get(), event, dragState().m_dragClipboard.get());
 }
 
-static bool exactlyOneBitSet(DragSourceAction n)
-{
-    return n && !(n & (n - 1));
-}
-
 bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDragHysteresis checkDragHysteresis)
 {
+    ASSERT(event.event().type() == PlatformEvent::MouseMoved);
     // Callers must protect the reference to FrameView, since this function may dispatch DOM
     // events, causing page/FrameView to go away.
     ASSERT(m_frame);
@@ -3242,58 +3210,27 @@
         return false;
     }
 
-    if (m_mouseDownMayStartDrag && !dragState().m_dragSrc) {
-        // try to find an element that wants to be dragged
-        HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+    if (m_mouseDownMayStartDrag) {
+        HitTestRequest request(HitTestRequest::ReadOnly);
         HitTestResult result(m_mouseDownPos);
         m_frame->contentRenderer()->hitTest(request, result);
         Node* node = result.innerNode();
-        if (node)
-            dragState().m_dragSrc = m_frame->page()->dragController().draggableNode(m_frame, node, m_mouseDownPos, dragState());
-        else
+        if (node) {
+            DragController::SelectionDragPolicy selectionDragPolicy = event.event().timestamp() - m_mouseDownTimestamp < TextDragDelay
+                ? DragController::DelayedSelectionDragResolution
+                : DragController::ImmediateSelectionDragResolution;
+            dragState().m_dragSrc = m_frame->page()->dragController().draggableNode(m_frame, node, m_mouseDownPos, selectionDragPolicy, dragState().m_dragType);
+        } else {
             dragState().m_dragSrc = 0;
+        }
 
         if (!dragState().m_dragSrc)
             m_mouseDownMayStartDrag = false; // no element is draggable
-        else
-            m_dragMayStartSelectionInstead = (dragState().m_dragType & DragSourceActionSelection);
-    }
-
-    // For drags starting in the selection, the user must wait between the mousedown and mousedrag,
-    // or else we bail on the dragging stuff and allow selection to occur
-    if (m_mouseDownMayStartDrag && m_dragMayStartSelectionInstead && (dragState().m_dragType & DragSourceActionSelection) && event.event().timestamp() - m_mouseDownTimestamp < TextDragDelay) {
-        ASSERT(event.event().type() == PlatformEvent::MouseMoved);
-        if ((dragState().m_dragType & DragSourceActionImage)) {
-            // ... unless the mouse is over an image, then we start dragging just the image
-            dragState().m_dragType = DragSourceActionImage;
-        } else if (!(dragState().m_dragType & (DragSourceActionDHTML | DragSourceActionLink))) {
-            // ... but only bail if we're not over an unselectable element.
-            m_mouseDownMayStartDrag = false;
-            dragState().m_dragSrc = 0;
-        } else {
-            // Prevent the following case from occuring:
-            // 1. User starts a drag immediately after mouse down over an unselectable element.
-            // 2. We enter this block and decided that since we're over an unselectable element,
-            //    don't cancel the drag.
-            // 3. The drag gets resolved as a potential selection drag below /but/ we haven't
-            //    exceeded the drag hysteresis yet.
-            // 4. We enter this block again, and since it's now marked as a selection drag, we
-            //    cancel the drag.
-            m_dragMayStartSelectionInstead = false;
-        }
     }
 
     if (!m_mouseDownMayStartDrag)
         return !mouseDownMayStartSelect() && !m_mouseDownMayStartAutoscroll;
 
-    if (!exactlyOneBitSet(dragState().m_dragType)) {
-        ASSERT((dragState().m_dragType & DragSourceActionSelection));
-        ASSERT((dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionDHTML
-                || (dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionImage
-                || (dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionLink);
-        dragState().m_dragType = DragSourceActionSelection;
-    }
-
     // We are starting a text/image/url drag, so the cursor should be an arrow
     // FIXME <rdar://7577595>: Custom cursors aren't supported during drag and drop (default to pointer).
     m_frame->view()->setCursor(pointerCursor());
@@ -3496,13 +3433,6 @@
     }
 }
 
-void EventHandler::sendResizeEvent()
-{
-    RefPtr<Event> event = Event::create(EventTypeNames::resize);
-    event->setTarget(m_frame->document()->domWindow());
-    m_frame->document()->scheduleAnimationFrameEvent(event.release());
-}
-
 void EventHandler::sendScrollEvent()
 {
     setFrameWasScrolledByUser();
@@ -3620,7 +3550,9 @@
         PlatformTouchPoint::State pointState = point.state();
         LayoutPoint pagePoint = documentPointForWindowPoint(m_frame, point.pos());
 
-        HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
+        // Gesture events trigger the active state, not touch events,
+        // so touch event hit tests can always be read only.
+        HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent | HitTestRequest::ReadOnly;
         // The HitTestRequest types used for mouse events map quite adequately
         // to touch events. Note that in addition to meaning that the hit test
         // should affect the active state of the current node if necessary,
@@ -3631,23 +3563,20 @@
             hitType |= HitTestRequest::Active;
             break;
         case PlatformTouchPoint::TouchMoved:
-            hitType |= HitTestRequest::Active | HitTestRequest::Move | HitTestRequest::ReadOnly;
+            hitType |= HitTestRequest::Active | HitTestRequest::Move;
             break;
         case PlatformTouchPoint::TouchReleased:
         case PlatformTouchPoint::TouchCancelled:
             hitType |= HitTestRequest::Release;
             break;
         case PlatformTouchPoint::TouchStationary:
-            hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
+            hitType |= HitTestRequest::Active;
             break;
         default:
             ASSERT_NOT_REACHED();
             break;
         }
 
-        if (shouldGesturesTriggerActive())
-            hitType |= HitTestRequest::ReadOnly;
-
         // Increment the platform touch id by 1 to avoid storing a key of 0 in the hashmap.
         unsigned touchPointTargetKey = point.id() + 1;
         RefPtr<EventTarget> touchTarget;
@@ -3681,14 +3610,6 @@
             m_originatingTouchPointTargets.set(touchPointTargetKey, node);
             touchTarget = node;
         } else if (pointState == PlatformTouchPoint::TouchReleased || pointState == PlatformTouchPoint::TouchCancelled) {
-            // We only perform a hittest on release or cancel to unset :active or :hover state.
-            if (touchPointTargetKey == m_originatingTouchPointTargetKey) {
-                hitTestResultAtPoint(pagePoint, hitType);
-                m_originatingTouchPointTargetKey = 0;
-            } else if (m_originatingTouchPointDocument.get() && m_originatingTouchPointDocument->frame()) {
-                LayoutPoint pagePointInOriginatingDocument = documentPointForWindowPoint(m_originatingTouchPointDocument->frame(), point.pos());
-                hitTestResultInFrame(m_originatingTouchPointDocument->frame(), pagePointInOriginatingDocument, hitType);
-            }
             // The target should be the original target for this touch, so get it from the hashmap. As it's a release or cancel
             // we also remove it from the map.
             touchTarget = m_originatingTouchPointTargets.take(touchPointTargetKey);
@@ -3808,18 +3729,18 @@
 bool EventHandler::handleMouseEventAsEmulatedGesture(const PlatformMouseEvent& event)
 {
     PlatformEvent::Type eventType = event.type();
-    Page* page = m_frame->page();
-    FrameView* view = m_frame->view();
-    if (event.button() != LeftButton || page->mainFrame() != m_frame)
+    if (event.button() != LeftButton || !m_frame->isMainFrame())
         return false;
 
     // Simulate pinch / scroll gesture.
     const IntPoint& position = event.position();
     bool swallowEvent = false;
 
+    FrameView* view = m_frame->view();
     if (event.shiftKey()) {
         // Shift pressed - consider it gesture.
         swallowEvent = true;
+        Page* page = m_frame->page();
         float pageScaleFactor = page->pageScaleFactor();
         switch (eventType) {
         case PlatformEvent::MousePressed:
diff --git a/Source/core/page/EventHandler.h b/Source/core/page/EventHandler.h
index 2fca448..f22e7fe 100644
--- a/Source/core/page/EventHandler.h
+++ b/Source/core/page/EventHandler.h
@@ -170,8 +170,7 @@
 
     void capsLockStateMayHaveChanged(); // Only called by FrameSelection
 
-    void sendResizeEvent(); // Only called in FrameView
-    void sendScrollEvent(); // Ditto
+    void sendScrollEvent(); // Only called in FrameView
 
     bool handleTouchEvent(const PlatformTouchEvent&);
 
@@ -200,9 +199,9 @@
     bool handlePasteGlobalSelection(const PlatformMouseEvent&);
 
     bool handleGestureTap(const PlatformGestureEvent&);
-    bool handleGestureLongPress(const PlatformGestureEvent&);
-    bool handleGestureLongTap(const PlatformGestureEvent&);
-    bool handleGestureTwoFingerTap(const PlatformGestureEvent&);
+    bool handleGestureLongPress(const PlatformGestureEvent&, const IntPoint& adjustedPoint);
+    bool handleGestureLongTap(const PlatformGestureEvent&, const IntPoint& adjustedPoint);
+    bool handleGestureTwoFingerTap(const PlatformGestureEvent&, const IntPoint& adjustedPoint);
     bool handleGestureScrollUpdate(const PlatformGestureEvent&);
     bool handleGestureScrollBegin(const PlatformGestureEvent&);
     void clearGestureScrollNodes();
@@ -303,7 +302,6 @@
 
     bool m_mouseDownMayStartSelect;
     bool m_mouseDownMayStartDrag;
-    bool m_dragMayStartSelectionInstead;
     bool m_mouseDownWasSingleClickInSelection;
     enum SelectionInitiationState { HaveNotStartedSelection, PlacedCaret, ExtendedSelection };
     SelectionInitiationState m_selectionInitiationState;
diff --git a/Source/core/page/EventSource.cpp b/Source/core/page/EventSource.cpp
index 061c4d5..6a9600c 100644
--- a/Source/core/page/EventSource.cpp
+++ b/Source/core/page/EventSource.cpp
@@ -50,7 +50,7 @@
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
@@ -63,7 +63,7 @@
     , m_withCredentials(false)
     , m_state(CONNECTING)
     , m_decoder(TextResourceDecoder::create("text/plain", "UTF-8"))
-    , m_reconnectTimer(this, &EventSource::reconnectTimerFired)
+    , m_connectTimer(this, &EventSource::connectTimerFired)
     , m_discardTrailingNewline(false)
     , m_requestInFlight(false)
     , m_reconnectDelay(defaultReconnectDelay)
@@ -72,16 +72,16 @@
     eventSourceInit.get("withCredentials", m_withCredentials);
 }
 
-PassRefPtr<EventSource> EventSource::create(ExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& es)
+PassRefPtr<EventSource> EventSource::create(ExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& exceptionState)
 {
     if (url.isEmpty()) {
-        es.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
+        exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
         return 0;
     }
 
     KURL fullURL = context->completeURL(url);
     if (!fullURL.isValid()) {
-        es.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
+        exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
         return 0;
     }
 
@@ -93,14 +93,14 @@
     }
     if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
         // We can safely expose the URL to JavaScript, as this exception is generate synchronously before any redirects take place.
-        es.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
+        exceptionState.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
         return 0;
     }
 
     RefPtr<EventSource> source = adoptRef(new EventSource(context, fullURL, eventSourceInit));
 
     source->setPendingActivity(source.get());
-    source->connect();
+    source->scheduleInitialConnect();
     source->suspendIfNeeded();
 
     return source.release();
@@ -112,6 +112,14 @@
     ASSERT(!m_requestInFlight);
 }
 
+void EventSource::scheduleInitialConnect()
+{
+    ASSERT(m_state == CONNECTING);
+    ASSERT(!m_requestInFlight);
+
+    m_connectTimer.startOneShot(0);
+}
+
 void EventSource::connect()
 {
     ASSERT(m_state == CONNECTING);
@@ -159,11 +167,11 @@
 void EventSource::scheduleReconnect()
 {
     m_state = CONNECTING;
-    m_reconnectTimer.startOneShot(m_reconnectDelay / 1000.0);
+    m_connectTimer.startOneShot(m_reconnectDelay / 1000.0);
     dispatchEvent(Event::create(EventTypeNames::error));
 }
 
-void EventSource::reconnectTimerFired(Timer<EventSource>*)
+void EventSource::connectTimerFired(Timer<EventSource>*)
 {
     connect();
 }
@@ -191,8 +199,8 @@
     }
 
     // Stop trying to reconnect if EventSource was explicitly closed or if ActiveDOMObject::stop() was called.
-    if (m_reconnectTimer.isActive()) {
-        m_reconnectTimer.stop();
+    if (m_connectTimer.isActive()) {
+        m_connectTimer.stop();
         unsetPendingActivity(this);
     }
 
@@ -306,9 +314,13 @@
 void EventSource::abortConnectionAttempt()
 {
     ASSERT(m_state == CONNECTING);
-    ASSERT(m_requestInFlight);
 
-    m_loader->cancel();
+    if (m_requestInFlight) {
+        m_loader->cancel();
+    } else {
+        m_state = CLOSED;
+        unsetPendingActivity(this);
+    }
 
     ASSERT(m_state == CLOSED);
     dispatchEvent(Event::create(EventTypeNames::error));
diff --git a/Source/core/page/EventSource.h b/Source/core/page/EventSource.h
index a290bde..66ea83a 100644
--- a/Source/core/page/EventSource.h
+++ b/Source/core/page/EventSource.h
@@ -37,7 +37,7 @@
 #include "core/events/EventTarget.h"
 #include "core/loader/ThreadableLoaderClient.h"
 #include "platform/Timer.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
@@ -96,10 +96,11 @@
     virtual void didFailAccessControlCheck(const ResourceError&);
     virtual void didFailRedirectCheck();
 
+    void scheduleInitialConnect();
     void connect();
     void networkRequestEnded();
     void scheduleReconnect();
-    void reconnectTimerFired(Timer<EventSource>*);
+    void connectTimerFired(Timer<EventSource>*);
     void abortConnectionAttempt();
     void parseEventStream();
     void parseEventStreamLine(unsigned pos, int fieldLength, int lineLength);
@@ -109,9 +110,9 @@
     bool m_withCredentials;
     State m_state;
 
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
     RefPtr<ThreadableLoader> m_loader;
-    Timer<EventSource> m_reconnectTimer;
+    Timer<EventSource> m_connectTimer;
     Vector<UChar> m_receiveBuf;
     bool m_discardTrailingNewline;
     bool m_requestInFlight;
diff --git a/Source/core/page/EventSource.idl b/Source/core/page/EventSource.idl
index b43938d..fcf7dc1 100644
--- a/Source/core/page/EventSource.idl
+++ b/Source/core/page/EventSource.idl
@@ -34,7 +34,7 @@
     ActiveDOMObject,
     Constructor(DOMString url, optional Dictionary eventSourceInit),
     ConstructorCallWith=ExecutionContext,
-    ConstructorRaisesException
+    RaisesException=Constructor
 ] interface EventSource : EventTarget {
 
     readonly attribute DOMString URL; // Lowercased .url is the one in the spec, but leaving .URL for compatibility reasons.
diff --git a/Source/core/page/FocusController.cpp b/Source/core/page/FocusController.cpp
index 56871f6..be1d745 100644
--- a/Source/core/page/FocusController.cpp
+++ b/Source/core/page/FocusController.cpp
@@ -50,7 +50,7 @@
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 #include "core/page/Chrome.h"
-#include "core/page/EditorClient.h"
+#include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
@@ -165,6 +165,7 @@
     return element->isHTMLElement() && toHTMLElement(element)->hasCustomFocusLogic();
 }
 
+#if !ASSERT_DISABLED
 static inline bool isNonFocusableShadowHost(Node* node)
 {
     ASSERT(node);
@@ -173,6 +174,7 @@
     Element* element = toElement(node);
     return !element->isFocusable() && isShadowHost(element) && !hasCustomFocusLogic(element);
 }
+#endif
 
 static inline bool isNonKeyboardFocusableShadowHost(Node* node)
 {
@@ -466,7 +468,7 @@
 Node* FocusController::findNodeWithExactTabIndex(Node* start, int tabIndex, FocusDirection direction)
 {
     // Search is inclusive of start
-    for (Node* node = start; node; node = direction == FocusDirectionForward ? NodeTraversal::next(node) : NodeTraversal::previous(node)) {
+    for (Node* node = start; node; node = direction == FocusDirectionForward ? NodeTraversal::next(*node) : NodeTraversal::previous(*node)) {
         if (shouldVisit(node) && adjustedTabIndex(node) == tabIndex)
             return node;
     }
@@ -478,7 +480,7 @@
     // Search is inclusive of start
     int winningTabIndex = std::numeric_limits<short>::max() + 1;
     Node* winner = 0;
-    for (Node* node = start; node; node = NodeTraversal::next(node)) {
+    for (Node* node = start; node; node = NodeTraversal::next(*node)) {
         if (shouldVisit(node) && node->tabIndex() > tabIndex && node->tabIndex() < winningTabIndex) {
             winner = node;
             winningTabIndex = node->tabIndex();
@@ -493,7 +495,7 @@
     // Search is inclusive of start
     int winningTabIndex = 0;
     Node* winner = 0;
-    for (Node* node = start; node; node = NodeTraversal::previous(node)) {
+    for (Node* node = start; node; node = NodeTraversal::previous(*node)) {
         int currentTabIndex = adjustedTabIndex(node);
         if ((shouldVisit(node) || isNonKeyboardFocusableShadowHost(node)) && currentTabIndex < tabIndex && currentTabIndex > winningTabIndex) {
             winner = node;
@@ -509,14 +511,14 @@
         int tabIndex = adjustedTabIndex(start);
         // If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
         if (tabIndex < 0) {
-            for (Node* node = NodeTraversal::next(start); node; node = NodeTraversal::next(node)) {
+            for (Node* node = NodeTraversal::next(*start); node; node = NodeTraversal::next(*node)) {
                 if (shouldVisit(node) && adjustedTabIndex(node) >= 0)
                     return node;
             }
         }
 
         // First try to find a node with the same tabindex as start that comes after start in the scope.
-        if (Node* winner = findNodeWithExactTabIndex(NodeTraversal::next(start), tabIndex, FocusDirectionForward))
+        if (Node* winner = findNodeWithExactTabIndex(NodeTraversal::next(*start), tabIndex, FocusDirectionForward))
             return winner;
 
         if (!tabIndex)
@@ -547,7 +549,7 @@
     Node* startingNode;
     int startingTabIndex;
     if (start) {
-        startingNode = NodeTraversal::previous(start);
+        startingNode = NodeTraversal::previous(*start);
         startingTabIndex = adjustedTabIndex(start);
     } else {
         startingNode = last;
@@ -556,7 +558,7 @@
 
     // However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
     if (startingTabIndex < 0) {
-        for (Node* node = startingNode; node; node = NodeTraversal::previous(node)) {
+        for (Node* node = startingNode; node; node = NodeTraversal::previous(*node)) {
             if (shouldVisit(node) && adjustedTabIndex(node) >= 0)
                 return node;
         }
@@ -622,28 +624,26 @@
     RefPtr<Document> oldDocument = oldFocusedFrame ? oldFocusedFrame->document() : 0;
 
     Element* oldFocusedElement = oldDocument ? oldDocument->focusedElement() : 0;
-    if (oldFocusedElement == element)
+    if (element && oldFocusedElement == element)
         return true;
 
     // FIXME: Might want to disable this check for caretBrowsing
     if (oldFocusedElement && oldFocusedElement->isRootEditableElement() && !relinquishesEditingFocus(oldFocusedElement))
         return false;
 
-    m_page->editorClient().willSetInputMethodState();
+    m_page->chrome().client().willSetInputMethodState();
 
-    clearSelectionIfNeeded(oldFocusedFrame.get(), newFocusedFrame.get(), element);
-
-    if (!element) {
-        if (oldDocument)
-            oldDocument->setFocusedElement(0);
-        return true;
-    }
-
-    RefPtr<Document> newDocument(element->document());
+    RefPtr<Document> newDocument;
+    if (element)
+        newDocument = &element->document();
+    else if (newFocusedFrame)
+        newDocument = newFocusedFrame->document();
 
     if (newDocument && newDocument->focusedElement() == element)
         return true;
 
+    clearSelectionIfNeeded(oldFocusedFrame.get(), newFocusedFrame.get(), element);
+
     if (oldDocument && oldDocument != newDocument)
         oldDocument->setFocusedElement(0);
 
@@ -767,9 +767,8 @@
         closest = candidate;
 }
 
-void FocusController::findFocusCandidateInContainer(Node* container, const LayoutRect& startingRect, FocusDirection direction, FocusCandidate& closest)
+void FocusController::findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusDirection direction, FocusCandidate& closest)
 {
-    ASSERT(container);
     Element* focusedElement = (focusedFrame() && focusedFrame()->document()) ? focusedFrame()->document()->focusedElement() : 0;
 
     Element* element = ElementTraversal::firstWithin(container);
@@ -779,8 +778,8 @@
     current.visibleNode = focusedElement;
 
     for (; element; element = (element->isFrameOwnerElement() || canScrollInDirection(element, direction))
-        ? ElementTraversal::nextSkippingChildren(element, container)
-        : ElementTraversal::next(element, container)) {
+        ? ElementTraversal::nextSkippingChildren(*element, &container)
+        : ElementTraversal::next(*element, &container)) {
         if (element == focusedElement)
             continue;
 
@@ -791,7 +790,7 @@
         if (candidate.isNull())
             continue;
 
-        candidate.enclosingScrollableBox = container;
+        candidate.enclosingScrollableBox = &container;
         updateFocusCandidateIfNeeded(direction, current, candidate, closest);
     }
 }
@@ -808,7 +807,7 @@
 
     // Find the closest node within current container in the direction of the navigation.
     FocusCandidate focusCandidate;
-    findFocusCandidateInContainer(container, newStartingRect, direction, focusCandidate);
+    findFocusCandidateInContainer(*container, newStartingRect, direction, focusCandidate);
 
     if (focusCandidate.isNull()) {
         // Nothing to focus, scroll if possible.
diff --git a/Source/core/page/FocusController.h b/Source/core/page/FocusController.h
index 8abdb66..38069eb 100644
--- a/Source/core/page/FocusController.h
+++ b/Source/core/page/FocusController.h
@@ -112,7 +112,7 @@
     Node* findNodeWithExactTabIndex(Node* start, int tabIndex, FocusDirection);
 
     bool advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusDirection);
-    void findFocusCandidateInContainer(Node* container, const LayoutRect& startingRect, FocusDirection, FocusCandidate& closest);
+    void findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusDirection, FocusCandidate& closest);
 
     Page* m_page;
     RefPtr<Frame> m_focusedFrame;
diff --git a/Source/core/page/Page.cpp b/Source/core/page/Page.cpp
index 57dfbb0..849418f 100644
--- a/Source/core/page/Page.cpp
+++ b/Source/core/page/Page.cpp
@@ -25,6 +25,7 @@
 #include "core/dom/StyleEngine.h"
 #include "core/dom/VisitedLinkState.h"
 #include "core/editing/Caret.h"
+#include "core/editing/UndoStack.h"
 #include "core/events/Event.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/frame/DOMTimer.h"
@@ -50,10 +51,10 @@
 #include "core/page/Settings.h"
 #include "core/page/ValidationMessageClient.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/plugins/PluginData.h"
 #include "core/rendering/RenderView.h"
 #include "core/storage/StorageNamespace.h"
 #include "core/workers/SharedWorkerRepositoryClient.h"
+#include "platform/plugins/PluginData.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/StdLibExtras.h"
@@ -104,19 +105,21 @@
     , m_contextMenuController(ContextMenuController::create(this, pageClients.contextMenuClient))
     , m_inspectorController(InspectorController::create(this, pageClients.inspectorClient))
     , m_pointerLockController(PointerLockController::create(this))
+    , m_history(adoptPtr(new HistoryController(this)))
     , m_settings(Settings::create(this))
     , m_progress(ProgressTracker::create())
+    , m_undoStack(UndoStack::create())
     , m_backForwardClient(pageClients.backForwardClient)
     , m_editorClient(pageClients.editorClient)
     , m_validationMessageClient(0)
     , m_sharedWorkerRepositoryClient(0)
+    , m_spellCheckerClient(pageClients.spellCheckerClient)
     , m_subframeCount(0)
     , m_openedByDOM(false)
     , m_tabKeyCyclesThroughElements(true)
     , m_defersLoading(false)
     , m_pageScaleFactor(1)
     , m_deviceScaleFactor(1)
-    , m_didLoadUserStyleSheet(false)
     , m_group(0)
     , m_timerAlignmentInterval(DOMTimer::visiblePageAlignmentInterval())
     , m_visibilityState(PageVisibilityStateVisible)
@@ -222,18 +225,6 @@
     m_openedByDOM = true;
 }
 
-void Page::goToItem(HistoryItem* item)
-{
-    // stopAllLoaders may end up running onload handlers, which could cause further history traversals that may lead to the passed in HistoryItem
-    // being deref()-ed. Make sure we can still use it with HistoryController::goToItem later.
-    RefPtr<HistoryItem> protector(item);
-
-    if (m_mainFrame->loader().history()->shouldStopLoadingForHistoryItem(item))
-        m_mainFrame->loader().stopAllLoaders();
-
-    m_mainFrame->loader().history()->goToItem(item);
-}
-
 void Page::clearPageGroup()
 {
     if (!m_group)
@@ -247,9 +238,6 @@
     clearPageGroup();
 
     switch (type) {
-    case InspectorPageGroup:
-        m_group = PageGroup::inspectorGroup();
-        break;
     case PrivatePageGroup:
         m_group = PageGroup::create();
         break;
@@ -341,6 +329,7 @@
         return;
 
     m_defersLoading = defers;
+    m_history->setDefersLoading(defers);
     for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
         frame->loader().setDefersLoading(defers);
 }
@@ -390,36 +379,6 @@
     setNeedsRecalcStyleInAllFrames();
 }
 
-void Page::userStyleSheetLocationChanged()
-{
-    // FIXME: Eventually we will move to a model of just being handed the sheet
-    // text instead of loading the URL ourselves.
-    KURL url = m_settings->userStyleSheetLocation();
-
-    m_didLoadUserStyleSheet = false;
-    m_userStyleSheet = String();
-
-    // Data URLs with base64-encoded UTF-8 style sheets are common. We can process them
-    // synchronously and avoid using a loader.
-    if (url.protocolIsData() && url.string().startsWith("data:text/css;charset=utf-8;base64,")) {
-        m_didLoadUserStyleSheet = true;
-
-        Vector<char> styleSheetAsUTF8;
-        if (base64Decode(decodeURLEscapeSequences(url.string().substring(35)), styleSheetAsUTF8, Base64IgnoreWhitespace))
-            m_userStyleSheet = String::fromUTF8(styleSheetAsUTF8.data(), styleSheetAsUTF8.size());
-    }
-
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document())
-            frame->document()->styleEngine()->updatePageUserSheet();
-    }
-}
-
-const String& Page::userStyleSheet() const
-{
-    return m_userStyleSheet;
-}
-
 void Page::allVisitedStateChanged(PageGroup* group)
 {
     ASSERT(group);
@@ -544,7 +503,7 @@
 
 PageLifecycleNotifier& Page::lifecycleNotifier()
 {
-    return static_cast<PageLifecycleNotifier&>(LifecycleContext::lifecycleNotifier());
+    return static_cast<PageLifecycleNotifier&>(LifecycleContext<Page>::lifecycleNotifier());
 }
 
 PassOwnPtr<LifecycleNotifier<Page> > Page::createLifecycleNotifier()
@@ -559,6 +518,7 @@
     , dragClient(0)
     , inspectorClient(0)
     , backForwardClient(0)
+    , spellCheckerClient(0)
 {
 }
 
diff --git a/Source/core/page/Page.h b/Source/core/page/Page.h
index c29caa8..79bad5f 100644
--- a/Source/core/page/Page.h
+++ b/Source/core/page/Page.h
@@ -23,7 +23,8 @@
 
 #include "core/dom/ViewportDescription.h"
 #include "core/page/PageVisibilityState.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
+#include "core/loader/HistoryController.h"
 #include "core/rendering/Pagination.h"
 #include "platform/LifecycleContext.h"
 #include "platform/Supplementable.h"
@@ -72,7 +73,9 @@
 class ScrollingCoordinator;
 class Settings;
 class SharedWorkerRepositoryClient;
+class SpellCheckerClient;
 class StorageNamespace;
+class UndoStack;
 class ValidationMessageClient;
 
 typedef uint64_t LinkHash;
@@ -98,6 +101,7 @@
         DragClient* dragClient;
         InspectorClient* inspectorClient;
         BackForwardClient* backForwardClient;
+        SpellCheckerClient* spellCheckerClient;
     };
 
     explicit Page(PageClients&);
@@ -111,6 +115,10 @@
     PluginData* pluginData() const;
 
     EditorClient& editorClient() const { return *m_editorClient; }
+    SpellCheckerClient& spellCheckerClient() const { return *m_spellCheckerClient; }
+    UndoStack& undoStack() const { return *m_undoStack; }
+
+    HistoryController* history() const { return m_history.get(); }
 
     void setMainFrame(PassRefPtr<Frame>);
     Frame* mainFrame() const { return m_mainFrame.get(); }
@@ -120,11 +128,7 @@
     bool openedByDOM() const;
     void setOpenedByDOM();
 
-    // DEPRECATED. Use backForward() instead of the following function.
-    void goToItem(HistoryItem*);
-
-    // FIXME: InspectorPageGroup is only needed to support single process debugger layout tests, it should be removed when DumpRenderTree is gone.
-    enum PageGroupType { InspectorPageGroup, PrivatePageGroup, SharedPageGroup };
+    enum PageGroupType { PrivatePageGroup, SharedPageGroup };
     void setGroupType(PageGroupType);
     void clearPageGroup();
     PageGroup& group()
@@ -183,9 +187,6 @@
     const Pagination& pagination() const { return m_pagination; }
     void setPagination(const Pagination&);
 
-    void userStyleSheetLocationChanged();
-    const String& userStyleSheet() const;
-
     void dnsPrefetchingStateChanged();
 
     static void allVisitedStateChanged(PageGroup*);
@@ -252,8 +253,10 @@
     const OwnPtr<PointerLockController> m_pointerLockController;
     RefPtr<ScrollingCoordinator> m_scrollingCoordinator;
 
+    const OwnPtr<HistoryController> m_history;
     const OwnPtr<Settings> m_settings;
     const OwnPtr<ProgressTracker> m_progress;
+    const OwnPtr<UndoStack> m_undoStack;
 
     RefPtr<Frame> m_mainFrame;
 
@@ -263,6 +266,7 @@
     EditorClient* const m_editorClient;
     ValidationMessageClient* m_validationMessageClient;
     SharedWorkerRepositoryClient* m_sharedWorkerRepositoryClient;
+    SpellCheckerClient* const m_spellCheckerClient;
 
     UseCounter m_useCounter;
 
@@ -277,9 +281,6 @@
 
     Pagination m_pagination;
 
-    String m_userStyleSheet;
-    bool m_didLoadUserStyleSheet;
-
     RefPtr<PageGroup> m_group;
 
     OwnPtr<StorageNamespace> m_sessionStorage;
diff --git a/Source/core/page/PageGroup.cpp b/Source/core/page/PageGroup.cpp
index c163264..b4a7271 100644
--- a/Source/core/page/PageGroup.cpp
+++ b/Source/core/page/PageGroup.cpp
@@ -30,6 +30,7 @@
 #include "core/dom/StyleEngine.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
@@ -44,16 +45,10 @@
 
 PageGroup* PageGroup::sharedGroup()
 {
-    static PageGroup* staticSharedGroup = create().leakRef();
+    DEFINE_STATIC_REF(PageGroup, staticSharedGroup, (create()));
     return staticSharedGroup;
 }
 
-PageGroup* PageGroup::inspectorGroup()
-{
-    static PageGroup* staticInspectorGroup = create().leakRef();
-    return staticInspectorGroup;
-}
-
 void PageGroup::addPage(Page* page)
 {
     ASSERT(page);
diff --git a/Source/core/page/PageGroup.h b/Source/core/page/PageGroup.h
index 0c7fb0d..65b24a1 100644
--- a/Source/core/page/PageGroup.h
+++ b/Source/core/page/PageGroup.h
@@ -46,7 +46,6 @@
 
         static PassRefPtr<PageGroup> create() { return adoptRef(new PageGroup()); }
         static PageGroup* sharedGroup();
-        static PageGroup* inspectorGroup();
 
         const HashSet<Page*>& pages() const { return m_pages; }
 
diff --git a/Source/core/page/PageLifecycleNotifier.cpp b/Source/core/page/PageLifecycleNotifier.cpp
index a48592b..d573334 100644
--- a/Source/core/page/PageLifecycleNotifier.cpp
+++ b/Source/core/page/PageLifecycleNotifier.cpp
@@ -30,7 +30,7 @@
 namespace WebCore {
 
 PageLifecycleNotifier::PageLifecycleNotifier(Page* context)
-    : LifecycleNotifier(context)
+    : LifecycleNotifier<Page>(context)
 {
 }
 
@@ -41,7 +41,7 @@
         m_pageObservers.add(static_cast<PageLifecycleObserver*>(observer));
     }
 
-    LifecycleNotifier::addObserver(observer);
+    LifecycleNotifier<Page>::addObserver(observer);
 }
 
 void PageLifecycleNotifier::removeObserver(PageLifecycleNotifier::Observer* observer)
@@ -51,7 +51,7 @@
         m_pageObservers.remove(static_cast<PageLifecycleObserver*>(observer));
     }
 
-    LifecycleNotifier::removeObserver(observer);
+    LifecycleNotifier<Page>::removeObserver(observer);
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/PageLifecycleObserver.cpp b/Source/core/page/PageLifecycleObserver.cpp
index 040dccc..ce6c819 100644
--- a/Source/core/page/PageLifecycleObserver.cpp
+++ b/Source/core/page/PageLifecycleObserver.cpp
@@ -42,7 +42,7 @@
 }
 
 PageLifecycleObserver::PageLifecycleObserver(Page* page)
-    : LifecycleObserver(page, PageLifecycleObserverType)
+    : LifecycleObserver<Page>(page, PageLifecycleObserverType)
 {
 }
 
diff --git a/Source/core/page/PagePopupController.cpp b/Source/core/page/PagePopupController.cpp
index ba31b02..961d96e 100644
--- a/Source/core/page/PagePopupController.cpp
+++ b/Source/core/page/PagePopupController.cpp
@@ -74,7 +74,6 @@
     return numberString;
 }
 
-#if ENABLE(CALENDAR_PICKER)
 String PagePopupController::formatMonth(int year, int zeroBaseMonth)
 {
     if (!m_popupClient)
@@ -92,7 +91,6 @@
     date.setMonthsSinceEpoch((year - 1970) * 12.0 + zeroBaseMonth);
     return m_popupClient->locale().formatDateTime(date, Locale::FormatTypeShort);
 }
-#endif
 
 void PagePopupController::clearPagePopupClient()
 {
@@ -101,7 +99,7 @@
 
 void PagePopupController::histogramEnumeration(const String& name, int sample, int boundaryValue)
 {
-    WebKit::Platform::current()->histogramEnumeration(name.utf8().data(), sample, boundaryValue);
+    blink::Platform::current()->histogramEnumeration(name.utf8().data(), sample, boundaryValue);
 }
 
 }
diff --git a/Source/core/page/PagePopupController.h b/Source/core/page/PagePopupController.h
index 398fa4e..7a4846f 100644
--- a/Source/core/page/PagePopupController.h
+++ b/Source/core/page/PagePopupController.h
@@ -46,10 +46,8 @@
     void setValue(const String&);
     void closePopup();
     String localizeNumberString(const String&);
-#if ENABLE(CALENDAR_PICKER)
     String formatMonth(int year, int zeroBaseMonth);
     String formatShortMonth(int year, int zeroBaseMonth);
-#endif
     void clearPagePopupClient();
     void histogramEnumeration(const String& name, int sample, int boundaryValue);
 
diff --git a/Source/core/page/PagePopupController.idl b/Source/core/page/PagePopupController.idl
index 069098c..0a4fbd4 100644
--- a/Source/core/page/PagePopupController.idl
+++ b/Source/core/page/PagePopupController.idl
@@ -36,7 +36,7 @@
     void setValue(DOMString value);
     void closePopup();
     DOMString localizeNumberString(DOMString numberString);
-    [Conditional=CALENDAR_PICKER] DOMString formatMonth(long year, long zeroBaseMonth);
-    [Conditional=CALENDAR_PICKER] DOMString formatShortMonth(long year, long zeroBaseMonth);
+    DOMString formatMonth(long year, long zeroBaseMonth);
+    DOMString formatShortMonth(long year, long zeroBaseMonth);
     void histogramEnumeration(DOMString name, long sample, long boundaryValue);
 };
diff --git a/Source/core/page/PageSerializer.h b/Source/core/page/PageSerializer.h
index 93a4dc1..745af7e 100644
--- a/Source/core/page/PageSerializer.h
+++ b/Source/core/page/PageSerializer.h
@@ -31,8 +31,8 @@
 #ifndef PageSerializer_h
 #define PageSerializer_h
 
-#include "weborigin/KURL.h"
-#include "weborigin/KURLHash.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/KURLHash.h"
 #include "wtf/HashMap.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/Vector.h"
diff --git a/Source/core/page/PageVisibilityState.cpp b/Source/core/page/PageVisibilityState.cpp
index 630b0db..4b015df 100644
--- a/Source/core/page/PageVisibilityState.cpp
+++ b/Source/core/page/PageVisibilityState.cpp
@@ -38,7 +38,6 @@
     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:
@@ -47,8 +46,6 @@
         return hidden;
     case PageVisibilityStatePrerender:
         return prerender;
-    case PageVisibilityStatePreview:
-        return preview;
     }
 
     ASSERT_NOT_REACHED();
diff --git a/Source/core/page/PageVisibilityState.h b/Source/core/page/PageVisibilityState.h
index 229b22f..cd09a2a 100644
--- a/Source/core/page/PageVisibilityState.h
+++ b/Source/core/page/PageVisibilityState.h
@@ -41,7 +41,6 @@
     PageVisibilityStateVisible,
     PageVisibilityStateHidden,
     PageVisibilityStatePrerender,
-    PageVisibilityStatePreview
 };
 
 String pageVisibilityStateString(PageVisibilityState);
diff --git a/Source/core/page/Settings.cpp b/Source/core/page/Settings.cpp
index 53aae2d..c341480 100644
--- a/Source/core/page/Settings.cpp
+++ b/Source/core/page/Settings.cpp
@@ -113,7 +113,7 @@
 Settings::Settings(Page* page)
     : m_page(0)
     , m_mediaTypeOverride("screen")
-    , m_textAutosizingFontScaleFactor(1)
+    , m_accessibilityFontScaleFactor(1)
     , m_deviceScaleAdjustment(1.0f)
 #if HACK_FORCE_TEXT_AUTOSIZING_ON_DESKTOP
     , m_textAutosizingWindowSizeOverride(320, 480)
@@ -133,7 +133,9 @@
     , m_touchEventEmulationEnabled(false)
     , m_openGLMultisamplingEnabled(false)
     , m_viewportEnabled(false)
+    , m_viewportMetaEnabled(false)
     , m_compositorDrivenAcceleratedScrollingEnabled(false)
+    , m_layerSquashingEnabled(false)
     , m_setImageLoadingSettingsTimer(this, &Settings::imageLoadingSettingsTimerFired)
 {
     m_page = page; // Page is not yet fully initialized wen constructing Settings, so keeping m_page null over initializeDefaultFontFamilies() call.
@@ -230,11 +232,6 @@
     return InspectorInstrumentation::overrideTextAutosizing(m_page, m_textAutosizingEnabled);
 }
 
-float Settings::textAutosizingFontScaleFactor() const
-{
-    return InspectorInstrumentation::overrideTextAutosizingFontScaleFactor(m_page, m_textAutosizingFontScaleFactor);
-}
-
 void Settings::setTextAutosizingWindowSizeOverride(const IntSize& textAutosizingWindowSizeOverride)
 {
     if (m_textAutosizingWindowSizeOverride == textAutosizingWindowSizeOverride)
@@ -273,9 +270,9 @@
     m_page->setNeedsRecalcStyleInAllFrames();
 }
 
-void Settings::setTextAutosizingFontScaleFactor(float fontScaleFactor)
+void Settings::setAccessibilityFontScaleFactor(float fontScaleFactor)
 {
-    m_textAutosizingFontScaleFactor = fontScaleFactor;
+    m_accessibilityFontScaleFactor = fontScaleFactor;
     recalculateTextAutosizingMultipliers();
 }
 
@@ -285,6 +282,11 @@
     recalculateTextAutosizingMultipliers();
 }
 
+float Settings::deviceScaleAdjustment() const
+{
+    return InspectorInstrumentation::overrideFontScaleFactor(m_page, m_deviceScaleAdjustment);
+}
+
 void Settings::setMediaTypeOverride(const String& mediaTypeOverride)
 {
     if (m_mediaTypeOverride == mediaTypeOverride)
@@ -355,16 +357,6 @@
     m_arePluginsEnabled = arePluginsEnabled;
 }
 
-void Settings::setUserStyleSheetLocation(const KURL& userStyleSheetLocation)
-{
-    if (m_userStyleSheetLocation == userStyleSheetLocation)
-        return;
-
-    m_userStyleSheetLocation = userStyleSheetLocation;
-
-    m_page->userStyleSheetLocationChanged();
-}
-
 void Settings::setDNSPrefetchingEnabled(bool dnsPrefetchingEnabled)
 {
     if (m_dnsPrefetchingEnabled == dnsPrefetchingEnabled)
@@ -403,9 +395,17 @@
     if (m_viewportEnabled == enabled)
         return;
 
+    // FIXME: Remove once Chromium-side lands.
+    setViewportMetaEnabled(enabled);
+
     m_viewportEnabled = enabled;
     if (m_page->mainFrame())
         m_page->mainFrame()->document()->updateViewportDescription();
 }
 
+void Settings::setViewportMetaEnabled(bool enabled)
+{
+    m_viewportMetaEnabled = enabled;
+}
+
 } // namespace WebCore
diff --git a/Source/core/page/Settings.h b/Source/core/page/Settings.h
index 86bfa9f..59a2add 100644
--- a/Source/core/page/Settings.h
+++ b/Source/core/page/Settings.h
@@ -31,7 +31,7 @@
 #include "core/editing/EditingBehaviorTypes.h"
 #include "platform/Timer.h"
 #include "platform/geometry/IntSize.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/HashMap.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/AtomicStringHash.h"
@@ -88,14 +88,15 @@
     void setTextAutosizingEnabled(bool);
     bool textAutosizingEnabled() const;
 
-    void setTextAutosizingFontScaleFactor(float);
-    float textAutosizingFontScaleFactor() const;
+    // Font scale factor for accessibility, applied as part of text autosizing.
+    void setAccessibilityFontScaleFactor(float);
+    float accessibilityFontScaleFactor() const { return m_accessibilityFontScaleFactor; }
 
     // Compensates for poor text legibility on mobile devices. This value is
     // multiplied by the font scale factor when performing text autosizing of
     // websites that do not set an explicit viewport description.
     void setDeviceScaleAdjustment(float);
-    float deviceScaleAdjustment() const { return m_deviceScaleAdjustment; }
+    float deviceScaleAdjustment() const;
 
     // Only set by Layout Tests, and only used if textAutosizingEnabled() returns true.
     void setTextAutosizingWindowSizeOverride(const IntSize&);
@@ -139,9 +140,6 @@
     void setDNSPrefetchingEnabled(bool);
     bool dnsPrefetchingEnabled() const { return m_dnsPrefetchingEnabled; }
 
-    void setUserStyleSheetLocation(const KURL&);
-    const KURL& userStyleSheetLocation() const { return m_userStyleSheetLocation; }
-
     static void setMockScrollbarsEnabled(bool flag);
     static bool mockScrollbarsEnabled();
 
@@ -154,18 +152,30 @@
     void setViewportEnabled(bool);
     bool viewportEnabled() const { return m_viewportEnabled; }
 
+    void setViewportMetaEnabled(bool);
+    bool viewportMetaEnabled() const
+    {
+        // FIXME: Remove and uncomment once chromium side changes land.
+        return true;
+        // return m_viewportMetaEnabled;
+    }
+
     // FIXME: This is a temporary flag and should be removed once accelerated
     // overflow scroll is ready (crbug.com/254111).
     void setCompositorDrivenAcceleratedScrollingEnabled(bool enabled) { m_compositorDrivenAcceleratedScrollingEnabled = enabled; }
     bool isCompositorDrivenAcceleratedScrollingEnabled() const { return m_compositorDrivenAcceleratedScrollingEnabled; }
 
+    // FIXME: This is a temporary flag and should be removed when squashing is ready.
+    // (crbug.com/261605)
+    void setLayerSquashingEnabled(bool enabled) { m_layerSquashingEnabled = enabled; }
+    bool isLayerSquashingEnabled() const { return m_layerSquashingEnabled; }
+
 private:
     explicit Settings(Page*);
 
     Page* m_page;
 
     String m_mediaTypeOverride;
-    KURL m_userStyleSheetLocation;
     ScriptFontFamilyMap m_standardFontFamilyMap;
     ScriptFontFamilyMap m_serifFontFamilyMap;
     ScriptFontFamilyMap m_fixedFontFamilyMap;
@@ -173,7 +183,7 @@
     ScriptFontFamilyMap m_cursiveFontFamilyMap;
     ScriptFontFamilyMap m_fantasyFontFamilyMap;
     ScriptFontFamilyMap m_pictographFontFamilyMap;
-    float m_textAutosizingFontScaleFactor;
+    float m_accessibilityFontScaleFactor;
     float m_deviceScaleAdjustment;
     IntSize m_textAutosizingWindowSizeOverride;
     bool m_textAutosizingEnabled : 1;
@@ -192,11 +202,15 @@
     bool m_touchEventEmulationEnabled : 1;
     bool m_openGLMultisamplingEnabled : 1;
     bool m_viewportEnabled : 1;
+    bool m_viewportMetaEnabled : 1;
 
     // FIXME: This is a temporary flag and should be removed once accelerated
     // overflow scroll is ready (crbug.com/254111).
     bool m_compositorDrivenAcceleratedScrollingEnabled : 1;
 
+    // FIXME: This is a temporary flag and should be removed when squashing is ready.
+    bool m_layerSquashingEnabled : 1;
+
     Timer<Settings> m_setImageLoadingSettingsTimer;
     void imageLoadingSettingsTimerFired(Timer<Settings>*);
     void recalculateTextAutosizingMultipliers();
diff --git a/Source/core/page/Settings.in b/Source/core/page/Settings.in
index 47b3187..4d21a27 100644
--- a/Source/core/page/Settings.in
+++ b/Source/core/page/Settings.in
@@ -72,7 +72,6 @@
 shouldPrintBackgrounds initial=false
 
 textAreasAreResizable initial=false, setNeedsStyleRecalcInAllFrames=1
-authorAndUserStylesEnabled initial=true, setNeedsStyleRecalcInAllFrames=1
 acceleratedCompositingEnabled initial=true, setNeedsStyleRecalcInAllFrames=1
 
 # Debugging feature used for accelerated compositing layers.
diff --git a/Source/core/platform/MIMETypeFromURL.h b/Source/core/page/SpellCheckerClient.h
similarity index 65%
copy from Source/core/platform/MIMETypeFromURL.h
copy to Source/core/page/SpellCheckerClient.h
index 50af6c2..73a49e5 100644
--- a/Source/core/platform/MIMETypeFromURL.h
+++ b/Source/core/page/SpellCheckerClient.h
@@ -1,5 +1,6 @@
 /*
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2006, 2007 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
@@ -23,18 +24,30 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MIMETypeFromURL_h
-#define MIMETypeFromURL_h
+#ifndef SpellCheckerClient_h
+#define SpellCheckerClient_h
 
 #include "wtf/Forward.h"
 
 namespace WebCore {
 
-class KURL;
+class TextCheckerClient;
 
-String mimeTypeFromDataURL(const String& url);
-String mimeTypeFromURL(const KURL&);
+class SpellCheckerClient {
+public:
+    virtual ~SpellCheckerClient() { }
 
-} // namespace WebCore
+    virtual bool isContinuousSpellCheckingEnabled() = 0;
+    virtual void toggleContinuousSpellChecking() = 0;
+    virtual bool isGrammarCheckingEnabled() = 0;
 
-#endif // MIMETypeFromURL_h
+    virtual TextCheckerClient& textChecker() = 0;
+
+    virtual void updateSpellingUIWithMisspelledWord(const WTF::String&) = 0;
+    virtual void showSpellingUI(bool show) = 0;
+    virtual bool spellingUIIsShowing() = 0;
+};
+
+}
+
+#endif // SpellCheckerClient_h
diff --git a/Source/core/page/TouchDisambiguation.cpp b/Source/core/page/TouchDisambiguation.cpp
index 019e61f..5fda7d8d 100644
--- a/Source/core/page/TouchDisambiguation.cpp
+++ b/Source/core/page/TouchDisambiguation.cpp
@@ -59,11 +59,11 @@
     while (node) {
         // Skip the whole sub-tree if the node doesn't propagate events.
         if (node != eventNode && node->willRespondToMouseClickEvents()) {
-            node = NodeTraversal::nextSkippingChildren(node, eventNode);
+            node = NodeTraversal::nextSkippingChildren(*node, eventNode);
             continue;
         }
         result.unite(node->pixelSnappedBoundingBox());
-        node = NodeTraversal::next(node, eventNode);
+        node = NodeTraversal::next(*node, eventNode);
     }
     return eventNode->document().view()->contentsToWindow(result);
 }
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index ca72786..07ec6a2 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -61,11 +61,11 @@
 #include "public/platform/WebScrollbarThemePainter.h"
 #include "wtf/text/StringBuilder.h"
 
-using WebKit::WebLayer;
-using WebKit::WebLayerPositionConstraint;
-using WebKit::WebRect;
-using WebKit::WebScrollbarLayer;
-using WebKit::WebVector;
+using blink::WebLayer;
+using blink::WebLayerPositionConstraint;
+using blink::WebRect;
+using blink::WebScrollbarLayer;
+using blink::WebVector;
 
 
 namespace WebCore {
@@ -90,6 +90,8 @@
     : m_page(page)
     , m_scrollGestureRegionIsDirty(false)
     , m_touchEventTargetRectsAreDirty(false)
+    , m_wasFrameScrollable(false)
+    , m_lastMainThreadScrollingReasons(0)
 {
 }
 
@@ -151,6 +153,12 @@
         m_touchEventTargetRectsAreDirty = false;
     }
 
+    FrameView* frameView = m_page->mainFrame()->view();
+    bool frameIsScrollable = frameView && frameView->isScrollable();
+    if (m_wasFrameScrollable != frameIsScrollable)
+        updateShouldUpdateScrollLayerPositionOnMainThread();
+    m_wasFrameScrollable = frameIsScrollable;
+
     const FrameTree& tree = m_page->mainFrame()->tree();
     for (const Frame* child = tree.firstChild(); child; child = child->tree().nextSibling()) {
         if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(child->view()))
@@ -172,7 +180,7 @@
 
 static WebLayerPositionConstraint computePositionConstraint(const RenderLayer* layer)
 {
-    ASSERT(layer->compositedLayerMapping());
+    ASSERT(layer->hasCompositedLayerMapping());
     do {
         if (layer->renderer()->style()->position() == FixedPosition) {
             const RenderObject* fixedPositionObject = layer->renderer();
@@ -185,14 +193,14 @@
 
         // Composited layers that inherit a fixed position state will be positioned with respect to the nearest compositedLayerMapping's GraphicsLayer.
         // So, once we find a layer that has its own compositedLayerMapping, we can stop searching for a fixed position RenderObject.
-    } while (layer && layer->compositedLayerMapping());
+    } while (layer && !layer->hasCompositedLayerMapping());
     return WebLayerPositionConstraint();
 }
 
 void ScrollingCoordinator::updateLayerPositionConstraint(RenderLayer* layer)
 {
-    ASSERT(layer->compositedLayerMapping());
-    CompositedLayerMapping* compositedLayerMapping = layer->compositedLayerMapping();
+    ASSERT(layer->hasCompositedLayerMapping());
+    CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
     GraphicsLayer* mainLayer = compositedLayerMapping->childForSuperlayers();
 
     // Avoid unnecessary commits
@@ -219,18 +227,18 @@
 static PassOwnPtr<WebScrollbarLayer> createScrollbarLayer(Scrollbar* scrollbar)
 {
     ScrollbarTheme* theme = scrollbar->theme();
-    WebKit::WebScrollbarThemePainter painter(theme, scrollbar);
-    OwnPtr<WebKit::WebScrollbarThemeGeometry> geometry(WebKit::WebScrollbarThemeGeometryNative::create(theme));
+    blink::WebScrollbarThemePainter painter(theme, scrollbar);
+    OwnPtr<blink::WebScrollbarThemeGeometry> geometry(blink::WebScrollbarThemeGeometryNative::create(theme));
 
-    OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createScrollbarLayer(new WebKit::WebScrollbarImpl(scrollbar), painter, geometry.leakPtr()));
+    OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(blink::Platform::current()->compositorSupport()->createScrollbarLayer(new blink::WebScrollbarImpl(scrollbar), painter, geometry.leakPtr()));
     GraphicsLayer::registerContentsLayer(scrollbarLayer->layer());
     return scrollbarLayer.release();
 }
 
 PassOwnPtr<WebScrollbarLayer> ScrollingCoordinator::createSolidColorScrollbarLayer(ScrollbarOrientation orientation, int thumbThickness, bool isLeftSideVerticalScrollbar)
 {
-    WebKit::WebScrollbar::Orientation webOrientation = (orientation == HorizontalScrollbar) ? WebKit::WebScrollbar::Horizontal : WebKit::WebScrollbar::Vertical;
-    OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createSolidColorScrollbarLayer(webOrientation, thumbThickness, isLeftSideVerticalScrollbar));
+    blink::WebScrollbar::Orientation webOrientation = (orientation == HorizontalScrollbar) ? blink::WebScrollbar::Horizontal : blink::WebScrollbar::Vertical;
+    OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(blink::Platform::current()->compositorSupport()->createSolidColorScrollbarLayer(webOrientation, thumbThickness, isLeftSideVerticalScrollbar));
     GraphicsLayer::registerContentsLayer(scrollbarLayer->layer());
     return scrollbarLayer.release();
 }
@@ -257,7 +265,7 @@
     scrollbarGraphicsLayer->setDrawsContent(false);
 }
 
-WebScrollbarLayer* ScrollingCoordinator::addWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, PassOwnPtr<WebKit::WebScrollbarLayer> scrollbarLayer)
+WebScrollbarLayer* ScrollingCoordinator::addWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, PassOwnPtr<blink::WebScrollbarLayer> scrollbarLayer)
 {
     ScrollbarMap& scrollbars = orientation == HorizontalScrollbar ? m_horizontalScrollbars : m_verticalScrollbars;
     return scrollbars.add(scrollableArea, scrollbarLayer).iterator->value.get();
@@ -493,6 +501,18 @@
     setTouchEventTargetRects(touchEventTargetRects);
 }
 
+void ScrollingCoordinator::reset()
+{
+    m_horizontalScrollbars.clear();
+    m_verticalScrollbars.clear();
+    m_layersWithTouchRects.clear();
+    m_wasFrameScrollable = false;
+
+    // This is retained for testing.
+    m_lastMainThreadScrollingReasons = 0;
+    setShouldUpdateScrollLayerPositionOnMainThread(m_lastMainThreadScrollingReasons);
+}
+
 // 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)
@@ -510,7 +530,9 @@
         WebVector<WebRect> webRects(iter->value.size());
         for (size_t i = 0; i < iter->value.size(); ++i)
             webRects[i] = enclosingIntRect(iter->value[i]);
-        CompositedLayerMapping* compositedLayerMapping = layer->compositedLayerMapping();
+        // This should be ensured by convertLayerRectsToEnclosingCompositedLayer above.
+        ASSERT(layer->hasCompositedLayerMapping());
+        CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
         // If the layer is using composited scrolling, then it's the contents that these
         // rects apply to.
         GraphicsLayer* graphicsLayer = compositedLayerMapping->scrollingContentsLayer();
@@ -523,10 +545,14 @@
 
     // If there are any layers left that we haven't updated, clear them out.
     for (HashSet<const RenderLayer*>::iterator it = oldLayersWithTouchRects.begin(); it != oldLayersWithTouchRects.end(); ++it) {
-        if (CompositedLayerMapping* compositedLayerMapping = (*it)->compositedLayerMapping()) {
-            GraphicsLayer* graphicsLayer = compositedLayerMapping->scrollingContentsLayer();
+        // FIXME: This is a bug. What's happening here is that we're clearing touch regions for
+        // layers that we didn't visit above. That assumes a 1:1 mapping between RenderLayer and
+        // the graphics layer that owns the touch rects. This is false in the case of
+        // HasOwnBackingButPaintsIntoAncestor and will be extra-false in the world of squashing.
+        if ((*it)->hasCompositedLayerMapping()) {
+            GraphicsLayer* graphicsLayer = (*it)->compositedLayerMapping()->scrollingContentsLayer();
             if (!graphicsLayer)
-                graphicsLayer = compositedLayerMapping->mainGraphicsLayer();
+                graphicsLayer = (*it)->compositedLayerMapping()->mainGraphicsLayer();
             graphicsLayer->platformLayer()->setTouchEventHandlerRegion(WebVector<WebRect>());
         }
     }
@@ -553,7 +579,7 @@
 void ScrollingCoordinator::updateScrollParentForGraphicsLayer(GraphicsLayer* child, RenderLayer* parent)
 {
     WebLayer* scrollParentWebLayer = 0;
-    if (parent && parent->compositedLayerMapping())
+    if (parent && parent->hasCompositedLayerMapping())
         scrollParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->compositedLayerMapping()->parentForSublayers());
 
     child->setScrollParent(scrollParentWebLayer);
@@ -562,7 +588,7 @@
 void ScrollingCoordinator::updateClipParentForGraphicsLayer(GraphicsLayer* child, RenderLayer* parent)
 {
     WebLayer* clipParentWebLayer = 0;
-    if (parent && parent->compositedLayerMapping())
+    if (parent && parent->hasCompositedLayerMapping())
         clipParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->compositedLayerMapping()->parentForSublayers());
 
     child->setClipParent(clipParentWebLayer);
@@ -587,8 +613,10 @@
 
 void ScrollingCoordinator::setShouldUpdateScrollLayerPositionOnMainThread(MainThreadScrollingReasons reasons)
 {
-    if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(m_page->mainFrame()->view()))
+    if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(m_page->mainFrame()->view())) {
+        m_lastMainThreadScrollingReasons = reasons;
         scrollLayer->setShouldScrollOnMainThread(reasons);
+    }
 }
 
 void ScrollingCoordinator::pageDestroyed()
@@ -853,8 +881,11 @@
 
 MainThreadScrollingReasons ScrollingCoordinator::mainThreadScrollingReasons() const
 {
+    // The main thread scrolling reasons are applicable to scrolls of the main
+    // frame. If it does not exist or if it is not scrollable, there is no
+    // reason to force main thread scrolling.
     FrameView* frameView = m_page->mainFrame()->view();
-    if (!frameView)
+    if (!frameView || !frameView->isScrollable())
         return static_cast<MainThreadScrollingReasons>(0);
 
     MainThreadScrollingReasons mainThreadScrollingReasons = (MainThreadScrollingReasons)0;
@@ -890,7 +921,14 @@
 
 String ScrollingCoordinator::mainThreadScrollingReasonsAsText() const
 {
-    return mainThreadScrollingReasonsAsText(mainThreadScrollingReasons());
+    return mainThreadScrollingReasonsAsText(m_lastMainThreadScrollingReasons);
+}
+
+bool ScrollingCoordinator::frameViewIsScrollableIsDirty() const
+{
+    FrameView* frameView = m_page->mainFrame()->view();
+    bool frameIsScrollable = frameView && frameView->isScrollable();
+    return frameIsScrollable != m_wasFrameScrollable;
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.h b/Source/core/page/scrolling/ScrollingCoordinator.h
index 0c42913..3acfe9a 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -32,7 +32,7 @@
 #include "platform/scroll/ScrollTypes.h"
 #include "wtf/text/WTFString.h"
 
-namespace WebKit {
+namespace blink {
 class WebLayer;
 class WebScrollbarLayer;
 }
@@ -66,7 +66,7 @@
     // Should be called after compositing has been updated.
     void updateAfterCompositingChange();
 
-    bool needsToUpdateAfterCompositingChange() const { return m_scrollGestureRegionIsDirty || m_touchEventTargetRectsAreDirty; }
+    bool needsToUpdateAfterCompositingChange() const { return m_scrollGestureRegionIsDirty || m_touchEventTargetRectsAreDirty || frameViewIsScrollableIsDirty(); }
 
     // Should be called whenever a wheel event handler is added or removed in the
     // frame view's underlying document.
@@ -95,7 +95,7 @@
     MainThreadScrollingReasons mainThreadScrollingReasons() const;
     bool shouldUpdateScrollLayerPositionOnMainThread() const { return mainThreadScrollingReasons() != 0; }
 
-    PassOwnPtr<WebKit::WebScrollbarLayer> createSolidColorScrollbarLayer(ScrollbarOrientation, int thumbThickness, bool isLeftSideVerticalScrollbar);
+    PassOwnPtr<blink::WebScrollbarLayer> createSolidColorScrollbarLayer(ScrollbarOrientation, int thumbThickness, bool isLeftSideVerticalScrollbar);
 
     void willDestroyScrollableArea(ScrollableArea*);
     // Returns true if the coordinator handled this change.
@@ -115,6 +115,10 @@
 
     void updateTouchEventTargetRectsIfNeeded();
 
+    // For testing purposes only. This ScrollingCoordinator is reused between layout test, and must be reset
+    // for the results to be valid.
+    void reset();
+
 protected:
     explicit ScrollingCoordinator(Page*);
 
@@ -140,7 +144,7 @@
     bool hasVisibleSlowRepaintViewportConstrainedObjects(FrameView*) const;
     void updateShouldUpdateScrollLayerPositionOnMainThread();
 
-    static WebKit::WebLayer* scrollingWebLayerForScrollableArea(ScrollableArea*);
+    static blink::WebLayer* scrollingWebLayerForScrollableArea(ScrollableArea*);
 
     bool touchHitTestingEnabled() const;
     void setShouldHandleScrollGestureOnMainThreadRegion(const Region&);
@@ -148,15 +152,20 @@
     void computeTouchEventTargetRects(LayerHitTestRects&);
     void setWheelEventHandlerCount(unsigned);
 
-    WebKit::WebScrollbarLayer* addWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation, PassOwnPtr<WebKit::WebScrollbarLayer>);
-    WebKit::WebScrollbarLayer* getWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
+    blink::WebScrollbarLayer* addWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation, PassOwnPtr<blink::WebScrollbarLayer>);
+    blink::WebScrollbarLayer* getWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
     void removeWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
 
+    bool frameViewIsScrollableIsDirty() const;
 
-    typedef HashMap<ScrollableArea*, OwnPtr<WebKit::WebScrollbarLayer> > ScrollbarMap;
+    typedef HashMap<ScrollableArea*, OwnPtr<blink::WebScrollbarLayer> > ScrollbarMap;
     ScrollbarMap m_horizontalScrollbars;
     ScrollbarMap m_verticalScrollbars;
     HashSet<const RenderLayer*> m_layersWithTouchRects;
+    bool m_wasFrameScrollable;
+
+    // This is retained for testing.
+    MainThreadScrollingReasons m_lastMainThreadScrollingReasons;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/ContextMenu.cpp b/Source/core/platform/ContextMenu.cpp
deleted file mode 100644
index 746bc5a..0000000
--- a/Source/core/platform/ContextMenu.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2010 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. 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 INC. 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/ContextMenu.h"
-
-namespace WebCore {
-
-static const ContextMenuItem* findItemWithAction(unsigned action, const Vector<ContextMenuItem>& items)
-{
-    for (size_t i = 0; i < items.size(); ++i) {
-        const ContextMenuItem& item = items[i];
-        if (item.action() == static_cast<ContextMenuAction>(action))
-            return &item;
-        if (item.type() != SubmenuType)
-            continue;
-        if (const ContextMenuItem* subMenuItem = findItemWithAction(action, item.subMenuItems()))
-            return subMenuItem;
-    }
-
-    return 0;
-}
-
-const ContextMenuItem* ContextMenu::itemWithAction(unsigned action) const
-{
-    return findItemWithAction(action, m_items);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/ContextMenu.h b/Source/core/platform/ContextMenu.h
deleted file mode 100644
index f2c9a91..0000000
--- a/Source/core/platform/ContextMenu.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, 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 ContextMenu_h
-#define ContextMenu_h
-
-#include "core/platform/ContextMenuItem.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-    class ContextMenu {
-        WTF_MAKE_NONCOPYABLE(ContextMenu); WTF_MAKE_FAST_ALLOCATED;
-    public:
-        ContextMenu() { }
-        const ContextMenuItem* itemWithAction(unsigned) const;
-        const Vector<ContextMenuItem>& items() const { return m_items; }
-        void appendItem(const ContextMenuItem& item) { m_items.append(item); }
-
-    private:
-        Vector<ContextMenuItem> m_items;
-    };
-}
-
-#endif // ContextMenu_h
diff --git a/Source/core/platform/ContextMenuItem.cpp b/Source/core/platform/ContextMenuItem.cpp
deleted file mode 100644
index 3be567b..0000000
--- a/Source/core/platform/ContextMenuItem.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2010 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. 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 INC. 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/ContextMenuItem.h"
-
-#include "core/platform/ContextMenu.h"
-
-namespace WebCore {
-
-ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, ContextMenu* subMenu)
-    : m_type(type)
-    , m_action(action)
-    , m_title(title)
-    , m_enabled(true)
-    , m_checked(false)
-{
-    if (subMenu)
-        setSubMenu(subMenu);
-}
-
-ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, bool enabled, bool checked)
-    : m_type(type)
-    , m_action(action)
-    , m_title(title)
-    , m_enabled(enabled)
-    , m_checked(checked)
-{
-}
-
-ContextMenuItem::ContextMenuItem(ContextMenuAction action, const String& title, bool enabled, bool checked, const Vector<ContextMenuItem>& subMenuItems)
-    : m_type(SubmenuType)
-    , m_action(action)
-    , m_title(title)
-    , m_enabled(enabled)
-    , m_checked(checked)
-    , m_subMenuItems(subMenuItems)
-{
-}
-
-ContextMenuItem::~ContextMenuItem()
-{
-}
-
-void ContextMenuItem::setSubMenu(ContextMenu* subMenu)
-{
-    if (subMenu) {
-        m_type = SubmenuType;
-        m_subMenuItems = subMenu->items();
-    } else {
-        m_type = ActionType;
-        m_subMenuItems.clear();
-    }
-}
-
-void ContextMenuItem::setType(ContextMenuItemType type)
-{
-    m_type = type;
-}
-
-ContextMenuItemType ContextMenuItem::type() const
-{
-    return m_type;
-}
-
-void ContextMenuItem::setAction(ContextMenuAction action)
-{
-    m_action = action;
-}
-
-ContextMenuAction ContextMenuItem::action() const
-{
-    return m_action;
-}
-
-void ContextMenuItem::setChecked(bool checked)
-{
-    m_checked = checked;
-}
-
-bool ContextMenuItem::checked() const
-{
-    return m_checked;
-}
-
-void ContextMenuItem::setEnabled(bool enabled)
-{
-    m_enabled = enabled;
-}
-
-bool ContextMenuItem::enabled() const
-{
-    return m_enabled;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/ContextMenuItem.h b/Source/core/platform/ContextMenuItem.h
deleted file mode 100644
index 67cc7c4..0000000
--- a/Source/core/platform/ContextMenuItem.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2010 Igalia S.L
- *
- * 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 ContextMenuItem_h
-#define ContextMenuItem_h
-
-#include "wtf/OwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-    class ContextMenu;
-
-    enum ContextMenuAction {
-        ContextMenuItemBaseCustomTag = 5000,
-        ContextMenuItemCustomTagNoAction = 5998,
-        ContextMenuItemLastCustomTag = 5999
-    };
-
-    enum ContextMenuItemType {
-        ActionType,
-        CheckableActionType,
-        SeparatorType,
-        SubmenuType
-    };
-
-    class ContextMenuItem {
-        WTF_MAKE_FAST_ALLOCATED;
-    public:
-        ContextMenuItem(ContextMenuItemType, ContextMenuAction, const String&, ContextMenu* subMenu = 0);
-        ContextMenuItem(ContextMenuItemType, ContextMenuAction, const String&, bool enabled, bool checked);
-
-        ~ContextMenuItem();
-
-        void setType(ContextMenuItemType);
-        ContextMenuItemType type() const;
-
-        void setAction(ContextMenuAction);
-        ContextMenuAction action() const;
-
-        void setChecked(bool = true);
-        bool checked() const;
-
-        void setEnabled(bool = true);
-        bool enabled() const;
-
-        void setSubMenu(ContextMenu*);
-
-        ContextMenuItem(ContextMenuAction, const String&, bool enabled, bool checked, const Vector<ContextMenuItem>& subMenuItems);
-
-        void setTitle(const String& title) { m_title = title; }
-        const String& title() const { return m_title; }
-
-        const Vector<ContextMenuItem>& subMenuItems() const { return m_subMenuItems; }
-   private:
-        ContextMenuItemType m_type;
-        ContextMenuAction m_action;
-        String m_title;
-        bool m_enabled;
-        bool m_checked;
-        Vector<ContextMenuItem> m_subMenuItems;
-    };
-}
-
-#endif // ContextMenuItem_h
diff --git a/Source/core/platform/Cookie.h b/Source/core/platform/Cookie.h
deleted file mode 100644
index 287a990..0000000
--- a/Source/core/platform/Cookie.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2009 Joseph Pecoraro. 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 Cookie_h
-#define Cookie_h
-
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-    // This struct is currently only used to provide more cookies information
-    // to the Web Inspector.
-
-    struct Cookie {
-        Cookie() { }
-
-        Cookie(const String& name, const String& value, const String& domain,
-                const String& path, double expires, bool httpOnly, bool secure,
-                bool session)
-            : name(name)
-            , value(value)
-            , domain(domain)
-            , path(path)
-            , expires(expires)
-            , httpOnly(httpOnly)
-            , secure(secure)
-            , session(session)
-        {
-        }
-
-        String name;
-        String value;
-        String domain;
-        String path;
-        double expires;
-        bool httpOnly;
-        bool secure;
-        bool session;
-    };
-
-    struct CookieHash {
-        static unsigned hash(Cookie key)
-        {
-            return StringHash::hash(key.name) + StringHash::hash(key.domain) + StringHash::hash(key.path) + key.secure;
-        }
-
-        static bool equal(Cookie a, Cookie b)
-        {
-            return a.name == b.name && a.domain == b.domain && a.path == b.path && a.secure == b.secure;
-        }
-    };
-}
-
-namespace WTF {
-    template<typename T> struct DefaultHash;
-    template<> struct DefaultHash<WebCore::Cookie> {
-        typedef WebCore::CookieHash Hash;
-    };
-}
-
-#endif
diff --git a/Source/core/platform/CryptoResult.h b/Source/core/platform/CryptoResult.h
index c62768c..45aaef5 100644
--- a/Source/core/platform/CryptoResult.h
+++ b/Source/core/platform/CryptoResult.h
@@ -42,14 +42,14 @@
     virtual ~CryptoResult() { }
 
     virtual void completeWithError() = 0;
-    virtual void completeWithBuffer(const WebKit::WebArrayBuffer&) = 0;
+    virtual void completeWithBuffer(const blink::WebArrayBuffer&) = 0;
     virtual void completeWithBoolean(bool) = 0;
-    virtual void completeWithKey(const WebKit::WebCryptoKey&) = 0;
-    virtual void completeWithKeyPair(const WebKit::WebCryptoKey& publicKey, const WebKit::WebCryptoKey& privateKey) = 0;
+    virtual void completeWithKey(const blink::WebCryptoKey&) = 0;
+    virtual void completeWithKeyPair(const blink::WebCryptoKey& publicKey, const blink::WebCryptoKey& privateKey) = 0;
 
-    WebKit::WebCryptoResult result()
+    blink::WebCryptoResult result()
     {
-        return WebKit::WebCryptoResult(this);
+        return blink::WebCryptoResult(this);
     }
 };
 
diff --git a/Source/core/platform/DEPS b/Source/core/platform/DEPS
index 3d6511a..f08d238 100644
--- a/Source/core/platform/DEPS
+++ b/Source/core/platform/DEPS
@@ -10,16 +10,9 @@
     "+webp",
     # platform/ shouldn't depends on core/ but unfortunately does (crbug.com/258901).
     # Please don't add anything to this list of exceptions.
-    "!core/accessibility",
-    "!core/css",
     "!core/dom",
-    "!core/editing",
     "!core/fileapi",
     "!core/html",
-    "!core/inspector",
     "!core/fetch",
-    "!core/frame",
-    "!core/page",
-    "!core/plugins",
     "!core/rendering",
 ]
diff --git a/Source/core/platform/DragImage.cpp b/Source/core/platform/DragImage.cpp
index 2c09410..3a07431 100644
--- a/Source/core/platform/DragImage.cpp
+++ b/Source/core/platform/DragImage.cpp
@@ -43,10 +43,10 @@
 #include "platform/graphics/Color.h"
 #include "platform/graphics/TextRun.h"
 #include "platform/transforms/AffineTransform.h"
+#include "platform/weborigin/KURL.h"
 #include "skia/ext/image_operations.h"
 #include "third_party/skia/include/core/SkCanvas.h"
 #include "third_party/skia/include/core/SkMatrix.h"
-#include "weborigin/KURL.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/platform/KillRing.h b/Source/core/platform/KillRing.h
deleted file mode 100644
index 5e743bb..0000000
--- a/Source/core/platform/KillRing.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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 KillRing_h
-#define KillRing_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KillRing {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    void append(const String&);
-    void prepend(const String&);
-    String yank();
-    void startNewSequence();
-    void setToYankedState();
-};
-
-} // namespace WebCore
-
-#endif // KillRing_h
diff --git a/Source/core/platform/KillRingNone.cpp b/Source/core/platform/KillRingNone.cpp
deleted file mode 100644
index 2fce392..0000000
--- a/Source/core/platform/KillRingNone.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.
- */
-
-#include "config.h"
-#include "core/platform/KillRing.h"
-
-namespace WebCore {
-
-void KillRing::append(const String&)
-{
-}
-
-void KillRing::prepend(const String&)
-{
-}
-
-String KillRing::yank()
-{
-    return String();
-}
-
-void KillRing::startNewSequence()
-{
-}
-
-void KillRing::setToYankedState()
-{
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/MIMETypeFromURL.cpp b/Source/core/platform/MIMETypeFromURL.cpp
deleted file mode 100644
index 74dba93..0000000
--- a/Source/core/platform/MIMETypeFromURL.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2004, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2012 Research In Motion Limited. 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 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/platform/MIMETypeFromURL.h"
-
-#include "core/platform/MIMETypeRegistry.h"
-#include "weborigin/KURL.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-String mimeTypeFromDataURL(const String& url)
-{
-    ASSERT(protocolIs(url, "data"));
-    size_t index = url.find(';');
-    if (index == kNotFound)
-        index = url.find(',');
-    if (index != kNotFound) {
-        if (index > 5)
-            return url.substring(5, index - 5).lower();
-        return "text/plain"; // Data URLs with no MIME type are considered text/plain.
-    }
-    return "";
-}
-
-String mimeTypeFromURL(const KURL& url)
-{
-    String decodedPath = decodeURLEscapeSequences(url.path());
-    String extension = decodedPath.substring(decodedPath.reverseFind('.') + 1);
-
-    // We don't use MIMETypeRegistry::getMIMETypeForPath() because it returns "application/octet-stream" upon failure
-    return MIMETypeRegistry::getMIMETypeForExtension(extension);
-}
-
-}
diff --git a/Source/core/platform/MIMETypeRegistry.h b/Source/core/platform/MIMETypeRegistry.h
deleted file mode 100644
index 983aa85..0000000
--- a/Source/core/platform/MIMETypeRegistry.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, 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 MIMETypeRegistry_h
-#define MIMETypeRegistry_h
-
-#include "wtf/HashSet.h"
-#include "wtf/Vector.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class MIMETypeRegistry {
-public:
-    static String getMIMETypeForExtension(const String& extension);
-    static String getWellKnownMIMETypeForExtension(const String& extension);
-
-    static String getMIMETypeForPath(const String& path);
-
-    // Check to see if a mime type is suitable for being loaded inline as an
-    // image (e.g., <img> tags).
-    static bool isSupportedImageMIMEType(const String& mimeType);
-
-    // Check to see if a mime type is suitable for being loaded as an image
-    // document in a frame.
-    static bool isSupportedImageResourceMIMEType(const String& mimeType);
-
-    // Check to see if a mime type is suitable for being encoded.
-    static bool isSupportedImageMIMETypeForEncoding(const String& mimeType);
-
-    // Check to see if a mime type is suitable for being loaded as a JavaScript
-    // resource.
-    static bool isSupportedJavaScriptMIMEType(const String& mimeType);
-
-    // Check to see if a non-image mime type is suitable for being loaded as a
-    // document in a frame.  Includes supported JavaScript MIME types.
-    static bool isSupportedNonImageMIMEType(const String& mimeType);
-
-    // Check to see if the mime type and codecs are supported by the MediaSource implementation.
-    static bool isSupportedMediaSourceMIMEType(const String& mimeType, const String& codecs);
-
-    // Check to see if a mime type is a valid Java applet mime type
-    static bool isJavaAppletMIMEType(const String& mimeType);
-};
-
-} // namespace WebCore
-
-#endif // MIMETypeRegistry_h
diff --git a/Source/core/platform/Pasteboard.cpp b/Source/core/platform/Pasteboard.cpp
index c34633a..e03be5a 100644
--- a/Source/core/platform/Pasteboard.cpp
+++ b/Source/core/platform/Pasteboard.cpp
@@ -35,8 +35,6 @@
 #include "SVGNames.h"
 #include "XLinkNames.h"
 #include "core/dom/Element.h"
-#include "core/dom/Range.h"
-#include "core/editing/markup.h"
 #include "core/fetch/ImageResource.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
@@ -44,12 +42,12 @@
 #include "core/platform/graphics/skia/NativeImageSkia.h"
 #include "core/rendering/RenderImage.h"
 #include "platform/clipboard/ClipboardUtilities.h"
+#include "platform/weborigin/KURL.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebClipboard.h"
 #include "public/platform/WebDragData.h"
 #include "public/platform/WebString.h"
 #include "public/platform/WebURL.h"
-#include "weborigin/KURL.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 
@@ -62,31 +60,18 @@
 }
 
 Pasteboard::Pasteboard()
-    : m_buffer(WebKit::WebClipboard::BufferStandard)
+    : m_buffer(blink::WebClipboard::BufferStandard)
 {
 }
 
 bool Pasteboard::isSelectionMode() const
 {
-    return m_buffer == WebKit::WebClipboard::BufferSelection;
+    return m_buffer == blink::WebClipboard::BufferSelection;
 }
 
 void Pasteboard::setSelectionMode(bool selectionMode)
 {
-    m_buffer = selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard;
-}
-
-void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, const String& text)
-{
-    String html = createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs);
-    KURL url = selectedRange->startContainer()->document().url();
-    String plainText = text;
-#if OS(WIN)
-    replaceNewlinesWithWindowsStyleNewlines(plainText);
-#endif
-    replaceNBSPWithSpace(plainText);
-
-    WebKit::Platform::current()->clipboard()->writeHTML(html, url, plainText, canSmartCopyOrDelete);
+    m_buffer = selectionMode ? blink::WebClipboard::BufferSelection : blink::WebClipboard::BufferStandard;
 }
 
 void Pasteboard::writePlainText(const String& text, SmartReplaceOption)
@@ -95,9 +80,9 @@
 #if OS(WIN)
     String plainText(text);
     replaceNewlinesWithWindowsStyleNewlines(plainText);
-    WebKit::Platform::current()->clipboard()->writePlainText(plainText);
+    blink::Platform::current()->clipboard()->writePlainText(plainText);
 #else
-    WebKit::Platform::current()->clipboard()->writePlainText(text);
+    blink::Platform::current()->clipboard()->writePlainText(text);
 #endif
 }
 
@@ -129,34 +114,34 @@
     else if (node->hasTagName(HTMLNames::embedTag) || node->hasTagName(HTMLNames::objectTag))
         urlString = toElement(node)->imageSourceURL();
     KURL url = urlString.isEmpty() ? KURL() : node->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
-    WebKit::WebImage webImage = bitmap->bitmap();
-    WebKit::Platform::current()->clipboard()->writeImage(webImage, WebKit::WebURL(url), WebKit::WebString(title));
+    blink::WebImage webImage = bitmap->bitmap();
+    blink::Platform::current()->clipboard()->writeImage(webImage, blink::WebURL(url), blink::WebString(title));
 }
 
 void Pasteboard::writeDataObject(PassRefPtr<ChromiumDataObject> dataObject)
 {
-    WebKit::Platform::current()->clipboard()->writeDataObject(dataObject);
+    blink::Platform::current()->clipboard()->writeDataObject(dataObject);
 }
 
 bool Pasteboard::canSmartReplace()
 {
-    return WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatSmartPaste, m_buffer);
+    return blink::Platform::current()->clipboard()->isFormatAvailable(blink::WebClipboard::FormatSmartPaste, m_buffer);
 }
 
 bool Pasteboard::isHTMLAvailable()
 {
-    return WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatHTML, m_buffer);
+    return blink::Platform::current()->clipboard()->isFormatAvailable(blink::WebClipboard::FormatHTML, m_buffer);
 }
 
 String Pasteboard::plainText()
 {
-    return WebKit::Platform::current()->clipboard()->readPlainText(m_buffer);
+    return blink::Platform::current()->clipboard()->readPlainText(m_buffer);
 }
 
 String Pasteboard::readHTML(KURL& url, unsigned& fragmentStart, unsigned& fragmentEnd)
 {
-    WebKit::WebURL webURL;
-    WebKit::WebString markup = WebKit::Platform::current()->clipboard()->readHTML(m_buffer, &webURL, &fragmentStart, &fragmentEnd);
+    blink::WebURL webURL;
+    blink::WebString markup = blink::Platform::current()->clipboard()->readHTML(m_buffer, &webURL, &fragmentStart, &fragmentEnd);
     if (!markup.isEmpty()) {
         url = webURL;
         // fragmentStart and fragmentEnd are populated by WebClipboard::readHTML.
@@ -168,4 +153,15 @@
     return markup;
 }
 
+void Pasteboard::writeHTML(const String& markup, const KURL& documentURL, const String& plainText, bool canSmartCopyOrDelete)
+{
+    String text = plainText;
+#if OS(WIN)
+    replaceNewlinesWithWindowsStyleNewlines(text);
+#endif
+    replaceNBSPWithSpace(text);
+
+    blink::Platform::current()->clipboard()->writeHTML(markup, documentURL, text, canSmartCopyOrDelete);
+}
+
 } // namespace WebCore
diff --git a/Source/core/platform/Pasteboard.h b/Source/core/platform/Pasteboard.h
index 4664460..b060a5e 100644
--- a/Source/core/platform/Pasteboard.h
+++ b/Source/core/platform/Pasteboard.h
@@ -41,7 +41,6 @@
 class ChromiumDataObject;
 class KURL;
 class Node;
-class Range;
 
 class Pasteboard {
     WTF_MAKE_NONCOPYABLE(Pasteboard); WTF_MAKE_FAST_ALLOCATED;
@@ -52,7 +51,6 @@
     };
 
     static Pasteboard* generalPasteboard();
-    void writeSelection(Range*, bool canSmartCopyOrDelete, const String& text);
     void writePlainText(const String&, SmartReplaceOption);
     void writeImage(Node*, const KURL&, const String& title);
     void writeDataObject(PassRefPtr<ChromiumDataObject>);
@@ -67,15 +65,17 @@
     // fragmentStart will be zero and fragmentEnd will be the same as the length of the markup.
     String readHTML(KURL&, unsigned& fragmentStart, unsigned& fragmentEnd);
 
+    void writeHTML(const String& markup, const KURL& documentURL, const String& plainText, bool canSmartCopyOrDelete);
+
     bool isSelectionMode() const;
     void setSelectionMode(bool);
 
-    WebKit::WebClipboard::Buffer buffer() const { return m_buffer; }
+    blink::WebClipboard::Buffer buffer() const { return m_buffer; }
 
 private:
     Pasteboard();
 
-    WebKit::WebClipboard::Buffer m_buffer;
+    blink::WebClipboard::Buffer m_buffer;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/PlatformInstrumentation.cpp b/Source/core/platform/PlatformInstrumentation.cpp
deleted file mode 100644
index 053d47a..0000000
--- a/Source/core/platform/PlatformInstrumentation.cpp
+++ /dev/null
@@ -1,59 +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/platform/PlatformInstrumentation.h"
-
-namespace WebCore {
-
-const char PlatformInstrumentation::CategoryName[] = "webkit";
-
-const char PlatformInstrumentation::ImageDecodeEvent[] = "Decode Image";
-const char PlatformInstrumentation::ImageResizeEvent[] = "Resize Image";
-const char PlatformInstrumentation::DrawLazyPixelRefEvent[] = "Draw LazyPixelRef";
-
-const char PlatformInstrumentation::LazyPixelRef[] = "LazyPixelRef";
-
-const char PlatformInstrumentation::ImageTypeArgument[] = "imageType";
-const char PlatformInstrumentation::CachedArgument[] = "cached";
-
-PlatformInstrumentationClient* PlatformInstrumentation::m_client;
-
-PlatformInstrumentationClient::~PlatformInstrumentationClient()
-{
-}
-
-void PlatformInstrumentation::setClient(PlatformInstrumentationClient* client)
-{
-    m_client = client;
-}
-
-}
diff --git a/Source/core/platform/PlatformInstrumentation.h b/Source/core/platform/PlatformInstrumentation.h
deleted file mode 100644
index aa68c88..0000000
--- a/Source/core/platform/PlatformInstrumentation.h
+++ /dev/null
@@ -1,121 +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.
- */
-
-#ifndef PlatformInstrumentation_h
-#define PlatformInstrumentation_h
-
-#include "platform/TraceEvent.h"
-#include "wtf/MainThread.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class PlatformInstrumentationClient {
-public:
-    virtual ~PlatformInstrumentationClient();
-
-    virtual void willDecodeImage(const String& imageType) = 0;
-    virtual void didDecodeImage() = 0;
-    virtual void willResizeImage(bool shouldCache) = 0;
-    virtual void didResizeImage() = 0;
-};
-
-class PlatformInstrumentation {
-public:
-    class LazyPixelRefTracker: TraceEvent::TraceScopedTrackableObject<void*> {
-    public:
-        LazyPixelRefTracker(void* instance)
-            : TraceScopedTrackableObject(CategoryName, LazyPixelRef, instance)
-        {
-        }
-    };
-
-    static const char ImageDecodeEvent[];
-    static const char ImageResizeEvent[];
-    static const char DrawLazyPixelRefEvent[];
-
-    static const char ImageTypeArgument[];
-    static const char CachedArgument[];
-
-    static const char LazyPixelRef[];
-
-    static void setClient(PlatformInstrumentationClient*);
-    static bool hasClient() { return m_client; }
-
-    static void willDecodeImage(const String& imageType);
-    static void didDecodeImage();
-    static void willResizeImage(bool shouldCache);
-    static void didResizeImage();
-    static void didDrawLazyPixelRef(unsigned long long lazyPixelRefId);
-
-private:
-    static const char CategoryName[];
-
-    static PlatformInstrumentationClient* m_client;
-};
-
-#define FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD() if (!m_client || !isMainThread()) return;
-
-inline void PlatformInstrumentation::willDecodeImage(const String& imageType)
-{
-    TRACE_EVENT_BEGIN1(CategoryName, ImageDecodeEvent, ImageTypeArgument, TRACE_STR_COPY(imageType.ascii().data()));
-    FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
-    m_client->willDecodeImage(imageType);
-}
-
-inline void PlatformInstrumentation::didDecodeImage()
-{
-    TRACE_EVENT_END0(CategoryName, ImageDecodeEvent);
-    FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
-    m_client->didDecodeImage();
-}
-
-inline void PlatformInstrumentation::willResizeImage(bool shouldCache)
-{
-    TRACE_EVENT_BEGIN1(CategoryName, ImageResizeEvent, CachedArgument, shouldCache);
-    FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
-    m_client->willResizeImage(shouldCache);
-}
-
-inline void PlatformInstrumentation::didResizeImage()
-{
-    TRACE_EVENT_END0(CategoryName, ImageResizeEvent);
-    FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
-    m_client->didResizeImage();
-}
-
-inline void PlatformInstrumentation::didDrawLazyPixelRef(unsigned long long lazyPixelRefId)
-{
-    TRACE_EVENT_INSTANT1(CategoryName, DrawLazyPixelRefEvent, LazyPixelRef, lazyPixelRefId);
-}
-
-} // namespace WebCore
-
-#endif // PlatformInstrumentation_h
diff --git a/Source/core/platform/PlatformSpeechSynthesizer.cpp b/Source/core/platform/PlatformSpeechSynthesizer.cpp
index 0744d83..60a7683 100644
--- a/Source/core/platform/PlatformSpeechSynthesizer.cpp
+++ b/Source/core/platform/PlatformSpeechSynthesizer.cpp
@@ -48,7 +48,7 @@
     : m_speechSynthesizerClient(client)
 {
     m_webSpeechSynthesizerClient = adoptPtr(new WebSpeechSynthesizerClientImpl(this, client));
-    m_webSpeechSynthesizer = adoptPtr(WebKit::Platform::current()->createSpeechSynthesizer(m_webSpeechSynthesizerClient.get()));
+    m_webSpeechSynthesizer = adoptPtr(blink::Platform::current()->createSpeechSynthesizer(m_webSpeechSynthesizerClient.get()));
 }
 
 PlatformSpeechSynthesizer::~PlatformSpeechSynthesizer()
@@ -60,7 +60,7 @@
     if (!m_webSpeechSynthesizer || !m_webSpeechSynthesizerClient)
         return;
 
-    m_webSpeechSynthesizer->speak(WebKit::WebSpeechSynthesisUtterance(utterance));
+    m_webSpeechSynthesizer->speak(blink::WebSpeechSynthesisUtterance(utterance));
 }
 
 void PlatformSpeechSynthesizer::pause()
diff --git a/Source/core/platform/PlatformSpeechSynthesizer.h b/Source/core/platform/PlatformSpeechSynthesizer.h
index 3d1b815..ced73ff 100644
--- a/Source/core/platform/PlatformSpeechSynthesizer.h
+++ b/Source/core/platform/PlatformSpeechSynthesizer.h
@@ -30,7 +30,7 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
 
-namespace WebKit {
+namespace blink {
 class WebSpeechSynthesizer;
 class WebSpeechSynthesizerClient;
 }
@@ -81,8 +81,8 @@
 private:
     PlatformSpeechSynthesizerClient* m_speechSynthesizerClient;
 
-    OwnPtr<WebKit::WebSpeechSynthesizer> m_webSpeechSynthesizer;
-    OwnPtr<WebKit::WebSpeechSynthesizerClient> m_webSpeechSynthesizerClient;
+    OwnPtr<blink::WebSpeechSynthesizer> m_webSpeechSynthesizer;
+    OwnPtr<blink::WebSpeechSynthesizerClient> m_webSpeechSynthesizerClient;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/PopupMenu.h b/Source/core/platform/PopupMenu.h
deleted file mode 100644
index e0938da..0000000
--- a/Source/core/platform/PopupMenu.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
- *
- * 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.
- *
- */
-
-#ifndef PopupMenu_h
-#define PopupMenu_h
-
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class FloatQuad;
-class FrameView;
-class IntRect;
-class IntSize;
-
-class PopupMenu : public RefCounted<PopupMenu> {
-public:
-    virtual ~PopupMenu() { }
-    virtual void show(const FloatQuad& controlPosition, const IntSize& controlSize, int index) = 0;
-    virtual void hide() = 0;
-    virtual void updateFromElement() = 0;
-    virtual void disconnectClient() = 0;
-};
-
-}
-
-#endif // PopupMenu_h
diff --git a/Source/core/platform/ScrollAnimatorNone.cpp b/Source/core/platform/ScrollAnimatorNone.cpp
index 387b1f5..0f94aa7 100644
--- a/Source/core/platform/ScrollAnimatorNone.cpp
+++ b/Source/core/platform/ScrollAnimatorNone.cpp
@@ -489,8 +489,6 @@
     TRACE_EVENT0("webkit", "ScrollAnimatorNone::animationTimerFired");
 
     double currentTime = WTF::monotonicallyIncreasingTime();
-    double deltaToNextFrame = ceil((currentTime - m_startTime) * kFrameRate) / kFrameRate - (currentTime - m_startTime);
-    currentTime += deltaToNextFrame;
 
     bool continueAnimation = false;
     if (m_horizontalData.m_startTime && m_horizontalData.animateScroll(currentTime))
diff --git a/Source/core/platform/ScrollView.cpp b/Source/core/platform/ScrollView.cpp
index 7174c9b..7337a3b 100644
--- a/Source/core/platform/ScrollView.cpp
+++ b/Source/core/platform/ScrollView.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 #include "core/platform/ScrollView.h"
 
-#include "core/accessibility/AXObjectCache.h"
 #include "core/platform/ScrollbarTheme.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/GraphicsLayer.h"
@@ -77,16 +76,13 @@
     if (hasBar && !m_horizontalScrollbar) {
         m_horizontalScrollbar = createScrollbar(HorizontalScrollbar);
         addChild(m_horizontalScrollbar.get());
-        didAddHorizontalScrollbar(m_horizontalScrollbar.get());
+        didAddScrollbar(m_horizontalScrollbar.get(), HorizontalScrollbar);
         m_horizontalScrollbar->styleChanged();
     } else if (!hasBar && m_horizontalScrollbar) {
-        willRemoveHorizontalScrollbar(m_horizontalScrollbar.get());
+        willRemoveScrollbar(m_horizontalScrollbar.get(), HorizontalScrollbar);
         removeChild(m_horizontalScrollbar.get());
         m_horizontalScrollbar = 0;
     }
-
-    if (AXObjectCache* cache = axObjectCache())
-        cache->handleScrollbarUpdate(this);
 }
 
 void ScrollView::setHasVerticalScrollbar(bool hasBar)
@@ -94,16 +90,13 @@
     if (hasBar && !m_verticalScrollbar) {
         m_verticalScrollbar = createScrollbar(VerticalScrollbar);
         addChild(m_verticalScrollbar.get());
-        didAddVerticalScrollbar(m_verticalScrollbar.get());
+        didAddScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
         m_verticalScrollbar->styleChanged();
     } else if (!hasBar && m_verticalScrollbar) {
-        willRemoveVerticalScrollbar(m_verticalScrollbar.get());
+        willRemoveScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
         removeChild(m_verticalScrollbar.get());
         m_verticalScrollbar = 0;
     }
-
-    if (AXObjectCache* cache = axObjectCache())
-        cache->handleScrollbarUpdate(this);
 }
 
 PassRefPtr<Scrollbar> ScrollView::createScrollbar(ScrollbarOrientation orientation)
@@ -439,7 +432,7 @@
     if (m_horizontalScrollbar) {
         int clientWidth = visibleWidth();
         IntRect oldRect(m_horizontalScrollbar->frameRect());
-        IntRect hBarRect(0,
+        IntRect hBarRect((shouldPlaceVerticalScrollbarOnLeft() && m_verticalScrollbar) ? m_verticalScrollbar->width() : 0,
                         height() - m_horizontalScrollbar->height(),
                         width() - (m_verticalScrollbar ? m_verticalScrollbar->width() : 0),
                         m_horizontalScrollbar->height());
@@ -458,7 +451,7 @@
     if (m_verticalScrollbar) {
         int clientHeight = visibleHeight();
         IntRect oldRect(m_verticalScrollbar->frameRect());
-        IntRect vBarRect(width() - m_verticalScrollbar->width(),
+        IntRect vBarRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - m_verticalScrollbar->width()),
                          0,
                          m_verticalScrollbar->width(),
                          height() - (m_horizontalScrollbar ? m_horizontalScrollbar->height() : 0));
@@ -505,7 +498,7 @@
 
 IntRect ScrollView::rectToCopyOnScroll() const
 {
-    IntRect scrollViewRect = convertToRootView(IntRect(0, 0, visibleWidth(), visibleHeight()));
+    IntRect scrollViewRect = convertToRootView(IntRect((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0, 0, visibleWidth(), visibleHeight()));
     if (hasOverlayScrollbars()) {
         int verticalScrollbarWidth = (verticalScrollbar() && !hasLayerForVerticalScrollbar()) ? verticalScrollbar()->width() : 0;
         int horizontalScrollbarHeight = (horizontalScrollbar() && !hasLayerForHorizontalScrollbar()) ? horizontalScrollbar()->height() : 0;
@@ -799,14 +792,14 @@
         return cornerRect;
 
     if (m_horizontalScrollbar && width() - m_horizontalScrollbar->width() > 0) {
-        cornerRect.unite(IntRect(m_horizontalScrollbar->width(),
+        cornerRect.unite(IntRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : m_horizontalScrollbar->width(),
                                  height() - m_horizontalScrollbar->height(),
                                  width() - m_horizontalScrollbar->width(),
                                  m_horizontalScrollbar->height()));
     }
 
     if (m_verticalScrollbar && height() - m_verticalScrollbar->height() > 0) {
-        cornerRect.unite(IntRect(width() - m_verticalScrollbar->width(),
+        cornerRect.unite(IntRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - m_verticalScrollbar->width()),
                                  m_verticalScrollbar->height(),
                                  m_verticalScrollbar->width(),
                                  height() - m_verticalScrollbar->height()));
@@ -863,7 +856,7 @@
 
 void ScrollView::paintPanScrollIcon(GraphicsContext* context)
 {
-    static Image* panScrollIcon = Image::loadPlatformResource("panIcon").leakRef();
+    DEFINE_STATIC_REF(Image, panScrollIcon, (Image::loadPlatformResource("panIcon")));
     IntPoint iconGCPoint = m_panScrollIconPoint;
     if (parent())
         iconGCPoint = toScrollView(parent())->windowToContents(iconGCPoint);
diff --git a/Source/core/platform/ScrollView.h b/Source/core/platform/ScrollView.h
index cb9abe2..2fe86da 100644
--- a/Source/core/platform/ScrollView.h
+++ b/Source/core/platform/ScrollView.h
@@ -232,9 +232,6 @@
         return newPoint;
     }
 
-    // A means to access the AX cache when this object can get a pointer to it.
-    virtual AXObjectCache* axObjectCache() const { return 0; }
-
     // Widget override. Handles painting of the contents of the view as well as the scrollbars.
     virtual void paint(GraphicsContext*, const IntRect&);
     void paintScrollbars(GraphicsContext*, const IntRect&);
@@ -346,13 +343,13 @@
 
 inline ScrollView* toScrollView(Widget* widget)
 {
-    ASSERT(!widget || widget->isScrollView());
+    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isScrollView());
     return static_cast<ScrollView*>(widget);
 }
 
 inline const ScrollView* toScrollView(const Widget* widget)
 {
-    ASSERT(!widget || widget->isScrollView());
+    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isScrollView());
     return static_cast<const ScrollView*>(widget);
 }
 
diff --git a/Source/core/platform/ScrollableArea.cpp b/Source/core/platform/ScrollableArea.cpp
index 0c608ac..3fa7616 100644
--- a/Source/core/platform/ScrollableArea.cpp
+++ b/Source/core/platform/ScrollableArea.cpp
@@ -275,30 +275,23 @@
         scrollAnimator->finishCurrentScrollAnimations();
 }
 
-void ScrollableArea::didAddVerticalScrollbar(Scrollbar* scrollbar)
+void ScrollableArea::didAddScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
 {
-    scrollAnimator()->didAddVerticalScrollbar(scrollbar);
+    if (orientation == VerticalScrollbar)
+        scrollAnimator()->didAddVerticalScrollbar(scrollbar);
+    else
+        scrollAnimator()->didAddHorizontalScrollbar(scrollbar);
 
     // <rdar://problem/9797253> AppKit resets the scrollbar's style when you attach a scrollbar
     setScrollbarOverlayStyle(scrollbarOverlayStyle());
 }
 
-void ScrollableArea::willRemoveVerticalScrollbar(Scrollbar* scrollbar)
+void ScrollableArea::willRemoveScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
 {
-    scrollAnimator()->willRemoveVerticalScrollbar(scrollbar);
-}
-
-void ScrollableArea::didAddHorizontalScrollbar(Scrollbar* scrollbar)
-{
-    scrollAnimator()->didAddHorizontalScrollbar(scrollbar);
-
-    // <rdar://problem/9797253> AppKit resets the scrollbar's style when you attach a scrollbar
-    setScrollbarOverlayStyle(scrollbarOverlayStyle());
-}
-
-void ScrollableArea::willRemoveHorizontalScrollbar(Scrollbar* scrollbar)
-{
-    scrollAnimator()->willRemoveHorizontalScrollbar(scrollbar);
+    if (orientation == VerticalScrollbar)
+        scrollAnimator()->willRemoveVerticalScrollbar(scrollbar);
+    else
+        scrollAnimator()->willRemoveHorizontalScrollbar(scrollbar);
 }
 
 void ScrollableArea::contentsResized()
diff --git a/Source/core/platform/ScrollableArea.h b/Source/core/platform/ScrollableArea.h
index 24294e0..1dc7b2e 100644
--- a/Source/core/platform/ScrollableArea.h
+++ b/Source/core/platform/ScrollableArea.h
@@ -79,10 +79,8 @@
 
     void finishCurrentScrollAnimations() const;
 
-    void didAddVerticalScrollbar(Scrollbar*);
-    void willRemoveVerticalScrollbar(Scrollbar*);
-    virtual void didAddHorizontalScrollbar(Scrollbar*);
-    virtual void willRemoveHorizontalScrollbar(Scrollbar*);
+    virtual void didAddScrollbar(Scrollbar*, ScrollbarOrientation);
+    virtual void willRemoveScrollbar(Scrollbar*, ScrollbarOrientation);
 
     virtual void contentsResized();
 
diff --git a/Source/core/platform/Scrollbar.cpp b/Source/core/platform/Scrollbar.cpp
index a5fd76f..4f1883e 100644
--- a/Source/core/platform/Scrollbar.cpp
+++ b/Source/core/platform/Scrollbar.cpp
@@ -28,16 +28,11 @@
 
 #include <algorithm>
 #include "core/platform/ScrollAnimator.h"
+#include "core/platform/ScrollView.h"
 #include "core/platform/ScrollableArea.h"
 #include "core/platform/ScrollbarTheme.h"
 #include "core/platform/graphics/GraphicsContext.h"
 
-// FIXME: The following #includes are a layering violation and should be removed.
-#include "core/accessibility/AXObjectCache.h"
-#include "core/page/EventHandler.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
-
 #include "platform/PlatformGestureEvent.h"
 #include "platform/PlatformMouseEvent.h"
 
@@ -93,9 +88,6 @@
 
 Scrollbar::~Scrollbar()
 {
-    if (AXObjectCache* cache = existingAXObjectCache())
-        cache->remove(this);
-
     stopTimerIfNeeded();
 
     m_theme->unregisterScrollbar(this);
@@ -135,7 +127,7 @@
 
 bool Scrollbar::isScrollViewScrollbar() const
 {
-    return parent() && parent()->isFrameView() && toFrameView(parent())->isScrollViewScrollbar(this);
+    return parent() && parent()->isFrameView() && toScrollView(parent())->isScrollViewScrollbar(this);
 }
 
 bool Scrollbar::isLeftSideVerticalScrollbar() const
@@ -359,7 +351,7 @@
     switch (evt.type()) {
     case PlatformEvent::GestureShowPress:
         setPressedPart(theme()->hitTest(this, evt.position()));
-        m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y());
+        m_pressedPos = orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y();
         return true;
     case PlatformEvent::GestureTapDownCancel:
     case PlatformEvent::GestureScrollBegin:
@@ -371,7 +363,7 @@
     case PlatformEvent::GestureScrollUpdate:
     case PlatformEvent::GestureScrollUpdateWithoutPropagation:
         if (m_pressedPart == ThumbPart) {
-            m_scrollPos += HorizontalScrollbar ? evt.deltaX() : evt.deltaY();
+            m_scrollPos += orientation() == HorizontalScrollbar ? evt.deltaX() : evt.deltaY();
             moveThumb(m_scrollPos, false);
             return true;
         }
@@ -406,7 +398,7 @@
     }
 
     if (m_pressedPart != NoPart)
-        m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y());
+        m_pressedPos = orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y();
 
     ScrollbarPart part = theme()->hitTest(this, evt.position());
     if (part != m_hoveredPart) {
@@ -457,9 +449,6 @@
         if (part == NoPart)
             m_scrollableArea->mouseExitedScrollbar(this);
     }
-
-    if (parent() && parent()->isFrameView())
-        toFrameView(parent())->frame().eventHandler().setMousePressed(false);
 }
 
 void Scrollbar::mouseDown(const PlatformMouseEvent& evt)
@@ -469,7 +458,7 @@
         return;
 
     setPressedPart(theme()->hitTest(this, evt.position()));
-    int pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y());
+    int pressedPos = orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y();
 
     if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && theme()->shouldCenterOnThumb(this, evt)) {
         setHoveredPart(ThumbPart);
@@ -558,14 +547,6 @@
     return m_scrollableArea && m_scrollableArea->isActive();
 }
 
-AXObjectCache* Scrollbar::existingAXObjectCache() const
-{
-    if (!parentScrollView())
-        return 0;
-
-    return parentScrollView()->axObjectCache();
-}
-
 void Scrollbar::invalidateRect(const IntRect& rect)
 {
     if (suppressInvalidation())
diff --git a/Source/core/platform/Scrollbar.h b/Source/core/platform/Scrollbar.h
index 398656e..c49cc71 100644
--- a/Source/core/platform/Scrollbar.h
+++ b/Source/core/platform/Scrollbar.h
@@ -35,7 +35,6 @@
 
 namespace WebCore {
 
-class AXObjectCache;
 class GraphicsContext;
 class IntRect;
 class PlatformGestureEvent;
@@ -193,7 +192,6 @@
 
 private:
     virtual bool isScrollbar() const { return true; }
-    virtual AXObjectCache* existingAXObjectCache() const;
 
     float scrollableAreaCurrentPos() const;
 };
diff --git a/Source/core/platform/ScrollbarThemeGtkOrAura.cpp b/Source/core/platform/ScrollbarThemeGtkOrAura.cpp
index da0b409..10f30f4 100644
--- a/Source/core/platform/ScrollbarThemeGtkOrAura.cpp
+++ b/Source/core/platform/ScrollbarThemeGtkOrAura.cpp
@@ -20,8 +20,8 @@
  * 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,
+ * 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
@@ -34,6 +34,7 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/platform/ScrollbarThemeOverlay.h"
 #include "core/platform/graphics/GraphicsContext.h"
+#include "platform/LayoutTestSupport.h"
 #include "platform/PlatformMouseEvent.h"
 #include "platform/scroll/ScrollbarThemeClient.h"
 #include "public/platform/Platform.h"
@@ -42,6 +43,11 @@
 
 namespace WebCore {
 
+static bool useMockTheme()
+{
+    return isRunningLayoutTest();
+}
+
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
     if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) {
@@ -56,70 +62,82 @@
 int ScrollbarThemeGtkOrAura::scrollbarThickness(ScrollbarControlSize controlSize)
 {
     // Horiz and Vert scrollbars are the same thickness.
-    IntSize scrollbarSize = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarVerticalTrack);
+    IntSize scrollbarSize = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarVerticalTrack);
     return scrollbarSize.width();
 }
 
 void ScrollbarThemeGtkOrAura::paintTrackPiece(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart partType)
 {
-    WebKit::WebThemeEngine::State state = scrollbar->hoveredPart() == partType ? WebKit::WebThemeEngine::StateHover : WebKit::WebThemeEngine::StateNormal;
+    blink::WebThemeEngine::State state = scrollbar->hoveredPart() == partType ? blink::WebThemeEngine::StateHover : blink::WebThemeEngine::StateNormal;
+
+    if (useMockTheme() && !scrollbar->enabled())
+        state = blink::WebThemeEngine::StateDisabled;
+
     IntRect alignRect = trackRect(scrollbar, false);
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = gc->canvas();
+    blink::WebThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = gc->canvas();
+    extraParams.scrollbarTrack.isBack = (partType == BackTrackPart);
     extraParams.scrollbarTrack.trackX = alignRect.x();
     extraParams.scrollbarTrack.trackY = alignRect.y();
     extraParams.scrollbarTrack.trackWidth = alignRect.width();
     extraParams.scrollbarTrack.trackHeight = alignRect.height();
-    WebKit::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::PartScrollbarHorizontalTrack : WebKit::WebThemeEngine::PartScrollbarVerticalTrack, state, WebKit::WebRect(rect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? blink::WebThemeEngine::PartScrollbarHorizontalTrack : blink::WebThemeEngine::PartScrollbarVerticalTrack, state, blink::WebRect(rect), &extraParams);
 }
 
 void ScrollbarThemeGtkOrAura::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
 {
-    WebKit::WebThemeEngine::Part paintPart;
-    WebKit::WebThemeEngine::State state = WebKit::WebThemeEngine::StateNormal;
-    WebKit::WebCanvas* canvas = gc->canvas();
+    blink::WebThemeEngine::Part paintPart;
+    blink::WebThemeEngine::State state = blink::WebThemeEngine::StateNormal;
+    blink::WebCanvas* canvas = gc->canvas();
     bool checkMin = false;
     bool checkMax = false;
+
     if (scrollbar->orientation() == HorizontalScrollbar) {
         if (part == BackButtonStartPart) {
-            paintPart = WebKit::WebThemeEngine::PartScrollbarLeftArrow;
+            paintPart = blink::WebThemeEngine::PartScrollbarLeftArrow;
             checkMin = true;
+        } else if (useMockTheme() && part != ForwardButtonEndPart) {
+            return;
         } else {
-            paintPart = WebKit::WebThemeEngine::PartScrollbarRightArrow;
+            paintPart = blink::WebThemeEngine::PartScrollbarRightArrow;
             checkMax = true;
         }
     } else {
         if (part == BackButtonStartPart) {
-            paintPart = WebKit::WebThemeEngine::PartScrollbarUpArrow;
+            paintPart = blink::WebThemeEngine::PartScrollbarUpArrow;
             checkMin = true;
+        } else if (useMockTheme() && part != ForwardButtonEndPart) {
+            return;
         } else {
-            paintPart = WebKit::WebThemeEngine::PartScrollbarDownArrow;
+            paintPart = blink::WebThemeEngine::PartScrollbarDownArrow;
             checkMax = true;
         }
     }
-    if ((checkMin && (scrollbar->currentPos() <= 0))
-        || (checkMax && scrollbar->currentPos() == scrollbar->maximum())) {
-        state = WebKit::WebThemeEngine::StateDisabled;
+    if (useMockTheme() && !scrollbar->enabled()) {
+        state = blink::WebThemeEngine::StateDisabled;
+    } else if (!useMockTheme() && ((checkMin && (scrollbar->currentPos() <= 0))
+        || (checkMax && scrollbar->currentPos() == scrollbar->maximum()))) {
+        state = blink::WebThemeEngine::StateDisabled;
     } else {
         if (part == scrollbar->pressedPart())
-            state = WebKit::WebThemeEngine::StatePressed;
+            state = blink::WebThemeEngine::StatePressed;
         else if (part == scrollbar->hoveredPart())
-            state = WebKit::WebThemeEngine::StateHover;
+            state = blink::WebThemeEngine::StateHover;
     }
-    WebKit::Platform::current()->themeEngine()->paint(canvas, paintPart, state, WebKit::WebRect(rect), 0);
+    blink::Platform::current()->themeEngine()->paint(canvas, paintPart, state, blink::WebRect(rect), 0);
 }
 
 void ScrollbarThemeGtkOrAura::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
-    WebKit::WebThemeEngine::State state;
-    WebKit::WebCanvas* canvas = gc->canvas();
+    blink::WebThemeEngine::State state;
+    blink::WebCanvas* canvas = gc->canvas();
     if (scrollbar->pressedPart() == ThumbPart)
-        state = WebKit::WebThemeEngine::StatePressed;
+        state = blink::WebThemeEngine::StatePressed;
     else if (scrollbar->hoveredPart() == ThumbPart)
-        state = WebKit::WebThemeEngine::StateHover;
+        state = blink::WebThemeEngine::StateHover;
     else
-        state = WebKit::WebThemeEngine::StateNormal;
-    WebKit::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::PartScrollbarHorizontalThumb : WebKit::WebThemeEngine::PartScrollbarVerticalThumb, state, WebKit::WebRect(rect), 0);
+        state = blink::WebThemeEngine::StateNormal;
+    blink::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? blink::WebThemeEngine::PartScrollbarHorizontalThumb : blink::WebThemeEngine::PartScrollbarVerticalThumb, state, blink::WebRect(rect), 0);
 }
 
 bool ScrollbarThemeGtkOrAura::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
@@ -130,23 +148,23 @@
 IntSize ScrollbarThemeGtkOrAura::buttonSize(ScrollbarThemeClient* scrollbar)
 {
     if (scrollbar->orientation() == VerticalScrollbar) {
-        IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarUpArrow);
+        IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarUpArrow);
         return IntSize(size.width(), scrollbar->height() < 2 * size.height() ? scrollbar->height() / 2 : size.height());
     }
 
     // HorizontalScrollbar
-    IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarLeftArrow);
+    IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarLeftArrow);
     return IntSize(scrollbar->width() < 2 * size.width() ? scrollbar->width() / 2 : size.width(), size.height());
 }
 
 int ScrollbarThemeGtkOrAura::minimumThumbLength(ScrollbarThemeClient* scrollbar)
 {
     if (scrollbar->orientation() == VerticalScrollbar) {
-        IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarVerticalThumb);
+        IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarVerticalThumb);
         return size.height();
     }
 
-    IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarHorizontalThumb);
+    IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarHorizontalThumb);
     return size.width();
 }
 
diff --git a/Source/core/platform/ScrollbarThemeMacCommon.h b/Source/core/platform/ScrollbarThemeMacCommon.h
index 8138976..27b16f2 100644
--- a/Source/core/platform/ScrollbarThemeMacCommon.h
+++ b/Source/core/platform/ScrollbarThemeMacCommon.h
@@ -32,12 +32,11 @@
 
 class ScrollbarThemeMacCommon : public ScrollbarTheme {
 public:
-    ScrollbarThemeMacCommon();
     virtual ~ScrollbarThemeMacCommon();
 
     virtual void registerScrollbar(ScrollbarThemeClient*) OVERRIDE;
     virtual void unregisterScrollbar(ScrollbarThemeClient*) OVERRIDE;
-    void preferencesChanged();
+    void preferencesChanged(float initialButtonDelay, float autoscrollButtonDelay, bool jumpOnTrackClick, bool redraw);
 
     virtual bool supportsControlTints() const OVERRIDE { return true; }
 
diff --git a/Source/core/platform/ScrollbarThemeMacCommon.mm b/Source/core/platform/ScrollbarThemeMacCommon.mm
index 8fbfc10..f37fb44 100644
--- a/Source/core/platform/ScrollbarThemeMacCommon.mm
+++ b/Source/core/platform/ScrollbarThemeMacCommon.mm
@@ -70,55 +70,6 @@
 
 }
 
-@interface WebScrollbarPrefsObserver : NSObject
-{
-}
-
-+ (void)registerAsObserver;
-+ (void)appearancePrefsChanged:(NSNotification*)theNotification;
-+ (void)behaviorPrefsChanged:(NSNotification*)theNotification;
-
-@end
-
-@implementation WebScrollbarPrefsObserver
-
-+ (void)appearancePrefsChanged:(NSNotification*)unusedNotification
-{
-    UNUSED_PARAM(unusedNotification);
-
-    ScrollbarTheme* theme = ScrollbarTheme::theme();
-    if (theme->isMockTheme())
-        return;
-
-    static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged();
-    if (scrollbarSet().isEmpty())
-        return;
-    ScrollbarSet::iterator end = scrollbarSet().end();
-    for (ScrollbarSet::iterator it = scrollbarSet().begin(); it != end; ++it) {
-        (*it)->styleChanged();
-        (*it)->invalidate();
-    }
-}
-
-+ (void)behaviorPrefsChanged:(NSNotification*)unusedNotification
-{
-    UNUSED_PARAM(unusedNotification);
-
-    ScrollbarTheme* theme = ScrollbarTheme::theme();
-    if (theme->isMockTheme())
-        return;
-
-    static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged();
-}
-
-+ (void)registerAsObserver
-{
-    [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(appearancePrefsChanged:) name:@"AppleAquaScrollBarVariantChanged" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorDeliverImmediately];
-    [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(behaviorPrefsChanged:) name:@"AppleNoRedisplayAppearancePreferenceChanged" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorCoalesce];
-}
-
-@end
-
 namespace WebCore {
 
 static float gInitialButtonDelay = 0.5f;
@@ -127,14 +78,17 @@
 
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
+    static ScrollbarThemeMacCommon* theme = NULL;
+    if (theme)
+        return theme;
     if (isScrollbarOverlayAPIAvailable()) {
-        DEFINE_STATIC_LOCAL(ScrollbarThemeMacOverlayAPI, theme, ());
-        return &theme;
+        DEFINE_STATIC_LOCAL(ScrollbarThemeMacOverlayAPI, overlayTheme, ());
+        theme = &overlayTheme;
     } else {
-        DEFINE_STATIC_LOCAL(ScrollbarThemeMacNonOverlayAPI, theme, ());
-        return &theme;
+        DEFINE_STATIC_LOCAL(ScrollbarThemeMacNonOverlayAPI, nonOverlayTheme, ());
+        theme = &nonOverlayTheme;
     }
-    return NULL;
+    return theme;
 }
 
 void ScrollbarThemeMacCommon::registerScrollbar(ScrollbarThemeClient* scrollbar)
@@ -334,28 +288,23 @@
     paintGivenTickmarks(context, scrollbar, tickmarkTrackRect, tickmarks);
 }
 
-ScrollbarThemeMacCommon::ScrollbarThemeMacCommon()
-{
-    static bool initialized;
-    if (!initialized) {
-        initialized = true;
-        [WebScrollbarPrefsObserver registerAsObserver];
-        preferencesChanged();
-    }
-}
-
 ScrollbarThemeMacCommon::~ScrollbarThemeMacCommon()
 {
 }
 
-void ScrollbarThemeMacCommon::preferencesChanged()
+void ScrollbarThemeMacCommon::preferencesChanged(float initialButtonDelay, float autoscrollButtonDelay, bool jumpOnTrackClick, bool redraw)
 {
-    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
-    [defaults synchronize];
     updateButtonPlacement();
-    gInitialButtonDelay = [defaults floatForKey:@"NSScrollerButtonDelay"];
-    gAutoscrollButtonDelay = [defaults floatForKey:@"NSScrollerButtonPeriod"];
-    gJumpOnTrackClick = [defaults boolForKey:@"AppleScrollerPagingBehavior"];
+    gInitialButtonDelay = initialButtonDelay;
+    gAutoscrollButtonDelay = autoscrollButtonDelay;
+    gJumpOnTrackClick = jumpOnTrackClick;
+    if (redraw && !scrollbarSet().isEmpty()) {
+        ScrollbarSet::iterator end = scrollbarSet().end();
+        for (ScrollbarSet::iterator it = scrollbarSet().begin(); it != end; ++it) {
+            (*it)->styleChanged();
+            (*it)->invalidate();
+        }
+    }
 }
 
 double ScrollbarThemeMacCommon::initialAutoscrollTimerDelay()
diff --git a/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm b/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
index f9ec392..1851659 100644
--- a/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
+++ b/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
@@ -68,16 +68,16 @@
     }
 }
 
-static WebKit::WebThemeEngine::State scrollbarStateToThemeState(ScrollbarThemeClient* scrollbar)
+static blink::WebThemeEngine::State scrollbarStateToThemeState(ScrollbarThemeClient* scrollbar)
 {
     if (!scrollbar->enabled())
-        return WebKit::WebThemeEngine::StateDisabled;
+        return blink::WebThemeEngine::StateDisabled;
     if (!scrollbar->isScrollableAreaActive())
-        return WebKit::WebThemeEngine::StateInactive;
+        return blink::WebThemeEngine::StateInactive;
     if (scrollbar->pressedPart() == ThumbPart)
-        return WebKit::WebThemeEngine::StatePressed;
+        return blink::WebThemeEngine::StatePressed;
 
-    return WebKit::WebThemeEngine::StateActive;
+    return blink::WebThemeEngine::StateActive;
 }
 
 // Override ScrollbarThemeMacCommon::paint() to add support for the following:
@@ -150,20 +150,20 @@
     paintGivenTickmarks(drawingContext, scrollbar, tickmarkTrackRect, tickmarks);
 
     if (hasThumb(scrollbar)) {
-        WebKit::WebThemeEngine::ScrollbarInfo scrollbarInfo;
-        scrollbarInfo.orientation = scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::ScrollbarOrientationHorizontal : WebKit::WebThemeEngine::ScrollbarOrientationVertical;
-        scrollbarInfo.parent = scrollbar->isScrollViewScrollbar() ? WebKit::WebThemeEngine::ScrollbarParentScrollView : WebKit::WebThemeEngine::ScrollbarParentRenderLayer;
+        blink::WebThemeEngine::ScrollbarInfo scrollbarInfo;
+        scrollbarInfo.orientation = scrollbar->orientation() == HorizontalScrollbar ? blink::WebThemeEngine::ScrollbarOrientationHorizontal : blink::WebThemeEngine::ScrollbarOrientationVertical;
+        scrollbarInfo.parent = scrollbar->isScrollViewScrollbar() ? blink::WebThemeEngine::ScrollbarParentScrollView : blink::WebThemeEngine::ScrollbarParentRenderLayer;
         scrollbarInfo.maxValue = scrollbar->maximum();
         scrollbarInfo.currentValue = scrollbar->currentPos();
         scrollbarInfo.visibleSize = scrollbar->visibleSize();
         scrollbarInfo.totalSize = scrollbar->totalSize();
 
-        WebKit::WebCanvas* webCanvas = drawingContext->canvas();
-        WebKit::Platform::current()->themeEngine()->paintScrollbarThumb(
+        blink::WebCanvas* webCanvas = drawingContext->canvas();
+        blink::Platform::current()->themeEngine()->paintScrollbarThumb(
             webCanvas,
             scrollbarStateToThemeState(scrollbar),
-            scrollbar->controlSize() == RegularScrollbar ? WebKit::WebThemeEngine::SizeRegular : WebKit::WebThemeEngine::SizeSmall,
-            WebKit::WebRect(scrollbar->frameRect()),
+            scrollbar->controlSize() == RegularScrollbar ? blink::WebThemeEngine::SizeRegular : blink::WebThemeEngine::SizeSmall,
+            blink::WebRect(scrollbar->frameRect()),
             scrollbarInfo);
     }
 
diff --git a/Source/core/platform/ScrollbarThemeWin.cpp b/Source/core/platform/ScrollbarThemeWin.cpp
index 78086bf..8814377 100644
--- a/Source/core/platform/ScrollbarThemeWin.cpp
+++ b/Source/core/platform/ScrollbarThemeWin.cpp
@@ -65,7 +65,7 @@
     if (!thickness) {
         if (isRunningLayoutTest())
             return kMacScrollbarSize[controlSize];
-        thickness = IntSize(WebKit::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
+        thickness = IntSize(blink::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
     }
     return thickness;
 }
@@ -105,9 +105,9 @@
 
     IntRect alignRect = trackRect(scrollbar, false);
 
-    WebKit::WebCanvas* canvas = gc->canvas();
+    blink::WebCanvas* canvas = gc->canvas();
     // Draw the track area before/after the thumb on the scroll bar.
-    WebKit::Platform::current()->themeEngine()->paintScrollbarTrack(canvas, partId, getThemeState(scrollbar, partType), getClassicThemeState(scrollbar, partType), WebKit::WebRect(rect), WebKit::WebRect(alignRect));
+    blink::Platform::current()->themeEngine()->paintScrollbarTrack(canvas, partId, getThemeState(scrollbar, partType), getClassicThemeState(scrollbar, partType), blink::WebRect(rect), blink::WebRect(alignRect));
 }
 
 void ScrollbarThemeWin::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
@@ -120,21 +120,21 @@
     else
         partId = horz ? DFCS_SCROLLRIGHT : DFCS_SCROLLDOWN;
 
-    WebKit::WebCanvas* canvas = gc->canvas();
+    blink::WebCanvas* canvas = gc->canvas();
     // Draw the thumb (the box you drag in the scroll bar to scroll).
-    WebKit::Platform::current()->themeEngine()->paintScrollbarArrow(canvas, getThemeArrowState(scrollbar, part), partId | getClassicThemeState(scrollbar, part), WebKit::WebRect(rect));
+    blink::Platform::current()->themeEngine()->paintScrollbarArrow(canvas, getThemeArrowState(scrollbar, part), partId | getClassicThemeState(scrollbar, part), blink::WebRect(rect));
 }
 
 void ScrollbarThemeWin::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
     bool horz = scrollbar->orientation() == HorizontalScrollbar;
 
-    WebKit::WebCanvas* canvas = gc->canvas();
+    blink::WebCanvas* canvas = gc->canvas();
     // Draw the thumb (the box you drag in the scroll bar to scroll).
-    WebKit::Platform::current()->themeEngine()->paintScrollbarThumb(canvas, horz ? SBP_THUMBBTNHORZ : SBP_THUMBBTNVERT, getThemeState(scrollbar, ThumbPart), getClassicThemeState(scrollbar, ThumbPart), WebKit::WebRect(rect));
+    blink::Platform::current()->themeEngine()->paintScrollbarThumb(canvas, horz ? SBP_THUMBBTNHORZ : SBP_THUMBBTNVERT, getThemeState(scrollbar, ThumbPart), getClassicThemeState(scrollbar, ThumbPart), blink::WebRect(rect));
 
     // Draw the gripper (the three little lines on the thumb).
-    WebKit::Platform::current()->themeEngine()->paintScrollbarThumb(canvas, horz ? SBP_GRIPPERHORZ : SBP_GRIPPERVERT, getThemeState(scrollbar, ThumbPart), getClassicThemeState(scrollbar, ThumbPart), WebKit::WebRect(rect));
+    blink::Platform::current()->themeEngine()->paintScrollbarThumb(canvas, horz ? SBP_GRIPPERHORZ : SBP_GRIPPERVERT, getThemeState(scrollbar, ThumbPart), getClassicThemeState(scrollbar, ThumbPart), blink::WebRect(rect));
 }
 
 int ScrollbarThemeWin::getThemeState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
diff --git a/Source/core/platform/Theme.h b/Source/core/platform/Theme.h
index a0cc99d..ca2b9f9 100644
--- a/Source/core/platform/Theme.h
+++ b/Source/core/platform/Theme.h
@@ -26,10 +26,10 @@
 #ifndef Theme_h
 #define Theme_h
 
-#include "core/platform/ThemeTypes.h"
 #include "core/platform/graphics/Font.h"
 #include "platform/LengthBox.h"
 #include "platform/LengthSize.h"
+#include "platform/ThemeTypes.h"
 #include "platform/geometry/IntRect.h"
 #include "platform/graphics/Color.h"
 #include "wtf/Forward.h"
diff --git a/Source/core/platform/ThemeTypes.h b/Source/core/platform/ThemeTypes.h
deleted file mode 100644
index 1d58bd4..0000000
--- a/Source/core/platform/ThemeTypes.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2008, 2009, 2010 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 ThemeTypes_h
-#define ThemeTypes_h
-
-namespace WebCore {
-
-enum ControlState {
-    HoverState = 1,
-    PressedState = 1 << 1,
-    FocusState = 1 << 2,
-    EnabledState = 1 << 3,
-    CheckedState = 1 << 4,
-    ReadOnlyState = 1 << 5,
-    WindowInactiveState = 1 << 7,
-    IndeterminateState = 1 << 8,
-    SpinUpState = 1 << 9, // Sub-state for HoverState and PressedState.
-    AllStates = 0xffffffff
-};
-
-typedef unsigned ControlStates;
-
-// Must follow CSSValueKeywords.in order
-enum ControlPart {
-    NoControlPart, CheckboxPart, RadioPart, PushButtonPart, SquareButtonPart, ButtonPart,
-    ButtonBevelPart, InnerSpinButtonPart, InputSpeechButtonPart, ListboxPart, ListItemPart,
-    MediaEnterFullscreenButtonPart, MediaExitFullscreenButtonPart, MediaFullScreenVolumeSliderPart, MediaFullScreenVolumeSliderThumbPart, MediaMuteButtonPart, MediaPlayButtonPart,
-    MediaOverlayPlayButtonPart, MediaSeekBackButtonPart, MediaSeekForwardButtonPart, MediaRewindButtonPart, MediaReturnToRealtimeButtonPart, MediaToggleClosedCaptionsButtonPart,
-    MediaSliderPart, MediaSliderThumbPart, MediaVolumeSliderContainerPart, MediaVolumeSliderPart, MediaVolumeSliderThumbPart,
-    MediaVolumeSliderMuteButtonPart, MediaControlsBackgroundPart, MediaControlsFullscreenBackgroundPart, MediaCurrentTimePart, MediaTimeRemainingPart,
-    MenulistPart, MenulistButtonPart, MenulistTextPart, MenulistTextFieldPart, MeterPart, ProgressBarPart, ProgressBarValuePart,
-    SliderHorizontalPart, SliderVerticalPart, SliderThumbHorizontalPart,
-    SliderThumbVerticalPart, CaretPart, SearchFieldPart, SearchFieldDecorationPart,
-    SearchFieldResultsDecorationPart,
-    SearchFieldCancelButtonPart, TextFieldPart,
-    RelevancyLevelIndicatorPart, ContinuousCapacityLevelIndicatorPart, DiscreteCapacityLevelIndicatorPart, RatingLevelIndicatorPart,
-    TextAreaPart, CapsLockIndicatorPart
-};
-
-enum SelectionPart {
-    SelectionBackground, SelectionForeground
-};
-
-enum ThemeFont {
-    CaptionFont, IconFont, MenuFont, MessageBoxFont, SmallCaptionFont, StatusBarFont, MiniControlFont, SmallControlFont, ControlFont
-};
-
-enum ThemeColor {
-    ActiveBorderColor, ActiveCaptionColor, AppWorkspaceColor, BackgroundColor, ButtonFaceColor, ButtonHighlightColor, ButtonShadowColor,
-    ButtonTextColor, CaptionTextColor, GrayTextColor, HighlightColor, HighlightTextColor, InactiveBorderColor, InactiveCaptionColor,
-    InactiveCaptionTextColor, InfoBackgroundColor, InfoTextColor, MatchColor, MenuTextColor, ScrollbarColor, ThreeDDarkDhasowColor,
-    ThreeDFaceColor, ThreeDHighlightColor, ThreeDLightShadowColor, ThreeDShadowCLor, WindowColor, WindowFrameColor, WindowTextColor,
-    FocusRingColor, ActiveListBoxSelection, ActiveListBoxSelectionText, InactiveListBoxSelection, InactiveListBoxSelectionText
-};
-
-}
-#endif
diff --git a/Source/core/platform/ThreadGlobalData.h b/Source/core/platform/ThreadGlobalData.h
deleted file mode 100644
index 2e0fc74..0000000
--- a/Source/core/platform/ThreadGlobalData.h
+++ /dev/null
@@ -1,39 +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 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 ThreadGlobalData_h
-#define ThreadGlobalData_h
-
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/ThreadSpecific.h"
-#include "wtf/Threading.h"
-#include "wtf/text/StringHash.h"
-
-#endif // ThreadGlobalData_h
diff --git a/Source/core/platform/WindowsKeyboardCodes.h b/Source/core/platform/WindowsKeyboardCodes.h
deleted file mode 100644
index 237b916..0000000
--- a/Source/core/platform/WindowsKeyboardCodes.h
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- * Copyright (C) 2010 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. 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 INC. 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.
- */
-
-#ifndef VK_UNKNOWN
-
-#define VK_UNKNOWN 0
-
-// Left mouse button
-// Right mouse button
-// Control-break processing
-// Middle mouse button (three-button mouse)
-// VK_XBUTTON1 (05)
-// VK_XBUTTON2 (06)
-
-#ifndef VK_BACK
-#define VK_BACK 0x08
-#endif
-#ifndef VK_TAB
-#define VK_TAB 0x09
-#endif
-#ifndef VK_CLEAR
-#define VK_CLEAR 0x0C
-#endif
-#ifndef VK_RETURN
-#define VK_RETURN 0x0D
-#endif
-#ifndef VK_SHIFT
-#define VK_SHIFT 0x10
-#endif
-#ifndef VK_CONTROL
-#define VK_CONTROL 0x11 // CTRL key
-#endif
-#ifndef VK_MENU
-#define VK_MENU 0x12 // ALT key
-#endif
-#ifndef VK_PAUSE
-#define VK_PAUSE 0x13 // PAUSE key
-#endif
-#ifndef VK_CAPITAL
-#define VK_CAPITAL 0x14 // CAPS LOCK key
-#endif
-#ifndef VK_KANA
-#define VK_KANA 0x15 // Input Method Editor (IME) Kana mode
-#endif
-#ifndef VK_HANGUL
-#define VK_HANGUL 0x15 // IME Hangul mode
-#endif
-#ifndef VK_JUNJA
-#define VK_JUNJA 0x17 // IME Junja mode
-#endif
-#ifndef VK_FINAL
-#define VK_FINAL 0x18 // IME final mode
-#endif
-#ifndef VK_HANJA
-#define VK_HANJA 0x19 // IME Hanja mode
-#endif
-#ifndef VK_KANJI
-#define VK_KANJI 0x19 // IME Kanji mode
-#endif
-#ifndef VK_ESCAPE
-#define VK_ESCAPE 0x1B // ESC key
-#endif
-#ifndef VK_CONVERT
-#define VK_CONVERT 0x1C // IME convert
-#endif
-#ifndef VK_NONCONVERT
-#define VK_NONCONVERT 0x1D // IME nonconvert
-#endif
-#ifndef VK_ACCEPT
-#define VK_ACCEPT 0x1E // IME accept
-#endif
-#ifndef VK_MODECHANGE
-#define VK_MODECHANGE 0x1F // IME mode change request
-#endif
-#ifndef VK_SPACE
-#define VK_SPACE 0x20 // SPACE key
-#endif
-#ifndef VK_PRIOR
-#define VK_PRIOR 0x21 // PAGE UP key
-#endif
-#ifndef VK_NEXT
-#define VK_NEXT 0x22 // PAGE DOWN key
-#endif
-#ifndef VK_END
-#define VK_END 0x23 // END key
-#endif
-#ifndef VK_HOME
-#define VK_HOME 0x24 // HOME key
-#endif
-#ifndef VK_LEFT
-#define VK_LEFT 0x25 // LEFT ARROW key
-#endif
-#ifndef VK_UP
-#define VK_UP 0x26 // UP ARROW key
-#endif
-#ifndef VK_RIGHT
-#define VK_RIGHT 0x27 // RIGHT ARROW key
-#endif
-#ifndef VK_DOWN
-#define VK_DOWN 0x28 // DOWN ARROW key
-#endif
-#ifndef VK_SELECT
-#define VK_SELECT 0x29 // SELECT key
-#endif
-#ifndef VK_PRINT
-#define VK_PRINT 0x2A // PRINT key
-#endif
-#ifndef VK_EXECUTE
-#define VK_EXECUTE 0x2B // EXECUTE key
-#endif
-#ifndef VK_SNAPSHOT
-#define VK_SNAPSHOT 0x2C // PRINT SCREEN key
-#endif
-#ifndef VK_INSERT
-#define VK_INSERT 0x2D // INS key
-#endif
-#ifndef VK_DELETE
-#define VK_DELETE 0x2E // DEL key
-#endif
-#ifndef VK_HELP
-#define VK_HELP 0x2F // HELP key
-#endif
-
-#define VK_0 0x30
-#define VK_1 0x31
-#define VK_2 0x32
-#define VK_3 0x33
-#define VK_4 0x34
-#define VK_5 0x35
-#define VK_6 0x36
-#define VK_7 0x37
-#define VK_8 0x38
-#define VK_9 0x39
-#define VK_A 0x41
-#define VK_B 0x42
-#define VK_C 0x43
-#define VK_D 0x44
-#define VK_E 0x45
-#define VK_F 0x46
-#define VK_G 0x47
-#define VK_H 0x48
-#define VK_I 0x49
-#define VK_J 0x4A
-#define VK_K 0x4B
-#define VK_L 0x4C
-#define VK_M 0x4D
-#define VK_N 0x4E
-#define VK_O 0x4F
-#define VK_P 0x50
-#define VK_Q 0x51
-#define VK_R 0x52
-#define VK_S 0x53
-#define VK_T 0x54
-#define VK_U 0x55
-#define VK_V 0x56
-#define VK_W 0x57
-#define VK_X 0x58
-#define VK_Y 0x59
-#define VK_Z 0x5A
-
-#define VK_LWIN 0x5B // Left Windows key (Microsoft Natural keyboard)
-
-#define VK_RWIN 0x5C // Right Windows key (Natural keyboard)
-
-#define VK_APPS 0x5D // Applications key (Natural keyboard)
-
-#define VK_SLEEP 0x5F // Computer Sleep key
-
-// Num pad keys
-#define VK_NUMPAD0 0x60
-#define VK_NUMPAD1 0x61
-#define VK_NUMPAD2 0x62
-#define VK_NUMPAD3 0x63
-#define VK_NUMPAD4 0x64
-#define VK_NUMPAD5 0x65
-#define VK_NUMPAD6 0x66
-#define VK_NUMPAD7 0x67
-#define VK_NUMPAD8 0x68
-#define VK_NUMPAD9 0x69
-#define VK_MULTIPLY 0x6A
-#define VK_ADD 0x6B
-#define VK_SEPARATOR 0x6C
-#define VK_SUBTRACT 0x6D
-#define VK_DECIMAL 0x6E
-#define VK_DIVIDE 0x6F
-
-#define VK_F1 0x70
-#define VK_F2 0x71
-#define VK_F3 0x72
-#define VK_F4 0x73
-#define VK_F5 0x74
-#define VK_F6 0x75
-#define VK_F7 0x76
-#define VK_F8 0x77
-#define VK_F9 0x78
-#define VK_F10 0x79
-#define VK_F11 0x7A
-#define VK_F12 0x7B
-#define VK_F13 0x7C
-#define VK_F14 0x7D
-#define VK_F15 0x7E
-#define VK_F16 0x7F
-#define VK_F17 0x80
-#define VK_F18 0x81
-#define VK_F19 0x82
-#define VK_F20 0x83
-#define VK_F21 0x84
-#define VK_F22 0x85
-#define VK_F23 0x86
-#define VK_F24 0x87
-
-#define VK_NUMLOCK 0x90
-#define VK_SCROLL 0x91
-#define VK_LSHIFT 0xA0
-#define VK_RSHIFT 0xA1
-#define VK_LCONTROL 0xA2
-#define VK_RCONTROL 0xA3
-#define VK_LMENU 0xA4
-#define VK_RMENU 0xA5
-
-#define VK_BROWSER_BACK 0xA6 // Windows 2000/XP: Browser Back key
-#define VK_BROWSER_FORWARD 0xA7 // Windows 2000/XP: Browser Forward key
-#define VK_BROWSER_REFRESH 0xA8 // Windows 2000/XP: Browser Refresh key
-#define VK_BROWSER_STOP 0xA9 // Windows 2000/XP: Browser Stop key
-#define VK_BROWSER_SEARCH 0xAA // Windows 2000/XP: Browser Search key
-#define VK_BROWSER_FAVORITES 0xAB // Windows 2000/XP: Browser Favorites key
-#define VK_BROWSER_HOME 0xAC // Windows 2000/XP: Browser Start and Home key
-#define VK_VOLUME_MUTE 0xAD // Windows 2000/XP: Volume Mute key
-#define VK_VOLUME_DOWN 0xAE // Windows 2000/XP: Volume Down key
-#define VK_VOLUME_UP 0xAF // Windows 2000/XP: Volume Up key
-#define VK_MEDIA_NEXT_TRACK 0xB0 // Windows 2000/XP: Next Track key
-#define VK_MEDIA_PREV_TRACK 0xB1 // Windows 2000/XP: Previous Track key
-#define VK_MEDIA_STOP 0xB2 // Windows 2000/XP: Stop Media key
-#define VK_MEDIA_PLAY_PAUSE 0xB3 // Windows 2000/XP: Play/Pause Media key
-#define VK_MEDIA_LAUNCH_MAIL 0xB4 // Windows 2000/XP: Start Mail key
-#define VK_MEDIA_LAUNCH_MEDIA_SELECT 0xB5 // Windows 2000/XP: Select Media key
-#define VK_MEDIA_LAUNCH_APP1 0xB6 // VK_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key
-#define VK_MEDIA_LAUNCH_APP2 0xB7 // VK_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key
-
-// VK_OEM_1 (BA) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key
-#define VK_OEM_1 0xBA
-
-// Windows 2000/XP: For any country/region, the '+' key
-#define VK_OEM_PLUS 0xBB
-
-// Windows 2000/XP: For any country/region, the ',' key
-#define VK_OEM_COMMA 0xBC
-
-// Windows 2000/XP: For any country/region, the '-' key
-#define VK_OEM_MINUS 0xBD
-
-// Windows 2000/XP: For any country/region, the '.' key
-#define VK_OEM_PERIOD 0xBE
-
-// VK_OEM_2 (BF) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
-#define VK_OEM_2 0xBF
-
-// VK_OEM_3 (C0) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
-#define VK_OEM_3 0xC0
-
-// VK_OEM_4 (DB) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
-#define VK_OEM_4 0xDB
-
-// VK_OEM_5 (DC) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
-#define VK_OEM_5 0xDC
-
-// VK_OEM_6 (DD) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
-#define VK_OEM_6 0xDD
-
-// VK_OEM_7 (DE) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
-#define VK_OEM_7 0xDE
-
-// VK_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard.
-#define VK_OEM_8 0xDF
-
-// VK_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
-#define VK_OEM_102 0xE2
-
-// Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
-#define VK_PROCESSKEY 0xE5
-
-// Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP
-#define VK_PACKET 0xE7
-
-#define VK_ATTN 0xF6 // Attn key
-#define VK_CRSEL 0xF7 // CrSel key
-#define VK_EXSEL 0xF8 // ExSel key
-#define VK_EREOF 0xF9 // Erase EOF key
-#define VK_PLAY 0xFA // Play key
-#define VK_ZOOM 0xFB // Zoom key
-
-#define VK_NONAME 0xFC // Reserved for future use
-
-#define VK_PA1 0xFD // VK_PA1 (FD) PA1 key
-
-#define VK_OEM_CLEAR 0xFE // Clear key
-
-#endif // VK_UNKNOWN
diff --git a/Source/core/platform/animation/AnimationTranslationUtil.cpp b/Source/core/platform/animation/AnimationTranslationUtil.cpp
index f35df95..e0637c9 100644
--- a/Source/core/platform/animation/AnimationTranslationUtil.cpp
+++ b/Source/core/platform/animation/AnimationTranslationUtil.cpp
@@ -56,19 +56,15 @@
 #include "wtf/text/CString.h"
 
 using namespace std;
-using namespace WebKit;
+using namespace blink;
 
 namespace WebCore {
 
-PassOwnPtr<WebTransformOperations> toWebTransformOperations(const TransformOperations& transformOperations, const FloatSize& boxSize)
+void toWebTransformOperations(const TransformOperations& transformOperations, const FloatSize& boxSize, WebTransformOperations* webTransformOperations)
 {
     // We need to do a deep copy the transformOperations may contain ref pointers to TransformOperation objects.
-    OwnPtr<WebTransformOperations> webTransformOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
-    if (!webTransformOperations)
-        return nullptr;
     for (size_t j = 0; j < transformOperations.size(); ++j) {
-        TransformOperation::OperationType operationType = transformOperations.operations()[j]->getOperationType();
-        switch (operationType) {
+        switch (transformOperations.operations()[j]->type()) {
         case TransformOperation::ScaleX:
         case TransformOperation::ScaleY:
         case TransformOperation::ScaleZ:
@@ -133,12 +129,10 @@
             break;
         } // switch
     } // for each operation
-
-    return webTransformOperations.release();
 }
 
 template <class Value, class Keyframe, class Curve>
-bool appendKeyframeWithStandardTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize&)
+bool appendKeyframeWithStandardTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize&)
 {
     curve->add(Keyframe(keyTime, value->value()), timingFunctionType);
     return true;
@@ -152,16 +146,18 @@
 }
 
 template <>
-bool appendKeyframeWithStandardTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
+bool appendKeyframeWithStandardTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
 {
     bool canBlend = !lastValue;
-    OwnPtr<WebTransformOperations> operations(toWebTransformOperations(*value->value(), boxSize));
+    OwnPtr<WebTransformOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
     if (!operations)
         return false;
+    toWebTransformOperations(*value->value(), boxSize, operations.get());
     if (!canBlend) {
-        OwnPtr<WebTransformOperations> lastOperations(toWebTransformOperations(*lastValue->value(), boxSize));
+        OwnPtr<WebTransformOperations> lastOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
         if (!lastOperations)
             return false;
+        toWebTransformOperations(*lastValue->value(), boxSize, lastOperations.get());
         canBlend = lastOperations->canBlendWith(*operations);
     }
     if (canBlend) {
@@ -175,13 +171,15 @@
 bool appendKeyframeWithCustomBezierTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, double x1, double y1, double x2, double y2, const FloatSize& boxSize)
 {
     bool canBlend = !lastValue;
-    OwnPtr<WebTransformOperations> operations(toWebTransformOperations(*value->value(), boxSize));
+    OwnPtr<WebTransformOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
     if (!operations)
         return false;
+    toWebTransformOperations(*value->value(), boxSize, operations.get());
     if (!canBlend) {
-        OwnPtr<WebTransformOperations> lastOperations(toWebTransformOperations(*lastValue->value(), boxSize));
+        OwnPtr<WebTransformOperations> lastOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
         if (!lastOperations)
             return false;
+        toWebTransformOperations(*lastValue->value(), boxSize, lastOperations.get());
         canBlend = lastOperations->canBlendWith(*operations);
     }
     if (canBlend) {
@@ -191,8 +189,16 @@
     return false;
 }
 
+bool toWebFilterOperations(const FilterOperations& inOperations, WebFilterOperations* outOperations)
+{
+    SkiaImageFilterBuilder builder;
+    FilterOutsets outsets = inOperations.outsets();
+    builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
+    return builder.buildFilterOperations(inOperations, outOperations);
+}
+
 template <>
-bool appendKeyframeWithStandardTimingFunction<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(WebFilterAnimationCurve* curve, double keyTime, const FilterAnimationValue* value, const FilterAnimationValue* lastValue, WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
+bool appendKeyframeWithStandardTimingFunction<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(WebFilterAnimationCurve* curve, double keyTime, const FilterAnimationValue* value, const FilterAnimationValue* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
 {
     // FIXME(ajuma): In order to animate pixel-moving filters on the compositor thread, we need
     // to update overlap testing to take into account the bounds within which the animation
@@ -200,11 +206,8 @@
     // progresses.
     if (value->value()->hasFilterThatMovesPixels())
         return false;
-    SkiaImageFilterBuilder builder;
     OwnPtr<WebFilterOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
-    FilterOutsets outsets = value->value()->outsets();
-    builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
-    if (!builder.buildFilterOperations(*value->value(), operations.get()))
+    if (!toWebFilterOperations(*(value->value()), operations.get()))
         return false;
     curve->add(WebFilterKeyframe(keyTime, operations.release()), timingFunctionType);
     return true;
@@ -219,18 +222,16 @@
     // progresses.
     if (value->value()->hasFilterThatMovesPixels())
         return false;
-    SkiaImageFilterBuilder builder;
+
     OwnPtr<WebFilterOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
-    FilterOutsets outsets = value->value()->outsets();
-    builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
-    if (!builder.buildFilterOperations(*value->value(), operations.get()))
+    if (!toWebFilterOperations(*(value->value()), operations.get()))
         return false;
     curve->add(WebFilterKeyframe(keyTime, operations.release()), x1, y1, x2, y2);
     return true;
 }
 
 template <class Value, class Keyframe, class Curve>
-PassOwnPtr<WebKit::WebAnimation> createWebAnimation(const KeyframeValueList& valueList, const CSSAnimationData* animation, int animationId, double timeOffset, Curve* curve, WebKit::WebAnimation::TargetProperty targetProperty, const FloatSize& boxSize)
+PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList& valueList, const CSSAnimationData* animation, int animationId, double timeOffset, Curve* curve, blink::WebAnimation::TargetProperty targetProperty, const FloatSize& boxSize)
 {
     bool alternate = false;
     bool reverse = false;
@@ -257,7 +258,7 @@
             originalTimingFunction = animation->timingFunction();
 
         // Ease is the default timing function.
-        WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType = WebKit::WebAnimationCurve::TimingFunctionTypeEase;
+        blink::WebAnimationCurve::TimingFunctionType timingFunctionType = blink::WebAnimationCurve::TimingFunctionTypeEase;
 
         bool isUsingCustomBezierTimingFunction = false;
         double x1 = 0;
@@ -271,16 +272,28 @@
                 // FIXME: add support for steps timing function.
                 return nullptr;
             case TimingFunction::LinearFunction:
-                timingFunctionType = WebKit::WebAnimationCurve::TimingFunctionTypeLinear;
+                // This doesn't need to be flipped when the animation is reversed.
+                timingFunctionType = blink::WebAnimationCurve::TimingFunctionTypeLinear;
                 break;
             case TimingFunction::CubicBezierFunction:
                 {
-                    const CubicBezierTimingFunction* originalBezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(originalTimingFunction);
+                    const CubicBezierTimingFunction* originalBezierTimingFunction = toCubicBezierTimingFunction(originalTimingFunction);
                     isUsingCustomBezierTimingFunction = true;
                     x1 = originalBezierTimingFunction->x1();
                     y1 = originalBezierTimingFunction->y1();
                     x2 = originalBezierTimingFunction->x2();
                     y2 = originalBezierTimingFunction->y2();
+                    if (reverse) {
+                        // When the animation is reversed, we need to swap the
+                        // start and end keyframes, and flip the timing
+                        // function in both x and y.
+                        double x1Old = x1;
+                        double y1Old = y1;
+                        x1 = 1 - x2;
+                        y1 = 1 - y2;
+                        x2 = 1 - x1Old;
+                        y2 = 1 - y1Old;
+                    }
                     break;
                 }
             default:
@@ -299,11 +312,12 @@
             addedKeyframe = appendKeyframeWithCustomBezierTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, x1, y1, x2, y2, boxSize);
         else
             addedKeyframe = appendKeyframeWithStandardTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, timingFunctionType, boxSize);
+
         if (!addedKeyframe)
             return nullptr;
     }
 
-    OwnPtr<WebKit::WebAnimation> webAnimation = adoptPtr(Platform::current()->compositorSupport()->createAnimation(*curve, targetProperty, animationId));
+    OwnPtr<blink::WebAnimation> webAnimation = adoptPtr(Platform::current()->compositorSupport()->createAnimation(*curve, targetProperty, animationId));
 
     int iterations = (animation && animation->isIterationCountSet()) ? animation->iterationCount() : 1;
     webAnimation->setIterations(iterations);
@@ -315,22 +329,22 @@
     return webAnimation.release();
 }
 
-PassOwnPtr<WebKit::WebAnimation> createWebAnimation(const KeyframeValueList& values, const CSSAnimationData* animation, int animationId, double timeOffset, const FloatSize& boxSize)
+PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList& values, const CSSAnimationData* animation, int animationId, double timeOffset, const FloatSize& boxSize)
 {
     switch (values.property()) {
     case AnimatedPropertyWebkitTransform: {
         OwnPtr<WebTransformAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createTransformAnimationCurve());
-        return createWebAnimation<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), WebKit::WebAnimation::TargetPropertyTransform, FloatSize(boxSize));
+        return createWebAnimation<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyTransform, FloatSize(boxSize));
     }
 
     case AnimatedPropertyOpacity: {
         OwnPtr<WebFloatAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createFloatAnimationCurve());
-        return createWebAnimation<FloatAnimationValue, WebFloatKeyframe, WebFloatAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), WebKit::WebAnimation::TargetPropertyOpacity, FloatSize());
+        return createWebAnimation<FloatAnimationValue, WebFloatKeyframe, WebFloatAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyOpacity, FloatSize());
     }
 
     case AnimatedPropertyWebkitFilter: {
         OwnPtr<WebFilterAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createFilterAnimationCurve());
-        return createWebAnimation<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), WebKit::WebAnimation::TargetPropertyFilter, FloatSize(boxSize));
+        return createWebAnimation<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyFilter, FloatSize(boxSize));
     }
 
     case AnimatedPropertyBackgroundColor:
diff --git a/Source/core/platform/animation/AnimationTranslationUtil.h b/Source/core/platform/animation/AnimationTranslationUtil.h
index 95af52a..f1a5a82 100644
--- a/Source/core/platform/animation/AnimationTranslationUtil.h
+++ b/Source/core/platform/animation/AnimationTranslationUtil.h
@@ -31,9 +31,12 @@
 #ifndef AnimationTranslationUtil_h
 #define AnimationTranslationUtil_h
 
+#include "core/platform/graphics/filters/FilterOperations.h"
+#include "platform/transforms/TransformOperations.h"
+#include "public/platform/WebTransformOperations.h"
 #include "wtf/PassOwnPtr.h"
 
-namespace WebKit {
+namespace blink {
 class WebAnimation;
 }
 
@@ -49,8 +52,11 @@
 //   - a steps timing function is used,
 //   - a property other than AnimatedPropertyWebkitTransform, or AnimatedPropertyOpacity is animated, or
 //   - a transform animation involves a non-invertable transform.
-PassOwnPtr<WebKit::WebAnimation> createWebAnimation(const KeyframeValueList&, const CSSAnimationData*, int animationId, double timeOffset, const FloatSize& boxSize);
+PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList&, const CSSAnimationData*, int animationId, double timeOffset, const FloatSize& boxSize);
 
+void toWebTransformOperations(const TransformOperations& inOperations, const FloatSize& boxSize, blink::WebTransformOperations* outOperations);
+
+bool toWebFilterOperations(const FilterOperations& inOperations, blink::WebFilterOperations* outOperations);
 } // namespace WebCore
 
 #endif // AnimationTranslationUtil_h
diff --git a/Source/core/platform/animation/AnimationTranslationUtilTest.cpp b/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
index edd0c71..50eb841 100644
--- a/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
+++ b/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
@@ -36,14 +36,48 @@
 #include "platform/transforms/TransformOperations.h"
 #include "platform/transforms/TranslateTransformOperation.h"
 #include "public/platform/WebAnimation.h"
+#include "public/platform/WebFilterOperations.h"
 #include "wtf/RefPtr.h"
+#include <gmock/gmock.h>
 #include <gtest/gtest.h>
 
 using namespace WebCore;
-using namespace WebKit;
+using namespace blink;
 
 namespace {
 
+class WebTransformOperationsMock : public blink::WebTransformOperations {
+public:
+    MOCK_CONST_METHOD1(canBlendWith, bool(const WebTransformOperations&));
+    MOCK_METHOD3(appendTranslate, void(double, double, double));
+    MOCK_METHOD4(appendRotate, void(double, double, double, double));
+    MOCK_METHOD3(appendScale, void(double, double, double));
+    MOCK_METHOD2(appendSkew, void(double, double));
+    MOCK_METHOD1(appendPerspective, void(double));
+    MOCK_METHOD1(appendMatrix, void(const SkMatrix44&));
+    MOCK_METHOD0(appendIdentity, void());
+    MOCK_CONST_METHOD0(isIdentity, bool());
+};
+
+class WebFilterOperationsMock : public blink::WebFilterOperations {
+public:
+    MOCK_METHOD1(appendGrayscaleFilter, void(float));
+    MOCK_METHOD1(appendSepiaFilter, void(float));
+    MOCK_METHOD1(appendSaturateFilter, void(float));
+    MOCK_METHOD1(appendHueRotateFilter, void(float));
+    MOCK_METHOD1(appendInvertFilter, void(float));
+    MOCK_METHOD1(appendBrightnessFilter, void(float));
+    MOCK_METHOD1(appendContrastFilter, void(float));
+    MOCK_METHOD1(appendOpacityFilter, void(float));
+    MOCK_METHOD1(appendBlurFilter, void(float));
+    MOCK_METHOD3(appendDropShadowFilter, void(WebPoint, float, WebColor));
+    MOCK_METHOD1(appendColorMatrixFilter, void(SkScalar[20]));
+    MOCK_METHOD2(appendZoomFilter, void(float, int));
+    MOCK_METHOD1(appendSaturatingBrightnessFilter, void(float));
+    MOCK_METHOD1(appendReferenceFilter, void(SkImageFilter*));
+    MOCK_METHOD0(clear, void());
+};
+
 bool animationCanBeTranslated(const KeyframeValueList& values, CSSAnimationData* animation)
 {
     IntSize boxSize;
@@ -279,5 +313,40 @@
     EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
 }
 
+TEST(AnimationTranslationUtilTest, transformsWork)
+{
+    TransformOperations ops;
+    FloatSize box(100, 200);
+    WebTransformOperationsMock outOps;
+
+    EXPECT_CALL(outOps, appendTranslate(2, 0, 0));
+    EXPECT_CALL(outOps, appendTranslate(2, 60, 0));
+    EXPECT_CALL(outOps, appendRotate(0.1, 0.2, 0.3, 200000.4));
+    EXPECT_CALL(outOps, appendScale(50.2, 100, -4));
+
+    ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+    ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Percent), Length(30, WebCore::Percent), TransformOperation::Translate));
+    ops.operations().append(RotateTransformOperation::create(0.1, 0.2, 0.3, 200000.4, TransformOperation::Rotate3D));
+    ops.operations().append(ScaleTransformOperation::create(50.2, 100, -4, TransformOperation::Scale3D));
+    toWebTransformOperations(ops, box, &outOps);
+}
+
+TEST(AnimationTranslationUtilTest, filtersWork)
+{
+    FilterOperations ops;
+    WebFilterOperationsMock outOps;
+
+    EXPECT_CALL(outOps, appendSaturateFilter(0.5));
+    EXPECT_CALL(outOps, appendGrayscaleFilter(0.2f));
+    EXPECT_CALL(outOps, appendSepiaFilter(0.8f));
+    EXPECT_CALL(outOps, appendOpacityFilter(0.1f));
+
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.2, FilterOperation::GRAYSCALE));
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.8, FilterOperation::SEPIA));
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.1, FilterOperation::OPACITY));
+    toWebFilterOperations(ops, &outOps);
+}
+
 }
 
diff --git a/Source/core/platform/animation/CSSAnimationData.cpp b/Source/core/platform/animation/CSSAnimationData.cpp
index 65f2fa6..a3bee6ac 100644
--- a/Source/core/platform/animation/CSSAnimationData.cpp
+++ b/Source/core/platform/animation/CSSAnimationData.cpp
@@ -104,34 +104,19 @@
 {
 }
 
-bool CSSAnimationData::animationsMatch(const CSSAnimationData* o, bool matchPlayStates) const
+bool CSSAnimationData::animationsMatchForStyleRecalc(const CSSAnimationData* o) const
 {
     if (!o)
         return false;
 
-    bool result = m_name == o->m_name
-                  && m_property == o->m_property
-                  && m_mode == o->m_mode
-                  && m_iterationCount == o->m_iterationCount
-                  && m_delay == o->m_delay
-                  && m_duration == o->m_duration
-                  && *(m_timingFunction.get()) == *(o->m_timingFunction.get())
-                  && m_direction == o->m_direction
-                  && m_fillMode == o->m_fillMode
-                  && m_delaySet == o->m_delaySet
-                  && m_directionSet == o->m_directionSet
-                  && m_durationSet == o->m_durationSet
-                  && m_fillModeSet == o->m_fillModeSet
-                  && m_iterationCountSet == o->m_iterationCountSet
-                  && m_nameSet == o->m_nameSet
-                  && m_propertySet == o->m_propertySet
-                  && m_timingFunctionSet == o->m_timingFunctionSet
-                  && m_isNone == o->m_isNone;
-
-    if (!result)
-        return false;
-
-    return !matchPlayStates || (m_playState == o->m_playState && m_playStateSet == o->m_playStateSet);
+    return m_name == o->m_name
+        && m_playState == o->m_playState
+        && m_property == o->m_property
+        && m_mode == o->m_mode
+        && m_nameSet == o->m_nameSet
+        && m_playStateSet == o->m_playStateSet
+        && m_propertySet == o->m_propertySet
+        && m_isNone == o->m_isNone;
 }
 
 const String& CSSAnimationData::initialAnimationName()
diff --git a/Source/core/platform/animation/CSSAnimationData.h b/Source/core/platform/animation/CSSAnimationData.h
index 49c4beb..6744748 100644
--- a/Source/core/platform/animation/CSSAnimationData.h
+++ b/Source/core/platform/animation/CSSAnimationData.h
@@ -137,7 +137,7 @@
     CSSAnimationData& operator=(const CSSAnimationData& o);
 
     // return true every CSSAnimationData in the chain (defined by m_next) match
-    bool operator==(const CSSAnimationData& o) const { return animationsMatch(&o); }
+    bool operator==(const CSSAnimationData& o) const { return animationsMatchForStyleRecalc(&o); }
     bool operator!=(const CSSAnimationData& o) const { return !(*this == o); }
 
     bool fillsBackwards() const { return m_fillModeSet && (m_fillMode == AnimationFillModeBackwards || m_fillMode == AnimationFillModeBoth); }
@@ -147,8 +147,9 @@
     CSSAnimationData();
     explicit CSSAnimationData(const CSSAnimationData&);
 
-    // return true if all members of this class match (excluding m_next)
-    bool animationsMatch(const CSSAnimationData*, bool matchPlayStates = true) const;
+    // Return whether this object matches another CSSAnimationData object for
+    // the purposes of style recalc. This excludes some properties.
+    bool animationsMatchForStyleRecalc(const CSSAnimationData*) const;
 
     AtomicString m_name;
     CSSPropertyID m_property;
diff --git a/Source/core/platform/animation/TimingFunction.h b/Source/core/platform/animation/TimingFunction.h
index 3429257..1752ff5 100644
--- a/Source/core/platform/animation/TimingFunction.h
+++ b/Source/core/platform/animation/TimingFunction.h
@@ -32,9 +32,11 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
+#include "wtf/StdLibExtras.h"
 #include "wtf/Vector.h"
 #include <algorithm>
 
+
 namespace WebCore {
 
 class TimingFunction : public RefCounted<TimingFunction> {
@@ -51,7 +53,6 @@
     // Evaluates the timing function at the given fraction. The accuracy parameter provides a hint as to the required
     // accuracy and is not guaranteed.
     virtual double evaluate(double fraction, double accuracy) const = 0;
-    virtual bool operator==(const TimingFunction& other) const = 0;
 
 protected:
     TimingFunction(Type type)
@@ -75,15 +76,10 @@
     virtual double evaluate(double fraction, double) const
     {
         ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
-        RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+        ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
         return fraction;
     }
 
-    virtual bool operator==(const TimingFunction& other) const
-    {
-        return other.type() == LinearFunction;
-    }
-
 private:
     LinearTimingFunction()
         : TimingFunction(LinearFunction)
@@ -91,6 +87,10 @@
     }
 };
 
+
+// Forward declare so we can friend it below. Don't use in production code!
+class ChainedTimingFunctionTestHelper;
+
 class CubicBezierTimingFunction : public TimingFunction {
 public:
     enum SubType {
@@ -111,22 +111,22 @@
         switch (subType) {
         case Ease:
             {
-                static CubicBezierTimingFunction* ease = adoptRef(new CubicBezierTimingFunction(Ease, 0.25, 0.1, 0.25, 1.0)).leakRef();
+                DEFINE_STATIC_REF(CubicBezierTimingFunction, ease, (adoptRef(new CubicBezierTimingFunction(Ease, 0.25, 0.1, 0.25, 1.0))));
                 return ease;
             }
         case EaseIn:
             {
-                static CubicBezierTimingFunction* easeIn = adoptRef(new CubicBezierTimingFunction(EaseIn, 0.42, 0.0, 1.0, 1.0)).leakRef();
+                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeIn, (adoptRef(new CubicBezierTimingFunction(EaseIn, 0.42, 0.0, 1.0, 1.0))));
                 return easeIn;
             }
         case EaseOut:
             {
-                static CubicBezierTimingFunction* easeOut = adoptRef(new CubicBezierTimingFunction(EaseOut, 0.0, 0.0, 0.58, 1.0)).leakRef();
+                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeOut, (adoptRef(new CubicBezierTimingFunction(EaseOut, 0.0, 0.0, 0.58, 1.0))));
                 return easeOut;
             }
         case EaseInOut:
             {
-                static CubicBezierTimingFunction* easeInOut = adoptRef(new CubicBezierTimingFunction(EaseInOut, 0.42, 0.0, 0.58, 1.0)).leakRef();
+                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeInOut, (adoptRef(new CubicBezierTimingFunction(EaseInOut, 0.42, 0.0, 0.58, 1.0))));
                 return easeInOut;
             }
         default:
@@ -140,24 +140,12 @@
     virtual double evaluate(double fraction, double accuracy) const
     {
         ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
-        RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+        ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
         if (!m_bezier)
             m_bezier = adoptPtr(new UnitBezier(m_x1, m_y1, m_x2, m_y2));
         return m_bezier->solve(fraction, accuracy);
     }
 
-    virtual bool operator==(const TimingFunction& other) const
-    {
-        if (other.type() == CubicBezierFunction) {
-            const CubicBezierTimingFunction* ctf = static_cast<const CubicBezierTimingFunction*>(&other);
-            if (m_subType != Custom)
-                return m_subType == ctf->m_subType;
-
-            return m_x1 == ctf->m_x1 && m_y1 == ctf->m_y1 && m_x2 == ctf->m_x2 && m_y2 == ctf->m_y2;
-        }
-        return false;
-    }
-
     double x1() const { return m_x1; }
     double y1() const { return m_y1; }
     double x2() const { return m_x2; }
@@ -202,12 +190,12 @@
         switch (subType) {
         case Start:
             {
-                static StepsTimingFunction* start = adoptRef(new StepsTimingFunction(Start, 1, true)).leakRef();
+                DEFINE_STATIC_REF(StepsTimingFunction, start, (adoptRef(new StepsTimingFunction(Start, 1, true))));
                 return start;
             }
         case End:
             {
-                static StepsTimingFunction* end = adoptRef(new StepsTimingFunction(End, 1, false)).leakRef();
+                DEFINE_STATIC_REF(StepsTimingFunction, end, (adoptRef(new StepsTimingFunction(End, 1, false))));
                 return end;
             }
         default:
@@ -222,21 +210,10 @@
     virtual double evaluate(double fraction, double) const
     {
         ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
-        RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+        ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
         return std::min(1.0, (floor(m_steps * fraction) + m_stepAtStart) / m_steps);
     }
 
-    virtual bool operator==(const TimingFunction& other) const
-    {
-        if (other.type() == StepsFunction) {
-            const StepsTimingFunction* stf = static_cast<const StepsTimingFunction*>(&other);
-            if (m_subType != Custom)
-                return m_subType == stf->m_subType;
-            return m_steps == stf->m_steps && m_stepAtStart == stf->m_stepAtStart;
-        }
-        return false;
-    }
-
     int numberOfSteps() const { return m_steps; }
     bool stepAtStart() const { return m_stepAtStart; }
 
@@ -271,7 +248,7 @@
     }
     virtual double evaluate(double fraction, double accuracy) const
     {
-        RELEASE_ASSERT_WITH_MESSAGE(fraction >= 0 && fraction <= 1, "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+        ASSERT_WITH_MESSAGE(fraction >= 0 && fraction <= 1, "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
         ASSERT(!m_segments.isEmpty());
         ASSERT(m_segments.last().max() == 1);
         size_t i = 0;
@@ -282,13 +259,6 @@
         return segment->evaluate(fraction, accuracy);
     }
 
-    virtual bool operator==(const TimingFunction& other) const
-    {
-        // This class is not exposed to CSS, so this method is not required.
-        ASSERT_NOT_REACHED();
-        return false;
-    }
-
 private:
     class Segment {
     public:
@@ -296,7 +266,7 @@
             : m_min(min)
             , m_max(max)
             , m_timingFunction(timingFunction)
-        { }
+        { ASSERT(timingFunction); }
 
         double max() const { return m_max; }
         double evaluate(double fraction, double accuracy) const
@@ -311,6 +281,16 @@
         double m_min;
         double m_max;
         RefPtr<TimingFunction> m_timingFunction;
+
+        // FIXME: Come up with a public API for the segments and remove this.
+        friend class CompositorAnimationsImpl;
+
+        // Allow the compositor to reverse the timing function.
+        friend class CompositorAnimationsTimingFunctionReverser;
+
+        // Allow PrintTo/operator== of the segments. Can be removed once
+        // ChainedTimingFunction has a public API for segments.
+        friend class ChainedTimingFunctionTestHelper;
     };
 
     ChainedTimingFunction()
@@ -320,8 +300,29 @@
     }
 
     Vector<Segment> m_segments;
+
+    // FIXME: Come up with a public API for the segments and remove this.
+    friend class CompositorAnimationsImpl;
+
+    // Allow the compositor to reverse the timing function.
+    friend class CompositorAnimationsTimingFunctionReverser;
+
+    // Allow PrintTo/operator== of the segments. Can be removed once
+    // ChainedTimingFunction has a public API for segments.
+    friend class ChainedTimingFunctionTestHelper;
 };
 
+#define DEFINE_TIMING_FUNCTION_TYPE_CASTS(typeName) \
+    DEFINE_TYPE_CASTS( \
+        typeName##TimingFunction, TimingFunction, value, \
+        value->type() == TimingFunction::typeName##Function, \
+        value.type() == TimingFunction::typeName##Function)
+
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(Linear);
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(CubicBezier);
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(Steps);
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(Chained);
+
 } // namespace WebCore
 
 #endif // TimingFunction_h
diff --git a/Source/core/platform/animation/TimingFunctionTestHelper.cpp b/Source/core/platform/animation/TimingFunctionTestHelper.cpp
new file mode 100644
index 0000000..66652f4
--- /dev/null
+++ b/Source/core/platform/animation/TimingFunctionTestHelper.cpp
@@ -0,0 +1,254 @@
+/*
+ * 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/animation/TimingFunctionTestHelper.h"
+
+#include <ostream> // NOLINT
+
+namespace WebCore {
+
+// This class exists so that ChainedTimingFunction only needs to friend one thing.
+class ChainedTimingFunctionTestHelper {
+    static void PrintTo(const ChainedTimingFunction& timingFunction, ::std::ostream* os)
+    {
+        // Forward declare the generic PrintTo function as ChainedTimingFunction needs to call it.
+        void PrintTo(const TimingFunction&, ::std::ostream*);
+
+        *os << "ChainedTimingFunction@" << &timingFunction << "(";
+        for (size_t i = 0; i < timingFunction.m_segments.size(); i++) {
+            ChainedTimingFunction::Segment segment = timingFunction.m_segments[i];
+            PrintTo(*(segment.m_timingFunction.get()), os);
+            *os << "[" << segment.m_min << " -> " << segment.m_max << "]";
+            if (i+1 != timingFunction.m_segments.size()) {
+                *os << ", ";
+            }
+        }
+        *os << ")";
+    }
+
+    static bool equals(const ChainedTimingFunction& lhs, const TimingFunction& rhs)
+    {
+        if (rhs.type() != TimingFunction::ChainedFunction)
+            return false;
+
+        if (&lhs == &rhs)
+            return true;
+
+        const ChainedTimingFunction& ctf = toChainedTimingFunction(rhs);
+        if (lhs.m_segments.size() != ctf.m_segments.size())
+            return false;
+
+        for (size_t i = 0; i < lhs.m_segments.size(); i++) {
+            if (!equals(lhs.m_segments[i], ctf.m_segments[i]))
+                return false;
+        }
+        return true;
+    }
+
+    static bool equals(const ChainedTimingFunction::Segment& lhs, const ChainedTimingFunction::Segment& rhs)
+    {
+        if (&lhs == &rhs)
+            return true;
+
+        if ((lhs.m_min != rhs.m_min) || (lhs.m_max != rhs.m_max))
+            return false;
+
+        if (lhs.m_timingFunction == rhs.m_timingFunction)
+            return true;
+
+        ASSERT(lhs.m_timingFunction);
+        ASSERT(rhs.m_timingFunction);
+
+        return (*(lhs.m_timingFunction.get())) == (*(rhs.m_timingFunction.get()));
+    }
+
+    friend void PrintTo(const ChainedTimingFunction&, ::std::ostream*);
+    friend bool operator==(const ChainedTimingFunction& lhs, const TimingFunction& rhs);
+};
+
+void PrintTo(const LinearTimingFunction& timingFunction, ::std::ostream* os)
+{
+    *os << "LinearTimingFunction@" << &timingFunction;
+}
+
+void PrintTo(const CubicBezierTimingFunction& timingFunction, ::std::ostream* os)
+{
+    *os << "CubicBezierTimingFunction@" << &timingFunction << "(";
+    switch (timingFunction.subType()) {
+    case CubicBezierTimingFunction::Ease:
+        *os << "Ease";
+        break;
+    case CubicBezierTimingFunction::EaseIn:
+        *os << "EaseIn";
+        break;
+    case CubicBezierTimingFunction::EaseOut:
+        *os << "EaseOut";
+        break;
+    case CubicBezierTimingFunction::EaseInOut:
+        *os << "EaseInOut";
+        break;
+    case CubicBezierTimingFunction::Custom:
+        *os << "Custom";
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+    }
+    *os << ", " << timingFunction.x1();
+    *os << ", " << timingFunction.y1();
+    *os << ", " << timingFunction.x2();
+    *os << ", " << timingFunction.y2();
+    *os << ")";
+}
+
+void PrintTo(const StepsTimingFunction& timingFunction, ::std::ostream* os)
+{
+    *os << "StepsTimingFunction@" << &timingFunction << "(";
+    switch (timingFunction.subType()) {
+    case StepsTimingFunction::Start:
+        *os << "Start";
+        break;
+    case StepsTimingFunction::End:
+        *os << "End";
+        break;
+    case StepsTimingFunction::Custom:
+        *os << "Custom";
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+    }
+    *os << ", " << timingFunction.numberOfSteps();
+    *os << ", " << (timingFunction.stepAtStart() ? "true" : "false");
+    *os << ")";
+}
+
+void PrintTo(const ChainedTimingFunction& timingFunction, ::std::ostream* os)
+{
+    ChainedTimingFunctionTestHelper::PrintTo(timingFunction, os);
+}
+
+// The generic PrintTo *must* come after the non-generic PrintTo otherwise it
+// will end up calling itself.
+void PrintTo(const TimingFunction& timingFunction, ::std::ostream* os)
+{
+    switch (timingFunction.type()) {
+    case TimingFunction::LinearFunction: {
+        const LinearTimingFunction& linear = toLinearTimingFunction(timingFunction);
+        PrintTo(linear, os);
+        return;
+    }
+    case TimingFunction::CubicBezierFunction: {
+        const CubicBezierTimingFunction& cubic = toCubicBezierTimingFunction(timingFunction);
+        PrintTo(cubic, os);
+        return;
+    }
+    case TimingFunction::StepsFunction: {
+        const StepsTimingFunction& step = toStepsTimingFunction(timingFunction);
+        PrintTo(step, os);
+        return;
+    }
+    case TimingFunction::ChainedFunction: {
+        const ChainedTimingFunction& chained = toChainedTimingFunction(timingFunction);
+        PrintTo(chained, os);
+        return;
+    }
+    default:
+        ASSERT_NOT_REACHED();
+    }
+}
+
+bool operator==(const LinearTimingFunction& lhs, const TimingFunction& rhs)
+{
+    return rhs.type() == TimingFunction::LinearFunction;
+}
+
+bool operator==(const CubicBezierTimingFunction& lhs, const TimingFunction& rhs)
+{
+    if (rhs.type() != TimingFunction::CubicBezierFunction)
+        return false;
+
+    const CubicBezierTimingFunction& ctf = toCubicBezierTimingFunction(rhs);
+    if ((lhs.subType() == CubicBezierTimingFunction::Custom) && (ctf.subType() == CubicBezierTimingFunction::Custom))
+        return (lhs.x1() == ctf.x1()) && (lhs.y1() == ctf.y1()) && (lhs.x2() == ctf.x2()) && (lhs.y2() == ctf.y2());
+
+    return lhs.subType() == ctf.subType();
+}
+
+bool operator==(const StepsTimingFunction& lhs, const TimingFunction& rhs)
+{
+    if (rhs.type() != TimingFunction::StepsFunction)
+        return false;
+
+    const StepsTimingFunction& stf = toStepsTimingFunction(rhs);
+    if ((lhs.subType() == StepsTimingFunction::Custom) && (stf.subType() == StepsTimingFunction::Custom))
+        return (lhs.numberOfSteps() == stf.numberOfSteps()) && (lhs.stepAtStart() == stf.stepAtStart());
+
+    return lhs.subType() == stf.subType();
+}
+
+bool operator==(const ChainedTimingFunction& lhs, const TimingFunction& rhs)
+{
+    return ChainedTimingFunctionTestHelper::equals(lhs, rhs);
+}
+
+// Like in the PrintTo case, the generic operator== *must* come after the
+// non-generic operator== otherwise it will end up calling itself.
+bool operator==(const TimingFunction& lhs, const TimingFunction& rhs)
+{
+    switch (lhs.type()) {
+    case TimingFunction::LinearFunction: {
+        const LinearTimingFunction& linear = toLinearTimingFunction(lhs);
+        return (linear == rhs);
+    }
+    case TimingFunction::CubicBezierFunction: {
+        const CubicBezierTimingFunction& cubic = toCubicBezierTimingFunction(lhs);
+        return (cubic == rhs);
+    }
+    case TimingFunction::StepsFunction: {
+        const StepsTimingFunction& step = toStepsTimingFunction(lhs);
+        return (step == rhs);
+    }
+    case TimingFunction::ChainedFunction: {
+        const ChainedTimingFunction& chained = toChainedTimingFunction(lhs);
+        return (chained == rhs);
+    }
+    default:
+        ASSERT_NOT_REACHED();
+    }
+    return false;
+}
+
+// No need to define specific operator!= as they can all come via this function.
+bool operator!=(const TimingFunction& lhs, const TimingFunction& rhs)
+{
+    return !(lhs == rhs);
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/animation/TimingFunctionTestHelper.h b/Source/core/platform/animation/TimingFunctionTestHelper.h
new file mode 100644
index 0000000..06eaf06
--- /dev/null
+++ b/Source/core/platform/animation/TimingFunctionTestHelper.h
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+/**
+ * Make testing with gtest and gmock nicer by adding pretty print and other
+ * helper functions.
+ */
+
+#ifndef TimingFunctionTestHelper_h
+#define TimingFunctionTestHelper_h
+
+#include "core/platform/animation/TimingFunction.h"
+
+#include <ostream> // NOLINT
+
+namespace WebCore {
+
+// PrintTo functions
+void PrintTo(const LinearTimingFunction&, ::std::ostream*);
+void PrintTo(const CubicBezierTimingFunction&, ::std::ostream*);
+void PrintTo(const StepsTimingFunction&, ::std::ostream*);
+void PrintTo(const ChainedTimingFunction&, ::std::ostream*);
+void PrintTo(const TimingFunction&, ::std::ostream*);
+
+// operator== functions
+bool operator==(const LinearTimingFunction&, const TimingFunction&);
+bool operator==(const CubicBezierTimingFunction&, const TimingFunction&);
+bool operator==(const StepsTimingFunction&, const TimingFunction&);
+bool operator==(const ChainedTimingFunction&, const TimingFunction&);
+
+bool operator==(const TimingFunction&, const TimingFunction&);
+bool operator!=(const TimingFunction&, const TimingFunction&);
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp b/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp
new file mode 100644
index 0000000..643c626
--- /dev/null
+++ b/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp
@@ -0,0 +1,341 @@
+/*
+ * 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/animation/TimingFunctionTestHelper.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <sstream>
+#include <string>
+
+// FIXME: Remove once https://codereview.chromium.org/50603011/ lands.
+#define EXPECT_REFV_EQ(a, b) EXPECT_EQ(*(a.get()), *(b.get()))
+#define EXPECT_REFV_NE(a, b) EXPECT_NE(*(a.get()), *(b.get()))
+
+// Couple of macros to quickly assert a bunch of timing functions are not
+// equal.
+#define NE_STRINGIZE(x) NE_STRINGIZE2(x)
+#define NE_STRINGIZE2(x) #x
+#define NE_HELPER(v) \
+    Vector<std::pair<std::string, RefPtr<TimingFunction> > > v;
+#define NE_HELPER_APPEND(v, x) \
+    v.append(std::make_pair(std::string("Line " NE_STRINGIZE(__LINE__) ":" # x), x))
+#define NE_HELPER_LOOP(v) \
+    for (size_t i = 0; i != v.size(); ++i) { \
+        for (size_t j = 0; j != v.size(); ++j) { \
+            if (i == j) \
+                continue; \
+            EXPECT_REFV_NE(v[i].second, v[j].second) \
+                << v[i].first \
+                << " (" << ::testing::PrintToString(*v[i].second.get()) << ")" \
+                << "  ==  " \
+                << v[j].first \
+                << " (" << ::testing::PrintToString(*v[j].second.get()) << ")" \
+                << "\n"; \
+        } \
+    }
+
+namespace {
+
+using namespace WebCore;
+
+class TimingFunctionTestHelperTest : public ::testing::Test {
+
+protected:
+    bool m_enabled;
+
+    virtual void SetUp()
+    {
+        m_enabled = RuntimeEnabledFeatures::webAnimationsEnabled();
+        // Needed for ChainedTimingFunction support
+        RuntimeEnabledFeatures::setWebAnimationsEnabled(true);
+    }
+
+    virtual void TearDown()
+    {
+        RuntimeEnabledFeatures::setWebAnimationsEnabled(m_enabled);
+    }
+
+public:
+    // Make sure that the CubicBezierTimingFunction call goes via the generic
+    // TimingFunction PrintTo.
+    ::std::string PrintToString(RefPtr<CubicBezierTimingFunction> timing)
+    {
+        RefPtr<TimingFunction> generic = timing;
+        return PrintToString(generic.get());
+    }
+
+    ::std::string PrintToString(RefPtr<TimingFunction> timing)
+    {
+        return PrintToString(timing.get());
+    }
+
+    ::std::string PrintToString(const TimingFunction* timing)
+    {
+        return ::testing::PrintToString(*timing);
+    }
+};
+
+TEST_F(TimingFunctionTestHelperTest, LinearPrintTo)
+{
+    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+    EXPECT_THAT(
+        PrintToString(linearTiming),
+        ::testing::MatchesRegex("LinearTimingFunction@.*"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, CubicPrintTo)
+{
+    RefPtr<TimingFunction> cubicEaseTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    EXPECT_THAT(
+        PrintToString(cubicEaseTiming),
+        ::testing::MatchesRegex("CubicBezierTimingFunction@.*\\(EaseIn, 0.42, 0, 1, 1\\)"));
+
+    RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+    EXPECT_THAT(
+        PrintToString(cubicCustomTiming),
+        ::testing::MatchesRegex("CubicBezierTimingFunction@.*\\(Custom, 0.17, 0.67, 1, -1.73\\)"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, StepPrintTo)
+{
+    RefPtr<TimingFunction> stepTimingStart = StepsTimingFunction::preset(StepsTimingFunction::Start);
+    EXPECT_THAT(
+        PrintToString(stepTimingStart),
+        ::testing::MatchesRegex("StepsTimingFunction@.*\\(Start, 1, true\\)"));
+
+    RefPtr<TimingFunction> stepTimingCustom = StepsTimingFunction::create(5, false);
+    EXPECT_THAT(
+        PrintToString(stepTimingCustom),
+        ::testing::MatchesRegex("StepsTimingFunction@.*\\(Custom, 5, false\\)"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, ChainedPrintTo)
+{
+    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+    RefPtr<ChainedTimingFunction> chainedLinearSingle = ChainedTimingFunction::create();
+    chainedLinearSingle->appendSegment(1.0, linearTiming.get());
+    EXPECT_THAT(
+        PrintToString(chainedLinearSingle),
+        ::testing::MatchesRegex(
+            "ChainedTimingFunction@.*\\("
+                "LinearTimingFunction@.*\\[0 -> 1\\]"
+            "\\)"));
+
+    RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(1.0, 0.0, 1, -1);
+
+    RefPtr<ChainedTimingFunction> chainedMixed = ChainedTimingFunction::create();
+    chainedMixed->appendSegment(0.75, chainedLinearSingle.get());
+    chainedMixed->appendSegment(1.0, cubicCustomTiming.get());
+    EXPECT_THAT(
+        PrintToString(chainedMixed),
+        ::testing::MatchesRegex(
+            "ChainedTimingFunction@.*\\("
+                "ChainedTimingFunction@.*\\("
+                    "LinearTimingFunction@.*\\[0 -> 1\\]"
+                "\\)\\[0 -> 0.75\\], "
+                "CubicBezierTimingFunction@.*\\(Custom, 1, 0, 1, -1\\)\\[0.75 -> 1\\]"
+            "\\)"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, BaseOperatorEq)
+{
+    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+    RefPtr<TimingFunction> cubicTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    RefPtr<TimingFunction> cubicTiming2 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+    RefPtr<TimingFunction> stepsTiming1 = StepsTimingFunction::preset(StepsTimingFunction::End);
+    RefPtr<TimingFunction> stepsTiming2 = StepsTimingFunction::create(5, true);
+
+    RefPtr<ChainedTimingFunction> chainedTiming1 = ChainedTimingFunction::create();
+    chainedTiming1->appendSegment(1.0, linearTiming.get());
+
+    RefPtr<ChainedTimingFunction> chainedTiming2 = ChainedTimingFunction::create();
+    chainedTiming2->appendSegment(0.5, cubicTiming1.get());
+    chainedTiming2->appendSegment(1.0, cubicTiming2.get());
+
+    NE_HELPER(v);
+    NE_HELPER_APPEND(v, linearTiming);
+    NE_HELPER_APPEND(v, cubicTiming1);
+    NE_HELPER_APPEND(v, cubicTiming2);
+    NE_HELPER_APPEND(v, stepsTiming1);
+    NE_HELPER_APPEND(v, stepsTiming2);
+    NE_HELPER_APPEND(v, chainedTiming1);
+    NE_HELPER_APPEND(v, chainedTiming2);
+    NE_HELPER_LOOP(v);
+}
+
+TEST_F(TimingFunctionTestHelperTest, LinearOperatorEq)
+{
+    RefPtr<TimingFunction> linearTiming1 = LinearTimingFunction::create();
+    RefPtr<TimingFunction> linearTiming2 = LinearTimingFunction::create();
+    EXPECT_REFV_EQ(linearTiming1, linearTiming1);
+    EXPECT_REFV_EQ(linearTiming1, linearTiming2);
+}
+
+TEST_F(TimingFunctionTestHelperTest, CubicOperatorEq)
+{
+    RefPtr<TimingFunction> cubicEaseInTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    RefPtr<TimingFunction> cubicEaseInTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    EXPECT_REFV_EQ(cubicEaseInTiming1, cubicEaseInTiming1);
+    EXPECT_REFV_EQ(cubicEaseInTiming1, cubicEaseInTiming2);
+
+    RefPtr<TimingFunction> cubicEaseOutTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+    RefPtr<TimingFunction> cubicEaseOutTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+    EXPECT_REFV_EQ(cubicEaseOutTiming1, cubicEaseOutTiming2);
+
+    RefPtr<TimingFunction> cubicEaseInOutTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
+    RefPtr<TimingFunction> cubicEaseInOutTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
+    EXPECT_REFV_EQ(cubicEaseInOutTiming1, cubicEaseInOutTiming2);
+
+    RefPtr<TimingFunction> cubicCustomTiming1 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+    RefPtr<TimingFunction> cubicCustomTiming2 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+    EXPECT_REFV_EQ(cubicCustomTiming1, cubicCustomTiming2);
+
+    NE_HELPER(v);
+    NE_HELPER_APPEND(v, cubicEaseInTiming1);
+    NE_HELPER_APPEND(v, cubicEaseOutTiming1);
+    NE_HELPER_APPEND(v, cubicEaseInOutTiming1);
+    NE_HELPER_APPEND(v, cubicCustomTiming1);
+    NE_HELPER_LOOP(v);
+}
+
+TEST_F(TimingFunctionTestHelperTest, CubicOperatorEqReflectivity)
+{
+    RefPtr<TimingFunction> cubicA = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+    RefPtr<TimingFunction> cubicB = CubicBezierTimingFunction::create(0.42, 0.0, 1.0, 1.0);
+    EXPECT_REFV_NE(cubicA, cubicB);
+    EXPECT_REFV_NE(cubicB, cubicA);
+}
+
+TEST_F(TimingFunctionTestHelperTest, StepsOperatorEq)
+{
+    RefPtr<TimingFunction> stepsTimingStart1 = StepsTimingFunction::preset(StepsTimingFunction::Start);
+    RefPtr<TimingFunction> stepsTimingStart2 = StepsTimingFunction::preset(StepsTimingFunction::Start);
+    EXPECT_REFV_EQ(stepsTimingStart1, stepsTimingStart1);
+    EXPECT_REFV_EQ(stepsTimingStart1, stepsTimingStart2);
+
+    RefPtr<TimingFunction> stepsTimingEnd1 = StepsTimingFunction::preset(StepsTimingFunction::End);
+    RefPtr<TimingFunction> stepsTimingEnd2 = StepsTimingFunction::preset(StepsTimingFunction::End);
+    EXPECT_REFV_EQ(stepsTimingEnd1, stepsTimingEnd2);
+
+    RefPtr<TimingFunction> stepsTimingCustom1 = StepsTimingFunction::create(5, true);
+    RefPtr<TimingFunction> stepsTimingCustom2 = StepsTimingFunction::create(5, false);
+    RefPtr<TimingFunction> stepsTimingCustom3 = StepsTimingFunction::create(7, true);
+    RefPtr<TimingFunction> stepsTimingCustom4 = StepsTimingFunction::create(7, false);
+
+    EXPECT_REFV_EQ(stepsTimingCustom1, StepsTimingFunction::create(5, true));
+    EXPECT_REFV_EQ(stepsTimingCustom2, StepsTimingFunction::create(5, false));
+    EXPECT_REFV_EQ(stepsTimingCustom3, StepsTimingFunction::create(7, true));
+    EXPECT_REFV_EQ(stepsTimingCustom4, StepsTimingFunction::create(7, false));
+
+    NE_HELPER(v);
+    NE_HELPER_APPEND(v, stepsTimingStart1);
+    NE_HELPER_APPEND(v, stepsTimingEnd1);
+    NE_HELPER_APPEND(v, stepsTimingCustom1);
+    NE_HELPER_APPEND(v, stepsTimingCustom2);
+    NE_HELPER_APPEND(v, stepsTimingCustom3);
+    NE_HELPER_APPEND(v, stepsTimingCustom4);
+    NE_HELPER_LOOP(v);
+}
+
+TEST_F(TimingFunctionTestHelperTest, StepsOperatorEqReflectivity)
+{
+    RefPtr<TimingFunction> stepsA = StepsTimingFunction::preset(StepsTimingFunction::Start);
+    RefPtr<TimingFunction> stepsB = StepsTimingFunction::create(1, true);
+    EXPECT_REFV_NE(stepsA, stepsB);
+    EXPECT_REFV_NE(stepsB, stepsA);
+}
+
+TEST_F(TimingFunctionTestHelperTest, ChainedEq)
+{
+    // Single item in chain
+    RefPtr<TimingFunction> cubicTiming1 = CubicBezierTimingFunction::create(0.25, 0.1, 0.25, 1.0);
+    RefPtr<TimingFunction> cubicTiming2 = CubicBezierTimingFunction::create(0.25, 0.1, 0.25, 1.0);
+    RefPtr<TimingFunction> cubicTiming3 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+
+    RefPtr<ChainedTimingFunction> chainedSingleCubic1 = ChainedTimingFunction::create();
+    chainedSingleCubic1->appendSegment(1.0, cubicTiming1.get());
+    EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic1);
+
+    RefPtr<ChainedTimingFunction> chainedSingleCubic2 = ChainedTimingFunction::create();
+    chainedSingleCubic2->appendSegment(1.0, cubicTiming1.get()); // Same inner timing function
+    EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic2);
+
+    RefPtr<ChainedTimingFunction> chainedSingleCubic3 = ChainedTimingFunction::create();
+    chainedSingleCubic3->appendSegment(1.0, cubicTiming2.get()); // == inner timing function
+    EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic3);
+
+    RefPtr<ChainedTimingFunction> chainedSingleCubic4 = ChainedTimingFunction::create();
+    chainedSingleCubic4->appendSegment(0.5, cubicTiming1.get()); // Different offset
+    EXPECT_REFV_NE(chainedSingleCubic1, chainedSingleCubic4);
+    EXPECT_REFV_NE(chainedSingleCubic3, chainedSingleCubic4);
+
+    RefPtr<ChainedTimingFunction> chainedSingleCubic5 = ChainedTimingFunction::create();
+    chainedSingleCubic5->appendSegment(1.0, cubicTiming3.get()); // != inner timing function (same type)
+    EXPECT_REFV_NE(chainedSingleCubic1, chainedSingleCubic5);
+    EXPECT_REFV_NE(chainedSingleCubic2, chainedSingleCubic5);
+    EXPECT_REFV_NE(chainedSingleCubic3, chainedSingleCubic5);
+    EXPECT_REFV_NE(chainedSingleCubic4, chainedSingleCubic5);
+
+    RefPtr<TimingFunction> linearTiming1 = LinearTimingFunction::create();
+    RefPtr<ChainedTimingFunction> chainedSingleLinear1 = ChainedTimingFunction::create();
+    chainedSingleLinear1->appendSegment(1.0, linearTiming1.get()); // != inner timing function (different type)
+    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic1);
+    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic2);
+    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic3);
+    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic4);
+
+    // Multiple items in chain
+    RefPtr<ChainedTimingFunction> chainedMixed1 = ChainedTimingFunction::create();
+    chainedMixed1->appendSegment(0.25, chainedSingleLinear1.get());
+    chainedMixed1->appendSegment(1.0, cubicTiming1.get());
+
+    RefPtr<ChainedTimingFunction> chainedMixed2 = ChainedTimingFunction::create();
+    chainedMixed2->appendSegment(0.25, chainedSingleLinear1.get());
+    chainedMixed2->appendSegment(1.0, cubicTiming1.get());
+
+    RefPtr<ChainedTimingFunction> chainedMixed3 = ChainedTimingFunction::create();
+    chainedMixed3->appendSegment(0.25, chainedSingleLinear1.get());
+    chainedMixed3->appendSegment(1.0, cubicTiming2.get());
+
+    EXPECT_REFV_EQ(chainedMixed1, chainedMixed2);
+    EXPECT_REFV_EQ(chainedMixed1, chainedMixed3);
+    EXPECT_REFV_NE(chainedMixed1, chainedSingleCubic1);
+    EXPECT_REFV_NE(chainedMixed1, chainedSingleLinear1);
+
+    RefPtr<ChainedTimingFunction> chainedMixed4 = ChainedTimingFunction::create();
+    chainedMixed4->appendSegment(0.20, chainedSingleLinear1.get()); // Different offset
+    chainedMixed4->appendSegment(1.0, cubicTiming1.get());
+    EXPECT_REFV_NE(chainedMixed1, chainedMixed4);
+}
+
+} // namespace
diff --git a/Source/core/platform/chromium/ChromiumDataObject.cpp b/Source/core/platform/chromium/ChromiumDataObject.cpp
index f649954..feb58e8 100644
--- a/Source/core/platform/chromium/ChromiumDataObject.cpp
+++ b/Source/core/platform/chromium/ChromiumDataObject.cpp
@@ -47,10 +47,10 @@
 PassRefPtr<ChromiumDataObject> ChromiumDataObject::createFromPasteboard(PasteMode pasteMode)
 {
     RefPtr<ChromiumDataObject> dataObject = create();
-    WebKit::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
-    uint64_t sequenceNumber = WebKit::Platform::current()->clipboard()->sequenceNumber(buffer);
+    blink::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
+    uint64_t sequenceNumber = blink::Platform::current()->clipboard()->sequenceNumber(buffer);
     bool ignored;
-    WebKit::WebVector<WebKit::WebString> webTypes = WebKit::Platform::current()->clipboard()->readAvailableTypes(buffer, &ignored);
+    blink::WebVector<blink::WebString> webTypes = blink::Platform::current()->clipboard()->readAvailableTypes(buffer, &ignored);
     ListHashSet<String> types;
     for (size_t i = 0; i < webTypes.size(); ++i)
         types.add(webTypes[i]);
@@ -96,11 +96,11 @@
     m_itemList.clear();
 }
 
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(const String& data, const String& type, ExceptionState& es)
+PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(const String& data, const String& type, ExceptionState& exceptionState)
 {
     RefPtr<ChromiumDataObjectItem> item = ChromiumDataObjectItem::createFromString(type, data);
     if (!internalAddStringItem(item)) {
-        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("add", "DataTransferItemList"));
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("add", "DataTransferItemList"));
         return 0;
     }
     return item;
diff --git a/Source/core/platform/chromium/ChromiumDataObjectItem.cpp b/Source/core/platform/chromium/ChromiumDataObjectItem.cpp
index 601bc60..321226c 100644
--- a/Source/core/platform/chromium/ChromiumDataObjectItem.cpp
+++ b/Source/core/platform/chromium/ChromiumDataObjectItem.cpp
@@ -138,7 +138,7 @@
         // method to the blob registry; that way the data is only copied over
         // into the renderer when it's actually read, not when the blob is
         // initially constructed).
-        RefPtr<SharedBuffer> data = static_cast<PassRefPtr<SharedBuffer> >(WebKit::Platform::current()->clipboard()->readImage(WebKit::WebClipboard::BufferStandard));
+        RefPtr<SharedBuffer> data = static_cast<PassRefPtr<SharedBuffer> >(blink::Platform::current()->clipboard()->readImage(blink::WebClipboard::BufferStandard));
         RefPtr<RawData> rawData = RawData::create();
         rawData->mutableData()->append(data->data(), data->size());
         OwnPtr<BlobData> blobData = BlobData::create();
@@ -159,19 +159,19 @@
 
     ASSERT(m_source == PasteboardSource);
 
-    WebKit::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
+    blink::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
     String data;
     // This is ugly but there's no real alternative.
     if (m_type == mimeTypeTextPlain)
-        data = WebKit::Platform::current()->clipboard()->readPlainText(buffer);
+        data = blink::Platform::current()->clipboard()->readPlainText(buffer);
     else if (m_type == mimeTypeTextHTML) {
-        WebKit::WebURL ignoredSourceURL;
+        blink::WebURL ignoredSourceURL;
         unsigned ignored;
-        data = WebKit::Platform::current()->clipboard()->readHTML(buffer, &ignoredSourceURL, &ignored, &ignored);
+        data = blink::Platform::current()->clipboard()->readHTML(buffer, &ignoredSourceURL, &ignored, &ignored);
     } else
-        data = WebKit::Platform::current()->clipboard()->readCustomData(buffer, m_type);
+        data = blink::Platform::current()->clipboard()->readCustomData(buffer, m_type);
 
-    return WebKit::Platform::current()->clipboard()->sequenceNumber(buffer) == m_sequenceNumber ? data : String();
+    return blink::Platform::current()->clipboard()->sequenceNumber(buffer) == m_sequenceNumber ? data : String();
 }
 
 bool ChromiumDataObjectItem::isFilename() const
diff --git a/Source/core/platform/chromium/ChromiumDataObjectItem.h b/Source/core/platform/chromium/ChromiumDataObjectItem.h
index 486a53e..20e2851 100644
--- a/Source/core/platform/chromium/ChromiumDataObjectItem.h
+++ b/Source/core/platform/chromium/ChromiumDataObjectItem.h
@@ -33,7 +33,7 @@
 
 #include "core/fileapi/File.h"
 #include "platform/SharedBuffer.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/platform/chromium/FramelessScrollView.cpp b/Source/core/platform/chromium/FramelessScrollView.cpp
index a2a39b8..8c810f5 100644
--- a/Source/core/platform/chromium/FramelessScrollView.cpp
+++ b/Source/core/platform/chromium/FramelessScrollView.cpp
@@ -85,7 +85,10 @@
 
 IntRect FramelessScrollView::windowClipRect(bool clipToContents) const
 {
-    return contentsToWindow(visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars));
+    IntRect clipRect = visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars);
+    if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar())
+        clipRect.move(verticalScrollbar()->width(), 0);
+    return contentsToWindow(clipRect);
 }
 
 void FramelessScrollView::paintContents(GraphicsContext*, const IntRect&)
diff --git a/Source/core/platform/chromium/KeyboardCodes.h b/Source/core/platform/chromium/KeyboardCodes.h
index 9228fdd..70a14e9 100644
--- a/Source/core/platform/chromium/KeyboardCodes.h
+++ b/Source/core/platform/chromium/KeyboardCodes.h
@@ -35,7 +35,7 @@
 #include <windows.h>
 #endif
 
-#include "core/platform/WindowsKeyboardCodes.h"
+#include "platform/WindowsKeyboardCodes.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp b/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp
deleted file mode 100644
index 1d93eeb..0000000
--- a/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2008, 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:
- *
- *     * 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/MIMETypeRegistry.h"
-
-#include "core/plugins/PluginData.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebMimeRegistry.h"
-#include "wtf/text/CString.h"
-
-namespace WebCore {
-
-String MIMETypeRegistry::getMIMETypeForExtension(const String &ext)
-{
-    return WebKit::Platform::current()->mimeRegistry()->mimeTypeForExtension(ext);
-}
-
-String MIMETypeRegistry::getWellKnownMIMETypeForExtension(const String &ext)
-{
-    // This method must be thread safe and should not consult the OS/registry.
-    return WebKit::Platform::current()->mimeRegistry()->wellKnownMimeTypeForExtension(ext);
-}
-
-String MIMETypeRegistry::getMIMETypeForPath(const String& path)
-{
-    int pos = path.reverseFind('.');
-    if (pos < 0)
-        return "application/octet-stream";
-    String extension = path.substring(pos + 1);
-    String mimeType = getMIMETypeForExtension(extension);
-    if (mimeType.isEmpty()) {
-        // If there's no mimetype registered for the extension, check to see
-        // if a plugin can handle the extension.
-        mimeType = getPluginMimeTypeFromExtension(extension);
-    }
-    if (mimeType.isEmpty())
-        return "application/octet-stream";
-    return mimeType;
-}
-
-bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType)
-{
-    return WebKit::Platform::current()->mimeRegistry()->supportsImageMIMEType(mimeType)
-        != WebKit::WebMimeRegistry::IsNotSupported;
-}
-
-bool MIMETypeRegistry::isSupportedImageResourceMIMEType(const String& mimeType)
-{
-    return isSupportedImageMIMEType(mimeType);
-}
-
-bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType)
-{
-    if (mimeType == "image/jpeg" || mimeType == "image/png")
-        return true;
-    if (mimeType == "image/webp")
-        return true;
-    return false;
-}
-
-bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType)
-{
-    return WebKit::Platform::current()->mimeRegistry()->supportsJavaScriptMIMEType(mimeType)
-        != WebKit::WebMimeRegistry::IsNotSupported;
-}
-
-bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType)
-{
-    return WebKit::Platform::current()->mimeRegistry()->supportsNonImageMIMEType(mimeType)
-        != WebKit::WebMimeRegistry::IsNotSupported;
-}
-
-bool MIMETypeRegistry::isSupportedMediaSourceMIMEType(const String& mimeType, const String& codecs)
-{
-    return !mimeType.isEmpty()
-        && WebKit::Platform::current()->mimeRegistry()->supportsMediaSourceMIMEType(mimeType, codecs);
-}
-
-bool MIMETypeRegistry::isJavaAppletMIMEType(const String& mimeType)
-{
-    // Since this set is very limited and is likely to remain so we won't bother with the overhead
-    // of using a hash set.
-    // Any of the MIME types below may be followed by any number of specific versions of the JVM,
-    // which is why we use startsWith()
-    return mimeType.startsWith("application/x-java-applet", false)
-        || mimeType.startsWith("application/x-java-bean", false)
-        || mimeType.startsWith("application/x-java-vm", false);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/support/WebArrayBuffer.cpp b/Source/core/platform/chromium/support/WebArrayBuffer.cpp
index 3b01f5e..05429fe 100644
--- a/Source/core/platform/chromium/support/WebArrayBuffer.cpp
+++ b/Source/core/platform/chromium/support/WebArrayBuffer.cpp
@@ -37,7 +37,7 @@
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
 WebArrayBuffer WebArrayBuffer::create(unsigned numElements, unsigned elementByteSize)
 {
@@ -78,7 +78,7 @@
 
 WebArrayBuffer* WebArrayBuffer::createFromV8Value(v8::Handle<v8::Value> value)
 {
-    if (!V8ArrayBuffer::HasInstanceInAnyWorld(value, v8::Isolate::GetCurrent()))
+    if (!V8ArrayBuffer::hasInstanceInAnyWorld(value, v8::Isolate::GetCurrent()))
         return 0;
     WTF::ArrayBuffer* buffer = V8ArrayBuffer::toNative(value->ToObject());
     return new WebArrayBuffer(buffer);
@@ -100,4 +100,4 @@
     return m_private.get();
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebCrypto.cpp b/Source/core/platform/chromium/support/WebCrypto.cpp
index 0d58262..3fd68af 100644
--- a/Source/core/platform/chromium/support/WebCrypto.cpp
+++ b/Source/core/platform/chromium/support/WebCrypto.cpp
@@ -35,7 +35,7 @@
 #include "public/platform/WebArrayBuffer.h"
 #include <string.h>
 
-namespace WebKit {
+namespace blink {
 
 void WebCryptoResult::completeWithError()
 {
@@ -52,7 +52,7 @@
 
 void WebCryptoResult::completeWithBuffer(const void* bytes, unsigned bytesSize)
 {
-    WebArrayBuffer buffer = WebKit::WebArrayBuffer::create(bytesSize, 1);
+    WebArrayBuffer buffer = blink::WebArrayBuffer::create(bytesSize, 1);
     RELEASE_ASSERT(!buffer.isNull());
     memcpy(buffer.data(), bytes, bytesSize);
     completeWithBuffer(buffer);
@@ -95,4 +95,4 @@
     m_impl = o.m_impl;
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebCursorInfo.cpp b/Source/core/platform/chromium/support/WebCursorInfo.cpp
index 0e7dfa5..cd4e64a 100644
--- a/Source/core/platform/chromium/support/WebCursorInfo.cpp
+++ b/Source/core/platform/chromium/support/WebCursorInfo.cpp
@@ -29,13 +29,13 @@
  */
 
 #include "config.h"
-#include "WebCursorInfo.h"
+#include "public/platform/WebCursorInfo.h"
 
 #include "core/platform/Cursor.h"
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
 WebCursorInfo::WebCursorInfo(const Cursor& cursor)
     : type(static_cast<Type>(cursor.type()))
@@ -48,4 +48,4 @@
 {
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebMediaConstraints.cpp b/Source/core/platform/chromium/support/WebMediaConstraints.cpp
deleted file mode 100644
index d64ef77..0000000
--- a/Source/core/platform/chromium/support/WebMediaConstraints.cpp
+++ /dev/null
@@ -1,108 +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 "public/platform/WebMediaConstraints.h"
-
-#include "core/platform/mediastream/MediaConstraints.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebMediaConstraint::WebMediaConstraint(const WebCore::MediaConstraint& other)
-    : m_name(other.m_name)
-    , m_value(other.m_value)
-{
-}
-
-WebMediaConstraints::WebMediaConstraints(const PassRefPtr<MediaConstraints>& constraints)
-    : m_private(constraints)
-{
-}
-
-WebMediaConstraints::WebMediaConstraints(MediaConstraints* constraints)
-    : m_private(constraints)
-{
-}
-
-void WebMediaConstraints::assign(const WebMediaConstraints& other)
-{
-    m_private = other.m_private;
-}
-
-void WebMediaConstraints::reset()
-{
-    m_private.reset();
-}
-
-void WebMediaConstraints::getMandatoryConstraints(WebVector<WebMediaConstraint>& constraints) const
-{
-    ASSERT(!isNull());
-    Vector<MediaConstraint> mandatoryConstraints;
-    m_private->getMandatoryConstraints(mandatoryConstraints);
-    WebVector<WebMediaConstraint> result(mandatoryConstraints);
-    constraints.swap(result);
-}
-
-void WebMediaConstraints::getOptionalConstraints(WebVector<WebMediaConstraint>& constraints) const
-{
-    ASSERT(!isNull());
-    Vector<MediaConstraint> optionalConstraints;
-    m_private->getOptionalConstraints(optionalConstraints);
-    WebVector<WebMediaConstraint> result(optionalConstraints);
-    constraints.swap(result);
-}
-
-bool WebMediaConstraints::getMandatoryConstraintValue(const WebString& name, WebString& value) const
-{
-    ASSERT(!isNull());
-    String result;
-    if (m_private->getMandatoryConstraintValue(name, result)) {
-        value = result;
-        return true;
-    }
-    return false;
-}
-
-bool WebMediaConstraints::getOptionalConstraintValue(const WebString& name, WebString& value) const
-{
-    ASSERT(!isNull());
-    String result;
-    if (m_private->getOptionalConstraintValue(name, result)) {
-        value = result;
-        return true;
-    }
-    return false;
-}
-
-} // namespace WebKit
-
diff --git a/Source/core/platform/chromium/support/WebMediaStream.cpp b/Source/core/platform/chromium/support/WebMediaStream.cpp
index 43e7b79..7572def 100644
--- a/Source/core/platform/chromium/support/WebMediaStream.cpp
+++ b/Source/core/platform/chromium/support/WebMediaStream.cpp
@@ -26,10 +26,10 @@
 
 #include "public/platform/WebMediaStream.h"
 
-#include "core/platform/mediastream/MediaStreamComponent.h"
 #include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
 #include "platform/UUID.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/MediaStreamSource.h"
 #include "public/platform/WebMediaStreamSource.h"
 #include "public/platform/WebMediaStreamTrack.h"
 #include "public/platform/WebString.h"
@@ -39,7 +39,7 @@
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
 namespace {
 
@@ -158,4 +158,4 @@
     m_private = other.m_private;
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebMediaStreamSource.cpp b/Source/core/platform/chromium/support/WebMediaStreamSource.cpp
deleted file mode 100644
index a1b607b..0000000
--- a/Source/core/platform/chromium/support/WebMediaStreamSource.cpp
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * 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:
- *
- *     * 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 "public/platform/WebMediaStreamSource.h"
-
-#include "platform/audio/AudioBus.h"
-#include "core/platform/mediastream/MediaConstraints.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
-#include "public/platform/WebAudioDestinationConsumer.h"
-#include "public/platform/WebMediaConstraints.h"
-#include "public/platform/WebString.h"
-#include "wtf/MainThread.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public MediaStreamSource::ExtraData {
-public:
-    ExtraDataContainer(WebMediaStreamSource::ExtraData* extraData) : m_extraData(adoptPtr(extraData)) { }
-
-    WebMediaStreamSource::ExtraData* extraData() { return m_extraData.get(); }
-
-private:
-    OwnPtr<WebMediaStreamSource::ExtraData> m_extraData;
-};
-
-} // namespace
-
-WebMediaStreamSource WebMediaStreamSource::ExtraData::owner()
-{
-    ASSERT(m_owner);
-    return WebMediaStreamSource(m_owner);
-}
-
-void WebMediaStreamSource::ExtraData::setOwner(WebCore::MediaStreamSource* owner)
-{
-    ASSERT(!m_owner);
-    m_owner = owner;
-}
-
-WebMediaStreamSource::WebMediaStreamSource(const PassRefPtr<MediaStreamSource>& mediaStreamSource)
-    : m_private(mediaStreamSource)
-{
-}
-
-WebMediaStreamSource& WebMediaStreamSource::operator=(WebCore::MediaStreamSource* mediaStreamSource)
-{
-    m_private = mediaStreamSource;
-    return *this;
-}
-
-void WebMediaStreamSource::assign(const WebMediaStreamSource& other)
-{
-    m_private = other.m_private;
-}
-
-void WebMediaStreamSource::reset()
-{
-    m_private.reset();
-}
-
-WebMediaStreamSource::operator PassRefPtr<MediaStreamSource>() const
-{
-    return m_private.get();
-}
-
-WebMediaStreamSource::operator MediaStreamSource*() const
-{
-    return m_private.get();
-}
-
-void WebMediaStreamSource::initialize(const WebString& id, Type type, const WebString& name)
-{
-    m_private = MediaStreamSource::create(id, static_cast<MediaStreamSource::Type>(type), name);
-}
-
-WebString WebMediaStreamSource::id() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private.get()->id();
-}
-
-WebMediaStreamSource::Type WebMediaStreamSource::type() const
-{
-    ASSERT(!m_private.isNull());
-    return static_cast<Type>(m_private.get()->type());
-}
-
-WebString WebMediaStreamSource::name() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private.get()->name();
-}
-
-void WebMediaStreamSource::setReadyState(ReadyState state)
-{
-    ASSERT(!m_private.isNull());
-    m_private->setReadyState(static_cast<MediaStreamSource::ReadyState>(state));
-}
-
-WebMediaStreamSource::ReadyState WebMediaStreamSource::readyState() const
-{
-    ASSERT(!m_private.isNull());
-    return static_cast<ReadyState>(m_private->readyState());
-}
-
-WebMediaStreamSource::ExtraData* WebMediaStreamSource::extraData() const
-{
-    ASSERT(!m_private.isNull());
-    MediaStreamSource::ExtraData* data = m_private->extraData();
-    if (!data)
-        return 0;
-    return static_cast<ExtraDataContainer*>(data)->extraData();
-}
-
-void WebMediaStreamSource::setExtraData(ExtraData* extraData)
-{
-    ASSERT(!m_private.isNull());
-
-    if (extraData)
-        extraData->setOwner(m_private.get());
-
-    m_private->setExtraData(new ExtraDataContainer(extraData));
-}
-
-WebMediaConstraints WebMediaStreamSource::constraints()
-{
-    ASSERT(!m_private.isNull());
-    return m_private->constraints();
-}
-
-WebString WebMediaStreamSource::deviceId() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->deviceId();
-}
-
-void WebMediaStreamSource::setDeviceId(const WebString& deviceId)
-{
-    ASSERT(!m_private.isNull());
-    m_private->setDeviceId(deviceId);
-}
-
-bool WebMediaStreamSource::requiresAudioConsumer() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->requiresAudioConsumer();
-}
-
-class ConsumerWrapper : public WebCore::AudioDestinationConsumer {
-public:
-    static PassRefPtr<ConsumerWrapper> create(WebAudioDestinationConsumer* consumer)
-    {
-        return adoptRef(new ConsumerWrapper(consumer));
-    }
-
-    virtual void setFormat(size_t numberOfChannels, float sampleRate) OVERRIDE;
-    virtual void consumeAudio(AudioBus*, size_t numberOfFrames) OVERRIDE;
-
-    WebAudioDestinationConsumer* consumer() { return m_consumer; }
-
-private:
-    explicit ConsumerWrapper(WebAudioDestinationConsumer* consumer) : m_consumer(consumer) { }
-
-    // m_consumer is not owned by this class.
-    WebAudioDestinationConsumer* m_consumer;
-};
-
-void ConsumerWrapper::setFormat(size_t numberOfChannels, float sampleRate)
-{
-    m_consumer->setFormat(numberOfChannels, sampleRate);
-}
-
-void ConsumerWrapper::consumeAudio(AudioBus* bus, size_t numberOfFrames)
-{
-    if (!bus)
-        return;
-
-    // Wrap AudioBus.
-    size_t numberOfChannels = bus->numberOfChannels();
-    WebKit::WebVector<const float*> busVector(numberOfChannels);
-    for (size_t i = 0; i < numberOfChannels; ++i)
-        busVector[i] = bus->channel(i)->data();
-
-    m_consumer->consumeAudio(busVector, numberOfFrames);
-}
-
-void WebMediaStreamSource::addAudioConsumer(WebAudioDestinationConsumer* consumer)
-{
-    ASSERT(isMainThread());
-    ASSERT(!m_private.isNull() && consumer);
-
-    m_private->addAudioConsumer(ConsumerWrapper::create(consumer));
-}
-
-bool WebMediaStreamSource::removeAudioConsumer(WebAudioDestinationConsumer* consumer)
-{
-    ASSERT(isMainThread());
-    ASSERT(!m_private.isNull() && consumer);
-
-    const Vector<RefPtr<AudioDestinationConsumer> >& consumers = m_private->audioConsumers();
-    for (Vector<RefPtr<AudioDestinationConsumer> >::const_iterator it = consumers.begin(); it != consumers.end(); ++it) {
-        ConsumerWrapper* wrapper = static_cast<ConsumerWrapper*>((*it).get());
-        if (wrapper->consumer() == consumer) {
-            m_private->removeAudioConsumer(wrapper);
-            return true;
-        }
-    }
-    return false;
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp b/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
index c7e6721..39dabdf 100644
--- a/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
+++ b/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
@@ -26,8 +26,8 @@
 
 #include "public/platform/WebMediaStreamTrack.h"
 
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/MediaStreamSource.h"
 #include "public/platform/WebAudioSourceProvider.h"
 #include "public/platform/WebMediaStream.h"
 #include "public/platform/WebMediaStreamSource.h"
@@ -36,7 +36,7 @@
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
 namespace {
 
@@ -143,4 +143,4 @@
     m_private = other.m_private;
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp b/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
index 6a9d860..1fc0caf 100644
--- a/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
+++ b/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
@@ -36,7 +36,7 @@
 #include "wtf/RefCounted.h"
 #include "public/platform/WebString.h"
 
-namespace WebKit {
+namespace blink {
 
 class WebRTCSessionDescriptionPrivate FINAL : public RefCounted<WebRTCSessionDescriptionPrivate> {
 public:
@@ -105,5 +105,5 @@
     return m_private->setSdp(sdp);
 }
 
-} // namespace WebKit
+} // namespace blink
 
diff --git a/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp b/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
index 7575a51..b35f305 100644
--- a/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
+++ b/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
@@ -32,13 +32,13 @@
 
 #include "public/platform/WebRTCSessionDescriptionRequest.h"
 
-#include "core/platform/mediastream/RTCSessionDescriptionRequest.h"
+#include "platform/mediastream/RTCSessionDescriptionRequest.h"
 #include "public/platform/WebRTCSessionDescription.h"
 #include "wtf/PassOwnPtr.h"
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
 namespace {
 
@@ -94,5 +94,5 @@
     m_private->setExtraData(adoptRef(new ExtraDataContainer(extraData)));
 }
 
-} // namespace WebKit
+} // namespace blink
 
diff --git a/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp b/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
index c5c925a..617bd56 100644
--- a/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
+++ b/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
@@ -41,7 +41,7 @@
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
 WebRTCStatsRequest::WebRTCStatsRequest(const PassRefPtr<RTCStatsRequest>& request)
     : m_private(request)
@@ -83,4 +83,4 @@
     m_private->requestSucceeded(response);
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebRTCStatsResponse.cpp b/Source/core/platform/chromium/support/WebRTCStatsResponse.cpp
deleted file mode 100644
index 59a6191..0000000
--- a/Source/core/platform/chromium/support/WebRTCStatsResponse.cpp
+++ /dev/null
@@ -1,69 +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 INC. 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 INC. 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 "public/platform/WebRTCStatsResponse.h"
-
-#include "core/platform/mediastream/RTCStatsResponseBase.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebRTCStatsResponse::WebRTCStatsResponse(const PassRefPtr<RTCStatsResponseBase>& request)
-    : m_private(request)
-{
-}
-
-void WebRTCStatsResponse::assign(const WebRTCStatsResponse& other)
-{
-    m_private = other.m_private;
-}
-
-void WebRTCStatsResponse::reset()
-{
-    m_private.reset();
-}
-
-WebRTCStatsResponse::operator WTF::PassRefPtr<WebCore::RTCStatsResponseBase>() const
-{
-    return m_private.get();
-}
-
-size_t WebRTCStatsResponse::addReport(WebString id, WebString type, double timestamp)
-{
-    ASSERT(!m_private.isNull());
-    return m_private->addReport(id, type, timestamp);
-}
-
-void WebRTCStatsResponse::addStatistic(size_t report, WebString name, WebString value)
-{
-    ASSERT(!m_private.isNull());
-    m_private->addStatistic(report, name, value);
-}
-
-} // namespace WebKit
-
diff --git a/Source/core/platform/chromium/support/WebRTCVoidRequest.cpp b/Source/core/platform/chromium/support/WebRTCVoidRequest.cpp
deleted file mode 100644
index 0f5603b..0000000
--- a/Source/core/platform/chromium/support/WebRTCVoidRequest.cpp
+++ /dev/null
@@ -1,97 +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 "public/platform/WebRTCVoidRequest.h"
-
-#include "core/platform/mediastream/RTCVoidRequest.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public RTCVoidRequest::ExtraData {
-public:
-    ExtraDataContainer(WebRTCVoidRequest::ExtraData* extraData) : m_extraData(adoptPtr(extraData)) { }
-
-    WebRTCVoidRequest::ExtraData* extraData() { return m_extraData.get(); }
-
-private:
-    OwnPtr<WebRTCVoidRequest::ExtraData> m_extraData;
-};
-
-} // namespace
-
-WebRTCVoidRequest::WebRTCVoidRequest(const PassRefPtr<RTCVoidRequest>& constraints)
-    : m_private(constraints)
-{
-}
-
-void WebRTCVoidRequest::assign(const WebRTCVoidRequest& other)
-{
-    m_private = other.m_private;
-}
-
-void WebRTCVoidRequest::reset()
-{
-    m_private.reset();
-}
-
-void WebRTCVoidRequest::requestSucceeded() const
-{
-    ASSERT(m_private.get());
-    m_private->requestSucceeded();
-}
-
-void WebRTCVoidRequest::requestFailed(const WebString& error) const
-{
-    ASSERT(m_private.get());
-    m_private->requestFailed(error);
-}
-
-WebRTCVoidRequest::ExtraData* WebRTCVoidRequest::extraData() const
-{
-    RefPtr<RTCVoidRequest::ExtraData> data = m_private->extraData();
-    if (!data)
-        return 0;
-    return static_cast<ExtraDataContainer*>(data.get())->extraData();
-}
-
-void WebRTCVoidRequest::setExtraData(ExtraData* extraData)
-{
-    m_private->setExtraData(adoptRef(new ExtraDataContainer(extraData)));
-}
-
-} // namespace WebKit
-
diff --git a/Source/core/platform/chromium/support/WebScrollbarImpl.cpp b/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
index 53b0d49..b8a9106 100644
--- a/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
+++ b/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
@@ -29,7 +29,7 @@
 #include "core/platform/Scrollbar.h"
 #include "platform/geometry/IntRect.h"
 
-namespace WebKit {
+namespace blink {
 
 WebScrollbarImpl::WebScrollbarImpl(WebCore::Scrollbar* scrollbar)
     : m_scrollbar(scrollbar)
@@ -138,4 +138,4 @@
     m_scrollbar->setIsAlphaLocked(flag);
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebScrollbarImpl.h b/Source/core/platform/chromium/support/WebScrollbarImpl.h
index e5459de..2be73d5 100644
--- a/Source/core/platform/chromium/support/WebScrollbarImpl.h
+++ b/Source/core/platform/chromium/support/WebScrollbarImpl.h
@@ -31,13 +31,13 @@
 class Scrollbar;
 }
 
-namespace WebKit {
+namespace blink {
 
 class WebScrollbarImpl : public WebScrollbar {
 public:
     explicit WebScrollbarImpl(WebCore::Scrollbar*);
 
-    // Implement WebKit::WebScrollbar methods
+    // Implement blink::WebScrollbar methods
     virtual bool isOverlay() const OVERRIDE;
     virtual int value() const OVERRIDE;
     virtual WebPoint location() const OVERRIDE;
@@ -62,6 +62,6 @@
     RefPtr<WebCore::Scrollbar> m_scrollbar;
 };
 
-} // namespace WebKit
+} // namespace blink
 
 #endif
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
index 333a564..f75ebe2 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
@@ -28,7 +28,7 @@
 #include "core/platform/chromium/support/WebScrollbarThemeClientImpl.h"
 #include "core/platform/ScrollbarTheme.h"
 
-using WebKit::WebScrollbar;
+using blink::WebScrollbar;
 
 namespace WebCore {
 
@@ -117,7 +117,7 @@
 
 void WebScrollbarThemeClientImpl::getTickmarks(Vector<IntRect>& tickmarks) const
 {
-    WebKit::WebVector<WebKit::WebRect> webTickmarks;
+    blink::WebVector<blink::WebRect> webTickmarks;
     m_scrollbar->getTickmarks(webTickmarks);
     tickmarks.resize(webTickmarks.size());
     for (size_t i = 0; i < webTickmarks.size(); ++i)
@@ -228,4 +228,4 @@
     m_scrollbar->setIsAlphaLocked(flag);
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
index 30e7738..976a6bd 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
@@ -39,7 +39,7 @@
 public:
     // Caller must retain ownership of this pointer and ensure that its lifetime
     // exceeds this instance.
-    WebScrollbarThemeClientImpl(WebKit::WebScrollbar*);
+    WebScrollbarThemeClientImpl(blink::WebScrollbar*);
     ~WebScrollbarThemeClientImpl();
 
     // Implement ScrollbarThemeClient interface
@@ -79,7 +79,7 @@
     virtual void setIsAlphaLocked(bool) OVERRIDE;
 
 private:
-    WebKit::WebScrollbar* m_scrollbar;
+    blink::WebScrollbar* m_scrollbar;
 };
 
 }
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
index 849732a..93def68 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
@@ -33,9 +33,9 @@
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
-PassOwnPtr<WebKit::WebScrollbarThemeGeometryNative> WebScrollbarThemeGeometryNative::create(WebCore::ScrollbarTheme* theme)
+PassOwnPtr<blink::WebScrollbarThemeGeometryNative> WebScrollbarThemeGeometryNative::create(WebCore::ScrollbarTheme* theme)
 {
     return adoptPtr(new WebScrollbarThemeGeometryNative(theme));
 }
@@ -154,4 +154,4 @@
     webEndTrack = endTrack;
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
index bd46129..d24ac7e 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
@@ -34,7 +34,7 @@
 class ScrollbarTheme;
 }
 
-namespace WebKit {
+namespace blink {
 
 class WebScrollbar;
 
@@ -70,6 +70,6 @@
     WebCore::ScrollbarTheme* m_theme;
 };
 
-} // namespace WebKit
+} // namespace blink
 
 #endif
diff --git a/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp b/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp
index 9a511a2..9a2cbe7 100644
--- a/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp
+++ b/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp
@@ -33,7 +33,7 @@
 
 using namespace WebCore;
 
-namespace WebKit {
+namespace blink {
 
 WebSpeechSynthesisUtterance::WebSpeechSynthesisUtterance(const PassRefPtr<PlatformSpeechSynthesisUtterance>& utterance)
     : m_private(utterance)
@@ -101,4 +101,4 @@
     return m_private->startTime();
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp b/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp
index 1fcbd29..c229140 100644
--- a/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp
+++ b/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp
@@ -31,7 +31,7 @@
 #include "wtf/PassRefPtr.h"
 #include "wtf/Vector.h"
 
-namespace WebKit {
+namespace blink {
 
 WebSpeechSynthesisVoice::WebSpeechSynthesisVoice()
     : m_private(WebCore::PlatformSpeechSynthesisVoice::create())
@@ -78,4 +78,4 @@
     return m_private.get();
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp b/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp
index 0b49a2f..d8e2a27 100644
--- a/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp
+++ b/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp
@@ -40,7 +40,7 @@
 {
 }
 
-void WebSpeechSynthesizerClientImpl::setVoiceList(const WebKit::WebVector<WebKit::WebSpeechSynthesisVoice>& voices)
+void WebSpeechSynthesizerClientImpl::setVoiceList(const blink::WebVector<blink::WebSpeechSynthesisVoice>& voices)
 {
     Vector<RefPtr<PlatformSpeechSynthesisVoice> > outVoices;
     for (size_t i = 0; i < voices.size(); i++)
@@ -49,37 +49,37 @@
     m_client->voicesDidChange();
 }
 
-void WebSpeechSynthesizerClientImpl::didStartSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
+void WebSpeechSynthesizerClientImpl::didStartSpeaking(const blink::WebSpeechSynthesisUtterance& utterance)
 {
     m_client->didStartSpeaking(utterance);
 }
 
-void WebSpeechSynthesizerClientImpl::didFinishSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
+void WebSpeechSynthesizerClientImpl::didFinishSpeaking(const blink::WebSpeechSynthesisUtterance& utterance)
 {
     m_client->didFinishSpeaking(utterance);
 }
 
-void WebSpeechSynthesizerClientImpl::didPauseSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
+void WebSpeechSynthesizerClientImpl::didPauseSpeaking(const blink::WebSpeechSynthesisUtterance& utterance)
 {
     m_client->didPauseSpeaking(utterance);
 }
 
-void WebSpeechSynthesizerClientImpl::didResumeSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
+void WebSpeechSynthesizerClientImpl::didResumeSpeaking(const blink::WebSpeechSynthesisUtterance& utterance)
 {
     m_client->didResumeSpeaking(utterance);
 }
 
-void WebSpeechSynthesizerClientImpl::speakingErrorOccurred(const WebKit::WebSpeechSynthesisUtterance& utterance)
+void WebSpeechSynthesizerClientImpl::speakingErrorOccurred(const blink::WebSpeechSynthesisUtterance& utterance)
 {
     m_client->speakingErrorOccurred(utterance);
 }
 
-void WebSpeechSynthesizerClientImpl::wordBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance& utterance, unsigned charIndex)
+void WebSpeechSynthesizerClientImpl::wordBoundaryEventOccurred(const blink::WebSpeechSynthesisUtterance& utterance, unsigned charIndex)
 {
     m_client->boundaryEventOccurred(utterance, SpeechWordBoundary, charIndex);
 }
 
-void WebSpeechSynthesizerClientImpl::sentenceBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance& utterance, unsigned charIndex)
+void WebSpeechSynthesizerClientImpl::sentenceBoundaryEventOccurred(const blink::WebSpeechSynthesisUtterance& utterance, unsigned charIndex)
 {
     m_client->boundaryEventOccurred(utterance, SpeechSentenceBoundary, charIndex);
 }
diff --git a/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h b/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h
index 91681a1..f70c2d2 100644
--- a/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h
+++ b/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h
@@ -38,19 +38,19 @@
 class PlatformSpeechSynthesizer;
 class PlatformSpeechSynthesizerClient;
 
-class WebSpeechSynthesizerClientImpl : public WebKit::WebSpeechSynthesizerClient {
+class WebSpeechSynthesizerClientImpl : public blink::WebSpeechSynthesizerClient {
 public:
     explicit WebSpeechSynthesizerClientImpl(PlatformSpeechSynthesizer*, PlatformSpeechSynthesizerClient*);
     virtual ~WebSpeechSynthesizerClientImpl();
 
-    virtual void setVoiceList(const WebKit::WebVector<WebKit::WebSpeechSynthesisVoice>& voices);
-    virtual void didStartSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
-    virtual void didFinishSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
-    virtual void didPauseSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
-    virtual void didResumeSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
-    virtual void speakingErrorOccurred(const WebKit::WebSpeechSynthesisUtterance&);
-    virtual void wordBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance&, unsigned charIndex);
-    virtual void sentenceBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance&, unsigned charIndex);
+    virtual void setVoiceList(const blink::WebVector<blink::WebSpeechSynthesisVoice>& voices);
+    virtual void didStartSpeaking(const blink::WebSpeechSynthesisUtterance&);
+    virtual void didFinishSpeaking(const blink::WebSpeechSynthesisUtterance&);
+    virtual void didPauseSpeaking(const blink::WebSpeechSynthesisUtterance&);
+    virtual void didResumeSpeaking(const blink::WebSpeechSynthesisUtterance&);
+    virtual void speakingErrorOccurred(const blink::WebSpeechSynthesisUtterance&);
+    virtual void wordBoundaryEventOccurred(const blink::WebSpeechSynthesisUtterance&, unsigned charIndex);
+    virtual void sentenceBoundaryEventOccurred(const blink::WebSpeechSynthesisUtterance&, unsigned charIndex);
 
 private:
     PlatformSpeechSynthesizer* m_synthesizer;
diff --git a/Source/core/platform/graphics/BitmapImage.cpp b/Source/core/platform/graphics/BitmapImage.cpp
index 10f6be4..650a140 100644
--- a/Source/core/platform/graphics/BitmapImage.cpp
+++ b/Source/core/platform/graphics/BitmapImage.cpp
@@ -28,11 +28,11 @@
 #include "core/platform/graphics/BitmapImage.h"
 
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/ImageObserver.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
 #include "core/platform/graphics/skia/SkiaUtils.h"
 #include "platform/Timer.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/graphics/ImageObserver.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/Vector.h"
diff --git a/Source/core/platform/graphics/BitmapImageTest.cpp b/Source/core/platform/graphics/BitmapImageTest.cpp
index b5c9b2c..402554d 100644
--- a/Source/core/platform/graphics/BitmapImageTest.cpp
+++ b/Source/core/platform/graphics/BitmapImageTest.cpp
@@ -32,7 +32,7 @@
 #include "core/platform/graphics/BitmapImage.h"
 
 #include "platform/SharedBuffer.h"
-#include "core/platform/graphics/ImageObserver.h"
+#include "platform/graphics/ImageObserver.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebUnitTestSupport.h"
 
@@ -60,9 +60,9 @@
 
     static PassRefPtr<SharedBuffer> readFile(const char* fileName)
     {
-        String filePath = WebKit::Platform::current()->unitTestSupport()->webKitRootDir();
+        String filePath = blink::Platform::current()->unitTestSupport()->webKitRootDir();
         filePath.append(fileName);
-        return WebKit::Platform::current()->unitTestSupport()->readFromFile(filePath);
+        return blink::Platform::current()->unitTestSupport()->readFromFile(filePath);
     }
 
     // Accessors to BitmapImage's protected methods.
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp b/Source/core/platform/graphics/Canvas2DLayerBridge.cpp
similarity index 95%
rename from Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
rename to Source/core/platform/graphics/Canvas2DLayerBridge.cpp
index a388ac3..52caea6 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
+++ b/Source/core/platform/graphics/Canvas2DLayerBridge.cpp
@@ -25,22 +25,22 @@
 
 #include "config.h"
 
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
+#include "core/platform/graphics/Canvas2DLayerBridge.h"
 
 #include "GrContext.h"
 #include "SkDevice.h"
 #include "SkSurface.h"
+#include "core/platform/graphics/Canvas2DLayerManager.h"
 #include "core/platform/graphics/GraphicsContext3D.h"
 #include "core/platform/graphics/GraphicsLayer.h"
-#include "core/platform/graphics/chromium/Canvas2DLayerManager.h"
 #include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
 #include "platform/TraceEvent.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebCompositorSupport.h"
 #include "public/platform/WebGraphicsContext3D.h"
 
-using WebKit::WebExternalTextureLayer;
-using WebKit::WebGraphicsContext3D;
+using blink::WebExternalTextureLayer;
+using blink::WebGraphicsContext3D;
 
 namespace WebCore {
 
@@ -66,10 +66,10 @@
     if (!gr)
         return 0;
     gr->resetContext();
-    SkImage::Info info;
+    SkImageInfo info;
     info.fWidth = size.width();
     info.fHeight = size.height();
-    info.fColorType = SkImage::kPMColor_ColorType;
+    info.fColorType = kPMColor_SkColorType;
     info.fAlphaType = kPremul_SkAlphaType;
     return SkSurface::NewRenderTarget(gr, info,  msaaSampleCount);
 }
@@ -103,7 +103,7 @@
     ASSERT(m_canvas);
     // Used by browser tests to detect the use of a Canvas2DLayerBridge.
     TRACE_EVENT_INSTANT0("test_gpu", "Canvas2DLayerBridgeCreation");
-    m_layer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createExternalTextureLayer(this));
+    m_layer = adoptPtr(blink::Platform::current()->compositorSupport()->createExternalTextureLayer(this));
     m_layer->setOpaque(opacityMode == Opaque);
     m_layer->setBlendBackgroundColor(opacityMode != Opaque);
     GraphicsLayer::registerContentsLayer(m_layer->layer());
@@ -275,7 +275,7 @@
     return m_surfaceIsValid;
 }
 
-bool Canvas2DLayerBridge::prepareMailbox(WebKit::WebExternalTextureMailbox* outMailbox, WebKit::WebExternalBitmap* bitmap)
+bool Canvas2DLayerBridge::prepareMailbox(blink::WebExternalTextureMailbox* outMailbox, blink::WebExternalBitmap* bitmap)
 {
     if (bitmap) {
         // Using accelerated 2d canvas with software renderer, which
@@ -368,7 +368,7 @@
     return mailboxInfo;
 }
 
-void Canvas2DLayerBridge::mailboxReleased(const WebKit::WebExternalTextureMailbox& mailbox)
+void Canvas2DLayerBridge::mailboxReleased(const blink::WebExternalTextureMailbox& mailbox)
 {
     Vector<MailboxInfo>::iterator mailboxInfo;
     for (mailboxInfo = m_mailboxes.begin(); mailboxInfo < m_mailboxes.end(); mailboxInfo++) {
@@ -386,7 +386,7 @@
     }
 }
 
-WebKit::WebLayer* Canvas2DLayerBridge::layer()
+blink::WebLayer* Canvas2DLayerBridge::layer()
 {
     ASSERT(m_layer);
     return m_layer->layer();
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h b/Source/core/platform/graphics/Canvas2DLayerBridge.h
similarity index 87%
rename from Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
rename to Source/core/platform/graphics/Canvas2DLayerBridge.h
index 47cd689..9cc2664 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
+++ b/Source/core/platform/graphics/Canvas2DLayerBridge.h
@@ -37,7 +37,7 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefPtr.h"
 
-namespace WebKit {
+namespace blink {
 class WebGraphicsContext3D;
 }
 
@@ -61,7 +61,7 @@
     RefPtr<Canvas2DLayerBridge> m_ptr;
 };
 
-class Canvas2DLayerBridge : public WebKit::WebExternalTextureLayerClient, public SkDeferredCanvas::NotificationClient, public DoublyLinkedListNode<Canvas2DLayerBridge>, public RefCounted<Canvas2DLayerBridge> {
+class Canvas2DLayerBridge : public blink::WebExternalTextureLayerClient, public SkDeferredCanvas::NotificationClient, public DoublyLinkedListNode<Canvas2DLayerBridge>, public RefCounted<Canvas2DLayerBridge> {
     WTF_MAKE_NONCOPYABLE(Canvas2DLayerBridge);
 public:
     enum OpacityMode {
@@ -73,10 +73,10 @@
 
     virtual ~Canvas2DLayerBridge();
 
-    // WebKit::WebExternalTextureLayerClient implementation.
-    virtual WebKit::WebGraphicsContext3D* context() OVERRIDE;
-    virtual bool prepareMailbox(WebKit::WebExternalTextureMailbox*, WebKit::WebExternalBitmap*) OVERRIDE;
-    virtual void mailboxReleased(const WebKit::WebExternalTextureMailbox&) OVERRIDE;
+    // blink::WebExternalTextureLayerClient implementation.
+    virtual blink::WebGraphicsContext3D* context() OVERRIDE;
+    virtual bool prepareMailbox(blink::WebExternalTextureMailbox*, blink::WebExternalBitmap*) OVERRIDE;
+    virtual void mailboxReleased(const blink::WebExternalTextureMailbox&) OVERRIDE;
 
     // SkDeferredCanvas::NotificationClient implementation
     virtual void prepareForDraw() OVERRIDE;
@@ -91,7 +91,7 @@
     size_t bytesAllocated() const {return m_bytesAllocated;}
     void limitPendingFrames();
 
-    WebKit::WebLayer* layer();
+    blink::WebLayer* layer();
     void contextAcquired();
     PassRefPtr<SkCanvas> getCanvas() { return PassRefPtr<SkCanvas>(m_canvas); }
 
@@ -106,7 +106,7 @@
     void setRateLimitingEnabled(bool);
 
     RefPtr<SkDeferredCanvas> m_canvas;
-    OwnPtr<WebKit::WebExternalTextureLayer> m_layer;
+    OwnPtr<blink::WebExternalTextureLayer> m_layer;
     RefPtr<GraphicsContext3D> m_context;
     int m_msaaSampleCount;
     size_t m_bytesAllocated;
@@ -127,7 +127,7 @@
     };
 
     struct MailboxInfo {
-        WebKit::WebExternalTextureMailbox m_mailbox;
+        blink::WebExternalTextureMailbox m_mailbox;
         SkAutoTUnref<SkImage> m_image;
         MailboxStatus m_status;
         RefPtr<Canvas2DLayerBridge> m_parentLayerBridge;
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp b/Source/core/platform/graphics/Canvas2DLayerBridgeTest.cpp
similarity index 97%
rename from Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
rename to Source/core/platform/graphics/Canvas2DLayerBridgeTest.cpp
index 6692672..391808a 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
+++ b/Source/core/platform/graphics/Canvas2DLayerBridgeTest.cpp
@@ -24,7 +24,7 @@
 
 #include "config.h"
 
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
+#include "core/platform/graphics/Canvas2DLayerBridge.h"
 
 #include "SkDeferredCanvas.h"
 #include "SkSurface.h"
@@ -39,7 +39,7 @@
 #include <gtest/gtest.h>
 
 using namespace WebCore;
-using namespace WebKit;
+using namespace blink;
 using testing::InSequence;
 using testing::Return;
 using testing::Test;
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp b/Source/core/platform/graphics/Canvas2DLayerManager.cpp
similarity index 93%
rename from Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp
rename to Source/core/platform/graphics/Canvas2DLayerManager.cpp
index ed38bd3..d8af5fe 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp
+++ b/Source/core/platform/graphics/Canvas2DLayerManager.cpp
@@ -23,12 +23,12 @@
 */
 #include "config.h"
 
-#include "core/platform/graphics/chromium/Canvas2DLayerManager.h"
+#include "core/platform/graphics/Canvas2DLayerManager.h"
 
 #include "public/platform/Platform.h"
 #include "wtf/StdLibExtras.h"
 
-using WebKit::WebThread;
+using blink::WebThread;
 
 namespace {
 enum {
@@ -60,7 +60,7 @@
     m_maxBytesAllocated = maxBytesAllocated;
     m_targetBytesAllocated = targetBytesAllocated;
     if (m_taskObserverActive) {
-        WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
+        blink::Platform::current()->currentThread()->removeTaskObserver(this);
         m_taskObserverActive = false;
     }
 }
@@ -79,7 +79,7 @@
 {
     // Called after the script action for the current frame has been processed.
     ASSERT(m_taskObserverActive);
-    WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
+    blink::Platform::current()->currentThread()->removeTaskObserver(this);
     m_taskObserverActive = false;
     for (Canvas2DLayerBridge* layer = m_layerList.head(); layer; layer = layer->next())
         layer->limitPendingFrames();
@@ -98,7 +98,7 @@
     if (!m_taskObserverActive) {
         m_taskObserverActive = true;
         // Schedule a call to didProcessTask() after completion of the current script task.
-        WebKit::Platform::current()->currentThread()->addTaskObserver(this);
+        blink::Platform::current()->currentThread()->addTaskObserver(this);
     }
 }
 
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerManager.h b/Source/core/platform/graphics/Canvas2DLayerManager.h
similarity index 94%
rename from Source/core/platform/graphics/chromium/Canvas2DLayerManager.h
rename to Source/core/platform/graphics/Canvas2DLayerManager.h
index 3379cec..551bfa6 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerManager.h
+++ b/Source/core/platform/graphics/Canvas2DLayerManager.h
@@ -25,14 +25,14 @@
 #ifndef Canvas2DLayerManager_h
 #define Canvas2DLayerManager_h
 
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
+#include "core/platform/graphics/Canvas2DLayerBridge.h"
 #include "public/platform/WebThread.h"
 
 class Canvas2DLayerManagerTest;
 
 namespace WebCore {
 
-class Canvas2DLayerManager : public WebKit::WebThread::TaskObserver {
+class Canvas2DLayerManager : public blink::WebThread::TaskObserver {
 public:
     static Canvas2DLayerManager& get();
     void init(size_t maxBytesAllocated, size_t targetBytesAllocated);
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp b/Source/core/platform/graphics/Canvas2DLayerManagerTest.cpp
similarity index 86%
rename from Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
rename to Source/core/platform/graphics/Canvas2DLayerManagerTest.cpp
index c6d7398..1d38674 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
+++ b/Source/core/platform/graphics/Canvas2DLayerManagerTest.cpp
@@ -24,7 +24,7 @@
 
 #include "config.h"
 
-#include "core/platform/graphics/chromium/Canvas2DLayerManager.h"
+#include "core/platform/graphics/Canvas2DLayerManager.h"
 
 #include "SkDevice.h"
 #include "SkSurface.h"
@@ -106,7 +106,7 @@
         Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
         manager.init(10, 10);
         {
-            RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
+            RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new blink::FakeWebGraphicsContext3D));
             RefPtr<SkDeferredCanvas> canvas1(createCanvas(context.get()));
             Canvas2DLayerBridgePtr layer1(adoptRef(new FakeCanvas2DLayerBridge(context, canvas1.release())));
             EXPECT_EQ((size_t)0, manager.m_bytesAllocated);
@@ -133,7 +133,7 @@
 
     void evictionTest()
     {
-        RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
+        RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new blink::FakeWebGraphicsContext3D));
         Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
         manager.init(10, 5);
         RefPtr<SkDeferredCanvas> canvas(createCanvas(context.get()));
@@ -150,7 +150,7 @@
 
     void flushEvictionTest()
     {
-        RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
+        RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new blink::FakeWebGraphicsContext3D));
         Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
         manager.init(10, 5);
         RefPtr<SkDeferredCanvas> canvas(createCanvas(context.get()));
@@ -177,10 +177,10 @@
             layer->storageAllocatedForRecordingChanged(0);
             layer->skippedPendingDrawCommands();
         }
-        WebKit::Platform::current()->currentThread()->exitRunLoop();
+        blink::Platform::current()->currentThread()->exitRunLoop();
     }
 
-    class DeferredFrameTestTask : public WebKit::WebThread::Task {
+    class DeferredFrameTestTask : public blink::WebThread::Task {
     public:
         DeferredFrameTestTask(Canvas2DLayerManagerTest* test, FakeCanvas2DLayerBridge* layer, bool skipCommands)
         {
@@ -201,36 +201,36 @@
 
     void deferredFrameTest()
     {
-        RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
+        RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new blink::FakeWebGraphicsContext3D));
         Canvas2DLayerManager::get().init(10, 10);
         RefPtr<SkDeferredCanvas> canvas(createCanvas(context.get()));
         Canvas2DLayerBridgePtr layer(adoptRef(new FakeCanvas2DLayerBridge(context, canvas.release())));
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
-        WebKit::Platform::current()->currentThread()->enterRunLoop();
+        blink::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
+        blink::Platform::current()->currentThread()->enterRunLoop();
         // Verify that didProcessTask was called upon completion
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
         // Verify that no flush was performed because frame is fresh
         EXPECT_EQ(0, fake(layer)->m_flushCount);
 
         // Verify that no flushes are triggered as long as frame are fresh
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
-        WebKit::Platform::current()->currentThread()->enterRunLoop();
+        blink::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
+        blink::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
         EXPECT_EQ(0, fake(layer)->m_flushCount);
 
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
-        WebKit::Platform::current()->currentThread()->enterRunLoop();
+        blink::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
+        blink::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
         EXPECT_EQ(0, fake(layer)->m_flushCount);
 
         // Verify that a flush is triggered when queue is accumulating a multi-frame backlog.
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
-        WebKit::Platform::current()->currentThread()->enterRunLoop();
+        blink::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
+        blink::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
         EXPECT_EQ(1, fake(layer)->m_flushCount);
 
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
-        WebKit::Platform::current()->currentThread()->enterRunLoop();
+        blink::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
+        blink::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
         EXPECT_EQ(2, fake(layer)->m_flushCount);
     }
diff --git a/Source/core/platform/graphics/CrossfadeGeneratedImage.h b/Source/core/platform/graphics/CrossfadeGeneratedImage.h
index 372461d..d68c2b8 100644
--- a/Source/core/platform/graphics/CrossfadeGeneratedImage.h
+++ b/Source/core/platform/graphics/CrossfadeGeneratedImage.h
@@ -28,8 +28,8 @@
 
 #include "core/platform/graphics/GeneratedImage.h"
 #include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageObserver.h"
 #include "platform/geometry/IntSize.h"
+#include "platform/graphics/ImageObserver.h"
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/graphics/CustomFontData.h b/Source/core/platform/graphics/CustomFontData.h
new file mode 100644
index 0000000..65a3d26
--- /dev/null
+++ b/Source/core/platform/graphics/CustomFontData.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2013 Google, Inc.
+ *
+ * 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.
+ *
+ */
+
+#ifndef CustomFontData_h
+#define CustomFontData_h
+
+#include "platform/fonts/Glyph.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include <unicode/uchar.h>
+
+namespace WebCore {
+
+class CSSFontFaceSource;
+struct GlyphData;
+class GlyphPage;
+class SimpleFontData;
+struct WidthIterator;
+
+class CustomFontData : public RefCounted<CustomFontData> {
+public:
+    static PassRefPtr<CustomFontData> create(bool isLoadingFallback = false)
+    {
+        return adoptRef(new CustomFontData(isLoadingFallback));
+    }
+
+    virtual ~CustomFontData() { }
+
+    virtual void beginLoadIfNeeded() const { };
+    bool isLoading() const { return m_isLoadingFallback && m_isUsed; }
+    bool isLoadingFallback() const { return m_isLoadingFallback; }
+
+    virtual bool isSVGFont() const { return false; }
+    virtual void initializeFontData(SimpleFontData*, float) { }
+    virtual float widthForSVGGlyph(Glyph, float) const { return 0.0f; }
+    virtual bool fillSVGGlyphPage(GlyphPage*, unsigned, unsigned, UChar*, unsigned, const SimpleFontData*) const { return false; }
+    virtual bool applySVGGlyphSelection(WidthIterator&, GlyphData&, bool, int, unsigned&) const { return false; }
+
+    virtual void setCSSFontFaceSource(CSSFontFaceSource* source) { ASSERT_NOT_REACHED(); }
+    virtual void clearCSSFontFaceSource() { }
+
+protected:
+    CustomFontData(bool isLoadingFallback)
+        : m_isLoadingFallback(isLoadingFallback)
+        , m_isUsed(false)
+    {
+    }
+
+    bool m_isLoadingFallback; // Whether or not this is a temporary font data for a custom font which is not yet loaded.
+    mutable bool m_isUsed;
+};
+
+}
+
+#endif // CustomFontData_h
diff --git a/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp b/Source/core/platform/graphics/DeferredImageDecoder.cpp
similarity index 85%
rename from Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp
rename to Source/core/platform/graphics/DeferredImageDecoder.cpp
index 1d45560..cb030e5 100644
--- a/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp
+++ b/Source/core/platform/graphics/DeferredImageDecoder.cpp
@@ -24,10 +24,10 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
+#include "core/platform/graphics/DeferredImageDecoder.h"
 
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
-#include "core/platform/graphics/chromium/LazyDecodingPixelRef.h"
+#include "core/platform/graphics/ImageFrameGenerator.h"
+#include "core/platform/graphics/LazyDecodingPixelRef.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -72,26 +72,6 @@
         && !memcmp(bitmap.pixelRef()->getURI(), labelLazyDecoded, sizeof(labelLazyDecoded));
 }
 
-SkBitmap DeferredImageDecoder::createResizedLazyDecodingBitmap(const SkBitmap& bitmap, const SkISize& scaledSize, const SkIRect& scaledSubset)
-{
-    LazyDecodingPixelRef* pixelRef = static_cast<LazyDecodingPixelRef*>(bitmap.pixelRef());
-
-    int rowBytes = 0;
-    rowBytes = SkBitmap::ComputeRowBytes(SkBitmap::kARGB_8888_Config, scaledSize.width());
-
-    SkBitmap resizedBitmap;
-    resizedBitmap.setConfig(SkBitmap::kARGB_8888_Config, scaledSubset.width(), scaledSubset.height(), rowBytes);
-
-    // FIXME: This code has the potential problem that multiple
-    // LazyDecodingPixelRefs are created even though they share the same
-    // scaled size and ImageFrameGenerator.
-    resizedBitmap.setPixelRef(new LazyDecodingPixelRef(pixelRef->frameGenerator(), scaledSize, pixelRef->frameIndex(), scaledSubset))->unref();
-
-    // See comments in createLazyDecodingBitmap().
-    resizedBitmap.setImmutable();
-    return resizedBitmap;
-}
-
 void DeferredImageDecoder::setEnabled(bool enabled)
 {
     s_enabled = enabled;
@@ -249,15 +229,14 @@
 
 SkBitmap DeferredImageDecoder::createLazyDecodingBitmap(size_t index)
 {
-    SkISize fullSize = SkISize::Make(m_actualDecoder->decodedSize().width(), m_actualDecoder->decodedSize().height());
-    ASSERT(!fullSize.isEmpty());
-
-    SkIRect fullRect = SkIRect::MakeSize(fullSize);
+    IntSize decodedSize = m_actualDecoder->decodedSize();
+    ASSERT(decodedSize.width() > 0);
+    ASSERT(decodedSize.height() > 0);
 
     // Creates a lazily decoded SkPixelRef that references the entire image without scaling.
     SkBitmap bitmap;
-    bitmap.setConfig(SkBitmap::kARGB_8888_Config, fullSize.width(), fullSize.height());
-    bitmap.setPixelRef(new LazyDecodingPixelRef(m_frameGenerator, fullSize, index, fullRect))->unref();
+    bitmap.setConfig(SkBitmap::kARGB_8888_Config, decodedSize.width(), decodedSize.height());
+    bitmap.setPixelRef(new LazyDecodingPixelRef(m_frameGenerator, index))->unref();
 
     // Use the URI to identify this as a lazily decoded SkPixelRef of type LazyDecodingPixelRef.
     // FIXME: It would be more useful to give the actual image URI.
diff --git a/Source/core/platform/graphics/chromium/DeferredImageDecoder.h b/Source/core/platform/graphics/DeferredImageDecoder.h
similarity index 96%
rename from Source/core/platform/graphics/chromium/DeferredImageDecoder.h
rename to Source/core/platform/graphics/DeferredImageDecoder.h
index 521ad80..4f5f549 100644
--- a/Source/core/platform/graphics/chromium/DeferredImageDecoder.h
+++ b/Source/core/platform/graphics/DeferredImageDecoder.h
@@ -48,8 +48,6 @@
 
     static bool isLazyDecoded(const SkBitmap&);
 
-    static SkBitmap createResizedLazyDecodingBitmap(const SkBitmap&, const SkISize& scaledSize, const SkIRect& scaledSubset);
-
     static void setEnabled(bool);
 
     String filenameExtension() const;
diff --git a/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp b/Source/core/platform/graphics/DeferredImageDecoderTest.cpp
similarity index 97%
rename from Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp
rename to Source/core/platform/graphics/DeferredImageDecoderTest.cpp
index 0bd09eb..b495d5b 100644
--- a/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp
+++ b/Source/core/platform/graphics/DeferredImageDecoderTest.cpp
@@ -24,13 +24,13 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
+#include "core/platform/graphics/DeferredImageDecoder.h"
 
 #include "SkBitmapDevice.h"
 #include "SkCanvas.h"
 #include "SkPicture.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-#include "core/platform/graphics/chromium/test/MockImageDecoder.h"
+#include "core/platform/graphics/ImageDecodingStore.h"
+#include "core/platform/graphics/test/MockImageDecoder.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
 #include "platform/SharedBuffer.h"
 #include "platform/Task.h"
@@ -223,7 +223,7 @@
     EXPECT_EQ(0, m_frameBufferRequestCount);
 
     // Create a thread to rasterize SkPicture.
-    OwnPtr<WebKit::WebThread> thread = adoptPtr(WebKit::Platform::current()->createThread("RasterThread"));
+    OwnPtr<blink::WebThread> thread = adoptPtr(blink::Platform::current()->createThread("RasterThread"));
     thread->postTask(new Task(WTF::bind(&rasterizeMain, m_canvas.get(), &m_picture)));
     thread.clear();
     EXPECT_EQ(0, m_frameBufferRequestCount);
diff --git a/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp b/Source/core/platform/graphics/DiscardablePixelRef.cpp
similarity index 95%
rename from Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp
rename to Source/core/platform/graphics/DiscardablePixelRef.cpp
index eb1fd65..117e770 100644
--- a/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp
+++ b/Source/core/platform/graphics/DiscardablePixelRef.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/DiscardablePixelRef.h"
+#include "core/platform/graphics/DiscardablePixelRef.h"
 
 #include "public/platform/Platform.h"
 #include "wtf/StdLibExtras.h"
@@ -77,7 +77,7 @@
 
 bool DiscardablePixelRef::allocAndLockDiscardableMemory(size_t bytes)
 {
-    m_discardable = adoptPtr(WebKit::Platform::current()->allocateAndLockDiscardableMemory(bytes));
+    m_discardable = adoptPtr(blink::Platform::current()->allocateAndLockDiscardableMemory(bytes));
     if (m_discardable) {
         m_lockedMemory = m_discardable->data();
         return true;
diff --git a/Source/core/platform/graphics/chromium/DiscardablePixelRef.h b/Source/core/platform/graphics/DiscardablePixelRef.h
similarity index 97%
rename from Source/core/platform/graphics/chromium/DiscardablePixelRef.h
rename to Source/core/platform/graphics/DiscardablePixelRef.h
index 28449b3..0c6a639 100644
--- a/Source/core/platform/graphics/chromium/DiscardablePixelRef.h
+++ b/Source/core/platform/graphics/DiscardablePixelRef.h
@@ -61,7 +61,7 @@
 
 private:
     void* m_lockedMemory;
-    OwnPtr<WebKit::WebDiscardableMemory> m_discardable;
+    OwnPtr<blink::WebDiscardableMemory> m_discardable;
     OwnPtr<SkMutex> m_mutex;
 };
 
diff --git a/Source/core/platform/graphics/Font.cpp b/Source/core/platform/graphics/Font.cpp
index 3ba67d9..ee37bb9 100644
--- a/Source/core/platform/graphics/Font.cpp
+++ b/Source/core/platform/graphics/Font.cpp
@@ -247,8 +247,9 @@
 
 #if !OS(MACOSX)
 
-PassOwnPtr<TextLayout> Font::createLayout(RenderText*, float, bool) const
+PassOwnPtr<TextLayout> Font::createLayoutForMacComplexText(const TextRun&, unsigned, float, bool) const
 {
+    ASSERT_NOT_REACHED();
     return nullptr;
 }
 
diff --git a/Source/core/platform/graphics/Font.h b/Source/core/platform/graphics/Font.h
index f353f81..eef5788 100644
--- a/Source/core/platform/graphics/Font.h
+++ b/Source/core/platform/graphics/Font.h
@@ -51,7 +51,6 @@
 class FontSelector;
 class GlyphBuffer;
 class GraphicsContext;
-class RenderText;
 class TextLayout;
 class TextRun;
 struct TextRunPaintInfo;
@@ -104,7 +103,7 @@
     float width(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
     float width(const TextRun&, int& charsConsumed, String& glyphName) const;
 
-    PassOwnPtr<TextLayout> createLayout(RenderText*, float xPos, bool collapseWhiteSpace) const;
+    PassOwnPtr<TextLayout> createLayoutForMacComplexText(const TextRun&, unsigned textLength, float xPos, bool collapseWhiteSpace) const;
     static void deleteLayout(TextLayout*);
     static float width(TextLayout&, unsigned from, unsigned len, HashSet<const SimpleFontData*>* fallbackFonts = 0);
 
@@ -174,7 +173,7 @@
     float getGlyphsAndAdvancesForSimpleText(const TextRun&, int from, int to, GlyphBuffer&, ForTextEmphasisOrNot = NotForTextEmphasis) const;
     void drawSimpleText(GraphicsContext*, const TextRunPaintInfo&, const FloatPoint&) const;
     void drawEmphasisMarksForSimpleText(GraphicsContext*, const TextRunPaintInfo&, const AtomicString& mark, const FloatPoint&) const;
-    void drawGlyphs(GraphicsContext*, const SimpleFontData*, const GlyphBuffer&, int from, int to, const FloatPoint&, const FloatRect& textRect) const;
+    void drawGlyphs(GraphicsContext*, const SimpleFontData*, const GlyphBuffer&, unsigned from, unsigned numGlyphs, const FloatPoint&, const FloatRect& textRect) const;
     void drawGlyphBuffer(GraphicsContext*, const TextRunPaintInfo&, const GlyphBuffer&, const FloatPoint&) const;
     void drawEmphasisMarks(GraphicsContext*, const TextRunPaintInfo&, const GlyphBuffer&, const AtomicString&, const FloatPoint&) const;
     float floatWidthForSimpleText(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
@@ -301,19 +300,19 @@
 inline const SimpleFontData* Font::primaryFont() const
 {
     ASSERT(m_fontFallbackList);
-    return m_fontFallbackList->primarySimpleFontData(this);
+    return m_fontFallbackList->primarySimpleFontData(m_fontDescription);
 }
 
 inline const FontData* Font::fontDataAt(unsigned index) const
 {
     ASSERT(m_fontFallbackList);
-    return m_fontFallbackList->fontDataAt(this, index);
+    return m_fontFallbackList->fontDataAt(m_fontDescription, index);
 }
 
 inline bool Font::isFixedPitch() const
 {
     ASSERT(m_fontFallbackList);
-    return m_fontFallbackList->isFixedPitch(this);
+    return m_fontFallbackList->isFixedPitch(m_fontDescription);
 }
 
 inline FontSelector* Font::fontSelector() const
diff --git a/Source/core/platform/graphics/FontCache.cpp b/Source/core/platform/graphics/FontCache.cpp
index 4ca2e48..2ee8f56 100644
--- a/Source/core/platform/graphics/FontCache.cpp
+++ b/Source/core/platform/graphics/FontCache.cpp
@@ -34,6 +34,7 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/Font.h"
+#include "core/platform/graphics/FontDataCache.h"
 #include "core/platform/graphics/FontFallbackList.h"
 #include "core/platform/graphics/FontPlatformData.h"
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
@@ -70,6 +71,15 @@
 
 static FontPlatformDataCache* gFontPlatformDataCache = 0;
 
+FontPlatformData* FontCache::addFontResourcePlatformData(const FontDescription& fontDescription, const AtomicString& family)
+{
+    FontCacheKey key = fontDescription.cacheKey(family);
+    OwnPtr<FontPlatformData>& result = gFontPlatformDataCache->add(key, nullptr).iterator->value;
+    if (!result)
+        result = adoptPtr(createFontPlatformData(fontDescription, family, fontDescription.effectiveFontSize()));
+    return result.get();
+}
+
 FontPlatformData* FontCache::getFontResourcePlatformData(const FontDescription& fontDescription,
     const AtomicString& passedFamilyName, bool checkingAlternateName)
 {
@@ -88,27 +98,19 @@
         platformInit();
     }
 
-    FontCacheKey key = fontDescription.cacheKey(familyName);
-    FontPlatformData* result = 0;
-    bool foundResult;
-    FontPlatformDataCache::iterator it = gFontPlatformDataCache->find(key);
-    if (it == gFontPlatformDataCache->end()) {
-        result = createFontPlatformData(fontDescription, familyName, fontDescription.effectiveFontSize());
-        gFontPlatformDataCache->set(key, adoptPtr(result));
-        foundResult = result;
-    } else {
-        result = it->value.get();
-        foundResult = true;
-    }
+    FontPlatformData* result = addFontResourcePlatformData(fontDescription, familyName);
+    if (result || checkingAlternateName)
+        return result;
 
-    if (!foundResult && !checkingAlternateName) {
-        // We were unable to find a font. We have a small set of fonts that we alias to other names,
-        // 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 = getFontResourcePlatformData(fontDescription, alternateName, true);
-        if (result)
-            gFontPlatformDataCache->set(key, adoptPtr(new FontPlatformData(*result))); // Cache the result under the old name.
+    // We were unable to find a font. We have a small set of fonts that we alias to other names,
+    // 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()) {
+        if (FontPlatformData* alternateFontPlatformData = addFontResourcePlatformData(fontDescription, alternateName)) {
+            FontCacheKey key = fontDescription.cacheKey(familyName);
+            result = new FontPlatformData(*alternateFontPlatformData);
+            gFontPlatformDataCache->set(key, adoptPtr(result));
+        }
     }
 
     return result;
@@ -138,109 +140,32 @@
 }
 #endif
 
-struct FontDataCacheKeyHash {
-    static unsigned hash(const FontPlatformData& platformData)
-    {
-        return platformData.hash();
-    }
-
-    static bool equal(const FontPlatformData& a, const FontPlatformData& b)
-    {
-        return a == b;
-    }
-
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-struct FontDataCacheKeyTraits : WTF::GenericHashTraits<FontPlatformData> {
-    static const bool emptyValueIsZero = true;
-    static const bool needsDestruction = true;
-    static const FontPlatformData& emptyValue()
-    {
-        DEFINE_STATIC_LOCAL(FontPlatformData, key, (0.f, false, false));
-        return key;
-    }
-    static void constructDeletedValue(FontPlatformData& slot)
-    {
-        new (NotNull, &slot) FontPlatformData(HashTableDeletedValue);
-    }
-    static bool isDeletedValue(const FontPlatformData& value)
-    {
-        return value.isHashTableDeletedValue();
-    }
-};
-
-typedef HashMap<FontPlatformData, pair<RefPtr<SimpleFontData>, unsigned>, FontDataCacheKeyHash, FontDataCacheKeyTraits> FontDataCache;
-
 static FontDataCache* gFontDataCache = 0;
 
-#if !OS(ANDROID)
-const int cMaxInactiveFontData = 250;
-const int cTargetInactiveFontData = 200;
-#else
-const int cMaxInactiveFontData = 225;
-const int cTargetInactiveFontData = 200;
-#endif
-static ListHashSet<RefPtr<SimpleFontData> >* gInactiveFontData = 0;
-
 PassRefPtr<SimpleFontData> FontCache::getFontResourceData(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName, ShouldRetain shouldRetain)
 {
-    FontPlatformData* platformData;
+    if (FontPlatformData* platformData = getFontResourcePlatformData(fontDescription, adjustFamilyNameToAvoidUnsupportedFonts(family), checkingAlternateName))
+        return getFontResourceData(platformData, shouldRetain);
 
-    const AtomicString& preferedAlternateName = alternateFamilyNameAvoidingBitmapFonts(family);
-    if (!preferedAlternateName.isEmpty())
-        platformData = getFontResourcePlatformData(fontDescription, preferedAlternateName, checkingAlternateName);
-    else
-        platformData = getFontResourcePlatformData(fontDescription, family, checkingAlternateName);
-
-    if (!platformData)
-        return 0;
-
-    return getFontResourceData(platformData, shouldRetain);
+    return 0;
 }
 
 PassRefPtr<SimpleFontData> FontCache::getFontResourceData(const FontPlatformData* platformData, ShouldRetain shouldRetain)
 {
-    if (!platformData)
-        return 0;
+    if (!gFontDataCache)
+        gFontDataCache = new FontDataCache;
 
 #if !ASSERT_DISABLED
     if (shouldRetain == DoNotRetain)
         ASSERT(m_purgePreventCount);
 #endif
 
-    if (!gFontDataCache) {
-        gFontDataCache = new FontDataCache;
-        gInactiveFontData = new ListHashSet<RefPtr<SimpleFontData> >;
-    }
-
-    FontDataCache::iterator result = gFontDataCache->find(*platformData);
-    if (result == gFontDataCache->end()) {
-        pair<RefPtr<SimpleFontData>, unsigned> newValue(SimpleFontData::create(*platformData), shouldRetain == Retain ? 1 : 0);
-        gFontDataCache->set(*platformData, newValue);
-        if (shouldRetain == DoNotRetain)
-            gInactiveFontData->add(newValue.first);
-        return newValue.first.release();
-    }
-
-    if (!result.get()->value.second) {
-        ASSERT(gInactiveFontData->contains(result.get()->value.first));
-        gInactiveFontData->remove(result.get()->value.first);
-    }
-
-    if (shouldRetain == Retain) {
-        result.get()->value.second++;
-    } else if (!result.get()->value.second) {
-        // If shouldRetain is DoNotRetain and count is 0, we want to remove the fontData from
-        // gInactiveFontData (above) and re-add here to update LRU position.
-        gInactiveFontData->add(result.get()->value.first);
-    }
-
-    return result.get()->value.first;
+    return gFontDataCache->get(platformData, shouldRetain);
 }
 
-bool FontCache::isPlatformFontAvailable(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName)
+bool FontCache::isPlatformFontAvailable(const FontDescription& fontDescription, const AtomicString& family)
 {
+    bool checkingAlternateName = true;
     return getFontResourcePlatformData(fontDescription, family, checkingAlternateName);
 }
 
@@ -252,69 +177,30 @@
 void FontCache::releaseFontData(const SimpleFontData* fontData)
 {
     ASSERT(gFontDataCache);
-    ASSERT(!fontData->isCustomFont());
 
-    FontDataCache::iterator it = gFontDataCache->find(fontData->platformData());
-    ASSERT(it != gFontDataCache->end());
-    if (it == gFontDataCache->end())
-        return;
-
-    ASSERT(it->value.second);
-    if (!--it->value.second)
-        gInactiveFontData->add(it->value.first);
+    gFontDataCache->release(fontData);
 }
 
-void FontCache::purgeInactiveFontDataIfNeeded()
+static inline void purgePlatformFontDataCache()
 {
-    if (gInactiveFontData && !m_purgePreventCount && gInactiveFontData->size() > cMaxInactiveFontData)
-        purgeInactiveFontData(gInactiveFontData->size() - cTargetInactiveFontData);
+    if (!gFontPlatformDataCache)
+        return;
+
+    Vector<FontCacheKey> keysToRemove;
+    keysToRemove.reserveInitialCapacity(gFontPlatformDataCache->size());
+    FontPlatformDataCache::iterator platformDataEnd = gFontPlatformDataCache->end();
+    for (FontPlatformDataCache::iterator platformData = gFontPlatformDataCache->begin(); platformData != platformDataEnd; ++platformData) {
+        if (platformData->value && !gFontDataCache->contains(platformData->value.get()))
+            keysToRemove.append(platformData->key);
+    }
+
+    size_t keysToRemoveCount = keysToRemove.size();
+    for (size_t i = 0; i < keysToRemoveCount; ++i)
+        gFontPlatformDataCache->remove(keysToRemove[i]);
 }
 
-void FontCache::purgeInactiveFontData(int count)
+static inline void purgeFontVerticalDataCache()
 {
-    if (!gInactiveFontData || m_purgePreventCount)
-        return;
-
-    static bool isPurging; // Guard against reentry when e.g. a deleted FontData releases its small caps FontData.
-    if (isPurging)
-        return;
-
-    isPurging = true;
-
-    Vector<RefPtr<SimpleFontData>, 20> fontDataToDelete;
-    ListHashSet<RefPtr<SimpleFontData> >::iterator end = gInactiveFontData->end();
-    ListHashSet<RefPtr<SimpleFontData> >::iterator it = gInactiveFontData->begin();
-    for (int i = 0; i < count && it != end; ++it, ++i) {
-        RefPtr<SimpleFontData>& fontData = *it.get();
-        gFontDataCache->remove(fontData->platformData());
-        // We should not delete SimpleFontData here because deletion can modify gInactiveFontData. See http://trac.webkit.org/changeset/44011
-        fontDataToDelete.append(fontData);
-    }
-
-    if (it == end) {
-        // Removed everything
-        gInactiveFontData->clear();
-    } else {
-        for (int i = 0; i < count; ++i)
-            gInactiveFontData->remove(gInactiveFontData->begin());
-    }
-
-    fontDataToDelete.clear();
-
-    if (gFontPlatformDataCache) {
-        Vector<FontCacheKey> keysToRemove;
-        keysToRemove.reserveInitialCapacity(gFontPlatformDataCache->size());
-        FontPlatformDataCache::iterator platformDataEnd = gFontPlatformDataCache->end();
-        for (FontPlatformDataCache::iterator platformData = gFontPlatformDataCache->begin(); platformData != platformDataEnd; ++platformData) {
-            if (platformData->value && !gFontDataCache->contains(*platformData->value.get()))
-                keysToRemove.append(platformData->key);
-        }
-
-        size_t keysToRemoveCount = keysToRemove.size();
-        for (size_t i = 0; i < keysToRemoveCount; ++i)
-            gFontPlatformDataCache->remove(keysToRemove[i]);
-    }
-
 #if ENABLE(OPENTYPE_VERTICAL)
     FontVerticalDataCache& fontVerticalDataCache = fontVerticalDataCacheInstance();
     if (!fontVerticalDataCache.isEmpty()) {
@@ -322,87 +208,35 @@
         FontVerticalDataCache::iterator verticalDataEnd = fontVerticalDataCache.end();
         for (FontVerticalDataCache::iterator verticalData = fontVerticalDataCache.begin(); verticalData != verticalDataEnd; ++verticalData) {
             if (verticalData->value)
-                verticalData->value->m_inFontCache = false;
+                verticalData->value->setInFontCache(false);
         }
-        FontDataCache::iterator fontDataEnd = gFontDataCache->end();
-        for (FontDataCache::iterator fontData = gFontDataCache->begin(); fontData != fontDataEnd; ++fontData) {
-            OpenTypeVerticalData* verticalData = const_cast<OpenTypeVerticalData*>(fontData->value.first->verticalData());
-            if (verticalData)
-                verticalData->m_inFontCache = true;
-        }
-        Vector<FontFileKey> keysToRemove;
+
+        gFontDataCache->markAllVerticalData();
+
+        Vector<FontCache::FontFileKey> keysToRemove;
         keysToRemove.reserveInitialCapacity(fontVerticalDataCache.size());
         for (FontVerticalDataCache::iterator verticalData = fontVerticalDataCache.begin(); verticalData != verticalDataEnd; ++verticalData) {
-            if (!verticalData->value || !verticalData->value->m_inFontCache)
+            if (!verticalData->value || !verticalData->value->inFontCache())
                 keysToRemove.append(verticalData->key);
         }
         for (size_t i = 0, count = keysToRemove.size(); i < count; ++i)
             fontVerticalDataCache.take(keysToRemove[i]);
     }
 #endif
-
-    isPurging = false;
 }
 
-size_t FontCache::fontDataCount()
+void FontCache::purge(PurgeSeverity PurgeSeverity)
 {
-    if (gFontDataCache)
-        return gFontDataCache->size();
-    return 0;
-}
+    // We should never be forcing the purge while the FontCachePurgePreventer is in scope.
+    ASSERT(!m_purgePreventCount || PurgeSeverity == PurgeIfNeeded);
+    if (m_purgePreventCount)
+        return;
 
-size_t FontCache::inactiveFontDataCount()
-{
-    if (gInactiveFontData)
-        return gInactiveFontData->size();
-    return 0;
-}
+    if (!gFontDataCache || !gFontDataCache->purge(PurgeSeverity))
+        return;
 
-PassRefPtr<FontData> FontCache::getFontData(const Font& font, int& familyIndex, FontSelector* fontSelector)
-{
-    RefPtr<FontData> result;
-
-    int startIndex = familyIndex;
-    const FontFamily* startFamily = &font.fontDescription().family();
-    for (int i = 0; startFamily && i < startIndex; i++)
-        startFamily = startFamily->next();
-    const FontFamily* currFamily = startFamily;
-    while (currFamily && !result) {
-        familyIndex++;
-        if (currFamily->family().length()) {
-            if (fontSelector)
-                result = fontSelector->getFontData(font.fontDescription(), currFamily->family());
-
-            if (!result)
-                result = getFontResourceData(font.fontDescription(), currFamily->family());
-        }
-        currFamily = currFamily->next();
-    }
-
-    if (!currFamily)
-        familyIndex = cAllFamiliesScanned;
-
-    if (!result) {
-        // We didn't find a font. Try to find a similar font using our own specific knowledge about our platform.
-        // For example on OS X, we know to map any families containing the words Arabic, Pashto, or Urdu to the
-        // Geeza Pro font.
-        result = getSimilarFontPlatformData(font);
-    }
-
-    if (!result && !startIndex) {
-        // If it's the primary font that we couldn't find, we try the following. In all other cases, we will
-        // just use per-character system fallback.
-
-        if (fontSelector) {
-            // Try the user's preferred standard font.
-            if (RefPtr<FontData> data = fontSelector->getFontData(font.fontDescription(), FontFamilyNames::webkit_standard))
-                return data.release();
-        }
-
-        // Still no result. Hand back our last resort fallback font.
-        result = getLastResortFallbackFont(font.fontDescription());
-    }
-    return result.release();
+    purgePlatformFontDataCache();
+    purgeFontVerticalDataCache();
 }
 
 static HashSet<FontSelector*>* gClients;
@@ -456,7 +290,7 @@
     for (size_t i = 0; i < numClients; ++i)
         clients[i]->fontCacheInvalidated();
 
-    purgeInactiveFontData();
+    purge(ForcePurge);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/FontCache.h b/Source/core/platform/graphics/FontCache.h
index 30516f4..4e5e17e 100644
--- a/Source/core/platform/graphics/FontCache.h
+++ b/Source/core/platform/graphics/FontCache.h
@@ -61,6 +61,9 @@
 class OpenTypeVerticalData;
 class SimpleFontData;
 
+enum ShouldRetain { Retain, DoNotRetain };
+enum PurgeSeverity { PurgeIfNeeded, ForcePurge };
+
 class FontCache {
     friend class FontCachePurgePreventer;
 
@@ -68,9 +71,6 @@
 public:
     friend FontCache* fontCache();
 
-    enum ShouldRetain { Retain, DoNotRetain };
-
-    PassRefPtr<FontData> getFontData(const Font&, int& familyIndex, FontSelector*);
     void releaseFontData(const SimpleFontData*);
 
     // This method is implemented by the plaform and used by
@@ -80,12 +80,10 @@
     // Also implemented by the platform.
     void platformInit();
 
-    void getTraitsInFamily(const AtomicString&, Vector<unsigned>&);
-
     PassRefPtr<SimpleFontData> getFontResourceData(const FontDescription&, const AtomicString&, bool checkingAlternateName = false, ShouldRetain = Retain);
     PassRefPtr<SimpleFontData> getLastResortFallbackFont(const FontDescription&, ShouldRetain = Retain);
     SimpleFontData* getNonRetainedLastResortFallbackFont(const FontDescription&);
-    bool isPlatformFontAvailable(const FontDescription&, const AtomicString&, bool checkingAlternateName = false);
+    bool isPlatformFontAvailable(const FontDescription&, const AtomicString&);
 
     void addClient(FontSelector*);
     void removeClient(FontSelector*);
@@ -93,10 +91,6 @@
     unsigned short generation();
     void invalidate();
 
-    size_t fontDataCount();
-    size_t inactiveFontDataCount();
-    void purgeInactiveFontData(int count = INT_MAX);
-
 #if OS(WIN)
     PassRefPtr<SimpleFontData> fontDataFromDescriptionAndLogFont(const FontDescription&, ShouldRetain, const LOGFONT&, wchar_t* outFontFamilyName);
 #endif
@@ -121,21 +115,21 @@
     FontCache();
     ~FontCache();
 
+    void purge(PurgeSeverity = PurgeIfNeeded);
+
     void disablePurging() { m_purgePreventCount++; }
     void enablePurging()
     {
         ASSERT(m_purgePreventCount);
         if (!--m_purgePreventCount)
-            purgeInactiveFontDataIfNeeded();
+            purge(PurgeIfNeeded);
     }
 
-    void purgeInactiveFontDataIfNeeded();
-
     // FIXME: This method should eventually be removed.
     FontPlatformData* getFontResourcePlatformData(const FontDescription&, const AtomicString& family, bool checkingAlternateName = false);
+    FontPlatformData* addFontResourcePlatformData(const FontDescription&, const AtomicString& family);
 
     // These methods are implemented by each platform.
-    PassRefPtr<SimpleFontData> getSimilarFontPlatformData(const Font&);
     FontPlatformData* createFontPlatformData(const FontDescription&, const AtomicString& family, float fontSize);
 
     // Implemented on skia platforms.
diff --git a/Source/core/platform/graphics/FontDataCache.cpp b/Source/core/platform/graphics/FontDataCache.cpp
new file mode 100644
index 0000000..fd6e5ab
--- /dev/null
+++ b/Source/core/platform/graphics/FontDataCache.cpp
@@ -0,0 +1,155 @@
+/*
+ * 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/FontDataCache.h"
+
+#include "core/platform/graphics/SimpleFontData.h"
+
+using namespace WTF;
+
+namespace WebCore {
+
+#if !OS(ANDROID)
+const unsigned cMaxInactiveFontData = 250;
+const unsigned cTargetInactiveFontData = 200;
+#else
+const unsigned cMaxInactiveFontData = 225;
+const unsigned cTargetInactiveFontData = 200;
+#endif
+
+PassRefPtr<SimpleFontData> FontDataCache::get(const FontPlatformData* platformData, ShouldRetain shouldRetain)
+{
+    if (!platformData)
+        return 0;
+
+    Cache::iterator result = m_cache.find(*platformData);
+    if (result == m_cache.end()) {
+        pair<RefPtr<SimpleFontData>, unsigned> newValue(SimpleFontData::create(*platformData), shouldRetain == Retain ? 1 : 0);
+        m_cache.set(*platformData, newValue);
+        if (shouldRetain == DoNotRetain)
+            m_inactiveFontData.add(newValue.first);
+        return newValue.first.release();
+    }
+
+    if (!result.get()->value.second) {
+        ASSERT(m_inactiveFontData.contains(result.get()->value.first));
+        m_inactiveFontData.remove(result.get()->value.first);
+    }
+
+    if (shouldRetain == Retain) {
+        result.get()->value.second++;
+    } else if (!result.get()->value.second) {
+        // If shouldRetain is DoNotRetain and count is 0, we want to remove the fontData from
+        // m_inactiveFontData (above) and re-add here to update LRU position.
+        m_inactiveFontData.add(result.get()->value.first);
+    }
+
+    return result.get()->value.first;
+}
+
+bool FontDataCache::contains(const FontPlatformData* fontPlatformData) const
+{
+    return m_cache.contains(*fontPlatformData);
+}
+
+void FontDataCache::release(const SimpleFontData* fontData)
+{
+    ASSERT(!fontData->isCustomFont());
+
+    Cache::iterator it = m_cache.find(fontData->platformData());
+    ASSERT(it != m_cache.end());
+    if (it == m_cache.end())
+        return;
+
+    ASSERT(it->value.second);
+    if (!--it->value.second)
+        m_inactiveFontData.add(it->value.first);
+}
+
+void FontDataCache::markAllVerticalData()
+{
+#if ENABLE(OPENTYPE_VERTICAL)
+    Cache::iterator end = m_cache.end();
+    for (Cache::iterator fontData = m_cache.begin(); fontData != end; ++fontData) {
+        OpenTypeVerticalData* verticalData = const_cast<OpenTypeVerticalData*>(fontData->value.first->verticalData());
+        if (verticalData)
+            verticalData->setInFontCache(true);
+    }
+#endif
+}
+
+bool FontDataCache::purge(PurgeSeverity PurgeSeverity)
+{
+    if (PurgeSeverity == ForcePurge)
+        return purgeLeastRecentlyUsed(INT_MAX);
+
+    if (m_inactiveFontData.size() > cMaxInactiveFontData)
+        return purgeLeastRecentlyUsed(m_inactiveFontData.size() - cTargetInactiveFontData);
+
+    return false;
+}
+
+bool FontDataCache::purgeLeastRecentlyUsed(int count)
+{
+    static bool isPurging; // Guard against reentry when e.g. a deleted FontData releases its small caps FontData.
+    if (isPurging)
+        return false;
+
+    isPurging = true;
+
+    Vector<RefPtr<SimpleFontData>, 20> fontDataToDelete;
+    ListHashSet<RefPtr<SimpleFontData> >::iterator end = m_inactiveFontData.end();
+    ListHashSet<RefPtr<SimpleFontData> >::iterator it = m_inactiveFontData.begin();
+    for (int i = 0; i < count && it != end; ++it, ++i) {
+        RefPtr<SimpleFontData>& fontData = *it.get();
+        m_cache.remove(fontData->platformData());
+        // We should not delete SimpleFontData here because deletion can modify m_inactiveFontData. See http://trac.webkit.org/changeset/44011
+        fontDataToDelete.append(fontData);
+    }
+
+    if (it == end) {
+        // Removed everything
+        m_inactiveFontData.clear();
+    } else {
+        for (int i = 0; i < count; ++i)
+            m_inactiveFontData.remove(m_inactiveFontData.begin());
+    }
+
+    bool didWork = fontDataToDelete.size();
+
+    fontDataToDelete.clear();
+
+    isPurging = false;
+
+    return didWork;
+}
+
+}
diff --git a/Source/core/platform/graphics/FontDataCache.h b/Source/core/platform/graphics/FontDataCache.h
new file mode 100644
index 0000000..a639ac2
--- /dev/null
+++ b/Source/core/platform/graphics/FontDataCache.h
@@ -0,0 +1,99 @@
+/*
+ * 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 FontDataCache_h
+#define FontDataCache_h
+
+#include "core/platform/graphics/FontCache.h"
+#include "core/platform/graphics/FontPlatformData.h"
+#include "wtf/HashMap.h"
+#include "wtf/ListHashSet.h"
+
+namespace WebCore {
+
+class SimpleFontData;
+
+struct FontDataCacheKeyHash {
+    static unsigned hash(const FontPlatformData& platformData)
+    {
+        return platformData.hash();
+    }
+
+    static bool equal(const FontPlatformData& a, const FontPlatformData& b)
+    {
+        return a == b;
+    }
+
+    static const bool safeToCompareToEmptyOrDeleted = true;
+};
+
+struct FontDataCacheKeyTraits : WTF::GenericHashTraits<FontPlatformData> {
+    static const bool emptyValueIsZero = true;
+    static const bool needsDestruction = true;
+    static const FontPlatformData& emptyValue()
+    {
+        DEFINE_STATIC_LOCAL(FontPlatformData, key, (0.f, false, false));
+        return key;
+    }
+    static void constructDeletedValue(FontPlatformData& slot)
+    {
+        new (NotNull, &slot) FontPlatformData(WTF::HashTableDeletedValue);
+    }
+    static bool isDeletedValue(const FontPlatformData& value)
+    {
+        return value.isHashTableDeletedValue();
+    }
+};
+
+class FontDataCache {
+public:
+    PassRefPtr<SimpleFontData> get(const FontPlatformData*, ShouldRetain = Retain);
+    bool contains(const FontPlatformData*) const;
+    void release(const SimpleFontData*);
+
+    // This is used by FontVerticalDataCache to mark all items with vertical data
+    // that are currently in cache as "in cache", which is later used to sweep the FontVerticalDataCache.
+    void markAllVerticalData();
+
+    // Purges items in FontDataCache according to provided severity.
+    // Returns true if any removal of cache items actually occurred.
+    bool purge(PurgeSeverity);
+
+private:
+    bool purgeLeastRecentlyUsed(int count);
+
+    typedef HashMap<FontPlatformData, pair<RefPtr<SimpleFontData>, unsigned>, FontDataCacheKeyHash, FontDataCacheKeyTraits> Cache;
+    Cache m_cache;
+    ListHashSet<RefPtr<SimpleFontData> > m_inactiveFontData;
+};
+
+}
+
+#endif
diff --git a/Source/core/platform/graphics/FontFallbackList.cpp b/Source/core/platform/graphics/FontFallbackList.cpp
index 229f6ee..ba5c0c2 100644
--- a/Source/core/platform/graphics/FontFallbackList.cpp
+++ b/Source/core/platform/graphics/FontFallbackList.cpp
@@ -29,8 +29,11 @@
 #include "config.h"
 #include "core/platform/graphics/FontFallbackList.h"
 
+#include "FontFamilyNames.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/SegmentedFontData.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/FontFamily.h"
 
 namespace WebCore {
 
@@ -73,9 +76,9 @@
     }
 }
 
-void FontFallbackList::determinePitch(const Font* font) const
+void FontFallbackList::determinePitch(const FontDescription& fontDescription) const
 {
-    const FontData* fontData = primaryFontData(font);
+    const FontData* fontData = primaryFontData(fontDescription);
     if (!fontData->isSegmented())
         m_pitch = static_cast<const SimpleFontData*>(fontData)->pitch();
     else {
@@ -103,14 +106,14 @@
     return false;
 }
 
-const FontData* FontFallbackList::primaryFontData(const Font* f) const
+const FontData* FontFallbackList::primaryFontData(const FontDescription& fontDescription) const
 {
     for (unsigned fontIndex = 0; ; ++fontIndex) {
-        const FontData* fontData = fontDataAt(f, fontIndex);
+        const FontData* fontData = fontDataAt(fontDescription, fontIndex);
         if (!fontData) {
             // All fonts are custom fonts and are loading. Return the first FontData.
             // FIXME: Correct fallback to the default font.
-            return fontDataAt(f, 0);
+            return fontDataAt(fontDescription, 0);
         }
 
         // When a custom font is loading, we should use the correct fallback font to layout the text.
@@ -121,13 +124,54 @@
         // Begin to load the first custom font if needed.
         if (!fontIndex) {
             const SimpleFontData* simpleFontData = fontData->fontDataForCharacter(' ');
-            if (simpleFontData)
-                simpleFontData->beginLoadIfNeeded();
+            if (simpleFontData && simpleFontData->customFontData())
+                simpleFontData->customFontData()->beginLoadIfNeeded();
         }
     }
 }
 
-const FontData* FontFallbackList::fontDataAt(const Font* font, unsigned realizedFontIndex) const
+PassRefPtr<FontData> FontFallbackList::getFontData(const FontDescription& fontDescription, int& familyIndex) const
+{
+    RefPtr<FontData> result;
+
+    int startIndex = familyIndex;
+    const FontFamily* startFamily = &fontDescription.family();
+    for (int i = 0; startFamily && i < startIndex; i++)
+        startFamily = startFamily->next();
+    const FontFamily* currFamily = startFamily;
+    while (currFamily && !result) {
+        familyIndex++;
+        if (currFamily->family().length()) {
+            if (m_fontSelector)
+                result = m_fontSelector->getFontData(fontDescription, currFamily->family());
+
+            if (!result)
+                result = fontCache()->getFontResourceData(fontDescription, currFamily->family());
+        }
+        currFamily = currFamily->next();
+    }
+
+    if (!currFamily)
+        familyIndex = cAllFamiliesScanned;
+
+    if (result || startIndex)
+        return result.release();
+
+    // If it's the primary font that we couldn't find, we try the following. In all other cases, we will
+    // just use per-character system fallback.
+
+    if (m_fontSelector) {
+        // Try the user's preferred standard font.
+        if (RefPtr<FontData> data = m_fontSelector->getFontData(fontDescription, FontFamilyNames::webkit_standard))
+            return data.release();
+    }
+
+    // Still no result. Hand back our last resort fallback font.
+    return fontCache()->getLastResortFallbackFont(fontDescription);
+}
+
+
+const FontData* FontFallbackList::fontDataAt(const FontDescription& fontDescription, unsigned realizedFontIndex) const
 {
     if (realizedFontIndex < m_fontList.size())
         return m_fontList[realizedFontIndex].get(); // This fallback font is already in our list.
@@ -143,7 +187,7 @@
     // in |m_familyIndex|, so that we never scan the same spot in the list twice.  getFontData will adjust our
     // |m_familyIndex| as it scans for the right font to make.
     ASSERT(fontCache()->generation() == m_generation);
-    RefPtr<FontData> result = fontCache()->getFontData(*font, m_familyIndex, m_fontSelector.get());
+    RefPtr<FontData> result = getFontData(fontDescription, m_familyIndex);
     if (result) {
         m_fontList.append(result);
         if (result->isLoading())
diff --git a/Source/core/platform/graphics/FontFallbackList.h b/Source/core/platform/graphics/FontFallbackList.h
index 01219c4..5964bba 100644
--- a/Source/core/platform/graphics/FontFallbackList.h
+++ b/Source/core/platform/graphics/FontFallbackList.h
@@ -29,7 +29,6 @@
 
 namespace WebCore {
 
-class Font;
 class GlyphPageTreeNode;
 class GraphicsContext;
 class IntRect;
@@ -70,8 +69,13 @@
     ~FontFallbackList() { releaseFontData(); }
     void invalidate(PassRefPtr<FontSelector>);
 
-    bool isFixedPitch(const Font* f) const { if (m_pitch == UnknownPitch) determinePitch(f); return m_pitch == FixedPitch; };
-    void determinePitch(const Font*) const;
+    bool isFixedPitch(const FontDescription& fontDescription) const
+    {
+        if (m_pitch == UnknownPitch)
+            determinePitch(fontDescription);
+        return m_pitch == FixedPitch;
+    }
+    void determinePitch(const FontDescription&) const;
 
     bool loadingCustomFonts() const;
 
@@ -85,16 +89,18 @@
 private:
     FontFallbackList();
 
-    const SimpleFontData* primarySimpleFontData(const Font* f)
+    const SimpleFontData* primarySimpleFontData(const FontDescription& fontDescription)
     {
         ASSERT(isMainThread());
         if (!m_cachedPrimarySimpleFontData)
-            m_cachedPrimarySimpleFontData = primaryFontData(f)->fontDataForCharacter(' ');
+            m_cachedPrimarySimpleFontData = primaryFontData(fontDescription)->fontDataForCharacter(' ');
         return m_cachedPrimarySimpleFontData;
     }
 
-    const FontData* primaryFontData(const Font*) const;
-    const FontData* fontDataAt(const Font*, unsigned index) const;
+    PassRefPtr<FontData> getFontData(const FontDescription&, int& familyIndex) const;
+
+    const FontData* primaryFontData(const FontDescription&) const;
+    const FontData* fontDataAt(const FontDescription&, unsigned index) const;
 
     void setPlatformFont(const FontPlatformData&);
 
diff --git a/Source/core/platform/graphics/FontFastPath.cpp b/Source/core/platform/graphics/FontFastPath.cpp
index 39ad4ba..7f871c1 100644
--- a/Source/core/platform/graphics/FontFastPath.cpp
+++ b/Source/core/platform/graphics/FontFastPath.cpp
@@ -453,8 +453,8 @@
     const SimpleFontData* fontData = glyphBuffer.fontDataAt(0);
     FloatPoint startPoint(point);
     float nextX = startPoint.x() + glyphBuffer.advanceAt(0);
-    int lastFrom = 0;
-    int nextGlyph = 1;
+    unsigned lastFrom = 0;
+    unsigned nextGlyph = 1;
 #if ENABLE(SVG_FONTS)
     TextRun::RenderingContext* renderingContext = runInfo.run.renderingContext();
 #endif
@@ -520,7 +520,7 @@
     FloatPoint startPoint(point.x() + middleOfLastGlyph - offsetToMiddleOfGlyph(markFontData, markGlyph), point.y());
 
     GlyphBuffer markBuffer;
-    for (int i = 0; i + 1 < glyphBuffer.size(); ++i) {
+    for (unsigned i = 0; i + 1 < glyphBuffer.size(); ++i) {
         float middleOfNextGlyph = offsetToMiddleOfGlyphAtIndex(glyphBuffer, i + 1);
         float advance = glyphBuffer.advanceAt(i) - middleOfLastGlyph + middleOfNextGlyph;
         markBuffer.add(glyphBuffer.glyphAt(i) ? markGlyph : spaceGlyph, markFontData, advance);
diff --git a/Source/core/platform/graphics/FontPlatformData.h b/Source/core/platform/graphics/FontPlatformData.h
index e05bb03..e0a1176 100644
--- a/Source/core/platform/graphics/FontPlatformData.h
+++ b/Source/core/platform/graphics/FontPlatformData.h
@@ -24,7 +24,7 @@
 
 // FIXME: This is temporary until all ports switch to using this file.
 #if OS(WIN)
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
 #elif !OS(MACOSX)
 #include "core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h"
 
@@ -54,7 +54,7 @@
 #include "wtf/text/StringImpl.h"
 
 #if OS(MACOSX)
-#include "core/platform/graphics/chromium/CrossProcessFontLoading.h"
+#include "core/platform/graphics/mac/MemoryActivatedFont.h"
 #endif
 
 #if OS(MACOSX)
diff --git a/Source/core/platform/graphics/GaneshUtils.cpp b/Source/core/platform/graphics/GaneshUtils.cpp
new file mode 100644
index 0000000..b1a1a9a
--- /dev/null
+++ b/Source/core/platform/graphics/GaneshUtils.cpp
@@ -0,0 +1,64 @@
+/*
+ * 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/GaneshUtils.h"
+
+#include "third_party/skia/include/core/SkCanvas.h"
+#include "third_party/skia/include/gpu/SkGrPixelRef.h"
+
+namespace WebCore {
+
+bool ensureTextureBackedSkBitmap(GrContext* gr, SkBitmap& bitmap, const IntSize& size, GrSurfaceOrigin origin, GrPixelConfig config)
+{
+    if (!bitmap.getTexture() || bitmap.width() != size.width() || bitmap.height() != size.height()) {
+        if (!gr)
+            return false;
+        GrTextureDesc desc;
+        desc.fConfig = config;
+        desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
+        desc.fSampleCnt = 0;
+        desc.fOrigin = origin;
+        desc.fWidth = size.width();
+        desc.fHeight = size.height();
+        SkAutoTUnref<GrTexture> texture(gr->createUncachedTexture(desc, 0, 0));
+        if (!texture.get())
+            return false;
+        SkGrPixelRef* pixelRef = SkNEW_ARGS(SkGrPixelRef, (texture.get()));
+        if (!pixelRef)
+            return false;
+        bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height());
+        bitmap.setPixelRef(pixelRef, 0)->unref();
+    }
+
+    return true;
+}
+
+} // namespace WebCore
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.cpp b/Source/core/platform/graphics/GaneshUtils.h
similarity index 79%
copy from Source/core/workers/WorkerGlobalScopeProxy.cpp
copy to Source/core/platform/graphics/GaneshUtils.h
index 06471bb..a86b0ef 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ b/Source/core/platform/graphics/GaneshUtils.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 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,11 +28,17 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
+#ifndef GaneshUtils_h
+#define GaneshUtils_h
+
+#include "platform/geometry/IntSize.h"
+#include "third_party/skia/include/core/SkBitmap.h"
+#include "third_party/skia/include/gpu/GrContext.h"
 
 namespace WebCore {
 
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
+bool ensureTextureBackedSkBitmap(GrContext*, SkBitmap&, const IntSize&, GrSurfaceOrigin, GrPixelConfig);
 
 } // namespace WebCore
+
+#endif // GaneshUtils_h
diff --git a/Source/core/platform/graphics/GlyphPageTreeNode.cpp b/Source/core/platform/graphics/GlyphPageTreeNode.cpp
index 23a66b7..d21eb21 100644
--- a/Source/core/platform/graphics/GlyphPageTreeNode.cpp
+++ b/Source/core/platform/graphics/GlyphPageTreeNode.cpp
@@ -122,8 +122,8 @@
 static bool fill(GlyphPage* pageToFill, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData)
 {
 #if ENABLE(SVG_FONTS)
-    if (SimpleFontData::AdditionalFontData* additionalFontData = fontData->fontData())
-        return additionalFontData->fillSVGGlyphPage(pageToFill, offset, length, buffer, bufferLength, fontData);
+    if (fontData->isSVGFont())
+        return fontData->customFontData()->fillSVGGlyphPage(pageToFill, offset, length, buffer, bufferLength, fontData);
 #endif
     bool hasGlyphs = pageToFill->fill(offset, length, buffer, bufferLength, fontData);
 #if ENABLE(OPENTYPE_VERTICAL)
@@ -229,8 +229,9 @@
                         // If this is a custom font needs to be loaded, kick off
                         // the load here, and do not fill the page so that
                         // font fallback is used while loading.
-                        if (range.fontData()->isLoadingFallback()) {
-                            range.fontData()->beginLoadIfNeeded();
+                        RefPtr<CustomFontData> customData = range.fontData()->customFontData();
+                        if (customData && customData->isLoadingFallback()) {
+                            customData->beginLoadIfNeeded();
                             continue;
                         }
 
diff --git a/Source/core/platform/graphics/GraphicsContext.cpp b/Source/core/platform/graphics/GraphicsContext.cpp
index fae5b96..f6d1f93 100644
--- a/Source/core/platform/graphics/GraphicsContext.cpp
+++ b/Source/core/platform/graphics/GraphicsContext.cpp
@@ -36,6 +36,7 @@
 #include "platform/graphics/DisplayList.h"
 #include "platform/graphics/TextRunIterator.h"
 #include "platform/text/BidiResolver.h"
+#include "platform/weborigin/KURL.h"
 #include "third_party/skia/include/core/SkAnnotation.h"
 #include "third_party/skia/include/core/SkColorFilter.h"
 #include "third_party/skia/include/core/SkData.h"
@@ -46,7 +47,6 @@
 #include "third_party/skia/include/effects/SkBlurMaskFilter.h"
 #include "third_party/skia/include/effects/SkCornerPathEffect.h"
 #include "third_party/skia/include/effects/SkLumaColorFilter.h"
-#include "weborigin/KURL.h"
 #include "wtf/Assertions.h"
 #include "wtf/MathExtras.h"
 
@@ -66,14 +66,16 @@
 };
 
 struct GraphicsContext::RecordingState {
-    RecordingState(SkCanvas* oldCanvas, PassRefPtr<DisplayList> displayList)
-        : m_savedCanvas(oldCanvas)
+    RecordingState(SkCanvas* currentCanvas, const SkMatrix& currentMatrix, PassRefPtr<DisplayList> displayList)
+        : m_savedCanvas(currentCanvas)
         , m_displayList(displayList)
+        , m_savedMatrix(currentMatrix)
     {
     }
 
     SkCanvas* m_savedCanvas;
     RefPtr<DisplayList> m_displayList;
+    const SkMatrix m_savedMatrix;
 };
 
 GraphicsContext::GraphicsContext(SkCanvas* canvas)
@@ -348,11 +350,19 @@
     return true;
 }
 
-const SkMatrix& GraphicsContext::getTotalMatrix() const
+SkMatrix GraphicsContext::getTotalMatrix() const
 {
     if (paintingDisabled())
         return SkMatrix::I();
-    return m_canvas->getTotalMatrix();
+
+    if (!isRecording())
+        return m_canvas->getTotalMatrix();
+
+    const RecordingState& recordingState = m_recordingStateStack.last();
+    SkMatrix totalMatrix = recordingState.m_savedMatrix;
+    totalMatrix.preConcat(m_canvas->getTotalMatrix());
+
+    return totalMatrix;
 }
 
 bool GraphicsContext::isPrintingDevice() const
@@ -482,15 +492,23 @@
 void GraphicsContext::beginRecording(const FloatRect& bounds)
 {
     RefPtr<DisplayList> displayList = adoptRef(new DisplayList(bounds));
-    m_recordingStateStack.append(RecordingState(m_canvas, displayList));
 
-    IntRect recordingRect = enclosingIntRect(displayList->bounds());
-    m_canvas = displayList->picture()->beginRecording(recordingRect.width(), recordingRect.height());
+    SkCanvas* savedCanvas = m_canvas;
+    SkMatrix savedMatrix = getTotalMatrix();
+
+    IntRect recordingRect = enclosingIntRect(bounds);
+    m_canvas = displayList->picture()->beginRecording(recordingRect.width(), recordingRect.height(),
+        SkPicture::kUsePathBoundsForClip_RecordingFlag);
 
     // We want the bounds offset mapped to (0, 0), such that the display list content
     // is fully contained within the SkPictureRecord's bounds.
-    if (bounds.x() || bounds.y())
+    if (!toFloatSize(bounds.location()).isZero()) {
         m_canvas->translate(-bounds.x(), -bounds.y());
+        // To avoid applying the offset repeatedly in getTotalMatrix(), we pre-apply it here.
+        savedMatrix.preTranslate(bounds.x(), bounds.y());
+    }
+
+    m_recordingStateStack.append(RecordingState(savedCanvas, savedMatrix, displayList));
 }
 
 PassRefPtr<DisplayList> GraphicsContext::endRecording()
@@ -507,6 +525,11 @@
     return recording.m_displayList.release();
 }
 
+bool GraphicsContext::isRecording() const
+{
+    return !m_recordingStateStack.isEmpty();
+}
+
 void GraphicsContext::drawDisplayList(DisplayList* displayList)
 {
     ASSERT(!displayList->picture()->getRecordingCanvas());
@@ -1585,7 +1608,7 @@
     if (paintingDisabled())
         return AffineTransform();
 
-    const SkMatrix& m = getTotalMatrix();
+    SkMatrix m = getTotalMatrix();
     return AffineTransform(SkScalarToDouble(m.getScaleX()),
                            SkScalarToDouble(m.getSkewY()),
                            SkScalarToDouble(m.getSkewX()),
@@ -1679,11 +1702,6 @@
     }
 }
 
-static bool scalesMatch(AffineTransform a, AffineTransform b)
-{
-    return a.xScale() == b.xScale() && a.yScale() == b.yScale();
-}
-
 PassOwnPtr<ImageBuffer> GraphicsContext::createCompatibleBuffer(const IntSize& size, bool hasAlpha) const
 {
     // Make the buffer larger if the context's transform is scaling it so we need a higher
@@ -1703,13 +1721,6 @@
     return buffer.release();
 }
 
-bool GraphicsContext::isCompatibleWithBuffer(ImageBuffer* buffer) const
-{
-    GraphicsContext* bufferContext = buffer->context();
-
-    return scalesMatch(getCTM(), bufferContext->getCTM()) && m_accelerated == bufferContext->isAccelerated();
-}
-
 void GraphicsContext::addCornerArc(SkPath* path, const SkRect& rect, const IntSize& size, int startAngle)
 {
     SkIRect ir;
diff --git a/Source/core/platform/graphics/GraphicsContext.h b/Source/core/platform/graphics/GraphicsContext.h
index b3f61ae..7015f0a 100644
--- a/Source/core/platform/graphics/GraphicsContext.h
+++ b/Source/core/platform/graphics/GraphicsContext.h
@@ -138,7 +138,7 @@
 
     bool getClipBounds(SkRect* bounds) const;
     bool getTransformedClipBounds(FloatRect* bounds) const;
-    const SkMatrix& getTotalMatrix() const;
+    SkMatrix getTotalMatrix() const;
     bool isPrintingDevice() const;
 
     void setShouldAntialias(bool antialias) { m_state->m_shouldAntialias = antialias; }
@@ -368,7 +368,6 @@
     // Create an image buffer compatible with this context, with suitable resolution
     // for drawing into the buffer and then into this context.
     PassOwnPtr<ImageBuffer> createCompatibleBuffer(const IntSize&, bool hasAlpha = true) const;
-    bool isCompatibleWithBuffer(ImageBuffer*) const;
 
     static void adjustLineToPixelBoundaries(FloatPoint& p1, FloatPoint& p2, float strokeWidth, StrokeStyle);
 
@@ -442,6 +441,8 @@
 
     void fillRectWithRoundedHole(const IntRect&, const RoundedRect& roundedHoleRect, const Color&);
 
+    bool isRecording() const;
+
     // null indicates painting is disabled. Never delete this object.
     SkCanvas* m_canvas;
 
diff --git a/Source/core/platform/graphics/GraphicsContext3D.cpp b/Source/core/platform/graphics/GraphicsContext3D.cpp
index 24b0cc6..c1578e6 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.cpp
+++ b/Source/core/platform/graphics/GraphicsContext3D.cpp
@@ -29,15 +29,14 @@
 
 #include "core/platform/graphics/GraphicsContext3D.h"
 
-#include "core/html/ImageData.h"
 #include "core/platform/graphics/Extensions3D.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/ImageObserver.h"
 #include "core/platform/graphics/gpu/DrawingBuffer.h"
 #include "core/platform/image-decoders/ImageDecoder.h"
 #include "platform/CheckedInt.h"
+#include "platform/graphics/ImageObserver.h"
 #include "third_party/skia/include/gpu/GrContext.h"
 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
 #include "wtf/CPU.h"
@@ -55,7 +54,7 @@
 
 namespace {
 
-void getDrawingParameters(DrawingBuffer* drawingBuffer, WebKit::WebGraphicsContext3D* graphicsContext3D,
+void getDrawingParameters(DrawingBuffer* drawingBuffer, blink::WebGraphicsContext3D* graphicsContext3D,
                           Platform3DObject* frameBufferId, int* width, int* height)
 {
     ASSERT(drawingBuffer);
@@ -66,7 +65,7 @@
 
 } // anonymous namespace
 
-GraphicsContext3D::GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3D> webContext, bool preserveDrawingBuffer)
+GraphicsContext3D::GraphicsContext3D(PassOwnPtr<blink::WebGraphicsContext3D> webContext, bool preserveDrawingBuffer)
     : m_impl(webContext.get())
     , m_ownedWebContext(webContext)
     , m_initializedAvailableExtensions(false)
@@ -78,7 +77,7 @@
 {
 }
 
-GraphicsContext3D::GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3DProvider> provider, bool preserveDrawingBuffer)
+GraphicsContext3D::GraphicsContext3D(PassOwnPtr<blink::WebGraphicsContext3DProvider> provider, bool preserveDrawingBuffer)
     : m_provider(provider)
     , m_impl(m_provider->context3d())
     , m_initializedAvailableExtensions(false)
@@ -207,7 +206,7 @@
     return m_impl->name(a1, a2, a3, a4, a5, a6, a7, a8, a9); \
 }
 
-class GraphicsContext3DContextLostCallbackAdapter : public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
+class GraphicsContext3DContextLostCallbackAdapter : public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback {
 public:
     GraphicsContext3DContextLostCallbackAdapter(PassOwnPtr<GraphicsContext3D::ContextLostCallback> callback)
         : m_contextLostCallback(callback) { }
@@ -222,13 +221,13 @@
     OwnPtr<GraphicsContext3D::ContextLostCallback> m_contextLostCallback;
 };
 
-class GraphicsContext3DErrorMessageCallbackAdapter : public WebKit::WebGraphicsContext3D::WebGraphicsErrorMessageCallback {
+class GraphicsContext3DErrorMessageCallbackAdapter : public blink::WebGraphicsContext3D::WebGraphicsErrorMessageCallback {
 public:
     GraphicsContext3DErrorMessageCallbackAdapter(PassOwnPtr<GraphicsContext3D::ErrorMessageCallback> callback)
         : m_errorMessageCallback(callback) { }
     virtual ~GraphicsContext3DErrorMessageCallbackAdapter() { }
 
-    virtual void onErrorMessage(const WebKit::WebString& message, WebKit::WGC3Dint id)
+    virtual void onErrorMessage(const blink::WebString& message, blink::WGC3Dint id)
     {
         if (m_errorMessageCallback)
             m_errorMessageCallback->onErrorMessage(message, id);
@@ -255,7 +254,7 @@
 
 PassRefPtr<GraphicsContext3D> GraphicsContext3D::create(GraphicsContext3D::Attributes attrs)
 {
-    WebKit::WebGraphicsContext3D::Attributes webAttributes;
+    blink::WebGraphicsContext3D::Attributes webAttributes;
     webAttributes.alpha = attrs.alpha;
     webAttributes.depth = attrs.depth;
     webAttributes.stencil = attrs.stencil;
@@ -264,22 +263,23 @@
     webAttributes.noExtensions = attrs.noExtensions;
     webAttributes.shareResources = attrs.shareResources;
     webAttributes.preferDiscreteGPU = attrs.preferDiscreteGPU;
+    webAttributes.failIfMajorPerformanceCaveat = attrs.failIfMajorPerformanceCaveat;
     webAttributes.topDocumentURL = attrs.topDocumentURL.string();
 
-    OwnPtr<WebKit::WebGraphicsContext3D> webContext = adoptPtr(WebKit::Platform::current()->createOffscreenGraphicsContext3D(webAttributes));
+    OwnPtr<blink::WebGraphicsContext3D> webContext = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(webAttributes));
     if (!webContext)
         return 0;
 
     return GraphicsContext3D::createGraphicsContextFromWebContext(webContext.release(), attrs.preserveDrawingBuffer);
 }
 
-PassRefPtr<GraphicsContext3D> GraphicsContext3D::createGraphicsContextFromProvider(PassOwnPtr<WebKit::WebGraphicsContext3DProvider> provider, bool preserveDrawingBuffer)
+PassRefPtr<GraphicsContext3D> GraphicsContext3D::createGraphicsContextFromProvider(PassOwnPtr<blink::WebGraphicsContext3DProvider> provider, bool preserveDrawingBuffer)
 {
     RefPtr<GraphicsContext3D> context = adoptRef(new GraphicsContext3D(provider, preserveDrawingBuffer));
     return context.release();
 }
 
-PassRefPtr<GraphicsContext3D> GraphicsContext3D::createGraphicsContextFromWebContext(PassOwnPtr<WebKit::WebGraphicsContext3D> webContext, bool preserveDrawingBuffer)
+PassRefPtr<GraphicsContext3D> GraphicsContext3D::createGraphicsContextFromWebContext(PassOwnPtr<blink::WebGraphicsContext3D> webContext, bool preserveDrawingBuffer)
 {
     RefPtr<GraphicsContext3D> context = adoptRef(new GraphicsContext3D(webContext, preserveDrawingBuffer));
     return context.release();
@@ -352,7 +352,7 @@
 
 bool GraphicsContext3D::getActiveAttrib(Platform3DObject program, GC3Duint index, ActiveInfo& info)
 {
-    WebKit::WebGraphicsContext3D::ActiveInfo webInfo;
+    blink::WebGraphicsContext3D::ActiveInfo webInfo;
     if (!m_impl->getActiveAttrib(program, index, webInfo))
         return false;
     info.name = webInfo.name;
@@ -363,7 +363,7 @@
 
 bool GraphicsContext3D::getActiveUniform(Platform3DObject program, GC3Duint index, ActiveInfo& info)
 {
-    WebKit::WebGraphicsContext3D::ActiveInfo webInfo;
+    blink::WebGraphicsContext3D::ActiveInfo webInfo;
     if (!m_impl->getActiveUniform(program, index, webInfo))
         return false;
     info.name = webInfo.name;
@@ -384,7 +384,7 @@
 
 GraphicsContext3D::Attributes GraphicsContext3D::getContextAttributes()
 {
-    WebKit::WebGraphicsContext3D::Attributes webAttributes = m_impl->getContextAttributes();
+    blink::WebGraphicsContext3D::Attributes webAttributes = m_impl->getContextAttributes();
     GraphicsContext3D::Attributes attributes;
     attributes.alpha = webAttributes.alpha;
     attributes.depth = webAttributes.depth;
@@ -524,23 +524,27 @@
     paintFramebufferToCanvas(framebufferId, width, height, !getContextAttributes().premultipliedAlpha, imageBuffer);
 }
 
-PassRefPtr<ImageData> GraphicsContext3D::paintRenderingResultsToImageData(DrawingBuffer* drawingBuffer)
+PassRefPtr<Uint8ClampedArray> GraphicsContext3D::paintRenderingResultsToImageData(DrawingBuffer* drawingBuffer, int& width, int& height)
 {
     if (getContextAttributes().premultipliedAlpha)
         return 0;
 
     Platform3DObject framebufferId;
-    int width, height;
     getDrawingParameters(drawingBuffer, m_impl, &framebufferId, &width, &height);
 
-    RefPtr<ImageData> imageData = ImageData::create(IntSize(width, height));
-    unsigned char* pixels = imageData->data()->data();
+    Checked<int, RecordOverflow> dataSize = 4;
+    dataSize *= width;
+    dataSize *= height;
+    if (dataSize.hasOverflowed())
+        return 0;
+
+    RefPtr<Uint8ClampedArray> pixels = Uint8ClampedArray::createUninitialized(width * height * 4);
 
     m_impl->bindFramebuffer(FRAMEBUFFER, framebufferId);
-    readBackFramebuffer(pixels, width, height, ReadbackRGBA, AlphaDoNothing);
-    flipVertically(pixels, width, height);
+    readBackFramebuffer(pixels->data(), width, height, ReadbackRGBA, AlphaDoNothing);
+    flipVertically(pixels->data(), width, height);
 
-    return imageData.release();
+    return pixels.release();
 }
 
 void GraphicsContext3D::readBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder readbackOrder, AlphaOp op)
diff --git a/Source/core/platform/graphics/GraphicsContext3D.h b/Source/core/platform/graphics/GraphicsContext3D.h
index 6c5f839..f976a12 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.h
+++ b/Source/core/platform/graphics/GraphicsContext3D.h
@@ -30,8 +30,8 @@
 #include "core/platform/graphics/Image.h"
 #include "platform/geometry/IntRect.h"
 #include "platform/graphics/GraphicsTypes3D.h"
+#include "platform/weborigin/KURL.h"
 #include "third_party/skia/include/core/SkBitmap.h"
-#include "weborigin/KURL.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/ListHashSet.h"
@@ -48,7 +48,7 @@
 
 class GrContext;
 
-namespace WebKit {
+namespace blink {
 class WebGraphicsContext3D;
 class WebGraphicsContext3DProvider;
 }
@@ -60,7 +60,6 @@
 class GraphicsContext3DErrorMessageCallbackAdapter;
 class Image;
 class ImageBuffer;
-class ImageData;
 class IntRect;
 class IntSize;
 
@@ -398,6 +397,7 @@
             , noExtensions(false)
             , shareResources(true)
             , preferDiscreteGPU(false)
+            , failIfMajorPerformanceCaveat(false)
         {
         }
 
@@ -410,6 +410,7 @@
         bool noExtensions;
         bool shareResources;
         bool preferDiscreteGPU;
+        bool failIfMajorPerformanceCaveat;
         KURL topDocumentURL;
     };
 
@@ -433,13 +434,13 @@
     // Callers must make the context current before using it AND check that the context was created successfully
     // via ContextLost before using the context in any way. Once made current on a thread, the context cannot
     // be used on any other thread.
-    static PassRefPtr<GraphicsContext3D> createGraphicsContextFromWebContext(PassOwnPtr<WebKit::WebGraphicsContext3D>, bool preserveDrawingBuffer = false);
-    static PassRefPtr<GraphicsContext3D> createGraphicsContextFromProvider(PassOwnPtr<WebKit::WebGraphicsContext3DProvider>, bool preserveDrawingBuffer = false);
+    static PassRefPtr<GraphicsContext3D> createGraphicsContextFromWebContext(PassOwnPtr<blink::WebGraphicsContext3D>, bool preserveDrawingBuffer = false);
+    static PassRefPtr<GraphicsContext3D> createGraphicsContextFromProvider(PassOwnPtr<blink::WebGraphicsContext3DProvider>, bool preserveDrawingBuffer = false);
 
     ~GraphicsContext3D();
 
     GrContext* grContext();
-    WebKit::WebGraphicsContext3D* webContext() const { return m_impl; }
+    blink::WebGraphicsContext3D* webContext() const { return m_impl; }
 
     bool makeContextCurrent();
 
@@ -668,7 +669,7 @@
     bool layerComposited() const;
 
     void paintRenderingResultsToCanvas(ImageBuffer*, DrawingBuffer*);
-    PassRefPtr<ImageData> paintRenderingResultsToImageData(DrawingBuffer*);
+    PassRefPtr<Uint8ClampedArray> paintRenderingResultsToImageData(DrawingBuffer*, int&, int&);
 
     // Support for buffer creation and deletion
     Platform3DObject createBuffer();
@@ -775,7 +776,7 @@
     // packing the pixel data according to the given format and type,
     // and obeying the flipY and premultiplyAlpha flags. Returns true
     // upon success.
-    static bool extractImageData(ImageData*, GC3Denum format, GC3Denum type, bool flipY, bool premultiplyAlpha, Vector<uint8_t>& data);
+    static bool extractImageData(const uint8_t*, const IntSize&, GC3Denum format, GC3Denum type, bool flipY, bool premultiplyAlpha, Vector<uint8_t>& data);
 
     // Helper function which extracts the user-supplied texture
     // data, applying the flipY and premultiplyAlpha parameters.
@@ -799,8 +800,8 @@
 private:
     friend class Extensions3D;
 
-    GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3D>, bool preserveDrawingBuffer);
-    GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3DProvider>, bool preserveDrawingBuffer);
+    GraphicsContext3D(PassOwnPtr<blink::WebGraphicsContext3D>, bool preserveDrawingBuffer);
+    GraphicsContext3D(PassOwnPtr<blink::WebGraphicsContext3DProvider>, bool preserveDrawingBuffer);
 
     // Helper for packImageData/extractImageData/extractTextureData which implement packing of pixel
     // data into the specified OpenGL destination format and type.
@@ -823,11 +824,11 @@
 
     bool preserveDrawingBuffer() const { return m_preserveDrawingBuffer; }
 
-    OwnPtr<WebKit::WebGraphicsContext3DProvider> m_provider;
-    WebKit::WebGraphicsContext3D* m_impl;
+    OwnPtr<blink::WebGraphicsContext3DProvider> m_provider;
+    blink::WebGraphicsContext3D* m_impl;
     OwnPtr<GraphicsContext3DContextLostCallbackAdapter> m_contextLostCallbackAdapter;
     OwnPtr<GraphicsContext3DErrorMessageCallbackAdapter> m_errorMessageCallbackAdapter;
-    OwnPtr<WebKit::WebGraphicsContext3D> m_ownedWebContext;
+    OwnPtr<blink::WebGraphicsContext3D> m_ownedWebContext;
     OwnPtr<Extensions3D> m_extensions;
     bool m_initializedAvailableExtensions;
     HashSet<String> m_enabledExtensions;
diff --git a/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp b/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp
index a75308c..aa8ff22 100644
--- a/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp
+++ b/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp
@@ -27,10 +27,9 @@
 #include "config.h"
 #include "core/platform/graphics/GraphicsContext3D.h"
 
-#include "core/html/ImageData.h"
-#include "core/platform/graphics/ImageObserver.h"
 #include "core/platform/graphics/cpu/arm/GraphicsContext3DNEON.h"
 #include "core/platform/image-decoders/ImageDecoder.h"
+#include "platform/graphics/ImageObserver.h"
 
 namespace WebCore {
 
@@ -1490,7 +1489,8 @@
 }
 
 bool GraphicsContext3D::extractImageData(
-    ImageData* imageData,
+    const uint8_t* imageData,
+    const IntSize& imageDataSize,
     GC3Denum format,
     GC3Denum type,
     bool flipY,
@@ -1499,8 +1499,8 @@
 {
     if (!imageData)
         return false;
-    int width = imageData->width();
-    int height = imageData->height();
+    int width = imageDataSize.width();
+    int height = imageDataSize.height();
 
     unsigned packedSize;
     // Output data is tightly packed (alignment == 1).
@@ -1508,7 +1508,7 @@
         return false;
     data.resize(packedSize);
 
-    if (!packPixels(imageData->data()->data(), DataFormatRGBA8, width, height, 0, format, type, premultiplyAlpha ? AlphaDoPremultiply : AlphaDoNothing, data.data(), flipY))
+    if (!packPixels(imageData, DataFormatRGBA8, width, height, 0, format, type, premultiplyAlpha ? AlphaDoPremultiply : AlphaDoNothing, data.data(), flipY))
         return false;
 
     return true;
diff --git a/Source/core/platform/graphics/GraphicsContextTest.cpp b/Source/core/platform/graphics/GraphicsContextTest.cpp
index 2bfaf1f..b53f278 100644
--- a/Source/core/platform/graphics/GraphicsContextTest.cpp
+++ b/Source/core/platform/graphics/GraphicsContextTest.cpp
@@ -30,6 +30,8 @@
 #include "core/platform/graphics/BitmapImage.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
+#include "platform/graphics/DisplayList.h"
+#include "third_party/skia/include/core/SkBitmapDevice.h"
 #include <gtest/gtest.h>
 
 using namespace WebCore;
@@ -1080,4 +1082,42 @@
     EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
 }
 
+#define DISPATCH(c1, c2, op, params) do { c1.op(params); c2.op(params); } while (0);
+
+TEST(GraphicsContextTest, RecordingTotalMatrix)
+{
+    SkBitmap bitmap;
+    bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
+    bitmap.allocPixels();
+    bitmap.eraseColor(0);
+    SkCanvas canvas(bitmap);
+    GraphicsContext context(&canvas);
+
+    SkBitmapDevice controlDevice(SkBitmap::kNo_Config, 400, 400);
+    SkCanvas controlCanvas(&controlDevice);
+    GraphicsContext controlContext(&controlCanvas);
+
+    EXPECT_EQ(context.getCTM(), controlContext.getCTM());
+    DISPATCH(context, controlContext, scale, FloatSize(2, 2));
+    EXPECT_EQ(context.getCTM(), controlContext.getCTM());
+
+    controlContext.save();
+    context.beginRecording(FloatRect(0, 0, 200, 200));
+    DISPATCH(context, controlContext, translate, FloatSize(10, 10));
+    EXPECT_EQ(context.getCTM(), controlContext.getCTM());
+
+    controlContext.save();
+    context.beginRecording(FloatRect(10, 10, 100, 100));
+    DISPATCH(context, controlContext, rotate, 45);
+    EXPECT_EQ(context.getCTM(), controlContext.getCTM());
+
+    controlContext.restore();
+    context.endRecording();
+    EXPECT_EQ(context.getCTM(), controlContext.getCTM());
+
+    controlContext.restore();
+    context.endRecording();
+    EXPECT_EQ(context.getCTM(), controlContext.getCTM());
+}
+
 } // namespace
diff --git a/Source/core/platform/graphics/GraphicsLayer.cpp b/Source/core/platform/graphics/GraphicsLayer.cpp
index 238bac8..93e47e6 100644
--- a/Source/core/platform/graphics/GraphicsLayer.cpp
+++ b/Source/core/platform/graphics/GraphicsLayer.cpp
@@ -58,11 +58,11 @@
 #include <stdio.h>
 #endif
 
-using WebKit::Platform;
-using WebKit::WebAnimation;
-using WebKit::WebFilterOperations;
-using WebKit::WebLayer;
-using WebKit::WebPoint;
+using blink::Platform;
+using blink::WebAnimation;
+using blink::WebFilterOperations;
+using blink::WebLayer;
+using blink::WebPoint;
 
 namespace WebCore {
 
@@ -101,9 +101,8 @@
     , m_paintCount(0)
     , m_contentsLayer(0)
     , m_contentsLayerId(0)
-    , m_contentsLayerPurpose(NoContentsLayer)
     , m_scrollableArea(0)
-    , m_compositingReasons(WebKit::CompositingReasonUnknown)
+    , m_compositingReasons(blink::CompositingReasonUnknown)
 {
 #ifndef NDEBUG
     if (m_client)
@@ -449,7 +448,7 @@
     s_registeredLayerSet->remove(layer->id());
 }
 
-void GraphicsLayer::setContentsTo(ContentsLayerPurpose purpose, WebLayer* layer)
+void GraphicsLayer::setContentsTo(WebLayer* layer)
 {
     bool childrenChanged = false;
     if (layer) {
@@ -458,7 +457,6 @@
             CRASH();
         if (m_contentsLayerId != layer->id()) {
             setupContentsLayer(layer);
-            m_contentsLayerPurpose = purpose;
             childrenChanged = true;
         }
         updateContentsRect();
@@ -756,7 +754,7 @@
     return ts.release();
 }
 
-WebKit::WebString GraphicsLayer::debugName(WebKit::WebLayer* webLayer)
+blink::WebString GraphicsLayer::debugName(blink::WebLayer* webLayer)
 {
     String name;
     if (!m_client)
@@ -782,7 +780,7 @@
     return name;
 }
 
-void GraphicsLayer::setCompositingReasons(WebKit::WebCompositingReasons reasons)
+void GraphicsLayer::setCompositingReasons(blink::WebCompositingReasons reasons)
 {
     m_compositingReasons = reasons;
     m_layer->layer()->setCompositingReasons(reasons);
@@ -868,13 +866,13 @@
     updateLayerIsDrawable();
 }
 
-void GraphicsLayer::setClipParent(WebKit::WebLayer* parent)
+void GraphicsLayer::setClipParent(blink::WebLayer* parent)
 {
     m_hasClipParent = !!parent;
     m_layer->layer()->setClipParent(parent);
 }
 
-void GraphicsLayer::setScrollParent(WebKit::WebLayer* parent)
+void GraphicsLayer::setScrollParent(blink::WebLayer* parent)
 {
     m_hasScrollParent = !!parent;
     m_layer->layer()->setScrollParent(parent);
@@ -972,33 +970,23 @@
 
 void GraphicsLayer::setContentsToImage(Image* image)
 {
-    bool childrenChanged = false;
     RefPtr<NativeImageSkia> nativeImage = image ? image->nativeImageForCurrentFrame() : 0;
     if (nativeImage) {
-        if (m_contentsLayerPurpose != ContentsLayerForImage) {
+        if (!m_imageLayer) {
             m_imageLayer = adoptPtr(Platform::current()->compositorSupport()->createImageLayer());
             registerContentsLayer(m_imageLayer->layer());
-
-            setupContentsLayer(m_imageLayer->layer());
-            m_contentsLayerPurpose = ContentsLayerForImage;
-            childrenChanged = true;
         }
         m_imageLayer->setBitmap(nativeImage->bitmap());
         m_imageLayer->layer()->setOpaque(image->currentFrameKnownToBeOpaque());
         updateContentsRect();
     } else {
         if (m_imageLayer) {
-            childrenChanged = true;
-
             unregisterContentsLayer(m_imageLayer->layer());
             m_imageLayer.clear();
         }
-        // The old contents layer will be removed via updateChildList.
-        m_contentsLayer = 0;
     }
 
-    if (childrenChanged)
-        updateChildList();
+    setContentsTo(m_imageLayer ? m_imageLayer->layer() : 0);
 }
 
 void GraphicsLayer::setContentsToNinePatch(Image* image, const IntRect& aperture)
@@ -1014,17 +1002,7 @@
         m_ninePatchLayer->layer()->setOpaque(image->currentFrameKnownToBeOpaque());
         registerContentsLayer(m_ninePatchLayer->layer());
     }
-    setContentsTo(ContentsLayerForNinePatch, m_ninePatchLayer ? m_ninePatchLayer->layer() : 0);
-}
-
-void GraphicsLayer::setContentsToCanvas(WebLayer* layer)
-{
-    setContentsTo(ContentsLayerForCanvas, layer);
-}
-
-void GraphicsLayer::setContentsToMedia(WebLayer* layer)
-{
-    setContentsTo(ContentsLayerForVideo, layer);
+    setContentsTo(m_ninePatchLayer ? m_ninePatchLayer->layer() : 0);
 }
 
 bool GraphicsLayer::addAnimation(PassOwnPtr<WebAnimation> popAnimation)
@@ -1057,15 +1035,15 @@
 {
     for (size_t i = 0; i < filters.size(); ++i) {
         const FilterOperation& op = *filters.at(i);
-        switch (op.getOperationType()) {
+        switch (op.type()) {
         case FilterOperation::REFERENCE:
             return false; // Not supported.
         case FilterOperation::GRAYSCALE:
         case FilterOperation::SEPIA:
         case FilterOperation::SATURATE:
         case FilterOperation::HUE_ROTATE: {
-            float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
-            switch (op.getOperationType()) {
+            float amount = toBasicColorMatrixFilterOperation(op).amount();
+            switch (op.type()) {
             case FilterOperation::GRAYSCALE:
                 webFilters.appendGrayscaleFilter(amount);
                 break;
@@ -1087,8 +1065,8 @@
         case FilterOperation::OPACITY:
         case FilterOperation::BRIGHTNESS:
         case FilterOperation::CONTRAST: {
-            float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
-            switch (op.getOperationType()) {
+            float amount = toBasicComponentTransferFilterOperation(op).amount();
+            switch (op.type()) {
             case FilterOperation::INVERT:
                 webFilters.appendInvertFilter(amount);
                 break;
@@ -1107,12 +1085,12 @@
             break;
         }
         case FilterOperation::BLUR: {
-            float pixelRadius = static_cast<const BlurFilterOperation*>(&op)->stdDeviation().getFloatValue();
+            float pixelRadius = toBlurFilterOperation(op).stdDeviation().getFloatValue();
             webFilters.appendBlurFilter(pixelRadius);
             break;
         }
         case FilterOperation::DROP_SHADOW: {
-            const DropShadowFilterOperation& dropShadowOp = *static_cast<const DropShadowFilterOperation*>(&op);
+            const DropShadowFilterOperation& dropShadowOp = toDropShadowFilterOperation(op);
             webFilters.appendDropShadowFilter(WebPoint(dropShadowOp.x(), dropShadowOp.y()), dropShadowOp.stdDeviation(), dropShadowOp.color().rgb());
             break;
         }
diff --git a/Source/core/platform/graphics/GraphicsLayer.h b/Source/core/platform/graphics/GraphicsLayer.h
index 3f3d29f..5baa510 100644
--- a/Source/core/platform/graphics/GraphicsLayer.h
+++ b/Source/core/platform/graphics/GraphicsLayer.h
@@ -28,7 +28,7 @@
 #define GraphicsLayer_h
 
 #include "core/platform/graphics/GraphicsLayerClient.h"
-#include "core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h"
+#include "core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
 #include "platform/geometry/FloatPoint.h"
 #include "platform/geometry/FloatPoint3D.h"
@@ -49,7 +49,7 @@
 #include "public/platform/WebNinePatchLayer.h"
 #include "public/platform/WebSolidColorLayer.h"
 
-namespace WebKit {
+namespace blink {
 class GraphicsLayerFactoryChromium;
 class WebAnimation;
 class WebLayer;
@@ -69,7 +69,7 @@
 public:
     virtual void invalidate() = 0;
     virtual void clearCurrentGraphicsLayer() = 0;
-    virtual WebKit::WebLayer* layer() = 0;
+    virtual blink::WebLayer* layer() = 0;
 
 protected:
     virtual ~LinkHighlightClient() { }
@@ -78,28 +78,20 @@
 // GraphicsLayer is an abstraction for a rendering surface with backing store,
 // which may have associated transformation and animations.
 
-class GraphicsLayer : public GraphicsContextPainter, public WebKit::WebAnimationDelegate, public WebKit::WebLayerScrollClient, public WebKit::WebLayerClient {
+class GraphicsLayer : public GraphicsContextPainter, public blink::WebAnimationDelegate, public blink::WebLayerScrollClient, public blink::WebLayerClient {
     WTF_MAKE_NONCOPYABLE(GraphicsLayer); WTF_MAKE_FAST_ALLOCATED;
 public:
-    enum ContentsLayerPurpose {
-        NoContentsLayer = 0,
-        ContentsLayerForImage,
-        ContentsLayerForNinePatch,
-        ContentsLayerForVideo,
-        ContentsLayerForCanvas,
-    };
-
     static PassOwnPtr<GraphicsLayer> create(GraphicsLayerFactory*, GraphicsLayerClient*);
 
     virtual ~GraphicsLayer();
 
     GraphicsLayerClient* client() const { return m_client; }
 
-    // WebKit::WebLayerClient implementation.
-    virtual WebKit::WebString debugName(WebKit::WebLayer*) OVERRIDE;
+    // blink::WebLayerClient implementation.
+    virtual blink::WebString debugName(blink::WebLayer*) OVERRIDE;
 
-    void setCompositingReasons(WebKit::WebCompositingReasons);
-    WebKit::WebCompositingReasons compositingReasons() const { return m_compositingReasons; }
+    void setCompositingReasons(blink::WebCompositingReasons);
+    blink::WebCompositingReasons compositingReasons() const { return m_compositingReasons; }
 
     GraphicsLayer* parent() const { return m_parent; };
     void setParent(GraphicsLayer*); // Internal use only.
@@ -183,8 +175,8 @@
     bool contentsAreVisible() const { return m_contentsVisible; }
     void setContentsVisible(bool);
 
-    void setScrollParent(WebKit::WebLayer*);
-    void setClipParent(WebKit::WebLayer*);
+    void setScrollParent(blink::WebLayer*);
+    void setClipParent(blink::WebLayer*);
 
     // For special cases, e.g. drawing missing tiles on Android.
     // The compositor should never paint this color in normal cases because the RenderLayer
@@ -225,30 +217,25 @@
     // Return true if the animation is handled by the compositing system. If this returns
     // false, the animation will be run by AnimationController.
     // These methods handle both transitions and keyframe animations.
-    bool addAnimation(PassOwnPtr<WebKit::WebAnimation>);
+    bool addAnimation(PassOwnPtr<blink::WebAnimation>);
     void pauseAnimation(int animationId, double /*timeOffset*/);
     void removeAnimation(int animationId);
 
     // Layer contents
     void setContentsToImage(Image*);
     void setContentsToNinePatch(Image*, const IntRect& aperture);
-    bool shouldDirectlyCompositeImage(Image*) const { return true; }
-    void setContentsToMedia(WebKit::WebLayer*); // video or plug-in
     // Pass an invalid color to remove the contents layer.
     void setContentsToSolidColor(const Color&) { }
-    void setContentsToCanvas(WebKit::WebLayer*);
-    // FIXME: webkit.org/b/109658
-    // Should unify setContentsToMedia and setContentsToCanvas
-    void setContentsToPlatformLayer(WebKit::WebLayer* layer) { setContentsToMedia(layer); }
+    void setContentsToPlatformLayer(blink::WebLayer* layer) { setContentsTo(layer); }
     bool hasContentsLayer() const { return m_contentsLayer; }
 
     // Callback from the underlying graphics system to draw layer contents.
     void paintGraphicsLayerContents(GraphicsContext&, const IntRect& clip);
     // Callback from the underlying graphics system when the layer has been displayed
-    void layerDidDisplay(WebKit::WebLayer*) { }
+    void layerDidDisplay(blink::WebLayer*) { }
 
     // For hosting this GraphicsLayer in a native layer hierarchy.
-    WebKit::WebLayer* platformLayer() const;
+    blink::WebLayer* platformLayer() const;
 
     enum CompositingCoordinatesOrientation { CompositingCoordinatesTopDown, CompositingCoordinatesBottomUp };
 
@@ -297,13 +284,10 @@
     void setScrollableArea(ScrollableArea*, bool isMainFrame);
     ScrollableArea* scrollableArea() const { return m_scrollableArea; }
 
-    WebKit::WebContentLayer* contentLayer() const { return m_layer.get(); }
+    blink::WebContentLayer* contentLayer() const { return m_layer.get(); }
 
-    // Exposed for tests. FIXME - name is too similar to contentLayer(), very error prone.
-    WebKit::WebLayer* contentsLayer() const { return m_contentsLayer; }
-
-    static void registerContentsLayer(WebKit::WebLayer*);
-    static void unregisterContentsLayer(WebKit::WebLayer*);
+    static void registerContentsLayer(blink::WebLayer*);
+    static void unregisterContentsLayer(blink::WebLayer*);
 
     // GraphicsContextPainter implementation.
     virtual void paint(GraphicsContext&, const IntRect& clip) OVERRIDE;
@@ -318,7 +302,10 @@
 protected:
     explicit GraphicsLayer(GraphicsLayerClient*);
     // GraphicsLayerFactoryChromium that wants to create a GraphicsLayer need to be friends.
-    friend class WebKit::GraphicsLayerFactoryChromium;
+    friend class blink::GraphicsLayerFactoryChromium;
+
+    // Exposed for tests.
+    virtual blink::WebLayer* contentsLayer() const { return m_contentsLayer; }
 
 private:
     // Adds a child without calling updateChildList(), so that adding children
@@ -342,10 +329,10 @@
     void updateLayerIsDrawable();
     void updateContentsRect();
 
-    void setContentsTo(ContentsLayerPurpose, WebKit::WebLayer*);
-    void setupContentsLayer(WebKit::WebLayer*);
+    void setContentsTo(blink::WebLayer*);
+    void setupContentsLayer(blink::WebLayer*);
     void clearContentsLayerIfUnregistered();
-    WebKit::WebLayer* contentsLayerIfRegistered();
+    blink::WebLayer* contentsLayerIfRegistered();
 
     GraphicsLayerClient* m_client;
 
@@ -395,10 +382,10 @@
 
     int m_paintCount;
 
-    OwnPtr<WebKit::WebContentLayer> m_layer;
-    OwnPtr<WebKit::WebImageLayer> m_imageLayer;
-    OwnPtr<WebKit::WebNinePatchLayer> m_ninePatchLayer;
-    WebKit::WebLayer* m_contentsLayer;
+    OwnPtr<blink::WebContentLayer> m_layer;
+    OwnPtr<blink::WebImageLayer> m_imageLayer;
+    OwnPtr<blink::WebNinePatchLayer> m_ninePatchLayer;
+    blink::WebLayer* m_contentsLayer;
     // We don't have ownership of m_contentsLayer, but we do want to know if a given layer is the
     // same as our current layer in setContentsTo(). Since m_contentsLayer may be deleted at this point,
     // we stash an ID away when we know m_contentsLayer is alive and use that for comparisons from that point
@@ -409,10 +396,8 @@
 
     OwnPtr<OpaqueRectTrackingContentLayerDelegate> m_opaqueRectTrackingContentLayerDelegate;
 
-    ContentsLayerPurpose m_contentsLayerPurpose;
-
     ScrollableArea* m_scrollableArea;
-    WebKit::WebCompositingReasons m_compositingReasons;
+    blink::WebCompositingReasons m_compositingReasons;
 };
 
 
diff --git a/Source/core/platform/graphics/Image.cpp b/Source/core/platform/graphics/Image.cpp
index fd8bfd0..82b3ab0 100644
--- a/Source/core/platform/graphics/Image.cpp
+++ b/Source/core/platform/graphics/Image.cpp
@@ -27,11 +27,11 @@
 #include "config.h"
 #include "core/platform/graphics/Image.h"
 
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/graphics/BitmapImage.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "platform/Length.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/SharedBuffer.h"
 #include "platform/TraceEvent.h"
 #include "platform/geometry/FloatPoint.h"
@@ -60,13 +60,13 @@
 Image* Image::nullImage()
 {
     ASSERT(isMainThread());
-    DEFINE_STATIC_LOCAL(RefPtr<Image>, nullImage, (BitmapImage::create()));;
-    return nullImage.get();
+    DEFINE_STATIC_REF(Image, nullImage, (BitmapImage::create()));
+    return nullImage;
 }
 
 PassRefPtr<Image> Image::loadPlatformResource(const char *name)
 {
-    const WebKit::WebData& resource = WebKit::Platform::current()->loadResource(name);
+    const blink::WebData& resource = blink::Platform::current()->loadResource(name);
     if (resource.isEmpty())
         return Image::nullImage();
 
diff --git a/Source/core/platform/graphics/ImageBuffer.cpp b/Source/core/platform/graphics/ImageBuffer.cpp
index f481ec1..8f8682e 100644
--- a/Source/core/platform/graphics/ImageBuffer.cpp
+++ b/Source/core/platform/graphics/ImageBuffer.cpp
@@ -33,19 +33,20 @@
 #include "config.h"
 #include "core/platform/graphics/ImageBuffer.h"
 
-#include "core/html/ImageData.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/graphics/BitmapImage.h"
+#include "core/platform/graphics/Canvas2DLayerBridge.h"
 #include "core/platform/graphics/Extensions3D.h"
+#include "core/platform/graphics/GaneshUtils.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
+#include "core/platform/graphics/gpu/DrawingBuffer.h"
 #include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
 #include "core/platform/graphics/skia/SkiaUtils.h"
 #include "core/platform/image-encoders/skia/JPEGImageEncoder.h"
 #include "core/platform/image-encoders/skia/PNGImageEncoder.h"
 #include "core/platform/image-encoders/skia/WEBPImageEncoder.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/geometry/IntRect.h"
 #include "public/platform/Platform.h"
 #include "skia/ext/platform_canvas.h"
@@ -56,6 +57,7 @@
 #include "third_party/skia/include/effects/SkTableColorFilter.h"
 #include "third_party/skia/include/gpu/GrContext.h"
 #include "third_party/skia/include/gpu/SkGpuDevice.h"
+#include "third_party/skia/include/gpu/SkGrPixelRef.h"
 #include "wtf/MathExtras.h"
 #include "wtf/text/Base64.h"
 #include "wtf/text/WTFString.h"
@@ -76,6 +78,20 @@
     return (*outLayerBridge) ? (*outLayerBridge)->getCanvas() : 0;
 }
 
+static PassRefPtr<SkCanvas> createTextureBackedCanvas(const IntSize& size)
+{
+    RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
+    if (!context3D)
+        return 0;
+    GrContext* gr = context3D->grContext();
+    if (!gr)
+        return 0;
+    SkBitmap* bitmap = new SkBitmap;
+    if (!bitmap || !ensureTextureBackedSkBitmap(gr, *bitmap, size, kDefault_GrSurfaceOrigin, kRGBA_8888_GrPixelConfig))
+        return 0;
+    return adoptRef(new SkCanvas(*bitmap));
+}
+
 static PassRefPtr<SkCanvas> createNonPlatformCanvas(const IntSize& size)
 {
     SkAutoTUnref<SkBaseDevice> device(new SkBitmapDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height()));
@@ -92,6 +108,28 @@
     return buf.release();
 }
 
+PassOwnPtr<ImageBuffer> ImageBuffer::createBufferForTile(const FloatSize& tileSize, const FloatSize& clampedTileSize, RenderingMode renderingMode)
+{
+    IntSize imageSize(roundedIntSize(clampedTileSize));
+    IntSize unclampedImageSize(roundedIntSize(tileSize));
+
+    // Don't create empty ImageBuffers.
+    if (imageSize.isEmpty())
+        return nullptr;
+
+    OwnPtr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, renderingMode);
+    if (!image)
+        return nullptr;
+
+    GraphicsContext* imageContext = image->context();
+    ASSERT(imageContext);
+
+    // Compensate rounding effects, as the absolute target rect is using floating-point numbers and the image buffer size is integer.
+    imageContext->scale(FloatSize(unclampedImageSize.width() / tileSize.width(), unclampedImageSize.height() / tileSize.height()));
+
+    return image.release();
+}
+
 ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* compatibleContext, bool hasAlpha, bool& success)
     : m_size(size)
     , m_logicalSize(size)
@@ -133,6 +171,12 @@
             renderingMode = UnacceleratedNonPlatformBuffer;
     }
 
+    if (renderingMode == TextureBacked) {
+        m_canvas = createTextureBackedCanvas(size);
+        if (!m_canvas)
+            renderingMode = UnacceleratedNonPlatformBuffer;
+    }
+
     if (renderingMode == UnacceleratedNonPlatformBuffer)
         m_canvas = createNonPlatformCanvas(size);
 
@@ -152,10 +196,12 @@
     // Clear the background transparent or opaque, as required. It would be nice if this wasn't
     // required, but the canvas is currently filled with the magic transparency
     // color. Can we have another way to manage this?
-    if (opacityMode == Opaque)
-        m_canvas->drawARGB(255, 0, 0, 0, SkXfermode::kSrc_Mode);
-    else
-        m_canvas->drawARGB(0, 0, 0, 0, SkXfermode::kClear_Mode);
+    if (renderingMode != TextureBacked) {
+        if (opacityMode == Opaque)
+            m_canvas->drawARGB(255, 0, 0, 0, SkXfermode::kSrc_Mode);
+        else
+            m_canvas->drawARGB(0, 0, 0, 0, SkXfermode::kClear_Mode);
+    }
 
     success = true;
 }
@@ -206,7 +252,7 @@
     return DontCopyBackingStore;
 }
 
-WebKit::WebLayer* ImageBuffer::platformLayer() const
+blink::WebLayer* ImageBuffer::platformLayer() const
 {
     return m_layerBridge ? m_layerBridge->layer() : 0;
 }
@@ -245,6 +291,29 @@
     return (src == dst);
 }
 
+Platform3DObject ImageBuffer::getBackingTexture()
+{
+    if (!m_context || !m_context->bitmap())
+        return 0;
+    const SkBitmap& bitmap = *m_context->bitmap();
+    if (bitmap.getTexture())
+        return (bitmap.getTexture())->getTextureHandle();
+    return 0;
+}
+
+bool ImageBuffer::copyRenderingResultsFromDrawingBuffer(DrawingBuffer* drawingBuffer)
+{
+    if (!drawingBuffer)
+        return false;
+    RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
+    Platform3DObject tex = getBackingTexture();
+    if (!context3D || !tex)
+        return false;
+
+    return drawingBuffer->copyToPlatformTexture(*(context3D.get()), tex, GraphicsContext3D::RGBA,
+        GraphicsContext3D::UNSIGNED_BYTE, 0, true, false);
+}
+
 void ImageBuffer::draw(GraphicsContext* context, const FloatRect& destRect, const FloatRect& srcRect,
     CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
 {
@@ -484,7 +553,7 @@
     return "data:" + mimeType + ";base64," + base64Data;
 }
 
-String ImageDataToDataURL(const ImageData& imageData, const String& mimeType, const double* quality)
+String ImageDataToDataURL(const ImageDataBuffer& imageData, const String& mimeType, const double* quality)
 {
     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
 
diff --git a/Source/core/platform/graphics/ImageBuffer.h b/Source/core/platform/graphics/ImageBuffer.h
index edc8a65..0e5da98 100644
--- a/Source/core/platform/graphics/ImageBuffer.h
+++ b/Source/core/platform/graphics/ImageBuffer.h
@@ -29,7 +29,7 @@
 #define ImageBuffer_h
 
 #include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
+#include "core/platform/graphics/Canvas2DLayerBridge.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/geometry/IntSize.h"
 #include "platform/graphics/ColorSpace.h"
@@ -45,12 +45,11 @@
 
 class SkCanvas;
 
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
 
 namespace WebCore {
 
 class Image;
-class ImageData;
 class IntPoint;
 class IntRect;
 class GraphicsContext3D;
@@ -63,7 +62,8 @@
 enum RenderingMode {
     Unaccelerated,
     UnacceleratedNonPlatformBuffer, // Use plain memory allocation rather than platform API to allocate backing store.
-    Accelerated
+    TextureBacked, // Allocate a texture-based SkBitmap for the backing store.
+    Accelerated, // Besides a texture-based SkBitmap for the backing store, allocate Canvas2DLayerBridge, etc as well for 2D Canvas drawing.
 };
 
 enum BackingStoreCopy {
@@ -96,6 +96,9 @@
 
     static PassOwnPtr<ImageBuffer> createCompatibleBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha);
 
+    // Tiles may need float-to-integer coordinate mapping.
+    static PassOwnPtr<ImageBuffer> createBufferForTile(const FloatSize& tileSize, const FloatSize& clampedTileSize, RenderingMode);
+
     ~ImageBuffer();
 
     // The actual resolution of the backing store
@@ -119,13 +122,16 @@
     String toDataURL(const String& mimeType, const double* quality = 0, CoordinateSystem = LogicalCoordinateSystem) const;
     AffineTransform baseTransform() const { return AffineTransform(); }
     void transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace);
-    WebKit::WebLayer* platformLayer() const;
+    blink::WebLayer* platformLayer() const;
 
     // FIXME: current implementations of this method have the restriction that they only work
     // with textures that are RGB or RGBA format, UNSIGNED_BYTE type and level 0, as specified in
     // Extensions3D::canUseCopyTextureCHROMIUM().
     bool copyToPlatformTexture(GraphicsContext3D&, Platform3DObject, GC3Denum, GC3Denum, GC3Dint, bool, bool);
 
+    Platform3DObject getBackingTexture();
+    bool copyRenderingResultsFromDrawingBuffer(DrawingBuffer*);
+
 private:
     bool isValid() const;
 
@@ -152,7 +158,16 @@
     ImageBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha, bool& success);
 };
 
-String ImageDataToDataURL(const ImageData&, const String& mimeType, const double* quality);
+struct ImageDataBuffer {
+    ImageDataBuffer(const IntSize& size, PassRefPtr<Uint8ClampedArray> data) : m_size(size), m_data(data) { }
+    IntSize size() const { return m_size; }
+    unsigned char* data() const { return m_data->data(); }
+
+    IntSize m_size;
+    RefPtr<Uint8ClampedArray> m_data;
+};
+
+String ImageDataToDataURL(const ImageDataBuffer&, const String& mimeType, const double* quality);
 
 } // namespace WebCore
 
diff --git a/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp b/Source/core/platform/graphics/ImageDecodingStore.cpp
similarity index 97%
rename from Source/core/platform/graphics/chromium/ImageDecodingStore.cpp
rename to Source/core/platform/graphics/ImageDecodingStore.cpp
index f8744b3..d9aae41 100644
--- a/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp
+++ b/Source/core/platform/graphics/ImageDecodingStore.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
+#include "core/platform/graphics/ImageDecodingStore.h"
 
 #include "platform/TraceEvent.h"
 #include "platform/graphics/ScaledImageFragment.h"
@@ -98,7 +98,7 @@
     MutexLocker lock(m_mutex);
     cachedImage->bitmap().unlockPixels();
     ImageCacheMap::iterator iter = m_imageCacheMap.find(ImageCacheEntry::makeCacheKey(generator, cachedImage->scaledSize(), cachedImage->index(), cachedImage->generation()));
-    ASSERT(iter != m_imageCacheMap.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(iter != m_imageCacheMap.end());
 
     CacheEntry* cacheEntry = iter->value.get();
     cacheEntry->decrementUseCount();
@@ -162,7 +162,7 @@
 {
     MutexLocker lock(m_mutex);
     DecoderCacheMap::iterator iter = m_decoderCacheMap.find(DecoderCacheEntry::makeCacheKey(generator, decoder));
-    ASSERT(iter != m_decoderCacheMap.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(iter != m_decoderCacheMap.end());
 
     CacheEntry* cacheEntry = iter->value.get();
     cacheEntry->decrementUseCount();
@@ -190,7 +190,7 @@
     {
         MutexLocker lock(m_mutex);
         DecoderCacheMap::iterator iter = m_decoderCacheMap.find(DecoderCacheEntry::makeCacheKey(generator, decoder));
-        ASSERT(iter != m_decoderCacheMap.end());
+        ASSERT_WITH_SECURITY_IMPLICATION(iter != m_decoderCacheMap.end());
 
         CacheEntry* cacheEntry = iter->value.get();
         ASSERT(cacheEntry->useCount());
diff --git a/Source/core/platform/graphics/chromium/ImageDecodingStore.h b/Source/core/platform/graphics/ImageDecodingStore.h
similarity index 98%
rename from Source/core/platform/graphics/chromium/ImageDecodingStore.h
rename to Source/core/platform/graphics/ImageDecodingStore.h
index 370146b..77c2485 100644
--- a/Source/core/platform/graphics/chromium/ImageDecodingStore.h
+++ b/Source/core/platform/graphics/ImageDecodingStore.h
@@ -28,10 +28,10 @@
 
 #include "SkSize.h"
 #include "SkTypes.h"
-#include "core/platform/graphics/chromium/DiscardablePixelRef.h"
-#include "core/platform/graphics/chromium/SkSizeHash.h"
+#include "core/platform/graphics/DiscardablePixelRef.h"
 #include "core/platform/image-decoders/ImageDecoder.h"
 #include "platform/graphics/ScaledImageFragment.h"
+#include "platform/graphics/SkSizeHash.h"
 
 #include "wtf/DoublyLinkedList.h"
 #include "wtf/HashSet.h"
diff --git a/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp b/Source/core/platform/graphics/ImageDecodingStoreTest.cpp
similarity index 98%
rename from Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp
rename to Source/core/platform/graphics/ImageDecodingStoreTest.cpp
index 9b70cce..9c2bf7c 100644
--- a/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp
+++ b/Source/core/platform/graphics/ImageDecodingStoreTest.cpp
@@ -25,12 +25,12 @@
 
 #include "config.h"
 
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
+#include "core/platform/graphics/ImageDecodingStore.h"
 
 #include "platform/SharedBuffer.h"
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
-#include "core/platform/graphics/chromium/test/MockDiscardablePixelRef.h"
-#include "core/platform/graphics/chromium/test/MockImageDecoder.h"
+#include "core/platform/graphics/ImageFrameGenerator.h"
+#include "core/platform/graphics/test/MockDiscardablePixelRef.h"
+#include "core/platform/graphics/test/MockImageDecoder.h"
 #include <gtest/gtest.h>
 
 using namespace WebCore;
diff --git a/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp b/Source/core/platform/graphics/ImageFrameGenerator.cpp
similarity index 97%
rename from Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp
rename to Source/core/platform/graphics/ImageFrameGenerator.cpp
index ae1ae25..0b2f758 100644
--- a/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp
+++ b/Source/core/platform/graphics/ImageFrameGenerator.cpp
@@ -25,10 +25,10 @@
 
 #include "config.h"
 
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
+#include "core/platform/graphics/ImageFrameGenerator.h"
 
-#include "core/platform/graphics/chromium/DiscardablePixelRef.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
+#include "core/platform/graphics/DiscardablePixelRef.h"
+#include "core/platform/graphics/ImageDecodingStore.h"
 #include "core/platform/image-decoders/ImageDecoder.h"
 #include "platform/SharedBuffer.h"
 #include "platform/TraceEvent.h"
diff --git a/Source/core/platform/graphics/chromium/ImageFrameGenerator.h b/Source/core/platform/graphics/ImageFrameGenerator.h
similarity index 100%
rename from Source/core/platform/graphics/chromium/ImageFrameGenerator.h
rename to Source/core/platform/graphics/ImageFrameGenerator.h
diff --git a/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp b/Source/core/platform/graphics/ImageFrameGeneratorTest.cpp
similarity index 98%
rename from Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
rename to Source/core/platform/graphics/ImageFrameGeneratorTest.cpp
index c5e9f6c..8c248c7 100644
--- a/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
+++ b/Source/core/platform/graphics/ImageFrameGeneratorTest.cpp
@@ -24,10 +24,10 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
+#include "core/platform/graphics/ImageFrameGenerator.h"
 
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-#include "core/platform/graphics/chromium/test/MockImageDecoder.h"
+#include "core/platform/graphics/ImageDecodingStore.h"
+#include "core/platform/graphics/test/MockImageDecoder.h"
 #include "platform/SharedBuffer.h"
 #include "platform/Task.h"
 #include "public/platform/Platform.h"
@@ -327,7 +327,7 @@
     // Frame can now be decoded completely.
     setFrameStatus(ImageFrame::FrameComplete);
     addNewData();
-    OwnPtr<WebKit::WebThread> thread = adoptPtr(WebKit::Platform::current()->createThread("DecodeThread"));
+    OwnPtr<blink::WebThread> thread = adoptPtr(blink::Platform::current()->createThread("DecodeThread"));
     thread->postTask(new Task(WTF::bind(&decodeThreadMain, m_generator.get())));
     thread.clear();
 
diff --git a/Source/core/platform/graphics/ImageObserver.h b/Source/core/platform/graphics/ImageObserver.h
deleted file mode 100644
index 5db6a9e..0000000
--- a/Source/core/platform/graphics/ImageObserver.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, 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 ImageObserver_h
-#define ImageObserver_h
-
-namespace WebCore {
-
-class Image;
-class IntRect;
-
-// Interface for notification about changes to an image, including decoding,
-// drawing, and animating.
-class ImageObserver {
-protected:
-    virtual ~ImageObserver() {}
-public:
-    virtual void decodedSizeChanged(const Image*, int delta) = 0;
-    virtual void didDraw(const Image*) = 0;
-
-    virtual bool shouldPauseAnimation(const Image*) = 0;
-    virtual void animationAdvanced(const Image*) = 0;
-
-    virtual void changedInRect(const Image*, const IntRect&) = 0;
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/graphics/ImageSource.cpp b/Source/core/platform/graphics/ImageSource.cpp
index 7839aa5..1e9dfdc 100644
--- a/Source/core/platform/graphics/ImageSource.cpp
+++ b/Source/core/platform/graphics/ImageSource.cpp
@@ -28,7 +28,7 @@
 #include "config.h"
 #include "core/platform/graphics/ImageSource.h"
 
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
+#include "core/platform/graphics/DeferredImageDecoder.h"
 #include "core/platform/image-decoders/ImageDecoder.h"
 #include "platform/graphics/ImageOrientation.h"
 #include "wtf/PassOwnPtr.h"
diff --git a/Source/core/platform/graphics/InbandTextTrackPrivate.h b/Source/core/platform/graphics/InbandTextTrackPrivate.h
deleted file mode 100644
index 9492d8a..0000000
--- a/Source/core/platform/graphics/InbandTextTrackPrivate.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2012 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 InbandTextTrackPrivate_h
-#define InbandTextTrackPrivate_h
-
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class InbandTextTrackPrivateClient;
-
-class InbandTextTrackPrivate : public RefCounted<InbandTextTrackPrivate> {
-    WTF_MAKE_NONCOPYABLE(InbandTextTrackPrivate); WTF_MAKE_FAST_ALLOCATED;
-public:
-    static PassRefPtr<InbandTextTrackPrivate> create()
-    {
-        return adoptRef(new InbandTextTrackPrivate());
-    }
-    virtual ~InbandTextTrackPrivate() { }
-
-    void setClient(InbandTextTrackPrivateClient* client) { m_client = client; }
-    InbandTextTrackPrivateClient* client() { return m_client; }
-
-    enum Mode { Disabled, Hidden, Showing };
-    virtual void setMode(Mode mode) { m_mode = mode; };
-    virtual InbandTextTrackPrivate::Mode mode() const { return m_mode; }
-
-    enum Kind { Subtitles, Captions, Descriptions, Chapters, Metadata, None };
-    virtual Kind kind() const { return Subtitles; }
-    virtual bool isClosedCaptions() const { return false; }
-    virtual bool containsOnlyForcedSubtitles() const { return false; }
-    virtual bool isMainProgramContent() const { return true; }
-    virtual bool isEasyToRead() const { return false; }
-
-    virtual AtomicString label() const { return emptyAtom; }
-    virtual AtomicString language() const { return emptyAtom; }
-    virtual bool isDefault() const { return false; }
-
-    virtual int textTrackIndex() const { return 0; }
-
-protected:
-    InbandTextTrackPrivate()
-        : m_client(0)
-        , m_mode(Disabled)
-    {
-    }
-
-private:
-    InbandTextTrackPrivateClient* m_client;
-    Mode m_mode;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/graphics/InbandTextTrackPrivateClient.h b/Source/core/platform/graphics/InbandTextTrackPrivateClient.h
deleted file mode 100644
index 2382311..0000000
--- a/Source/core/platform/graphics/InbandTextTrackPrivateClient.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012, 2013 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 InbandTextTrackPrivateClient_h
-#define InbandTextTrackPrivateClient_h
-
-#include "platform/graphics/Color.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class InbandTextTrackPrivate;
-
-class InbandTextTrackPrivateClient {
-public:
-    virtual ~InbandTextTrackPrivateClient() { }
-
-    virtual void addWebVTTCue(InbandTextTrackPrivate*, double /*start*/, double /*end*/, const String& /*id*/, const String& /*content*/, const String& /*settings*/) = 0;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/graphics/IntSizeHash.h b/Source/core/platform/graphics/IntSizeHash.h
deleted file mode 100644
index c80f4d2..0000000
--- a/Source/core/platform/graphics/IntSizeHash.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2006, 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.
- *
- */
-#ifndef IntSizeHash_h
-#define IntSizeHash_h
-
-#include "platform/geometry/IntSize.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-
-namespace WTF {
-
-template<> struct IntHash<WebCore::IntSize> {
-    static unsigned hash(const WebCore::IntSize& key) { return pairIntHash(key.width(), key.height()); }
-    static bool equal(const WebCore::IntSize& a, const WebCore::IntSize& b) { return a == b; }
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-template<> struct DefaultHash<WebCore::IntSize> {
-    typedef IntHash<WebCore::IntSize> Hash;
-};
-
-template<> struct HashTraits<WebCore::IntSize> : GenericHashTraits<WebCore::IntSize> {
-    static const bool emptyValueIsZero = true;
-    static const bool needsDestruction = false;
-    static void constructDeletedValue(WebCore::IntSize& slot) { new (NotNull, &slot) WebCore::IntSize(-1, -1); }
-    static bool isDeletedValue(const WebCore::IntSize& value) { return value.width() == -1 && value.height() == -1; }
-};
-
-} // namespace WTF
-
-#endif
diff --git a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp b/Source/core/platform/graphics/LazyDecodingPixelRef.cpp
similarity index 76%
rename from Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp
rename to Source/core/platform/graphics/LazyDecodingPixelRef.cpp
index 26cfa18..4bc3c71 100644
--- a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp
+++ b/Source/core/platform/graphics/LazyDecodingPixelRef.cpp
@@ -24,20 +24,18 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/LazyDecodingPixelRef.h"
+#include "core/platform/graphics/LazyDecodingPixelRef.h"
 
 #include "SkData.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
+#include "core/platform/graphics/ImageDecodingStore.h"
+#include "core/platform/graphics/ImageFrameGenerator.h"
 #include "platform/TraceEvent.h"
 
 namespace WebCore {
 
-LazyDecodingPixelRef::LazyDecodingPixelRef(PassRefPtr<ImageFrameGenerator> frameGenerator, const SkISize& scaledSize, size_t index, const SkIRect& scaledSubset)
+LazyDecodingPixelRef::LazyDecodingPixelRef(PassRefPtr<ImageFrameGenerator> frameGenerator, size_t index)
     : m_frameGenerator(frameGenerator)
     , m_frameIndex(index)
-    , m_scaledSize(scaledSize)
-    , m_scaledSubset(scaledSubset)
     , m_lockedImageResource(0)
     , m_objectTracker(this)
 {
@@ -47,22 +45,10 @@
 {
 }
 
-bool LazyDecodingPixelRef::isScaled(const SkISize& fullSize) const
-{
-    return fullSize != m_scaledSize;
-}
-
-bool LazyDecodingPixelRef::isClipped() const
-{
-    return m_scaledSize.width() != m_scaledSubset.width() || m_scaledSize.height() != m_scaledSubset.height();
-}
-
 SkData* LazyDecodingPixelRef::onRefEncodedData()
 {
     // If the image has been clipped or scaled, do not return the original encoded data, since
     // on playback it will not be known how the clipping/scaling was done.
-    if (isClipped() || isScaled(m_frameGenerator->getFullSize()))
-        return 0;
     RefPtr<SharedBuffer> buffer = 0;
     bool allDataReceived = false;
     m_frameGenerator->copyData(&buffer, &allDataReceived);
@@ -79,20 +65,23 @@
 
     ASSERT(!m_lockedImageResource);
 
-    if (!ImageDecodingStore::instance()->lockCache(m_frameGenerator.get(), m_scaledSize, m_frameIndex, &m_lockedImageResource))
+    SkISize size = m_frameGenerator->getFullSize();
+    if (!ImageDecodingStore::instance()->lockCache(m_frameGenerator.get(), size, m_frameIndex, &m_lockedImageResource))
         m_lockedImageResource = 0;
 
     // Use ImageFrameGenerator to generate the image. It will lock the cache
     // entry for us.
-    if (!m_lockedImageResource)
-        m_lockedImageResource = m_frameGenerator->decodeAndScale(m_scaledSize, m_frameIndex);
-
+    if (!m_lockedImageResource) {
+        PlatformInstrumentation::willDecodeLazyPixelRef(reinterpret_cast<unsigned long long>(this));
+        m_lockedImageResource = m_frameGenerator->decodeAndScale(size, m_frameIndex);
+        PlatformInstrumentation::didDecodeLazyPixelRef(reinterpret_cast<unsigned long long>(this));
+    }
     if (!m_lockedImageResource)
         return 0;
 
     ASSERT(!m_lockedImageResource->bitmap().isNull());
-    ASSERT(m_lockedImageResource->scaledSize() == m_scaledSize);
-    return m_lockedImageResource->bitmap().getAddr(m_scaledSubset.x(), m_scaledSubset.y());
+    ASSERT(m_lockedImageResource->scaledSize() == size);
+    return m_lockedImageResource->bitmap().getAddr(0, 0);
 }
 
 void LazyDecodingPixelRef::onUnlockPixels()
@@ -112,7 +101,7 @@
 
 bool LazyDecodingPixelRef::MaybeDecoded()
 {
-    return ImageDecodingStore::instance()->isCached(m_frameGenerator.get(), m_scaledSize, m_frameIndex);
+    return ImageDecodingStore::instance()->isCached(m_frameGenerator.get(), m_frameGenerator->getFullSize(), m_frameIndex);
 }
 
 bool LazyDecodingPixelRef::PrepareToDecode(const LazyPixelRef::PrepareParams& params)
@@ -128,4 +117,4 @@
 }
 
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h b/Source/core/platform/graphics/LazyDecodingPixelRef.h
similarity index 89%
rename from Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h
rename to Source/core/platform/graphics/LazyDecodingPixelRef.h
index 48d8015..7c9cbdd 100644
--- a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h
+++ b/Source/core/platform/graphics/LazyDecodingPixelRef.h
@@ -31,7 +31,7 @@
 #include "SkRect.h"
 #include "SkSize.h"
 #include "SkTypes.h"
-#include "core/platform/PlatformInstrumentation.h"
+#include "platform/PlatformInstrumentation.h"
 #include "skia/ext/lazy_pixel_ref.h"
 
 #include "wtf/RefPtr.h"
@@ -47,15 +47,13 @@
 
 class LazyDecodingPixelRef : public LazyPixelRef {
 public:
-    LazyDecodingPixelRef(PassRefPtr<ImageFrameGenerator>, const SkISize& scaledSize, size_t index, const SkIRect& scaledSubset);
+    LazyDecodingPixelRef(PassRefPtr<ImageFrameGenerator>, size_t index);
     virtual ~LazyDecodingPixelRef();
 
     SK_DECLARE_UNFLATTENABLE_OBJECT()
 
     PassRefPtr<ImageFrameGenerator> frameGenerator() const { return m_frameGenerator; }
     size_t frameIndex() const { return m_frameIndex; }
-    bool isScaled(const SkISize& fullSize) const;
-    bool isClipped() const;
 
     // Returns true if the image might already be decoded in the cache.
     // Optimistic version of PrepareToDecode; requires less locking.
@@ -74,8 +72,6 @@
 private:
     RefPtr<ImageFrameGenerator> m_frameGenerator;
     size_t m_frameIndex;
-    SkISize m_scaledSize;
-    SkIRect m_scaledSubset;
 
     const ScaledImageFragment* m_lockedImageResource;
     PlatformInstrumentation::LazyPixelRefTracker m_objectTracker;
diff --git a/Source/core/platform/graphics/MediaPlayer.cpp b/Source/core/platform/graphics/MediaPlayer.cpp
deleted file mode 100644
index 5d5a379..0000000
--- a/Source/core/platform/graphics/MediaPlayer.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 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.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/MediaPlayer.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-static CreateMediaEnginePlayer createMediaEngineFunction = 0;
-
-void MediaPlayer::setMediaEngineCreateFunction(CreateMediaEnginePlayer createFunction)
-{
-    ASSERT(createFunction);
-    ASSERT(!createMediaEngineFunction);
-    createMediaEngineFunction = createFunction;
-}
-
-PassOwnPtr<MediaPlayer> MediaPlayer::create(MediaPlayerClient* client)
-{
-    ASSERT(createMediaEngineFunction);
-    return createMediaEngineFunction(client);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/MediaPlayer.h b/Source/core/platform/graphics/MediaPlayer.h
deleted file mode 100644
index 3c9fc2c..0000000
--- a/Source/core/platform/graphics/MediaPlayer.h
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 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 MediaPlayer_h
-#define MediaPlayer_h
-
-#include "platform/graphics/GraphicsTypes3D.h"
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebKit { class WebLayer; }
-
-namespace WebCore {
-
-class AudioSourceProvider;
-class GraphicsContext;
-class GraphicsContext3D;
-class InbandTextTrackPrivate;
-class IntRect;
-class IntSize;
-class KURL;
-class MediaPlayer;
-class HTMLMediaSource;
-class TimeRanges;
-
-class MediaPlayerClient {
-public:
-    enum CORSMode { Unspecified, Anonymous, UseCredentials };
-
-    virtual ~MediaPlayerClient() { }
-
-    // the network state has changed
-    virtual void mediaPlayerNetworkStateChanged() = 0;
-
-    // the ready state has changed
-    virtual void mediaPlayerReadyStateChanged() = 0;
-
-    // time has jumped, eg. not as a result of normal playback
-    virtual void mediaPlayerTimeChanged() = 0;
-
-    // the media file duration has changed, or is now known
-    virtual void mediaPlayerDurationChanged() = 0;
-
-    // the play/pause status changed
-    virtual void mediaPlayerPlaybackStateChanged() = 0;
-
-    virtual void mediaPlayerRequestFullscreen() = 0;
-
-    virtual void mediaPlayerRequestSeek(double) = 0;
-
-// Presentation-related methods
-    // a new frame of video is available
-    virtual void mediaPlayerRepaint() = 0;
-
-    // the movie size has changed
-    virtual void mediaPlayerSizeChanged() = 0;
-
-    virtual void mediaPlayerEngineUpdated() = 0;
-
-    enum MediaKeyErrorCode { UnknownError = 1, ClientError, ServiceError, OutputError, HardwareChangeError, DomainError };
-    virtual void mediaPlayerKeyAdded(const String& /* keySystem */, const String& /* sessionId */) = 0;
-    virtual void mediaPlayerKeyError(const String& /* keySystem */, const String& /* sessionId */, MediaKeyErrorCode, unsigned short /* systemCode */) = 0;
-    virtual void mediaPlayerKeyMessage(const String& /* keySystem */, const String& /* sessionId */, const unsigned char* /* message */, unsigned /* messageLength */, const KURL& /* defaultURL */) = 0;
-    virtual bool mediaPlayerKeyNeeded(const String& /* keySystem */, const String& /* sessionId */, const unsigned char* /* initData */, unsigned /* initDataLength */) = 0;
-
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-    virtual bool mediaPlayerKeyNeeded(Uint8Array*) = 0;
-#endif
-
-    virtual CORSMode mediaPlayerCORSMode() const = 0;
-
-    virtual void mediaPlayerScheduleLayerUpdate() = 0;
-
-    virtual void mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate>) = 0;
-    virtual void mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPrivate>) = 0;
-};
-
-typedef PassOwnPtr<MediaPlayer> (*CreateMediaEnginePlayer)(MediaPlayerClient*);
-
-class MediaPlayer {
-    WTF_MAKE_NONCOPYABLE(MediaPlayer);
-public:
-    static PassOwnPtr<MediaPlayer> create(MediaPlayerClient*);
-    static void setMediaEngineCreateFunction(CreateMediaEnginePlayer);
-
-    static double invalidTime() { return -1.0; }
-
-    MediaPlayer() { }
-    virtual ~MediaPlayer() { }
-
-    virtual void load(const String& url) = 0;
-    virtual void load(const String& url, PassRefPtr<HTMLMediaSource>) = 0;
-
-    virtual void prepareToPlay() = 0;
-    virtual WebKit::WebLayer* platformLayer() const = 0;
-
-    virtual void play() = 0;
-    virtual void pause() = 0;
-
-    virtual bool supportsFullscreen() const = 0;
-    virtual bool supportsSave() const = 0;
-    virtual IntSize naturalSize() const = 0;
-
-    virtual bool hasVideo() const = 0;
-    virtual bool hasAudio() const = 0;
-
-    virtual double duration() const = 0;
-
-    virtual double currentTime() const = 0;
-
-    virtual void seek(double) = 0;
-
-    virtual bool seeking() const = 0;
-
-    virtual double rate() const = 0;
-    virtual void setRate(double) = 0;
-
-    virtual bool paused() const = 0;
-
-    virtual void setVolume(double) = 0;
-    virtual void setMuted(bool) = 0;
-
-    enum NetworkState { Empty, Idle, Loading, Loaded, FormatError, NetworkError, DecodeError };
-    virtual NetworkState networkState() const = 0;
-
-    enum ReadyState  { HaveNothing, HaveMetadata, HaveCurrentData, HaveFutureData, HaveEnoughData };
-    virtual ReadyState readyState() const = 0;
-
-    virtual double maxTimeSeekable() const = 0;
-    virtual PassRefPtr<TimeRanges> buffered() const = 0;
-
-    virtual bool didLoadingProgress() const = 0;
-
-    virtual void paint(GraphicsContext*, const IntRect&) = 0;
-
-    virtual void paintCurrentFrameInContext(GraphicsContext*, const IntRect&) = 0;
-    virtual bool copyVideoTextureToPlatformTexture(GraphicsContext3D*, Platform3DObject, GC3Dint, GC3Denum, GC3Denum, bool, bool) = 0;
-
-    enum Preload { None, MetaData, Auto };
-    virtual void setPreload(Preload) = 0;
-
-    virtual void showFullscreenOverlay() = 0;
-    virtual void hideFullscreenOverlay() = 0;
-    virtual bool canShowFullscreenOverlay() const = 0;
-
-    // whether accelerated rendering is supported by the media engine for the current media.
-    virtual bool supportsAcceleratedRendering() const = 0;
-
-    virtual bool hasSingleSecurityOrigin() const = 0;
-
-    virtual bool didPassCORSAccessCheck() const = 0;
-
-    // Time value in the movie's time scale. It is only necessary to override this if the media
-    // engine uses rational numbers to represent media time.
-    virtual double mediaTimeForTimeValue(double timeValue) const = 0;
-
-    virtual unsigned decodedFrameCount() const = 0;
-    virtual unsigned droppedFrameCount() const = 0;
-    virtual unsigned corruptedFrameCount() const = 0;
-    virtual unsigned audioDecodedByteCount() const = 0;
-    virtual unsigned videoDecodedByteCount() const = 0;
-
-#if ENABLE(WEB_AUDIO)
-    virtual AudioSourceProvider* audioSourceProvider() = 0;
-#endif
-
-    enum MediaKeyException { NoError, InvalidPlayerState, KeySystemNotSupported };
-    virtual MediaKeyException addKey(const String&, const unsigned char*, unsigned, const unsigned char*, unsigned, const String&) = 0;
-    virtual MediaKeyException generateKeyRequest(const String&, const unsigned char*, unsigned) = 0;
-    virtual MediaKeyException cancelKeyRequest(const String&, const String&) = 0;
-};
-
-}
-
-#endif // MediaPlayer_h
diff --git a/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp b/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp
similarity index 95%
rename from Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp
rename to Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp
index fc0f0cf..3fed148 100644
--- a/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp
+++ b/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp
@@ -24,7 +24,7 @@
 
 #include "config.h"
 
-#include "core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h"
+#include "core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.h"
 
 #include "core/platform/graphics/GraphicsContext.h"
 #include "platform/EventTracer.h"
@@ -33,8 +33,8 @@
 #include "public/platform/WebFloatRect.h"
 #include "public/platform/WebRect.h"
 
-using WebKit::WebFloatRect;
-using WebKit::WebRect;
+using blink::WebFloatRect;
+using blink::WebRect;
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h b/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.h
similarity index 89%
rename from Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h
rename to Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.h
index e83ce93..8aece87 100644
--- a/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h
+++ b/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.h
@@ -44,7 +44,7 @@
     virtual ~GraphicsContextPainter() { }
 };
 
-class OpaqueRectTrackingContentLayerDelegate : public WebKit::WebContentLayerClient {
+class OpaqueRectTrackingContentLayerDelegate : public blink::WebContentLayerClient {
     WTF_MAKE_NONCOPYABLE(OpaqueRectTrackingContentLayerDelegate);
 public:
     explicit OpaqueRectTrackingContentLayerDelegate(GraphicsContextPainter*);
@@ -54,8 +54,8 @@
     // tracking opaqueness.
     void setOpaque(bool opaque) { m_opaque = opaque; }
 
-    // WebKit::WebContentLayerClient implementation.
-    virtual void paintContents(SkCanvas*, const WebKit::WebRect& clip, bool canPaintLCDText, WebKit::WebFloatRect& opaque) OVERRIDE;
+    // blink::WebContentLayerClient implementation.
+    virtual void paintContents(SkCanvas*, const blink::WebRect& clip, bool canPaintLCDText, blink::WebFloatRect& opaque) OVERRIDE;
 
 private:
     GraphicsContextPainter* m_painter;
diff --git a/Source/core/platform/graphics/Pattern.cpp b/Source/core/platform/graphics/Pattern.cpp
index 61ae7ce..3de80d9 100644
--- a/Source/core/platform/graphics/Pattern.cpp
+++ b/Source/core/platform/graphics/Pattern.cpp
@@ -42,8 +42,9 @@
     , m_repeatY(repeatY)
     , m_externalMemoryAllocated(0)
 {
-    ASSERT(image);
-    m_tileImage = image->nativeImageForCurrentFrame();
+    if (image) {
+        m_tileImage = image->nativeImageForCurrentFrame();
+    }
 }
 
 Pattern::~Pattern()
diff --git a/Source/core/platform/graphics/SimpleFontData.cpp b/Source/core/platform/graphics/SimpleFontData.cpp
index 8dcc30f..1772a2a 100644
--- a/Source/core/platform/graphics/SimpleFontData.cpp
+++ b/Source/core/platform/graphics/SimpleFontData.cpp
@@ -30,7 +30,6 @@
 #include "config.h"
 #include "core/platform/graphics/SimpleFontData.h"
 
-#include "core/css/CSSFontFaceSource.h"
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
 
 #include "wtf/MathExtras.h"
@@ -43,7 +42,7 @@
 const float smallCapsFontSizeMultiplier = 0.7f;
 const float emphasisMarkFontSizeMultiplier = 0.5f;
 
-SimpleFontData::SimpleFontData(const FontPlatformData& platformData, bool isCustomFont, bool isLoadingFallback, bool isTextOrientationFallback)
+SimpleFontData::SimpleFontData(const FontPlatformData& platformData, PassRefPtr<CustomFontData> customData, bool isTextOrientationFallback)
     : m_maxCharWidth(-1)
     , m_avgCharWidth(-1)
     , m_platformData(platformData)
@@ -54,7 +53,7 @@
     , m_verticalData(0)
 #endif
     , m_hasVerticalGlyphs(false)
-    , m_customFontData(isCustomFont, isLoadingFallback)
+    , m_customFontData(customData)
 {
     platformInit();
     platformGlyphInit();
@@ -67,9 +66,8 @@
 #endif
 }
 
-SimpleFontData::SimpleFontData(PassOwnPtr<AdditionalFontData> fontData, float fontSize, bool syntheticBold, bool syntheticItalic)
+SimpleFontData::SimpleFontData(PassRefPtr<CustomFontData> customData, float fontSize, bool syntheticBold, bool syntheticItalic)
     : m_platformData(FontPlatformData(fontSize, syntheticBold, syntheticItalic))
-    , m_fontData(fontData)
     , m_treatAsFixedPitch(false)
     , m_isTextOrientationFallback(false)
     , m_isBrokenIdeographFallback(false)
@@ -77,9 +75,10 @@
     , m_verticalData(0)
 #endif
     , m_hasVerticalGlyphs(false)
-    , m_customFontData(true, false)
+    , m_customFontData(customData)
 {
-    m_fontData->initializeFontData(this, fontSize);
+    if (m_customFontData)
+        m_customFontData->initializeFontData(this, fontSize);
 }
 
 // Estimates of avgCharWidth and maxCharWidth for platforms that don't support accessing these values from the font.
@@ -148,7 +147,7 @@
 
 SimpleFontData::~SimpleFontData()
 {
-    if (!m_fontData)
+    if (!isSVGFont())
         platformDestroy();
 
     if (isCustomFont())
@@ -180,7 +179,7 @@
     if (!m_derivedFontData->verticalRightOrientation) {
         FontPlatformData verticalRightPlatformData(m_platformData);
         verticalRightPlatformData.setOrientation(Horizontal);
-        m_derivedFontData->verticalRightOrientation = create(verticalRightPlatformData, isCustomFont(), false, true);
+        m_derivedFontData->verticalRightOrientation = create(verticalRightPlatformData, isCustomFont() ? CustomFontData::create(false): 0, true);
     }
     return m_derivedFontData->verticalRightOrientation;
 }
@@ -190,7 +189,7 @@
     if (!m_derivedFontData)
         m_derivedFontData = DerivedFontData::create(isCustomFont());
     if (!m_derivedFontData->uprightOrientation)
-        m_derivedFontData->uprightOrientation = create(m_platformData, isCustomFont(), false, true);
+        m_derivedFontData->uprightOrientation = create(m_platformData, isCustomFont() ? CustomFontData::create(false): 0, true);
     return m_derivedFontData->uprightOrientation;
 }
 
@@ -219,20 +218,12 @@
     if (!m_derivedFontData)
         m_derivedFontData = DerivedFontData::create(isCustomFont());
     if (!m_derivedFontData->brokenIdeograph) {
-        m_derivedFontData->brokenIdeograph = create(m_platformData, isCustomFont(), false);
+        m_derivedFontData->brokenIdeograph = create(m_platformData, isCustomFont() ? CustomFontData::create(false): 0);
         m_derivedFontData->brokenIdeograph->m_isBrokenIdeographFallback = true;
     }
     return m_derivedFontData->brokenIdeograph;
 }
 
-void SimpleFontData::beginLoadIfNeeded() const
-{
-    if (!m_customFontData.isUsed && m_customFontData.isLoadingFallback && m_customFontData.fontFaceSource) {
-        m_customFontData.isUsed = true;
-        m_customFontData.fontFaceSource->beginLoadingFontSoon();
-    }
-}
-
 #ifndef NDEBUG
 String SimpleFontData::description() const
 {
@@ -269,8 +260,8 @@
 
 PassRefPtr<SimpleFontData> SimpleFontData::createScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
 {
-    // FIXME: Support scaled fonts that used AdditionalFontData.
-    if (m_fontData)
+    // FIXME: Support scaled SVG fonts. Given that SVG is scalable in general this should be achievable.
+    if (isSVGFont())
         return 0;
 
     return platformCreateScaledFontData(fontDescription, scaleFactor);
diff --git a/Source/core/platform/graphics/SimpleFontData.h b/Source/core/platform/graphics/SimpleFontData.h
index a877074..c001860 100644
--- a/Source/core/platform/graphics/SimpleFontData.h
+++ b/Source/core/platform/graphics/SimpleFontData.h
@@ -24,6 +24,7 @@
 #ifndef SimpleFontData_h
 #define SimpleFontData_h
 
+#include "core/platform/graphics/CustomFontData.h"
 #include "core/platform/graphics/FontPlatformData.h"
 #include "core/platform/graphics/GlyphPageTreeNode.h"
 #include "platform/fonts/FontBaseline.h"
@@ -57,27 +58,16 @@
 
 class SimpleFontData : public FontData {
 public:
-    class AdditionalFontData {
-        WTF_MAKE_FAST_ALLOCATED;
-    public:
-        virtual ~AdditionalFontData() { }
-
-        virtual void initializeFontData(SimpleFontData*, float fontSize) = 0;
-        virtual float widthForSVGGlyph(Glyph, float fontSize) const = 0;
-        virtual bool fillSVGGlyphPage(GlyphPage*, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData*) const = 0;
-        virtual bool applySVGGlyphSelection(WidthIterator&, GlyphData&, bool mirror, int currentCharacter, unsigned& advanceLength) const = 0;
-    };
-
     // Used to create platform fonts.
-    static PassRefPtr<SimpleFontData> create(const FontPlatformData& platformData, bool isCustomFont = false, bool isLoadingFallback = false, bool isTextOrientationFallback = false)
+    static PassRefPtr<SimpleFontData> create(const FontPlatformData& platformData, PassRefPtr<CustomFontData> customData = 0, bool isTextOrientationFallback = false)
     {
-        return adoptRef(new SimpleFontData(platformData, isCustomFont, isLoadingFallback, isTextOrientationFallback));
+        return adoptRef(new SimpleFontData(platformData, customData, isTextOrientationFallback));
     }
 
     // Used to create SVG Fonts.
-    static PassRefPtr<SimpleFontData> create(PassOwnPtr<AdditionalFontData> fontData, float fontSize, bool syntheticBold, bool syntheticItalic)
+    static PassRefPtr<SimpleFontData> create(PassRefPtr<CustomFontData> customData, float fontSize, bool syntheticBold, bool syntheticItalic)
     {
-        return adoptRef(new SimpleFontData(fontData, fontSize, syntheticBold, syntheticItalic));
+        return adoptRef(new SimpleFontData(customData, fontSize, syntheticBold, syntheticItalic));
     }
 
     virtual ~SimpleFontData();
@@ -155,19 +145,15 @@
     void determinePitch();
     Pitch pitch() const { return m_treatAsFixedPitch ? FixedPitch : VariablePitch; }
 
-    AdditionalFontData* fontData() const { return m_fontData.get(); }
-    bool isSVGFont() const { return m_fontData; }
-
-    virtual bool isCustomFont() const OVERRIDE { return m_customFontData.isCustomFont; }
-    virtual bool isLoading() const OVERRIDE { return m_customFontData.isLoadingFallback && m_customFontData.isUsed; }
-    virtual bool isLoadingFallback() const OVERRIDE { return m_customFontData.isLoadingFallback; }
+    bool isSVGFont() const { return m_customFontData && m_customFontData->isSVGFont(); }
+    virtual bool isCustomFont() const OVERRIDE { return m_customFontData; }
+    virtual bool isLoading() const OVERRIDE { return m_customFontData ? m_customFontData->isLoading() : false; }
+    virtual bool isLoadingFallback() const OVERRIDE { return m_customFontData ? m_customFontData->isLoadingFallback() : false; }
     virtual bool isSegmented() const OVERRIDE;
 
     const GlyphData& missingGlyphData() const { return m_missingGlyphData; }
     void setMissingGlyphData(const GlyphData& glyphData) { m_missingGlyphData = glyphData; }
 
-    void beginLoadIfNeeded() const;
-
 #ifndef NDEBUG
     virtual String description() const;
 #endif
@@ -194,13 +180,12 @@
         return false;
     }
 
-    void setCSSFontFaceSource(CSSFontFaceSource* source) { m_customFontData.fontFaceSource = source; }
-    void clearCSSFontFaceSource() { m_customFontData.fontFaceSource = 0; }
+    PassRefPtr<CustomFontData> customFontData() const { return m_customFontData; }
 
 private:
-    SimpleFontData(const FontPlatformData&, bool isCustomFont = false, bool isLoadingFallback = false, bool isTextOrientationFallback = false);
+    SimpleFontData(const FontPlatformData&, PassRefPtr<CustomFontData> customData, bool isTextOrientationFallback = false);
 
-    SimpleFontData(PassOwnPtr<AdditionalFontData> , float fontSize, bool syntheticBold, bool syntheticItalic);
+    SimpleFontData(PassRefPtr<CustomFontData> customData, float fontSize, bool syntheticBold, bool syntheticItalic);
 
     void platformInit();
     void platformGlyphInit();
@@ -217,7 +202,6 @@
     float m_avgCharWidth;
 
     FontPlatformData m_platformData;
-    OwnPtr<AdditionalFontData> m_fontData;
 
     mutable OwnPtr<GlyphMetricsMap<FloatRect> > m_glyphToBoundsMap;
     mutable GlyphMetricsMap<float> m_glyphToWidthMap;
@@ -263,20 +247,7 @@
 
     mutable OwnPtr<DerivedFontData> m_derivedFontData;
 
-    struct CustomFontData {
-        CustomFontData(bool isCustomFont, bool isLoadingFallback)
-            : isCustomFont(isCustomFont)
-            , isLoadingFallback(isLoadingFallback)
-            , isUsed(false)
-            , fontFaceSource(0)
-        {
-        }
-        bool isCustomFont; // Whether or not we are custom font loaded via @font-face
-        bool isLoadingFallback; // Whether or not this is a temporary font data for a custom font which is not yet loaded.
-        mutable bool isUsed;
-        CSSFontFaceSource* fontFaceSource;
-    };
-    CustomFontData m_customFontData;
+    RefPtr<CustomFontData> m_customFontData;
 
 #if OS(MACOSX)
     float m_syntheticBoldOffset;
@@ -317,8 +288,8 @@
     if (width != cGlyphSizeUnknown)
         return width;
 
-    if (m_fontData)
-        width = m_fontData->widthForSVGGlyph(glyph, m_platformData.size());
+    if (isSVGFont())
+        width = m_customFontData->widthForSVGGlyph(glyph, m_platformData.size());
 #if ENABLE(OPENTYPE_VERTICAL)
     else if (m_verticalData)
 #if OS(MACOSX)
diff --git a/Source/core/platform/graphics/SourceBufferPrivate.h b/Source/core/platform/graphics/SourceBufferPrivate.h
deleted file mode 100644
index f3bf4a9..0000000
--- a/Source/core/platform/graphics/SourceBufferPrivate.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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 SourceBufferPrivate_h
-#define SourceBufferPrivate_h
-
-#include "core/html/TimeRanges.h"
-
-namespace WebCore {
-
-class SourceBufferPrivate {
-public:
-    SourceBufferPrivate() { }
-    virtual ~SourceBufferPrivate() { }
-
-    virtual PassRefPtr<TimeRanges> buffered() = 0;
-    virtual void append(const unsigned char* data, unsigned length) = 0;
-    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;
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/graphics/chromium/VDMXParser.cpp b/Source/core/platform/graphics/VDMXParser.cpp
similarity index 100%
rename from Source/core/platform/graphics/chromium/VDMXParser.cpp
rename to Source/core/platform/graphics/VDMXParser.cpp
diff --git a/Source/core/platform/graphics/chromium/VDMXParser.h b/Source/core/platform/graphics/VDMXParser.h
similarity index 100%
rename from Source/core/platform/graphics/chromium/VDMXParser.h
rename to Source/core/platform/graphics/VDMXParser.h
diff --git a/Source/core/platform/graphics/WidthIterator.cpp b/Source/core/platform/graphics/WidthIterator.cpp
index b82b500..19e07b5 100644
--- a/Source/core/platform/graphics/WidthIterator.cpp
+++ b/Source/core/platform/graphics/WidthIterator.cpp
@@ -100,20 +100,20 @@
 
 typedef Vector<pair<int, OriginalAdvancesForCharacterTreatedAsSpace>, 64> CharactersTreatedAsSpace;
 
-static inline float applyFontTransforms(GlyphBuffer* glyphBuffer, bool ltr, int& lastGlyphCount, const SimpleFontData* fontData, TypesettingFeatures typesettingFeatures, CharactersTreatedAsSpace& charactersTreatedAsSpace)
+static inline float applyFontTransforms(GlyphBuffer* glyphBuffer, bool ltr, unsigned& lastGlyphCount, const SimpleFontData* fontData, TypesettingFeatures typesettingFeatures, CharactersTreatedAsSpace& charactersTreatedAsSpace)
 {
     ASSERT(typesettingFeatures & (Kerning | Ligatures));
 
     if (!glyphBuffer)
         return 0;
 
-    int glyphBufferSize = glyphBuffer->size();
+    unsigned glyphBufferSize = glyphBuffer->size();
     if (glyphBuffer->size() <= lastGlyphCount + 1)
         return 0;
 
     GlyphBufferAdvance* advances = glyphBuffer->advances(0);
     float widthDifference = 0;
-    for (int i = lastGlyphCount; i < glyphBufferSize; ++i)
+    for (unsigned i = lastGlyphCount; i < glyphBufferSize; ++i)
         widthDifference -= advances[i].width();
 
     if (!ltr)
@@ -133,7 +133,7 @@
     }
     charactersTreatedAsSpace.clear();
 
-    for (int i = lastGlyphCount; i < glyphBufferSize; ++i)
+    for (unsigned i = lastGlyphCount; i < glyphBufferSize; ++i)
         widthDifference += advances[i].width();
 
     lastGlyphCount = glyphBufferSize;
@@ -155,7 +155,7 @@
 
     const SimpleFontData* primaryFont = m_font->primaryFont();
     const SimpleFontData* lastFontData = primaryFont;
-    int lastGlyphCount = glyphBuffer ? glyphBuffer->size() : 0;
+    unsigned lastGlyphCount = glyphBuffer ? glyphBuffer->size() : 0;
 
     UChar32 character = 0;
     unsigned clusterLength = 0;
@@ -335,10 +335,10 @@
 
 bool WidthIterator::advanceOneCharacter(float& width, GlyphBuffer& glyphBuffer)
 {
-    int oldSize = glyphBuffer.size();
+    unsigned oldSize = glyphBuffer.size();
     advance(m_currentCharacter + 1, &glyphBuffer);
     float w = 0;
-    for (int i = oldSize; i < glyphBuffer.size(); ++i)
+    for (unsigned i = oldSize; i < glyphBuffer.size(); ++i)
         w += glyphBuffer.advanceAt(i);
     width = w;
     return glyphBuffer.size() > oldSize;
diff --git a/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp b/Source/core/platform/graphics/android/FontCacheAndroid.cpp
similarity index 98%
rename from Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
rename to Source/core/platform/graphics/android/FontCacheAndroid.cpp
index 45f487c..390e10a 100644
--- a/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
+++ b/Source/core/platform/graphics/android/FontCacheAndroid.cpp
@@ -73,7 +73,7 @@
     AtomicString familyName = getFamilyNameForCharacter(c, font.fontDescription().script());
     if (familyName.isEmpty())
         return 0;
-    return getFontResourceData(getFontResourcePlatformData(font.fontDescription(), familyName, DoNotRetain), DoNotRetain);
+    return getFontResourceData(getFontResourcePlatformData(font.fontDescription(), familyName), DoNotRetain);
 }
 
 // static
diff --git a/Source/core/platform/graphics/cg/FloatPointCG.cpp b/Source/core/platform/graphics/cg/FloatPointCG.cpp
deleted file mode 100644
index 4fb7675..0000000
--- a/Source/core/platform/graphics/cg/FloatPointCG.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2004, 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2005 Nokia.  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 "platform/geometry/FloatPoint.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-FloatPoint::FloatPoint(const CGPoint& p) : m_x(p.x), m_y(p.y)
-{
-}
-
-FloatPoint::operator CGPoint() const
-{
-    return CGPointMake(m_x, m_y);
-}
-
-}
diff --git a/Source/core/platform/graphics/cg/FloatRectCG.cpp b/Source/core/platform/graphics/cg/FloatRectCG.cpp
deleted file mode 100644
index 6f74b6c..0000000
--- a/Source/core/platform/graphics/cg/FloatRectCG.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2005 Nokia.  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 "platform/geometry/FloatRect.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-FloatRect::FloatRect(const CGRect& r) : m_location(r.origin), m_size(r.size)
-{
-}
-
-FloatRect::operator CGRect() const
-{
-    return CGRectMake(x(), y(), width(), height());
-}
-
-}
diff --git a/Source/core/platform/graphics/cg/FloatSizeCG.cpp b/Source/core/platform/graphics/cg/FloatSizeCG.cpp
deleted file mode 100644
index cd17d4f..0000000
--- a/Source/core/platform/graphics/cg/FloatSizeCG.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2005 Nokia.  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 "platform/geometry/FloatSize.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-FloatSize::FloatSize(const CGSize& s) : m_width(s.width), m_height(s.height)
-{
-}
-
-FloatSize::operator CGSize() const
-{
-    return CGSizeMake(m_width, m_height);
-}
-
-}
diff --git a/Source/core/platform/graphics/cg/IntPointCG.cpp b/Source/core/platform/graphics/cg/IntPointCG.cpp
deleted file mode 100644
index ee60682..0000000
--- a/Source/core/platform/graphics/cg/IntPointCG.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, 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 "platform/geometry/IntPoint.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-IntPoint::IntPoint(const CGPoint& p) : m_x(static_cast<int>(p.x)), m_y(static_cast<int>(p.y))
-{
-}
-
-IntPoint::operator CGPoint() const
-{
-    return CGPointMake(m_x, m_y);
-}
-
-}
diff --git a/Source/core/platform/graphics/cg/IntRectCG.cpp b/Source/core/platform/graphics/cg/IntRectCG.cpp
deleted file mode 100644
index 6a6c8fe..0000000
--- a/Source/core/platform/graphics/cg/IntRectCG.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, 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 "platform/geometry/IntRect.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-IntRect::operator CGRect() const
-{
-    return CGRectMake(x(), y(), width(), height());
-}
-
-IntRect enclosingIntRect(const CGRect& rect)
-{
-    int l = static_cast<int>(floorf(rect.origin.x));
-    int t = static_cast<int>(floorf(rect.origin.y));
-    int r = static_cast<int>(ceilf(CGRectGetMaxX(rect)));
-    int b = static_cast<int>(ceilf(CGRectGetMaxY(rect)));
-    return IntRect(l, t, r - l, b - t);
-}
-
-}
diff --git a/Source/core/platform/graphics/cg/IntSizeCG.cpp b/Source/core/platform/graphics/cg/IntSizeCG.cpp
deleted file mode 100644
index 4dabb81..0000000
--- a/Source/core/platform/graphics/cg/IntSizeCG.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, 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 "platform/geometry/IntSize.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-IntSize::IntSize(const CGSize& s) : m_width(static_cast<int>(s.width)), m_height(static_cast<int>(s.height))
-{
-}
-
-IntSize::operator CGSize() const
-{
-    return CGSizeMake(m_width, m_height);
-}
-
-}
diff --git a/Source/core/platform/graphics/chromium/FontFallbackWin.cpp b/Source/core/platform/graphics/chromium/FontFallbackWin.cpp
deleted file mode 100644
index dacbf03..0000000
--- a/Source/core/platform/graphics/chromium/FontFallbackWin.cpp
+++ /dev/null
@@ -1,348 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 2009, 2010, 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/platform/graphics/chromium/FontFallbackWin.h"
-
-#include "platform/win/HWndDC.h"
-#include "wtf/HashMap.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-#include <limits>
-#include <unicode/locid.h>
-#include <unicode/uchar.h>
-
-namespace WebCore {
-
-namespace {
-
-bool isFontPresent(const UChar* fontName)
-{
-    HFONT hfont = CreateFont(12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, fontName);
-    if (!hfont)
-        return false;
-    HWndDC dc(0);
-    HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont));
-    WCHAR actualFontName[LF_FACESIZE];
-    GetTextFace(dc, LF_FACESIZE, actualFontName);
-    actualFontName[LF_FACESIZE - 1] = 0;
-    SelectObject(dc, oldFont);
-    DeleteObject(hfont);
-    // We don't have to worry about East Asian fonts with locale-dependent
-    // names here for now.
-    // FIXME: Why not?
-    return !wcscmp(fontName, actualFontName);
-}
-
-// A simple mapping from UScriptCode to family name. This is a sparse array,
-// which works well since the range of UScriptCode values is small.
-typedef const UChar* ScriptToFontMap[USCRIPT_CODE_LIMIT];
-
-void initializeScriptFontMap(ScriptToFontMap& scriptFontMap)
-{
-    struct FontMap {
-        UScriptCode script;
-        const UChar* family;
-    };
-
-    static const FontMap fontMap[] = {
-        {USCRIPT_LATIN, L"times new roman"},
-        {USCRIPT_GREEK, L"times new roman"},
-        {USCRIPT_CYRILLIC, L"times new roman"},
-        // FIXME: Consider trying new Vista fonts before XP fonts for CJK.
-        // Some Vista users do want to use Vista cleartype CJK fonts. If we
-        // did, the results of tests with CJK characters would have to be
-        // regenerated for Vista.
-        {USCRIPT_SIMPLIFIED_HAN, L"simsun"},
-        {USCRIPT_TRADITIONAL_HAN, L"pmingliu"},
-        {USCRIPT_HIRAGANA, L"ms pgothic"},
-        {USCRIPT_KATAKANA, L"ms pgothic"},
-        {USCRIPT_KATAKANA_OR_HIRAGANA, L"ms pgothic"},
-        {USCRIPT_HANGUL, L"gulim"},
-        {USCRIPT_THAI, L"tahoma"},
-        {USCRIPT_HEBREW, L"david"},
-        {USCRIPT_ARABIC, L"tahoma"},
-        {USCRIPT_DEVANAGARI, L"mangal"},
-        {USCRIPT_BENGALI, L"vrinda"},
-        {USCRIPT_GURMUKHI, L"raavi"},
-        {USCRIPT_GUJARATI, L"shruti"},
-        {USCRIPT_TAMIL, L"latha"},
-        {USCRIPT_TELUGU, L"gautami"},
-        {USCRIPT_KANNADA, L"tunga"},
-        {USCRIPT_GEORGIAN, L"sylfaen"},
-        {USCRIPT_ARMENIAN, L"sylfaen"},
-        {USCRIPT_THAANA, L"mv boli"},
-        {USCRIPT_CANADIAN_ABORIGINAL, L"euphemia"},
-        {USCRIPT_CHEROKEE, L"plantagenet cherokee"},
-        {USCRIPT_MONGOLIAN, L"mongolian balti"},
-        // For USCRIPT_COMMON, we map blocks to scripts when
-        // that makes sense.
-    };
-
-    struct ScriptToFontFamilies {
-        UScriptCode script;
-        const UChar** families;
-    };
-
-    // Kartika on Vista or earlier lacks the support for Chillu
-    // letters added to Unicode 5.1.
-    // Try AnjaliOldLipi (a very widely used Malaylalam font with the full
-    // Unicode 5.x support) before falling back to Kartika.
-    static const UChar* malayalamFonts[] = {L"AnjaliOldLipi", L"Lohit Malayalam", L"Kartika", L"Rachana", 0};
-    // Try Khmer OS before Vista fonts because 'Khmer OS' goes along better
-    // with Latin and looks better/larger for the same size.
-    static const UChar* khmerFonts[] = {L"Khmer OS", L"MoolBoran", L"DaunPenh", L"Code2000", 0};
-    // For the following 6 scripts, two or fonts are listed. The fonts in
-    // the 1st slot are not available on Windows XP. To support these
-    // scripts on XP, listed in the rest of slots are widely used
-    // fonts.
-    static const UChar* ethiopicFonts[] = {L"Nyala", L"Abyssinica SIL", L"Ethiopia Jiret", L"Visual Geez Unicode", L"GF Zemen Unicode", 0};
-    static const UChar* oriyaFonts[] = {L"Kalinga", L"ori1Uni", L"Lohit Oriya", 0};
-    static const UChar* laoFonts[] = {L"DokChampa", L"Saysettha OT", L"Phetsarath OT", L"Code2000", 0};
-    static const UChar* tibetanFonts[] = {L"Microsoft Himalaya", L"Jomolhari", L"Tibetan Machine Uni", 0};
-    static const UChar* sinhalaFonts[] = {L"Iskoola Pota", L"AksharUnicode", 0};
-    static const UChar* yiFonts[] = {L"Microsoft Yi Balti", L"Nuosu SIL", L"Code2000", 0};
-    // http://www.bethmardutho.org/support/meltho/download/index.php
-    static const UChar* syriacFonts[] = {L"Estrangelo Edessa", L"Estrangelo Nisibin", L"Code2000", 0};
-    // No Myanmar/Burmese font is shipped with Windows, yet. Try a few
-    // widely available/used ones that supports Unicode 5.1 or later.
-    static const UChar* myanmarFonts[] = {L"Padauk", L"Parabaik", L"Myanmar3", L"Code2000", 0};
-
-    static const ScriptToFontFamilies scriptToFontFamilies[] = {
-        {USCRIPT_MALAYALAM, malayalamFonts},
-        {USCRIPT_KHMER, khmerFonts},
-        {USCRIPT_ETHIOPIC, ethiopicFonts},
-        {USCRIPT_ORIYA, oriyaFonts},
-        {USCRIPT_LAO, laoFonts},
-        {USCRIPT_TIBETAN, tibetanFonts},
-        {USCRIPT_SINHALA, sinhalaFonts},
-        {USCRIPT_YI, yiFonts},
-        {USCRIPT_SYRIAC, syriacFonts},
-        {USCRIPT_MYANMAR, myanmarFonts},
-    };
-
-    for (size_t i = 0; i < WTF_ARRAY_LENGTH(fontMap); ++i)
-        scriptFontMap[fontMap[i].script] = fontMap[i].family;
-
-    // FIXME: Instead of scanning the hard-coded list, we have to
-    // use EnumFont* to 'inspect' fonts to pick up fonts covering scripts
-    // when it's possible (e.g. using OS/2 table). If we do that, this
-    // had better be pulled out of here.
-    for (size_t i = 0; i < WTF_ARRAY_LENGTH(scriptToFontFamilies); ++i) {
-        UScriptCode script = scriptToFontFamilies[i].script;
-        scriptFontMap[script] = 0;
-        const UChar** familyPtr = scriptToFontFamilies[i].families;
-        while (*familyPtr) {
-            if (isFontPresent(*familyPtr)) {
-                scriptFontMap[script] = *familyPtr;
-                break;
-            }
-            ++familyPtr;
-        }
-    }
-
-    // Initialize the locale-dependent mapping.
-    // Since Chrome synchronizes the ICU default locale with its UI locale,
-    // this ICU locale tells the current UI locale of Chrome.
-    icu::Locale locale = icu::Locale::getDefault();
-    const UChar* localeFamily = 0;
-    if (locale == icu::Locale::getJapanese()) {
-        localeFamily = scriptFontMap[USCRIPT_HIRAGANA];
-    } else if (locale == icu::Locale::getKorean()) {
-        localeFamily = scriptFontMap[USCRIPT_HANGUL];
-    } else if (locale == icu::Locale::getTraditionalChinese()) {
-        localeFamily = scriptFontMap[USCRIPT_TRADITIONAL_HAN];
-    } else {
-        // For other locales, use the simplified Chinese font for Han.
-        localeFamily = scriptFontMap[USCRIPT_SIMPLIFIED_HAN];
-    }
-    if (localeFamily)
-        scriptFontMap[USCRIPT_HAN] = localeFamily;
-}
-
-// There are a lot of characters in USCRIPT_COMMON that can be covered
-// by fonts for scripts closely related to them. See
-// http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Script=Common:]
-// FIXME: make this more efficient with a wider coverage
-UScriptCode getScriptBasedOnUnicodeBlock(int ucs4)
-{
-    UBlockCode block = ublock_getCode(ucs4);
-    switch (block) {
-    case UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION:
-        return USCRIPT_HAN;
-    case UBLOCK_HIRAGANA:
-    case UBLOCK_KATAKANA:
-        return USCRIPT_HIRAGANA;
-    case UBLOCK_ARABIC:
-        return USCRIPT_ARABIC;
-    case UBLOCK_THAI:
-        return USCRIPT_THAI;
-    case UBLOCK_GREEK:
-        return USCRIPT_GREEK;
-    case UBLOCK_DEVANAGARI:
-        // For Danda and Double Danda (U+0964, U+0965), use a Devanagari
-        // font for now although they're used by other scripts as well.
-        // Without a context, we can't do any better.
-        return USCRIPT_DEVANAGARI;
-    case UBLOCK_ARMENIAN:
-        return USCRIPT_ARMENIAN;
-    case UBLOCK_GEORGIAN:
-        return USCRIPT_GEORGIAN;
-    case UBLOCK_KANNADA:
-        return USCRIPT_KANNADA;
-    default:
-        return USCRIPT_COMMON;
-    }
-}
-
-UScriptCode getScript(int ucs4)
-{
-    UErrorCode err = U_ZERO_ERROR;
-    UScriptCode script = uscript_getScript(ucs4, &err);
-    // If script is invalid, common or inherited or there's an error,
-    // infer a script based on the unicode block of a character.
-    if (script <= USCRIPT_INHERITED || U_FAILURE(err))
-        script = getScriptBasedOnUnicodeBlock(ucs4);
-    return script;
-}
-
-} // namespace
-
-// FIXME: this is font fallback code version 0.1
-//  - Cover all the scripts
-//  - Get the default font for each script/generic family from the
-//    preference instead of hardcoding in the source.
-//    (at least, read values from the registry for IE font settings).
-//  - Support generic families (from FontDescription)
-//  - If the default font for a script is not available,
-//    try some more fonts known to support it. Finally, we can
-//    use EnumFontFamilies or similar APIs to come up with a list of
-//    fonts supporting the script and cache the result.
-//  - Consider using UnicodeSet (or UnicodeMap) converted from
-//    GLYPHSET (BMP) or directly read from truetype cmap tables to
-//    keep track of which character is supported by which font
-//  - Update script_font_cache in response to WM_FONTCHANGE
-
-const UChar* getFontFamilyForScript(UScriptCode script,
-    FontDescription::GenericFamilyType generic)
-{
-    static ScriptToFontMap scriptFontMap;
-    static bool initialized = false;
-    if (!initialized) {
-        initializeScriptFontMap(scriptFontMap);
-        initialized = true;
-    }
-    if (script == USCRIPT_INVALID_CODE)
-        return 0;
-    ASSERT(script < USCRIPT_CODE_LIMIT);
-    return scriptFontMap[script];
-}
-
-// FIXME:
-//  - Handle 'Inherited', 'Common' and 'Unknown'
-//    (see http://www.unicode.org/reports/tr24/#Usage_Model )
-//    For 'Inherited' and 'Common', perhaps we need to
-//    accept another parameter indicating the previous family
-//    and just return it.
-//  - All the characters (or characters up to the point a single
-//    font can cover) need to be taken into account
-const UChar* getFallbackFamily(UChar32 character,
-    FontDescription::GenericFamilyType generic,
-    UScriptCode* scriptChecked)
-{
-    ASSERT(character);
-    UScriptCode script = getScript(character);
-
-    // For the full-width ASCII characters (U+FF00 - U+FF5E), use the font for
-    // Han (determined in a locale-dependent way above). Full-width ASCII
-    // characters are rather widely used in Japanese and Chinese documents and
-    // they're fully covered by Chinese, Japanese and Korean fonts.
-    if (0xFF00 < character && character < 0xFF5F)
-        script = USCRIPT_HAN;
-
-    if (script == USCRIPT_COMMON)
-        script = getScriptBasedOnUnicodeBlock(character);
-
-    const UChar* family = getFontFamilyForScript(script, generic);
-    // Another lame work-around to cover non-BMP characters.
-    // If the font family for script is not found or the character is
-    // not in BMP (> U+FFFF), we resort to the hard-coded list of
-    // fallback fonts for now.
-    if (!family || character > 0xFFFF) {
-        int plane = character >> 16;
-        switch (plane) {
-        case 1:
-            family = L"code2001";
-            break;
-        case 2:
-            // Use a Traditional Chinese ExtB font if in Traditional Chinese locale.
-            // Otherwise, use a Simplified Chinese ExtB font. Windows Japanese
-            // fonts do support a small subset of ExtB (that are included in JIS X 0213),
-            // but its coverage is rather sparse.
-            // Eventually, this should be controlled by lang/xml:lang.
-            if (icu::Locale::getDefault() == icu::Locale::getTraditionalChinese())
-                family = L"pmingliu-extb";
-            else
-                family = L"simsun-extb";
-            break;
-        default:
-            family = L"lucida sans unicode";
-        }
-    }
-
-    if (scriptChecked)
-        *scriptChecked = script;
-    return family;
-}
-
-
-const UChar* getFallbackFamilyForFirstNonCommonCharacter(const UChar* characters,
-    int length,
-    FontDescription::GenericFamilyType generic)
-{
-    ASSERT(characters && characters[0] && length > 0);
-    UScriptCode script = USCRIPT_COMMON;
-
-    // Sometimes characters common to script (e.g. space) is at
-    // the beginning of a string so that we need to skip them
-    // to get a font required to render the string.
-    int i = 0;
-    UChar32 ucs4 = 0;
-    while (i < length && script == USCRIPT_COMMON) {
-        U16_NEXT(characters, i, length, ucs4);
-        script = getScript(ucs4);
-    }
-
-    const UChar* family = getFallbackFamily(ucs4, generic, 0);
-
-    return family;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/chromium/FontFallbackWin.h b/Source/core/platform/graphics/chromium/FontFallbackWin.h
deleted file mode 100644
index bba33c8..0000000
--- a/Source/core/platform/graphics/chromium/FontFallbackWin.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 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.
- */
-
-// A collection of utilities for font handling.
-
-// FIXME: Move all methods to the files that have their callsites and remove this file.
-// *Utils files are not very WebKit-ty.
-
-#ifndef FontFallbackWin_h
-#define FontFallbackWin_h
-
-#include "platform/fonts/FontDescription.h"
-#include <unicode/uscript.h>
-#include <usp10.h>
-#include <wchar.h>
-#include <windows.h>
-
-namespace WebCore {
-
-// Return a font family that can render |characters| based on
-// what script characters belong to.
-// FIXME: This function needs a total overhaul.
-const UChar* getFallbackFamilyForFirstNonCommonCharacter(const UChar* characters,
-    int length,
-    FontDescription::GenericFamilyType);
-
-// Return a font family that can render |character| based on what script
-// that characters belong to.
-// When scriptChecked is non-zero, the script used to determine
-// the family is returned.
-const UChar* getFallbackFamily(UChar32 character,
-    FontDescription::GenericFamilyType,
-    UScriptCode* scriptChecked);
-
-} // namespace WebCore
-
-#endif // FontFallbackWin_h
diff --git a/Source/core/platform/graphics/chromium/FontRenderStyle.h b/Source/core/platform/graphics/chromium/FontRenderStyle.h
deleted file mode 100644
index e44abb4..0000000
--- a/Source/core/platform/graphics/chromium/FontRenderStyle.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/* 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:
- *
- *     * 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 FontRenderStyle_h
-#define FontRenderStyle_h
-
-namespace WebCore {
-
-// FontRenderStyle describes the user's preferences for rendering a font at a
-// given size.
-struct FontRenderStyle {
-    enum {
-        NoPreference = 2,
-    };
-
-    FontRenderStyle()
-        : useBitmaps(0)
-        , useAutoHint(0)
-        , useHinting(0)
-        , hintStyle(0)
-        , useAntiAlias(0)
-        , useSubpixelRendering(0)
-        , useSubpixelPositioning(0) { }
-
-    bool operator==(const FontRenderStyle& a) const
-    {
-        return useBitmaps == a.useBitmaps
-            && useAutoHint == a.useAutoHint
-            && useHinting == a.useHinting
-            && hintStyle == a.hintStyle
-            && useAntiAlias == a.useAntiAlias
-            && useSubpixelRendering == a.useSubpixelRendering
-            && useSubpixelPositioning == a.useSubpixelPositioning;
-    }
-
-    // Each of the use* members below can take one of three values:
-    //   0: off
-    //   1: on
-    //   NoPreference: no preference expressed
-    char useBitmaps; // use embedded bitmap strike if possible
-    char useAutoHint; // use 'auto' hinting (FreeType specific)
-    char useHinting; // hint glyphs to the pixel grid
-    char hintStyle; // level of hinting, 0..3
-    char useAntiAlias; // antialias glyph shapes
-    char useSubpixelRendering; // use subpixel rendering (partially-filled pixels)
-    char useSubpixelPositioning; // use subpixel positioning (fractional X positions for glyphs)
-};
-
-}
-
-#endif // FontRenderStyle_h
diff --git a/Source/core/platform/graphics/chromium/SkSizeHash.h b/Source/core/platform/graphics/chromium/SkSizeHash.h
deleted file mode 100644
index dd95c82..0000000
--- a/Source/core/platform/graphics/chromium/SkSizeHash.h
+++ /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 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 SkSizeHash_h
-#define SkSizeHash_h
-
-#include "SkScalar.h"
-#include "SkSize.h"
-
-#include "wtf/HashMap.h"
-
-namespace WTF {
-
-template<> struct IntHash<SkSize> {
-    static unsigned hash(const SkSize& key) { return pairIntHash(key.width(), key.height()); }
-    static bool equal(const SkSize& a, const SkSize& b) { return a == b; }
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-template<> struct DefaultHash<SkSize> {
-    typedef IntHash<SkSize> Hash;
-};
-
-template<> struct HashTraits<SkSize> : GenericHashTraits<SkSize> {
-    static const bool emptyValueIsZero = true;
-    static const bool needsDestruction = false;
-    static SkSize emptyValue() { return SkSize::Make(0, 0); }
-    static void constructDeletedValue(SkSize& slot)
-    {
-        slot = SkSize::Make(-1, -1);
-    }
-    static bool isDeletedValue(const SkSize& value)
-    {
-        return value.width() == -1 && value.height() == -1;
-    }
-};
-
-template<> struct IntHash<SkISize> {
-    static unsigned hash(const SkISize& key) { return pairIntHash(key.width(), key.height()); }
-    static bool equal(const SkISize& a, const SkISize& b) { return a == b; }
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-template<> struct DefaultHash<SkISize> {
-    typedef IntHash<SkISize> Hash;
-};
-
-template<> struct HashTraits<SkISize> : GenericHashTraits<SkISize> {
-    static const bool emptyValueIsZero = true;
-    static const bool needsDestruction = false;
-    static SkISize emptyValue() { return SkISize::Make(0, 0); }
-    static void constructDeletedValue(SkISize& slot)
-    {
-        slot = SkISize::Make(-1, -1);
-    }
-    static bool isDeletedValue(const SkISize& value)
-    {
-        return value.width() == -1 && value.height() == -1;
-    }
-};
-
-} // namespace WTF
-
-#endif // SkSizeHash_h
diff --git a/Source/core/platform/graphics/chromium/TextureUploader.h b/Source/core/platform/graphics/chromium/TextureUploader.h
deleted file mode 100644
index 0a86161..0000000
--- a/Source/core/platform/graphics/chromium/TextureUploader.h
+++ /dev/null
@@ -1,50 +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 INC. 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 INC. 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.
- */
-
-#ifndef TextureUploader_h
-#define TextureUploader_h
-
-#include "LayerTextureUpdater.h"
-
-namespace WebCore {
-
-class TextureUploader {
-public:
-    struct Parameters {
-        LayerTextureUpdater::Texture* texture;
-        IntRect sourceRect;
-        IntSize destOffset;
-    };
-
-    virtual ~TextureUploader() { }
-
-    virtual bool isBusy() = 0;
-    virtual void beginUploads() = 0;
-    virtual void endUploads() = 0;
-    virtual void uploadTexture(CCResourceProvider*, Parameters) = 0;
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/graphics/filters/DistantLightSource.h b/Source/core/platform/graphics/filters/DistantLightSource.h
index 8999bf5..c8c3b3f 100644
--- a/Source/core/platform/graphics/filters/DistantLightSource.h
+++ b/Source/core/platform/graphics/filters/DistantLightSource.h
@@ -23,7 +23,7 @@
 #ifndef DistantLightSource_h
 #define DistantLightSource_h
 
-#include "core/platform/graphics/filters/LightSource.h"
+#include "platform/graphics/filters/LightSource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/FEComposite.cpp b/Source/core/platform/graphics/filters/FEComposite.cpp
index 14c8731..08b4b90 100644
--- a/Source/core/platform/graphics/filters/FEComposite.cpp
+++ b/Source/core/platform/graphics/filters/FEComposite.cpp
@@ -42,67 +42,6 @@
 
 namespace WebCore {
 
-class CompositeImageFilter : public SkImageFilter {
-public:
-    CompositeImageFilter(SkXfermode::Mode mode, SkImageFilter* background, SkImageFilter* foreground, const CropRect* cropRect) : SkImageFilter(background, foreground, cropRect), m_mode(mode)
-    {
-    }
-
-    virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* dst, SkIPoint* offset)
-    {
-        SkBitmap background = src;
-        SkBitmap foreground = src;
-        SkImageFilter* backgroundInput = getInput(0);
-        SkImageFilter* foregroundInput = getInput(1);
-        SkIPoint backgroundOffset = SkIPoint::Make(0, 0), foregroundOffset = SkIPoint::Make(0, 0);
-        if (backgroundInput && !backgroundInput->filterImage(proxy, src, ctm, &background, &backgroundOffset))
-            return false;
-
-        if (foregroundInput && !foregroundInput->filterImage(proxy, src, ctm, &foreground, &foregroundOffset))
-            return false;
-
-        SkIRect bounds;
-        background.getBounds(&bounds);
-        if (!applyCropRect(&bounds, ctm)) {
-            return false;
-        }
-        backgroundOffset.fX -= bounds.left();
-        backgroundOffset.fY -= bounds.top();
-        foregroundOffset.fX -= bounds.left();
-        foregroundOffset.fY -= bounds.top();
-
-        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
-        SkCanvas canvas(device);
-        SkPaint paint;
-        paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-        canvas.drawBitmap(background, backgroundOffset.fX, backgroundOffset.fY, &paint);
-        paint.setXfermodeMode(m_mode);
-        canvas.drawBitmap(foreground, foregroundOffset.fX, foregroundOffset.fY, &paint);
-        *dst = device->accessBitmap(false);
-        offset->fX += bounds.left();
-        offset->fY += bounds.top();
-        return true;
-    }
-
-    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(CompositeImageFilter)
-
-protected:
-    explicit CompositeImageFilter(SkFlattenableReadBuffer& buffer)
-        : SkImageFilter(buffer)
-    {
-        m_mode = (SkXfermode::Mode) buffer.readInt();
-    }
-
-    virtual void flatten(SkFlattenableWriteBuffer& buffer) const
-    {
-        this->SkImageFilter::flatten(buffer);
-        buffer.writeInt((int) m_mode);
-    }
-
-private:
-    SkXfermode::Mode m_mode;
-};
-
 FEComposite::FEComposite(Filter* filter, const CompositeOperationType& type, float k1, float k2, float k3, float k4)
     : FilterEffect(filter)
     , m_type(type)
@@ -412,7 +351,8 @@
         return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get()));
     }
     SkImageFilter::CropRect cropRect = getCropRect(builder->cropOffset());
-    return adoptRef(new CompositeImageFilter(toXfermode(m_type), background.get(), foreground.get(), &cropRect));
+    SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(toXfermode(m_type)));
+    return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get(), &cropRect));
 }
 
 static TextStream& operator<<(TextStream& ts, const CompositeOperationType& type)
diff --git a/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp b/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
index b6e08ca..8230935 100644
--- a/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
+++ b/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
@@ -27,9 +27,9 @@
 #include "core/platform/graphics/filters/FEConvolveMatrix.h"
 
 #include "core/platform/graphics/filters/Filter.h"
+#include "core/platform/graphics/filters/ParallelJobs.h"
 #include "platform/text/TextStream.h"
 #include "wtf/OwnPtr.h"
-#include "wtf/ParallelJobs.h"
 #include "wtf/Uint8ClampedArray.h"
 
 #include "SkMatrixConvolutionImageFilter.h"
@@ -454,7 +454,7 @@
 
         int optimalThreadNumber = (absolutePaintRect().width() * absolutePaintRect().height()) / s_minimalRectDimension;
         if (optimalThreadNumber > 1) {
-            WTF::ParallelJobs<InteriorPixelParameters> parallelJobs(&WebCore::FEConvolveMatrix::setInteriorPixelsWorker, optimalThreadNumber);
+            ParallelJobs<InteriorPixelParameters> parallelJobs(&WebCore::FEConvolveMatrix::setInteriorPixelsWorker, optimalThreadNumber);
             const int numOfThreads = parallelJobs.numberOfJobs();
 
             // Split the job into "heightPerThread" jobs but there a few jobs that need to be slightly larger since
diff --git a/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp b/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp
index 5913c7b..12e8868 100644
--- a/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp
+++ b/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp
@@ -24,7 +24,7 @@
 
 #include "core/platform/graphics/filters/FEDiffuseLighting.h"
 
-#include "core/platform/graphics/filters/LightSource.h"
+#include "platform/graphics/filters/LightSource.h"
 #include "platform/text/TextStream.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/graphics/filters/FEFlood.cpp b/Source/core/platform/graphics/filters/FEFlood.cpp
index ea55912..5392647 100644
--- a/Source/core/platform/graphics/filters/FEFlood.cpp
+++ b/Source/core/platform/graphics/filters/FEFlood.cpp
@@ -25,63 +25,15 @@
 
 #include "core/platform/graphics/filters/FEFlood.h"
 
+#include "SkColorFilter.h"
+#include "SkColorFilterImageFilter.h"
 #include "SkFlattenableBuffers.h"
-#include "SkImageFilter.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "platform/text/TextStream.h"
 #include "third_party/skia/include/core/SkDevice.h"
 
-namespace {
-
-class FloodImageFilter : public SkImageFilter {
-public:
-    FloodImageFilter(const SkColor& color, const CropRect* cropRect)
-        : SkImageFilter(0, 0, cropRect)
-        , m_color(color)
-    {
-    }
-    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(FloodImageFilter)
-
-    FloodImageFilter(SkFlattenableReadBuffer& buffer) : SkImageFilter(buffer)
-    {
-        m_color = buffer.readColor();
-    }
-
-    virtual void flatten(SkFlattenableWriteBuffer& buffer) const
-    {
-        this->SkImageFilter::flatten(buffer);
-        buffer.writeColor(m_color);
-    }
-
-    virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* result, SkIPoint* offset)
-    {
-        if (!src.width() || !src.height())
-            return false;
-
-        SkIRect bounds;
-        src.getBounds(&bounds);
-        if (!applyCropRect(&bounds, ctm)) {
-            return false;
-        }
-
-        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
-        SkCanvas canvas(device.get());
-        SkPaint paint;
-        paint.setColor(m_color);
-        canvas.drawRect(SkRect::MakeWH(src.width(), src.height()), paint);
-        *result = device->accessBitmap(false);
-        offset->fX += bounds.left();
-        offset->fY += bounds.top();
-        return true;
-    }
-private:
-    SkColor m_color;
-};
-
-}; // unnamed namespace
-
 namespace WebCore {
 
 FEFlood::FEFlood(Filter* filter, const Color& floodColor, float floodOpacity)
@@ -139,7 +91,8 @@
     Color color = colorWithOverrideAlpha(floodColor().rgb(), floodOpacity());
 
     SkImageFilter::CropRect rect = getCropRect(builder->cropOffset());
-    return adoptRef(new FloodImageFilter(color.rgb(), &rect));
+    SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(color.rgb(), SkXfermode::kSrc_Mode));
+    return adoptRef(SkColorFilterImageFilter::Create(cf, 0, &rect));
 }
 
 TextStream& FEFlood::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
index 4dc40eb..75af57d 100644
--- a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
+++ b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
@@ -30,10 +30,10 @@
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/cpu/arm/filters/FEGaussianBlurNEON.h"
 #include "core/platform/graphics/filters/Filter.h"
+#include "core/platform/graphics/filters/ParallelJobs.h"
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "platform/text/TextStream.h"
 #include "wtf/MathExtras.h"
-#include "wtf/ParallelJobs.h"
 #include "wtf/Uint8ClampedArray.h"
 
 #include "SkBlurImageFilter.h"
@@ -168,7 +168,7 @@
     int optimalThreadNumber = (paintSize.width() * paintSize.height()) / (s_minimalRectDimension + extraHeight * paintSize.width());
 
     if (optimalThreadNumber > 1) {
-        WTF::ParallelJobs<PlatformApplyParameters> parallelJobs(&platformApplyWorker, optimalThreadNumber);
+        ParallelJobs<PlatformApplyParameters> parallelJobs(&platformApplyWorker, optimalThreadNumber);
 
         int jobs = parallelJobs.numberOfJobs();
         if (jobs > 1) {
diff --git a/Source/core/platform/graphics/filters/FELighting.cpp b/Source/core/platform/graphics/filters/FELighting.cpp
index aa17504..f25bd9b 100644
--- a/Source/core/platform/graphics/filters/FELighting.cpp
+++ b/Source/core/platform/graphics/filters/FELighting.cpp
@@ -30,7 +30,7 @@
 #include "core/platform/graphics/filters/FELighting.h"
 
 #include "core/platform/graphics/cpu/arm/filters/FELightingNEON.h"
-#include "wtf/ParallelJobs.h"
+#include "core/platform/graphics/filters/ParallelJobs.h"
 
 #include "SkLightingImageFilter.h"
 #include "core/platform/graphics/filters/DistantLightSource.h"
@@ -259,7 +259,7 @@
     int optimalThreadNumber = ((data.widthDecreasedByOne - 1) * (data.heightDecreasedByOne - 1)) / s_minimalRectDimension;
     if (optimalThreadNumber > 1) {
         // Initialize parallel jobs
-        WTF::ParallelJobs<PlatformApplyGenericParameters> parallelJobs(&platformApplyGenericWorker, optimalThreadNumber);
+        ParallelJobs<PlatformApplyGenericParameters> parallelJobs(&platformApplyGenericWorker, optimalThreadNumber);
 
         // Fill the parameter array
         int job = parallelJobs.numberOfJobs();
@@ -416,7 +416,7 @@
 
 PassRefPtr<SkImageFilter> FELighting::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkImageFilter::CropRect rect = getCropRect(builder->cropOffset());
+    SkImageFilter::CropRect rect = getCropRect(builder ? builder->cropOffset() : FloatSize());
     RefPtr<SkImageFilter> input(builder ? builder->build(inputEffect(0), operatingColorSpace()) : 0);
     switch (m_lightSource->type()) {
     case LS_DISTANT: {
diff --git a/Source/core/platform/graphics/filters/FELighting.h b/Source/core/platform/graphics/filters/FELighting.h
index 6b4e476..dc8b319 100644
--- a/Source/core/platform/graphics/filters/FELighting.h
+++ b/Source/core/platform/graphics/filters/FELighting.h
@@ -30,10 +30,10 @@
 
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/LightSource.h"
 #include "core/platform/graphics/filters/PointLightSource.h"
 #include "core/platform/graphics/filters/SpotLightSource.h"
 #include "platform/graphics/Color.h"
+#include "platform/graphics/filters/LightSource.h"
 #include "wtf/Uint8ClampedArray.h"
 
 // Common base class for FEDiffuseLighting and FESpecularLighting
diff --git a/Source/core/platform/graphics/filters/FEMorphology.cpp b/Source/core/platform/graphics/filters/FEMorphology.cpp
index 1944712..d1dc8a0 100644
--- a/Source/core/platform/graphics/filters/FEMorphology.cpp
+++ b/Source/core/platform/graphics/filters/FEMorphology.cpp
@@ -27,9 +27,9 @@
 #include "core/platform/graphics/filters/FEMorphology.h"
 
 #include "core/platform/graphics/filters/Filter.h"
+#include "core/platform/graphics/filters/ParallelJobs.h"
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "platform/text/TextStream.h"
-#include "wtf/ParallelJobs.h"
 #include "wtf/Uint8ClampedArray.h"
 #include "wtf/Vector.h"
 
diff --git a/Source/core/platform/graphics/filters/FEOffset.cpp b/Source/core/platform/graphics/filters/FEOffset.cpp
index e027127..b37e7d0 100644
--- a/Source/core/platform/graphics/filters/FEOffset.cpp
+++ b/Source/core/platform/graphics/filters/FEOffset.cpp
@@ -27,7 +27,7 @@
 #include "core/platform/graphics/filters/FEOffset.h"
 
 #include "SkFlattenableBuffers.h"
-#include "SkImageFilter.h"
+#include "SkOffsetImageFilter.h"
 
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/filters/Filter.h"
@@ -37,59 +37,6 @@
 
 namespace WebCore {
 
-class OffsetImageFilter : public SkImageFilter {
-public:
-    OffsetImageFilter(SkScalar dx, SkScalar dy, SkImageFilter* input, const CropRect* cropRect = 0) : SkImageFilter(input, cropRect), m_dx(dx), m_dy(dy)
-    {
-    }
-
-    virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* dst, SkIPoint* offset)
-    {
-        SkBitmap source = src;
-        SkImageFilter* input = getInput(0);
-        SkIPoint srcOffset = SkIPoint::Make(0, 0);
-        if (input && !input->filterImage(proxy, src, ctm, &source, &srcOffset))
-            return false;
-
-        SkIRect bounds;
-        source.getBounds(&bounds);
-
-        if (!applyCropRect(&bounds, ctm)) {
-            return false;
-        }
-
-        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
-        SkCanvas canvas(device);
-        SkPaint paint;
-        paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-        canvas.drawBitmap(source, m_dx - bounds.left(), m_dy - bounds.top(), &paint);
-        *dst = device->accessBitmap(false);
-        offset->fX += bounds.left();
-        offset->fY += bounds.top();
-        return true;
-    }
-
-    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(OffsetImageFilter)
-
-protected:
-    explicit OffsetImageFilter(SkFlattenableReadBuffer& buffer)
-        : SkImageFilter(buffer)
-    {
-        m_dx = buffer.readScalar();
-        m_dy = buffer.readScalar();
-    }
-
-    virtual void flatten(SkFlattenableWriteBuffer& buffer) const
-    {
-        this->SkImageFilter::flatten(buffer);
-        buffer.writeScalar(m_dx);
-        buffer.writeScalar(m_dy);
-    }
-
-private:
-    SkScalar m_dx, m_dy;
-};
-
 FEOffset::FEOffset(Filter* filter, float dx, float dy)
     : FilterEffect(filter)
     , m_dx(dx)
@@ -165,7 +112,7 @@
     RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     Filter* filter = this->filter();
     SkImageFilter::CropRect cropRect = getCropRect(builder->cropOffset());
-    return adoptRef(new OffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input.get(), &cropRect));
+    return adoptRef(new SkOffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input.get(), &cropRect));
 }
 
 TextStream& FEOffset::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FESpecularLighting.cpp b/Source/core/platform/graphics/filters/FESpecularLighting.cpp
index 388a6a6..2831fb9 100644
--- a/Source/core/platform/graphics/filters/FESpecularLighting.cpp
+++ b/Source/core/platform/graphics/filters/FESpecularLighting.cpp
@@ -24,7 +24,7 @@
 
 #include "core/platform/graphics/filters/FESpecularLighting.h"
 
-#include "core/platform/graphics/filters/LightSource.h"
+#include "platform/graphics/filters/LightSource.h"
 #include "platform/text/TextStream.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/graphics/filters/FETile.cpp b/Source/core/platform/graphics/filters/FETile.cpp
index d00e0c4..438c971 100644
--- a/Source/core/platform/graphics/filters/FETile.cpp
+++ b/Source/core/platform/graphics/filters/FETile.cpp
@@ -24,83 +24,18 @@
 #include "core/platform/graphics/filters/FETile.h"
 
 #include "SkFlattenableBuffers.h"
-#include "SkImageFilter.h"
+#include "SkTileImageFilter.h"
 
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/Pattern.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/rendering/svg/SVGRenderingContext.h"
 #include "platform/text/TextStream.h"
 #include "platform/transforms/AffineTransform.h"
 #include "third_party/skia/include/core/SkDevice.h"
 
 namespace WebCore {
 
-class TileImageFilter : public SkImageFilter {
-public:
-    TileImageFilter(const SkRect& srcRect, const SkRect& dstRect, SkImageFilter* input)
-        : SkImageFilter(input)
-        , m_srcRect(srcRect)
-        , m_dstRect(dstRect)
-    {
-    }
-
-    virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* dst, SkIPoint* offset)
-    {
-        SkBitmap source = src;
-        SkImageFilter* input = getInput(0);
-        SkIPoint localOffset = SkIPoint::Make(0, 0);
-        if (input && !input->filterImage(proxy, src, ctm, &source, &localOffset))
-            return false;
-
-        if (!m_srcRect.width() || !m_srcRect.height() || !m_dstRect.width() || !m_dstRect.height())
-            return false;
-
-        SkIRect srcRect;
-        m_srcRect.roundOut(&srcRect);
-        SkBitmap subset;
-        if (!source.extractSubset(&subset, srcRect))
-            return false;
-
-        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(m_dstRect.width(), m_dstRect.height()));
-        SkIRect bounds;
-        source.getBounds(&bounds);
-        SkCanvas canvas(device);
-        SkPaint paint;
-        paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-
-        SkAutoTUnref<SkShader> shader(SkShader::CreateBitmapShader(subset, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
-        paint.setShader(shader);
-        SkRect dstRect = m_dstRect;
-        dstRect.offset(localOffset.fX, localOffset.fY);
-        canvas.drawRect(dstRect, paint);
-        *dst = device->accessBitmap(false);
-        return true;
-    }
-
-    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(TileImageFilter)
-
-protected:
-    explicit TileImageFilter(SkFlattenableReadBuffer& buffer)
-        : SkImageFilter(buffer)
-    {
-        buffer.readRect(&m_srcRect);
-        buffer.readRect(&m_dstRect);
-    }
-
-    virtual void flatten(SkFlattenableWriteBuffer& buffer) const
-    {
-        this->SkImageFilter::flatten(buffer);
-        buffer.writeRect(m_srcRect);
-        buffer.writeRect(m_dstRect);
-    }
-
-private:
-    SkRect m_srcRect;
-    SkRect m_dstRect;
-};
-
 FETile::FETile(Filter* filter)
     : FilterEffect(filter)
 {
@@ -132,8 +67,8 @@
         tileRect.scale(filter->filterResolution().width(), filter->filterResolution().height());
     }
 
-    OwnPtr<ImageBuffer> tileImage;
-    if (!SVGRenderingContext::createImageBufferForPattern(tileRect, tileRect, tileImage, filter()->renderingMode()))
+    OwnPtr<ImageBuffer> tileImage = ImageBuffer::createBufferForTile(tileRect.size(), tileRect.size(), filter()->renderingMode());
+    if (!tileImage)
         return;
 
     GraphicsContext* tileImageContext = tileImage->context();
@@ -154,7 +89,7 @@
 {
     RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     FloatRect srcRect = inputEffect(0) ? inputEffect(0)->effectBoundaries() : FloatRect();
-    return adoptRef(new TileImageFilter(srcRect, effectBoundaries(), input.get()));
+    return adoptRef(new SkTileImageFilter(srcRect, effectBoundaries(), input.get()));
 }
 
 TextStream& FETile::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FETurbulence.cpp b/Source/core/platform/graphics/filters/FETurbulence.cpp
index 6d6d8ec..3a08013 100644
--- a/Source/core/platform/graphics/filters/FETurbulence.cpp
+++ b/Source/core/platform/graphics/filters/FETurbulence.cpp
@@ -29,10 +29,10 @@
 #include "SkPerlinNoiseShader.h"
 #include "SkRectShaderImageFilter.h"
 #include "core/platform/graphics/filters/Filter.h"
+#include "core/platform/graphics/filters/ParallelJobs.h"
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "platform/text/TextStream.h"
 #include "wtf/MathExtras.h"
-#include "wtf/ParallelJobs.h"
 #include "wtf/Uint8ClampedArray.h"
 
 namespace WebCore {
@@ -371,7 +371,7 @@
     int optimalThreadNumber = (absolutePaintRect().width() * absolutePaintRect().height()) / s_minimalRectDimension;
     if (optimalThreadNumber > 1) {
         // Initialize parallel jobs
-        WTF::ParallelJobs<FillRegionParameters> parallelJobs(&WebCore::FETurbulence::fillRegionWorker, optimalThreadNumber);
+        ParallelJobs<FillRegionParameters> parallelJobs(&WebCore::FETurbulence::fillRegionWorker, optimalThreadNumber);
 
         // Fill the parameter array
         int i = parallelJobs.numberOfJobs();
@@ -428,7 +428,7 @@
     if (!resultImage)
         return false;
 
-    const IntRect filterRegion = absolutePaintRect();
+    const IntRect filterRegion(IntPoint::zero(), absolutePaintRect().size());
 
     SkPaint paint;
     paint.setShader(createShader(filterRegion))->unref();
diff --git a/Source/core/platform/graphics/filters/FilterOperation.cpp b/Source/core/platform/graphics/filters/FilterOperation.cpp
index de27ba4..ee21fa5 100644
--- a/Source/core/platform/graphics/filters/FilterOperation.cpp
+++ b/Source/core/platform/graphics/filters/FilterOperation.cpp
@@ -44,7 +44,7 @@
     double fromAmount;
     if (from) {
         ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
-        fromAmount = static_cast<const BasicColorMatrixFilterOperation*>(from)->amount();
+        fromAmount = toBasicColorMatrixFilterOperation(from)->amount();
     } else {
         switch (m_type) {
         case GRAYSCALE:
@@ -83,7 +83,7 @@
     double fromAmount;
     if (from) {
         ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
-        fromAmount = static_cast<const BasicComponentTransferFilterOperation*>(from)->amount();
+        fromAmount = toBasicComponentTransferFilterOperation(from)->amount();
     } else {
         switch (m_type) {
         case OPACITY:
@@ -116,48 +116,30 @@
     return BasicComponentTransferFilterOperation::create(result, m_type);
 }
 
-PassRefPtr<FilterOperation> GammaFilterOperation::blend(const FilterOperation* from, double progress) const
-{
-    if (!from)
-        return GammaFilterOperation::create(
-            WebCore::blend(m_amplitude, 1.0, progress),
-            WebCore::blend(m_exponent, 1.0, progress),
-            WebCore::blend(m_offset, 0.0, progress), m_type);
-
-    ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
-    const GammaFilterOperation* fromOp = static_cast<const GammaFilterOperation*>(from);
-    return GammaFilterOperation::create(
-        WebCore::blend(fromOp->amplitude(), m_amplitude, progress),
-        WebCore::blend(fromOp->exponent(), m_exponent, progress),
-        WebCore::blend(fromOp->offset(), m_offset, progress), m_type);
-}
-
 PassRefPtr<FilterOperation> BlurFilterOperation::blend(const FilterOperation* from, double progress) const
 {
     LengthType lengthType = m_stdDeviation.type();
     if (!from)
-        return BlurFilterOperation::create(m_stdDeviation.blend(Length(lengthType), progress, ValueRangeNonNegative), m_type);
+        return BlurFilterOperation::create(m_stdDeviation.blend(Length(lengthType), progress, ValueRangeNonNegative));
 
-    ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
-    const BlurFilterOperation* fromOp = static_cast<const BlurFilterOperation*>(from);
-    return BlurFilterOperation::create(m_stdDeviation.blend(fromOp->m_stdDeviation, progress, ValueRangeNonNegative), m_type);
+    const BlurFilterOperation* fromOp = toBlurFilterOperation(from);
+    return BlurFilterOperation::create(m_stdDeviation.blend(fromOp->m_stdDeviation, progress, ValueRangeNonNegative));
 }
 
 PassRefPtr<FilterOperation> DropShadowFilterOperation::blend(const FilterOperation* from, double progress) const
 {
-    if (!from)
+    if (!from) {
         return DropShadowFilterOperation::create(
             WebCore::blend(IntPoint(), m_location, progress),
             WebCore::blend(0, m_stdDeviation, progress),
-            WebCore::blend(Color(Color::transparent), m_color, progress),
-            m_type);
+            WebCore::blend(Color(Color::transparent), m_color, progress));
+    }
 
-    ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
-    const DropShadowFilterOperation* fromOp = static_cast<const DropShadowFilterOperation*>(from);
+    const DropShadowFilterOperation* fromOp = toDropShadowFilterOperation(from);
     return DropShadowFilterOperation::create(
         WebCore::blend(fromOp->location(), m_location, progress),
         WebCore::blend(fromOp->stdDeviation(), m_stdDeviation, progress),
-        WebCore::blend(fromOp->color(), m_color, progress), m_type);
+        WebCore::blend(fromOp->color(), m_color, progress));
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/filters/FilterOperation.h b/Source/core/platform/graphics/filters/FilterOperation.h
index 6b83c6e..489bfe6 100644
--- a/Source/core/platform/graphics/filters/FilterOperation.h
+++ b/Source/core/platform/graphics/filters/FilterOperation.h
@@ -26,7 +26,6 @@
 #ifndef FilterOperation_h
 #define FilterOperation_h
 
-#include "core/fetch/DocumentResourceReference.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/ReferenceFilter.h"
 #include "platform/Length.h"
@@ -90,10 +89,8 @@
     virtual bool operator==(const FilterOperation&) const = 0;
     bool operator!=(const FilterOperation& o) const { return !(*this == o); }
 
-    virtual OperationType getOperationType() const { return m_type; }
-    virtual bool isSameType(const FilterOperation& o) const { return o.getOperationType() == m_type; }
-
-    virtual bool isDefault() const { return false; }
+    OperationType type() const { return m_type; }
+    virtual bool isSameType(const FilterOperation& o) const { return o.type() == m_type; }
 
     // True if the alpha channel of any pixel can change under this operation.
     virtual bool affectsOpacity() const { return false; }
@@ -112,38 +109,14 @@
     virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const = 0;
 };
 
-class DefaultFilterOperation : public FilterOperation {
-public:
-    static PassRefPtr<DefaultFilterOperation> create(OperationType type)
-    {
-        return adoptRef(new DefaultFilterOperation(type));
-    }
-
-private:
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation*, double) const OVERRIDE
-    {
-        ASSERT_NOT_REACHED();
-        return 0;
-    }
-
-    virtual bool operator==(const FilterOperation& o) const
-    {
-        return isSameType(o);
-    }
-
-    virtual bool isDefault() const { return true; }
-
-    DefaultFilterOperation(OperationType type)
-        : FilterOperation(type)
-    {
-    }
-};
+#define DEFINE_FILTER_OPERATION_TYPE_CASTS(thisType, operationType) \
+    DEFINE_TYPE_CASTS(thisType, FilterOperation, op, op->type() == FilterOperation::operationType, op.type() == FilterOperation::operationType);
 
 class ReferenceFilterOperation : public FilterOperation {
 public:
-    static PassRefPtr<ReferenceFilterOperation> create(const String& url, const String& fragment, OperationType type)
+    static PassRefPtr<ReferenceFilterOperation> create(const String& url, const String& fragment)
     {
-        return adoptRef(new ReferenceFilterOperation(url, fragment, type));
+        return adoptRef(new ReferenceFilterOperation(url, fragment));
     }
 
     virtual bool affectsOpacity() const { return true; }
@@ -152,9 +125,6 @@
     const String& url() const { return m_url; }
     const String& fragment() const { return m_fragment; }
 
-    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; }
 
@@ -173,8 +143,8 @@
         return m_url == other->m_url;
     }
 
-    ReferenceFilterOperation(const String& url, const String& fragment, OperationType type)
-        : FilterOperation(type)
+    ReferenceFilterOperation(const String& url, const String& fragment)
+        : FilterOperation(REFERENCE)
         , m_url(url)
         , m_fragment(fragment)
     {
@@ -182,10 +152,11 @@
 
     String m_url;
     String m_fragment;
-    OwnPtr<DocumentResourceReference> m_documentResourceReference;
     RefPtr<ReferenceFilter> m_filter;
 };
 
+DEFINE_FILTER_OPERATION_TYPE_CASTS(ReferenceFilterOperation, REFERENCE);
+
 // GRAYSCALE, SEPIA, SATURATE and HUE_ROTATE are variations on a basic color matrix effect.
 // For HUE_ROTATE, the angle of rotation is stored in m_amount.
 class BasicColorMatrixFilterOperation : public FilterOperation {
@@ -217,6 +188,14 @@
     double m_amount;
 };
 
+inline bool isBasicColorMatrixFilterOperation(const FilterOperation& operation)
+{
+    FilterOperation::OperationType type = operation.type();
+    return type == FilterOperation::GRAYSCALE || type == FilterOperation::SEPIA || type == FilterOperation::SATURATE || type == FilterOperation::HUE_ROTATE;
+}
+
+DEFINE_TYPE_CASTS(BasicColorMatrixFilterOperation, FilterOperation, op, isBasicColorMatrixFilterOperation(*op), isBasicColorMatrixFilterOperation(op));
+
 // INVERT, BRIGHTNESS, CONTRAST and OPACITY are variations on a basic component transfer effect.
 class BasicComponentTransferFilterOperation : public FilterOperation {
 public:
@@ -249,46 +228,19 @@
     double m_amount;
 };
 
-class GammaFilterOperation : public FilterOperation {
-public:
-    static PassRefPtr<GammaFilterOperation> create(double amplitude, double exponent, double offset, OperationType type)
-    {
-        return adoptRef(new GammaFilterOperation(amplitude, exponent, offset, type));
-    }
+inline bool isBasicComponentTransferFilterOperation(const FilterOperation& operation)
+{
+    FilterOperation::OperationType type = operation.type();
+    return type == FilterOperation::INVERT || type == FilterOperation::OPACITY || type == FilterOperation::BRIGHTNESS || type == FilterOperation::CONTRAST;
+}
 
-    double amplitude() const { return m_amplitude; }
-    double exponent() const { return m_exponent; }
-    double offset() const { return m_offset; }
-
-
-private:
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
-    virtual bool operator==(const FilterOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const GammaFilterOperation* other = static_cast<const GammaFilterOperation*>(&o);
-        return m_amplitude == other->m_amplitude && m_exponent == other->m_exponent && m_offset == other->m_offset;
-    }
-
-    GammaFilterOperation(double amplitude, double exponent, double offset, OperationType type)
-        : FilterOperation(type)
-        , m_amplitude(amplitude)
-        , m_exponent(exponent)
-        , m_offset(offset)
-    {
-    }
-
-    double m_amplitude;
-    double m_exponent;
-    double m_offset;
-};
+DEFINE_TYPE_CASTS(BasicComponentTransferFilterOperation, FilterOperation, op, isBasicComponentTransferFilterOperation(*op), isBasicComponentTransferFilterOperation(op));
 
 class BlurFilterOperation : public FilterOperation {
 public:
-    static PassRefPtr<BlurFilterOperation> create(Length stdDeviation, OperationType type)
+    static PassRefPtr<BlurFilterOperation> create(Length stdDeviation)
     {
-        return adoptRef(new BlurFilterOperation(stdDeviation, type));
+        return adoptRef(new BlurFilterOperation(stdDeviation));
     }
 
     Length stdDeviation() const { return m_stdDeviation; }
@@ -307,8 +259,8 @@
         return m_stdDeviation == other->m_stdDeviation;
     }
 
-    BlurFilterOperation(Length stdDeviation, OperationType type)
-        : FilterOperation(type)
+    BlurFilterOperation(Length stdDeviation)
+        : FilterOperation(BLUR)
         , m_stdDeviation(stdDeviation)
     {
     }
@@ -316,11 +268,13 @@
     Length m_stdDeviation;
 };
 
+DEFINE_FILTER_OPERATION_TYPE_CASTS(BlurFilterOperation, BLUR);
+
 class DropShadowFilterOperation : public FilterOperation {
 public:
-    static PassRefPtr<DropShadowFilterOperation> create(const IntPoint& location, int stdDeviation, Color color, OperationType type)
+    static PassRefPtr<DropShadowFilterOperation> create(const IntPoint& location, int stdDeviation, Color color)
     {
-        return adoptRef(new DropShadowFilterOperation(location, stdDeviation, color, type));
+        return adoptRef(new DropShadowFilterOperation(location, stdDeviation, color));
     }
 
     int x() const { return m_location.x(); }
@@ -343,8 +297,8 @@
         return m_location == other->m_location && m_stdDeviation == other->m_stdDeviation && m_color == other->m_color;
     }
 
-    DropShadowFilterOperation(const IntPoint& location, int stdDeviation, Color color, OperationType type)
-        : FilterOperation(type)
+    DropShadowFilterOperation(const IntPoint& location, int stdDeviation, Color color)
+        : FilterOperation(DROP_SHADOW)
         , m_location(location)
         , m_stdDeviation(stdDeviation)
         , m_color(color)
@@ -356,6 +310,8 @@
     Color m_color;
 };
 
+DEFINE_FILTER_OPERATION_TYPE_CASTS(DropShadowFilterOperation, DROP_SHADOW);
+
 } // namespace WebCore
 
 
diff --git a/Source/core/platform/graphics/filters/FilterOperations.cpp b/Source/core/platform/graphics/filters/FilterOperations.cpp
index 768a8cf..42c1daf 100644
--- a/Source/core/platform/graphics/filters/FilterOperations.cpp
+++ b/Source/core/platform/graphics/filters/FilterOperations.cpp
@@ -73,12 +73,12 @@
 bool FilterOperations::canInterpolateWith(const FilterOperations& other) const
 {
     for (size_t i = 0; i < operations().size(); ++i) {
-        if (!FilterOperation::canInterpolate(operations()[i]->getOperationType()))
+        if (!FilterOperation::canInterpolate(operations()[i]->type()))
             return false;
     }
 
     for (size_t i = 0; i < other.operations().size(); ++i) {
-        if (!FilterOperation::canInterpolate(other.operations()[i]->getOperationType()))
+        if (!FilterOperation::canInterpolate(other.operations()[i]->type()))
             return false;
     }
 
@@ -93,7 +93,7 @@
 bool FilterOperations::hasCustomFilter() const
 {
     for (size_t i = 0; i < m_operations.size(); ++i) {
-        FilterOperation::OperationType type = m_operations.at(i)->getOperationType();
+        FilterOperation::OperationType type = m_operations.at(i)->type();
         if (type == FilterOperation::CUSTOM || type == FilterOperation::VALIDATED_CUSTOM)
             return true;
     }
@@ -103,7 +103,7 @@
 bool FilterOperations::hasReferenceFilter() const
 {
     for (size_t i = 0; i < m_operations.size(); ++i) {
-        if (m_operations.at(i)->getOperationType() == FilterOperation::REFERENCE)
+        if (m_operations.at(i)->type() == FilterOperation::REFERENCE)
             return true;
     }
     return false;
@@ -112,7 +112,7 @@
 bool FilterOperations::hasOutsets() const
 {
     for (size_t i = 0; i < m_operations.size(); ++i) {
-        FilterOperation::OperationType operationType = m_operations.at(i).get()->getOperationType();
+        FilterOperation::OperationType operationType = m_operations.at(i)->type();
         if (operationType == FilterOperation::BLUR || operationType == FilterOperation::DROP_SHADOW || operationType == FilterOperation::REFERENCE)
             return true;
     }
@@ -124,9 +124,9 @@
     FilterOutsets totalOutsets;
     for (size_t i = 0; i < m_operations.size(); ++i) {
         FilterOperation* filterOperation = m_operations.at(i).get();
-        switch (filterOperation->getOperationType()) {
+        switch (filterOperation->type()) {
         case FilterOperation::BLUR: {
-            BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
+            BlurFilterOperation* blurOperation = toBlurFilterOperation(filterOperation);
             float stdDeviation = floatValueForLength(blurOperation->stdDeviation(), 0);
             IntSize outsetSize = outsetSizeForBlur(stdDeviation);
             FilterOutsets outsets(outsetSize.height(), outsetSize.width(), outsetSize.height(), outsetSize.width());
@@ -134,7 +134,7 @@
             break;
         }
         case FilterOperation::DROP_SHADOW: {
-            DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
+            DropShadowFilterOperation* dropShadowOperation = toDropShadowFilterOperation(filterOperation);
             IntSize outsetSize = outsetSizeForBlur(dropShadowOperation->stdDeviation());
             FilterOutsets outsets(
                 std::max(0, outsetSize.height() - dropShadowOperation->y()),
@@ -146,7 +146,7 @@
             break;
         }
         case FilterOperation::REFERENCE: {
-            ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
+            ReferenceFilterOperation* referenceOperation = toReferenceFilterOperation(filterOperation);
             if (referenceOperation->filter() && referenceOperation->filter()->lastEffect()) {
                 FloatRect outsetRect(0, 0, 1, 1);
                 outsetRect = referenceOperation->filter()->lastEffect()->mapRectRecursive(outsetRect);
diff --git a/Source/core/platform/graphics/filters/LightSource.h b/Source/core/platform/graphics/filters/LightSource.h
deleted file mode 100644
index e6ece4a..0000000
--- a/Source/core/platform/graphics/filters/LightSource.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>
- *
- * 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.
- */
-
-#ifndef LightSource_h
-#define LightSource_h
-
-#include "platform/geometry/FloatPoint3D.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-enum LightType {
-    LS_DISTANT,
-    LS_POINT,
-    LS_SPOT
-};
-
-class TextStream;
-
-class LightSource : public RefCounted<LightSource> {
-public:
-
-    // Light vectors must be calculated for every pixel during
-    // painting. It is expensive to pass all these arguments to
-    // a frequently called function, especially because not all
-    // light sources require all of them. Instead, we just pass
-    // a reference to the following structure
-    struct PaintingData {
-        // SVGFELighting also use them
-        FloatPoint3D lightVector;
-        FloatPoint3D colorVector;
-        float lightVectorLength;
-        // Private members
-        FloatPoint3D directionVector;
-        FloatPoint3D privateColorVector;
-        float coneCutOffLimit;
-        float coneFullLight;
-        int specularExponent;
-    };
-
-    LightSource(LightType type)
-        : m_type(type)
-    { }
-
-    virtual ~LightSource() { }
-
-    LightType type() const { return m_type; }
-    virtual TextStream& externalRepresentation(TextStream&) const = 0;
-
-    virtual void initPaintingData(PaintingData&) = 0;
-    // z is a float number, since it is the alpha value scaled by a user
-    // specified "surfaceScale" constant, which type is <number> in the SVG standard
-    virtual void updatePaintingData(PaintingData&, int x, int y, float z) = 0;
-
-    virtual bool setAzimuth(float) { return false; }
-    virtual bool setElevation(float) { return false; }
-    virtual bool setX(float) { return false; }
-    virtual bool setY(float) { return false; }
-    virtual bool setZ(float) { return false; }
-    virtual bool setPointsAtX(float) { return false; }
-    virtual bool setPointsAtY(float) { return false; }
-    virtual bool setPointsAtZ(float) { return false; }
-    virtual bool setSpecularExponent(float) { return false; }
-    virtual bool setLimitingConeAngle(float) { return false; }
-
-private:
-    LightType m_type;
-};
-
-} // namespace WebCore
-
-#endif // LightSource_h
diff --git a/Source/core/platform/graphics/filters/ParallelJobs.h b/Source/core/platform/graphics/filters/ParallelJobs.h
new file mode 100644
index 0000000..1790901
--- /dev/null
+++ b/Source/core/platform/graphics/filters/ParallelJobs.h
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2011 University of Szeged
+ * Copyright (C) 2011 Gabor Loki <loki@webkit.org>
+ * 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 UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED 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 ParallelJobs_h
+#define ParallelJobs_h
+
+#include "platform/Task.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebThread.h"
+#include "wtf/Assertions.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/Vector.h"
+
+// Usage:
+//
+//     // Initialize parallel jobs
+//     ParallelJobs<TypeOfParameter> parallelJobs(&worker, requestedNumberOfJobs);
+//
+//     // Fill the parameter array
+//     for(i = 0; i < parallelJobs.numberOfJobs(); ++i) {
+//       TypeOfParameter& params = parallelJobs.parameter(i);
+//       params.attr1 = localVars ...
+//       ...
+//     }
+//
+//     // Execute parallel jobs
+//     parallelJobs.execute();
+//
+
+namespace WebCore {
+
+template<typename Type>
+class ParallelJobs {
+    WTF_MAKE_NONCOPYABLE(ParallelJobs);
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    typedef void (*WorkerFunction)(Type*);
+
+    ParallelJobs(WorkerFunction func, size_t requestedJobNumber)
+        : m_func(func)
+    {
+        m_parameters.grow(requestedJobNumber);
+        // The main thread can execute one job, so only create requestJobNumber - 1 threads.
+        for (size_t i = 0; i < requestedJobNumber - 1; ++i) {
+            OwnPtr<blink::WebThread> thread = adoptPtr(blink::Platform::current()->createThread("Unfortunate parallel worker"));
+            m_threads.append(thread.release());
+        }
+    }
+
+    size_t numberOfJobs()
+    {
+        return m_parameters.size();
+    }
+
+    Type& parameter(size_t i)
+    {
+        return m_parameters[i];
+    }
+
+    void execute()
+    {
+        for (size_t i = 0; i < numberOfJobs() - 1; ++i)
+            m_threads[i]->postTask(new Task(WTF::bind(m_func, &parameter(i))));
+        m_func(&parameter(numberOfJobs() - 1));
+        m_threads.clear();
+    }
+
+private:
+    WorkerFunction m_func;
+    Vector<OwnPtr<blink::WebThread> > m_threads;
+    Vector<Type> m_parameters;
+};
+
+} // namespace WebCore
+
+#endif // ParallelJobs_h
diff --git a/Source/core/platform/graphics/filters/PointLightSource.h b/Source/core/platform/graphics/filters/PointLightSource.h
index c27de27..51e9e51 100644
--- a/Source/core/platform/graphics/filters/PointLightSource.h
+++ b/Source/core/platform/graphics/filters/PointLightSource.h
@@ -23,7 +23,7 @@
 #ifndef PointLightSource_h
 #define PointLightSource_h
 
-#include "core/platform/graphics/filters/LightSource.h"
+#include "platform/graphics/filters/LightSource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
index 9d5f88f..1144e1c 100644
--- a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
+++ b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
@@ -85,7 +85,7 @@
     return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), input));
 }
 
-bool SkiaImageFilterBuilder::buildFilterOperations(const FilterOperations& operations, WebKit::WebFilterOperations* filters)
+bool SkiaImageFilterBuilder::buildFilterOperations(const FilterOperations& operations, blink::WebFilterOperations* filters)
 {
     if (!filters)
         return false;
@@ -100,11 +100,10 @@
 
     for (size_t i = 0; i < operations.size(); ++i) {
         const FilterOperation& op = *operations.at(i);
-        switch (op.getOperationType()) {
+        switch (op.type()) {
         case FilterOperation::REFERENCE: {
             RefPtr<SkImageFilter> filter;
-            const ReferenceFilterOperation* referenceFilterOperation = static_cast<const ReferenceFilterOperation*>(&op);
-            ReferenceFilter* referenceFilter = referenceFilterOperation->filter();
+            ReferenceFilter* referenceFilter = toReferenceFilterOperation(op).filter();
             if (referenceFilter && referenceFilter->lastEffect()) {
                 FilterEffect* filterEffect = referenceFilter->lastEffect();
                 // Link SourceGraphic to a noop filter that serves as a placholder for
@@ -130,8 +129,8 @@
         case FilterOperation::SEPIA:
         case FilterOperation::SATURATE:
         case FilterOperation::HUE_ROTATE: {
-            float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
-            switch (op.getOperationType()) {
+            float amount = toBasicColorMatrixFilterOperation(op).amount();
+            switch (op.type()) {
             case FilterOperation::GRAYSCALE:
                 filters->appendGrayscaleFilter(amount);
                 break;
@@ -153,8 +152,8 @@
         case FilterOperation::OPACITY:
         case FilterOperation::BRIGHTNESS:
         case FilterOperation::CONTRAST: {
-            float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
-            switch (op.getOperationType()) {
+            float amount = toBasicComponentTransferFilterOperation(op).amount();
+            switch (op.type()) {
             case FilterOperation::INVERT:
                 filters->appendInvertFilter(amount);
                 break;
@@ -173,13 +172,13 @@
             break;
         }
         case FilterOperation::BLUR: {
-            float pixelRadius = static_cast<const BlurFilterOperation*>(&op)->stdDeviation().getFloatValue();
+            float pixelRadius = toBlurFilterOperation(op).stdDeviation().getFloatValue();
             filters->appendBlurFilter(pixelRadius);
             break;
         }
         case FilterOperation::DROP_SHADOW: {
-            const DropShadowFilterOperation* drop = static_cast<const DropShadowFilterOperation*>(&op);
-            filters->appendDropShadowFilter(WebKit::WebPoint(drop->x(), drop->y()), drop->stdDeviation(), drop->color().rgb());
+            const DropShadowFilterOperation& drop = toDropShadowFilterOperation(op);
+            filters->appendDropShadowFilter(blink::WebPoint(drop.x(), drop.y()), drop.stdDeviation(), drop.color().rgb());
             break;
         }
         case FilterOperation::VALIDATED_CUSTOM:
diff --git a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
index b798f16..d21afdd 100644
--- a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
+++ b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
@@ -43,7 +43,7 @@
     ~SkiaImageFilterBuilder();
 
     PassRefPtr<SkImageFilter> build(FilterEffect*, ColorSpace);
-    bool buildFilterOperations(const FilterOperations&, WebKit::WebFilterOperations*);
+    bool buildFilterOperations(const FilterOperations&, blink::WebFilterOperations*);
 
     PassRefPtr<SkImageFilter> transformColorSpace(
         SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace);
diff --git a/Source/core/platform/graphics/filters/SpotLightSource.h b/Source/core/platform/graphics/filters/SpotLightSource.h
index 7379e66..2131e11 100644
--- a/Source/core/platform/graphics/filters/SpotLightSource.h
+++ b/Source/core/platform/graphics/filters/SpotLightSource.h
@@ -23,7 +23,7 @@
 #ifndef SpotLightSource_h
 #define SpotLightSource_h
 
-#include "core/platform/graphics/filters/LightSource.h"
+#include "platform/graphics/filters/LightSource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h b/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h
index c5a5d42..9375d96 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h
@@ -31,7 +31,7 @@
 #define CustomFilterCompiledProgram_h
 
 #include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp
index 8088f08..0c8857b 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp
@@ -100,7 +100,7 @@
 void CustomFilterGlobalContext::removeValidatedProgram(const CustomFilterValidatedProgram* program)
 {
     CustomFilterValidatedProgramsMap::iterator iter = m_programs.find(program->programInfo());
-    ASSERT(iter != m_programs.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(iter != m_programs.end());
     m_programs.remove(iter);
 
 #ifndef NDEBUG
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h b/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h
index c417b89..41fe2e7 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h
@@ -30,8 +30,8 @@
 #ifndef CustomFilterGlobalContext_h
 #define CustomFilterGlobalContext_h
 
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "platform/graphics/angle/ANGLEPlatformBridge.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp
index 9d6894e..b18d65b 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp
@@ -31,7 +31,7 @@
 
 #include "core/platform/graphics/GraphicsContext3D.h"
 #include "core/platform/graphics/filters/custom/CustomFilterMesh.h"
-#include "core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h"
+#include "platform/graphics/filters/custom/CustomFilterMeshGenerator.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp
deleted file mode 100644
index ff191c5..0000000
--- a/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 HOLDER 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/custom/CustomFilterMeshGenerator.h"
-
-#ifndef NDEBUG
-#include <stdio.h> // Needed for printf used in dumpBuffers.
-#endif
-
-namespace WebCore {
-
-#ifndef NDEBUG
-// Use "call 'WebCore::s_dumpCustomFilterMeshBuffers' = 1" in GDB to activate printing of the mesh buffers.
-static bool s_dumpCustomFilterMeshBuffers = false;
-#endif
-
-CustomFilterMeshGenerator::CustomFilterMeshGenerator(unsigned columns, unsigned rows, const FloatRect& meshBox, CustomFilterMeshType meshType)
-    : m_meshType(meshType)
-    , m_points(columns + 1, rows + 1)
-    , m_tiles(columns, rows)
-    , m_tileSizeInPixels(meshBox.width() / m_tiles.width(), meshBox.height() / m_tiles.height())
-    , m_tileSizeInDeviceSpace(1.0f / m_tiles.width(), 1.0f / m_tiles.height())
-    , m_meshBox(meshBox)
-{
-    // Build the two buffers needed to draw triangles:
-    // * m_vertices has a number of float attributes that will be passed to the vertex shader
-    // for each computed vertex. This number is calculated in floatsPerVertex() based on the meshType.
-    // * m_indices is a buffer that will have 3 indices per triangle. Each index will point inside
-    // the m_vertices buffer.
-    m_vertices.reserveCapacity(verticesCount() * floatsPerVertex());
-    m_indices.reserveCapacity(indicesCount());
-
-    // Based on the meshType there can be two types of meshes.
-    // * attached: each triangle uses vertices from the neighbor triangles. This is useful to save some GPU memory
-    // when there's no need to explode the tiles.
-    // * detached: each triangle has its own vertices. This means each triangle can be moved independently and a vec3
-    // attribute is passed, so that each vertex can be uniquely identified.
-    if (m_meshType == MeshTypeAttached)
-        generateAttachedMesh();
-    else
-        generateDetachedMesh();
-
-#ifndef NDEBUG
-    if (s_dumpCustomFilterMeshBuffers)
-        dumpBuffers();
-#endif
-}
-
-void CustomFilterMeshGenerator::addAttachedMeshIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle)
-{
-    UNUSED_PARAM(triangle);
-    m_indices.append((quadY + triangleY) * m_points.width() + (quadX + triangleX));
-}
-
-void CustomFilterMeshGenerator::generateAttachedMesh()
-{
-    for (int j = 0; j < m_points.height(); ++j) {
-        for (int i = 0; i < m_points.width(); ++i)
-            addAttachedMeshVertexAttributes(i, j);
-    }
-
-    for (int j = 0; j < m_tiles.height(); ++j) {
-        for (int i = 0; i < m_tiles.width(); ++i)
-            addTile<&CustomFilterMeshGenerator::addAttachedMeshIndex>(i, j);
-    }
-}
-
-void CustomFilterMeshGenerator::addDetachedMeshVertexAndIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle)
-{
-    addDetachedMeshVertexAttributes(quadX, quadY, triangleX, triangleY, triangle);
-    m_indices.append(m_indices.size());
-}
-
-void CustomFilterMeshGenerator::generateDetachedMesh()
-{
-    for (int j = 0; j < m_tiles.height(); ++j) {
-        for (int i = 0; i < m_tiles.width(); ++i)
-            addTile<&CustomFilterMeshGenerator::addDetachedMeshVertexAndIndex>(i, j);
-    }
-}
-
-void CustomFilterMeshGenerator::addPositionAttribute(int quadX, int quadY)
-{
-    // vec4 a_position
-    m_vertices.append(m_tileSizeInPixels.width() * quadX - 0.5f + m_meshBox.x());
-    m_vertices.append(m_tileSizeInPixels.height() * quadY - 0.5f + m_meshBox.y());
-    m_vertices.append(0.0f); // z
-    m_vertices.append(1.0f);
-}
-
-void CustomFilterMeshGenerator::addTexCoordAttribute(int quadX, int quadY)
-{
-    // vec2 a_texCoord
-    m_vertices.append(m_tileSizeInPixels.width() * quadX + m_meshBox.x());
-    m_vertices.append(m_tileSizeInPixels.height() * quadY + m_meshBox.y());
-}
-
-void CustomFilterMeshGenerator::addMeshCoordAttribute(int quadX, int quadY)
-{
-    // vec2 a_meshCoord
-    m_vertices.append(m_tileSizeInDeviceSpace.width() * quadX);
-    m_vertices.append(m_tileSizeInDeviceSpace.height() * quadY);
-}
-
-void CustomFilterMeshGenerator::addTriangleCoordAttribute(int quadX, int quadY, int triangle)
-{
-    // vec3 a_triangleCoord
-    m_vertices.append(quadX);
-    m_vertices.append(quadY);
-    m_vertices.append(triangle);
-}
-
-void CustomFilterMeshGenerator::addAttachedMeshVertexAttributes(int quadX, int quadY)
-{
-    addPositionAttribute(quadX, quadY);
-    addTexCoordAttribute(quadX, quadY);
-    addMeshCoordAttribute(quadX, quadY);
-}
-
-void CustomFilterMeshGenerator::addDetachedMeshVertexAttributes(int quadX, int quadY, int triangleX, int triangleY, int triangle)
-{
-    addAttachedMeshVertexAttributes(quadX + triangleX, quadY + triangleY);
-    addTriangleCoordAttribute(quadX, quadY, triangle);
-}
-
-#ifndef NDEBUG
-void CustomFilterMeshGenerator::dumpBuffers() const
-{
-    printf("Mesh buffers: Points.width(): %d, Points.height(): %d meshBox: %f, %f, %f, %f, type: %s\n",
-        m_points.width(), m_points.height(), m_meshBox.x(), m_meshBox.y(), m_meshBox.width(), m_meshBox.height(),
-        (m_meshType == MeshTypeAttached) ? "Attached" : "Detached");
-    printf("---Vertex:\n\t");
-    for (unsigned i = 0; i < m_vertices.size(); ++i) {
-        printf("%f ", m_vertices.at(i));
-        if (!((i + 1) % floatsPerVertex()))
-            printf("\n\t");
-    }
-    printf("\n---Indices: ");
-    for (unsigned i = 0; i < m_indices.size(); ++i)
-        printf("%d ", m_indices.at(i));
-    printf("\n");
-}
-#endif
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h b/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h
deleted file mode 100644
index 8396c5f..0000000
--- a/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 HOLDER 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 CustomFilterMeshGenerator_h
-#define CustomFilterMeshGenerator_h
-
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "platform/geometry/FloatRect.h"
-#include "platform/graphics/filters/custom/CustomFilterConstants.h"
-
-namespace WebCore {
-
-class CustomFilterMeshGenerator {
-public:
-    // Lines and columns are the values passed in CSS. The result is vertex mesh that has 'rows' numbers of rows
-    // and 'columns' number of columns with a total of 'rows + 1' * 'columns + 1' vertices.
-    // MeshBox is the filtered area calculated defined using the border-box, padding-box, content-box or filter-box
-    // attributes. A value of (0, 0, 1, 1) will cover the entire output surface.
-    CustomFilterMeshGenerator(unsigned columns, unsigned rows, const FloatRect& meshBox, CustomFilterMeshType);
-
-    const Vector<float>& vertices() const { return m_vertices; }
-    const Vector<uint16_t>& indices() const { return m_indices; }
-
-    const IntSize& points() const { return m_points; }
-    unsigned pointsCount() const { return m_points.width() * m_points.height(); }
-
-    const IntSize& tiles() const { return m_tiles; }
-    unsigned tilesCount() const { return m_tiles.width() * m_tiles.height(); }
-
-    unsigned indicesCount() const
-    {
-        const unsigned trianglesPerTile = 2;
-        const unsigned indicesPerTriangle = 3;
-        return tilesCount() * trianglesPerTile * indicesPerTriangle;
-    }
-
-    unsigned floatsPerVertex() const
-    {
-        static const unsigned AttachedMeshVertexSize = PositionAttribSize + TexAttribSize + MeshAttribSize;
-        static const unsigned DetachedMeshVertexSize = AttachedMeshVertexSize + TriangleAttribSize;
-        return m_meshType == MeshTypeAttached ? AttachedMeshVertexSize : DetachedMeshVertexSize;
-    }
-
-    unsigned verticesCount() const
-    {
-        return m_meshType == MeshTypeAttached ? pointsCount() : indicesCount();
-    }
-
-private:
-    typedef void (CustomFilterMeshGenerator::*AddTriangleVertexFunction)(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
-    template <AddTriangleVertexFunction addTriangleVertex>
-    void addTile(int quadX, int quadY)
-    {
-        ((*this).*(addTriangleVertex))(quadX, quadY, 0, 0, 1);
-        ((*this).*(addTriangleVertex))(quadX, quadY, 1, 0, 2);
-        ((*this).*(addTriangleVertex))(quadX, quadY, 1, 1, 3);
-        ((*this).*(addTriangleVertex))(quadX, quadY, 0, 0, 4);
-        ((*this).*(addTriangleVertex))(quadX, quadY, 1, 1, 5);
-        ((*this).*(addTriangleVertex))(quadX, quadY, 0, 1, 6);
-    }
-
-    void addAttachedMeshIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
-    void generateAttachedMesh();
-
-    void addDetachedMeshVertexAndIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
-    void generateDetachedMesh();
-    void addPositionAttribute(int quadX, int quadY);
-    void addTexCoordAttribute(int quadX, int quadY);
-    void addMeshCoordAttribute(int quadX, int quadY);
-    void addTriangleCoordAttribute(int quadX, int quadY, int triangle);
-    void addAttachedMeshVertexAttributes(int quadX, int quadY);
-    void addDetachedMeshVertexAttributes(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
-#ifndef NDEBUG
-    void dumpBuffers() const;
-#endif
-
-private:
-    Vector<float> m_vertices;
-    Vector<uint16_t> m_indices;
-
-    CustomFilterMeshType m_meshType;
-    IntSize m_points;
-    IntSize m_tiles;
-    FloatSize m_tileSizeInPixels;
-    FloatSize m_tileSizeInDeviceSpace;
-    FloatRect m_meshBox;
-};
-
-} // namespace WebCore
-
-#endif // CustomFilterMeshGenerator_h
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
index 450fa1a..e6e1fcf 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
@@ -60,7 +60,7 @@
     }
 
     ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
-    const CustomFilterOperation* fromOp = static_cast<const CustomFilterOperation*>(from);
+    const CustomFilterOperation* fromOp = toCustomFilterOperation(from);
     if (m_program.get() != fromOp->m_program.get()
         || m_meshRows != fromOp->m_meshRows
         || m_meshColumns != fromOp->m_meshColumns
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
index ee50825..c157462 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
@@ -89,6 +89,8 @@
     CustomFilterMeshType m_meshType;
 };
 
+DEFINE_FILTER_OPERATION_TYPE_CASTS(CustomFilterOperation, CUSTOM);
+
 } // namespace WebCore
 
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp
index 266c56f..f69eca9 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp
@@ -30,8 +30,8 @@
 #include "config.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "platform/graphics/filters/custom/CustomFilterProgramClient.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h b/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h
index e8b62b2..73ab6e4 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h
@@ -30,7 +30,7 @@
 #ifndef CustomFilterProgram_h
 #define CustomFilterProgram_h
 
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 
 #include "wtf/HashCountedSet.h"
 #include "wtf/RefCounted.h"
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp
deleted file mode 100644
index 4a75a15..0000000
--- a/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 HOLDER 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/custom/CustomFilterProgramInfo.h"
-
-#include "wtf/HashFunctions.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-static unsigned hashPossiblyNullString(const String& string)
-{
-    return string.isNull() ? 0 : DefaultHash<String>::Hash::hash(string);
-}
-
-CustomFilterProgramInfo::CustomFilterProgramInfo()
-{
-}
-
-bool CustomFilterProgramInfo::isEmptyValue() const
-{
-    return m_vertexShaderString.isNull()
-        && m_fragmentShaderString.isNull();
-}
-
-CustomFilterProgramInfo::CustomFilterProgramInfo(WTF::HashTableDeletedValueType)
-    : m_vertexShaderString(WTF::HashTableDeletedValue)
-    , m_fragmentShaderString(WTF::HashTableDeletedValue)
-{
-}
-
-bool CustomFilterProgramInfo::isHashTableDeletedValue() const
-{
-    return m_vertexShaderString.isHashTableDeletedValue()
-        && m_fragmentShaderString.isHashTableDeletedValue();
-}
-
-CustomFilterProgramInfo::CustomFilterProgramInfo(const String& vertexShader, const String& fragmentShader, CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType)
-    : m_vertexShaderString(vertexShader)
-    , m_fragmentShaderString(fragmentShader)
-    , m_programType(programType)
-    , m_mixSettings(mixSettings)
-    , m_meshType(meshType)
-{
-    // At least one of the shaders needs to be non-null.
-    ASSERT(!m_vertexShaderString.isNull() || !m_fragmentShaderString.isNull());
-}
-
-unsigned CustomFilterProgramInfo::hash() const
-{
-    // At least one of the shaders needs to be non-null.
-    ASSERT(!m_vertexShaderString.isNull() || !m_fragmentShaderString.isNull());
-
-    bool blendsElementTexture = (m_programType == ProgramTypeBlendsElementTexture);
-    uintptr_t hashCodes[6] = {
-        hashPossiblyNullString(m_vertexShaderString),
-        hashPossiblyNullString(m_fragmentShaderString),
-        blendsElementTexture,
-        static_cast<uintptr_t>(blendsElementTexture ? m_mixSettings.blendMode : 0),
-        static_cast<uintptr_t>(blendsElementTexture ? m_mixSettings.compositeOperator : 0),
-        m_meshType
-    };
-    return StringHasher::hashMemory<sizeof(hashCodes)>(&hashCodes);
-}
-
-bool CustomFilterProgramInfo::operator==(const CustomFilterProgramInfo& o) const
-{
-    ASSERT(!isHashTableDeletedValue());
-    ASSERT(!o.isHashTableDeletedValue());
-
-    return m_programType == o.m_programType
-        && (m_programType != ProgramTypeBlendsElementTexture || m_mixSettings == o.m_mixSettings)
-        && m_meshType == o.m_meshType
-        && m_vertexShaderString == o.m_vertexShaderString
-        && m_fragmentShaderString == o.m_fragmentShaderString;
-}
-
-} // namespace WebCore
-
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h b/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h
deleted file mode 100644
index ce55b4b..0000000
--- a/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 HOLDER 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 CustomFilterProgramInfo_h
-#define CustomFilterProgramInfo_h
-
-#include "platform/graphics/GraphicsTypes.h"
-#include "platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/HashTraits.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-
-struct CustomFilterProgramMixSettings {
-    CustomFilterProgramMixSettings()
-        : blendMode(BlendModeNormal)
-        , compositeOperator(CompositeSourceAtop)
-    {
-    }
-
-    bool operator==(const CustomFilterProgramMixSettings& o) const
-    {
-        return blendMode == o.blendMode && compositeOperator == o.compositeOperator;
-    }
-
-    BlendMode blendMode;
-    CompositeOperator compositeOperator;
-};
-
-// CustomFilterProgramInfo is the key used to link CustomFilterProgram with CustomFilterCompiledProgram.
-// It can be used as a key in a HashMap, with the note that at least one of Strings needs to be non-null.
-// Null strings are placeholders for the default shader.
-class CustomFilterProgramInfo {
-public:
-    CustomFilterProgramInfo(const String&, const String&, CustomFilterProgramType, const CustomFilterProgramMixSettings&, CustomFilterMeshType);
-
-    CustomFilterProgramInfo();
-    bool isEmptyValue() const;
-
-    CustomFilterProgramInfo(WTF::HashTableDeletedValueType);
-    bool isHashTableDeletedValue() const;
-
-    unsigned hash() const;
-    bool operator==(const CustomFilterProgramInfo&) const;
-
-    const String& vertexShaderString() const { return m_vertexShaderString; }
-    const String& fragmentShaderString() const { return m_fragmentShaderString; }
-    CustomFilterProgramType programType() const { return m_programType; }
-    const CustomFilterProgramMixSettings& mixSettings() const { return m_mixSettings; }
-    CustomFilterMeshType meshType() const { return m_meshType; }
-private:
-    String m_vertexShaderString;
-    String m_fragmentShaderString;
-    CustomFilterProgramType m_programType;
-    CustomFilterProgramMixSettings m_mixSettings;
-    CustomFilterMeshType m_meshType;
-};
-
-struct CustomFilterProgramInfoHash {
-    static unsigned hash(const CustomFilterProgramInfo& programInfo) { return programInfo.hash(); }
-    static bool equal(const CustomFilterProgramInfo& a, const CustomFilterProgramInfo& b) { return a == b; }
-    static const bool safeToCompareToEmptyOrDeleted = false;
-};
-
-struct CustomFilterProgramInfoHashTraits : WTF::SimpleClassHashTraits<CustomFilterProgramInfo> {
-    static const bool hasIsEmptyValueFunction = true;
-    static bool isEmptyValue(const CustomFilterProgramInfo& info) { return info.isEmptyValue(); }
-};
-
-} // namespace WebCore
-
-namespace WTF {
-
-template<> struct HashTraits<WebCore::CustomFilterProgramInfo> : WebCore::CustomFilterProgramInfoHashTraits { };
-template<> struct DefaultHash<WebCore::CustomFilterProgramInfo> {
-    typedef WebCore::CustomFilterProgramInfoHash Hash;
-};
-
-}
-
-#endif // CustomFilterProgramInfo_h
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp
index cf13bbf..496fa89 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp
@@ -35,11 +35,11 @@
 #include "core/platform/graphics/GraphicsContext3D.h"
 #include "core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h"
 #include "core/platform/graphics/filters/custom/CustomFilterMesh.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 #include "platform/graphics/filters/custom/CustomFilterArrayParameter.h"
 #include "platform/graphics/filters/custom/CustomFilterConstants.h"
 #include "platform/graphics/filters/custom/CustomFilterNumberParameter.h"
 #include "platform/graphics/filters/custom/CustomFilterParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 #include "platform/transforms/TransformationMatrix.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h b/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
deleted file mode 100644
index 6927ae5..0000000
--- a/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 HOLDER 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 CustomFilterTransformParameter_h
-#define CustomFilterTransformParameter_h
-
-#include "platform/geometry/FloatSize.h"
-#include "platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "platform/transforms/TransformOperations.h"
-
-namespace WebCore {
-
-class FloatRect;
-class TransformationMatrix;
-
-class CustomFilterTransformParameter : public CustomFilterParameter {
-public:
-    static PassRefPtr<CustomFilterTransformParameter> create(const String& name)
-    {
-        return adoptRef(new CustomFilterTransformParameter(name));
-    }
-
-    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* fromParameter, double progress)
-    {
-        if (!fromParameter || !isSameType(*fromParameter))
-            return this;
-
-        const CustomFilterTransformParameter* fromTransformParameter = static_cast<const CustomFilterTransformParameter*>(fromParameter);
-        const TransformOperations& from = fromTransformParameter->operations();
-        const TransformOperations& to = operations();
-        if (from == to)
-            return this;
-
-        RefPtr<CustomFilterTransformParameter> result = CustomFilterTransformParameter::create(name());
-        if (from.size() && to.size())
-            result->setOperations(to.blend(from, progress));
-        else
-            result->setOperations(progress > 0.5 ? to : from);
-        return result;
-    }
-
-    virtual bool operator==(const CustomFilterParameter& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const CustomFilterTransformParameter* other = static_cast<const CustomFilterTransformParameter*>(&o);
-        return m_operations == other->m_operations;
-    }
-
-    void applyTransform(TransformationMatrix& transform, const FloatSize& boxSize) const
-    {
-        for (unsigned i = 0, size = m_operations.size(); i < size; ++i)
-            m_operations.at(i)->apply(transform, boxSize);
-    }
-
-    const TransformOperations& operations() const { return m_operations; }
-    void setOperations(const TransformOperations& value) { m_operations = value; }
-
-private:
-    CustomFilterTransformParameter(const String& name)
-        : CustomFilterParameter(Transform, name)
-    {
-    }
-    virtual ~CustomFilterTransformParameter()
-    {
-    }
-
-    TransformOperations m_operations;
-};
-
-} // namespace WebCore
-
-
-#endif // CustomFilterTransformParameter_h
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
index 874144f..372a406 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
@@ -31,10 +31,10 @@
 #include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
 
 #include "core/platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "platform/NotImplemented.h"
 #include "platform/graphics/angle/ANGLEPlatformBridge.h"
 #include "platform/graphics/filters/custom/CustomFilterConstants.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "wtf/HashMap.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/text/StringHash.h"
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h b/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h
index 9155709..9057644 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h
@@ -31,7 +31,7 @@
 #define CustomFilterValidatedProgram_h
 
 #include "core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
index 21c0109..d653714 100644
--- a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
+++ b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
@@ -85,6 +85,8 @@
     CustomFilterMeshType m_meshType;
 };
 
+DEFINE_FILTER_OPERATION_TYPE_CASTS(ValidatedCustomFilterOperation, VALIDATED_CUSTOM);
+
 } // namespace WebCore
 
 
diff --git a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
index b85518d..15316a6 100644
--- a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
+++ b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
@@ -144,14 +144,14 @@
     m_contentsChangeCommitted = false;
 }
 
-WebKit::WebGraphicsContext3D* DrawingBuffer::context()
+blink::WebGraphicsContext3D* DrawingBuffer::context()
 {
     if (!m_context)
         return 0;
     return m_context->webContext();
 }
 
-bool DrawingBuffer::prepareMailbox(WebKit::WebExternalTextureMailbox* outMailbox, WebKit::WebExternalBitmap* bitmap)
+bool DrawingBuffer::prepareMailbox(blink::WebExternalTextureMailbox* outMailbox, blink::WebExternalBitmap* bitmap)
 {
     if (!m_context || !m_contentsChanged || !m_lastColorBuffer)
         return false;
@@ -220,7 +220,7 @@
     return true;
 }
 
-void DrawingBuffer::mailboxReleased(const WebKit::WebExternalTextureMailbox& mailbox)
+void DrawingBuffer::mailboxReleased(const blink::WebExternalTextureMailbox& mailbox)
 {
     for (size_t i = 0; i < m_textureMailboxes.size(); i++) {
          RefPtr<MailboxInfo> mailboxInfo = m_textureMailboxes[i];
@@ -313,7 +313,7 @@
         }
         m_context->flush();
     }
-    Platform3DObject sourceTexture = frontColorBuffer() ? frontColorBuffer() : colorBuffer();
+    Platform3DObject sourceTexture = colorBuffer();
 
     if (!context.makeContextCurrent())
         return false;
@@ -345,13 +345,13 @@
     return m_fbo;
 }
 
-WebKit::WebLayer* DrawingBuffer::platformLayer()
+blink::WebLayer* DrawingBuffer::platformLayer()
 {
     if (!m_context)
         return 0;
 
     if (!m_layer) {
-        m_layer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createExternalTextureLayer(this));
+        m_layer = adoptPtr(blink::Platform::current()->compositorSupport()->createExternalTextureLayer(this));
 
         m_layer->setOpaque(!m_attributes.alpha);
         m_layer->setBlendBackgroundColor(m_attributes.alpha);
@@ -368,6 +368,16 @@
         return;
 
     Extensions3D* extensions = m_context->extensions();
+
+    if (!imageBuffer)
+        return;
+    Platform3DObject tex = imageBuffer->getBackingTexture();
+    if (tex) {
+        extensions->copyTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, m_frontColorBuffer,
+            tex, 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE);
+        return;
+    }
+
     // Since the m_frontColorBuffer was produced and sent to the compositor, it cannot be bound to an fbo.
     // We have to make a copy of it here and bind that copy instead.
     // FIXME: That's not true any more, provided we don't change texture
diff --git a/Source/core/platform/graphics/gpu/DrawingBuffer.h b/Source/core/platform/graphics/gpu/DrawingBuffer.h
index b327dbd..2516e28 100644
--- a/Source/core/platform/graphics/gpu/DrawingBuffer.h
+++ b/Source/core/platform/graphics/gpu/DrawingBuffer.h
@@ -41,7 +41,7 @@
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
-namespace WebKit {
+namespace blink {
 class WebExternalBitmap;
 class WebExternalTextureLayer;
 class WebGraphicsContext3D;
@@ -62,10 +62,10 @@
 };
 
 // Manages a rendering target (framebuffer + attachment) for a canvas.  Can publish its rendering
-// results to a WebKit::WebLayer for compositing.
-class DrawingBuffer : public RefCounted<DrawingBuffer>, public WebKit::WebExternalTextureLayerClient  {
+// results to a blink::WebLayer for compositing.
+class DrawingBuffer : public RefCounted<DrawingBuffer>, public blink::WebExternalTextureLayerClient  {
     struct MailboxInfo : public RefCounted<MailboxInfo> {
-        WebKit::WebExternalTextureMailbox mailbox;
+        blink::WebExternalTextureMailbox mailbox;
         unsigned textureId;
         IntSize size;
     };
@@ -120,13 +120,13 @@
 
     void markContentsChanged();
 
-    WebKit::WebLayer* platformLayer();
+    blink::WebLayer* platformLayer();
     void paintCompositedResultsToCanvas(ImageBuffer*);
 
     // WebExternalTextureLayerClient implementation.
-    virtual WebKit::WebGraphicsContext3D* context() OVERRIDE;
-    virtual bool prepareMailbox(WebKit::WebExternalTextureMailbox*, WebKit::WebExternalBitmap*) OVERRIDE;
-    virtual void mailboxReleased(const WebKit::WebExternalTextureMailbox&) OVERRIDE;
+    virtual blink::WebGraphicsContext3D* context() OVERRIDE;
+    virtual bool prepareMailbox(blink::WebExternalTextureMailbox*, blink::WebExternalBitmap*) OVERRIDE;
+    virtual void mailboxReleased(const blink::WebExternalTextureMailbox&) OVERRIDE;
 
     bool copyToPlatformTexture(GraphicsContext3D&, Platform3DObject texture, GC3Denum internalFormat,
         GC3Denum destType, GC3Dint level, bool premultiplyAlpha, bool flipY);
@@ -202,7 +202,7 @@
     unsigned m_internalRenderbufferFormat;
     int m_maxTextureSize;
 
-    OwnPtr<WebKit::WebExternalTextureLayer> m_layer;
+    OwnPtr<blink::WebExternalTextureLayer> m_layer;
 
     // All of the mailboxes that this DrawingBuffer has ever created.
     Vector<RefPtr<MailboxInfo> > m_textureMailboxes;
diff --git a/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp b/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp
index 29e54b4..f7a0009 100644
--- a/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp
+++ b/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp
@@ -41,7 +41,7 @@
 #include <gtest/gtest.h>
 
 using namespace WebCore;
-using namespace WebKit;
+using namespace blink;
 using testing::Test;
 using testing::_;
 
@@ -76,7 +76,7 @@
     m_drawingBuffer->markContentsChanged();
     m_drawingBuffer->releaseResources();
 
-    WebKit::WebExternalTextureMailbox mailbox;
+    blink::WebExternalTextureMailbox mailbox;
     EXPECT_FALSE(m_drawingBuffer->prepareMailbox(&mailbox, 0));
 }
 
diff --git a/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp b/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp
index 11af84b..24a41ba 100644
--- a/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp
+++ b/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp
@@ -45,9 +45,9 @@
     {
         bool wasCreated = false;
 
-        OwnPtr<WebKit::WebGraphicsContext3DProvider> provider = adoptPtr(WebKit::Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
+        OwnPtr<blink::WebGraphicsContext3DProvider> provider = adoptPtr(blink::Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
 
-        WebKit::WebGraphicsContext3D* webContext = 0;
+        blink::WebGraphicsContext3D* webContext = 0;
         GrContext* grContext = 0;
 
         if (provider) {
@@ -56,7 +56,7 @@
         }
 
         if (webContext && grContext) {
-            WebKit::WebGraphicsContext3D* oldWebContext = m_context ? m_context->webContext() : 0;
+            blink::WebGraphicsContext3D* oldWebContext = m_context ? m_context->webContext() : 0;
             GrContext* oldGrContext = m_context ? m_context->grContext() : 0;
             if (webContext != oldWebContext || grContext != oldGrContext)
                 m_context.clear();
diff --git a/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp b/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
index 0304641..184ea66 100644
--- a/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
+++ b/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
@@ -55,48 +55,11 @@
     return false;
 }
 
-void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
-                      const GlyphBuffer& glyphBuffer,  int from, int numGlyphs,
-                      const FloatPoint& point, const FloatRect& textRect) const {
-    SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert
 
-    const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
-    SkScalar x = SkFloatToScalar(point.x());
-    SkScalar y = SkFloatToScalar(point.y());
-
-    // FIXME: text rendering speed:
-    // Android has code in their WebCore fork to special case when the
-    // GlyphBuffer has no advances other than the defaults. In that case the
-    // text drawing can proceed faster. However, it's unclear when those
-    // patches may be upstreamed to WebKit so we always use the slower path
-    // here.
-    const GlyphBufferAdvance* adv = glyphBuffer.advances(from);
-    SkAutoSTMalloc<32, SkPoint> storage(numGlyphs), storage2(numGlyphs), storage3(numGlyphs);
-    SkPoint* pos = storage.get();
-    SkPoint* vPosBegin = storage2.get();
-    SkPoint* vPosEnd = storage3.get();
-
-    bool isVertical = font->platformData().orientation() == Vertical;
-    SkScalar verticalPosCompensation = isVertical ? SkFloatToScalar((font->fontMetrics().floatHeight() - font->fontMetrics().floatAscent()) / 2) : 0;
-    for (int i = 0; i < numGlyphs; i++) {
-        SkScalar myWidth = SkFloatToScalar(adv[i].width());
-        pos[i].set(x, y);
-        if (isVertical) {
-            // In vertical mode, we need to align the left of ideographics to the vertical baseline.
-            // (Note vertical/horizontal are in absolute orientation, that is, here x is vertical.)
-            // However, when the glyph is drawn in drawTextOnPath(), the baseline is the horizontal path,
-            // so the ideographics will look shifted to the bottom-right direction because the ascent is
-            // applied vertically. Compensate the position so that ascent will look like to be applied
-            // horizontally.
-            SkScalar bottom = x + myWidth - verticalPosCompensation;
-            SkScalar left = y + verticalPosCompensation;
-            vPosBegin[i].set(bottom, left);
-            vPosEnd[i].set(bottom, left - myWidth);
-        }
-        x += myWidth;
-        y += SkFloatToScalar(adv[i].height());
-    }
-
+static void paintGlyphs(GraphicsContext* gc, const SimpleFontData* font,
+    const GlyphBufferGlyph* glyphs, unsigned numGlyphs,
+    SkPoint* pos, const FloatRect& textRect)
+{
     TextDrawingModeFlags textMode = gc->textDrawingMode();
 
     // We draw text up to two times (once for fill, once for stroke).
@@ -107,16 +70,7 @@
         gc->adjustTextRenderMode(&paint);
         paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
 
-        if (isVertical) {
-            SkPath path;
-            for (int i = 0; i < numGlyphs; ++i) {
-                path.reset();
-                path.moveTo(vPosBegin[i]);
-                path.lineTo(vPosEnd[i]);
-                gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint);
-            }
-        } else
-            gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint);
+        gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint);
     }
 
     if ((textMode & TextModeStroke)
@@ -136,19 +90,78 @@
             paint.setLooper(0);
         }
 
-        if (isVertical) {
-            SkPath path;
-            for (int i = 0; i < numGlyphs; ++i) {
-                path.reset();
-                path.moveTo(vPosBegin[i]);
-                path.lineTo(vPosEnd[i]);
-                gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint);
-            }
-        } else
-            gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint);
+        gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint);
     }
 }
 
+void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
+    const GlyphBuffer& glyphBuffer, unsigned from, unsigned numGlyphs,
+    const FloatPoint& point, const FloatRect& textRect) const
+{
+    SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert
+
+    SkScalar x = SkFloatToScalar(point.x());
+    SkScalar y = SkFloatToScalar(point.y());
+
+    SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
+    SkPoint* pos = storage.get();
+
+    const OpenTypeVerticalData* verticalData = font->verticalData();
+    if (font->platformData().orientation() == Vertical && verticalData) {
+        AffineTransform savedMatrix = gc->getCTM();
+        gc->concatCTM(AffineTransform(0, -1, 1, 0, point.x(), point.y()));
+        gc->concatCTM(AffineTransform(1, 0, 0, 1, -point.x(), -point.y()));
+
+        const unsigned kMaxBufferLength = 256;
+        Vector<FloatPoint, kMaxBufferLength> translations;
+
+        const FontMetrics& metrics = font->fontMetrics();
+        SkScalar verticalOriginX = SkFloatToScalar(point.x() + metrics.floatAscent() - metrics.floatAscent(IdeographicBaseline));
+        float horizontalOffset = point.x();
+
+        unsigned glyphIndex = 0;
+        while (glyphIndex < numGlyphs) {
+            unsigned chunkLength = std::min(kMaxBufferLength, numGlyphs - glyphIndex);
+
+            const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from + glyphIndex);
+            translations.resize(chunkLength);
+            verticalData->getVerticalTranslationsForGlyphs(font, &glyphs[0], chunkLength, reinterpret_cast<float*>(&translations[0]));
+
+            x = verticalOriginX;
+            y = SkFloatToScalar(point.y() + horizontalOffset - point.x());
+
+            float currentWidth = 0;
+            for (unsigned i = 0; i < chunkLength; ++i, ++glyphIndex) {
+                pos[i].set(
+                    x + SkIntToScalar(lroundf(translations[i].x())),
+                    y + -SkIntToScalar(-lroundf(currentWidth - translations[i].y())));
+                currentWidth += glyphBuffer.advanceAt(from + glyphIndex);
+            }
+            horizontalOffset += currentWidth;
+            paintGlyphs(gc, font, glyphs, chunkLength, pos, textRect);
+        }
+
+        gc->setCTM(savedMatrix);
+        return;
+    }
+
+    // FIXME: text rendering speed:
+    // Android has code in their WebCore fork to special case when the
+    // GlyphBuffer has no advances other than the defaults. In that case the
+    // text drawing can proceed faster. However, it's unclear when those
+    // patches may be upstreamed to WebKit so we always use the slower path
+    // here.
+    const GlyphBufferAdvance* adv = glyphBuffer.advances(from);
+    for (unsigned i = 0; i < numGlyphs; i++) {
+        pos[i].set(x, y);
+        x += SkFloatToScalar(adv[i].width());
+        y += SkFloatToScalar(adv[i].height());
+    }
+
+    const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
+    paintGlyphs(gc, font, glyphs, numGlyphs, pos, textRect);
+}
+
 void Font::drawComplexText(GraphicsContext* gc, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
 {
     if (!runInfo.run.length())
diff --git a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
index 7a280e5..7386728 100644
--- a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
+++ b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
@@ -34,6 +34,7 @@
 #include "RuntimeEnabledFeatures.h"
 #include "SkPaint.h"
 #include "SkTypeface.h"
+#include "platform/LayoutTestSupport.h"
 #include "platform/NotImplemented.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
@@ -52,7 +53,6 @@
 static bool useSkiaBitmaps = true;
 static bool useSkiaAntiAlias = true;
 static bool useSkiaSubpixelRendering = false;
-static bool useSkiaSubpixelPositioning = false;
 
 void FontPlatformData::setHinting(SkPaint::Hinting hinting)
 {
@@ -79,11 +79,6 @@
     useSkiaSubpixelRendering = useSubpixelRendering;
 }
 
-void FontPlatformData::setSubpixelPositioning(bool useSubpixelPositioning)
-{
-    useSkiaSubpixelPositioning = useSubpixelPositioning;
-}
-
 FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)
     : m_textSize(0)
     , m_emSizeInFontUnits(0)
@@ -128,7 +123,7 @@
 {
 }
 
-FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation)
+FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation, bool subpixelTextPosition)
     : m_typeface(tf)
     , m_family(family)
     , m_textSize(textSize)
@@ -138,7 +133,7 @@
     , m_orientation(orientation)
     , m_isHashTableDeletedValue(false)
 {
-    querySystemForRenderStyle();
+    querySystemForRenderStyle(subpixelTextPosition);
 }
 
 FontPlatformData::FontPlatformData(const FontPlatformData& src, float textSize)
@@ -152,7 +147,7 @@
     , m_harfBuzzFace(0)
     , m_isHashTableDeletedValue(false)
 {
-    querySystemForRenderStyle();
+    querySystemForRenderStyle(FontDescription::subpixelPositioning());
 }
 
 FontPlatformData::~FontPlatformData()
@@ -197,7 +192,7 @@
     paint->setHinting(static_cast<SkPaint::Hinting>(m_style.hintStyle));
     paint->setEmbeddedBitmapText(m_style.useBitmaps);
     paint->setAutohinted(m_style.useAutoHint);
-    paint->setSubpixelText(m_style.useSubpixelPositioning || RuntimeEnabledFeatures::subpixelFontScalingEnabled());
+    paint->setSubpixelText(m_style.useSubpixelPositioning);
     if (m_style.useAntiAlias)
         paint->setLCDRenderText(m_style.useSubpixelRendering);
 
@@ -257,23 +252,23 @@
 
 void FontPlatformData::getRenderStyleForStrike(const char* font, int sizeAndStyle)
 {
-    WebKit::WebFontRenderStyle style;
+    blink::WebFontRenderStyle style;
 
 #if OS(ANDROID)
     style.setDefaults();
 #else
     if (!font || !*font)
         style.setDefaults(); // It's probably a webfont. Take the system defaults.
-    else if (WebKit::Platform::current()->sandboxSupport())
-        WebKit::Platform::current()->sandboxSupport()->getRenderStyleForStrike(font, sizeAndStyle, &style);
+    else if (blink::Platform::current()->sandboxSupport())
+        blink::Platform::current()->sandboxSupport()->getRenderStyleForStrike(font, sizeAndStyle, &style);
     else
-        WebKit::WebFontInfo::renderStyleForStrike(font, sizeAndStyle, &style);
+        blink::WebFontInfo::renderStyleForStrike(font, sizeAndStyle, &style);
 #endif
 
     style.toFontRenderStyle(&m_style);
 }
 
-void FontPlatformData::querySystemForRenderStyle()
+void FontPlatformData::querySystemForRenderStyle(bool useSkiaSubpixelPositioning)
 {
     getRenderStyleForStrike(m_family.data(), (((int)m_textSize) << 2) | (m_typeface->style() & 3));
 
@@ -290,12 +285,15 @@
         m_style.useBitmaps = useSkiaBitmaps;
     if (m_style.useAutoHint == FontRenderStyle::NoPreference)
         m_style.useAutoHint = useSkiaAutoHint;
-    if (m_style.useSubpixelPositioning == FontRenderStyle::NoPreference)
-        m_style.useSubpixelPositioning = useSkiaSubpixelPositioning;
     if (m_style.useAntiAlias == FontRenderStyle::NoPreference)
         m_style.useAntiAlias = useSkiaAntiAlias;
     if (m_style.useSubpixelRendering == FontRenderStyle::NoPreference)
         m_style.useSubpixelRendering = useSkiaSubpixelRendering;
+
+    // TestRunner specifically toggles the subpixel positioning flag.
+    if (m_style.useSubpixelPositioning == FontRenderStyle::NoPreference
+        || isRunningLayoutTest())
+        m_style.useSubpixelPositioning = useSkiaSubpixelPositioning;
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
index 5665bef..b5b7c6f 100644
--- a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
+++ b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
@@ -33,9 +33,10 @@
 
 #include "SkPaint.h"
 #include "platform/SharedBuffer.h"
-#include "core/platform/graphics/chromium/FontRenderStyle.h"
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
+#include "platform/fonts/FontDescription.h"
 #include "platform/fonts/FontOrientation.h"
+#include "platform/fonts/FontRenderStyle.h"
 #include "wtf/Forward.h"
 #include "wtf/HashTableDeletedValueType.h"
 #include "wtf/RefPtr.h"
@@ -47,7 +48,6 @@
 
 namespace WebCore {
 
-class FontDescription;
 class GraphicsContext;
 class HarfBuzzFace;
 
@@ -67,7 +67,7 @@
     FontPlatformData();
     FontPlatformData(float textSize, bool fakeBold, bool fakeItalic);
     FontPlatformData(const FontPlatformData&);
-    FontPlatformData(PassRefPtr<SkTypeface>, const char* name, float textSize, bool fakeBold, bool fakeItalic, FontOrientation = Horizontal);
+    FontPlatformData(PassRefPtr<SkTypeface>, const char* name, float textSize, bool fakeBold, bool fakeItalic, FontOrientation = Horizontal, bool subpixelTextPosition = FontDescription::subpixelPositioning());
     FontPlatformData(const FontPlatformData& src, float textSize);
     ~FontPlatformData();
 
@@ -125,11 +125,10 @@
     static void setUseBitmaps(bool);
     static void setAntiAlias(bool);
     static void setSubpixelRendering(bool);
-    static void setSubpixelPositioning(bool);
 
 private:
     void getRenderStyleForStrike(const char*, int);
-    void querySystemForRenderStyle();
+    void querySystemForRenderStyle(bool useSkiaSubpixelPositioning);
 
     RefPtr<SkTypeface> m_typeface;
     CString m_family;
diff --git a/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp b/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp
index 88f67cb..a54b7d3 100644
--- a/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp
+++ b/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp
@@ -93,7 +93,7 @@
 HarfBuzzFace::~HarfBuzzFace()
 {
     HarfBuzzFaceCache::iterator result = harfBuzzFaceCache()->find(m_uniqueID);
-    ASSERT(result != harfBuzzFaceCache()->end());
+    ASSERT_WITH_SECURITY_IMPLICATION(result != harfBuzzFaceCache()->end());
     ASSERT(result.get()->value->refCount() > 1);
     result.get()->value->deref();
     if (result.get()->value->refCount() == 1)
diff --git a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
index 2ba5126..852d143 100644
--- a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
+++ b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 BlackBerry Limited. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -508,6 +509,19 @@
         m_features.append(vrt2);
     }
 
+    static hb_feature_t noKern = { HB_TAG('k', 'e', 'r', 'n'), 0, 0, static_cast<unsigned>(-1) };
+    static hb_feature_t noVkrn = { HB_TAG('v', 'k', 'r', 'n'), 0, 0, static_cast<unsigned>(-1) };
+    switch (description.kerning()) {
+    case FontDescription::NormalKerning:
+        // kern/vkrn are enabled by default
+        break;
+    case FontDescription::NoneKerning:
+        m_features.append(description.orientation() == Vertical ? noVkrn : noKern);
+        break;
+    case FontDescription::AutoKerning:
+        break;
+    }
+
     FontFeatureSettings* settings = description.featureSettings();
     if (!settings)
         return;
@@ -768,7 +782,7 @@
         float glyphAdvanceX = advances[i] + nextOffset.x() - currentOffset.x();
         float glyphAdvanceY = nextOffset.y() - currentOffset.y();
         if (m_run.rtl()) {
-            if (currentCharacterIndex > m_toIndex)
+            if (currentCharacterIndex >= m_toIndex)
                 m_startOffset.move(glyphAdvanceX, glyphAdvanceY);
             else if (currentCharacterIndex >= m_fromIndex)
                 glyphBuffer->add(glyphs[i], currentRun->fontData(), createGlyphBufferAdvance(glyphAdvanceX, glyphAdvanceY));
diff --git a/Source/core/platform/graphics/chromium/FontCacheChromiumLinux.cpp b/Source/core/platform/graphics/linux/FontCacheLinux.cpp
similarity index 86%
rename from Source/core/platform/graphics/chromium/FontCacheChromiumLinux.cpp
rename to Source/core/platform/graphics/linux/FontCacheLinux.cpp
index 17d9af5..5e39f46 100644
--- a/Source/core/platform/graphics/chromium/FontCacheChromiumLinux.cpp
+++ b/Source/core/platform/graphics/linux/FontCacheLinux.cpp
@@ -36,11 +36,11 @@
 
 void FontCache::getFontFamilyForCharacter(UChar32 c, const char* preferredLocale, FontCache::SimpleFontFamily* family)
 {
-    WebKit::WebFontFamily webFamily;
-    if (WebKit::Platform::current()->sandboxSupport())
-        WebKit::Platform::current()->sandboxSupport()->getFontFamilyForCharacter(c, preferredLocale, &webFamily);
+    blink::WebFontFamily webFamily;
+    if (blink::Platform::current()->sandboxSupport())
+        blink::Platform::current()->sandboxSupport()->getFontFamilyForCharacter(c, preferredLocale, &webFamily);
     else
-        WebKit::WebFontInfo::familyForChar(c, preferredLocale, &webFamily);
+        blink::WebFontInfo::familyForChar(c, preferredLocale, &webFamily);
     family->name = String::fromUTF8(CString(webFamily.name));
     family->isBold = webFamily.isBold;
     family->isItalic = webFamily.isItalic;
diff --git a/Source/core/platform/graphics/mac/ComplexTextController.cpp b/Source/core/platform/graphics/mac/ComplexTextController.cpp
index 8b149f7..9e34f8a 100644
--- a/Source/core/platform/graphics/mac/ComplexTextController.cpp
+++ b/Source/core/platform/graphics/mac/ComplexTextController.cpp
@@ -27,8 +27,6 @@
 
 #include <ApplicationServices/ApplicationServices.h>
 #include "core/platform/graphics/Font.h"
-#include "core/rendering/RenderBlockFlow.h"
-#include "core/rendering/RenderText.h"
 #include "platform/geometry/FloatSize.h"
 #include "platform/graphics/TextRun.h"
 #include "platform/text/TextBreakIterator.h"
@@ -41,15 +39,14 @@
 
 class TextLayout {
 public:
-    static bool isNeeded(RenderText* text, const Font& font)
+    static bool isNeeded(const TextRun& run, const Font& font)
     {
-        TextRun run = RenderBlockFlow::constructTextRun(text, font, text, text->style());
         return font.codePath(run) == Font::Complex;
     }
 
-    TextLayout(RenderText* text, const Font& font, float xPos)
+    TextLayout(const TextRun& run, unsigned textLength, const Font& font, float xPos)
         : m_font(font)
-        , m_run(constructTextRun(text, font, xPos))
+        , m_run(constructTextRun(run, textLength, font, xPos))
         , m_controller(adoptPtr(new ComplexTextController(&m_font, m_run, true)))
     {
     }
@@ -66,10 +63,10 @@
     }
 
 private:
-    static TextRun constructTextRun(RenderText* text, const Font& font, float xPos)
+    static TextRun constructTextRun(const TextRun& textRun, unsigned textLength, const Font& font, float xPos)
     {
-        TextRun run = RenderBlockFlow::constructTextRun(text, font, text, text->style());
-        run.setCharactersLength(text->textLength());
+        TextRun run = textRun;
+        run.setCharactersLength(textLength);
         ASSERT(run.charactersLength() >= run.length());
 
         run.setXPos(xPos);
@@ -82,11 +79,11 @@
     OwnPtr<ComplexTextController> m_controller;
 };
 
-PassOwnPtr<TextLayout> Font::createLayout(RenderText* text, float xPos, bool collapseWhiteSpace) const
+PassOwnPtr<TextLayout> Font::createLayoutForMacComplexText(const TextRun& run, unsigned textLength, float xPos, bool collapseWhiteSpace) const
 {
-    if (!collapseWhiteSpace || !TextLayout::isNeeded(text, *this))
+    if (!collapseWhiteSpace || !TextLayout::isNeeded(run, *this))
         return nullptr;
-    return adoptPtr(new TextLayout(text, *this, xPos));
+    return adoptPtr(new TextLayout(run, textLength, *this, xPos));
 }
 
 void Font::deleteLayout(TextLayout* layout)
diff --git a/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm b/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
index 17257db..58cf46a 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()->getFontResourceData(m_font.fontDescription(), fontName.get(), false, FontCache::DoNotRetain).get();
+                    runFontData = fontCache()->getFontResourceData(m_font.fontDescription(), fontName.get(), false, 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()->getFontResourceData(&runFontPlatformData, FontCache::DoNotRetain).get();
+                        runFontData = fontCache()->getFontResourceData(&runFontPlatformData, DoNotRetain).get();
                     }
                 }
                 if (m_fallbackFonts && runFontData != m_font.primaryFont())
diff --git a/Source/core/platform/graphics/mac/FloatPointMac.mm b/Source/core/platform/graphics/mac/FloatPointMac.mm
deleted file mode 100644
index 811c08a..0000000
--- a/Source/core/platform/graphics/mac/FloatPointMac.mm
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2004, 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2005 Nokia.  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 "platform/geometry/FloatPoint.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-FloatPoint::FloatPoint(const NSPoint& p) : m_x(p.x), m_y(p.y)
-{
-}
-
-FloatPoint::operator NSPoint() const
-{
-    return NSMakePoint(m_x, m_y);
-}
-
-#endif
-
-}
diff --git a/Source/core/platform/graphics/mac/FloatRectMac.mm b/Source/core/platform/graphics/mac/FloatRectMac.mm
deleted file mode 100644
index 0b070dd..0000000
--- a/Source/core/platform/graphics/mac/FloatRectMac.mm
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2005 Nokia.  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 "platform/geometry/FloatRect.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-FloatRect::FloatRect(const NSRect& r) : m_location(r.origin), m_size(r.size)
-{
-}
-
-FloatRect::operator NSRect() const
-{
-    return NSMakeRect(x(), y(), width(), height());
-}
-
-#endif
-
-}
diff --git a/Source/core/platform/graphics/mac/FloatSizeMac.mm b/Source/core/platform/graphics/mac/FloatSizeMac.mm
deleted file mode 100644
index ceee89a..0000000
--- a/Source/core/platform/graphics/mac/FloatSizeMac.mm
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2005 Nokia.  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 "platform/geometry/FloatSize.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-FloatSize::FloatSize(const NSSize& s) : m_width(s.width), m_height(s.height)
-{
-}
-
-FloatSize::operator NSSize() const
-{
-    return NSMakeSize(m_width, m_height);
-}
-
-#endif
-
-}
diff --git a/Source/core/platform/graphics/mac/FontCacheMac.mm b/Source/core/platform/graphics/mac/FontCacheMac.mm
index 2af329c..0058b97 100644
--- a/Source/core/platform/graphics/mac/FontCacheMac.mm
+++ b/Source/core/platform/graphics/mac/FontCacheMac.mm
@@ -34,7 +34,7 @@
 #import "core/platform/graphics/Font.h"
 #import "core/platform/graphics/FontPlatformData.h"
 #import "core/platform/graphics/SimpleFontData.h"
-#import "core/platform/mac/WebFontCache.h"
+#import "platform/mac/WebFontCache.h"
 #import <wtf/MainThread.h>
 #import <wtf/StdLibExtras.h>
 
@@ -173,27 +173,6 @@
     return getFontResourceData(&alternateFont, DoNotRetain);
 }
 
-PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
-{
-    // Attempt to find an appropriate font using a match based on
-    // the presence of keywords in the the requested names.  For example, we'll
-    // match any name that contains "Arabic" to Geeza Pro.
-    RefPtr<SimpleFontData> simpleFontData;
-    const FontFamily* currFamily = &font.fontDescription().family();
-    while (currFamily && !simpleFontData) {
-        if (currFamily->family().length()) {
-            static String* matchWords[3] = { new String("Arabic"), new String("Pashto"), new String("Urdu") };
-            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 = getFontResourceData(font.fontDescription(), geezaStr);
-        }
-        currFamily = currFamily->next();
-    }
-
-    return simpleFontData.release();
-}
-
 PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& fontDescription, ShouldRetain shouldRetain)
 {
     DEFINE_STATIC_LOCAL(AtomicString, timesStr, ("Times", AtomicString::ConstructFromLiteral));
@@ -212,11 +191,6 @@
     return getFontResourceData(fontDescription, lucidaGrandeStr, false, shouldRetain);
 }
 
-void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
-{
-    [WebFontCache getTraits:traitsMasks inFamily:familyName];
-}
-
 FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family, float fontSize)
 {
     NSFontTraitMask traits = fontDescription.italic() ? NSFontItalicTrait : 0;
@@ -234,8 +208,8 @@
     NSInteger actualWeight = [fontManager weightOfFont:nsFont];
 
     NSFont *platformFont = fontDescription.usePrinterFont() ? [nsFont printerFont] : [nsFont screenFont];
-    bool syntheticBold = isAppKitFontWeightBold(weight) && !isAppKitFontWeightBold(actualWeight);
-    bool syntheticOblique = (traits & NSFontItalicTrait) && !(actualTraits & NSFontItalicTrait);
+    bool syntheticBold = (isAppKitFontWeightBold(weight) && !isAppKitFontWeightBold(actualWeight)) || fontDescription.isSyntheticBold();
+    bool syntheticOblique = ((traits & NSFontItalicTrait) && !(actualTraits & NSFontItalicTrait)) || fontDescription.isSyntheticItalic();
 
     // FontPlatformData::font() can be null for the case of Chromium out-of-process font loading.
     // In that case, we don't want to use the platformData.
diff --git a/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp b/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp
index 27c7032..5fb3616 100644
--- a/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp
+++ b/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp
@@ -24,7 +24,6 @@
 #include "platform/SharedBuffer.h"
 #include "core/platform/graphics/FontPlatformData.h"
 #include "core/platform/graphics/opentype/OpenTypeSanitizer.h"
-#include "core/platform/graphics/skia/SkiaSharedBufferStream.h"
 #include "third_party/skia/include/core/SkStream.h"
 #include "third_party/skia/include/core/SkTypeface.h"
 #include "wtf/PassOwnPtr.h"
@@ -68,7 +67,7 @@
     // Since we store this anyways, it might be worthwhile just plumbing this to FontMac.cpp in
     // a more obvious way.
     // FIXME: Remove this, add an explicit use, or add a comment explaining why this exists.
-    RefPtr<SkiaSharedBufferStream> stream = SkiaSharedBufferStream::create(buffer);
+    RefPtr<SkMemoryStream> stream = adoptRef(new SkMemoryStream(buffer->getAsSkData().get()));
     RefPtr<SkTypeface> typeface = adoptRef(SkTypeface::CreateFromStream(stream.get()));
     if (!typeface)
         return nullptr;
diff --git a/Source/core/platform/graphics/mac/FontMac.cpp b/Source/core/platform/graphics/mac/FontMac.cpp
index a34738b..bc29df0 100644
--- a/Source/core/platform/graphics/mac/FontMac.cpp
+++ b/Source/core/platform/graphics/mac/FontMac.cpp
@@ -87,8 +87,9 @@
 // inputs/outputs, and reduce duplicate code.
 // This issue is tracked in https://bugs.webkit.org/show_bug.cgi?id=62989
 void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
-                      const GlyphBuffer& glyphBuffer,  int from, int numGlyphs,
-                      const FloatPoint& point, const FloatRect& textRect) const {
+    const GlyphBuffer& glyphBuffer, unsigned from, unsigned numGlyphs,
+    const FloatPoint& point, const FloatRect& textRect) const
+{
     COMPILE_ASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t), GlyphBufferGlyphSize_equals_uint16_t);
 
     bool shouldSmoothFonts = true;
@@ -130,7 +131,7 @@
     SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
     SkPoint* pos = storage.get();
 
-    for (int i = 0; i < numGlyphs; i++) {
+    for (unsigned i = 0; i < numGlyphs; i++) {
         pos[i].set(x, y);
         x += SkFloatToScalar(adv[i].width());
         y += SkFloatToScalar(adv[i].height());
diff --git a/Source/core/platform/graphics/mac/IntPointMac.mm b/Source/core/platform/graphics/mac/IntPointMac.mm
deleted file mode 100644
index 353c228..0000000
--- a/Source/core/platform/graphics/mac/IntPointMac.mm
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, 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 "platform/geometry/IntPoint.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-IntPoint::IntPoint(const NSPoint& p) : m_x(static_cast<int>(p.x)), m_y(static_cast<int>(p.y))
-{
-}
-
-IntPoint::operator NSPoint() const
-{
-    return NSMakePoint(m_x, m_y);
-}
-
-#endif
-
-}
diff --git a/Source/core/platform/graphics/mac/IntRectMac.mm b/Source/core/platform/graphics/mac/IntRectMac.mm
deleted file mode 100644
index 66ecee9..0000000
--- a/Source/core/platform/graphics/mac/IntRectMac.mm
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, 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 "platform/geometry/IntRect.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-IntRect::operator NSRect() const
-{
-    return NSMakeRect(x(), y(), width(), height());
-}
-
-IntRect enclosingIntRect(const NSRect& rect)
-{
-    int l = static_cast<int>(floorf(rect.origin.x));
-    int t = static_cast<int>(floorf(rect.origin.y));
-    int r = static_cast<int>(ceilf(NSMaxX(rect)));
-    int b = static_cast<int>(ceilf(NSMaxY(rect)));
-    return IntRect(l, t, r - l, b - t);
-}
-
-#endif
-
-}
diff --git a/Source/core/platform/graphics/mac/IntSizeMac.mm b/Source/core/platform/graphics/mac/IntSizeMac.mm
deleted file mode 100644
index 2a9d100..0000000
--- a/Source/core/platform/graphics/mac/IntSizeMac.mm
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, 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 "platform/geometry/IntSize.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-IntSize::IntSize(const NSSize& s) : m_width(static_cast<int>(s.width)), m_height(static_cast<int>(s.height))
-{
-}
-
-IntSize::operator NSSize() const
-{
-    return NSMakeSize(m_width, m_height);
-}
-
-#endif
-
-}
diff --git a/Source/core/platform/graphics/chromium/CrossProcessFontLoading.h b/Source/core/platform/graphics/mac/MemoryActivatedFont.h
similarity index 96%
rename from Source/core/platform/graphics/chromium/CrossProcessFontLoading.h
rename to Source/core/platform/graphics/mac/MemoryActivatedFont.h
index 782c837..1f2bbae 100644
--- a/Source/core/platform/graphics/chromium/CrossProcessFontLoading.h
+++ b/Source/core/platform/graphics/mac/MemoryActivatedFont.h
@@ -28,8 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CrossProcessFontLoading_h
-#define CrossProcessFontLoading_h
+#ifndef MemoryActivatedFont_h
+#define MemoryActivatedFont_h
 
 #import <wtf/RefCounted.h>
 #import <wtf/RetainPtr.h>
@@ -92,4 +92,4 @@
 
 } // namespace WebCore
 
-#endif // CrossProcessFontLoading_h
+#endif // MemoryActivatedFont_h
diff --git a/Source/core/platform/graphics/chromium/CrossProcessFontLoading.mm b/Source/core/platform/graphics/mac/MemoryActivatedFont.mm
similarity index 97%
rename from Source/core/platform/graphics/chromium/CrossProcessFontLoading.mm
rename to Source/core/platform/graphics/mac/MemoryActivatedFont.mm
index 129f005..42fffb9 100644
--- a/Source/core/platform/graphics/chromium/CrossProcessFontLoading.mm
+++ b/Source/core/platform/graphics/mac/MemoryActivatedFont.mm
@@ -27,7 +27,7 @@
 // do the loading of in-memory fonts and keep track of them.
 
 #import "config.h"
-#import "core/platform/graphics/chromium/CrossProcessFontLoading.h"
+#import "core/platform/graphics/mac/MemoryActivatedFont.h"
 
 #import <AppKit/NSFont.h>
 #import "core/platform/graphics/FontPlatformData.h"
@@ -112,7 +112,7 @@
     CGFontRef tmpCGFont;
     uint32_t fontID;
     // Send cross-process request to load font.
-    WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport();
+    blink::WebSandboxSupport* sandboxSupport = blink::Platform::current()->sandboxSupport();
     if (!sandboxSupport) {
         // This function should only be called in response to an error loading a
         // font due to being blocked by the sandbox.
@@ -171,7 +171,7 @@
 //
 // Considerations:
 // * cgFont must be CFRelease()ed by the caller when done.
-// 
+//
 // Parameters:
 // * nsFont - The font we wish to load.
 // * fontSize - point size of the font we wish to load.
@@ -193,7 +193,7 @@
         m_inMemoryFont = loadFontFromBrowserProcess(outNSFont);
         if (m_inMemoryFont) {
             cgFont = m_inMemoryFont->cgFont();
-            
+
             // Need to add an extra retain so output semantics of this function
             // are consistent.
             CFRetain(cgFont);
diff --git a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
index ab68457..0e1b50d 100644
--- a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
+++ b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
@@ -34,10 +34,10 @@
 #import "platform/SharedBuffer.h"
 #import "core/platform/graphics/Font.h"
 #import "core/platform/graphics/FontCache.h"
-#import "core/platform/mac/BlockExceptions.h"
 #import "platform/fonts/FontDescription.h"
 #import "platform/geometry/FloatRect.h"
 #import "platform/graphics/Color.h"
+#import "platform/mac/BlockExceptions.h"
 #import <wtf/Assertions.h>
 #import <wtf/RetainPtr.h>
 #import <wtf/StdLibExtras.h>
@@ -128,7 +128,7 @@
             bool syntheticOblique = platformData().syntheticOblique() && !(traits & kCTFontItalicTrait);
 
             FontPlatformData substitutePlatform(substituteFont, platformData().size(), isUsingPrinterFont, syntheticBold, syntheticOblique, platformData().orientation(), platformData().widthVariant());
-            SimpleFontData* value = new SimpleFontData(substitutePlatform, isCustomFont());
+            SimpleFontData* value = new SimpleFontData(substitutePlatform, isCustomFont() ? CustomFontData::create(false) : 0);
             if (value) {
                 CFDictionaryAddValue(dictionary, key, value);
                 return value;
@@ -305,7 +305,7 @@
     if (isCustomFont()) {
         FontPlatformData scaledFontData(m_platformData);
         scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
-        return SimpleFontData::create(scaledFontData, true, false);
+        return SimpleFontData::create(scaledFontData, CustomFontData::create(false));
     }
 
     BEGIN_BLOCK_OBJC_EXCEPTIONS;
diff --git a/Source/core/platform/graphics/opentype/OpenTypeTypes.h b/Source/core/platform/graphics/opentype/OpenTypeTypes.h
deleted file mode 100644
index 25a3a81..0000000
--- a/Source/core/platform/graphics/opentype/OpenTypeTypes.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2012 Koji Ishii <kojiishi@gmail.com>
- *
- * 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. 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 INC. 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.
- */
-
-#ifndef OpenTypeTypes_h
-#define OpenTypeTypes_h
-
-#include "platform/SharedBuffer.h"
-#include "wtf/ByteOrder.h"
-
-namespace WebCore {
-namespace OpenType {
-
-struct Int16 {
-    Int16(int16_t u) : v(htons(static_cast<uint16_t>(u))) { }
-    operator int16_t() const { return static_cast<int16_t>(ntohs(v)); }
-    uint16_t v; // in BigEndian
-};
-
-struct UInt16 {
-    UInt16(uint16_t u) : v(htons(u)) { }
-    operator uint16_t() const { return ntohs(v); }
-    uint16_t v; // in BigEndian
-};
-
-struct Int32 {
-    Int32(int32_t u) : v(htonl(static_cast<uint32_t>(u))) { }
-    operator int32_t() const { return static_cast<int32_t>(ntohl(v)); }
-    uint32_t v; // in BigEndian
-};
-
-struct UInt32 {
-    UInt32(uint32_t u) : v(htonl(u)) { }
-    operator uint32_t() const { return ntohl(v); }
-    uint32_t v; // in BigEndian
-};
-
-typedef UInt32 Fixed;
-typedef UInt16 Offset;
-typedef UInt16 GlyphID;
-
-// OTTag is native because it's only compared against constants, so we don't
-// do endian conversion here but make sure constants are in big-endian order.
-// Note that multi-character literal is implementation-defined in C++0x.
-typedef uint32_t Tag;
-#define OT_MAKE_TAG(ch1, ch2, ch3, ch4) ((((uint32_t)(ch4)) << 24) | (((uint32_t)(ch3)) << 16) | (((uint32_t)(ch2)) << 8) | ((uint32_t)(ch1)))
-
-template <typename T> static const T* validateTable(const RefPtr<SharedBuffer>& buffer, size_t count = 1)
-{
-    if (!buffer || buffer->size() < sizeof(T) * count)
-        return 0;
-    return reinterpret_cast<const T*>(buffer->data());
-}
-
-struct TableBase {
-protected:
-    static bool isValidEnd(const SharedBuffer& buffer, const void* position)
-    {
-        if (position < buffer.data())
-            return false;
-        size_t offset = reinterpret_cast<const char*>(position) - buffer.data();
-        return offset <= buffer.size(); // "<=" because end is included as valid
-    }
-
-    template <typename T> static const T* validatePtr(const SharedBuffer& buffer, const void* position)
-    {
-        const T* casted = reinterpret_cast<const T*>(position);
-        if (!isValidEnd(buffer, &casted[1]))
-            return 0;
-        return casted;
-    }
-
-    template <typename T> const T* validateOffset(const SharedBuffer& buffer, uint16_t offset) const
-    {
-        return validatePtr<T>(buffer, reinterpret_cast<const int8_t*>(this) + offset);
-    }
-};
-
-} // namespace OpenType
-} // namespace WebCore
-#endif // OpenTypeTypes_h
diff --git a/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp b/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp
index ae03971..37077b8 100644
--- a/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp
+++ b/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp
@@ -28,8 +28,8 @@
 
 #include "platform/SharedBuffer.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/opentype/OpenTypeTypes.h"
 #include "platform/fonts/GlyphPage.h"
+#include "platform/fonts/opentype/OpenTypeTypes.h"
 #include "platform/geometry/FloatRect.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h b/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
index e1a5fdf..3dd6760 100644
--- a/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
+++ b/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
@@ -52,6 +52,9 @@
     void getVerticalTranslationsForGlyphs(const SimpleFontData*, const Glyph*, size_t, float* outXYArray) const;
     void substituteWithVerticalGlyphs(const SimpleFontData*, GlyphPage*, unsigned offset, unsigned length) const;
 
+    bool inFontCache() const { return m_inFontCache; }
+    void setInFontCache(bool inFontCache) { m_inFontCache = inFontCache; }
+
 private:
     explicit OpenTypeVerticalData(const FontPlatformData&);
 
@@ -66,7 +69,6 @@
     int16_t m_defaultVertOriginY;
     HashMap<Glyph, int16_t> m_vertOriginY;
 
-    friend class FontCache;
     bool m_inFontCache; // for mark & sweep in FontCache::purgeInactiveFontData()
 };
 
diff --git a/Source/core/platform/graphics/skia/FontCacheSkia.cpp b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
index 65edbee..42ac13d 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkia.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
@@ -78,7 +78,7 @@
         description.setItalic(FontItalicOff);
     }
 
-    FontPlatformData* substitutePlatformData = getFontResourcePlatformData(description, atomicFamily, DoNotRetain);
+    FontPlatformData* substitutePlatformData = getFontResourcePlatformData(description, atomicFamily);
     if (!substitutePlatformData)
         return 0;
     FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
@@ -89,11 +89,6 @@
 
 #endif // !OS(WINDOWNS) && !OS(ANDROID)
 
-PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
-{
-    return 0;
-}
-
 PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
 {
     const AtomicString fallbackFontFamily = getFallbackFontFamily(description);
@@ -111,12 +106,6 @@
     return getFontResourceData(fontPlatformData, shouldRetain);
 }
 
-void FontCache::getTraitsInFamily(const AtomicString& familyName,
-                                  Vector<unsigned>& traitsMasks)
-{
-    notImplemented();
-}
-
 PassRefPtr<SkTypeface> FontCache::createTypeface(const FontDescription& fontDescription, const AtomicString& family, CString& name)
 {
     name = "";
@@ -173,9 +162,10 @@
     FontPlatformData* result = new FontPlatformData(tf,
         name.data(),
         fontSize,
-        fontDescription.weight() >= FontWeightBold && !tf->isBold(),
-        fontDescription.italic() && !tf->isItalic(),
-        fontDescription.orientation());
+        (fontDescription.weight() >= FontWeightBold && !tf->isBold()) || fontDescription.isSyntheticBold(),
+        (fontDescription.italic() && !tf->isItalic()) || fontDescription.isSyntheticItalic(),
+        fontDescription.orientation(),
+        fontDescription.useSubpixelPositioning());
     return result;
 }
 #endif // !OS(WINDOWNS)
diff --git a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
index f65a0c0..c9afa93 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
@@ -37,8 +37,8 @@
 #include "SkTypeface_win.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontFallbackWin.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
+#include "platform/fonts/FontFallbackWin.h"
 
 namespace WebCore {
 
@@ -82,7 +82,7 @@
         &script);
     FontPlatformData* data = 0;
     if (family)
-        data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false);
+        data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)));
 
     // Last resort font list : PanUnicode. CJK fonts have a pretty
     // large repertoire. Eventually, we need to scan all the fonts
@@ -205,8 +205,8 @@
     FontPlatformData* result = new FontPlatformData(tf,
         name.data(),
         fontSize,
-        fontDescription.weight() >= FontWeightBold && !tf->isBold(),
-        fontDescription.italic() && !tf->isItalic(),
+        fontDescription.weight() >= FontWeightBold && !tf->isBold() || fontDescription.isSyntheticBold(),
+        fontDescription.italic() && !tf->isItalic() || fontDescription.isSyntheticItalic(),
         fontDescription.orientation());
     return result;
 }
diff --git a/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp b/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp
index 7e22902..4c8388d 100644
--- a/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp
+++ b/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp
@@ -37,7 +37,6 @@
 #include "platform/SharedBuffer.h"
 #include "core/platform/graphics/FontPlatformData.h"
 #include "core/platform/graphics/opentype/OpenTypeSanitizer.h"
-#include "core/platform/graphics/skia/SkiaSharedBufferStream.h"
 #include "third_party/skia/include/core/SkStream.h"
 #include "third_party/skia/include/core/SkTypeface.h"
 #include "wtf/PassOwnPtr.h"
@@ -69,7 +68,7 @@
         return nullptr; // validation failed.
     buffer = transcodeBuffer.get();
 
-    RefPtr<SkiaSharedBufferStream> stream = SkiaSharedBufferStream::create(buffer);
+    RefPtr<SkMemoryStream> stream = adoptRef(new SkMemoryStream(buffer->getAsSkData().get()));
     RefPtr<SkTypeface> typeface = adoptRef(SkTypeface::CreateFromStream(stream.get()));
     if (!typeface)
         return nullptr;
diff --git a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
index eaf7581..19f1f99 100644
--- a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
+++ b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
@@ -47,13 +47,7 @@
         return false;
     }
 
-#if OS(WIN)
-    // FIXME: For some reason SkAutoSTMalloc fails to link on Windows.
-    // SkAutoSTArray works fine though...
-    SkAutoSTArray<GlyphPage::size, uint16_t> glyphStorage(length);
-#else
     SkAutoSTMalloc<GlyphPage::size, uint16_t> glyphStorage(length);
-#endif
 
     uint16_t* glyphs = glyphStorage.get();
     SkTypeface* typeface = fontData->platformData().typeface();
diff --git a/Source/core/platform/graphics/skia/NativeImageSkia.cpp b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
index 94268c2..b9b5967 100644
--- a/Source/core/platform/graphics/skia/NativeImageSkia.cpp
+++ b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
@@ -31,11 +31,11 @@
 #include "config.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
 
-#include "core/platform/PlatformInstrumentation.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
+#include "core/platform/graphics/DeferredImageDecoder.h"
 #include "core/platform/graphics/skia/SkiaUtils.h"
+#include "platform/PlatformInstrumentation.h"
 #include "platform/TraceEvent.h"
 #include "platform/geometry/FloatPoint.h"
 #include "platform/geometry/FloatRect.h"
@@ -339,10 +339,11 @@
     } else {
         // Take into account scale applied to the canvas when computing sampling mode (e.g. CSS scale or page scale).
         SkRect destRectTarget = destRect;
-        if (!(context->getTotalMatrix().getType() & (SkMatrix::kAffine_Mask | SkMatrix::kPerspective_Mask)))
-            context->getTotalMatrix().mapRect(&destRectTarget, destRect);
+        SkMatrix totalMatrix = context->getTotalMatrix();
+        if (!(totalMatrix.getType() & (SkMatrix::kAffine_Mask | SkMatrix::kPerspective_Mask)))
+            totalMatrix.mapRect(&destRectTarget, destRect);
 
-        resampling = computeResamplingMode(context->getTotalMatrix(),
+        resampling = computeResamplingMode(totalMatrix,
             SkScalarToFloat(srcRect.width()), SkScalarToFloat(srcRect.height()),
             SkScalarToFloat(destRectTarget.width()), SkScalarToFloat(destRectTarget.height()));
     }
@@ -384,7 +385,7 @@
 static SkBitmap createBitmapWithSpace(const SkBitmap& bitmap, int spaceWidth, int spaceHeight)
 {
     SkBitmap result;
-    result.setConfig(bitmap.getConfig(),
+    result.setConfig(bitmap.config(),
         bitmap.width() + spaceWidth,
         bitmap.height() + spaceHeight);
     result.allocPixels();
diff --git a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
index 2e74476..5cb2e81 100644
--- a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
+++ b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
@@ -36,7 +36,7 @@
 #include "SkPath.h"
 #include "SkTypeface.h"
 #include "SkTypes.h"
-#include "core/platform/graphics/chromium/VDMXParser.h"
+#include "core/platform/graphics/VDMXParser.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/geometry/FloatRect.h"
 #include "wtf/unicode/Unicode.h"
@@ -65,6 +65,7 @@
     m_platformData.setupPaint(&paint);
     paint.getFontMetrics(&metrics);
     SkTypeface* face = paint.getTypeface();
+    ASSERT(face);
 
     static const uint32_t vdmxTag = SkSetFourByteTag('V', 'D', 'M', 'X');
     int pixelSize = m_platformData.size() + 0.5;
@@ -173,7 +174,7 @@
 PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
 {
     const float scaledSize = lroundf(fontDescription.computedSize() * scaleFactor);
-    return SimpleFontData::create(FontPlatformData(m_platformData, scaledSize), isCustomFont(), false);
+    return SimpleFontData::create(FontPlatformData(m_platformData, scaledSize), isCustomFont() ? CustomFontData::create(false) : 0);
 }
 
 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
diff --git a/Source/core/platform/graphics/skia/SkiaFontWin.cpp b/Source/core/platform/graphics/skia/SkiaFontWin.cpp
index 893b3fa..4b3c853 100644
--- a/Source/core/platform/graphics/skia/SkiaFontWin.cpp
+++ b/Source/core/platform/graphics/skia/SkiaFontWin.cpp
@@ -35,7 +35,7 @@
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/Pattern.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
 #include "platform/transforms/AffineTransform.h"
 #include "third_party/skia/include/core/SkCanvas.h"
 #include "third_party/skia/include/core/SkDevice.h"
@@ -47,13 +47,13 @@
 namespace WebCore {
 
 static void skiaDrawText(GraphicsContext* context,
-                         const SkPoint& point,
-                         const SkRect& textRect,
-                         SkPaint* paint,
-                         const WORD* glyphs,
-                         const int* advances,
-                         const GOFFSET* offsets,
-                         int numGlyphs)
+    const SkPoint& point,
+    const SkRect& textRect,
+    SkPaint* paint,
+    const WORD* glyphs,
+    const int* advances,
+    const GOFFSET* offsets,
+    unsigned numGlyphs)
 {
     // Reserve space for 64 SkPoints on the stack. If numGlyphs is larger, the array
     // will dynamically allocate it space for numGlyph glyphs. This is used to store
@@ -66,7 +66,7 @@
     if (offsets) {
         SkAutoSTArray<kLocalGlyphMax, SkPoint> storage(numGlyphs);
         SkPoint* pos = storage.get();
-        for (int i = 0; i < numGlyphs; i++) {
+        for (unsigned i = 0; i < numGlyphs; i++) {
             // GDI has dv go up, so we negate it
             pos[i].set(x + SkIntToScalar(offsets[i].du),
                        y + -SkIntToScalar(offsets[i].dv));
@@ -76,7 +76,7 @@
     } else {
         SkAutoSTArray<kLocalGlyphMax * 2, SkScalar> storage(numGlyphs);
         SkScalar* xpos = storage.get();
-        for (int i = 0; i < numGlyphs; i++) {
+        for (unsigned i = 0; i < numGlyphs; i++) {
             xpos[i] = x;
             x += SkIntToScalar(advances[i]);
         }
@@ -88,7 +88,7 @@
 static void paintSkiaText(GraphicsContext* context,
     const FontPlatformData& data,
     SkTypeface* face, float size, uint32_t textFlags,
-    int numGlyphs,
+    unsigned numGlyphs,
     const WORD* glyphs,
     const int* advances,
     const GOFFSET* offsets,
@@ -146,22 +146,22 @@
 ///////////////////////////////////////////////////////////////////////////////////////////
 
 void paintSkiaText(GraphicsContext* context,
-                   const FontPlatformData& data,
-                   int numGlyphs,
-                   const WORD* glyphs,
-                   const int* advances,
-                   const GOFFSET* offsets,
-                   const SkPoint& origin,
-                   const SkRect& textRect)
+    const FontPlatformData& data,
+    unsigned numGlyphs,
+    const WORD* glyphs,
+    const int* advances,
+    const GOFFSET* offsets,
+    const SkPoint& origin,
+    const SkRect& textRect)
 {
     paintSkiaText(context, data, data.typeface(), data.size(), data.paintTextFlags(),
                   numGlyphs, glyphs, advances, offsets, origin, textRect);
 }
-
+#if !USE(HARFBUZZ)
 void paintSkiaText(GraphicsContext* context,
     const FontPlatformData& data,
     HFONT hfont,
-    int numGlyphs,
+    unsigned numGlyphs,
     const WORD* glyphs,
     const int* advances,
     const GOFFSET* offsets,
@@ -178,5 +178,5 @@
     RefPtr<SkTypeface> face = CreateTypefaceFromHFont(hfont, &size, &paintTextFlags);
     paintSkiaText(context, data, face.get(), size, paintTextFlags, numGlyphs, glyphs, advances, offsets, origin, textRect);
 }
-
+#endif
 }  // namespace WebCore
diff --git a/Source/core/platform/graphics/skia/SkiaFontWin.h b/Source/core/platform/graphics/skia/SkiaFontWin.h
index b5253ba..977e6c0 100644
--- a/Source/core/platform/graphics/skia/SkiaFontWin.h
+++ b/Source/core/platform/graphics/skia/SkiaFontWin.h
@@ -45,14 +45,15 @@
 // Note that the offsets parameter is optional. If not null it represents a
 // per glyph offset (such as returned by ScriptPlace Windows API function).
 void paintSkiaText(GraphicsContext*,
-                   const FontPlatformData&,
-                   int numGlyphs,
-                   const WORD* glyphs,
-                   const int* advances,
-                   const GOFFSET* offsets,
-                   const SkPoint& origin,
-                   const SkRect& textRect);
+    const FontPlatformData&,
+    unsigned numGlyphs,
+    const WORD* glyphs,
+    const int* advances,
+    const GOFFSET* offsets,
+    const SkPoint& origin,
+    const SkRect& textRect);
 
+#if !USE(HARFBUZZ)
 // Note that the offsets parameter is optional. If not null it represents a
 // per glyph offset (such as returned by ScriptPlace Windows API function).
 // Note: this is less efficient than calling the version with FontPlatformData,
@@ -60,12 +61,13 @@
 void paintSkiaText(GraphicsContext*,
     const FontPlatformData&,
     HFONT,
-    int numGlyphs,
+    unsigned numGlyphs,
     const WORD* glyphs,
     const int* advances,
     const GOFFSET* offsets,
     const SkPoint& origin,
     const SkRect& textRect);
+#endif
 
 }  // namespace WebCore
 
diff --git a/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp b/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp
deleted file mode 100644
index c5a9cec..0000000
--- a/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * 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/skia/SkiaSharedBufferStream.h"
-
-#include "third_party/skia/include/core/SkStream.h"
-#include "platform/SharedBuffer.h"
-#include <algorithm>
-#include <cstring>
-
-namespace WebCore {
-
-size_t SkiaSharedBufferStream::read(void* buffer, size_t bytesRequested)
-{
-    const size_t bytesLeft = m_buffer->size() - m_offset;
-    const size_t bytesToConsume = std::min(bytesLeft, bytesRequested);
-
-    if (buffer) {
-        char* byteBuffer = reinterpret_cast<char*>(buffer);
-        unsigned byteOffset = m_offset;
-        unsigned bytesLeftToConsume = bytesToConsume;
-        while (bytesLeftToConsume > 0) {
-            const char* segment;
-            unsigned bytesInSegment = m_buffer->getSomeData(segment, byteOffset);
-            if (!bytesInSegment) {
-                unsigned bytesRead = bytesToConsume - bytesLeftToConsume;
-                m_offset += bytesRead;
-                return bytesRead;
-            }
-            unsigned bytesToCopy = std::min(bytesInSegment, bytesLeftToConsume);
-            std::memcpy(byteBuffer, segment, bytesToCopy);
-            bytesLeftToConsume -= bytesToCopy;
-            byteBuffer += bytesToCopy;
-            byteOffset += bytesToCopy;
-        }
-    }
-    m_offset += bytesToConsume;
-    return bytesToConsume;
-}
-
-bool SkiaSharedBufferStream::isAtEnd() const
-{
-    return this->getLength() == m_offset;
-}
-
-bool SkiaSharedBufferStream::rewind()
-{
-    m_offset = 0;
-    return true;
-}
-
-SkiaSharedBufferStream* SkiaSharedBufferStream::duplicate() const
-{
-    return new SkiaSharedBufferStream(m_buffer);
-}
-
-size_t SkiaSharedBufferStream::getPosition() const
-{
-    return m_offset;
-}
-
-bool SkiaSharedBufferStream::seek(size_t position)
-{
-    m_offset = std::min(position, static_cast<size_t>(m_buffer->size()));
-    return true;
-}
-
-bool SkiaSharedBufferStream::move(long offset)
-{
-    return this->seek(m_offset + offset);
-}
-
-SkiaSharedBufferStream* SkiaSharedBufferStream::fork() const
-{
-    SkiaSharedBufferStream* that = this->duplicate();
-    that->m_offset = this->m_offset;
-    return that;
-}
-
-size_t SkiaSharedBufferStream::getLength() const
-{
-    return m_buffer->size();
-}
-
-const void* SkiaSharedBufferStream::getMemoryBase()
-{
-    const char* segment;
-    unsigned bytesInSegment = m_buffer->getSomeData(segment);
-    return (bytesInSegment != m_buffer->size()) ? 0 : segment;
-}
-
-}
diff --git a/Source/core/platform/graphics/skia/SkiaSharedBufferStream.h b/Source/core/platform/graphics/skia/SkiaSharedBufferStream.h
deleted file mode 100644
index 81bc469..0000000
--- a/Source/core/platform/graphics/skia/SkiaSharedBufferStream.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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 SkiaSharedBufferStream_h
-#define SkiaSharedBufferStream_h
-
-#include "platform/SharedBuffer.h"
-#include "third_party/skia/include/core/SkStream.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class SkiaSharedBufferStream : public SkStreamAsset {
-public:
-    static PassRefPtr<SkiaSharedBufferStream> create(PassRefPtr<SharedBuffer> buffer)
-    {
-        return adoptRef(new SkiaSharedBufferStream(buffer));
-    }
-
-    virtual ~SkiaSharedBufferStream()
-    {
-    }
-
-    virtual size_t read(void* buffer, size_t bytesRequested) OVERRIDE;
-    virtual bool isAtEnd() const OVERRIDE;
-
-    virtual bool rewind() OVERRIDE;
-    virtual SkiaSharedBufferStream* duplicate() const OVERRIDE;
-
-    virtual size_t getPosition() const OVERRIDE;
-    virtual bool seek(size_t position) OVERRIDE;
-    virtual bool move(long offset) OVERRIDE;
-    virtual SkiaSharedBufferStream* fork() const OVERRIDE;
-
-    virtual size_t getLength() const OVERRIDE;
-
-    virtual const void* getMemoryBase() OVERRIDE;
-
-private:
-    explicit SkiaSharedBufferStream(PassRefPtr<SharedBuffer> buffer)
-        : m_buffer(buffer)
-        , m_offset(0)
-    {
-    }
-
-    RefPtr<SharedBuffer> m_buffer;
-    size_t m_offset;
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/graphics/chromium/test/MockDiscardablePixelRef.h b/Source/core/platform/graphics/test/MockDiscardablePixelRef.h
similarity index 100%
rename from Source/core/platform/graphics/chromium/test/MockDiscardablePixelRef.h
rename to Source/core/platform/graphics/test/MockDiscardablePixelRef.h
diff --git a/Source/core/platform/graphics/chromium/test/MockImageDecoder.h b/Source/core/platform/graphics/test/MockImageDecoder.h
similarity index 98%
rename from Source/core/platform/graphics/chromium/test/MockImageDecoder.h
rename to Source/core/platform/graphics/test/MockImageDecoder.h
index 8efdd29..e590b7c 100644
--- a/Source/core/platform/graphics/chromium/test/MockImageDecoder.h
+++ b/Source/core/platform/graphics/test/MockImageDecoder.h
@@ -25,7 +25,7 @@
 
 #ifndef MockImageDecoder_h
 
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
+#include "core/platform/graphics/ImageFrameGenerator.h"
 #include "core/platform/image-decoders/ImageDecoder.h"
 #include "wtf/PassOwnPtr.h"
 
diff --git a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp b/Source/core/platform/graphics/win/FontCacheWin.cpp
similarity index 92%
rename from Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
rename to Source/core/platform/graphics/win/FontCacheWin.cpp
index b5a661a..cea4160 100644
--- a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
+++ b/Source/core/platform/graphics/win/FontCacheWin.cpp
@@ -35,12 +35,11 @@
 #include <unicode/uniset.h>
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontFallbackWin.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
 #include "platform/LayoutTestSupport.h"
+#include "platform/fonts/FontFallbackWin.h"
 #include "platform/win/HWndDC.h"
 #include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
 #include "wtf/text/StringHash.h"
 
 #include <windows.h>
@@ -362,37 +361,6 @@
     winfont->lfWeight = toGDIFontWeight(fontDescription.weight());
 }
 
-struct TraitsInFamilyProcData {
-    TraitsInFamilyProcData(const AtomicString& familyName)
-        : m_familyName(familyName)
-    {
-    }
-
-    const AtomicString& m_familyName;
-    HashSet<unsigned> m_traitsMasks;
-};
-
-static int CALLBACK traitsInFamilyEnumProc(CONST LOGFONT* logFont, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam)
-{
-    TraitsInFamilyProcData* procData = reinterpret_cast<TraitsInFamilyProcData*>(lParam);
-
-    unsigned traitsMask = 0;
-    traitsMask |= logFont->lfItalic ? FontStyleItalicMask : FontStyleNormalMask;
-    traitsMask |= FontVariantNormalMask;
-    LONG weight = logFont->lfWeight;
-    traitsMask |= weight == FW_THIN ? FontWeight100Mask :
-        weight == FW_EXTRALIGHT ? FontWeight200Mask :
-        weight == FW_LIGHT ? FontWeight300Mask :
-        weight == FW_NORMAL ? FontWeight400Mask :
-        weight == FW_MEDIUM ? FontWeight500Mask :
-        weight == FW_SEMIBOLD ? FontWeight600Mask :
-        weight == FW_BOLD ? FontWeight700Mask :
-        weight == FW_EXTRABOLD ? FontWeight800Mask :
-                                 FontWeight900Mask;
-    procData->m_traitsMasks.add(traitsMask);
-    return 1;
-}
-
 struct GetLastResortFallbackFontProcData {
     GetLastResortFallbackFontProcData(FontCache* fontCache, const FontDescription* fontDescription, FontCache::ShouldRetain shouldRetain, wchar_t* fontName)
         : m_fontCache(fontCache)
@@ -447,7 +415,7 @@
     const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script);
     FontPlatformData* data = 0;
     if (family)
-        data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false);
+        data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)));
 
     // Last resort font list : PanUnicode. CJK fonts have a pretty
     // large repertoire. Eventually, we need to scan all the fonts
@@ -521,11 +489,6 @@
 
 }
 
-PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
-{
-    return 0;
-}
-
 PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
 {
     FontDescription::GenericFamilyType generic = description.genericFamily();
@@ -596,22 +559,6 @@
     return 0;
 }
 
-void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
-{
-    HWndDC hdc(0);
-
-    LOGFONT logFont;
-    logFont.lfCharSet = DEFAULT_CHARSET;
-    unsigned familyLength = min(familyName.length(), static_cast<unsigned>(LF_FACESIZE - 1));
-    familyName.string().copyTo(logFont.lfFaceName, 0, familyLength);
-    logFont.lfFaceName[familyLength] = 0;
-    logFont.lfPitchAndFamily = 0;
-
-    TraitsInFamilyProcData procData(familyName);
-    EnumFontFamiliesEx(hdc, &logFont, traitsInFamilyEnumProc, reinterpret_cast<LPARAM>(&procData), 0);
-    copyToVector(procData.m_traitsMasks, traitsMasks);
-}
-
 FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family, float fontSize)
 {
     LOGFONT winfont = {0};
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/Source/core/platform/graphics/win/FontPlatformDataWin.cpp
similarity index 85%
rename from Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
rename to Source/core/platform/graphics/win/FontPlatformDataWin.cpp
index f987b2f..32b02d0 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/win/FontPlatformDataWin.cpp
@@ -65,29 +65,27 @@
     if (RuntimeEnabledFeatures::subpixelFontScalingEnabled())
         paint->setSubpixelText(true);
 
+    int textFlags = paintTextFlags();
     // Only set painting flags when we're actually painting.
-    if (context) {
-        int textFlags = paintTextFlags();
-        if (!context->couldUseLCDRenderedText()) {
-            textFlags &= ~SkPaint::kLCDRenderText_Flag;
-            // If we *just* clear our request for LCD, then GDI seems to
-            // sometimes give us AA text, and sometimes give us BW text. Since the
-            // original intent was LCD, we want to force AA (rather than BW), so we
-            // add a special bit to tell Skia to do its best to avoid the BW: by
-            // drawing LCD offscreen and downsampling that to AA.
-            textFlags |= SkPaint::kGenA8FromLCD_Flag;
-        }
-
-        static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag |
-            SkPaint::kLCDRenderText_Flag |
-            SkPaint::kGenA8FromLCD_Flag;
-
-        SkASSERT(!(textFlags & ~textFlagsMask));
-        uint32_t flags = paint->getFlags();
-        flags &= ~textFlagsMask;
-        flags |= textFlags;
-        paint->setFlags(flags);
+    if (context && !context->couldUseLCDRenderedText()) {
+        textFlags &= ~SkPaint::kLCDRenderText_Flag;
+        // If we *just* clear our request for LCD, then GDI seems to
+        // sometimes give us AA text, and sometimes give us BW text. Since the
+        // original intent was LCD, we want to force AA (rather than BW), so we
+        // add a special bit to tell Skia to do its best to avoid the BW: by
+        // drawing LCD offscreen and downsampling that to AA.
+        textFlags |= SkPaint::kGenA8FromLCD_Flag;
     }
+
+    static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag |
+        SkPaint::kLCDRenderText_Flag |
+        SkPaint::kGenA8FromLCD_Flag;
+
+    SkASSERT(!(textFlags & ~textFlagsMask));
+    uint32_t flags = paint->getFlags();
+    flags &= ~textFlagsMask;
+    flags |= textFlags;
+    paint->setFlags(flags);
 }
 
 // Lookup the current system settings for font smoothing.
@@ -158,6 +156,7 @@
     return textFlags;
 }
 
+#if !USE(HARFBUZZ)
 PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size, int* paintTextFlags)
 {
     LOGFONT info;
@@ -172,34 +171,39 @@
         *paintTextFlags = computePaintTextFlags(info);
     return adoptRef(SkCreateTypefaceFromLOGFONT(info));
 }
+#endif
 
 FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)
-    : m_font(0)
-    , m_textSize(-1)
+    : m_textSize(-1)
     , m_fakeBold(false)
     , m_fakeItalic(false)
     , m_orientation(Horizontal)
-    , m_scriptCache(0)
     , m_typeface(adoptRef(SkTypeface::RefDefault()))
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(true)
 {
+#if !USE(HARFBUZZ)
+    m_font = 0;
+    m_scriptCache = 0;
+#endif
 }
 
 FontPlatformData::FontPlatformData()
-    : m_font(0)
-    , m_textSize(0)
+    : m_textSize(0)
     , m_fakeBold(false)
     , m_fakeItalic(false)
     , m_orientation(Horizontal)
-    , m_scriptCache(0)
     , m_typeface(adoptRef(SkTypeface::RefDefault()))
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(false)
 {
+#if !USE(HARFBUZZ)
+    m_font = 0;
+    m_scriptCache = 0;
+#endif
 }
 
-#if ENABLE(GDI_FONTS_ON_WINDOWS)
+#if ENABLE(GDI_FONTS_ON_WINDOWS) && !USE(HARFBUZZ)
 FontPlatformData::FontPlatformData(HFONT font, float size, FontOrientation orientation)
     : m_font(RefCountedHFONT::create(font))
     , m_textSize(size)
@@ -215,51 +219,55 @@
 
 // FIXME: this constructor is needed for SVG fonts but doesn't seem to do much
 FontPlatformData::FontPlatformData(float size, bool bold, bool oblique)
-    : m_font(0)
-    , m_textSize(size)
+    : m_textSize(size)
     , m_fakeBold(false)
     , m_fakeItalic(false)
     , m_orientation(Horizontal)
-    , m_scriptCache(0)
     , m_typeface(adoptRef(SkTypeface::RefDefault()))
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(false)
 {
+#if !USE(HARFBUZZ)
+    m_font = 0;
+    m_scriptCache = 0;
+#endif
 }
 
 FontPlatformData::FontPlatformData(const FontPlatformData& data)
-    : m_font(data.m_font)
-    , m_textSize(data.m_textSize)
+    : m_textSize(data.m_textSize)
     , m_fakeBold(data.m_fakeBold)
     , m_fakeItalic(data.m_fakeItalic)
     , m_orientation(data.m_orientation)
-    , m_scriptCache(0)
     , m_typeface(data.m_typeface)
     , m_paintTextFlags(data.m_paintTextFlags)
     , m_isHashTableDeletedValue(false)
 {
+#if !USE(HARFBUZZ)
+    m_font = data.m_font;
+    m_scriptCache = 0;
+#endif
 }
 
 FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize)
-    : m_font(data.m_font)
-    , m_textSize(textSize)
+    : m_textSize(textSize)
     , m_fakeBold(data.m_fakeBold)
     , m_fakeItalic(data.m_fakeItalic)
     , m_orientation(data.m_orientation)
-    , m_scriptCache(0)
     , m_typeface(data.m_typeface)
     , m_paintTextFlags(data.m_paintTextFlags)
     , m_isHashTableDeletedValue(false)
 {
+#if !USE(HARFBUZZ)
+    m_font = data.m_font;
+    m_scriptCache = 0;
+#endif
 }
 
 FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation)
-    : m_font(0)
-    , m_textSize(textSize)
+    : m_textSize(textSize)
     , m_fakeBold(fakeBold)
     , m_fakeItalic(fakeItalic)
     , m_orientation(orientation)
-    , m_scriptCache(0)
     , m_typeface(tf)
     , m_isHashTableDeletedValue(false)
 {
@@ -268,16 +276,18 @@
     LOGFONT logFont;
     SkLOGFONTFromTypeface(m_typeface.get(), &logFont);
     logFont.lfHeight = -textSize;
-    HFONT hFont = CreateFontIndirect(&logFont);
-    if (hFont)
-        m_font = RefCountedHFONT::create(hFont);
     m_paintTextFlags = computePaintTextFlags(logFont);
+
+#if !USE(HARFBUZZ)
+    HFONT hFont = CreateFontIndirect(&logFont);
+    m_font = hFont ? RefCountedHFONT::create(hFont) : 0;
+    m_scriptCache = 0;
+#endif
 }
 
 FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data)
 {
     if (this != &data) {
-        m_font = data.m_font;
         m_textSize = data.m_textSize;
         m_fakeBold = data.m_fakeBold;
         m_fakeItalic = data.m_fakeItalic;
@@ -285,18 +295,23 @@
         m_typeface = data.m_typeface;
         m_paintTextFlags = data.m_paintTextFlags;
 
+#if !USE(HARFBUZZ)
+        m_font = data.m_font;
         // The following fields will get re-computed if necessary.
         ScriptFreeCache(&m_scriptCache);
         m_scriptCache = 0;
         m_scriptFontProperties.clear();
+#endif
     }
     return *this;
 }
 
 FontPlatformData::~FontPlatformData()
 {
+#if !USE(HARFBUZZ)
     ScriptFreeCache(&m_scriptCache);
     m_scriptCache = 0;
+#endif
 }
 
 String FontPlatformData::fontFamilyName() const
@@ -350,6 +365,26 @@
 #endif
 }
 
+bool FontPlatformData::operator==(const FontPlatformData& a) const
+{
+    return SkTypeface::Equal(m_typeface.get(), a.m_typeface.get())
+        && m_textSize == a.m_textSize
+        && m_fakeBold == a.m_fakeBold
+        && m_fakeItalic == a.m_fakeItalic
+        && m_orientation == a.m_orientation
+        && m_isHashTableDeletedValue == a.m_isHashTableDeletedValue;
+}
+
+#if USE(HARFBUZZ)
+HarfBuzzFace* FontPlatformData::harfBuzzFace() const
+{
+    if (!m_harfBuzzFace)
+        m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID());
+
+    return m_harfBuzzFace.get();
+}
+
+#else
 FontPlatformData::RefCountedHFONT::~RefCountedHFONT()
 {
     DeleteObject(m_hfont);
@@ -382,28 +417,19 @@
     return m_scriptFontProperties.get();
 }
 
-#ifndef NDEBUG
-String FontPlatformData::description() const
-{
-    return String();
-}
-#endif
-
 bool FontPlatformData::ensureFontLoaded(HFONT font)
 {
-    WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport();
+    blink::WebSandboxSupport* sandboxSupport = blink::Platform::current()->sandboxSupport();
     // if there is no sandbox, then we can assume the font
     // was able to be loaded successfully already
     return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true;
 }
+#endif
 
-#if USE(HARFBUZZ)
-HarfBuzzFace* FontPlatformData::harfBuzzFace() const
+#ifndef NDEBUG
+String FontPlatformData::description() const
 {
-    if (!m_harfBuzzFace)
-        m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID());
-
-    return m_harfBuzzFace.get();
+    return String();
 }
 #endif
 
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h b/Source/core/platform/graphics/win/FontPlatformDataWin.h
similarity index 91%
rename from Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
rename to Source/core/platform/graphics/win/FontPlatformDataWin.h
index 3b1d22e..1f55a7e 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
+++ b/Source/core/platform/graphics/win/FontPlatformDataWin.h
@@ -32,8 +32,6 @@
 #ifndef FontPlatformDataChromiumWin_h
 #define FontPlatformDataChromiumWin_h
 
-#include "config.h"
-
 #include "SkPaint.h"
 #include "SkTypeface.h"
 #include "SkTypeface_win.h"
@@ -89,8 +87,12 @@
     ~FontPlatformData();
 
     bool isFixedPitch() const;
-    HFONT hfont() const { return m_font ? m_font->hfont() : 0; }
     float size() const { return m_textSize; }
+#if USE(HARFBUZZ)
+    HarfBuzzFace* harfBuzzFace() const;
+#else
+    HFONT hfont() const { return m_font ? m_font->hfont() : 0; }
+#endif
     SkTypeface* typeface() const { return m_typeface.get(); }
     SkFontID uniqueID() const { return m_typeface->uniqueID(); }
     int paintTextFlags() const { return m_paintTextFlags; }
@@ -109,10 +111,7 @@
     unsigned hash() const;
 #endif
 
-    bool operator==(const FontPlatformData& other) const
-    {
-        return m_font == other.m_font && m_textSize == other.m_textSize && m_fakeBold == other.m_fakeBold && m_fakeItalic == other.m_fakeItalic && m_orientation == other.m_orientation;
-    }
+    bool operator==(const FontPlatformData&) const;
 
 #if ENABLE(OPENTYPE_VERTICAL)
     PassRefPtr<OpenTypeVerticalData> verticalData() const;
@@ -123,19 +122,14 @@
     String description() const;
 #endif
 
-    // FIXME: Only used by Uniscribe, should be protected by a
-    // ENABLE(GDI_FONTS_ON_WINDOWS) macro once we have an abstraction layer
-    // for complex text shaping.
+#if !USE(HARFBUZZ)
     SCRIPT_FONTPROPERTIES* scriptFontProperties() const;
     SCRIPT_CACHE* scriptCache() const { return &m_scriptCache; }
-
     static bool ensureFontLoaded(HFONT);
-
-#if USE(HARFBUZZ)
-    HarfBuzzFace* harfBuzzFace() const;
 #endif
 
 private:
+#if !USE(HARFBUZZ)
     // We refcount the internal HFONT so that FontPlatformData can be
     // efficiently copied. WebKit depends on being able to copy it, and we
     // don't really want to re-create the HFONT.
@@ -170,19 +164,20 @@
     };
 
     RefPtr<RefCountedHFONT> m_font;
+#endif // !USE(HARFBUZZ)
     float m_textSize; // Point size of the font in pixels.
     FontOrientation m_orientation;
     bool m_fakeBold;
     bool m_fakeItalic;
 
-    RefPtr<SkTypeface> m_typeface; // cached from m_font
-    int m_paintTextFlags; // cached from m_font
-
-    mutable SCRIPT_CACHE m_scriptCache;
-    mutable OwnPtr<SCRIPT_FONTPROPERTIES> m_scriptFontProperties;
+    RefPtr<SkTypeface> m_typeface;
+    int m_paintTextFlags;
 
 #if USE(HARFBUZZ)
     mutable RefPtr<HarfBuzzFace> m_harfBuzzFace;
+#else
+    mutable SCRIPT_CACHE m_scriptCache;
+    mutable OwnPtr<SCRIPT_FONTPROPERTIES> m_scriptFontProperties;
 #endif
 
     bool m_isHashTableDeletedValue;
diff --git a/Source/core/platform/graphics/chromium/FontChromiumWin.cpp b/Source/core/platform/graphics/win/FontWin.cpp
similarity index 91%
rename from Source/core/platform/graphics/chromium/FontChromiumWin.cpp
rename to Source/core/platform/graphics/win/FontWin.cpp
index 4bd4d53..aa2b482 100644
--- a/Source/core/platform/graphics/chromium/FontChromiumWin.cpp
+++ b/Source/core/platform/graphics/win/FontWin.cpp
@@ -32,14 +32,14 @@
 #include "config.h"
 #include "core/platform/graphics/Font.h"
 
-#include "platform/NotImplemented.h"
 #include "core/platform/graphics/FontFallbackList.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/UniscribeHelperTextRun.h"
 #include "core/platform/graphics/skia/SkiaFontWin.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
+#include "core/platform/graphics/win/UniscribeHelperTextRun.h"
 #include "platform/fonts/GlyphBuffer.h"
+#include "platform/NotImplemented.h"
 
 #include <windows.h>
 
@@ -58,12 +58,9 @@
 }
 
 void Font::drawGlyphs(GraphicsContext* graphicsContext,
-                      const SimpleFontData* font,
-                      const GlyphBuffer& glyphBuffer,
-                      int from,
-                      int numGlyphs,
-                      const FloatPoint& point,
-                      const FloatRect& textRect) const
+    const SimpleFontData* font, const GlyphBuffer& glyphBuffer,
+    unsigned from, unsigned numGlyphs, const FloatPoint& point,
+    const FloatRect& textRect) const
 {
     SkColor color = graphicsContext->effectiveFillColor();
     unsigned char alpha = SkColorGetA(color);
@@ -73,9 +70,9 @@
 
     // We draw the glyphs in chunks to avoid having to do a heap allocation for
     // the arrays of characters and advances.
-    const int kMaxBufferLength = 256;
+    const unsigned kMaxBufferLength = 256;
     Vector<int, kMaxBufferLength> advances;
-    int glyphIndex = 0;  // The starting glyph of the current chunk.
+    unsigned glyphIndex = 0; // The starting glyph of the current chunk.
 
     float horizontalOffset = point.x(); // The floating point offset of the left side of the current glyph.
 
@@ -94,7 +91,7 @@
         SkScalar verticalOriginX = SkFloatToScalar(point.x() + metrics.floatAscent() - metrics.floatAscent(IdeographicBaseline));
         while (glyphIndex < numGlyphs) {
             // How many chars will be in this chunk?
-            int curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex);
+            unsigned curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex);
 
             const Glyph* glyphs = glyphBuffer.glyphs(from + glyphIndex);
             translations.resize(curLen);
@@ -104,7 +101,7 @@
             advances.fill(0);
             offsets.resize(curLen);
             float currentWidth = 0;
-            for (int i = 0; i < curLen; ++i, ++glyphIndex) {
+            for (unsigned i = 0; i < curLen; ++i, ++glyphIndex) {
                 offsets[i].du = lroundf(translations[i].x());
                 offsets[i].dv = -lroundf(currentWidth - translations[i].y());
                 currentWidth += glyphBuffer.advanceAt(from + glyphIndex);
@@ -127,12 +124,12 @@
     Vector<WORD, kMaxBufferLength> glyphs;
     while (glyphIndex < numGlyphs) {
         // How many chars will be in this chunk?
-        int curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex);
+        unsigned curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex);
         glyphs.resize(curLen);
         advances.resize(curLen);
 
         float currentWidth = 0;
-        for (int i = 0; i < curLen; ++i, ++glyphIndex) {
+        for (unsigned i = 0; i < curLen; ++i, ++glyphIndex) {
             glyphs[i] = glyphBuffer.glyphAt(from + glyphIndex);
             horizontalOffset += glyphBuffer.advanceAt(from + glyphIndex);
             advances[i] = lroundf(horizontalOffset) - lastHorizontalOffsetRounded;
diff --git a/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp b/Source/core/platform/graphics/win/GlyphPageTreeNodeWin.cpp
similarity index 98%
rename from Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp
rename to Source/core/platform/graphics/win/GlyphPageTreeNodeWin.cpp
index c9a3217..66d2e68 100644
--- a/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp
+++ b/Source/core/platform/graphics/win/GlyphPageTreeNodeWin.cpp
@@ -35,8 +35,8 @@
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GlyphPageTreeNode.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/UniscribeHelperTextRun.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
+#include "core/platform/graphics/win/UniscribeHelperTextRun.h"
 #include "platform/win/HWndDC.h"
 #include "platform/win/SystemInfo.h"
 
diff --git a/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp b/Source/core/platform/graphics/win/SimpleFontDataWin.cpp
similarity index 97%
rename from Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp
rename to Source/core/platform/graphics/win/SimpleFontDataWin.cpp
index 3f26a13..14b0353 100644
--- a/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/win/SimpleFontDataWin.cpp
@@ -38,7 +38,7 @@
 #include <unicode/unorm.h>
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/win/HWndDC.h"
@@ -115,7 +115,7 @@
     float scaledSize = scaleFactor * fontDescription.computedSize();
     winFont.lfHeight = -lroundf(scaledSize);
     HFONT hfont = CreateFontIndirect(&winFont);
-    return SimpleFontData::create(FontPlatformData(hfont, scaledSize, m_platformData.orientation()), isCustomFont(), false);
+    return SimpleFontData::create(FontPlatformData(hfont, scaledSize, m_platformData.orientation()), isCustomFont() ? CustomFontData::create(false) : 0);
 }
 
 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
diff --git a/Source/core/platform/graphics/chromium/TransparencyWin.cpp b/Source/core/platform/graphics/win/TransparencyWin.cpp
similarity index 99%
rename from Source/core/platform/graphics/chromium/TransparencyWin.cpp
rename to Source/core/platform/graphics/win/TransparencyWin.cpp
index 63dcc0c..217dc3d 100644
--- a/Source/core/platform/graphics/chromium/TransparencyWin.cpp
+++ b/Source/core/platform/graphics/win/TransparencyWin.cpp
@@ -34,8 +34,8 @@
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/TransparencyWin.h"
 #include "core/platform/graphics/skia/SkiaUtils.h"
+#include "core/platform/graphics/win/TransparencyWin.h"
 #include "platform/transforms/AffineTransform.h"
 
 #include "SkColorPriv.h"
diff --git a/Source/core/platform/graphics/chromium/TransparencyWin.h b/Source/core/platform/graphics/win/TransparencyWin.h
similarity index 100%
rename from Source/core/platform/graphics/chromium/TransparencyWin.h
rename to Source/core/platform/graphics/win/TransparencyWin.h
diff --git a/Source/core/platform/graphics/chromium/UniscribeHelper.cpp b/Source/core/platform/graphics/win/UniscribeHelper.cpp
similarity index 99%
rename from Source/core/platform/graphics/chromium/UniscribeHelper.cpp
rename to Source/core/platform/graphics/win/UniscribeHelper.cpp
index 4695f93..8bd6a48 100644
--- a/Source/core/platform/graphics/chromium/UniscribeHelper.cpp
+++ b/Source/core/platform/graphics/win/UniscribeHelper.cpp
@@ -29,13 +29,13 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/UniscribeHelper.h"
+#include "core/platform/graphics/win/UniscribeHelper.h"
 
 #include <windows.h>
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/chromium/FontFallbackWin.h"
 #include "core/platform/graphics/skia/SkiaFontWin.h"
+#include "platform/fonts/FontFallbackWin.h"
 #include "platform/win/HWndDC.h"
 #include "third_party/skia/include/core/SkPoint.h"
 #include "wtf/Assertions.h"
diff --git a/Source/core/platform/graphics/chromium/UniscribeHelper.h b/Source/core/platform/graphics/win/UniscribeHelper.h
similarity index 100%
rename from Source/core/platform/graphics/chromium/UniscribeHelper.h
rename to Source/core/platform/graphics/win/UniscribeHelper.h
diff --git a/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.cpp b/Source/core/platform/graphics/win/UniscribeHelperTextRun.cpp
similarity index 96%
rename from Source/core/platform/graphics/chromium/UniscribeHelperTextRun.cpp
rename to Source/core/platform/graphics/win/UniscribeHelperTextRun.cpp
index 57fbf17..27b18a2 100644
--- a/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.cpp
+++ b/Source/core/platform/graphics/win/UniscribeHelperTextRun.cpp
@@ -29,11 +29,11 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/UniscribeHelperTextRun.h"
+#include "core/platform/graphics/win/UniscribeHelperTextRun.h"
 
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "core/platform/graphics/win/FontPlatformDataWin.h"
 #include "platform/graphics/TextRun.h"
 
 namespace WebCore {
@@ -102,7 +102,7 @@
     // This check is necessary because NextWinFontData can be called again
     // after we already ran out of fonts. fontDataAt behaves in a strange
     // manner when the difference between param passed and # of fonts stored in
-    // WebKit::Font is larger than one. We can avoid this check by setting
+    // blink::Font is larger than one. We can avoid this check by setting
     // font_index_ to # of elements in hfonts_ when we run out of font. In that
     // case, we'd have to go through a couple of more checks before returning
     // false.
diff --git a/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.h b/Source/core/platform/graphics/win/UniscribeHelperTextRun.h
similarity index 96%
rename from Source/core/platform/graphics/chromium/UniscribeHelperTextRun.h
rename to Source/core/platform/graphics/win/UniscribeHelperTextRun.h
index 0bac52e..44a94e4 100644
--- a/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.h
+++ b/Source/core/platform/graphics/win/UniscribeHelperTextRun.h
@@ -31,7 +31,7 @@
 #ifndef UniscribeHelperTextRun_h
 #define UniscribeHelperTextRun_h
 
-#include "core/platform/graphics/chromium/UniscribeHelper.h"
+#include "core/platform/graphics/win/UniscribeHelper.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -70,7 +70,7 @@
     virtual bool nextWinFontData(HFONT&, SCRIPT_CACHE*&, SCRIPT_FONTPROPERTIES*&, int& ascent, WORD& spaceGlyph);
     virtual void resetFontIndex();
 
-    // Reference to WebKit::Font that contains all the information about fonts
+    // Reference to blink::Font that contains all the information about fonts
     // we can use to render this input run of text.  It is used in
     // NextWinFontData to retrieve Windows font data for a series of
     // non-primary fonts.
diff --git a/Source/core/platform/image-decoders/ImageDecoder.cpp b/Source/core/platform/image-decoders/ImageDecoder.cpp
index 7b9938b..619c31d 100644
--- a/Source/core/platform/image-decoders/ImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/ImageDecoder.cpp
@@ -88,7 +88,7 @@
     static const unsigned longestSignatureLength = sizeof("RIFF????WEBPVP") - 1;
     ASSERT(longestSignatureLength == 14);
 
-    size_t maxDecodedBytes = WebKit::Platform::current()->maxDecodedImageBytes();
+    size_t maxDecodedBytes = blink::Platform::current()->maxDecodedImageBytes();
 
     char contents[longestSignatureLength];
     if (copyFromSharedBuffer(contents, longestSignatureLength, data, 0) < longestSignatureLength)
diff --git a/Source/core/platform/image-decoders/ImageDecoder.h b/Source/core/platform/image-decoders/ImageDecoder.h
index 2f6d8d9..cafd9a3 100644
--- a/Source/core/platform/image-decoders/ImageDecoder.h
+++ b/Source/core/platform/image-decoders/ImageDecoder.h
@@ -135,6 +135,8 @@
         bool premultiplyAlpha() const { return m_premultiplyAlpha; }
         SkBitmap::Allocator* allocator() const { return m_allocator; }
         const SkBitmap& getSkBitmap() const { return m_bitmap->bitmap(); }
+        // Returns true if the pixels changed, but the bitmap has not yet been notified.
+        bool pixelsChanged() const { return m_pixelsChanged; }
 
         size_t requiredPreviousFrameIndex() const
         {
@@ -153,6 +155,9 @@
         void setPremultiplyAlpha(bool premultiplyAlpha) { m_premultiplyAlpha = premultiplyAlpha; }
         void setMemoryAllocator(SkBitmap::Allocator* allocator) { m_allocator = allocator; }
         void setSkBitmap(const SkBitmap& bitmap) { m_bitmap = NativeImageSkia::create(bitmap); }
+        // The pixelsChanged flag needs to be set when the raw pixel data was directly modified
+        // (e.g. through a pointer or setRGBA). The flag is usually set after a batch of changes was made.
+        void setPixelsChanged(bool pixelsChanged) { m_pixelsChanged = pixelsChanged; }
 
         void setRequiredPreviousFrameIndex(size_t previousFrameIndex)
         {
@@ -198,6 +203,14 @@
             *dest = SkPackARGB32NoCheck(a, r, g, b);
         }
 
+        // Notifies the SkBitmap if any pixels changed and resets the flag.
+        inline void notifyBitmapIfPixelsChanged()
+        {
+            if (m_pixelsChanged)
+                m_bitmap->bitmap().notifyPixelsChanged();
+            m_pixelsChanged = false;
+        }
+
     private:
         int width() const
         {
@@ -220,6 +233,8 @@
         DisposalMethod m_disposalMethod;
         AlphaBlendSource m_alphaBlendSource;
         bool m_premultiplyAlpha;
+        // True if the pixels changed, but the bitmap has not yet been notified.
+        bool m_pixelsChanged;
 
         // The frame that must be decoded before this frame can be decoded.
         // WTF::kNotFound if this frame doesn't require any previous frame.
@@ -237,7 +252,7 @@
     class ImageDecoder {
         WTF_MAKE_NONCOPYABLE(ImageDecoder); WTF_MAKE_FAST_ALLOCATED;
     public:
-        static const size_t noDecodedImageByteLimit = WebKit::Platform::noDecodedImageByteLimit;
+        static const size_t noDecodedImageByteLimit = blink::Platform::noDecodedImageByteLimit;
 
         ImageDecoder(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption, size_t maxDecodedBytes)
             : m_premultiplyAlpha(alphaOption == ImageSource::AlphaPremultiplied)
diff --git a/Source/core/platform/image-decoders/ImageFrame.cpp b/Source/core/platform/image-decoders/ImageFrame.cpp
index 7d234f0..9250978 100644
--- a/Source/core/platform/image-decoders/ImageFrame.cpp
+++ b/Source/core/platform/image-decoders/ImageFrame.cpp
@@ -41,6 +41,7 @@
     , m_disposalMethod(DisposeNotSpecified)
     , m_alphaBlendSource(BlendAtopPreviousFrame)
     , m_premultiplyAlpha(true)
+    , m_pixelsChanged(false)
     , m_requiredPreviousFrameIndex(kNotFound)
 #if !ASSERT_DISABLED
     , m_requiredPreviousFrameIndexValid(false)
@@ -57,6 +58,9 @@
     // Keep the pixels locked since we will be writing directly into the
     // bitmap throughout this object's lifetime.
     m_bitmap->bitmap().lockPixels();
+    // Be sure to assign this before calling setStatus(), since setStatus() may
+    // call notifyBitmapIfPixelsChanged().
+    m_pixelsChanged = other.m_pixelsChanged;
     setMemoryAllocator(other.allocator());
     setOriginalFrameRect(other.originalFrameRect());
     setStatus(other.status());
@@ -142,6 +146,9 @@
     m_status = status;
     if (m_status == FrameComplete) {
         m_bitmap->bitmap().setAlphaType(m_hasAlpha ? kPremul_SkAlphaType : kOpaque_SkAlphaType);
+        // Send pending pixels changed notifications now, because we can't do this after
+        // the bitmap was set immutable by setDataComplete().
+        notifyBitmapIfPixelsChanged();
         m_bitmap->setDataComplete(); // Tell the bitmap it's done.
     }
 }
diff --git a/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp b/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
index 3afdcbc..926df00 100644
--- a/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
@@ -31,8 +31,8 @@
 #include "config.h"
 #include "core/platform/image-decoders/bmp/BMPImageDecoder.h"
 
-#include "core/platform/PlatformInstrumentation.h"
 #include "core/platform/image-decoders/bmp/BMPImageReader.h"
+#include "platform/PlatformInstrumentation.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
index 91cb1d5..621415b 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
@@ -27,8 +27,8 @@
 #include "core/platform/image-decoders/gif/GIFImageDecoder.h"
 
 #include <limits>
-#include "core/platform/PlatformInstrumentation.h"
 #include "core/platform/image-decoders/gif/GIFImageReader.h"
+#include "platform/PlatformInstrumentation.h"
 #include "wtf/NotFound.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -114,6 +114,8 @@
         decode(index);
         PlatformInstrumentation::didDecodeImage();
     }
+
+    frame.notifyBitmapIfPixelsChanged();
     return &frame;
 }
 
@@ -203,6 +205,7 @@
     if (repeatCount > 1)
         buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd);
 
+    buffer.setPixelsChanged(true);
     return true;
 }
 
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp b/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
index 9c89225..352d974 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
@@ -44,7 +44,7 @@
 #include <gtest/gtest.h>
 
 using namespace WebCore;
-using namespace WebKit;
+using namespace blink;
 
 namespace {
 
@@ -146,14 +146,17 @@
     EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
 
     ImageFrame* frame = decoder->frameBufferAtIndex(0);
+    uint32_t generationID0 = frame->getSkBitmap().getGenerationID();
     EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
     EXPECT_EQ(16, frame->getSkBitmap().width());
     EXPECT_EQ(16, frame->getSkBitmap().height());
 
     frame = decoder->frameBufferAtIndex(1);
+    uint32_t generationID1 = frame->getSkBitmap().getGenerationID();
     EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
     EXPECT_EQ(16, frame->getSkBitmap().width());
     EXPECT_EQ(16, frame->getSkBitmap().height());
+    EXPECT_TRUE(generationID0 != generationID1);
 
     EXPECT_EQ(2u, decoder->frameCount());
     EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
diff --git a/Source/core/platform/image-decoders/gif/GIFImageReader.cpp b/Source/core/platform/image-decoders/gif/GIFImageReader.cpp
index b933855..b7f7a9c 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageReader.cpp
+++ b/Source/core/platform/image-decoders/gif/GIFImageReader.cpp
@@ -488,11 +488,11 @@
 
         case GIFExtension: {
             size_t bytesInBlock = currentComponent[1];
-            GIFState es = GIFSkipBlock;
+            GIFState exceptionState = GIFSkipBlock;
 
             switch (*currentComponent) {
             case 0xf9:
-                es = GIFControlExtension;
+                exceptionState = GIFControlExtension;
                 // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
                 // and the parser for this block reads 4 bytes, so we must enforce that the buffer
                 // contains at least this many bytes. If the GIF specifies a different length, we
@@ -511,16 +511,16 @@
                 break;
 
             case 0xff:
-                es = GIFApplicationExtension;
+                exceptionState = GIFApplicationExtension;
                 break;
 
             case 0xfe:
-                es = GIFConsumeComment;
+                exceptionState = GIFConsumeComment;
                 break;
             }
 
             if (bytesInBlock)
-                GETN(bytesInBlock, es);
+                GETN(bytesInBlock, exceptionState);
             else
                 GETN(1, GIFImageStart);
             break;
diff --git a/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp b/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
index 6367662..f8e256b 100644
--- a/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
@@ -33,9 +33,9 @@
 
 #include <algorithm>
 
-#include "core/platform/PlatformInstrumentation.h"
 #include "core/platform/image-decoders/bmp/BMPImageReader.h"
 #include "core/platform/image-decoders/png/PNGImageDecoder.h"
+#include "platform/PlatformInstrumentation.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
index 8dbdb50..b988f8c 100644
--- a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
@@ -40,7 +40,7 @@
 #include "config.h"
 #include "core/platform/image-decoders/jpeg/JPEGImageDecoder.h"
 
-#include "core/platform/PlatformInstrumentation.h"
+#include "platform/PlatformInstrumentation.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/dtoa/utils.h"
 
@@ -657,6 +657,8 @@
         decode(false);
         PlatformInstrumentation::didDecodeImage();
     }
+
+    frame.notifyBitmapIfPixelsChanged();
     return &frame;
 }
 
@@ -712,6 +714,7 @@
             setPixel<colorSpace>(buffer, pixel, samples, x);
     }
 
+    buffer.setPixelsChanged(true);
     return true;
 }
 
@@ -749,9 +752,10 @@
             if (qcms_transform* transform = m_reader->colorTransform())
                 qcms_transform_data_type(transform, row, row, info->output_width, rgbOutputColorSpace() == JCS_EXT_BGRA ? QCMS_OUTPUT_BGRX : QCMS_OUTPUT_RGBX);
 #endif
-         }
-         return true;
-     }
+        }
+        buffer.setPixelsChanged(true);
+        return true;
+    }
 #endif
 
     switch (info->out_color_space) {
diff --git a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
index 9c2f95a..076ac5d 100644
--- a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
@@ -45,7 +45,7 @@
 #include <gtest/gtest.h>
 
 using namespace WebCore;
-using namespace WebKit;
+using namespace blink;
 
 namespace {
 
diff --git a/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp b/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
index fff9848..d616390 100644
--- a/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
@@ -39,7 +39,7 @@
 #include "config.h"
 #include "core/platform/image-decoders/png/PNGImageDecoder.h"
 
-#include "core/platform/PlatformInstrumentation.h"
+#include "platform/PlatformInstrumentation.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -251,6 +251,8 @@
         decode(false);
         PlatformInstrumentation::didDecodeImage();
     }
+
+    frame.notifyBitmapIfPixelsChanged();
     return &frame;
 }
 
@@ -504,6 +506,8 @@
 
     if (nonTrivialAlpha && !buffer.hasAlpha())
         buffer.setHasAlpha(nonTrivialAlpha);
+
+    buffer.setPixelsChanged(true);
 }
 
 void PNGImageDecoder::pngComplete()
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
index 5c9a0b4..c2da555 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
@@ -30,7 +30,7 @@
 #include "core/platform/image-decoders/webp/WEBPImageDecoder.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "core/platform/PlatformInstrumentation.h"
+#include "platform/PlatformInstrumentation.h"
 
 #if USE(QCMSLIB)
 #include "qcms.h"
@@ -152,6 +152,7 @@
         if (index >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_demux && m_demuxState != WEBP_DEMUX_DONE)
             setFailed();
 
+        frame.notifyBitmapIfPixelsChanged();
         return &frame;
     }
 
@@ -462,6 +463,7 @@
     }
 
     m_decodedHeight = decodedHeight;
+    buffer.setPixelsChanged(true);
 }
 
 bool WEBPImageDecoder::decode(const uint8_t* dataBytes, size_t dataSize, bool onlySize, size_t frameIndex)
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
index 8747467..4fcd360 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
@@ -46,7 +46,7 @@
 #include <gtest/gtest.h>
 
 using namespace WebCore;
-using namespace WebKit;
+using namespace blink;
 
 namespace {
 
@@ -183,6 +183,22 @@
     }
 };
 
+TEST_F(AnimatedWebPTests, uniqueGenerationIDs)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+
+    RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
+    ASSERT_TRUE(data.get());
+    decoder->setData(data.get(), true);
+
+    ImageFrame* frame = decoder->frameBufferAtIndex(0);
+    uint32_t generationID0 = frame->getSkBitmap().getGenerationID();
+    frame = decoder->frameBufferAtIndex(1);
+    uint32_t generationID1 = frame->getSkBitmap().getGenerationID();
+
+    EXPECT_TRUE(generationID0 != generationID1);
+}
+
 TEST_F(AnimatedWebPTests, verifyAnimationParametersTransparentImage)
 {
     OwnPtr<WEBPImageDecoder> decoder = createDecoder();
diff --git a/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp b/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp
index de34c98..bb7b6ad 100644
--- a/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp
+++ b/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp
@@ -33,7 +33,7 @@
 
 #include "SkBitmap.h"
 #include "SkColorPriv.h"
-#include "core/html/ImageData.h"
+#include "core/platform/graphics/ImageBuffer.h"
 #include "platform/geometry/IntSize.h"
 extern "C" {
 #include <setjmp.h>
@@ -106,6 +106,17 @@
     }
 }
 
+static void disableSubsamplingForHighQuality(jpeg_compress_struct* cinfo, int quality)
+{
+    if (quality < 100)
+        return;
+
+    for (int i = 0; i < MAX_COMPONENTS; ++i) {
+        cinfo->comp_info[i].h_samp_factor = 1;
+        cinfo->comp_info[i].v_samp_factor = 1;
+    }
+}
+
 static bool encodePixels(IntSize imageSize, unsigned char* inputPixels, bool premultiplied, int quality, Vector<unsigned char>* output)
 {
     JPEGOutputBuffer destination;
@@ -142,6 +153,7 @@
 
         jpeg_set_defaults(&cinfo);
         jpeg_set_quality(&cinfo, quality, TRUE);
+        disableSubsamplingForHighQuality(&cinfo, quality);
         jpeg_start_compress(&cinfo, TRUE);
 
         unsigned char* pixels = inputPixels;
@@ -167,6 +179,7 @@
 
     jpeg_set_defaults(&cinfo);
     jpeg_set_quality(&cinfo, quality, TRUE);
+    disableSubsamplingForHighQuality(&cinfo, quality);
     jpeg_start_compress(&cinfo, TRUE);
 
     unsigned char* pixels = inputPixels;
@@ -194,9 +207,9 @@
     return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char *>(bitmap.getPixels()), true, quality, output);
 }
 
-bool JPEGImageEncoder::encode(const ImageData& imageData, int quality, Vector<unsigned char>* output)
+bool JPEGImageEncoder::encode(const ImageDataBuffer& imageData, int quality, Vector<unsigned char>* output)
 {
-    return encodePixels(imageData.size(), imageData.data()->data(), false, quality, output);
+    return encodePixels(imageData.size(), imageData.data(), false, quality, output);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h b/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h
index ca3ef48..8c53446 100644
--- a/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h
+++ b/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h
@@ -37,13 +37,13 @@
 
 namespace WebCore {
 
-class ImageData;
+struct ImageDataBuffer;
 
 class JPEGImageEncoder {
 public:
     // Encode the input data with a compression quality in [0-100].
     static bool encode(const SkBitmap&, int quality, Vector<unsigned char>*);
-    static bool encode(const ImageData&, int quality, Vector<unsigned char>*);
+    static bool encode(const ImageDataBuffer&, int quality, Vector<unsigned char>*);
 
     // For callers: provide a reasonable compression quality default.
     enum Quality { DefaultCompressionQuality = 92 };
diff --git a/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp b/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp
index edb1e46..8e8710c 100644
--- a/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp
+++ b/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp
@@ -34,7 +34,7 @@
 #include "SkBitmap.h"
 #include "SkColorPriv.h"
 #include "SkUnPreMultiply.h"
-#include "core/html/ImageData.h"
+#include "core/platform/graphics/ImageBuffer.h"
 #include "platform/geometry/IntSize.h"
 extern "C" {
 #include "png.h"
@@ -124,9 +124,9 @@
     return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char*>(bitmap.getPixels()), true, output);
 }
 
-bool PNGImageEncoder::encode(const ImageData& imageData, Vector<unsigned char>* output)
+bool PNGImageEncoder::encode(const ImageDataBuffer& imageData, Vector<unsigned char>* output)
 {
-    return encodePixels(imageData.size(), imageData.data()->data(), false, output);
+    return encodePixels(imageData.size(), imageData.data(), false, output);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/image-encoders/skia/PNGImageEncoder.h b/Source/core/platform/image-encoders/skia/PNGImageEncoder.h
index a8f0ea5..e8fc52f 100644
--- a/Source/core/platform/image-encoders/skia/PNGImageEncoder.h
+++ b/Source/core/platform/image-encoders/skia/PNGImageEncoder.h
@@ -37,13 +37,13 @@
 
 namespace WebCore {
 
-class ImageData;
+struct ImageDataBuffer;
 
 // Interface for encoding PNG data. This is a wrapper around libpng.
 class PNGImageEncoder {
 public:
     static bool encode(const SkBitmap&, Vector<unsigned char>* output);
-    static bool encode(const ImageData&, Vector<unsigned char>* output);
+    static bool encode(const ImageDataBuffer&, Vector<unsigned char>* output);
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp b/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp
index a45e321..46b0624 100644
--- a/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp
+++ b/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp
@@ -32,7 +32,7 @@
 #include "core/platform/image-encoders/skia/WEBPImageEncoder.h"
 
 #include "SkBitmap.h"
-#include "core/html/ImageData.h"
+#include "core/platform/graphics/ImageBuffer.h"
 #include "platform/geometry/IntSize.h"
 #include "webp/encode.h"
 
@@ -125,9 +125,9 @@
     return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char *>(bitmap.getPixels()), true, quality, output);
 }
 
-bool WEBPImageEncoder::encode(const ImageData& imageData, int quality, Vector<unsigned char>* output)
+bool WEBPImageEncoder::encode(const ImageDataBuffer& imageData, int quality, Vector<unsigned char>* output)
 {
-    return encodePixels(imageData.size(), imageData.data()->data(), false, quality, output);
+    return encodePixels(imageData.size(), imageData.data(), false, quality, output);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h b/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h
index e04c702..e138bc8 100644
--- a/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h
+++ b/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h
@@ -37,13 +37,13 @@
 
 namespace WebCore {
 
-class ImageData;
+struct ImageDataBuffer;
 
 class WEBPImageEncoder {
 public:
     // Encode the input data with a compression quality in [0-100].
     static bool encode(const SkBitmap&, int quality, Vector<unsigned char>*);
-    static bool encode(const ImageData&, int quality, Vector<unsigned char>*);
+    static bool encode(const ImageDataBuffer&, int quality, Vector<unsigned char>*);
 
     // For callers: provide a reasonable compression quality default.
     enum Quality { DefaultCompressionQuality = 80 };
diff --git a/Source/core/platform/mac/BlockExceptions.h b/Source/core/platform/mac/BlockExceptions.h
deleted file mode 100644
index 3968a55..0000000
--- a/Source/core/platform/mac/BlockExceptions.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2003 Apple Computer, 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.
- */
-
-#import <Foundation/NSException.h>
-#import <wtf/Assertions.h>
-
-NO_RETURN_DUE_TO_ASSERT void ReportBlockedObjCException(NSException *);
-
-#define BEGIN_BLOCK_OBJC_EXCEPTIONS @try {
-#define END_BLOCK_OBJC_EXCEPTIONS } @catch(NSException *localException) { ReportBlockedObjCException(localException); }
-
diff --git a/Source/core/platform/mac/BlockExceptions.mm b/Source/core/platform/mac/BlockExceptions.mm
deleted file mode 100644
index 66dca3f..0000000
--- a/Source/core/platform/mac/BlockExceptions.mm
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2003, 2007 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. 
- */
-
-#import "config.h"
-#import "core/platform/mac/BlockExceptions.h"
-
-#import <wtf/Assertions.h>
-
-void ReportBlockedObjCException(NSException *exception)
-{
-#if ASSERT_DISABLED
-    NSLog(@"*** WebKit discarding exception: <%@> %@", [exception name], [exception reason]);
-#else
-    ASSERT_WITH_MESSAGE(0, "Uncaught exception - %@", exception);
-#endif
-}
diff --git a/Source/core/platform/mac/KillRingMac.mm b/Source/core/platform/mac/KillRingMac.mm
deleted file mode 100644
index 6213569..0000000
--- a/Source/core/platform/mac/KillRingMac.mm
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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. 
- */
-
-#import "config.h"
-#import "core/platform/KillRing.h"
-
-namespace WebCore {
-
-extern "C" {
-
-// Kill ring calls. Would be better to use NSKillRing.h, but that's not available as API or SPI.
-
-void _NSInitializeKillRing();
-void _NSAppendToKillRing(NSString *);
-void _NSPrependToKillRing(NSString *);
-NSString *_NSYankFromKillRing();
-void _NSNewKillRingSequence();
-void _NSSetKillRingToYankedState();
-
-}
-
-static void initializeKillRingIfNeeded()
-{
-    static bool initializedKillRing = false;
-    if (!initializedKillRing) {
-        initializedKillRing = true;
-        _NSInitializeKillRing();
-    }
-}
-
-void KillRing::append(const String& string)
-{
-    initializeKillRingIfNeeded();
-    _NSAppendToKillRing(string);
-}
-
-void KillRing::prepend(const String& string)
-{
-    initializeKillRingIfNeeded();
-    _NSPrependToKillRing(string);
-}
-
-String KillRing::yank()
-{
-    initializeKillRingIfNeeded();
-    return _NSYankFromKillRing();
-}
-
-void KillRing::startNewSequence()
-{
-    initializeKillRingIfNeeded();
-    _NSNewKillRingSequence();
-}
-
-void KillRing::setToYankedState()
-{
-    initializeKillRingIfNeeded();
-    _NSSetKillRingToYankedState();
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/mac/NSScrollerImpDetails.h b/Source/core/platform/mac/NSScrollerImpDetails.h
index bc260f0..2ec59f5 100644
--- a/Source/core/platform/mac/NSScrollerImpDetails.h
+++ b/Source/core/platform/mac/NSScrollerImpDetails.h
@@ -26,7 +26,6 @@
 #ifndef WebCore_NSScrollerImpDetails_h
 #define WebCore_NSScrollerImpDetails_h
 
-#include "config.h"
 #import <AvailabilityMacros.h>
 
 // Public APIs not available on versions of Mac on which we build
diff --git a/Source/core/platform/mac/ScrollAnimatorMac.mm b/Source/core/platform/mac/ScrollAnimatorMac.mm
index 2d9a1e0..a25135b 100644
--- a/Source/core/platform/mac/ScrollAnimatorMac.mm
+++ b/Source/core/platform/mac/ScrollAnimatorMac.mm
@@ -32,12 +32,12 @@
 #include "core/platform/ScrollbarTheme.h"
 #include "core/platform/ScrollbarThemeMacCommon.h"
 #include "core/platform/ScrollbarThemeMacOverlayAPI.h"
-#include "core/platform/mac/BlockExceptions.h"
 #include "core/platform/mac/EmptyProtocolDefinitions.h"
 #include "core/platform/mac/NSScrollerImpDetails.h"
 #include "platform/PlatformGestureEvent.h"
 #include "platform/PlatformWheelEvent.h"
 #include "platform/geometry/FloatPoint.h"
+#include "platform/mac/BlockExceptions.h"
 #include "wtf/MainThread.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/UnusedParam.h"
diff --git a/Source/core/platform/mac/ThemeMac.mm b/Source/core/platform/mac/ThemeMac.mm
index d9a696a..8a977c1 100644
--- a/Source/core/platform/mac/ThemeMac.mm
+++ b/Source/core/platform/mac/ThemeMac.mm
@@ -29,7 +29,7 @@
 #import <Carbon/Carbon.h>
 #import "core/platform/ScrollView.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
-#import "core/platform/mac/BlockExceptions.h"
+#import "platform/mac/BlockExceptions.h"
 #import "core/platform/mac/LocalCurrentGraphicsContext.h"
 #import "core/platform/mac/WebCoreNSCellExtras.h"
 #include "wtf/StdLibExtras.h"
diff --git a/Source/core/platform/mac/WebFontCache.h b/Source/core/platform/mac/WebFontCache.h
deleted file mode 100644
index 822c1b5..0000000
--- a/Source/core/platform/mac/WebFontCache.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc.  All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
- *
- * 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.
- */
-
-#import <AppKit/NSFontManager.h>
-#import <wtf/Vector.h>
-
-// This interface exists so that third party products (like Silk) can patch in to an Obj-C method to manipulate WebKit's font caching/substitution.
-@interface WebFontCache : NSObject
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits weight:(int)desiredWeight size:(float)size;
-+ (void)getTraits:(Vector<unsigned>&)traitsMasks inFamily:(NSString *)desiredFamily;
-
-// This older version of the interface is relied upon by some clients. WebCore doesn't use it.
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size;
-@end
diff --git a/Source/core/platform/mac/WebFontCache.mm b/Source/core/platform/mac/WebFontCache.mm
deleted file mode 100644
index bfcab60..0000000
--- a/Source/core/platform/mac/WebFontCache.mm
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
- *
- * 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. 
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 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.
- */
-
-#import "config.h"
-#import "core/platform/mac/WebFontCache.h"
-
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-#import <math.h>
-#import "platform/fonts/FontTraitsMask.h"
-#import <wtf/UnusedParam.h>
-
-using namespace WebCore;
-
-
-#define SYNTHESIZED_FONT_TRAITS (NSBoldFontMask | NSItalicFontMask)
-
-#define IMPORTANT_FONT_TRAITS (0 \
-    | NSCompressedFontMask \
-    | NSCondensedFontMask \
-    | NSExpandedFontMask \
-    | NSItalicFontMask \
-    | NSNarrowFontMask \
-    | NSPosterFontMask \
-    | NSSmallCapsFontMask \
-)
-
-static BOOL acceptableChoice(NSFontTraitMask desiredTraits, NSFontTraitMask candidateTraits)
-{
-    desiredTraits &= ~SYNTHESIZED_FONT_TRAITS;
-    return (candidateTraits & desiredTraits) == desiredTraits;
-}
-
-static BOOL betterChoice(NSFontTraitMask desiredTraits, int desiredWeight,
-    NSFontTraitMask chosenTraits, int chosenWeight,
-    NSFontTraitMask candidateTraits, int candidateWeight)
-{
-    if (!acceptableChoice(desiredTraits, candidateTraits))
-        return NO;
-
-    // A list of the traits we care about.
-    // The top item in the list is the worst trait to mismatch; if a font has this
-    // and we didn't ask for it, we'd prefer any other font in the family.
-    const NSFontTraitMask masks[] = {
-        NSPosterFontMask,
-        NSSmallCapsFontMask,
-        NSItalicFontMask,
-        NSCompressedFontMask,
-        NSCondensedFontMask,
-        NSExpandedFontMask,
-        NSNarrowFontMask,
-        0
-    };
-
-    int i = 0;
-    NSFontTraitMask mask;
-    while ((mask = masks[i++])) {
-        BOOL desired = (desiredTraits & mask) != 0;
-        BOOL chosenHasUnwantedTrait = desired != ((chosenTraits & mask) != 0);
-        BOOL candidateHasUnwantedTrait = desired != ((candidateTraits & mask) != 0);
-        if (!candidateHasUnwantedTrait && chosenHasUnwantedTrait)
-            return YES;
-        if (!chosenHasUnwantedTrait && candidateHasUnwantedTrait)
-            return NO;
-    }
-
-    int chosenWeightDeltaMagnitude = abs(chosenWeight - desiredWeight);
-    int candidateWeightDeltaMagnitude = abs(candidateWeight - desiredWeight);
-
-    // If both are the same distance from the desired weight, prefer the candidate if it is further from medium.
-    if (chosenWeightDeltaMagnitude == candidateWeightDeltaMagnitude)
-        return abs(candidateWeight - 6) > abs(chosenWeight - 6);
-
-    // Otherwise, prefer the one closer to the desired weight.
-    return candidateWeightDeltaMagnitude < chosenWeightDeltaMagnitude;
-}
-
-static inline FontTraitsMask toTraitsMask(NSFontTraitMask appKitTraits, NSInteger appKitWeight)
-{
-    return static_cast<FontTraitsMask>(((appKitTraits & NSFontItalicTrait) ? FontStyleItalicMask : FontStyleNormalMask)
-        | FontVariantNormalMask
-        | (appKitWeight == 1 ? FontWeight100Mask :
-              appKitWeight == 2 ? FontWeight200Mask :
-              appKitWeight <= 4 ? FontWeight300Mask :
-              appKitWeight == 5 ? FontWeight400Mask :
-              appKitWeight == 6 ? FontWeight500Mask :
-              appKitWeight <= 8 ? FontWeight600Mask :
-              appKitWeight == 9 ? FontWeight700Mask :
-              appKitWeight <= 11 ? FontWeight800Mask :
-                                   FontWeight900Mask));
-}
-
-@implementation WebFontCache
-
-+ (void)getTraits:(Vector<unsigned>&)traitsMasks inFamily:(NSString *)desiredFamily
-{
-    NSFontManager *fontManager = [NSFontManager sharedFontManager];
-
-    NSEnumerator *e = [[fontManager availableFontFamilies] objectEnumerator];
-    NSString *availableFamily;
-    while ((availableFamily = [e nextObject])) {
-        if ([desiredFamily caseInsensitiveCompare:availableFamily] == NSOrderedSame)
-            break;
-    }
-
-    if (!availableFamily) {
-        // Match by PostScript name.
-        NSEnumerator *availableFonts = [[fontManager availableFonts] objectEnumerator];
-        NSString *availableFont;
-        while ((availableFont = [availableFonts nextObject])) {
-            if ([desiredFamily caseInsensitiveCompare:availableFont] == NSOrderedSame) {
-                NSFont *font = [NSFont fontWithName:availableFont size:10];
-                NSInteger weight = [fontManager weightOfFont:font];
-                traitsMasks.append(toTraitsMask([fontManager traitsOfFont:font], weight));
-                break;
-            }
-        }
-        return;
-    }
-
-    NSArray *fonts = [fontManager availableMembersOfFontFamily:availableFamily];    
-    unsigned n = [fonts count];
-    unsigned i;
-    for (i = 0; i < n; i++) {
-        NSArray *fontInfo = [fonts objectAtIndex:i];
-        // Array indices must be hard coded because of lame AppKit API.
-        NSInteger fontWeight = [[fontInfo objectAtIndex:2] intValue];
-
-        NSFontTraitMask fontTraits = [[fontInfo objectAtIndex:3] unsignedIntValue];
-        traitsMasks.append(toTraitsMask(fontTraits, fontWeight));
-    }
-}
-
-// Family name is somewhat of a misnomer here.  We first attempt to find an exact match
-// comparing the desiredFamily to the PostScript name of the installed fonts.  If that fails
-// we then do a search based on the family names of the installed fonts.
-+ (NSFont *)internalFontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits weight:(int)desiredWeight size:(float)size
-{
-    NSFontManager *fontManager = [NSFontManager sharedFontManager];
-
-    // Do a simple case insensitive search for a matching font family.
-    // NSFontManager requires exact name matches.
-    // This addresses the problem of matching arial to Arial, etc., but perhaps not all the issues.
-    NSEnumerator *e = [[fontManager availableFontFamilies] objectEnumerator];
-    NSString *availableFamily;
-    while ((availableFamily = [e nextObject])) {
-        if ([desiredFamily caseInsensitiveCompare:availableFamily] == NSOrderedSame)
-            break;
-    }
-
-    if (!availableFamily) {
-        // Match by PostScript name.
-        NSEnumerator *availableFonts = [[fontManager availableFonts] objectEnumerator];
-        NSString *availableFont;
-        NSFont *nameMatchedFont = nil;
-        NSFontTraitMask desiredTraitsForNameMatch = desiredTraits | (desiredWeight >= 7 ? NSBoldFontMask : 0);
-        while ((availableFont = [availableFonts nextObject])) {
-            if ([desiredFamily caseInsensitiveCompare:availableFont] == NSOrderedSame) {
-                nameMatchedFont = [NSFont fontWithName:availableFont size:size];
-
-                // Special case Osaka-Mono.  According to <rdar://problem/3999467>, we need to 
-                // treat Osaka-Mono as fixed pitch.
-                if ([desiredFamily caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame && desiredTraitsForNameMatch == 0)
-                    return nameMatchedFont;
-
-                NSFontTraitMask traits = [fontManager traitsOfFont:nameMatchedFont];
-                if ((traits & desiredTraitsForNameMatch) == desiredTraitsForNameMatch)
-                    return [fontManager convertFont:nameMatchedFont toHaveTrait:desiredTraitsForNameMatch];
-
-                availableFamily = [nameMatchedFont familyName];
-                break;
-            }
-        }
-    }
-
-    // Found a family, now figure out what weight and traits to use.
-    BOOL choseFont = false;
-    int chosenWeight = 0;
-    NSFontTraitMask chosenTraits = 0;
-    NSString *chosenFullName = 0;
-
-    NSArray *fonts = [fontManager availableMembersOfFontFamily:availableFamily];    
-    unsigned n = [fonts count];
-    unsigned i;
-    for (i = 0; i < n; i++) {
-        NSArray *fontInfo = [fonts objectAtIndex:i];
-
-        // Array indices must be hard coded because of lame AppKit API.
-        NSString *fontFullName = [fontInfo objectAtIndex:0];
-        NSInteger fontWeight = [[fontInfo objectAtIndex:2] intValue];
-
-        NSFontTraitMask fontTraits = [[fontInfo objectAtIndex:3] unsignedIntValue];
-
-        BOOL newWinner;
-        if (!choseFont)
-            newWinner = acceptableChoice(desiredTraits, fontTraits);
-        else
-            newWinner = betterChoice(desiredTraits, desiredWeight, chosenTraits, chosenWeight, fontTraits, fontWeight);
-
-        if (newWinner) {
-            choseFont = YES;
-            chosenWeight = fontWeight;
-            chosenTraits = fontTraits;
-            chosenFullName = fontFullName;
-
-            if (chosenWeight == desiredWeight && (chosenTraits & IMPORTANT_FONT_TRAITS) == (desiredTraits & IMPORTANT_FONT_TRAITS))
-                break;
-        }
-    }
-
-    if (!choseFont)
-        return nil;
-
-    NSFont *font = [NSFont fontWithName:chosenFullName size:size];
-
-    if (!font)
-        return nil;
-
-    NSFontTraitMask actualTraits = 0;
-    if (desiredTraits & NSFontItalicTrait)
-        actualTraits = [fontManager traitsOfFont:font];
-    int actualWeight = [fontManager weightOfFont:font];
-
-    bool syntheticBold = desiredWeight >= 7 && actualWeight < 7;
-    bool syntheticOblique = (desiredTraits & NSFontItalicTrait) && !(actualTraits & NSFontItalicTrait);
-
-    // There are some malformed fonts that will be correctly returned by -fontWithFamily:traits:weight:size: as a match for a particular trait,
-    // though -[NSFontManager traitsOfFont:] incorrectly claims the font does not have the specified trait. This could result in applying 
-    // synthetic bold on top of an already-bold font, as reported in <http://bugs.webkit.org/show_bug.cgi?id=6146>. To work around this
-    // problem, if we got an apparent exact match, but the requested traits aren't present in the matched font, we'll try to get a font from 
-    // the same family without those traits (to apply the synthetic traits to later).
-    NSFontTraitMask nonSyntheticTraits = desiredTraits;
-
-    if (syntheticBold)
-        nonSyntheticTraits &= ~NSBoldFontMask;
-
-    if (syntheticOblique)
-        nonSyntheticTraits &= ~NSItalicFontMask;
-
-    if (nonSyntheticTraits != desiredTraits) {
-        NSFont *fontWithoutSyntheticTraits = [fontManager fontWithFamily:availableFamily traits:nonSyntheticTraits weight:chosenWeight size:size];
-        if (fontWithoutSyntheticTraits)
-            font = fontWithoutSyntheticTraits;
-    }
-
-    return font;
-}
-
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits weight:(int)desiredWeight size:(float)size
-{
-    NSFont *font = [self internalFontWithFamily:desiredFamily traits:desiredTraits weight:desiredWeight size:size];
-    if (font)
-        return font;
-
-    // Auto activate the font before looking for it a second time.
-    // Ignore the result because we want to use our own algorithm to actually find the font.
-    [NSFont fontWithName:desiredFamily size:size];
-
-    return [self internalFontWithFamily:desiredFamily traits:desiredTraits weight:desiredWeight size:size];
-}
-
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size
-{
-    int desiredWeight = (desiredTraits & NSBoldFontMask) ? 9 : 5;
-    return [self fontWithFamily:desiredFamily traits:desiredTraits weight:desiredWeight size:size];
-}
-
-@end
diff --git a/Source/core/platform/mediastream/MediaConstraints.h b/Source/core/platform/mediastream/MediaConstraints.h
deleted file mode 100644
index cb4d264..0000000
--- a/Source/core/platform/mediastream/MediaConstraints.h
+++ /dev/null
@@ -1,66 +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.
- * 3. 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 MediaConstraints_h
-#define MediaConstraints_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-struct MediaConstraint {
-    MediaConstraint(String name, String value)
-        : m_name(name)
-        , m_value(value)
-    {
-    }
-
-    String m_name;
-    String m_value;
-};
-
-class MediaConstraints : public RefCounted<MediaConstraints> {
-public:
-    virtual ~MediaConstraints() { }
-
-    virtual void getMandatoryConstraints(Vector<MediaConstraint>&) const = 0;
-    virtual void getOptionalConstraints(Vector<MediaConstraint>&) const = 0;
-
-    virtual bool getMandatoryConstraintValue(const String& name, String& value) const = 0;
-    virtual bool getOptionalConstraintValue(const String& name, String& value) const = 0;
-
-protected:
-    MediaConstraints() { }
-};
-
-} // namespace WebCore
-
-#endif // MediaConstraints_h
diff --git a/Source/core/platform/mediastream/MediaStreamCenter.cpp b/Source/core/platform/mediastream/MediaStreamCenter.cpp
index c626977..3baadb4 100644
--- a/Source/core/platform/mediastream/MediaStreamCenter.cpp
+++ b/Source/core/platform/mediastream/MediaStreamCenter.cpp
@@ -53,7 +53,7 @@
 }
 
 MediaStreamCenter::MediaStreamCenter()
-    : m_private(adoptPtr(WebKit::Platform::current()->createMediaStreamCenter(this)))
+    : m_private(adoptPtr(blink::Platform::current()->createMediaStreamCenter(this)))
 {
 }
 
@@ -69,10 +69,13 @@
 void MediaStreamCenter::didSetMediaStreamTrackEnabled(MediaStreamDescriptor* stream,  MediaStreamComponent* component)
 {
     if (m_private) {
-        if (component->enabled())
+        if (component->enabled()) {
             m_private->didEnableMediaStreamTrack(stream, component);
-        else
+            m_private->didEnableMediaStreamTrack(component);
+        } else {
             m_private->didDisableMediaStreamTrack(stream, component);
+            m_private->didDisableMediaStreamTrack(component);
+        }
     }
 }
 
@@ -100,12 +103,18 @@
 void MediaStreamCenter::didCreateMediaStream(MediaStreamDescriptor* stream)
 {
     if (m_private) {
-        WebKit::WebMediaStream webStream(stream);
+        blink::WebMediaStream webStream(stream);
         m_private->didCreateMediaStream(webStream);
     }
 }
 
-void MediaStreamCenter::stopLocalMediaStream(const WebKit::WebMediaStream& webStream)
+void MediaStreamCenter::didCreateMediaStreamTrack(MediaStreamComponent* track)
+{
+    if (m_private)
+        m_private->didCreateMediaStreamTrack(track);
+}
+
+void MediaStreamCenter::stopLocalMediaStream(const blink::WebMediaStream& webStream)
 {
     MediaStreamDescriptor* stream = webStream;
     MediaStreamDescriptorClient* client = stream->client();
diff --git a/Source/core/platform/mediastream/MediaStreamCenter.h b/Source/core/platform/mediastream/MediaStreamCenter.h
index 28ee46a..ba3c9c4 100644
--- a/Source/core/platform/mediastream/MediaStreamCenter.h
+++ b/Source/core/platform/mediastream/MediaStreamCenter.h
@@ -39,7 +39,7 @@
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/WTFString.h"
 
-namespace WebKit {
+namespace blink {
 class WebMediaStream;
 class WebMediaStreamCenter;
 class WebMediaStreamTrack;
@@ -51,27 +51,30 @@
 class MediaStreamDescriptor;
 class MediaStreamTrackSourcesRequest;
 
-class MediaStreamCenter : public WebKit::WebMediaStreamCenterClient {
+class MediaStreamCenter : public blink::WebMediaStreamCenterClient {
 public:
     ~MediaStreamCenter();
 
     static MediaStreamCenter& instance();
 
     bool getMediaStreamTrackSources(PassRefPtr<MediaStreamTrackSourcesRequest>);
+
+    void didCreateMediaStreamTrack(MediaStreamComponent*);
     void didSetMediaStreamTrackEnabled(MediaStreamDescriptor*, MediaStreamComponent*);
+    bool didStopMediaStreamTrack(MediaStreamComponent*);
+
+    void didCreateMediaStream(MediaStreamDescriptor*);
     bool didAddMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
     bool didRemoveMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
     void didStopLocalMediaStream(MediaStreamDescriptor*);
-    bool didStopMediaStreamTrack(MediaStreamComponent*);
-    void didCreateMediaStream(MediaStreamDescriptor*);
 
-    // WebKit::WebMediaStreamCenterClient
-    virtual void stopLocalMediaStream(const WebKit::WebMediaStream&) OVERRIDE;
+    // blink::WebMediaStreamCenterClient
+    virtual void stopLocalMediaStream(const blink::WebMediaStream&) OVERRIDE;
 
 private:
     MediaStreamCenter();
 
-    OwnPtr<WebKit::WebMediaStreamCenter> m_private;
+    OwnPtr<blink::WebMediaStreamCenter> m_private;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/mediastream/MediaStreamComponent.cpp b/Source/core/platform/mediastream/MediaStreamComponent.cpp
deleted file mode 100644
index 60a7a85..0000000
--- a/Source/core/platform/mediastream/MediaStreamComponent.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. 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
- * 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/mediastream/MediaStreamComponent.h"
-
-#include "platform/audio/AudioBus.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
-#include "platform/UUID.h"
-#include "public/platform/WebAudioSourceProvider.h"
-
-namespace WebCore {
-
-PassRefPtr<MediaStreamComponent> MediaStreamComponent::create(PassRefPtr<MediaStreamSource> source)
-{
-    return adoptRef(new MediaStreamComponent(createCanonicalUUIDString(), 0, source));
-}
-
-PassRefPtr<MediaStreamComponent> MediaStreamComponent::create(const String& id, PassRefPtr<MediaStreamSource> source)
-{
-    return adoptRef(new MediaStreamComponent(id, 0, source));
-}
-
-PassRefPtr<MediaStreamComponent> MediaStreamComponent::create(MediaStreamDescriptor* stream, PassRefPtr<MediaStreamSource> source)
-{
-    return adoptRef(new MediaStreamComponent(createCanonicalUUIDString(), stream, source));
-}
-
-MediaStreamComponent::MediaStreamComponent(const String& id, MediaStreamDescriptor* stream, PassRefPtr<MediaStreamSource> source)
-    : m_stream(stream)
-    , m_source(source)
-    , m_id(id)
-    , m_enabled(true)
-{
-    ASSERT(m_id.length());
-}
-
-#if ENABLE(WEB_AUDIO)
-void MediaStreamComponent::AudioSourceProviderImpl::wrap(WebKit::WebAudioSourceProvider* provider)
-{
-    MutexLocker locker(m_provideInputLock);
-    m_webAudioSourceProvider = provider;
-}
-
-void MediaStreamComponent::AudioSourceProviderImpl::provideInput(AudioBus* bus, size_t framesToProcess)
-{
-    ASSERT(bus);
-    if (!bus)
-        return;
-
-    MutexTryLocker tryLocker(m_provideInputLock);
-    if (!tryLocker.locked() || !m_webAudioSourceProvider) {
-        bus->zero();
-        return;
-    }
-
-    // Wrap the AudioBus channel data using WebVector.
-    size_t n = bus->numberOfChannels();
-    WebKit::WebVector<float*> webAudioData(n);
-    for (size_t i = 0; i < n; ++i)
-        webAudioData[i] = bus->channel(i)->mutableData();
-
-    m_webAudioSourceProvider->provideInput(webAudioData, framesToProcess);
-}
-#endif // #if ENABLE(WEB_AUDIO)
-
-} // namespace WebCore
-
diff --git a/Source/core/platform/mediastream/MediaStreamComponent.h b/Source/core/platform/mediastream/MediaStreamComponent.h
deleted file mode 100644
index b0cbd9c..0000000
--- a/Source/core/platform/mediastream/MediaStreamComponent.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. 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 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.
- * 3. Neither the name of Ericsson 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 MediaStreamComponent_h
-#define MediaStreamComponent_h
-
-#include "platform/audio/AudioSourceProvider.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-class WebAudioSourceProvider;
-}
-
-namespace WebCore {
-
-class MediaStreamDescriptor;
-class MediaStreamSource;
-
-class MediaStreamComponent : public RefCounted<MediaStreamComponent> {
-public:
-    class ExtraData : public RefCounted<ExtraData> {
-    public:
-        virtual ~ExtraData() { }
-    };
-
-    static PassRefPtr<MediaStreamComponent> create(PassRefPtr<MediaStreamSource>);
-    static PassRefPtr<MediaStreamComponent> create(const String& id, PassRefPtr<MediaStreamSource>);
-    static PassRefPtr<MediaStreamComponent> create(MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);
-
-    MediaStreamDescriptor* stream() const { return m_stream; }
-    void setStream(MediaStreamDescriptor* stream) { m_stream = stream; }
-
-    MediaStreamSource* source() const { return m_source.get(); }
-
-    String id() const { return m_id; }
-    bool enabled() const { return m_enabled; }
-    void setEnabled(bool enabled) { m_enabled = enabled; }
-
-#if ENABLE(WEB_AUDIO)
-    AudioSourceProvider* audioSourceProvider() { return &m_sourceProvider; }
-    void setSourceProvider(WebKit::WebAudioSourceProvider* provider) { m_sourceProvider.wrap(provider); }
-#endif // ENABLE(WEB_AUDIO)
-
-    ExtraData* extraData() const { return m_extraData.get(); }
-    void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
-private:
-    MediaStreamComponent(const String& id, MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);
-
-#if ENABLE(WEB_AUDIO)
-    // AudioSourceProviderImpl wraps a WebAudioSourceProvider::provideInput()
-    // calls into chromium to get a rendered audio stream.
-
-    class AudioSourceProviderImpl : public AudioSourceProvider {
-    public:
-        AudioSourceProviderImpl()
-            : m_webAudioSourceProvider(0)
-        {
-        }
-
-        virtual ~AudioSourceProviderImpl() { }
-
-        // Wraps the given WebKit::WebAudioSourceProvider to WebCore::AudioSourceProvider.
-        void wrap(WebKit::WebAudioSourceProvider*);
-
-        // WebCore::AudioSourceProvider
-        virtual void provideInput(WebCore::AudioBus*, size_t framesToProcess);
-
-    private:
-        WebKit::WebAudioSourceProvider* m_webAudioSourceProvider;
-        Mutex m_provideInputLock;
-    };
-
-    AudioSourceProviderImpl m_sourceProvider;
-#endif // ENABLE(WEB_AUDIO)
-
-    MediaStreamDescriptor* m_stream;
-    RefPtr<MediaStreamSource> m_source;
-    String m_id;
-    bool m_enabled;
-    RefPtr<ExtraData> m_extraData;
-};
-
-typedef Vector<RefPtr<MediaStreamComponent> > MediaStreamComponentVector;
-
-} // namespace WebCore
-
-#endif // MediaStreamComponent_h
diff --git a/Source/core/platform/mediastream/MediaStreamDescriptor.cpp b/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
index 90f9ff5..50d3163 100644
--- a/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
+++ b/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
@@ -33,9 +33,9 @@
 
 #include "core/platform/mediastream/MediaStreamDescriptor.h"
 
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
 #include "platform/UUID.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/MediaStreamSource.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
diff --git a/Source/core/platform/mediastream/MediaStreamDescriptor.h b/Source/core/platform/mediastream/MediaStreamDescriptor.h
index b9bcf4f..383602b 100644
--- a/Source/core/platform/mediastream/MediaStreamDescriptor.h
+++ b/Source/core/platform/mediastream/MediaStreamDescriptor.h
@@ -32,8 +32,8 @@
 #ifndef MediaStreamDescriptor_h
 #define MediaStreamDescriptor_h
 
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/MediaStreamSource.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
diff --git a/Source/core/platform/mediastream/MediaStreamSource.cpp b/Source/core/platform/mediastream/MediaStreamSource.cpp
deleted file mode 100644
index ea2e034..0000000
--- a/Source/core/platform/mediastream/MediaStreamSource.cpp
+++ /dev/null
@@ -1,108 +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.
- * 3. 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/mediastream/MediaStreamSource.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-PassRefPtr<MediaStreamSource> MediaStreamSource::create(const String& id, Type type, const String& name, ReadyState readyState, bool requiresConsumer)
-{
-    return adoptRef(new MediaStreamSource(id, type, name, readyState, requiresConsumer));
-}
-
-MediaStreamSource::MediaStreamSource(const String& id, Type type, const String& name, ReadyState readyState, bool requiresConsumer)
-    : m_id(id)
-    , m_type(type)
-    , m_name(name)
-    , m_readyState(readyState)
-    , m_requiresConsumer(requiresConsumer)
-{
-}
-
-void MediaStreamSource::setReadyState(ReadyState readyState)
-{
-    if (m_readyState != ReadyStateEnded && m_readyState != readyState) {
-        m_readyState = readyState;
-        for (Vector<Observer*>::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
-            (*i)->sourceChangedState();
-    }
-}
-
-void MediaStreamSource::addObserver(MediaStreamSource::Observer* observer)
-{
-    m_observers.append(observer);
-}
-
-void MediaStreamSource::removeObserver(MediaStreamSource::Observer* observer)
-{
-    size_t pos = m_observers.find(observer);
-    if (pos != kNotFound)
-        m_observers.remove(pos);
-}
-
-void MediaStreamSource::addAudioConsumer(PassRefPtr<AudioDestinationConsumer> consumer)
-{
-    ASSERT(m_requiresConsumer);
-    MutexLocker locker(m_audioConsumersLock);
-    m_audioConsumers.append(consumer);
-}
-
-bool MediaStreamSource::removeAudioConsumer(AudioDestinationConsumer* consumer)
-{
-    ASSERT(m_requiresConsumer);
-    MutexLocker locker(m_audioConsumersLock);
-    size_t pos = m_audioConsumers.find(consumer);
-    if (pos != kNotFound) {
-        m_audioConsumers.remove(pos);
-        return true;
-    }
-    return false;
-}
-
-void MediaStreamSource::setAudioFormat(size_t numberOfChannels, float sampleRate)
-{
-    ASSERT(m_requiresConsumer);
-    MutexLocker locker(m_audioConsumersLock);
-    for (Vector<RefPtr<AudioDestinationConsumer> >::iterator it = m_audioConsumers.begin(); it != m_audioConsumers.end(); ++it)
-        (*it)->setFormat(numberOfChannels, sampleRate);
-}
-
-void MediaStreamSource::consumeAudio(AudioBus* bus, size_t numberOfFrames)
-{
-    ASSERT(m_requiresConsumer);
-    MutexLocker locker(m_audioConsumersLock);
-    for (Vector<RefPtr<AudioDestinationConsumer> >::iterator it = m_audioConsumers.begin(); it != m_audioConsumers.end(); ++it)
-        (*it)->consumeAudio(bus, numberOfFrames);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/mediastream/MediaStreamSource.h b/Source/core/platform/mediastream/MediaStreamSource.h
deleted file mode 100644
index 11989f7..0000000
--- a/Source/core/platform/mediastream/MediaStreamSource.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * 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.
- * 3. Neither the name of Ericsson 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 MediaStreamSource_h
-#define MediaStreamSource_h
-
-#include "platform/audio/AudioDestinationConsumer.h"
-#include "core/platform/mediastream/MediaConstraints.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class MediaStreamSource : public RefCounted<MediaStreamSource> {
-public:
-    class Observer {
-    public:
-        virtual ~Observer() { }
-        virtual void sourceChangedState() = 0;
-    };
-
-    class ExtraData {
-    public:
-        virtual ~ExtraData() { }
-    };
-
-    enum Type {
-        TypeAudio,
-        TypeVideo
-    };
-
-    enum ReadyState {
-        ReadyStateLive = 0,
-        ReadyStateMuted = 1,
-        ReadyStateEnded = 2
-    };
-
-    static PassRefPtr<MediaStreamSource> create(const String& id, Type, const String& name, ReadyState = ReadyStateLive, bool requiresConsumer = false);
-
-    const String& id() const { return m_id; }
-    Type type() const { return m_type; }
-    const String& name() const { return m_name; }
-
-    void setReadyState(ReadyState);
-    ReadyState readyState() const { return m_readyState; }
-
-    void addObserver(Observer*);
-    void removeObserver(Observer*);
-
-    ExtraData* extraData() const { return m_extraData.get(); }
-    void setExtraData(ExtraData* extraData) { m_extraData = adoptPtr(extraData); }
-
-    void setConstraints(PassRefPtr<MediaConstraints> constraints) { m_constraints = constraints; }
-    MediaConstraints* constraints() { return m_constraints.get(); }
-
-    const String& deviceId() { return m_deviceId; }
-    void setDeviceId(const String& deviceId) { m_deviceId = deviceId; }
-
-    void setAudioFormat(size_t numberOfChannels, float sampleRate);
-    void consumeAudio(AudioBus*, size_t numberOfFrames);
-
-    bool requiresAudioConsumer() const { return m_requiresConsumer; }
-    void addAudioConsumer(PassRefPtr<AudioDestinationConsumer>);
-    bool removeAudioConsumer(AudioDestinationConsumer*);
-    const Vector<RefPtr<AudioDestinationConsumer> >& audioConsumers() { return m_audioConsumers; }
-
-private:
-    MediaStreamSource(const String& id, Type, const String& name, ReadyState, bool requiresConsumer);
-
-    String m_id;
-    Type m_type;
-    String m_name;
-    ReadyState m_readyState;
-    String m_deviceId;
-    bool m_requiresConsumer;
-    Vector<Observer*> m_observers;
-    Mutex m_audioConsumersLock;
-    Vector<RefPtr<AudioDestinationConsumer> > m_audioConsumers;
-    OwnPtr<ExtraData> m_extraData;
-    RefPtr<MediaConstraints> m_constraints;
-};
-
-typedef Vector<RefPtr<MediaStreamSource> > MediaStreamSourceVector;
-
-} // namespace WebCore
-
-#endif // MediaStreamSource_h
diff --git a/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp b/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp
deleted file mode 100644
index ca3d5bc..0000000
--- a/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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:
- * 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 GOOGLE 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 GOOGLE 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/mediastream/RTCDTMFSenderHandler.h"
-
-#include "core/platform/mediastream/RTCDTMFSenderHandlerClient.h"
-#include "public/platform/WebRTCDTMFSenderHandler.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebKit;
-
-namespace WebCore {
-
-PassOwnPtr<RTCDTMFSenderHandler> RTCDTMFSenderHandler::create(WebRTCDTMFSenderHandler* webHandler)
-{
-    return adoptPtr(new RTCDTMFSenderHandler(webHandler));
-}
-
-RTCDTMFSenderHandler::RTCDTMFSenderHandler(WebRTCDTMFSenderHandler* webHandler)
-    : m_webHandler(adoptPtr(webHandler))
-    , m_client(0)
-{
-}
-
-RTCDTMFSenderHandler::~RTCDTMFSenderHandler()
-{
-}
-
-void RTCDTMFSenderHandler::setClient(RTCDTMFSenderHandlerClient* client)
-{
-    m_client = client;
-    m_webHandler->setClient(m_client ? this : 0);
-}
-
-String RTCDTMFSenderHandler::currentToneBuffer()
-{
-    return m_webHandler->currentToneBuffer();
-}
-
-bool RTCDTMFSenderHandler::canInsertDTMF()
-{
-    return m_webHandler->canInsertDTMF();
-}
-
-bool RTCDTMFSenderHandler::insertDTMF(const String& tones, long duration, long interToneGap)
-{
-    return m_webHandler->insertDTMF(tones, duration, interToneGap);
-}
-
-void RTCDTMFSenderHandler::didPlayTone(const WebString& tone) const
-{
-    if (m_client)
-        m_client->didPlayTone(tone);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/mediastream/RTCDTMFSenderHandler.h b/Source/core/platform/mediastream/RTCDTMFSenderHandler.h
deleted file mode 100644
index f9ef7fb..0000000
--- a/Source/core/platform/mediastream/RTCDTMFSenderHandler.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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:
- * 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 GOOGLE 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 GOOGLE 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 RTCDTMFSenderHandler_h
-#define RTCDTMFSenderHandler_h
-
-#include "core/platform/mediastream/RTCDTMFSenderHandler.h"
-#include "core/platform/mediastream/RTCDTMFSenderHandlerClient.h"
-#include "public/platform/WebRTCDTMFSenderHandler.h"
-#include "public/platform/WebRTCDTMFSenderHandlerClient.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class RTCDTMFSenderHandlerClient;
-
-class RTCDTMFSenderHandler : public WebKit::WebRTCDTMFSenderHandlerClient {
-public:
-    static PassOwnPtr<RTCDTMFSenderHandler> create(WebKit::WebRTCDTMFSenderHandler*);
-    virtual ~RTCDTMFSenderHandler();
-
-    void setClient(RTCDTMFSenderHandlerClient*);
-
-    String currentToneBuffer();
-
-    bool canInsertDTMF();
-    bool insertDTMF(const String& tones, long duration, long interToneGap);
-
-    // WebKit::WebRTCDTMFSenderHandlerClient implementation.
-    virtual void didPlayTone(const WebKit::WebString& tone) const OVERRIDE;
-
-private:
-    explicit RTCDTMFSenderHandler(WebKit::WebRTCDTMFSenderHandler*);
-
-    OwnPtr<WebKit::WebRTCDTMFSenderHandler> m_webHandler;
-    RTCDTMFSenderHandlerClient* m_client;
-};
-
-} // namespace WebCore
-
-#endif // RTCDTMFSenderHandler_h
diff --git a/Source/core/platform/mediastream/RTCDTMFSenderHandlerClient.h b/Source/core/platform/mediastream/RTCDTMFSenderHandlerClient.h
deleted file mode 100644
index 3a3f18b..0000000
--- a/Source/core/platform/mediastream/RTCDTMFSenderHandlerClient.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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:
- * 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 GOOGLE 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 GOOGLE 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 RTCDTMFSenderHandlerClient_h
-#define RTCDTMFSenderHandlerClient_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCDTMFSenderHandlerClient {
-public:
-    virtual ~RTCDTMFSenderHandlerClient() { }
-
-    virtual void didPlayTone(const String&) = 0;
-};
-
-} // namespace WebCore
-
-#endif // RTCDTMFSenderHandlerClient_h
diff --git a/Source/core/platform/mediastream/RTCDataChannelHandler.cpp b/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
index cd3d749..b317931 100644
--- a/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
+++ b/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
@@ -32,12 +32,12 @@
 
 namespace WebCore {
 
-PassOwnPtr<RTCDataChannelHandler> RTCDataChannelHandler::create(WebKit::WebRTCDataChannelHandler* webHandler)
+PassOwnPtr<RTCDataChannelHandler> RTCDataChannelHandler::create(blink::WebRTCDataChannelHandler* webHandler)
 {
     return adoptPtr(new RTCDataChannelHandler(webHandler));
 }
 
-RTCDataChannelHandler::RTCDataChannelHandler(WebKit::WebRTCDataChannelHandler* webHandler)
+RTCDataChannelHandler::RTCDataChannelHandler(blink::WebRTCDataChannelHandler* webHandler)
     : m_webHandler(adoptPtr(webHandler))
     , m_client(0)
 {
@@ -119,7 +119,7 @@
         m_client->didChangeReadyState(static_cast<RTCDataChannelHandlerClient::ReadyState>(state));
 }
 
-void RTCDataChannelHandler::didReceiveStringData(const WebKit::WebString& data) const
+void RTCDataChannelHandler::didReceiveStringData(const blink::WebString& data) const
 {
     if (m_client)
         m_client->didReceiveStringData(data);
diff --git a/Source/core/platform/mediastream/RTCDataChannelHandler.h b/Source/core/platform/mediastream/RTCDataChannelHandler.h
index 70a3076..3f2acf3 100644
--- a/Source/core/platform/mediastream/RTCDataChannelHandler.h
+++ b/Source/core/platform/mediastream/RTCDataChannelHandler.h
@@ -36,9 +36,9 @@
 
 class RTCDataChannelHandlerClient;
 
-class RTCDataChannelHandler : public WebKit::WebRTCDataChannelHandlerClient {
+class RTCDataChannelHandler : public blink::WebRTCDataChannelHandlerClient {
 public:
-    static PassOwnPtr<RTCDataChannelHandler> create(WebKit::WebRTCDataChannelHandler*);
+    static PassOwnPtr<RTCDataChannelHandler> create(blink::WebRTCDataChannelHandler*);
     virtual ~RTCDataChannelHandler();
 
     void setClient(RTCDataChannelHandlerClient*);
@@ -60,16 +60,16 @@
     bool sendRawData(const char*, size_t);
     void close();
 
-    // WebKit::WebRTCDataChannelHandlerClient implementation.
+    // blink::WebRTCDataChannelHandlerClient implementation.
     virtual void didChangeReadyState(ReadyState) const OVERRIDE;
-    virtual void didReceiveStringData(const WebKit::WebString&) const OVERRIDE;
+    virtual void didReceiveStringData(const blink::WebString&) const OVERRIDE;
     virtual void didReceiveRawData(const char*, size_t) const OVERRIDE;
     virtual void didDetectError() const OVERRIDE;
 
 private:
-    explicit RTCDataChannelHandler(WebKit::WebRTCDataChannelHandler*);
+    explicit RTCDataChannelHandler(blink::WebRTCDataChannelHandler*);
 
-    OwnPtr<WebKit::WebRTCDataChannelHandler> m_webHandler;
+    OwnPtr<blink::WebRTCDataChannelHandler> m_webHandler;
     RTCDataChannelHandlerClient* m_client;
 };
 
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp b/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
index 794d1f5..37660ac 100644
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
+++ b/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
@@ -32,15 +32,15 @@
 
 #include "core/platform/mediastream/RTCPeerConnectionHandler.h"
 
-#include "core/platform/mediastream/MediaConstraints.h"
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/RTCDTMFSenderHandler.h"
 #include "core/platform/mediastream/RTCDataChannelHandler.h"
 #include "core/platform/mediastream/RTCPeerConnectionHandlerClient.h"
-#include "core/platform/mediastream/RTCSessionDescriptionRequest.h"
 #include "core/platform/mediastream/RTCStatsRequest.h"
-#include "core/platform/mediastream/RTCVoidRequest.h"
+#include "platform/mediastream/MediaConstraints.h"
+#include "platform/mediastream/MediaStreamComponent.h"
 #include "platform/mediastream/RTCConfiguration.h"
+#include "platform/mediastream/RTCDTMFSenderHandler.h"
+#include "platform/mediastream/RTCSessionDescriptionRequest.h"
+#include "platform/mediastream/RTCVoidRequest.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebMediaConstraints.h"
 #include "public/platform/WebMediaStream.h"
@@ -57,7 +57,7 @@
 
 namespace WebCore {
 
-WebKit::WebRTCPeerConnectionHandler* RTCPeerConnectionHandler::toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler* handler)
+blink::WebRTCPeerConnectionHandler* RTCPeerConnectionHandler::toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler* handler)
 {
     return static_cast<RTCPeerConnectionHandler*>(handler)->m_webHandler.get();
 }
@@ -84,7 +84,7 @@
 
 bool RTCPeerConnectionHandler::createWebHandler()
 {
-    m_webHandler = adoptPtr(WebKit::Platform::current()->createRTCPeerConnectionHandler(this));
+    m_webHandler = adoptPtr(blink::Platform::current()->createRTCPeerConnectionHandler(this));
     return m_webHandler;
 }
 
@@ -103,12 +103,12 @@
     m_webHandler->createAnswer(request, constraints);
 }
 
-void RTCPeerConnectionHandler::setLocalDescription(PassRefPtr<RTCVoidRequest> request, WebKit::WebRTCSessionDescription sessionDescription)
+void RTCPeerConnectionHandler::setLocalDescription(PassRefPtr<RTCVoidRequest> request, blink::WebRTCSessionDescription sessionDescription)
 {
     m_webHandler->setLocalDescription(request, sessionDescription);
 }
 
-void RTCPeerConnectionHandler::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, WebKit::WebRTCSessionDescription sessionDescription)
+void RTCPeerConnectionHandler::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, blink::WebRTCSessionDescription sessionDescription)
 {
     m_webHandler->setRemoteDescription(request, sessionDescription);
 }
@@ -118,22 +118,22 @@
     return m_webHandler->updateICE(configuration, constraints);
 }
 
-bool RTCPeerConnectionHandler::addIceCandidate(WebKit::WebRTCICECandidate iceCandidate)
+bool RTCPeerConnectionHandler::addIceCandidate(blink::WebRTCICECandidate iceCandidate)
 {
     return m_webHandler->addICECandidate(iceCandidate);
 }
 
-bool RTCPeerConnectionHandler::addIceCandidate(PassRefPtr<RTCVoidRequest> request, WebKit::WebRTCICECandidate iceCandidate)
+bool RTCPeerConnectionHandler::addIceCandidate(PassRefPtr<RTCVoidRequest> request, blink::WebRTCICECandidate iceCandidate)
 {
     return m_webHandler->addICECandidate(request, iceCandidate);
 }
 
-WebKit::WebRTCSessionDescription RTCPeerConnectionHandler::localDescription()
+blink::WebRTCSessionDescription RTCPeerConnectionHandler::localDescription()
 {
     return m_webHandler->localDescription();
 }
 
-WebKit::WebRTCSessionDescription RTCPeerConnectionHandler::remoteDescription()
+blink::WebRTCSessionDescription RTCPeerConnectionHandler::remoteDescription()
 {
     return m_webHandler->remoteDescription();
 }
@@ -153,9 +153,9 @@
     m_webHandler->getStats(request);
 }
 
-PassOwnPtr<RTCDataChannelHandler> RTCPeerConnectionHandler::createDataChannel(const String& label, const WebKit::WebRTCDataChannelInit& init)
+PassOwnPtr<RTCDataChannelHandler> RTCPeerConnectionHandler::createDataChannel(const String& label, const blink::WebRTCDataChannelInit& init)
 {
-    WebKit::WebRTCDataChannelHandler* webHandler = m_webHandler->createDataChannel(label, init);
+    blink::WebRTCDataChannelHandler* webHandler = m_webHandler->createDataChannel(label, init);
     if (!webHandler)
         return nullptr;
 
@@ -164,7 +164,7 @@
 
 PassOwnPtr<RTCDTMFSenderHandler> RTCPeerConnectionHandler::createDTMFSender(PassRefPtr<MediaStreamComponent> track)
 {
-    WebKit::WebRTCDTMFSenderHandler* webHandler = m_webHandler->createDTMFSender(track);
+    blink::WebRTCDTMFSenderHandler* webHandler = m_webHandler->createDTMFSender(track);
     if (!webHandler)
         return nullptr;
 
@@ -181,37 +181,37 @@
     m_client->negotiationNeeded();
 }
 
-void RTCPeerConnectionHandler::didGenerateICECandidate(const WebKit::WebRTCICECandidate& iceCandidate)
+void RTCPeerConnectionHandler::didGenerateICECandidate(const blink::WebRTCICECandidate& iceCandidate)
 {
     m_client->didGenerateIceCandidate(iceCandidate);
 }
 
-void RTCPeerConnectionHandler::didChangeSignalingState(WebKit::WebRTCPeerConnectionHandlerClient::SignalingState state)
+void RTCPeerConnectionHandler::didChangeSignalingState(blink::WebRTCPeerConnectionHandlerClient::SignalingState state)
 {
     m_client->didChangeSignalingState(static_cast<RTCPeerConnectionHandlerClient::SignalingState>(state));
 }
 
-void RTCPeerConnectionHandler::didChangeICEGatheringState(WebKit::WebRTCPeerConnectionHandlerClient::ICEGatheringState state)
+void RTCPeerConnectionHandler::didChangeICEGatheringState(blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState state)
 {
     m_client->didChangeIceGatheringState(static_cast<RTCPeerConnectionHandlerClient::IceGatheringState>(state));
 }
 
-void RTCPeerConnectionHandler::didChangeICEConnectionState(WebKit::WebRTCPeerConnectionHandlerClient::ICEConnectionState state)
+void RTCPeerConnectionHandler::didChangeICEConnectionState(blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState state)
 {
     m_client->didChangeIceConnectionState(static_cast<RTCPeerConnectionHandlerClient::IceConnectionState>(state));
 }
 
-void RTCPeerConnectionHandler::didAddRemoteStream(const WebKit::WebMediaStream& webMediaStreamDescriptor)
+void RTCPeerConnectionHandler::didAddRemoteStream(const blink::WebMediaStream& webMediaStreamDescriptor)
 {
     m_client->didAddRemoteStream(webMediaStreamDescriptor);
 }
 
-void RTCPeerConnectionHandler::didRemoveRemoteStream(const WebKit::WebMediaStream& webMediaStreamDescriptor)
+void RTCPeerConnectionHandler::didRemoveRemoteStream(const blink::WebMediaStream& webMediaStreamDescriptor)
 {
     m_client->didRemoveRemoteStream(webMediaStreamDescriptor);
 }
 
-void RTCPeerConnectionHandler::didAddRemoteDataChannel(WebKit::WebRTCDataChannelHandler* webHandler)
+void RTCPeerConnectionHandler::didAddRemoteDataChannel(blink::WebRTCDataChannelHandler* webHandler)
 {
     ASSERT(webHandler);
     m_client->didAddRemoteDataChannel(RTCDataChannelHandler::create(webHandler));
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandler.h b/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
index 5b0d689..5565981 100644
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
+++ b/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
@@ -38,7 +38,7 @@
 #include "wtf/OwnPtr.h"
 #include "wtf/PassRefPtr.h"
 
-namespace WebKit {
+namespace blink {
 class WebMediaStream;
 class WebRTCICECandidate;
 class WebRTCSessionDescription;
@@ -57,7 +57,7 @@
 class RTCStatsRequest;
 class RTCVoidRequest;
 
-class RTCPeerConnectionHandler : public WebKit::WebRTCPeerConnectionHandlerClient {
+class RTCPeerConnectionHandler : public blink::WebRTCPeerConnectionHandlerClient {
 public:
     static PassOwnPtr<RTCPeerConnectionHandler> create(RTCPeerConnectionHandlerClient*);
     virtual ~RTCPeerConnectionHandler();
@@ -68,39 +68,39 @@
 
     void createOffer(PassRefPtr<RTCSessionDescriptionRequest>, PassRefPtr<MediaConstraints>);
     void createAnswer(PassRefPtr<RTCSessionDescriptionRequest>, PassRefPtr<MediaConstraints>);
-    void setLocalDescription(PassRefPtr<RTCVoidRequest>, WebKit::WebRTCSessionDescription);
-    void setRemoteDescription(PassRefPtr<RTCVoidRequest>, WebKit::WebRTCSessionDescription);
-    WebKit::WebRTCSessionDescription localDescription();
-    WebKit::WebRTCSessionDescription remoteDescription();
+    void setLocalDescription(PassRefPtr<RTCVoidRequest>, blink::WebRTCSessionDescription);
+    void setRemoteDescription(PassRefPtr<RTCVoidRequest>, blink::WebRTCSessionDescription);
+    blink::WebRTCSessionDescription localDescription();
+    blink::WebRTCSessionDescription remoteDescription();
     bool updateIce(PassRefPtr<RTCConfiguration>, PassRefPtr<MediaConstraints>);
 
     // DEPRECATED
-    bool addIceCandidate(WebKit::WebRTCICECandidate);
+    bool addIceCandidate(blink::WebRTCICECandidate);
 
-    bool addIceCandidate(PassRefPtr<RTCVoidRequest>, WebKit::WebRTCICECandidate);
+    bool addIceCandidate(PassRefPtr<RTCVoidRequest>, blink::WebRTCICECandidate);
     bool addStream(PassRefPtr<MediaStreamDescriptor>, PassRefPtr<MediaConstraints>);
     void removeStream(PassRefPtr<MediaStreamDescriptor>);
     void getStats(PassRefPtr<RTCStatsRequest>);
-    PassOwnPtr<RTCDataChannelHandler> createDataChannel(const String& label, const WebKit::WebRTCDataChannelInit&);
+    PassOwnPtr<RTCDataChannelHandler> createDataChannel(const String& label, const blink::WebRTCDataChannelInit&);
     PassOwnPtr<RTCDTMFSenderHandler> createDTMFSender(PassRefPtr<MediaStreamComponent>);
     void stop();
 
-    // WebKit::WebRTCPeerConnectionHandlerClient implementation.
+    // blink::WebRTCPeerConnectionHandlerClient implementation.
     virtual void negotiationNeeded() OVERRIDE;
-    virtual void didGenerateICECandidate(const WebKit::WebRTCICECandidate&) OVERRIDE;
-    virtual void didChangeSignalingState(WebKit::WebRTCPeerConnectionHandlerClient::SignalingState) OVERRIDE;
-    virtual void didChangeICEGatheringState(WebKit::WebRTCPeerConnectionHandlerClient::ICEGatheringState) OVERRIDE;
-    virtual void didChangeICEConnectionState(WebKit::WebRTCPeerConnectionHandlerClient::ICEConnectionState) OVERRIDE;
-    virtual void didAddRemoteStream(const WebKit::WebMediaStream&) OVERRIDE;
-    virtual void didRemoveRemoteStream(const WebKit::WebMediaStream&) OVERRIDE;
-    virtual void didAddRemoteDataChannel(WebKit::WebRTCDataChannelHandler*) OVERRIDE;
+    virtual void didGenerateICECandidate(const blink::WebRTCICECandidate&) OVERRIDE;
+    virtual void didChangeSignalingState(blink::WebRTCPeerConnectionHandlerClient::SignalingState) OVERRIDE;
+    virtual void didChangeICEGatheringState(blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState) OVERRIDE;
+    virtual void didChangeICEConnectionState(blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState) OVERRIDE;
+    virtual void didAddRemoteStream(const blink::WebMediaStream&) OVERRIDE;
+    virtual void didRemoveRemoteStream(const blink::WebMediaStream&) OVERRIDE;
+    virtual void didAddRemoteDataChannel(blink::WebRTCDataChannelHandler*) OVERRIDE;
 
-    static WebKit::WebRTCPeerConnectionHandler* toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler*);
+    static blink::WebRTCPeerConnectionHandler* toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler*);
 
 private:
     explicit RTCPeerConnectionHandler(RTCPeerConnectionHandlerClient*);
 
-    OwnPtr<WebKit::WebRTCPeerConnectionHandler> m_webHandler;
+    OwnPtr<blink::WebRTCPeerConnectionHandler> m_webHandler;
     RTCPeerConnectionHandlerClient* m_client;
 };
 
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h b/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
index e78e44c..46f276f 100644
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
+++ b/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
@@ -33,7 +33,7 @@
 
 #include "wtf/PassRefPtr.h"
 
-namespace WebKit {
+namespace blink {
 class WebRTCICECandidate;
 }
 
@@ -72,7 +72,7 @@
     virtual ~RTCPeerConnectionHandlerClient() { }
 
     virtual void negotiationNeeded() = 0;
-    virtual void didGenerateIceCandidate(WebKit::WebRTCICECandidate) = 0;
+    virtual void didGenerateIceCandidate(blink::WebRTCICECandidate) = 0;
     virtual void didChangeSignalingState(SignalingState) = 0;
     virtual void didChangeIceGatheringState(IceGatheringState) = 0;
     virtual void didChangeIceConnectionState(IceConnectionState) = 0;
diff --git a/Source/core/platform/mediastream/RTCSessionDescriptionRequest.h b/Source/core/platform/mediastream/RTCSessionDescriptionRequest.h
deleted file mode 100644
index 0c7b7be..0000000
--- a/Source/core/platform/mediastream/RTCSessionDescriptionRequest.h
+++ /dev/null
@@ -1,69 +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.
- * 3. 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 RTCSessionDescriptionRequest_h
-#define RTCSessionDescriptionRequest_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-class WebRTCSessionDescription;
-}
-
-namespace WebCore {
-
-class RTCSessionDescriptionRequest : public RefCounted<RTCSessionDescriptionRequest> {
-public:
-    class ExtraData : public RefCounted<ExtraData> {
-    public:
-        virtual ~ExtraData() { }
-    };
-
-    virtual ~RTCSessionDescriptionRequest() { }
-
-    virtual void requestSucceeded(const WebKit::WebRTCSessionDescription&) = 0;
-    virtual void requestFailed(const String& error) = 0;
-
-    PassRefPtr<ExtraData> extraData() const { return m_extraData; }
-    void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
-protected:
-    RTCSessionDescriptionRequest() { }
-
-private:
-    RefPtr<ExtraData> m_extraData;
-};
-
-} // namespace WebCore
-
-#endif // RTCSessionDescriptionRequest_h
diff --git a/Source/core/platform/mediastream/RTCStatsResponseBase.h b/Source/core/platform/mediastream/RTCStatsResponseBase.h
deleted file mode 100644
index dee70fb..0000000
--- a/Source/core/platform/mediastream/RTCStatsResponseBase.h
+++ /dev/null
@@ -1,45 +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 INC. 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 INC. 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.
- */
-
-#ifndef RTCStatsResponseBase_h
-#define RTCStatsResponseBase_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCStatsResponseBase : public RefCounted<RTCStatsResponseBase> {
-public:
-    virtual ~RTCStatsResponseBase() { }
-
-    virtual size_t addReport(String id, String type, double timestamp) = 0;
-    virtual void addStatistic(size_t report, String name, String value) = 0;
-};
-
-} // namespace WebCore
-
-#endif // RTCStatsResponseBase_h
-
diff --git a/Source/core/platform/mediastream/RTCVoidRequest.h b/Source/core/platform/mediastream/RTCVoidRequest.h
deleted file mode 100644
index fe3b451..0000000
--- a/Source/core/platform/mediastream/RTCVoidRequest.h
+++ /dev/null
@@ -1,65 +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.
- * 3. 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 RTCVoidRequest_h
-#define RTCVoidRequest_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCVoidRequest : public RefCounted<RTCVoidRequest> {
-public:
-    class ExtraData : public RefCounted<ExtraData> {
-    public:
-        virtual ~ExtraData() { }
-    };
-
-    virtual ~RTCVoidRequest() { }
-
-    virtual void requestSucceeded() = 0;
-    virtual void requestFailed(const String& error) = 0;
-
-    PassRefPtr<ExtraData> extraData() const { return m_extraData; }
-    void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
-protected:
-    RTCVoidRequest() { }
-
-private:
-    RefPtr<ExtraData> m_extraData;
-};
-
-} // namespace WebCore
-
-#endif // RTCVoidRequest_h
diff --git a/Source/core/platform/testing/FakeWebGraphicsContext3D.h b/Source/core/platform/testing/FakeWebGraphicsContext3D.h
index bf4c87e..db97f80 100644
--- a/Source/core/platform/testing/FakeWebGraphicsContext3D.h
+++ b/Source/core/platform/testing/FakeWebGraphicsContext3D.h
@@ -29,7 +29,7 @@
 #include "core/platform/graphics/GraphicsContext3D.h"
 #include "public/platform/WebGraphicsContext3D.h"
 
-namespace WebKit {
+namespace blink {
 
 // WebGraphicsContext3D base class for use in WebKit unit tests.
 // All operations are no-ops (returning 0 if necessary).
@@ -289,6 +289,6 @@
     Attributes m_attrs;
 };
 
-} // namespace WebKit
+} // namespace blink
 
 #endif // FakeWebGraphicsContext3D_h
diff --git a/Source/core/plugins/DOMMimeType.cpp b/Source/core/plugins/DOMMimeType.cpp
index 4c8d65e..3e35097 100644
--- a/Source/core/plugins/DOMMimeType.cpp
+++ b/Source/core/plugins/DOMMimeType.cpp
@@ -23,7 +23,6 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "core/plugins/DOMPlugin.h"
-#include "core/plugins/PluginData.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
diff --git a/Source/core/plugins/DOMMimeType.h b/Source/core/plugins/DOMMimeType.h
index 047a635..8670725 100644
--- a/Source/core/plugins/DOMMimeType.h
+++ b/Source/core/plugins/DOMMimeType.h
@@ -22,7 +22,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/frame/FrameDestructionObserver.h"
-#include "core/plugins/PluginData.h"
+#include "platform/plugins/PluginData.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
diff --git a/Source/core/plugins/DOMMimeTypeArray.cpp b/Source/core/plugins/DOMMimeTypeArray.cpp
index 16cf19a..cddfa83 100644
--- a/Source/core/plugins/DOMMimeTypeArray.cpp
+++ b/Source/core/plugins/DOMMimeTypeArray.cpp
@@ -22,7 +22,7 @@
 
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/plugins/PluginData.h"
+#include "platform/plugins/PluginData.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
diff --git a/Source/core/plugins/DOMPlugin.cpp b/Source/core/plugins/DOMPlugin.cpp
index 534e04d..eb4b99c 100644
--- a/Source/core/plugins/DOMPlugin.cpp
+++ b/Source/core/plugins/DOMPlugin.cpp
@@ -19,7 +19,7 @@
 #include "config.h"
 #include "core/plugins/DOMPlugin.h"
 
-#include "core/plugins/PluginData.h"
+#include "platform/plugins/PluginData.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
diff --git a/Source/core/plugins/DOMPluginArray.cpp b/Source/core/plugins/DOMPluginArray.cpp
index 44e9269..7a9d81c 100644
--- a/Source/core/plugins/DOMPluginArray.cpp
+++ b/Source/core/plugins/DOMPluginArray.cpp
@@ -23,7 +23,7 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "core/plugins/DOMPlugin.h"
-#include "core/plugins/PluginData.h"
+#include "platform/plugins/PluginData.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
diff --git a/Source/core/plugins/PluginData.cpp b/Source/core/plugins/PluginData.cpp
deleted file mode 100644
index d941dca..0000000
--- a/Source/core/plugins/PluginData.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
-    Copyright (C) 2000 Harri Porten (porten@kde.org)
-    Copyright (C) 2000 Daniel Molkentin (molkentin@kde.org)
-    Copyright (C) 2000 Stefan Schimanski (schimmi@kde.org)
-    Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All Rights Reserved.
-    Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
-
-    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.
-*/
-
-#include "config.h"
-#include "core/plugins/PluginData.h"
-
-#include "core/plugins/PluginListBuilder.h"
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-class PluginCache {
-public:
-    PluginCache() : m_loaded(false), m_refresh(false) {}
-    ~PluginCache() { reset(false); }
-
-    void reset(bool refresh)
-    {
-        m_plugins.clear();
-        m_loaded = false;
-        m_refresh = refresh;
-    }
-
-    const Vector<PluginInfo>& plugins()
-    {
-        if (!m_loaded) {
-            PluginListBuilder builder(&m_plugins);
-            WebKit::Platform::current()->getPluginList(m_refresh, &builder);
-            m_loaded = true;
-            m_refresh = false;
-        }
-        return m_plugins;
-    }
-
-private:
-    Vector<PluginInfo> m_plugins;
-    bool m_loaded;
-    bool m_refresh;
-};
-
-static PluginCache& pluginCache()
-{
-    DEFINE_STATIC_LOCAL(PluginCache, cache, ());
-    return cache;
-}
-
-PluginData::PluginData(const Page* page)
-{
-    initPlugins(page);
-
-    for (unsigned i = 0; i < m_plugins.size(); ++i) {
-        const PluginInfo& plugin = m_plugins[i];
-        for (unsigned j = 0; j < plugin.mimes.size(); ++j) {
-            m_mimes.append(plugin.mimes[j]);
-            m_mimePluginIndices.append(i);
-        }
-    }
-}
-
-bool PluginData::supportsMimeType(const String& mimeType) const
-{
-    for (unsigned i = 0; i < m_mimes.size(); ++i)
-        if (m_mimes[i].type == mimeType)
-            return true;
-    return false;
-}
-
-const PluginInfo* PluginData::pluginInfoForMimeType(const String& mimeType) const
-{
-    for (unsigned i = 0; i < m_mimes.size(); ++i) {
-        const MimeClassInfo& info = m_mimes[i];
-
-        if (info.type == mimeType)
-            return &m_plugins[m_mimePluginIndices[i]];
-    }
-
-    return 0;
-}
-
-String PluginData::pluginNameForMimeType(const String& mimeType) const
-{
-    if (const PluginInfo* info = pluginInfoForMimeType(mimeType))
-        return info->name;
-    return String();
-}
-
-String PluginData::pluginFileForMimeType(const String& mimeType) const
-{
-    if (const PluginInfo* info = pluginInfoForMimeType(mimeType))
-        return info->file;
-    return String();
-}
-
-void PluginData::initPlugins(const Page*)
-{
-    const Vector<PluginInfo>& plugins = pluginCache().plugins();
-    for (size_t i = 0; i < plugins.size(); ++i)
-        m_plugins.append(plugins[i]);
-}
-
-void PluginData::refresh()
-{
-    pluginCache().reset(true);
-    pluginCache().plugins(); // Force the plugins to be reloaded now.
-}
-
-String getPluginMimeTypeFromExtension(const String& extension)
-{
-    const Vector<PluginInfo>& plugins = pluginCache().plugins();
-    for (size_t i = 0; i < plugins.size(); ++i) {
-        for (size_t j = 0; j < plugins[i].mimes.size(); ++j) {
-            const MimeClassInfo& mime = plugins[i].mimes[j];
-            const Vector<String>& extensions = mime.extensions;
-            for (size_t k = 0; k < extensions.size(); ++k) {
-                if (extension == extensions[k])
-                    return mime.type;
-            }
-        }
-    }
-    return String();
-}
-
-}
diff --git a/Source/core/plugins/PluginData.h b/Source/core/plugins/PluginData.h
deleted file mode 100644
index d60c127..0000000
--- a/Source/core/plugins/PluginData.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
-    Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
-
-    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.
-*/
-
-#ifndef PluginData_h
-#define PluginData_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Page;
-struct PluginInfo;
-
-struct MimeClassInfo {
-    String type;
-    String desc;
-    Vector<String> extensions;
-};
-
-inline bool operator==(const MimeClassInfo& a, const MimeClassInfo& b)
-{
-    return a.type == b.type && a.desc == b.desc && a.extensions == b.extensions;
-}
-
-struct PluginInfo {
-    String name;
-    String file;
-    String desc;
-    Vector<MimeClassInfo> mimes;
-};
-
-class PluginData : public RefCounted<PluginData> {
-public:
-    static PassRefPtr<PluginData> create(const Page* page) { return adoptRef(new PluginData(page)); }
-
-    const Vector<PluginInfo>& plugins() const { return m_plugins; }
-    const Vector<MimeClassInfo>& mimes() const { return m_mimes; }
-    const Vector<size_t>& mimePluginIndices() const { return m_mimePluginIndices; }
-
-    bool supportsMimeType(const String& mimeType) const;
-    String pluginNameForMimeType(const String& mimeType) const;
-    String pluginFileForMimeType(const String& mimeType) const;
-
-    static void refresh();
-
-private:
-    explicit PluginData(const Page*);
-    void initPlugins(const Page*);
-    const PluginInfo* pluginInfoForMimeType(const String& mimeType) const;
-
-    Vector<PluginInfo> m_plugins;
-    Vector<MimeClassInfo> m_mimes;
-    Vector<size_t> m_mimePluginIndices;
-};
-
-// Checks if any of the plugins handle this extension, and if so returns the
-// plugin's mime type for this extension.  Otherwise returns an empty string.
-String getPluginMimeTypeFromExtension(const String& extension);
-
-}
-
-#endif
diff --git a/Source/core/plugins/PluginListBuilder.cpp b/Source/core/plugins/PluginListBuilder.cpp
deleted file mode 100644
index 98482fb..0000000
--- a/Source/core/plugins/PluginListBuilder.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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:
- *
- *     * 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/plugins/PluginListBuilder.h"
-
-#include "core/plugins/PluginData.h"
-#include "public/platform/WebString.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-void PluginListBuilder::addPlugin(const WebKit::WebString& name, const WebKit::WebString& description, const WebKit::WebString& fileName)
-{
-    PluginInfo info;
-    info.name = name;
-    info.desc = description;
-    info.file = fileName;
-    m_results->append(info);
-}
-
-void PluginListBuilder::addMediaTypeToLastPlugin(const WebKit::WebString& name, const WebKit::WebString& description)
-{
-    MimeClassInfo info;
-    info.type = name;
-    info.desc = description;
-    m_results->last().mimes.append(info);
-}
-
-void PluginListBuilder::addFileExtensionToLastMediaType(const WebKit::WebString& extension)
-{
-    MimeClassInfo& info = m_results->last().mimes.last();
-    info.extensions.append(extension);
-}
-
-} // namespace WebCore
diff --git a/Source/core/plugins/PluginListBuilder.h b/Source/core/plugins/PluginListBuilder.h
deleted file mode 100644
index 4ff0b4e..0000000
--- a/Source/core/plugins/PluginListBuilder.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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:
- *
- *     * 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 PluginListBuilder_h
-#define PluginListBuilder_h
-
-#include "core/plugins/PluginData.h"
-#include "public/platform/WebPluginListBuilder.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class PluginListBuilder : public WebKit::WebPluginListBuilder {
-public:
-    PluginListBuilder(Vector<WebCore::PluginInfo>* results) : m_results(results) { }
-
-    // WebPluginListBuilder methods:
-    virtual void addPlugin(const WebKit::WebString& name, const WebKit::WebString& description, const WebKit::WebString& fileName);
-    virtual void addMediaTypeToLastPlugin(const WebKit::WebString& name, const WebKit::WebString& description);
-    virtual void addFileExtensionToLastMediaType(const WebKit::WebString& extension);
-
-private:
-    Vector<PluginInfo>* m_results;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/plugins/PluginView.h b/Source/core/plugins/PluginView.h
index 5b1c68d..19d4453 100644
--- a/Source/core/plugins/PluginView.h
+++ b/Source/core/plugins/PluginView.h
@@ -32,7 +32,7 @@
 
 struct NPObject;
 
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
 
 namespace WebCore {
 
@@ -44,7 +44,7 @@
 public:
     virtual bool isPluginView() const { return true; }
 
-    virtual WebKit::WebLayer* platformLayer() const { return 0; }
+    virtual blink::WebLayer* platformLayer() const { return 0; }
     virtual NPObject* scriptableObject() { return 0; }
     virtual bool getFormValue(String&) { return false; }
     virtual bool wantsWheelEvents() { return false; }
@@ -62,13 +62,13 @@
 
 inline PluginView* toPluginView(Widget* widget)
 {
-    ASSERT(!widget || widget->isPluginView());
+    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isPluginView());
     return static_cast<PluginView*>(widget);
 }
 
 inline const PluginView* toPluginView(const Widget* widget)
 {
-    ASSERT(!widget || widget->isPluginView());
+    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isPluginView());
     return static_cast<const PluginView*>(widget);
 }
 
diff --git a/Source/core/rendering/ClipPathOperation.h b/Source/core/rendering/ClipPathOperation.h
index fcbf07b..62125d1 100644
--- a/Source/core/rendering/ClipPathOperation.h
+++ b/Source/core/rendering/ClipPathOperation.h
@@ -51,8 +51,8 @@
     virtual bool operator==(const ClipPathOperation&) const = 0;
     bool operator!=(const ClipPathOperation& o) const { return !(*this == o); }
 
-    virtual OperationType getOperationType() const { return m_type; }
-    virtual bool isSameType(const ClipPathOperation& o) const { return o.getOperationType() == m_type; }
+    OperationType type() const { return m_type; }
+    bool isSameType(const ClipPathOperation& o) const { return o.type() == m_type; }
 
 protected:
     ClipPathOperation(OperationType type)
@@ -74,12 +74,9 @@
     const String& fragment() const { return m_fragment; }
 
 private:
-    virtual bool operator==(const ClipPathOperation& o) const
+    virtual bool operator==(const ClipPathOperation& o) const OVERRIDE
     {
-        if (!isSameType(o))
-            return false;
-        const ReferenceClipPathOperation* other = static_cast<const ReferenceClipPathOperation*>(&o);
-        return m_url == other->m_url;
+        return isSameType(o) && m_url == static_cast<const ReferenceClipPathOperation&>(o).m_url;
     }
 
     ReferenceClipPathOperation(const String& url, const String& fragment)
@@ -93,6 +90,8 @@
     String m_fragment;
 };
 
+DEFINE_TYPE_CASTS(ReferenceClipPathOperation, ClipPathOperation, op, op->type() == ClipPathOperation::REFERENCE, op.type() == ClipPathOperation::REFERENCE);
+
 class ShapeClipPathOperation : public ClipPathOperation {
 public:
     static PassRefPtr<ShapeClipPathOperation> create(PassRefPtr<BasicShape> shape)
@@ -112,12 +111,9 @@
     }
 
 private:
-    virtual bool operator==(const ClipPathOperation& o) const
+    virtual bool operator==(const ClipPathOperation& o) const OVERRIDE
     {
-        if (!isSameType(o))
-            return false;
-        const ShapeClipPathOperation* other = static_cast<const ShapeClipPathOperation*>(&o);
-        return m_shape == other->m_shape;
+        return isSameType(o) && m_shape == static_cast<const ShapeClipPathOperation&>(o).m_shape;
     }
 
     ShapeClipPathOperation(PassRefPtr<BasicShape> shape)
@@ -129,6 +125,9 @@
     RefPtr<BasicShape> m_shape;
     OwnPtr<Path> m_path;
 };
+
+DEFINE_TYPE_CASTS(ShapeClipPathOperation, ClipPathOperation, op, op->type() == ClipPathOperation::SHAPE, op.type() == ClipPathOperation::SHAPE);
+
 }
 
 #endif // ClipPathOperation_h
diff --git a/Source/core/rendering/ClipRect.h b/Source/core/rendering/ClipRect.h
index 01feb66..8fbcebf 100644
--- a/Source/core/rendering/ClipRect.h
+++ b/Source/core/rendering/ClipRect.h
@@ -138,7 +138,7 @@
         return m_overflowClipRect == other.overflowClipRect()
             && m_fixedClipRect == other.fixedClipRect()
             && m_posClipRect == other.posClipRect()
-            && m_fixed == other.fixed();
+            && fixed() == other.fixed();
     }
 
     ClipRects& operator=(const ClipRects& other)
diff --git a/Source/core/rendering/CompositedLayerMapping.cpp b/Source/core/rendering/CompositedLayerMapping.cpp
index b24185b..3459118 100644
--- a/Source/core/rendering/CompositedLayerMapping.cpp
+++ b/Source/core/rendering/CompositedLayerMapping.cpp
@@ -30,6 +30,7 @@
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
+#include "core/animation/ActiveAnimations.h"
 #include "core/fetch/ImageResource.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLMediaElement.h"
@@ -53,6 +54,7 @@
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/animation/WebAnimationProvider.h"
@@ -162,17 +164,13 @@
     , m_artificiallyInflatedBounds(false)
     , m_boundsConstrainedByClipping(false)
     , m_isMainFrameRenderViewLayer(false)
-    , m_requiresOwnBackingStore(true)
+    , m_requiresOwnBackingStoreForIntrinsicReasons(true)
+    , m_requiresOwnBackingStoreForAncestorReasons(true)
     , m_canCompositeFilters(false)
     , m_backgroundLayerPaintsFixedRootBackground(false)
 {
-    if (layer->isRootLayer()) {
-        Frame& frame = toRenderView(renderer())->frameView()->frame();
-        Page* page = frame.page();
-        if (page && page->mainFrame() == &frame) {
-            m_isMainFrameRenderViewLayer = true;
-        }
-    }
+    if (layer->isRootLayer() && renderer()->frame()->isMainFrame())
+        m_isMainFrameRenderViewLayer = true;
 
     createPrimaryGraphicsLayer();
 }
@@ -327,6 +325,10 @@
 
 void CompositedLayerMapping::updateCompositedBounds()
 {
+    // We need to know if we draw content in order to update our bounds (this has an effect
+    // on whether or not descendands will paint into our backing). Update this value now.
+    updateDrawsContent(isSimpleContainerCompositingLayer());
+
     IntRect layerBounds = compositor()->calculateCompositedBounds(m_owningLayer, m_owningLayer);
 
     // Clip to the size of the document or enclosing overflow-scroll layer.
@@ -463,12 +465,19 @@
     if (updateMaskLayer(renderer->hasMask()))
         m_graphicsLayer->setMaskLayer(m_maskLayer.get());
 
-    bool needsChildClippingMask = (renderer->style()->hasBorderRadius() || renderer->style()->clipPath()) && isAcceleratedContents(renderer);
-    if (updateClippingMaskLayers(needsChildClippingMask))
-        m_graphicsLayer->setContentsClippingMaskLayer(m_childClippingMaskLayer.get());
+    bool hasChildClippingLayer = compositor->clipsCompositingDescendants(m_owningLayer) && (hasClippingLayer() || hasScrollingLayer());
+    bool needsChildClippingMask = (renderer->style()->clipPath() || renderer->style()->hasBorderRadius()) && (hasChildClippingLayer || isAcceleratedContents(renderer));
+    if (updateClippingMaskLayers(needsChildClippingMask)) {
+        if (hasClippingLayer())
+            clippingLayer()->setMaskLayer(m_childClippingMaskLayer.get());
+        else if (hasScrollingLayer())
+            scrollingLayer()->setMaskLayer(m_childClippingMaskLayer.get());
+        else if (isAcceleratedContents(renderer))
+            m_graphicsLayer->setContentsClippingMaskLayer(m_childClippingMaskLayer.get());
+    }
 
     if (m_owningLayer->reflectionInfo()) {
-        if (m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping()) {
+        if (m_owningLayer->reflectionInfo()->reflectionLayer()->hasCompositedLayerMapping()) {
             GraphicsLayer* reflectionLayer = m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping()->mainGraphicsLayer();
             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
         }
@@ -483,14 +492,14 @@
 
     if (renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing()) {
         PluginView* pluginView = toPluginView(toRenderWidget(renderer)->widget());
-        m_graphicsLayer->setContentsToMedia(pluginView->platformLayer());
+        m_graphicsLayer->setContentsToPlatformLayer(pluginView->platformLayer());
     } else if (renderer->isVideo()) {
         HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer->node());
-        m_graphicsLayer->setContentsToMedia(mediaElement->platformLayer());
+        m_graphicsLayer->setContentsToPlatformLayer(mediaElement->platformLayer());
     } else if (isAcceleratedCanvas(renderer)) {
         HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
         if (CanvasRenderingContext* context = canvas->renderingContext())
-            m_graphicsLayer->setContentsToCanvas(context->platformLayer());
+            m_graphicsLayer->setContentsToPlatformLayer(context->platformLayer());
         layerConfigChanged = true;
     }
     if (renderer->isRenderPart())
@@ -519,11 +528,15 @@
 
     // Set transform property, if it is not animating. We have to do this here because the transform
     // is affected by the layer dimensions.
-    if (!renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform))
+    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+        ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitTransform)
+        : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform))
         updateTransform(renderer()->style());
 
     // Set opacity, if it is not animating.
-    if (!renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity))
+    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+        ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyOpacity)
+        : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity))
         updateOpacity(renderer()->style());
 
     if (RuntimeEnabledFeatures::cssCompositingEnabled())
@@ -555,7 +568,7 @@
     // We compute everything relative to the enclosing compositing layer.
     IntRect ancestorCompositingBounds;
     if (compAncestor) {
-        ASSERT(compAncestor->compositedLayerMapping());
+        ASSERT(compAncestor->hasCompositedLayerMapping());
         ancestorCompositingBounds = pixelSnappedIntRect(compAncestor->compositedLayerMapping()->compositedBounds());
     }
 
@@ -624,6 +637,11 @@
         clipLayer->setPosition(FloatPoint(clippingBox.location() - localCompositingBounds.location()));
         clipLayer->setSize(clippingBox.size());
         clipLayer->setOffsetFromRenderer(toIntSize(clippingBox.location()));
+        if (m_childClippingMaskLayer && !m_scrollingLayer) {
+            m_childClippingMaskLayer->setPosition(clipLayer->position());
+            m_childClippingMaskLayer->setSize(clipLayer->size());
+            m_childClippingMaskLayer->setOffsetFromRenderer(clipLayer->offsetFromRenderer());
+        }
     }
 
     if (m_maskLayer) {
@@ -704,8 +722,8 @@
         m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
     }
 
-    if (m_owningLayer->reflectionInfo() && m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping()) {
-        CompositedLayerMapping* reflectionCompositedLayerMapping = m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping();
+    if (m_owningLayer->reflectionInfo() && m_owningLayer->reflectionInfo()->reflectionLayer()->hasCompositedLayerMapping()) {
+        CompositedLayerMappingPtr reflectionCompositedLayerMapping = m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping();
         reflectionCompositedLayerMapping->updateGraphicsLayerGeometry();
 
         // The reflection layer has the bounds of m_owningLayer->reflectionLayer(),
@@ -730,6 +748,12 @@
         IntSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
         m_scrollingLayer->setOffsetFromRenderer(-toIntSize(clientBox.location()));
 
+        if (m_childClippingMaskLayer) {
+            m_childClippingMaskLayer->setPosition(m_scrollingLayer->position());
+            m_childClippingMaskLayer->setSize(m_scrollingLayer->size());
+            m_childClippingMaskLayer->setOffsetFromRenderer(toIntSize(clientBox.location()));
+        }
+
         bool clientBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
 
         IntSize scrollSize(renderBox->scrollWidth(), renderBox->scrollHeight());
@@ -761,8 +785,9 @@
     if (m_owningLayer->scrollableArea())
         m_owningLayer->scrollableArea()->positionOverflowControls();
 
-    // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
-    setRequiresOwnBackingStore(compositor()->requiresOwnBackingStore(m_owningLayer, compAncestor));
+    // We can't make this call in RenderLayerCompositor::allocateOrClearCompositedLayerMapping
+    // since it depends on whether compAncestor draws content, which gets updated later.
+    updateRequiresOwnBackingStoreForAncestorReasons(compAncestor);
 
     updateContentsRect(isSimpleContainer);
     updateBackgroundColor(isSimpleContainer);
@@ -862,7 +887,7 @@
     if (hasPaintedContent && isAcceleratedCanvas(renderer())) {
         CanvasRenderingContext* context = toHTMLCanvasElement(renderer()->node())->renderingContext();
         // Content layer may be null if context is lost.
-        if (WebKit::WebLayer* contentLayer = context->platformLayer()) {
+        if (blink::WebLayer* contentLayer = context->platformLayer()) {
             Color bgColor;
             if (contentLayerSupportsDirectBackgroundComposition(renderer())) {
                 bgColor = rendererBackgroundColor();
@@ -1351,40 +1376,23 @@
     LayerListMutationDetector mutationChecker(parent->stackingNode());
 #endif
 
-    if (Vector<RenderLayerStackingNode*>* normalFlowList = parent->stackingNode()->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i)->layer();
-            if (!curLayer->compositedLayerMapping()
-                && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
-                return true;
-        }
+    RenderLayerStackingNodeIterator normalFlowIterator(*parent->stackingNode(), NormalFlowChildren);
+    while (RenderLayerStackingNode* curNode = normalFlowIterator.next()) {
+        RenderLayer* curLayer = curNode->layer();
+        if (!curLayer->hasCompositedLayerMapping()
+            && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
+            return true;
     }
 
-    if (parent->stackingNode()->isStackingContainer()) {
-        if (!parent->hasVisibleDescendant())
-            return false;
+    if (!parent->hasVisibleDescendant())
+        return false;
 
-        // Use the m_hasCompositingDescendant bit to optimize?
-        if (Vector<RenderLayerStackingNode*>* negZOrderList = parent->stackingNode()->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = negZOrderList->at(i)->layer();
-                if (!curLayer->compositedLayerMapping()
-                    && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
-                    return true;
-            }
-        }
-
-        if (Vector<RenderLayerStackingNode*>* posZOrderList = parent->stackingNode()->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = posZOrderList->at(i)->layer();
-                if (!curLayer->compositedLayerMapping()
-                    && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
-                    return true;
-            }
-        }
+    RenderLayerStackingNodeIterator zOrderIterator(*parent->stackingNode(), NegativeZOrderChildren | PositiveZOrderChildren);
+    while (RenderLayerStackingNode* curNode = zOrderIterator.next()) {
+        RenderLayer* curLayer = curNode->layer();
+        if (!curLayer->hasCompositedLayerMapping()
+            && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
+            return true;
     }
 
     return false;
@@ -1429,10 +1437,7 @@
             return false;
 
         Image* image = cachedImage->imageForRenderer(imageRenderer);
-        if (!image->isBitmapImage())
-            return false;
-
-        return m_graphicsLayer->shouldDirectlyCompositeImage(image);
+        return image->isBitmapImage();
     }
 
     return false;
@@ -1547,15 +1552,42 @@
     return m_graphicsLayer.get();
 }
 
-void CompositedLayerMapping::setRequiresOwnBackingStore(bool requiresOwnBacking)
+bool CompositedLayerMapping::updateRequiresOwnBackingStoreForAncestorReasons(const RenderLayer* compositingAncestorLayer)
 {
-    if (requiresOwnBacking == m_requiresOwnBackingStore)
-        return;
+    bool previousRequiresOwnBackingStoreForAncestorReasons = m_requiresOwnBackingStoreForAncestorReasons;
+    bool previousPaintsIntoCompositedAncestor = paintsIntoCompositedAncestor();
+    bool canPaintIntoAncestor = compositingAncestorLayer
+        && (compositingAncestorLayer->compositedLayerMapping()->mainGraphicsLayer()->drawsContent()
+            || compositingAncestorLayer->compositedLayerMapping()->paintsIntoCompositedAncestor());
+    m_requiresOwnBackingStoreForAncestorReasons = !canPaintIntoAncestor;
 
-    m_requiresOwnBackingStore = requiresOwnBacking;
+    if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
+        paintsIntoCompositedAncestorChanged();
+    return m_requiresOwnBackingStoreForAncestorReasons != previousRequiresOwnBackingStoreForAncestorReasons;
+}
 
-    // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
-    // cached clip rects, so when it changes we have to clear clip rects on descendants.
+bool CompositedLayerMapping::updateRequiresOwnBackingStoreForIntrinsicReasons()
+{
+    bool previousRequiresOwnBackingStoreForIntrinsicReasons = m_requiresOwnBackingStoreForIntrinsicReasons;
+    bool previousPaintsIntoCompositedAncestor = paintsIntoCompositedAncestor();
+    RenderObject* renderer = m_owningLayer->renderer();
+    m_requiresOwnBackingStoreForIntrinsicReasons = m_owningLayer->isRootLayer()
+        || (m_owningLayer->compositingReasons() & CompositingReasonComboReasonsThatRequireOwnBacking)
+        || m_owningLayer->transform()
+        || renderer->isTransparent()
+        || renderer->hasMask()
+        || renderer->hasReflection()
+        || renderer->hasFilter();
+
+    if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
+        paintsIntoCompositedAncestorChanged();
+    return m_requiresOwnBackingStoreForIntrinsicReasons != previousRequiresOwnBackingStoreForIntrinsicReasons;
+}
+
+void CompositedLayerMapping::paintsIntoCompositedAncestorChanged()
+{
+    // The answer to paintsIntoCompositedAncestor() affects cached clip rects, so when
+    // it changes we have to clear clip rects on descendants.
     m_owningLayer->clipper().clearClipRectsIncludingDescendants(PaintingClipRects);
     m_owningLayer->repainter().computeRepaintRectsIncludingDescendants();
 
@@ -1661,8 +1693,6 @@
     else if (compositor()->fixedRootBackgroundLayer())
         paintFlags |= PaintLayerPaintingSkipRootBackground;
 
-    InspectorInstrumentation::willPaint(paintInfo.renderLayer->renderer());
-
     // Note carefully: in theory it is appropriate to invoke context->save() here
     // and restore the context after painting. For efficiency, we are assuming that
     // it is equivalent to manually undo this offset translation, which means we are
@@ -1696,8 +1726,6 @@
 
     // Manually restore the context to its original state by applying the opposite translation.
     context->translate(offset);
-
-    InspectorInstrumentation::didPaint(paintInfo.renderLayer->renderer(), context, clip);
 }
 
 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
@@ -1721,6 +1749,7 @@
     if (Page* page = renderer()->frame()->page())
         page->setIsPainting(true);
 #endif
+    InspectorInstrumentation::willPaint(m_owningLayer->renderer());
 
     if (graphicsLayer == m_graphicsLayer.get()
         || graphicsLayer == m_foregroundLayer.get()
@@ -1752,6 +1781,7 @@
         m_owningLayer->scrollableArea()->paintResizer(&context, IntPoint(), transformedClip);
         context.restore();
     }
+    InspectorInstrumentation::didPaint(m_owningLayer->renderer(), graphicsLayer, &context, clip);
 #ifndef NDEBUG
     if (Page* page = renderer()->frame()->page())
         page->setIsPainting(false);
@@ -1916,7 +1946,10 @@
 
 void CompositedLayerMapping::notifyAnimationStarted(const GraphicsLayer*, double time)
 {
-    renderer()->animation().notifyAnimationStarted(renderer(), time);
+    if (RuntimeEnabledFeatures::webAnimationsEnabled())
+        renderer()->node()->document().cssPendingAnimations().notifyCompositorAnimationStarted(monotonicallyIncreasingTime() - (currentTime() - time));
+    else
+        renderer()->animation().notifyAnimationStarted(renderer(), time);
 }
 
 IntRect CompositedLayerMapping::compositedBounds() const
@@ -1985,6 +2018,8 @@
         name = "Child Containment Layer";
     } else if (graphicsLayer == m_maskLayer.get()) {
         name = "Mask Layer";
+    } else if (graphicsLayer == m_childClippingMaskLayer.get()) {
+        name = "Child Clipping Mask Layer";
     } else if (graphicsLayer == m_layerForHorizontalScrollbar.get()) {
         name = "Horizontal Scrollbar Layer";
     } else if (graphicsLayer == m_layerForVerticalScrollbar.get()) {
diff --git a/Source/core/rendering/CompositedLayerMapping.h b/Source/core/rendering/CompositedLayerMapping.h
index 0582e7e..2a4cac9 100644
--- a/Source/core/rendering/CompositedLayerMapping.h
+++ b/Source/core/rendering/CompositedLayerMapping.h
@@ -117,9 +117,16 @@
 
     // Returns true for a composited layer that has no backing store of its own, so
     // paints into some ancestor layer.
-    bool paintsIntoCompositedAncestor() const { return !m_requiresOwnBackingStore; }
+    bool paintsIntoCompositedAncestor() const { return !(m_requiresOwnBackingStoreForAncestorReasons || m_requiresOwnBackingStoreForIntrinsicReasons); }
 
-    void setRequiresOwnBackingStore(bool);
+    // Updates whether a backing store is needed based on the layer's compositing ancestor's
+    // properties; returns true if the need for a backing store for ancestor reasons changed.
+    bool updateRequiresOwnBackingStoreForAncestorReasons(const RenderLayer* compositingAncestor);
+
+    // Updates whether a backing store is needed for intrinsic reasons (that is, based on the
+    // layer's own properties or compositing reasons); returns true if the intrinsic need for
+    // a backing store changed.
+    bool updateRequiresOwnBackingStoreForIntrinsicReasons();
 
     void setContentsNeedDisplay();
     // r is in the coordinate space of the layer's render object
@@ -245,6 +252,8 @@
 
     bool shouldClipCompositedBounds() const;
 
+    void paintsIntoCompositedAncestorChanged();
+
     void doPaintTask(GraphicsLayerPaintInfo&, GraphicsContext*, const IntRect& clip);
 
     RenderLayer* m_owningLayer;
@@ -324,7 +333,8 @@
     bool m_artificiallyInflatedBounds; // bounds had to be made non-zero to make transform-origin work
     bool m_boundsConstrainedByClipping;
     bool m_isMainFrameRenderViewLayer;
-    bool m_requiresOwnBackingStore;
+    bool m_requiresOwnBackingStoreForIntrinsicReasons;
+    bool m_requiresOwnBackingStoreForAncestorReasons;
     bool m_canCompositeFilters;
     bool m_backgroundLayerPaintsFixedRootBackground;
 };
diff --git a/Source/core/rendering/CompositedLayerMappingPtr.h b/Source/core/rendering/CompositedLayerMappingPtr.h
new file mode 100644
index 0000000..27cb685
--- /dev/null
+++ b/Source/core/rendering/CompositedLayerMappingPtr.h
@@ -0,0 +1,39 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CompositedLayerMappingPtr_h
+#define CompositedLayerMappingPtr_h
+
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+class CompositedLayerMapping;
+
+class CompositedLayerMappingPtr {
+public:
+    CompositedLayerMappingPtr(CompositedLayerMapping* mapping)
+        : m_mapping(mapping)
+    {
+    }
+
+    CompositedLayerMapping& operator*() const
+    {
+        ASSERT(m_mapping);
+        return *m_mapping;
+    }
+
+    CompositedLayerMapping* operator->() const
+    {
+        ASSERT(m_mapping);
+        return m_mapping;
+    }
+
+private:
+    CompositedLayerMapping* m_mapping;
+};
+
+} // namespace WebCore
+
+#endif // CompositedLayerMappingPtr_h
diff --git a/Source/core/rendering/CompositingReasons.h b/Source/core/rendering/CompositingReasons.h
index 4190494..21a545e 100644
--- a/Source/core/rendering/CompositingReasons.h
+++ b/Source/core/rendering/CompositingReasons.h
@@ -61,6 +61,33 @@
 
 const uint64_t CompositingReasonLayerForVideoOverlay                   = UINT64_C(1) << 34;
 
+const uint64_t CompositingReasonComboAllDirectReasons =
+    CompositingReason3DTransform
+    | CompositingReasonVideo
+    | CompositingReasonCanvas
+    | CompositingReasonPlugin
+    | CompositingReasonIFrame
+    | CompositingReasonBackfaceVisibilityHidden
+    | CompositingReasonAnimation
+    | CompositingReasonFilters
+    | CompositingReasonPositionFixed
+    | CompositingReasonPositionSticky
+    | CompositingReasonOverflowScrollingTouch
+    | CompositingReasonOverflowScrollingParent
+    | CompositingReasonOutOfFlowClipping;
+
+const uint64_t CompositingReasonComboReasonsThatRequireOwnBacking =
+    CompositingReasonComboAllDirectReasons
+    | CompositingReasonOverlap
+    | CompositingReasonAssumedOverlap
+    | CompositingReasonNegativeZIndexChildren
+    | CompositingReasonTransformWithCompositedDescendants
+    | CompositingReasonOpacityWithCompositedDescendants
+    | CompositingReasonMaskWithCompositedDescendants
+    | CompositingReasonFilterWithCompositedDescendants
+    | CompositingReasonBlendingWithCompositedDescendants
+    | CompositingReasonPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
+
 // 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/CounterNode.cpp b/Source/core/rendering/CounterNode.cpp
index 53957f8..87beb7f 100644
--- a/Source/core/rendering/CounterNode.cpp
+++ b/Source/core/rendering/CounterNode.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-CounterNode::CounterNode(RenderObject* o, bool hasResetType, int value)
+CounterNode::CounterNode(RenderObject& o, bool hasResetType, int value)
     : m_hasResetType(hasResetType)
     , m_value(value)
     , m_countInParent(0)
@@ -92,7 +92,7 @@
     resetRenderers();
 }
 
-PassRefPtr<CounterNode> CounterNode::create(RenderObject* owner, bool hasResetType, int value)
+PassRefPtr<CounterNode> CounterNode::create(RenderObject& owner, bool hasResetType, int value)
 {
     return adoptRef(new CounterNode(owner, hasResetType, value));
 }
@@ -367,7 +367,7 @@
         fprintf(stderr, "%p %s: %d %d P:%p PS:%p NS:%p R:%p\n",
             current, current->actsAsReset() ? "reset____" : "increment", current->value(),
             current->countInParent(), current->parent(), current->previousSibling(),
-            current->nextSibling(), current->owner());
+            current->nextSibling(), &current->owner());
     }
     fflush(stderr);
 }
diff --git a/Source/core/rendering/CounterNode.h b/Source/core/rendering/CounterNode.h
index c467036..baaeed3 100644
--- a/Source/core/rendering/CounterNode.h
+++ b/Source/core/rendering/CounterNode.h
@@ -42,13 +42,13 @@
 
 class CounterNode : public RefCounted<CounterNode> {
 public:
-    static PassRefPtr<CounterNode> create(RenderObject*, bool isReset, int value);
+    static PassRefPtr<CounterNode> create(RenderObject&, bool isReset, int value);
     ~CounterNode();
     bool actsAsReset() const { return m_hasResetType || !m_parent; }
     bool hasResetType() const { return m_hasResetType; }
     int value() const { return m_value; }
     int countInParent() const { return m_countInParent; }
-    RenderObject* owner() const { return m_owner; }
+    RenderObject& owner() const { return m_owner; }
     void addRenderer(RenderCounter*);
     void removeRenderer(RenderCounter*);
 
@@ -71,7 +71,7 @@
     void removeChild(CounterNode*);
 
 private:
-    CounterNode(RenderObject*, bool isReset, int value);
+    CounterNode(RenderObject&, bool isReset, int value);
     int computeCountInParent() const;
     // Invalidates the text in the renderer of this counter, if any,
     // and in the renderers of all descendants of this counter, if any.
@@ -81,7 +81,7 @@
     bool m_hasResetType;
     int m_value;
     int m_countInParent;
-    RenderObject* m_owner;
+    RenderObject& m_owner;
     RenderCounter* m_rootRenderer;
 
     CounterNode* m_parent;
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index 1a5c1a2..d8f0eef 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -124,16 +124,14 @@
     for (size_t i = 0; i < operations.operations().size(); ++i) {
         RefPtr<FilterEffect> effect;
         FilterOperation* filterOperation = operations.operations().at(i).get();
-        switch (filterOperation->getOperationType()) {
+        switch (filterOperation->type()) {
         case FilterOperation::REFERENCE: {
-            ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
-            effect = ReferenceFilterBuilder::build(this, renderer, previousEffect.get(), referenceOperation);
+            effect = ReferenceFilterBuilder::build(this, renderer, previousEffect.get(), toReferenceFilterOperation(filterOperation));
             break;
         }
         case FilterOperation::GRAYSCALE: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
             Vector<float> inputParameters;
-            double oneMinusAmount = clampTo(1 - colorMatrixOperation->amount(), 0.0, 1.0);
+            double oneMinusAmount = clampTo(1 - toBasicColorMatrixFilterOperation(filterOperation)->amount(), 0.0, 1.0);
 
             // See https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#grayscaleEquivalent
             // for information on parameters.
@@ -159,9 +157,8 @@
             break;
         }
         case FilterOperation::SEPIA: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
             Vector<float> inputParameters;
-            double oneMinusAmount = clampTo(1 - colorMatrixOperation->amount(), 0.0, 1.0);
+            double oneMinusAmount = clampTo(1 - toBasicColorMatrixFilterOperation(filterOperation)->amount(), 0.0, 1.0);
 
             // See https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#sepiaEquivalent
             // for information on parameters.
@@ -187,21 +184,19 @@
             break;
         }
         case FilterOperation::SATURATE: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
             Vector<float> inputParameters;
-            inputParameters.append(narrowPrecisionToFloat(colorMatrixOperation->amount()));
+            inputParameters.append(narrowPrecisionToFloat(toBasicColorMatrixFilterOperation(filterOperation)->amount()));
             effect = FEColorMatrix::create(this, FECOLORMATRIX_TYPE_SATURATE, inputParameters);
             break;
         }
         case FilterOperation::HUE_ROTATE: {
-            BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
             Vector<float> inputParameters;
-            inputParameters.append(narrowPrecisionToFloat(colorMatrixOperation->amount()));
+            inputParameters.append(narrowPrecisionToFloat(toBasicColorMatrixFilterOperation(filterOperation)->amount()));
             effect = FEColorMatrix::create(this, FECOLORMATRIX_TYPE_HUEROTATE, inputParameters);
             break;
         }
         case FilterOperation::INVERT: {
-            BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+            BasicComponentTransferFilterOperation* componentTransferOperation = toBasicComponentTransferFilterOperation(filterOperation);
             ComponentTransferFunction transferFunction;
             transferFunction.type = FECOMPONENTTRANSFER_TYPE_TABLE;
             Vector<float> transferParameters;
@@ -214,12 +209,11 @@
             break;
         }
         case FilterOperation::OPACITY: {
-            BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
             ComponentTransferFunction transferFunction;
             transferFunction.type = FECOMPONENTTRANSFER_TYPE_TABLE;
             Vector<float> transferParameters;
             transferParameters.append(0);
-            transferParameters.append(narrowPrecisionToFloat(componentTransferOperation->amount()));
+            transferParameters.append(narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount()));
             transferFunction.tableValues = transferParameters;
 
             ComponentTransferFunction nullFunction;
@@ -227,10 +221,9 @@
             break;
         }
         case FilterOperation::BRIGHTNESS: {
-            BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
             ComponentTransferFunction transferFunction;
             transferFunction.type = FECOMPONENTTRANSFER_TYPE_LINEAR;
-            transferFunction.slope = narrowPrecisionToFloat(componentTransferOperation->amount());
+            transferFunction.slope = narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount());
             transferFunction.intercept = 0;
 
             ComponentTransferFunction nullFunction;
@@ -238,10 +231,9 @@
             break;
         }
         case FilterOperation::CONTRAST: {
-            BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
             ComponentTransferFunction transferFunction;
             transferFunction.type = FECOMPONENTTRANSFER_TYPE_LINEAR;
-            float amount = narrowPrecisionToFloat(componentTransferOperation->amount());
+            float amount = narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount());
             transferFunction.slope = amount;
             transferFunction.intercept = -0.5 * amount + 0.5;
 
@@ -250,13 +242,12 @@
             break;
         }
         case FilterOperation::BLUR: {
-            BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
-            float stdDeviation = floatValueForLength(blurOperation->stdDeviation(), 0) * invZoom;
+            float stdDeviation = floatValueForLength(toBlurFilterOperation(filterOperation)->stdDeviation(), 0) * invZoom;
             effect = FEGaussianBlur::create(this, stdDeviation, stdDeviation);
             break;
         }
         case FilterOperation::DROP_SHADOW: {
-            DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
+            DropShadowFilterOperation* dropShadowOperation = toDropShadowFilterOperation(filterOperation);
             float stdDeviation = dropShadowOperation->stdDeviation() * invZoom;
             float x = dropShadowOperation->x() * invZoom;
             float y = dropShadowOperation->y() * invZoom;
@@ -269,9 +260,8 @@
             ASSERT_NOT_REACHED();
             break;
         case FilterOperation::VALIDATED_CUSTOM: {
-            ValidatedCustomFilterOperation* customFilterOperation = static_cast<ValidatedCustomFilterOperation*>(filterOperation);
             Document* document = renderer ? &renderer->document() : 0;
-            effect = createCustomFilterEffect(this, document, customFilterOperation);
+            effect = createCustomFilterEffect(this, document, toValidatedCustomFilterOperation(filterOperation));
             if (effect)
                 m_hasCustomShaderFilter = true;
             break;
@@ -281,7 +271,7 @@
         }
 
         if (effect) {
-            if (filterOperation->getOperationType() != FilterOperation::REFERENCE) {
+            if (filterOperation->type() != FilterOperation::REFERENCE) {
                 // Unlike SVG, filters applied here should not clip to their primitive subregions.
                 effect->setClipsToBounds(false);
                 effect->setOperatingColorSpace(ColorSpaceDeviceRGB);
diff --git a/Source/core/rendering/FloatingObjects.cpp b/Source/core/rendering/FloatingObjects.cpp
index 332b30b..152a3a3 100644
--- a/Source/core/rendering/FloatingObjects.cpp
+++ b/Source/core/rendering/FloatingObjects.cpp
@@ -104,7 +104,7 @@
 public:
     typedef FloatingObjectInterval IntervalType;
 
-    ComputeFloatOffsetAdapter(const RenderBlockFlow* renderer, int lineTop, int lineBottom, LayoutUnit& offset)
+    ComputeFloatOffsetAdapter(const RenderBlockFlow* renderer, int lineTop, int lineBottom, LayoutUnit offset)
         : m_renderer(renderer)
         , m_lineTop(lineTop)
         , m_lineBottom(lineBottom)
@@ -117,13 +117,9 @@
     int highValue() const { return m_lineBottom; }
     void collectIfNeeded(const IntervalType&);
 
-    // When computing the offset caused by the floats on a given line, if
-    // the outermost float on that line has a shape-outside, the inline
-    // content that butts up against that float must be positioned using
-    // the contours of the shape, not the margin box of the float.
-    const FloatingObject* outermostFloat() const { return m_outermostFloat; }
-
-    LayoutUnit getHeightRemaining() const;
+    LayoutUnit offset() const { return m_offset; }
+    LayoutUnit shapeOffset() const;
+    LayoutUnit heightRemaining() const;
 
 private:
     bool updateOffsetIfNeeded(const FloatingObject*);
@@ -131,7 +127,7 @@
     const RenderBlockFlow* m_renderer;
     int m_lineTop;
     int m_lineBottom;
-    LayoutUnit& m_offset;
+    LayoutUnit m_offset;
     const FloatingObject* m_outermostFloat;
 };
 
@@ -362,44 +358,74 @@
     }
 }
 
-LayoutUnit FloatingObjects::logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode, LayoutUnit *heightRemaining)
+static inline ShapeOutsideInfo* shapeInfoForFloat(const FloatingObject* floatingObject, const RenderBlockFlow* containingBlock, LayoutUnit lineTop, LayoutUnit lineBottom)
 {
-    LayoutUnit offset = fixedOffset;
-    ComputeFloatOffsetAdapter<FloatingObject::FloatLeft> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), offset);
-    placedFloatsTree().allOverlapsWithAdapter(adapter);
-
-    if (heightRemaining)
-        *heightRemaining = adapter.getHeightRemaining();
-
-    const FloatingObject* outermostFloat = adapter.outermostFloat();
-    if (offsetMode == ShapeOutsideFloatShapeOffset && outermostFloat) {
-        if (ShapeOutsideInfo* shapeOutside = outermostFloat->renderer()->shapeOutsideInfo()) {
-            shapeOutside->updateDeltasForContainingBlockLine(m_renderer, outermostFloat, logicalTop, logicalHeight);
-            offset += shapeOutside->rightMarginBoxDelta();
+    if (floatingObject) {
+        if (ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo()) {
+            shapeOutside->updateDeltasForContainingBlockLine(containingBlock, floatingObject, lineTop, lineBottom - lineTop);
+            return shapeOutside;
         }
     }
 
-    return offset;
+    return 0;
 }
 
-LayoutUnit FloatingObjects::logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode, LayoutUnit *heightRemaining)
+template<>
+inline LayoutUnit ComputeFloatOffsetAdapter<FloatingObject::FloatLeft>::shapeOffset() const
 {
-    LayoutUnit offset = fixedOffset;
-    ComputeFloatOffsetAdapter<FloatingObject::FloatRight> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), offset);
+    if (ShapeOutsideInfo* shapeOutside = shapeInfoForFloat(m_outermostFloat, m_renderer, m_lineTop, m_lineBottom))
+        return m_offset + shapeOutside->rightMarginBoxDelta();
+
+    return m_offset;
+}
+
+template<>
+inline LayoutUnit ComputeFloatOffsetAdapter<FloatingObject::FloatRight>::shapeOffset() const
+{
+    if (ShapeOutsideInfo* shapeOutside = shapeInfoForFloat(m_outermostFloat, m_renderer, m_lineTop, m_lineBottom))
+        return m_offset + shapeOutside->leftMarginBoxDelta();
+
+    return m_offset;
+}
+
+LayoutUnit FloatingObjects::logicalLeftOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit *heightRemaining)
+{
+    int logicalTopAsInt = roundToInt(logicalTop);
+    ComputeFloatOffsetAdapter<FloatingObject::FloatLeft> adapter(m_renderer, logicalTopAsInt, logicalTopAsInt, fixedOffset);
     placedFloatsTree().allOverlapsWithAdapter(adapter);
 
     if (heightRemaining)
-        *heightRemaining = adapter.getHeightRemaining();
+        *heightRemaining = adapter.heightRemaining();
 
-    const FloatingObject* outermostFloat = adapter.outermostFloat();
-    if (offsetMode == ShapeOutsideFloatShapeOffset && outermostFloat) {
-        if (ShapeOutsideInfo* shapeOutside = outermostFloat->renderer()->shapeOutsideInfo()) {
-            shapeOutside->updateDeltasForContainingBlockLine(m_renderer, outermostFloat, logicalTop, logicalHeight);
-            offset += shapeOutside->leftMarginBoxDelta();
-        }
-    }
+    return adapter.offset();
+}
 
-    return min(fixedOffset, offset);
+LayoutUnit FloatingObjects::logicalRightOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit *heightRemaining)
+{
+    int logicalTopAsInt = roundToInt(logicalTop);
+    ComputeFloatOffsetAdapter<FloatingObject::FloatRight> adapter(m_renderer, logicalTopAsInt, logicalTopAsInt, fixedOffset);
+    placedFloatsTree().allOverlapsWithAdapter(adapter);
+
+    if (heightRemaining)
+        *heightRemaining = adapter.heightRemaining();
+
+    return min(fixedOffset, adapter.offset());
+}
+
+LayoutUnit FloatingObjects::logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight)
+{
+    ComputeFloatOffsetAdapter<FloatingObject::FloatLeft> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), fixedOffset);
+    placedFloatsTree().allOverlapsWithAdapter(adapter);
+
+    return adapter.shapeOffset();
+}
+
+LayoutUnit FloatingObjects::logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight)
+{
+    ComputeFloatOffsetAdapter<FloatingObject::FloatRight> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), fixedOffset);
+    placedFloatsTree().allOverlapsWithAdapter(adapter);
+
+    return min(fixedOffset, adapter.shapeOffset());
 }
 
 FloatingObjects::FloatBottomCachedValue::FloatBottomCachedValue()
@@ -457,7 +483,7 @@
 }
 
 template <FloatingObject::Type FloatTypeValue>
-LayoutUnit ComputeFloatOffsetAdapter<FloatTypeValue>::getHeightRemaining() const
+LayoutUnit ComputeFloatOffsetAdapter<FloatTypeValue>::heightRemaining() const
 {
     return m_outermostFloat ? m_renderer->logicalBottomForFloat(m_outermostFloat) - m_lineTop : LayoutUnit(1);
 }
diff --git a/Source/core/rendering/FloatingObjects.h b/Source/core/rendering/FloatingObjects.h
index 570537c..ca3beb1 100644
--- a/Source/core/rendering/FloatingObjects.h
+++ b/Source/core/rendering/FloatingObjects.h
@@ -35,6 +35,7 @@
 class RenderBlockFlow;
 class RenderBox;
 
+// FIXME this should be removed once RenderBlockFlow::nextFloatLogicalBottomBelow doesn't need it anymore. (Bug 123931)
 enum ShapeOutsideFloatOffsetMode { ShapeOutsideFloatShapeOffset, ShapeOutsideFloatMarginBoxOffset };
 
 class FloatingObject {
@@ -144,8 +145,12 @@
     bool hasRightObjects() const { return m_rightObjectsCount > 0; }
     const FloatingObjectSet& set() const { return m_set; }
     void clearLineBoxTreePointers();
-    LayoutUnit logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatShapeOffset, LayoutUnit* heightRemaining = 0);
-    LayoutUnit logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatShapeOffset, LayoutUnit* heightRemaining = 0);
+
+    LayoutUnit logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight);
+    LayoutUnit logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight);
+
+    LayoutUnit logicalLeftOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit* heightRemaining);
+    LayoutUnit logicalRightOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit* heightRemaining);
 
     LayoutUnit lowestFloatLogicalBottom(FloatingObject::Type);
 
diff --git a/Source/core/rendering/FlowThreadController.cpp b/Source/core/rendering/FlowThreadController.cpp
index d7f0559..521085e 100644
--- a/Source/core/rendering/FlowThreadController.cpp
+++ b/Source/core/rendering/FlowThreadController.cpp
@@ -117,7 +117,7 @@
 {
     ASSERT(contentNode && contentNode->isElementNode());
     HashMap<const Node*, RenderNamedFlowThread*>::iterator it = m_mapNamedFlowContentNodes.find(contentNode);
-    ASSERT(it != m_mapNamedFlowContentNodes.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(it != m_mapNamedFlowContentNodes.end());
     ASSERT(it->value);
     ASSERT(it->value->hasContentNode(contentNode));
     it->value->unregisterNamedFlowContentNode(contentNode);
diff --git a/Source/core/rendering/InlineBox.cpp b/Source/core/rendering/InlineBox.cpp
index a6713e3..0e1e21e 100644
--- a/Source/core/rendering/InlineBox.cpp
+++ b/Source/core/rendering/InlineBox.cpp
@@ -22,7 +22,7 @@
 
 #include "core/rendering/InlineFlowBox.h"
 #include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RootInlineBox.h"
 #include "platform/Partitions.h"
 #include "platform/fonts/FontMetrics.h"
@@ -316,7 +316,7 @@
 {
     if (!renderer()->style()->isFlippedBlocksWritingMode())
         return FloatPoint(x(), y());
-    RenderBlock* block = root()->block();
+    RenderBlockFlow* block = root()->block();
     if (block->style()->isHorizontalWritingMode())
         return FloatPoint(x(), block->height() - height() - y());
     else
diff --git a/Source/core/rendering/InlineIterator.h b/Source/core/rendering/InlineIterator.h
index 2aa0c6f..cbd866e 100644
--- a/Source/core/rendering/InlineIterator.h
+++ b/Source/core/rendering/InlineIterator.h
@@ -71,6 +71,8 @@
     }
 
     RenderObject* object() const { return m_obj; }
+    void setObject(RenderObject* object) { m_obj = object; }
+
     unsigned offset() const { return m_pos; }
     RenderObject* root() const { return m_root; }
 
@@ -96,22 +98,22 @@
 
 private:
     RenderObject* m_root;
-
-    // FIXME: These should be private.
-public:
     RenderObject* m_obj;
+
+// FIXME: These should be private.
+public:
     unsigned m_pos;
     int m_nextBreakablePosition;
 };
 
 inline bool operator==(const InlineIterator& it1, const InlineIterator& it2)
 {
-    return it1.m_pos == it2.m_pos && it1.m_obj == it2.m_obj;
+    return it1.m_pos == it2.m_pos && it1.object() == it2.object();
 }
 
 inline bool operator!=(const InlineIterator& it1, const InlineIterator& it2)
 {
-    return it1.m_pos != it2.m_pos || it1.m_obj != it2.m_obj;
+    return it1.m_pos != it2.m_pos || it1.object() != it2.object();
 }
 
 static inline WTF::Unicode::Direction embedCharFromDirection(TextDirection dir, EUnicodeBidi unicodeBidi)
@@ -420,15 +422,15 @@
 }
 
 template <>
-inline bool InlineBidiResolver::isEndOfParagraph(const InlineIterator& end)
+inline bool InlineBidiResolver::isEndOfLine(const InlineIterator& end)
 {
-    bool inEndOfParagraph = m_current == end || m_current.atEnd() || (inIsolate() && m_current.m_obj == end.m_obj);
-    if (inIsolate() && inEndOfParagraph) {
-        m_current.moveTo(m_current.m_obj, end.m_pos, m_current.m_nextBreakablePosition);
+    bool inEndOfLine = m_current == end || m_current.atEnd() || (inIsolate() && m_current.object() == end.object());
+    if (inIsolate() && inEndOfLine) {
+        m_current.moveTo(m_current.object(), end.m_pos, m_current.m_nextBreakablePosition);
         m_last = m_current;
         updateStatusLastFromCurrentDirection(WTF::Unicode::OtherNeutral);
     }
-    return inEndOfParagraph;
+    return inEndOfLine;
 }
 
 static inline bool isIsolatedInline(RenderObject* object)
@@ -466,7 +468,7 @@
 
 // FIXME: This belongs on InlineBidiResolver, except it's a template specialization
 // of BidiResolver which knows nothing about RenderObjects.
-static inline void addPlaceholderRunForIsolatedInline(InlineBidiResolver& resolver, RenderObject* obj, unsigned pos)
+static inline BidiRun* addPlaceholderRunForIsolatedInline(InlineBidiResolver& resolver, RenderObject* obj, unsigned pos)
 {
     ASSERT(obj);
     BidiRun* isolatedRun = new BidiRun(pos, pos, obj, resolver.context(), resolver.dir());
@@ -474,8 +476,7 @@
     // FIXME: isolatedRuns() could be a hash of object->run and then we could cheaply
     // ASSERT here that we didn't create multiple objects for the same inline.
     resolver.isolatedRuns().append(isolatedRun);
-    LineMidpointState& lineMidpointState = resolver.midpointState();
-    resolver.setMidpointStateForIsolatedRun(isolatedRun, lineMidpointState);
+    return isolatedRun;
 }
 
 static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
@@ -488,50 +489,6 @@
     AppendingRunsForObject
 };
 
-static void adjustMidpointsAndAppendRunsForObjectIfNeeded(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, AppendRunBehavior behavior = AppendingFakeRun, BidiRunList<BidiRun>* runs = 0)
-{
-    if (start > end || RenderBlockFlow::shouldSkipCreatingRunsForObject(obj))
-        return;
-
-    LineMidpointState& lineMidpointState = resolver.midpointState();
-    bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
-    InlineIterator nextMidpoint;
-    if (haveNextMidpoint)
-        nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
-    if (lineMidpointState.betweenMidpoints) {
-        if (!(haveNextMidpoint && nextMidpoint.m_obj == obj))
-            return;
-        // This is a new start point. Stop ignoring objects and
-        // adjust our start.
-        lineMidpointState.betweenMidpoints = false;
-        start = nextMidpoint.m_pos;
-        lineMidpointState.currentMidpoint++;
-        if (start < end)
-            return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, resolver, behavior, runs);
-    } else {
-        if (!haveNextMidpoint || (obj != nextMidpoint.m_obj)) {
-            if (behavior == AppendingFakeRun)
-                return;
-            runs->addRun(createRun(start, end, obj, resolver));
-            return;
-        }
-
-        // An end midpoint has been encountered within our object. We
-        // need to go ahead and append a run with our endpoint.
-        if (nextMidpoint.m_pos + 1 <= end) {
-            lineMidpointState.betweenMidpoints = true;
-            lineMidpointState.currentMidpoint++;
-            if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't nclude any of it.
-                if (nextMidpoint.m_pos + 1 > start && behavior == AppendingRunsForObject)
-                    runs->addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
-                return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, nextMidpoint.m_pos + 1, end, resolver, behavior, runs);
-            }
-        } else if (behavior == AppendingRunsForObject) {
-            runs->addRun(createRun(start, end, obj, resolver));
-        }
-    }
-}
-
 class IsolateTracker {
 public:
     explicit IsolateTracker(unsigned nestedIsolateCount)
@@ -540,6 +497,11 @@
     {
     }
 
+    void setMidpointStateForRootIsolate(const LineMidpointState& midpointState)
+    {
+        m_midpointStateForRootIsolate = midpointState;
+    }
+
     void enterIsolate() { m_nestedIsolateCount++; }
     void exitIsolate()
     {
@@ -554,7 +516,6 @@
     void embed(WTF::Unicode::Direction, BidiEmbeddingSource) { }
     void commitExplicitEmbedding() { }
 
-
     void addFakeRunIfNecessary(RenderObject* obj, unsigned pos, unsigned end, InlineBidiResolver& resolver)
     {
         // We only need to add a fake run for a given isolated span once during each call to createBidiRunsForLine.
@@ -563,11 +524,10 @@
         if (RenderBlockFlow::shouldSkipCreatingRunsForObject(obj))
             return;
         if (!m_haveAddedFakeRunForRootIsolate) {
-            addPlaceholderRunForIsolatedInline(resolver, obj, pos);
+            BidiRun* run = addPlaceholderRunForIsolatedInline(resolver, obj, pos);
+            resolver.setMidpointStateForIsolatedRun(run, m_midpointStateForRootIsolate);
             m_haveAddedFakeRunForRootIsolate = true;
         }
-        adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, pos, end, resolver);
-
         // obj and pos together denote a single position in the inline, from which the parsing of the isolate will start.
         // We don't need to mark the end of the run because this is implicit: it is either endOfLine or the end of the
         // isolate, when we call createBidiRunsForLine it will stop at whichever comes first.
@@ -576,8 +536,65 @@
 private:
     unsigned m_nestedIsolateCount;
     bool m_haveAddedFakeRunForRootIsolate;
+    LineMidpointState m_midpointStateForRootIsolate;
 };
 
+static void inline appendRunObjectIfNecessary(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, AppendRunBehavior behavior, IsolateTracker& tracker)
+{
+    if (behavior == AppendingFakeRun)
+        tracker.addFakeRunIfNecessary(obj, start, end, resolver);
+    else
+        resolver.runs().addRun(createRun(start, end, obj, resolver));
+}
+
+static void adjustMidpointsAndAppendRunsForObjectIfNeeded(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, AppendRunBehavior behavior, IsolateTracker& tracker)
+{
+    if (start > end || RenderBlockFlow::shouldSkipCreatingRunsForObject(obj))
+        return;
+
+    LineMidpointState& lineMidpointState = resolver.midpointState();
+    bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
+    InlineIterator nextMidpoint;
+    if (haveNextMidpoint)
+        nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
+    if (lineMidpointState.betweenMidpoints) {
+        if (!(haveNextMidpoint && nextMidpoint.object() == obj))
+            return;
+        // This is a new start point. Stop ignoring objects and
+        // adjust our start.
+        lineMidpointState.betweenMidpoints = false;
+        start = nextMidpoint.m_pos;
+        lineMidpointState.currentMidpoint++;
+        if (start < end)
+            return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, resolver, behavior, tracker);
+    } else {
+        if (!haveNextMidpoint || (obj != nextMidpoint.object())) {
+            appendRunObjectIfNecessary(obj, start, end, resolver, behavior, tracker);
+            return;
+        }
+
+        // An end midpoint has been encountered within our object. We
+        // need to go ahead and append a run with our endpoint.
+        if (nextMidpoint.m_pos + 1 <= end) {
+            lineMidpointState.betweenMidpoints = true;
+            lineMidpointState.currentMidpoint++;
+            if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't nclude any of it.
+                if (nextMidpoint.m_pos + 1 > start)
+                    appendRunObjectIfNecessary(obj, start, nextMidpoint.m_pos + 1, resolver, behavior, tracker);
+                return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, nextMidpoint.m_pos + 1, end, resolver, behavior, tracker);
+            }
+        } else {
+            appendRunObjectIfNecessary(obj, start, end, resolver, behavior, tracker);
+        }
+    }
+}
+
+static inline void addFakeRunIfNecessary(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, IsolateTracker& tracker)
+{
+    tracker.setMidpointStateForRootIsolate(resolver.midpointState());
+    adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, obj->length(), resolver, AppendingFakeRun, tracker);
+}
+
 template <>
 inline void InlineBidiResolver::appendRun()
 {
@@ -587,30 +604,33 @@
         // FIXME: Could this initialize from this->inIsolate() instead of walking up the render tree?
         IsolateTracker isolateTracker(numberOfIsolateAncestors(m_sor));
         int start = m_sor.m_pos;
-        RenderObject* obj = m_sor.m_obj;
-        while (obj && obj != m_eor.m_obj && obj != endOfLine.m_obj) {
+        RenderObject* obj = m_sor.object();
+        while (obj && obj != m_eor.object() && obj != m_endOfRunAtEndOfLine.object()) {
             if (isolateTracker.inIsolate())
-                isolateTracker.addFakeRunIfNecessary(obj, start, obj->length(), *this);
+                addFakeRunIfNecessary(obj, start, obj->length(), *this, isolateTracker);
             else
-                RenderBlockFlow::appendRunsForObject(m_runs, start, obj->length(), obj, *this);
+                adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, obj->length(), *this, AppendingRunsForObject, isolateTracker);
             // FIXME: start/obj should be an InlineIterator instead of two separate variables.
             start = 0;
             obj = bidiNextSkippingEmptyInlines(m_sor.root(), obj, &isolateTracker);
         }
-        if (obj) {
-            unsigned pos = obj == m_eor.m_obj ? m_eor.m_pos : INT_MAX;
-            if (obj == endOfLine.m_obj && endOfLine.m_pos <= pos) {
+        bool isEndOfLine = obj == m_endOfLine.object() && !m_endOfLine.m_pos;
+        if (obj && !isEndOfLine) {
+            unsigned pos = obj == m_eor.object() ? m_eor.m_pos : INT_MAX;
+            if (obj == m_endOfRunAtEndOfLine.object() && m_endOfRunAtEndOfLine.m_pos <= pos) {
                 m_reachedEndOfLine = true;
-                pos = endOfLine.m_pos;
+                pos = m_endOfRunAtEndOfLine.m_pos;
             }
             // It's OK to add runs for zero-length RenderObjects, just don't make the run larger than it should be
             int end = obj->length() ? pos + 1 : 0;
             if (isolateTracker.inIsolate())
-                isolateTracker.addFakeRunIfNecessary(obj, start, end, *this);
+                addFakeRunIfNecessary(obj, start, end, *this, isolateTracker);
             else
-                RenderBlockFlow::appendRunsForObject(m_runs, start, end, obj, *this);
+                adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, *this, AppendingRunsForObject, isolateTracker);
         }
 
+        if (isEndOfLine)
+            m_reachedEndOfLine = true;
         m_eor.increment();
         m_sor = m_eor;
     }
diff --git a/Source/core/rendering/InlineTextBox.cpp b/Source/core/rendering/InlineTextBox.cpp
index f908248..6c9a772 100644
--- a/Source/core/rendering/InlineTextBox.cpp
+++ b/Source/core/rendering/InlineTextBox.cpp
@@ -922,10 +922,8 @@
     // pixel gap, if underline is thick then use a bigger gap.
     const int gap = std::max<int>(1, ceilf(textDecorationThickness / 2.f));
 
-    // According to the specification TextUnderlinePositionAuto should default to 'alphabetic' for horizontal text
-    // and to 'under Left' for vertical text (e.g. japanese). We support only horizontal text for now.
+    // FIXME: We support only horizontal text for now.
     switch (underlinePosition) {
-    case TextUnderlinePositionAlphabetic:
     case TextUnderlinePositionAuto:
         return fontMetrics.ascent() + gap; // Position underline near the alphabetic baseline.
     case TextUnderlinePositionUnder: {
diff --git a/Source/core/rendering/LayoutRectRecorder.cpp b/Source/core/rendering/LayoutRectRecorder.cpp
new file mode 100644
index 0000000..5544d5d
--- /dev/null
+++ b/Source/core/rendering/LayoutRectRecorder.cpp
@@ -0,0 +1,69 @@
+/*
+ * 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/LayoutRectRecorder.h"
+
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+LayoutRectRecorder::LayoutRectRecorder(RenderObject& object, bool skipRecording)
+    : m_object(object)
+    , m_repaintContainer(0)
+    , m_skipRecording(skipRecording)
+{
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+        return;
+    if (m_skipRecording)
+        return;
+
+    m_repaintContainer = m_object.containerForRepaint();
+
+    // FIXME: This will do more work then needed in some cases. The isEmpty will
+    // return true if width <=0 or height <=0 so if we have a 0x0 item it will
+    // set the old rect each time it comes through here until it's given a size.
+    if (m_object.everHadLayout() && m_object.oldRepaintRect().isEmpty()) {
+        m_object.setOldRepaintRect(m_object.clippedOverflowRectForRepaint(m_repaintContainer));
+    }
+}
+
+LayoutRectRecorder::~LayoutRectRecorder()
+{
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+        return;
+    if (m_skipRecording)
+        return;
+
+    m_object.setNewRepaintRect(m_object.clippedOverflowRectForRepaint(m_repaintContainer));
+}
+
+} // namespace WebCore
+
diff --git a/Source/core/rendering/RenderingConfiguration.h b/Source/core/rendering/LayoutRectRecorder.h
similarity index 73%
rename from Source/core/rendering/RenderingConfiguration.h
rename to Source/core/rendering/LayoutRectRecorder.h
index dc1af6d..25d9869 100644
--- a/Source/core/rendering/RenderingConfiguration.h
+++ b/Source/core/rendering/LayoutRectRecorder.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,33 +28,30 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderingConfiguration_h
-#define RenderingConfiguration_h
+#ifndef LayoutRectRecorder_h
+#define LayoutRectRecorder_h
 
+#include "platform/geometry/LayoutRect.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
-class Document;
+class RenderLayerModelObject;
+class RenderObject;
 
-class RenderingConfiguration {
-    WTF_MAKE_NONCOPYABLE(RenderingConfiguration);
+class LayoutRectRecorder {
+    WTF_MAKE_NONCOPYABLE(LayoutRectRecorder);
 public:
-    RenderingConfiguration();
-    ~RenderingConfiguration();
-
-    void update(Document&);
-
-    bool inQuirksMode() const { return m_inQuirksMode; }
-    bool paginated() const { return m_paginated; }
-    bool printing() const { return m_printing; }
+    LayoutRectRecorder(RenderObject&, bool skipRecording = false);
+    ~LayoutRectRecorder();
 
 private:
-    bool m_inQuirksMode;
-    bool m_paginated;
-    bool m_printing;
+    RenderObject& m_object;
+    RenderLayerModelObject* m_repaintContainer;
+    unsigned m_skipRecording : 1;
 };
 
-}
+} // namespace WebCore
 
-#endif // RenderingConfiguration_h
+#endif // LayoutRectRecorder_h
+
diff --git a/Source/core/rendering/LayoutState.cpp b/Source/core/rendering/LayoutState.cpp
index fc87b5a..088c0d8 100644
--- a/Source/core/rendering/LayoutState.cpp
+++ b/Source/core/rendering/LayoutState.cpp
@@ -127,7 +127,7 @@
 
     // If we have a new grid to track, then add it to our set.
     if (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isRenderBlockFlow())
-        establishLineGrid(toRenderBlock(renderer));
+        establishLineGrid(toRenderBlockFlow(renderer));
 
     // FIXME: <http://bugs.webkit.org/show_bug.cgi?id=13443> Apply control clip if present.
 }
@@ -204,13 +204,13 @@
     m_lineGridPaginationOrigin = m_next->m_lineGridPaginationOrigin;
 }
 
-void LayoutState::establishLineGrid(RenderBlock* block)
+void LayoutState::establishLineGrid(RenderBlockFlow* block)
 {
     // First check to see if this grid has been established already.
     if (m_lineGrid) {
         if (m_lineGrid->style()->lineGrid() == block->style()->lineGrid())
             return;
-        RenderBlock* currentGrid = m_lineGrid;
+        RenderBlockFlow* currentGrid = m_lineGrid;
         for (LayoutState* currentState = m_next; currentState; currentState = currentState->m_next) {
             if (currentState->m_lineGrid == currentGrid)
                 continue;
diff --git a/Source/core/rendering/LayoutState.h b/Source/core/rendering/LayoutState.h
index 2fb1e07..16aa5b6 100644
--- a/Source/core/rendering/LayoutState.h
+++ b/Source/core/rendering/LayoutState.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class RenderBlock;
+class RenderBlockFlow;
 class RenderBox;
 class RenderObject;
 class RenderFlowThread;
@@ -81,7 +81,7 @@
     LayoutUnit pageLogicalHeight() const { return m_pageLogicalHeight; }
     bool pageLogicalHeightChanged() const { return m_pageLogicalHeightChanged; }
 
-    RenderBlock* lineGrid() const { return m_lineGrid; }
+    RenderBlockFlow* lineGrid() const { return m_lineGrid; }
     LayoutSize lineGridOffset() const { return m_lineGridOffset; }
     LayoutSize lineGridPaginationOrigin() const { return m_lineGridPaginationOrigin; }
 
@@ -96,7 +96,7 @@
 #endif
 private:
     void propagateLineGridInfo(RenderBox*);
-    void establishLineGrid(RenderBlock*);
+    void establishLineGrid(RenderBlockFlow*);
 
     void computeLineGridPaginationOrigin(RenderBox*);
 
@@ -113,7 +113,7 @@
     // If the enclosing pagination model is a column model, then this will store column information for easy retrieval/manipulation.
     ColumnInfo* m_columnInfo;
     // The current line grid that we're snapping to and the offset of the start of the grid.
-    RenderBlock* m_lineGrid;
+    RenderBlockFlow* m_lineGrid;
     LayoutState* m_next;
     ShapeInsideInfo* m_shapeInsideInfo;
 
diff --git a/Source/core/rendering/PointerEventsHitRules.cpp b/Source/core/rendering/PointerEventsHitRules.cpp
index 8ae6aa7..b0fd42c 100644
--- a/Source/core/rendering/PointerEventsHitRules.cpp
+++ b/Source/core/rendering/PointerEventsHitRules.cpp
@@ -32,7 +32,7 @@
     if (request.svgClipContent())
         pointerEvents = PE_FILL;
 
-    if (hitTesting == SVG_PATH_HITTESTING) {
+    if (hitTesting == SVG_GEOMETRY_HITTESTING) {
         switch (pointerEvents)
         {
             case PE_VISIBLE_PAINTED:
diff --git a/Source/core/rendering/PointerEventsHitRules.h b/Source/core/rendering/PointerEventsHitRules.h
index bc0e24c..aba46f9 100644
--- a/Source/core/rendering/PointerEventsHitRules.h
+++ b/Source/core/rendering/PointerEventsHitRules.h
@@ -29,7 +29,7 @@
 public:
     enum EHitTesting {
         SVG_IMAGE_HITTESTING,
-        SVG_PATH_HITTESTING,
+        SVG_GEOMETRY_HITTESTING,
         SVG_TEXT_HITTESTING
     };
 
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index 93a4947..aaff934 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -43,12 +43,12 @@
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderCombineText.h"
 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
 #include "core/rendering/RenderFlexibleBox.h"
-#include "core/rendering/RenderGrid.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderMarquee.h"
@@ -128,11 +128,9 @@
         if (!horizontalLayoutOverflowChanged && !verticalLayoutOverflowChanged)
             return;
 
-        if (FrameView* frameView = m_block->frameView()) {
-            RefPtr<OverflowEvent> event = OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow);
-            event->setTarget(m_block->node());
-            frameView->scheduleOverflowEvent(event);
-        }
+        RefPtr<OverflowEvent> event = OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow);
+        event->setTarget(m_block->node());
+        m_block->document().enqueueAnimationFrameEvent(event.release());
     }
 
 private:
@@ -231,9 +229,6 @@
 
     m_lineBoxes.deleteLineBoxes();
 
-    if (lineGridBox())
-        lineGridBox()->destroy();
-
     if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
         gDelayedUpdateScrollInfoSet->remove(this);
 
@@ -875,11 +870,6 @@
         cache->recomputeIsIgnored(this);
 }
 
-RootInlineBox* RenderBlock::createRootInlineBox()
-{
-    return new RootInlineBox(this);
-}
-
 RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
 {
     RootInlineBox* rootBox = createRootInlineBox();
@@ -980,6 +970,7 @@
     // Remove all the information in the flow thread associated with the leftover anonymous block.
     child->removeFromRenderFlowThread();
 
+    child->setParent(0);
     child->setPreviousSibling(0);
     child->setNextSibling(0);
 
@@ -1241,6 +1232,7 @@
 void RenderBlock::layout()
 {
     OverflowEventDispatcher dispatcher(this);
+    LayoutRectRecorder recorder(*this);
 
     // Update our first letter info now.
     updateFirstLetter();
@@ -1374,7 +1366,7 @@
 
     // Compute the maximum logical height content may cause this block to expand to
     // FIXME: These should eventually use the const computeLogicalHeight rather than updateLogicalHeight
-    setLogicalHeight(LayoutUnit::max() / 2);
+    setLogicalHeight(RenderFlowThread::maxLogicalHeight());
     updateLogicalHeight();
 
     computeShapeSize();
@@ -1392,7 +1384,14 @@
 void RenderBlock::computeShapeSize()
 {
     ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
-    if (shapeInsideInfo) {
+    if (!shapeInsideInfo)
+        return;
+
+    if (isRenderNamedFlowFragment()) {
+        ShapeInsideInfo* parentShapeInsideInfo = toRenderBlock(parent())->shapeInsideInfo();
+        ASSERT(parentShapeInsideInfo);
+        shapeInsideInfo->setShapeSize(parentShapeInsideInfo->shapeSize().width(), parentShapeInsideInfo->shapeSize().height());
+    } else {
         bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
         shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
     }
@@ -1506,14 +1505,6 @@
             m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
     }
 
-    // Allow our overflow to catch cases where the caret in an empty editable element with negative text indent needs to get painted.
-    LayoutUnit textIndent = textIndentOffset();
-    if (textIndent < 0) {
-        LayoutRect clientRect(noOverflowRect());
-        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.
     addVisualEffectOverflow();
 
@@ -1544,12 +1535,8 @@
         positionedObject = *it;
 
         // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
-        if (positionedObject->style()->position() != FixedPosition) {
-            LayoutUnit x = positionedObject->x();
-            if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
-                x -= verticalScrollbarWidth();
-            addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
-        }
+        if (positionedObject->style()->position() != FixedPosition)
+            addOverflowFromChild(positionedObject, LayoutSize(positionedObject->x(), positionedObject->y()));
     }
 }
 
@@ -1581,7 +1568,7 @@
     if (region)
         blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
 
-    LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, logicalHeightForChild(child));
+    LayoutUnit startOff = startOffsetForLineInRegion(blockOffset, false, region, logicalHeightForChild(child));
 
     if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
         if (childMarginStart < 0)
@@ -2163,6 +2150,11 @@
         return;
     }
 
+    if (paintPhase == PaintPhaseClippingMask && style()->visibility() == VISIBLE) {
+        paintClippingMask(paintInfo, paintOffset);
+        return;
+    }
+
     // We're done.  We don't bother painting any children.
     if (paintPhase == PaintPhaseBlockBackground || paintInfo.paintRootBackgroundOnly())
         return;
@@ -2393,14 +2385,14 @@
     }
 }
 
-static LayoutUnit blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
+LayoutUnit RenderBlock::blockDirectionOffset(const LayoutSize& offsetFromBlock) const
 {
-    return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
+    return isHorizontalWritingMode() ? offsetFromBlock.height() : offsetFromBlock.width();
 }
 
-static LayoutUnit inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
+LayoutUnit RenderBlock::inlineDirectionOffset(const LayoutSize& offsetFromBlock) const
 {
-    return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
+    return isHorizontalWritingMode() ? offsetFromBlock.width() : offsetFromBlock.height();
 }
 
 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
@@ -2440,14 +2432,14 @@
 
     if (hasColumns() || hasTransform() || style()->columnSpan()) {
         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
-        lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
+        lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
         return result;
     }
 
     if (childrenInline())
-        result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
+        result = toRenderBlockFlow(this)->inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
     else
         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
 
@@ -2458,61 +2450,6 @@
     return result;
 }
 
-GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
-                                          LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
-{
-    GapRects result;
-
-    bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
-
-    if (!firstLineBox()) {
-        if (containsStart) {
-            // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
-            // case.
-            lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
-            lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
-            lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
-        }
-        return result;
-    }
-
-    RootInlineBox* lastSelectedLine = 0;
-    RootInlineBox* curr;
-    for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
-
-    // Now paint the gaps for the lines.
-    for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
-        LayoutUnit selTop =  curr->selectionTopAdjustedForPrecedingBlock();
-        LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
-
-        if (!containsStart && !lastSelectedLine &&
-            selectionState() != SelectionStart && selectionState() != SelectionBoth)
-            result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
-                                                 selTop, paintInfo));
-
-        LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
-        logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
-        LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
-        if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
-            || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
-            result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
-
-        lastSelectedLine = curr;
-    }
-
-    if (containsStart && !lastSelectedLine)
-        // VisibleSelection must start just after our last line.
-        lastSelectedLine = lastRootBox();
-
-    if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
-        // Go ahead and update our lastY to be the bottom of the last selected line.
-        lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
-        lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
-        lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
-    }
-    return result;
-}
-
 GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
                                          LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
 {
@@ -2564,7 +2501,7 @@
             // Update lastLogicalTop to be just underneath the object.  lastLogicalLeft and lastLogicalRight extend as far as
             // they can without bumping into floating or positioned objects.  Ideally they will go right up
             // to the border of the root selection block.
-            lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
+            lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + curr->logicalBottom();
             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
             lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
         } else if (childState != SelectionNone)
@@ -2579,7 +2516,7 @@
                                           LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo)
 {
     LayoutUnit logicalTop = lastLogicalTop;
-    LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
+    LayoutUnit logicalHeight = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalBottom - logicalTop;
     if (logicalHeight <= 0)
         return LayoutRect();
 
@@ -2599,9 +2536,9 @@
 LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
                                                 RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
 {
-    LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
+    LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
     LayoutUnit rootBlockLogicalLeft = max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
-    LayoutUnit rootBlockLogicalRight = min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + floorToInt(logicalLeft), min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
+    LayoutUnit rootBlockLogicalRight = min(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + floorToInt(logicalLeft), min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
     if (rootBlockLogicalWidth <= 0)
         return LayoutRect();
@@ -2615,8 +2552,8 @@
 LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
                                                  RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
 {
-    LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
-    LayoutUnit rootBlockLogicalLeft = max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + floorToInt(logicalRight), max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
+    LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
+    LayoutUnit rootBlockLogicalLeft = max(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + floorToInt(logicalRight), max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
     LayoutUnit rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
     if (rootBlockLogicalWidth <= 0)
@@ -4779,7 +4716,7 @@
 
     if (RenderStyle::compare(firstLetter->style(), pseudoStyle) == Reattach) {
         // The first-letter renderer needs to be replaced. Create a new renderer of the right type.
-        RenderObject* newFirstLetter;
+        RenderBoxModelObject* newFirstLetter;
         if (pseudoStyle->display() == INLINE)
             newFirstLetter = RenderInline::createAnonymous(&document());
         else
@@ -4795,16 +4732,12 @@
             newFirstLetter->addChild(child, 0);
         }
 
-        RenderTextFragment* remainingText = 0;
         RenderObject* nextSibling = firstLetter->nextSibling();
-        RenderObject* remainingTextObject = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText();
-        if (remainingTextObject && remainingTextObject->isText() && toRenderText(remainingTextObject)->isTextFragment())
-            remainingText = toRenderTextFragment(remainingTextObject);
-        if (remainingText) {
+        if (RenderTextFragment* remainingText = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText()) {
             ASSERT(remainingText->isAnonymous() || remainingText->node()->renderer() == remainingText);
             // Replace the old renderer with the new one.
             remainingText->setFirstLetter(newFirstLetter);
-            toRenderBoxModelObject(newFirstLetter)->setFirstLetterRemainingText(remainingText);
+            newFirstLetter->setFirstLetterRemainingText(remainingText);
         }
         // To prevent removal of single anonymous block in RenderBlock::removeChild and causing
         // |nextSibling| to go stale, we remove the old first letter using removeChildNode first.
@@ -4824,10 +4757,15 @@
 static inline unsigned firstLetterLength(const String& text)
 {
     unsigned length = 0;
+    bool punctuationOpen = false;
 
     // Account for leading spaces and punctuation.
-    while (length < text.length() && shouldSkipForFirstLetter((text)[length]))
+    while (length < text.length() && shouldSkipForFirstLetter((text)[length])) {
+        if (isPunctuationForFirstLetter((text)[length]))
+            punctuationOpen = true;
+
         length++;
+    }
 
     // Bail if we didn't find a letter
     if (text.length() && length == text.length())
@@ -4836,6 +4774,9 @@
     // Account for first letter.
     length++;
 
+    if (!punctuationOpen)
+        return length;
+
     // Keep looking for whitespace and allowed punctuation, but avoid
     // accumulating just whitespace into the :first-letter.
     for (unsigned scanLength = length; scanLength < text.length(); ++scanLength) {
@@ -5648,23 +5589,6 @@
     return flowThread->regionAtBlockOffset(offsetFromLogicalTopOfFirstPage() + blockOffset, true);
 }
 
-void RenderBlock::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
-{
-    if (child->style()->isOriginalDisplayInlineType())
-        setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
-    else
-        setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
-}
-
-void RenderBlock::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
-{
-    if (flowThreadContainingBlock()) {
-        // Shift the inline position to exclude the region offset.
-        inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
-    }
-    child->layer()->setStaticInlinePosition(inlinePosition);
-}
-
 bool RenderBlock::logicalWidthChangedInRegions(RenderFlowThread* flowThread) const
 {
     if (!flowThread || !flowThread->hasValidRegionInfo())
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index c771f44..74be88c 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -146,8 +146,6 @@
 
     RootInlineBox* createAndAppendRootInlineBox();
 
-    bool generatesLineBoxesForInlineChild(RenderObject*);
-
     void markShapeInsideDescendantsForLayout();
     void markPositionedObjectsForLayout();
     // FIXME: Do we really need this to be virtual? It's just so we can call this on
@@ -159,41 +157,41 @@
 
     // Versions that can compute line offsets with the region and page offset passed in. Used for speed to avoid having to
     // compute the region all over again when you already know it.
-    LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+    LayoutUnit availableLogicalWidthForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return max<LayoutUnit>(0, logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight)
-            - logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight));
+        return max<LayoutUnit>(0, logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
+            - logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight));
     }
-    LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+    LayoutUnit logicalRightOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(region), shouldIndentText, 0, logicalHeight);
+        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(region), shouldIndentText, logicalHeight);
     }
-    LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+    LayoutUnit logicalLeftOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(region), shouldIndentText, 0, logicalHeight);
+        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(region), shouldIndentText, logicalHeight);
     }
-    LayoutUnit startOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+    LayoutUnit startOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight);
+        return style()->isLeftToRightDirection() ? logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
+            : logicalWidth() - logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight);
     }
-    LayoutUnit endOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+    LayoutUnit endOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight);
+        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
+            : logicalWidth() - logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight);
     }
 
     LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
     {
-        return availableLogicalWidthForLine(position, shouldIndentText, regionAtBlockOffset(position), logicalHeight);
+        return availableLogicalWidthForLineInRegion(position, shouldIndentText, regionAtBlockOffset(position), logicalHeight);
     }
     LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
     {
-        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(position), shouldIndentText, 0, logicalHeight);
+        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(position), shouldIndentText, logicalHeight);
     }
     LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
     {
-        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(position), shouldIndentText, 0, logicalHeight);
+        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(position), shouldIndentText, logicalHeight);
     }
     LayoutUnit pixelSnappedLogicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
     {
@@ -218,7 +216,6 @@
             : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, logicalHeight);
     }
 
-    LayoutUnit startAlignedOffsetForLine(LayoutUnit position, bool shouldIndentText);
     LayoutUnit textIndentOffset() const;
 
     virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE;
@@ -229,6 +226,9 @@
     LayoutPoint flipForWritingModeIncludingColumns(const LayoutPoint&) const;
     void adjustStartEdgeForWritingModeIncludingColumns(LayoutRect&) const;
 
+    LayoutUnit blockDirectionOffset(const LayoutSize& offsetFromBlock) const;
+    LayoutUnit inlineDirectionOffset(const LayoutSize& offsetFromBlock) const;
+
     RootInlineBox* firstRootBox() const { return static_cast<RootInlineBox*>(firstLineBox()); }
     RootInlineBox* lastRootBox() const { return static_cast<RootInlineBox*>(lastLineBox()); }
 
@@ -297,17 +297,6 @@
     LayoutUnit pageLogicalOffset() const { return m_rareData ? m_rareData->m_pageLogicalOffset : LayoutUnit(); }
     void setPageLogicalOffset(LayoutUnit);
 
-    RootInlineBox* lineGridBox() const { return m_rareData ? m_rareData->m_lineGridBox : 0; }
-    void setLineGridBox(RootInlineBox* box)
-    {
-        if (!m_rareData)
-            m_rareData = adoptPtr(new RenderBlockRareData());
-        if (m_rareData->m_lineGridBox)
-            m_rareData->m_lineGridBox->destroy();
-        m_rareData->m_lineGridBox = box;
-    }
-    void layoutLineGridBox();
-
     // Accessors for logical width/height and margins in the containing block's block-flow direction.
     enum ApplyLayoutDeltaMode { ApplyLayoutDelta, DoNotApplyLayoutDelta };
     LayoutUnit logicalWidthForChild(const RenderBox* child) const { return isHorizontalWritingMode() ? child->width() : child->height(); }
@@ -326,8 +315,6 @@
     LayoutUnit collapsedMarginBeforeForChild(const RenderBox* child) const;
     LayoutUnit collapsedMarginAfterForChild(const RenderBox* child) const;
 
-    void updateLogicalWidthForAlignment(const ETextAlign&, const RootInlineBox*, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount);
-
     virtual void updateFirstLetter();
 
     virtual void scrollbarsChanged(bool /*horizontalScrollbarChanged*/, bool /*verticalScrollbarChanged*/) { };
@@ -370,9 +357,6 @@
     LayoutUnit startOffsetForContent() const { return style()->isLeftToRightDirection() ? logicalLeftOffsetForContent() : logicalWidth() - logicalRightOffsetForContent(); }
     LayoutUnit endOffsetForContent() const { return !style()->isLeftToRightDirection() ? logicalLeftOffsetForContent() : logicalWidth() - logicalRightOffsetForContent(); }
 
-    void setStaticInlinePositionForChild(RenderBox*, LayoutUnit blockOffset, LayoutUnit inlinePosition);
-    void updateStaticInlinePositionForChild(RenderBox*, LayoutUnit logicalTop);
-
     LayoutUnit computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* = 0);
 
 #ifndef NDEBUG
@@ -425,21 +409,13 @@
     void paintChild(RenderBox*, PaintInfo&, const LayoutPoint&);
     void paintChildAsInlineBlock(RenderBox*, PaintInfo&, const LayoutPoint&);
 
-    LayoutUnit logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
+    LayoutUnit logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
     {
-        return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatShapeOffset), applyTextIndent);
+        return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
     }
-    LayoutUnit logicalLeftOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
+    LayoutUnit logicalLeftOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
     {
-        return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatShapeOffset), applyTextIndent);
-    }
-    LayoutUnit logicalRightOffsetForLineIgnoringShapeOutside(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
-    {
-        return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatMarginBoxOffset), applyTextIndent);
-    }
-    LayoutUnit logicalLeftOffsetForLineIgnoringShapeOutside(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
-    {
-        return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatMarginBoxOffset), applyTextIndent);
+        return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
     }
 
     virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const;
@@ -501,9 +477,9 @@
 
 private:
     // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
-    virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit*, LayoutUnit, ShapeOutsideFloatOffsetMode) const { return fixedOffset; }
+    virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit) const { return fixedOffset; }
     // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
-    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit*, LayoutUnit, ShapeOutsideFloatOffsetMode) const { return fixedOffset; }
+    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit) const { return fixedOffset; }
     LayoutUnit adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
     LayoutUnit adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
 
@@ -539,7 +515,7 @@
     void insertIntoTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
     static void removeFromTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
 
-    virtual RootInlineBox* createRootInlineBox(); // Subclassed by SVG and Ruby.
+    virtual RootInlineBox* createRootInlineBox() { return 0; } // Subclassed by RenderBlockFlow, SVG and Ruby.
 
     // Called to lay out the legend for a fieldset or the ruby text of a ruby run.
     virtual RenderObject* layoutSpecialExcludedChild(bool /*relayoutChildren*/, SubtreeLayoutScope&) { return 0; }
@@ -592,8 +568,6 @@
     bool isSelectionRoot() const;
     GapRects selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
                            LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* = 0);
-    GapRects inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
-                                 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
     GapRects blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
                                 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
     LayoutRect blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
@@ -708,7 +682,6 @@
         RenderBlockRareData()
             : m_paginationStrut(0)
             , m_pageLogicalOffset(0)
-            , m_lineGridBox(0)
             , m_lineBreakToAvoidWidow(-1)
             , m_didBreakAtLineToAvoidWidow(false)
         {
@@ -717,8 +690,6 @@
         LayoutUnit m_paginationStrut;
         LayoutUnit m_pageLogicalOffset;
 
-        RootInlineBox* m_lineGridBox;
-
         int m_lineBreakToAvoidWidow;
         OwnPtr<ShapeInsideInfo> m_shapeInsideInfo;
         bool m_didBreakAtLineToAvoidWidow : 1;
diff --git a/Source/core/rendering/RenderBlockFlow.cpp b/Source/core/rendering/RenderBlockFlow.cpp
index 2017658..94c09f6 100644
--- a/Source/core/rendering/RenderBlockFlow.cpp
+++ b/Source/core/rendering/RenderBlockFlow.cpp
@@ -36,6 +36,7 @@
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/LineWidth.h"
 #include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderNamedFlowFragment.h"
 #include "core/rendering/RenderNamedFlowThread.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderView.h"
@@ -157,6 +158,17 @@
 {
 }
 
+void RenderBlockFlow::willBeDestroyed()
+{
+    if (lineGridBox())
+        lineGridBox()->destroy();
+
+    if (renderNamedFlowFragment())
+        setRenderNamedFlowFragment(0);
+
+    RenderBlock::willBeDestroyed();
+}
+
 void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
 {
     ASSERT(needsLayout());
@@ -193,6 +205,8 @@
         relayoutChildren = true;
     if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
+    if (!relayoutChildren && isRenderNamedFlowFragmentContainer())
+        relayoutChildren = true;
 
     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
     // our current maximal positive and negative margins. These values are used when we
@@ -1644,6 +1658,26 @@
         parentBlockFlow->markAllDescendantsWithFloatsForLayout();
         parentBlockFlow->markSiblingsWithFloatsForLayout();
     }
+
+    if (renderNamedFlowFragment())
+        renderNamedFlowFragment()->setStyleForNamedFlowFragment(style());
+}
+
+void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
+{
+    if (child->style()->isOriginalDisplayInlineType())
+        setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
+    else
+        setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
+}
+
+void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
+{
+    if (flowThreadContainingBlock()) {
+        // Shift the inline position to exclude the region offset.
+        inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
+    }
+    child->layer()->setStaticInlinePosition(inlinePosition);
 }
 
 void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
@@ -1784,7 +1818,7 @@
 
 bool RenderBlockFlow::containsFloat(RenderBox* renderer) const
 {
-    return m_floatingObjects && m_floatingObjects->set().contains<RenderBox*, FloatingObjectHashTranslator>(renderer);
+    return m_floatingObjects && m_floatingObjects->set().contains<FloatingObjectHashTranslator>(renderer);
 }
 
 void RenderBlockFlow::removeFloatingObjects()
@@ -1808,6 +1842,22 @@
     return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
 }
 
+LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
+{
+    LayoutUnit offset = fixedOffset;
+    if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
+        offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
+    return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
+}
+
+LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
+{
+    LayoutUnit offset = fixedOffset;
+    if (m_floatingObjects && m_floatingObjects->hasRightObjects())
+        offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
+    return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
+}
+
 LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
 {
     RenderBox* childBox = floatingObject->renderer();
@@ -1846,10 +1896,10 @@
     if (childBox->style()->floating() == LeftFloat) {
         LayoutUnit heightRemainingLeft = 1;
         LayoutUnit heightRemainingRight = 1;
-        floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
-        while (logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
+        floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
+        while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
             logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
-            floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
+            floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
             if (insideFlowThread) {
                 // Have to re-evaluate all of our offsets, since they may have changed.
                 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
@@ -1861,10 +1911,10 @@
     } else {
         LayoutUnit heightRemainingLeft = 1;
         LayoutUnit heightRemainingRight = 1;
-        floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
-        while (floatLogicalLeft - logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
+        floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
+        while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
             logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
-            floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
+            floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
             if (insideFlowThread) {
                 // Have to re-evaluate all of our offsets, since they may have changed.
                 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
@@ -1891,7 +1941,7 @@
     } else {
         // Don't insert the object again if it's already in the list
         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(floatBox);
+        FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
         if (it != floatingObjectSet.end())
             return *it;
     }
@@ -1916,9 +1966,6 @@
 
     setLogicalWidthForFloat(newObj.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
 
-    if (ShapeOutsideInfo* shapeOutside = floatBox->shapeOutsideInfo())
-        shapeOutside->setShapeSize(logicalWidthForChild(floatBox), logicalHeightForChild(floatBox));
-
     return m_floatingObjects->add(newObj.release());
 }
 
@@ -1926,7 +1973,7 @@
 {
     if (m_floatingObjects) {
         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(floatBox);
+        FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
         if (it != floatingObjectSet.end()) {
             FloatingObject* floatingObject = *it;
             if (childrenInline()) {
@@ -2077,6 +2124,9 @@
 
         m_floatingObjects->addPlacedObject(floatingObject);
 
+        if (ShapeOutsideInfo* shapeOutside = childBox->shapeOutsideInfo())
+            shapeOutside->setShapeSize(logicalWidthForChild(childBox), logicalHeightForChild(childBox));
+
         // If the child moved, we have to repaint it.
         if (childBox->checkForRepaintDuringLayout())
             childBox->repaintDuringLayoutIfMoved(oldRect);
@@ -2090,7 +2140,7 @@
         return false;
 
     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(renderer);
+    FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(renderer);
     if (it == floatingObjectSet.end())
         return false;
 
@@ -2272,22 +2322,78 @@
     }
 }
 
-LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
+LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
 {
     if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
-        return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
+        return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
 
     return fixedOffset;
 }
 
-LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
+LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
 {
     if (m_floatingObjects && m_floatingObjects->hasRightObjects())
-        return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
+        return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
 
     return fixedOffset;
 }
 
+GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
+    LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
+{
+    GapRects result;
+
+    bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
+
+    if (!firstLineBox()) {
+        if (containsStart) {
+            // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
+            // case.
+            lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
+            lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
+            lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
+        }
+        return result;
+    }
+
+    RootInlineBox* lastSelectedLine = 0;
+    RootInlineBox* curr;
+    for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
+
+    // Now paint the gaps for the lines.
+    for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
+        LayoutUnit selTop =  curr->selectionTopAdjustedForPrecedingBlock();
+        LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
+
+        if (!containsStart && !lastSelectedLine && selectionState() != SelectionStart && selectionState() != SelectionBoth) {
+            result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop,
+                lastLogicalLeft, lastLogicalRight, selTop, paintInfo));
+        }
+
+        LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
+        logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
+        LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
+        if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
+            || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
+            result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
+
+        lastSelectedLine = curr;
+    }
+
+    if (containsStart && !lastSelectedLine) {
+        // VisibleSelection must start just after our last line.
+        lastSelectedLine = lastRootBox();
+    }
+
+    if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
+        // Go ahead and update our lastY to be the bottom of the last selected line.
+        lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + lastSelectedLine->selectionBottom();
+        lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
+        lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
+    }
+    return result;
+}
+
 template <typename CharacterType>
 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
 {
@@ -2358,4 +2464,67 @@
     return constructTextRunInternal(context, font, string.characters16(), length, style, expansion, flags);
 }
 
+RootInlineBox* RenderBlockFlow::createRootInlineBox()
+{
+    return new RootInlineBox(this);
+}
+
+void RenderBlockFlow::createRenderNamedFlowFragmentIfNeeded()
+{
+    if (!RuntimeEnabledFeatures::cssRegionsEnabled()
+        || renderNamedFlowFragment()
+        || isRenderNamedFlowFragment())
+        return;
+
+    RenderStyle* styleToUse = style();
+    if (styleToUse->isDisplayRegionType() && styleToUse->hasFlowFrom() && document().renderView()) {
+        RenderNamedFlowFragment* flowFragment = RenderNamedFlowFragment::createAnonymous(&document());
+        flowFragment->setStyleForNamedFlowFragment(styleToUse);
+        setRenderNamedFlowFragment(flowFragment);
+        addChild(flowFragment);
+    }
+}
+
+void RenderBlockFlow::insertedIntoTree()
+{
+    RenderBlock::insertedIntoTree();
+
+    createRenderNamedFlowFragmentIfNeeded();
+}
+
+bool RenderBlockFlow::canHaveChildren() const
+{
+    return !renderNamedFlowFragment() ? RenderBlock::canHaveChildren() : renderNamedFlowFragment()->canHaveChildren();
+}
+
+bool RenderBlockFlow::canHaveGeneratedChildren() const
+{
+    return !renderNamedFlowFragment() ? RenderBlock::canHaveGeneratedChildren() : renderNamedFlowFragment()->canHaveGeneratedChildren();
+}
+
+void RenderBlockFlow::updateLogicalHeight()
+{
+    RenderBlock::updateLogicalHeight();
+
+    if (renderNamedFlowFragment())
+        renderNamedFlowFragment()->setLogicalHeight(max<LayoutUnit>(0, logicalHeight() - borderAndPaddingLogicalHeight()));
+}
+
+void RenderBlockFlow::setRenderNamedFlowFragment(RenderNamedFlowFragment* flowFragment)
+{
+    RenderBlockFlow::RenderBlockFlowRareData& rareData = ensureRareData();
+    if (rareData.m_renderNamedFlowFragment)
+        rareData.m_renderNamedFlowFragment->destroy();
+    rareData.m_renderNamedFlowFragment = flowFragment;
+}
+
+RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareData()
+{
+    if (m_rareData)
+        return *m_rareData;
+
+    m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
+    return *m_rareData;
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBlockFlow.h b/Source/core/rendering/RenderBlockFlow.h
index 8592c32..9797379 100644
--- a/Source/core/rendering/RenderBlockFlow.h
+++ b/Source/core/rendering/RenderBlockFlow.h
@@ -44,6 +44,7 @@
 class MarginInfo;
 class LineBreaker;
 class LineWidth;
+class RenderNamedFlowFragment;
 
 class RenderBlockFlow : public RenderBlock {
 public:
@@ -65,6 +66,8 @@
 
     void removeFloatingObjects();
 
+    bool generatesLineBoxesForInlineChild(RenderObject*);
+
     LayoutUnit logicalTopForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->y() : floatingObject->x(); }
     LayoutUnit logicalBottomForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->maxY() : floatingObject->maxX(); }
     LayoutUnit logicalLeftForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->x() : floatingObject->y(); }
@@ -107,6 +110,11 @@
             floatingObject->setHeight(logicalWidth);
     }
 
+    LayoutUnit startAlignedOffsetForLine(LayoutUnit position, bool shouldIndentText);
+
+    void setStaticInlinePositionForChild(RenderBox*, LayoutUnit blockOffset, LayoutUnit inlinePosition);
+    void updateStaticInlinePositionForChild(RenderBox*, LayoutUnit logicalTop);
+
     static bool shouldSkipCreatingRunsForObject(RenderObject* obj)
     {
         return obj->isFloating() || (obj->isOutOfFlowPositioned() && !obj->style()->isOriginalDisplayInlineType() && !obj->container()->isRenderInline());
@@ -129,6 +137,19 @@
 
     static TextRun constructTextRun(RenderObject* context, const Font&, const UChar* characters, int length, RenderStyle*,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
+
+    RootInlineBox* lineGridBox() const { return m_rareData ? m_rareData->m_lineGridBox : 0; }
+    void setLineGridBox(RootInlineBox* box)
+    {
+        RenderBlockFlow::RenderBlockFlowRareData& rareData = ensureRareData();
+        if (rareData.m_lineGridBox)
+            rareData.m_lineGridBox->destroy();
+        rareData.m_lineGridBox = box;
+    }
+    void layoutLineGridBox();
+
+    GapRects inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
+        LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
 protected:
     // Only used by RenderSVGText, which explicitly overrides RenderBlock::layoutBlock(), do NOT use for anything else.
     void forceLayoutInlineChildren()
@@ -145,6 +166,9 @@
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     void addOverflowFromFloats();
+
+    virtual void insertedIntoTree() OVERRIDE;
+    virtual void willBeDestroyed() OVERRIDE;
 private:
     void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
     void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
@@ -200,10 +224,18 @@
     virtual void paintFloats(PaintInfo&, const LayoutPoint&, bool preservePhase = false) OVERRIDE FINAL;
     virtual void clipOutFloatingObjects(RenderBlock*, const PaintInfo*, const LayoutPoint&, const LayoutSize&) OVERRIDE;
     void clearFloats(EClear);
-    virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const OVERRIDE;
-    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const OVERRIDE;
+
+    virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const OVERRIDE;
+    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const OVERRIDE;
+
+    LayoutUnit logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const;
+    LayoutUnit logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const;
+
     virtual void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const OVERRIDE; // Helper function for borderFitAdjust
 
+    virtual RootInlineBox* createRootInlineBox() OVERRIDE;
+
+    void updateLogicalWidthForAlignment(const ETextAlign&, const RootInlineBox*, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount);
 public:
     struct FloatWithRect {
         FloatWithRect(RenderBox* f)
@@ -245,14 +277,18 @@
     };
     MarginValues marginValuesForChild(RenderBox* child) const;
 
+    virtual void updateLogicalHeight() OVERRIDE;
+
     // Allocated only when some of these fields have non-default values
     struct RenderBlockFlowRareData {
         WTF_MAKE_NONCOPYABLE(RenderBlockFlowRareData); WTF_MAKE_FAST_ALLOCATED;
     public:
         RenderBlockFlowRareData(const RenderBlockFlow* block)
             : m_margins(positiveMarginBeforeDefault(block), negativeMarginBeforeDefault(block), positiveMarginAfterDefault(block), negativeMarginAfterDefault(block))
+            , m_lineGridBox(0)
             , m_discardMarginBefore(false)
             , m_discardMarginAfter(false)
+            , m_renderNamedFlowFragment(0)
         {
         }
 
@@ -274,10 +310,17 @@
         }
 
         MarginValues m_margins;
+
+        RootInlineBox* m_lineGridBox;
+
         bool m_discardMarginBefore : 1;
         bool m_discardMarginAfter : 1;
+        RenderNamedFlowFragment* m_renderNamedFlowFragment;
     };
 
+    RenderNamedFlowFragment* renderNamedFlowFragment() const { return m_rareData ? m_rareData->m_renderNamedFlowFragment : 0; }
+    void setRenderNamedFlowFragment(RenderNamedFlowFragment*);
+
 protected:
     LayoutUnit maxPositiveMarginBefore() const { return m_rareData ? m_rareData->m_margins.positiveMarginBefore() : RenderBlockFlowRareData::positiveMarginBeforeDefault(this); }
     LayoutUnit maxNegativeMarginBefore() const { return m_rareData ? m_rareData->m_margins.negativeMarginBefore() : RenderBlockFlowRareData::negativeMarginBeforeDefault(this); }
@@ -329,6 +372,13 @@
     // Used to store state between styleWillChange and styleDidChange
     static bool s_canPropagateFloatIntoSibling;
 
+    virtual bool canHaveChildren() const OVERRIDE;
+    virtual bool canHaveGeneratedChildren() const OVERRIDE;
+
+    void createRenderNamedFlowFragmentIfNeeded();
+
+    RenderBlockFlowRareData& ensureRareData();
+
 protected:
     OwnPtr<RenderBlockFlowRareData> m_rareData;
     OwnPtr<FloatingObjects> m_floatingObjects;
@@ -342,9 +392,6 @@
 // RenderBlockLineLayout. They should be moved to the proper header once the
 // line layout code is separated from RenderBlock and RenderBlockFlow.
 // START METHODS DEFINED IN RenderBlockLineLayout
-public:
-    static void appendRunsForObject(BidiRunList<BidiRun>&, int start, int end, RenderObject*, InlineBidiResolver&);
-
 private:
     InlineFlowBox* createLineBoxes(RenderObject*, const LineInfo&, InlineBox* childBox, bool startsNewSegment);
     RootInlineBox* constructLine(BidiRunList<BidiRun>&, const LineInfo&);
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index 422ed05..bec0a8d 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -22,13 +22,9 @@
 
 #include "config.h"
 
-#include "core/rendering/InlineIterator.h"
-#include "core/rendering/InlineTextBox.h"
-#include "core/rendering/LineWidth.h"
-#include "core/rendering/RenderCombineText.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderCounter.h"
 #include "core/rendering/RenderFlowThread.h"
-#include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderListMarker.h"
 #include "core/rendering/RenderRegion.h"
@@ -36,9 +32,7 @@
 #include "core/rendering/RenderView.h"
 #include "core/rendering/TrailingFloatsRootInlineBox.h"
 #include "core/rendering/VerticalPositionCache.h"
-#include "core/rendering/break_lines.h"
-#include "core/rendering/shapes/ShapeInsideInfo.h"
-#include "core/rendering/svg/RenderSVGInlineText.h"
+#include "core/rendering/line/BreakingContextInlineHeaders.h"
 #include "core/rendering/svg/SVGRootInlineBox.h"
 #include "platform/text/BidiResolver.h"
 #include "wtf/RefCountedLeakCounter.h"
@@ -46,88 +40,8 @@
 #include "wtf/Vector.h"
 #include "wtf/unicode/CharacterNames.h"
 
-using namespace std;
-using namespace WTF;
-using namespace Unicode;
-
 namespace WebCore {
 
-// We don't let our line box tree for a single line get any deeper than this.
-const unsigned cMaxLineDepth = 200;
-
-struct RenderTextInfo {
-    // Destruction of m_layout requires TextLayout to be a complete type, so the constructor and destructor are made non-inline to avoid compilation errors.
-    RenderTextInfo();
-    ~RenderTextInfo();
-
-    RenderText* m_text;
-    OwnPtr<TextLayout> m_layout;
-    LazyLineBreakIterator m_lineBreakIterator;
-    const Font* m_font;
-};
-
-class TrailingObjects {
-public:
-    TrailingObjects();
-    void setTrailingWhitespace(RenderText*);
-    void clear();
-    void appendBoxIfNeeded(RenderBox*);
-
-    enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
-
-    void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
-
-private:
-    RenderText* m_whitespace;
-    Vector<RenderBox*, 4> m_boxes;
-};
-
-class LineInfo {
-public:
-    LineInfo()
-        : m_isFirstLine(true)
-        , m_isLastLine(false)
-        , m_isEmpty(true)
-        , m_previousLineBrokeCleanly(true)
-        , m_floatPaginationStrut(0)
-        , m_runsFromLeadingWhitespace(0)
-    { }
-
-    bool isFirstLine() const { return m_isFirstLine; }
-    bool isLastLine() const { return m_isLastLine; }
-    bool isEmpty() const { return m_isEmpty; }
-    bool previousLineBrokeCleanly() const { return m_previousLineBrokeCleanly; }
-    LayoutUnit floatPaginationStrut() const { return m_floatPaginationStrut; }
-    unsigned runsFromLeadingWhitespace() const { return m_runsFromLeadingWhitespace; }
-    void resetRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace = 0; }
-    void incrementRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace++; }
-
-    void setFirstLine(bool firstLine) { m_isFirstLine = firstLine; }
-    void setLastLine(bool lastLine) { m_isLastLine = lastLine; }
-    void setEmpty(bool empty, RenderBlock* block = 0, LineWidth* lineWidth = 0)
-    {
-        if (m_isEmpty == empty)
-            return;
-        m_isEmpty = empty;
-        if (!empty && block && floatPaginationStrut()) {
-            block->setLogicalHeight(block->logicalHeight() + floatPaginationStrut());
-            setFloatPaginationStrut(0);
-            lineWidth->updateAvailableWidth();
-        }
-    }
-
-    void setPreviousLineBrokeCleanly(bool previousLineBrokeCleanly) { m_previousLineBrokeCleanly = previousLineBrokeCleanly; }
-    void setFloatPaginationStrut(LayoutUnit strut) { m_floatPaginationStrut = strut; }
-
-private:
-    bool m_isFirstLine;
-    bool m_isLastLine;
-    bool m_isEmpty;
-    bool m_previousLineBrokeCleanly;
-    LayoutUnit m_floatPaginationStrut;
-    unsigned m_runsFromLeadingWhitespace;
-};
-
 static IndentTextOrNot requiresIndent(bool isFirstLine, bool isAfterHardLineBreak, RenderStyle* style)
 {
     if (isFirstLine)
@@ -164,180 +78,6 @@
     Vector<RenderBox*> m_positionedObjects;
 };
 
-class BreakingContext {
-public:
-    BreakingContext(InlineBidiResolver& resolver, LineInfo& inLineInfo, LineWidth& lineWidth, RenderTextInfo& inRenderTextInfo, FloatingObject* inLastFloatFromPreviousLine, bool appliedStartWidth, RenderBlockFlow* block)
-        : m_resolver(resolver)
-        , m_current(resolver.position())
-        , m_lineBreak(resolver.position())
-        , m_block(block)
-        , m_lastObject(m_current.m_obj)
-        , m_nextObject(0)
-        , m_currentStyle(0)
-        , m_blockStyle(block->style())
-        , m_lineInfo(inLineInfo)
-        , m_renderTextInfo(inRenderTextInfo)
-        , m_lastFloatFromPreviousLine(inLastFloatFromPreviousLine)
-        , m_width(lineWidth)
-        , m_currWS(NORMAL)
-        , m_lastWS(NORMAL)
-        , m_preservesNewline(false)
-        , m_atStart(true)
-        , m_ignoringSpaces(false)
-        , m_currentCharacterIsSpace(false)
-        , m_currentCharacterShouldCollapseIfPreWap(false)
-        , m_appliedStartWidth(appliedStartWidth)
-        , m_includeEndWidth(true)
-        , m_autoWrap(false)
-        , m_autoWrapWasEverTrueOnLine(false)
-        , m_floatsFitOnLine(true)
-        , m_collapseWhiteSpace(false)
-        , m_startingNewParagraph(m_lineInfo.previousLineBrokeCleanly())
-        , m_allowImagesToBreak(!block->document().inQuirksMode() || !block->isTableCell() || !m_blockStyle->logicalWidth().isIntrinsicOrAuto())
-        , m_atEnd(false)
-        , m_lineMidpointState(resolver.midpointState())
-    {
-        m_lineInfo.setPreviousLineBrokeCleanly(false);
-    }
-
-    RenderObject* currentObject() { return m_current.m_obj; }
-    InlineIterator lineBreak() { return m_lineBreak; }
-    bool atEnd() { return m_atEnd; }
-
-    void initializeForCurrentObject();
-
-    void increment();
-
-    void handleBR(EClear&);
-    void handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects);
-    void handleFloat();
-    void handleEmptyInline();
-    void handleReplaced();
-    bool handleText(WordMeasurements&, bool& hyphenated);
-    void commitAndUpdateLineBreakIfNeeded();
-    InlineIterator handleEndOfLine();
-
-    void clearLineBreakIfFitsOnLine()
-    {
-        if (m_width.fitsOnLine() || m_lastWS == NOWRAP)
-            m_lineBreak.clear();
-    }
-
-private:
-    void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
-
-    InlineBidiResolver& m_resolver;
-
-    InlineIterator m_current;
-    InlineIterator m_lineBreak;
-    InlineIterator m_startOfIgnoredSpaces;
-
-    RenderBlockFlow* m_block;
-    RenderObject* m_lastObject;
-    RenderObject* m_nextObject;
-
-    RenderStyle* m_currentStyle;
-    RenderStyle* m_blockStyle;
-
-    LineInfo& m_lineInfo;
-
-    RenderTextInfo& m_renderTextInfo;
-
-    FloatingObject* m_lastFloatFromPreviousLine;
-
-    LineWidth m_width;
-
-    EWhiteSpace m_currWS;
-    EWhiteSpace m_lastWS;
-
-    bool m_preservesNewline;
-    bool m_atStart;
-    bool m_ignoringSpaces;
-    bool m_currentCharacterIsSpace;
-    bool m_currentCharacterShouldCollapseIfPreWap;
-    bool m_appliedStartWidth;
-    bool m_includeEndWidth;
-    bool m_autoWrap;
-    bool m_autoWrapWasEverTrueOnLine;
-    bool m_floatsFitOnLine;
-    bool m_collapseWhiteSpace;
-    bool m_startingNewParagraph;
-    bool m_allowImagesToBreak;
-    bool m_atEnd;
-
-    LineMidpointState& m_lineMidpointState;
-
-    TrailingObjects m_trailingObjects;
-};
-
-inline void BreakingContext::initializeForCurrentObject()
-{
-    m_currentStyle = m_current.m_obj->style();
-    m_nextObject = bidiNextSkippingEmptyInlines(m_block, m_current.m_obj);
-    if (m_nextObject && m_nextObject->parent() && !m_nextObject->parent()->isDescendantOf(m_current.m_obj->parent()))
-        m_includeEndWidth = true;
-
-    m_currWS = m_current.m_obj->isReplaced() ? m_current.m_obj->parent()->style()->whiteSpace() : m_currentStyle->whiteSpace();
-    m_lastWS = m_lastObject->isReplaced() ? m_lastObject->parent()->style()->whiteSpace() : m_lastObject->style()->whiteSpace();
-
-    m_autoWrap = RenderStyle::autoWrap(m_currWS);
-    m_autoWrapWasEverTrueOnLine = m_autoWrapWasEverTrueOnLine || m_autoWrap;
-
-    m_preservesNewline = m_current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(m_currWS);
-
-    m_collapseWhiteSpace = RenderStyle::collapseWhiteSpace(m_currWS);
-}
-
-inline void BreakingContext::increment()
-{
-    // Clear out our character space bool, since inline <pre>s don't collapse whitespace
-    // with adjacent inline normal/nowrap spans.
-    if (!m_collapseWhiteSpace)
-        m_currentCharacterIsSpace = false;
-
-    m_current.moveToStartOf(m_nextObject);
-    m_atStart = false;
-}
-
-static inline LayoutUnit borderPaddingMarginStart(RenderInline* child)
-{
-    return child->marginStart() + child->paddingStart() + child->borderStart();
-}
-
-static inline LayoutUnit borderPaddingMarginEnd(RenderInline* child)
-{
-    return child->marginEnd() + child->paddingEnd() + child->borderEnd();
-}
-
-static bool shouldAddBorderPaddingMargin(RenderObject* child, bool &checkSide)
-{
-    if (!child || (child->isText() && !toRenderText(child)->textLength()))
-        return true;
-    checkSide = false;
-    return checkSide;
-}
-
-static LayoutUnit inlineLogicalWidth(RenderObject* child, bool start = true, bool end = true)
-{
-    unsigned lineDepth = 1;
-    LayoutUnit extraWidth = 0;
-    RenderObject* parent = child->parent();
-    while (parent->isRenderInline() && lineDepth++ < cMaxLineDepth) {
-        RenderInline* parentAsRenderInline = toRenderInline(parent);
-        if (!isEmptyInline(parentAsRenderInline)) {
-            if (start && shouldAddBorderPaddingMargin(child->previousSibling(), start))
-                extraWidth += borderPaddingMarginStart(parentAsRenderInline);
-            if (end && shouldAddBorderPaddingMargin(child->nextSibling(), end))
-                extraWidth += borderPaddingMarginEnd(parentAsRenderInline);
-            if (!start && !end)
-                return extraWidth;
-        }
-        child = parent;
-        parent = child->parent();
-    }
-    return extraWidth;
-}
-
 static RenderObject* firstRenderObjectForDirectionalityDetermination(RenderObject* root, RenderObject* current = 0)
 {
     RenderObject* next = current;
@@ -391,71 +131,6 @@
     return observer.determineParagraphDirectionality();
 }
 
-static void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
-{
-    // Check to see if our last midpoint is a start point beyond the line break.  If so,
-    // shave it off the list, and shave off a trailing space if the previous end point doesn't
-    // preserve whitespace.
-    if (lBreak.m_obj && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
-        InlineIterator* midpoints = lineMidpointState.midpoints.data();
-        InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
-        const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
-        InlineIterator currpoint = endpoint;
-        while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
-            currpoint.increment();
-        if (currpoint == lBreak) {
-            // We hit the line break before the start point.  Shave off the start point.
-            lineMidpointState.numMidpoints--;
-            if (endpoint.m_obj->style()->collapseWhiteSpace() && endpoint.m_obj->isText())
-                endpoint.m_pos--;
-        }
-    }
-}
-
-// Don't call this directly. Use one of the descriptive helper functions below.
-static void deprecatedAddMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
-    if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
-        lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
-
-    InlineIterator* midpoints = lineMidpointState.midpoints.data();
-    midpoints[lineMidpointState.numMidpoints++] = midpoint;
-}
-
-static inline void startIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
-    ASSERT(!(lineMidpointState.numMidpoints % 2));
-    deprecatedAddMidpoint(lineMidpointState, midpoint);
-}
-
-static inline void stopIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
-    ASSERT(lineMidpointState.numMidpoints % 2);
-    deprecatedAddMidpoint(lineMidpointState, midpoint);
-}
-
-// When ignoring spaces, this needs to be called for objects that need line boxes such as RenderInlines or
-// hard line breaks to ensure that they're not ignored.
-static inline void ensureLineBoxInsideIgnoredSpaces(LineMidpointState& lineMidpointState, RenderObject* renderer)
-{
-    InlineIterator midpoint(0, renderer, 0);
-    stopIgnoringSpaces(lineMidpointState, midpoint);
-    startIgnoringSpaces(lineMidpointState, midpoint);
-}
-
-// Adding a pair of midpoints before a character will split it out into a new line box.
-static inline void ensureCharacterGetsLineBox(LineMidpointState& lineMidpointState, InlineIterator& textParagraphSeparator)
-{
-    InlineIterator midpoint(0, textParagraphSeparator.m_obj, textParagraphSeparator.m_pos);
-    startIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.m_obj, textParagraphSeparator.m_pos - 1));
-    stopIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.m_obj, textParagraphSeparator.m_pos));
-}
-
-void RenderBlockFlow::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
-{
-    adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, resolver, AppendingRunsForObject, &runs);
-}
-
 static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
 {
     if (isRootLineBox)
@@ -766,29 +441,6 @@
     setMarginEndForChild(renderer, -endOverhang);
 }
 
-static inline float measureHyphenWidth(RenderText* renderer, const Font& font)
-{
-    RenderStyle* style = renderer->style();
-    return font.width(RenderBlockFlow::constructTextRun(renderer, font, style->hyphenString().string(), style));
-}
-
-class WordMeasurement {
-public:
-    WordMeasurement()
-        : renderer(0)
-        , width(0)
-        , startOffset(0)
-        , endOffset(0)
-    {
-    }
-
-    RenderText* renderer;
-    float width;
-    int startOffset;
-    int endOffset;
-    HashSet<const SimpleFontData*> fallbackFonts;
-};
-
 static inline void setLogicalWidthForTextRun(RootInlineBox* lineBox, BidiRun* run, RenderText* renderer, float xPos, const LineInfo& lineInfo,
                                              GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache, WordMeasurements& wordMeasurements)
 {
@@ -911,7 +563,7 @@
     }
 }
 
-void RenderBlock::updateLogicalWidthForAlignment(const ETextAlign& textAlign, const RootInlineBox* rootInlineBox, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
+void RenderBlockFlow::updateLogicalWidthForAlignment(const ETextAlign& textAlign, const RootInlineBox* rootInlineBox, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
 {
     TextDirection direction;
     if (rootInlineBox && rootInlineBox->renderer()->style()->unicodeBidi() == Plaintext)
@@ -1135,24 +787,6 @@
     return false;
 }
 
-
-static void setStaticPositions(RenderBlockFlow* block, RenderBox* child)
-{
-    // FIXME: The math here is actually not really right. It's a best-guess approximation that
-    // will work for the common cases
-    RenderObject* containerBlock = child->container();
-    LayoutUnit blockHeight = block->logicalHeight();
-    if (containerBlock->isRenderInline()) {
-        // A relative positioned inline encloses us. In this case, we also have to determine our
-        // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
-        // inline so that we can obtain the value later.
-        toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(blockHeight, false));
-        toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
-    }
-    block->updateStaticInlinePositionForChild(child, blockHeight);
-    child->layer()->setStaticBlockPosition(blockHeight);
-}
-
 template <typename CharacterType>
 static inline int findFirstTrailingSpace(RenderText* lastText, const CharacterType* characters, int start, int stop)
 {
@@ -1301,15 +935,12 @@
         // first run within the isolate.
         InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start);
         isolatedResolver.setPositionIgnoringNestedIsolates(iter);
-
         // We stop at the next end of line; we may re-enter this isolate in the next call to constructBidiRuns().
         // FIXME: What should end and previousLineBrokeCleanly be?
         // rniwa says previousLineBrokeCleanly is just a WinIE hack and could always be false here?
         isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly);
-        // Note that we do not delete the runs from the resolver.
-        // We're not guaranteed to get any BidiRuns in the previous step. If we don't, we allow the placeholder
-        // itself to be turned into an InlineBox. We can't remove it here without potentially losing track of
-        // the logically last run.
+
+        ASSERT(isolatedResolver.runs().runCount());
         if (isolatedResolver.runs().runCount())
             bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs());
 
@@ -1345,8 +976,8 @@
         iterator = segmentRanges[i].end;
         InlineIterator segmentEnd(iterator.root, iterator.object, iterator.offset);
         if (i) {
-            ASSERT(segmentStart.m_obj);
-            BidiRun* segmentMarker = createRun(segmentStart.m_pos, segmentStart.m_pos, segmentStart.m_obj, topResolver);
+            ASSERT(segmentStart.object());
+            BidiRun* segmentMarker = createRun(segmentStart.m_pos, segmentStart.m_pos, segmentStart.object(), topResolver);
             segmentMarker->m_startsSegment = true;
             bidiRuns.addRun(segmentMarker);
             // Do not collapse midpoints between segments
@@ -1366,7 +997,7 @@
         return 0;
 
     // FIXME: Why is this only done when we had runs?
-    lineInfo.setLastLine(!end.m_obj);
+    lineInfo.setLastLine(!end.object());
 
     RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
     if (!lineBox)
@@ -1587,16 +1218,6 @@
     return oldEnd;
 }
 
-static inline float firstPositiveWidth(const WordMeasurements& wordMeasurements)
-{
-    for (size_t i = 0; i < wordMeasurements.size(); ++i) {
-        if (wordMeasurements[i].width > 0)
-            return wordMeasurements[i].width;
-    }
-    return 0;
-}
-
-
 static inline LayoutUnit adjustLogicalLineTop(ShapeInsideInfo* shapeInsideInfo, InlineIterator start, InlineIterator end, const WordMeasurements& wordMeasurements)
 {
     if (!shapeInsideInfo || end != start)
@@ -1757,7 +1378,7 @@
     RenderStyle* styleToUse = style();
     bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
     LineMidpointState& lineMidpointState = resolver.midpointState();
-    InlineIterator end = resolver.position();
+    InlineIterator endOfLine = resolver.position();
     bool checkForEndLineMatch = layoutState.endLine();
     RenderTextInfo renderTextInfo;
     VerticalPositionCache verticalPositionCache;
@@ -1782,7 +1403,7 @@
         }
     }
 
-    while (!end.atEnd()) {
+    while (!endOfLine.atEnd()) {
         // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
         if (checkForEndLineMatch) {
             layoutState.setEndLineMatched(matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus));
@@ -1797,14 +1418,14 @@
         layoutState.lineInfo().setEmpty(true);
         layoutState.lineInfo().resetRunsFromLeadingWhitespace();
 
-        const InlineIterator oldEnd = end;
+        const InlineIterator previousEndofLine = endOfLine;
         bool isNewUBAParagraph = layoutState.lineInfo().previousLineBrokeCleanly();
         FloatingObject* lastFloatFromPreviousLine = (containsFloats()) ? m_floatingObjects->set().last() : 0;
 
         updateShapeAndSegmentsForCurrentLine(shapeInsideInfo, logicalOffsetFromShapeContainer, layoutState);
 
         WordMeasurements wordMeasurements;
-        end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
+        endOfLine = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
         renderTextInfo.m_lineBreakIterator.resetPriorContext();
         if (resolver.position().atEnd()) {
             // FIXME: We shouldn't be creating any runs in nextLineBreak to begin with!
@@ -1816,15 +1437,15 @@
             break;
         }
 
-        if (adjustLogicalLineTopAndLogicalHeightIfNeeded(shapeInsideInfo, logicalOffsetFromShapeContainer.height(), layoutState, resolver, lastFloatFromPreviousLine, end, wordMeasurements))
+        if (adjustLogicalLineTopAndLogicalHeightIfNeeded(shapeInsideInfo, logicalOffsetFromShapeContainer.height(), layoutState, resolver, lastFloatFromPreviousLine, endOfLine, wordMeasurements))
             continue;
 
-        ASSERT(end != resolver.position());
+        ASSERT(endOfLine != resolver.position());
 
         // This is a short-cut for empty lines.
         if (layoutState.lineInfo().isEmpty()) {
             if (lastRootBox())
-                lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
+                lastRootBox()->setLineBreakInfo(endOfLine.object(), endOfLine.m_pos, resolver.status());
         } else {
             VisualDirectionOverride override = (styleToUse->rtlOrdering() == VisualOrder ? (styleToUse->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
 
@@ -1834,8 +1455,8 @@
             }
             // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
             BidiRunList<BidiRun>& bidiRuns = resolver.runs();
-            constructBidiRunsForLine(this, resolver, bidiRuns, end, override, layoutState.lineInfo().previousLineBrokeCleanly(), isNewUBAParagraph);
-            ASSERT(resolver.position() == end);
+            constructBidiRunsForLine(this, resolver, bidiRuns, endOfLine, override, layoutState.lineInfo().previousLineBrokeCleanly(), isNewUBAParagraph);
+            ASSERT(resolver.position() == endOfLine);
 
             BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
 
@@ -1850,13 +1471,13 @@
             // inline flow boxes.
 
             LayoutUnit oldLogicalHeight = logicalHeight();
-            RootInlineBox* lineBox = createLineBoxesFromBidiRuns(resolver.status().context->level(), bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun, wordMeasurements);
+            RootInlineBox* lineBox = createLineBoxesFromBidiRuns(resolver.status().context->level(), bidiRuns, endOfLine, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun, wordMeasurements);
 
             bidiRuns.deleteRuns();
             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
 
             if (lineBox) {
-                lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
+                lineBox->setLineBreakInfo(endOfLine.object(), endOfLine.m_pos, resolver.status());
                 if (layoutState.usesRepaintBounds())
                     layoutState.updateRepaintRangeFromBox(lineBox);
 
@@ -1872,7 +1493,7 @@
                         if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, layoutState.lineInfo().isFirstLine()) != oldLineWidth) {
                             // We have to delete this line, remove all floats that got added, and let line layout re-run.
                             lineBox->deleteLine();
-                            end = restartLayoutRunsAndFloatsInRange(oldLogicalHeight, oldLogicalHeight + adjustment, lastFloatFromPreviousLine, resolver, oldEnd);
+                            endOfLine = restartLayoutRunsAndFloatsInRange(oldLogicalHeight, oldLogicalHeight + adjustment, lastFloatFromPreviousLine, resolver, previousEndofLine);
                             continue;
                         }
 
@@ -1916,7 +1537,7 @@
         }
 
         lineMidpointState.reset();
-        resolver.setPosition(end, numberOfIsolateAncestors(end));
+        resolver.setPosition(endOfLine, numberOfIsolateAncestors(endOfLine));
     }
 
     // In case we already adjusted the line positions during this layout to avoid widows
@@ -2117,6 +1738,9 @@
         Vector<RenderBox*> replacedChildren;
         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
             RenderObject* o = walker.current();
+
+            LayoutRectRecorder recorder(*o, !o->isText());
+
             if (!hasInlineChild && o->isInline())
                 hasInlineChild = true;
 
@@ -2428,7 +2052,7 @@
     RootInlineBox* originalEndLine = layoutState.endLine();
     RootInlineBox* line = originalEndLine;
     for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
-        if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
+        if (line->lineBreakObj() == resolver.position().object() && line->lineBreakPos() == resolver.position().m_pos) {
             // We have a match.
             if (line->lineBreakBidiStatus() != resolver.status())
                 return false; // ...but the bidi state doesn't match.
@@ -2450,53 +2074,8 @@
     return false;
 }
 
-enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
-static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
-{
-    // CSS2 16.6.1
-    // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
-    // If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.
-    // If spaces (U+0020) or tabs (U+0009) at the end of a line have 'white-space' set to 'pre-wrap', UAs may visually collapse them.
-    return style->collapseWhiteSpace()
-        || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
-}
+bool RenderBlockFlow::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
 
-static bool requiresLineBoxForContent(RenderInline* flow, const LineInfo& lineInfo)
-{
-    RenderObject* parent = flow->parent();
-    if (flow->document().inNoQuirksMode()
-        && (flow->style(lineInfo.isFirstLine())->lineHeight() != parent->style(lineInfo.isFirstLine())->lineHeight()
-        || flow->style()->verticalAlign() != parent->style()->verticalAlign()
-        || !parent->style()->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(flow->style()->font().fontMetrics())))
-        return true;
-    return false;
-}
-
-static bool alwaysRequiresLineBox(RenderObject* flow)
-{
-    // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
-    // We need to fix this, though, because at the very least, inlines containing only
-    // ignorable whitespace should should also have line boxes.
-    return isEmptyInline(flow) && toRenderInline(flow)->hasInlineDirectionBordersPaddingOrMargin();
-}
-
-static bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
-{
-    if (it.m_obj->isFloatingOrOutOfFlowPositioned())
-        return false;
-
-    if (it.m_obj->isRenderInline() && !alwaysRequiresLineBox(it.m_obj) && !requiresLineBoxForContent(toRenderInline(it.m_obj), lineInfo))
-        return false;
-
-    if (!shouldCollapseWhiteSpace(it.m_obj->style(), lineInfo, whitespacePosition) || it.m_obj->isBR())
-        return true;
-
-    UChar current = it.current();
-    bool notJustWhitespace = current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline());
-    return notJustWhitespace || isEmptyInline(it.m_obj);
-}
-
-bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
 {
     ASSERT(inlineObj->parent() == this);
 
@@ -2508,29 +2087,11 @@
     return !it.atEnd();
 }
 
-// FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
-// line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
-// elements quite right. In other words, we need to build this function's work into the normal line
-// object iteration process.
-// NB. this function will insert any floating elements that would otherwise
-// be skipped but it will not position them.
-inline void BreakingContext::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
-{
-    while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
-        RenderObject* object = iterator.m_obj;
-        if (object->isOutOfFlowPositioned())
-            setStaticPositions(m_block, toRenderBox(object));
-        else if (object->isFloating())
-            m_block->insertFloatingObject(toRenderBox(object));
-        iterator.increment();
-    }
-}
-
 void LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
                                                      FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
 {
     while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
-        RenderObject* object = resolver.position().m_obj;
+        RenderObject* object = resolver.position().object();
         if (object->isOutOfFlowPositioned()) {
             setStaticPositions(m_block, toRenderBox(object));
             if (object->style()->isOriginalDisplayInlineType()) {
@@ -2555,113 +2116,6 @@
     resolver.commitExplicitEmbedding();
 }
 
-// This is currently just used for list markers and inline flows that have line boxes. Neither should
-// have an effect on whitespace at the start of the line.
-static bool shouldSkipWhitespaceAfterStartObject(RenderBlockFlow* block, RenderObject* o, LineMidpointState& lineMidpointState)
-{
-    RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
-    while (next && next->isFloatingOrOutOfFlowPositioned())
-        next = bidiNextSkippingEmptyInlines(block, next);
-
-    if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
-        RenderText* nextText = toRenderText(next);
-        UChar nextChar = nextText->characterAt(0);
-        if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
-            startIgnoringSpaces(lineMidpointState, InlineIterator(0, o, 0));
-            return true;
-        }
-    }
-
-    return false;
-}
-
-static ALWAYS_INLINE float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace, HashSet<const SimpleFontData*>* fallbackFonts = 0, TextLayout* layout = 0)
-{
-    GlyphOverflow glyphOverflow;
-    if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
-        return text->width(from, len, font, xPos, fallbackFonts, &glyphOverflow);
-
-    if (layout)
-        return Font::width(*layout, from, len, fallbackFonts);
-
-    TextRun run = RenderBlockFlow::constructTextRun(text, font, text, from, len, text->style());
-    run.setCharactersLength(text->textLength() - from);
-    ASSERT(run.charactersLength() >= run.length());
-
-    run.setCharacterScanForCodePath(!text->canUseSimpleFontCodePath());
-    run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
-    run.setXPos(xPos);
-    return font.width(run, fallbackFonts, &glyphOverflow);
-}
-
-TrailingObjects::TrailingObjects()
-    : m_whitespace(0)
-{
-}
-
-inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
-{
-    ASSERT(whitespace);
-    m_whitespace = whitespace;
-}
-
-inline void TrailingObjects::clear()
-{
-    m_whitespace = 0;
-    // Using resize(0) rather than clear() here saves 2% on
-    // PerformanceTests/Layout/line-layout.html because we avoid freeing and
-    // re-allocating the underlying buffer repeatedly.
-    m_boxes.resize(0);
-}
-
-inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
-{
-    if (m_whitespace)
-        m_boxes.append(box);
-}
-
-void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
-{
-    if (!m_whitespace)
-        return;
-
-    // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
-    // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
-    if (lineMidpointState.numMidpoints % 2) {
-        // Find the trailing space object's midpoint.
-        int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
-        for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != m_whitespace; --trailingSpaceMidpoint) { }
-        ASSERT(trailingSpaceMidpoint >= 0);
-        if (collapseFirstSpace == CollapseFirstSpace)
-            lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
-
-        // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
-        // ignoring spaces.
-        size_t currentMidpoint = trailingSpaceMidpoint + 1;
-        for (size_t i = 0; i < m_boxes.size(); ++i) {
-            if (currentMidpoint >= lineMidpointState.numMidpoints) {
-                // We don't have a midpoint for this box yet.
-                ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
-            } else {
-                ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == m_boxes[i]);
-                ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == m_boxes[i]);
-            }
-            currentMidpoint += 2;
-        }
-    } else if (!lBreak.m_obj) {
-        ASSERT(m_whitespace->isText());
-        ASSERT(collapseFirstSpace == CollapseFirstSpace);
-        // Add a new end midpoint that stops right at the very end.
-        unsigned length = m_whitespace->textLength();
-        unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
-        InlineIterator endMid(0, m_whitespace, pos);
-        startIgnoringSpaces(lineMidpointState, endMid);
-        for (size_t i = 0; i < m_boxes.size(); ++i) {
-            ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
-        }
-    }
-}
-
 void LineBreaker::reset()
 {
     m_positionedObjects.clear();
@@ -2719,608 +2173,6 @@
     return end;
 }
 
-static inline bool iteratorIsBeyondEndOfRenderCombineText(const InlineIterator& iter, RenderCombineText* renderer)
-{
-    return iter.m_obj == renderer && iter.m_pos >= renderer->textLength();
-}
-
-inline void BreakingContext::handleBR(EClear& clear)
-{
-    if (m_width.fitsOnLine()) {
-        RenderObject* br = m_current.m_obj;
-        m_lineBreak.moveToStartOf(br);
-        m_lineBreak.increment();
-
-        // A <br> always breaks a line, so don't let the line be collapsed
-        // away. Also, the space at the end of a line with a <br> does not
-        // get collapsed away. It only does this if the previous line broke
-        // cleanly. Otherwise the <br> has no effect on whether the line is
-        // empty or not.
-        if (m_startingNewParagraph)
-            m_lineInfo.setEmpty(false, m_block, &m_width);
-        m_trailingObjects.clear();
-        m_lineInfo.setPreviousLineBrokeCleanly(true);
-
-        // A <br> with clearance always needs a linebox in case the lines below it get dirtied later and
-        // need to check for floats to clear - so if we're ignoring spaces, stop ignoring them and add a
-        // run for this object.
-        if (m_ignoringSpaces && m_currentStyle->clear() != CNONE)
-            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, br);
-
-        if (!m_lineInfo.isEmpty())
-            clear = m_currentStyle->clear();
-    }
-    m_atEnd = true;
-}
-
-inline void BreakingContext::handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects)
-{
-    // If our original display wasn't an inline type, then we can
-    // go ahead and determine our static inline position now.
-    RenderBox* box = toRenderBox(m_current.m_obj);
-    bool isInlineType = box->style()->isOriginalDisplayInlineType();
-    if (!isInlineType) {
-        m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));
-    } else {
-        // If our original display was an INLINE type, then we can go ahead
-        // and determine our static y position now.
-        box->layer()->setStaticBlockPosition(m_block->logicalHeight());
-    }
-
-    // If we're ignoring spaces, we have to stop and include this object and
-    // then start ignoring spaces again.
-    if (isInlineType || box->container()->isRenderInline()) {
-        if (m_ignoringSpaces)
-            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, box);
-        m_trailingObjects.appendBoxIfNeeded(box);
-    } else {
-        positionedObjects.append(box);
-    }
-    m_width.addUncommittedWidth(inlineLogicalWidth(box));
-    // Reset prior line break context characters.
-    m_renderTextInfo.m_lineBreakIterator.resetPriorContext();
-}
-
-inline void BreakingContext::handleFloat()
-{
-    RenderBox* floatBox = toRenderBox(m_current.m_obj);
-    FloatingObject* floatingObject = m_block->insertFloatingObject(floatBox);
-    // check if it fits in the current line.
-    // If it does, position it now, otherwise, position
-    // it after moving to next line (in newLine() func)
-    // FIXME: Bug 110372: Properly position multiple stacked floats with non-rectangular shape outside.
-    if (m_floatsFitOnLine && m_width.fitsOnLine(m_block->logicalWidthForFloat(floatingObject))) {
-        m_block->positionNewFloatOnLine(floatingObject, m_lastFloatFromPreviousLine, m_lineInfo, m_width);
-        if (m_lineBreak.m_obj == m_current.m_obj) {
-            ASSERT(!m_lineBreak.m_pos);
-            m_lineBreak.increment();
-        }
-    } else {
-        m_floatsFitOnLine = false;
-    }
-    // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for floating element.
-    m_renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
-}
-
-inline void BreakingContext::handleEmptyInline()
-{
-    // This should only end up being called on empty inlines
-    ASSERT(isEmptyInline(m_current.m_obj));
-
-    RenderInline* flowBox = toRenderInline(m_current.m_obj);
-
-    // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
-    // to make sure that we stop to include this object and then start ignoring spaces again.
-    // If this object is at the start of the line, we need to behave like list markers and
-    // start ignoring spaces.
-    bool requiresLineBox = alwaysRequiresLineBox(m_current.m_obj);
-    if (requiresLineBox || requiresLineBoxForContent(flowBox, m_lineInfo)) {
-        // An empty inline that only has line-height, vertical-align or font-metrics will only get a
-        // line box to affect the height of the line if the rest of the line is not empty.
-        if (requiresLineBox)
-            m_lineInfo.setEmpty(false, m_block, &m_width);
-        if (m_ignoringSpaces) {
-            m_trailingObjects.clear();
-            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, m_current.m_obj);
-        } else if (m_blockStyle->collapseWhiteSpace() && m_resolver.position().m_obj == m_current.m_obj
-            && shouldSkipWhitespaceAfterStartObject(m_block, m_current.m_obj, m_lineMidpointState)) {
-            // Like with list markers, we start ignoring spaces to make sure that any
-            // additional spaces we see will be discarded.
-            m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = true;
-            m_ignoringSpaces = true;
-        }
-    }
-
-    m_width.addUncommittedWidth(inlineLogicalWidth(m_current.m_obj) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
-}
-
-inline void BreakingContext::handleReplaced()
-{
-    RenderBox* replacedBox = toRenderBox(m_current.m_obj);
-
-    if (m_atStart)
-        m_width.updateAvailableWidth(replacedBox->logicalHeight());
-
-    // Break on replaced elements if either has normal white-space.
-    if ((m_autoWrap || RenderStyle::autoWrap(m_lastWS)) && (!m_current.m_obj->isImage() || m_allowImagesToBreak)) {
-        m_width.commit();
-        m_lineBreak.moveToStartOf(m_current.m_obj);
-    }
-
-    if (m_ignoringSpaces)
-        stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.m_obj, 0));
-
-    m_lineInfo.setEmpty(false, m_block, &m_width);
-    m_ignoringSpaces = false;
-    m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = false;
-    m_trailingObjects.clear();
-
-    // Optimize for a common case. If we can't find whitespace after the list
-    // item, then this is all moot.
-    LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(m_current.m_obj);
-    if (m_current.m_obj->isListMarker()) {
-        if (m_blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, m_current.m_obj, m_lineMidpointState)) {
-            // Like with inline flows, we start ignoring spaces to make sure that any
-            // additional spaces we see will be discarded.
-            m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = true;
-            m_ignoringSpaces = true;
-        }
-        if (toRenderListMarker(m_current.m_obj)->isInside())
-            m_width.addUncommittedWidth(replacedLogicalWidth);
-    } else {
-        m_width.addUncommittedWidth(replacedLogicalWidth);
-    }
-    if (m_current.m_obj->isRubyRun())
-        m_width.applyOverhang(toRenderRubyRun(m_current.m_obj), m_lastObject, m_nextObject);
-    // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for replaced element.
-    m_renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
-}
-
-static inline void nextCharacter(UChar& currentCharacter, UChar& lastCharacter, UChar& secondToLastCharacter)
-{
-    secondToLastCharacter = lastCharacter;
-    lastCharacter = currentCharacter;
-}
-
-static void updateSegmentsForShapes(RenderBlockFlow* block, const FloatingObject* lastFloatFromPreviousLine, const WordMeasurements& wordMeasurements, LineWidth& width, bool isFirstLine)
-{
-    ASSERT(lastFloatFromPreviousLine);
-
-    ShapeInsideInfo* shapeInsideInfo = block->layoutShapeInsideInfo();
-    if (!lastFloatFromPreviousLine->isPlaced() || !shapeInsideInfo)
-        return;
-
-    bool isHorizontalWritingMode = block->isHorizontalWritingMode();
-    LayoutUnit logicalOffsetFromShapeContainer = block->logicalOffsetFromShapeAncestorContainer(shapeInsideInfo->owner()).height();
-
-    LayoutUnit lineLogicalTop = block->logicalHeight() + logicalOffsetFromShapeContainer;
-    LayoutUnit lineLogicalHeight = block->lineHeight(isFirstLine, isHorizontalWritingMode ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
-    LayoutUnit lineLogicalBottom = lineLogicalTop + lineLogicalHeight;
-
-    LayoutUnit floatLogicalTop = block->logicalTopForFloat(lastFloatFromPreviousLine);
-    LayoutUnit floatLogicalBottom = block->logicalBottomForFloat(lastFloatFromPreviousLine);
-
-    bool lineOverlapsWithFloat = (floatLogicalTop < lineLogicalBottom) && (lineLogicalTop < floatLogicalBottom);
-    if (!lineOverlapsWithFloat)
-        return;
-
-    float minSegmentWidth = firstPositiveWidth(wordMeasurements);
-
-    LayoutUnit floatLogicalWidth = block->logicalWidthForFloat(lastFloatFromPreviousLine);
-    LayoutUnit availableLogicalWidth = block->logicalWidth() - block->logicalRightForFloat(lastFloatFromPreviousLine);
-    if (availableLogicalWidth < minSegmentWidth)
-        block->setLogicalHeight(floatLogicalBottom);
-
-    if (block->logicalHeight() < floatLogicalTop) {
-        shapeInsideInfo->adjustLogicalLineTop(minSegmentWidth + floatLogicalWidth);
-        block->setLogicalHeight(shapeInsideInfo->logicalLineTop() - logicalOffsetFromShapeContainer);
-    }
-
-    lineLogicalTop = block->logicalHeight() + logicalOffsetFromShapeContainer;
-
-    shapeInsideInfo->updateSegmentsForLine(lineLogicalTop, lineLogicalHeight);
-    width.updateCurrentShapeSegment();
-    width.updateAvailableWidth();
-}
-
-inline bool BreakingContext::handleText(WordMeasurements& wordMeasurements, bool& hyphenated)
-{
-    if (!m_current.m_pos)
-        m_appliedStartWidth = false;
-
-    RenderText* renderText = toRenderText(m_current.m_obj);
-
-    bool isSVGText = renderText->isSVGInlineText();
-
-    if (renderText->style()->hasTextCombine() && m_current.m_obj->isCombineText() && !toRenderCombineText(m_current.m_obj)->isCombined()) {
-        RenderCombineText* combineRenderer = toRenderCombineText(m_current.m_obj);
-        combineRenderer->combineText();
-        // The length of the renderer's text may have changed. Increment stale iterator positions
-        if (iteratorIsBeyondEndOfRenderCombineText(m_lineBreak, combineRenderer)) {
-            ASSERT(iteratorIsBeyondEndOfRenderCombineText(m_resolver.position(), combineRenderer));
-            m_lineBreak.increment();
-            m_resolver.position().increment(&m_resolver);
-        }
-    }
-
-    RenderStyle* style = renderText->style(m_lineInfo.isFirstLine());
-    const Font& font = style->font();
-    bool isFixedPitch = font.isFixedPitch();
-
-    unsigned lastSpace = m_current.m_pos;
-    float wordSpacing = m_currentStyle->wordSpacing();
-    float lastSpaceWordSpacing = 0;
-    float wordSpacingForWordMeasurement = 0;
-
-    float wrapW = m_width.uncommittedWidth() + inlineLogicalWidth(m_current.m_obj, !m_appliedStartWidth, true);
-    float charWidth = 0;
-    // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
-    // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
-    bool breakWords = m_currentStyle->breakWords() && ((m_autoWrap && !m_width.committedWidth()) || m_currWS == PRE);
-    bool midWordBreak = false;
-    bool breakAll = m_currentStyle->wordBreak() == BreakAllWordBreak && m_autoWrap;
-    float hyphenWidth = 0;
-
-    if (isSVGText) {
-        breakWords = false;
-        breakAll = false;
-    }
-
-    if (renderText->isWordBreak()) {
-        m_width.commit();
-        m_lineBreak.moveToStartOf(m_current.m_obj);
-        ASSERT(m_current.m_pos == renderText->textLength());
-    }
-
-    if (m_renderTextInfo.m_text != renderText) {
-        m_renderTextInfo.m_text = renderText;
-        m_renderTextInfo.m_font = &font;
-        m_renderTextInfo.m_layout = font.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
-        m_renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(renderText->text(), style->locale());
-    } else if (m_renderTextInfo.m_layout && m_renderTextInfo.m_font != &font) {
-        m_renderTextInfo.m_font = &font;
-        m_renderTextInfo.m_layout = font.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
-    }
-
-    TextLayout* textLayout = m_renderTextInfo.m_layout.get();
-
-    // Non-zero only when kerning is enabled and TextLayout isn't used, in which case we measure
-    // words with their trailing space, then subtract its width.
-    float wordTrailingSpaceWidth = (font.typesettingFeatures() & Kerning) && !textLayout ? font.width(RenderBlockFlow::constructTextRun(renderText, font, &space, 1, style)) + wordSpacing : 0;
-
-    UChar lastCharacter = m_renderTextInfo.m_lineBreakIterator.lastCharacter();
-    UChar secondToLastCharacter = m_renderTextInfo.m_lineBreakIterator.secondToLastCharacter();
-    for (; m_current.m_pos < renderText->textLength(); m_current.fastIncrementInTextNode()) {
-        bool previousCharacterIsSpace = m_currentCharacterIsSpace;
-        bool previousCharacterShouldCollapseIfPreWap = m_currentCharacterShouldCollapseIfPreWap;
-        UChar c = m_current.current();
-        m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = c == ' ' || c == '\t' || (!m_preservesNewline && (c == '\n'));
-
-        if (!m_collapseWhiteSpace || !m_currentCharacterIsSpace)
-            m_lineInfo.setEmpty(false, m_block, &m_width);
-
-        if (c == softHyphen && m_autoWrap && !hyphenWidth) {
-            hyphenWidth = measureHyphenWidth(renderText, font);
-            m_width.addUncommittedWidth(hyphenWidth);
-        }
-
-        bool applyWordSpacing = false;
-
-        if ((breakAll || breakWords) && !midWordBreak) {
-            wrapW += charWidth;
-            bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && m_current.m_pos + 1 < renderText->textLength() && U16_IS_TRAIL((*renderText)[m_current.m_pos + 1]);
-            charWidth = textWidth(renderText, m_current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, font, m_width.committedWidth() + wrapW, isFixedPitch, m_collapseWhiteSpace, 0, textLayout);
-            midWordBreak = m_width.committedWidth() + wrapW + charWidth > m_width.availableWidth();
-        }
-
-        bool betweenWords = c == '\n' || (m_currWS != PRE && !m_atStart && isBreakable(m_renderTextInfo.m_lineBreakIterator, m_current.m_pos, m_current.m_nextBreakablePosition));
-
-        if (betweenWords || midWordBreak) {
-            bool stoppedIgnoringSpaces = false;
-            if (m_ignoringSpaces) {
-                lastSpaceWordSpacing = 0;
-                if (!m_currentCharacterIsSpace) {
-                    // Stop ignoring spaces and begin at this
-                    // new point.
-                    m_ignoringSpaces = false;
-                    wordSpacingForWordMeasurement = 0;
-                    lastSpace = m_current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
-                    stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.m_obj, m_current.m_pos));
-                    stoppedIgnoringSpaces = true;
-                } else {
-                    // Just keep ignoring these spaces.
-                    nextCharacter(c, lastCharacter, secondToLastCharacter);
-                    continue;
-                }
-            }
-
-            wordMeasurements.grow(wordMeasurements.size() + 1);
-            WordMeasurement& wordMeasurement = wordMeasurements.last();
-
-            wordMeasurement.renderer = renderText;
-            wordMeasurement.endOffset = m_current.m_pos;
-            wordMeasurement.startOffset = lastSpace;
-
-            float additionalTmpW;
-            if (wordTrailingSpaceWidth && c == ' ')
-                additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos + 1 - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth;
-            else
-                additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
-
-            wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement;
-            additionalTmpW += lastSpaceWordSpacing;
-            m_width.addUncommittedWidth(additionalTmpW);
-            if (!m_appliedStartWidth) {
-                m_width.addUncommittedWidth(inlineLogicalWidth(m_current.m_obj, true, false));
-                m_appliedStartWidth = true;
-            }
-
-            if (m_lastFloatFromPreviousLine)
-                updateSegmentsForShapes(m_block, m_lastFloatFromPreviousLine, wordMeasurements, m_width, m_lineInfo.isFirstLine());
-
-            applyWordSpacing = wordSpacing && m_currentCharacterIsSpace;
-
-            if (!m_width.committedWidth() && m_autoWrap && !m_width.fitsOnLine())
-                m_width.fitBelowFloats();
-
-            if (m_autoWrap || breakWords) {
-                // If we break only after white-space, consider the current character
-                // as candidate width for this line.
-                bool lineWasTooWide = false;
-                if (m_width.fitsOnLine() && m_currentCharacterIsSpace && m_currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
-                    float charWidth = textWidth(renderText, m_current.m_pos, 1, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0);
-                    // Check if line is too big even without the extra space
-                    // at the end of the line. If it is not, do nothing.
-                    // If the line needs the extra whitespace to be too long,
-                    // then move the line break to the space and skip all
-                    // additional whitespace.
-                    if (!m_width.fitsOnLine(charWidth)) {
-                        lineWasTooWide = true;
-                        m_lineBreak.moveTo(m_current.m_obj, m_current.m_pos, m_current.m_nextBreakablePosition);
-                        skipTrailingWhitespace(m_lineBreak, m_lineInfo);
-                    }
-                }
-                if (lineWasTooWide || !m_width.fitsOnLine()) {
-                    if (m_lineBreak.atTextParagraphSeparator()) {
-                        if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
-                            ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
-                        m_lineBreak.increment();
-                        m_lineInfo.setPreviousLineBrokeCleanly(true);
-                        wordMeasurement.endOffset = m_lineBreak.m_pos;
-                    }
-                    if (m_lineBreak.m_obj && m_lineBreak.m_pos && m_lineBreak.m_obj->isText() && toRenderText(m_lineBreak.m_obj)->textLength() && toRenderText(m_lineBreak.m_obj)->characterAt(m_lineBreak.m_pos - 1) == softHyphen)
-                        hyphenated = true;
-                    if (m_lineBreak.m_pos && m_lineBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) {
-                        if (charWidth) {
-                            wordMeasurement.endOffset = m_lineBreak.m_pos;
-                            wordMeasurement.width = charWidth;
-                        }
-                    }
-                    // Didn't fit. Jump to the end unless there's still an opportunity to collapse whitespace.
-                    if (m_ignoringSpaces || !m_collapseWhiteSpace || !m_currentCharacterIsSpace || !previousCharacterIsSpace) {
-                        m_atEnd = true;
-                        return false;
-                    }
-                } else {
-                    if (!betweenWords || (midWordBreak && !m_autoWrap))
-                        m_width.addUncommittedWidth(-additionalTmpW);
-                    if (hyphenWidth) {
-                        // Subtract the width of the soft hyphen out since we fit on a line.
-                        m_width.addUncommittedWidth(-hyphenWidth);
-                        hyphenWidth = 0;
-                    }
-                }
-            }
-
-            if (c == '\n' && m_preservesNewline) {
-                if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
-                    ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
-                m_lineBreak.moveTo(m_current.m_obj, m_current.m_pos, m_current.m_nextBreakablePosition);
-                m_lineBreak.increment();
-                m_lineInfo.setPreviousLineBrokeCleanly(true);
-                return true;
-            }
-
-            if (m_autoWrap && betweenWords) {
-                m_width.commit();
-                wrapW = 0;
-                m_lineBreak.moveTo(m_current.m_obj, m_current.m_pos, m_current.m_nextBreakablePosition);
-                // Auto-wrapping text should not wrap in the middle of a word once it has had an
-                // opportunity to break after a word.
-                breakWords = false;
-            }
-
-            if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
-                // Remember this as a breakable position in case
-                // adding the end width forces a break.
-                m_lineBreak.moveTo(m_current.m_obj, m_current.m_pos, m_current.m_nextBreakablePosition);
-                midWordBreak &= (breakWords || breakAll);
-            }
-
-            if (betweenWords) {
-                lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
-                wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0;
-                lastSpace = m_current.m_pos;
-            }
-
-            if (!m_ignoringSpaces && m_currentStyle->collapseWhiteSpace()) {
-                // If we encounter a newline, or if we encounter a
-                // second space, we need to go ahead and break up this
-                // run and enter a mode where we start collapsing spaces.
-                if (m_currentCharacterIsSpace && previousCharacterIsSpace) {
-                    m_ignoringSpaces = true;
-
-                    // We just entered a mode where we are ignoring
-                    // spaces. Create a midpoint to terminate the run
-                    // before the second space.
-                    startIgnoringSpaces(m_lineMidpointState, m_startOfIgnoredSpaces);
-                    m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
-                }
-            }
-        } else if (m_ignoringSpaces) {
-            // Stop ignoring spaces and begin at this
-            // new point.
-            m_ignoringSpaces = false;
-            lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
-            wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0;
-            lastSpace = m_current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
-            stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.m_obj, m_current.m_pos));
-        }
-
-        if (isSVGText && m_current.m_pos > 0) {
-            // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
-            if (toRenderSVGInlineText(renderText)->characterStartsNewTextChunk(m_current.m_pos))
-                ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
-        }
-
-        if (m_currentCharacterIsSpace && !previousCharacterIsSpace) {
-            m_startOfIgnoredSpaces.m_obj = m_current.m_obj;
-            m_startOfIgnoredSpaces.m_pos = m_current.m_pos;
-        }
-
-        if (!m_currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) {
-            if (m_autoWrap && m_currentStyle->breakOnlyAfterWhiteSpace())
-                m_lineBreak.moveTo(m_current.m_obj, m_current.m_pos, m_current.m_nextBreakablePosition);
-        }
-
-        if (m_collapseWhiteSpace && m_currentCharacterIsSpace && !m_ignoringSpaces)
-            m_trailingObjects.setTrailingWhitespace(toRenderText(m_current.m_obj));
-        else if (!m_currentStyle->collapseWhiteSpace() || !m_currentCharacterIsSpace)
-            m_trailingObjects.clear();
-
-        m_atStart = false;
-        nextCharacter(c, lastCharacter, secondToLastCharacter);
-    }
-
-    m_renderTextInfo.m_lineBreakIterator.setPriorContext(lastCharacter, secondToLastCharacter);
-
-    wordMeasurements.grow(wordMeasurements.size() + 1);
-    WordMeasurement& wordMeasurement = wordMeasurements.last();
-    wordMeasurement.renderer = renderText;
-
-    // IMPORTANT: current.m_pos is > length here!
-    float additionalTmpW = m_ignoringSpaces ? 0 : textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
-    wordMeasurement.startOffset = lastSpace;
-    wordMeasurement.endOffset = m_current.m_pos;
-    wordMeasurement.width = m_ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement;
-    additionalTmpW += lastSpaceWordSpacing;
-    m_width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(m_current.m_obj, !m_appliedStartWidth, m_includeEndWidth));
-    m_includeEndWidth = false;
-
-    if (!m_width.fitsOnLine()) {
-        if (!hyphenated && m_lineBreak.previousInSameNode() == softHyphen) {
-            hyphenated = true;
-            m_atEnd = true;
-        }
-    }
-    return false;
-}
-
-inline void BreakingContext::commitAndUpdateLineBreakIfNeeded()
-{
-    bool checkForBreak = m_autoWrap;
-    if (m_width.committedWidth() && !m_width.fitsOnLine() && m_lineBreak.m_obj && m_currWS == NOWRAP) {
-        checkForBreak = true;
-    } else if (m_nextObject && m_current.m_obj->isText() && m_nextObject->isText() && !m_nextObject->isBR() && (m_autoWrap || m_nextObject->style()->autoWrap())) {
-        if (m_autoWrap && m_currentCharacterIsSpace) {
-            checkForBreak = true;
-        } else {
-            RenderText* nextText = toRenderText(m_nextObject);
-            if (nextText->textLength()) {
-                UChar c = nextText->characterAt(0);
-                // If the next item on the line is text, and if we did not end with
-                // a space, then the next text run continues our word (and so it needs to
-                // keep adding to the uncommitted width. Just update and continue.
-                checkForBreak = !m_currentCharacterIsSpace && (c == ' ' || c == '\t' || (c == '\n' && !m_nextObject->preservesNewline()));
-            } else if (nextText->isWordBreak()) {
-                checkForBreak = true;
-            }
-
-            if (!m_width.fitsOnLine() && !m_width.committedWidth())
-                m_width.fitBelowFloats();
-
-            bool canPlaceOnLine = m_width.fitsOnLine() || !m_autoWrapWasEverTrueOnLine;
-            if (canPlaceOnLine && checkForBreak) {
-                m_width.commit();
-                m_lineBreak.moveToStartOf(m_nextObject);
-            }
-        }
-    }
-
-    if (checkForBreak && !m_width.fitsOnLine()) {
-        // if we have floats, try to get below them.
-        if (m_currentCharacterIsSpace && !m_ignoringSpaces && m_currentStyle->collapseWhiteSpace())
-            m_trailingObjects.clear();
-
-        if (m_width.committedWidth()) {
-            m_atEnd = true;
-            return;
-        }
-
-        m_width.fitBelowFloats();
-
-        // |width| may have been adjusted because we got shoved down past a float (thus
-        // giving us more room), so we need to retest, and only jump to
-        // the end label if we still don't fit on the line. -dwh
-        if (!m_width.fitsOnLine()) {
-            m_atEnd = true;
-            return;
-        }
-    } else if (m_blockStyle->autoWrap() && !m_width.fitsOnLine() && !m_width.committedWidth()) {
-        // If the container autowraps but the current child does not then we still need to ensure that it
-        // wraps and moves below any floats.
-        m_width.fitBelowFloats();
-    }
-
-    if (!m_current.m_obj->isFloatingOrOutOfFlowPositioned()) {
-        m_lastObject = m_current.m_obj;
-        if (m_lastObject->isReplaced() && m_autoWrap && (!m_lastObject->isImage() || m_allowImagesToBreak) && (!m_lastObject->isListMarker() || toRenderListMarker(m_lastObject)->isInside())) {
-            m_width.commit();
-            m_lineBreak.moveToStartOf(m_nextObject);
-        }
-    }
-}
-
-InlineIterator BreakingContext::handleEndOfLine()
-{
-    ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
-    bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
-
-    if (m_lineBreak == m_resolver.position() && (!m_lineBreak.m_obj || !m_lineBreak.m_obj->isBR()) && segmentAllowsOverflow) {
-        // we just add as much as possible
-        if (m_blockStyle->whiteSpace() == PRE && !m_current.m_pos) {
-            m_lineBreak.moveTo(m_lastObject, m_lastObject->isText() ? m_lastObject->length() : 0);
-        } else if (m_lineBreak.m_obj) {
-            // Don't ever break in the middle of a word if we can help it.
-            // There's no room at all. We just have to be on this line,
-            // even though we'll spill out.
-            m_lineBreak.moveTo(m_current.m_obj, m_current.m_pos);
-        }
-    }
-
-    // FIXME Bug 100049: We do not need to consume input in a multi-segment line
-    // unless no segment will.
-    // make sure we consume at least one char/object.
-    if (m_lineBreak == m_resolver.position() && segmentAllowsOverflow)
-        m_lineBreak.increment();
-
-    // Sanity check our midpoints.
-    checkMidpoints(m_lineMidpointState, m_lineBreak);
-
-    m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, m_lineBreak, TrailingObjects::CollapseFirstSpace);
-
-    // We might have made lineBreak an iterator that points past the end
-    // of the object. Do this adjustment to make it point to the start
-    // of the next object instead to avoid confusing the rest of the
-    // code.
-    if (m_lineBreak.m_pos > 0) {
-        m_lineBreak.m_pos--;
-        m_lineBreak.increment();
-    }
-
-    return m_lineBreak;
-}
-
 InlineIterator LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
 {
     reset();
@@ -3512,7 +2364,7 @@
     return true;
 }
 
-LayoutUnit RenderBlock::startAlignedOffsetForLine(LayoutUnit position, bool firstLine)
+LayoutUnit RenderBlockFlow::startAlignedOffsetForLine(LayoutUnit position, bool firstLine)
 {
     ETextAlign textAlign = style()->textAlign();
 
@@ -3530,8 +2382,7 @@
     return logicalLeft;
 }
 
-
-void RenderBlock::layoutLineGridBox()
+void RenderBlockFlow::layoutLineGridBox()
 {
     if (style()->lineGrid() == RenderStyle::initialLineGrid()) {
         setLineGridBox(0);
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 7723bc6..24cfbb6 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -43,6 +43,7 @@
 #include "core/page/Page.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBoxRegionInfo.h"
 #include "core/rendering/RenderFlexibleBox.h"
@@ -163,11 +164,6 @@
 
     ShapeOutsideInfo::removeInfo(this);
 
-    // RenderGrid keep track of its grid items, ensure that we invalidate
-    // it here. FIXME: We probably could be smarter, see RenderGrid::removeChild.
-    if (parent() && parent()->isRenderGrid())
-        toRenderGrid(parent())->dirtyGrid();
-
     RenderBoxModelObject::willBeDestroyed();
 }
 
@@ -293,8 +289,11 @@
     Length shapeMargin = style.shapeMargin();
     Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
 
+    float shapeImageThreshold = style.shapeImageThreshold();
+    float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
+
     // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
-    if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin)
+    if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
         return;
 
     if (!shapeOutside)
@@ -358,7 +357,7 @@
             if (!s_hadOverflowClip)
                 // Erase the overflow
                 repaint();
-            setHasOverflowClip();
+            setHasOverflowClip(true);
         }
     }
 
@@ -370,6 +369,8 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
+
     RenderObject* child = firstChild();
     if (!child) {
         clearNeedsLayout();
@@ -1435,6 +1436,8 @@
             return false;
         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
             return false;
+        if (childBox->hasOverflowClip() && childStyle->hasBorderRadius())
+            return false;
     }
     return true;
 }
@@ -1825,7 +1828,7 @@
     return clipRect;
 }
 
-LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
+LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb, RenderRegion* region) const
 {
     RenderRegion* containingBlockRegion = 0;
     LayoutUnit logicalTopPosition = logicalTop();
@@ -1835,7 +1838,7 @@
         containingBlockRegion = cb->clampToStartAndEndRegions(region);
     }
 
-    LayoutUnit result = cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
+    LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
 
     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
@@ -1845,7 +1848,7 @@
     if (childMarginStart > 0) {
         LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
-        LayoutUnit startOffset = cb->startOffsetForLine(logicalTopPosition, false, containingBlockRegion);
+        LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
         if (startOffset > startContentSideWithMargin)
             result += childMarginStart;
         else
@@ -1855,7 +1858,7 @@
     if (childMarginEnd > 0) {
         LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
-        LayoutUnit endOffset = cb->endOffsetForLine(logicalTopPosition, false, containingBlockRegion);
+        LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
         if (endOffset > endContentSideWithMargin)
             result += childMarginEnd;
         else
@@ -1909,7 +1912,7 @@
         logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
         containingBlockRegion = cb->clampToStartAndEndRegions(region);
     }
-    return cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
+    return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
 }
 
 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
@@ -2452,7 +2455,7 @@
     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
 
     if (shrinkToAvoidFloats() && cb->containsFloats())
-        logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
+        logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb), region));
 
     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
         return max(minPreferredLogicalWidth(), min(maxPreferredLogicalWidth(), logicalWidthResult));
@@ -3031,7 +3034,6 @@
         case Intrinsic:
         case MinIntrinsic:
         case Auto:
-        case Relative:
         case ExtendToZoom:
         case Undefined:
             return intrinsicLogicalWidth();
@@ -4327,7 +4329,7 @@
     // FIXME: Border/padding should be added for all elements but this workaround
     // is needed because we use offsets inside an "atomic" element to represent
     // positions before and after the element in deprecated editing offsets.
-    if (node() && !(editingIgnoresContent(node()) || isTableElement(node()))) {
+    if (node() && !(editingIgnoresContent(node()) || isRenderedTable(node()))) {
         rect.setX(rect.x() + borderLeft() + paddingLeft());
         rect.setY(rect.y() + paddingTop() + borderTop());
     }
@@ -4777,7 +4779,7 @@
     // writing modes, x in vertical writing modes), which is always "logical top". Apart from the
     // flipping, this method does the same as clientBoxRect().
 
-    LayoutUnit left = borderLeft();
+    LayoutUnit left = borderLeft() + (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? verticalScrollbarWidth() : 0);
     LayoutUnit top = borderTop();
     LayoutUnit right = borderRight();
     LayoutUnit bottom = borderBottom();
@@ -4792,7 +4794,10 @@
     // FIXME: when the above mentioned bug is fixed, it should hopefully be possible to call
     // clientBoxRect() or paddingBoxRect() in this method, rather than fiddling with the edges on
     // our own.
-    rect.contract(verticalScrollbarWidth(), horizontalScrollbarHeight());
+    if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+        rect.contract(0, horizontalScrollbarHeight());
+    else
+        rect.contract(verticalScrollbarWidth(), horizontalScrollbarHeight());
     return rect;
 }
 
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index cf11d56..2aa00d4 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -421,7 +421,7 @@
     // of a containing block).  HTML4 buttons, <select>s, <input>s, legends, and floating/compact elements do this.
     bool sizesLogicalWidthToFitContent(SizeType) const;
 
-    LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion*) const;
+    LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb, RenderRegion*) const;
 
     LayoutUnit computeLogicalWidthInRegionUsing(SizeType, Length logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* containingBlock, RenderRegion*) const;
     LayoutUnit computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const;
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index 072a4cf..d8f3ee8 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -65,7 +65,7 @@
 
 // This HashMap is similar to the continuation map, but connects first-letter
 // renderers to their remaining text fragments.
-typedef HashMap<const RenderBoxModelObject*, RenderObject*> FirstLetterRemainingTextMap;
+typedef HashMap<const RenderBoxModelObject*, RenderTextFragment*> FirstLetterRemainingTextMap;
 static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0;
 
 void RenderBoxModelObject::setSelectionState(SelectionState state)
@@ -1010,17 +1010,6 @@
     // Determine the background positioning area and set destRect to the background painting area.
     // destRect will be adjusted later if the background is non-repeating.
     bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
-
-#if ENABLE(FAST_MOBILE_SCROLLING)
-    if (view()->frameView() && view()->frameView()->canBlitOnScroll()) {
-        // As a side effect of an optimization to blit on scroll, we do not honor the CSS
-        // property "background-attachment: fixed" because it may result in rendering
-        // artifacts. Note, these artifacts only appear if we are blitting on scroll of
-        // a page that has fixed background images.
-        fixedAttachment = false;
-    }
-#endif
-
     if (!fixedAttachment) {
         geometry.setDestRect(snappedPaintRect);
 
@@ -1148,13 +1137,13 @@
     geometry.setDestOrigin(geometry.destRect().location());
 }
 
-static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
+static LayoutUnit computeBorderImageSide(const BorderImageLength& borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
 {
-    if (borderSlice.isRelative())
-        return borderSlice.value() * borderSide;
-    if (borderSlice.isAuto())
+    if (borderSlice.isNumber())
+        return borderSlice.number() * borderSide;
+    if (borderSlice.length().isAuto())
         return imageSide;
-    return valueForLength(borderSlice, boxExtent, renderView);
+    return valueForLength(borderSlice.length(), boxExtent, renderView);
 }
 
 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
@@ -2471,20 +2460,6 @@
     return true;
 }
 
-static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
-{
-    IntRect bounds(holeRect);
-
-    bounds.inflate(shadowBlur);
-
-    if (shadowSpread < 0)
-        bounds.inflate(-shadowSpread);
-
-    IntRect offsetBounds = bounds;
-    offsetBounds.move(-shadowOffset);
-    return unionRect(bounds, offsetBounds);
-}
-
 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
 {
     // FIXME: Deal with border-image.  Would be great to use border-image as a mask.
@@ -2638,14 +2613,14 @@
         continuation()->computeLayerHitTestRects(rects);
 }
 
-RenderObject* RenderBoxModelObject::firstLetterRemainingText() const
+RenderTextFragment* RenderBoxModelObject::firstLetterRemainingText() const
 {
     if (!firstLetterRemainingTextMap)
         return 0;
     return firstLetterRemainingTextMap->get(this);
 }
 
-void RenderBoxModelObject::setFirstLetterRemainingText(RenderObject* remainingText)
+void RenderBoxModelObject::setFirstLetterRemainingText(RenderTextFragment* remainingText)
 {
     if (remainingText) {
         if (!firstLetterRemainingTextMap)
@@ -2664,7 +2639,7 @@
     // constructed and this kludge is not called any more. So only the caret size
     // of an empty :first-line'd block is wrong. I think we can live with that.
     RenderStyle* currentStyle = firstLineStyle();
-    LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine);
+    LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine,  PositionOfInteriorLineBoxes);
 
     enum CaretAlignment { alignLeft, alignRight, alignCenter };
 
diff --git a/Source/core/rendering/RenderBoxModelObject.h b/Source/core/rendering/RenderBoxModelObject.h
index 169438c..0841e47 100644
--- a/Source/core/rendering/RenderBoxModelObject.h
+++ b/Source/core/rendering/RenderBoxModelObject.h
@@ -52,6 +52,7 @@
 };
 
 class KeyframeList;
+class RenderTextFragment;
 class StickyPositionViewportConstraints;
 
 // This class is the base for all objects that adhere to the CSS box model as described
@@ -271,8 +272,8 @@
 
 public:
     // For RenderBlocks and RenderInlines with m_style->styleType() == FIRST_LETTER, this tracks their remaining text fragments
-    RenderObject* firstLetterRemainingText() const;
-    void setFirstLetterRemainingText(RenderObject*);
+    RenderTextFragment* firstLetterRemainingText() const;
+    void setFirstLetterRemainingText(RenderTextFragment*);
 
     // These functions are only used internally to manipulate the render tree structure via remove/insert/appendChildNode.
     // Since they are typically called only to move objects around within anonymous blocks (which only have layers in
diff --git a/Source/core/rendering/RenderButton.h b/Source/core/rendering/RenderButton.h
index 704b797..33df32b 100644
--- a/Source/core/rendering/RenderButton.h
+++ b/Source/core/rendering/RenderButton.h
@@ -63,8 +63,6 @@
 
     virtual bool hasLineIfEmpty() const { return node() && node()->hasTagName(HTMLNames::inputTag); }
 
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
     RenderBlock* m_inner;
 };
 
diff --git a/Source/core/rendering/RenderCounter.cpp b/Source/core/rendering/RenderCounter.cpp
index 6b4f959..5aac629 100644
--- a/Source/core/rendering/RenderCounter.cpp
+++ b/Source/core/rendering/RenderCounter.cpp
@@ -45,7 +45,7 @@
 typedef HashMap<AtomicString, RefPtr<CounterNode> > CounterMap;
 typedef HashMap<const RenderObject*, OwnPtr<CounterMap> > CounterMaps;
 
-static CounterNode* makeCounterNode(RenderObject*, const AtomicString& identifier, bool alwaysCreateCounter);
+static CounterNode* makeCounterNode(RenderObject&, const AtomicString& identifier, bool alwaysCreateCounter);
 
 static CounterMaps& counterMaps()
 {
@@ -55,70 +55,71 @@
 
 // This function processes the renderer tree in the order of the DOM tree
 // including pseudo elements as defined in CSS 2.1.
-static RenderObject* previousInPreOrder(const RenderObject* object)
+static RenderObject* previousInPreOrder(const RenderObject& object)
 {
-    Element* self = toElement(object->node());
-    Element* previous = ElementTraversal::previousIncludingPseudo(self);
+    Element* self = toElement(object.node());
+    ASSERT(self);
+    Element* previous = ElementTraversal::previousIncludingPseudo(*self);
     while (previous && !previous->renderer())
-        previous = ElementTraversal::previousIncludingPseudo(previous);
+        previous = ElementTraversal::previousIncludingPseudo(*previous);
     return previous ? previous->renderer() : 0;
 }
 
 // This function processes the renderer tree in the order of the DOM tree
 // including pseudo elements as defined in CSS 2.1.
-static RenderObject* previousSiblingOrParent(const RenderObject* object)
+static RenderObject* previousSiblingOrParent(const RenderObject& object)
 {
-    Element* self = toElement(object->node());
-    Element* previous = ElementTraversal::pseudoAwarePreviousSibling(self);
+    Element* self = toElement(object.node());
+    ASSERT(self);
+    Element* previous = ElementTraversal::pseudoAwarePreviousSibling(*self);
     while (previous && !previous->renderer())
-        previous = ElementTraversal::pseudoAwarePreviousSibling(previous);
+        previous = ElementTraversal::pseudoAwarePreviousSibling(*previous);
     if (previous)
         return previous->renderer();
     previous = self->parentElement();
     return previous ? previous->renderer() : 0;
 }
 
-static inline Element* parentElement(RenderObject* object)
+static inline Element* parentElement(RenderObject& object)
 {
-    return toElement(object->node())->parentElement();
+    return toElement(object.node())->parentElement();
 }
 
-static inline bool areRenderersElementsSiblings(RenderObject* first, RenderObject* second)
+static inline bool areRenderersElementsSiblings(RenderObject& first, RenderObject& second)
 {
     return parentElement(first) == parentElement(second);
 }
 
 // This function processes the renderer tree in the order of the DOM tree
 // including pseudo elements as defined in CSS 2.1.
-static RenderObject* nextInPreOrder(const RenderObject* object, const Element* stayWithin, bool skipDescendants = false)
+static RenderObject* nextInPreOrder(const RenderObject& object, const Element* stayWithin, bool skipDescendants = false)
 {
-    Element* self = toElement(object->node());
-    Element* next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(self, stayWithin) : ElementTraversal::nextIncludingPseudo(self, stayWithin);
+    Element* self = toElement(object.node());
+    ASSERT(self);
+    Element* next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(*self, stayWithin) : ElementTraversal::nextIncludingPseudo(*self, stayWithin);
     while (next && !next->renderer())
-        next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(next, stayWithin) : ElementTraversal::nextIncludingPseudo(next, stayWithin);
+        next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(*next, stayWithin) : ElementTraversal::nextIncludingPseudo(*next, stayWithin);
     return next ? next->renderer() : 0;
 }
 
-static bool planCounter(RenderObject* object, const AtomicString& identifier, bool& isReset, int& value)
+static bool planCounter(RenderObject& object, const AtomicString& identifier, bool& isReset, int& value)
 {
-    ASSERT(object);
-
     // Real text nodes don't have their own style so they can't have counters.
     // We can't even look at their styles or we'll see extra resets and increments!
-    if (object->isText() && !object->isBR())
+    if (object.isText() && !object.isBR())
         return false;
-    Node* generatingNode = object->generatingNode();
+    Node* generatingNode = object.generatingNode();
     // We must have a generating node or else we cannot have a counter.
     if (!generatingNode)
         return false;
-    RenderStyle* style = object->style();
+    RenderStyle* style = object.style();
     ASSERT(style);
 
     switch (style->styleType()) {
     case NOPSEUDO:
         // Sometimes nodes have more then one renderer. Only the first one gets the counter
         // LayoutTests/http/tests/css/counter-crash.html
-        if (generatingNode->renderer() != object)
+        if (generatingNode->renderer() != &object)
             return false;
         break;
     case BEFORE:
@@ -136,9 +137,9 @@
     }
 
     if (identifier == "list-item") {
-        if (object->isListItem()) {
-            if (toRenderListItem(object)->hasExplicitValue()) {
-                value = toRenderListItem(object)->explicitValue();
+        if (object.isListItem()) {
+            if (toRenderListItem(object).hasExplicitValue()) {
+                value = toRenderListItem(object).explicitValue();
                 isReset = true;
                 return true;
             }
@@ -146,7 +147,7 @@
             isReset = false;
             return true;
         }
-        if (Node* e = object->node()) {
+        if (Node* e = object.node()) {
             if (e->hasTagName(olTag)) {
                 value = toHTMLOListElement(e)->start();
                 isReset = true;
@@ -179,7 +180,7 @@
 // reset node.
 // - Non-reset CounterNodes cannot have descendants.
 
-static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString& identifier, bool isReset, RefPtr<CounterNode>& parent, RefPtr<CounterNode>& previousSibling)
+static bool findPlaceForCounter(RenderObject& counterOwner, const AtomicString& identifier, bool isReset, RefPtr<CounterNode>& parent, RefPtr<CounterNode>& previousSibling)
 {
     // We cannot stop searching for counters with the same identifier before we also
     // check this renderer, because it may affect the positioning in the tree of our counter.
@@ -192,7 +193,7 @@
     RefPtr<CounterNode> previousSiblingProtector = 0;
 
     while (currentRenderer) {
-        CounterNode* currentCounter = makeCounterNode(currentRenderer, identifier, false);
+        CounterNode* currentCounter = makeCounterNode(*currentRenderer, identifier, false);
         if (searchEndRenderer == currentRenderer) {
             // We may be at the end of our search.
             if (currentCounter) {
@@ -200,7 +201,7 @@
                 if (previousSiblingProtector) { // But we already found another counter that we come after.
                     if (currentCounter->actsAsReset()) {
                         // We found a reset counter that is on a renderer that is a sibling of ours or a parent.
-                        if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+                        if (isReset && areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
                             // We are also a reset counter and the previous reset was on a sibling renderer
                             // hence we are the next sibling of that counter if that reset is not a root or
                             // we are a root node if that reset is a root.
@@ -221,7 +222,7 @@
                         return true;
                     }
                     // CurrentCounter, the counter at the EndSearchRenderer, is not reset.
-                    if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+                    if (!isReset || !areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
                         // If the node we are placing is not reset or we have found a counter that is attached
                         // to an ancestor of the placed counter's owner renderer we know we are a sibling of that node.
                         if (currentCounter->parent() != previousSiblingProtector->parent())
@@ -237,7 +238,7 @@
                     // previousSibling, and when we are a sibling of the end counter we must set previousSibling
                     // to currentCounter.
                     if (currentCounter->actsAsReset()) {
-                        if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+                        if (isReset && areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
                             parent = currentCounter->parent();
                             previousSibling = currentCounter;
                             return parent;
@@ -246,7 +247,7 @@
                         previousSibling = previousSiblingProtector.get();
                         return true;
                     }
-                    if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+                    if (!isReset || !areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
                         parent = currentCounter->parent();
                         previousSibling = currentCounter;
                         return true;
@@ -258,7 +259,7 @@
             // good counter, or we are a reset node and the counter on the previous sibling
             // of our owner renderer was not a reset counter.
             // Set a new goal for the end of the search.
-            searchEndRenderer = previousSiblingOrParent(currentRenderer);
+            searchEndRenderer = previousSiblingOrParent(*currentRenderer);
         } else {
             // We are searching descendants of a previous sibling of the renderer that the
             // counter being placed is attached to.
@@ -271,12 +272,12 @@
                         previousSiblingProtector = currentCounter;
                         // We are no longer interested in previous siblings of the currentRenderer or their children
                         // as counters they may have attached cannot be the previous sibling of the counter we are placing.
-                        currentRenderer = parentElement(currentRenderer)->renderer();
+                        currentRenderer = parentElement(*currentRenderer)->renderer();
                         continue;
                     }
                 } else
                     previousSiblingProtector = currentCounter;
-                currentRenderer = previousSiblingOrParent(currentRenderer);
+                currentRenderer = previousSiblingOrParent(*currentRenderer);
                 continue;
             }
         }
@@ -285,19 +286,17 @@
         // performance improvement would create more code duplication than is worthwhile in my oppinion and may further
         // impede the readability of this already complex algorithm.
         if (previousSiblingProtector)
-            currentRenderer = previousSiblingOrParent(currentRenderer);
+            currentRenderer = previousSiblingOrParent(*currentRenderer);
         else
-            currentRenderer = previousInPreOrder(currentRenderer);
+            currentRenderer = previousInPreOrder(*currentRenderer);
     }
     return false;
 }
 
-static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& identifier, bool alwaysCreateCounter)
+static CounterNode* makeCounterNode(RenderObject& object, const AtomicString& identifier, bool alwaysCreateCounter)
 {
-    ASSERT(object);
-
-    if (object->hasCounterNodeMap()) {
-        if (CounterMap* nodeMap = counterMaps().get(object)) {
+    if (object.hasCounterNodeMap()) {
+        if (CounterMap* nodeMap = counterMaps().get(&object)) {
             if (CounterNode* node = nodeMap->get(identifier))
                 return node;
         }
@@ -314,12 +313,12 @@
     if (findPlaceForCounter(object, identifier, isReset, newParent, newPreviousSibling))
         newParent->insertAfter(newNode.get(), newPreviousSibling.get(), identifier);
     CounterMap* nodeMap;
-    if (object->hasCounterNodeMap())
-        nodeMap = counterMaps().get(object);
+    if (object.hasCounterNodeMap())
+        nodeMap = counterMaps().get(&object);
     else {
         nodeMap = new CounterMap;
-        counterMaps().set(object, adoptPtr(nodeMap));
-        object->setHasCounterNodeMap(true);
+        counterMaps().set(&object, adoptPtr(nodeMap));
+        object.setHasCounterNodeMap(true);
     }
     nodeMap->set(identifier, newNode);
     if (newNode->parent())
@@ -329,7 +328,7 @@
     CounterMaps& maps = counterMaps();
     Element* stayWithin = parentElement(object);
     bool skipDescendants;
-    for (RenderObject* currentRenderer = nextInPreOrder(object, stayWithin); currentRenderer; currentRenderer = nextInPreOrder(currentRenderer, stayWithin, skipDescendants)) {
+    for (RenderObject* currentRenderer = nextInPreOrder(object, stayWithin); currentRenderer; currentRenderer = nextInPreOrder(*currentRenderer, stayWithin, skipDescendants)) {
         skipDescendants = false;
         if (!currentRenderer->hasCounterNodeMap())
             continue;
@@ -339,7 +338,7 @@
         skipDescendants = true;
         if (currentCounter->parent())
             continue;
-        if (stayWithin == parentElement(currentRenderer) && currentCounter->hasResetType())
+        if (stayWithin == parentElement(*currentRenderer) && currentCounter->hasResetType())
             break;
         newNode->insertAfter(currentCounter, newNode->lastChild(), identifier);
     }
@@ -394,7 +393,7 @@
                 break;
             beforeAfterContainer = beforeAfterContainer->parent();
         }
-        makeCounterNode(beforeAfterContainer, m_counter.identifier(), true)->addRenderer(const_cast<RenderCounter*>(this));
+        makeCounterNode(*beforeAfterContainer, m_counter.identifier(), true)->addRenderer(const_cast<RenderCounter*>(this));
         ASSERT(m_counterNode);
     }
     CounterNode* child = m_counterNode;
@@ -435,17 +434,17 @@
     for (RefPtr<CounterNode> child = node->lastDescendant(); child && child != node; child = previous) {
         previous = child->previousInPreOrder();
         child->parent()->removeChild(child.get());
-        ASSERT(counterMaps().get(child->owner())->get(identifier) == child);
-        counterMaps().get(child->owner())->remove(identifier);
+        ASSERT(counterMaps().get(&child->owner())->get(identifier) == child);
+        counterMaps().get(&child->owner())->remove(identifier);
     }
     if (CounterNode* parent = node->parent())
         parent->removeChild(node);
 }
 
-void RenderCounter::destroyCounterNodes(RenderObject* owner)
+void RenderCounter::destroyCounterNodes(RenderObject& owner)
 {
     CounterMaps& maps = counterMaps();
-    CounterMaps::iterator mapsIterator = maps.find(owner);
+    CounterMaps::iterator mapsIterator = maps.find(&owner);
     if (mapsIterator == maps.end())
         return;
     CounterMap* map = mapsIterator->value.get();
@@ -454,12 +453,12 @@
         destroyCounterNodeWithoutMapRemoval(it->key, it->value.get());
     }
     maps.remove(mapsIterator);
-    owner->setHasCounterNodeMap(false);
+    owner.setHasCounterNodeMap(false);
 }
 
-void RenderCounter::destroyCounterNode(RenderObject* owner, const AtomicString& identifier)
+void RenderCounter::destroyCounterNode(RenderObject& owner, const AtomicString& identifier)
 {
-    CounterMap* map = counterMaps().get(owner);
+    CounterMap* map = counterMaps().get(&owner);
     if (!map)
         return;
     CounterMap::iterator mapIterator = map->find(identifier);
@@ -489,26 +488,26 @@
     if (!currentRenderer)
         currentRenderer = renderer;
     while (true) {
-        destroyCounterNodes(currentRenderer);
+        destroyCounterNodes(*currentRenderer);
         if (currentRenderer == renderer)
             break;
         currentRenderer = currentRenderer->previousInPreOrder();
     }
 }
 
-static void updateCounters(RenderObject* renderer)
+static void updateCounters(RenderObject& renderer)
 {
-    ASSERT(renderer->style());
-    const CounterDirectiveMap* directiveMap = renderer->style()->counterDirectives();
+    ASSERT(renderer.style());
+    const CounterDirectiveMap* directiveMap = renderer.style()->counterDirectives();
     if (!directiveMap)
         return;
     CounterDirectiveMap::const_iterator end = directiveMap->end();
-    if (!renderer->hasCounterNodeMap()) {
+    if (!renderer.hasCounterNodeMap()) {
         for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it)
             makeCounterNode(renderer, it->key, false);
         return;
     }
-    CounterMap* counterMap = counterMaps().get(renderer);
+    CounterMap* counterMap = counterMaps().get(&renderer);
     ASSERT(counterMap);
     for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it) {
         RefPtr<CounterNode> node = counterMap->get(it->key);
@@ -545,12 +544,12 @@
     if (node && node->needsAttach())
         return; // No need to update if the parent is not attached yet
     for (RenderObject* descendant = renderer; descendant; descendant = descendant->nextInPreOrder(renderer))
-        updateCounters(descendant);
+        updateCounters(*descendant);
 }
 
-void RenderCounter::rendererStyleChanged(RenderObject* renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
+void RenderCounter::rendererStyleChanged(RenderObject& renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
 {
-    Node* node = renderer->generatingNode();
+    Node* node = renderer.generatingNode();
     if (!node || node->needsAttach())
         return; // cannot have generated content or if it can have, it will be handled during attaching
     const CounterDirectiveMap* newCounterDirectives;
@@ -577,7 +576,7 @@
                     RenderCounter::destroyCounterNode(renderer, it->key);
             }
         } else {
-            if (renderer->hasCounterNodeMap())
+            if (renderer.hasCounterNodeMap())
                 RenderCounter::destroyCounterNodes(renderer);
         }
     } else if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
diff --git a/Source/core/rendering/RenderCounter.h b/Source/core/rendering/RenderCounter.h
index 61cb9ff..85cdff3 100644
--- a/Source/core/rendering/RenderCounter.h
+++ b/Source/core/rendering/RenderCounter.h
@@ -34,11 +34,11 @@
     RenderCounter(Document*, const CounterContent&);
     virtual ~RenderCounter();
 
-    static void destroyCounterNodes(RenderObject*);
-    static void destroyCounterNode(RenderObject*, const AtomicString& identifier);
+    static void destroyCounterNodes(RenderObject&);
+    static void destroyCounterNode(RenderObject&, const AtomicString& identifier);
     static void rendererSubtreeAttached(RenderObject*);
     static void rendererRemovedFromTree(RenderObject*);
-    static void rendererStyleChanged(RenderObject*, const RenderStyle* oldStyle, const RenderStyle* newStyle);
+    static void rendererStyleChanged(RenderObject&, const RenderStyle* oldStyle, const RenderStyle* newStyle);
 
     void updateCounter();
 
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index 675bb55..3047f15 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -25,7 +25,7 @@
 #include "config.h"
 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
 
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/platform/graphics/Font.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderLayer.h"
@@ -81,11 +81,11 @@
                 if (!m_ordinalIteration)
                     m_currentOrdinal = m_forward ? 1 : m_largestOrdinal;
                 else {
-                    if (m_ordinalIteration >= m_ordinalValues.size() + 1)
+                    if (static_cast<size_t>(m_ordinalIteration) >= m_ordinalValues.size() + 1)
                         return 0;
 
                     // Only copy+sort the values once per layout even if the iterator is reset.
-                    if (static_cast<size_t>(m_ordinalValues.size()) != m_sortedOrdinalValues.size()) {
+                    if (m_ordinalValues.size() != m_sortedOrdinalValues.size()) {
                         copyToVector(m_ordinalValues, m_sortedOrdinalValues);
                         sort(m_sortedOrdinalValues.begin(), m_sortedOrdinalValues.end());
                     }
diff --git a/Source/core/rendering/RenderEmbeddedObject.cpp b/Source/core/rendering/RenderEmbeddedObject.cpp
index 9b985c6..efb8bd6 100644
--- a/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -34,6 +34,7 @@
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/Path.h"
 #include "core/plugins/PluginView.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
@@ -83,9 +84,9 @@
     Locale& locale = node ? toElement(node)->locale() : Locale::defaultLocale();
     switch (pluginUnavailabilityReason) {
     case RenderEmbeddedObject::PluginMissing:
-        return locale.queryString(WebKit::WebLocalizedString::MissingPluginText);
+        return locale.queryString(blink::WebLocalizedString::MissingPluginText);
     case RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy:
-        return locale.queryString(WebKit::WebLocalizedString::BlockedPluginText);
+        return locale.queryString(blink::WebLocalizedString::BlockedPluginText);
     }
 
     ASSERT_NOT_REACHED();
@@ -196,6 +197,7 @@
     ASSERT(needsLayout());
 
     LayoutSize oldSize = contentBoxRect().size();
+    LayoutRectRecorder recorder(*this);
 
     updateLogicalWidth();
     updateLogicalHeight();
diff --git a/Source/core/rendering/RenderFileUploadControl.cpp b/Source/core/rendering/RenderFileUploadControl.cpp
index ed97088..2fc30d0 100644
--- a/Source/core/rendering/RenderFileUploadControl.cpp
+++ b/Source/core/rendering/RenderFileUploadControl.cpp
@@ -157,7 +157,7 @@
     RenderFileUploadControl* renderer = const_cast<RenderFileUploadControl*>(this);
     float minDefaultLabelWidth = defaultWidthNumChars * font.width(constructTextRun(renderer, font, characterAsString, style(), TextRun::AllowTrailingExpansion));
 
-    const String label = toHTMLInputElement(node())->locale().queryString(WebKit::WebLocalizedString::FileButtonNoFileSelectedLabel);
+    const String label = toHTMLInputElement(node())->locale().queryString(blink::WebLocalizedString::FileButtonNoFileSelectedLabel);
     float defaultLabelWidth = font.width(constructTextRun(renderer, font, label, style(), TextRun::AllowTrailingExpansion));
     if (HTMLInputElement* button = uploadButton())
         if (RenderObject* buttonRenderer = button->renderer())
diff --git a/Source/core/rendering/RenderFileUploadControl.h b/Source/core/rendering/RenderFileUploadControl.h
index ad46230..f83bb2a 100644
--- a/Source/core/rendering/RenderFileUploadControl.h
+++ b/Source/core/rendering/RenderFileUploadControl.h
@@ -49,8 +49,6 @@
     virtual void computePreferredLogicalWidths();
     virtual void paintObject(PaintInfo&, const LayoutPoint&);
 
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
     int maxFilenameWidth() const;
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index 60dde02..f61aa8e 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -35,6 +35,7 @@
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBoxRegionInfo.h"
 #include "core/rendering/RenderInline.h"
@@ -193,6 +194,7 @@
 
 void RenderFlowThread::layout()
 {
+    LayoutRectRecorder recorder(*this);
     m_pageLogicalSizeChanged = m_regionsInvalidated && everHadLayout();
 
     // In case this is the second pass of the normal phase we need to update the auto-height regions to their initial value.
@@ -403,8 +405,9 @@
     // FIXME: This needs to be adapted for different writing modes inside the flow thread.
     RenderRegion* startRegion = regionAtBlockOffset(referencePoint.y());
     if (startRegion) {
+        RenderBoxModelObject* startRegionBox = startRegion->isRenderNamedFlowFragment() ? toRenderBoxModelObject(startRegion->parent()) : startRegion;
         // Take into account the offset coordinates of the region.
-        RenderObject* currObject = startRegion;
+        RenderObject* currObject = startRegionBox;
         RenderObject* currOffsetParentRenderer;
         Element* currOffsetParentElement;
         while ((currOffsetParentElement = currObject->offsetParent()) && (currOffsetParentRenderer = currOffsetParentElement->renderer())) {
@@ -461,7 +464,7 @@
             // and compute the object's top, relative to the region's top.
             LayoutUnit regionLogicalTop = startRegion->pageLogicalTopForOffset(top);
             LayoutUnit topRelativeToRegion = top - regionLogicalTop;
-            referencePoint.setY(startRegion->offsetTop() + topRelativeToRegion);
+            referencePoint.setY(startRegionBox->offsetTop() + topRelativeToRegion);
 
             // Since the top has been overriden, check if the
             // relative/sticky positioning must be reconsidered.
@@ -473,7 +476,7 @@
 
         // Since we're looking for the offset relative to the body, we must also
         // take into consideration the borders of the region.
-        referencePoint.move(startRegion->borderLeft(), startRegion->borderTop());
+        referencePoint.move(startRegionBox->borderLeft(), startRegionBox->borderTop());
     }
 
     return referencePoint;
@@ -872,7 +875,7 @@
             region->clearComputedAutoHeight();
 
         LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
-        LayoutUnit regionLogicalHeight = std::min<LayoutUnit>(LayoutUnit::max() / 2 - logicalHeight, region->logicalHeightOfAllFlowThreadContent());
+        LayoutUnit regionLogicalHeight = std::min<LayoutUnit>(RenderFlowThread::maxLogicalHeight() - logicalHeight, region->logicalHeightOfAllFlowThreadContent());
 
         LayoutRect regionRect(style()->direction() == LTR ? LayoutUnit() : logicalWidth() - regionLogicalWidth, logicalHeight, regionLogicalWidth, regionLogicalHeight);
 
@@ -909,7 +912,7 @@
     RenderObjectToRegionMap::iterator iter = mapToUse.find(breakChild);
     if (iter != mapToUse.end()) {
         RenderRegionList::iterator regionIter = m_regionList.find(iter->value);
-        ASSERT(regionIter != m_regionList.end());
+        ASSERT_WITH_SECURITY_IMPLICATION(regionIter != m_regionList.end());
         ASSERT((*regionIter)->hasAutoLogicalHeight());
         initializeRegionsComputedAutoHeight(*regionIter);
 
diff --git a/Source/core/rendering/RenderFlowThread.h b/Source/core/rendering/RenderFlowThread.h
index 4f1e3fa..b7b3a4d 100644
--- a/Source/core/rendering/RenderFlowThread.h
+++ b/Source/core/rendering/RenderFlowThread.h
@@ -171,6 +171,9 @@
     void popFlowThreadLayoutState();
     LayoutUnit offsetFromLogicalTopOfFirstRegion(const RenderBlock*) const;
 
+    // Used to estimate the maximum height of the flow thread.
+    static LayoutUnit maxLogicalHeight() { return LayoutUnit::max() / 2; }
+
 protected:
     virtual const char* renderName() const = 0;
 
diff --git a/Source/core/rendering/RenderFrameSet.cpp b/Source/core/rendering/RenderFrameSet.cpp
index 7f17bdf..494bdbb 100644
--- a/Source/core/rendering/RenderFrameSet.cpp
+++ b/Source/core/rendering/RenderFrameSet.cpp
@@ -34,6 +34,7 @@
 #include "core/platform/Cursor.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderFrame.h"
 #include "core/rendering/RenderView.h"
@@ -440,6 +441,7 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     bool doFullRepaint = selfNeedsLayout() && checkForRepaintDuringLayout();
     LayoutRect oldBounds;
     RenderLayerModelObject* repaintContainer = 0;
diff --git a/Source/core/rendering/RenderGeometryMap.cpp b/Source/core/rendering/RenderGeometryMap.cpp
index f9e1a6f..c525290 100644
--- a/Source/core/rendering/RenderGeometryMap.cpp
+++ b/Source/core/rendering/RenderGeometryMap.cpp
@@ -331,8 +331,7 @@
     if (!(m_mapCoordinatesFlags & TraverseDocumentBoundaries))
         return true;
 
-    Frame* thisFrame = renderer->frame();
-    return thisFrame == thisFrame->page()->mainFrame();
+    return renderer->frame()->isMainFrame();
 }
 #endif
 
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index 5264398..38c296a 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -191,11 +191,6 @@
     }
 
     RenderBox* newChildBox = toRenderBox(newChild);
-    // If the new box ends up wrapped under an anonymous block,
-    // the anonymous block will act as the grid item.
-    if (newChildBox->parent() != this)
-        return;
-
     OwnPtr<GridSpan> rowPositions = resolveGridPositionsFromStyle(newChildBox, ForRows);
     OwnPtr<GridSpan> columnPositions = resolveGridPositionsFromStyle(newChildBox, ForColumns);
     if (!rowPositions || !columnPositions) {
@@ -405,7 +400,7 @@
 
     const Length& trackLength = gridLength.length();
     ASSERT(!trackLength.isAuto());
-    if (trackLength.isFixed() || trackLength.isPercent() || trackLength.isViewportPercentage())
+    if (trackLength.isSpecified())
         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
 
     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
@@ -419,7 +414,7 @@
 
     const Length& trackLength = gridLength.length();
     ASSERT(!trackLength.isAuto());
-    if (trackLength.isFixed() || trackLength.isPercent() || trackLength.isViewportPercentage()) {
+    if (trackLength.isSpecified()) {
         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
         ASSERT(computedBreadth != infinity);
         return computedBreadth;
@@ -431,8 +426,7 @@
 
 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
 {
-    // FIXME: We still need to support calc() here (https://webkit.org/b/103761).
-    ASSERT(trackLength.isFixed() || trackLength.isPercent() || trackLength.isViewportPercentage());
+    ASSERT(trackLength.isSpecified());
     // FIXME: The -1 here should be replaced by whatever the intrinsic height of the grid is.
     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style()->logicalHeight(), -1), view());
 }
@@ -623,10 +617,13 @@
         GridTrack& track = *tracks[i];
         LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
         LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
-        LayoutUnit growthShare = std::max(LayoutUnit(), std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth));
+        LayoutUnit growthShare = std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth);
+        sizingData.distributeTrackVector[i] = trackBreadth;
         // We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function.
-        sizingData.distributeTrackVector[i] = trackBreadth + growthShare;
-        availableLogicalSpace -= growthShare;
+        if (growthShare > 0) {
+            sizingData.distributeTrackVector[i] += growthShare;
+            availableLogicalSpace -= growthShare;
+        }
     }
 
     if (availableLogicalSpace > 0 && tracksForGrowthAboveMaxBreadth) {
@@ -837,35 +834,10 @@
     m_gridIsDirty = true;
 }
 
-void RenderGrid::checkGridCoherency() const
-{
-#ifndef NDEBUG
-    HashSet<RenderBox*> childrenBoxes;
-    for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox())
-        childrenBoxes.add(child);
-
-    HashSet<RenderBox*> gridChildrenBoxes;
-    for (size_t row = 0; row < gridRowCount(); ++row) {
-        for (size_t column = 0; column < gridColumnCount(); ++column) {
-            const Vector<RenderBox*, 1>& children = m_grid[row][column];
-            for (size_t i = 0; i < children.size(); ++i)
-                gridChildrenBoxes.add(children[i]);
-        }
-    }
-
-    ASSERT(childrenBoxes.size() == gridChildrenBoxes.size());
-    HashSet<RenderBox*>::const_iterator end = gridChildrenBoxes.end();
-    for (HashSet<RenderBox*>::const_iterator it = gridChildrenBoxes.begin(); it != end; ++it)
-        ASSERT(childrenBoxes.contains(*it));
-#endif
-}
-
 void RenderGrid::layoutGridItems()
 {
     placeItemsOnGrid();
 
-    checkGridCoherency();
-
     GridSizingData sizingData(gridColumnCount(), gridRowCount());
     computedUsedBreadthOfGridTracks(ForColumns, sizingData);
     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
@@ -913,7 +885,7 @@
     for (size_t i = 0; i < sizingData.rowTracks.size(); ++i)
         setLogicalHeight(logicalHeight() + sizingData.rowTracks[i].m_usedBreadth);
 
-    // FIXME: We should handle min / max logical height.
+    // Min / max logical height is handled by the call to updateLogicalHeight in layoutBlock.
 
     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
 }
@@ -1018,7 +990,7 @@
     {
         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());
+        ASSERT_WITH_SECURITY_IMPLICATION(it != style()->namedGridArea().end());
         const GridCoordinate& gridAreaCoordinate = it->value;
         switch (side) {
         case ColumnStartSide:
diff --git a/Source/core/rendering/RenderGrid.h b/Source/core/rendering/RenderGrid.h
index f64eaa9..f8a4de3 100644
--- a/Source/core/rendering/RenderGrid.h
+++ b/Source/core/rendering/RenderGrid.h
@@ -90,8 +90,6 @@
     GridTrackSizingDirection autoPlacementMajorAxisDirection() const;
     GridTrackSizingDirection autoPlacementMinorAxisDirection() const;
 
-    void checkGridCoherency() const;
-
     void layoutGridItems();
     void populateGridPositions(const GridSizingData&);
 
diff --git a/Source/core/rendering/RenderIFrame.cpp b/Source/core/rendering/RenderIFrame.cpp
index bea0845..85016cc 100644
--- a/Source/core/rendering/RenderIFrame.cpp
+++ b/Source/core/rendering/RenderIFrame.cpp
@@ -30,6 +30,7 @@
 #include "core/html/HTMLIFrameElement.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderView.h"
 
 namespace WebCore {
@@ -123,6 +124,7 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     if (isSeamless()) {
         layoutSeamlessly();
         // Do not return so as to share the layer and overflow updates below.
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index de034ab..478152b 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -42,6 +42,7 @@
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderView.h"
 #include "core/svg/graphics/SVGImage.h"
@@ -567,6 +568,7 @@
 
 void RenderImage::layout()
 {
+    LayoutRectRecorder recorder(*this);
     RenderReplaced::layout();
     updateInnerContentRect();
 }
diff --git a/Source/core/rendering/RenderImageResourceStyleImage.cpp b/Source/core/rendering/RenderImageResourceStyleImage.cpp
index 9c3b03e..5e0fff7 100644
--- a/Source/core/rendering/RenderImageResourceStyleImage.cpp
+++ b/Source/core/rendering/RenderImageResourceStyleImage.cpp
@@ -49,7 +49,7 @@
     RenderImageResource::initialize(renderer);
 
     if (m_styleImage->isImageResource())
-        m_cachedImage = static_cast<StyleFetchedImage*>(m_styleImage.get())->cachedImage();
+        m_cachedImage = toStyleFetchedImage(m_styleImage)->cachedImage();
 
     m_styleImage->addClient(m_renderer);
 }
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index 9578848..63f310f 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -514,12 +514,11 @@
     else {
         // The goal here is to match up if we can, so that we can coalesce and create the
         // minimal # of continuations needed for the inline.
-        if (childInline == bcpInline)
+        if (childInline == bcpInline || (beforeChild && beforeChild->isInline()))
             return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
-        else if (flowInline == childInline)
+        if (flowInline == childInline)
             return flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
-        else
-            return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
+        return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
     }
 }
 
@@ -999,7 +998,7 @@
 
 LayoutRect RenderInline::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
 {
-    ASSERT(!view() || !view()->layoutStateEnabled());
+    ASSERT(!view() || !view()->layoutStateEnabled() || RuntimeEnabledFeatures::repaintAfterLayoutEnabled());
 
     if (!firstLineBoxIncludingCulling() && !continuation())
         return LayoutRect();
diff --git a/Source/core/rendering/RenderInputSpeech.cpp b/Source/core/rendering/RenderInputSpeech.cpp
index c6e83ee..0174652 100644
--- a/Source/core/rendering/RenderInputSpeech.cpp
+++ b/Source/core/rendering/RenderInputSpeech.cpp
@@ -82,16 +82,16 @@
     // Account for the local drawing offset.
     buttonRect.moveBy(rect.location());
 
-    DEFINE_STATIC_LOCAL(RefPtr<Image>, imageStateNormal, (Image::loadPlatformResource("inputSpeech")));
-    DEFINE_STATIC_LOCAL(RefPtr<Image>, imageStateRecording, (Image::loadPlatformResource("inputSpeechRecording")));
-    DEFINE_STATIC_LOCAL(RefPtr<Image>, imageStateWaiting, (Image::loadPlatformResource("inputSpeechWaiting")));
+    DEFINE_STATIC_REF(Image, imageStateNormal, (Image::loadPlatformResource("inputSpeech")));
+    DEFINE_STATIC_REF(Image, imageStateRecording, (Image::loadPlatformResource("inputSpeechRecording")));
+    DEFINE_STATIC_REF(Image, imageStateWaiting, (Image::loadPlatformResource("inputSpeechWaiting")));
 
     InputFieldSpeechButtonElement* speechButton = toInputFieldSpeechButtonElement(element);
-    Image* image = imageStateNormal.get();
+    Image* image = imageStateNormal;
     if (speechButton->state() == InputFieldSpeechButtonElement::Recording)
-        image = imageStateRecording.get();
+        image = imageStateRecording;
     else if (speechButton->state() == InputFieldSpeechButtonElement::Recognizing)
-        image = imageStateWaiting.get();
+        image = imageStateWaiting;
     paintInfo.context->drawImage(image, pixelSnappedIntRect(buttonRect));
 
     return false;
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 3c589e1..43edddd 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -48,6 +48,7 @@
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
+#include "core/animation/ActiveAnimations.h"
 #include "core/css/PseudoStyleRequest.h"
 #include "core/dom/Document.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -110,7 +111,6 @@
     , m_hasOutOfFlowPositionedDescendantDirty(true)
     , m_hasUnclippedDescendant(false)
     , m_isUnclippedDescendant(false)
-    , m_needsCompositedScrolling(false)
     , m_isRootLayer(renderer->isRenderView())
     , m_usedTransparency(false)
     , m_childLayerHasBlendMode(false)
@@ -136,7 +136,6 @@
     , m_staticInlinePosition(0)
     , m_staticBlockPosition(0)
     , m_enclosingPaginationLayer(0)
-    , m_forceNeedsCompositedScrolling(DoNotForceCompositedScrolling)
     , m_repainter(renderer)
     , m_clipper(renderer)
 {
@@ -291,7 +290,7 @@
 
     // Clear the IsCompositingUpdateRoot flag once we've found the first compositing layer in this update.
     bool isUpdateRoot = (flags & IsCompositingUpdateRoot);
-    if (compositedLayerMapping())
+    if (hasCompositedLayerMapping())
         flags &= ~IsCompositingUpdateRoot;
 
     if (useRegionBasedColumns() && renderer()->isInFlowRenderFlowThread()) {
@@ -305,7 +304,7 @@
     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
         child->updateLayerPositions(geometryMap, flags);
 
-    if ((flags & UpdateCompositingLayers) && compositedLayerMapping()) {
+    if ((flags & UpdateCompositingLayers) && hasCompositedLayerMapping()) {
         CompositedLayerMapping::UpdateAfterLayoutFlags updateFlags = CompositedLayerMapping::CompositingChildrenOnly;
         if (flags & NeedsFullRepaintInBacking)
             updateFlags |= CompositedLayerMapping::NeedsFullRepaint;
@@ -537,7 +536,7 @@
         if (!hadBlendMode || !hasBlendMode())
             dirtyAncestorChainBlendedDescendantStatus();
 
-        if (compositedLayerMapping())
+        if (hasCompositedLayerMapping())
             compositedLayerMapping()->setBlendMode(newBlendMode);
     }
 }
@@ -577,7 +576,8 @@
     if (!m_transform)
         return TransformationMatrix();
 
-    if (renderer()->style()->isRunningAcceleratedAnimation()) {
+    // FIXME: handle this under web-animations
+    if (!RuntimeEnabledFeatures::webAnimationsEnabled() && renderer()->style()->isRunningAcceleratedAnimation()) {
         TransformationMatrix currTransform;
         RefPtr<RenderStyle> style = renderer()->animation().getAnimatedStyleForRenderer(renderer());
         style->applyTransform(currTransform, renderBox()->pixelSnappedBorderBoxRect().size(), applyOrigin);
@@ -644,7 +644,7 @@
     m_isPaginated = false;
     m_enclosingPaginationLayer = 0;
 
-    if (compositedLayerMapping() || !parent())
+    if (hasCompositedLayerMapping() || !parent())
         return; // FIXME: We will have to deal with paginated compositing layers someday.
                 // FIXME: For now the RenderView can't be paginated.  Eventually printing will move to a model where it is though.
 
@@ -995,7 +995,7 @@
             localPoint += offset;
         }
     } else if (parent()) {
-        if (compositedLayerMapping()) {
+        if (hasCompositedLayerMapping()) {
             // FIXME: Composited layers ignore pagination, so about the best we can do is make sure they're offset into the appropriate column.
             // They won't split across columns properly.
             LayoutSize columnOffset;
@@ -1115,11 +1115,11 @@
 // enclosingCompositingLayerForRepaint().
 RenderLayer* RenderLayer::enclosingCompositingLayer(bool includeSelf) const
 {
-    if (includeSelf && compositedLayerMapping())
+    if (includeSelf && hasCompositedLayerMapping())
         return const_cast<RenderLayer*>(this);
 
     for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
-        if (curr->compositedLayerMapping())
+        if (curr->hasCompositedLayerMapping())
             return const_cast<RenderLayer*>(curr);
     }
 
@@ -1193,7 +1193,7 @@
 
 RenderLayer* RenderLayer::clippingRootForPainting() const
 {
-    if (compositedLayerMapping())
+    if (hasCompositedLayerMapping())
         return const_cast<RenderLayer*>(this);
 
     const RenderLayer* current = this;
@@ -1232,11 +1232,11 @@
 
 RenderLayer* RenderLayer::transparentPaintingAncestor()
 {
-    if (compositedLayerMapping())
+    if (hasCompositedLayerMapping())
         return 0;
 
     for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
-        if (curr->compositedLayerMapping())
+        if (curr->hasCompositedLayerMapping())
             return 0;
         if (curr->isTransparent())
             return curr;
@@ -1482,10 +1482,6 @@
     if (!m_parent)
         return;
 
-    // Mark that we are about to lose our layer. This makes render tree
-    // walks ignore this layer while we're removing it.
-    m_renderer->setHasLayer(false);
-
     compositor()->layerWillBeRemoved(m_parent, this);
 
     // Dirty the clip rects.
@@ -1505,8 +1501,6 @@
         removeChild(current);
         m_parent->addChild(current, nextSib);
         current->repainter().setRepaintStatus(NeedsFullRepaint);
-        // updateLayerPositions depends on hasLayer() already being false for proper layout.
-        ASSERT(!renderer()->hasLayer());
         current->updateLayerPositions(0); // FIXME: use geometry map.
         current = next;
     }
@@ -1677,26 +1671,6 @@
     rect.move(-delta.x(), -delta.y());
 }
 
-bool RenderLayer::adjustForForceCompositedScrollingMode(bool value) const
-{
-    switch (m_forceNeedsCompositedScrolling) {
-    case DoNotForceCompositedScrolling:
-        return value;
-    case CompositedScrollingAlwaysOn:
-        return true;
-    case CompositedScrollingAlwaysOff:
-        return false;
-    }
-
-    ASSERT_NOT_REACHED();
-    return value;
-}
-
-bool RenderLayer::needsCompositedScrolling() const
-{
-    return adjustForForceCompositedScrollingMode(m_needsCompositedScrolling);
-}
-
 RenderLayer* RenderLayer::scrollParent() const
 {
     if (!compositorDrivenAcceleratedScrollingEnabled())
@@ -1747,15 +1721,6 @@
     return clipParent;
 }
 
-void RenderLayer::setForceNeedsCompositedScrolling(RenderLayer::ForceNeedsCompositedScrollingMode mode)
-{
-    if (m_forceNeedsCompositedScrolling == mode)
-        return;
-
-    m_forceNeedsCompositedScrolling = mode;
-    didUpdateNeedsCompositedScrolling();
-}
-
 void RenderLayer::didUpdateNeedsCompositedScrolling()
 {
     m_stackingNode->updateIsNormalFlowOnly();
@@ -1801,8 +1766,8 @@
 
 PassOwnPtr<Vector<FloatRect> > RenderLayer::collectTrackedRepaintRects() const
 {
-    if (CompositedLayerMapping* mapping = compositedLayerMapping())
-        return mapping->collectTrackedRepaintRects();
+    if (hasCompositedLayerMapping())
+        return compositedLayerMapping()->collectTrackedRepaintRects();
     return nullptr;
 }
 
@@ -2057,10 +2022,10 @@
     ClipperContext clipperContext;
     if (renderer()->hasClipPath() && !context->paintingDisabled() && style) {
         ASSERT(style->clipPath());
-        if (style->clipPath()->getOperationType() == ClipPathOperation::SHAPE) {
+        if (style->clipPath()->type() == ClipPathOperation::SHAPE) {
             hasClipPath = true;
             context->save();
-            ShapeClipPathOperation* clipPath = static_cast<ShapeClipPathOperation*>(style->clipPath());
+            ShapeClipPathOperation* clipPath = toShapeClipPathOperation(style->clipPath());
 
             if (!rootRelativeBoundsComputed) {
                 rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, &offsetFromRoot, 0);
@@ -2068,8 +2033,8 @@
             }
 
             context->clipPath(clipPath->path(rootRelativeBounds), clipPath->windRule());
-        } else if (style->clipPath()->getOperationType() == ClipPathOperation::REFERENCE) {
-            ReferenceClipPathOperation* referenceClipPathOperation = static_cast<ReferenceClipPathOperation*>(style->clipPath());
+        } else if (style->clipPath()->type() == ClipPathOperation::REFERENCE) {
+            ReferenceClipPathOperation* referenceClipPathOperation = toReferenceClipPathOperation(style->clipPath());
             Document& document = renderer()->document();
             // FIXME: It doesn't work with forward or external SVG references (https://bugs.webkit.org/show_bug.cgi?id=90405)
             Element* element = document.getElementById(referenceClipPathOperation->fragment());
@@ -2178,7 +2143,7 @@
                 localPaintingInfo, paintBehavior, paintingRootForRenderer);
 
     if (shouldPaintNegZOrderList)
-        paintList(m_stackingNode->negZOrderList(), context, localPaintingInfo, paintFlags);
+        paintChildren(NegativeZOrderChildren, context, localPaintingInfo, paintFlags);
 
     if (shouldPaintOwnContents)
         paintForegroundForFragments(layerFragments, context, transparencyLayerContext, paintingInfo.paintDirtyRect, haveTransparency,
@@ -2187,10 +2152,8 @@
     if (shouldPaintOutline)
         paintOutlineForFragments(layerFragments, context, localPaintingInfo, paintBehavior, paintingRootForRenderer);
 
-    if (shouldPaintNormalFlowAndPosZOrderLists) {
-        paintList(m_stackingNode->normalFlowList(), context, localPaintingInfo, paintFlags);
-        paintList(m_stackingNode->posZOrderList(), context, localPaintingInfo, paintFlags);
-    }
+    if (shouldPaintNormalFlowAndPosZOrderLists)
+        paintChildren(NormalFlowChildren | PositiveZOrderChildren, context, localPaintingInfo, paintFlags);
 
     if (shouldPaintOverlayScrollbars)
         paintOverflowControlsForFragments(layerFragments, context, localPaintingInfo);
@@ -2251,11 +2214,8 @@
     paintLayerContentsAndReflection(context, transformedPaintingInfo, paintFlags);
 }
 
-void RenderLayer::paintList(Vector<RenderLayerStackingNode*>* list, GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
+void RenderLayer::paintChildren(unsigned childrenToVisit, GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
 {
-    if (!list)
-        return;
-
     if (!hasSelfPaintingLayerDescendant())
         return;
 
@@ -2263,8 +2223,9 @@
     LayerListMutationDetector mutationChecker(m_stackingNode.get());
 #endif
 
-    for (size_t i = 0; i < list->size(); ++i) {
-        RenderLayer* childLayer = list->at(i)->layer();
+    RenderLayerStackingNodeIterator iterator(*m_stackingNode, childrenToVisit);
+    while (RenderLayerStackingNode* child = iterator.next()) {
+        RenderLayer* childLayer = child->layer();
         if (!childLayer->isPaginated())
             childLayer->paintLayer(context, paintingInfo, paintFlags);
         else
@@ -2901,7 +2862,7 @@
     RenderLayer* candidateLayer = 0;
 
     // Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
-    RenderLayer* hitLayer = hitTestList(m_stackingNode->posZOrderList(), rootLayer, request, result, hitTestRect, hitTestLocation,
+    RenderLayer* hitLayer = hitTestChildren(PositiveZOrderChildren, rootLayer, request, result, hitTestRect, hitTestLocation,
                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
     if (hitLayer) {
         if (!depthSortDescendants)
@@ -2910,7 +2871,7 @@
     }
 
     // Now check our overflow objects.
-    hitLayer = hitTestList(m_stackingNode->normalFlowList(), rootLayer, request, result, hitTestRect, hitTestLocation,
+    hitLayer = hitTestChildren(NormalFlowChildren, rootLayer, request, result, hitTestRect, hitTestLocation,
                            localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
     if (hitLayer) {
         if (!depthSortDescendants)
@@ -2948,7 +2909,7 @@
     }
 
     // Now check our negative z-index children.
-    hitLayer = hitTestList(m_stackingNode->negZOrderList(), rootLayer, request, result, hitTestRect, hitTestLocation,
+    hitLayer = hitTestChildren(NegativeZOrderChildren, rootLayer, request, result, hitTestRect, hitTestLocation,
         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
     if (hitLayer) {
         if (!depthSortDescendants)
@@ -3091,23 +3052,21 @@
     return true;
 }
 
-RenderLayer* RenderLayer::hitTestList(Vector<RenderLayerStackingNode*>* list, RenderLayer* rootLayer,
-                                      const HitTestRequest& request, HitTestResult& result,
-                                      const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation,
-                                      const HitTestingTransformState* transformState,
-                                      double* zOffsetForDescendants, double* zOffset,
-                                      const HitTestingTransformState* unflattenedTransformState,
-                                      bool depthSortDescendants)
+RenderLayer* RenderLayer::hitTestChildren(ChildrenIteration childrentoVisit, RenderLayer* rootLayer,
+    const HitTestRequest& request, HitTestResult& result,
+    const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation,
+    const HitTestingTransformState* transformState,
+    double* zOffsetForDescendants, double* zOffset,
+    const HitTestingTransformState* unflattenedTransformState,
+    bool depthSortDescendants)
 {
-    if (!list)
-        return 0;
-
     if (!hasSelfPaintingLayerDescendant())
         return 0;
 
     RenderLayer* resultLayer = 0;
-    for (int i = list->size() - 1; i >= 0; --i) {
-        RenderLayer* childLayer = list->at(i)->layer();
+    RenderLayerStackingNodeReverseIterator iterator(*m_stackingNode, childrentoVisit);
+    while (RenderLayerStackingNode* child = iterator.next()) {
+        RenderLayer* childLayer = child->layer();
         RenderLayer* hitLayer = 0;
         HitTestResult tempResult(result.hitTestLocation());
         if (childLayer->isPaginated())
@@ -3620,13 +3579,13 @@
 
     if (m_reflectionInfo) {
         RenderLayer* reflectionLayer = m_reflectionInfo->reflectionLayer();
-        if (!reflectionLayer->compositedLayerMapping()) {
+        if (!reflectionLayer->hasCompositedLayerMapping()) {
             IntRect childUnionBounds = reflectionLayer->calculateLayerBounds(this, 0, descendantFlags);
             unionBounds.unite(childUnionBounds);
         }
     }
 
-    ASSERT(m_stackingNode->isStackingContainer() || (!m_stackingNode->posZOrderList() || !m_stackingNode->posZOrderList()->size()));
+    ASSERT(m_stackingNode->isStackingContainer() || !m_stackingNode->hasPositiveZOrderList());
 
 #if !ASSERT_DISABLED
     LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(this)->stackingNode());
@@ -3637,7 +3596,15 @@
     // This applies to all z-order lists below.
     RenderLayerStackingNodeIterator iterator(*m_stackingNode.get(), AllChildren);
     while (RenderLayerStackingNode* node = iterator.next()) {
-        if (flags & IncludeCompositedDescendants || !node->layer()->compositedLayerMapping()) {
+        // Node's compositing ancestor may have changed its draw content status
+        // prior to updating its bounds. The requires-own-backing-store-for-ancestor-reasons
+        // could be stale. Refresh them now.
+        if (node->layer()->hasCompositedLayerMapping()) {
+            RenderLayer* enclosingCompositingLayer = node->layer()->enclosingCompositingLayer(false);
+            node->layer()->compositedLayerMapping()->updateRequiresOwnBackingStoreForAncestorReasons(enclosingCompositingLayer);
+        }
+
+        if (flags & IncludeCompositedDescendants || !node->layer()->hasCompositedLayerMapping()) {
             IntRect childUnionBounds = node->layer()->calculateLayerBounds(this, 0, descendantFlags);
             unionBounds.unite(childUnionBounds);
         }
@@ -3680,7 +3647,7 @@
     return PaintsIntoOwnBacking;
 }
 
-CompositedLayerMapping* RenderLayer::ensureCompositedLayerMapping()
+CompositedLayerMappingPtr RenderLayer::ensureCompositedLayerMapping()
 {
     if (!m_compositedLayerMapping) {
         m_compositedLayerMapping = adoptPtr(new CompositedLayerMapping(this));
@@ -3755,19 +3722,15 @@
     if (renderer()->hasOverflowClip())
         return false;
 
-    return listBackgroundIsKnownToBeOpaqueInRect(m_stackingNode->posZOrderList(), localRect)
-        || listBackgroundIsKnownToBeOpaqueInRect(m_stackingNode->negZOrderList(), localRect)
-        || listBackgroundIsKnownToBeOpaqueInRect(m_stackingNode->normalFlowList(), localRect);
+    return childBackgroundIsKnownToBeOpaqueInRect(localRect);
 }
 
-bool RenderLayer::listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayerStackingNode*>* list, const LayoutRect& localRect) const
+bool RenderLayer::childBackgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
 {
-    if (!list || list->isEmpty())
-        return false;
-
-    for (Vector<RenderLayerStackingNode*>::const_reverse_iterator iter = list->rbegin(); iter != list->rend(); ++iter) {
-        const RenderLayer* childLayer = (*iter)->layer();
-        if (childLayer->compositedLayerMapping())
+    RenderLayerStackingNodeReverseIterator revertseIterator(*m_stackingNode, PositiveZOrderChildren | NormalFlowChildren | NegativeZOrderChildren);
+    while (RenderLayerStackingNode* child = revertseIterator.next()) {
+        const RenderLayer* childLayer = child->layer();
+        if (childLayer->hasCompositedLayerMapping())
             continue;
 
         if (!childLayer->canUseConvertToLayerCoords())
@@ -3814,8 +3777,8 @@
 
 void RenderLayer::updateSelfPaintingLayer()
 {
-    bool isSelfPaintingLayer = shouldBeSelfPaintingLayer();
-    if (m_isSelfPaintingLayer == isSelfPaintingLayer)
+    bool isSelfPaintingLayer = this->shouldBeSelfPaintingLayer();
+    if (this->isSelfPaintingLayer() == isSelfPaintingLayer)
         return;
 
     m_isSelfPaintingLayer = isSelfPaintingLayer;
@@ -3940,7 +3903,7 @@
 inline bool RenderLayer::needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const
 {
     ASSERT(newStyle);
-    return !compositedLayerMapping() && oldStyle && (oldStyle->overflowX() != newStyle->overflowX()) && m_stackingNode->ancestorStackingContainerNode()->layer()->hasCompositingDescendant();
+    return !hasCompositedLayerMapping() && oldStyle && (oldStyle->overflowX() != newStyle->overflowX()) && m_stackingNode->ancestorStackingContainerNode()->layer()->hasCompositingDescendant();
 }
 
 inline bool RenderLayer::needsCompositingLayersRebuiltForFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle, bool didPaintWithFilters) const
@@ -3948,7 +3911,10 @@
     if (!hasOrHadFilters(oldStyle, newStyle))
         return false;
 
-    if (renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)) {
+    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+        ? hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter)
+        : renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)) {
+
         // When the compositor is performing the filter animation, we shouldn't touch the compositing layers.
         // All of the layers above us should have been promoted to compositing layers already.
         return false;
@@ -3984,8 +3950,9 @@
     updateOrRemoveFilterClients();
     // During an accelerated animation, both WebKit and the compositor animate properties.
     // However, WebKit shouldn't ask the compositor to update its filters if the compositor is performing the animation.
-    bool shouldUpdateFilters = compositedLayerMapping() && !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter);
-    if (shouldUpdateFilters)
+    if (hasCompositedLayerMapping() && (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+        ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter)
+        : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)))
         compositedLayerMapping()->updateFilters(renderer()->style());
     updateOrRemoveFilterEffectRenderer();
 }
@@ -4023,7 +3990,7 @@
         || needsCompositingLayersRebuiltForOverflow(oldStyle, newStyle)
         || needsCompositingLayersRebuiltForFilters(oldStyle, newStyle, didPaintWithFilters))
         compositor()->setCompositingLayersNeedRebuild();
-    else if (compositedLayerMapping())
+    else if (hasCompositedLayerMapping())
         compositedLayerMapping()->updateGraphicsLayerGeometry();
 }
 
@@ -4048,9 +4015,9 @@
     if (filters.hasReferenceFilter()) {
         for (size_t i = 0; i < filters.size(); ++i) {
             FilterOperation* filterOperation = filters.operations().at(i).get();
-            if (filterOperation->getOperationType() != FilterOperation::REFERENCE)
+            if (filterOperation->type() != FilterOperation::REFERENCE)
                 continue;
-            ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
+            ReferenceFilterOperation* referenceOperation = toReferenceFilterOperation(filterOperation);
             // FIXME: Cache the ReferenceFilter if it didn't change.
             RefPtr<ReferenceFilter> referenceFilter = ReferenceFilter::create();
             float zoom = style->effectiveZoom() * WebCore::deviceScaleFactor(renderer()->frame());
@@ -4074,10 +4041,10 @@
     FilterOperations outputFilters;
     for (size_t i = 0; i < filters.size(); ++i) {
         RefPtr<FilterOperation> filterOperation = filters.operations().at(i);
-        if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
+        if (filterOperation->type() == FilterOperation::CUSTOM) {
             // We have to wait until the program of CSS Shaders is loaded before setting it on the layer.
             // Note that we will handle the loading of the shaders and repainting of the layer in updateOrRemoveFilterClients.
-            const CustomFilterOperation* customOperation = static_cast<const CustomFilterOperation*>(filterOperation.get());
+            const CustomFilterOperation* customOperation = toCustomFilterOperation(filterOperation.get());
             RefPtr<CustomFilterProgram> program = customOperation->program();
             if (!program->isLoaded())
                 continue;
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index 4d4749c..3fd2d65 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -45,20 +45,20 @@
 #ifndef RenderLayer_h
 #define RenderLayer_h
 
+#include "core/rendering/CompositedLayerMappingPtr.h"
 #include "core/rendering/CompositingReasons.h"
 #include "core/rendering/LayerPaintingInfo.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderLayerClipper.h"
+#include "core/rendering/RenderLayerFilterInfo.h"
 #include "core/rendering/RenderLayerReflectionInfo.h"
 #include "core/rendering/RenderLayerRepainter.h"
 #include "core/rendering/RenderLayerScrollableArea.h"
 #include "core/rendering/RenderLayerStackingNode.h"
-
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
 #include "wtf/OwnPtr.h"
 
-#include "core/rendering/RenderLayerFilterInfo.h"
-
 namespace WebCore {
 
 class FilterEffectRenderer;
@@ -345,16 +345,18 @@
 
     CompositingState compositingState() const;
 
-    // NOTE: If you are accessing the CompositedLayerMapping as a boolean condition to determine the state of compositing for this layer,
+    CompositedLayerMappingPtr compositedLayerMapping() const { return m_compositedLayerMapping.get(); }
+    CompositedLayerMappingPtr ensureCompositedLayerMapping();
+
+    // NOTE: If you are using hasCompositedLayerMapping to determine the state of compositing for this layer,
+    // (and not just to do bookkeeping related to the mapping like, say, allocating or deallocating a mapping),
     // then you may have incorrect logic. Use compositingState() instead.
-    CompositedLayerMapping* compositedLayerMapping() const { return m_compositedLayerMapping.get(); }
-    CompositedLayerMapping* ensureCompositedLayerMapping();
+    bool hasCompositedLayerMapping() const { return m_compositedLayerMapping.get(); }
     void clearCompositedLayerMapping(bool layerBeingDestroyed = false);
-    bool adjustForForceCompositedScrollingMode(bool) const;
 
     bool hasCompositedMask() const;
     bool hasCompositedClippingMask() const;
-    bool needsCompositedScrolling() const;
+    bool needsCompositedScrolling() const { return m_scrollableArea && m_scrollableArea->needsCompositedScrolling(); }
 
     RenderLayer* scrollParent() const;
     RenderLayer* clipParent() const;
@@ -421,14 +423,6 @@
 
     bool scrollsWithRespectTo(const RenderLayer*) const;
 
-    enum ForceNeedsCompositedScrollingMode {
-        DoNotForceCompositedScrolling = 0,
-        CompositedScrollingAlwaysOn = 1,
-        CompositedScrollingAlwaysOff = 2
-    };
-
-    void setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode);
-
     void addLayerHitTestRects(LayerHitTestRects&) const;
 
     // FIXME: This should probably return a ScrollableArea but a lot of internal methods are mistakenly exposed.
@@ -474,7 +468,6 @@
 
     void updateOutOfFlowPositioned(const RenderStyle* oldStyle);
 
-    bool setNeedsCompositedScrolling(bool);
     void didUpdateNeedsCompositedScrolling();
 
     // Returns true if the position changed.
@@ -503,7 +496,7 @@
     void paintLayerContentsAndReflection(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintLayerByApplyingTransform(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const LayoutPoint& translationOffset = LayoutPoint());
     void paintLayerContents(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
-    void paintList(Vector<RenderLayerStackingNode*>*, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
+    void paintChildren(unsigned childrenToVisit, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintPaginatedChildLayer(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintChildLayerIntoColumns(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const Vector<RenderLayer*>& columnLayers, size_t columnIndex);
 
@@ -529,7 +522,7 @@
     RenderLayer* hitTestLayerByApplyingTransform(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&,
         const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0,
         const LayoutPoint& translationOffset = LayoutPoint());
-    RenderLayer* hitTestList(Vector<RenderLayerStackingNode*>*, RenderLayer* rootLayer, const HitTestRequest&, HitTestResult&,
+    RenderLayer* hitTestChildren(ChildrenIteration, RenderLayer* rootLayer, const HitTestRequest&, HitTestResult&,
                              const LayoutRect& hitTestRect, const HitTestLocation&,
                              const HitTestingTransformState* transformState, double* zOffsetForDescendants, double* zOffset,
                              const HitTestingTransformState* unflattenedTransformState, bool depthSortDescendants);
@@ -551,7 +544,7 @@
     RenderLayer* hitTestTransformedLayerInFragments(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&,
         const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0);
 
-    bool listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayerStackingNode*>*, const LayoutRect&) const;
+    bool childBackgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const;
 
     bool shouldBeSelfPaintingLayer() const;
 
@@ -634,8 +627,6 @@
 
     unsigned m_isUnclippedDescendant : 1;
 
-    unsigned m_needsCompositedScrolling : 1;
-
     const unsigned m_isRootLayer : 1;
 
     unsigned m_usedTransparency : 1; // Tracks whether we need to close a transparent layer, i.e., whether
@@ -722,8 +713,6 @@
 
     CompositingProperties m_compositingProperties;
 
-    ForceNeedsCompositedScrollingMode m_forceNeedsCompositedScrolling;
-
 private:
     enum CompositedScrollingHistogramBuckets {
         IsScrollableAreaBucket = 0,
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index 94a5fef..d7ab5b4 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -30,6 +30,8 @@
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/DocumentAnimations.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/NodeList.h"
 #include "core/html/HTMLCanvasElement.h"
@@ -272,6 +274,14 @@
     m_forceCompositingMode = forceCompositingMode;
 }
 
+bool RenderLayerCompositor::isLayerSquashingEnabled() const
+{
+    if (Settings* settings = m_renderView->document().settings())
+        return settings->isLayerSquashingEnabled();
+
+    return false;
+}
+
 bool RenderLayerCompositor::canRender3DTransforms() const
 {
     return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
@@ -302,7 +312,7 @@
 
 bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer* rootLayer) const
 {
-    return m_compositedLayerCount > (rootLayer->compositedLayerMapping() ? 1 : 0);
+    return m_compositedLayerCount > (rootLayer->hasCompositedLayerMapping() ? 1 : 0);
 }
 
 void RenderLayerCompositor::updateCompositingRequirementsState()
@@ -431,7 +441,9 @@
             // should be removed as soon as proper overlap testing based on
             // scrolling and animation bounds is implemented (crbug.com/252472).
             Vector<RenderLayer*> unclippedDescendants;
-            computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, recursionData, layersChanged, saw3DTransform, unclippedDescendants);
+            computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, recursionData, saw3DTransform, unclippedDescendants);
+
+            assignLayersToBackings(updateRoot, layersChanged);
 
             const FrameView::ScrollableAreaSet* scrollableAreas = m_renderView->frameView()->scrollableAreas();
             if (scrollableAreas) {
@@ -453,14 +465,13 @@
         // Host the document layer in the RenderView's root layer.
         if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isMainFrame()) {
             RenderVideo* video = findFullscreenVideoRenderer(&m_renderView->document());
-            if (video) {
-                CompositedLayerMapping* compositedLayerMapping = video->compositedLayerMapping();
-                if (compositedLayerMapping) {
-                    childList.clear();
-                    childList.append(compositedLayerMapping->mainGraphicsLayer());
-                }
+            if (video && video->hasCompositedLayerMapping()) {
+                childList.clear();
+                childList.append(video->compositedLayerMapping()->mainGraphicsLayer());
             }
         }
+
+        // FIXME: the following comment and if-statement seem wrong. We do traverse visibility:hidden elements.
         // Even when childList is empty, don't drop out of compositing mode if there are
         // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
         if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(updateRoot))
@@ -509,27 +520,27 @@
     m_outOfFlowPositionedLayers.remove(layer);
 }
 
-bool RenderLayerCompositor::allocateOrClearCompositedLayerMapping(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
+bool RenderLayerCompositor::allocateOrClearCompositedLayerMapping(RenderLayer* layer)
 {
-    bool layerChanged = false;
+    bool compositedLayerMappingChanged = false;
     RenderLayer::ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason = RenderLayer::NoNotCompositedReason;
     requiresCompositingForPosition(layer->renderer(), layer, &viewportConstrainedNotCompositedReason);
 
     // FIXME: It would be nice to directly use the layer's compositing reason,
-    // but allocateCompositedLayerMappingIfNeeded() also gets called without having updated compositing
+    // but allocateOrClearCompositedLayerMapping also gets called without having updated compositing
     // requirements fully.
-    if (needsToBeComposited(layer)) {
+    if (needsOwnBacking(layer)) {
         enableCompositingMode();
 
-        if (!layer->compositedLayerMapping()) {
+        if (!layer->hasCompositedLayerMapping()) {
             // If we need to repaint, do so before allocating the compositedLayerMapping
-            if (shouldRepaint == CompositingChangeRepaintNow)
-                repaintOnCompositingChange(layer);
+            repaintOnCompositingChange(layer);
 
             layer->ensureCompositedLayerMapping();
+            compositedLayerMappingChanged = true;
 
             // At this time, the ScrollingCooridnator only supports the top-level frame.
-            if (layer->isRootLayer() && !isMainFrame()) {
+            if (layer->isRootLayer() && isMainFrame()) {
                 if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
                     scrollingCoordinator->frameViewRootLayerDidChange(m_renderView->frameView());
             }
@@ -538,69 +549,71 @@
             // the repaint container, so change when compositing changes; we need to update them here.
             if (layer->parent())
                 layer->repainter().computeRepaintRectsIncludingDescendants();
-
-            layerChanged = true;
         }
+
+        if (layer->compositedLayerMapping()->updateRequiresOwnBackingStoreForIntrinsicReasons())
+            compositedLayerMappingChanged = true;
     } else {
-        if (layer->compositedLayerMapping()) {
+        if (layer->hasCompositedLayerMapping()) {
             // If we're removing the compositedLayerMapping from a reflection, clear the source GraphicsLayer's pointer to
             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection
             // are both either composited, or not composited.
             if (layer->isReflection()) {
                 RenderLayer* sourceLayer = toRenderLayerModelObject(layer->renderer()->parent())->layer();
-                if (CompositedLayerMapping* compositedLayerMapping = sourceLayer->compositedLayerMapping()) {
-                    ASSERT(compositedLayerMapping->mainGraphicsLayer()->replicaLayer() == layer->compositedLayerMapping()->mainGraphicsLayer());
-                    compositedLayerMapping->mainGraphicsLayer()->setReplicatedByLayer(0);
+                if (sourceLayer->hasCompositedLayerMapping()) {
+                    ASSERT(sourceLayer->compositedLayerMapping()->mainGraphicsLayer()->replicaLayer() == layer->compositedLayerMapping()->mainGraphicsLayer());
+                    sourceLayer->compositedLayerMapping()->mainGraphicsLayer()->setReplicatedByLayer(0);
                 }
             }
 
             removeViewportConstrainedLayer(layer);
 
             layer->clearCompositedLayerMapping();
-            layerChanged = true;
+            compositedLayerMappingChanged = true;
 
             // This layer and all of its descendants have cached repaints rects that are relative to
             // the repaint container, so change when compositing changes; we need to update them here.
             layer->repainter().computeRepaintRectsIncludingDescendants();
 
             // If we need to repaint, do so now that we've removed the compositedLayerMapping
-            if (shouldRepaint == CompositingChangeRepaintNow)
-                repaintOnCompositingChange(layer);
+            repaintOnCompositingChange(layer);
         }
     }
 
-    if (layerChanged && layer->renderer()->isRenderPart()) {
+    if (compositedLayerMappingChanged && layer->renderer()->isRenderPart()) {
         RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderPart(layer->renderer()));
         if (innerCompositor && innerCompositor->inCompositingMode())
             innerCompositor->updateRootLayerAttachment();
     }
 
-    if (layerChanged)
+    if (compositedLayerMappingChanged)
         layer->clipper().clearClipRectsIncludingDescendants(PaintingClipRects);
 
     // If a fixed position layer gained/lost a compositedLayerMapping or the reason not compositing it changed,
     // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
+    bool nonCompositedReasonChanged = false;
     if (layer->renderer()->style()->position() == FixedPosition) {
         if (layer->viewportConstrainedNotCompositedReason() != viewportConstrainedNotCompositedReason) {
             layer->setViewportConstrainedNotCompositedReason(viewportConstrainedNotCompositedReason);
-            layerChanged = true;
+            nonCompositedReasonChanged = true;
         }
-        if (layerChanged) {
+        if (compositedLayerMappingChanged || nonCompositedReasonChanged) {
             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
                 scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView->frameView());
         }
     }
 
-    return layerChanged;
+    return compositedLayerMappingChanged || nonCompositedReasonChanged;
 }
 
-bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
+bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer)
 {
-    bool layerChanged = allocateOrClearCompositedLayerMapping(layer, shouldRepaint);
+    updateDirectCompositingReasons(layer);
+    bool layerChanged = allocateOrClearCompositedLayerMapping(layer);
 
     // See if we need content or clipping layers. Methods called here should assume
     // that the compositing state of descendant layers has not been updated yet.
-    if (layer->compositedLayerMapping() && layer->compositedLayerMapping()->updateGraphicsLayerConfiguration())
+    if (layer->hasCompositedLayerMapping() && layer->compositedLayerMapping()->updateGraphicsLayerConfiguration())
         layerChanged = true;
 
     return layerChanged;
@@ -659,7 +672,7 @@
 
 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer* parent, RenderLayer* child)
 {
-    if (!child->compositedLayerMapping() || parent->renderer()->documentBeingDestroyed())
+    if (!child->hasCompositedLayerMapping() || parent->renderer()->documentBeingDestroyed())
         return;
 
     removeViewportConstrainedLayer(child);
@@ -735,7 +748,7 @@
 //      must be compositing so that its contents render over that child.
 //      This implies that its positive z-index children must also be compositing.
 //
-void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingRecursionData& currentRecursionData, bool& layersChanged, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants)
+void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingRecursionData& currentRecursionData, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants)
 {
     layer->stackingNode()->updateLayerListsIfNeeded();
 
@@ -759,10 +772,8 @@
     if (currentRecursionData.m_compositingAncestor && currentRecursionData.m_compositingAncestor->renderer()->isVideo())
         directReasons |= CompositingReasonLayerForVideoOverlay;
 
-    if (canBeComposited(layer)) {
+    if (canBeComposited(layer))
         reasonsToComposite |= directReasons;
-        reasonsToComposite |= (inCompositingMode() && layer->isRootLayer()) ? CompositingReasonRoot : CompositingReasonNone;
-    }
 
     // Next, accumulate reasons related to overlap.
     // If overlap testing is used, this reason will be overridden. If overlap testing is not
@@ -843,7 +854,7 @@
     if (layer->stackingNode()->isStackingContainer()) {
         RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
         while (RenderLayerStackingNode* curNode = iterator.next()) {
-            computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
+            computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, anyDescendantHas3DTransform, unclippedDescendants);
 
             // If we have to make a layer for this child, make one now so we can have a contents layer
             // (since we need to ensure that the -ve z-order child renders underneath our contents).
@@ -889,7 +900,7 @@
 
     RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
     while (RenderLayerStackingNode* curNode = iterator.next())
-        computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
+        computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, anyDescendantHas3DTransform, unclippedDescendants);
 
     // Now that the subtree has been traversed, we can check for compositing reasons that depended on the state of the subtree.
 
@@ -944,14 +955,17 @@
     if (overlapMap && childRecursionData.m_compositingAncestor == layer && !layer->isRootLayer())
         overlapMap->finishCurrentOverlapTestingContext();
 
-    // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
-    // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
-    // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
-    // FIXME: hasAnyAdditionalCompositedLayers() code seems fishy. We need to make root layer logic more obvious.
-    if (layer->isRootLayer() && !childRecursionData.m_subtreeIsCompositing && !requiresCompositing(directReasons) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
-        enableCompositingMode(false);
-        willBeComposited = false;
-        reasonsToComposite = CompositingReasonNone;
+    if (layer->isRootLayer()) {
+        // The root layer needs to be composited if anything else in the tree is composited.
+        // Otherwise, we can disable compositing entirely.
+        if (childRecursionData.m_subtreeIsCompositing || requiresCompositing(reasonsToComposite) || m_forceCompositingMode) {
+            willBeComposited = true;
+            reasonsToComposite |= CompositingReasonRoot;
+        } else {
+            enableCompositingMode(false);
+            willBeComposited = false;
+            reasonsToComposite = CompositingReasonNone;
+        }
     }
 
     // At this point we have finished collecting all reasons to composite this layer.
@@ -960,28 +974,46 @@
     if (!willBeComposited && layer->parent())
         layer->parent()->setHasNonCompositedChild(true);
 
-    // Allocate or deallocate the compositedLayerMapping now, so that we can know the layer's compositing state reliably during tree traversal in rebuildCompositingLayerTree().
-    if (allocateOrClearCompositedLayerMapping(layer, CompositingChangeRepaintNow))
-        layersChanged = true;
-
-    if (layer->reflectionInfo() && updateLayerCompositingState(layer->reflectionInfo()->reflectionLayer(), CompositingChangeRepaintNow))
-        layersChanged = true;
-
     descendantHas3DTransform |= anyDescendantHas3DTransform || layer->has3DTransform();
 
     if (overlapMap)
         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
 }
 
+void RenderLayerCompositor::assignLayersToBackings(RenderLayer* layer, bool& layersChanged)
+{
+    if (allocateOrClearCompositedLayerMapping(layer))
+        layersChanged = true;
+
+    if (layer->reflectionInfo() && updateLayerCompositingState(layer->reflectionInfo()->reflectionLayer()))
+        layersChanged = true;
+
+    // FIXME: squashing code here: if a layer requiresSquashing(), then assign this layer to the most recent
+    // squashing layer and update recursion state of this function.
+
+    if (layer->stackingNode()->isStackingContainer()) {
+        RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
+        while (RenderLayerStackingNode* curNode = iterator.next())
+            assignLayersToBackings(curNode->layer(), layersChanged);
+    }
+
+    // FIXME: squashing code here: if this layer actually becomes separately composited, then we need to update the
+    // squashing layer that subsequent overlapping layers will contribute to.
+
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next())
+        assignLayersToBackings(curNode->layer(), layersChanged);
+}
+
 void RenderLayerCompositor::setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer)
 {
     ASSERT(!parentLayer || childLayer->ancestorCompositingLayer() == parentLayer);
-    ASSERT(childLayer->compositedLayerMapping());
+    ASSERT(childLayer->hasCompositedLayerMapping());
 
     // It's possible to be called with a parent that isn't yet composited when we're doing
     // partial updates as required by painting or hit testing. Just bail in that case;
     // we'll do a full layer update soon.
-    if (!parentLayer || !parentLayer->compositedLayerMapping())
+    if (!parentLayer || !parentLayer->hasCompositedLayerMapping())
         return;
 
     if (parentLayer) {
@@ -996,7 +1028,7 @@
 
 void RenderLayerCompositor::removeCompositedChildren(RenderLayer* layer)
 {
-    ASSERT(layer->compositedLayerMapping());
+    ASSERT(layer->hasCompositedLayerMapping());
 
     GraphicsLayer* hostingLayer = layer->compositedLayerMapping()->parentForSublayers();
     hostingLayer->removeAllChildren();
@@ -1028,15 +1060,16 @@
         pixelsAddedByPromotingAllTransitions = 0.0;
     }
 
-    CompositedLayerMapping* currentCompositedLayerMapping = layer->compositedLayerMapping();
-    if (currentCompositedLayerMapping) {
+    const bool hasCompositedLayerMapping = layer->hasCompositedLayerMapping();
+    CompositedLayerMappingPtr currentCompositedLayerMapping = layer->compositedLayerMapping();
+    if (hasCompositedLayerMapping) {
         // The compositing state of all our children has been updated already, so now
         // we can compute and cache the composited bounds for this layer.
         currentCompositedLayerMapping->updateCompositedBounds();
 
         if (layer->reflectionInfo()) {
             RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
-            if (reflectionLayer->compositedLayerMapping())
+            if (reflectionLayer->hasCompositedLayerMapping())
                 reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
         }
 
@@ -1060,7 +1093,7 @@
     // If this layer has a compositedLayerMapping, then that is where we place subsequent children GraphicsLayers.
     // Otherwise children continue to append to the child list of the enclosing layer.
     Vector<GraphicsLayer*> layerChildren;
-    Vector<GraphicsLayer*>& childList = currentCompositedLayerMapping ? layerChildren : childLayersOfEnclosingLayer;
+    Vector<GraphicsLayer*>& childList = hasCompositedLayerMapping ? layerChildren : childLayersOfEnclosingLayer;
 
 #if !ASSERT_DISABLED
     LayerListMutationDetector mutationChecker(layer->stackingNode());
@@ -1072,7 +1105,7 @@
             rebuildCompositingLayerTree(curNode->layer(), childList, depth + 1);
 
         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
-        if (currentCompositedLayerMapping && currentCompositedLayerMapping->foregroundLayer())
+        if (hasCompositedLayerMapping && currentCompositedLayerMapping->foregroundLayer())
             childList.append(currentCompositedLayerMapping->foregroundLayer());
     }
 
@@ -1080,7 +1113,7 @@
     while (RenderLayerStackingNode* curNode = iterator.next())
         rebuildCompositingLayerTree(curNode->layer(), childList, depth + 1);
 
-    if (currentCompositedLayerMapping) {
+    if (hasCompositedLayerMapping) {
         bool parented = false;
         if (layer->renderer()->isRenderPart())
             parented = parentFrameContentLayers(toRenderPart(layer->renderer()));
@@ -1112,7 +1145,7 @@
 
     if (!depth) {
         int percentageIncreaseInPixels = static_cast<int>(pixelsAddedByPromotingAllTransitions / pixelsWithoutPromotingAllTransitions * 100);
-        WebKit::Platform::current()->histogramCustomCounts("Renderer.PixelIncreaseFromTransitions", percentageIncreaseInPixels, 0, 1000, 50);
+        blink::Platform::current()->histogramCustomCounts("Renderer.PixelIncreaseFromTransitions", percentageIncreaseInPixels, 0, 1000, 50);
     }
 }
 
@@ -1165,14 +1198,14 @@
         m_scrollLayer->setPosition(-scrollPosition);
 
 
-    WebKit::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+    blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
         ScrolledMainFrameBucket,
         AcceleratedFixedRootBackgroundHistogramMax);
 
     if (!m_renderView->rootBackgroundIsEntirelyFixed())
         return;
 
-    WebKit::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+    blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
         !!fixedRootBackgroundLayer()
             ? ScrolledMainFrameWithAcceleratedFixedRootBackground
             : ScrolledMainFrameWithUnacceleratedFixedRootBackground,
@@ -1263,10 +1296,10 @@
         return false;
 
     RenderLayer* layer = renderer->layer();
-    if (!layer->compositedLayerMapping())
+    if (!layer->hasCompositedLayerMapping())
         return false;
 
-    CompositedLayerMapping* compositedLayerMapping = layer->compositedLayerMapping();
+    CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
     GraphicsLayer* hostingLayer = compositedLayerMapping->parentForSublayers();
     GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
@@ -1279,14 +1312,15 @@
 // This just updates layer geometry without changing the hierarchy.
 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer)
 {
-    if (CompositedLayerMapping* compositedLayerMapping = layer->compositedLayerMapping()) {
+    if (layer->hasCompositedLayerMapping()) {
+        CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
         // The compositing state of all our children has been updated already, so now
         // we can compute and cache the composited bounds for this layer.
         compositedLayerMapping->updateCompositedBounds();
 
         if (layer->reflectionInfo()) {
             RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
-            if (reflectionLayer->compositedLayerMapping())
+            if (reflectionLayer->hasCompositedLayerMapping())
                 reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
         }
 
@@ -1310,12 +1344,13 @@
 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayerStackingNode* compositingAncestor, RenderLayer* layer, bool compositedChildrenOnly)
 {
     if (layer->stackingNode() != compositingAncestor) {
-        if (CompositedLayerMapping* compositedLayerMapping = layer->compositedLayerMapping()) {
+        if (layer->hasCompositedLayerMapping()) {
+            CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
             compositedLayerMapping->updateCompositedBounds();
 
             if (layer->reflectionInfo()) {
                 RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
-                if (reflectionLayer->compositedLayerMapping())
+                if (reflectionLayer->hasCompositedLayerMapping())
                     reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
             }
 
@@ -1416,7 +1451,7 @@
     if (!layer)
         return;
 
-    if (layer->compositedLayerMapping()) {
+    if (layer->hasCompositedLayerMapping()) {
         removeViewportConstrainedLayer(layer);
         layer->clearCompositedLayerMapping();
     }
@@ -1452,12 +1487,21 @@
     return layerHas3DContent(rootRenderLayer());
 }
 
-bool RenderLayerCompositor::needsToBeComposited(const RenderLayer* layer) const
+void RenderLayerCompositor::updateDirectCompositingReasons(RenderLayer* layer)
+{
+    CompositingReasons layerReasons = layer->compositingReasons();
+
+    layerReasons &= ~CompositingReasonComboAllDirectReasons;
+    layerReasons |= directReasonsForCompositing(layer);
+    layer->setCompositingReasons(layerReasons);
+}
+
+bool RenderLayerCompositor::needsOwnBacking(const RenderLayer* layer) const
 {
     if (!canBeComposited(layer))
         return false;
 
-    return requiresCompositing(directReasonsForCompositing(layer)) || requiresCompositing(layer->compositingReasons()) || (inCompositingMode() && layer->isRootLayer());
+    return requiresCompositing(layer->compositingReasons()) || (inCompositingMode() && layer->isRootLayer());
 }
 
 bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
@@ -1467,48 +1511,6 @@
     return m_hasAcceleratedCompositing && layer->isSelfPaintingLayer() && layer->renderer()->flowThreadState() == RenderObject::NotInsideFlowThread;
 }
 
-bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer* layer, const RenderLayer* compositingAncestorLayer) const
-{
-    RenderObject* renderer = layer->renderer();
-
-    // A layer definitely needs its own backing if we cannot paint into the composited ancestor.
-    if (compositingAncestorLayer
-        && !(compositingAncestorLayer->compositedLayerMapping()->mainGraphicsLayer()->drawsContent()
-            || compositingAncestorLayer->compositedLayerMapping()->paintsIntoCompositedAncestor()))
-        return true;
-
-    if (layer->isRootLayer()
-        || layer->transform() // note: excludes perspective and transformStyle3D.
-        || requiresCompositingForVideo(renderer)
-        || requiresCompositingForCanvas(renderer)
-        || requiresCompositingForPlugin(renderer)
-        || requiresCompositingForFrame(renderer)
-        || requiresCompositingForBackfaceVisibilityHidden(renderer)
-        || requiresCompositingForAnimation(renderer)
-        || requiresCompositingForTransition(renderer)
-        || requiresCompositingForFilters(renderer)
-        || requiresCompositingForPosition(renderer, layer)
-        || requiresCompositingForOverflowScrolling(layer)
-        || requiresCompositingForOverflowScrollingParent(layer)
-        || requiresCompositingForOutOfFlowClipping(layer)
-        || renderer->isTransparent()
-        || renderer->hasMask()
-        || renderer->hasReflection()
-        || renderer->hasFilter())
-        return true;
-
-    CompositingReasons indirectReasonsThatNeedBacking = CompositingReasonOverlap
-        | CompositingReasonAssumedOverlap
-        | CompositingReasonNegativeZIndexChildren
-        | CompositingReasonTransformWithCompositedDescendants
-        | CompositingReasonOpacityWithCompositedDescendants
-        | CompositingReasonMaskWithCompositedDescendants
-        | CompositingReasonFilterWithCompositedDescendants
-        | CompositingReasonBlendingWithCompositedDescendants
-        | CompositingReasonPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
-    return layer->compositingReasons() & indirectReasonsThatNeedBacking;
-}
-
 CompositingReasons RenderLayerCompositor::directReasonsForCompositing(const RenderLayer* layer) const
 {
     RenderObject* renderer = layer->renderer();
@@ -1561,7 +1563,7 @@
 // but a sibling in the z-order hierarchy.
 bool RenderLayerCompositor::clippedByAncestor(const RenderLayer* layer) const
 {
-    if (!layer->compositedLayerMapping() || !layer->parent())
+    if (!layer->hasCompositedLayerMapping() || !layer->parent())
         return false;
 
     const RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
@@ -1666,7 +1668,7 @@
     RenderWidget* pluginRenderer = toRenderWidget(renderer);
     // If we can't reliably know the size of the plugin yet, don't change compositing state.
     if (pluginRenderer->needsLayout())
-        return pluginRenderer->hasLayer() && pluginRenderer->layer()->compositedLayerMapping();
+        return pluginRenderer->hasLayer() && pluginRenderer->layer()->hasCompositedLayerMapping();
 
     // Don't go into compositing mode if height or width are zero, or size is 1x1.
     IntRect contentBox = pixelSnappedIntRect(pluginRenderer->contentBoxRect());
@@ -1692,7 +1694,7 @@
 
     // If we can't reliably know the size of the iframe yet, don't change compositing state.
     if (renderer->needsLayout())
-        return frameRenderer->hasLayer() && frameRenderer->layer()->compositedLayerMapping();
+        return frameRenderer->hasLayer() && frameRenderer->layer()->hasCompositedLayerMapping();
 
     // Don't go into compositing mode if height or width are zero.
     IntRect contentBox = pixelSnappedIntRect(frameRenderer->contentBoxRect());
@@ -1709,9 +1711,13 @@
     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
         return false;
 
-    return (renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity) && inCompositingMode())
-        || renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitFilter)
-        || renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
+    if (!RuntimeEnabledFeatures::webAnimationsEnabled()) {
+        // FIXME: Remove this condition once force-compositing-mode is enabled on all platforms.
+        bool shouldAccelerateOpacity = inCompositingMode();
+        return renderer->animation().isRunningAcceleratableAnimationOnRenderer(renderer, shouldAccelerateOpacity);
+    }
+
+    return shouldCompositeForActiveAnimations(*renderer, inCompositingMode());
 }
 
 bool RenderLayerCompositor::requiresCompositingForTransition(RenderObject* renderer) const
@@ -1862,7 +1868,7 @@
     // Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
     if (!m_inPostLayoutUpdate) {
         m_needsToRecomputeCompositingRequirements = true;
-        return layer->compositedLayerMapping();
+        return layer->hasCompositedLayerMapping();
     }
 
     bool paintsContent = layer->isVisuallyNonEmpty() || layer->hasVisibleDescendant();
@@ -1902,7 +1908,9 @@
 {
     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
         return false;
-    return renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
+    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+        return renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
+    return hasActiveAnimations(*renderer, CSSPropertyWebkitTransform);
 }
 
 // If an element has negative z-index children, those children render in front of the
@@ -2290,6 +2298,7 @@
 
 bool RenderLayerCompositor::isMainFrame() const
 {
+    // FIXME: Frame::isMainFrame() is probably better.
     return !m_renderView->document().ownerElement();
 }
 
@@ -2348,7 +2357,7 @@
         return false;
 
     for (RenderLayerStackingNode* stackingContainerNode = layer->stackingNode()->ancestorStackingContainerNode(); stackingContainerNode; stackingContainerNode = stackingContainerNode->ancestorStackingContainerNode()) {
-        if (stackingContainerNode->layer()->compositedLayerMapping() && stackingContainerNode->layer()->renderer()->style()->position() == FixedPosition)
+        if (stackingContainerNode->layer()->hasCompositedLayerMapping() && stackingContainerNode->layer()->renderer()->style()->position() == FixedPosition)
             return false;
     }
 
@@ -2378,7 +2387,7 @@
 
 FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer* layer) const
 {
-    ASSERT(layer->compositedLayerMapping());
+    ASSERT(layer->hasCompositedLayerMapping());
 
     FrameView* frameView = m_renderView->frameView();
     LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
@@ -2416,7 +2425,7 @@
 
 StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer* layer) const
 {
-    ASSERT(layer->compositedLayerMapping());
+    ASSERT(layer->hasCompositedLayerMapping());
 
     FrameView* frameView = m_renderView->frameView();
     LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
diff --git a/Source/core/rendering/RenderLayerCompositor.h b/Source/core/rendering/RenderLayerCompositor.h
index 59a30c9..dfc9185 100644
--- a/Source/core/rendering/RenderLayerCompositor.h
+++ b/Source/core/rendering/RenderLayerCompositor.h
@@ -75,6 +75,7 @@
 
     // Returns true if the accelerated compositing is enabled
     bool hasAcceleratedCompositing() const { return m_hasAcceleratedCompositing; }
+    bool isLayerSquashingEnabled() const;
 
     bool canRender3DTransforms() const;
 
@@ -99,8 +100,7 @@
     void updateCompositingLayers(CompositingUpdateType);
 
     // Update the compositing state of the given layer. Returns true if that state changed.
-    enum CompositingChangeRepaint { CompositingChangeRepaintNow, CompositingChangeWillRepaintLater };
-    bool updateLayerCompositingState(RenderLayer*, CompositingChangeRepaint = CompositingChangeRepaintNow);
+    bool updateLayerCompositingState(RenderLayer*);
 
     // Update the geometry for compositing children of compositingAncestor.
     void updateCompositingDescendantGeometry(RenderLayerStackingNode* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
@@ -136,9 +136,6 @@
     // Repaint parts of all composited layers that intersect the given absolute rectangle (or the entire layer if the pointer is null).
     void repaintCompositedLayers(const IntRect* = 0);
 
-    // Returns true if the given layer needs it own backing store.
-    bool requiresOwnBackingStore(const RenderLayer*, const RenderLayer* compositingAncestorLayer) const;
-
     RenderLayer* rootRenderLayer() const;
     GraphicsLayer* rootGraphicsLayer() const;
     GraphicsLayer* scrollLayer() const;
@@ -211,19 +208,21 @@
 
     virtual bool isTrackingRepaints() const OVERRIDE;
 
-    // Whether the given RL needs a compositing layer.
-    bool needsToBeComposited(const RenderLayer*) const;
+    // Whether the given RL needs to paint into its own separate backing (and hence would need its own CompositedLayerMapping).
+    bool needsOwnBacking(const RenderLayer*) const;
     // Whether the layer could ever be composited.
     bool canBeComposited(const RenderLayer*) const;
 
     // Returns all direct reasons that a layer should be composited.
     CompositingReasons directReasonsForCompositing(const RenderLayer*) const;
 
+    void updateDirectCompositingReasons(RenderLayer*);
+
     // Returns indirect reasons that a layer should be composited because of something in its subtree.
     CompositingReasons subtreeReasonsForCompositing(RenderObject*, bool hasCompositedDescendants, bool has3DTransformedDescendants) const;
 
     // Make or destroy the CompositedLayerMapping for this layer; returns true if the compositedLayerMapping changed.
-    bool allocateOrClearCompositedLayerMapping(RenderLayer*, CompositingChangeRepaint shouldRepaint);
+    bool allocateOrClearCompositedLayerMapping(RenderLayer*);
 
     void clearMappingForRenderLayerIncludingDescendants(RenderLayer*);
 
@@ -238,7 +237,10 @@
     static void finishCompositingUpdateForFrameTree(Frame*);
 
     // Returns true if any layer's compositing changed
-    void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingRecursionData&, bool& layersChanged, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants);
+    void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingRecursionData&, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants);
+
+    // Defines which RenderLayers will paint into which composited backings, by allocating and destroying CompositedLayerMappings as needed.
+    void assignLayersToBackings(RenderLayer*, bool& layersChanged);
 
     // Recurses down the tree, parenting descendant compositing layers and collecting an array of child layers for the current compositing layer.
     void rebuildCompositingLayerTree(RenderLayer*, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth);
diff --git a/Source/core/rendering/RenderLayerFilterInfo.cpp b/Source/core/rendering/RenderLayerFilterInfo.cpp
index 2d4f8b6..865e566 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.cpp
+++ b/Source/core/rendering/RenderLayerFilterInfo.cpp
@@ -37,6 +37,7 @@
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 #include "core/rendering/FilterEffectRenderer.h"
 #include "core/rendering/RenderLayer.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
 #include "core/rendering/svg/RenderSVGResourceContainer.h"
 #include "core/svg/SVGFilterElement.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
@@ -116,10 +117,10 @@
     removeReferenceFilterClients();
     for (size_t i = 0; i < operations.size(); ++i) {
         RefPtr<FilterOperation> filterOperation = operations.operations().at(i);
-        if (filterOperation->getOperationType() != FilterOperation::REFERENCE)
+        if (filterOperation->type() != FilterOperation::REFERENCE)
             continue;
-        ReferenceFilterOperation* referenceFilterOperation = static_cast<ReferenceFilterOperation*>(filterOperation.get());
-        DocumentResourceReference* documentReference = referenceFilterOperation->documentResourceReference();
+        ReferenceFilterOperation* referenceFilterOperation = toReferenceFilterOperation(filterOperation.get());
+        DocumentResourceReference* documentReference = ReferenceFilterBuilder::documentResourceReference(referenceFilterOperation);
         DocumentResource* cachedSVGDocument = documentReference ? documentReference->document() : 0;
 
         if (cachedSVGDocument) {
@@ -172,10 +173,9 @@
     CustomFilterProgramList cachedCustomFilterPrograms;
     for (size_t i = 0; i < operations.size(); ++i) {
         const FilterOperation* filterOperation = operations.at(i);
-        if (filterOperation->getOperationType() != FilterOperation::CUSTOM)
+        if (filterOperation->type() != FilterOperation::CUSTOM)
             continue;
-        const CustomFilterOperation* customFilterOperation = static_cast<const CustomFilterOperation*>(filterOperation);
-        RefPtr<CustomFilterProgram> program = customFilterOperation->program();
+        RefPtr<CustomFilterProgram> program = toCustomFilterOperation(filterOperation)->program();
         cachedCustomFilterPrograms.append(program);
         program->addClient(this);
     }
diff --git a/Source/core/rendering/RenderLayerModelObject.cpp b/Source/core/rendering/RenderLayerModelObject.cpp
index 457c657..c89225c 100644
--- a/Source/core/rendering/RenderLayerModelObject.cpp
+++ b/Source/core/rendering/RenderLayerModelObject.cpp
@@ -40,7 +40,6 @@
 
 RenderLayerModelObject::RenderLayerModelObject(ContainerNode* node)
     : RenderObject(node)
-    , m_layer(0)
 {
 }
 
@@ -53,16 +52,14 @@
 
 void RenderLayerModelObject::destroyLayer()
 {
-    ASSERT(!hasLayer()); // Callers should have already called setHasLayer(false)
-    ASSERT(m_layer);
-    delete m_layer;
-    m_layer = 0;
+    setHasLayer(false);
+    m_layer = nullptr;
 }
 
 void RenderLayerModelObject::createLayer()
 {
     ASSERT(!m_layer);
-    m_layer = new RenderLayer(this);
+    m_layer = adoptPtr(new RenderLayer(this));
     setHasLayer(true);
     m_layer->insertOnlyThisLayer();
 }
@@ -89,8 +86,9 @@
         }
     }
 
-    // RenderObject::willBeDestroyed calls back to destroyLayer() for layer destruction
     RenderObject::willBeDestroyed();
+
+    destroyLayer();
 }
 
 void RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
@@ -204,10 +202,15 @@
     }
 }
 
-CompositedLayerMapping* RenderLayerModelObject::compositedLayerMapping() const
+CompositedLayerMappingPtr RenderLayerModelObject::compositedLayerMapping() const
 {
     return m_layer ? m_layer->compositedLayerMapping() : 0;
 }
 
+bool RenderLayerModelObject::hasCompositedLayerMapping() const
+{
+    return m_layer ? m_layer->hasCompositedLayerMapping() : false;
+}
+
 } // namespace WebCore
 
diff --git a/Source/core/rendering/RenderLayerModelObject.h b/Source/core/rendering/RenderLayerModelObject.h
index 559c4ea..819e483 100644
--- a/Source/core/rendering/RenderLayerModelObject.h
+++ b/Source/core/rendering/RenderLayerModelObject.h
@@ -23,6 +23,7 @@
 #ifndef RenderLayerModelObject_h
 #define RenderLayerModelObject_h
 
+#include "core/rendering/CompositedLayerMappingPtr.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebCore {
@@ -36,11 +37,11 @@
     explicit RenderLayerModelObject(ContainerNode*);
     virtual ~RenderLayerModelObject();
 
-    // Called by RenderObject::willBeDestroyed() and is the only way layers should ever be destroyed
+    // This is the only way layers should ever be destroyed.
     void destroyLayer();
 
     bool hasSelfPaintingLayer() const;
-    RenderLayer* layer() const { return m_layer; }
+    RenderLayer* layer() const { return m_layer.get(); }
     ScrollableArea* scrollableArea() const;
 
     virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
@@ -56,7 +57,8 @@
     // This is null for anonymous renderers.
     ContainerNode* node() const { return toContainerNode(RenderObject::node()); }
 
-    CompositedLayerMapping* compositedLayerMapping() const;
+    CompositedLayerMappingPtr compositedLayerMapping() const;
+    bool hasCompositedLayerMapping() const;
 
 protected:
     void createLayer();
@@ -68,7 +70,7 @@
 private:
     virtual bool isLayerModelObject() const OVERRIDE FINAL { return true; }
 
-    RenderLayer* m_layer;
+    OwnPtr<RenderLayer> m_layer;
 
     // Used to store state between styleWillChange and styleDidChange
     static bool s_wasFloating;
diff --git a/Source/core/rendering/RenderLayerReflectionInfo.cpp b/Source/core/rendering/RenderLayerReflectionInfo.cpp
index 5a2fd69..38801bd 100644
--- a/Source/core/rendering/RenderLayerReflectionInfo.cpp
+++ b/Source/core/rendering/RenderLayerReflectionInfo.cpp
@@ -44,7 +44,7 @@
 #include "config.h"
 #include "core/rendering/RenderLayerReflectionInfo.h"
 
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderReplica.h"
 #include "core/rendering/style/RenderStyle.h"
diff --git a/Source/core/rendering/RenderLayerRepainter.cpp b/Source/core/rendering/RenderLayerRepainter.cpp
index 595431f..eb65cb6 100644
--- a/Source/core/rendering/RenderLayerRepainter.cpp
+++ b/Source/core/rendering/RenderLayerRepainter.cpp
@@ -135,7 +135,7 @@
     m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_renderer->clippedOverflowRectForRepaint(repaintContainer)));
 
     for (RenderLayer* curr = m_renderer->layer()->firstChild(); curr; curr = curr->nextSibling()) {
-        if (!curr->compositedLayerMapping())
+        if (!curr->hasCompositedLayerMapping())
             curr->repainter().repaintIncludingNonCompositingDescendants(repaintContainer);
     }
 }
@@ -145,7 +145,7 @@
     LayoutRect repaintRect = m_repaintRect;
     for (RenderLayer* child = m_renderer->layer()->firstChild(); child; child = child->nextSibling()) {
         // Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.
-        if (child->compositedLayerMapping())
+        if (child->hasCompositedLayerMapping())
             continue;
 
         repaintRect.unite(child->repainter().repaintRectIncludingNonCompositingDescendants());
@@ -155,7 +155,7 @@
 
 void RenderLayerRepainter::setBackingNeedsRepaint()
 {
-    ASSERT(m_renderer->compositedLayerMapping());
+    ASSERT(m_renderer->hasCompositedLayerMapping());
     m_renderer->compositedLayerMapping()->setContentsNeedDisplay();
 }
 
@@ -163,8 +163,8 @@
 {
     // https://bugs.webkit.org/show_bug.cgi?id=61159 describes an unreproducible crash here,
     // so assert but check that the layer is composited.
-    ASSERT(m_renderer->compositedLayerMapping());
-    if (!m_renderer->compositedLayerMapping()) {
+    ASSERT(m_renderer->hasCompositedLayerMapping());
+    if (!m_renderer->hasCompositedLayerMapping()) {
         // If we're trying to repaint the placeholder document layer, propagate the
         // repaint to the native view system.
         LayoutRect absRect(r);
@@ -212,7 +212,7 @@
     FloatQuad repaintQuad(rectForRepaint);
     LayoutRect parentLayerRect = m_renderer->localToContainerQuad(repaintQuad, parentLayer->renderer()).enclosingBoundingBox();
 
-    if (parentLayer->compositedLayerMapping()) {
+    if (parentLayer->hasCompositedLayerMapping()) {
         parentLayer->repainter().setBackingNeedsRepaintInRect(parentLayerRect);
         return;
     }
diff --git a/Source/core/rendering/RenderLayerScrollableArea.cpp b/Source/core/rendering/RenderLayerScrollableArea.cpp
index f036d80..530c5f9 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.cpp
+++ b/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -78,8 +78,10 @@
     , m_inResizeMode(false)
     , m_scrollDimensionsDirty(true)
     , m_inOverflowRelayout(false)
+    , m_needsCompositedScrolling(false)
     , m_willUseCompositedScrollingHasBeenRecorded(false)
     , m_isScrollableAreaHasBeenRecorded(false)
+    , m_forceNeedsCompositedScrolling(DoNotForceCompositedScrolling)
     , m_scrollCorner(0)
     , m_resizer(0)
 {
@@ -148,22 +150,22 @@
 
 GraphicsLayer* RenderLayerScrollableArea::layerForScrolling() const
 {
-    return m_box->compositedLayerMapping() ? m_box->compositedLayerMapping()->scrollingContentsLayer() : 0;
+    return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->scrollingContentsLayer() : 0;
 }
 
 GraphicsLayer* RenderLayerScrollableArea::layerForHorizontalScrollbar() const
 {
-    return m_box->compositedLayerMapping() ? m_box->compositedLayerMapping()->layerForHorizontalScrollbar() : 0;
+    return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->layerForHorizontalScrollbar() : 0;
 }
 
 GraphicsLayer* RenderLayerScrollableArea::layerForVerticalScrollbar() const
 {
-    return m_box->compositedLayerMapping() ? m_box->compositedLayerMapping()->layerForVerticalScrollbar() : 0;
+    return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->layerForVerticalScrollbar() : 0;
 }
 
 GraphicsLayer* RenderLayerScrollableArea::layerForScrollCorner() const
 {
-    return m_box->compositedLayerMapping() ? m_box->compositedLayerMapping()->layerForScrollCorner() : 0;
+    return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->layerForScrollCorner() : 0;
 }
 
 void RenderLayerScrollableArea::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
@@ -364,7 +366,8 @@
     bool requiresRepaint = true;
 
     if (m_box->view()->compositor()->inCompositingMode()) {
-        bool onlyScrolledCompositedLayers = !layer()->hasVisibleNonLayerContent()
+        bool onlyScrolledCompositedLayers = scrollsOverflow()
+            && !layer()->hasVisibleNonLayerContent()
             && !layer()->hasNonCompositedChild()
             && !layer()->hasBlockSelectionGapBounds()
             && !m_box->isMarquee();
@@ -512,7 +515,7 @@
     m_overflowRect = m_box->layoutOverflowRect();
     m_box->flipForWritingMode(m_overflowRect);
 
-    int scrollableLeftOverflow = m_overflowRect.x() - m_box->borderLeft();
+    int scrollableLeftOverflow = m_overflowRect.x() - m_box->borderLeft() - (m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? m_box->verticalScrollbarWidth() : 0);
     int scrollableTopOverflow = m_overflowRect.y() - m_box->borderTop();
     setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
 }
@@ -768,9 +771,9 @@
     } else {
         widget = Scrollbar::create(this, orientation, RegularScrollbar);
         if (orientation == HorizontalScrollbar)
-            didAddHorizontalScrollbar(widget.get());
+            didAddScrollbar(widget.get(), HorizontalScrollbar);
         else
-            didAddVerticalScrollbar(widget.get());
+            didAddScrollbar(widget.get(), VerticalScrollbar);
     }
     m_box->document().view()->addChild(widget.get());
     return widget.release();
@@ -782,12 +785,8 @@
     if (!scrollbar)
         return;
 
-    if (!scrollbar->isCustomScrollbar()) {
-        if (orientation == HorizontalScrollbar)
-            willRemoveHorizontalScrollbar(scrollbar.get());
-        else
-            willRemoveVerticalScrollbar(scrollbar.get());
-    }
+    if (!scrollbar->isCustomScrollbar())
+        willRemoveScrollbar(scrollbar.get(), orientation);
 
     scrollbar->removeFromParent();
     scrollbar->disconnectFromScrollableArea();
@@ -889,7 +888,7 @@
     // FIXME, this should eventually be removed, once we are certain that composited
     // controls get correctly positioned on a compositor update. For now, conservatively
     // leaving this unchanged.
-    if (m_box->compositedLayerMapping())
+    if (m_box->hasCompositedLayerMapping())
         m_box->compositedLayerMapping()->positionOverflowControlsLayers(offsetFromRoot);
 }
 
@@ -1189,12 +1188,12 @@
     RefPtr<Image> resizeCornerImage;
     IntSize cornerResizerSize;
     if (deviceScaleFactor >= 2) {
-        DEFINE_STATIC_LOCAL(Image*, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x").leakRef()));
+        DEFINE_STATIC_REF(Image, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x")));
         resizeCornerImage = resizeCornerImageHiRes;
         cornerResizerSize = resizeCornerImage->size();
         cornerResizerSize.scale(0.5f);
     } else {
-        DEFINE_STATIC_LOCAL(Image*, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner").leakRef()));
+        DEFINE_STATIC_REF(Image, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner")));
         resizeCornerImage = resizeCornerImageLoRes;
         cornerResizerSize = resizeCornerImage->size();
     }
@@ -1347,7 +1346,7 @@
         // Count the total number of RenderLayers that are scrollable areas for
         // any period. We only want to record this at most once per RenderLayer.
         if (requiresScrollableArea && !m_isScrollableAreaHasBeenRecorded) {
-            WebKit::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::IsScrollableAreaBucket, RenderLayer::CompositedScrollingHistogramMax);
+            blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::IsScrollableAreaBucket, RenderLayer::CompositedScrollingHistogramMax);
             m_isScrollableAreaHasBeenRecorded = true;
         }
 
@@ -1385,7 +1384,7 @@
     // relax composited scrolling requirements, thereby increasing the
     // number of composited overflow divs.
     if (layer()->acceleratedCompositingForOverflowScrollEnabled())
-        WebKit::Platform::current()->histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
+        blink::Platform::current()->histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
 
     const bool needsCompositedScrollingDidChange = setNeedsCompositedScrolling(needsCompositedScrolling);
 
@@ -1400,18 +1399,18 @@
 
 bool RenderLayerScrollableArea::setNeedsCompositedScrolling(bool needsCompositedScrolling)
 {
-    if (layer()->m_needsCompositedScrolling == needsCompositedScrolling)
+    if (this->needsCompositedScrolling() == needsCompositedScrolling)
         return false;
 
     // Count the total number of RenderLayers which need composited scrolling at
     // some point. This should be recorded at most once per RenderLayer, so we
     // check m_willUseCompositedScrollingHasBeenRecorded.
     if (layer()->acceleratedCompositingForOverflowScrollEnabled() && !m_willUseCompositedScrollingHasBeenRecorded) {
-        WebKit::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::WillUseCompositedScrollingBucket, RenderLayer::CompositedScrollingHistogramMax);
+        blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::WillUseCompositedScrollingBucket, RenderLayer::CompositedScrollingHistogramMax);
         m_willUseCompositedScrollingHasBeenRecorded = true;
     }
 
-    layer()->m_needsCompositedScrolling = needsCompositedScrolling;
+    m_needsCompositedScrolling = needsCompositedScrolling;
 
     return true;
 }
@@ -1441,7 +1440,36 @@
     if (m_box && (m_box->isIntristicallyScrollable(VerticalScrollbar) || m_box->isIntristicallyScrollable(HorizontalScrollbar)))
         return false;
 
-    return m_box->compositedLayerMapping() && m_box->compositedLayerMapping()->scrollingLayer();
+    return m_box->hasCompositedLayerMapping() && m_box->compositedLayerMapping()->scrollingLayer();
+}
+
+bool RenderLayerScrollableArea::adjustForForceCompositedScrollingMode(bool value) const
+{
+    switch (m_forceNeedsCompositedScrolling) {
+    case DoNotForceCompositedScrolling:
+        return value;
+    case CompositedScrollingAlwaysOn:
+        return true;
+    case CompositedScrollingAlwaysOff:
+        return false;
+    }
+
+    ASSERT_NOT_REACHED();
+    return value;
+}
+
+bool RenderLayerScrollableArea::needsCompositedScrolling() const
+{
+    return adjustForForceCompositedScrollingMode(m_needsCompositedScrolling);
+}
+
+void RenderLayerScrollableArea::setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode mode)
+{
+    if (m_forceNeedsCompositedScrolling == mode)
+        return;
+
+    m_forceNeedsCompositedScrolling = mode;
+    layer()->didUpdateNeedsCompositedScrolling();
 }
 
 } // Namespace WebCore
diff --git a/Source/core/rendering/RenderLayerScrollableArea.h b/Source/core/rendering/RenderLayerScrollableArea.h
index c14b304..607c9bf 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.h
+++ b/Source/core/rendering/RenderLayerScrollableArea.h
@@ -53,12 +53,20 @@
     ResizerForTouch
 };
 
+enum ForceNeedsCompositedScrollingMode {
+    DoNotForceCompositedScrolling = 0,
+    CompositedScrollingAlwaysOn = 1,
+    CompositedScrollingAlwaysOff = 2
+};
+
 class PlatformEvent;
 class RenderBox;
 class RenderLayer;
 class RenderScrollbarPart;
 
 class RenderLayerScrollableArea FINAL : public ScrollableArea {
+    friend class Internals;
+
 public:
     RenderLayerScrollableArea(RenderBox*);
     virtual ~RenderLayerScrollableArea();
@@ -164,6 +172,12 @@
     // Rectangle encompassing the scroll corner and resizer rect.
     IntRect scrollCornerAndResizerRect() const;
 
+    bool needsCompositedScrolling() const;
+
+    // FIXME: This needs to be exposed as forced compositing scrolling is a RenderLayerScrollableArea
+    // concept and stacking container is a RenderLayerStackingNode concept.
+    bool adjustForForceCompositedScrollingMode(bool) const;
+
 private:
     bool hasHorizontalOverflow() const;
     bool hasVerticalOverflow() const;
@@ -207,6 +221,8 @@
 
     virtual void updateHasVisibleNonLayerContent() OVERRIDE;
 
+    void setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode);
+
     RenderBox* m_box;
 
     // Keeps track of whether the layer is currently resizing, so events can cause resizing to start and stop.
@@ -215,10 +231,13 @@
     unsigned m_scrollDimensionsDirty : 1;
     unsigned m_inOverflowRelayout : 1;
 
+    unsigned m_needsCompositedScrolling : 1;
     unsigned m_willUseCompositedScrollingHasBeenRecorded : 1;
 
     unsigned m_isScrollableAreaHasBeenRecorded : 1;
 
+    ForceNeedsCompositedScrollingMode m_forceNeedsCompositedScrolling;
+
     // The width/height of our scrolled area.
     LayoutRect m_overflowRect;
 
diff --git a/Source/core/rendering/RenderLayerStackingNode.cpp b/Source/core/rendering/RenderLayerStackingNode.cpp
index 3251fbe..8f25001 100644
--- a/Source/core/rendering/RenderLayerStackingNode.cpp
+++ b/Source/core/rendering/RenderLayerStackingNode.cpp
@@ -430,7 +430,7 @@
         || renderer()->hasFilter()
         || renderer()->hasBlendMode()
         || layer()->isTransparent()
-        || renderer()->isRenderRegion();
+        || renderer()->style()->hasFlowFrom();
 
     return couldBeNormalFlow && !preventsElementFromBeingNormalFlow;
 }
@@ -438,7 +438,7 @@
 void RenderLayerStackingNode::updateIsNormalFlowOnly()
 {
     bool isNormalFlowOnly = shouldBeNormalFlowOnly();
-    if (isNormalFlowOnly == m_isNormalFlowOnly)
+    if (isNormalFlowOnly == this->isNormalFlowOnly())
         return;
 
     m_isNormalFlowOnly = isNormalFlowOnly;
@@ -449,7 +449,7 @@
 
 bool RenderLayerStackingNode::needsToBeStackingContainer() const
 {
-    return layer()->adjustForForceCompositedScrollingMode(m_needsToBeStackingContainer);
+    return layer()->scrollableArea() && layer()->scrollableArea()->adjustForForceCompositedScrollingMode(m_needsToBeStackingContainer);
 }
 
 // Determine whether the current layer can be promoted to a stacking container.
@@ -620,14 +620,14 @@
 
 bool RenderLayerStackingNode::setNeedsToBeStackingContainer(bool needsToBeStackingContainer)
 {
-    if (m_needsToBeStackingContainer == needsToBeStackingContainer)
+    if (this->needsToBeStackingContainer() == needsToBeStackingContainer)
         return false;
 
     // Count the total number of RenderLayers which need to be stacking
     // containers some point. This should be recorded at most once per
     // RenderLayer, so we check m_needsToBeStackingContainerHasBeenRecorded.
     if (layer()->acceleratedCompositingForOverflowScrollEnabled() && !m_needsToBeStackingContainerHasBeenRecorded) {
-        WebKit::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::NeedsToBeStackingContainerBucket, RenderLayer::CompositedScrollingHistogramMax);
+        blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::NeedsToBeStackingContainerBucket, RenderLayer::CompositedScrollingHistogramMax);
         m_needsToBeStackingContainerHasBeenRecorded = true;
     }
 
diff --git a/Source/core/rendering/RenderLayerStackingNode.h b/Source/core/rendering/RenderLayerStackingNode.h
index 573ac69..d19cc50 100644
--- a/Source/core/rendering/RenderLayerStackingNode.h
+++ b/Source/core/rendering/RenderLayerStackingNode.h
@@ -46,7 +46,6 @@
 #define RenderLayerStackingNode_h
 
 #include "core/rendering/RenderLayerModelObject.h"
-
 #include "wtf/Noncopyable.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/Vector.h"
@@ -74,7 +73,6 @@
     // necessarily be stacking contexts.
     bool isStackingContainer() const { return isStackingContext() || needsToBeStackingContainer(); }
 
-    bool needsToBeStackingContainer() const;
     bool setNeedsToBeStackingContainer(bool);
 
     // Returns true if z ordering would not change if this layer were a stacking container.
@@ -91,32 +89,13 @@
     void clearZOrderLists();
     void dirtyStackingContainerZOrderLists();
 
-    // FIXME: These accessors should be made private and callers moved to RenderLayerStackingNodeIterator.
-    Vector<RenderLayerStackingNode*>* posZOrderList() const
-    {
-        ASSERT(!m_zOrderListsDirty);
-        ASSERT(isStackingContainer() || !m_posZOrderList);
-        return m_posZOrderList.get();
-    }
-
+    bool hasPositiveZOrderList() const { return posZOrderList() && posZOrderList()->size(); }
     bool hasNegativeZOrderList() const { return negZOrderList() && negZOrderList()->size(); }
 
-    Vector<RenderLayerStackingNode*>* negZOrderList() const
-    {
-        ASSERT(!m_zOrderListsDirty);
-        ASSERT(isStackingContainer() || !m_negZOrderList);
-        return m_negZOrderList.get();
-    }
-
     bool isNormalFlowOnly() const { return m_isNormalFlowOnly; }
     void updateIsNormalFlowOnly();
     bool normalFlowListDirty() const { return m_normalFlowListDirty; }
     void dirtyNormalFlowList();
-    Vector<RenderLayerStackingNode*>* normalFlowList() const
-    {
-        ASSERT(!m_normalFlowListDirty);
-        return m_normalFlowList.get();
-    }
 
     enum PaintOrderListType {BeforePromote, AfterPromote};
     void computePaintOrderList(PaintOrderListType, Vector<RefPtr<Node> >&);
@@ -138,6 +117,30 @@
 #endif
 
 private:
+    friend class RenderLayerStackingNodeIterator;
+    friend class RenderLayerStackingNodeReverseIterator;
+    friend class RenderTreeAsText;
+
+    Vector<RenderLayerStackingNode*>* posZOrderList() const
+    {
+        ASSERT(!m_zOrderListsDirty);
+        ASSERT(isStackingContainer() || !m_posZOrderList);
+        return m_posZOrderList.get();
+    }
+
+    Vector<RenderLayerStackingNode*>* normalFlowList() const
+    {
+        ASSERT(!m_normalFlowListDirty);
+        return m_normalFlowList.get();
+    }
+
+    Vector<RenderLayerStackingNode*>* negZOrderList() const
+    {
+        ASSERT(!m_zOrderListsDirty);
+        ASSERT(isStackingContainer() || !m_negZOrderList);
+        return m_negZOrderList.get();
+    }
+
     enum CollectLayersBehavior {
         ForceLayerToStackingContainer,
         OverflowScrollCanBeStackingContainers,
@@ -183,6 +186,8 @@
 
     bool isDirtyStackingContainer() const { return m_zOrderListsDirty && isStackingContainer(); }
 
+    bool needsToBeStackingContainer() const;
+
     RenderLayerCompositor* compositor() const;
     // FIXME: Investigate changing this to Renderbox.
     RenderLayerModelObject* renderer() const;
diff --git a/Source/core/rendering/RenderLayerStackingNodeIterator.cpp b/Source/core/rendering/RenderLayerStackingNodeIterator.cpp
index d523c20..8c16179 100644
--- a/Source/core/rendering/RenderLayerStackingNodeIterator.cpp
+++ b/Source/core/rendering/RenderLayerStackingNodeIterator.cpp
@@ -68,4 +68,73 @@
     return 0;
 }
 
+RenderLayerStackingNode* RenderLayerStackingNodeReverseIterator::next()
+{
+    if (m_remainingChildren & NegativeZOrderChildren) {
+        Vector<RenderLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
+        if (negZOrderList && m_index >= 0)
+            return negZOrderList->at(m_index--);
+
+        m_remainingChildren &= ~NegativeZOrderChildren;
+        setIndexToLastItem();
+    }
+
+    if (m_remainingChildren & NormalFlowChildren) {
+        Vector<RenderLayerStackingNode*>* normalFlowList = m_root.normalFlowList();
+        if (normalFlowList && m_index >= 0)
+            return normalFlowList->at(m_index--);
+
+        m_remainingChildren &= ~NormalFlowChildren;
+        setIndexToLastItem();
+    }
+
+    if (m_remainingChildren & PositiveZOrderChildren) {
+        Vector<RenderLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
+        if (posZOrderList && m_index >= 0)
+            return posZOrderList->at(m_index--);
+
+        m_remainingChildren &= ~PositiveZOrderChildren;
+        setIndexToLastItem();
+    }
+
+    return 0;
+}
+
+void RenderLayerStackingNodeReverseIterator::setIndexToLastItem()
+{
+    if (m_remainingChildren & NegativeZOrderChildren) {
+        Vector<RenderLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
+        if (negZOrderList) {
+            m_index  = negZOrderList->size() - 1;
+            return;
+        }
+
+        m_remainingChildren &= ~NegativeZOrderChildren;
+    }
+
+    if (m_remainingChildren & NormalFlowChildren) {
+        Vector<RenderLayerStackingNode*>* normalFlowList = m_root.normalFlowList();
+        if (normalFlowList) {
+            m_index = normalFlowList->size() - 1;
+            return;
+        }
+
+        m_remainingChildren &= ~NormalFlowChildren;
+    }
+
+    if (m_remainingChildren & PositiveZOrderChildren) {
+        Vector<RenderLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
+        if (posZOrderList) {
+            m_index = posZOrderList->size() - 1;
+            return;
+        }
+
+        m_remainingChildren &= ~PositiveZOrderChildren;
+    }
+
+    // No more list to visit.
+    ASSERT(!m_remainingChildren);
+    m_index = -1;
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerStackingNodeIterator.h b/Source/core/rendering/RenderLayerStackingNodeIterator.h
index 67abde5..7682ea3 100644
--- a/Source/core/rendering/RenderLayerStackingNodeIterator.h
+++ b/Source/core/rendering/RenderLayerStackingNodeIterator.h
@@ -45,6 +45,8 @@
 class RenderLayer;
 class RenderLayerStackingNode;
 
+// This iterator walks the RenderLayerStackingNode lists in the following order:
+// NegativeZOrderChildren -> NormalFlowChildren -> PositiveZOrderChildren.
 class RenderLayerStackingNodeIterator {
     WTF_MAKE_NONCOPYABLE(RenderLayerStackingNodeIterator);
 public:
@@ -63,6 +65,28 @@
     unsigned m_index;
 };
 
+// This iterator is similar to RenderLayerStackingNodeIterator but it walks the lists in reverse order
+// (from the last item to the first one).
+class RenderLayerStackingNodeReverseIterator {
+    WTF_MAKE_NONCOPYABLE(RenderLayerStackingNodeReverseIterator);
+public:
+    RenderLayerStackingNodeReverseIterator(const RenderLayerStackingNode& root, unsigned whichChildren)
+        : m_root(root)
+        , m_remainingChildren(whichChildren)
+    {
+        setIndexToLastItem();
+    }
+
+    RenderLayerStackingNode* next();
+
+private:
+    void setIndexToLastItem();
+
+    const RenderLayerStackingNode& m_root;
+    unsigned m_remainingChildren;
+    int m_index;
+};
+
 } // namespace WebCore
 
 #endif // RenderLayerStackingNodeIterator_h
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index 0790752..9b41078 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -51,6 +51,7 @@
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderText.h"
@@ -164,6 +165,7 @@
 
 void RenderListBox::layout()
 {
+    LayoutRectRecorder recorder(*this);
     RenderBlockFlow::layout();
 
     if (m_vBar) {
@@ -893,7 +895,7 @@
         widget = RenderScrollbar::createCustomScrollbar(this, VerticalScrollbar, this->node());
     else {
         widget = Scrollbar::create(this, VerticalScrollbar, RenderTheme::theme().scrollbarControlSizeForPart(ListboxPart));
-        didAddVerticalScrollbar(widget.get());
+        didAddScrollbar(widget.get(), VerticalScrollbar);
     }
     document().view()->addChild(widget.get());
     return widget.release();
@@ -905,7 +907,7 @@
         return;
 
     if (!m_vBar->isCustomScrollbar())
-        ScrollableArea::willRemoveVerticalScrollbar(m_vBar.get());
+        ScrollableArea::willRemoveScrollbar(m_vBar.get(), VerticalScrollbar);
     m_vBar->removeFromParent();
     m_vBar->disconnectFromScrollableArea();
     m_vBar = 0;
diff --git a/Source/core/rendering/RenderListItem.cpp b/Source/core/rendering/RenderListItem.cpp
index d5a7b8a..b3b57a5 100644
--- a/Source/core/rendering/RenderListItem.cpp
+++ b/Source/core/rendering/RenderListItem.cpp
@@ -27,6 +27,7 @@
 #include "HTMLNames.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLOListElement.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderListMarker.h"
 #include "core/rendering/RenderView.h"
 #include "wtf/StdLibExtras.h"
@@ -82,7 +83,7 @@
 
 void RenderListItem::insertedIntoTree()
 {
-    RenderBlock::insertedIntoTree();
+    RenderBlockFlow::insertedIntoTree();
 
     updateListMarkerNumbers();
 }
@@ -125,12 +126,13 @@
         return 0;
 
     const Node* current = item ? item->node() : listNode;
-    current = ElementTraversal::nextIncludingPseudo(current, listNode);
+    ASSERT(current);
+    current = ElementTraversal::nextIncludingPseudo(*current, listNode);
 
     while (current) {
         if (isList(current)) {
             // We've found a nested, independent list: nothing to do here.
-            current = ElementTraversal::nextIncludingPseudoSkippingChildren(current, listNode);
+            current = ElementTraversal::nextIncludingPseudoSkippingChildren(*current, listNode);
             continue;
         }
 
@@ -139,7 +141,7 @@
             return toRenderListItem(renderer);
 
         // FIXME: Can this be optimized to skip the children of the elements without a renderer?
-        current = ElementTraversal::nextIncludingPseudo(current, listNode);
+        current = ElementTraversal::nextIncludingPseudo(*current, listNode);
     }
 
     return 0;
@@ -149,7 +151,8 @@
 static RenderListItem* previousListItem(const Node* listNode, const RenderListItem* item)
 {
     Node* current = item->node();
-    for (current = ElementTraversal::previousIncludingPseudo(current, listNode); current; current = ElementTraversal::previousIncludingPseudo(current, listNode)) {
+    ASSERT(current);
+    for (current = ElementTraversal::previousIncludingPseudo(*current, listNode); current; current = ElementTraversal::previousIncludingPseudo(*current, listNode)) {
         RenderObject* renderer = current->renderer();
         if (!renderer || (renderer && !renderer->isListItem()))
             continue;
@@ -162,7 +165,7 @@
         // be a list item itself. We need to examine it, so we do this to counteract
         // the previousIncludingPseudo() that will be done by the loop.
         if (otherList)
-            current = ElementTraversal::nextIncludingPseudo(otherList);
+            current = ElementTraversal::nextIncludingPseudo(*otherList);
     }
     return 0;
 }
@@ -219,7 +222,7 @@
     return lastChild() == m_marker;
 }
 
-static RenderObject* getParentOfFirstLineBox(RenderBlock* curr, RenderObject* marker)
+static RenderObject* getParentOfFirstLineBox(RenderBlockFlow* curr, RenderObject* marker)
 {
     RenderObject* firstChild = curr->firstChild();
     if (!firstChild)
@@ -236,14 +239,14 @@
         if (currChild->isFloating() || currChild->isOutOfFlowPositioned())
             continue;
 
-        if (currChild->isTable() || !currChild->isRenderBlock() || (currChild->isBox() && toRenderBox(currChild)->isWritingModeRoot()))
+        if (!currChild->isRenderBlockFlow() || (currChild->isBox() && toRenderBox(currChild)->isWritingModeRoot()))
             break;
 
         if (curr->isListItem() && inQuirksMode && currChild->node() &&
             (currChild->node()->hasTagName(ulTag)|| currChild->node()->hasTagName(olTag)))
             break;
 
-        RenderObject* lineBox = getParentOfFirstLineBox(toRenderBlock(currChild), marker);
+        RenderObject* lineBox = getParentOfFirstLineBox(toRenderBlockFlow(currChild), marker);
         if (lineBox)
             return lineBox;
     }
@@ -313,6 +316,7 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     updateMarkerLocation();
     RenderBlockFlow::layout();
 }
diff --git a/Source/core/rendering/RenderListItem.h b/Source/core/rendering/RenderListItem.h
index 5bf76b0..797ccc7 100644
--- a/Source/core/rendering/RenderListItem.h
+++ b/Source/core/rendering/RenderListItem.h
@@ -74,8 +74,6 @@
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
 
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
     virtual void addOverflowFromChildren();
 
     void updateMarkerLocation();
diff --git a/Source/core/rendering/RenderListMarker.cpp b/Source/core/rendering/RenderListMarker.cpp
index 47ae106..614b293 100644
--- a/Source/core/rendering/RenderListMarker.cpp
+++ b/Source/core/rendering/RenderListMarker.cpp
@@ -30,6 +30,7 @@
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderView.h"
@@ -1324,6 +1325,7 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     if (isImage()) {
         updateMarginsAndContent();
         setWidth(m_image->imageSize(this, style()->effectiveZoom()).width());
diff --git a/Source/core/rendering/RenderMarquee.cpp b/Source/core/rendering/RenderMarquee.cpp
index ecad8bd..10340b3 100644
--- a/Source/core/rendering/RenderMarquee.cpp
+++ b/Source/core/rendering/RenderMarquee.cpp
@@ -49,7 +49,7 @@
 #include "HTMLNames.h"
 #include "core/html/HTMLMarqueeElement.h"
 #include "core/frame/FrameView.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 
diff --git a/Source/core/rendering/RenderMedia.cpp b/Source/core/rendering/RenderMedia.cpp
index f76855e..aacc6ae 100644
--- a/Source/core/rendering/RenderMedia.cpp
+++ b/Source/core/rendering/RenderMedia.cpp
@@ -28,6 +28,7 @@
 #include "core/rendering/RenderMedia.h"
 
 #include "core/html/HTMLMediaElement.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderView.h"
 
@@ -39,13 +40,6 @@
     setImageResource(RenderImageResource::create());
 }
 
-RenderMedia::RenderMedia(HTMLMediaElement* video, const IntSize& intrinsicSize)
-    : RenderImage(video)
-{
-    setImageResource(RenderImageResource::create());
-    setIntrinsicSize(intrinsicSize);
-}
-
 RenderMedia::~RenderMedia()
 {
 }
@@ -57,6 +51,7 @@
 
 void RenderMedia::layout()
 {
+    LayoutRectRecorder recorder(*this);
     LayoutSize oldSize = contentBoxRect().size();
 
     RenderImage::layout();
diff --git a/Source/core/rendering/RenderMedia.h b/Source/core/rendering/RenderMedia.h
index 2c1c9b4..ada064b 100644
--- a/Source/core/rendering/RenderMedia.h
+++ b/Source/core/rendering/RenderMedia.h
@@ -35,7 +35,6 @@
 class RenderMedia : public RenderImage {
 public:
     explicit RenderMedia(HTMLMediaElement*);
-    RenderMedia(HTMLMediaElement*, const IntSize& intrinsicSize);
     virtual ~RenderMedia();
 
     RenderObject* firstChild() const { ASSERT(children() == virtualChildren()); return children()->firstChild(); }
@@ -63,8 +62,6 @@
     virtual bool isImage() const OVERRIDE FINAL { return false; }
     virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
 
-    virtual bool requiresForcedStyleRecalcPropagation() const OVERRIDE FINAL { return true; }
-
     RenderObjectChildList m_children;
 };
 
diff --git a/Source/core/rendering/RenderMediaControlElements.cpp b/Source/core/rendering/RenderMediaControlElements.cpp
index 4e14e90..da2babc 100644
--- a/Source/core/rendering/RenderMediaControlElements.cpp
+++ b/Source/core/rendering/RenderMediaControlElements.cpp
@@ -29,6 +29,7 @@
 
 #include "core/rendering/RenderMediaControlElements.h"
 
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderView.h"
 
 namespace WebCore {
@@ -40,6 +41,7 @@
 
 void RenderTextTrackContainerElement::layout()
 {
+    LayoutRectRecorder recorder(*this);
     RenderBlock::layout();
     if (style()->display() == NONE)
         return;
diff --git a/Source/core/rendering/RenderMenuList.cpp b/Source/core/rendering/RenderMenuList.cpp
index e115d4f..c0a92f7 100644
--- a/Source/core/rendering/RenderMenuList.cpp
+++ b/Source/core/rendering/RenderMenuList.cpp
@@ -39,12 +39,12 @@
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/platform/PopupMenu.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/rendering/RenderBR.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
+#include "platform/PopupMenu.h"
 #include "platform/geometry/IntSize.h"
 
 using namespace std;
@@ -379,13 +379,8 @@
     int listIndex = select->optionToListIndex(optionIndex);
     if (listIndex < 0 || listIndex >= static_cast<int>(select->listItems().size()))
         return;
-
-    HTMLElement* listItem = select->listItems()[listIndex];
-    ASSERT(listItem);
-    if (listItem->confusingAndOftenMisusedAttached()) {
-        if (AXMenuList* menuList = toAXMenuList(document().axObjectCache()->get(this)))
-            menuList->didUpdateActiveOption(optionIndex);
-    }
+    if (AXMenuList* menuList = toAXMenuList(document().axObjectCache()->get(this)))
+        menuList->didUpdateActiveOption(optionIndex);
 }
 
 String RenderMenuList::itemText(unsigned listIndex) const
diff --git a/Source/core/rendering/RenderMenuList.h b/Source/core/rendering/RenderMenuList.h
index d4e69fa..7c22cd6 100644
--- a/Source/core/rendering/RenderMenuList.h
+++ b/Source/core/rendering/RenderMenuList.h
@@ -24,9 +24,9 @@
 #ifndef RenderMenuList_h
 #define RenderMenuList_h
 
-#include "core/platform/PopupMenu.h"
 #include "core/platform/PopupMenuClient.h"
 #include "core/rendering/RenderFlexibleBox.h"
+#include "platform/PopupMenu.h"
 #include "platform/geometry/LayoutRect.h"
 
 namespace WebCore {
@@ -73,8 +73,6 @@
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
 
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
     // PopupMenuClient methods
     virtual void valueChanged(unsigned listIndex, bool fireOnChange = true) OVERRIDE;
     virtual void selectionChanged(unsigned, bool) OVERRIDE { }
diff --git a/Source/core/rendering/RenderMeter.h b/Source/core/rendering/RenderMeter.h
index 853679f..d1f1e43 100644
--- a/Source/core/rendering/RenderMeter.h
+++ b/Source/core/rendering/RenderMeter.h
@@ -44,7 +44,6 @@
 
     virtual const char* renderName() const { return "RenderMeter"; }
     virtual bool isMeter() const { return true; }
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
 
     double valueRatio() const;
 };
diff --git a/Source/core/rendering/RenderNamedFlowFragment.cpp b/Source/core/rendering/RenderNamedFlowFragment.cpp
new file mode 100644
index 0000000..5a754e9
--- /dev/null
+++ b/Source/core/rendering/RenderNamedFlowFragment.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 HOLDER 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/RenderNamedFlowFragment.h"
+
+#include "core/rendering/FlowThreadController.h"
+#include "core/rendering/RenderBoxRegionInfo.h"
+#include "core/rendering/RenderFlowThread.h"
+#include "core/rendering/RenderNamedFlowThread.h"
+#include "core/rendering/RenderView.h"
+
+using namespace std;
+
+namespace WebCore {
+
+RenderNamedFlowFragment::RenderNamedFlowFragment()
+    : RenderRegion(0, 0)
+{
+}
+
+RenderNamedFlowFragment::~RenderNamedFlowFragment()
+{
+}
+
+RenderNamedFlowFragment* RenderNamedFlowFragment::createAnonymous(Document* document)
+{
+    RenderNamedFlowFragment* region = new RenderNamedFlowFragment();
+    region->setDocumentForAnonymous(document);
+    return region;
+}
+
+void RenderNamedFlowFragment::setStyleForNamedFlowFragment(const RenderStyle* parentStyle)
+{
+    RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parentStyle, BLOCK);
+
+    newStyle->setFlowThread(parentStyle->flowThread());
+    newStyle->setRegionThread(parentStyle->regionThread());
+    newStyle->setRegionFragment(parentStyle->regionFragment());
+    newStyle->setShapeInside(parentStyle->shapeInside());
+    newStyle->setOverflowX(parentStyle->overflowX());
+    newStyle->setOverflowY(parentStyle->overflowY());
+
+    setStyle(newStyle.release());
+}
+
+void RenderNamedFlowFragment::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
+{
+    RenderRegion::styleDidChange(diff, oldStyle);
+
+    if (parent() && parent()->needsLayout())
+        setNeedsLayout();
+}
+
+// FIXME: flex items as regions with flex-basis: 0 inside a flex container
+// with flex-direction: column should not be treated as auto-height regions
+bool RenderNamedFlowFragment::shouldHaveAutoLogicalHeight() const
+{
+    ASSERT(parent());
+
+    RenderStyle* styleToUse = parent()->style();
+    bool hasSpecifiedEndpointsForHeight = styleToUse->logicalTop().isSpecified() && styleToUse->logicalBottom().isSpecified();
+    bool hasAnchoredEndpointsForHeight = isOutOfFlowPositioned() && hasSpecifiedEndpointsForHeight;
+    bool hasAutoHeightStyle = styleToUse->logicalHeight().isAuto()
+        || styleToUse->logicalHeight().isFitContent()
+        || styleToUse->logicalHeight().isMaxContent()
+        || styleToUse->logicalHeight().isMinContent();
+    return hasAutoHeightStyle && !hasAnchoredEndpointsForHeight;
+}
+
+LayoutUnit RenderNamedFlowFragment::maxPageLogicalHeight() const
+{
+    ASSERT(m_flowThread);
+    ASSERT(hasAutoLogicalHeight() && !m_flowThread->inConstrainedLayoutPhase());
+    ASSERT(isAnonymous());
+    ASSERT(parent());
+
+    RenderStyle* styleToUse = parent()->style();
+    return styleToUse->logicalMaxHeight().isUndefined() ? RenderFlowThread::maxLogicalHeight() : toRenderBlock(parent())->computeReplacedLogicalHeightUsing(styleToUse->logicalMaxHeight());
+}
+
+}
diff --git a/Source/core/rendering/RenderNamedFlowFragment.h b/Source/core/rendering/RenderNamedFlowFragment.h
new file mode 100644
index 0000000..f02f263
--- /dev/null
+++ b/Source/core/rendering/RenderNamedFlowFragment.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 HOLDER 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 RenderNamedFlowFragment_h
+#define RenderNamedFlowFragment_h
+
+#include "core/rendering/RenderRegion.h"
+
+namespace WebCore {
+
+class Element;
+class RenderStyle;
+
+// RenderNamedFlowFragment represents a region that is responsible for the fragmentation of
+// the RenderNamedFlowThread content.
+//
+// A RenderNamedFlowFragment object is created as an anonymous child for a RenderBlockFlow object
+// that has a valid -webkit-flow-from property.
+//
+// This allows a non-replaced block to behave like a region if needed, following the CSSRegions specification:
+// http://dev.w3.org/csswg/css-regions/#the-flow-from-property.
+// list-item, table-caption, table-cell can become regions in addition to block | inline-block.
+
+class RenderNamedFlowFragment FINAL : public RenderRegion {
+public:
+    virtual ~RenderNamedFlowFragment();
+    static RenderNamedFlowFragment* createAnonymous(Document*);
+
+    void setStyleForNamedFlowFragment(const RenderStyle*);
+
+    virtual bool isRenderNamedFlowFragment() const OVERRIDE { return true; }
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+
+    virtual LayoutUnit maxPageLogicalHeight() const OVERRIDE;
+
+protected:
+    RenderNamedFlowFragment();
+
+private:
+    virtual bool shouldHaveAutoLogicalHeight() const OVERRIDE;
+    virtual const char* renderName() const OVERRIDE { return "RenderNamedFlowFragment"; }
+};
+
+inline RenderNamedFlowFragment* toRenderNamedFlowFragment(RenderObject* object)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderNamedFlowFragment());
+    return static_cast<RenderNamedFlowFragment*>(object);
+}
+
+inline const RenderNamedFlowFragment* toRenderNamedFlowFragment(const RenderObject* object)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderNamedFlowFragment());
+    return static_cast<const RenderNamedFlowFragment*>(object);
+}
+
+// This will catch anyone doing an unnecessary cast.
+void toRenderNamedFlowFragment(const RenderNamedFlowFragment*);
+
+}
+
+#endif // RenderNamedFlowFragment_h
diff --git a/Source/core/rendering/RenderNamedFlowThread.cpp b/Source/core/rendering/RenderNamedFlowThread.cpp
index 9051dc5..7204954 100644
--- a/Source/core/rendering/RenderNamedFlowThread.cpp
+++ b/Source/core/rendering/RenderNamedFlowThread.cpp
@@ -193,12 +193,12 @@
     ASSERT(firstRegion);
     ASSERT(secondRegion);
 
-    ASSERT(firstRegion->generatingNode());
-    ASSERT(secondRegion->generatingNode());
+    ASSERT(firstRegion->generatingNodeForRegion());
+    ASSERT(secondRegion->generatingNodeForRegion());
 
     // If the regions belong to different nodes, compare their position in the DOM.
-    if (firstRegion->generatingNode() != secondRegion->generatingNode()) {
-        unsigned short position = firstRegion->generatingNode()->compareDocumentPosition(secondRegion->generatingNode());
+    if (firstRegion->generatingNodeForRegion() != secondRegion->generatingNodeForRegion()) {
+        unsigned short position = firstRegion->generatingNodeForRegion()->compareDocumentPosition(secondRegion->generatingNodeForRegion());
 
         // If the second region is contained in the first one, the first region is "less" if it's :before.
         if (position & Node::DOCUMENT_POSITION_CONTAINED_BY) {
@@ -568,12 +568,11 @@
 }
 
 // Retrieve the next node to be visited while computing the ranges inside a region.
-static Node* nextNodeInsideContentNode(const Node* currNode, const Node* contentNode)
+static Node* nextNodeInsideContentNode(const Node& currNode, const Node* contentNode)
 {
-    ASSERT(currNode);
     ASSERT(contentNode && contentNode->inNamedFlow());
 
-    if (currNode->renderer() && currNode->renderer()->isSVGRoot())
+    if (currNode.renderer() && currNode.renderer()->isSVGRoot())
         return NodeTraversal::nextSkippingChildren(currNode, contentNode);
     return NodeTraversal::next(currNode, contentNode);
 }
@@ -615,7 +614,7 @@
         bool skipOverOutsideNodes = false;
         Node* lastEndNode = 0;
 
-        for (Node* node = contentNode; node; node = nextNodeInsideContentNode(node, contentNode)) {
+        for (Node* node = contentNode; node; node = nextNodeInsideContentNode(*node, contentNode)) {
             RenderObject* renderer = node->renderer();
             if (!renderer)
                 continue;
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index bebdc1b..408557f 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -45,12 +45,13 @@
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/frame/animation/AnimationController.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderCounter.h"
 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
 #include "core/rendering/RenderFlexibleBox.h"
@@ -118,14 +119,13 @@
     unsigned m_debugBitfields : 2;
 #endif
     unsigned m_bitfields;
+    LayoutRect rects[2]; // Stores the old/new layout rectangles.
 };
 
 COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
 
 bool RenderObject::s_affectsParentBlock = false;
 
-RenderObjectAncestorLineboxDirtySet* RenderObject::s_ancestorLineboxDirtySet = 0;
-
 void* RenderObject::operator new(size_t sz)
 {
     ASSERT(isMainThread());
@@ -170,8 +170,6 @@
     // treat <rt> as ruby text ONLY if it still has its default treatment of block
     if (element->hasTagName(rtTag) && style->display() == BLOCK)
         return new RenderRubyText(element);
-    if (RuntimeEnabledFeatures::cssRegionsEnabled() && style->isDisplayRegionType() && style->hasFlowFrom() && doc.renderView())
-        return new RenderRegion(element, 0);
 
     switch (style->display()) {
     case NONE:
@@ -798,18 +796,29 @@
     toRenderLayerModelObject(this)->layer()->repainter().setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
 }
 
+RenderBlock* RenderObject::containerForFixedPosition(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
+{
+    ASSERT(!repaintContainerSkipped || !*repaintContainerSkipped);
+    ASSERT(!isText());
+    ASSERT(style()->position() == FixedPosition);
+
+    RenderObject* ancestor = parent();
+    for (; ancestor && !ancestor->canContainFixedPositionObjects(); ancestor = ancestor->parent()) {
+        if (repaintContainerSkipped && ancestor == repaintContainer)
+            *repaintContainerSkipped = true;
+    }
+
+    ASSERT(!ancestor || !ancestor->isAnonymousBlock());
+    return toRenderBlock(ancestor);
+}
+
 RenderBlock* RenderObject::containingBlock() const
 {
     RenderObject* o = parent();
     if (!o && isRenderScrollbarPart())
         o = toRenderScrollbarPart(this)->rendererOwningScrollbar();
     if (!isText() && m_style->position() == FixedPosition) {
-        while (o) {
-            if (o->canContainFixedPositionObjects())
-                break;
-            o = o->parent();
-        }
-        ASSERT(!o || !o->isAnonymousBlock());
+        return containerForFixedPosition();
     } else if (!isText() && m_style->position() == AbsolutePosition) {
         while (o) {
             // For relpositioned inlines, we return the nearest non-anonymous enclosing block. We don't try
@@ -819,17 +828,14 @@
             // inline directly.
             if (o->style()->position() != StaticPosition && (!o->isInline() || o->isReplaced()))
                 break;
-            if (o->isRenderView())
-                break;
-            if (o->hasTransform() && o->isRenderBlock())
+
+            if (o->canContainAbsolutePositionObjects())
                 break;
 
             if (o->style()->hasInFlowPosition() && o->isInline() && !o->isReplaced()) {
                 o = o->containingBlock();
                 break;
             }
-            if (o->isSVGForeignObject()) //foreignObject is the containing block for contents inside it
-                break;
 
             o = o->parent();
         }
@@ -1772,7 +1778,7 @@
 void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
 {
     if (!isText() && style && !RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
-        setStyle(animation().updateAnimations(this, style.get()));
+        setStyle(animation().updateAnimations(*this, *style));
         return;
     }
     setStyle(style);
@@ -2004,20 +2010,11 @@
         s_affectsParentBlock = false;
 
     if (view()->frameView()) {
-        bool shouldBlitOnFixedBackgroundImage = false;
-#if ENABLE(FAST_MOBILE_SCROLLING)
-        // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
-        // when scrolling a page with a fixed background image. As an optimization, assuming there are
-        // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
-        // ignore the CSS property "background-attachment: fixed".
-        shouldBlitOnFixedBackgroundImage = true;
-#endif
-
-        bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
-        bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
+        bool newStyleSlowScroll = newStyle && newStyle->hasFixedBackgroundImage();
+        bool oldStyleSlowScroll = m_style && m_style->hasFixedBackgroundImage();
 
         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
-        if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
+        if (drawsRootBackground) {
             if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
                 if (newStyleSlowScroll && newStyle->hasEntirelyFixedBackground())
                     newStyleSlowScroll = false;
@@ -2056,7 +2053,7 @@
         return;
 
     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
-        RenderCounter::rendererStyleChanged(this, oldStyle, m_style.get());
+        RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.get());
 
         // If the object already needs layout, then setNeedsLayout won't do
         // any work. But if the containing block has changed, then we may need
@@ -2482,35 +2479,16 @@
 
     EPosition pos = m_style->position();
     if (pos == FixedPosition) {
-        // container() can be called on an object that is not in the
-        // tree yet.  We don't call view() since it will assert if it
-        // can't get back to the canvas.  Instead we just walk as high up
-        // as we can.  If we're in the tree, we'll get the root.  If we
-        // aren't we'll get the root of our little subtree (most likely
-        // we'll just return 0).
-        // FIXME: The definition of view() has changed to not crawl up the render tree.  It might
-        // be safe now to use it.
-        while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
-            // foreignObject is the containing block for its contents.
-            if (o->isSVGForeignObject())
-                break;
-
-            // The render flow thread is the top most containing block
-            // for the fixed positioned elements.
-            if (o->isOutOfFlowRenderFlowThread())
-                break;
-
-            if (repaintContainerSkipped && o == repaintContainer)
-                *repaintContainerSkipped = true;
-
-            o = o->parent();
-        }
+        return containerForFixedPosition(repaintContainer, repaintContainerSkipped);
     } else if (pos == AbsolutePosition) {
-        // Same goes here.  We technically just want our containing block, but
-        // we may not have one if we're part of an uninstalled subtree.  We'll
-        // climb as high as we can though.
-        while (o && o->style()->position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
-            if (o->isSVGForeignObject()) // foreignObject is the containing block for contents inside it
+        // We technically just want our containing block, but
+        // we may not have one if we're part of an uninstalled
+        // subtree. We'll climb as high as we can though.
+        while (o) {
+            if (o->style()->position() != StaticPosition)
+                break;
+
+            if (o->canContainFixedPositionObjects())
                 break;
 
             if (repaintContainerSkipped && o == repaintContainer)
@@ -2589,14 +2567,7 @@
     // this renderer had no parent at the time remove() was called.
 
     if (hasCounterNodeMap())
-        RenderCounter::destroyCounterNodes(this);
-
-    // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
-    // be moved into RenderBoxModelObject::destroy.
-    if (hasLayer()) {
-        setHasLayer(false);
-        toRenderLayerModelObject(this)->destroyLayer();
-    }
+        RenderCounter::destroyCounterNodes(*this);
 
     setAncestorLineBoxDirty(false);
 
@@ -2845,6 +2816,7 @@
 void RenderObject::layout()
 {
     ASSERT(needsLayout());
+    LayoutRectRecorder recorder(*this);
     RenderObject* child = firstChild();
     while (child) {
         child->layoutIfNeeded();
@@ -2984,16 +2956,17 @@
     return result;
 }
 
-void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
+void RenderObject::getTextDecorationColors(unsigned decorations, Color& underline, Color& overline,
                                            Color& linethrough, bool quirksMode, bool firstlineStyle)
 {
     RenderObject* curr = this;
     RenderStyle* styleToUse = 0;
-    TextDecoration currDecs = TextDecorationNone;
+    unsigned currDecs = TextDecorationNone;
     Color resultColor;
     do {
         styleToUse = curr->style(firstlineStyle);
         currDecs = styleToUse->textDecoration();
+        currDecs &= decorations;
         resultColor = decorationColor(this, styleToUse);
         // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
         if (currDecs) {
@@ -3357,6 +3330,11 @@
     return objectIsRelayoutBoundary(this);
 }
 
+bool RenderObject::isRenderNamedFlowFragmentContainer() const
+{
+    return isRenderBlockFlow() && toRenderBlockFlow(this)->renderNamedFlowFragment();
+}
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index 9ccbc02..5b2d592 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -41,7 +41,6 @@
 #include "platform/geometry/FloatQuad.h"
 #include "platform/geometry/LayoutRect.h"
 #include "platform/transforms/TransformationMatrix.h"
-#include "wtf/HashSet.h"
 
 namespace WebCore {
 
@@ -129,7 +128,6 @@
     bool draggable;
 };
 
-typedef WTF::HashSet<const RenderObject*> RenderObjectAncestorLineboxDirtySet;
 typedef WTF::HashMap<const RenderLayer*, Vector<LayoutRect> > LayerHitTestRects;
 
 #ifndef NDEBUG
@@ -353,6 +351,7 @@
     virtual bool isRenderInline() const { return false; }
     virtual bool isRenderPart() const { return false; }
     virtual bool isRenderRegion() const { return false; }
+    virtual bool isRenderNamedFlowFragment() const { return false; }
     virtual bool isRenderView() const { return false; }
     virtual bool isReplica() const { return false; }
 
@@ -384,6 +383,7 @@
     virtual bool isRenderNamedFlowThread() const { return false; }
     bool isInFlowRenderFlowThread() const { return isRenderFlowThread() && !isOutOfFlowPositioned(); }
     bool isOutOfFlowRenderFlowThread() const { return isRenderFlowThread() && isOutOfFlowPositioned(); }
+    bool isRenderNamedFlowFragmentContainer() const;
 
     virtual bool isRenderMultiColumnBlock() const { return false; }
     virtual bool isRenderMultiColumnSet() const { return false; }
@@ -413,21 +413,12 @@
     bool hasColumns() const { return m_bitfields.hasColumns(); }
     void setHasColumns(bool b = true) { m_bitfields.setHasColumns(b); }
 
-    bool ancestorLineBoxDirty() const { return s_ancestorLineboxDirtySet && s_ancestorLineboxDirtySet->contains(this); }
-    void setAncestorLineBoxDirty(bool b = true)
+    bool ancestorLineBoxDirty() const { return m_bitfields.ancestorLineBoxDirty(); }
+    void setAncestorLineBoxDirty(bool value = true)
     {
-        if (b) {
-            if (!s_ancestorLineboxDirtySet)
-                s_ancestorLineboxDirtySet = new RenderObjectAncestorLineboxDirtySet;
-            s_ancestorLineboxDirtySet->add(this);
+        m_bitfields.setAncestorLineBoxDirty(value);
+        if (value)
             setNeedsLayout();
-        } else if (s_ancestorLineboxDirtySet) {
-            s_ancestorLineboxDirtySet->remove(this);
-            if (s_ancestorLineboxDirtySet->isEmpty()) {
-                delete s_ancestorLineboxDirtySet;
-                s_ancestorLineboxDirtySet = 0;
-            }
-        }
     }
 
     enum FlowThreadState {
@@ -441,8 +432,6 @@
     FlowThreadState flowThreadState() const { return m_bitfields.flowThreadState(); }
     void setFlowThreadState(FlowThreadState state) { m_bitfields.setFlowThreadState(state); }
 
-    virtual bool requiresForcedStyleRecalcPropagation() const { return false; }
-
     // FIXME: Until all SVG renders can be subclasses of RenderSVGModelObject we have
     // to add SVG renderer methods to RenderObject with an ASSERT_NOT_REACHED() default implementation.
     virtual bool isSVGRoot() const { return false; }
@@ -601,7 +590,11 @@
     // Returns true if this renderer is rooted, and optionally returns the hosting view (the root of the hierarchy).
     bool isRooted(RenderView** = 0) const;
 
-    Node* node() const { return isAnonymous() ? 0 : m_node; }
+    Node* node() const
+    {
+        return isAnonymous() ? 0 : m_node;
+    }
+
     Node* nonPseudoNode() const
     {
         ASSERT(!LayoutIndicator::inLayout());
@@ -654,21 +647,21 @@
     }
     void clearPositionedState() { m_bitfields.clearPositionedState(); }
 
-    void setFloating(bool b = true) { m_bitfields.setFloating(b); }
-    void setInline(bool b = true) { m_bitfields.setIsInline(b); }
+    void setFloating(bool isFloating) { m_bitfields.setFloating(isFloating); }
+    void setInline(bool isInline) { m_bitfields.setIsInline(isInline); }
 
-    void setHasBoxDecorations(bool = true);
+    void setHasBoxDecorations(bool);
     void invalidateBackgroundObscurationStatus();
     virtual bool computeBackgroundIsKnownToBeObscured() { return false; }
 
     void setIsText() { m_bitfields.setIsText(true); }
     void setIsBox() { m_bitfields.setIsBox(true); }
-    void setReplaced(bool b = true) { m_bitfields.setIsReplaced(b); }
-    void setHorizontalWritingMode(bool b = true) { m_bitfields.setHorizontalWritingMode(b); }
-    void setHasOverflowClip(bool b = true) { m_bitfields.setHasOverflowClip(b); }
-    void setHasLayer(bool b = true) { m_bitfields.setHasLayer(b); }
-    void setHasTransform(bool b = true) { m_bitfields.setHasTransform(b); }
-    void setHasReflection(bool b = true) { m_bitfields.setHasReflection(b); }
+    void setReplaced(bool isReplaced) { m_bitfields.setIsReplaced(isReplaced); }
+    void setHorizontalWritingMode(bool hasHorizontalWritingMode) { m_bitfields.setHorizontalWritingMode(hasHorizontalWritingMode); }
+    void setHasOverflowClip(bool hasOverflowClip) { m_bitfields.setHasOverflowClip(hasOverflowClip); }
+    void setHasLayer(bool hasLayer) { m_bitfields.setHasLayer(hasLayer); }
+    void setHasTransform(bool hasTransform) { m_bitfields.setHasTransform(hasTransform); }
+    void setHasReflection(bool hasReflection) { m_bitfields.setHasReflection(hasReflection); }
 
     void scheduleRelayout();
 
@@ -715,7 +708,7 @@
     void setAnimatableStyle(PassRefPtr<RenderStyle>);
 
     // Set the style of the object and update the state of the object accordingly.
-    virtual void setStyle(PassRefPtr<RenderStyle>);
+    void setStyle(PassRefPtr<RenderStyle>);
 
     // Set the style of the object if it's generated content.
     void setPseudoStyle(PassRefPtr<RenderStyle>);
@@ -731,6 +724,10 @@
     {
         return isRenderView() || (hasTransform() && isRenderBlock()) || isSVGForeignObject() || isOutOfFlowRenderFlowThread();
     }
+    bool canContainAbsolutePositionObjects() const
+    {
+        return isRenderView() || (hasTransform() && isRenderBlock()) || isSVGForeignObject();
+    }
 
     // Convert the given local point to absolute coordinates
     // FIXME: Temporary. If UseTransforms is true, take transforms into account. Eventually localToAbsolute() will always be transform-aware.
@@ -811,7 +808,7 @@
 
     virtual CursorDirective getCursor(const LayoutPoint&, Cursor&) const;
 
-    void getTextDecorationColors(int decorations, Color& underline, Color& overline, Color& linethrough, bool quirksMode = false, bool firstlineStyle = false);
+    void getTextDecorationColors(unsigned decorations, Color& underline, Color& overline, Color& linethrough, bool quirksMode = false, bool firstlineStyle = false);
 
     // Return the RenderLayerModelObject in the container chain which is responsible for painting this object, or 0
     // if painting is root-relative. This is the container that should be passed to the 'forRepaint'
@@ -917,8 +914,9 @@
      */
     virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0);
 
-    // When performing a global document tear-down we use this as a hook to not waste time doing unnecessary work.
-    bool documentBeingDestroyed() const { return document().isStopping(); }
+    // When performing a global document tear-down, the renderer of the document is cleared. We use this
+    // as a hook to detect the case of document destruction and don't waste time doing unnecessary work.
+    bool documentBeingDestroyed() const;
 
     void destroyAndCleanupAnonymousWrappers();
     virtual void destroy();
@@ -970,7 +968,6 @@
     bool shouldUseTransformFromContainer(const RenderObject* container) const;
     void getTransformFromContainer(const RenderObject* container, const LayoutSize& offsetInContainer, TransformationMatrix&) const;
 
-    // return true if this object requires a new stacking context
     bool createsGroup() const { return isTransparent() || hasMask() || hasFilter() || hasBlendMode(); }
 
     virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& /* additionalOffset */, const RenderLayerModelObject* /* paintContainer */ = 0) { };
@@ -990,6 +987,18 @@
 
     bool isRelayoutBoundaryForInspector() const;
 
+    const LayoutRect& oldRepaintRect() const { return m_oldRepaintRect; }
+    void setOldRepaintRect(const LayoutRect& rect) { m_oldRepaintRect = rect; }
+
+    const LayoutRect& newRepaintRect() const { return m_newRepaintRect; }
+    void setNewRepaintRect(const LayoutRect& rect) { m_newRepaintRect = rect; }
+
+    void clearRepaintRects()
+    {
+        setOldRepaintRect(LayoutRect());
+        setNewRepaintRect(LayoutRect());
+    }
+
 protected:
     inline bool layerCreationAllowedForSubtree() const;
 
@@ -1042,6 +1051,8 @@
     virtual void computeSelfHitTestRects(Vector<LayoutRect>&, const LayoutPoint& layerOffset) const { };
 
 private:
+    RenderBlock* containerForFixedPosition(const RenderLayerModelObject* repaintContainer = 0, bool* repaintContainerSkipped = 0) const;
+
     RenderFlowThread* locateFlowThreadContainingBlock() const;
     void removeFromRenderFlowThread();
     void removeFromRenderFlowThreadRecursive(RenderFlowThread*);
@@ -1069,8 +1080,6 @@
     RenderObject* m_previous;
     RenderObject* m_next;
 
-    static RenderObjectAncestorLineboxDirtySet* s_ancestorLineboxDirtySet;
-
 #ifndef NDEBUG
     unsigned m_hasAXObject             : 1;
     unsigned m_setNeedsLayoutForbidden : 1;
@@ -1113,6 +1122,7 @@
             , m_hasReflection(false)
             , m_hasCounterNodeMap(false)
             , m_everHadLayout(false)
+            , m_ancestorLineBoxDirty(false)
             , m_childrenInline(false)
             , m_hasColumns(false)
             , m_positionedState(IsStaticallyPositioned)
@@ -1122,7 +1132,7 @@
         {
         }
 
-        // 31 bits have been used here. There is one bit available.
+        // 32 bits have been used here, none are available.
         ADD_BOOLEAN_BITFIELD(selfNeedsLayout, SelfNeedsLayout);
         ADD_BOOLEAN_BITFIELD(needsPositionedMovementLayout, NeedsPositionedMovementLayout);
         ADD_BOOLEAN_BITFIELD(normalChildNeedsLayout, NormalChildNeedsLayout);
@@ -1146,6 +1156,7 @@
 
         ADD_BOOLEAN_BITFIELD(hasCounterNodeMap, HasCounterNodeMap);
         ADD_BOOLEAN_BITFIELD(everHadLayout, EverHadLayout);
+        ADD_BOOLEAN_BITFIELD(ancestorLineBoxDirty, AncestorLineBoxDirty);
 
         // from RenderBlock
         ADD_BOOLEAN_BITFIELD(childrenInline, ChildrenInline);
@@ -1195,8 +1206,16 @@
 private:
     // Store state between styleWillChange and styleDidChange
     static bool s_affectsParentBlock;
+
+    LayoutRect m_oldRepaintRect;
+    LayoutRect m_newRepaintRect;
 };
 
+inline bool RenderObject::documentBeingDestroyed() const
+{
+    return !document().renderer();
+}
+
 inline bool RenderObject::isBeforeContent() const
 {
     if (style()->styleType() != BEFORE)
@@ -1355,21 +1374,22 @@
     return adjustForAbsoluteZoom(value, renderer->style());
 }
 
-inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, RenderObject* renderer)
+inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, RenderObject& renderer)
 {
-    return adjustLayoutUnitForAbsoluteZoom(value, renderer->style());
+    ASSERT(renderer.style());
+    return adjustLayoutUnitForAbsoluteZoom(value, *renderer.style());
 }
 
-inline void adjustFloatQuadForAbsoluteZoom(FloatQuad& quad, RenderObject* renderer)
+inline void adjustFloatQuadForAbsoluteZoom(FloatQuad& quad, RenderObject& renderer)
 {
-    float zoom = renderer->style()->effectiveZoom();
+    float zoom = renderer.style()->effectiveZoom();
     if (zoom != 1)
         quad.scale(1 / zoom, 1 / zoom);
 }
 
-inline void adjustFloatRectForAbsoluteZoom(FloatRect& rect, RenderObject* renderer)
+inline void adjustFloatRectForAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
 {
-    float zoom = renderer->style()->effectiveZoom();
+    float zoom = renderer.style()->effectiveZoom();
     if (zoom != 1)
         rect.scale(1 / zoom, 1 / zoom);
 }
diff --git a/Source/core/rendering/RenderProgress.h b/Source/core/rendering/RenderProgress.h
index 957887f..bd1cac9 100644
--- a/Source/core/rendering/RenderProgress.h
+++ b/Source/core/rendering/RenderProgress.h
@@ -44,7 +44,6 @@
 private:
     virtual const char* renderName() const { return "RenderProgress"; }
     virtual bool isProgress() const { return true; }
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
     void animationTimerFired(Timer<RenderProgress>*);
diff --git a/Source/core/rendering/RenderQuote.cpp b/Source/core/rendering/RenderQuote.cpp
index d6e308e..6891671 100644
--- a/Source/core/rendering/RenderQuote.cpp
+++ b/Source/core/rendering/RenderQuote.cpp
@@ -251,7 +251,7 @@
 static const QuotesData* basicQuotesData()
 {
     // FIXME: The default quotes should be the fancy quotes for "en".
-    static QuotesData* staticBasicQuotes = QuotesData::create('"', '"', '\'', '\'').leakRef();
+    DEFINE_STATIC_REF(QuotesData, staticBasicQuotes, (QuotesData::create('"', '"', '\'', '\'')));
     return staticBasicQuotes;
 }
 
diff --git a/Source/core/rendering/RenderRegion.cpp b/Source/core/rendering/RenderRegion.cpp
index b53a28b..a9a60a1 100644
--- a/Source/core/rendering/RenderRegion.cpp
+++ b/Source/core/rendering/RenderRegion.cpp
@@ -32,6 +32,7 @@
 
 #include "core/css/resolver/StyleResolver.h"
 #include "core/rendering/FlowThreadController.h"
+#include "core/rendering/HitTestLocation.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBoxRegionInfo.h"
 #include "core/rendering/RenderNamedFlowThread.h"
@@ -74,7 +75,7 @@
 {
     ASSERT(m_flowThread);
     ASSERT(hasAutoLogicalHeight() && !m_flowThread->inConstrainedLayoutPhase());
-    return style()->logicalMaxHeight().isUndefined() ? LayoutUnit::max() / 2 : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
+    return style()->logicalMaxHeight().isUndefined() ? RenderFlowThread::maxLogicalHeight() : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
 }
 
 LayoutUnit RenderRegion::logicalHeightOfAllFlowThreadContent() const
@@ -96,12 +97,8 @@
 {
     ASSERT(isValid());
 
-    // FIXME: Would like to just use hasOverflowClip() but we aren't a block yet. When RenderRegion is eliminated and
-    // folded into RenderBlock, switch to hasOverflowClip().
-    bool clipX = style()->overflowX() != OVISIBLE;
-    bool clipY = style()->overflowY() != OVISIBLE;
     bool isLastRegionWithRegionFragmentBreak = (isLastPortion && (style()->regionFragment() == BreakRegionFragment));
-    if ((clipX && clipY) || isLastRegionWithRegionFragmentBreak)
+    if (hasOverflowClip() || isLastRegionWithRegionFragmentBreak)
         return flowThreadPortionRect;
 
     LayoutRect flowThreadOverflow = m_flowThread->visualOverflowRect();
@@ -112,12 +109,14 @@
     if (m_flowThread->isHorizontalWritingMode()) {
         LayoutUnit minY = isFirstPortion ? (flowThreadOverflow.y() - outlineSize) : flowThreadPortionRect.y();
         LayoutUnit maxY = isLastPortion ? max(flowThreadPortionRect.maxY(), flowThreadOverflow.maxY()) + outlineSize : flowThreadPortionRect.maxY();
+        bool clipX = style()->overflowX() != OVISIBLE;
         LayoutUnit minX = clipX ? flowThreadPortionRect.x() : min(flowThreadPortionRect.x(), flowThreadOverflow.x() - outlineSize);
         LayoutUnit maxX = clipX ? flowThreadPortionRect.maxX() : max(flowThreadPortionRect.maxX(), (flowThreadOverflow.maxX() + outlineSize));
         clipRect = LayoutRect(minX, minY, maxX - minX, maxY - minY);
     } else {
         LayoutUnit minX = isFirstPortion ? (flowThreadOverflow.x() - outlineSize) : flowThreadPortionRect.x();
         LayoutUnit maxX = isLastPortion ? max(flowThreadPortionRect.maxX(), flowThreadOverflow.maxX()) + outlineSize : flowThreadPortionRect.maxX();
+        bool clipY = style()->overflowY() != OVISIBLE;
         LayoutUnit minY = clipY ? flowThreadPortionRect.y() : min(flowThreadPortionRect.y(), (flowThreadOverflow.y() - outlineSize));
         LayoutUnit maxY = clipY ? flowThreadPortionRect.maxY() : max(flowThreadPortionRect.y(), (flowThreadOverflow.maxY() + outlineSize));
         clipRect = LayoutRect(minX, minY, maxX - minX, maxY - minY);
@@ -142,8 +141,8 @@
 
 Element* RenderRegion::element() const
 {
-    ASSERT(node() && node()->isElementNode());
-    return toElement(node());
+    ASSERT(nodeForRegion() && nodeForRegion()->isElementNode());
+    return toElement(nodeForRegion());
 }
 
 LayoutUnit RenderRegion::pageLogicalTopForOffset(LayoutUnit /* offset */) const
@@ -217,10 +216,9 @@
     bool customRegionStyle = false;
 
     // FIXME: Region styling doesn't work for pseudo elements.
-    if (node()) {
-        Element* regionElement = toElement(node());
-        customRegionStyle = view()->document().styleResolver()->checkRegionStyle(regionElement);
-    }
+    if (isElementBasedRegion())
+        customRegionStyle = view()->document().styleResolver()->checkRegionStyle(this->element());
+
     setHasCustomRegionStyle(customRegionStyle);
     m_flowThread->checkRegionsWithStyling();
 }
@@ -658,7 +656,7 @@
     LayoutUnit autoHeight = hasOverrideHeight() ? overrideLogicalContentHeight() : computedAutoHeight();
 
     LayoutUnit newLogicalHeight = autoHeight + borderAndPaddingLogicalHeight();
-    ASSERT(newLogicalHeight < LayoutUnit::max() / 2);
+    ASSERT(newLogicalHeight < RenderFlowThread::maxLogicalHeight());
     if (newLogicalHeight > logicalHeight()) {
         setLogicalHeight(newLogicalHeight);
         // Recalculate position of the render block after new logical height is set.
@@ -667,4 +665,24 @@
     }
 }
 
+Node* RenderRegion::nodeForRegion() const
+{
+    if (parent() && isRenderNamedFlowFragment())
+        return parent()->node();
+    return node();
+}
+
+Node* RenderRegion::generatingNodeForRegion() const
+{
+    if (parent() && isRenderNamedFlowFragment())
+        return parent()->generatingNode();
+    return generatingNode();
+}
+
+bool RenderRegion::isElementBasedRegion() const
+{
+    Node* node = nodeForRegion();
+    return node && node->isElementNode() && !node->isPseudoElement();
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderRegion.h b/Source/core/rendering/RenderRegion.h
index 1fa5de5..c05d613 100644
--- a/Source/core/rendering/RenderRegion.h
+++ b/Source/core/rendering/RenderRegion.h
@@ -46,11 +46,11 @@
 public:
     explicit RenderRegion(Element*, RenderFlowThread*);
 
-    virtual bool isRenderRegion() const { return true; }
+    virtual bool isRenderRegion() const OVERRIDE { return true; }
 
     bool hitTestFlowThreadContents(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     void setFlowThreadPortionRect(const LayoutRect& rect) { m_flowThreadPortionRect = rect; }
     LayoutRect flowThreadPortionRect() const { return m_flowThreadPortionRect; }
@@ -85,14 +85,12 @@
     RegionOversetState regionOversetState() const;
     void setRegionOversetState(RegionOversetState);
 
-    Element* element() const;
-
     // These methods represent the width and height of a "page" and for a RenderRegion they are just the
     // content width and content height of a region. For RenderRegionSets, however, they will be the width and
     // height of a single column or page in the set.
     virtual LayoutUnit pageLogicalWidth() const;
     virtual LayoutUnit pageLogicalHeight() const;
-    LayoutUnit maxPageLogicalHeight() const;
+    virtual LayoutUnit maxPageLogicalHeight() const;
 
     LayoutUnit logicalTopOfFlowThreadContentRect(const LayoutRect&) const;
     LayoutUnit logicalBottomOfFlowThreadContentRect(const LayoutRect&) const;
@@ -127,8 +125,6 @@
 
     bool hasComputedAutoHeight() const { return (m_computedAutoHeight >= 0); }
 
-    virtual void updateLogicalHeight() OVERRIDE;
-
     // The top of the nearest page inside the region. For RenderRegions, this is just the logical top of the
     // flow thread portion we contain. For sets, we have to figure out the top of the nearest column or
     // page.
@@ -143,6 +139,16 @@
 
     virtual void collectLayerFragments(LayerFragments&, const LayoutRect&, const LayoutRect&) { }
 
+    virtual bool canHaveChildren() const OVERRIDE { return false; }
+    virtual bool canHaveGeneratedChildren() const OVERRIDE { return true; }
+
+    bool isElementBasedRegion() const;
+
+    Node* nodeForRegion() const;
+    Node* generatingNodeForRegion() const;
+
+    virtual const char* renderName() const OVERRIDE { return "RenderRegion"; }
+
 protected:
     void setRegionObjectsRegionStyle();
     void restoreRegionObjectsOriginalStyle();
@@ -156,10 +162,6 @@
     virtual bool shouldHaveAutoLogicalHeight() const;
 
 private:
-    virtual const char* renderName() const { return "RenderRegion"; }
-
-    virtual bool canHaveChildren() const OVERRIDE { return false; }
-
     virtual void insertedIntoTree() OVERRIDE;
     virtual void willBeRemovedFromTree() OVERRIDE;
 
@@ -167,6 +169,8 @@
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
+    virtual void updateLogicalHeight() OVERRIDE;
+
     virtual void installFlowThread();
 
     PassRefPtr<RenderStyle> computeStyleInRegion(const RenderObject*);
@@ -179,6 +183,8 @@
     void incrementAutoLogicalHeightCount();
     void decrementAutoLogicalHeightCount();
 
+    Element* element() const;
+
 protected:
     RenderFlowThread* m_flowThread;
 
diff --git a/Source/core/rendering/RenderReplaced.cpp b/Source/core/rendering/RenderReplaced.cpp
index 4dbce99..7f8fc8a 100644
--- a/Source/core/rendering/RenderReplaced.cpp
+++ b/Source/core/rendering/RenderReplaced.cpp
@@ -27,6 +27,7 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderImage.h"
@@ -80,6 +81,7 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
 
     setHeight(minimumReplacedHeight());
diff --git a/Source/core/rendering/RenderReplica.cpp b/Source/core/rendering/RenderReplica.cpp
index 2c45b7f..d7885c2 100644
--- a/Source/core/rendering/RenderReplica.cpp
+++ b/Source/core/rendering/RenderReplica.cpp
@@ -30,6 +30,7 @@
 #include "core/rendering/RenderReplica.h"
 
 #include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderLayer.h"
 
 namespace WebCore {
@@ -57,6 +58,7 @@
 
 void RenderReplica::layout()
 {
+    LayoutRectRecorder recorder(*this);
     setFrameRect(parentBox()->borderBoxRect());
     updateLayerTransform();
     clearNeedsLayout();
diff --git a/Source/core/rendering/RenderRubyRun.cpp b/Source/core/rendering/RenderRubyRun.cpp
index 85d00e2..fe58c87 100644
--- a/Source/core/rendering/RenderRubyRun.cpp
+++ b/Source/core/rendering/RenderRubyRun.cpp
@@ -32,6 +32,7 @@
 
 #include "core/rendering/RenderRubyRun.h"
 
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderRubyBase.h"
 #include "core/rendering/RenderRubyText.h"
 #include "core/rendering/RenderText.h"
@@ -228,6 +229,7 @@
 
 void RenderRubyRun::layout()
 {
+    LayoutRectRecorder recorder(*this);
     RenderBlock::layout();
 
     RenderRubyText* rt = rubyText();
diff --git a/Source/core/rendering/RenderScrollbarPart.cpp b/Source/core/rendering/RenderScrollbarPart.cpp
index fc56bfc..13a35eb 100644
--- a/Source/core/rendering/RenderScrollbarPart.cpp
+++ b/Source/core/rendering/RenderScrollbarPart.cpp
@@ -26,6 +26,7 @@
 #include "config.h"
 #include "core/rendering/RenderScrollbarPart.h"
 
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderScrollbarTheme.h"
@@ -55,6 +56,7 @@
 
 void RenderScrollbarPart::layout()
 {
+    LayoutRectRecorder recorder(*this);
     setLocation(LayoutPoint()); // We don't worry about positioning ourselves. We're just determining our minimum width/height.
     if (m_scrollbar->orientation() == HorizontalScrollbar)
         layoutHorizontalPart();
diff --git a/Source/core/rendering/RenderSlider.cpp b/Source/core/rendering/RenderSlider.cpp
index 425ec57..73e4d67 100644
--- a/Source/core/rendering/RenderSlider.cpp
+++ b/Source/core/rendering/RenderSlider.cpp
@@ -25,6 +25,7 @@
 #include "core/html/HTMLInputElement.h"
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/SliderThumbElement.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "wtf/MathExtras.h"
 
 using std::min;
@@ -92,6 +93,7 @@
 
 void RenderSlider::layout()
 {
+    LayoutRectRecorder recorder(*this);
     // FIXME: Find a way to cascade appearance.
     // http://webkit.org/b/62535
     RenderBox* thumbBox = sliderThumbElement()->renderBox();
diff --git a/Source/core/rendering/RenderSlider.h b/Source/core/rendering/RenderSlider.h
index cfc5c15..a627e2c 100644
--- a/Source/core/rendering/RenderSlider.h
+++ b/Source/core/rendering/RenderSlider.h
@@ -45,7 +45,6 @@
     virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
     virtual void layout();
 
     SliderThumbElement* sliderThumbElement() const;
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index 707ecda..33e8016 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -35,6 +35,7 @@
 #include "core/rendering/FixedTableLayout.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderTableCaption.h"
@@ -272,7 +273,7 @@
         LayoutUnit availableContentLogicalWidth = max<LayoutUnit>(0, containerWidthInInlineDirection - marginTotal);
         if (shrinkToAvoidFloats() && cb->containsFloats() && !hasPerpendicularContainingBlock) {
             // FIXME: Work with regions someday.
-            availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, 0);
+            availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb), 0);
         }
 
         // Ensure we aren't bigger than our available width.
@@ -409,6 +410,8 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
+
     if (simplifiedLayout())
         return;
 
diff --git a/Source/core/rendering/RenderTableCaption.cpp b/Source/core/rendering/RenderTableCaption.cpp
index e35acc5..af677b7 100644
--- a/Source/core/rendering/RenderTableCaption.cpp
+++ b/Source/core/rendering/RenderTableCaption.cpp
@@ -41,7 +41,7 @@
 
 void RenderTableCaption::insertedIntoTree()
 {
-    RenderBlock::insertedIntoTree();
+    RenderBlockFlow::insertedIntoTree();
 
     table()->addCaption(this);
 }
diff --git a/Source/core/rendering/RenderTableCell.cpp b/Source/core/rendering/RenderTableCell.cpp
index ba41636..9e00d98 100644
--- a/Source/core/rendering/RenderTableCell.cpp
+++ b/Source/core/rendering/RenderTableCell.cpp
@@ -29,6 +29,7 @@
 #include "core/css/StylePropertySet.h"
 #include "core/html/HTMLTableCellElement.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTableCol.h"
 #include "core/rendering/RenderView.h"
@@ -236,6 +237,8 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
+
     updateFirstLetter();
 
     int oldCellBaseline = cellBaselinePosition();
diff --git a/Source/core/rendering/RenderTableRow.cpp b/Source/core/rendering/RenderTableRow.cpp
index b50d880..528ae08 100644
--- a/Source/core/rendering/RenderTableRow.cpp
+++ b/Source/core/rendering/RenderTableRow.cpp
@@ -30,6 +30,7 @@
 #include "core/fetch/ImageResource.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTableCell.h"
 #include "core/rendering/RenderView.h"
@@ -159,6 +160,8 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
+
     // Table rows do not add translation.
     LayoutStateMaintainer statePusher(view(), this, LayoutSize(), style()->isFlippedBlocksWritingMode());
 
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index fda9887..2526e13 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -31,6 +31,7 @@
 #include <limits>
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTableCell.h"
 #include "core/rendering/RenderTableCol.h"
@@ -731,6 +732,8 @@
     ASSERT(!needsCellRecalc());
     ASSERT(!table()->needsSectionRecalc());
 
+    LayoutRectRecorder recorder(*this);
+
     // addChild may over-grow m_grid but we don't want to throw away the memory too early as addChild
     // can be called in a loop (e.g during parsing). Doing it now ensures we have a stable-enough structure.
     m_grid.shrinkToFit();
@@ -1027,7 +1030,7 @@
 void RenderTableSection::computeOverflowFromCells(unsigned totalRows, unsigned nEffCols)
 {
     unsigned totalCellsCount = nEffCols * totalRows;
-    int maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
+    unsigned maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
 
 #ifndef NDEBUG
     bool hasOverflowingCell = false;
@@ -1785,7 +1788,7 @@
 {
     ASSERT(table()->collapseBorders());
     HashMap<pair<const RenderTableCell*, int>, CollapsedBorderValue>::iterator it = m_cellsCollapsedBorders.find(make_pair(cell, side));
-    ASSERT(it != m_cellsCollapsedBorders.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(it != m_cellsCollapsedBorders.end());
     return it->value;
 }
 
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index 9f021e6..8fcee94 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -1653,7 +1653,7 @@
     return result;
 }
 
-#if OS(MACOSX) || OS(POSIX)
+#if OS(POSIX)
 
 #define HANGUL_CHOSEONG_START (0x1100)
 #define HANGUL_CHOSEONG_END (0x115F)
@@ -1695,7 +1695,7 @@
 
 int RenderText::previousOffsetForBackwardDeletion(int current) const
 {
-#if OS(MACOSX) || OS(POSIX)
+#if OS(POSIX)
     ASSERT(m_text);
     StringImpl& text = *m_text.impl();
     UChar32 character;
@@ -1779,7 +1779,7 @@
 
     return current;
 #else
-    // Platforms other than Mac or Unix delete by one code point.
+    // Platforms other than Unix-like delete by one code point.
     if (U16_IS_TRAIL(m_text[--current]))
         --current;
     if (current < 0)
diff --git a/Source/core/rendering/RenderText.h b/Source/core/rendering/RenderText.h
index 089e06f..13af4be 100644
--- a/Source/core/rendering/RenderText.h
+++ b/Source/core/rendering/RenderText.h
@@ -178,7 +178,6 @@
     bool containsOnlyWhitespace(unsigned from, unsigned len) const;
     float widthFromCache(const Font&, int start, int len, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow*) const;
     bool isAllASCII() const { return m_isAllASCII; }
-    void updateNeedsTranscoding();
 
     void secureText(UChar mask);
 
@@ -197,7 +196,6 @@
     bool m_isAllASCII : 1;
     bool m_canUseSimpleFontCodePath : 1;
     mutable bool m_knownToHaveNoOverflowAndNoFallbackFonts : 1;
-    bool m_needsTranscoding : 1;
 
     float m_minWidth;
     float m_maxWidth;
diff --git a/Source/core/rendering/RenderTextControl.cpp b/Source/core/rendering/RenderTextControl.cpp
index a779f3a..3ff52dc 100644
--- a/Source/core/rendering/RenderTextControl.cpp
+++ b/Source/core/rendering/RenderTextControl.cpp
@@ -57,7 +57,7 @@
     // FIXME: This is a terrible hack to get the caret over the placeholder text since it'll
     // make us paint the placeholder first. (See https://trac.webkit.org/changeset/118733)
     Node* node = newChild->node();
-    if (node && node->isElementNode() && toElement(node)->part() == "-webkit-input-placeholder")
+    if (node && node->isElementNode() && toElement(node)->pseudo() == "-webkit-input-placeholder")
         RenderBlock::addChild(newChild, firstChild());
     else
         RenderBlock::addChild(newChild, beforeChild);
diff --git a/Source/core/rendering/RenderTextControl.h b/Source/core/rendering/RenderTextControl.h
index 01e94ca..6269af8 100644
--- a/Source/core/rendering/RenderTextControl.h
+++ b/Source/core/rendering/RenderTextControl.h
@@ -83,8 +83,6 @@
     virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE;
 
     virtual bool canBeProgramaticallyScrolled() const { return true; }
-
-    virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTextControl, isTextControl());
diff --git a/Source/core/rendering/RenderTextControlSingleLine.cpp b/Source/core/rendering/RenderTextControlSingleLine.cpp
index 774be23..ec125b8 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -31,6 +31,7 @@
 #include "core/frame/Frame.h"
 #include "core/platform/graphics/SimpleFontData.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderTheme.h"
 #include "platform/PlatformKeyboardEvent.h"
@@ -94,6 +95,7 @@
 
 void RenderTextControlSingleLine::layout()
 {
+    LayoutRectRecorder recorder(*this);
     SubtreeLayoutScope layoutScope(this);
 
     // FIXME: We should remove the height-related hacks in layout() and
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index 393e34e..3ee3ec8 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -24,6 +24,7 @@
 
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
+#include "InputTypeNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/Document.h"
 #include "core/dom/shadow/ElementShadow.h"
@@ -34,7 +35,6 @@
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLMeterElement.h"
 #include "core/html/HTMLOptionElement.h"
-#include "core/html/forms/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/MediaControlElements.h"
 #include "core/html/shadow/ShadowElementNames.h"
@@ -75,16 +75,16 @@
     return color;
 }
 
-static WebKit::WebFallbackThemeEngine::State getWebFallbackThemeState(const RenderTheme* theme, const RenderObject* o)
+static blink::WebFallbackThemeEngine::State getWebFallbackThemeState(const RenderTheme* theme, const RenderObject* o)
 {
     if (!theme->isEnabled(o))
-        return WebKit::WebFallbackThemeEngine::StateDisabled;
+        return blink::WebFallbackThemeEngine::StateDisabled;
     if (theme->isPressed(o))
-        return WebKit::WebFallbackThemeEngine::StatePressed;
+        return blink::WebFallbackThemeEngine::StatePressed;
     if (theme->isHovered(o))
-        return WebKit::WebFallbackThemeEngine::StateHover;
+        return blink::WebFallbackThemeEngine::StateHover;
 
-    return WebKit::WebFallbackThemeEngine::StateNormal;
+    return blink::WebFallbackThemeEngine::StateNormal;
 }
 
 RenderTheme::RenderTheme()
@@ -1154,12 +1154,12 @@
 
     String string;
     if (fileList->isEmpty()) {
-        string = locale.queryString(WebKit::WebLocalizedString::FileButtonNoFileSelectedLabel);
+        string = locale.queryString(blink::WebLocalizedString::FileButtonNoFileSelectedLabel);
     } else if (fileList->length() == 1) {
         string = fileList->item(0)->name();
     } else {
         // FIXME: Localization of fileList->length().
-        return StringTruncator::rightTruncate(locale.queryString(WebKit::WebLocalizedString::MultipleFileUploadText, String::number(fileList->length())), width, font, StringTruncator::EnableRoundingHacks);
+        return StringTruncator::rightTruncate(locale.queryString(blink::WebLocalizedString::MultipleFileUploadText, String::number(fileList->length())), width, font, StringTruncator::EnableRoundingHacks);
     }
 
     return StringTruncator::centerTruncate(string, width, font, StringTruncator::EnableRoundingHacks);
@@ -1172,26 +1172,26 @@
 
 bool RenderTheme::supportsDataListUI(const AtomicString& type) const
 {
-    return type == InputTypeNames::text() || type == InputTypeNames::search() || type == InputTypeNames::url()
-        || type == InputTypeNames::telephone() || type == InputTypeNames::email() || type == InputTypeNames::number()
-        || type == InputTypeNames::color()
-        || type == InputTypeNames::date()
-        || type == InputTypeNames::datetime()
-        || type == InputTypeNames::datetimelocal()
-        || type == InputTypeNames::month()
-        || type == InputTypeNames::week()
-        || type == InputTypeNames::time()
-        || type == InputTypeNames::range();
+    return type == InputTypeNames::text || type == InputTypeNames::search || type == InputTypeNames::url
+        || type == InputTypeNames::tel || type == InputTypeNames::email || type == InputTypeNames::number
+        || type == InputTypeNames::color
+        || type == InputTypeNames::date
+        || type == InputTypeNames::datetime
+        || type == InputTypeNames::datetime_local
+        || type == InputTypeNames::month
+        || type == InputTypeNames::week
+        || type == InputTypeNames::time
+        || type == InputTypeNames::range;
 }
 
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
 bool RenderTheme::supportsCalendarPicker(const AtomicString& type) const
 {
-    return type == InputTypeNames::date()
-        || type == InputTypeNames::datetime()
-        || type == InputTypeNames::datetimelocal()
-        || type == InputTypeNames::month()
-        || type == InputTypeNames::week();
+    return type == InputTypeNames::date
+        || type == InputTypeNames::datetime
+        || type == InputTypeNames::datetime_local
+        || type == InputTypeNames::month
+        || type == InputTypeNames::week;
 }
 #endif
 
@@ -1238,8 +1238,8 @@
 
 bool RenderTheme::paintCheckboxUsingFallbackTheme(RenderObject* o, const PaintInfo& i, const IntRect& r)
 {
-    WebKit::WebFallbackThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebFallbackThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.button.checked = isChecked(o);
     extraParams.button.indeterminate = isIndeterminate(o);
 
@@ -1254,7 +1254,7 @@
         i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
     }
 
-    WebKit::Platform::current()->fallbackThemeEngine()->paint(canvas, WebKit::WebFallbackThemeEngine::PartCheckbox, getWebFallbackThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+    blink::Platform::current()->fallbackThemeEngine()->paint(canvas, blink::WebFallbackThemeEngine::PartCheckbox, getWebFallbackThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
     return false;
 }
 
@@ -1264,7 +1264,7 @@
     if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
         return;
 
-    IntSize size = WebKit::Platform::current()->fallbackThemeEngine()->getSize(WebKit::WebFallbackThemeEngine::PartCheckbox);
+    IntSize size = blink::Platform::current()->fallbackThemeEngine()->getSize(blink::WebFallbackThemeEngine::PartCheckbox);
     float zoomLevel = style->effectiveZoom();
     size.setWidth(size.width() * zoomLevel);
     size.setHeight(size.height() * zoomLevel);
@@ -1280,8 +1280,8 @@
 
 bool RenderTheme::paintRadioUsingFallbackTheme(RenderObject* o, const PaintInfo& i, const IntRect& r)
 {
-    WebKit::WebFallbackThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebFallbackThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.button.checked = isChecked(o);
     extraParams.button.indeterminate = isIndeterminate(o);
 
@@ -1296,7 +1296,7 @@
         i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
     }
 
-    WebKit::Platform::current()->fallbackThemeEngine()->paint(canvas, WebKit::WebFallbackThemeEngine::PartRadio, getWebFallbackThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+    blink::Platform::current()->fallbackThemeEngine()->paint(canvas, blink::WebFallbackThemeEngine::PartRadio, getWebFallbackThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
     return false;
 }
 
@@ -1306,7 +1306,7 @@
     if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
         return;
 
-    IntSize size = WebKit::Platform::current()->fallbackThemeEngine()->getSize(WebKit::WebFallbackThemeEngine::PartRadio);
+    IntSize size = blink::Platform::current()->fallbackThemeEngine()->getSize(blink::WebFallbackThemeEngine::PartRadio);
     float zoomLevel = style->effectiveZoom();
     size.setWidth(size.width() * zoomLevel);
     size.setHeight(size.height() * zoomLevel);
diff --git a/Source/core/rendering/RenderTheme.h b/Source/core/rendering/RenderTheme.h
index 7729b0b..ea1be2d 100644
--- a/Source/core/rendering/RenderTheme.h
+++ b/Source/core/rendering/RenderTheme.h
@@ -26,7 +26,7 @@
 #if USE(NEW_THEME)
 #include "core/platform/Theme.h"
 #else
-#include "core/platform/ThemeTypes.h"
+#include "platform/ThemeTypes.h"
 #endif
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/style/CachedUAStyle.h"
diff --git a/Source/core/rendering/RenderThemeChromiumAndroid.cpp b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
index 98f7071..b3393bb 100644
--- a/Source/core/rendering/RenderThemeChromiumAndroid.cpp
+++ b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
@@ -27,6 +27,7 @@
 #include "core/rendering/RenderThemeChromiumAndroid.h"
 
 #include "CSSValueKeywords.h"
+#include "InputTypeNames.h"
 #include "UserAgentStyleSheets.h"
 #include "core/platform/ScrollbarTheme.h"
 #include "core/rendering/PaintInfo.h"
@@ -36,9 +37,9 @@
 #include "core/rendering/RenderSlider.h"
 #include "platform/LayoutTestSupport.h"
 #include "platform/graphics/Color.h"
-
 #include "public/platform/android/WebThemeEngine.h"
 #include "public/platform/Platform.h"
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
@@ -49,7 +50,7 @@
 
 RenderTheme& RenderTheme::theme()
 {
-    static RenderTheme* renderTheme = RenderThemeChromiumAndroid::create().leakRef();
+    DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumAndroid::create()));
     return *renderTheme;
 }
 
@@ -83,7 +84,7 @@
     if (isRunningLayoutTest()) {
         // Match Linux spin button style in layout tests.
         // FIXME: Consider removing the conditional if a future Android theme matches this.
-        IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartInnerSpinButton);
+        IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton);
 
         style->setWidth(Length(size.width(), Fixed));
         style->setMinWidth(Length(size.width(), Fixed));
@@ -99,13 +100,14 @@
 {
     // We cannot use the scrollbar thickness here, as it's width is 0 on Android.
     // Instead, use the width of the scrollbar down arrow.
-    IntSize scrollbarSize = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarDownArrow);
+    IntSize scrollbarSize = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarDownArrow);
     return scrollbarSize.width();
 }
 
 bool RenderThemeChromiumAndroid::supportsDataListUI(const AtomicString& type) const
 {
-    return false;
+    // FIXME: Add other input types.
+    return type == InputTypeNames::color;
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.cpp b/Source/core/rendering/RenderThemeChromiumDefault.cpp
index 0eec664..3a08440 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.cpp
+++ b/Source/core/rendering/RenderThemeChromiumDefault.cpp
@@ -32,13 +32,20 @@
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderProgress.h"
+#include "platform/LayoutTestSupport.h"
 #include "platform/graphics/Color.h"
 #include "public/platform/default/WebThemeEngine.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebRect.h"
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
+static bool useMockTheme()
+{
+    return isRunningLayoutTest();
+}
+
 unsigned RenderThemeChromiumDefault::m_activeSelectionBackgroundColor =
     0xff1e90ff;
 unsigned RenderThemeChromiumDefault::m_activeSelectionForegroundColor =
@@ -52,16 +59,20 @@
 
 static const unsigned defaultButtonBackgroundColor = 0xffdddddd;
 
-static WebKit::WebThemeEngine::State getWebThemeState(const RenderTheme* theme, const RenderObject* o)
+static blink::WebThemeEngine::State getWebThemeState(const RenderTheme* theme, const RenderObject* o)
 {
     if (!theme->isEnabled(o))
-        return WebKit::WebThemeEngine::StateDisabled;
+        return blink::WebThemeEngine::StateDisabled;
+    if (useMockTheme() && theme->isReadOnlyControl(o))
+        return blink::WebThemeEngine::StateReadonly;
     if (theme->isPressed(o))
-        return WebKit::WebThemeEngine::StatePressed;
+        return blink::WebThemeEngine::StatePressed;
+    if (useMockTheme() && theme->isFocused(o))
+        return blink::WebThemeEngine::StateFocused;
     if (theme->isHovered(o))
-        return WebKit::WebThemeEngine::StateHover;
+        return blink::WebThemeEngine::StateHover;
 
-    return WebKit::WebThemeEngine::StateNormal;
+    return blink::WebThemeEngine::StateNormal;
 }
 
 PassRefPtr<RenderTheme> RenderThemeChromiumDefault::create()
@@ -73,7 +84,7 @@
 #if !OS(ANDROID)
 RenderTheme& RenderTheme::theme()
 {
-    static RenderTheme* renderTheme = RenderThemeChromiumDefault::create().leakRef();
+    DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumDefault::create()));
     return *renderTheme;
 }
 #endif
@@ -87,13 +98,28 @@
 {
 }
 
+bool RenderThemeChromiumDefault::supportsFocusRing(const RenderStyle* style) const
+{
+    if (useMockTheme()) {
+        // Don't use focus rings for buttons when mocking controls.
+        return style->appearance() == ButtonPart
+            || style->appearance() == PushButtonPart
+            || style->appearance() == SquareButtonPart;
+    }
+
+    return RenderThemeChromiumSkia::supportsFocusRing(style);
+}
+
 Color RenderThemeChromiumDefault::systemColor(CSSValueID cssValueId) const
 {
     static const Color defaultButtonGrayColor(0xffdddddd);
     static const Color defaultMenuColor(0xfff7f7f7);
 
-    if (cssValueId == CSSValueButtonface)
+    if (cssValueId == CSSValueButtonface) {
+        if (useMockTheme())
+            return Color(0xc0, 0xc0, 0xc0);
         return defaultButtonGrayColor;
+    }
     if (cssValueId == CSSValueMenu)
         return defaultMenuColor;
     return RenderTheme::systemColor(cssValueId);
@@ -138,38 +164,52 @@
 
 Color RenderThemeChromiumDefault::platformActiveSelectionBackgroundColor() const
 {
+    if (useMockTheme())
+        return Color(0x00, 0x00, 0xff); // Royal blue.
     return m_activeSelectionBackgroundColor;
 }
 
 Color RenderThemeChromiumDefault::platformInactiveSelectionBackgroundColor() const
 {
+    if (useMockTheme())
+        return Color(0x99, 0x99, 0x99); // Medium gray.
     return m_inactiveSelectionBackgroundColor;
 }
 
 Color RenderThemeChromiumDefault::platformActiveSelectionForegroundColor() const
 {
+    if (useMockTheme())
+        return Color(0xff, 0xff, 0xcc); // Pale yellow.
     return m_activeSelectionForegroundColor;
 }
 
 Color RenderThemeChromiumDefault::platformInactiveSelectionForegroundColor() const
 {
+    if (useMockTheme())
+        return Color::white;
     return m_inactiveSelectionForegroundColor;
 }
 
 IntSize RenderThemeChromiumDefault::sliderTickSize() const
 {
+    if (useMockTheme())
+        return IntSize(1, 3);
     return IntSize(1, 6);
 }
 
 int RenderThemeChromiumDefault::sliderTickOffsetFromTrackCenter() const
 {
+    if (useMockTheme())
+        return 11;
     return -16;
 }
 
 void RenderThemeChromiumDefault::adjustSliderThumbSize(RenderStyle* style, Element* element) const
 {
-    IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartSliderThumb);
-    float zoomLevel = style->effectiveZoom();
+    IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartSliderThumb);
+
+    // FIXME: Mock theme doesn't handle zoomed sliders.
+    float zoomLevel = useMockTheme() ? 1 : style->effectiveZoom();
     if (style->appearance() == SliderThumbHorizontalPart) {
         style->setWidth(Length(size.width() * zoomLevel, Fixed));
         style->setHeight(Length(size.height() * zoomLevel, Fixed));
@@ -209,8 +249,8 @@
 
 bool RenderThemeChromiumDefault::paintCheckbox(RenderObject* o, const PaintInfo& i, const IntRect& rect)
 {
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.button.checked = isChecked(o);
     extraParams.button.indeterminate = isIndeterminate(o);
 
@@ -225,7 +265,7 @@
         i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
     }
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartCheckbox, getWebThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartCheckbox, getWebThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
     return false;
 }
 
@@ -235,7 +275,7 @@
     if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
         return;
 
-    IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartCheckbox);
+    IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartCheckbox);
     float zoomLevel = style->effectiveZoom();
     size.setWidth(size.width() * zoomLevel);
     size.setHeight(size.height() * zoomLevel);
@@ -244,11 +284,11 @@
 
 bool RenderThemeChromiumDefault::paintRadio(RenderObject* o, const PaintInfo& i, const IntRect& rect)
 {
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.button.checked = isChecked(o);
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartRadio, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartRadio, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
     return false;
 }
 
@@ -258,7 +298,7 @@
     if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
         return;
 
-    IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartRadio);
+    IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartRadio);
     float zoomLevel = style->effectiveZoom();
     size.setWidth(size.width() * zoomLevel);
     size.setHeight(size.height() * zoomLevel);
@@ -267,14 +307,14 @@
 
 bool RenderThemeChromiumDefault::paintButton(RenderObject* o, const PaintInfo& i, const IntRect& rect)
 {
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.button.hasBorder = true;
-    extraParams.button.backgroundColor = defaultButtonBackgroundColor;
+    extraParams.button.backgroundColor = useMockTheme() ? 0xffc0c0c0 : defaultButtonBackgroundColor;
     if (o->hasBackground())
         extraParams.button.backgroundColor = o->resolveColor(CSSPropertyBackgroundColor).rgb();
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartButton, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartButton, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
     return false;
 }
 
@@ -287,17 +327,17 @@
 
     ControlPart part = o->style()->appearance();
 
-    WebKit::WebThemeEngine::ExtraParams extraParams;
+    blink::WebThemeEngine::ExtraParams extraParams;
     extraParams.textField.isTextArea = part == TextAreaPart;
     extraParams.textField.isListbox = part == ListboxPart;
 
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebCanvas* canvas = i.context->canvas();
 
     // Fallback to white if the specified color object is invalid.
     Color backgroundColor = o->resolveColor(CSSPropertyBackgroundColor, Color::white);
     extraParams.textField.backgroundColor = backgroundColor.rgb();
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartTextField, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartTextField, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
     return false;
 }
 
@@ -309,33 +349,53 @@
     const int right = rect.x() + rect.width();
     const int middle = rect.y() + rect.height() / 2;
 
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 7 : right - 13;
+    blink::WebThemeEngine::ExtraParams extraParams;
     extraParams.menuList.arrowY = middle;
     const RenderBox* box = toRenderBox(o);
     // Match Chromium Win behaviour of showing all borders if any are shown.
     extraParams.menuList.hasBorder = box->borderRight() || box->borderLeft() || box->borderTop() || box->borderBottom();
     extraParams.menuList.hasBorderRadius = o->style()->hasBorderRadius();
     // Fallback to transparent if the specified color object is invalid.
-    extraParams.menuList.backgroundColor = Color::transparent;
+    Color backgroundColor(Color::transparent);
     if (o->hasBackground())
-        extraParams.menuList.backgroundColor = o->resolveColor(CSSPropertyBackgroundColor).rgb();
+        backgroundColor = o->resolveColor(CSSPropertyBackgroundColor);
+    extraParams.menuList.backgroundColor = backgroundColor.rgb();
 
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    // If we have a background image, don't fill the content area to expose the
+    // parent's background. Also, we shouldn't fill the content area if the
+    // alpha of the color is 0. The API of Windows GDI ignores the alpha.
+    // FIXME: the normal Aura theme doesn't care about this, so we should
+    // investigate if we really need fillContentArea.
+    extraParams.menuList.fillContentArea = !o->style()->hasBackgroundImage() && backgroundColor.alpha();
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartMenuList, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+    if (useMockTheme()) {
+        // The size and position of the drop-down button is different between
+        // the mock theme and the regular aura theme.
+        int spacingTop = box->borderTop() + box->paddingTop();
+        int spacingBottom = box->borderBottom() + box->paddingBottom();
+        int spacingRight = box->borderRight() + box->paddingRight();
+        extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 4 + spacingRight: right - 13 - spacingRight;
+        extraParams.menuList.arrowHeight = rect.height() - spacingBottom - spacingTop;
+    } else {
+        extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 7 : right - 13;
+    }
+
+    blink::WebCanvas* canvas = i.context->canvas();
+
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartMenuList, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
     return false;
 }
 
 bool RenderThemeChromiumDefault::paintSliderTrack(RenderObject* o, const PaintInfo& i, const IntRect& rect)
 {
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.slider.vertical = o->style()->appearance() == SliderVerticalPart;
 
     paintSliderTicks(o, i, rect);
 
-    float zoomLevel = o->style()->effectiveZoom();
+    // FIXME: Mock theme doesn't handle zoomed sliders.
+    float zoomLevel = useMockTheme() ? 1 : o->style()->effectiveZoom();
     GraphicsContextStateSaver stateSaver(*i.context);
     IntRect unzoomedRect = rect;
     if (zoomLevel != 1) {
@@ -346,19 +406,20 @@
         i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
     }
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartSliderTrack, getWebThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartSliderTrack, getWebThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
 
     return false;
 }
 
 bool RenderThemeChromiumDefault::paintSliderThumb(RenderObject* o, const PaintInfo& i, const IntRect& rect)
 {
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.slider.vertical = o->style()->appearance() == SliderThumbVerticalPart;
     extraParams.slider.inDrag = isPressed(o);
 
-    float zoomLevel = o->style()->effectiveZoom();
+    // FIXME: Mock theme doesn't handle zoomed sliders.
+    float zoomLevel = useMockTheme() ? 1 : o->style()->effectiveZoom();
     GraphicsContextStateSaver stateSaver(*i.context);
     IntRect unzoomedRect = rect;
     if (zoomLevel != 1) {
@@ -369,13 +430,13 @@
         i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
     }
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartSliderThumb, getWebThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartSliderThumb, getWebThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
     return false;
 }
 
 void RenderThemeChromiumDefault::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
 {
-    IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartInnerSpinButton);
+    IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton);
 
     style->setWidth(Length(size.width(), Fixed));
     style->setMinWidth(Length(size.width(), Fixed));
@@ -383,12 +444,12 @@
 
 bool RenderThemeChromiumDefault::paintInnerSpinButton(RenderObject* o, const PaintInfo& i, const IntRect& rect)
 {
-    WebKit::WebThemeEngine::ExtraParams extraParams;
-    WebKit::WebCanvas* canvas = i.context->canvas();
+    blink::WebThemeEngine::ExtraParams extraParams;
+    blink::WebCanvas* canvas = i.context->canvas();
     extraParams.innerSpin.spinUp = (controlStatesForRenderer(o) & SpinUpState);
     extraParams.innerSpin.readOnly = isReadOnlyControl(o);
 
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartInnerSpinButton, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartInnerSpinButton, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
     return false;
 }
 
@@ -400,7 +461,7 @@
     RenderProgress* renderProgress = toRenderProgress(o);
     IntRect valueRect = progressValueRectFor(renderProgress, rect);
 
-    WebKit::WebThemeEngine::ExtraParams extraParams;
+    blink::WebThemeEngine::ExtraParams extraParams;
     extraParams.progressBar.determinate = renderProgress->isDeterminate();
     extraParams.progressBar.valueRectX = valueRect.x();
     extraParams.progressBar.valueRectY = valueRect.y();
@@ -408,8 +469,8 @@
     extraParams.progressBar.valueRectHeight = valueRect.height();
 
     DirectionFlippingScope scope(o, i, rect);
-    WebKit::WebCanvas* canvas = i.context->canvas();
-    WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartProgressBar, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+    blink::WebCanvas* canvas = i.context->canvas();
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartProgressBar, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
     return false;
 }
 
@@ -418,4 +479,15 @@
     return true;
 }
 
+bool RenderThemeChromiumDefault::shouldUseFallbackTheme(RenderStyle* style) const
+{
+    if (useMockTheme()) {
+        // The mock theme can't handle zoomed controls, so we fall back to the "fallback" theme.
+        ControlPart part = style->appearance();
+        if (part == CheckboxPart || part == RadioPart)
+            return style->effectiveZoom() != 1;
+    }
+    return RenderTheme::shouldUseFallbackTheme(style);
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.h b/Source/core/rendering/RenderThemeChromiumDefault.h
index 25423ed..bba1aa5 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.h
+++ b/Source/core/rendering/RenderThemeChromiumDefault.h
@@ -43,6 +43,8 @@
     // A method asking if the control changes its tint when the window has focus or not.
     virtual bool controlSupportsTints(const RenderObject*) const;
 
+    virtual bool supportsFocusRing(const RenderStyle*) const OVERRIDE;
+
     // List Box selection color
     virtual Color activeListBoxSelectionBackgroundColor() const;
     virtual Color activeListBoxSelectionForegroundColor() const;
@@ -87,6 +89,7 @@
 protected:
     RenderThemeChromiumDefault();
     virtual ~RenderThemeChromiumDefault();
+    virtual bool shouldUseFallbackTheme(RenderStyle*) const OVERRIDE;
 
 private:
     // A general method asking if any control tinting is supported at all.
diff --git a/Source/core/rendering/RenderThemeChromiumMac.mm b/Source/core/rendering/RenderThemeChromiumMac.mm
index d66988c..04a01fc 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.mm
+++ b/Source/core/rendering/RenderThemeChromiumMac.mm
@@ -1868,12 +1868,12 @@
 
     String strToTruncate;
     if (fileList->isEmpty()) {
-        strToTruncate = locale.queryString(WebKit::WebLocalizedString::FileButtonNoFileSelectedLabel);
+        strToTruncate = locale.queryString(blink::WebLocalizedString::FileButtonNoFileSelectedLabel);
     } else if (fileList->length() == 1) {
         strToTruncate = [[NSFileManager defaultManager] displayNameAtPath:(fileList->item(0)->path())];
     } else {
         // FIXME: Localization of fileList->length().
-        return StringTruncator::rightTruncate(locale.queryString(WebKit::WebLocalizedString::MultipleFileUploadText, String::number(fileList->length())), width, font, StringTruncator::EnableRoundingHacks);
+        return StringTruncator::rightTruncate(locale.queryString(blink::WebLocalizedString::MultipleFileUploadText, String::number(fileList->length())), width, font, StringTruncator::EnableRoundingHacks);
     }
 
     return StringTruncator::centerTruncate(strToTruncate, width, font, StringTruncator::EnableRoundingHacks);
@@ -1887,7 +1887,7 @@
 
 RenderTheme& RenderTheme::theme()
 {
-    static RenderTheme* renderTheme = RenderThemeChromiumMac::create().leakRef();
+    DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumMac::create()));
     return *renderTheme;
 }
 
diff --git a/Source/core/rendering/RenderThemeChromiumSkia.cpp b/Source/core/rendering/RenderThemeChromiumSkia.cpp
index 159785a..915c908 100644
--- a/Source/core/rendering/RenderThemeChromiumSkia.cpp
+++ b/Source/core/rendering/RenderThemeChromiumSkia.cpp
@@ -36,6 +36,7 @@
 #include "core/rendering/RenderThemeChromiumFontProvider.h"
 #include "platform/LayoutTestSupport.h"
 #include "wtf/CurrentTime.h"
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
@@ -243,8 +244,8 @@
                                 cancelButtonSize, cancelButtonSize);
     IntRect paintingRect = convertToPaintingRect(inputRenderBox, cancelButtonObject, cancelButtonRect, r);
 
-    static Image* cancelImage = Image::loadPlatformResource("searchCancel").leakRef();
-    static Image* cancelPressedImage = Image::loadPlatformResource("searchCancelPressed").leakRef();
+    DEFINE_STATIC_REF(Image, cancelImage, (Image::loadPlatformResource("searchCancel")));
+    DEFINE_STATIC_REF(Image, cancelPressedImage, (Image::loadPlatformResource("searchCancelPressed")));
     paintInfo.context->drawImage(isPressed(cancelButtonObject) ? cancelPressedImage : cancelImage, paintingRect);
     return false;
 }
@@ -286,7 +287,7 @@
                              magnifierSize, magnifierSize);
     IntRect paintingRect = convertToPaintingRect(inputRenderBox, magnifierObject, magnifierRect, r);
 
-    static Image* magnifierImage = Image::loadPlatformResource("searchMagnifier").leakRef();
+    DEFINE_STATIC_REF(Image, magnifierImage, (Image::loadPlatformResource("searchMagnifier")));
     paintInfo.context->drawImage(magnifierImage, paintingRect);
     return false;
 }
diff --git a/Source/core/rendering/RenderThemeChromiumWin.cpp b/Source/core/rendering/RenderThemeChromiumWin.cpp
index 8324b05..bd11906 100644
--- a/Source/core/rendering/RenderThemeChromiumWin.cpp
+++ b/Source/core/rendering/RenderThemeChromiumWin.cpp
@@ -35,7 +35,7 @@
 #include "core/html/shadow/MediaControlElements.h"
 #include "core/platform/ScrollbarTheme.h"
 #include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/chromium/TransparencyWin.h"
+#include "core/platform/graphics/win/TransparencyWin.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderProgress.h"
@@ -48,6 +48,7 @@
 #include "public/platform/WebRect.h"
 #include "public/platform/win/WebThemeEngine.h"
 #include "wtf/CurrentTime.h"
+#include "wtf/StdLibExtras.h"
 
 // FIXME: This dependency should eventually be removed.
 #include <skia/ext/skia_utils_win.h>
@@ -163,7 +164,7 @@
 
 RenderTheme& RenderTheme::theme()
 {
-    static RenderTheme* renderTheme = RenderThemeChromiumWin::create().leakRef();
+    DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumWin::create()));
     return *renderTheme;
 }
 
@@ -301,8 +302,8 @@
     const ThemeData& themeData = getThemeData(o);
 
     ThemePainter painter(i.context, r);
-    WebKit::WebCanvas* canvas = painter.context()->canvas();
-    WebKit::Platform::current()->themeEngine()->paintButton(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()));
+    blink::WebCanvas* canvas = painter.context()->canvas();
+    blink::Platform::current()->themeEngine()->paintButton(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
     return false;
 }
 
@@ -316,8 +317,8 @@
     const ThemeData& themeData = getThemeData(o);
 
     ThemePainter painter(i.context, r);
-    WebKit::WebCanvas* canvas = painter.context()->canvas();
-    WebKit::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()));
+    blink::WebCanvas* canvas = painter.context()->canvas();
+    blink::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
 
     paintSliderTicks(o, i, r);
 
@@ -329,8 +330,8 @@
     const ThemeData& themeData = getThemeData(o);
 
     ThemePainter painter(i.context, r);
-    WebKit::WebCanvas* canvas = painter.context()->canvas();
-    WebKit::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()));
+    blink::WebCanvas* canvas = painter.context()->canvas();
+    blink::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
 
     return false;
 }
@@ -338,7 +339,7 @@
 static int menuListButtonWidth()
 {
     static int width = isRunningLayoutTest() ? kStandardMenuListButtonWidth :
-        IntSize(WebKit::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
+        IntSize(blink::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
     return width;
 }
 
@@ -394,8 +395,8 @@
 
     // Get the correct theme data for a textfield and paint the menu.
     ThemePainter painter(i.context, rect);
-    WebKit::WebCanvas* canvas = painter.context()->canvas();
-    WebKit::Platform::current()->themeEngine()->paintMenuList(canvas, CP_DROPDOWNBUTTON, determineState(o), determineClassicState(o), WebKit::WebRect(painter.drawRect()));
+    blink::WebCanvas* canvas = painter.context()->canvas();
+    blink::Platform::current()->themeEngine()->paintMenuList(canvas, CP_DROPDOWNBUTTON, determineState(o), determineClassicState(o), blink::WebRect(painter.drawRect()));
     return false;
 }
 
@@ -571,8 +572,8 @@
     {
         const ThemeData& themeData = getThemeData(o);
         ThemePainter painter(i.context, r);
-        WebKit::WebCanvas* canvas = painter.context()->canvas();
-        WebKit::Platform::current()->themeEngine()->paintTextField(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()), backgroundColor.rgb(), fillContentArea, drawEdges);
+        blink::WebCanvas* canvas = painter.context()->canvas();
+        blink::Platform::current()->themeEngine()->paintTextField(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()), backgroundColor.rgb(), fillContentArea, drawEdges);
         // End of block commits the painter before restoring context.
     }
     if (o->style()->hasBorderRadius())
@@ -596,16 +597,16 @@
         half.setHeight(rect.height() / 2);
         const ThemeData& upThemeData = getThemeData(object, SpinButtonUp);
         ThemePainter upPainter(info.context, half);
-        WebKit::WebCanvas* canvas = upPainter.context()->canvas();
-        WebKit::Platform::current()->themeEngine()->paintSpinButton(canvas, upThemeData.m_part, upThemeData.m_state, upThemeData.m_classicState, WebKit::WebRect(upPainter.drawRect()));
+        blink::WebCanvas* canvas = upPainter.context()->canvas();
+        blink::Platform::current()->themeEngine()->paintSpinButton(canvas, upThemeData.m_part, upThemeData.m_state, upThemeData.m_classicState, blink::WebRect(upPainter.drawRect()));
     }
 
     {
         half.setY(rect.y() + rect.height() / 2);
         const ThemeData& downThemeData = getThemeData(object, SpinButtonDown);
         ThemePainter downPainter(info.context, half);
-        WebKit::WebCanvas* canvas = downPainter.context()->canvas();
-        WebKit::Platform::current()->themeEngine()->paintSpinButton(canvas, downThemeData.m_part, downThemeData.m_state, downThemeData.m_classicState, WebKit::WebRect(downPainter.drawRect()));
+        blink::WebCanvas* canvas = downPainter.context()->canvas();
+        blink::Platform::current()->themeEngine()->paintSpinButton(canvas, downThemeData.m_part, downThemeData.m_state, downThemeData.m_classicState, blink::WebRect(downPainter.drawRect()));
     }
     return false;
 }
@@ -638,8 +639,8 @@
     double animatedSeconds = renderProgress->animationStartTime() ?  WTF::currentTime() - renderProgress->animationStartTime() : 0;
     ThemePainter painter(i.context, r);
     DirectionFlippingScope scope(o, i, r);
-    WebKit::WebCanvas* canvas = painter.context()->canvas();
-    WebKit::Platform::current()->themeEngine()->paintProgressBar(canvas, WebKit::WebRect(r), WebKit::WebRect(valueRect), renderProgress->isDeterminate(), animatedSeconds);
+    blink::WebCanvas* canvas = painter.context()->canvas();
+    blink::Platform::current()->themeEngine()->paintProgressBar(canvas, blink::WebRect(r), blink::WebRect(valueRect), renderProgress->isDeterminate(), animatedSeconds);
     return false;
 }
 
diff --git a/Source/core/rendering/RenderTreeAsText.cpp b/Source/core/rendering/RenderTreeAsText.cpp
index d055863..4da8fb1 100644
--- a/Source/core/rendering/RenderTreeAsText.cpp
+++ b/Source/core/rendering/RenderTreeAsText.cpp
@@ -67,8 +67,6 @@
 
 using namespace HTMLNames;
 
-static void writeLayers(TextStream&, const RenderLayer* rootLayer, RenderLayer*, const LayoutRect& paintDirtyRect, int indent = 0, RenderAsTextBehavior = RenderAsTextBehaviorNormal);
-
 static void printBorderStyle(TextStream& ts, const EBorderStyle borderStyle)
 {
     switch (borderStyle) {
@@ -493,7 +491,7 @@
                 view->layout();
                 RenderLayer* l = root->layer();
                 if (l)
-                    writeLayers(ts, l, l, l->rect(), indent + 1, behavior);
+                    RenderTreeAsText::writeLayers(ts, l, l, l->rect(), indent + 1, behavior);
             }
         }
     }
@@ -551,7 +549,7 @@
         ts << " layerType: foreground only";
 
     if (behavior & RenderAsTextShowCompositedLayers) {
-        if (l.compositedLayerMapping()) {
+        if (l.hasCompositedLayerMapping()) {
             ts << " (composited, bounds="
                 << l.compositedLayerMapping()->compositedBounds()
                 << ", drawsContent="
@@ -571,24 +569,47 @@
 static void writeRenderRegionList(const RenderRegionList& flowThreadRegionList, TextStream& ts, int indent)
 {
     for (RenderRegionList::const_iterator itRR = flowThreadRegionList.begin(); itRR != flowThreadRegionList.end(); ++itRR) {
-        RenderRegion* renderRegion = *itRR;
-        writeIndent(ts, indent + 2);
-        ts << "RenderRegion";
-        if (renderRegion->generatingNode()) {
-            String tagName = getTagName(renderRegion->generatingNode());
-            if (!tagName.isEmpty())
-                ts << " {" << tagName << "}";
-            if (renderRegion->generatingNode()->isElementNode() && renderRegion->generatingNode()->hasID()) {
-                Element* element = toElement(renderRegion->generatingNode());
-                ts << " #" << element->idForStyleResolution();
-            }
+        const RenderRegion* renderRegion = *itRR;
+
+        writeIndent(ts, indent);
+        ts << renderRegion->renderName();
+
+        Node* generatingNodeForRegion = renderRegion->generatingNodeForRegion();
+        if (generatingNodeForRegion) {
             if (renderRegion->hasCustomRegionStyle())
                 ts << " region style: 1";
             if (renderRegion->hasAutoLogicalHeight())
                 ts << " hasAutoLogicalHeight";
+
+            bool isRenderNamedFlowFragment = renderRegion->isRenderNamedFlowFragment();
+            if (isRenderNamedFlowFragment)
+                ts << " (anonymous child of";
+
+            StringBuilder tagName;
+            tagName.append(generatingNodeForRegion->nodeName());
+
+            Node* nodeForRegion = renderRegion->nodeForRegion();
+            if (nodeForRegion->isPseudoElement()) {
+                if (nodeForRegion->isBeforePseudoElement())
+                    tagName.append("::before");
+                else if (nodeForRegion->isAfterPseudoElement())
+                    tagName.append("::after");
+            }
+
+            ts << " {" << tagName.toString() << "}";
+
+            if (generatingNodeForRegion->isElementNode() && generatingNodeForRegion->hasID()) {
+                Element* element = toElement(generatingNodeForRegion);
+                ts << " #" << element->idForStyleResolution();
+            }
+
+            if (isRenderNamedFlowFragment)
+                ts << ")";
         }
+
         if (!renderRegion->isValid())
             ts << " invalid";
+
         ts << "\n";
     }
 }
@@ -602,54 +623,59 @@
     const RenderNamedFlowThreadList* list = renderView->flowThreadController()->renderNamedFlowThreadList();
 
     writeIndent(ts, indent);
-    ts << "Flow Threads\n";
+    ts << "Named flows\n";
 
     for (RenderNamedFlowThreadList::const_iterator iter = list->begin(); iter != list->end(); ++iter) {
         const RenderNamedFlowThread* renderFlowThread = *iter;
 
         writeIndent(ts, indent + 1);
-        ts << "Thread with flow-name '" << renderFlowThread->flowThreadName() << "'\n";
+        ts << "Named flow '" << renderFlowThread->flowThreadName() << "'\n";
 
         RenderLayer* layer = renderFlowThread->layer();
-        writeLayers(ts, rootLayer, layer, paintRect, indent + 2, behavior);
+        RenderTreeAsText::writeLayers(ts, rootLayer, layer, paintRect, indent + 2, behavior);
 
         // Display the valid and invalid render regions attached to this flow thread.
         const RenderRegionList& validRegionsList = renderFlowThread->renderRegionList();
+        if (!validRegionsList.isEmpty()) {
+            writeIndent(ts, indent + 2);
+            ts << "Regions for named flow '" << renderFlowThread->flowThreadName() << "'\n";
+            writeRenderRegionList(validRegionsList, ts, indent + 3);
+        }
+
         const RenderRegionList& invalidRegionsList = renderFlowThread->invalidRenderRegionList();
-        if (!validRegionsList.isEmpty() || !invalidRegionsList.isEmpty()) {
-            writeIndent(ts, indent + 1);
-            ts << "Regions for flow '"<< renderFlowThread->flowThreadName() << "'\n";
-            writeRenderRegionList(validRegionsList, ts, indent);
-            writeRenderRegionList(invalidRegionsList, ts, indent);
+        if (!invalidRegionsList.isEmpty()) {
+            writeIndent(ts, indent + 2);
+            ts << "Invalid regions for named flow '" << renderFlowThread->flowThreadName() << "'\n";
+            writeRenderRegionList(invalidRegionsList, ts, indent + 3);
         }
     }
 }
 
-static void writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLayer* l,
+void RenderTreeAsText::writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLayer* layer,
                         const LayoutRect& paintRect, int indent, RenderAsTextBehavior behavior)
 {
     // FIXME: Apply overflow to the root layer to not break every test.  Complete hack.  Sigh.
     LayoutRect paintDirtyRect(paintRect);
-    if (rootLayer == l) {
+    if (rootLayer == layer) {
         paintDirtyRect.setWidth(max<LayoutUnit>(paintDirtyRect.width(), rootLayer->renderBox()->layoutOverflowRect().maxX()));
         paintDirtyRect.setHeight(max<LayoutUnit>(paintDirtyRect.height(), rootLayer->renderBox()->layoutOverflowRect().maxY()));
-        l->setSize(l->size().expandedTo(pixelSnappedIntSize(l->renderBox()->maxLayoutOverflow(), LayoutPoint(0, 0))));
+        layer->setSize(layer->size().expandedTo(pixelSnappedIntSize(layer->renderBox()->maxLayoutOverflow(), LayoutPoint(0, 0))));
     }
 
     // Calculate the clip rects we should use.
     LayoutRect layerBounds;
     ClipRect damageRect, clipRectToApply, outlineRect;
-    l->calculateRects(ClipRectsContext(rootLayer, 0, TemporaryClipRects), paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
+    layer->calculateRects(ClipRectsContext(rootLayer, 0, TemporaryClipRects), paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
 
     // Ensure our lists are up-to-date.
-    l->stackingNode()->updateLayerListsIfNeeded();
+    layer->stackingNode()->updateLayerListsIfNeeded();
 
-    bool shouldPaint = (behavior & RenderAsTextShowAllLayers) ? true : l->intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
+    bool shouldPaint = (behavior & RenderAsTextShowAllLayers) ? true : layer->intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
 
-    Vector<RenderLayerStackingNode*>* negList = l->stackingNode()->negZOrderList();
+    Vector<RenderLayerStackingNode*>* negList = layer->stackingNode()->negZOrderList();
     bool paintsBackgroundSeparately = negList && negList->size() > 0;
     if (shouldPaint && paintsBackgroundSeparately)
-        write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), LayerPaintPhaseBackground, indent, behavior);
+        write(ts, *layer, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), LayerPaintPhaseBackground, indent, behavior);
 
     if (negList) {
         int currIndent = indent;
@@ -663,9 +689,9 @@
     }
 
     if (shouldPaint)
-        write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), paintsBackgroundSeparately ? LayerPaintPhaseForeground : LayerPaintPhaseAll, indent, behavior);
+        write(ts, *layer, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), paintsBackgroundSeparately ? LayerPaintPhaseForeground : LayerPaintPhaseAll, indent, behavior);
 
-    if (Vector<RenderLayerStackingNode*>* normalFlowList = l->stackingNode()->normalFlowList()) {
+    if (Vector<RenderLayerStackingNode*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
         int currIndent = indent;
         if (behavior & RenderAsTextShowLayerNesting) {
             writeIndent(ts, indent);
@@ -676,7 +702,7 @@
             writeLayers(ts, rootLayer, normalFlowList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
     }
 
-    if (Vector<RenderLayerStackingNode*>* posList = l->stackingNode()->posZOrderList()) {
+    if (Vector<RenderLayerStackingNode*>* posList = layer->stackingNode()->posZOrderList()) {
         int currIndent = indent;
         if (behavior & RenderAsTextShowLayerNesting) {
             writeIndent(ts, indent);
@@ -689,8 +715,8 @@
 
     // Altough the RenderFlowThread requires a layer, it is not collected by its parent,
     // so we have to treat it as a special case.
-    if (l->renderer()->isRenderView()) {
-        RenderView* renderView = toRenderView(l->renderer());
+    if (layer->renderer()->isRenderView()) {
+        RenderView* renderView = toRenderView(layer->renderer());
         writeRenderNamedFlowThreads(ts, renderView, rootLayer, paintDirtyRect, indent, behavior);
     }
 }
@@ -758,7 +784,7 @@
         return ts.release();
 
     RenderLayer* layer = renderer->layer();
-    writeLayers(ts, layer, layer, layer->rect(), 0, behavior);
+    RenderTreeAsText::writeLayers(ts, layer, layer, layer->rect(), 0, behavior);
     writeSelection(ts, renderer);
     return ts.release();
 }
diff --git a/Source/core/rendering/RenderTreeAsText.h b/Source/core/rendering/RenderTreeAsText.h
index cf8b386..63c900c 100644
--- a/Source/core/rendering/RenderTreeAsText.h
+++ b/Source/core/rendering/RenderTreeAsText.h
@@ -33,6 +33,8 @@
 
 class Element;
 class Frame;
+class LayoutRect;
+class RenderLayer;
 class RenderObject;
 class TextStream;
 
@@ -60,6 +62,7 @@
 // not being done).
 public:
 static void writeRenderObject(TextStream& ts, const RenderObject& o, RenderAsTextBehavior behavior);
+static void writeLayers(TextStream&, const RenderLayer* rootLayer, RenderLayer*, const LayoutRect& paintDirtyRect, int indent = 0, RenderAsTextBehavior = RenderAsTextBehaviorNormal);
 };
 
 // Helper function shared with SVGRenderTreeAsText
diff --git a/Source/core/rendering/RenderTextTrackCue.cpp b/Source/core/rendering/RenderVTTCue.cpp
similarity index 81%
rename from Source/core/rendering/RenderTextTrackCue.cpp
rename to Source/core/rendering/RenderVTTCue.cpp
index a4b6587..4507321 100644
--- a/Source/core/rendering/RenderTextTrackCue.cpp
+++ b/Source/core/rendering/RenderVTTCue.cpp
@@ -24,21 +24,23 @@
  */
 
 #include "config.h"
-#include "core/rendering/RenderTextTrackCue.h"
+#include "core/rendering/RenderVTTCue.h"
 
-#include "core/html/track/TextTrackCue.h"
+#include "core/html/track/vtt/VTTCue.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
-RenderTextTrackCue::RenderTextTrackCue(TextTrackCueBox* element)
+RenderVTTCue::RenderVTTCue(VTTCueBox* element)
     : RenderBlockFlow(element)
     , m_cue(element->getCue())
 {
 }
 
-void RenderTextTrackCue::layout()
+void RenderVTTCue::layout()
 {
+    LayoutRectRecorder recorder(*this);
     RenderBlockFlow::layout();
 
     // If WebVTT Regions are used, the regular WebVTT layout algorithm is no
@@ -58,7 +60,7 @@
     statePusher.pop();
 }
 
-bool RenderTextTrackCue::findFirstLineBox(InlineFlowBox*& firstLineBox)
+bool RenderVTTCue::findFirstLineBox(InlineFlowBox*& firstLineBox)
 {
     if (firstChild()->isRenderInline())
         firstLineBox = toRenderInline(firstChild())->firstLineBox();
@@ -68,7 +70,7 @@
     return true;
 }
 
-bool RenderTextTrackCue::initializeLayoutParameters(InlineFlowBox* firstLineBox, LayoutUnit& step, LayoutUnit& position)
+bool RenderVTTCue::initializeLayoutParameters(InlineFlowBox* firstLineBox, LayoutUnit& step, LayoutUnit& position)
 {
     ASSERT(firstChild());
 
@@ -76,7 +78,7 @@
 
     // 1. Horizontal: Let step be the height of the first line box in boxes.
     //    Vertical: Let step be the width of the first line box in boxes.
-    step = m_cue->getWritingDirection() == TextTrackCue::Horizontal ? firstLineBox->height() : firstLineBox->width();
+    step = m_cue->getWritingDirection() == VTTCue::Horizontal ? firstLineBox->height() : firstLineBox->width();
 
     // 2. If step is zero, then jump to the step labeled done positioning below.
     if (!step)
@@ -86,7 +88,7 @@
     int linePosition = m_cue->calculateComputedLinePosition();
 
     // 4. Vertical Growing Left: Add one to line position then negate it.
-    if (m_cue->getWritingDirection() == TextTrackCue::VerticalGrowingLeft)
+    if (m_cue->getWritingDirection() == VTTCue::VerticalGrowingLeft)
         linePosition = -(linePosition + 1);
 
     // 5. Let position be the result of multiplying step and line position.
@@ -94,7 +96,7 @@
 
     // 6. Vertical Growing Left: Decrease position by the width of the
     // bounding box of the boxes in boxes, then increase position by step.
-    if (m_cue->getWritingDirection() == TextTrackCue::VerticalGrowingLeft) {
+    if (m_cue->getWritingDirection() == VTTCue::VerticalGrowingLeft) {
         position -= width();
         position += step;
     }
@@ -103,7 +105,7 @@
     if (linePosition < 0) {
         // Horizontal / Vertical: ... then increase position by the
         // height / width of the video's rendering area ...
-        position += m_cue->getWritingDirection() == TextTrackCue::Horizontal ? parentBlock->height() : parentBlock->width();
+        position += m_cue->getWritingDirection() == VTTCue::Horizontal ? parentBlock->height() : parentBlock->width();
 
         // ... and negate step.
         step = -step;
@@ -112,15 +114,16 @@
     return true;
 }
 
-void RenderTextTrackCue::placeBoxInDefaultPosition(LayoutUnit position, bool& switched)
+void RenderVTTCue::placeBoxInDefaultPosition(LayoutUnit position, bool& switched)
 {
     // 8. Move all boxes in boxes ...
-    if (m_cue->getWritingDirection() == TextTrackCue::Horizontal)
+    if (m_cue->getWritingDirection() == VTTCue::Horizontal) {
         // Horizontal: ... down by the distance given by position
         setY(y() + position);
-    else
+    } else {
         // Vertical: ... right by the distance given by position
         setX(x() + position);
+    }
 
     // 9. Default: Remember the position of all the boxes in boxes as their
     // default position.
@@ -130,12 +133,12 @@
     switched = false;
 }
 
-bool RenderTextTrackCue::isOutside() const
+bool RenderVTTCue::isOutside() const
 {
     return !containingBlock()->absoluteBoundingBoxRect().contains(absoluteContentBox());
 }
 
-bool RenderTextTrackCue::isOverlapping() const
+bool RenderVTTCue::isOverlapping() const
 {
     for (RenderObject* box = previousSibling(); box; box = box->previousSibling()) {
         IntRect boxRect = box->absoluteBoundingBoxRect();
@@ -147,7 +150,7 @@
     return false;
 }
 
-bool RenderTextTrackCue::shouldSwitchDirection(InlineFlowBox* firstLineBox, LayoutUnit step) const
+bool RenderVTTCue::shouldSwitchDirection(InlineFlowBox* firstLineBox, LayoutUnit step) const
 {
     LayoutUnit top = y();
     LayoutUnit left = x();
@@ -160,7 +163,7 @@
     // boxes is now below the bottom of the video's rendering area, jump
     // to the step labeled switch direction.
     LayoutUnit parentHeight = containingBlock()->height();
-    if (m_cue->getWritingDirection() == TextTrackCue::Horizontal && ((step < 0 && top < 0) || (step > 0 && bottom > parentHeight)))
+    if (m_cue->getWritingDirection() == VTTCue::Horizontal && ((step < 0 && top < 0) || (step > 0 && bottom > parentHeight)))
         return true;
 
     // 12. Vertical: If step is negative and the left edge of the first line
@@ -169,18 +172,18 @@
     // first line box in boxes is now to the right of the right edge of
     // the video's rendering area, jump to the step labeled switch direction.
     LayoutUnit parentWidth = containingBlock()->width();
-    if (m_cue->getWritingDirection() != TextTrackCue::Horizontal && ((step < 0 && left < 0) || (step > 0 && right > parentWidth)))
+    if (m_cue->getWritingDirection() != VTTCue::Horizontal && ((step < 0 && left < 0) || (step > 0 && right > parentWidth)))
         return true;
 
     return false;
 }
 
-void RenderTextTrackCue::moveBoxesByStep(LayoutUnit step)
+void RenderVTTCue::moveBoxesByStep(LayoutUnit step)
 {
     // 13. Horizontal: Move all the boxes in boxes down by the distance
     // given by step. (If step is negative, then this will actually
     // result in an upwards movement of the boxes in absolute terms.)
-    if (m_cue->getWritingDirection() == TextTrackCue::Horizontal)
+    if (m_cue->getWritingDirection() == VTTCue::Horizontal)
         setY(y() + step);
 
     // 13. Vertical: Move all the boxes in boxes right by the distance
@@ -190,7 +193,7 @@
         setX(x() + step);
 }
 
-bool RenderTextTrackCue::switchDirection(bool& switched, LayoutUnit& step)
+bool RenderVTTCue::switchDirection(bool& switched, LayoutUnit& step)
 {
     // 15. Switch direction: Move all the boxes in boxes back to their
     // default position as determined in the step above labeled default.
@@ -210,7 +213,7 @@
     return true;
 }
 
-void RenderTextTrackCue::repositionCueSnapToLinesSet()
+void RenderVTTCue::repositionCueSnapToLinesSet()
 {
     InlineFlowBox* firstLineBox;
     LayoutUnit step;
@@ -229,12 +232,13 @@
     // in output and all the boxes in output are within the video's rendering area
     // then jump to the step labeled done positioning.
     while (isOutside() || isOverlapping()) {
-        if (!shouldSwitchDirection(firstLineBox, step))
+        if (!shouldSwitchDirection(firstLineBox, step)) {
             // 13. Move all the boxes in boxes ...
             // 14. Jump back to the step labeled step loop.
             moveBoxesByStep(step);
-        else if (!switchDirection(switched, step))
+        } else if (!switchDirection(switched, step)) {
             break;
+        }
 
         // 19. Jump back to the step labeled step loop.
     }
@@ -259,7 +263,7 @@
     }
 }
 
-void RenderTextTrackCue::repositionCueSnapToLinesNotSet()
+void RenderVTTCue::repositionCueSnapToLinesNotSet()
 {
     // FIXME: Implement overlapping detection when snap-to-lines is not set. http://wkb.ug/84296
 }
diff --git a/Source/core/rendering/RenderTextTrackCue.h b/Source/core/rendering/RenderVTTCue.h
similarity index 89%
rename from Source/core/rendering/RenderTextTrackCue.h
rename to Source/core/rendering/RenderVTTCue.h
index ee02097..d357b24 100644
--- a/Source/core/rendering/RenderTextTrackCue.h
+++ b/Source/core/rendering/RenderVTTCue.h
@@ -23,8 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderTextTrackCue_h
-#define RenderTextTrackCue_h
+#ifndef RenderVTTCue_h
+#define RenderVTTCue_h
 
 #include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderInline.h"
@@ -32,11 +32,12 @@
 
 namespace WebCore {
 
-class TextTrackCueBox;
+class VTTCue;
+class VTTCueBox;
 
-class RenderTextTrackCue FINAL : public RenderBlockFlow {
+class RenderVTTCue FINAL : public RenderBlockFlow {
 public:
-    explicit RenderTextTrackCue(TextTrackCueBox*);
+    explicit RenderVTTCue(VTTCueBox*);
 
 private:
     virtual void layout() OVERRIDE;
@@ -55,10 +56,10 @@
     void repositionCueSnapToLinesSet();
     void repositionCueSnapToLinesNotSet();
 
-    TextTrackCue* m_cue;
+    VTTCue* m_cue;
     FloatPoint m_fallbackPosition;
 };
 
 } // namespace WebCore
 
-#endif // RenderTextTrackCue_h
+#endif // RenderVTTCue_h
diff --git a/Source/core/rendering/RenderVideo.cpp b/Source/core/rendering/RenderVideo.cpp
index cdda831..e706558 100644
--- a/Source/core/rendering/RenderVideo.cpp
+++ b/Source/core/rendering/RenderVideo.cpp
@@ -33,9 +33,10 @@
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/platform/graphics/MediaPlayer.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderFullScreen.h"
+#include "platform/graphics/media/MediaPlayer.h"
 
 namespace WebCore {
 
@@ -180,6 +181,7 @@
 
 void RenderVideo::layout()
 {
+    LayoutRectRecorder recorder(*this);
     updatePlayer();
     RenderMedia::layout();
 }
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index 365d855..4ef32ee 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -37,6 +37,7 @@
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderLayer.h"
@@ -77,7 +78,6 @@
 
 RenderView::~RenderView()
 {
-    document().clearRenderView();
 }
 
 bool RenderView::hitTest(const HitTestRequest& request, HitTestResult& result)
@@ -168,6 +168,7 @@
     UNUSED_PARAM(state);
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     RenderBlock::layout();
 
     if (RuntimeEnabledFeatures::dialogElementEnabled())
@@ -302,7 +303,7 @@
 
 void RenderView::layout()
 {
-    if (!configuration().paginated())
+    if (!document().paginated())
         setPageLogicalHeight(0);
 
     if (shouldUsePrintingLayout())
@@ -364,7 +365,7 @@
 
 void RenderView::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
 {
-    ASSERT_UNUSED(wasFixed, !wasFixed || *wasFixed == (mode & IsFixed));
+    ASSERT_UNUSED(wasFixed, !wasFixed || *wasFixed == static_cast<bool>(mode & IsFixed));
 
     if (!repaintContainer && mode & UseTransforms && shouldUseTransformFromContainer(0)) {
         TransformationMatrix t;
@@ -768,6 +769,11 @@
 
 void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* end, int endPos, SelectionRepaintMode blockRepaintMode)
 {
+    // This code makes no assumptions as to if the rendering tree is up to date or not
+    // and will not try to update it. Currently clearSelection calls this
+    // (intentionally) without updating the rendering tree as it doesn't care.
+    // Other callers may want to force recalc style before calling this.
+
     // Make sure both our start and end objects are defined.
     // Check www.msnbc.com and try clicking around to find the case where this happened.
     if ((start && !end) || (end && !start))
@@ -939,11 +945,6 @@
     endPos = m_selectionEndPos;
 }
 
-void RenderView::updateConfiguration()
-{
-    m_configuration.update(document());
-}
-
 bool RenderView::shouldUsePrintingLayout() const
 {
     if (!document().printing() || !m_frameView)
@@ -1208,9 +1209,7 @@
 bool RenderView::backgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const
 {
     // FIXME: Remove this main frame check. Same concept applies to subframes too.
-    Page* page = document().page();
-    Frame* mainFrame = page ? page->mainFrame() : 0;
-    if (!m_frameView || &m_frameView->frame() != mainFrame)
+    if (!m_frameView || !m_frameView->isMainFrame())
         return false;
 
     return m_frameView->hasOpaqueBackground();
diff --git a/Source/core/rendering/RenderView.h b/Source/core/rendering/RenderView.h
index 97702b0..5bde8b4 100644
--- a/Source/core/rendering/RenderView.h
+++ b/Source/core/rendering/RenderView.h
@@ -27,7 +27,6 @@
 #include "core/rendering/LayoutIndicator.h"
 #include "core/rendering/LayoutState.h"
 #include "core/rendering/RenderBlockFlow.h"
-#include "core/rendering/RenderingConfiguration.h"
 #include "platform/PODFreeListArena.h"
 #include "wtf/OwnPtr.h"
 
@@ -100,14 +99,6 @@
     void selectionStartEnd(int& startPos, int& endPos) const;
     void repaintSelection() const;
 
-    void updateConfiguration();
-    const RenderingConfiguration& configuration()
-    {
-        // If we're not inLayout(), then the configuration might be out of date.
-        ASSERT(LayoutIndicator::inLayout());
-        return m_configuration;
-    }
-
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const;
     virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
 
@@ -285,9 +276,6 @@
     RenderObject* m_selectionStart;
     RenderObject* m_selectionEnd;
 
-    // Please use the configuration() accessor instead of accessing this member directly.
-    RenderingConfiguration m_configuration;
-
     int m_selectionStartPos;
     int m_selectionEndPos;
 
diff --git a/Source/core/rendering/RenderWidget.cpp b/Source/core/rendering/RenderWidget.cpp
index 7622005..93c4dac 100644
--- a/Source/core/rendering/RenderWidget.cpp
+++ b/Source/core/rendering/RenderWidget.cpp
@@ -30,6 +30,7 @@
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 #include "wtf/HashMap.h"
@@ -211,6 +212,7 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     clearNeedsLayout();
 }
 
diff --git a/Source/core/rendering/RootInlineBox.cpp b/Source/core/rendering/RootInlineBox.cpp
index 9558269..9c6dba8 100644
--- a/Source/core/rendering/RootInlineBox.cpp
+++ b/Source/core/rendering/RootInlineBox.cpp
@@ -25,8 +25,9 @@
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderFlowThread.h"
+#include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/VerticalPositionCache.h"
 #include "platform/text/BidiResolver.h"
@@ -46,7 +47,7 @@
 typedef WTF::HashMap<const RootInlineBox*, EllipsisBox*> EllipsisBoxMap;
 static EllipsisBoxMap* gEllipsisBoxMap = 0;
 
-RootInlineBox::RootInlineBox(RenderBlock* block)
+RootInlineBox::RootInlineBox(RenderBlockFlow* block)
     : InlineFlowBox(block)
     , m_lineBreakPos(0)
     , m_lineBreakObj(0)
@@ -337,7 +338,7 @@
 
     // Get the current line grid and offset.
     LayoutState* layoutState = block()->view()->layoutState();
-    RenderBlock* lineGrid = layoutState->lineGrid();
+    RenderBlockFlow* lineGrid = layoutState->lineGrid();
     LayoutSize lineGridOffset = layoutState->lineGridOffset();
     if (!lineGrid || lineGrid->style()->writingMode() != block()->style()->writingMode())
         return 0;
@@ -595,9 +596,9 @@
     return !block()->style()->isFlippedBlocksWritingMode() ? max(lineTop(), selectionTop()) : min(lineBottom(), selectionBottom());
 }
 
-RenderBlock* RootInlineBox::block() const
+RenderBlockFlow* RootInlineBox::block() const
 {
-    return toRenderBlock(renderer());
+    return toRenderBlockFlow(renderer());
 }
 
 static bool isEditableLeaf(InlineBox* leaf)
@@ -657,6 +658,13 @@
 
 void RootInlineBox::setLineBreakInfo(RenderObject* obj, unsigned breakPos, const BidiStatus& status)
 {
+    // When setting lineBreakObj, the RenderObject must not be a RenderInline
+    // with no line boxes, otherwise all sorts of invariants are broken later.
+    // This has security implications because if the RenderObject does not
+    // point to at least one line box, then that RenderInline can be deleted
+    // later without resetting the lineBreakObj, leading to use-after-free.
+    ASSERT_WITH_SECURITY_IMPLICATION(!obj || obj->isText() || !(obj->isRenderInline() && obj->isBox() && !toRenderBox(obj)->inlineBoxWrapper()));
+
     m_lineBreakObj = obj;
     m_lineBreakPos = breakPos;
     m_lineBreakBidiStatusEor = status.eor;
diff --git a/Source/core/rendering/RootInlineBox.h b/Source/core/rendering/RootInlineBox.h
index 3790532..7dfde5f 100644
--- a/Source/core/rendering/RootInlineBox.h
+++ b/Source/core/rendering/RootInlineBox.h
@@ -28,6 +28,7 @@
 
 class EllipsisBox;
 class HitTestResult;
+class RenderBlockFlow;
 class RenderRegion;
 
 struct BidiStatus;
@@ -35,7 +36,7 @@
 
 class RootInlineBox : public InlineFlowBox {
 public:
-    explicit RootInlineBox(RenderBlock*);
+    explicit RootInlineBox(RenderBlockFlow*);
 
     virtual void destroy() OVERRIDE FINAL;
 
@@ -128,7 +129,7 @@
 
     GapRects lineSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock, LayoutUnit selTop, LayoutUnit selHeight, const PaintInfo*);
 
-    RenderBlock* block() const;
+    RenderBlockFlow* block() const;
 
     InlineBox* closestLeafChildForPoint(const IntPoint&, bool onlyEditableLeaves);
     InlineBox* closestLeafChildForLogicalLeftPosition(int, bool onlyEditableLeaves = false);
diff --git a/Source/core/rendering/TextAutosizer.cpp b/Source/core/rendering/TextAutosizer.cpp
index 044d80e..eaf3d70 100644
--- a/Source/core/rendering/TextAutosizer.cpp
+++ b/Source/core/rendering/TextAutosizer.cpp
@@ -24,9 +24,7 @@
 #include <algorithm>
 
 #include "core/dom/Document.h"
-#include "core/html/HTMLDivElement.h"
 #include "core/html/HTMLElement.h"
-#include "core/html/HTMLMetaElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Settings.h"
 #include "core/rendering/RenderListItem.h"
@@ -83,33 +81,6 @@
     return formInputTags;
 }
 
-static const String& vBulletinForumCommentId()
-{
-    // Websites using vBulletin forum software typically contain <div id="post_message_*"..> blocks.
-    DEFINE_STATIC_LOCAL(const String, vBulletinForumCommentId, ("post_message_"));
-    return vBulletinForumCommentId;
-}
-
-static bool isVBulletinComment(const RenderBlock* block)
-{
-    Node* blockNode = block->node();
-    if (blockNode && blockNode->hasTagName(divTag)) {
-        const HTMLDivElement* element = toHTMLDivElement(blockNode);
-        if (element && element->hasID() && element->idForStyleResolution().startsWith(vBulletinForumCommentId()))
-            return true;
-    }
-    return false;
-}
-
-static bool hasForumCommentAncestor(const RenderBlock* container)
-{
-    for (const RenderBlock* block = container; block; block = block->containingBlock()) {
-        if (isVBulletinComment(block))
-            return true;
-    }
-    return false;
-}
-
 static RenderListItem* getAncestorListItem(const RenderObject* renderer)
 {
     RenderObject* ancestor = renderer->parent();
@@ -133,7 +104,6 @@
 
 TextAutosizer::TextAutosizer(Document* document)
     : m_document(document)
-    , m_contentType(Unknown)
 {
 }
 
@@ -147,17 +117,6 @@
     }
 }
 
-TextAutosizer::ContentType TextAutosizer::detectContentType()
-{
-    RefPtr<NodeList> metaElements = m_document->getElementsByTagNameNS(xhtmlNamespaceURI, metaTag.localName());
-    for (unsigned i = 0; i < metaElements->length(); ++i) {
-        HTMLMetaElement* metaElement = toHTMLMetaElement(metaElements->item(i));
-        if (equalIgnoringCase(metaElement->name(), "generator") && metaElement->content().startsWith("vBulletin", false))
-            return VBulletin;
-    }
-    return Default;
-}
-
 bool TextAutosizer::processSubtree(RenderObject* layoutRoot)
 {
     TRACE_EVENT0("webkit", "TextAutosizer::processSubtree");
@@ -165,10 +124,6 @@
     if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->document().printing() || !m_document->page())
         return false;
 
-    InspectorInstrumentation::willAutosizeText(layoutRoot);
-    if (m_contentType == Unknown && m_document->body())
-        m_contentType = detectContentType();
-
     Frame* mainFrame = m_document->page()->mainFrame();
 
     TextAutosizingWindowInfo windowInfo;
@@ -193,6 +148,13 @@
     while (cluster && (!isAutosizingContainer(cluster) || !isIndependentDescendant(cluster)))
         cluster = cluster->containingBlock();
 
+    // Skip autosizing if it will have no effect.
+    // Note: this might suppress autosizing of an inner cluster with a different writing mode.
+    // It's not clear what the correct behavior is for mixed writing modes anyway.
+    if (clusterMultiplier(cluster->style()->writingMode(), windowInfo,
+        std::numeric_limits<float>::infinity()) == 1.0f)
+        return false;
+
     TextAutosizingClusterInfo clusterInfo(cluster);
     processCluster(clusterInfo, container, layoutRoot, windowInfo);
     InspectorInstrumentation::didAutosizeText(layoutRoot);
@@ -207,7 +169,7 @@
     float logicalClusterWidth = std::min<float>(textWidth, logicalLayoutWidth);
 
     float multiplier = logicalClusterWidth / logicalWindowWidth;
-    multiplier *= m_document->settings()->textAutosizingFontScaleFactor();
+    multiplier *= m_document->settings()->accessibilityFontScaleFactor();
 
     // If the page has a meta viewport or @viewport, don't apply the device scale adjustment.
     const ViewportDescription& viewportDescription = m_document->page()->mainFrame()->document()->viewportDescription();
@@ -300,9 +262,9 @@
 
 void TextAutosizer::setMultiplier(RenderObject* renderer, float multiplier)
 {
-    // FIXME: Investigate if a clone() is needed and whether it does the right thing w.r.t. style sharing.
     RefPtr<RenderStyle> newStyle = RenderStyle::clone(renderer->style());
     newStyle->setTextAutosizingMultiplier(multiplier);
+    newStyle->setUnique();
     renderer->setStyle(newStyle.release());
 }
 
@@ -569,22 +531,15 @@
     // few lines of text you'll only need to pan across once or twice.
     //
     // An exception to the 4 lines of text are the textarea and contenteditable
-    // clusters, which are always autosized by default (i.e. treated as if they
+    // clusters, which are always autosized by default (i.e. threated as if they
     // contain more than 4 lines of text). This is to ensure that the text does
     // not suddenly get autosized when the user enters more than 4 lines of text.
-    // Another exception are the forum comments which are autosized by default
-    // to guarantee consistency.
     float totalTextWidth = 0;
     const float minLinesOfText = 4;
     float minTextWidth = blockWidth * minLinesOfText;
     for (size_t i = 0; i < clusterInfos.size(); ++i) {
         if (clusterInfos[i].root->isTextArea() || (clusterInfos[i].root->style() && clusterInfos[i].root->style()->userModify() != READ_ONLY))
             return true;
-        if (m_contentType == VBulletin) {
-            if (hasForumCommentAncestor(clusterInfos[i].blockContainingAllText)
-                || clusterContainsForumComment(clusterInfos[i].blockContainingAllText, clusterInfos[i]))
-                return true;
-        }
         measureDescendantTextWidth(clusterInfos[i].blockContainingAllText, clusterInfos[i], minTextWidth, totalTextWidth);
         if (totalTextWidth >= minTextWidth)
             return true;
@@ -592,25 +547,6 @@
     return false;
 }
 
-bool TextAutosizer::clusterContainsForumComment(const RenderBlock* container, TextAutosizingClusterInfo& clusterInfo)
-{
-    ASSERT(m_contentType == VBulletin);
-
-    RenderObject* descendant = nextInPreOrderSkippingDescendantsOfContainers(container, container);
-    while (descendant) {
-        if (isAutosizingContainer(descendant)) {
-            RenderBlock* descendantBlock = toRenderBlock(descendant);
-            if (isVBulletinComment(descendantBlock))
-                return true;
-            if (!isAutosizingCluster(descendantBlock, clusterInfo)
-                && clusterContainsForumComment(descendantBlock, clusterInfo))
-                return true;
-        }
-        descendant = nextInPreOrderSkippingDescendantsOfContainers(descendant, container);
-    }
-    return false;
-}
-
 void TextAutosizer::measureDescendantTextWidth(const RenderBlock* container, TextAutosizingClusterInfo& clusterInfo, float minTextWidth, float& textWidth)
 {
     bool skipLocalText = !containerShouldBeAutosized(container);
diff --git a/Source/core/rendering/TextAutosizer.h b/Source/core/rendering/TextAutosizer.h
index 7236009..3da3841 100644
--- a/Source/core/rendering/TextAutosizer.h
+++ b/Source/core/rendering/TextAutosizer.h
@@ -57,12 +57,6 @@
         LastToFirst
     };
 
-    enum ContentType {
-        Unknown,
-        Default,
-        VBulletin
-    };
-
     explicit TextAutosizer(Document*);
 
     float clusterMultiplier(WritingMode, const TextAutosizingWindowInfo&, float textWidth) const;
@@ -72,15 +66,9 @@
     void processCompositeCluster(Vector<TextAutosizingClusterInfo>&, const TextAutosizingWindowInfo&);
     void processContainer(float multiplier, RenderBlock* container, TextAutosizingClusterInfo&, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&);
 
-    bool clusterShouldBeAutosized(TextAutosizingClusterInfo&, float blockWidth);
-    bool compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>&, float blockWidth);
-    bool clusterContainsForumComment(const RenderBlock* container, TextAutosizingClusterInfo&);
-
     void setMultiplier(RenderObject*, float);
     void setMultiplierForList(RenderObject* renderer, float multiplier);
 
-    ContentType detectContentType();
-
     static bool isAutosizingContainer(const RenderObject*);
     static bool isNarrowDescendant(const RenderBlock*, TextAutosizingClusterInfo& parentClusterInfo);
     static bool isWiderDescendant(const RenderBlock*, const TextAutosizingClusterInfo& parentClusterInfo);
@@ -91,6 +79,8 @@
     static bool containerContainsOneOfTags(const RenderBlock* cluster, const Vector<QualifiedName>& tags);
     static bool containerIsRowOfLinks(const RenderObject* container);
     static bool contentHeightIsConstrained(const RenderBlock* container);
+    static bool clusterShouldBeAutosized(TextAutosizingClusterInfo&, float blockWidth);
+    static bool compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>&, float blockWidth);
     static void measureDescendantTextWidth(const RenderBlock* container, TextAutosizingClusterInfo&, float minTextWidth, float& textWidth);
 
     // Use to traverse the tree of descendants, excluding descendants of containers (but returning the containers themselves).
@@ -108,7 +98,6 @@
     static void getNarrowDescendantsGroupedByWidth(const TextAutosizingClusterInfo& parentClusterInfo, Vector<Vector<TextAutosizingClusterInfo> >&);
 
     Document* m_document;
-    ContentType m_contentType;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/TrailingFloatsRootInlineBox.h b/Source/core/rendering/TrailingFloatsRootInlineBox.h
index 9bd0530..8036f5a 100644
--- a/Source/core/rendering/TrailingFloatsRootInlineBox.h
+++ b/Source/core/rendering/TrailingFloatsRootInlineBox.h
@@ -32,7 +32,7 @@
 
 class TrailingFloatsRootInlineBox FINAL : public RootInlineBox {
 public:
-    TrailingFloatsRootInlineBox(RenderBlock* block)
+    TrailingFloatsRootInlineBox(RenderBlockFlow* block)
         : RootInlineBox(block)
     {
         setHasVirtualLogicalHeight();
diff --git a/Source/core/rendering/animation/WebAnimationProvider.cpp b/Source/core/rendering/animation/WebAnimationProvider.cpp
index 5532f77..473e3ff 100644
--- a/Source/core/rendering/animation/WebAnimationProvider.cpp
+++ b/Source/core/rendering/animation/WebAnimationProvider.cpp
@@ -34,7 +34,7 @@
 #include "public/platform/WebAnimation.h"
 #include "wtf/text/StringBuilder.h"
 
-using WebKit::WebAnimation;
+using blink::WebAnimation;
 
 namespace WebCore {
 
@@ -139,7 +139,7 @@
             continue;
 
         // Get timing function.
-        RefPtr<TimingFunction> tf = KeyframeValue::timingFunction(keyframeStyle, keyframes.animationName());
+        RefPtr<TimingFunction> tf = KeyframeValue::timingFunction(*keyframeStyle);
 
         bool isFirstOrLastKeyframe = !key || key == 1;
         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
diff --git a/Source/core/rendering/animation/WebAnimationProvider.h b/Source/core/rendering/animation/WebAnimationProvider.h
index c13f38a..724de2e 100644
--- a/Source/core/rendering/animation/WebAnimationProvider.h
+++ b/Source/core/rendering/animation/WebAnimationProvider.h
@@ -33,7 +33,7 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/WTFString.h"
 
-namespace WebKit {
+namespace blink {
 class WebAnimation;
 }
 
@@ -48,9 +48,9 @@
     ~WebAnimations();
     WebAnimations(const WebAnimations&);
     bool isEmpty() const;
-    OwnPtr<WebKit::WebAnimation> m_transformAnimation;
-    OwnPtr<WebKit::WebAnimation> m_opacityAnimation;
-    OwnPtr<WebKit::WebAnimation> m_filterAnimation;
+    OwnPtr<blink::WebAnimation> m_transformAnimation;
+    OwnPtr<blink::WebAnimation> m_opacityAnimation;
+    OwnPtr<blink::WebAnimation> m_filterAnimation;
 };
 
 class WebAnimationProvider {
@@ -65,7 +65,7 @@
     WebAnimations startTransition(double timeOffset, CSSPropertyID, const RenderStyle* fromStyle, const RenderStyle* toStyle, bool hasTransform, bool hasFilter, const IntSize& boxSize, float fromOpacity, float toOpacity);
 
 private:
-    PassOwnPtr<WebKit::WebAnimation> createWebAnimationAndStoreId(const KeyframeValueList&, const IntSize& boxSize, const CSSAnimationData*, const String& animationName, double timeOffset);
+    PassOwnPtr<blink::WebAnimation> createWebAnimationAndStoreId(const KeyframeValueList&, const IntSize& boxSize, const CSSAnimationData*, const String& animationName, double timeOffset);
 
     typedef HashMap<String, int> AnimationIdMap;
     AnimationIdMap m_animationIdMap;
diff --git a/Source/core/rendering/line/BreakingContextInlineHeaders.h b/Source/core/rendering/line/BreakingContextInlineHeaders.h
new file mode 100644
index 0000000..0486240
--- /dev/null
+++ b/Source/core/rendering/line/BreakingContextInlineHeaders.h
@@ -0,0 +1,1141 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Adobe Systems Incorporated.
+ *
+ * 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.
+ *
+ */
+
+#ifndef BreakingContextInlineHeaders_h
+#define BreakingContextInlineHeaders_h
+
+#include "core/rendering/InlineIterator.h"
+#include "core/rendering/InlineTextBox.h"
+#include "core/rendering/LineWidth.h"
+#include "core/rendering/RenderCombineText.h"
+#include "core/rendering/RenderInline.h"
+#include "core/rendering/break_lines.h"
+#include "core/rendering/line/LineInfo.h"
+#include "core/rendering/shapes/ShapeInsideInfo.h"
+#include "core/rendering/svg/RenderSVGInlineText.h"
+
+namespace WebCore {
+
+using namespace std;
+using namespace WTF;
+using namespace Unicode;
+
+// We don't let our line box tree for a single line get any deeper than this.
+const unsigned cMaxLineDepth = 200;
+
+struct RenderTextInfo {
+    // Destruction of m_layout requires TextLayout to be a complete type, so the constructor and destructor are made non-inline to avoid compilation errors.
+    RenderTextInfo();
+    ~RenderTextInfo();
+
+    RenderText* m_text;
+    OwnPtr<TextLayout> m_layout;
+    LazyLineBreakIterator m_lineBreakIterator;
+    const Font* m_font;
+
+    void createLayout(RenderText* renderText, float xPos, bool collapseWhiteSpace)
+    {
+#if OS(MACOSX)
+        m_layout = m_font->createLayoutForMacComplexText(RenderBlockFlow::constructTextRun(renderText, *m_font, renderText, renderText->style()), renderText->textLength(), xPos, collapseWhiteSpace);
+#else
+        m_layout = nullptr;
+#endif
+    }
+};
+
+class WordMeasurement {
+public:
+    WordMeasurement()
+        : renderer(0)
+        , width(0)
+        , startOffset(0)
+        , endOffset(0)
+    {
+    }
+
+    RenderText* renderer;
+    float width;
+    int startOffset;
+    int endOffset;
+    HashSet<const SimpleFontData*> fallbackFonts;
+};
+
+// Don't call this directly. Use one of the descriptive helper functions below.
+inline void deprecatedAddMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
+{
+    if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
+        lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
+
+    InlineIterator* midpoints = lineMidpointState.midpoints.data();
+    midpoints[lineMidpointState.numMidpoints++] = midpoint;
+}
+
+inline void startIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
+{
+    ASSERT(!(lineMidpointState.numMidpoints % 2));
+    deprecatedAddMidpoint(lineMidpointState, midpoint);
+}
+
+inline void stopIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
+{
+    ASSERT(lineMidpointState.numMidpoints % 2);
+    deprecatedAddMidpoint(lineMidpointState, midpoint);
+}
+
+// When ignoring spaces, this needs to be called for objects that need line boxes such as RenderInlines or
+// hard line breaks to ensure that they're not ignored.
+inline void ensureLineBoxInsideIgnoredSpaces(LineMidpointState& lineMidpointState, RenderObject* renderer)
+{
+    InlineIterator midpoint(0, renderer, 0);
+    stopIgnoringSpaces(lineMidpointState, midpoint);
+    startIgnoringSpaces(lineMidpointState, midpoint);
+}
+
+// Adding a pair of midpoints before a character will split it out into a new line box.
+inline void ensureCharacterGetsLineBox(LineMidpointState& lineMidpointState, InlineIterator& textParagraphSeparator)
+{
+    InlineIterator midpoint(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos);
+    startIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos - 1));
+    stopIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos));
+}
+
+class TrailingObjects {
+public:
+    TrailingObjects();
+    void setTrailingWhitespace(RenderText*);
+    void clear();
+    void appendBoxIfNeeded(RenderBox*);
+
+    enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
+
+    void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
+
+private:
+    RenderText* m_whitespace;
+    Vector<RenderBox*, 4> m_boxes;
+};
+
+TrailingObjects::TrailingObjects()
+    : m_whitespace(0)
+{
+}
+
+inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
+{
+    ASSERT(whitespace);
+    m_whitespace = whitespace;
+}
+
+inline void TrailingObjects::clear()
+{
+    m_whitespace = 0;
+    // Using resize(0) rather than clear() here saves 2% on
+    // PerformanceTests/Layout/line-layout.html because we avoid freeing and
+    // re-allocating the underlying buffer repeatedly.
+    m_boxes.resize(0);
+}
+
+inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
+{
+    if (m_whitespace)
+        m_boxes.append(box);
+}
+
+void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
+{
+    if (!m_whitespace)
+        return;
+
+    // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
+    // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
+    if (lineMidpointState.numMidpoints % 2) {
+        // Find the trailing space object's midpoint.
+        int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
+        for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].object() != m_whitespace; --trailingSpaceMidpoint) { }
+        ASSERT(trailingSpaceMidpoint >= 0);
+        if (collapseFirstSpace == CollapseFirstSpace)
+            lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
+
+        // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
+        // ignoring spaces.
+        size_t currentMidpoint = trailingSpaceMidpoint + 1;
+        for (size_t i = 0; i < m_boxes.size(); ++i) {
+            if (currentMidpoint >= lineMidpointState.numMidpoints) {
+                // We don't have a midpoint for this box yet.
+                ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
+            } else {
+                ASSERT(lineMidpointState.midpoints[currentMidpoint].object() == m_boxes[i]);
+                ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].object() == m_boxes[i]);
+            }
+            currentMidpoint += 2;
+        }
+    } else if (!lBreak.object()) {
+        ASSERT(m_whitespace->isText());
+        ASSERT(collapseFirstSpace == CollapseFirstSpace);
+        // Add a new end midpoint that stops right at the very end.
+        unsigned length = m_whitespace->textLength();
+        unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
+        InlineIterator endMid(0, m_whitespace, pos);
+        startIgnoringSpaces(lineMidpointState, endMid);
+        for (size_t i = 0; i < m_boxes.size(); ++i) {
+            ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
+        }
+    }
+}
+
+class BreakingContext {
+public:
+    BreakingContext(InlineBidiResolver& resolver, LineInfo& inLineInfo, LineWidth& lineWidth, RenderTextInfo& inRenderTextInfo, FloatingObject* inLastFloatFromPreviousLine, bool appliedStartWidth, RenderBlockFlow* block)
+        : m_resolver(resolver)
+        , m_current(resolver.position())
+        , m_lineBreak(resolver.position())
+        , m_block(block)
+        , m_lastObject(m_current.object())
+        , m_nextObject(0)
+        , m_currentStyle(0)
+        , m_blockStyle(block->style())
+        , m_lineInfo(inLineInfo)
+        , m_renderTextInfo(inRenderTextInfo)
+        , m_lastFloatFromPreviousLine(inLastFloatFromPreviousLine)
+        , m_width(lineWidth)
+        , m_currWS(NORMAL)
+        , m_lastWS(NORMAL)
+        , m_preservesNewline(false)
+        , m_atStart(true)
+        , m_ignoringSpaces(false)
+        , m_currentCharacterIsSpace(false)
+        , m_currentCharacterShouldCollapseIfPreWap(false)
+        , m_appliedStartWidth(appliedStartWidth)
+        , m_includeEndWidth(true)
+        , m_autoWrap(false)
+        , m_autoWrapWasEverTrueOnLine(false)
+        , m_floatsFitOnLine(true)
+        , m_collapseWhiteSpace(false)
+        , m_startingNewParagraph(m_lineInfo.previousLineBrokeCleanly())
+        , m_allowImagesToBreak(!block->document().inQuirksMode() || !block->isTableCell() || !m_blockStyle->logicalWidth().isIntrinsicOrAuto())
+        , m_atEnd(false)
+        , m_lineMidpointState(resolver.midpointState())
+    {
+        m_lineInfo.setPreviousLineBrokeCleanly(false);
+    }
+
+    RenderObject* currentObject() { return m_current.object(); }
+    InlineIterator lineBreak() { return m_lineBreak; }
+    bool atEnd() { return m_atEnd; }
+
+    void initializeForCurrentObject();
+
+    void increment();
+
+    void handleBR(EClear&);
+    void handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects);
+    void handleFloat();
+    void handleEmptyInline();
+    void handleReplaced();
+    bool handleText(WordMeasurements&, bool& hyphenated);
+    void commitAndUpdateLineBreakIfNeeded();
+    InlineIterator handleEndOfLine();
+
+    void clearLineBreakIfFitsOnLine()
+    {
+        if (m_width.fitsOnLine() || m_lastWS == NOWRAP)
+            m_lineBreak.clear();
+    }
+
+private:
+    void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
+
+    InlineBidiResolver& m_resolver;
+
+    InlineIterator m_current;
+    InlineIterator m_lineBreak;
+    InlineIterator m_startOfIgnoredSpaces;
+
+    RenderBlockFlow* m_block;
+    RenderObject* m_lastObject;
+    RenderObject* m_nextObject;
+
+    RenderStyle* m_currentStyle;
+    RenderStyle* m_blockStyle;
+
+    LineInfo& m_lineInfo;
+
+    RenderTextInfo& m_renderTextInfo;
+
+    FloatingObject* m_lastFloatFromPreviousLine;
+
+    LineWidth m_width;
+
+    EWhiteSpace m_currWS;
+    EWhiteSpace m_lastWS;
+
+    bool m_preservesNewline;
+    bool m_atStart;
+    bool m_ignoringSpaces;
+    bool m_currentCharacterIsSpace;
+    bool m_currentCharacterShouldCollapseIfPreWap;
+    bool m_appliedStartWidth;
+    bool m_includeEndWidth;
+    bool m_autoWrap;
+    bool m_autoWrapWasEverTrueOnLine;
+    bool m_floatsFitOnLine;
+    bool m_collapseWhiteSpace;
+    bool m_startingNewParagraph;
+    bool m_allowImagesToBreak;
+    bool m_atEnd;
+
+    LineMidpointState& m_lineMidpointState;
+
+    TrailingObjects m_trailingObjects;
+};
+
+enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
+
+inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
+{
+    // CSS2 16.6.1
+    // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
+    // If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.
+    // If spaces (U+0020) or tabs (U+0009) at the end of a line have 'white-space' set to 'pre-wrap', UAs may visually collapse them.
+    return style->collapseWhiteSpace()
+        || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
+}
+
+inline bool requiresLineBoxForContent(RenderInline* flow, const LineInfo& lineInfo)
+{
+    RenderObject* parent = flow->parent();
+    if (flow->document().inNoQuirksMode()
+        && (flow->style(lineInfo.isFirstLine())->lineHeight() != parent->style(lineInfo.isFirstLine())->lineHeight()
+        || flow->style()->verticalAlign() != parent->style()->verticalAlign()
+        || !parent->style()->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(flow->style()->font().fontMetrics())))
+        return true;
+    return false;
+}
+
+inline bool alwaysRequiresLineBox(RenderObject* flow)
+{
+    // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
+    // We need to fix this, though, because at the very least, inlines containing only
+    // ignorable whitespace should should also have line boxes.
+    return isEmptyInline(flow) && toRenderInline(flow)->hasInlineDirectionBordersPaddingOrMargin();
+}
+
+inline bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
+{
+    if (it.object()->isFloatingOrOutOfFlowPositioned())
+        return false;
+
+    if (it.object()->isRenderInline() && !alwaysRequiresLineBox(it.object()) && !requiresLineBoxForContent(toRenderInline(it.object()), lineInfo))
+        return false;
+
+    if (!shouldCollapseWhiteSpace(it.object()->style(), lineInfo, whitespacePosition) || it.object()->isBR())
+        return true;
+
+    UChar current = it.current();
+    bool notJustWhitespace = current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.object()->preservesNewline());
+    return notJustWhitespace || isEmptyInline(it.object());
+}
+
+inline void setStaticPositions(RenderBlockFlow* block, RenderBox* child)
+{
+    // FIXME: The math here is actually not really right. It's a best-guess approximation that
+    // will work for the common cases
+    RenderObject* containerBlock = child->container();
+    LayoutUnit blockHeight = block->logicalHeight();
+    if (containerBlock->isRenderInline()) {
+        // A relative positioned inline encloses us. In this case, we also have to determine our
+        // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
+        // inline so that we can obtain the value later.
+        toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(blockHeight, false));
+        toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
+    }
+    block->updateStaticInlinePositionForChild(child, blockHeight);
+    child->layer()->setStaticBlockPosition(blockHeight);
+}
+
+// FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
+// line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
+// elements quite right. In other words, we need to build this function's work into the normal line
+// object iteration process.
+// NB. this function will insert any floating elements that would otherwise
+// be skipped but it will not position them.
+inline void BreakingContext::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
+{
+    while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
+        RenderObject* object = iterator.object();
+        if (object->isOutOfFlowPositioned())
+            setStaticPositions(m_block, toRenderBox(object));
+        else if (object->isFloating())
+            m_block->insertFloatingObject(toRenderBox(object));
+        iterator.increment();
+    }
+}
+
+inline void BreakingContext::initializeForCurrentObject()
+{
+    m_currentStyle = m_current.object()->style();
+    m_nextObject = bidiNextSkippingEmptyInlines(m_block, m_current.object());
+    if (m_nextObject && m_nextObject->parent() && !m_nextObject->parent()->isDescendantOf(m_current.object()->parent()))
+        m_includeEndWidth = true;
+
+    m_currWS = m_current.object()->isReplaced() ? m_current.object()->parent()->style()->whiteSpace() : m_currentStyle->whiteSpace();
+    m_lastWS = m_lastObject->isReplaced() ? m_lastObject->parent()->style()->whiteSpace() : m_lastObject->style()->whiteSpace();
+
+    m_autoWrap = RenderStyle::autoWrap(m_currWS);
+    m_autoWrapWasEverTrueOnLine = m_autoWrapWasEverTrueOnLine || m_autoWrap;
+
+    m_preservesNewline = m_current.object()->isSVGInlineText() ? false : RenderStyle::preserveNewline(m_currWS);
+
+    m_collapseWhiteSpace = RenderStyle::collapseWhiteSpace(m_currWS);
+}
+
+inline void BreakingContext::increment()
+{
+    // Clear out our character space bool, since inline <pre>s don't collapse whitespace
+    // with adjacent inline normal/nowrap spans.
+    if (!m_collapseWhiteSpace)
+        m_currentCharacterIsSpace = false;
+
+    m_current.moveToStartOf(m_nextObject);
+    m_atStart = false;
+}
+
+inline void BreakingContext::handleBR(EClear& clear)
+{
+    if (m_width.fitsOnLine()) {
+        RenderObject* br = m_current.object();
+        m_lineBreak.moveToStartOf(br);
+        m_lineBreak.increment();
+
+        // A <br> always breaks a line, so don't let the line be collapsed
+        // away. Also, the space at the end of a line with a <br> does not
+        // get collapsed away. It only does this if the previous line broke
+        // cleanly. Otherwise the <br> has no effect on whether the line is
+        // empty or not.
+        if (m_startingNewParagraph)
+            m_lineInfo.setEmpty(false, m_block, &m_width);
+        m_trailingObjects.clear();
+        m_lineInfo.setPreviousLineBrokeCleanly(true);
+
+        // A <br> with clearance always needs a linebox in case the lines below it get dirtied later and
+        // need to check for floats to clear - so if we're ignoring spaces, stop ignoring them and add a
+        // run for this object.
+        if (m_ignoringSpaces && m_currentStyle->clear() != CNONE)
+            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, br);
+
+        if (!m_lineInfo.isEmpty())
+            clear = m_currentStyle->clear();
+    }
+    m_atEnd = true;
+}
+
+inline LayoutUnit borderPaddingMarginStart(RenderInline* child)
+{
+    return child->marginStart() + child->paddingStart() + child->borderStart();
+}
+
+inline LayoutUnit borderPaddingMarginEnd(RenderInline* child)
+{
+    return child->marginEnd() + child->paddingEnd() + child->borderEnd();
+}
+
+inline bool shouldAddBorderPaddingMargin(RenderObject* child, bool &checkSide)
+{
+    if (!child || (child->isText() && !toRenderText(child)->textLength()))
+        return true;
+    checkSide = false;
+    return checkSide;
+}
+
+inline LayoutUnit inlineLogicalWidth(RenderObject* child, bool start = true, bool end = true)
+{
+    unsigned lineDepth = 1;
+    LayoutUnit extraWidth = 0;
+    RenderObject* parent = child->parent();
+    while (parent->isRenderInline() && lineDepth++ < cMaxLineDepth) {
+        RenderInline* parentAsRenderInline = toRenderInline(parent);
+        if (!isEmptyInline(parentAsRenderInline)) {
+            if (start && shouldAddBorderPaddingMargin(child->previousSibling(), start))
+                extraWidth += borderPaddingMarginStart(parentAsRenderInline);
+            if (end && shouldAddBorderPaddingMargin(child->nextSibling(), end))
+                extraWidth += borderPaddingMarginEnd(parentAsRenderInline);
+            if (!start && !end)
+                return extraWidth;
+        }
+        child = parent;
+        parent = child->parent();
+    }
+    return extraWidth;
+}
+
+inline void BreakingContext::handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects)
+{
+    // If our original display wasn't an inline type, then we can
+    // go ahead and determine our static inline position now.
+    RenderBox* box = toRenderBox(m_current.object());
+    bool isInlineType = box->style()->isOriginalDisplayInlineType();
+    if (!isInlineType) {
+        m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));
+    } else {
+        // If our original display was an INLINE type, then we can go ahead
+        // and determine our static y position now.
+        box->layer()->setStaticBlockPosition(m_block->logicalHeight());
+    }
+
+    // If we're ignoring spaces, we have to stop and include this object and
+    // then start ignoring spaces again.
+    if (isInlineType || box->container()->isRenderInline()) {
+        if (m_ignoringSpaces)
+            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, box);
+        m_trailingObjects.appendBoxIfNeeded(box);
+    } else {
+        positionedObjects.append(box);
+    }
+    m_width.addUncommittedWidth(inlineLogicalWidth(box));
+    // Reset prior line break context characters.
+    m_renderTextInfo.m_lineBreakIterator.resetPriorContext();
+}
+
+inline void BreakingContext::handleFloat()
+{
+    RenderBox* floatBox = toRenderBox(m_current.object());
+    FloatingObject* floatingObject = m_block->insertFloatingObject(floatBox);
+    // check if it fits in the current line.
+    // If it does, position it now, otherwise, position
+    // it after moving to next line (in newLine() func)
+    // FIXME: Bug 110372: Properly position multiple stacked floats with non-rectangular shape outside.
+    if (m_floatsFitOnLine && m_width.fitsOnLine(m_block->logicalWidthForFloat(floatingObject))) {
+        m_block->positionNewFloatOnLine(floatingObject, m_lastFloatFromPreviousLine, m_lineInfo, m_width);
+        if (m_lineBreak.object() == m_current.object()) {
+            ASSERT(!m_lineBreak.m_pos);
+            m_lineBreak.increment();
+        }
+    } else {
+        m_floatsFitOnLine = false;
+    }
+    // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for floating element.
+    m_renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
+}
+
+// This is currently just used for list markers and inline flows that have line boxes. Neither should
+// have an effect on whitespace at the start of the line.
+inline bool shouldSkipWhitespaceAfterStartObject(RenderBlockFlow* block, RenderObject* o, LineMidpointState& lineMidpointState)
+{
+    RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
+    while (next && next->isFloatingOrOutOfFlowPositioned())
+        next = bidiNextSkippingEmptyInlines(block, next);
+
+    if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
+        RenderText* nextText = toRenderText(next);
+        UChar nextChar = nextText->characterAt(0);
+        if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
+            startIgnoringSpaces(lineMidpointState, InlineIterator(0, o, 0));
+            return true;
+        }
+    }
+
+    return false;
+}
+
+inline void BreakingContext::handleEmptyInline()
+{
+    // This should only end up being called on empty inlines
+    ASSERT(isEmptyInline(m_current.object()));
+
+    RenderInline* flowBox = toRenderInline(m_current.object());
+
+    // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
+    // to make sure that we stop to include this object and then start ignoring spaces again.
+    // If this object is at the start of the line, we need to behave like list markers and
+    // start ignoring spaces.
+    bool requiresLineBox = alwaysRequiresLineBox(m_current.object());
+    if (requiresLineBox || requiresLineBoxForContent(flowBox, m_lineInfo)) {
+        // An empty inline that only has line-height, vertical-align or font-metrics will only get a
+        // line box to affect the height of the line if the rest of the line is not empty.
+        if (requiresLineBox)
+            m_lineInfo.setEmpty(false, m_block, &m_width);
+        if (m_ignoringSpaces) {
+            m_trailingObjects.clear();
+            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, m_current.object());
+        } else if (m_blockStyle->collapseWhiteSpace() && m_resolver.position().object() == m_current.object()
+            && shouldSkipWhitespaceAfterStartObject(m_block, m_current.object(), m_lineMidpointState)) {
+            // Like with list markers, we start ignoring spaces to make sure that any
+            // additional spaces we see will be discarded.
+            m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = true;
+            m_ignoringSpaces = true;
+        }
+    }
+
+    m_width.addUncommittedWidth(inlineLogicalWidth(m_current.object()) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
+}
+
+inline void BreakingContext::handleReplaced()
+{
+    RenderBox* replacedBox = toRenderBox(m_current.object());
+
+    if (m_atStart)
+        m_width.updateAvailableWidth(replacedBox->logicalHeight());
+
+    // Break on replaced elements if either has normal white-space.
+    if ((m_autoWrap || RenderStyle::autoWrap(m_lastWS)) && (!m_current.object()->isImage() || m_allowImagesToBreak)) {
+        m_width.commit();
+        m_lineBreak.moveToStartOf(m_current.object());
+    }
+
+    if (m_ignoringSpaces)
+        stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), 0));
+
+    m_lineInfo.setEmpty(false, m_block, &m_width);
+    m_ignoringSpaces = false;
+    m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = false;
+    m_trailingObjects.clear();
+
+    // Optimize for a common case. If we can't find whitespace after the list
+    // item, then this is all moot.
+    LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(m_current.object());
+    if (m_current.object()->isListMarker()) {
+        if (m_blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, m_current.object(), m_lineMidpointState)) {
+            // Like with inline flows, we start ignoring spaces to make sure that any
+            // additional spaces we see will be discarded.
+            m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = true;
+            m_ignoringSpaces = true;
+        }
+        if (toRenderListMarker(m_current.object())->isInside())
+            m_width.addUncommittedWidth(replacedLogicalWidth);
+    } else {
+        m_width.addUncommittedWidth(replacedLogicalWidth);
+    }
+    if (m_current.object()->isRubyRun())
+        m_width.applyOverhang(toRenderRubyRun(m_current.object()), m_lastObject, m_nextObject);
+    // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for replaced element.
+    m_renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
+}
+
+inline bool iteratorIsBeyondEndOfRenderCombineText(const InlineIterator& iter, RenderCombineText* renderer)
+{
+    return iter.object() == renderer && iter.m_pos >= renderer->textLength();
+}
+
+inline void nextCharacter(UChar& currentCharacter, UChar& lastCharacter, UChar& secondToLastCharacter)
+{
+    secondToLastCharacter = lastCharacter;
+    lastCharacter = currentCharacter;
+}
+
+inline float firstPositiveWidth(const WordMeasurements& wordMeasurements)
+{
+    for (size_t i = 0; i < wordMeasurements.size(); ++i) {
+        if (wordMeasurements[i].width > 0)
+            return wordMeasurements[i].width;
+    }
+    return 0;
+}
+
+inline void updateSegmentsForShapes(RenderBlockFlow* block, const FloatingObject* lastFloatFromPreviousLine, const WordMeasurements& wordMeasurements, LineWidth& width, bool isFirstLine)
+{
+    ASSERT(lastFloatFromPreviousLine);
+
+    ShapeInsideInfo* shapeInsideInfo = block->layoutShapeInsideInfo();
+    if (!lastFloatFromPreviousLine->isPlaced() || !shapeInsideInfo)
+        return;
+
+    bool isHorizontalWritingMode = block->isHorizontalWritingMode();
+    LayoutUnit logicalOffsetFromShapeContainer = block->logicalOffsetFromShapeAncestorContainer(shapeInsideInfo->owner()).height();
+
+    LayoutUnit lineLogicalTop = block->logicalHeight() + logicalOffsetFromShapeContainer;
+    LayoutUnit lineLogicalHeight = block->lineHeight(isFirstLine, isHorizontalWritingMode ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
+    LayoutUnit lineLogicalBottom = lineLogicalTop + lineLogicalHeight;
+
+    LayoutUnit floatLogicalTop = block->logicalTopForFloat(lastFloatFromPreviousLine);
+    LayoutUnit floatLogicalBottom = block->logicalBottomForFloat(lastFloatFromPreviousLine);
+
+    bool lineOverlapsWithFloat = (floatLogicalTop < lineLogicalBottom) && (lineLogicalTop < floatLogicalBottom);
+    if (!lineOverlapsWithFloat)
+        return;
+
+    float minSegmentWidth = firstPositiveWidth(wordMeasurements);
+
+    LayoutUnit floatLogicalWidth = block->logicalWidthForFloat(lastFloatFromPreviousLine);
+    LayoutUnit availableLogicalWidth = block->logicalWidth() - block->logicalRightForFloat(lastFloatFromPreviousLine);
+    if (availableLogicalWidth < minSegmentWidth)
+        block->setLogicalHeight(floatLogicalBottom);
+
+    if (block->logicalHeight() < floatLogicalTop) {
+        shapeInsideInfo->adjustLogicalLineTop(minSegmentWidth + floatLogicalWidth);
+        block->setLogicalHeight(shapeInsideInfo->logicalLineTop() - logicalOffsetFromShapeContainer);
+    }
+
+    lineLogicalTop = block->logicalHeight() + logicalOffsetFromShapeContainer;
+
+    shapeInsideInfo->updateSegmentsForLine(lineLogicalTop, lineLogicalHeight);
+    width.updateCurrentShapeSegment();
+    width.updateAvailableWidth();
+}
+
+inline float measureHyphenWidth(RenderText* renderer, const Font& font)
+{
+    RenderStyle* style = renderer->style();
+    return font.width(RenderBlockFlow::constructTextRun(renderer, font, style->hyphenString().string(), style));
+}
+
+ALWAYS_INLINE float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace, HashSet<const SimpleFontData*>* fallbackFonts = 0, TextLayout* layout = 0)
+{
+    GlyphOverflow glyphOverflow;
+    if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
+        return text->width(from, len, font, xPos, fallbackFonts, &glyphOverflow);
+
+    if (layout)
+        return Font::width(*layout, from, len, fallbackFonts);
+
+    TextRun run = RenderBlockFlow::constructTextRun(text, font, text, from, len, text->style());
+    run.setCharactersLength(text->textLength() - from);
+    ASSERT(run.charactersLength() >= run.length());
+
+    run.setCharacterScanForCodePath(!text->canUseSimpleFontCodePath());
+    run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
+    run.setXPos(xPos);
+    return font.width(run, fallbackFonts, &glyphOverflow);
+}
+
+inline bool BreakingContext::handleText(WordMeasurements& wordMeasurements, bool& hyphenated)
+{
+    if (!m_current.m_pos)
+        m_appliedStartWidth = false;
+
+    RenderText* renderText = toRenderText(m_current.object());
+
+    bool isSVGText = renderText->isSVGInlineText();
+
+    if (renderText->style()->hasTextCombine() && m_current.object()->isCombineText() && !toRenderCombineText(m_current.object())->isCombined()) {
+        RenderCombineText* combineRenderer = toRenderCombineText(m_current.object());
+        combineRenderer->combineText();
+        // The length of the renderer's text may have changed. Increment stale iterator positions
+        if (iteratorIsBeyondEndOfRenderCombineText(m_lineBreak, combineRenderer)) {
+            ASSERT(iteratorIsBeyondEndOfRenderCombineText(m_resolver.position(), combineRenderer));
+            m_lineBreak.increment();
+            m_resolver.position().increment(&m_resolver);
+        }
+    }
+
+    RenderStyle* style = renderText->style(m_lineInfo.isFirstLine());
+    const Font& font = style->font();
+    bool isFixedPitch = font.isFixedPitch();
+
+    unsigned lastSpace = m_current.m_pos;
+    float wordSpacing = m_currentStyle->wordSpacing();
+    float lastSpaceWordSpacing = 0;
+    float wordSpacingForWordMeasurement = 0;
+
+    float wrapW = m_width.uncommittedWidth() + inlineLogicalWidth(m_current.object(), !m_appliedStartWidth, true);
+    float charWidth = 0;
+    // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
+    // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
+    bool breakWords = m_currentStyle->breakWords() && ((m_autoWrap && !m_width.committedWidth()) || m_currWS == PRE);
+    bool midWordBreak = false;
+    bool breakAll = m_currentStyle->wordBreak() == BreakAllWordBreak && m_autoWrap;
+    float hyphenWidth = 0;
+
+    if (isSVGText) {
+        breakWords = false;
+        breakAll = false;
+    }
+
+    if (renderText->isWordBreak()) {
+        m_width.commit();
+        m_lineBreak.moveToStartOf(m_current.object());
+        ASSERT(m_current.m_pos == renderText->textLength());
+    }
+
+    if (m_renderTextInfo.m_text != renderText) {
+        m_renderTextInfo.m_text = renderText;
+        m_renderTextInfo.m_font = &font;
+        m_renderTextInfo.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
+        m_renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(renderText->text(), style->locale());
+    } else if (m_renderTextInfo.m_layout && m_renderTextInfo.m_font != &font) {
+        m_renderTextInfo.m_font = &font;
+        m_renderTextInfo.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
+    }
+
+    TextLayout* textLayout = m_renderTextInfo.m_layout.get();
+
+    // Non-zero only when kerning is enabled and TextLayout isn't used, in which case we measure
+    // words with their trailing space, then subtract its width.
+    float wordTrailingSpaceWidth = (font.typesettingFeatures() & Kerning) && !textLayout ? font.width(RenderBlockFlow::constructTextRun(renderText, font, &space, 1, style)) + wordSpacing : 0;
+
+    UChar lastCharacter = m_renderTextInfo.m_lineBreakIterator.lastCharacter();
+    UChar secondToLastCharacter = m_renderTextInfo.m_lineBreakIterator.secondToLastCharacter();
+    for (; m_current.m_pos < renderText->textLength(); m_current.fastIncrementInTextNode()) {
+        bool previousCharacterIsSpace = m_currentCharacterIsSpace;
+        bool previousCharacterShouldCollapseIfPreWap = m_currentCharacterShouldCollapseIfPreWap;
+        UChar c = m_current.current();
+        m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = c == ' ' || c == '\t' || (!m_preservesNewline && (c == '\n'));
+
+        if (!m_collapseWhiteSpace || !m_currentCharacterIsSpace)
+            m_lineInfo.setEmpty(false, m_block, &m_width);
+
+        if (c == softHyphen && m_autoWrap && !hyphenWidth) {
+            hyphenWidth = measureHyphenWidth(renderText, font);
+            m_width.addUncommittedWidth(hyphenWidth);
+        }
+
+        bool applyWordSpacing = false;
+
+        if ((breakAll || breakWords) && !midWordBreak) {
+            wrapW += charWidth;
+            bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && m_current.m_pos + 1 < renderText->textLength() && U16_IS_TRAIL((*renderText)[m_current.m_pos + 1]);
+            charWidth = textWidth(renderText, m_current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, font, m_width.committedWidth() + wrapW, isFixedPitch, m_collapseWhiteSpace, 0, textLayout);
+            midWordBreak = m_width.committedWidth() + wrapW + charWidth > m_width.availableWidth();
+        }
+
+        bool betweenWords = c == '\n' || (m_currWS != PRE && !m_atStart && isBreakable(m_renderTextInfo.m_lineBreakIterator, m_current.m_pos, m_current.m_nextBreakablePosition));
+
+        if (betweenWords || midWordBreak) {
+            bool stoppedIgnoringSpaces = false;
+            if (m_ignoringSpaces) {
+                lastSpaceWordSpacing = 0;
+                if (!m_currentCharacterIsSpace) {
+                    // Stop ignoring spaces and begin at this
+                    // new point.
+                    m_ignoringSpaces = false;
+                    wordSpacingForWordMeasurement = 0;
+                    lastSpace = m_current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
+                    stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), m_current.m_pos));
+                    stoppedIgnoringSpaces = true;
+                } else {
+                    // Just keep ignoring these spaces.
+                    nextCharacter(c, lastCharacter, secondToLastCharacter);
+                    continue;
+                }
+            }
+
+            wordMeasurements.grow(wordMeasurements.size() + 1);
+            WordMeasurement& wordMeasurement = wordMeasurements.last();
+
+            wordMeasurement.renderer = renderText;
+            wordMeasurement.endOffset = m_current.m_pos;
+            wordMeasurement.startOffset = lastSpace;
+
+            float additionalTmpW;
+            if (wordTrailingSpaceWidth && c == ' ')
+                additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos + 1 - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth;
+            else
+                additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
+
+            wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement;
+            additionalTmpW += lastSpaceWordSpacing;
+            m_width.addUncommittedWidth(additionalTmpW);
+            if (!m_appliedStartWidth) {
+                m_width.addUncommittedWidth(inlineLogicalWidth(m_current.object(), true, false));
+                m_appliedStartWidth = true;
+            }
+
+            if (m_lastFloatFromPreviousLine)
+                updateSegmentsForShapes(m_block, m_lastFloatFromPreviousLine, wordMeasurements, m_width, m_lineInfo.isFirstLine());
+
+            applyWordSpacing = wordSpacing && m_currentCharacterIsSpace;
+
+            if (!m_width.committedWidth() && m_autoWrap && !m_width.fitsOnLine())
+                m_width.fitBelowFloats();
+
+            if (m_autoWrap || breakWords) {
+                // If we break only after white-space, consider the current character
+                // as candidate width for this line.
+                bool lineWasTooWide = false;
+                if (m_width.fitsOnLine() && m_currentCharacterIsSpace && m_currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
+                    float charWidth = textWidth(renderText, m_current.m_pos, 1, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0);
+                    // Check if line is too big even without the extra space
+                    // at the end of the line. If it is not, do nothing.
+                    // If the line needs the extra whitespace to be too long,
+                    // then move the line break to the space and skip all
+                    // additional whitespace.
+                    if (!m_width.fitsOnLine(charWidth)) {
+                        lineWasTooWide = true;
+                        m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                        skipTrailingWhitespace(m_lineBreak, m_lineInfo);
+                    }
+                }
+                if (lineWasTooWide || !m_width.fitsOnLine()) {
+                    if (m_lineBreak.atTextParagraphSeparator()) {
+                        if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
+                            ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+                        m_lineBreak.increment();
+                        m_lineInfo.setPreviousLineBrokeCleanly(true);
+                        wordMeasurement.endOffset = m_lineBreak.m_pos;
+                    }
+                    if (m_lineBreak.object() && m_lineBreak.m_pos && m_lineBreak.object()->isText() && toRenderText(m_lineBreak.object())->textLength() && toRenderText(m_lineBreak.object())->characterAt(m_lineBreak.m_pos - 1) == softHyphen)
+                        hyphenated = true;
+                    if (m_lineBreak.m_pos && m_lineBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) {
+                        if (charWidth) {
+                            wordMeasurement.endOffset = m_lineBreak.m_pos;
+                            wordMeasurement.width = charWidth;
+                        }
+                    }
+                    // Didn't fit. Jump to the end unless there's still an opportunity to collapse whitespace.
+                    if (m_ignoringSpaces || !m_collapseWhiteSpace || !m_currentCharacterIsSpace || !previousCharacterIsSpace) {
+                        m_atEnd = true;
+                        return false;
+                    }
+                } else {
+                    if (!betweenWords || (midWordBreak && !m_autoWrap))
+                        m_width.addUncommittedWidth(-additionalTmpW);
+                    if (hyphenWidth) {
+                        // Subtract the width of the soft hyphen out since we fit on a line.
+                        m_width.addUncommittedWidth(-hyphenWidth);
+                        hyphenWidth = 0;
+                    }
+                }
+            }
+
+            if (c == '\n' && m_preservesNewline) {
+                if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
+                    ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                m_lineBreak.increment();
+                m_lineInfo.setPreviousLineBrokeCleanly(true);
+                return true;
+            }
+
+            if (m_autoWrap && betweenWords) {
+                m_width.commit();
+                wrapW = 0;
+                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                // Auto-wrapping text should not wrap in the middle of a word once it has had an
+                // opportunity to break after a word.
+                breakWords = false;
+            }
+
+            if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
+                // Remember this as a breakable position in case
+                // adding the end width forces a break.
+                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                midWordBreak &= (breakWords || breakAll);
+            }
+
+            if (betweenWords) {
+                lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
+                wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0;
+                lastSpace = m_current.m_pos;
+            }
+
+            if (!m_ignoringSpaces && m_currentStyle->collapseWhiteSpace()) {
+                // If we encounter a newline, or if we encounter a
+                // second space, we need to go ahead and break up this
+                // run and enter a mode where we start collapsing spaces.
+                if (m_currentCharacterIsSpace && previousCharacterIsSpace) {
+                    m_ignoringSpaces = true;
+
+                    // We just entered a mode where we are ignoring
+                    // spaces. Create a midpoint to terminate the run
+                    // before the second space.
+                    startIgnoringSpaces(m_lineMidpointState, m_startOfIgnoredSpaces);
+                    m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
+                }
+            }
+        } else if (m_ignoringSpaces) {
+            // Stop ignoring spaces and begin at this
+            // new point.
+            m_ignoringSpaces = false;
+            lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
+            wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0;
+            lastSpace = m_current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
+            stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), m_current.m_pos));
+        }
+
+        if (isSVGText && m_current.m_pos > 0) {
+            // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
+            if (toRenderSVGInlineText(renderText)->characterStartsNewTextChunk(m_current.m_pos))
+                ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+        }
+
+        if (m_currentCharacterIsSpace && !previousCharacterIsSpace) {
+            m_startOfIgnoredSpaces.setObject(m_current.object());
+            m_startOfIgnoredSpaces.m_pos = m_current.m_pos;
+        }
+
+        if (!m_currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) {
+            if (m_autoWrap && m_currentStyle->breakOnlyAfterWhiteSpace())
+                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+        }
+
+        if (m_collapseWhiteSpace && m_currentCharacterIsSpace && !m_ignoringSpaces)
+            m_trailingObjects.setTrailingWhitespace(toRenderText(m_current.object()));
+        else if (!m_currentStyle->collapseWhiteSpace() || !m_currentCharacterIsSpace)
+            m_trailingObjects.clear();
+
+        m_atStart = false;
+        nextCharacter(c, lastCharacter, secondToLastCharacter);
+    }
+
+    m_renderTextInfo.m_lineBreakIterator.setPriorContext(lastCharacter, secondToLastCharacter);
+
+    wordMeasurements.grow(wordMeasurements.size() + 1);
+    WordMeasurement& wordMeasurement = wordMeasurements.last();
+    wordMeasurement.renderer = renderText;
+
+    // IMPORTANT: current.m_pos is > length here!
+    float additionalTmpW = m_ignoringSpaces ? 0 : textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
+    wordMeasurement.startOffset = lastSpace;
+    wordMeasurement.endOffset = m_current.m_pos;
+    wordMeasurement.width = m_ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement;
+    additionalTmpW += lastSpaceWordSpacing;
+    m_width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(m_current.object(), !m_appliedStartWidth, m_includeEndWidth));
+    m_includeEndWidth = false;
+
+    if (!m_width.fitsOnLine()) {
+        if (!hyphenated && m_lineBreak.previousInSameNode() == softHyphen) {
+            hyphenated = true;
+            m_atEnd = true;
+        }
+    }
+    return false;
+}
+
+inline void BreakingContext::commitAndUpdateLineBreakIfNeeded()
+{
+    bool checkForBreak = m_autoWrap;
+    if (m_width.committedWidth() && !m_width.fitsOnLine() && m_lineBreak.object() && m_currWS == NOWRAP) {
+        checkForBreak = true;
+    } else if (m_nextObject && m_current.object()->isText() && m_nextObject->isText() && !m_nextObject->isBR() && (m_autoWrap || m_nextObject->style()->autoWrap())) {
+        if (m_autoWrap && m_currentCharacterIsSpace) {
+            checkForBreak = true;
+        } else {
+            RenderText* nextText = toRenderText(m_nextObject);
+            if (nextText->textLength()) {
+                UChar c = nextText->characterAt(0);
+                // If the next item on the line is text, and if we did not end with
+                // a space, then the next text run continues our word (and so it needs to
+                // keep adding to the uncommitted width. Just update and continue.
+                checkForBreak = !m_currentCharacterIsSpace && (c == ' ' || c == '\t' || (c == '\n' && !m_nextObject->preservesNewline()));
+            } else if (nextText->isWordBreak()) {
+                checkForBreak = true;
+            }
+
+            if (!m_width.fitsOnLine() && !m_width.committedWidth())
+                m_width.fitBelowFloats();
+
+            bool canPlaceOnLine = m_width.fitsOnLine() || !m_autoWrapWasEverTrueOnLine;
+            if (canPlaceOnLine && checkForBreak) {
+                m_width.commit();
+                m_lineBreak.moveToStartOf(m_nextObject);
+            }
+        }
+    }
+
+    if (checkForBreak && !m_width.fitsOnLine()) {
+        // if we have floats, try to get below them.
+        if (m_currentCharacterIsSpace && !m_ignoringSpaces && m_currentStyle->collapseWhiteSpace())
+            m_trailingObjects.clear();
+
+        if (m_width.committedWidth()) {
+            m_atEnd = true;
+            return;
+        }
+
+        m_width.fitBelowFloats();
+
+        // |width| may have been adjusted because we got shoved down past a float (thus
+        // giving us more room), so we need to retest, and only jump to
+        // the end label if we still don't fit on the line. -dwh
+        if (!m_width.fitsOnLine()) {
+            m_atEnd = true;
+            return;
+        }
+    } else if (m_blockStyle->autoWrap() && !m_width.fitsOnLine() && !m_width.committedWidth()) {
+        // If the container autowraps but the current child does not then we still need to ensure that it
+        // wraps and moves below any floats.
+        m_width.fitBelowFloats();
+    }
+
+    if (!m_current.object()->isFloatingOrOutOfFlowPositioned()) {
+        m_lastObject = m_current.object();
+        if (m_lastObject->isReplaced() && m_autoWrap && (!m_lastObject->isImage() || m_allowImagesToBreak) && (!m_lastObject->isListMarker() || toRenderListMarker(m_lastObject)->isInside())) {
+            m_width.commit();
+            m_lineBreak.moveToStartOf(m_nextObject);
+        }
+    }
+}
+
+inline void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
+{
+    // Check to see if our last midpoint is a start point beyond the line break. If so,
+    // shave it off the list, and shave off a trailing space if the previous end point doesn't
+    // preserve whitespace.
+    if (lBreak.object() && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
+        InlineIterator* midpoints = lineMidpointState.midpoints.data();
+        InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
+        const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
+        InlineIterator currpoint = endpoint;
+        while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
+            currpoint.increment();
+        if (currpoint == lBreak) {
+            // We hit the line break before the start point. Shave off the start point.
+            lineMidpointState.numMidpoints--;
+            if (endpoint.object()->style()->collapseWhiteSpace() && endpoint.object()->isText())
+                endpoint.m_pos--;
+        }
+    }
+}
+
+InlineIterator BreakingContext::handleEndOfLine()
+{
+    ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
+    bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
+
+    if (m_lineBreak == m_resolver.position() && (!m_lineBreak.object() || !m_lineBreak.object()->isBR()) && segmentAllowsOverflow) {
+        // we just add as much as possible
+        if (m_blockStyle->whiteSpace() == PRE && !m_current.m_pos) {
+            m_lineBreak.moveTo(m_lastObject, m_lastObject->isText() ? m_lastObject->length() : 0);
+        } else if (m_lineBreak.object()) {
+            // Don't ever break in the middle of a word if we can help it.
+            // There's no room at all. We just have to be on this line,
+            // even though we'll spill out.
+            m_lineBreak.moveTo(m_current.object(), m_current.m_pos);
+        }
+    }
+
+    // FIXME Bug 100049: We do not need to consume input in a multi-segment line
+    // unless no segment will.
+    // make sure we consume at least one char/object.
+    if (m_lineBreak == m_resolver.position() && segmentAllowsOverflow)
+        m_lineBreak.increment();
+
+    // Sanity check our midpoints.
+    checkMidpoints(m_lineMidpointState, m_lineBreak);
+
+    m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, m_lineBreak, TrailingObjects::CollapseFirstSpace);
+
+    // We might have made lineBreak an iterator that points past the end
+    // of the object. Do this adjustment to make it point to the start
+    // of the next object instead to avoid confusing the rest of the
+    // code.
+    if (m_lineBreak.m_pos > 0) {
+        m_lineBreak.m_pos--;
+        m_lineBreak.increment();
+    }
+
+    return m_lineBreak;
+}
+
+}
+
+#endif // BreakingContextInlineHeaders_h
diff --git a/Source/core/rendering/line/LineInfo.h b/Source/core/rendering/line/LineInfo.h
new file mode 100644
index 0000000..337da11
--- /dev/null
+++ b/Source/core/rendering/line/LineInfo.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Adobe Systems Incorporated.
+ *
+ * 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.
+ *
+ */
+
+#ifndef LineInfo_h
+#define LineInfo_h
+
+namespace WebCore {
+
+class LineInfo {
+public:
+    LineInfo()
+        : m_isFirstLine(true)
+        , m_isLastLine(false)
+        , m_isEmpty(true)
+        , m_previousLineBrokeCleanly(true)
+        , m_floatPaginationStrut(0)
+        , m_runsFromLeadingWhitespace(0)
+    { }
+
+    bool isFirstLine() const { return m_isFirstLine; }
+    bool isLastLine() const { return m_isLastLine; }
+    bool isEmpty() const { return m_isEmpty; }
+    bool previousLineBrokeCleanly() const { return m_previousLineBrokeCleanly; }
+    LayoutUnit floatPaginationStrut() const { return m_floatPaginationStrut; }
+    unsigned runsFromLeadingWhitespace() const { return m_runsFromLeadingWhitespace; }
+    void resetRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace = 0; }
+    void incrementRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace++; }
+
+    void setFirstLine(bool firstLine) { m_isFirstLine = firstLine; }
+    void setLastLine(bool lastLine) { m_isLastLine = lastLine; }
+    void setEmpty(bool empty, RenderBlock* block = 0, LineWidth* lineWidth = 0)
+    {
+        if (m_isEmpty == empty)
+            return;
+        m_isEmpty = empty;
+        if (!empty && block && floatPaginationStrut()) {
+            block->setLogicalHeight(block->logicalHeight() + floatPaginationStrut());
+            setFloatPaginationStrut(0);
+            lineWidth->updateAvailableWidth();
+        }
+    }
+
+    void setPreviousLineBrokeCleanly(bool previousLineBrokeCleanly) { m_previousLineBrokeCleanly = previousLineBrokeCleanly; }
+    void setFloatPaginationStrut(LayoutUnit strut) { m_floatPaginationStrut = strut; }
+
+private:
+    bool m_isFirstLine;
+    bool m_isLastLine;
+    bool m_isEmpty;
+    bool m_previousLineBrokeCleanly;
+    LayoutUnit m_floatPaginationStrut;
+    unsigned m_runsFromLeadingWhitespace;
+};
+
+}
+
+#endif // LineInfo_h
diff --git a/Source/core/rendering/shapes/PolygonShape.cpp b/Source/core/rendering/shapes/PolygonShape.cpp
index 5b155ed..26ddcf3 100644
--- a/Source/core/rendering/shapes/PolygonShape.cpp
+++ b/Source/core/rendering/shapes/PolygonShape.cpp
@@ -182,7 +182,7 @@
 const FloatPolygon& PolygonShape::shapePaddingBounds() const
 {
     ASSERT(shapePadding() >= 0);
-    if (!shapePadding())
+    if (!shapePadding() || m_polygon.isEmpty())
         return m_polygon;
 
     if (!m_paddingBounds)
@@ -194,7 +194,7 @@
 const FloatPolygon& PolygonShape::shapeMarginBounds() const
 {
     ASSERT(shapeMargin() >= 0);
-    if (!shapeMargin())
+    if (!shapeMargin() || m_polygon.isEmpty())
         return m_polygon;
 
     if (!m_marginBounds)
diff --git a/Source/core/rendering/shapes/RasterShape.cpp b/Source/core/rendering/shapes/RasterShape.cpp
index b8f4b15..78b0021 100644
--- a/Source/core/rendering/shapes/RasterShape.cpp
+++ b/Source/core/rendering/shapes/RasterShape.cpp
@@ -70,25 +70,24 @@
 {
     unsigned xInterceptsIndex = abs(y - m_y);
     int dx = (xInterceptsIndex >= m_xIntercepts.size()) ? 0 : m_xIntercepts[xInterceptsIndex];
-    return IntShapeInterval(std::max(0, m_x1 - dx), m_x2 + dx);
+    return IntShapeInterval(m_x1 - dx, m_x2 + dx);
 }
 
 void RasterShapeIntervals::appendInterval(int y, int x1, int x2)
 {
-    ASSERT(y >= 0 && y < size() && x1 >= 0 && x2 > x1 && (m_intervalLists[y].isEmpty() || x1 > m_intervalLists[y].last().x2()));
-
+    ASSERT(x2 > x1 && (intervalsAt(y).isEmpty() || x1 > intervalsAt(y).last().x2()));
     m_bounds.unite(IntRect(x1, y, x2 - x1, 1));
-    m_intervalLists[y].append(IntShapeInterval(x1, x2));
+    intervalsAt(y).append(IntShapeInterval(x1, x2));
 }
 
 void RasterShapeIntervals::uniteMarginInterval(int y, const IntShapeInterval& interval)
 {
-    ASSERT(m_intervalLists[y].size() <= 1);
+    ASSERT(intervalsAt(y).size() <= 1); // Each m_intervalLists entry has 0 or one interval.
 
-    if (m_intervalLists[y].isEmpty()) {
-        m_intervalLists[y].append(interval);
+    if (intervalsAt(y).isEmpty()) {
+        intervalsAt(y).append(interval);
     } else {
-        IntShapeInterval& resultInterval = m_intervalLists[y][0];
+        IntShapeInterval& resultInterval = intervalsAt(y)[0];
         resultInterval.set(std::min(resultInterval.x1(), interval.x1()), std::max(resultInterval.x2(), interval.x2()));
     }
 
@@ -206,10 +205,8 @@
     if (y2 < bounds().y() || y1 >= bounds().maxY())
         return;
 
-    for (int y = y1; y < y2;  y++) {
-        if (intervalsAt(y).isEmpty())
-            return;
-    }
+    y1 = std::max(y1, bounds().y());
+    y2 = std::min(y2, bounds().maxY());
 
     result = intervalsAt(y1);
     for (int y = y1 + 1; y < y2;  y++) {
@@ -219,22 +216,25 @@
     }
 }
 
-PassOwnPtr<RasterShapeIntervals> RasterShapeIntervals::computeShapeMarginIntervals(unsigned margin) const
+PassOwnPtr<RasterShapeIntervals> RasterShapeIntervals::computeShapeMarginIntervals(unsigned shapeMargin) const
 {
-    OwnPtr<RasterShapeIntervals> result = adoptPtr(new RasterShapeIntervals(size() + margin));
-    MarginIntervalGenerator marginIntervalGenerator(margin);
+    OwnPtr<RasterShapeIntervals> result = adoptPtr(new RasterShapeIntervals(size(), shapeMargin));
+    MarginIntervalGenerator marginIntervalGenerator(shapeMargin);
 
-    for (int y = bounds().y(); y < bounds().maxY(); ++y) {
+    int minY = bounds().y();
+    int maxY = bounds().maxY();
+
+    for (int y = minY; y < maxY; ++y) {
         const IntShapeInterval& intervalAtY = limitIntervalAt(y);
         if (intervalAtY.isEmpty())
             continue;
 
         marginIntervalGenerator.set(y, intervalAtY);
-        int marginY0 = std::max(0, clampToPositiveInteger(y - margin));
-        int marginY1 = std::min(result->size() - 1, clampToPositiveInteger(y + margin));
+        int marginY0 = y - clampToInteger(shapeMargin);
+        int marginY1 = y + clampToInteger(shapeMargin);
 
         for (int marginY = y - 1; marginY >= marginY0; --marginY) {
-            if (limitIntervalAt(marginY).contains(intervalAtY))
+            if (marginY > minY && limitIntervalAt(marginY).contains(intervalAtY))
                 break;
             result->uniteMarginInterval(marginY, marginIntervalGenerator.intervalAt(marginY));
         }
@@ -242,7 +242,7 @@
         result->uniteMarginInterval(y, marginIntervalGenerator.intervalAt(y));
 
         for (int marginY = y + 1; marginY <= marginY1; ++marginY) {
-            if (marginY < size() && limitIntervalAt(marginY).contains(intervalAtY))
+            if (marginY < maxY && limitIntervalAt(marginY).contains(intervalAtY))
                 break;
             result->uniteMarginInterval(marginY, marginIntervalGenerator.intervalAt(marginY));
         }
diff --git a/Source/core/rendering/shapes/RasterShape.h b/Source/core/rendering/shapes/RasterShape.h
index a0d6fa9..903eabb 100644
--- a/Source/core/rendering/shapes/RasterShape.h
+++ b/Source/core/rendering/shapes/RasterShape.h
@@ -40,9 +40,10 @@
 
 class RasterShapeIntervals {
 public:
-    RasterShapeIntervals(unsigned size)
+    RasterShapeIntervals(unsigned size, unsigned shapeMargin = 0)
+        : m_shapeMargin(shapeMargin)
     {
-        m_intervalLists.resize(size);
+        m_intervalLists.resize(size + shapeMargin * 2);
     }
 
     const IntRect& bounds() const { return m_bounds; }
@@ -52,15 +53,21 @@
     void getIncludedIntervals(int y1, int y2, IntShapeIntervals& result) const;
     void getExcludedIntervals(int y1, int y2, IntShapeIntervals& result) const;
     bool firstIncludedIntervalY(int minY, const IntSize& minSize, LayoutUnit& result) const;
-    PassOwnPtr<RasterShapeIntervals> computeShapeMarginIntervals(unsigned margin) const;
+    PassOwnPtr<RasterShapeIntervals> computeShapeMarginIntervals(unsigned shapeMargin) const;
 
 private:
     int size() const { return m_intervalLists.size(); }
 
+    IntShapeIntervals& intervalsAt(int y)
+    {
+        ASSERT(y + m_shapeMargin >= 0 && y + m_shapeMargin < m_intervalLists.size());
+        return m_intervalLists[y + m_shapeMargin];
+    }
+
     const IntShapeIntervals& intervalsAt(int y) const
     {
-        ASSERT(y >= 0 && y < size());
-        return m_intervalLists[y];
+        ASSERT(y + m_shapeMargin >= 0 && y + m_shapeMargin < m_intervalLists.size());
+        return m_intervalLists[y + m_shapeMargin];
     }
 
     IntShapeInterval limitIntervalAt(int y) const
@@ -74,6 +81,7 @@
     void uniteMarginInterval(int y, const IntShapeInterval&);
     IntRect m_bounds;
     Vector<IntShapeIntervals> m_intervalLists;
+    unsigned m_shapeMargin;
 };
 
 class RasterShape : public Shape {
diff --git a/Source/core/rendering/shapes/RectangleShape.cpp b/Source/core/rendering/shapes/RectangleShape.cpp
index b2b26aa..16953fd 100644
--- a/Source/core/rendering/shapes/RectangleShape.cpp
+++ b/Source/core/rendering/shapes/RectangleShape.cpp
@@ -46,7 +46,7 @@
     return ry * sqrt(1 - (x * x) / (rx * rx));
 }
 
-FloatRoundedRect FloatRoundedRect::paddingBounds(float padding) const
+RectangleShape::ShapeBounds RectangleShape::ShapeBounds::paddingBounds(float padding) const
 {
     ASSERT(padding >= 0);
     if (!padding || isEmpty())
@@ -58,10 +58,10 @@
     float boundsHeight = std::max(0.0f, height() - padding * 2);
     float boundsRadiusX = std::max(0.0f, rx() - padding);
     float boundsRadiusY = std::max(0.0f, ry() - padding);
-    return FloatRoundedRect(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
+    return RectangleShape::ShapeBounds(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
 }
 
-FloatRoundedRect FloatRoundedRect::marginBounds(float margin) const
+RectangleShape::ShapeBounds RectangleShape::ShapeBounds::marginBounds(float margin) const
 {
     ASSERT(margin >= 0);
     if (!margin)
@@ -73,17 +73,17 @@
     float boundsHeight = height() + margin * 2;
     float boundsRadiusX = rx() + margin;
     float boundsRadiusY = ry() + margin;
-    return FloatRoundedRect(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
+    return RectangleShape::ShapeBounds(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
 }
 
-FloatPoint FloatRoundedRect::cornerInterceptForWidth(float widthAtIntercept) const
+FloatPoint RectangleShape::ShapeBounds::cornerInterceptForWidth(float widthAtIntercept) const
 {
     float xi = (width() - widthAtIntercept) / 2;
     float yi = ry() - ellipseYIntercept(rx() - xi, rx(), ry());
     return FloatPoint(xi, yi);
 }
 
-FloatRoundedRect RectangleShape::shapePaddingBounds() const
+RectangleShape::ShapeBounds RectangleShape::shapePaddingBounds() const
 {
     if (!m_haveInitializedPaddingBounds) {
         m_haveInitializedPaddingBounds = true;
@@ -92,7 +92,7 @@
     return m_paddingBounds;
 }
 
-FloatRoundedRect RectangleShape::shapeMarginBounds() const
+RectangleShape::ShapeBounds RectangleShape::shapeMarginBounds() const
 {
     if (!m_haveInitializedMarginBounds) {
         m_haveInitializedMarginBounds = true;
@@ -103,7 +103,7 @@
 
 void RectangleShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
-    const FloatRoundedRect& bounds = shapeMarginBounds();
+    const RectangleShape::ShapeBounds& bounds = shapeMarginBounds();
     if (bounds.isEmpty())
         return;
 
@@ -135,7 +135,7 @@
 
 void RectangleShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
-    const FloatRoundedRect& bounds = shapePaddingBounds();
+    const RectangleShape::ShapeBounds& bounds = shapePaddingBounds();
     if (bounds.isEmpty())
         return;
 
@@ -184,7 +184,7 @@
     float minIntervalHeight = minLogicalIntervalSize.height();
     float minIntervalWidth = minLogicalIntervalSize.width();
 
-    const FloatRoundedRect& bounds = shapePaddingBounds();
+    const RectangleShape::ShapeBounds& bounds = shapePaddingBounds();
     if (bounds.isEmpty() || minIntervalWidth > bounds.width())
         return false;
 
diff --git a/Source/core/rendering/shapes/RectangleShape.h b/Source/core/rendering/shapes/RectangleShape.h
index 6db9921..35db8a4 100644
--- a/Source/core/rendering/shapes/RectangleShape.h
+++ b/Source/core/rendering/shapes/RectangleShape.h
@@ -39,25 +39,6 @@
 
 namespace WebCore {
 
-class FloatRoundedRect : public FloatRect {
-public:
-    FloatRoundedRect() { }
-    FloatRoundedRect(const FloatRect& bounds, const FloatSize& radii)
-        : FloatRect(bounds)
-        , m_radii(radii)
-    {
-    }
-
-    float rx() const { return m_radii.width(); }
-    float ry() const { return m_radii.height(); }
-    FloatRoundedRect marginBounds(float margin) const;
-    FloatRoundedRect paddingBounds(float padding) const;
-    FloatPoint cornerInterceptForWidth(float width) const;
-
-private:
-    FloatSize m_radii;
-};
-
 class RectangleShape : public Shape {
 public:
     RectangleShape(const FloatRect& bounds, const FloatSize& radii)
@@ -76,12 +57,31 @@
     virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
 
 private:
-    FloatRoundedRect shapeMarginBounds() const;
-    FloatRoundedRect shapePaddingBounds() const;
+    class ShapeBounds : public FloatRect {
+    public:
+        ShapeBounds() { }
+        ShapeBounds(const FloatRect& bounds, const FloatSize& radii)
+            : FloatRect(bounds)
+            , m_radii(radii)
+        {
+        }
 
-    FloatRoundedRect m_bounds;
-    mutable FloatRoundedRect m_marginBounds;
-    mutable FloatRoundedRect m_paddingBounds;
+        float rx() const { return m_radii.width(); }
+        float ry() const { return m_radii.height(); }
+        ShapeBounds marginBounds(float shapeMargin) const;
+        ShapeBounds paddingBounds(float shapePadding) const;
+        FloatPoint cornerInterceptForWidth(float width) const;
+
+    private:
+        FloatSize m_radii;
+    };
+
+    ShapeBounds shapeMarginBounds() const;
+    ShapeBounds shapePaddingBounds() const;
+
+    ShapeBounds m_bounds;
+    mutable ShapeBounds m_marginBounds;
+    mutable ShapeBounds m_paddingBounds;
     mutable bool m_haveInitializedMarginBounds : 1;
     mutable bool m_haveInitializedPaddingBounds : 1;
 };
diff --git a/Source/core/rendering/shapes/Shape.h b/Source/core/rendering/shapes/Shape.h
index 790f6da..b88ede6 100644
--- a/Source/core/rendering/shapes/Shape.h
+++ b/Source/core/rendering/shapes/Shape.h
@@ -71,12 +71,21 @@
     virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const = 0;
     virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const = 0;
     virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const = 0;
+    bool lineOverlapsShapeMarginBounds(LayoutUnit lineTop, LayoutUnit lineHeight) const { return lineOverlapsBoundingBox(lineTop, lineHeight, shapeMarginLogicalBoundingBox()); }
+    bool lineOverlapsShapePaddingBounds(LayoutUnit lineTop, LayoutUnit lineHeight) const { return lineOverlapsBoundingBox(lineTop, lineHeight, shapePaddingLogicalBoundingBox()); }
 
 protected:
     float shapeMargin() const { return m_margin; }
     float shapePadding() const { return m_padding; }
 
 private:
+    bool lineOverlapsBoundingBox(LayoutUnit lineTop, LayoutUnit lineHeight, const LayoutRect& rect) const
+    {
+        if (rect.isEmpty())
+            return false;
+        return (lineTop < rect.maxY() && lineTop + lineHeight > rect.y()) || (!lineHeight && lineTop == rect.y());
+    }
+
     WritingMode m_writingMode;
     float m_margin;
     float m_padding;
diff --git a/Source/core/rendering/shapes/ShapeInfo.h b/Source/core/rendering/shapes/ShapeInfo.h
index 9f98160..ff78a1a 100644
--- a/Source/core/rendering/shapes/ShapeInfo.h
+++ b/Source/core/rendering/shapes/ShapeInfo.h
@@ -100,6 +100,7 @@
     void dirtyShapeSize() { m_shape.clear(); }
     bool shapeSizeDirty() { return !m_shape.get(); }
     const RenderType* owner() const { return m_renderer; }
+    LayoutSize shapeSize() const { return m_shapeLogicalSize; }
 
 protected:
     ShapeInfo(const RenderType* renderer): m_renderer(renderer) { }
diff --git a/Source/core/rendering/shapes/ShapeInsideInfo.h b/Source/core/rendering/shapes/ShapeInsideInfo.h
index 4d21306..0f0f385 100644
--- a/Source/core/rendering/shapes/ShapeInsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.h
@@ -96,8 +96,7 @@
 
     virtual bool lineOverlapsShapeBounds() const OVERRIDE
     {
-        // The <= test is to handle the case of a zero height line or a zero height shape.
-        return logicalLineTop() < shapeLogicalBottom() && shapeLogicalTop() <= logicalLineBottom();
+        return computedShape()->lineOverlapsShapePaddingBounds(m_shapeLineTop, m_lineHeight);
     }
 
 protected:
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
index 9925aef..ced8cde 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
@@ -56,17 +56,17 @@
 void ShapeOutsideInfo::updateDeltasForContainingBlockLine(const RenderBlockFlow* containingBlock, const FloatingObject* floatingObject, LayoutUnit lineTop, LayoutUnit lineHeight)
 {
     LayoutUnit shapeTop = containingBlock->logicalTopForFloat(floatingObject) + std::max(LayoutUnit(), containingBlock->marginBeforeForChild(m_renderer));
-    LayoutUnit lineTopInShapeCoordinates = lineTop - shapeTop + logicalTopOffset();
+    LayoutUnit floatRelativeLineTop = lineTop - shapeTop;
 
-    if (shapeSizeDirty() || m_lineTop != lineTopInShapeCoordinates || m_lineHeight != lineHeight) {
-        m_lineTop = lineTopInShapeCoordinates;
-        m_shapeLineTop = lineTopInShapeCoordinates - logicalTopOffset();
+    if (shapeSizeDirty() || m_lineTop != floatRelativeLineTop || m_lineHeight != lineHeight) {
+        m_lineTop = floatRelativeLineTop;
+        m_shapeLineTop = floatRelativeLineTop - logicalTopOffset();
         m_lineHeight = lineHeight;
 
         LayoutUnit floatMarginBoxWidth = containingBlock->logicalWidthForFloat(floatingObject);
 
         if (lineOverlapsShapeBounds()) {
-            SegmentList segments = computeSegmentsForLine(lineTopInShapeCoordinates, lineHeight);
+            SegmentList segments = computeSegmentsForLine(floatRelativeLineTop, lineHeight);
             if (segments.size()) {
                 LayoutUnit rawLeftMarginBoxDelta = segments.first().logicalLeft + containingBlock->marginStartForChild(m_renderer);
                 m_leftMarginBoxDelta = clampTo<LayoutUnit>(rawLeftMarginBoxDelta, LayoutUnit(), floatMarginBoxWidth);
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.h b/Source/core/rendering/shapes/ShapeOutsideInfo.h
index 2da8c1f..82b31f6 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.h
@@ -51,8 +51,7 @@
 
     virtual bool lineOverlapsShapeBounds() const OVERRIDE
     {
-        return (logicalLineTop() < shapeLogicalBottom() && shapeLogicalTop() < logicalLineBottom())
-            || logicalLineTop() == shapeLogicalTop(); // case of zero height line or zero height shape
+        return computedShape()->lineOverlapsShapeMarginBounds(m_shapeLineTop, m_lineHeight);
     }
 
 protected:
diff --git a/Source/core/rendering/style/BorderImageLength.h b/Source/core/rendering/style/BorderImageLength.h
new file mode 100644
index 0000000..a3a954f
--- /dev/null
+++ b/Source/core/rendering/style/BorderImageLength.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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 Opera Software ASA 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 BorderImageLength_h
+#define BorderImageLength_h
+
+#include "platform/Length.h"
+
+namespace WebCore {
+
+// Represents an individual computed border image width or outset.
+//
+// http://www.w3.org/TR/css3-background/#border-image-width
+// http://www.w3.org/TR/css3-background/#border-image-outset
+class BorderImageLength {
+public:
+    BorderImageLength(double number)
+        : m_length(Undefined)
+        , m_number(number)
+        , m_type(NumberType)
+    {
+    }
+
+    BorderImageLength(const Length& length)
+        : m_length(length)
+        , m_number(0)
+        , m_type(LengthType)
+    {
+    }
+
+    bool isNumber() const { return m_type == NumberType; }
+    bool isLength() const { return m_type == LengthType; }
+
+    const Length& length() const { ASSERT(isLength()); return m_length; }
+    Length& length() { ASSERT(isLength()); return m_length; }
+
+    double number() const { ASSERT(isNumber()); return m_number; }
+
+    bool operator==(const BorderImageLength& other) const
+    {
+        return m_type == other.m_type && m_length == other.m_length && m_number == other.m_number;
+    }
+
+    bool isZero() const
+    {
+        return (isLength() && m_length.isZero()) || (isNumber() && m_number);
+    }
+
+private:
+    // Ideally we would put the 2 following fields in a union, but Length has a constructor,
+    // a destructor and a copy assignment which isn't allowed.
+    Length m_length;
+    double m_number;
+    enum {
+        LengthType,
+        NumberType
+    } m_type;
+};
+
+} // namespace WebCore
+
+#endif // BorderImageLength_h
diff --git a/Source/core/rendering/style/BorderImageLengthBox.h b/Source/core/rendering/style/BorderImageLengthBox.h
new file mode 100644
index 0000000..436846a
--- /dev/null
+++ b/Source/core/rendering/style/BorderImageLengthBox.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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 Opera Software ASA 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 BorderImageLengthBox_h
+#define BorderImageLengthBox_h
+
+#include "core/rendering/style/BorderImageLength.h"
+
+namespace WebCore {
+
+// Represents a computed border image width or outset.
+//
+// http://www.w3.org/TR/css3-background/#border-image-width
+// http://www.w3.org/TR/css3-background/#border-image-outset
+class BorderImageLengthBox {
+public:
+    BorderImageLengthBox(Length length)
+        : m_left(length)
+        , m_right(length)
+        , m_top(length)
+        , m_bottom(length)
+    {
+    }
+
+    BorderImageLengthBox(double number)
+        : m_left(number)
+        , m_right(number)
+        , m_top(number)
+        , m_bottom(number)
+    {
+    }
+
+    BorderImageLengthBox(const BorderImageLength& top, const BorderImageLength& right,
+        const BorderImageLength& bottom, const BorderImageLength& left)
+        : m_left(left)
+        , m_right(right)
+        , m_top(top)
+        , m_bottom(bottom)
+    {
+    }
+
+    const BorderImageLength& left() const { return m_left; }
+    const BorderImageLength& right() const { return m_right; }
+    const BorderImageLength& top() const { return m_top; }
+    const BorderImageLength& bottom() const { return m_bottom; }
+
+    bool operator==(const BorderImageLengthBox& other) const
+    {
+        return m_left == other.m_left && m_right == other.m_right
+            && m_top == other.m_top && m_bottom == other.m_bottom;
+    }
+
+    bool operator!=(const BorderImageLengthBox& other) const
+    {
+        return !(*this == other);
+    }
+
+    bool nonZero() const
+    {
+        return !(m_left.isZero() && m_right.isZero() && m_top.isZero() && m_bottom.isZero());
+    }
+
+private:
+    BorderImageLength m_left;
+    BorderImageLength m_right;
+    BorderImageLength m_top;
+    BorderImageLength m_bottom;
+};
+
+} // namespace WebCore
+
+#endif // BorderImageLengthBox_h
diff --git a/Source/core/rendering/style/FillLayer.cpp b/Source/core/rendering/style/FillLayer.cpp
index fc784c8..c4b48bf 100644
--- a/Source/core/rendering/style/FillLayer.cpp
+++ b/Source/core/rendering/style/FillLayer.cpp
@@ -40,7 +40,7 @@
 
 COMPILE_ASSERT(sizeof(FillLayer) == sizeof(SameSizeAsFillLayer), FillLayer_should_stay_small);
 
-FillLayer::FillLayer(EFillLayerType type)
+FillLayer::FillLayer(EFillLayerType type, bool useInitialValues)
     : m_next(0)
     , m_image(FillLayer::initialFillImage(type))
     , m_xPosition(FillLayer::initialFillXPosition(type))
@@ -52,24 +52,24 @@
     , m_repeatX(FillLayer::initialFillRepeatX(type))
     , m_repeatY(FillLayer::initialFillRepeatY(type))
     , m_composite(FillLayer::initialFillComposite(type))
-    , m_sizeType(SizeNone) // SizeNone indicates size is unset.
+    , m_sizeType(useInitialValues ? FillLayer::initialFillSizeType(type) : SizeNone)
     , m_blendMode(FillLayer::initialFillBlendMode(type))
     , m_maskSourceType(FillLayer::initialFillMaskSourceType(type))
     , m_backgroundXOrigin(LeftEdge)
     , m_backgroundYOrigin(TopEdge)
-    , m_imageSet(false)
-    , m_attachmentSet(false)
-    , m_clipSet(false)
-    , m_originSet(false)
-    , m_repeatXSet(false)
-    , m_repeatYSet(false)
-    , m_xPosSet(false)
-    , m_yPosSet(false)
-    , m_backgroundXOriginSet(false)
-    , m_backgroundYOriginSet(false)
-    , m_compositeSet(type == MaskFillLayer)
-    , m_blendModeSet(false)
-    , m_maskSourceTypeSet(false)
+    , m_imageSet(useInitialValues)
+    , m_attachmentSet(useInitialValues)
+    , m_clipSet(useInitialValues)
+    , m_originSet(useInitialValues)
+    , m_repeatXSet(useInitialValues)
+    , m_repeatYSet(useInitialValues)
+    , m_xPosSet(useInitialValues)
+    , m_yPosSet(useInitialValues)
+    , m_backgroundXOriginSet(useInitialValues)
+    , m_backgroundYOriginSet(useInitialValues)
+    , m_compositeSet(useInitialValues || type == MaskFillLayer)
+    , m_blendModeSet(useInitialValues)
+    , m_maskSourceTypeSet(useInitialValues)
     , m_type(type)
 {
 }
diff --git a/Source/core/rendering/style/FillLayer.h b/Source/core/rendering/style/FillLayer.h
index b285d81..30101f8 100644
--- a/Source/core/rendering/style/FillLayer.h
+++ b/Source/core/rendering/style/FillLayer.h
@@ -62,7 +62,7 @@
 class FillLayer {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    FillLayer(EFillLayerType);
+    FillLayer(EFillLayerType, bool useInitialValues = false);
     ~FillLayer();
 
     StyleImage* image() const { return m_image.get(); }
diff --git a/Source/core/rendering/style/KeyframeList.cpp b/Source/core/rendering/style/KeyframeList.cpp
index a28da7e..2ed5836 100644
--- a/Source/core/rendering/style/KeyframeList.cpp
+++ b/Source/core/rendering/style/KeyframeList.cpp
@@ -42,15 +42,11 @@
     }
 }
 
-TimingFunction* KeyframeValue::timingFunction(const RenderStyle* keyframeStyle, const AtomicString& name)
+TimingFunction* KeyframeValue::timingFunction(const RenderStyle& keyframeStyle)
 {
-    ASSERT(keyframeStyle && keyframeStyle->animations());
-    for (size_t i = 0; i < keyframeStyle->animations()->size(); i++) {
-        if (name == keyframeStyle->animations()->animation(i)->name())
-            return keyframeStyle->animations()->animation(i)->timingFunction();
-    }
-    ASSERT_NOT_REACHED();
-    return 0;
+    const CSSAnimationDataList* animations = keyframeStyle.animations();
+    ASSERT(animations && !animations->isEmpty());
+    return animations->animation(0)->timingFunction();
 }
 
 KeyframeList::~KeyframeList()
@@ -64,25 +60,6 @@
     m_properties.clear();
 }
 
-bool KeyframeList::operator==(const KeyframeList& o) const
-{
-    if (m_keyframes.size() != o.m_keyframes.size())
-        return false;
-
-    Vector<KeyframeValue>::const_iterator it2 = o.m_keyframes.begin();
-    for (Vector<KeyframeValue>::const_iterator it1 = m_keyframes.begin(); it1 != m_keyframes.end(); ++it1) {
-        if (it1->key() != it2->key())
-            return false;
-        const RenderStyle& style1 = *it1->style();
-        const RenderStyle& style2 = *it2->style();
-        if (style1 != style2)
-            return false;
-        ++it2;
-    }
-
-    return true;
-}
-
 void KeyframeList::insert(const KeyframeValue& keyframe)
 {
     if (keyframe.key() < 0 || keyframe.key() > 1)
diff --git a/Source/core/rendering/style/KeyframeList.h b/Source/core/rendering/style/KeyframeList.h
index 792f1eb..ee2d237 100644
--- a/Source/core/rendering/style/KeyframeList.h
+++ b/Source/core/rendering/style/KeyframeList.h
@@ -58,7 +58,7 @@
     const RenderStyle* style() const { return m_style.get(); }
     void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
 
-    static TimingFunction* timingFunction(const RenderStyle*, const AtomicString& name);
+    static TimingFunction* timingFunction(const RenderStyle& keyframeStyle);
 
 private:
     double m_key;
@@ -68,7 +68,7 @@
 
 class KeyframeList {
 public:
-    KeyframeList(RenderObject*, const AtomicString& animationName)
+    KeyframeList(RenderObject&, const AtomicString& animationName)
         : m_animationName(animationName)
     {
         insert(KeyframeValue(0, 0));
@@ -76,9 +76,6 @@
     }
     ~KeyframeList();
 
-    bool operator==(const KeyframeList& o) const;
-    bool operator!=(const KeyframeList& o) const { return !(*this == o); }
-
     const AtomicString& animationName() const { return m_animationName; }
 
     void insert(const KeyframeValue& keyframe);
diff --git a/Source/core/rendering/style/NinePieceImage.cpp b/Source/core/rendering/style/NinePieceImage.cpp
index afe320e..383ca14 100644
--- a/Source/core/rendering/style/NinePieceImage.cpp
+++ b/Source/core/rendering/style/NinePieceImage.cpp
@@ -39,7 +39,7 @@
 {
 }
 
-NinePieceImage::NinePieceImage(PassRefPtr<StyleImage> image, LengthBox imageSlices, bool fill, LengthBox borderSlices, LengthBox outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule)
+NinePieceImage::NinePieceImage(PassRefPtr<StyleImage> image, LengthBox imageSlices, bool fill, const BorderImageLengthBox& borderSlices, const BorderImageLengthBox& outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule)
 {
     m_data.init();
     m_data.access()->image = image;
@@ -57,8 +57,8 @@
     , verticalRule(StretchImageRule)
     , image(0)
     , imageSlices(Length(100, Percent), Length(100, Percent), Length(100, Percent), Length(100, Percent))
-    , borderSlices(Length(1, Relative), Length(1, Relative), Length(1, Relative), Length(1, Relative))
-    , outset(0)
+    , borderSlices(1.0, 1.0, 1.0, 1.0)
+    , outset(Length(0, Fixed), Length(0, Fixed), Length(0, Fixed), Length(0, Fixed))
 {
 }
 
diff --git a/Source/core/rendering/style/NinePieceImage.h b/Source/core/rendering/style/NinePieceImage.h
index 3bf40c1..dd5ec09 100644
--- a/Source/core/rendering/style/NinePieceImage.h
+++ b/Source/core/rendering/style/NinePieceImage.h
@@ -24,6 +24,7 @@
 #ifndef NinePieceImage_h
 #define NinePieceImage_h
 
+#include "core/rendering/style/BorderImageLengthBox.h"
 #include "core/rendering/style/DataRef.h"
 #include "core/rendering/style/StyleImage.h"
 #include "platform/LayoutUnit.h"
@@ -48,8 +49,8 @@
     unsigned verticalRule : 2; // ENinePieceImageRule
     RefPtr<StyleImage> image;
     LengthBox imageSlices;
-    LengthBox borderSlices;
-    LengthBox outset;
+    BorderImageLengthBox borderSlices;
+    BorderImageLengthBox outset;
 
 private:
     NinePieceImageData();
@@ -59,7 +60,8 @@
 class NinePieceImage {
 public:
     NinePieceImage();
-    NinePieceImage(PassRefPtr<StyleImage>, LengthBox imageSlices, bool fill, LengthBox borderSlices, LengthBox outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule);
+    NinePieceImage(PassRefPtr<StyleImage>, LengthBox imageSlices, bool fill, const BorderImageLengthBox& borderSlices,
+        const BorderImageLengthBox& outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule);
 
     bool operator==(const NinePieceImage& other) const { return m_data == other.m_data; }
     bool operator!=(const NinePieceImage& other) const { return m_data != other.m_data; }
@@ -74,11 +76,11 @@
     bool fill() const { return m_data->fill; }
     void setFill(bool fill) { m_data.access()->fill = fill; }
 
-    const LengthBox& borderSlices() const { return m_data->borderSlices; }
-    void setBorderSlices(const LengthBox& slices) { m_data.access()->borderSlices = slices; }
+    const BorderImageLengthBox& borderSlices() const { return m_data->borderSlices; }
+    void setBorderSlices(const BorderImageLengthBox& slices) { m_data.access()->borderSlices = slices; }
 
-    const LengthBox& outset() const { return m_data->outset; }
-    void setOutset(const LengthBox& outset) { m_data.access()->outset = outset; }
+    const BorderImageLengthBox& outset() const { return m_data->outset; }
+    void setOutset(const BorderImageLengthBox& outset) { m_data.access()->outset = outset; }
 
     ENinePieceImageRule horizontalRule() const { return static_cast<ENinePieceImageRule>(m_data->horizontalRule); }
     void setHorizontalRule(ENinePieceImageRule rule) { m_data.access()->horizontalRule = rule; }
@@ -112,14 +114,14 @@
     {
         m_data.access()->imageSlices = LengthBox(0);
         m_data.access()->fill = true;
-        m_data.access()->borderSlices = LengthBox();
+        m_data.access()->borderSlices = BorderImageLengthBox(Length(Auto));
     }
 
-    static LayoutUnit computeOutset(Length outsetSide, LayoutUnit borderSide)
+    static LayoutUnit computeOutset(const BorderImageLength& outsetSide, LayoutUnit borderSide)
     {
-        if (outsetSide.isRelative())
-            return outsetSide.value() * borderSide;
-        return outsetSide.value();
+        if (outsetSide.isNumber())
+            return outsetSide.number() * borderSide;
+        return outsetSide.length().value();
     }
 
 private:
diff --git a/Source/core/rendering/style/RenderStyle.cpp b/Source/core/rendering/style/RenderStyle.cpp
index c7e0870..e812ea9 100644
--- a/Source/core/rendering/style/RenderStyle.cpp
+++ b/Source/core/rendering/style/RenderStyle.cpp
@@ -69,7 +69,7 @@
 
 inline RenderStyle* defaultStyle()
 {
-    static RenderStyle* s_defaultStyle = RenderStyle::createDefaultStyle().leakRef();
+    DEFINE_STATIC_REF(RenderStyle, s_defaultStyle, (RenderStyle::createDefaultStyle()));
     return s_defaultStyle;
 }
 
@@ -260,30 +260,6 @@
     return this != StyleResolver::styleNotYetAvailable();
 }
 
-static inline int pseudoBit(PseudoId pseudo)
-{
-    return 1 << (pseudo - 1);
-}
-
-bool RenderStyle::hasAnyPublicPseudoStyles() const
-{
-    return PUBLIC_PSEUDOID_MASK & noninherited_flags._pseudoBits;
-}
-
-bool RenderStyle::hasPseudoStyle(PseudoId pseudo) const
-{
-    ASSERT(pseudo > NOPSEUDO);
-    ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
-    return pseudoBit(pseudo) & noninherited_flags._pseudoBits;
-}
-
-void RenderStyle::setHasPseudoStyle(PseudoId pseudo)
-{
-    ASSERT(pseudo > NOPSEUDO);
-    ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
-    noninherited_flags._pseudoBits |= pseudoBit(pseudo);
-}
-
 bool RenderStyle::hasUniquePseudoStyle() const
 {
     if (!m_cachedPseudoStyles || styleType() != NOPSEUDO)
@@ -859,6 +835,13 @@
         rareNonInheritedData.access()->m_isolation = v;
 }
 
+bool RenderStyle::hasIsolation() const
+{
+    if (RuntimeEnabledFeatures::cssCompositingEnabled())
+        return rareNonInheritedData->m_isolation != IsolationAuto;
+    return false;
+}
+
 inline bool requireTransformOrigin(const Vector<RefPtr<TransformOperation> >& transformOperations, RenderStyle::ApplyTransformOrigin applyOrigin)
 {
     // transform-origin brackets the transform with translate operations.
@@ -869,7 +852,7 @@
 
     unsigned size = transformOperations.size();
     for (unsigned i = 0; i < size; ++i) {
-        TransformOperation::OperationType type = transformOperations[i]->getOperationType();
+        TransformOperation::OperationType type = transformOperations[i]->type();
         if (type != TransformOperation::TranslateX
             && type != TransformOperation::TranslateY
             && type != TransformOperation::Translate
@@ -1611,14 +1594,14 @@
     surround.access()->border.m_image.setImageSlices(slices);
 }
 
-void RenderStyle::setBorderImageWidth(LengthBox slices)
+void RenderStyle::setBorderImageWidth(const BorderImageLengthBox& slices)
 {
     if (surround->border.m_image.borderSlices() == slices)
         return;
     surround.access()->border.m_image.setBorderSlices(slices);
 }
 
-void RenderStyle::setBorderImageOutset(LengthBox outset)
+void RenderStyle::setBorderImageOutset(const BorderImageLengthBox& outset)
 {
     if (surround->border.m_image.outset() == outset)
         return;
@@ -1627,8 +1610,8 @@
 
 ShapeValue* RenderStyle::initialShapeInside()
 {
-    DEFINE_STATIC_LOCAL(RefPtr<ShapeValue>, sOutsideValue, (ShapeValue::createOutsideValue()));
-    return sOutsideValue.get();
+    DEFINE_STATIC_REF(ShapeValue, sOutsideValue, (ShapeValue::createOutsideValue()));
+    return sOutsideValue;
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index 2f7ede4..413bd25 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -29,7 +29,6 @@
 #include "core/css/CSSLengthFunctions.h"
 #include "core/css/CSSLineBoxContainValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/platform/ThemeTypes.h"
 #include "core/platform/animation/CSSAnimationDataList.h"
 #include "core/rendering/style/BorderValue.h"
 #include "core/rendering/style/CounterDirectives.h"
@@ -59,6 +58,7 @@
 #include "platform/Length.h"
 #include "platform/LengthBox.h"
 #include "platform/LengthSize.h"
+#include "platform/ThemeTypes.h"
 #include "platform/fonts/FontBaseline.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/geometry/LayoutBoxExtent.h"
@@ -210,6 +210,7 @@
                 && _page_break_after == other._page_break_after
                 && _page_break_inside == other._page_break_inside
                 && _styleType == other._styleType
+                && _affectedByFocus == other._affectedByFocus
                 && _affectedByHover == other._affectedByHover
                 && _affectedByActive == other._affectedByActive
                 && _affectedByDrag == other._affectedByDrag
@@ -251,6 +252,8 @@
         unsigned firstChildState : 1;
         unsigned lastChildState : 1;
 
+        bool affectedByFocus() const { return _affectedByFocus; }
+        void setAffectedByFocus(bool value) { _affectedByFocus = value; }
         bool affectedByHover() const { return _affectedByHover; }
         void setAffectedByHover(bool value) { _affectedByHover = value; }
         bool affectedByActive() const { return _affectedByActive; }
@@ -260,12 +263,13 @@
         bool isLink() const { return _isLink; }
         void setIsLink(bool value) { _isLink = value; }
     private:
+        unsigned _affectedByFocus : 1;
         unsigned _affectedByHover : 1;
         unsigned _affectedByActive : 1;
         unsigned _affectedByDrag : 1;
         unsigned _isLink : 1;
         // If you add more style bits here, you will also need to update RenderStyle::copyNonInheritedFrom()
-        // 61 bits
+        // 60 bits
     } noninherited_flags;
 
 // !END SYNC!
@@ -312,6 +316,7 @@
         noninherited_flags.emptyState = false;
         noninherited_flags.firstChildState = false;
         noninherited_flags.lastChildState = false;
+        noninherited_flags.setAffectedByFocus(false);
         noninherited_flags.setAffectedByHover(false);
         noninherited_flags.setAffectedByActive(false);
         noninherited_flags.setAffectedByDrag(false);
@@ -355,10 +360,12 @@
     void setVariable(const AtomicString& name, const String& value) { rareInheritedData.access()->m_variables.access()->setVariable(name, value); }
     const HashMap<AtomicString, String>* variables() { return &(rareInheritedData->m_variables->m_data); }
 
+    bool affectedByFocus() const { return noninherited_flags.affectedByFocus(); }
     bool affectedByHover() const { return noninherited_flags.affectedByHover(); }
     bool affectedByActive() const { return noninherited_flags.affectedByActive(); }
     bool affectedByDrag() const { return noninherited_flags.affectedByDrag(); }
 
+    void setAffectedByFocus() { noninherited_flags.setAffectedByFocus(true); }
     void setAffectedByHover() { noninherited_flags.setAffectedByHover(true); }
     void setAffectedByActive() { noninherited_flags.setAffectedByActive(true); }
     void setAffectedByDrag() { noninherited_flags.setAffectedByDrag(true); }
@@ -473,8 +480,8 @@
     const NinePieceImage& borderImage() const { return surround->border.image(); }
     StyleImage* borderImageSource() const { return surround->border.image().image(); }
     LengthBox borderImageSlices() const { return surround->border.image().imageSlices(); }
-    LengthBox borderImageWidth() const { return surround->border.image().borderSlices(); }
-    LengthBox borderImageOutset() const { return surround->border.image().outset(); }
+    const BorderImageLengthBox& borderImageWidth() const { return surround->border.image().borderSlices(); }
+    const BorderImageLengthBox& borderImageOutset() const { return surround->border.image().outset(); }
 
     LengthSize borderTopLeftRadius() const { return surround->border.topLeft(); }
     LengthSize borderTopRightRadius() const { return surround->border.topRight(); }
@@ -648,8 +655,8 @@
     StyleImage* maskBoxImageSource() const { return rareNonInheritedData->m_maskBoxImage.image(); }
     LengthBox maskBoxImageSlices() const { return rareNonInheritedData->m_maskBoxImage.imageSlices(); }
     bool maskBoxImageSlicesFill() const { return rareNonInheritedData->m_maskBoxImage.fill(); }
-    LengthBox maskBoxImageWidth() const { return rareNonInheritedData->m_maskBoxImage.borderSlices(); }
-    LengthBox maskBoxImageOutset() const { return rareNonInheritedData->m_maskBoxImage.outset(); }
+    const BorderImageLengthBox& maskBoxImageWidth() const { return rareNonInheritedData->m_maskBoxImage.borderSlices(); }
+    const BorderImageLengthBox& maskBoxImageOutset() const { return rareNonInheritedData->m_maskBoxImage.outset(); }
 
     EBorderCollapse borderCollapse() const { return static_cast<EBorderCollapse>(inherited_flags._border_collapse); }
     short horizontalBorderSpacing() const;
@@ -917,6 +924,7 @@
 
     EIsolation isolation() const;
     void setIsolation(EIsolation v);
+    bool hasIsolation() const;
 
     bool shouldPlaceBlockDirectionScrollbarOnLogicalLeft() const { return !isLeftToRightDirection() && isHorizontalWritingMode(); }
 
@@ -986,8 +994,8 @@
     void setBorderImage(const NinePieceImage& b) { SET_VAR(surround, border.m_image, b); }
     void setBorderImageSource(PassRefPtr<StyleImage>);
     void setBorderImageSlices(LengthBox);
-    void setBorderImageWidth(LengthBox);
-    void setBorderImageOutset(LengthBox);
+    void setBorderImageWidth(const BorderImageLengthBox&);
+    void setBorderImageOutset(const BorderImageLengthBox&);
 
     void setBorderTopLeftRadius(LengthSize s) { SET_VAR(surround, border.m_topLeft, s); }
     void setBorderTopRightRadius(LengthSize s) { SET_VAR(surround, border.m_topRight, s); }
@@ -1118,11 +1126,11 @@
     {
         rareNonInheritedData.access()->m_maskBoxImage.setFill(fill);
     }
-    void setMaskBoxImageWidth(LengthBox slices)
+    void setMaskBoxImageWidth(const BorderImageLengthBox& slices)
     {
         rareNonInheritedData.access()->m_maskBoxImage.setBorderSlices(slices);
     }
-    void setMaskBoxImageOutset(LengthBox outset)
+    void setMaskBoxImageOutset(const BorderImageLengthBox& outset)
     {
         rareNonInheritedData.access()->m_maskBoxImage.setOutset(outset);
     }
@@ -1779,14 +1787,14 @@
     return roundForImpreciseConversion<int>(value / zoomFactor);
 }
 
-inline float adjustFloatForAbsoluteZoom(float value, const RenderStyle* style)
+inline float adjustFloatForAbsoluteZoom(float value, const RenderStyle& style)
 {
-    return value / style->effectiveZoom();
+    return value / style.effectiveZoom();
 }
 
-inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, const RenderStyle* style)
+inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, const RenderStyle& style)
 {
-    return value / style->effectiveZoom();
+    return value / style.effectiveZoom();
 }
 
 inline bool RenderStyle::setZoom(float f)
@@ -1826,6 +1834,25 @@
     return true;
 }
 
+inline bool RenderStyle::hasAnyPublicPseudoStyles() const
+{
+    return PUBLIC_PSEUDOID_MASK & noninherited_flags._pseudoBits;
+}
+
+inline bool RenderStyle::hasPseudoStyle(PseudoId pseudo) const
+{
+    ASSERT(pseudo > NOPSEUDO);
+    ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
+    return (1 << (pseudo - 1)) & noninherited_flags._pseudoBits;
+}
+
+inline void RenderStyle::setHasPseudoStyle(PseudoId pseudo)
+{
+    ASSERT(pseudo > NOPSEUDO);
+    ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
+    noninherited_flags._pseudoBits |= 1 << (pseudo - 1);
+}
+
 } // namespace WebCore
 
 #endif // RenderStyle_h
diff --git a/Source/core/rendering/style/RenderStyleConstants.h b/Source/core/rendering/style/RenderStyleConstants.h
index 359bd55..04d96a1 100644
--- a/Source/core/rendering/style/RenderStyleConstants.h
+++ b/Source/core/rendering/style/RenderStyleConstants.h
@@ -379,7 +379,8 @@
 
 enum TextUnderlinePosition {
     // FIXME: Implement support for 'under left' and 'under right' values.
-    TextUnderlinePositionAuto = 0x1, TextUnderlinePositionAlphabetic = 0x2, TextUnderlinePositionUnder = 0x4
+    TextUnderlinePositionAuto = 0x1,
+    TextUnderlinePositionUnder = 0x2
 };
 
 enum EPageBreak {
diff --git a/Source/core/rendering/style/SVGRenderStyle.cpp b/Source/core/rendering/style/SVGRenderStyle.cpp
index 7d7498a..c273e16 100644
--- a/Source/core/rendering/style/SVGRenderStyle.cpp
+++ b/Source/core/rendering/style/SVGRenderStyle.cpp
@@ -209,7 +209,8 @@
         || svg_inherited_flags._clipRule != other->svg_inherited_flags._clipRule
         || svg_inherited_flags._fillRule != other->svg_inherited_flags._fillRule
         || svg_inherited_flags._colorInterpolation != other->svg_inherited_flags._colorInterpolation
-        || svg_inherited_flags._colorInterpolationFilters != other->svg_inherited_flags._colorInterpolationFilters)
+        || svg_inherited_flags._colorInterpolationFilters != other->svg_inherited_flags._colorInterpolationFilters
+        || svg_inherited_flags._paintOrder != other->svg_inherited_flags._paintOrder)
         return StyleDifferenceRepaint;
 
     if (svg_noninherited_flags.f.bufferedRendering != other->svg_noninherited_flags.f.bufferedRendering)
diff --git a/Source/core/rendering/style/StyleBackgroundData.cpp b/Source/core/rendering/style/StyleBackgroundData.cpp
index 8c4261e..d0b7ba4 100644
--- a/Source/core/rendering/style/StyleBackgroundData.cpp
+++ b/Source/core/rendering/style/StyleBackgroundData.cpp
@@ -28,7 +28,7 @@
 namespace WebCore {
 
 StyleBackgroundData::StyleBackgroundData()
-    : m_background(BackgroundFillLayer)
+    : m_background(BackgroundFillLayer, true)
     , m_color(RenderStyle::initialBackgroundColor())
 {
 }
diff --git a/Source/core/rendering/style/StyleCustomFilterProgram.h b/Source/core/rendering/style/StyleCustomFilterProgram.h
index 5166998..acbc73f 100644
--- a/Source/core/rendering/style/StyleCustomFilterProgram.h
+++ b/Source/core/rendering/style/StyleCustomFilterProgram.h
@@ -35,7 +35,7 @@
 #include "core/fetch/ShaderResource.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 #include "core/rendering/style/StyleShader.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/FastAllocBase.h"
 
 namespace WebCore {
diff --git a/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp b/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
index fb4c011..0aa8b1a 100644
--- a/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
+++ b/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
@@ -31,8 +31,8 @@
 
 #include "core/rendering/style/StyleCustomFilterProgramCache.h"
 
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "core/rendering/style/StyleCustomFilterProgram.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 
 namespace WebCore {
 
@@ -77,7 +77,7 @@
 void StyleCustomFilterProgramCache::remove(StyleCustomFilterProgram* program)
 {
     CacheMap::iterator iter = m_cache.find(programCacheKey(program));
-    ASSERT(iter != m_cache.end());
+    ASSERT_WITH_SECURITY_IMPLICATION(iter != m_cache.end());
     m_cache.remove(iter);
 }
 
diff --git a/Source/core/rendering/style/StyleCustomFilterProgramCache.h b/Source/core/rendering/style/StyleCustomFilterProgramCache.h
index bfd1610..2bc1652 100644
--- a/Source/core/rendering/style/StyleCustomFilterProgramCache.h
+++ b/Source/core/rendering/style/StyleCustomFilterProgramCache.h
@@ -30,7 +30,7 @@
 #ifndef StyleCustomFilterProgramCache_h
 #define StyleCustomFilterProgramCache_h
 
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
 #include "wtf/FastAllocBase.h"
 #include "wtf/HashMap.h"
 
diff --git a/Source/core/rendering/style/StyleFetchedImage.h b/Source/core/rendering/style/StyleFetchedImage.h
index 9ea82f5..e783439 100644
--- a/Source/core/rendering/style/StyleFetchedImage.h
+++ b/Source/core/rendering/style/StyleFetchedImage.h
@@ -63,5 +63,7 @@
     ResourcePtr<ImageResource> m_image;
 };
 
+DEFINE_STYLE_IMAGE_TYPE_CASTS(StyleFetchedImage, isImageResource());
+
 }
 #endif
diff --git a/Source/core/rendering/style/StyleFetchedImageSet.h b/Source/core/rendering/style/StyleFetchedImageSet.h
index c618047..873c142 100644
--- a/Source/core/rendering/style/StyleFetchedImageSet.h
+++ b/Source/core/rendering/style/StyleFetchedImageSet.h
@@ -80,6 +80,8 @@
     CSSImageSetValue* m_imageSetValue; // Not retained; it owns us.
 };
 
+DEFINE_STYLE_IMAGE_TYPE_CASTS(StyleFetchedImageSet, isImageResourceSet());
+
 } // namespace WebCore
 
 #endif // StyleFetchedImageSet_h
diff --git a/Source/core/rendering/style/StyleImage.h b/Source/core/rendering/style/StyleImage.h
index 27bd826..c302ebb 100644
--- a/Source/core/rendering/style/StyleImage.h
+++ b/Source/core/rendering/style/StyleImage.h
@@ -97,5 +97,10 @@
     bool m_isImageResourceSet:1;
 };
 
+#define DEFINE_STYLE_IMAGE_TYPE_CASTS(thisType, function) \
+    DEFINE_TYPE_CASTS(thisType, StyleImage, styleImage, styleImage->function, styleImage.function); \
+    inline thisType* to##thisType(const RefPtr<StyleImage>& styleImage) { return to##thisType(styleImage.get()); } \
+    typedef int NeedsSemiColonAfterDefineStyleImageTypeCasts
+
 }
 #endif
diff --git a/Source/core/rendering/style/StylePendingImage.h b/Source/core/rendering/style/StylePendingImage.h
index f9a00bc..a518886 100644
--- a/Source/core/rendering/style/StylePendingImage.h
+++ b/Source/core/rendering/style/StylePendingImage.h
@@ -76,5 +76,7 @@
     CSSValue* m_value; // Not retained; it owns us.
 };
 
+DEFINE_STYLE_IMAGE_TYPE_CASTS(StylePendingImage, isPendingImage());
+
 }
 #endif
diff --git a/Source/core/rendering/style/StyleRareInheritedData.h b/Source/core/rendering/style/StyleRareInheritedData.h
index 5234762..11d3c4b 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.h
+++ b/Source/core/rendering/style/StyleRareInheritedData.h
@@ -101,7 +101,7 @@
     unsigned m_imageRendering : 2; // EImageRendering
     unsigned m_lineSnap : 2; // LineSnap
     unsigned m_lineAlign : 1; // LineAlign
-    unsigned m_textUnderlinePosition : 3; // TextUnderlinePosition
+    unsigned m_textUnderlinePosition : 2; // TextUnderlinePosition
     unsigned m_rubyPosition : 1; // RubyPosition
     unsigned m_touchActionDelay : 1; // TouchActionDelay
 
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.cpp b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
index 66ef53e..2d31278 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
@@ -27,6 +27,7 @@
 #include "core/rendering/style/ShadowList.h"
 #include "core/rendering/style/StyleFilterData.h"
 #include "core/rendering/style/StyleTransformData.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
 
 namespace WebCore {
 
@@ -39,7 +40,7 @@
     , m_perspectiveOriginY(RenderStyle::initialPerspectiveOriginY())
     , lineClamp(RenderStyle::initialLineClamp())
     , m_draggableRegionMode(DraggableRegionNone)
-    , m_mask(FillLayer(MaskFillLayer))
+    , m_mask(MaskFillLayer, true)
     , m_pageSize()
     , m_shapeInside(RenderStyle::initialShapeInside())
     , m_shapeOutside(RenderStyle::initialShapeOutside())
@@ -160,6 +161,9 @@
 
 StyleRareNonInheritedData::~StyleRareNonInheritedData()
 {
+    const FilterOperations& filterOperations = m_filter->m_operations;
+    for (unsigned i = 0; i < filterOperations.size(); ++i)
+        ReferenceFilterBuilder::clearDocumentResourceReference(filterOperations.at(i));
 }
 
 bool StyleRareNonInheritedData::operator==(const StyleRareNonInheritedData& o) const
diff --git a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
index e9c656c..89d6eb2 100644
--- a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
+++ b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
@@ -34,7 +34,6 @@
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/dom/Element.h"
 #include "core/fetch/DocumentResource.h"
-#include "core/fetch/DocumentResourceReference.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
 #include "core/platform/graphics/filters/SourceAlpha.h"
 #include "core/rendering/svg/RenderSVGResourceFilter.h"
@@ -44,6 +43,31 @@
 
 namespace WebCore {
 
+HashMap<const FilterOperation*, OwnPtr<DocumentResourceReference> >* ReferenceFilterBuilder::documentResourceReferences = 0;
+
+DocumentResourceReference* ReferenceFilterBuilder::documentResourceReference(const FilterOperation* filterOperation)
+{
+    if (!documentResourceReferences)
+        return 0;
+
+    return documentResourceReferences->get(filterOperation);
+}
+
+void ReferenceFilterBuilder::setDocumentResourceReference(const FilterOperation* filterOperation, PassOwnPtr<DocumentResourceReference> documentResourceReference)
+{
+    if (!documentResourceReferences)
+        documentResourceReferences = new HashMap<const FilterOperation*, OwnPtr<DocumentResourceReference> >;
+    documentResourceReferences->add(filterOperation, documentResourceReference);
+}
+
+void ReferenceFilterBuilder::clearDocumentResourceReference(const FilterOperation* filterOperation)
+{
+    if (!documentResourceReferences)
+        return;
+
+    documentResourceReferences->remove(filterOperation);
+}
+
 // Returns whether or not the SVGElement object contains a valid color-interpolation-filters attribute
 static bool getSVGElementColorSpace(SVGElement* svgElement, ColorSpace& cs)
 {
@@ -91,13 +115,14 @@
 
     Document* document = &renderer->document();
 
-    DocumentResourceReference* documentResourceReference = filterOperation->documentResourceReference();
-    DocumentResource* cachedSVGDocument = documentResourceReference ? documentResourceReference->document() : 0;
+    if (DocumentResourceReference* documentResourceRef = documentResourceReference(filterOperation)) {
+        DocumentResource* cachedSVGDocument = documentResourceRef->document();
 
-    // If we have an SVG document, this is an external reference. Otherwise
-    // we look up the referenced node in the current document.
-    if (cachedSVGDocument)
-        document = cachedSVGDocument->document();
+        // If we have an SVG document, this is an external reference. Otherwise
+        // we look up the referenced node in the current document.
+        if (cachedSVGDocument)
+            document = cachedSVGDocument->document();
+    }
 
     if (!document)
         return 0;
diff --git a/Source/core/rendering/svg/ReferenceFilterBuilder.h b/Source/core/rendering/svg/ReferenceFilterBuilder.h
index 9cc113a..e158a4f 100644
--- a/Source/core/rendering/svg/ReferenceFilterBuilder.h
+++ b/Source/core/rendering/svg/ReferenceFilterBuilder.h
@@ -31,19 +31,29 @@
 #ifndef ReferenceFilterBuilder_h
 #define ReferenceFilterBuilder_h
 
+#include "core/fetch/DocumentResourceReference.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
+#include "wtf/HashMap.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
 class Filter;
 class FilterEffect;
+class FilterOperation;
 class ReferenceFilterOperation;
 class RenderObject;
 
 class ReferenceFilterBuilder {
 public:
+    static DocumentResourceReference* documentResourceReference(const FilterOperation*);
+    static void setDocumentResourceReference(const FilterOperation*, PassOwnPtr<DocumentResourceReference>);
+    static void clearDocumentResourceReference(const FilterOperation*);
+
     static PassRefPtr<FilterEffect> build(Filter*, RenderObject* renderer, FilterEffect* previousEffect, const ReferenceFilterOperation*);
+
+private:
+    static HashMap<const FilterOperation*, OwnPtr<DocumentResourceReference> >* documentResourceReferences;
 };
 
 }
diff --git a/Source/core/rendering/svg/RenderSVGBlock.cpp b/Source/core/rendering/svg/RenderSVGBlock.cpp
index 7ce9ad6..ab40394 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.cpp
+++ b/Source/core/rendering/svg/RenderSVGBlock.cpp
@@ -44,21 +44,6 @@
     return borderRect;
 }
 
-void RenderSVGBlock::setStyle(PassRefPtr<RenderStyle> style)
-{
-    RefPtr<RenderStyle> useStyle = style;
-
-    // SVG text layout code expects us to be a block-level style element.
-    if (useStyle->isDisplayInlineType()) {
-        RefPtr<RenderStyle> newStyle = RenderStyle::create();
-        newStyle->inheritFrom(useStyle.get());
-        newStyle->setDisplay(BLOCK);
-        useStyle = newStyle.release();
-    }
-
-    RenderBlock::setStyle(useStyle.release());
-}
-
 void RenderSVGBlock::updateFromStyle()
 {
     RenderBlock::updateFromStyle();
@@ -87,7 +72,7 @@
 void RenderSVGBlock::willBeDestroyed()
 {
     SVGResourcesCache::clientDestroyed(this);
-    RenderBlock::willBeDestroyed();
+    RenderBlockFlow::willBeDestroyed();
 }
 
 void RenderSVGBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
diff --git a/Source/core/rendering/svg/RenderSVGBlock.h b/Source/core/rendering/svg/RenderSVGBlock.h
index 1d638cc..6f08eb1 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.h
+++ b/Source/core/rendering/svg/RenderSVGBlock.h
@@ -36,7 +36,6 @@
     virtual void willBeDestroyed() OVERRIDE;
 
 private:
-    virtual void setStyle(PassRefPtr<RenderStyle>) OVERRIDE FINAL;
     virtual void updateFromStyle() OVERRIDE FINAL;
 
     virtual bool isRenderSVGBlock() const OVERRIDE FINAL { return true; };
diff --git a/Source/core/rendering/svg/RenderSVGContainer.cpp b/Source/core/rendering/svg/RenderSVGContainer.cpp
index ee869d9..1cccfb2 100644
--- a/Source/core/rendering/svg/RenderSVGContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGContainer.cpp
@@ -27,6 +27,7 @@
 
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/svg/SVGRenderingContext.h"
@@ -53,6 +54,7 @@
     // RenderSVGRoot disables layoutState for the SVG rendering tree.
     ASSERT(!view()->layoutStateEnabled());
 
+    LayoutRectRecorder recorder(*this);
     LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) || selfWillPaint());
 
     // Allow RenderSVGViewportContainer to update its viewport.
diff --git a/Source/core/rendering/svg/RenderSVGForeignObject.cpp b/Source/core/rendering/svg/RenderSVGForeignObject.cpp
index 2506ee4..92511f0 100644
--- a/Source/core/rendering/svg/RenderSVGForeignObject.cpp
+++ b/Source/core/rendering/svg/RenderSVGForeignObject.cpp
@@ -25,6 +25,7 @@
 
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/svg/SVGRenderSupport.h"
@@ -122,6 +123,7 @@
     ASSERT(needsLayout());
     ASSERT(!view()->layoutStateEnabled()); // RenderSVGRoot disables layoutState for the SVG rendering tree.
 
+    LayoutRectRecorder recorder(*this);
     LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this));
     SVGForeignObjectElement* foreign = toSVGForeignObjectElement(node());
 
diff --git a/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp b/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
index 08ce4ad..0f15789 100644
--- a/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
@@ -21,6 +21,8 @@
 
 #include "core/rendering/svg/RenderSVGHiddenContainer.h"
 
+#include "core/rendering/LayoutRectRecorder.h"
+
 namespace WebCore {
 
 RenderSVGHiddenContainer::RenderSVGHiddenContainer(SVGElement* element)
@@ -31,6 +33,7 @@
 void RenderSVGHiddenContainer::layout()
 {
     ASSERT(needsLayout());
+    LayoutRectRecorder recorder(*this);
     SVGRenderSupport::layoutChildren(this, selfNeedsLayout());
     updateCachedBoundaries();
     clearNeedsLayout();
diff --git a/Source/core/rendering/svg/RenderSVGImage.cpp b/Source/core/rendering/svg/RenderSVGImage.cpp
index 2b4c679..9ad1a9a 100644
--- a/Source/core/rendering/svg/RenderSVGImage.cpp
+++ b/Source/core/rendering/svg/RenderSVGImage.cpp
@@ -30,6 +30,7 @@
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/ImageQualityController.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/PointerEventsHitRules.h"
 #include "core/rendering/RenderImageResource.h"
@@ -92,6 +93,7 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
     LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) && selfNeedsLayout());
     updateImageViewport();
 
diff --git a/Source/core/rendering/svg/RenderSVGModelObject.cpp b/Source/core/rendering/svg/RenderSVGModelObject.cpp
index 56312a7..12da706 100644
--- a/Source/core/rendering/svg/RenderSVGModelObject.cpp
+++ b/Source/core/rendering/svg/RenderSVGModelObject.cpp
@@ -35,7 +35,7 @@
 #include "SVGNames.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/rendering/svg/SVGResourcesCache.h"
-#include "core/svg/SVGElement.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
@@ -123,12 +123,12 @@
     return false;
 }
 
-static void getElementCTM(SVGElement* element, AffineTransform& transform)
+static void getElementCTM(SVGGraphicsElement* element, AffineTransform& transform)
 {
     ASSERT(element);
     element->document().updateLayoutIgnorePendingStylesheets();
 
-    SVGElement* stopAtElement = SVGLocatable::nearestViewportElement(element);
+    SVGElement* stopAtElement = element->nearestViewportElement();
     ASSERT(stopAtElement);
 
     AffineTransform localTransform;
@@ -182,7 +182,7 @@
     if (!isGraphicsElement(renderer))
         return false;
     AffineTransform ctm;
-    SVGElement* svgElement = toSVGElement(renderer->node());
+    SVGGraphicsElement* svgElement = toSVGGraphicsElement(renderer->node());
     getElementCTM(svgElement, ctm);
     ASSERT(svgElement->renderer());
     return intersectsAllowingEmpty(rect, ctm.mapRect(svgElement->renderer()->repaintRectInLocalCoordinates()));
@@ -195,7 +195,7 @@
     if (!isGraphicsElement(renderer))
         return false;
     AffineTransform ctm;
-    SVGElement* svgElement = toSVGElement(renderer->node());
+    SVGGraphicsElement* svgElement = toSVGGraphicsElement(renderer->node());
     getElementCTM(svgElement, ctm);
     ASSERT(svgElement->renderer());
     return rect.contains(ctm.mapRect(svgElement->renderer()->repaintRectInLocalCoordinates()));
diff --git a/Source/core/rendering/svg/RenderSVGResource.h b/Source/core/rendering/svg/RenderSVGResource.h
index 314a69e..676562d 100644
--- a/Source/core/rendering/svg/RenderSVGResource.h
+++ b/Source/core/rendering/svg/RenderSVGResource.h
@@ -82,6 +82,9 @@
     static void markForLayoutAndParentResourceInvalidation(RenderObject*, bool needsLayout = true);
 };
 
+#define DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(thisType, typeName) \
+    DEFINE_TYPE_CASTS(thisType, RenderSVGResource, resource, resource->resourceType() == typeName, resource.resourceType() == typeName)
+
 }
 
 #endif
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index c115bb9..9344e70 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -76,6 +76,8 @@
     ASSERT(object);
     ASSERT(context);
 
+    clearInvalidationMask();
+
     return applyClippingToContext(object, object->objectBoundingBox(), object->repaintRectInLocalCoordinates(), context, clipperContext);
 }
 
@@ -146,6 +148,7 @@
     const FloatRect& repaintRect, GraphicsContext* context, ClipperContext& clipperContext)
 {
     ASSERT(target);
+    ASSERT(target->node());
     ASSERT(context);
     ASSERT(clipperContext.state == ClipperContext::NotAppliedState);
     ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
@@ -154,8 +157,17 @@
         return false;
     TemporaryChange<bool> inClipExpansionChange(m_inClipExpansion, true);
 
-    // First, try to apply the clip as a clipPath.
     AffineTransform animatedLocalTransform = toSVGClipPathElement(element())->animatedLocalTransform();
+    // When drawing a clip for non-SVG elements, the CTM does not include the zoom factor.
+    // In this case, we need to apply the zoom scale explicitly - but only for clips with
+    // userSpaceOnUse units (the zoom is accounted for objectBoundingBox-resolved lengths).
+    if (!target->node()->isSVGElement()
+        && toSVGClipPathElement(element())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE) {
+        ASSERT(style());
+        animatedLocalTransform.scale(style()->effectiveZoom());
+    }
+
+    // First, try to apply the clip as a clipPath.
     if (tryPathOnlyClipping(context, animatedLocalTransform, targetBoundingBox)) {
         clipperContext.state = ClipperContext::AppliedPathState;
         return true;
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.h b/Source/core/rendering/svg/RenderSVGResourceClipper.h
index 38fb13f..ae89b1e 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.h
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.h
@@ -86,11 +86,7 @@
     bool m_inClipExpansion;
 };
 
-inline RenderSVGResourceClipper* toRenderSVGResourceClipper(RenderSVGResource* resource)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == ClipperResourceType);
-    return static_cast<RenderSVGResourceClipper*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceClipper, ClipperResourceType);
 
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
index 6280a41..61c783d 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
@@ -21,6 +21,7 @@
 
 #include "core/rendering/svg/RenderSVGResourceContainer.h"
 
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/svg/SVGRenderingContext.h"
@@ -41,6 +42,7 @@
     : RenderSVGHiddenContainer(node)
     , m_isInLayout(false)
     , m_id(node->getIdAttribute())
+    , m_invalidationMask(0)
     , m_registered(false)
     , m_isInvalidating(false)
 {
@@ -60,9 +62,12 @@
     if (m_isInLayout)
         return;
 
+    LayoutRectRecorder recorder(*this);
     TemporaryChange<bool> inLayoutChange(m_isInLayout, true);
 
     RenderSVGHiddenContainer::layout();
+
+    clearInvalidationMask();
 }
 
 void RenderSVGResourceContainer::willBeDestroyed()
@@ -99,6 +104,10 @@
     if ((m_clients.isEmpty() && m_clientLayers.isEmpty()) || m_isInvalidating)
         return;
 
+    if (m_invalidationMask & mode)
+        return;
+
+    m_invalidationMask |= mode;
     m_isInvalidating = true;
     bool needsLayout = mode == LayoutAndBoundariesInvalidation;
     bool markForInvalidation = mode != ParentOnlyInvalidation;
@@ -152,6 +161,7 @@
 {
     ASSERT(client);
     m_clients.add(client);
+    clearInvalidationMask();
 }
 
 void RenderSVGResourceContainer::removeClient(RenderObject* client)
@@ -167,12 +177,14 @@
     if (!node->renderer() || !node->renderer()->hasLayer())
         return;
     m_clientLayers.add(toRenderLayerModelObject(node->renderer())->layer());
+    clearInvalidationMask();
 }
 
 void RenderSVGResourceContainer::addClientRenderLayer(RenderLayer* client)
 {
     ASSERT(client);
     m_clientLayers.add(client);
+    clearInvalidationMask();
 }
 
 void RenderSVGResourceContainer::removeClientRenderLayer(RenderLayer* client)
@@ -242,7 +254,7 @@
         return resourceTransform;
 
     SVGGraphicsElement* element = toSVGGraphicsElement(object->node());
-    AffineTransform transform = element->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
+    AffineTransform transform = element->getScreenCTM(SVGGraphicsElement::DisallowStyleUpdate);
     transform *= resourceTransform;
     return transform;
 }
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.h b/Source/core/rendering/svg/RenderSVGResourceContainer.h
index 07bee61..71d3c6f 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.h
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.h
@@ -49,11 +49,12 @@
     void invalidateCacheAndMarkForLayout(SubtreeLayoutScope* = 0);
 
 protected:
+    // When adding modes, make sure we don't overflow m_invalidationMask below.
     enum InvalidationMode {
-        LayoutAndBoundariesInvalidation,
-        BoundariesInvalidation,
-        RepaintInvalidation,
-        ParentOnlyInvalidation
+        LayoutAndBoundariesInvalidation = 1 << 0,
+        BoundariesInvalidation = 1 << 1,
+        RepaintInvalidation = 1 << 2,
+        ParentOnlyInvalidation = 1 << 3
     };
 
     // Used from the invalidateClient/invalidateClients methods from classes, inheriting from us.
@@ -61,6 +62,8 @@
     void markAllClientLayersForInvalidation();
     void markClientForInvalidation(RenderObject*, InvalidationMode);
 
+    void clearInvalidationMask() { m_invalidationMask = 0; }
+
     bool m_isInLayout;
 
 private:
@@ -72,8 +75,13 @@
     void registerResource();
 
     AtomicString m_id;
+    // Track global (markAllClientsForInvalidation) invals to avoid redundant crawls.
+    unsigned m_invalidationMask : 8;
+
     bool m_registered : 1;
     bool m_isInvalidating : 1;
+    // 22 padding bits available
+
     HashSet<RenderObject*> m_clients;
     HashSet<RenderLayer*> m_clientLayers;
 };
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index fccbe59..f01b33a 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -142,6 +142,8 @@
     ASSERT(context);
     ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
 
+    clearInvalidationMask();
+
     if (m_filter.contains(object)) {
         FilterData* filterData = m_filter.get(object);
         if (filterData->state == FilterData::PaintingSource || filterData->state == FilterData::Applying)
diff --git a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
index 7cd75f1..1449ae9 100644
--- a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
@@ -58,6 +58,8 @@
     ASSERT(context);
     ASSERT(resourceMode != ApplyToDefaultMode);
 
+    clearInvalidationMask();
+
     // Be sure to synchronize all SVG properties on the gradientElement _before_ processing any further.
     // Otherwhise the call to collectGradientAttributes() in createTileImage(), may cause the SVG DOM property
     // synchronization to kick in, which causes removeAllClientsFromCache() to be called, which in turn deletes our
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
index ce2aa98..086a994 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
@@ -24,6 +24,7 @@
 #include "core/rendering/svg/RenderSVGResourceMarker.h"
 
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/svg/RenderSVGContainer.h"
 #include "core/rendering/svg/SVGRenderSupport.h"
 #include "core/svg/SVGElement.h"
@@ -50,6 +51,7 @@
     if (m_isInLayout)
         return;
 
+    LayoutRectRecorder recorder(*this);
     TemporaryChange<bool> inLayoutChange(m_isInLayout, true);
 
     // Invalidate all resources if our layout changed.
@@ -60,6 +62,8 @@
     // layouting of RenderSVGContainer for calculating  local
     // transformations and repaint.
     RenderSVGContainer::layout();
+
+    clearInvalidationMask();
 }
 
 void RenderSVGResourceMarker::removeAllClientsFromCache(bool markForInvalidation)
@@ -135,6 +139,8 @@
 
 void RenderSVGResourceMarker::draw(PaintInfo& paintInfo, const AffineTransform& transform)
 {
+    clearInvalidationMask();
+
     // An empty viewBox disables rendering.
     SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.h b/Source/core/rendering/svg/RenderSVGResourceMarker.h
index afe4913..625b37a 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.h
@@ -73,11 +73,7 @@
     FloatRect m_viewport;
 };
 
-inline RenderSVGResourceMarker* toRenderSVGResourceMarker(RenderSVGResource* resource)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == MarkerResourceType);
-    return static_cast<RenderSVGResourceMarker*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceMarker, MarkerResourceType);
 
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
index e4e96d4..3b0c5d9 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
@@ -70,6 +70,8 @@
     ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
     ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
 
+    clearInvalidationMask();
+
     FloatRect repaintRect = object->repaintRectInLocalCoordinates();
     if (repaintRect.isEmpty() || !element()->hasChildNodes())
         return false;
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.h b/Source/core/rendering/svg/RenderSVGResourceMasker.h
index db86274..bf8aa08 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.h
@@ -63,11 +63,7 @@
     FloatRect m_maskContentBoundaries;
 };
 
-inline RenderSVGResourceMasker* toRenderSVGResourceMasker(RenderSVGResource* resource)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == MaskerResourceType);
-    return static_cast<RenderSVGResourceMasker*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceMasker, MaskerResourceType);
 
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
index 1333841..f36e19f 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
@@ -139,6 +139,8 @@
     ASSERT(context);
     ASSERT(resourceMode != ApplyToDefaultMode);
 
+    clearInvalidationMask();
+
     // Spec: When the geometry of the applicable element has no width or height and objectBoundingBox is specified,
     // then the given effect (e.g. a gradient or a filter) will be ignored.
     FloatRect objectBoundingBox = object->objectBoundingBox();
@@ -239,9 +241,8 @@
 {
     clampedAbsoluteTileBoundaries = SVGRenderingContext::clampedAbsoluteTargetRect(absoluteTileBoundaries);
 
-    OwnPtr<ImageBuffer> tileImage;
-
-    if (!SVGRenderingContext::createImageBufferForPattern(absoluteTileBoundaries, clampedAbsoluteTileBoundaries, tileImage, Unaccelerated))
+    OwnPtr<ImageBuffer> tileImage = ImageBuffer::createBufferForTile(absoluteTileBoundaries.size(), clampedAbsoluteTileBoundaries.size(), Unaccelerated);
+    if (!tileImage)
         return nullptr;
 
     GraphicsContext* tileImageContext = tileImage->context();
diff --git a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
index 3705c81..43ee076 100644
--- a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
@@ -52,11 +52,7 @@
     RadialGradientAttributes m_attributes;
 };
 
-inline RenderSVGResourceRadialGradient* toRenderSVGResourceRadialGradient(RenderSVGResourceContainer* resource)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == RadialGradientResourceType);
-    return static_cast<RenderSVGResourceRadialGradient*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceRadialGradient, RadialGradientResourceType);
 
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index b3100fc..2424065 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -31,6 +31,7 @@
 #include "core/page/Page.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderPart.h"
 #include "core/rendering/RenderView.h"
@@ -197,6 +198,8 @@
 {
     ASSERT(needsLayout());
 
+    LayoutRectRecorder recorder(*this);
+
     // Arbitrary affine transforms are incompatible with LayoutState.
     LayoutStateDisabler layoutStateDisabler(view());
 
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index 1b0d559..b5268fd 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -32,6 +32,7 @@
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/HitTestRequest.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/PointerEventsHitRules.h"
 #include "core/rendering/svg/RenderSVGResourceMarker.h"
@@ -139,6 +140,7 @@
 
 void RenderSVGShape::layout()
 {
+    LayoutRectRecorder recorder(*this);
     LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) && selfNeedsLayout());
 
     bool updateCachedBoundariesInParents = false;
@@ -191,7 +193,7 @@
 
 AffineTransform RenderSVGShape::nonScalingStrokeTransform() const
 {
-    return toSVGGraphicsElement(element())->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
+    return toSVGGraphicsElement(element())->getScreenCTM(SVGGraphicsElement::DisallowStyleUpdate);
 }
 
 bool RenderSVGShape::shouldGenerateMarkerPositions() const
@@ -310,7 +312,7 @@
 
 bool RenderSVGShape::nodeAtFloatPoint(const HitTestRequest& request, HitTestResult& result, const FloatPoint& pointInParent, HitTestAction hitTestAction)
 {
-    // We only draw in the forground phase, so we only hit-test then.
+    // We only draw in the foreground phase, so we only hit-test then.
     if (hitTestAction != HitTestForeground)
         return false;
 
@@ -319,7 +321,17 @@
     if (!SVGRenderSupport::pointInClippingArea(this, localPoint))
         return false;
 
-    PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_PATH_HITTESTING, request, style()->pointerEvents());
+    PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, style()->pointerEvents());
+    if (nodeAtFloatPointInternal(request, localPoint, hitRules)) {
+        updateHitTestResult(result, roundedLayoutPoint(localPoint));
+        return true;
+    }
+
+    return false;
+}
+
+bool RenderSVGShape::nodeAtFloatPointInternal(const HitTestRequest& request, const FloatPoint& localPoint, PointerEventsHitRules hitRules)
+{
     bool isVisible = (style()->visibility() == VISIBLE);
     if (isVisible || !hitRules.requireVisible) {
         const SVGRenderStyle* svgStyle = style()->svgStyle();
@@ -327,10 +339,8 @@
         if (request.svgClipContent())
             fillRule = svgStyle->clipRule();
         if ((hitRules.canHitStroke && (svgStyle->hasStroke() || !hitRules.requireStroke) && strokeContains(localPoint, hitRules.requireStroke))
-            || (hitRules.canHitFill && (svgStyle->hasFill() || !hitRules.requireFill) && fillContains(localPoint, hitRules.requireFill, fillRule))) {
-            updateHitTestResult(result, roundedLayoutPoint(localPoint));
+            || (hitRules.canHitFill && (svgStyle->hasFill() || !hitRules.requireFill) && fillContains(localPoint, hitRules.requireFill, fillRule)))
             return true;
-        }
     }
     return false;
 }
diff --git a/Source/core/rendering/svg/RenderSVGShape.h b/Source/core/rendering/svg/RenderSVGShape.h
index 4cd4fb7..f800b2d 100644
--- a/Source/core/rendering/svg/RenderSVGShape.h
+++ b/Source/core/rendering/svg/RenderSVGShape.h
@@ -37,6 +37,7 @@
 
 class FloatPoint;
 class GraphicsContextStateSaver;
+class PointerEventsHitRules;
 class RenderSVGContainer;
 class RenderSVGPath;
 class RenderSVGResource;
@@ -55,6 +56,8 @@
     virtual void fillShape(GraphicsContext*) const;
     virtual void strokeShape(GraphicsContext*) const;
 
+    bool nodeAtFloatPointInternal(const HitTestRequest&, const FloatPoint&, PointerEventsHitRules);
+
     Path& path() const
     {
         ASSERT(m_path);
diff --git a/Source/core/rendering/svg/RenderSVGText.cpp b/Source/core/rendering/svg/RenderSVGText.cpp
index e9f50f7..c4092c2 100644
--- a/Source/core/rendering/svg/RenderSVGText.cpp
+++ b/Source/core/rendering/svg/RenderSVGText.cpp
@@ -33,6 +33,7 @@
 #include "core/platform/graphics/SimpleFontData.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/PointerEventsHitRules.h"
 #include "core/rendering/style/ShadowList.h"
@@ -347,6 +348,7 @@
 void RenderSVGText::layout()
 {
     ASSERT(needsLayout());
+    LayoutRectRecorder recorder(*this);
     LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this));
 
     bool updateCachedBoundariesInParents = false;
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.cpp b/Source/core/rendering/svg/SVGInlineTextBox.cpp
index 8efa435..aeb1b88 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineTextBox.cpp
@@ -321,7 +321,7 @@
             paintInfo.context->concatCTM(fragmentTransform);
 
         // Spec: All text decorations except line-through should be drawn before the text is filled and stroked; thus, the text is rendered on top of these decorations.
-        int decorations = style->textDecorationsInEffect();
+        unsigned decorations = style->textDecorationsInEffect();
         if (decorations & TextDecorationUnderline)
             paintDecoration(paintInfo.context, TextDecorationUnderline, fragment);
         if (decorations & TextDecorationOverline)
diff --git a/Source/core/rendering/svg/SVGPathData.cpp b/Source/core/rendering/svg/SVGPathData.cpp
index d9085d6..7e59f82 100644
--- a/Source/core/rendering/svg/SVGPathData.cpp
+++ b/Source/core/rendering/svg/SVGPathData.cpp
@@ -74,7 +74,7 @@
 
 static void updatePathFromPolygonElement(SVGElement* element, Path& path)
 {
-    SVGPointList& points = toSVGPolygonElement(element)->pointList();
+    SVGPointList& points = toSVGPolygonElement(element)->pointsCurrentValue();
     if (points.isEmpty())
         return;
 
@@ -89,7 +89,7 @@
 
 static void updatePathFromPolylineElement(SVGElement* element, Path& path)
 {
-    SVGPointList& points = toSVGPolylineElement(element)->pointList();
+    SVGPointList& points = toSVGPolylineElement(element)->pointsCurrentValue();
     if (points.isEmpty())
         return;
 
diff --git a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index 4f59f08..b92e9b9 100644
--- a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -343,7 +343,7 @@
         writeNameValuePair(ts, "cy", element->cyCurrentValue().value(lengthContext));
         writeNameValuePair(ts, "r", element->rCurrentValue().value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::polygonTag) || svgElement->hasTagName(SVGNames::polylineTag)) {
-        writeNameAndQuotedValue(ts, "points", toSVGPolyElement(svgElement)->pointList().valueAsString());
+        writeNameAndQuotedValue(ts, "points", toSVGPolyElement(svgElement)->pointsCurrentValue().valueAsString());
     } else if (svgElement->hasTagName(SVGNames::pathTag)) {
         String pathString;
         // FIXME: We should switch to UnalteredParsing here - this will affect the path dumping output of dozens of tests.
diff --git a/Source/core/rendering/svg/SVGRenderingContext.cpp b/Source/core/rendering/svg/SVGRenderingContext.cpp
index 2f79029..11f2c90 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.cpp
+++ b/Source/core/rendering/svg/SVGRenderingContext.cpp
@@ -134,8 +134,8 @@
     }
 
     ClipPathOperation* clipPathOperation = style->clipPath();
-    if (clipPathOperation && clipPathOperation->getOperationType() == ClipPathOperation::SHAPE) {
-        ShapeClipPathOperation* clipPath = static_cast<ShapeClipPathOperation*>(clipPathOperation);
+    if (clipPathOperation && clipPathOperation->type() == ClipPathOperation::SHAPE) {
+        ShapeClipPathOperation* clipPath = toShapeClipPathOperation(clipPathOperation);
         m_paintInfo->context->clipPath(clipPath->path(object->objectBoundingBox()), clipPath->windRule());
     }
 
@@ -228,7 +228,9 @@
         // We can stop at compositing layers, to match the backing resolution.
         // FIXME: should we be computing the transform to the nearest composited layer,
         // or the nearest composited layer that does not paint into its ancestor?
-        if (layer->compositedLayerMapping())
+        // I think this is the nearest composited ancestor since we will inherit its
+        // transforms in the composited layer tree.
+        if (layer->hasCompositedLayerMapping())
             break;
 
         layer = layer->parent();
@@ -238,29 +240,6 @@
         absoluteTransform.scale(deviceScaleFactor);
 }
 
-bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
-{
-    IntSize imageSize(roundedIntSize(clampedAbsoluteTargetRect.size()));
-    IntSize unclampedImageSize(roundedIntSize(absoluteTargetRect.size()));
-
-    // Don't create empty ImageBuffers.
-    if (imageSize.isEmpty())
-        return false;
-
-    OwnPtr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, renderingMode);
-    if (!image)
-        return false;
-
-    GraphicsContext* imageContext = image->context();
-    ASSERT(imageContext);
-
-    // Compensate rounding effects, as the absolute target rect is using floating-point numbers and the image buffer size is integer.
-    imageContext->scale(FloatSize(unclampedImageSize.width() / absoluteTargetRect.width(), unclampedImageSize.height() / absoluteTargetRect.height()));
-
-    imageBuffer = image.release();
-    return true;
-}
-
 void SVGRenderingContext::renderSubtree(GraphicsContext* context, RenderObject* item, const AffineTransform& subtreeContentTransformation)
 {
     ASSERT(item);
diff --git a/Source/core/rendering/svg/SVGRenderingContext.h b/Source/core/rendering/svg/SVGRenderingContext.h
index 5b679ba..12463bd 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.h
+++ b/Source/core/rendering/svg/SVGRenderingContext.h
@@ -76,9 +76,6 @@
     void prepareToRenderSVGContent(RenderObject*, PaintInfo&, NeedsGraphicsContextSave = DontSaveGraphicsContext);
     bool isRenderingPrepared() const { return m_renderingFlags & RenderingPrepared; }
 
-    // Patterns need a different float-to-integer coordinate mapping.
-    static bool createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>&, RenderingMode);
-
     static void renderSubtree(GraphicsContext*, RenderObject*, const AffineTransform&);
 
     static float calculateScreenFontSizeScalingFactor(const RenderObject*);
diff --git a/Source/core/rendering/svg/SVGRootInlineBox.cpp b/Source/core/rendering/svg/SVGRootInlineBox.cpp
index d9e6ec7..ec9a953 100644
--- a/Source/core/rendering/svg/SVGRootInlineBox.cpp
+++ b/Source/core/rendering/svg/SVGRootInlineBox.cpp
@@ -166,7 +166,7 @@
 
 void SVGRootInlineBox::layoutRootBox(const FloatRect& childRect)
 {
-    RenderBlock* parentBlock = block();
+    RenderBlockFlow* parentBlock = block();
     ASSERT(parentBlock);
 
     // Finally, assign the root block position, now that all content is laid out.
diff --git a/Source/core/rendering/svg/SVGRootInlineBox.h b/Source/core/rendering/svg/SVGRootInlineBox.h
index 41475cd..4576b50 100644
--- a/Source/core/rendering/svg/SVGRootInlineBox.h
+++ b/Source/core/rendering/svg/SVGRootInlineBox.h
@@ -33,7 +33,7 @@
 
 class SVGRootInlineBox FINAL : public RootInlineBox {
 public:
-    SVGRootInlineBox(RenderBlock* block)
+    SVGRootInlineBox(RenderBlockFlow* block)
         : RootInlineBox(block)
         , m_logicalHeight(0)
     {
diff --git a/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp b/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
index 5eb5530..9a364dd 100644
--- a/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
+++ b/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
@@ -53,7 +53,8 @@
     ASSERT(fontData->isCustomFont());
     ASSERT(fontData->isSVGFont());
 
-    const SVGFontData* svgFontData = static_cast<const SVGFontData*>(fontData->fontData());
+    RefPtr<CustomFontData> customFontData = fontData->customFontData();
+    const SVGFontData* svgFontData = static_cast<const SVGFontData*>(customFontData.get());
     SVGFontFaceElement* svgFontFace = svgFontData->svgFontFaceElement();
     ASSERT(svgFontFace);
 
diff --git a/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp b/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp
index 08468fa..3eac7ed 100644
--- a/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp
+++ b/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp
@@ -44,7 +44,8 @@
     ASSERT(fontData->isCustomFont());
     ASSERT(fontData->isSVGFont());
 
-    const SVGFontData* svgFontData = static_cast<const SVGFontData*>(fontData->fontData());
+    RefPtr<CustomFontData> customFontData = fontData->customFontData();
+    const SVGFontData* svgFontData = static_cast<const SVGFontData*>(customFontData.get());
 
     fontFace = svgFontData->svgFontFaceElement();
     ASSERT(fontFace);
@@ -192,7 +193,7 @@
 
     // Characters enclosed by an <altGlyph> element, may not be registered in the GlyphPage.
     const SimpleFontData* originalFontData = glyphData.fontData;
-    if (glyphData.fontData && !glyphData.fontData->isSVGFont()) {
+    if (originalFontData && !originalFontData->isSVGFont()) {
         if (TextRun::RenderingContext* renderingContext = run.renderingContext()) {
             RenderObject* renderObject = static_cast<SVGTextRunRenderingContext*>(renderingContext)->renderer();
             RenderObject* parentRenderObject = renderObject->isText() ? renderObject->parent() : renderObject;
diff --git a/Source/core/storage/Storage.cpp b/Source/core/storage/Storage.cpp
index c46e9bb..76abd82 100644
--- a/Source/core/storage/Storage.cpp
+++ b/Source/core/storage/Storage.cpp
@@ -51,73 +51,73 @@
 {
 }
 
-String Storage::anonymousIndexedGetter(unsigned index, ExceptionState& es)
+String Storage::anonymousIndexedGetter(unsigned index, ExceptionState& exceptionState)
 {
-    return anonymousNamedGetter(String::number(index), es);
+    return anonymousNamedGetter(AtomicString::number(index), exceptionState);
 }
 
-String Storage::anonymousNamedGetter(const AtomicString& name, ExceptionState& es)
+String Storage::anonymousNamedGetter(const AtomicString& name, ExceptionState& exceptionState)
 {
-    bool found = contains(name, es);
-    if (es.hadException() || !found)
+    bool found = contains(name, exceptionState);
+    if (exceptionState.hadException() || !found)
         return String();
-    String result = getItem(name, es);
-    if (es.hadException())
+    String result = getItem(name, exceptionState);
+    if (exceptionState.hadException())
         return String();
     return result;
 }
 
-bool Storage::anonymousNamedSetter(const AtomicString& name, const AtomicString& value, ExceptionState& es)
+bool Storage::anonymousNamedSetter(const AtomicString& name, const AtomicString& value, ExceptionState& exceptionState)
 {
-    setItem(name, value, es);
+    setItem(name, value, exceptionState);
     return true;
 }
 
-bool Storage::anonymousIndexedSetter(unsigned index, const AtomicString& value, ExceptionState& es)
+bool Storage::anonymousIndexedSetter(unsigned index, const AtomicString& value, ExceptionState& exceptionState)
 {
-    return anonymousNamedSetter(String::number(index), value, es);
+    return anonymousNamedSetter(AtomicString::number(index), value, exceptionState);
 }
 
-bool Storage::anonymousNamedDeleter(const AtomicString& name, ExceptionState& es)
+bool Storage::anonymousNamedDeleter(const AtomicString& name, ExceptionState& exceptionState)
 {
-    bool found = contains(name, es);
-    if (!found || es.hadException())
+    bool found = contains(name, exceptionState);
+    if (!found || exceptionState.hadException())
         return false;
-    removeItem(name, es);
-    if (es.hadException())
+    removeItem(name, exceptionState);
+    if (exceptionState.hadException())
         return false;
     return true;
 }
 
-bool Storage::anonymousIndexedDeleter(unsigned index, ExceptionState& es)
+bool Storage::anonymousIndexedDeleter(unsigned index, ExceptionState& exceptionState)
 {
-    return anonymousNamedDeleter(String::number(index), es);
+    return anonymousNamedDeleter(AtomicString::number(index), exceptionState);
 }
 
-void Storage::namedPropertyEnumerator(Vector<String>& names, ExceptionState& es)
+void Storage::namedPropertyEnumerator(Vector<String>& names, ExceptionState& exceptionState)
 {
-    unsigned length = this->length(es);
-    if (es.hadException())
+    unsigned length = this->length(exceptionState);
+    if (exceptionState.hadException())
         return;
     names.resize(length);
     for (unsigned i = 0; i < length; ++i) {
-        String key = this->key(i, es);
-        if (es.hadException())
+        String key = this->key(i, exceptionState);
+        if (exceptionState.hadException())
             return;
         ASSERT(!key.isNull());
-        String val = getItem(key, es);
-        if (es.hadException())
+        String val = getItem(key, exceptionState);
+        if (exceptionState.hadException())
             return;
         names[i] = key;
     }
 }
 
-bool Storage::namedPropertyQuery(const AtomicString& name, ExceptionState& es)
+bool Storage::namedPropertyQuery(const AtomicString& name, ExceptionState& exceptionState)
 {
     if (name == "length")
         return false;
-    bool found = contains(name, es);
-    if (es.hadException() || !found)
+    bool found = contains(name, exceptionState);
+    if (exceptionState.hadException() || !found)
         return false;
     return true;
 }
diff --git a/Source/core/storage/Storage.idl b/Source/core/storage/Storage.idl
index 15cdf26..90309fe 100644
--- a/Source/core/storage/Storage.idl
+++ b/Source/core/storage/Storage.idl
@@ -30,11 +30,11 @@
     [RaisesException, ImplementedAs=anonymousNamedGetter] getter DOMString(DOMString name);
     [RaisesException, ImplementedAs=anonymousNamedSetter] setter DOMString(DOMString name, DOMString value);
     [ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
-    [NotEnumerable, GetterRaisesException] readonly attribute unsigned long length;
+    [NotEnumerable, RaisesException=Getter] readonly attribute unsigned long length;
     [NotEnumerable, TreatReturnedNullStringAs=Null, RaisesException] DOMString key(unsigned long index);
-    [NotEnumerable, TreatReturnedNullStringAs=Null, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, RaisesException] DOMString getItem(DOMString key);
-    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds] void setItem(DOMString key, DOMString data);
-    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds] void removeItem(DOMString key);
-    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds] void clear();
+    [NotEnumerable, TreatReturnedNullStringAs=Null, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] DOMString getItem(DOMString key);
+    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void setItem(DOMString key, DOMString data);
+    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void removeItem(DOMString key);
+    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void clear();
 };
 
diff --git a/Source/core/svg/SVGAElement.cpp b/Source/core/svg/SVGAElement.cpp
index facae10..e1d9784 100644
--- a/Source/core/svg/SVGAElement.cpp
+++ b/Source/core/svg/SVGAElement.cpp
@@ -66,17 +66,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGAElement::SVGAElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGAElement::SVGAElement(Document& document)
+    : SVGGraphicsElement(SVGNames::aTag, document)
 {
-    ASSERT(hasTagName(SVGNames::aTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGAElement();
 }
 
-PassRefPtr<SVGAElement> SVGAElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAElement> SVGAElement::create(Document& document)
 {
-    return adoptRef(new SVGAElement(tagName, document));
+    return adoptRef(new SVGAElement(document));
 }
 
 String SVGAElement::title() const
diff --git a/Source/core/svg/SVGAElement.h b/Source/core/svg/SVGAElement.h
index b3d0743..10036db 100644
--- a/Source/core/svg/SVGAElement.h
+++ b/Source/core/svg/SVGAElement.h
@@ -33,10 +33,10 @@
                           public SVGURIReference,
                           public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGAElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAElement> create(Document&);
 
 private:
-    SVGAElement(const QualifiedName&, Document&);
+    explicit SVGAElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
 
diff --git a/Source/core/svg/SVGAltGlyphDefElement.cpp b/Source/core/svg/SVGAltGlyphDefElement.cpp
index d99b165..4924ec5 100644
--- a/Source/core/svg/SVGAltGlyphDefElement.cpp
+++ b/Source/core/svg/SVGAltGlyphDefElement.cpp
@@ -28,16 +28,15 @@
 
 namespace WebCore {
 
-inline SVGAltGlyphDefElement::SVGAltGlyphDefElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGAltGlyphDefElement::SVGAltGlyphDefElement(Document& document)
+    : SVGElement(SVGNames::altGlyphDefTag, document)
 {
-    ASSERT(hasTagName(SVGNames::altGlyphDefTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAltGlyphDefElement> SVGAltGlyphDefElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAltGlyphDefElement> SVGAltGlyphDefElement::create(Document& document)
 {
-    return adoptRef(new SVGAltGlyphDefElement(tagName, document));
+    return adoptRef(new SVGAltGlyphDefElement(document));
 }
 
 bool SVGAltGlyphDefElement::hasValidGlyphElements(Vector<String>& glyphNames) const
diff --git a/Source/core/svg/SVGAltGlyphDefElement.h b/Source/core/svg/SVGAltGlyphDefElement.h
index f3b1fd8..e557944 100644
--- a/Source/core/svg/SVGAltGlyphDefElement.h
+++ b/Source/core/svg/SVGAltGlyphDefElement.h
@@ -28,12 +28,12 @@
 
 class SVGAltGlyphDefElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGAltGlyphDefElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAltGlyphDefElement> create(Document&);
 
     bool hasValidGlyphElements(Vector<String>& glyphNames) const;
 
 private:
-    SVGAltGlyphDefElement(const QualifiedName&, Document&);
+    explicit SVGAltGlyphDefElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
diff --git a/Source/core/svg/SVGAltGlyphElement.cpp b/Source/core/svg/SVGAltGlyphElement.cpp
index 8ed0841..b170919 100644
--- a/Source/core/svg/SVGAltGlyphElement.cpp
+++ b/Source/core/svg/SVGAltGlyphElement.cpp
@@ -42,22 +42,21 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextPositioningElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGAltGlyphElement::SVGAltGlyphElement(const QualifiedName& tagName, Document& document)
-    : SVGTextPositioningElement(tagName, document)
+inline SVGAltGlyphElement::SVGAltGlyphElement(Document& document)
+    : SVGTextPositioningElement(SVGNames::altGlyphTag, document)
 {
-    ASSERT(hasTagName(SVGNames::altGlyphTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGAltGlyphElement();
 }
 
-PassRefPtr<SVGAltGlyphElement> SVGAltGlyphElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAltGlyphElement> SVGAltGlyphElement::create(Document& document)
 {
-    return adoptRef(new SVGAltGlyphElement(tagName, document));
+    return adoptRef(new SVGAltGlyphElement(document));
 }
 
-void SVGAltGlyphElement::setGlyphRef(const AtomicString&, ExceptionState& es)
+void SVGAltGlyphElement::setGlyphRef(const AtomicString&, ExceptionState& exceptionState)
 {
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
 const AtomicString& SVGAltGlyphElement::glyphRef() const
@@ -65,9 +64,9 @@
     return fastGetAttribute(SVGNames::glyphRefAttr);
 }
 
-void SVGAltGlyphElement::setFormat(const AtomicString&, ExceptionState& es)
+void SVGAltGlyphElement::setFormat(const AtomicString&, ExceptionState& exceptionState)
 {
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
 const AtomicString& SVGAltGlyphElement::format() const
diff --git a/Source/core/svg/SVGAltGlyphElement.h b/Source/core/svg/SVGAltGlyphElement.h
index 2ab0ee7..841e1f0 100644
--- a/Source/core/svg/SVGAltGlyphElement.h
+++ b/Source/core/svg/SVGAltGlyphElement.h
@@ -35,7 +35,7 @@
 class SVGAltGlyphElement FINAL : public SVGTextPositioningElement,
                                  public SVGURIReference {
 public:
-    static PassRefPtr<SVGAltGlyphElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAltGlyphElement> create(Document&);
 
     const AtomicString& glyphRef() const;
     void setGlyphRef(const AtomicString&, ExceptionState&);
@@ -45,7 +45,7 @@
     bool hasValidGlyphElements(Vector<String>& glyphNames) const;
 
 private:
-    SVGAltGlyphElement(const QualifiedName&, Document&);
+    explicit SVGAltGlyphElement(Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const Node& child) const;
diff --git a/Source/core/svg/SVGAltGlyphElement.idl b/Source/core/svg/SVGAltGlyphElement.idl
index 999598e..e3f9915 100644
--- a/Source/core/svg/SVGAltGlyphElement.idl
+++ b/Source/core/svg/SVGAltGlyphElement.idl
@@ -26,8 +26,8 @@
 [
     Conditional=SVG_FONTS
 ] interface SVGAltGlyphElement : SVGTextPositioningElement {
-    [SetterRaisesException] attribute DOMString glyphRef;
-    [SetterRaisesException] attribute DOMString format;
+    [RaisesException=Setter] attribute DOMString glyphRef;
+    [RaisesException=Setter] attribute DOMString format;
 };
 
 SVGAltGlyphElement implements SVGURIReference;
diff --git a/Source/core/svg/SVGAltGlyphItemElement.cpp b/Source/core/svg/SVGAltGlyphItemElement.cpp
index 22c4d95..662dfeb 100644
--- a/Source/core/svg/SVGAltGlyphItemElement.cpp
+++ b/Source/core/svg/SVGAltGlyphItemElement.cpp
@@ -27,16 +27,15 @@
 
 namespace WebCore {
 
-inline SVGAltGlyphItemElement::SVGAltGlyphItemElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGAltGlyphItemElement::SVGAltGlyphItemElement(Document& document)
+    : SVGElement(SVGNames::altGlyphItemTag, document)
 {
-    ASSERT(hasTagName(SVGNames::altGlyphItemTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAltGlyphItemElement> SVGAltGlyphItemElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAltGlyphItemElement> SVGAltGlyphItemElement::create(Document& document)
 {
-    return adoptRef(new SVGAltGlyphItemElement(tagName, document));
+    return adoptRef(new SVGAltGlyphItemElement(document));
 }
 
 bool SVGAltGlyphItemElement::hasValidGlyphElements(Vector<String>& glyphNames) const
diff --git a/Source/core/svg/SVGAltGlyphItemElement.h b/Source/core/svg/SVGAltGlyphItemElement.h
index 18223d7..cf4c9b0 100644
--- a/Source/core/svg/SVGAltGlyphItemElement.h
+++ b/Source/core/svg/SVGAltGlyphItemElement.h
@@ -28,12 +28,12 @@
 
 class SVGAltGlyphItemElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGAltGlyphItemElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAltGlyphItemElement> create(Document&);
 
     bool hasValidGlyphElements(Vector<String>& glyphNames) const;
 
 private:
-    SVGAltGlyphItemElement(const QualifiedName&, Document&);
+    explicit SVGAltGlyphItemElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
diff --git a/Source/core/svg/SVGAngle.cpp b/Source/core/svg/SVGAngle.cpp
index 90ee200..30f4155 100644
--- a/Source/core/svg/SVGAngle.cpp
+++ b/Source/core/svg/SVGAngle.cpp
@@ -150,7 +150,7 @@
     return true;
 }
 
-void SVGAngle::setValueAsString(const String& value, ExceptionState& es)
+void SVGAngle::setValueAsString(const String& value, ExceptionState& exceptionState)
 {
     if (value.isEmpty()) {
         m_unitType = SVG_ANGLETYPE_UNSPECIFIED;
@@ -163,7 +163,7 @@
     bool success = value.is8Bit() ? parseValue<LChar>(value, valueInSpecifiedUnits, unitType)
                                   : parseValue<UChar>(value, valueInSpecifiedUnits, unitType);
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
@@ -171,10 +171,10 @@
     m_valueInSpecifiedUnits = valueInSpecifiedUnits;
 }
 
-void SVGAngle::newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState& es)
+void SVGAngle::newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState& exceptionState)
 {
     if (unitType == SVG_ANGLETYPE_UNKNOWN || unitType > SVG_ANGLETYPE_GRAD) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
@@ -184,10 +184,10 @@
     m_valueInSpecifiedUnits = valueInSpecifiedUnits;
 }
 
-void SVGAngle::convertToSpecifiedUnits(unsigned short unitType, ExceptionState& es)
+void SVGAngle::convertToSpecifiedUnits(unsigned short unitType, ExceptionState& exceptionState)
 {
     if (unitType == SVG_ANGLETYPE_UNKNOWN || m_unitType == SVG_ANGLETYPE_UNKNOWN || unitType > SVG_ANGLETYPE_GRAD) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
diff --git a/Source/core/svg/SVGAngle.idl b/Source/core/svg/SVGAngle.idl
index 4501978..665f6ea 100644
--- a/Source/core/svg/SVGAngle.idl
+++ b/Source/core/svg/SVGAngle.idl
@@ -32,7 +32,7 @@
     [StrictTypeChecking] attribute float value;
     [StrictTypeChecking] attribute float valueInSpecifiedUnits;
 
-    [TreatNullAs=NullString, SetterRaisesException] attribute DOMString valueAsString;
+    [TreatNullAs=NullString, RaisesException=Setter] attribute DOMString valueAsString;
 
     [StrictTypeChecking, RaisesException] void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
 
diff --git a/Source/core/svg/SVGAnimateColorElement.cpp b/Source/core/svg/SVGAnimateColorElement.cpp
index b01d7f3..7bf3842 100644
--- a/Source/core/svg/SVGAnimateColorElement.cpp
+++ b/Source/core/svg/SVGAnimateColorElement.cpp
@@ -22,23 +22,22 @@
 #include "config.h"
 
 #include "SVGNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/svg/SVGAnimateColorElement.h"
 
 namespace WebCore {
 
-inline SVGAnimateColorElement::SVGAnimateColorElement(const QualifiedName& tagName, Document& document)
-    : SVGAnimateElement(tagName, document)
+inline SVGAnimateColorElement::SVGAnimateColorElement(Document& document)
+    : SVGAnimateElement(SVGNames::animateColorTag, document)
 {
-    ASSERT(hasTagName(SVGNames::animateColorTag));
     ScriptWrappable::init(this);
 
     UseCounter::count(document, UseCounter::SVGAnimateColorElement);
 }
 
-PassRefPtr<SVGAnimateColorElement> SVGAnimateColorElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAnimateColorElement> SVGAnimateColorElement::create(Document& document)
 {
-    return adoptRef(new SVGAnimateColorElement(tagName, document));
+    return adoptRef(new SVGAnimateColorElement(document));
 }
 
 static bool attributeValueIsCurrentColor(const String& value)
diff --git a/Source/core/svg/SVGAnimateColorElement.h b/Source/core/svg/SVGAnimateColorElement.h
index 160b1c6..f17ea26 100644
--- a/Source/core/svg/SVGAnimateColorElement.h
+++ b/Source/core/svg/SVGAnimateColorElement.h
@@ -28,10 +28,10 @@
 
 class SVGAnimateColorElement FINAL : public SVGAnimateElement {
 public:
-    static PassRefPtr<SVGAnimateColorElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAnimateColorElement> create(Document&);
 
 private:
-    SVGAnimateColorElement(const QualifiedName&, Document&);
+    explicit SVGAnimateColorElement(Document&);
     virtual void determinePropertyValueTypes(const String& from, const String& to);
 };
 
diff --git a/Source/core/svg/SVGAnimateElement.cpp b/Source/core/svg/SVGAnimateElement.cpp
index de4239b..7835b43 100644
--- a/Source/core/svg/SVGAnimateElement.cpp
+++ b/Source/core/svg/SVGAnimateElement.cpp
@@ -44,9 +44,9 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAnimateElement> SVGAnimateElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAnimateElement> SVGAnimateElement::create(Document& document)
 {
-    return adoptRef(new SVGAnimateElement(tagName, document));
+    return adoptRef(new SVGAnimateElement(SVGNames::animateTag, document));
 }
 
 SVGAnimateElement::~SVGAnimateElement()
diff --git a/Source/core/svg/SVGAnimateElement.h b/Source/core/svg/SVGAnimateElement.h
index e7f2c67..592613c 100644
--- a/Source/core/svg/SVGAnimateElement.h
+++ b/Source/core/svg/SVGAnimateElement.h
@@ -35,7 +35,7 @@
 
 class SVGAnimateElement : public SVGAnimationElement {
 public:
-    static PassRefPtr<SVGAnimateElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAnimateElement> create(Document&);
     virtual ~SVGAnimateElement();
 
     AnimatedPropertyType determineAnimatedPropertyType(SVGElement*) const;
diff --git a/Source/core/svg/SVGAnimateMotionElement.cpp b/Source/core/svg/SVGAnimateMotionElement.cpp
index 6f0a5fd..9c76b31 100644
--- a/Source/core/svg/SVGAnimateMotionElement.cpp
+++ b/Source/core/svg/SVGAnimateMotionElement.cpp
@@ -40,12 +40,11 @@
 
 using namespace SVGNames;
 
-inline SVGAnimateMotionElement::SVGAnimateMotionElement(const QualifiedName& tagName, Document& document)
-    : SVGAnimationElement(tagName, document)
+inline SVGAnimateMotionElement::SVGAnimateMotionElement(Document& document)
+    : SVGAnimationElement(animateMotionTag, document)
     , m_hasToPointAtEndOfDuration(false)
 {
     setCalcMode(CalcModePaced);
-    ASSERT(hasTagName(animateMotionTag));
     ScriptWrappable::init(this);
 }
 
@@ -55,9 +54,9 @@
         clearAnimatedType(targetElement());
 }
 
-PassRefPtr<SVGAnimateMotionElement> SVGAnimateMotionElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAnimateMotionElement> SVGAnimateMotionElement::create(Document& document)
 {
-    return adoptRef(new SVGAnimateMotionElement(tagName, document));
+    return adoptRef(new SVGAnimateMotionElement(document));
 }
 
 bool SVGAnimateMotionElement::hasValidAttributeType()
diff --git a/Source/core/svg/SVGAnimateMotionElement.h b/Source/core/svg/SVGAnimateMotionElement.h
index 3993759..b79d190 100644
--- a/Source/core/svg/SVGAnimateMotionElement.h
+++ b/Source/core/svg/SVGAnimateMotionElement.h
@@ -32,11 +32,11 @@
 public:
     virtual ~SVGAnimateMotionElement();
 
-    static PassRefPtr<SVGAnimateMotionElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAnimateMotionElement> create(Document&);
     void updateAnimationPath();
 
 private:
-    SVGAnimateMotionElement(const QualifiedName&, Document&);
+    explicit SVGAnimateMotionElement(Document&);
 
     virtual bool hasValidAttributeType();
     virtual bool hasValidAttributeName();
diff --git a/Source/core/svg/SVGAnimateTransformElement.cpp b/Source/core/svg/SVGAnimateTransformElement.cpp
index 051cf93..bd43e05 100644
--- a/Source/core/svg/SVGAnimateTransformElement.cpp
+++ b/Source/core/svg/SVGAnimateTransformElement.cpp
@@ -25,21 +25,21 @@
 #include "core/svg/SVGAnimateTransformElement.h"
 
 #include "SVGNames.h"
-#include "core/svg/SVGTransformable.h"
+#include "core/svg/SVGParserUtilities.h"
+#include "core/svg/SVGTransform.h"
 
 namespace WebCore {
 
-inline SVGAnimateTransformElement::SVGAnimateTransformElement(const QualifiedName& tagName, Document& document)
-    : SVGAnimateElement(tagName, document)
+inline SVGAnimateTransformElement::SVGAnimateTransformElement(Document& document)
+    : SVGAnimateElement(SVGNames::animateTransformTag, document)
     , m_type(SVGTransform::SVG_TRANSFORM_UNKNOWN)
 {
-    ASSERT(hasTagName(SVGNames::animateTransformTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAnimateTransformElement> SVGAnimateTransformElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAnimateTransformElement> SVGAnimateTransformElement::create(Document& document)
 {
-    return adoptRef(new SVGAnimateTransformElement(tagName, document));
+    return adoptRef(new SVGAnimateTransformElement(document));
 }
 
 bool SVGAnimateTransformElement::hasValidAttributeType()
@@ -70,7 +70,7 @@
     }
 
     if (name == SVGNames::typeAttr) {
-        m_type = SVGTransformable::parseTransformType(value);
+        m_type = parseTransformType(value);
         if (m_type == SVGTransform::SVG_TRANSFORM_MATRIX)
             m_type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
         return;
diff --git a/Source/core/svg/SVGAnimateTransformElement.h b/Source/core/svg/SVGAnimateTransformElement.h
index 21c80f2..86606d8 100644
--- a/Source/core/svg/SVGAnimateTransformElement.h
+++ b/Source/core/svg/SVGAnimateTransformElement.h
@@ -32,12 +32,12 @@
 
 class SVGAnimateTransformElement FINAL : public SVGAnimateElement {
 public:
-    static PassRefPtr<SVGAnimateTransformElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGAnimateTransformElement> create(Document&);
 
     SVGTransform::SVGTransformType transformType() const { return m_type; }
 
 private:
-    SVGAnimateTransformElement(const QualifiedName&, Document&);
+    explicit SVGAnimateTransformElement(Document&);
 
     virtual bool hasValidAttributeType();
 
diff --git a/Source/core/svg/SVGAnimatedAngle.cpp b/Source/core/svg/SVGAnimatedAngle.cpp
index e5e1a77..a6265e5 100644
--- a/Source/core/svg/SVGAnimatedAngle.cpp
+++ b/Source/core/svg/SVGAnimatedAngle.cpp
@@ -31,13 +31,6 @@
 {
 }
 
-static inline SVGAngle& sharedSVGAngle(const String& valueAsString)
-{
-    DEFINE_STATIC_LOCAL(SVGAngle, sharedAngle, ());
-    sharedAngle.setValueAsString(valueAsString, ASSERT_NO_EXCEPTION);
-    return sharedAngle;
-}
-
 PassOwnPtr<SVGAnimatedType> SVGAnimatedAngleAnimator::constructFromString(const String& string)
 {
     OwnPtr<SVGAnimatedType> animatedType = SVGAnimatedType::createAngleAndEnumeration(new pair<SVGAngle, unsigned>);
diff --git a/Source/core/svg/SVGAnimatedBoolean.idl b/Source/core/svg/SVGAnimatedBoolean.idl
index fa2ca08..7fc919c 100644
--- a/Source/core/svg/SVGAnimatedBoolean.idl
+++ b/Source/core/svg/SVGAnimatedBoolean.idl
@@ -24,7 +24,7 @@
  */
 
 interface SVGAnimatedBoolean {
-    [StrictTypeChecking, SetterRaisesException] attribute boolean baseVal;
+    [StrictTypeChecking, RaisesException=Setter] attribute boolean baseVal;
     readonly attribute boolean animVal;
 };
 
diff --git a/Source/core/svg/SVGAnimatedEnumeration.idl b/Source/core/svg/SVGAnimatedEnumeration.idl
index cb04e75..e51c9c1 100644
--- a/Source/core/svg/SVGAnimatedEnumeration.idl
+++ b/Source/core/svg/SVGAnimatedEnumeration.idl
@@ -24,7 +24,7 @@
  */
 
 interface SVGAnimatedEnumeration {
-    [StrictTypeChecking, SetterRaisesException] attribute unsigned short baseVal;
+    [StrictTypeChecking, RaisesException=Setter] attribute unsigned short baseVal;
     readonly attribute unsigned short animVal;
 };
 
diff --git a/Source/core/svg/SVGAnimatedInteger.idl b/Source/core/svg/SVGAnimatedInteger.idl
index ae72080..3c31681 100644
--- a/Source/core/svg/SVGAnimatedInteger.idl
+++ b/Source/core/svg/SVGAnimatedInteger.idl
@@ -24,7 +24,7 @@
  */
 
 interface SVGAnimatedInteger {
-    [StrictTypeChecking, SetterRaisesException] attribute long baseVal;
+    [StrictTypeChecking, RaisesException=Setter] attribute long baseVal;
     readonly attribute long animVal;
 };
 
diff --git a/Source/core/svg/SVGAnimatedNumber.idl b/Source/core/svg/SVGAnimatedNumber.idl
index 6e3485c..e8cc9ba 100644
--- a/Source/core/svg/SVGAnimatedNumber.idl
+++ b/Source/core/svg/SVGAnimatedNumber.idl
@@ -25,7 +25,7 @@
  */
 
 interface SVGAnimatedNumber {
-    [StrictTypeChecking, SetterRaisesException] attribute float baseVal;
+    [StrictTypeChecking, RaisesException=Setter] attribute float baseVal;
     readonly attribute float animVal;
 };
 
diff --git a/Source/core/svg/SVGAnimatedString.idl b/Source/core/svg/SVGAnimatedString.idl
index 27e27dc..d1fbf52 100644
--- a/Source/core/svg/SVGAnimatedString.idl
+++ b/Source/core/svg/SVGAnimatedString.idl
@@ -24,7 +24,7 @@
  */
 
 interface SVGAnimatedString {
-    [SetterRaisesException] attribute DOMString baseVal;
+    [RaisesException=Setter] attribute DOMString baseVal;
     readonly attribute DOMString animVal;
 };
 
diff --git a/Source/core/svg/SVGAnimatedType.cpp b/Source/core/svg/SVGAnimatedType.cpp
index 148e00b..486773f 100644
--- a/Source/core/svg/SVGAnimatedType.cpp
+++ b/Source/core/svg/SVGAnimatedType.cpp
@@ -280,9 +280,9 @@
         break;
     case AnimatedLength: {
         ASSERT(m_data.length);
-        TrackExceptionState es;
-        m_data.length->setValueAsString(value, SVGLength::lengthModeForAnimatedLengthAttribute(attrName), es);
-        return !es.hadException();
+        TrackExceptionState exceptionState;
+        m_data.length->setValueAsString(value, SVGLength::lengthModeForAnimatedLengthAttribute(attrName), exceptionState);
+        return !exceptionState.hadException();
     }
     case AnimatedLengthList:
         ASSERT(m_data.lengthList);
diff --git a/Source/core/svg/SVGAnimationElement.cpp b/Source/core/svg/SVGAnimationElement.cpp
index 323ba5c..f17bd5e 100644
--- a/Source/core/svg/SVGAnimationElement.cpp
+++ b/Source/core/svg/SVGAnimationElement.cpp
@@ -30,7 +30,7 @@
 #include "SVGNames.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
 #include "core/css/CSSParser.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/svg/SVGAnimateElement.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGParserUtilities.h"
diff --git a/Source/core/svg/SVGCircleElement.cpp b/Source/core/svg/SVGCircleElement.cpp
index 8852d8c..f1304dd 100644
--- a/Source/core/svg/SVGCircleElement.cpp
+++ b/Source/core/svg/SVGCircleElement.cpp
@@ -44,20 +44,19 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGCircleElement::SVGCircleElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGCircleElement::SVGCircleElement(Document& document)
+    : SVGGeometryElement(SVGNames::circleTag, document)
     , m_cx(LengthModeWidth)
     , m_cy(LengthModeHeight)
     , m_r(LengthModeOther)
 {
-    ASSERT(hasTagName(SVGNames::circleTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGCircleElement();
 }
 
-PassRefPtr<SVGCircleElement> SVGCircleElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGCircleElement> SVGCircleElement::create(Document& document)
 {
-    return adoptRef(new SVGCircleElement(tagName, document));
+    return adoptRef(new SVGCircleElement(document));
 }
 
 bool SVGCircleElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -78,7 +77,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGGraphicsElement::parseAttribute(name, value);
+        SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::cxAttr)
         setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::cyAttr)
@@ -96,7 +95,7 @@
 void SVGCircleElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGGraphicsElement::svgAttributeChanged(attrName);
+        SVGGeometryElement::svgAttributeChanged(attrName);
         return;
     }
 
diff --git a/Source/core/svg/SVGCircleElement.h b/Source/core/svg/SVGCircleElement.h
index f720aa6..eb689f8 100644
--- a/Source/core/svg/SVGCircleElement.h
+++ b/Source/core/svg/SVGCircleElement.h
@@ -25,17 +25,17 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGCircleElement FINAL : public SVGGraphicsElement,
+class SVGCircleElement FINAL : public SVGGeometryElement,
                                public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGCircleElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGCircleElement> create(Document&);
 
 private:
-    SVGCircleElement(const QualifiedName&, Document&);
+    explicit SVGCircleElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGCircleElement.idl b/Source/core/svg/SVGCircleElement.idl
index 00ef676..67f3d44 100644
--- a/Source/core/svg/SVGCircleElement.idl
+++ b/Source/core/svg/SVGCircleElement.idl
@@ -24,7 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGCircleElement : SVGGraphicsElement {
+interface SVGCircleElement : SVGGeometryElement {
     readonly attribute SVGAnimatedLength cx;
     readonly attribute SVGAnimatedLength cy;
     readonly attribute SVGAnimatedLength r;
diff --git a/Source/core/svg/SVGClipPathElement.cpp b/Source/core/svg/SVGClipPathElement.cpp
index 2971ac1..a693775 100644
--- a/Source/core/svg/SVGClipPathElement.cpp
+++ b/Source/core/svg/SVGClipPathElement.cpp
@@ -39,18 +39,17 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGClipPathElement::SVGClipPathElement(Document& document)
+    : SVGGraphicsElement(SVGNames::clipPathTag, document)
     , m_clipPathUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
 {
-    ASSERT(hasTagName(SVGNames::clipPathTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGClipPathElement();
 }
 
-PassRefPtr<SVGClipPathElement> SVGClipPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGClipPathElement> SVGClipPathElement::create(Document& document)
 {
-    return adoptRef(new SVGClipPathElement(tagName, document));
+    return adoptRef(new SVGClipPathElement(document));
 }
 
 bool SVGClipPathElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGClipPathElement.h b/Source/core/svg/SVGClipPathElement.h
index d098e69..0b0baec 100644
--- a/Source/core/svg/SVGClipPathElement.h
+++ b/Source/core/svg/SVGClipPathElement.h
@@ -35,10 +35,10 @@
 class SVGClipPathElement FINAL : public SVGGraphicsElement,
                                  public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGClipPathElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGClipPathElement> create(Document&);
 
 private:
-    SVGClipPathElement(const QualifiedName&, Document&);
+    explicit SVGClipPathElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool needsPendingResourceHandling() const { return false; }
diff --git a/Source/core/svg/SVGColor.cpp b/Source/core/svg/SVGColor.cpp
index 60853d6..788ecf8 100644
--- a/Source/core/svg/SVGColor.cpp
+++ b/Source/core/svg/SVGColor.cpp
@@ -54,21 +54,21 @@
     return Color();
 }
 
-void SVGColor::setRGBColor(const String&, ExceptionState& es)
+void SVGColor::setRGBColor(const String&, ExceptionState& exceptionState)
 {
     // The whole SVGColor interface is deprecated in SVG 1.1 (2nd edition).
     // The setters are the most problematic part so we remove the support for those first.
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
-void SVGColor::setRGBColorICCColor(const String&, const String&, ExceptionState& es)
+void SVGColor::setRGBColorICCColor(const String&, const String&, ExceptionState& exceptionState)
 {
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
-void SVGColor::setColor(unsigned short, const String&, const String&, ExceptionState& es)
+void SVGColor::setColor(unsigned short, const String&, const String&, ExceptionState& exceptionState)
 {
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
 String SVGColor::customCSSText() const
diff --git a/Source/core/svg/SVGCursorElement.cpp b/Source/core/svg/SVGCursorElement.cpp
index f83ffa9..87cd2bc 100644
--- a/Source/core/svg/SVGCursorElement.cpp
+++ b/Source/core/svg/SVGCursorElement.cpp
@@ -43,19 +43,18 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGCursorElement::SVGCursorElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGCursorElement::SVGCursorElement(Document& document)
+    : SVGElement(SVGNames::cursorTag, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
 {
-    ASSERT(hasTagName(SVGNames::cursorTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGCursorElement();
 }
 
-PassRefPtr<SVGCursorElement> SVGCursorElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGCursorElement> SVGCursorElement::create(Document& document)
 {
-    return adoptRef(new SVGCursorElement(tagName, document));
+    return adoptRef(new SVGCursorElement(document));
 }
 
 SVGCursorElement::~SVGCursorElement()
diff --git a/Source/core/svg/SVGCursorElement.h b/Source/core/svg/SVGCursorElement.h
index eb93d4a..b79d44f 100644
--- a/Source/core/svg/SVGCursorElement.h
+++ b/Source/core/svg/SVGCursorElement.h
@@ -36,7 +36,7 @@
                                public SVGExternalResourcesRequired,
                                public SVGURIReference {
 public:
-    static PassRefPtr<SVGCursorElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGCursorElement> create(Document&);
 
     virtual ~SVGCursorElement();
 
@@ -45,7 +45,7 @@
     void removeReferencedElement(SVGElement*);
 
 private:
-    SVGCursorElement(const QualifiedName&, Document&);
+    explicit SVGCursorElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
 
diff --git a/Source/core/svg/SVGDefsElement.cpp b/Source/core/svg/SVGDefsElement.cpp
index 4b2d39b..ae425f3 100644
--- a/Source/core/svg/SVGDefsElement.cpp
+++ b/Source/core/svg/SVGDefsElement.cpp
@@ -35,17 +35,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGDefsElement::SVGDefsElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGDefsElement::SVGDefsElement(Document& document)
+    : SVGGraphicsElement(SVGNames::defsTag, document)
 {
-    ASSERT(hasTagName(SVGNames::defsTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGDefsElement();
 }
 
-PassRefPtr<SVGDefsElement> SVGDefsElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGDefsElement> SVGDefsElement::create(Document& document)
 {
-    return adoptRef(new SVGDefsElement(tagName, document));
+    return adoptRef(new SVGDefsElement(document));
 }
 
 bool SVGDefsElement::isValid() const
diff --git a/Source/core/svg/SVGDefsElement.h b/Source/core/svg/SVGDefsElement.h
index b29d526..60ff06b 100644
--- a/Source/core/svg/SVGDefsElement.h
+++ b/Source/core/svg/SVGDefsElement.h
@@ -30,10 +30,10 @@
 class SVGDefsElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGDefsElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGDefsElement> create(Document&);
 
 private:
-    SVGDefsElement(const QualifiedName&, Document&);
+    explicit SVGDefsElement(Document&);
 
     virtual bool isValid() const;
 
diff --git a/Source/core/svg/SVGDescElement.cpp b/Source/core/svg/SVGDescElement.cpp
index 219beda..9696aa1 100644
--- a/Source/core/svg/SVGDescElement.cpp
+++ b/Source/core/svg/SVGDescElement.cpp
@@ -24,16 +24,15 @@
 
 namespace WebCore {
 
-inline SVGDescElement::SVGDescElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGDescElement::SVGDescElement(Document& document)
+    : SVGElement(SVGNames::descTag, document)
 {
-    ASSERT(hasTagName(SVGNames::descTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGDescElement> SVGDescElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGDescElement> SVGDescElement::create(Document& document)
 {
-    return adoptRef(new SVGDescElement(tagName, document));
+    return adoptRef(new SVGDescElement(document));
 }
 
 String SVGDescElement::description() const
diff --git a/Source/core/svg/SVGDescElement.h b/Source/core/svg/SVGDescElement.h
index 2c8cfa6..181053d 100644
--- a/Source/core/svg/SVGDescElement.h
+++ b/Source/core/svg/SVGDescElement.h
@@ -27,12 +27,12 @@
 
 class SVGDescElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGDescElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGDescElement> create(Document&);
 
     String description() const;
 
 private:
-    SVGDescElement(const QualifiedName&, Document&);
+    explicit SVGDescElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 };
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index 8a5fc46..ffbceb3 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -32,7 +32,6 @@
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/css/CSSCursorImageValue.h"
 #include "core/css/CSSParser.h"
-#include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/events/Event.h"
@@ -77,6 +76,7 @@
     , m_inRelativeLengthClientsInvalidation(false)
 #endif
     , m_animatedPropertiesDestructed(false)
+    , m_isContextElement(false)
 {
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGElement();
@@ -100,7 +100,7 @@
     else {
         SVGElementRareData::SVGElementRareDataMap& rareDataMap = SVGElementRareData::rareDataMap();
         SVGElementRareData::SVGElementRareDataMap::iterator it = rareDataMap.find(this);
-        ASSERT(it != rareDataMap.end());
+        ASSERT_WITH_SECURITY_IMPLICATION(it != rareDataMap.end());
 
         SVGElementRareData* rareData = it->value;
         rareData->destroyAnimatedSMILStyleProperties();
@@ -238,12 +238,6 @@
     ASSERT_NOT_REACHED();
 }
 
-
-bool SVGElement::isSupported(StringImpl* feature, StringImpl* version) const
-{
-    return DOMImplementation::hasFeature(feature, version);
-}
-
 String SVGElement::title() const
 {
     // According to spec, we should not return titles when hovering over root <svg> elements (those
@@ -270,8 +264,8 @@
 
     // If we aren't an instance in a <use> or the <use> title was not found, then find the first
     // <title> child of this element.
-    Element* titleElement = ElementTraversal::firstWithin(this);
-    for (; titleElement; titleElement = ElementTraversal::nextSkippingChildren(titleElement, this)) {
+    Element* titleElement = ElementTraversal::firstWithin(*this);
+    for (; titleElement; titleElement = ElementTraversal::nextSkippingChildren(*titleElement, this)) {
         if (titleElement->hasTagName(SVGNames::titleTag) && titleElement->isSVGElement())
             break;
     }
@@ -317,7 +311,7 @@
         svgRareData()->setInstanceUpdatesBlocked(value);
 }
 
-AffineTransform SVGElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope) const
+AffineTransform SVGElement::localCoordinateSpaceTransform(CTMScope) const
 {
     // To be overriden by SVGGraphicsElement (or as special case SVGTextElement and SVGPatternElement)
     return AffineTransform();
diff --git a/Source/core/svg/SVGElement.h b/Source/core/svg/SVGElement.h
index cf7374e..f401221 100644
--- a/Source/core/svg/SVGElement.h
+++ b/Source/core/svg/SVGElement.h
@@ -25,7 +25,6 @@
 #include "core/dom/Element.h"
 #include "core/svg/SVGAnimatedString.h"
 #include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGLocatable.h"
 #include "core/svg/SVGParsingError.h"
 #include "core/svg/properties/SVGAnimatedPropertyMacros.h"
 #include "core/svg/properties/SVGPropertyInfo.h"
@@ -59,7 +58,11 @@
     PassRefPtr<CSSValue> getPresentationAttribute(const String& name);
     bool isKnownAttribute(const QualifiedName&);
     static bool isAnimatableCSSProperty(const QualifiedName&);
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
+    enum CTMScope {
+        NearestViewportScope, // Used by SVGGraphicsElement::getCTM()
+        ScreenScope // Used by SVGGraphicsElement::getScreenCTM()
+    };
+    virtual AffineTransform localCoordinateSpaceTransform(CTMScope) const;
     virtual bool needsPendingResourceHandling() const { return true; }
 
     bool instanceUpdatesBlocked() const;
@@ -136,6 +139,9 @@
 
     void invalidateRelativeLengthClients(SubtreeLayoutScope* = 0);
 
+    bool isContextElement() const { return m_isContextElement; }
+    void setContextElement() { m_isContextElement = true; }
+
 protected:
     SVGElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
 
@@ -198,8 +204,6 @@
 
     void buildPendingResourcesIfNeeded();
 
-    virtual bool isSupported(StringImpl* feature, StringImpl* version) const;
-
     void mapInstanceToElement(SVGElementInstance*);
     void removeInstanceMapping(SVGElementInstance*);
 
@@ -216,6 +220,7 @@
     bool m_inRelativeLengthClientsInvalidation;
 #endif
     bool m_animatedPropertiesDestructed;
+    bool m_isContextElement;
 };
 
 struct SVGAttributeHashTranslator {
diff --git a/Source/core/svg/SVGElement.idl b/Source/core/svg/SVGElement.idl
index 74d4db4..4bdf3c2 100644
--- a/Source/core/svg/SVGElement.idl
+++ b/Source/core/svg/SVGElement.idl
@@ -21,7 +21,7 @@
  */
 
 [
-    CustomToV8
+    CustomWrap,
 ] interface SVGElement : Element {
     [TreatNullAs=NullString] attribute DOMString xmlbase;
     readonly attribute SVGSVGElement ownerSVGElement;
diff --git a/Source/core/svg/SVGEllipseElement.cpp b/Source/core/svg/SVGEllipseElement.cpp
index 8002b06..44117e5 100644
--- a/Source/core/svg/SVGEllipseElement.cpp
+++ b/Source/core/svg/SVGEllipseElement.cpp
@@ -46,21 +46,20 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGEllipseElement::SVGEllipseElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGEllipseElement::SVGEllipseElement(Document& document)
+    : SVGGeometryElement(SVGNames::ellipseTag, document)
     , m_cx(LengthModeWidth)
     , m_cy(LengthModeHeight)
     , m_rx(LengthModeWidth)
     , m_ry(LengthModeHeight)
 {
-    ASSERT(hasTagName(SVGNames::ellipseTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGEllipseElement();
 }
 
-PassRefPtr<SVGEllipseElement> SVGEllipseElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGEllipseElement> SVGEllipseElement::create(Document& document)
 {
-    return adoptRef(new SVGEllipseElement(tagName, document));
+    return adoptRef(new SVGEllipseElement(document));
 }
 
 bool SVGEllipseElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -82,7 +81,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGGraphicsElement::parseAttribute(name, value);
+        SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::cxAttr)
         setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::cyAttr)
@@ -102,7 +101,7 @@
 void SVGEllipseElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGGraphicsElement::svgAttributeChanged(attrName);
+        SVGGeometryElement::svgAttributeChanged(attrName);
         return;
     }
 
diff --git a/Source/core/svg/SVGEllipseElement.h b/Source/core/svg/SVGEllipseElement.h
index 1c34b9b..e0cc981 100644
--- a/Source/core/svg/SVGEllipseElement.h
+++ b/Source/core/svg/SVGEllipseElement.h
@@ -25,17 +25,17 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGEllipseElement FINAL : public SVGGraphicsElement,
+class SVGEllipseElement FINAL : public SVGGeometryElement,
                                 public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGEllipseElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGEllipseElement> create(Document&);
 
 private:
-    SVGEllipseElement(const QualifiedName&, Document&);
+    explicit SVGEllipseElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGEllipseElement.idl b/Source/core/svg/SVGEllipseElement.idl
index a9ea183..fcd09c7 100644
--- a/Source/core/svg/SVGEllipseElement.idl
+++ b/Source/core/svg/SVGEllipseElement.idl
@@ -23,7 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGEllipseElement : SVGGraphicsElement {
+interface SVGEllipseElement : SVGGeometryElement {
     readonly attribute SVGAnimatedLength cx;
     readonly attribute SVGAnimatedLength cy;
     readonly attribute SVGAnimatedLength rx;
diff --git a/Source/core/svg/SVGFEBlendElement.cpp b/Source/core/svg/SVGFEBlendElement.cpp
index 1719515..27cdfa8 100644
--- a/Source/core/svg/SVGFEBlendElement.cpp
+++ b/Source/core/svg/SVGFEBlendElement.cpp
@@ -41,18 +41,17 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEBlendElement::SVGFEBlendElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEBlendElement::SVGFEBlendElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feBlendTag, document)
     , m_mode(FEBLEND_MODE_NORMAL)
 {
-    ASSERT(hasTagName(SVGNames::feBlendTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEBlendElement();
 }
 
-PassRefPtr<SVGFEBlendElement> SVGFEBlendElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEBlendElement> SVGFEBlendElement::create(Document& document)
 {
-    return adoptRef(new SVGFEBlendElement(tagName, document));
+    return adoptRef(new SVGFEBlendElement(document));
 }
 
 bool SVGFEBlendElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFEBlendElement.h b/Source/core/svg/SVGFEBlendElement.h
index af78dd9..b4e300d 100644
--- a/Source/core/svg/SVGFEBlendElement.h
+++ b/Source/core/svg/SVGFEBlendElement.h
@@ -70,10 +70,10 @@
 
 class SVGFEBlendElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEBlendElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEBlendElement> create(Document&);
 
 private:
-    SVGFEBlendElement(const QualifiedName&, Document&);
+    explicit SVGFEBlendElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEColorMatrixElement.cpp b/Source/core/svg/SVGFEColorMatrixElement.cpp
index 1ecb088..c09d88f 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.cpp
+++ b/Source/core/svg/SVGFEColorMatrixElement.cpp
@@ -41,18 +41,17 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feColorMatrixTag, document)
     , m_type(FECOLORMATRIX_TYPE_MATRIX)
 {
-    ASSERT(hasTagName(SVGNames::feColorMatrixTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEColorMatrixElement();
 }
 
-PassRefPtr<SVGFEColorMatrixElement> SVGFEColorMatrixElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEColorMatrixElement> SVGFEColorMatrixElement::create(Document& document)
 {
-    return adoptRef(new SVGFEColorMatrixElement(tagName, document));
+    return adoptRef(new SVGFEColorMatrixElement(document));
 }
 
 bool SVGFEColorMatrixElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFEColorMatrixElement.h b/Source/core/svg/SVGFEColorMatrixElement.h
index acd3616..72528fe 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.h
+++ b/Source/core/svg/SVGFEColorMatrixElement.h
@@ -67,10 +67,10 @@
 
 class SVGFEColorMatrixElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEColorMatrixElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEColorMatrixElement> create(Document&);
 
 private:
-    SVGFEColorMatrixElement(const QualifiedName&, Document&);
+    explicit SVGFEColorMatrixElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEComponentTransferElement.cpp b/Source/core/svg/SVGFEComponentTransferElement.cpp
index 7b77498..4f7a85c 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.cpp
+++ b/Source/core/svg/SVGFEComponentTransferElement.cpp
@@ -40,17 +40,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feComponentTransferTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feComponentTransferTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEComponentTransferElement();
 }
 
-PassRefPtr<SVGFEComponentTransferElement> SVGFEComponentTransferElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEComponentTransferElement> SVGFEComponentTransferElement::create(Document& document)
 {
-    return adoptRef(new SVGFEComponentTransferElement(tagName, document));
+    return adoptRef(new SVGFEComponentTransferElement(document));
 }
 
 bool SVGFEComponentTransferElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFEComponentTransferElement.h b/Source/core/svg/SVGFEComponentTransferElement.h
index f9d212b..8412f13 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.h
+++ b/Source/core/svg/SVGFEComponentTransferElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEComponentTransferElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEComponentTransferElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEComponentTransferElement> create(Document&);
 
 private:
-    SVGFEComponentTransferElement(const QualifiedName&, Document&);
+    explicit SVGFEComponentTransferElement(Document&);
 
     // FIXME: svgAttributeChanged missing.
     bool isSupportedAttribute(const QualifiedName&);
diff --git a/Source/core/svg/SVGFECompositeElement.cpp b/Source/core/svg/SVGFECompositeElement.cpp
index 343ca10..10f9dbd 100644
--- a/Source/core/svg/SVGFECompositeElement.cpp
+++ b/Source/core/svg/SVGFECompositeElement.cpp
@@ -49,18 +49,17 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFECompositeElement::SVGFECompositeElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFECompositeElement::SVGFECompositeElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feCompositeTag, document)
     , m_svgOperator(FECOMPOSITE_OPERATOR_OVER)
 {
-    ASSERT(hasTagName(SVGNames::feCompositeTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFECompositeElement();
 }
 
-PassRefPtr<SVGFECompositeElement> SVGFECompositeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFECompositeElement> SVGFECompositeElement::create(Document& document)
 {
-    return adoptRef(new SVGFECompositeElement(tagName, document));
+    return adoptRef(new SVGFECompositeElement(document));
 }
 
 bool SVGFECompositeElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFECompositeElement.h b/Source/core/svg/SVGFECompositeElement.h
index 7b7b943..15f1e2c 100644
--- a/Source/core/svg/SVGFECompositeElement.h
+++ b/Source/core/svg/SVGFECompositeElement.h
@@ -75,10 +75,10 @@
 
 class SVGFECompositeElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFECompositeElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFECompositeElement> create(Document&);
 
 private:
-    SVGFECompositeElement(const QualifiedName&, Document&);
+    explicit SVGFECompositeElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.cpp b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
index dc42d93..7e5e106 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.cpp
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
@@ -62,18 +62,17 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feConvolveMatrixTag, document)
     , m_edgeMode(EDGEMODE_DUPLICATE)
 {
-    ASSERT(hasTagName(SVGNames::feConvolveMatrixTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEConvolveMatrixElement();
 }
 
-PassRefPtr<SVGFEConvolveMatrixElement> SVGFEConvolveMatrixElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEConvolveMatrixElement> SVGFEConvolveMatrixElement::create(Document& document)
 {
-    return adoptRef(new SVGFEConvolveMatrixElement(tagName, document));
+    return adoptRef(new SVGFEConvolveMatrixElement(document));
 }
 
 const AtomicString& SVGFEConvolveMatrixElement::kernelUnitLengthXIdentifier()
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.h b/Source/core/svg/SVGFEConvolveMatrixElement.h
index f1faec5..3f285cc 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.h
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.h
@@ -65,13 +65,13 @@
 
 class SVGFEConvolveMatrixElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEConvolveMatrixElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEConvolveMatrixElement> create(Document&);
 
     void setOrder(float orderX, float orderY);
     void setKernelUnitLength(float kernelUnitLengthX, float kernelUnitLengthY);
 
 private:
-    SVGFEConvolveMatrixElement(const QualifiedName&, Document&);
+    explicit SVGFEConvolveMatrixElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.cpp b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
index 7f14645..ec8503a 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.cpp
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
@@ -48,19 +48,18 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feDiffuseLightingTag, document)
     , m_diffuseConstant(1)
     , m_surfaceScale(1)
 {
-    ASSERT(hasTagName(SVGNames::feDiffuseLightingTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEDiffuseLightingElement();
 }
 
-PassRefPtr<SVGFEDiffuseLightingElement> SVGFEDiffuseLightingElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDiffuseLightingElement> SVGFEDiffuseLightingElement::create(Document& document)
 {
-    return adoptRef(new SVGFEDiffuseLightingElement(tagName, document));
+    return adoptRef(new SVGFEDiffuseLightingElement(document));
 }
 
 const AtomicString& SVGFEDiffuseLightingElement::kernelUnitLengthXIdentifier()
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.h b/Source/core/svg/SVGFEDiffuseLightingElement.h
index dc10343..c3cbbc4 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.h
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.h
@@ -33,11 +33,11 @@
 
 class SVGFEDiffuseLightingElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEDiffuseLightingElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEDiffuseLightingElement> create(Document&);
     void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
 
 private:
-    SVGFEDiffuseLightingElement(const QualifiedName&, Document&);
+    explicit SVGFEDiffuseLightingElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.cpp b/Source/core/svg/SVGFEDisplacementMapElement.cpp
index 61fc8a9..2e3a57f 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.cpp
+++ b/Source/core/svg/SVGFEDisplacementMapElement.cpp
@@ -44,19 +44,18 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feDisplacementMapTag, document)
     , m_xChannelSelector(CHANNEL_A)
     , m_yChannelSelector(CHANNEL_A)
 {
-    ASSERT(hasTagName(SVGNames::feDisplacementMapTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEDisplacementMapElement();
 }
 
-PassRefPtr<SVGFEDisplacementMapElement> SVGFEDisplacementMapElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDisplacementMapElement> SVGFEDisplacementMapElement::create(Document& document)
 {
-    return adoptRef(new SVGFEDisplacementMapElement(tagName, document));
+    return adoptRef(new SVGFEDisplacementMapElement(document));
 }
 
 bool SVGFEDisplacementMapElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.h b/Source/core/svg/SVGFEDisplacementMapElement.h
index 0aa95c1..334df60 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.h
+++ b/Source/core/svg/SVGFEDisplacementMapElement.h
@@ -66,12 +66,12 @@
 
 class SVGFEDisplacementMapElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEDisplacementMapElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEDisplacementMapElement> create(Document&);
 
     static ChannelSelectorType stringToChannel(const String&);
 
 private:
-    SVGFEDisplacementMapElement(const QualifiedName& tagName, Document&);
+    SVGFEDisplacementMapElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEDistantLightElement.cpp b/Source/core/svg/SVGFEDistantLightElement.cpp
index d453563..68b3940 100644
--- a/Source/core/svg/SVGFEDistantLightElement.cpp
+++ b/Source/core/svg/SVGFEDistantLightElement.cpp
@@ -26,16 +26,15 @@
 
 namespace WebCore {
 
-inline SVGFEDistantLightElement::SVGFEDistantLightElement(const QualifiedName& tagName, Document& document)
-    : SVGFELightElement(tagName, document)
+inline SVGFEDistantLightElement::SVGFEDistantLightElement(Document& document)
+    : SVGFELightElement(SVGNames::feDistantLightTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feDistantLightTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEDistantLightElement> SVGFEDistantLightElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDistantLightElement> SVGFEDistantLightElement::create(Document& document)
 {
-    return adoptRef(new SVGFEDistantLightElement(tagName, document));
+    return adoptRef(new SVGFEDistantLightElement(document));
 }
 
 PassRefPtr<LightSource> SVGFEDistantLightElement::lightSource() const
diff --git a/Source/core/svg/SVGFEDistantLightElement.h b/Source/core/svg/SVGFEDistantLightElement.h
index df1b9c2..8a50cc8 100644
--- a/Source/core/svg/SVGFEDistantLightElement.h
+++ b/Source/core/svg/SVGFEDistantLightElement.h
@@ -26,10 +26,10 @@
 
 class SVGFEDistantLightElement FINAL : public SVGFELightElement {
 public:
-    static PassRefPtr<SVGFEDistantLightElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEDistantLightElement> create(Document&);
 
 private:
-    SVGFEDistantLightElement(const QualifiedName&, Document&);
+    explicit SVGFEDistantLightElement(Document&);
 
     virtual PassRefPtr<LightSource> lightSource() const;
 };
diff --git a/Source/core/svg/SVGFEDropShadowElement.cpp b/Source/core/svg/SVGFEDropShadowElement.cpp
index d5a5d29..366eaf3 100644
--- a/Source/core/svg/SVGFEDropShadowElement.cpp
+++ b/Source/core/svg/SVGFEDropShadowElement.cpp
@@ -46,21 +46,20 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEDropShadowElement::SVGFEDropShadowElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEDropShadowElement::SVGFEDropShadowElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feDropShadowTag, document)
     , m_dx(2)
     , m_dy(2)
     , m_stdDeviationX(2)
     , m_stdDeviationY(2)
 {
-    ASSERT(hasTagName(SVGNames::feDropShadowTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEDropShadowElement();
 }
 
-PassRefPtr<SVGFEDropShadowElement> SVGFEDropShadowElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDropShadowElement> SVGFEDropShadowElement::create(Document& document)
 {
-    return adoptRef(new SVGFEDropShadowElement(tagName, document));
+    return adoptRef(new SVGFEDropShadowElement(document));
 }
 
 const AtomicString& SVGFEDropShadowElement::stdDeviationXIdentifier()
diff --git a/Source/core/svg/SVGFEDropShadowElement.h b/Source/core/svg/SVGFEDropShadowElement.h
index 352f602..75b5a92 100644
--- a/Source/core/svg/SVGFEDropShadowElement.h
+++ b/Source/core/svg/SVGFEDropShadowElement.h
@@ -28,12 +28,12 @@
 
 class SVGFEDropShadowElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEDropShadowElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEDropShadowElement> create(Document&);
 
     void setStdDeviation(float stdDeviationX, float stdDeviationY);
 
 private:
-    SVGFEDropShadowElement(const QualifiedName&, Document&);
+    explicit SVGFEDropShadowElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEFloodElement.cpp b/Source/core/svg/SVGFEFloodElement.cpp
index 33d3aa3..baee77b 100644
--- a/Source/core/svg/SVGFEFloodElement.cpp
+++ b/Source/core/svg/SVGFEFloodElement.cpp
@@ -28,16 +28,15 @@
 
 namespace WebCore {
 
-inline SVGFEFloodElement::SVGFEFloodElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEFloodElement::SVGFEFloodElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feFloodTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feFloodTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFloodElement> SVGFEFloodElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFloodElement> SVGFEFloodElement::create(Document& document)
 {
-    return adoptRef(new SVGFEFloodElement(tagName, document));
+    return adoptRef(new SVGFEFloodElement(document));
 }
 
 
diff --git a/Source/core/svg/SVGFEFloodElement.h b/Source/core/svg/SVGFEFloodElement.h
index 378533e..6882038 100644
--- a/Source/core/svg/SVGFEFloodElement.h
+++ b/Source/core/svg/SVGFEFloodElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEFloodElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEFloodElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEFloodElement> create(Document&);
 
 private:
-    SVGFEFloodElement(const QualifiedName&, Document&);
+    explicit SVGFEFloodElement(Document&);
 
     virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName);
     virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
diff --git a/Source/core/svg/SVGFEFuncAElement.cpp b/Source/core/svg/SVGFEFuncAElement.cpp
index 4d35ab7..0a483cb 100644
--- a/Source/core/svg/SVGFEFuncAElement.cpp
+++ b/Source/core/svg/SVGFEFuncAElement.cpp
@@ -25,16 +25,15 @@
 
 namespace WebCore {
 
-inline SVGFEFuncAElement::SVGFEFuncAElement(const QualifiedName& tagName, Document& document)
-    : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncAElement::SVGFEFuncAElement(Document& document)
+    : SVGComponentTransferFunctionElement(SVGNames::feFuncATag, document)
 {
-    ASSERT(hasTagName(SVGNames::feFuncATag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncAElement> SVGFEFuncAElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncAElement> SVGFEFuncAElement::create(Document& document)
 {
-    return adoptRef(new SVGFEFuncAElement(tagName, document));
+    return adoptRef(new SVGFEFuncAElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGFEFuncAElement.h b/Source/core/svg/SVGFEFuncAElement.h
index fcd7aee..01a473a 100644
--- a/Source/core/svg/SVGFEFuncAElement.h
+++ b/Source/core/svg/SVGFEFuncAElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEFuncAElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncAElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEFuncAElement> create(Document&);
 
 private:
-    SVGFEFuncAElement(const QualifiedName&, Document&);
+    explicit SVGFEFuncAElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGFEFuncAElement, hasTagName(SVGNames::feFuncATag));
diff --git a/Source/core/svg/SVGFEFuncBElement.cpp b/Source/core/svg/SVGFEFuncBElement.cpp
index abca696..c2d97de 100644
--- a/Source/core/svg/SVGFEFuncBElement.cpp
+++ b/Source/core/svg/SVGFEFuncBElement.cpp
@@ -25,16 +25,15 @@
 
 namespace WebCore {
 
-inline SVGFEFuncBElement::SVGFEFuncBElement(const QualifiedName& tagName, Document& document)
-    : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncBElement::SVGFEFuncBElement(Document& document)
+    : SVGComponentTransferFunctionElement(SVGNames::feFuncBTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feFuncBTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncBElement> SVGFEFuncBElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncBElement> SVGFEFuncBElement::create(Document& document)
 {
-    return adoptRef(new SVGFEFuncBElement(tagName, document));
+    return adoptRef(new SVGFEFuncBElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGFEFuncBElement.h b/Source/core/svg/SVGFEFuncBElement.h
index 4639acb..24560e3 100644
--- a/Source/core/svg/SVGFEFuncBElement.h
+++ b/Source/core/svg/SVGFEFuncBElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEFuncBElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncBElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEFuncBElement> create(Document&);
 
 private:
-    SVGFEFuncBElement(const QualifiedName&, Document&);
+    explicit SVGFEFuncBElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGFEFuncBElement, hasTagName(SVGNames::feFuncBTag));
diff --git a/Source/core/svg/SVGFEFuncGElement.cpp b/Source/core/svg/SVGFEFuncGElement.cpp
index f7de1f3..1a148c6 100644
--- a/Source/core/svg/SVGFEFuncGElement.cpp
+++ b/Source/core/svg/SVGFEFuncGElement.cpp
@@ -25,16 +25,15 @@
 
 namespace WebCore {
 
-inline SVGFEFuncGElement::SVGFEFuncGElement(const QualifiedName& tagName, Document& document)
-    : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncGElement::SVGFEFuncGElement(Document& document)
+    : SVGComponentTransferFunctionElement(SVGNames::feFuncGTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feFuncGTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncGElement> SVGFEFuncGElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncGElement> SVGFEFuncGElement::create(Document& document)
 {
-    return adoptRef(new SVGFEFuncGElement(tagName, document));
+    return adoptRef(new SVGFEFuncGElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGFEFuncGElement.h b/Source/core/svg/SVGFEFuncGElement.h
index d8fcb05..3d6ccb8 100644
--- a/Source/core/svg/SVGFEFuncGElement.h
+++ b/Source/core/svg/SVGFEFuncGElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEFuncGElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncGElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEFuncGElement> create(Document&);
 
 private:
-    SVGFEFuncGElement(const QualifiedName&, Document&);
+    explicit SVGFEFuncGElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGFEFuncGElement, hasTagName(SVGNames::feFuncGTag));
diff --git a/Source/core/svg/SVGFEFuncRElement.cpp b/Source/core/svg/SVGFEFuncRElement.cpp
index cf059b6..74d5f2d 100644
--- a/Source/core/svg/SVGFEFuncRElement.cpp
+++ b/Source/core/svg/SVGFEFuncRElement.cpp
@@ -25,16 +25,15 @@
 
 namespace WebCore {
 
-inline SVGFEFuncRElement::SVGFEFuncRElement(const QualifiedName& tagName, Document& document)
-    : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncRElement::SVGFEFuncRElement(Document& document)
+    : SVGComponentTransferFunctionElement(SVGNames::feFuncRTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feFuncRTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncRElement> SVGFEFuncRElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncRElement> SVGFEFuncRElement::create(Document& document)
 {
-    return adoptRef(new SVGFEFuncRElement(tagName, document));
+    return adoptRef(new SVGFEFuncRElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGFEFuncRElement.h b/Source/core/svg/SVGFEFuncRElement.h
index 6b309a3..49bff72 100644
--- a/Source/core/svg/SVGFEFuncRElement.h
+++ b/Source/core/svg/SVGFEFuncRElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEFuncRElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncRElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEFuncRElement> create(Document&);
 
 private:
-    SVGFEFuncRElement(const QualifiedName&, Document&);
+    explicit SVGFEFuncRElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGFEFuncRElement, hasTagName(SVGNames::feFuncRTag));
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.cpp b/Source/core/svg/SVGFEGaussianBlurElement.cpp
index 3611e96..70de3d6 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.cpp
+++ b/Source/core/svg/SVGFEGaussianBlurElement.cpp
@@ -42,17 +42,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feGaussianBlurTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feGaussianBlurTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEGaussianBlurElement();
 }
 
-PassRefPtr<SVGFEGaussianBlurElement> SVGFEGaussianBlurElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEGaussianBlurElement> SVGFEGaussianBlurElement::create(Document& document)
 {
-    return adoptRef(new SVGFEGaussianBlurElement(tagName, document));
+    return adoptRef(new SVGFEGaussianBlurElement(document));
 }
 
 const AtomicString& SVGFEGaussianBlurElement::stdDeviationXIdentifier()
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.h b/Source/core/svg/SVGFEGaussianBlurElement.h
index 317addc..c8b6385 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.h
+++ b/Source/core/svg/SVGFEGaussianBlurElement.h
@@ -29,12 +29,12 @@
 
 class SVGFEGaussianBlurElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEGaussianBlurElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEGaussianBlurElement> create(Document&);
 
     void setStdDeviation(float stdDeviationX, float stdDeviationY);
 
 private:
-    SVGFEGaussianBlurElement(const QualifiedName&, Document&);
+    explicit SVGFEGaussianBlurElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEImageElement.cpp b/Source/core/svg/SVGFEImageElement.cpp
index e164c65..e93fafe 100644
--- a/Source/core/svg/SVGFEImageElement.cpp
+++ b/Source/core/svg/SVGFEImageElement.cpp
@@ -48,17 +48,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEImageElement::SVGFEImageElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEImageElement::SVGFEImageElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feImageTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feImageTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEImageElement();
 }
 
-PassRefPtr<SVGFEImageElement> SVGFEImageElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEImageElement> SVGFEImageElement::create(Document& document)
 {
-    return adoptRef(new SVGFEImageElement(tagName, document));
+    return adoptRef(new SVGFEImageElement(document));
 }
 
 SVGFEImageElement::~SVGFEImageElement()
diff --git a/Source/core/svg/SVGFEImageElement.h b/Source/core/svg/SVGFEImageElement.h
index 78864b5..8869b1e 100644
--- a/Source/core/svg/SVGFEImageElement.h
+++ b/Source/core/svg/SVGFEImageElement.h
@@ -39,14 +39,14 @@
                                 public SVGExternalResourcesRequired,
                                 public ImageResourceClient {
 public:
-    static PassRefPtr<SVGFEImageElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEImageElement> create(Document&);
 
     bool currentFrameHasSingleSecurityOrigin() const;
 
     virtual ~SVGFEImageElement();
 
 private:
-    SVGFEImageElement(const QualifiedName&, Document&);
+    explicit SVGFEImageElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFELightElement.h b/Source/core/svg/SVGFELightElement.h
index 4d14e30..4473ed3 100644
--- a/Source/core/svg/SVGFELightElement.h
+++ b/Source/core/svg/SVGFELightElement.h
@@ -22,9 +22,9 @@
 #ifndef SVGFELightElement_h
 #define SVGFELightElement_h
 
-#include "core/platform/graphics/filters/LightSource.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGElement.h"
+#include "platform/graphics/filters/LightSource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/svg/SVGFEMergeElement.cpp b/Source/core/svg/SVGFEMergeElement.cpp
index 401fc30..5f8a25a 100644
--- a/Source/core/svg/SVGFEMergeElement.cpp
+++ b/Source/core/svg/SVGFEMergeElement.cpp
@@ -29,16 +29,15 @@
 
 namespace WebCore {
 
-inline SVGFEMergeElement::SVGFEMergeElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEMergeElement::SVGFEMergeElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feMergeTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feMergeTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEMergeElement> SVGFEMergeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEMergeElement> SVGFEMergeElement::create(Document& document)
 {
-    return adoptRef(new SVGFEMergeElement(tagName, document));
+    return adoptRef(new SVGFEMergeElement(document));
 }
 
 PassRefPtr<FilterEffect> SVGFEMergeElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
diff --git a/Source/core/svg/SVGFEMergeElement.h b/Source/core/svg/SVGFEMergeElement.h
index ab682bb..cf60809 100644
--- a/Source/core/svg/SVGFEMergeElement.h
+++ b/Source/core/svg/SVGFEMergeElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEMergeElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEMergeElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEMergeElement> create(Document&);
 
 private:
-    SVGFEMergeElement(const QualifiedName&, Document&);
+    explicit SVGFEMergeElement(Document&);
 
     virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
 };
diff --git a/Source/core/svg/SVGFEMergeNodeElement.cpp b/Source/core/svg/SVGFEMergeNodeElement.cpp
index 648f22e..c6e2846 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.cpp
+++ b/Source/core/svg/SVGFEMergeNodeElement.cpp
@@ -35,17 +35,16 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(Document& document)
+    : SVGElement(SVGNames::feMergeNodeTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feMergeNodeTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEMergeNodeElement();
 }
 
-PassRefPtr<SVGFEMergeNodeElement> SVGFEMergeNodeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEMergeNodeElement> SVGFEMergeNodeElement::create(Document& document)
 {
-    return adoptRef(new SVGFEMergeNodeElement(tagName, document));
+    return adoptRef(new SVGFEMergeNodeElement(document));
 }
 
 bool SVGFEMergeNodeElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFEMergeNodeElement.h b/Source/core/svg/SVGFEMergeNodeElement.h
index b93938a..a076088 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.h
+++ b/Source/core/svg/SVGFEMergeNodeElement.h
@@ -29,10 +29,10 @@
 
 class SVGFEMergeNodeElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFEMergeNodeElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEMergeNodeElement> create(Document&);
 
 private:
-    SVGFEMergeNodeElement(const QualifiedName&, Document&);
+    explicit SVGFEMergeNodeElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEMorphologyElement.cpp b/Source/core/svg/SVGFEMorphologyElement.cpp
index 4502e22..f1ec058 100644
--- a/Source/core/svg/SVGFEMorphologyElement.cpp
+++ b/Source/core/svg/SVGFEMorphologyElement.cpp
@@ -43,18 +43,17 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEMorphologyElement::SVGFEMorphologyElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEMorphologyElement::SVGFEMorphologyElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feMorphologyTag, document)
     , m_svgOperator(FEMORPHOLOGY_OPERATOR_ERODE)
 {
-    ASSERT(hasTagName(SVGNames::feMorphologyTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEMorphologyElement();
 }
 
-PassRefPtr<SVGFEMorphologyElement> SVGFEMorphologyElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEMorphologyElement> SVGFEMorphologyElement::create(Document& document)
 {
-    return adoptRef(new SVGFEMorphologyElement(tagName, document));
+    return adoptRef(new SVGFEMorphologyElement(document));
 }
 
 const AtomicString& SVGFEMorphologyElement::radiusXIdentifier()
diff --git a/Source/core/svg/SVGFEMorphologyElement.h b/Source/core/svg/SVGFEMorphologyElement.h
index 38dede0..4754095 100644
--- a/Source/core/svg/SVGFEMorphologyElement.h
+++ b/Source/core/svg/SVGFEMorphologyElement.h
@@ -58,12 +58,12 @@
 
 class SVGFEMorphologyElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEMorphologyElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEMorphologyElement> create(Document&);
 
     void setRadius(float radiusX, float radiusY);
 
 private:
-    SVGFEMorphologyElement(const QualifiedName&, Document&);
+    explicit SVGFEMorphologyElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEOffsetElement.cpp b/Source/core/svg/SVGFEOffsetElement.cpp
index a110b83..f2320f2 100644
--- a/Source/core/svg/SVGFEOffsetElement.cpp
+++ b/Source/core/svg/SVGFEOffsetElement.cpp
@@ -41,17 +41,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEOffsetElement::SVGFEOffsetElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEOffsetElement::SVGFEOffsetElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feOffsetTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feOffsetTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFEOffsetElement();
 }
 
-PassRefPtr<SVGFEOffsetElement> SVGFEOffsetElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEOffsetElement> SVGFEOffsetElement::create(Document& document)
 {
-    return adoptRef(new SVGFEOffsetElement(tagName, document));
+    return adoptRef(new SVGFEOffsetElement(document));
 }
 
 bool SVGFEOffsetElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFEOffsetElement.h b/Source/core/svg/SVGFEOffsetElement.h
index a0489a4..6762d28 100644
--- a/Source/core/svg/SVGFEOffsetElement.h
+++ b/Source/core/svg/SVGFEOffsetElement.h
@@ -29,10 +29,10 @@
 
 class SVGFEOffsetElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEOffsetElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEOffsetElement> create(Document&);
 
 private:
-    SVGFEOffsetElement(const QualifiedName&, Document&);
+    explicit SVGFEOffsetElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEPointLightElement.cpp b/Source/core/svg/SVGFEPointLightElement.cpp
index 0f971b1..e617c96 100644
--- a/Source/core/svg/SVGFEPointLightElement.cpp
+++ b/Source/core/svg/SVGFEPointLightElement.cpp
@@ -26,16 +26,15 @@
 
 namespace WebCore {
 
-inline SVGFEPointLightElement::SVGFEPointLightElement(const QualifiedName& tagName, Document& document)
-    : SVGFELightElement(tagName, document)
+inline SVGFEPointLightElement::SVGFEPointLightElement(Document& document)
+    : SVGFELightElement(SVGNames::fePointLightTag, document)
 {
-    ASSERT(hasTagName(SVGNames::fePointLightTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEPointLightElement> SVGFEPointLightElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEPointLightElement> SVGFEPointLightElement::create(Document& document)
 {
-    return adoptRef(new SVGFEPointLightElement(tagName, document));
+    return adoptRef(new SVGFEPointLightElement(document));
 }
 
 PassRefPtr<LightSource> SVGFEPointLightElement::lightSource() const
diff --git a/Source/core/svg/SVGFEPointLightElement.h b/Source/core/svg/SVGFEPointLightElement.h
index 10bdec9..b32b951 100644
--- a/Source/core/svg/SVGFEPointLightElement.h
+++ b/Source/core/svg/SVGFEPointLightElement.h
@@ -26,10 +26,10 @@
 
 class SVGFEPointLightElement FINAL : public SVGFELightElement {
 public:
-    static PassRefPtr<SVGFEPointLightElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFEPointLightElement> create(Document&);
 
 private:
-    SVGFEPointLightElement(const QualifiedName&, Document&);
+    explicit SVGFEPointLightElement(Document&);
 
     virtual PassRefPtr<LightSource> lightSource() const;
 };
diff --git a/Source/core/svg/SVGFESpecularLightingElement.cpp b/Source/core/svg/SVGFESpecularLightingElement.cpp
index 12cd0c7..7f0b42b 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.cpp
+++ b/Source/core/svg/SVGFESpecularLightingElement.cpp
@@ -51,20 +51,19 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feSpecularLightingTag, document)
     , m_specularConstant(1)
     , m_specularExponent(1)
     , m_surfaceScale(1)
 {
-    ASSERT(hasTagName(SVGNames::feSpecularLightingTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFESpecularLightingElement();
 }
 
-PassRefPtr<SVGFESpecularLightingElement> SVGFESpecularLightingElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFESpecularLightingElement> SVGFESpecularLightingElement::create(Document& document)
 {
-    return adoptRef(new SVGFESpecularLightingElement(tagName, document));
+    return adoptRef(new SVGFESpecularLightingElement(document));
 }
 
 const AtomicString& SVGFESpecularLightingElement::kernelUnitLengthXIdentifier()
diff --git a/Source/core/svg/SVGFESpecularLightingElement.h b/Source/core/svg/SVGFESpecularLightingElement.h
index 4b562fe..4aaff3e 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.h
+++ b/Source/core/svg/SVGFESpecularLightingElement.h
@@ -32,11 +32,11 @@
 
 class SVGFESpecularLightingElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFESpecularLightingElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFESpecularLightingElement> create(Document&);
     void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
 
 private:
-    SVGFESpecularLightingElement(const QualifiedName&, Document&);
+    explicit SVGFESpecularLightingElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFESpotLightElement.cpp b/Source/core/svg/SVGFESpotLightElement.cpp
index c41e52a..21e7bfc 100644
--- a/Source/core/svg/SVGFESpotLightElement.cpp
+++ b/Source/core/svg/SVGFESpotLightElement.cpp
@@ -26,16 +26,15 @@
 
 namespace WebCore {
 
-inline SVGFESpotLightElement::SVGFESpotLightElement(const QualifiedName& tagName, Document& document)
-    : SVGFELightElement(tagName, document)
+inline SVGFESpotLightElement::SVGFESpotLightElement(Document& document)
+    : SVGFELightElement(SVGNames::feSpotLightTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feSpotLightTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFESpotLightElement> SVGFESpotLightElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFESpotLightElement> SVGFESpotLightElement::create(Document& document)
 {
-    return adoptRef(new SVGFESpotLightElement(tagName, document));
+    return adoptRef(new SVGFESpotLightElement(document));
 }
 
 PassRefPtr<LightSource> SVGFESpotLightElement::lightSource() const
diff --git a/Source/core/svg/SVGFESpotLightElement.h b/Source/core/svg/SVGFESpotLightElement.h
index 3b0ca9c..a36d762 100644
--- a/Source/core/svg/SVGFESpotLightElement.h
+++ b/Source/core/svg/SVGFESpotLightElement.h
@@ -26,10 +26,10 @@
 
 class SVGFESpotLightElement FINAL : public SVGFELightElement {
 public:
-    static PassRefPtr<SVGFESpotLightElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFESpotLightElement> create(Document&);
 
 private:
-    SVGFESpotLightElement(const QualifiedName&, Document&);
+    explicit SVGFESpotLightElement(Document&);
 
     virtual PassRefPtr<LightSource> lightSource() const;
 };
diff --git a/Source/core/svg/SVGFETileElement.cpp b/Source/core/svg/SVGFETileElement.cpp
index 44b94a0..1417f22 100644
--- a/Source/core/svg/SVGFETileElement.cpp
+++ b/Source/core/svg/SVGFETileElement.cpp
@@ -37,17 +37,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFETileElement::SVGFETileElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFETileElement::SVGFETileElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feTileTag, document)
 {
-    ASSERT(hasTagName(SVGNames::feTileTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFETileElement();
 }
 
-PassRefPtr<SVGFETileElement> SVGFETileElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFETileElement> SVGFETileElement::create(Document& document)
 {
-    return adoptRef(new SVGFETileElement(tagName, document));
+    return adoptRef(new SVGFETileElement(document));
 }
 
 bool SVGFETileElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFETileElement.h b/Source/core/svg/SVGFETileElement.h
index 005c53b..8f077a5 100644
--- a/Source/core/svg/SVGFETileElement.h
+++ b/Source/core/svg/SVGFETileElement.h
@@ -28,10 +28,10 @@
 
 class SVGFETileElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFETileElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFETileElement> create(Document&);
 
 private:
-    SVGFETileElement(const QualifiedName&, Document&);
+    explicit SVGFETileElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFETurbulenceElement.cpp b/Source/core/svg/SVGFETurbulenceElement.cpp
index 14236b2..b020f0f 100644
--- a/Source/core/svg/SVGFETurbulenceElement.cpp
+++ b/Source/core/svg/SVGFETurbulenceElement.cpp
@@ -46,20 +46,19 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFETurbulenceElement::SVGFETurbulenceElement(const QualifiedName& tagName, Document& document)
-    : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFETurbulenceElement::SVGFETurbulenceElement(Document& document)
+    : SVGFilterPrimitiveStandardAttributes(SVGNames::feTurbulenceTag, document)
     , m_numOctaves(1)
     , m_stitchTiles(SVG_STITCHTYPE_NOSTITCH)
     , m_type(FETURBULENCE_TYPE_TURBULENCE)
 {
-    ASSERT(hasTagName(SVGNames::feTurbulenceTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFETurbulenceElement();
 }
 
-PassRefPtr<SVGFETurbulenceElement> SVGFETurbulenceElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFETurbulenceElement> SVGFETurbulenceElement::create(Document& document)
 {
-    return adoptRef(new SVGFETurbulenceElement(tagName, document));
+    return adoptRef(new SVGFETurbulenceElement(document));
 }
 
 const AtomicString& SVGFETurbulenceElement::baseFrequencyXIdentifier()
diff --git a/Source/core/svg/SVGFETurbulenceElement.h b/Source/core/svg/SVGFETurbulenceElement.h
index c77eceb..600094c 100644
--- a/Source/core/svg/SVGFETurbulenceElement.h
+++ b/Source/core/svg/SVGFETurbulenceElement.h
@@ -95,10 +95,10 @@
 
 class SVGFETurbulenceElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFETurbulenceElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFETurbulenceElement> create(Document&);
 
 private:
-    SVGFETurbulenceElement(const QualifiedName&, Document&);
+    explicit SVGFETurbulenceElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFilterElement.cpp b/Source/core/svg/SVGFilterElement.cpp
index 8aac4d7..1dfe33d 100644
--- a/Source/core/svg/SVGFilterElement.cpp
+++ b/Source/core/svg/SVGFilterElement.cpp
@@ -58,8 +58,8 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFilterElement::SVGFilterElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFilterElement::SVGFilterElement(Document& document)
+    : SVGElement(SVGNames::filterTag, document)
     , m_filterUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_primitiveUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
     , m_x(LengthModeWidth, "-10%")
@@ -69,14 +69,13 @@
 {
     // Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
     // Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
-    ASSERT(hasTagName(SVGNames::filterTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFilterElement();
 }
 
-PassRefPtr<SVGFilterElement> SVGFilterElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFilterElement> SVGFilterElement::create(Document& document)
 {
-    return adoptRef(new SVGFilterElement(tagName, document));
+    return adoptRef(new SVGFilterElement(document));
 }
 
 const AtomicString& SVGFilterElement::filterResXIdentifier()
diff --git a/Source/core/svg/SVGFilterElement.h b/Source/core/svg/SVGFilterElement.h
index f929a3e..791939a 100644
--- a/Source/core/svg/SVGFilterElement.h
+++ b/Source/core/svg/SVGFilterElement.h
@@ -39,14 +39,14 @@
                                public SVGURIReference,
                                public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGFilterElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFilterElement> create(Document&);
 
     void setFilterRes(unsigned filterResX, unsigned filterResY);
     void addClient(Node*);
     void removeClient(Node*);
 
 private:
-    SVGFilterElement(const QualifiedName&, Document&);
+    explicit SVGFilterElement(Document&);
 
     virtual bool needsPendingResourceHandling() const { return false; }
 
diff --git a/Source/core/svg/SVGFontData.cpp b/Source/core/svg/SVGFontData.cpp
index 5054eaf..a345661 100644
--- a/Source/core/svg/SVGFontData.cpp
+++ b/Source/core/svg/SVGFontData.cpp
@@ -25,6 +25,7 @@
 #include "SVGNames.h"
 #include "XMLNames.h"
 #include "core/platform/graphics/SVGGlyph.h"
+#include "core/platform/graphics/SimpleFontData.h"
 #include "core/platform/graphics/WidthIterator.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
@@ -43,7 +44,8 @@
 namespace WebCore {
 
 SVGFontData::SVGFontData(SVGFontFaceElement* fontFaceElement)
-    : m_svgFontFaceElement(fontFaceElement)
+    : CustomFontData(false)
+    , m_svgFontFaceElement(fontFaceElement)
     , m_horizontalOriginX(fontFaceElement->horizontalOriginX())
     , m_horizontalOriginY(fontFaceElement->horizontalOriginY())
     , m_horizontalAdvanceX(fontFaceElement->horizontalAdvanceX())
diff --git a/Source/core/svg/SVGFontData.h b/Source/core/svg/SVGFontData.h
index 1e20938..94af31f 100644
--- a/Source/core/svg/SVGFontData.h
+++ b/Source/core/svg/SVGFontData.h
@@ -21,26 +21,30 @@
 #define SVGFontData_h
 
 #if ENABLE(SVG_FONTS)
-#include "core/platform/graphics/SimpleFontData.h"
+#include "core/platform/graphics/CustomFontData.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
+class SimpleFontData;
 class SVGFontElement;
 class SVGFontFaceElement;
 
-class SVGFontData : public SimpleFontData::AdditionalFontData {
+class SVGFontData FINAL : public CustomFontData {
 public:
-    static PassOwnPtr<SVGFontData> create(SVGFontFaceElement* element)
+    static PassRefPtr<SVGFontData> create(SVGFontFaceElement* element)
     {
-        return adoptPtr(new SVGFontData(element));
+        return adoptRef(new SVGFontData(element));
     }
 
     virtual ~SVGFontData() { }
 
-    virtual void initializeFontData(SimpleFontData*, float fontSize);
-    virtual float widthForSVGGlyph(Glyph, float fontSize) const;
-    virtual bool fillSVGGlyphPage(GlyphPage*, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData*) const;
-    virtual bool applySVGGlyphSelection(WidthIterator&, GlyphData&, bool mirror, int currentCharacter, unsigned& advanceLength) const;
+    virtual bool isSVGFont() const OVERRIDE { return true; };
+    virtual void initializeFontData(SimpleFontData*, float fontSize) OVERRIDE;
+    virtual float widthForSVGGlyph(Glyph, float fontSize) const OVERRIDE;
+    virtual bool fillSVGGlyphPage(GlyphPage*, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData*) const OVERRIDE;
+    virtual bool applySVGGlyphSelection(WidthIterator&, GlyphData&, bool mirror, int currentCharacter, unsigned& advanceLength) const OVERRIDE;
+
 
     SVGFontFaceElement* svgFontFaceElement() const { return m_svgFontFaceElement; }
 
diff --git a/Source/core/svg/SVGFontElement.cpp b/Source/core/svg/SVGFontElement.cpp
index bfc92ff..40bc9af 100644
--- a/Source/core/svg/SVGFontElement.cpp
+++ b/Source/core/svg/SVGFontElement.cpp
@@ -25,7 +25,7 @@
 #include "core/svg/SVGFontElement.h"
 
 #include "SVGNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/svg/SVGGlyphElement.h"
 #include "core/svg/SVGHKernElement.h"
 #include "core/svg/SVGMissingGlyphElement.h"
@@ -42,21 +42,20 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFontElement::SVGFontElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFontElement::SVGFontElement(Document& document)
+    : SVGElement(SVGNames::fontTag, document)
     , m_missingGlyph(0)
     , m_isGlyphCacheValid(false)
 {
-    ASSERT(hasTagName(SVGNames::fontTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFontElement();
 
     UseCounter::count(document, UseCounter::SVGFontElement);
 }
 
-PassRefPtr<SVGFontElement> SVGFontElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontElement> SVGFontElement::create(Document& document)
 {
-    return adoptRef(new SVGFontElement(tagName, document));
+    return adoptRef(new SVGFontElement(document));
 }
 
 void SVGFontElement::invalidateGlyphCache()
diff --git a/Source/core/svg/SVGFontElement.h b/Source/core/svg/SVGFontElement.h
index 2ac4d45..f7d945e 100644
--- a/Source/core/svg/SVGFontElement.h
+++ b/Source/core/svg/SVGFontElement.h
@@ -55,7 +55,7 @@
 class SVGFontElement FINAL : public SVGElement
                            , public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGFontElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFontElement> create(Document&);
 
     void invalidateGlyphCache();
     void collectGlyphsForString(const String&, Vector<SVGGlyph>&);
@@ -71,7 +71,7 @@
     SVGMissingGlyphElement* firstMissingGlyphElement() const;
 
 private:
-    SVGFontElement(const QualifiedName&, Document&);
+    explicit SVGFontElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 
diff --git a/Source/core/svg/SVGFontFaceElement.cpp b/Source/core/svg/SVGFontFaceElement.cpp
index 6b8865d..9fb4cd4 100644
--- a/Source/core/svg/SVGFontFaceElement.cpp
+++ b/Source/core/svg/SVGFontFaceElement.cpp
@@ -46,20 +46,19 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceElement::SVGFontFaceElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFontFaceElement::SVGFontFaceElement(Document& document)
+    : SVGElement(font_faceTag, document)
     , m_fontFaceRule(StyleRuleFontFace::create())
     , m_fontElement(0)
 {
-    ASSERT(hasTagName(font_faceTag));
     ScriptWrappable::init(this);
     RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create(HTMLStandardMode);
     m_fontFaceRule->setProperties(styleDeclaration.release());
 }
 
-PassRefPtr<SVGFontFaceElement> SVGFontFaceElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceElement> SVGFontFaceElement::create(Document& document)
 {
-    return adoptRef(new SVGFontFaceElement(tagName, document));
+    return adoptRef(new SVGFontFaceElement(document));
 }
 
 static CSSPropertyID cssPropertyIdForFontFaceAttributeName(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFontFaceElement.h b/Source/core/svg/SVGFontFaceElement.h
index e671ff4..0950ef4 100644
--- a/Source/core/svg/SVGFontFaceElement.h
+++ b/Source/core/svg/SVGFontFaceElement.h
@@ -33,7 +33,7 @@
 
 class SVGFontFaceElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFontFaceElement> create(Document&);
 
     unsigned unitsPerEm() const;
     int xHeight() const;
@@ -53,7 +53,7 @@
     StyleRuleFontFace* fontFaceRule() const { return m_fontFaceRule.get(); }
 
 private:
-    SVGFontFaceElement(const QualifiedName&, Document&);
+    explicit SVGFontFaceElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/svg/SVGFontFaceFormatElement.cpp b/Source/core/svg/SVGFontFaceFormatElement.cpp
index 94970cc..5468bdb 100644
--- a/Source/core/svg/SVGFontFaceFormatElement.cpp
+++ b/Source/core/svg/SVGFontFaceFormatElement.cpp
@@ -29,16 +29,15 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceFormatElement::SVGFontFaceFormatElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFontFaceFormatElement::SVGFontFaceFormatElement(Document& document)
+    : SVGElement(font_face_formatTag, document)
 {
-    ASSERT(hasTagName(font_face_formatTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceFormatElement> SVGFontFaceFormatElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceFormatElement> SVGFontFaceFormatElement::create(Document& document)
 {
-    return adoptRef(new SVGFontFaceFormatElement(tagName, document));
+    return adoptRef(new SVGFontFaceFormatElement(document));
 }
 
 void SVGFontFaceFormatElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/Source/core/svg/SVGFontFaceFormatElement.h b/Source/core/svg/SVGFontFaceFormatElement.h
index 33e7502..986431a 100644
--- a/Source/core/svg/SVGFontFaceFormatElement.h
+++ b/Source/core/svg/SVGFontFaceFormatElement.h
@@ -27,10 +27,10 @@
 
 class SVGFontFaceFormatElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceFormatElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFontFaceFormatElement> create(Document&);
 
 private:
-    SVGFontFaceFormatElement(const QualifiedName&, Document&);
+    explicit SVGFontFaceFormatElement(Document&);
 
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
diff --git a/Source/core/svg/SVGFontFaceNameElement.cpp b/Source/core/svg/SVGFontFaceNameElement.cpp
index 8157a5e..79f2551 100644
--- a/Source/core/svg/SVGFontFaceNameElement.cpp
+++ b/Source/core/svg/SVGFontFaceNameElement.cpp
@@ -27,16 +27,15 @@
 
 namespace WebCore {
 
-inline SVGFontFaceNameElement::SVGFontFaceNameElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFontFaceNameElement::SVGFontFaceNameElement(Document& document)
+    : SVGElement(SVGNames::font_face_nameTag, document)
 {
-    ASSERT(hasTagName(SVGNames::font_face_nameTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceNameElement> SVGFontFaceNameElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceNameElement> SVGFontFaceNameElement::create(Document& document)
 {
-    return adoptRef(new SVGFontFaceNameElement(tagName, document));
+    return adoptRef(new SVGFontFaceNameElement(document));
 }
 
 PassRefPtr<CSSFontFaceSrcValue> SVGFontFaceNameElement::srcValue() const
diff --git a/Source/core/svg/SVGFontFaceNameElement.h b/Source/core/svg/SVGFontFaceNameElement.h
index 3d83e20..8b93942 100644
--- a/Source/core/svg/SVGFontFaceNameElement.h
+++ b/Source/core/svg/SVGFontFaceNameElement.h
@@ -30,12 +30,12 @@
 
 class SVGFontFaceNameElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceNameElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFontFaceNameElement> create(Document&);
 
     PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
 
 private:
-    SVGFontFaceNameElement(const QualifiedName&, Document&);
+    explicit SVGFontFaceNameElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
diff --git a/Source/core/svg/SVGFontFaceSrcElement.cpp b/Source/core/svg/SVGFontFaceSrcElement.cpp
index e5ba1db..bc2254d 100644
--- a/Source/core/svg/SVGFontFaceSrcElement.cpp
+++ b/Source/core/svg/SVGFontFaceSrcElement.cpp
@@ -33,16 +33,15 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceSrcElement::SVGFontFaceSrcElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFontFaceSrcElement::SVGFontFaceSrcElement(Document& document)
+    : SVGElement(font_face_srcTag, document)
 {
-    ASSERT(hasTagName(font_face_srcTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceSrcElement> SVGFontFaceSrcElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceSrcElement> SVGFontFaceSrcElement::create(Document& document)
 {
-    return adoptRef(new SVGFontFaceSrcElement(tagName, document));
+    return adoptRef(new SVGFontFaceSrcElement(document));
 }
 
 PassRefPtr<CSSValueList> SVGFontFaceSrcElement::srcValue() const
diff --git a/Source/core/svg/SVGFontFaceSrcElement.h b/Source/core/svg/SVGFontFaceSrcElement.h
index eb11d7b..f7ef1af 100644
--- a/Source/core/svg/SVGFontFaceSrcElement.h
+++ b/Source/core/svg/SVGFontFaceSrcElement.h
@@ -29,12 +29,12 @@
 
 class SVGFontFaceSrcElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceSrcElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFontFaceSrcElement> create(Document&);
 
     PassRefPtr<CSSValueList> srcValue() const;
 
 private:
-    SVGFontFaceSrcElement(const QualifiedName&, Document&);
+    explicit SVGFontFaceSrcElement(Document&);
 
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
diff --git a/Source/core/svg/SVGFontFaceUriElement.cpp b/Source/core/svg/SVGFontFaceUriElement.cpp
index f5168be..6bda919 100644
--- a/Source/core/svg/SVGFontFaceUriElement.cpp
+++ b/Source/core/svg/SVGFontFaceUriElement.cpp
@@ -36,16 +36,15 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceUriElement::SVGFontFaceUriElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGFontFaceUriElement::SVGFontFaceUriElement(Document& document)
+    : SVGElement(font_face_uriTag, document)
 {
-    ASSERT(hasTagName(font_face_uriTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceUriElement> SVGFontFaceUriElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceUriElement> SVGFontFaceUriElement::create(Document& document)
 {
-    return adoptRef(new SVGFontFaceUriElement(tagName, document));
+    return adoptRef(new SVGFontFaceUriElement(document));
 }
 
 SVGFontFaceUriElement::~SVGFontFaceUriElement()
diff --git a/Source/core/svg/SVGFontFaceUriElement.h b/Source/core/svg/SVGFontFaceUriElement.h
index 61a3478..338ce85 100644
--- a/Source/core/svg/SVGFontFaceUriElement.h
+++ b/Source/core/svg/SVGFontFaceUriElement.h
@@ -32,14 +32,14 @@
 
 class SVGFontFaceUriElement FINAL : public SVGElement, public FontResourceClient {
 public:
-    static PassRefPtr<SVGFontFaceUriElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGFontFaceUriElement> create(Document&);
 
     virtual ~SVGFontFaceUriElement();
 
     PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
 
 private:
-    SVGFontFaceUriElement(const QualifiedName&, Document&);
+    explicit SVGFontFaceUriElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
diff --git a/Source/core/svg/SVGForeignObjectElement.cpp b/Source/core/svg/SVGForeignObjectElement.cpp
index e8a99a2..2ef541b 100644
--- a/Source/core/svg/SVGForeignObjectElement.cpp
+++ b/Source/core/svg/SVGForeignObjectElement.cpp
@@ -49,21 +49,20 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGForeignObjectElement::SVGForeignObjectElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGForeignObjectElement::SVGForeignObjectElement(Document& document)
+    : SVGGraphicsElement(SVGNames::foreignObjectTag, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
     , m_height(LengthModeHeight)
 {
-    ASSERT(hasTagName(SVGNames::foreignObjectTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGForeignObjectElement();
 }
 
-PassRefPtr<SVGForeignObjectElement> SVGForeignObjectElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGForeignObjectElement> SVGForeignObjectElement::create(Document& document)
 {
-    return adoptRef(new SVGForeignObjectElement(tagName, document));
+    return adoptRef(new SVGForeignObjectElement(document));
 }
 
 bool SVGForeignObjectElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGForeignObjectElement.h b/Source/core/svg/SVGForeignObjectElement.h
index 68ed016..38d3734 100644
--- a/Source/core/svg/SVGForeignObjectElement.h
+++ b/Source/core/svg/SVGForeignObjectElement.h
@@ -32,10 +32,10 @@
 class SVGForeignObjectElement FINAL : public SVGGraphicsElement,
                                       public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGForeignObjectElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGForeignObjectElement> create(Document&);
 
 private:
-    SVGForeignObjectElement(const QualifiedName&, Document&);
+    explicit SVGForeignObjectElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     bool isSupportedAttribute(const QualifiedName&);
diff --git a/Source/core/svg/SVGGElement.cpp b/Source/core/svg/SVGGElement.cpp
index 20e2dd8..aa767c0 100644
--- a/Source/core/svg/SVGGElement.cpp
+++ b/Source/core/svg/SVGGElement.cpp
@@ -38,17 +38,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGGElement::SVGGElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
-    : SVGGraphicsElement(tagName, document, constructionType)
+SVGGElement::SVGGElement(Document& document, ConstructionType constructionType)
+    : SVGGraphicsElement(SVGNames::gTag, document, constructionType)
 {
-    ASSERT(hasTagName(SVGNames::gTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGGElement();
 }
 
-PassRefPtr<SVGGElement> SVGGElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGGElement> SVGGElement::create(Document& document)
 {
-    return adoptRef(new SVGGElement(tagName, document));
+    return adoptRef(new SVGGElement(document));
 }
 
 bool SVGGElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGGElement.h b/Source/core/svg/SVGGElement.h
index ee1e91a..255e514 100644
--- a/Source/core/svg/SVGGElement.h
+++ b/Source/core/svg/SVGGElement.h
@@ -30,10 +30,10 @@
 class SVGGElement FINAL : public SVGGraphicsElement,
                           public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGGElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGGElement> create(Document&);
 
 protected:
-    SVGGElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
+    explicit SVGGElement(Document&, ConstructionType = CreateSVGElement);
 
     virtual RenderObject* createRenderer(RenderStyle*);
 
diff --git a/Source/core/svg/SVGGeometryElement.cpp b/Source/core/svg/SVGGeometryElement.cpp
new file mode 100644
index 0000000..56b3d03
--- /dev/null
+++ b/Source/core/svg/SVGGeometryElement.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Samsung Electronics. 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/svg/SVGGeometryElement.h"
+
+#include "SVGNames.h"
+#include "core/rendering/HitTestRequest.h"
+#include "core/rendering/PointerEventsHitRules.h"
+#include "core/rendering/svg/RenderSVGShape.h"
+
+namespace WebCore {
+
+SVGGeometryElement::SVGGeometryElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
+    : SVGGraphicsElement(tagName, document, constructionType)
+{
+}
+
+bool SVGGeometryElement::isPointInFill(const SVGPoint& point) const
+{
+    document().updateLayoutIgnorePendingStylesheets();
+
+    // FIXME: Eventually we should support isPointInFill for display:none elements.
+    if (!renderer() || !renderer()->isSVGShape())
+        return false;
+
+    HitTestRequest request(HitTestRequest::ReadOnly);
+    PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, renderer()->style()->pointerEvents());
+    hitRules.canHitStroke = false;
+    return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point, hitRules);
+}
+
+bool SVGGeometryElement::isPointInStroke(const SVGPoint& point) const
+{
+    document().updateLayoutIgnorePendingStylesheets();
+
+    // FIXME: Eventually we should support isPointInStroke for display:none elements.
+    if (!renderer() || !renderer()->isSVGShape())
+        return false;
+
+    HitTestRequest request(HitTestRequest::ReadOnly);
+    PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, renderer()->style()->pointerEvents());
+    hitRules.canHitFill = false;
+    return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point, hitRules);
+}
+
+}
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.cpp b/Source/core/svg/SVGGeometryElement.h
similarity index 75%
copy from Source/core/workers/WorkerGlobalScopeProxy.cpp
copy to Source/core/svg/SVGGeometryElement.h
index 06471bb..09fffa5 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ b/Source/core/svg/SVGGeometryElement.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,11 +28,23 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
+#ifndef SVGGeometryElement_h
+#define SVGGeometryElement_h
+
+#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGPoint.h"
 
 namespace WebCore {
 
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
+class SVGGeometryElement : public SVGGraphicsElement {
+public:
+    bool isPointInFill(const SVGPoint&) const;
+    bool isPointInStroke(const SVGPoint&) const;
+
+protected:
+    SVGGeometryElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
+};
 
 } // namespace WebCore
+
+#endif // SVGGraphicsElement_h
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.cpp b/Source/core/svg/SVGGeometryElement.idl
similarity index 84%
rename from Source/core/workers/WorkerGlobalScopeProxy.cpp
rename to Source/core/svg/SVGGeometryElement.idl
index 06471bb..d783758 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ b/Source/core/svg/SVGGeometryElement.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,11 +28,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
-
-namespace WebCore {
-
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
-
-} // namespace WebCore
+interface SVGGeometryElement : SVGGraphicsElement {
+    boolean isPointInFill(SVGPoint point);
+    boolean isPointInStroke(SVGPoint point);
+};
diff --git a/Source/core/svg/SVGGlyphElement.cpp b/Source/core/svg/SVGGlyphElement.cpp
index 93263a2..669d663 100644
--- a/Source/core/svg/SVGGlyphElement.cpp
+++ b/Source/core/svg/SVGGlyphElement.cpp
@@ -31,16 +31,15 @@
 
 namespace WebCore {
 
-inline SVGGlyphElement::SVGGlyphElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGGlyphElement::SVGGlyphElement(Document& document)
+    : SVGElement(SVGNames::glyphTag, document)
 {
-    ASSERT(hasTagName(SVGNames::glyphTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGGlyphElement> SVGGlyphElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGGlyphElement> SVGGlyphElement::create(Document& document)
 {
-    return adoptRef(new SVGGlyphElement(tagName, document));
+    return adoptRef(new SVGGlyphElement(document));
 }
 
 void SVGGlyphElement::invalidateGlyphCache()
diff --git a/Source/core/svg/SVGGlyphElement.h b/Source/core/svg/SVGGlyphElement.h
index a08bc82..86a6b80 100644
--- a/Source/core/svg/SVGGlyphElement.h
+++ b/Source/core/svg/SVGGlyphElement.h
@@ -33,7 +33,7 @@
 
 class SVGGlyphElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGGlyphElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGGlyphElement> create(Document&);
 
     SVGGlyph buildGlyphIdentifier() const;
 
@@ -45,7 +45,7 @@
     static SVGGlyph buildGenericGlyphIdentifier(const SVGElement*);
 
 private:
-    SVGGlyphElement(const QualifiedName&, Document&);
+    explicit SVGGlyphElement(Document&);
 
     // FIXME: svgAttributeChanged missing.
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGGlyphRefElement.cpp b/Source/core/svg/SVGGlyphRefElement.cpp
index 159a20b..63908b4 100644
--- a/Source/core/svg/SVGGlyphRefElement.cpp
+++ b/Source/core/svg/SVGGlyphRefElement.cpp
@@ -37,21 +37,20 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGGlyphRefElement::SVGGlyphRefElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGGlyphRefElement::SVGGlyphRefElement(Document& document)
+    : SVGElement(SVGNames::glyphRefTag, document)
     , m_x(0)
     , m_y(0)
     , m_dx(0)
     , m_dy(0)
 {
-    ASSERT(hasTagName(SVGNames::glyphRefTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGGlyphRefElement();
 }
 
-PassRefPtr<SVGGlyphRefElement> SVGGlyphRefElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGGlyphRefElement> SVGGlyphRefElement::create(Document& document)
 {
-    return adoptRef(new SVGGlyphRefElement(tagName, document));
+    return adoptRef(new SVGGlyphRefElement(document));
 }
 
 bool SVGGlyphRefElement::hasValidGlyphElement(String& glyphName) const
diff --git a/Source/core/svg/SVGGlyphRefElement.h b/Source/core/svg/SVGGlyphRefElement.h
index 9afe97d..8de1d2b 100644
--- a/Source/core/svg/SVGGlyphRefElement.h
+++ b/Source/core/svg/SVGGlyphRefElement.h
@@ -30,7 +30,7 @@
 class SVGGlyphRefElement FINAL : public SVGElement,
                                  public SVGURIReference {
 public:
-    static PassRefPtr<SVGGlyphRefElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGGlyphRefElement> create(Document&);
 
     bool hasValidGlyphElement(String& glyphName) const;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -48,7 +48,7 @@
     void setDy(float);
 
 private:
-    SVGGlyphRefElement(const QualifiedName&, Document&);
+    explicit SVGGlyphRefElement(Document&);
 
     template<typename CharType>
     void parseAttributeInternal(const QualifiedName&, const AtomicString&);
diff --git a/Source/core/svg/SVGGradientElement.cpp b/Source/core/svg/SVGGradientElement.cpp
index 063bc58..614cca3 100644
--- a/Source/core/svg/SVGGradientElement.cpp
+++ b/Source/core/svg/SVGGradientElement.cpp
@@ -33,7 +33,6 @@
 #include "core/svg/SVGElementInstance.h"
 #include "core/svg/SVGStopElement.h"
 #include "core/svg/SVGTransformList.h"
-#include "core/svg/SVGTransformable.h"
 
 namespace WebCore {
 
diff --git a/Source/core/svg/SVGGraphicsElement.cpp b/Source/core/svg/SVGGraphicsElement.cpp
index 2d9afe5..95bb0c2 100644
--- a/Source/core/svg/SVGGraphicsElement.cpp
+++ b/Source/core/svg/SVGGraphicsElement.cpp
@@ -50,14 +50,53 @@
 {
 }
 
+AffineTransform SVGGraphicsElement::getTransformToElement(SVGElement* target, ExceptionState& exceptionState)
+{
+    AffineTransform ctm = getCTM(AllowStyleUpdate);
+
+    if (target && target->isSVGGraphicsElement()) {
+        AffineTransform targetCTM = toSVGGraphicsElement(target)->getCTM(AllowStyleUpdate);
+        if (!targetCTM.isInvertible()) {
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+            return ctm;
+        }
+        ctm = targetCTM.inverse() * ctm;
+    }
+
+    return ctm;
+}
+
+static AffineTransform computeCTM(SVGGraphicsElement* element, SVGElement::CTMScope mode, SVGGraphicsElement::StyleUpdateStrategy styleUpdateStrategy)
+{
+    ASSERT(element);
+    if (styleUpdateStrategy == SVGGraphicsElement::AllowStyleUpdate)
+        element->document().updateLayoutIgnorePendingStylesheets();
+
+    AffineTransform ctm;
+
+    SVGElement* stopAtElement = mode == SVGGraphicsElement::NearestViewportScope ? element->nearestViewportElement() : 0;
+    for (Element* currentElement = element; currentElement; currentElement = currentElement->parentOrShadowHostElement()) {
+        if (!currentElement->isSVGElement())
+            break;
+
+        ctm = toSVGElement(currentElement)->localCoordinateSpaceTransform(mode).multiply(ctm);
+
+        // For getCTM() computation, stop at the nearest viewport element
+        if (currentElement == stopAtElement)
+            break;
+    }
+
+    return ctm;
+}
+
 AffineTransform SVGGraphicsElement::getCTM(StyleUpdateStrategy styleUpdateStrategy)
 {
-    return SVGLocatable::computeCTM(this, SVGLocatable::NearestViewportScope, styleUpdateStrategy);
+    return computeCTM(this, NearestViewportScope, styleUpdateStrategy);
 }
 
 AffineTransform SVGGraphicsElement::getScreenCTM(StyleUpdateStrategy styleUpdateStrategy)
 {
-    return SVGLocatable::computeCTM(this, SVGLocatable::ScreenScope, styleUpdateStrategy);
+    return computeCTM(this, ScreenScope, styleUpdateStrategy);
 }
 
 AffineTransform SVGGraphicsElement::animatedLocalTransform() const
@@ -156,14 +195,32 @@
     ASSERT_NOT_REACHED();
 }
 
+static bool isViewportElement(Node* node)
+{
+    return (node->hasTagName(SVGNames::svgTag)
+        || node->hasTagName(SVGNames::symbolTag)
+        || node->hasTagName(SVGNames::foreignObjectTag)
+        || node->hasTagName(SVGNames::imageTag));
+}
+
 SVGElement* SVGGraphicsElement::nearestViewportElement() const
 {
-    return SVGTransformable::nearestViewportElement(this);
+    for (Element* current = parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
+        if (isViewportElement(current))
+            return toSVGElement(current);
+    }
+
+    return 0;
 }
 
 SVGElement* SVGGraphicsElement::farthestViewportElement() const
 {
-    return SVGTransformable::farthestViewportElement(this);
+    SVGElement* farthest = 0;
+    for (Element* current = parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
+        if (isViewportElement(current))
+            farthest = toSVGElement(current);
+    }
+    return farthest;
 }
 
 SVGRect SVGGraphicsElement::getBBox()
diff --git a/Source/core/svg/SVGGraphicsElement.h b/Source/core/svg/SVGGraphicsElement.h
index 1e20804..3190334 100644
--- a/Source/core/svg/SVGGraphicsElement.h
+++ b/Source/core/svg/SVGGraphicsElement.h
@@ -24,23 +24,25 @@
 #include "core/svg/SVGAnimatedTransformList.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGTests.h"
-#include "core/svg/SVGTransformable.h"
 
 namespace WebCore {
 
 class AffineTransform;
 class Path;
 
-class SVGGraphicsElement : public SVGElement, public SVGTransformable, public SVGTests {
+class SVGGraphicsElement : public SVGElement, public SVGTests {
 public:
     virtual ~SVGGraphicsElement();
 
-    virtual AffineTransform getCTM(StyleUpdateStrategy = AllowStyleUpdate);
-    virtual AffineTransform getScreenCTM(StyleUpdateStrategy = AllowStyleUpdate);
-    virtual SVGElement* nearestViewportElement() const;
-    virtual SVGElement* farthestViewportElement() const;
+    enum StyleUpdateStrategy { AllowStyleUpdate, DisallowStyleUpdate };
 
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope mode) const { return SVGTransformable::localCoordinateSpaceTransform(mode); }
+    AffineTransform getCTM(StyleUpdateStrategy = AllowStyleUpdate);
+    AffineTransform getScreenCTM(StyleUpdateStrategy = AllowStyleUpdate);
+    AffineTransform getTransformToElement(SVGElement*, ExceptionState&);
+    SVGElement* nearestViewportElement() const;
+    SVGElement* farthestViewportElement() const;
+
+    virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const OVERRIDE { return animatedLocalTransform(); }
     virtual AffineTransform animatedLocalTransform() const;
     virtual AffineTransform* supplementalTransform();
 
diff --git a/Source/core/svg/SVGHKernElement.cpp b/Source/core/svg/SVGHKernElement.cpp
index d927727..1bdac71 100644
--- a/Source/core/svg/SVGHKernElement.cpp
+++ b/Source/core/svg/SVGHKernElement.cpp
@@ -29,16 +29,15 @@
 
 namespace WebCore {
 
-inline SVGHKernElement::SVGHKernElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGHKernElement::SVGHKernElement(Document& document)
+    : SVGElement(SVGNames::hkernTag, document)
 {
-    ASSERT(hasTagName(SVGNames::hkernTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGHKernElement> SVGHKernElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGHKernElement> SVGHKernElement::create(Document& document)
 {
-    return adoptRef(new SVGHKernElement(tagName, document));
+    return adoptRef(new SVGHKernElement(document));
 }
 
 Node::InsertionNotificationRequest SVGHKernElement::insertedInto(ContainerNode* rootParent)
diff --git a/Source/core/svg/SVGHKernElement.h b/Source/core/svg/SVGHKernElement.h
index 719a5aa..d54d89d 100644
--- a/Source/core/svg/SVGHKernElement.h
+++ b/Source/core/svg/SVGHKernElement.h
@@ -30,12 +30,12 @@
 
 class SVGHKernElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGHKernElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGHKernElement> create(Document&);
 
     void buildHorizontalKerningPair(KerningPairVector&);
 
 private:
-    SVGHKernElement(const QualifiedName&, Document&);
+    explicit SVGHKernElement(Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/svg/SVGImageElement.cpp b/Source/core/svg/SVGImageElement.cpp
index 9533db1..4b54acc 100644
--- a/Source/core/svg/SVGImageElement.cpp
+++ b/Source/core/svg/SVGImageElement.cpp
@@ -53,22 +53,21 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGImageElement::SVGImageElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGImageElement::SVGImageElement(Document& document)
+    : SVGGraphicsElement(SVGNames::imageTag, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
     , m_height(LengthModeHeight)
     , m_imageLoader(this)
 {
-    ASSERT(hasTagName(SVGNames::imageTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGImageElement();
 }
 
-PassRefPtr<SVGImageElement> SVGImageElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGImageElement> SVGImageElement::create(Document& document)
 {
-    return adoptRef(new SVGImageElement(tagName, document));
+    return adoptRef(new SVGImageElement(document));
 }
 
 bool SVGImageElement::currentFrameHasSingleSecurityOrigin() const
diff --git a/Source/core/svg/SVGImageElement.h b/Source/core/svg/SVGImageElement.h
index c58bde7..1270dc1 100644
--- a/Source/core/svg/SVGImageElement.h
+++ b/Source/core/svg/SVGImageElement.h
@@ -36,12 +36,12 @@
                               public SVGExternalResourcesRequired,
                               public SVGURIReference {
 public:
-    static PassRefPtr<SVGImageElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGImageElement> create(Document&);
 
     bool currentFrameHasSingleSecurityOrigin() const;
 
 private:
-    SVGImageElement(const QualifiedName&, Document&);
+    explicit SVGImageElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGLength.cpp b/Source/core/svg/SVGLength.cpp
index b4843b5..4b0a06c 100644
--- a/Source/core/svg/SVGLength.cpp
+++ b/Source/core/svg/SVGLength.cpp
@@ -150,11 +150,11 @@
 {
 }
 
-void SVGLength::setValueAsString(const String& valueAsString, SVGLengthMode mode, ExceptionState& es)
+void SVGLength::setValueAsString(const String& valueAsString, SVGLengthMode mode, ExceptionState& exceptionState)
 {
     m_valueInSpecifiedUnits = 0;
     m_unit = storeUnit(mode, LengthTypeNumber);
-    setValueAsString(valueAsString, es);
+    setValueAsString(valueAsString, exceptionState);
 }
 
 bool SVGLength::operator==(const SVGLength& other) const
@@ -170,12 +170,12 @@
 
 SVGLength SVGLength::construct(SVGLengthMode mode, const String& valueAsString, SVGParsingError& parseError, SVGLengthNegativeValuesMode negativeValuesMode)
 {
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
     SVGLength length(mode);
 
-    length.setValueAsString(valueAsString, es);
+    length.setValueAsString(valueAsString, exceptionState);
 
-    if (es.hadException())
+    if (exceptionState.hadException())
         parseError = ParsingAttributeFailedError;
     else if (negativeValuesMode == ForbidNegativeLengths && length.valueInSpecifiedUnits() < 0)
         parseError = NegativeValueForbiddenError;
@@ -198,25 +198,25 @@
     return value(context, IGNORE_EXCEPTION);
 }
 
-float SVGLength::value(const SVGLengthContext& context, ExceptionState& es) const
+float SVGLength::value(const SVGLengthContext& context, ExceptionState& exceptionState) const
 {
-    return context.convertValueToUserUnits(m_valueInSpecifiedUnits, extractMode(m_unit), extractType(m_unit), es);
+    return context.convertValueToUserUnits(m_valueInSpecifiedUnits, extractMode(m_unit), extractType(m_unit), exceptionState);
 }
 
-void SVGLength::setValue(const SVGLengthContext& context, float value, SVGLengthMode mode, SVGLengthType unitType, ExceptionState& es)
+void SVGLength::setValue(const SVGLengthContext& context, float value, SVGLengthMode mode, SVGLengthType unitType, ExceptionState& exceptionState)
 {
     m_unit = storeUnit(mode, unitType);
-    setValue(value, context, es);
+    setValue(value, context, exceptionState);
 }
 
-void SVGLength::setValue(float value, const SVGLengthContext& context, ExceptionState& es)
+void SVGLength::setValue(float value, const SVGLengthContext& context, ExceptionState& exceptionState)
 {
     // 100% = 100.0 instead of 1.0 for historical reasons, this could eventually be changed
     if (extractType(m_unit) == LengthTypePercentage)
         value = value / 100;
 
-    float convertedValue = context.convertValueFromUserUnits(value, extractMode(m_unit), extractType(m_unit), es);
-    if (!es.hadException())
+    float convertedValue = context.convertValueFromUserUnits(value, extractMode(m_unit), extractType(m_unit), exceptionState);
+    if (!exceptionState.hadException())
         m_valueInSpecifiedUnits = convertedValue;
 }
 float SVGLength::valueAsPercentage() const
@@ -245,7 +245,7 @@
     return true;
 }
 
-void SVGLength::setValueAsString(const String& string, ExceptionState& es)
+void SVGLength::setValueAsString(const String& string, ExceptionState& exceptionState)
 {
     if (string.isEmpty())
         return;
@@ -258,7 +258,7 @@
         parseValueInternal<UChar>(string, convertedNumber, type);
 
     if (!success) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
@@ -271,10 +271,10 @@
     return String::number(m_valueInSpecifiedUnits) + lengthTypeToString(extractType(m_unit));
 }
 
-void SVGLength::newValueSpecifiedUnits(unsigned short type, float value, ExceptionState& es)
+void SVGLength::newValueSpecifiedUnits(unsigned short type, float value, ExceptionState& exceptionState)
 {
     if (type == LengthTypeUnknown || type > LengthTypePC) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
@@ -282,21 +282,21 @@
     m_valueInSpecifiedUnits = value;
 }
 
-void SVGLength::convertToSpecifiedUnits(unsigned short type, const SVGLengthContext& context, ExceptionState& es)
+void SVGLength::convertToSpecifiedUnits(unsigned short type, const SVGLengthContext& context, ExceptionState& exceptionState)
 {
     if (type == LengthTypeUnknown || type > LengthTypePC) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
-    float valueInUserUnits = value(context, es);
-    if (es.hadException())
+    float valueInUserUnits = value(context, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     unsigned int originalUnitAndType = m_unit;
     m_unit = storeUnit(extractMode(m_unit), toSVGLengthType(type));
-    setValue(valueInUserUnits, context, es);
-    if (!es.hadException())
+    setValue(valueInUserUnits, context, exceptionState);
+    if (!exceptionState.hadException())
         return;
 
     // Eventually restore old unit and type
@@ -348,10 +348,10 @@
     if (svgType == LengthTypeUnknown)
         return SVGLength();
 
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
     SVGLength length;
-    length.newValueSpecifiedUnits(svgType, value->getFloatValue(), es);
-    if (es.hadException())
+    length.newValueSpecifiedUnits(svgType, value->getFloatValue(), exceptionState);
+    if (exceptionState.hadException())
         return SVGLength();
 
     return length;
diff --git a/Source/core/svg/SVGLength.h b/Source/core/svg/SVGLength.h
index b43f59c..3131050 100644
--- a/Source/core/svg/SVGLength.h
+++ b/Source/core/svg/SVGLength.h
@@ -114,13 +114,13 @@
             return *this;
 
         SVGLength length;
-        TrackExceptionState es;
+        TrackExceptionState exceptionState;
 
         if (fromType == LengthTypePercentage || toType == LengthTypePercentage) {
             float fromPercent = from.valueAsPercentage() * 100;
             float toPercent = valueAsPercentage() * 100;
-            length.newValueSpecifiedUnits(LengthTypePercentage, WebCore::blend(fromPercent, toPercent, progress), es);
-            if (es.hadException())
+            length.newValueSpecifiedUnits(LengthTypePercentage, WebCore::blend(fromPercent, toPercent, progress), exceptionState);
+            if (exceptionState.hadException())
                 return SVGLength();
             return length;
         }
@@ -129,10 +129,10 @@
             float fromValue = from.valueInSpecifiedUnits();
             float toValue = valueInSpecifiedUnits();
             if (isZero())
-                length.newValueSpecifiedUnits(fromType, WebCore::blend(fromValue, toValue, progress), es);
+                length.newValueSpecifiedUnits(fromType, WebCore::blend(fromValue, toValue, progress), exceptionState);
             else
-                length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), es);
-            if (es.hadException())
+                length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), exceptionState);
+            if (exceptionState.hadException())
                 return SVGLength();
             return length;
         }
@@ -141,18 +141,18 @@
         ASSERT(!from.isRelative());
 
         SVGLengthContext nonRelativeLengthContext(0);
-        float fromValueInUserUnits = nonRelativeLengthContext.convertValueToUserUnits(from.valueInSpecifiedUnits(), from.unitMode(), fromType, es);
-        if (es.hadException())
+        float fromValueInUserUnits = nonRelativeLengthContext.convertValueToUserUnits(from.valueInSpecifiedUnits(), from.unitMode(), fromType, exceptionState);
+        if (exceptionState.hadException())
             return SVGLength();
 
-        float fromValue = nonRelativeLengthContext.convertValueFromUserUnits(fromValueInUserUnits, unitMode(), toType, es);
-        if (es.hadException())
+        float fromValue = nonRelativeLengthContext.convertValueFromUserUnits(fromValueInUserUnits, unitMode(), toType, exceptionState);
+        if (exceptionState.hadException())
             return SVGLength();
 
         float toValue = valueInSpecifiedUnits();
-        length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), es);
+        length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), exceptionState);
 
-        if (es.hadException())
+        if (exceptionState.hadException())
             return SVGLength();
         return length;
     }
diff --git a/Source/core/svg/SVGLength.idl b/Source/core/svg/SVGLength.idl
index e073b1a..4d29af7 100644
--- a/Source/core/svg/SVGLength.idl
+++ b/Source/core/svg/SVGLength.idl
@@ -35,10 +35,10 @@
     const unsigned short SVG_LENGTHTYPE_PC         = 10;
 
     readonly attribute unsigned short unitType;
-    [Custom, StrictTypeChecking, GetterRaisesException, SetterRaisesException] attribute float value;
+    [Custom, StrictTypeChecking, RaisesException] attribute float value;
 
     [StrictTypeChecking] attribute float valueInSpecifiedUnits;
-    [TreatNullAs=NullString, StrictTypeChecking, SetterRaisesException] attribute DOMString valueAsString;
+    [TreatNullAs=NullString, StrictTypeChecking, RaisesException=Setter] attribute DOMString valueAsString;
 
     [StrictTypeChecking, RaisesException] void newValueSpecifiedUnits(unsigned short unitType,
                                                      float valueInSpecifiedUnits);
diff --git a/Source/core/svg/SVGLengthContext.cpp b/Source/core/svg/SVGLengthContext.cpp
index 0b75f92..8146c8b 100644
--- a/Source/core/svg/SVGLengthContext.cpp
+++ b/Source/core/svg/SVGLengthContext.cpp
@@ -86,30 +86,30 @@
     return x.valueAsPercentage();
 }
 
-float SVGLengthContext::convertValueToUserUnits(float value, SVGLengthMode mode, SVGLengthType fromUnit, ExceptionState& es) const
+float SVGLengthContext::convertValueToUserUnits(float value, SVGLengthMode mode, SVGLengthType fromUnit, ExceptionState& exceptionState) const
 {
     // If the SVGLengthContext carries a custom viewport, force resolving against it.
     if (!m_overridenViewport.isEmpty()) {
         // 100% = 100.0 instead of 1.0 for historical reasons, this could eventually be changed
         if (fromUnit == LengthTypePercentage)
             value /= 100;
-        return convertValueFromPercentageToUserUnits(value, mode, es);
+        return convertValueFromPercentageToUserUnits(value, mode, exceptionState);
     }
 
     switch (fromUnit) {
     case LengthTypeUnknown:
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     case LengthTypeNumber:
         return value;
     case LengthTypePX:
         return value;
     case LengthTypePercentage:
-        return convertValueFromPercentageToUserUnits(value / 100, mode, es);
+        return convertValueFromPercentageToUserUnits(value / 100, mode, exceptionState);
     case LengthTypeEMS:
-        return convertValueFromEMSToUserUnits(value, es);
+        return convertValueFromEMSToUserUnits(value, exceptionState);
     case LengthTypeEXS:
-        return convertValueFromEXSToUserUnits(value, es);
+        return convertValueFromEXSToUserUnits(value, exceptionState);
     case LengthTypeCM:
         return value * cssPixelsPerInch / 2.54f;
     case LengthTypeMM:
@@ -126,20 +126,20 @@
     return 0;
 }
 
-float SVGLengthContext::convertValueFromUserUnits(float value, SVGLengthMode mode, SVGLengthType toUnit, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnits(float value, SVGLengthMode mode, SVGLengthType toUnit, ExceptionState& exceptionState) const
 {
     switch (toUnit) {
     case LengthTypeUnknown:
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     case LengthTypeNumber:
         return value;
     case LengthTypePercentage:
-        return convertValueFromUserUnitsToPercentage(value * 100, mode, es);
+        return convertValueFromUserUnitsToPercentage(value * 100, mode, exceptionState);
     case LengthTypeEMS:
-        return convertValueFromUserUnitsToEMS(value, es);
+        return convertValueFromUserUnitsToEMS(value, exceptionState);
     case LengthTypeEXS:
-        return convertValueFromUserUnitsToEXS(value, es);
+        return convertValueFromUserUnitsToEXS(value, exceptionState);
     case LengthTypePX:
         return value;
     case LengthTypeCM:
@@ -158,44 +158,42 @@
     return 0;
 }
 
-float SVGLengthContext::convertValueFromUserUnitsToPercentage(float value, SVGLengthMode mode, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnitsToPercentage(float value, SVGLengthMode mode, ExceptionState& exceptionState) const
 {
-    float width = 0;
-    float height = 0;
-    if (!determineViewport(width, height)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+    FloatSize viewportSize;
+    if (!determineViewport(viewportSize)) {
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     switch (mode) {
     case LengthModeWidth:
-        return value / width * 100;
+        return value / viewportSize.width() * 100;
     case LengthModeHeight:
-        return value / height * 100;
+        return value / viewportSize.height() * 100;
     case LengthModeOther:
-        return value / (sqrtf((width * width + height * height) / 2)) * 100;
+        return value / sqrtf(viewportSize.diagonalLengthSquared() / 2) * 100;
     };
 
     ASSERT_NOT_REACHED();
     return 0;
 }
 
-float SVGLengthContext::convertValueFromPercentageToUserUnits(float value, SVGLengthMode mode, ExceptionState& es) const
+float SVGLengthContext::convertValueFromPercentageToUserUnits(float value, SVGLengthMode mode, ExceptionState& exceptionState) const
 {
-    float width = 0;
-    float height = 0;
-    if (!determineViewport(width, height)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+    FloatSize viewportSize;
+    if (!determineViewport(viewportSize)) {
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     switch (mode) {
     case LengthModeWidth:
-        return value * width;
+        return value * viewportSize.width();
     case LengthModeHeight:
-        return value * height;
+        return value * viewportSize.height();
     case LengthModeOther:
-        return value * sqrtf((width * width + height * height) / 2);
+        return value * sqrtf(viewportSize.diagonalLengthSquared() / 2);
     };
 
     ASSERT_NOT_REACHED();
@@ -219,39 +217,39 @@
     return 0;
 }
 
-float SVGLengthContext::convertValueFromUserUnitsToEMS(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnitsToEMS(float value, ExceptionState& exceptionState) const
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     float fontSize = style->specifiedFontSize();
     if (!fontSize) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     return value / fontSize;
 }
 
-float SVGLengthContext::convertValueFromEMSToUserUnits(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromEMSToUserUnits(float value, ExceptionState& exceptionState) const
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     return value * style->specifiedFontSize();
 }
 
-float SVGLengthContext::convertValueFromUserUnitsToEXS(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnitsToEXS(float value, ExceptionState& exceptionState) const
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
@@ -259,18 +257,18 @@
     // if this causes problems in real world cases maybe it would be best to remove this
     float xHeight = ceilf(style->fontMetrics().xHeight());
     if (!xHeight) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
     return value / xHeight;
 }
 
-float SVGLengthContext::convertValueFromEXSToUserUnits(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromEXSToUserUnits(float value, ExceptionState& exceptionState) const
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
 
@@ -279,21 +277,22 @@
     return value * ceilf(style->fontMetrics().xHeight());
 }
 
-bool SVGLengthContext::determineViewport(float& width, float& height) const
+bool SVGLengthContext::determineViewport(FloatSize& viewportSize) const
 {
     if (!m_context)
         return false;
 
     // If an overriden viewport is given, it has precedence.
     if (!m_overridenViewport.isEmpty()) {
-        width = m_overridenViewport.width();
-        height = m_overridenViewport.height();
+        viewportSize = m_overridenViewport.size();
         return true;
     }
 
-    // SVGLengthContext should NEVER be used to resolve width/height values for <svg> elements,
-    // as they require special treatment, due the relationship with the CSS width/height properties.
-    ASSERT(m_context->document().documentElement() != m_context);
+    // Root <svg> element lengths are resolved against the top level viewport.
+    if (m_context->isOutermostSVGSVGElement()) {
+        viewportSize = toSVGSVGElement(m_context)->currentViewportSize();
+        return true;
+    }
 
     // Take size from nearest viewport element.
     SVGElement* viewportElement = m_context->viewportElement();
@@ -301,12 +300,10 @@
         return false;
 
     const SVGSVGElement* svg = static_cast<const SVGSVGElement*>(viewportElement);
-    FloatSize viewportSize = svg->currentViewBoxRect().size();
+    viewportSize = svg->currentViewBoxRect().size();
     if (viewportSize.isEmpty())
         viewportSize = svg->currentViewportSize();
 
-    width = viewportSize.width();
-    height = viewportSize.height();
     return true;
 }
 
diff --git a/Source/core/svg/SVGLengthContext.h b/Source/core/svg/SVGLengthContext.h
index 5bb2130..64c2370 100644
--- a/Source/core/svg/SVGLengthContext.h
+++ b/Source/core/svg/SVGLengthContext.h
@@ -66,7 +66,7 @@
     float convertValueToUserUnits(float, SVGLengthMode, SVGLengthType fromUnit, ExceptionState&) const;
     float convertValueFromUserUnits(float, SVGLengthMode, SVGLengthType toUnit, ExceptionState&) const;
 
-    bool determineViewport(float& width, float& height) const;
+    bool determineViewport(FloatSize&) const;
 
 private:
     SVGLengthContext(const SVGElement*, const FloatRect& viewport);
diff --git a/Source/core/svg/SVGLengthList.cpp b/Source/core/svg/SVGLengthList.cpp
index 02c1a07..1518d2c 100644
--- a/Source/core/svg/SVGLengthList.cpp
+++ b/Source/core/svg/SVGLengthList.cpp
@@ -30,7 +30,7 @@
 template<typename CharType>
 void SVGLengthList::parseInternal(const CharType*& ptr, const CharType* end, SVGLengthMode mode)
 {
-    TrackExceptionState es;
+    TrackExceptionState exceptionState;
 
     while (ptr < end) {
         const CharType* start = ptr;
@@ -43,8 +43,8 @@
         String valueString(start, ptr - start);
         if (valueString.isEmpty())
             return;
-        length.setValueAsString(valueString, es);
-        if (es.hadException())
+        length.setValueAsString(valueString, exceptionState);
+        if (exceptionState.hadException())
             return;
         append(length);
         skipOptionalSVGSpacesOrDelimiter(ptr, end);
diff --git a/Source/core/svg/SVGLineElement.cpp b/Source/core/svg/SVGLineElement.cpp
index fe21256..cfdec93 100644
--- a/Source/core/svg/SVGLineElement.cpp
+++ b/Source/core/svg/SVGLineElement.cpp
@@ -45,21 +45,20 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGLineElement::SVGLineElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGLineElement::SVGLineElement(Document& document)
+    : SVGGeometryElement(SVGNames::lineTag, document)
     , m_x1(LengthModeWidth)
     , m_y1(LengthModeHeight)
     , m_x2(LengthModeWidth)
     , m_y2(LengthModeHeight)
 {
-    ASSERT(hasTagName(SVGNames::lineTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGLineElement();
 }
 
-PassRefPtr<SVGLineElement> SVGLineElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGLineElement> SVGLineElement::create(Document& document)
 {
-    return adoptRef(new SVGLineElement(tagName, document));
+    return adoptRef(new SVGLineElement(document));
 }
 
 bool SVGLineElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -81,7 +80,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGGraphicsElement::parseAttribute(name, value);
+        SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::x1Attr)
         setX1BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::y1Attr)
@@ -101,7 +100,7 @@
 void SVGLineElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGGraphicsElement::svgAttributeChanged(attrName);
+        SVGGeometryElement::svgAttributeChanged(attrName);
         return;
     }
 
diff --git a/Source/core/svg/SVGLineElement.h b/Source/core/svg/SVGLineElement.h
index ad09477..68b961a 100644
--- a/Source/core/svg/SVGLineElement.h
+++ b/Source/core/svg/SVGLineElement.h
@@ -25,17 +25,17 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGLineElement FINAL : public SVGGraphicsElement,
+class SVGLineElement FINAL : public SVGGeometryElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGLineElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGLineElement> create(Document&);
 
 private:
-    SVGLineElement(const QualifiedName&, Document&);
+    explicit SVGLineElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGLineElement.idl b/Source/core/svg/SVGLineElement.idl
index 9df8fe6..a12e80b 100644
--- a/Source/core/svg/SVGLineElement.idl
+++ b/Source/core/svg/SVGLineElement.idl
@@ -23,7 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGLineElement : SVGGraphicsElement {
+interface SVGLineElement : SVGGeometryElement {
     readonly attribute SVGAnimatedLength x1;
     readonly attribute SVGAnimatedLength y1;
     readonly attribute SVGAnimatedLength x2;
diff --git a/Source/core/svg/SVGLinearGradientElement.cpp b/Source/core/svg/SVGLinearGradientElement.cpp
index 0c6ae17..36b3f49 100644
--- a/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/Source/core/svg/SVGLinearGradientElement.cpp
@@ -48,22 +48,21 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGLinearGradientElement::SVGLinearGradientElement(const QualifiedName& tagName, Document& document)
-    : SVGGradientElement(tagName, document)
+inline SVGLinearGradientElement::SVGLinearGradientElement(Document& document)
+    : SVGGradientElement(SVGNames::linearGradientTag, document)
     , m_x1(LengthModeWidth)
     , m_y1(LengthModeHeight)
     , m_x2(LengthModeWidth, "100%")
     , m_y2(LengthModeHeight)
 {
     // Spec: If the x2 attribute is not specified, the effect is as if a value of "100%" were specified.
-    ASSERT(hasTagName(SVGNames::linearGradientTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGLinearGradientElement();
 }
 
-PassRefPtr<SVGLinearGradientElement> SVGLinearGradientElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGLinearGradientElement> SVGLinearGradientElement::create(Document& document)
 {
-    return adoptRef(new SVGLinearGradientElement(tagName, document));
+    return adoptRef(new SVGLinearGradientElement(document));
 }
 
 bool SVGLinearGradientElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGLinearGradientElement.h b/Source/core/svg/SVGLinearGradientElement.h
index 758ee9c..179424e 100644
--- a/Source/core/svg/SVGLinearGradientElement.h
+++ b/Source/core/svg/SVGLinearGradientElement.h
@@ -31,12 +31,12 @@
 
 class SVGLinearGradientElement FINAL : public SVGGradientElement {
 public:
-    static PassRefPtr<SVGLinearGradientElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGLinearGradientElement> create(Document&);
 
     bool collectGradientAttributes(LinearGradientAttributes&);
 
 private:
-    SVGLinearGradientElement(const QualifiedName&, Document&);
+    explicit SVGLinearGradientElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGLocatable.cpp b/Source/core/svg/SVGLocatable.cpp
deleted file mode 100644
index b8faf5e..0000000
--- a/Source/core/svg/SVGLocatable.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2009 Google, Inc.  All rights reserved.
- * Copyright (C) Research In Motion Limited 2010. 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.
- */
-
-#include "config.h"
-#include "core/svg/SVGLocatable.h"
-
-#include "SVGNames.h"
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/rendering/RenderObject.h"
-#include "core/svg/SVGGraphicsElement.h"
-
-namespace WebCore {
-
-static bool isViewportElement(Node* node)
-{
-    return (node->hasTagName(SVGNames::svgTag)
-        || node->hasTagName(SVGNames::symbolTag)
-        || node->hasTagName(SVGNames::foreignObjectTag)
-        || node->hasTagName(SVGNames::imageTag));
-}
-
-SVGElement* SVGLocatable::nearestViewportElement(const SVGElement* element)
-{
-    ASSERT(element);
-    for (Element* current = element->parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
-        if (isViewportElement(current))
-            return toSVGElement(current);
-    }
-
-    return 0;
-}
-
-SVGElement* SVGLocatable::farthestViewportElement(const SVGElement* element)
-{
-    ASSERT(element);
-    SVGElement* farthest = 0;
-    for (Element* current = element->parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
-        if (isViewportElement(current))
-            farthest = toSVGElement(current);
-    }
-    return farthest;
-}
-
-AffineTransform SVGLocatable::computeCTM(SVGElement* element, CTMScope mode, StyleUpdateStrategy styleUpdateStrategy)
-{
-    ASSERT(element);
-    if (styleUpdateStrategy == AllowStyleUpdate)
-        element->document().updateLayoutIgnorePendingStylesheets();
-
-    AffineTransform ctm;
-
-    SVGElement* stopAtElement = mode == NearestViewportScope ? nearestViewportElement(element) : 0;
-    for (Element* currentElement = element; currentElement; currentElement = currentElement->parentOrShadowHostElement()) {
-        if (!currentElement->isSVGElement())
-            break;
-
-        ctm = toSVGElement(currentElement)->localCoordinateSpaceTransform(mode).multiply(ctm);
-
-        // For getCTM() computation, stop at the nearest viewport element
-        if (currentElement == stopAtElement)
-            break;
-    }
-
-    return ctm;
-}
-
-AffineTransform SVGLocatable::getTransformToElement(SVGElement* target, ExceptionState& es, StyleUpdateStrategy styleUpdateStrategy)
-{
-    AffineTransform ctm = getCTM(styleUpdateStrategy);
-
-    if (target && target->isSVGGraphicsElement()) {
-        AffineTransform targetCTM = toSVGGraphicsElement(target)->getCTM(styleUpdateStrategy);
-        if (!targetCTM.isInvertible()) {
-            es.throwUninformativeAndGenericDOMException(InvalidStateError);
-            return ctm;
-        }
-        ctm = targetCTM.inverse() * ctm;
-    }
-
-    return ctm;
-}
-
-}
diff --git a/Source/core/svg/SVGLocatable.h b/Source/core/svg/SVGLocatable.h
deleted file mode 100644
index df44df4..0000000
--- a/Source/core/svg/SVGLocatable.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2007 Rob Buis <buis@kde.org>
- * Copyright (C) Research In Motion Limited 2010. 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.
- */
-
-#ifndef SVGLocatable_h
-#define SVGLocatable_h
-
-#include "core/svg/SVGRect.h"
-#include "platform/transforms/AffineTransform.h"
-
-namespace WebCore {
-
-class ExceptionState;
-class SVGElement;
-
-class SVGLocatable {
-public:
-    virtual ~SVGLocatable() { }
-
-    // 'SVGLocatable' functions
-    virtual SVGElement* nearestViewportElement() const = 0;
-    virtual SVGElement* farthestViewportElement() const = 0;
-
-    enum StyleUpdateStrategy { AllowStyleUpdate, DisallowStyleUpdate };
-
-    virtual AffineTransform getCTM(StyleUpdateStrategy) = 0;
-    virtual AffineTransform getScreenCTM(StyleUpdateStrategy) = 0;
-    AffineTransform getTransformToElement(SVGElement*, ExceptionState&, StyleUpdateStrategy = AllowStyleUpdate);
-
-    static SVGElement* nearestViewportElement(const SVGElement*);
-    static SVGElement* farthestViewportElement(const SVGElement*);
-
-    enum CTMScope {
-        NearestViewportScope, // Used for getCTM()
-        ScreenScope // Used for getScreenCTM()
-    };
-
-protected:
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const { return AffineTransform(); }
-
-    static AffineTransform computeCTM(SVGElement*, CTMScope, StyleUpdateStrategy);
-};
-
-} // namespace WebCore
-
-#endif // SVGLocatable_h
diff --git a/Source/core/svg/SVGMPathElement.cpp b/Source/core/svg/SVGMPathElement.cpp
index b766818..edfda2d 100644
--- a/Source/core/svg/SVGMPathElement.cpp
+++ b/Source/core/svg/SVGMPathElement.cpp
@@ -39,17 +39,16 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGMPathElement::SVGMPathElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGMPathElement::SVGMPathElement(Document& document)
+    : SVGElement(SVGNames::mpathTag, document)
 {
-    ASSERT(hasTagName(SVGNames::mpathTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGMPathElement();
 }
 
-PassRefPtr<SVGMPathElement> SVGMPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMPathElement> SVGMPathElement::create(Document& document)
 {
-    return adoptRef(new SVGMPathElement(tagName, document));
+    return adoptRef(new SVGMPathElement(document));
 }
 
 SVGMPathElement::~SVGMPathElement()
diff --git a/Source/core/svg/SVGMPathElement.h b/Source/core/svg/SVGMPathElement.h
index b07d8fd..0bccf80 100644
--- a/Source/core/svg/SVGMPathElement.h
+++ b/Source/core/svg/SVGMPathElement.h
@@ -35,7 +35,7 @@
                               public SVGURIReference,
                               public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGMPathElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGMPathElement> create(Document&);
 
     virtual ~SVGMPathElement();
 
@@ -44,7 +44,7 @@
     void targetPathChanged();
 
 private:
-    SVGMPathElement(const QualifiedName&, Document&);
+    explicit SVGMPathElement(Document&);
 
     void buildPendingResource();
     void clearResourceReferences();
diff --git a/Source/core/svg/SVGMarkerElement.cpp b/Source/core/svg/SVGMarkerElement.cpp
index c56b2c2..150f641 100644
--- a/Source/core/svg/SVGMarkerElement.cpp
+++ b/Source/core/svg/SVGMarkerElement.cpp
@@ -70,8 +70,8 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGMarkerElement::SVGMarkerElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGMarkerElement::SVGMarkerElement(Document& document)
+    : SVGElement(SVGNames::markerTag, document)
     , m_refX(LengthModeWidth)
     , m_refY(LengthModeHeight)
     , m_markerWidth(LengthModeWidth, "3")
@@ -80,14 +80,13 @@
     , m_orientType(SVGMarkerOrientAngle)
 {
     // Spec: If the markerWidth/markerHeight attribute is not specified, the effect is as if a value of "3" were specified.
-    ASSERT(hasTagName(SVGNames::markerTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGMarkerElement();
 }
 
-PassRefPtr<SVGMarkerElement> SVGMarkerElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMarkerElement> SVGMarkerElement::create(Document& document)
 {
-    return adoptRef(new SVGMarkerElement(tagName, document));
+    return adoptRef(new SVGMarkerElement(document));
 }
 
 const AtomicString& SVGMarkerElement::orientTypeIdentifier()
diff --git a/Source/core/svg/SVGMarkerElement.h b/Source/core/svg/SVGMarkerElement.h
index 08c21ca..6b7e485 100644
--- a/Source/core/svg/SVGMarkerElement.h
+++ b/Source/core/svg/SVGMarkerElement.h
@@ -86,9 +86,9 @@
         if (value == "auto")
             return SVGMarkerOrientAuto;
 
-        TrackExceptionState es;
-        angle.setValueAsString(value, es);
-        if (!es.hadException())
+        TrackExceptionState exceptionState;
+        angle.setValueAsString(value, exceptionState);
+        if (!exceptionState.hadException())
             return SVGMarkerOrientAngle;
         return SVGMarkerOrientUnknown;
     }
@@ -111,7 +111,7 @@
         SVG_MARKER_ORIENT_ANGLE = SVGMarkerOrientAngle
     };
 
-    static PassRefPtr<SVGMarkerElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGMarkerElement> create(Document&);
 
     AffineTransform viewBoxToViewTransform(float viewWidth, float viewHeight) const;
 
@@ -121,7 +121,7 @@
     static const SVGPropertyInfo* orientTypePropertyInfo();
 
 private:
-    SVGMarkerElement(const QualifiedName&, Document&);
+    explicit SVGMarkerElement(Document&);
 
     virtual bool needsPendingResourceHandling() const { return false; }
 
diff --git a/Source/core/svg/SVGMaskElement.cpp b/Source/core/svg/SVGMaskElement.cpp
index f4d95bf..6bd833c 100644
--- a/Source/core/svg/SVGMaskElement.cpp
+++ b/Source/core/svg/SVGMaskElement.cpp
@@ -53,8 +53,8 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGMaskElement::SVGMaskElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGMaskElement::SVGMaskElement(Document& document)
+    : SVGElement(SVGNames::maskTag, document)
     , m_maskUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_maskContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
     , m_x(LengthModeWidth, "-10%")
@@ -64,14 +64,13 @@
 {
     // Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
     // Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
-    ASSERT(hasTagName(SVGNames::maskTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGMaskElement();
 }
 
-PassRefPtr<SVGMaskElement> SVGMaskElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMaskElement> SVGMaskElement::create(Document& document)
 {
-    return adoptRef(new SVGMaskElement(tagName, document));
+    return adoptRef(new SVGMaskElement(document));
 }
 
 bool SVGMaskElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGMaskElement.h b/Source/core/svg/SVGMaskElement.h
index e53a824..a4b09ae 100644
--- a/Source/core/svg/SVGMaskElement.h
+++ b/Source/core/svg/SVGMaskElement.h
@@ -35,10 +35,10 @@
                              public SVGTests,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGMaskElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGMaskElement> create(Document&);
 
 private:
-    SVGMaskElement(const QualifiedName&, Document&);
+    explicit SVGMaskElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool needsPendingResourceHandling() const { return false; }
diff --git a/Source/core/svg/SVGMatrix.h b/Source/core/svg/SVGMatrix.h
index ea00ea5..3917b90 100644
--- a/Source/core/svg/SVGMatrix.h
+++ b/Source/core/svg/SVGMatrix.h
@@ -103,23 +103,23 @@
         return static_cast<SVGMatrix>(copy);
     }
 
-    SVGMatrix inverse(ExceptionState& es) const
+    SVGMatrix inverse(ExceptionState& exceptionState) const
     {
         AffineTransform transform = AffineTransform::inverse();
         if (!isInvertible()) {
             // FIXME: This used to have a more specific error message:
             // "An attempt was made to invert a matrix that is not invertible."
             // When switching to SVG2 style exceptions we lost this information.
-            es.throwUninformativeAndGenericDOMException(InvalidStateError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
         }
 
         return transform;
     }
 
-    SVGMatrix rotateFromVector(double x, double y, ExceptionState& es)
+    SVGMatrix rotateFromVector(double x, double y, ExceptionState& exceptionState)
     {
         if (!x || !y)
-            es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+            exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
 
         AffineTransform copy = *this;
         copy.rotateFromVector(x, y);
diff --git a/Source/core/svg/SVGMatrix.idl b/Source/core/svg/SVGMatrix.idl
index dc871be..af56029 100644
--- a/Source/core/svg/SVGMatrix.idl
+++ b/Source/core/svg/SVGMatrix.idl
@@ -20,7 +20,9 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGMatrix {
+[
+    SetReference(SVGTransform parent)
+] interface SVGMatrix {
     // FIXME: these attributes should all be floats but since we implement
     // AffineTransform with doubles setting these as doubles makes more sense.
     [StrictTypeChecking] attribute double a;
diff --git a/Source/core/svg/SVGMetadataElement.cpp b/Source/core/svg/SVGMetadataElement.cpp
index a02eb31..d8ef56a 100644
--- a/Source/core/svg/SVGMetadataElement.cpp
+++ b/Source/core/svg/SVGMetadataElement.cpp
@@ -24,16 +24,15 @@
 
 namespace WebCore {
 
-inline SVGMetadataElement::SVGMetadataElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGMetadataElement::SVGMetadataElement(Document& document)
+    : SVGElement(SVGNames::metadataTag, document)
 {
-    ASSERT(hasTagName(SVGNames::metadataTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGMetadataElement> SVGMetadataElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMetadataElement> SVGMetadataElement::create(Document& document)
 {
-    return adoptRef(new SVGMetadataElement(tagName, document));
+    return adoptRef(new SVGMetadataElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGMetadataElement.h b/Source/core/svg/SVGMetadataElement.h
index 596f317..1d889df 100644
--- a/Source/core/svg/SVGMetadataElement.h
+++ b/Source/core/svg/SVGMetadataElement.h
@@ -27,10 +27,10 @@
 
 class SVGMetadataElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGMetadataElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGMetadataElement> create(Document&);
 
 private:
-    SVGMetadataElement(const QualifiedName&, Document&);
+    explicit SVGMetadataElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
diff --git a/Source/core/svg/SVGMissingGlyphElement.cpp b/Source/core/svg/SVGMissingGlyphElement.cpp
index f426e6b..b3e9b43 100644
--- a/Source/core/svg/SVGMissingGlyphElement.cpp
+++ b/Source/core/svg/SVGMissingGlyphElement.cpp
@@ -25,16 +25,15 @@
 
 namespace WebCore {
 
-inline SVGMissingGlyphElement::SVGMissingGlyphElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGMissingGlyphElement::SVGMissingGlyphElement(Document& document)
+    : SVGElement(SVGNames::missing_glyphTag, document)
 {
-    ASSERT(hasTagName(SVGNames::missing_glyphTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGMissingGlyphElement> SVGMissingGlyphElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMissingGlyphElement> SVGMissingGlyphElement::create(Document& document)
 {
-    return adoptRef(new SVGMissingGlyphElement(tagName, document));
+    return adoptRef(new SVGMissingGlyphElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGMissingGlyphElement.h b/Source/core/svg/SVGMissingGlyphElement.h
index 0ba5189..9057582 100644
--- a/Source/core/svg/SVGMissingGlyphElement.h
+++ b/Source/core/svg/SVGMissingGlyphElement.h
@@ -28,10 +28,10 @@
 
 class SVGMissingGlyphElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGMissingGlyphElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGMissingGlyphElement> create(Document&);
 
 private:
-    SVGMissingGlyphElement(const QualifiedName&, Document&);
+    explicit SVGMissingGlyphElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 };
diff --git a/Source/core/svg/SVGPaint.cpp b/Source/core/svg/SVGPaint.cpp
index cb80ac7..295eb35 100644
--- a/Source/core/svg/SVGPaint.cpp
+++ b/Source/core/svg/SVGPaint.cpp
@@ -63,9 +63,9 @@
     // The setters are the most problematic part so we remove the support for those first.
 }
 
-void SVGPaint::setPaint(unsigned short, const String&, const String&, const String&, ExceptionState& es)
+void SVGPaint::setPaint(unsigned short, const String&, const String&, const String&, ExceptionState& exceptionState)
 {
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
 String SVGPaint::customCSSText() const
diff --git a/Source/core/svg/SVGParserUtilities.cpp b/Source/core/svg/SVGParserUtilities.cpp
index cf7c225..262ef62 100644
--- a/Source/core/svg/SVGParserUtilities.cpp
+++ b/Source/core/svg/SVGParserUtilities.cpp
@@ -25,7 +25,9 @@
 
 #include "core/dom/Document.h"
 #include "core/svg/SVGPointList.h"
+#include "core/svg/SVGTransformList.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/transforms/AffineTransform.h"
 #include "wtf/ASCIICType.h"
 #include <limits>
 
@@ -559,4 +561,207 @@
 template bool parseFloatPoint3(const LChar*& current, const LChar* end, FloatPoint& point1, FloatPoint& point2, FloatPoint& point3);
 template bool parseFloatPoint3(const UChar*& current, const UChar* end, FloatPoint& point1, FloatPoint& point2, FloatPoint& point3);
 
+template<typename CharType>
+static int parseTransformParamList(const CharType*& ptr, const CharType* end, float* values, int required, int optional)
+{
+    int optionalParams = 0, requiredParams = 0;
+
+    if (!skipOptionalSVGSpaces(ptr, end) || *ptr != '(')
+        return -1;
+
+    ptr++;
+
+    skipOptionalSVGSpaces(ptr, end);
+
+    while (requiredParams < required) {
+        if (ptr >= end || !parseNumber(ptr, end, values[requiredParams], false))
+            return -1;
+        requiredParams++;
+        if (requiredParams < required)
+            skipOptionalSVGSpacesOrDelimiter(ptr, end);
+    }
+    if (!skipOptionalSVGSpaces(ptr, end))
+        return -1;
+
+    bool delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
+
+    if (ptr >= end)
+        return -1;
+
+    if (*ptr == ')') { // skip optionals
+        ptr++;
+        if (delimParsed)
+            return -1;
+    } else {
+        while (optionalParams < optional) {
+            if (ptr >= end || !parseNumber(ptr, end, values[requiredParams + optionalParams], false))
+                return -1;
+            optionalParams++;
+            if (optionalParams < optional)
+                skipOptionalSVGSpacesOrDelimiter(ptr, end);
+        }
+
+        if (!skipOptionalSVGSpaces(ptr, end))
+            return -1;
+
+        delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
+
+        if (ptr >= end || *ptr != ')' || delimParsed)
+            return -1;
+        ptr++;
+    }
+
+    return requiredParams + optionalParams;
+}
+
+// These should be kept in sync with enum SVGTransformType
+static const int requiredValuesForType[] =  {0, 6, 1, 1, 1, 1, 1};
+static const int optionalValuesForType[] =  {0, 0, 1, 1, 2, 0, 0};
+
+template<typename CharType>
+static bool parseTransformValueInternal(unsigned type, const CharType*& ptr, const CharType* end, SVGTransform& transform)
+{
+    if (type == SVGTransform::SVG_TRANSFORM_UNKNOWN)
+        return false;
+
+    int valueCount = 0;
+    float values[] = {0, 0, 0, 0, 0, 0};
+    if ((valueCount = parseTransformParamList(ptr, end, values, requiredValuesForType[type], optionalValuesForType[type])) < 0)
+        return false;
+
+    switch (type) {
+    case SVGTransform::SVG_TRANSFORM_SKEWX:
+        transform.setSkewX(values[0]);
+        break;
+    case SVGTransform::SVG_TRANSFORM_SKEWY:
+        transform.setSkewY(values[0]);
+        break;
+    case SVGTransform::SVG_TRANSFORM_SCALE:
+        if (valueCount == 1) // Spec: if only one param given, assume uniform scaling
+            transform.setScale(values[0], values[0]);
+        else
+            transform.setScale(values[0], values[1]);
+        break;
+    case SVGTransform::SVG_TRANSFORM_TRANSLATE:
+        if (valueCount == 1) // Spec: if only one param given, assume 2nd param to be 0
+            transform.setTranslate(values[0], 0);
+        else
+            transform.setTranslate(values[0], values[1]);
+        break;
+    case SVGTransform::SVG_TRANSFORM_ROTATE:
+        if (valueCount == 1)
+            transform.setRotate(values[0], 0, 0);
+        else
+            transform.setRotate(values[0], values[1], values[2]);
+        break;
+    case SVGTransform::SVG_TRANSFORM_MATRIX:
+        transform.setMatrix(AffineTransform(values[0], values[1], values[2], values[3], values[4], values[5]));
+        break;
+    }
+
+    return true;
+}
+
+bool parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform& transform)
+{
+    return parseTransformValueInternal(type, ptr, end, transform);
+}
+
+bool parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform& transform)
+{
+    return parseTransformValueInternal(type, ptr, end, transform);
+}
+
+static const LChar skewXDesc[] =  {'s', 'k', 'e', 'w', 'X'};
+static const LChar skewYDesc[] =  {'s', 'k', 'e', 'w', 'Y'};
+static const LChar scaleDesc[] =  {'s', 'c', 'a', 'l', 'e'};
+static const LChar translateDesc[] =  {'t', 'r', 'a', 'n', 's', 'l', 'a', 't', 'e'};
+static const LChar rotateDesc[] =  {'r', 'o', 't', 'a', 't', 'e'};
+static const LChar matrixDesc[] =  {'m', 'a', 't', 'r', 'i', 'x'};
+
+template<typename CharType>
+static inline bool parseAndSkipType(const CharType*& ptr, const CharType* end, unsigned short& type)
+{
+    if (ptr >= end)
+        return false;
+
+    if (*ptr == 's') {
+        if (skipString(ptr, end, skewXDesc, WTF_ARRAY_LENGTH(skewXDesc)))
+            type = SVGTransform::SVG_TRANSFORM_SKEWX;
+        else if (skipString(ptr, end, skewYDesc, WTF_ARRAY_LENGTH(skewYDesc)))
+            type = SVGTransform::SVG_TRANSFORM_SKEWY;
+        else if (skipString(ptr, end, scaleDesc, WTF_ARRAY_LENGTH(scaleDesc)))
+            type = SVGTransform::SVG_TRANSFORM_SCALE;
+        else
+            return false;
+    } else if (skipString(ptr, end, translateDesc, WTF_ARRAY_LENGTH(translateDesc)))
+        type = SVGTransform::SVG_TRANSFORM_TRANSLATE;
+    else if (skipString(ptr, end, rotateDesc, WTF_ARRAY_LENGTH(rotateDesc)))
+        type = SVGTransform::SVG_TRANSFORM_ROTATE;
+    else if (skipString(ptr, end, matrixDesc, WTF_ARRAY_LENGTH(matrixDesc)))
+        type = SVGTransform::SVG_TRANSFORM_MATRIX;
+    else
+        return false;
+
+    return true;
+}
+
+SVGTransform::SVGTransformType parseTransformType(const String& string)
+{
+    if (string.isEmpty())
+        return SVGTransform::SVG_TRANSFORM_UNKNOWN;
+    unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        parseAndSkipType(ptr, end, type);
+    } else {
+        const UChar* ptr = string.characters16();
+        const UChar* end = ptr + string.length();
+        parseAndSkipType(ptr, end, type);
+    }
+    return static_cast<SVGTransform::SVGTransformType>(type);
+}
+
+template<typename CharType>
+bool parseTransformAttributeInternal(SVGTransformList& list, const CharType*& ptr, const CharType* end, TransformParsingMode mode)
+{
+    if (mode == ClearList)
+        list.clear();
+
+    bool delimParsed = false;
+    while (ptr < end) {
+        delimParsed = false;
+        unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
+        skipOptionalSVGSpaces(ptr, end);
+
+        if (!parseAndSkipType(ptr, end, type))
+            return false;
+
+        SVGTransform transform;
+        if (!parseTransformValue(type, ptr, end, transform))
+            return false;
+
+        list.append(transform);
+        skipOptionalSVGSpaces(ptr, end);
+        if (ptr < end && *ptr == ',') {
+            delimParsed = true;
+            ++ptr;
+        }
+        skipOptionalSVGSpaces(ptr, end);
+    }
+
+    return !delimParsed;
+}
+
+bool parseTransformAttribute(SVGTransformList& list, const LChar*& ptr, const LChar* end, TransformParsingMode mode)
+{
+    return parseTransformAttributeInternal(list, ptr, end, mode);
+}
+
+bool parseTransformAttribute(SVGTransformList& list, const UChar*& ptr, const UChar* end, TransformParsingMode mode)
+{
+    return parseTransformAttributeInternal(list, ptr, end, mode);
+}
+
 }
diff --git a/Source/core/svg/SVGParserUtilities.h b/Source/core/svg/SVGParserUtilities.h
index 74cbb83..2946cf1 100644
--- a/Source/core/svg/SVGParserUtilities.h
+++ b/Source/core/svg/SVGParserUtilities.h
@@ -22,6 +22,7 @@
 #ifndef SVGParserUtilities_h
 #define SVGParserUtilities_h
 
+#include "core/svg/SVGTransform.h"
 #include "platform/text/ParserUtilities.h"
 #include "wtf/HashSet.h"
 
@@ -33,6 +34,7 @@
 class FloatPoint;
 class FloatRect;
 class SVGPointList;
+class SVGTransformList;
 
 template <typename CharType>
 bool parseSVGNumber(CharType* ptr, size_t length, double& number);
@@ -86,6 +88,19 @@
 bool parseKerningUnicodeString(const String& input, UnicodeRanges&, HashSet<String>& stringList);
 bool parseGlyphName(const String& input, HashSet<String>& values);
 
+enum TransformParsingMode {
+    ClearList,
+    DoNotClearList
+};
+
+bool parseTransformAttribute(SVGTransformList&, const LChar*& ptr, const LChar* end, TransformParsingMode = ClearList);
+bool parseTransformAttribute(SVGTransformList&, const UChar*& ptr, const UChar* end, TransformParsingMode = ClearList);
+
+bool parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform&);
+bool parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform&);
+
+SVGTransform::SVGTransformType parseTransformType(const String&);
+
 } // namespace WebCore
 
 #endif // SVGParserUtilities_h
diff --git a/Source/core/svg/SVGPathElement.cpp b/Source/core/svg/SVGPathElement.cpp
index 247f948..a1f88dd 100644
--- a/Source/core/svg/SVGPathElement.cpp
+++ b/Source/core/svg/SVGPathElement.cpp
@@ -78,20 +78,19 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGPathElement::SVGPathElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGPathElement::SVGPathElement(Document& document)
+    : SVGGeometryElement(SVGNames::pathTag, document)
     , m_pathByteStream(SVGPathByteStream::create())
     , m_pathSegList(PathSegUnalteredRole)
     , m_isAnimValObserved(false)
 {
-    ASSERT(hasTagName(SVGNames::pathTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGPathElement();
 }
 
-PassRefPtr<SVGPathElement> SVGPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPathElement> SVGPathElement::create(Document& document)
 {
-    return adoptRef(new SVGPathElement(tagName, document));
+    return adoptRef(new SVGPathElement(document));
 }
 
 float SVGPathElement::getTotalLength()
@@ -224,7 +223,7 @@
 void SVGPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGGraphicsElement::parseAttribute(name, value);
+        SVGGeometryElement::parseAttribute(name, value);
         return;
     }
 
@@ -250,7 +249,7 @@
 void SVGPathElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGGraphicsElement::svgAttributeChanged(attrName);
+        SVGGeometryElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -290,14 +289,14 @@
 
 Node::InsertionNotificationRequest SVGPathElement::insertedInto(ContainerNode* rootParent)
 {
-    SVGGraphicsElement::insertedInto(rootParent);
+    SVGGeometryElement::insertedInto(rootParent);
     invalidateMPathDependencies();
     return InsertionDone;
 }
 
 void SVGPathElement::removedFrom(ContainerNode* rootParent)
 {
-    SVGGraphicsElement::removedFrom(rootParent);
+    SVGGeometryElement::removedFrom(rootParent);
     invalidateMPathDependencies();
 }
 
diff --git a/Source/core/svg/SVGPathElement.h b/Source/core/svg/SVGPathElement.h
index 00d7ec9..adc861c 100644
--- a/Source/core/svg/SVGPathElement.h
+++ b/Source/core/svg/SVGPathElement.h
@@ -25,7 +25,7 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
 #include "core/svg/SVGPathByteStream.h"
 #include "core/svg/SVGPathSegList.h"
 
@@ -52,10 +52,10 @@
 class SVGPathSegCurvetoQuadraticSmoothRel;
 class SVGPathSegListPropertyTearOff;
 
-class SVGPathElement FINAL : public SVGGraphicsElement,
+class SVGPathElement FINAL : public SVGGeometryElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGPathElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGPathElement> create(Document&);
 
     float getTotalLength();
     SVGPoint getPointAtLength(float distance);
@@ -98,7 +98,7 @@
     bool isAnimValObserved() const { return m_isAnimValObserved; }
 
 private:
-    SVGPathElement(const QualifiedName&, Document&);
+    explicit SVGPathElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -112,11 +112,6 @@
     static void synchronizeD(SVGElement* contextElement);
     static PassRefPtr<SVGAnimatedProperty> lookupOrCreateDWrapper(SVGElement* contextElement);
 
-    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPathElement)
-        DECLARE_ANIMATED_NUMBER(PathLength, pathLength)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
-    END_DECLARE_ANIMATED_PROPERTIES
-
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual Node::InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
@@ -124,10 +119,14 @@
 
     void invalidateMPathDependencies();
 
-private:
     OwnPtr<SVGPathByteStream> m_pathByteStream;
     mutable SVGSynchronizableAnimatedProperty<SVGPathSegList> m_pathSegList;
     bool m_isAnimValObserved;
+
+    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPathElement)
+        DECLARE_ANIMATED_NUMBER(PathLength, pathLength)
+        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
+    END_DECLARE_ANIMATED_PROPERTIES
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGPathElement, hasTagName(SVGNames::pathTag));
diff --git a/Source/core/svg/SVGPathElement.idl b/Source/core/svg/SVGPathElement.idl
index 5d75b70..297b5b1 100644
--- a/Source/core/svg/SVGPathElement.idl
+++ b/Source/core/svg/SVGPathElement.idl
@@ -24,7 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathElement : SVGGraphicsElement {
+interface SVGPathElement : SVGGeometryElement {
     readonly attribute SVGAnimatedNumber pathLength;
 
     float getTotalLength();
diff --git a/Source/core/svg/SVGPathSeg.idl b/Source/core/svg/SVGPathSeg.idl
index 4ca8a2c..45a0ccf 100644
--- a/Source/core/svg/SVGPathSeg.idl
+++ b/Source/core/svg/SVGPathSeg.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    CustomToV8
+    CustomWrap,
 ] interface SVGPathSeg {
     // Path Segment Types
     const unsigned short PATHSEG_UNKNOWN = 0;
diff --git a/Source/core/svg/SVGPathSegWithContext.h b/Source/core/svg/SVGPathSegWithContext.h
index bff62bf..c12689d 100644
--- a/Source/core/svg/SVGPathSegWithContext.h
+++ b/Source/core/svg/SVGPathSegWithContext.h
@@ -38,7 +38,7 @@
         case PathSegUndefinedRole:
             return 0;
         case PathSegUnalteredRole:
-            return SVGAnimatedProperty::lookupWrapper<SVGPathElement, SVGAnimatedPathSegListPropertyTearOff>(m_element.get(), SVGPathElement::dPropertyInfo());
+            return SVGAnimatedProperty::lookupWrapper<SVGPathElement, SVGAnimatedPathSegListPropertyTearOff>(m_element, SVGPathElement::dPropertyInfo());
         case PathSegNormalizedRole:
             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=15412 - Implement normalized path segment lists!
             return 0;
@@ -47,7 +47,7 @@
         return 0;
     }
 
-    SVGPathElement* contextElement() const { return m_element.get(); }
+    SVGPathElement* contextElement() const { return m_element; }
     SVGPathSegRole role() const { return m_role; }
 
     void setContextAndRole(SVGPathElement* element, SVGPathSegRole role)
@@ -69,7 +69,7 @@
 
 private:
     SVGPathSegRole m_role;
-    RefPtr<SVGPathElement> m_element;
+    SVGPathElement* m_element;
 };
 
 class SVGPathSegSingleCoordinate : public SVGPathSegWithContext {
diff --git a/Source/core/svg/SVGPathStringSource.cpp b/Source/core/svg/SVGPathStringSource.cpp
index ecde69f..75e983d 100644
--- a/Source/core/svg/SVGPathStringSource.cpp
+++ b/Source/core/svg/SVGPathStringSource.cpp
@@ -247,4 +247,4 @@
     return parseArcToSegmentHelper(m_current.m_character16, m_end.m_character16, rx, ry, angle, largeArc, sweep, targetPoint);
 }
 
-} // namespace WebKit
+} // namespace blink
diff --git a/Source/core/svg/SVGPatternElement.cpp b/Source/core/svg/SVGPatternElement.cpp
index 387f8d6..ee8a18e 100644
--- a/Source/core/svg/SVGPatternElement.cpp
+++ b/Source/core/svg/SVGPatternElement.cpp
@@ -62,8 +62,8 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGPatternElement::SVGPatternElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGPatternElement::SVGPatternElement(Document& document)
+    : SVGElement(SVGNames::patternTag, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
@@ -71,14 +71,13 @@
     , m_patternUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_patternContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
 {
-    ASSERT(hasTagName(SVGNames::patternTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGPatternElement();
 }
 
-PassRefPtr<SVGPatternElement> SVGPatternElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPatternElement> SVGPatternElement::create(Document& document)
 {
-    return adoptRef(new SVGPatternElement(tagName, document));
+    return adoptRef(new SVGPatternElement(document));
 }
 
 bool SVGPatternElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -232,7 +231,7 @@
     }
 }
 
-AffineTransform SVGPatternElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope) const
+AffineTransform SVGPatternElement::localCoordinateSpaceTransform(SVGElement::CTMScope) const
 {
     AffineTransform matrix;
     patternTransformCurrentValue().concatenate(matrix);
diff --git a/Source/core/svg/SVGPatternElement.h b/Source/core/svg/SVGPatternElement.h
index 1378011..3536b4b 100644
--- a/Source/core/svg/SVGPatternElement.h
+++ b/Source/core/svg/SVGPatternElement.h
@@ -45,14 +45,14 @@
                                 public SVGExternalResourcesRequired,
                                 public SVGFitToViewBox {
 public:
-    static PassRefPtr<SVGPatternElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGPatternElement> create(Document&);
 
     void collectPatternAttributes(PatternAttributes&) const;
 
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
+    virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const;
 
 private:
-    SVGPatternElement(const QualifiedName&, Document&);
+    explicit SVGPatternElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool needsPendingResourceHandling() const { return false; }
diff --git a/Source/core/svg/SVGPolyElement.cpp b/Source/core/svg/SVGPolyElement.cpp
index a6eec9b..75b1b5c 100644
--- a/Source/core/svg/SVGPolyElement.cpp
+++ b/Source/core/svg/SVGPolyElement.cpp
@@ -46,6 +46,17 @@
     return s_propertyInfo;
 }
 
+SVGPointList& SVGPolyElement::pointsCurrentValue()
+{
+    SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGPolyElement, SVGAnimatedPointList>(this, pointsPropertyInfo());
+    if (wrapper && wrapper->isAnimating()) {
+        if (SVGListPropertyTearOff<SVGPointList>* ap = animatedPoints())
+            return ap->values();
+    }
+
+    return m_points.value;
+}
+
 // Animated property definitions
 DEFINE_ANIMATED_BOOLEAN(SVGPolyElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
@@ -56,7 +67,7 @@
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGPolyElement::SVGPolyElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+    : SVGGeometryElement(tagName, document)
 {
     registerAnimatedPropertiesForSVGPolyElement();
 }
@@ -75,7 +86,7 @@
 void SVGPolyElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGGraphicsElement::parseAttribute(name, value);
+        SVGGeometryElement::parseAttribute(name, value);
         return;
     }
 
@@ -102,7 +113,7 @@
 void SVGPolyElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGGraphicsElement::svgAttributeChanged(attrName);
+        SVGGeometryElement::svgAttributeChanged(attrName);
         return;
     }
 
diff --git a/Source/core/svg/SVGPolyElement.h b/Source/core/svg/SVGPolyElement.h
index 617de15..3c5d036 100644
--- a/Source/core/svg/SVGPolyElement.h
+++ b/Source/core/svg/SVGPolyElement.h
@@ -24,18 +24,18 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
 #include "core/svg/SVGPointList.h"
 
 namespace WebCore {
 
-class SVGPolyElement : public SVGGraphicsElement
+class SVGPolyElement : public SVGGeometryElement
                      , public SVGExternalResourcesRequired {
 public:
     SVGListPropertyTearOff<SVGPointList>* points();
     SVGListPropertyTearOff<SVGPointList>* animatedPoints();
 
-    SVGPointList& pointList() const { return m_points.value; }
+    SVGPointList& pointsCurrentValue();
 
     static const SVGPropertyInfo* pointsPropertyInfo();
 
diff --git a/Source/core/svg/SVGPolygonElement.cpp b/Source/core/svg/SVGPolygonElement.cpp
index 28175e4..58e9a20 100644
--- a/Source/core/svg/SVGPolygonElement.cpp
+++ b/Source/core/svg/SVGPolygonElement.cpp
@@ -25,16 +25,15 @@
 
 namespace WebCore {
 
-inline SVGPolygonElement::SVGPolygonElement(const QualifiedName& tagName, Document& document)
-    : SVGPolyElement(tagName, document)
+inline SVGPolygonElement::SVGPolygonElement(Document& document)
+    : SVGPolyElement(SVGNames::polygonTag, document)
 {
-    ASSERT(hasTagName(SVGNames::polygonTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGPolygonElement> SVGPolygonElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPolygonElement> SVGPolygonElement::create(Document& document)
 {
-    return adoptRef(new SVGPolygonElement(tagName, document));
+    return adoptRef(new SVGPolygonElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGPolygonElement.h b/Source/core/svg/SVGPolygonElement.h
index 89626b0..89571f7 100644
--- a/Source/core/svg/SVGPolygonElement.h
+++ b/Source/core/svg/SVGPolygonElement.h
@@ -28,10 +28,10 @@
 
 class SVGPolygonElement FINAL : public SVGPolyElement {
 public:
-    static PassRefPtr<SVGPolygonElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGPolygonElement> create(Document&);
 
 private:
-    SVGPolygonElement(const QualifiedName&, Document&);
+    explicit SVGPolygonElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGPolygonElement, hasTagName(SVGNames::polygonTag));
diff --git a/Source/core/svg/SVGPolygonElement.idl b/Source/core/svg/SVGPolygonElement.idl
index 735067b..be639f1 100644
--- a/Source/core/svg/SVGPolygonElement.idl
+++ b/Source/core/svg/SVGPolygonElement.idl
@@ -23,7 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPolygonElement : SVGGraphicsElement {
+interface SVGPolygonElement : SVGGeometryElement {
     readonly attribute SVGPointList points;
     readonly attribute SVGPointList animatedPoints;
 };
diff --git a/Source/core/svg/SVGPolylineElement.cpp b/Source/core/svg/SVGPolylineElement.cpp
index 15b878d..5276a40 100644
--- a/Source/core/svg/SVGPolylineElement.cpp
+++ b/Source/core/svg/SVGPolylineElement.cpp
@@ -25,16 +25,15 @@
 
 namespace WebCore {
 
-inline SVGPolylineElement::SVGPolylineElement(const QualifiedName& tagName, Document& document)
-    : SVGPolyElement(tagName, document)
+inline SVGPolylineElement::SVGPolylineElement(Document& document)
+    : SVGPolyElement(SVGNames::polylineTag, document)
 {
-    ASSERT(hasTagName(SVGNames::polylineTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGPolylineElement> SVGPolylineElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPolylineElement> SVGPolylineElement::create(Document& document)
 {
-    return adoptRef(new SVGPolylineElement(tagName, document));
+    return adoptRef(new SVGPolylineElement(document));
 }
 
 }
diff --git a/Source/core/svg/SVGPolylineElement.h b/Source/core/svg/SVGPolylineElement.h
index 97fc80e..4283143 100644
--- a/Source/core/svg/SVGPolylineElement.h
+++ b/Source/core/svg/SVGPolylineElement.h
@@ -28,10 +28,10 @@
 
 class SVGPolylineElement FINAL : public SVGPolyElement {
 public:
-    static PassRefPtr<SVGPolylineElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGPolylineElement> create(Document&);
 
 private:
-    SVGPolylineElement(const QualifiedName&, Document&);
+    explicit SVGPolylineElement(Document&);
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGPolylineElement, hasTagName(SVGNames::polylineTag));
diff --git a/Source/core/svg/SVGPolylineElement.idl b/Source/core/svg/SVGPolylineElement.idl
index a7eefed..1fd499b 100644
--- a/Source/core/svg/SVGPolylineElement.idl
+++ b/Source/core/svg/SVGPolylineElement.idl
@@ -23,7 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPolylineElement : SVGGraphicsElement {
+interface SVGPolylineElement : SVGGeometryElement {
     readonly attribute SVGPointList points;
     readonly attribute SVGPointList animatedPoints;
 };
diff --git a/Source/core/svg/SVGPreserveAspectRatio.cpp b/Source/core/svg/SVGPreserveAspectRatio.cpp
index 9430d9f..5e9de72 100644
--- a/Source/core/svg/SVGPreserveAspectRatio.cpp
+++ b/Source/core/svg/SVGPreserveAspectRatio.cpp
@@ -37,20 +37,20 @@
 {
 }
 
-void SVGPreserveAspectRatio::setAlign(unsigned short align, ExceptionState& es)
+void SVGPreserveAspectRatio::setAlign(unsigned short align, ExceptionState& exceptionState)
 {
     if (align == SVG_PRESERVEASPECTRATIO_UNKNOWN || align > SVG_PRESERVEASPECTRATIO_XMAXYMAX) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
     m_align = static_cast<SVGPreserveAspectRatioType>(align);
 }
 
-void SVGPreserveAspectRatio::setMeetOrSlice(unsigned short meetOrSlice, ExceptionState& es)
+void SVGPreserveAspectRatio::setMeetOrSlice(unsigned short meetOrSlice, ExceptionState& exceptionState)
 {
     if (meetOrSlice == SVG_MEETORSLICE_UNKNOWN || meetOrSlice > SVG_MEETORSLICE_SLICE) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return;
     }
 
diff --git a/Source/core/svg/SVGPreserveAspectRatio.idl b/Source/core/svg/SVGPreserveAspectRatio.idl
index 178f1a0..477369e 100644
--- a/Source/core/svg/SVGPreserveAspectRatio.idl
+++ b/Source/core/svg/SVGPreserveAspectRatio.idl
@@ -42,8 +42,8 @@
     const unsigned short SVG_MEETORSLICE_MEET = 1;
     const unsigned short SVG_MEETORSLICE_SLICE = 2;
 
-    [StrictTypeChecking, SetterRaisesException] attribute unsigned short align;
+    [StrictTypeChecking, RaisesException=Setter] attribute unsigned short align;
 
-    [StrictTypeChecking, SetterRaisesException] attribute unsigned short meetOrSlice;
+    [StrictTypeChecking, RaisesException=Setter] attribute unsigned short meetOrSlice;
 };
 
diff --git a/Source/core/svg/SVGRadialGradientElement.cpp b/Source/core/svg/SVGRadialGradientElement.cpp
index d3a227a..e23898a 100644
--- a/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/Source/core/svg/SVGRadialGradientElement.cpp
@@ -51,8 +51,8 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGRadialGradientElement::SVGRadialGradientElement(const QualifiedName& tagName, Document& document)
-    : SVGGradientElement(tagName, document)
+inline SVGRadialGradientElement::SVGRadialGradientElement(Document& document)
+    : SVGGradientElement(SVGNames::radialGradientTag, document)
     , m_cx(LengthModeWidth, "50%")
     , m_cy(LengthModeHeight, "50%")
     , m_r(LengthModeOther, "50%")
@@ -61,14 +61,13 @@
     , m_fr(LengthModeOther, "0%")
 {
     // Spec: If the cx/cy/r/fr attribute is not specified, the effect is as if a value of "50%" were specified.
-    ASSERT(hasTagName(SVGNames::radialGradientTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGRadialGradientElement();
 }
 
-PassRefPtr<SVGRadialGradientElement> SVGRadialGradientElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGRadialGradientElement> SVGRadialGradientElement::create(Document& document)
 {
-    return adoptRef(new SVGRadialGradientElement(tagName, document));
+    return adoptRef(new SVGRadialGradientElement(document));
 }
 
 bool SVGRadialGradientElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGRadialGradientElement.h b/Source/core/svg/SVGRadialGradientElement.h
index 5ea1175..e448d20 100644
--- a/Source/core/svg/SVGRadialGradientElement.h
+++ b/Source/core/svg/SVGRadialGradientElement.h
@@ -31,12 +31,12 @@
 
 class SVGRadialGradientElement FINAL : public SVGGradientElement {
 public:
-    static PassRefPtr<SVGRadialGradientElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGRadialGradientElement> create(Document&);
 
     bool collectGradientAttributes(RadialGradientAttributes&);
 
 private:
-    SVGRadialGradientElement(const QualifiedName&, Document&);
+    explicit SVGRadialGradientElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGRectElement.cpp b/Source/core/svg/SVGRectElement.cpp
index 2f0e12c..5bb1897 100644
--- a/Source/core/svg/SVGRectElement.cpp
+++ b/Source/core/svg/SVGRectElement.cpp
@@ -50,8 +50,8 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGRectElement::SVGRectElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGRectElement::SVGRectElement(Document& document)
+    : SVGGeometryElement(SVGNames::rectTag, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
@@ -59,14 +59,13 @@
     , m_rx(LengthModeWidth)
     , m_ry(LengthModeHeight)
 {
-    ASSERT(hasTagName(SVGNames::rectTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGRectElement();
 }
 
-PassRefPtr<SVGRectElement> SVGRectElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGRectElement> SVGRectElement::create(Document& document)
 {
-    return adoptRef(new SVGRectElement(tagName, document));
+    return adoptRef(new SVGRectElement(document));
 }
 
 bool SVGRectElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -90,7 +89,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGGraphicsElement::parseAttribute(name, value);
+        SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
         setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::yAttr)
@@ -114,7 +113,7 @@
 void SVGRectElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGGraphicsElement::svgAttributeChanged(attrName);
+        SVGGeometryElement::svgAttributeChanged(attrName);
         return;
     }
 
diff --git a/Source/core/svg/SVGRectElement.h b/Source/core/svg/SVGRectElement.h
index 750d4ea..1a50088 100644
--- a/Source/core/svg/SVGRectElement.h
+++ b/Source/core/svg/SVGRectElement.h
@@ -25,17 +25,17 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGRectElement FINAL : public SVGGraphicsElement,
+class SVGRectElement FINAL : public SVGGeometryElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGRectElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGRectElement> create(Document&);
 
 private:
-    SVGRectElement(const QualifiedName&, Document&);
+    explicit SVGRectElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGRectElement.idl b/Source/core/svg/SVGRectElement.idl
index 42fe063..a3cf85e 100644
--- a/Source/core/svg/SVGRectElement.idl
+++ b/Source/core/svg/SVGRectElement.idl
@@ -24,7 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGRectElement : SVGGraphicsElement {
+interface SVGRectElement : SVGGeometryElement {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
     readonly attribute SVGAnimatedLength width;
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index 4fefa5b..40a3fa9 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -37,7 +37,7 @@
 #include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/frame/FrameView.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderPart.h"
 #include "core/rendering/svg/RenderSVGModelObject.h"
@@ -81,8 +81,8 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGSVGElement::SVGSVGElement(const QualifiedName& tagName, Document& doc)
-    : SVGGraphicsElement(tagName, doc)
+inline SVGSVGElement::SVGSVGElement(Document& doc)
+    : SVGGraphicsElement(SVGNames::svgTag, doc)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth, "100%")
@@ -90,23 +90,21 @@
     , m_useCurrentView(false)
     , m_zoomAndPan(SVGZoomAndPanMagnify)
     , m_timeContainer(SMILTimeContainer::create(this))
+    , m_weakFactory(this)
 {
-    ASSERT(hasTagName(SVGNames::svgTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGSVGElement();
 
     UseCounter::count(doc, UseCounter::SVGSVGElement);
 }
 
-PassRefPtr<SVGSVGElement> SVGSVGElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSVGElement> SVGSVGElement::create(Document& document)
 {
-    return adoptRef(new SVGSVGElement(tagName, document));
+    return adoptRef(new SVGSVGElement(document));
 }
 
 SVGSVGElement::~SVGSVGElement()
 {
-    if (m_viewSpec)
-        m_viewSpec->resetContextElement();
     // There are cases where removedFromDocument() is not called.
     // see ContainerNode::removeAllChildren, called by its destructor.
     document().accessSVGExtensions()->removeTimeContainer(this);
@@ -170,7 +168,7 @@
 SVGViewSpec* SVGSVGElement::currentView()
 {
     if (!m_viewSpec)
-        m_viewSpec = SVGViewSpec::create(this);
+        m_viewSpec = SVGViewSpec::create(m_weakFactory.createWeakPtr());
     return m_viewSpec.get();
 }
 
@@ -336,7 +334,7 @@
 PassRefPtr<NodeList> SVGSVGElement::collectIntersectionOrEnclosureList(const SVGRect& rect, SVGElement* referenceElement, CollectIntersectionOrEnclosure collect) const
 {
     Vector<RefPtr<Node> > nodes;
-    Element* element = ElementTraversal::next(referenceElement ? referenceElement : this);
+    Element* element = ElementTraversal::next(*(referenceElement ? referenceElement : this));
     while (element) {
         if (element->isSVGElement()) {
             SVGElement* svgElement = toSVGElement(element);
@@ -349,7 +347,7 @@
             }
         }
 
-        element = ElementTraversal::next(element, referenceElement ? referenceElement : this);
+        element = ElementTraversal::next(*element, referenceElement ? referenceElement : this);
     }
     return StaticNodeList::adopt(nodes);
 }
@@ -424,7 +422,7 @@
     return SVGTransform(static_cast<const AffineTransform&>(matrix));
 }
 
-AffineTransform SVGSVGElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope mode) const
+AffineTransform SVGSVGElement::localCoordinateSpaceTransform(SVGElement::CTMScope mode) const
 {
     AffineTransform viewBoxTransform;
     if (!hasEmptyViewBox()) {
@@ -436,7 +434,7 @@
     if (!isOutermostSVGSVGElement()) {
         SVGLengthContext lengthContext(this);
         transform.translate(xCurrentValue().value(lengthContext), yCurrentValue().value(lengthContext));
-    } else if (mode == SVGLocatable::ScreenScope) {
+    } else if (mode == SVGElement::ScreenScope) {
         if (RenderObject* renderer = this->renderer()) {
             FloatPoint location;
             float zoomFactor = 1;
@@ -729,9 +727,7 @@
         if (!viewElement)
             return;
 
-        SVGElement* element = SVGLocatable::nearestViewportElement(viewElement);
-        if (element->hasTagName(SVGNames::svgTag)) {
-            SVGSVGElement* svg = toSVGSVGElement(element);
+        if (SVGSVGElement* svg = viewElement->ownerSVGElement()) {
             svg->inheritViewAttributes(viewElement);
 
             if (RenderObject* renderer = svg->renderer())
@@ -774,7 +770,7 @@
 
     // Fall back to traversing our subtree. Duplicate ids are allowed, the first found will
     // be returned.
-    for (Node* node = firstChild(); node; node = NodeTraversal::next(node, this)) {
+    for (Node* node = firstChild(); node; node = NodeTraversal::next(*node, this)) {
         if (!node->isElementNode())
             continue;
 
diff --git a/Source/core/svg/SVGSVGElement.h b/Source/core/svg/SVGSVGElement.h
index 48bc4bf..aa9d45a 100644
--- a/Source/core/svg/SVGSVGElement.h
+++ b/Source/core/svg/SVGSVGElement.h
@@ -29,6 +29,7 @@
 #include "core/svg/SVGFitToViewBox.h"
 #include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGZoomAndPan.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
@@ -44,7 +45,7 @@
                             public SVGFitToViewBox,
                             public SVGZoomAndPan {
 public:
-    static PassRefPtr<SVGSVGElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGSVGElement> create(Document&);
 
     using SVGGraphicsElement::ref;
     using SVGGraphicsElement::deref;
@@ -133,7 +134,7 @@
     bool hasEmptyViewBox() const { return viewBoxCurrentValue().isValid() && viewBoxCurrentValue().isEmpty(); }
 
 private:
-    SVGSVGElement(const QualifiedName&, Document&);
+    explicit SVGSVGElement(Document&);
     virtual ~SVGSVGElement();
 
     virtual bool isSVGSVGElement() const OVERRIDE { return true; }
@@ -169,13 +170,14 @@
         DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
+    virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const;
 
     bool m_useCurrentView;
     SVGZoomAndPanType m_zoomAndPan;
     RefPtr<SMILTimeContainer> m_timeContainer;
     SVGPoint m_translation;
     RefPtr<SVGViewSpec> m_viewSpec;
+    WeakPtrFactory<SVGSVGElement> m_weakFactory;
 };
 
 inline SVGSVGElement* toSVGSVGElement(Node* node)
diff --git a/Source/core/svg/SVGScriptElement.cpp b/Source/core/svg/SVGScriptElement.cpp
index 832dfba..9a7040f 100644
--- a/Source/core/svg/SVGScriptElement.cpp
+++ b/Source/core/svg/SVGScriptElement.cpp
@@ -43,19 +43,18 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGScriptElement::SVGScriptElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
-    : SVGElement(tagName, document)
+inline SVGScriptElement::SVGScriptElement(Document& document, bool wasInsertedByParser, bool alreadyStarted)
+    : SVGElement(SVGNames::scriptTag, document)
     , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
     , m_loader(ScriptLoader::create(this, wasInsertedByParser, alreadyStarted))
 {
-    ASSERT(hasTagName(SVGNames::scriptTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGScriptElement();
 }
 
-PassRefPtr<SVGScriptElement> SVGScriptElement::create(const QualifiedName& tagName, Document& document, bool insertedByParser)
+PassRefPtr<SVGScriptElement> SVGScriptElement::create(Document& document, bool insertedByParser)
 {
-    return adoptRef(new SVGScriptElement(tagName, document, insertedByParser, false));
+    return adoptRef(new SVGScriptElement(document, insertedByParser, false));
 }
 
 bool SVGScriptElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -211,7 +210,7 @@
 
 PassRefPtr<Element> SVGScriptElement::cloneElementWithoutAttributesAndChildren()
 {
-    return adoptRef(new SVGScriptElement(tagQName(), document(), false, m_loader->alreadyStarted()));
+    return adoptRef(new SVGScriptElement(document(), false, m_loader->alreadyStarted()));
 }
 
 void SVGScriptElement::setHaveFiredLoadEvent(bool haveFiredLoadEvent)
diff --git a/Source/core/svg/SVGScriptElement.h b/Source/core/svg/SVGScriptElement.h
index 544838b..ec59d85 100644
--- a/Source/core/svg/SVGScriptElement.h
+++ b/Source/core/svg/SVGScriptElement.h
@@ -39,7 +39,7 @@
     , public SVGExternalResourcesRequired
     , public ScriptLoaderClient {
 public:
-    static PassRefPtr<SVGScriptElement> create(const QualifiedName&, Document&, bool wasInsertedByParser);
+    static PassRefPtr<SVGScriptElement> create(Document&, bool wasInsertedByParser);
 
     String type() const;
     void setType(const String&);
@@ -47,7 +47,7 @@
     ScriptLoader* loader() const { return m_loader.get(); }
 
 private:
-    SVGScriptElement(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted);
+    SVGScriptElement(Document&, bool wasInsertedByParser, bool alreadyStarted);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGSetElement.cpp b/Source/core/svg/SVGSetElement.cpp
index 934ed56..da8334b 100644
--- a/Source/core/svg/SVGSetElement.cpp
+++ b/Source/core/svg/SVGSetElement.cpp
@@ -24,17 +24,16 @@
 
 namespace WebCore {
 
-inline SVGSetElement::SVGSetElement(const QualifiedName& tagName, Document& document)
-    : SVGAnimateElement(tagName, document)
+inline SVGSetElement::SVGSetElement(Document& document)
+    : SVGAnimateElement(SVGNames::setTag, document)
 {
     setAnimationMode(ToAnimation);
-    ASSERT(hasTagName(SVGNames::setTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGSetElement> SVGSetElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSetElement> SVGSetElement::create(Document& document)
 {
-    return adoptRef(new SVGSetElement(tagName, document));
+    return adoptRef(new SVGSetElement(document));
 }
 
 void SVGSetElement::updateAnimationMode()
diff --git a/Source/core/svg/SVGSetElement.h b/Source/core/svg/SVGSetElement.h
index 7ff5a57..a2cd048 100644
--- a/Source/core/svg/SVGSetElement.h
+++ b/Source/core/svg/SVGSetElement.h
@@ -28,10 +28,10 @@
 // SVGAnimateElement implements superset of the functionality.
 class SVGSetElement FINAL : public SVGAnimateElement {
 public:
-    static PassRefPtr<SVGSetElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGSetElement> create(Document&);
 
 private:
-    SVGSetElement(const QualifiedName&, Document&);
+    explicit SVGSetElement(Document&);
     virtual void updateAnimationMode() OVERRIDE;
 };
 
diff --git a/Source/core/svg/SVGStopElement.cpp b/Source/core/svg/SVGStopElement.cpp
index 0751619..b6d8866 100644
--- a/Source/core/svg/SVGStopElement.cpp
+++ b/Source/core/svg/SVGStopElement.cpp
@@ -37,18 +37,17 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGStopElement::SVGStopElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGStopElement::SVGStopElement(Document& document)
+    : SVGElement(SVGNames::stopTag, document)
     , m_offset(0)
 {
-    ASSERT(hasTagName(SVGNames::stopTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGStopElement();
 }
 
-PassRefPtr<SVGStopElement> SVGStopElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGStopElement> SVGStopElement::create(Document& document)
 {
-    return adoptRef(new SVGStopElement(tagName, document));
+    return adoptRef(new SVGStopElement(document));
 }
 
 bool SVGStopElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGStopElement.h b/Source/core/svg/SVGStopElement.h
index 98b0dfe..4331a4a 100644
--- a/Source/core/svg/SVGStopElement.h
+++ b/Source/core/svg/SVGStopElement.h
@@ -29,12 +29,12 @@
 
 class SVGStopElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGStopElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGStopElement> create(Document&);
 
     Color stopColorIncludingOpacity() const;
 
 private:
-    SVGStopElement(const QualifiedName&, Document&);
+    explicit SVGStopElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGStyleElement.cpp b/Source/core/svg/SVGStyleElement.cpp
index adb399d..865caa5 100644
--- a/Source/core/svg/SVGStyleElement.cpp
+++ b/Source/core/svg/SVGStyleElement.cpp
@@ -29,12 +29,11 @@
 
 namespace WebCore {
 
-inline SVGStyleElement::SVGStyleElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : SVGElement(tagName, document)
+inline SVGStyleElement::SVGStyleElement(Document& document, bool createdByParser)
+    : SVGElement(SVGNames::styleTag, document)
     , StyleElement(&document, createdByParser)
     , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
 {
-    ASSERT(hasTagName(SVGNames::styleTag));
     ScriptWrappable::init(this);
 }
 
@@ -43,9 +42,9 @@
     StyleElement::clearDocumentData(document(), this);
 }
 
-PassRefPtr<SVGStyleElement> SVGStyleElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<SVGStyleElement> SVGStyleElement::create(Document& document, bool createdByParser)
 {
-    return adoptRef(new SVGStyleElement(tagName, document, createdByParser));
+    return adoptRef(new SVGStyleElement(document, createdByParser));
 }
 
 bool SVGStyleElement::disabled() const
diff --git a/Source/core/svg/SVGStyleElement.h b/Source/core/svg/SVGStyleElement.h
index 4106d28..522f0af 100644
--- a/Source/core/svg/SVGStyleElement.h
+++ b/Source/core/svg/SVGStyleElement.h
@@ -30,7 +30,7 @@
 class SVGStyleElement FINAL : public SVGElement
                             , public StyleElement {
 public:
-    static PassRefPtr<SVGStyleElement> create(const QualifiedName&, Document&, bool createdByParser);
+    static PassRefPtr<SVGStyleElement> create(Document&, bool createdByParser);
     virtual ~SVGStyleElement();
 
     using StyleElement::sheet;
@@ -48,7 +48,7 @@
     void setTitle(const AtomicString&);
 
 private:
-    SVGStyleElement(const QualifiedName&, Document&, bool createdByParser);
+    SVGStyleElement(Document&, bool createdByParser);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGSwitchElement.cpp b/Source/core/svg/SVGSwitchElement.cpp
index c0db5bc..b4719ce 100644
--- a/Source/core/svg/SVGSwitchElement.cpp
+++ b/Source/core/svg/SVGSwitchElement.cpp
@@ -23,7 +23,7 @@
 #include "core/svg/SVGSwitchElement.h"
 
 #include "SVGNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/rendering/svg/RenderSVGTransformableContainer.h"
 
 namespace WebCore {
@@ -36,19 +36,18 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGSwitchElement::SVGSwitchElement(const QualifiedName& tagName, Document& document)
-    : SVGGraphicsElement(tagName, document)
+inline SVGSwitchElement::SVGSwitchElement(Document& document)
+    : SVGGraphicsElement(SVGNames::switchTag, document)
 {
-    ASSERT(hasTagName(SVGNames::switchTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGSwitchElement();
 
     UseCounter::count(document, UseCounter::SVGSwitchElement);
 }
 
-PassRefPtr<SVGSwitchElement> SVGSwitchElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSwitchElement> SVGSwitchElement::create(Document& document)
 {
-    return adoptRef(new SVGSwitchElement(tagName, document));
+    return adoptRef(new SVGSwitchElement(document));
 }
 
 bool SVGSwitchElement::childShouldCreateRenderer(const Node& child) const
diff --git a/Source/core/svg/SVGSwitchElement.h b/Source/core/svg/SVGSwitchElement.h
index d7af51c..48312ea 100644
--- a/Source/core/svg/SVGSwitchElement.h
+++ b/Source/core/svg/SVGSwitchElement.h
@@ -30,10 +30,10 @@
 class SVGSwitchElement FINAL : public SVGGraphicsElement,
                                public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGSwitchElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGSwitchElement> create(Document&);
 
 private:
-    SVGSwitchElement(const QualifiedName&, Document&);
+    explicit SVGSwitchElement(Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGSymbolElement.cpp b/Source/core/svg/SVGSymbolElement.cpp
index 2d65a2d..2c16270 100644
--- a/Source/core/svg/SVGSymbolElement.cpp
+++ b/Source/core/svg/SVGSymbolElement.cpp
@@ -41,17 +41,16 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGSymbolElement::SVGSymbolElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGSymbolElement::SVGSymbolElement(Document& document)
+    : SVGElement(SVGNames::symbolTag, document)
 {
-    ASSERT(hasTagName(SVGNames::symbolTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGSymbolElement();
 }
 
-PassRefPtr<SVGSymbolElement> SVGSymbolElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSymbolElement> SVGSymbolElement::create(Document& document)
 {
-    return adoptRef(new SVGSymbolElement(tagName, document));
+    return adoptRef(new SVGSymbolElement(document));
 }
 
 bool SVGSymbolElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGSymbolElement.h b/Source/core/svg/SVGSymbolElement.h
index 9d010de..d65a0da 100644
--- a/Source/core/svg/SVGSymbolElement.h
+++ b/Source/core/svg/SVGSymbolElement.h
@@ -34,10 +34,10 @@
                                public SVGExternalResourcesRequired,
                                public SVGFitToViewBox {
 public:
-    static PassRefPtr<SVGSymbolElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGSymbolElement> create(Document&);
 
 private:
-    SVGSymbolElement(const QualifiedName&, Document&);
+    explicit SVGSymbolElement(Document&);
 
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
diff --git a/Source/core/svg/SVGTSpanElement.cpp b/Source/core/svg/SVGTSpanElement.cpp
index 7b47b96..77f13fc 100644
--- a/Source/core/svg/SVGTSpanElement.cpp
+++ b/Source/core/svg/SVGTSpanElement.cpp
@@ -27,16 +27,15 @@
 
 namespace WebCore {
 
-inline SVGTSpanElement::SVGTSpanElement(const QualifiedName& tagName, Document& document)
-    : SVGTextPositioningElement(tagName, document)
+inline SVGTSpanElement::SVGTSpanElement(Document& document)
+    : SVGTextPositioningElement(SVGNames::tspanTag, document)
 {
-    ASSERT(hasTagName(SVGNames::tspanTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGTSpanElement> SVGTSpanElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTSpanElement> SVGTSpanElement::create(Document& document)
 {
-    return adoptRef(new SVGTSpanElement(tagName, document));
+    return adoptRef(new SVGTSpanElement(document));
 }
 
 RenderObject* SVGTSpanElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGTSpanElement.h b/Source/core/svg/SVGTSpanElement.h
index 2861f85..547e9ee 100644
--- a/Source/core/svg/SVGTSpanElement.h
+++ b/Source/core/svg/SVGTSpanElement.h
@@ -27,10 +27,10 @@
 
 class SVGTSpanElement FINAL : public SVGTextPositioningElement {
 public:
-    static PassRefPtr<SVGTSpanElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGTSpanElement> create(Document&);
 
 private:
-    SVGTSpanElement(const QualifiedName&, Document&);
+    explicit SVGTSpanElement(Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const Node& child) const;
diff --git a/Source/core/svg/SVGTextContentElement.cpp b/Source/core/svg/SVGTextContentElement.cpp
index 6c87c15..a1901ab 100644
--- a/Source/core/svg/SVGTextContentElement.cpp
+++ b/Source/core/svg/SVGTextContentElement.cpp
@@ -113,13 +113,13 @@
     return SVGTextQuery(renderer()).textLength();
 }
 
-float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionState& es)
+float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     unsigned numberOfChars = getNumberOfChars();
     if (charnum >= numberOfChars) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return 0.0f;
     }
 
@@ -129,48 +129,48 @@
     return SVGTextQuery(renderer()).subStringLength(charnum, nchars);
 }
 
-SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionState& es)
+SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return FloatPoint();
     }
 
     return SVGTextQuery(renderer()).startPositionOfCharacter(charnum);
 }
 
-SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionState& es)
+SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return FloatPoint();
     }
 
     return SVGTextQuery(renderer()).endPositionOfCharacter(charnum);
 }
 
-SVGRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionState& es)
+SVGRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return SVGRect();
     }
 
     return SVGTextQuery(renderer()).extentOfCharacter(charnum);
 }
 
-float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionState& es)
+float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return 0.0f;
     }
 
@@ -183,11 +183,11 @@
     return SVGTextQuery(renderer()).characterNumberAtPosition(point);
 }
 
-void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionState& es)
+void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionState& exceptionState)
 {
     unsigned numberOfChars = getNumberOfChars();
     if (charnum >= numberOfChars) {
-        es.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
         return;
     }
 
diff --git a/Source/core/svg/SVGTextElement.cpp b/Source/core/svg/SVGTextElement.cpp
index d7ed0d6..1ab6fbb 100644
--- a/Source/core/svg/SVGTextElement.cpp
+++ b/Source/core/svg/SVGTextElement.cpp
@@ -29,16 +29,15 @@
 
 namespace WebCore {
 
-inline SVGTextElement::SVGTextElement(const QualifiedName& tagName, Document& doc)
-    : SVGTextPositioningElement(tagName, doc)
+inline SVGTextElement::SVGTextElement(Document& doc)
+    : SVGTextPositioningElement(SVGNames::textTag, doc)
 {
-    ASSERT(hasTagName(SVGNames::textTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGTextElement> SVGTextElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTextElement> SVGTextElement::create(Document& document)
 {
-    return adoptRef(new SVGTextElement(tagName, document));
+    return adoptRef(new SVGTextElement(document));
 }
 
 // We override SVGGraphics::animatedLocalTransform() so that the transform-origin
diff --git a/Source/core/svg/SVGTextElement.h b/Source/core/svg/SVGTextElement.h
index 7e05359..b52204c 100644
--- a/Source/core/svg/SVGTextElement.h
+++ b/Source/core/svg/SVGTextElement.h
@@ -28,12 +28,12 @@
 
 class SVGTextElement FINAL : public SVGTextPositioningElement {
 public:
-    static PassRefPtr<SVGTextElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGTextElement> create(Document&);
 
     virtual AffineTransform animatedLocalTransform() const;
 
 private:
-    SVGTextElement(const QualifiedName&, Document&);
+    explicit SVGTextElement(Document&);
 
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
diff --git a/Source/core/svg/SVGTextPathElement.cpp b/Source/core/svg/SVGTextPathElement.cpp
index eb21c90..9cbf1c1 100644
--- a/Source/core/svg/SVGTextPathElement.cpp
+++ b/Source/core/svg/SVGTextPathElement.cpp
@@ -44,20 +44,19 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextContentElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGTextPathElement::SVGTextPathElement(const QualifiedName& tagName, Document& document)
-    : SVGTextContentElement(tagName, document)
+inline SVGTextPathElement::SVGTextPathElement(Document& document)
+    : SVGTextContentElement(SVGNames::textPathTag, document)
     , m_startOffset(LengthModeOther)
     , m_method(SVGTextPathMethodAlign)
     , m_spacing(SVGTextPathSpacingExact)
 {
-    ASSERT(hasTagName(SVGNames::textPathTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGTextPathElement();
 }
 
-PassRefPtr<SVGTextPathElement> SVGTextPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTextPathElement> SVGTextPathElement::create(Document& document)
 {
-    return adoptRef(new SVGTextPathElement(tagName, document));
+    return adoptRef(new SVGTextPathElement(document));
 }
 
 SVGTextPathElement::~SVGTextPathElement()
diff --git a/Source/core/svg/SVGTextPathElement.h b/Source/core/svg/SVGTextPathElement.h
index d540780..2b7a38c 100644
--- a/Source/core/svg/SVGTextPathElement.h
+++ b/Source/core/svg/SVGTextPathElement.h
@@ -109,10 +109,10 @@
         TEXTPATH_SPACINGTYPE_EXACT = SVGTextPathSpacingExact
     };
 
-    static PassRefPtr<SVGTextPathElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGTextPathElement> create(Document&);
 
 private:
-    SVGTextPathElement(const QualifiedName&, Document&);
+    explicit SVGTextPathElement(Document&);
 
     virtual ~SVGTextPathElement();
 
diff --git a/Source/core/svg/SVGTitleElement.cpp b/Source/core/svg/SVGTitleElement.cpp
index acb2fd1..cd018b8 100644
--- a/Source/core/svg/SVGTitleElement.cpp
+++ b/Source/core/svg/SVGTitleElement.cpp
@@ -26,16 +26,15 @@
 
 namespace WebCore {
 
-inline SVGTitleElement::SVGTitleElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGTitleElement::SVGTitleElement(Document& document)
+    : SVGElement(SVGNames::titleTag, document)
 {
-    ASSERT(hasTagName(SVGNames::titleTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGTitleElement> SVGTitleElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTitleElement> SVGTitleElement::create(Document& document)
 {
-    return adoptRef(new SVGTitleElement(tagName, document));
+    return adoptRef(new SVGTitleElement(document));
 }
 
 Node::InsertionNotificationRequest SVGTitleElement::insertedInto(ContainerNode* rootParent)
diff --git a/Source/core/svg/SVGTitleElement.h b/Source/core/svg/SVGTitleElement.h
index e5ac03b..21c3127 100644
--- a/Source/core/svg/SVGTitleElement.h
+++ b/Source/core/svg/SVGTitleElement.h
@@ -27,10 +27,10 @@
 
 class SVGTitleElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGTitleElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGTitleElement> create(Document&);
 
 private:
-    SVGTitleElement(const QualifiedName&, Document&);
+    explicit SVGTitleElement(Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/svg/SVGTransformList.cpp b/Source/core/svg/SVGTransformList.cpp
index 76b94a8..f749b87 100644
--- a/Source/core/svg/SVGTransformList.cpp
+++ b/Source/core/svg/SVGTransformList.cpp
@@ -21,9 +21,9 @@
 #include "config.h"
 #include "core/svg/SVGTransformList.h"
 
+#include "core/svg/SVGParserUtilities.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/SVGTransform.h"
-#include "core/svg/SVGTransformable.h"
 #include "platform/transforms/AffineTransform.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -83,12 +83,12 @@
     } else if (transform.is8Bit()) {
         const LChar* ptr = transform.characters8();
         const LChar* end = ptr + transform.length();
-        if (!SVGTransformable::parseTransformAttribute(*this, ptr, end))
+        if (!parseTransformAttribute(*this, ptr, end))
             clear();
     } else {
         const UChar* ptr = transform.characters16();
         const UChar* end = ptr + transform.length();
-        if (!SVGTransformable::parseTransformAttribute(*this, ptr, end))
+        if (!parseTransformAttribute(*this, ptr, end))
             clear();
     }
 }
diff --git a/Source/core/svg/SVGTransformable.cpp b/Source/core/svg/SVGTransformable.cpp
deleted file mode 100644
index a7d1ea5..0000000
--- a/Source/core/svg/SVGTransformable.cpp
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
- * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
- *
- * 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.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGTransformable.h"
-
-#include "core/svg/SVGParserUtilities.h"
-#include "core/svg/SVGTransformList.h"
-#include "platform/transforms/AffineTransform.h"
-
-namespace WebCore {
-
-template<typename CharType>
-static int parseTransformParamList(const CharType*& ptr, const CharType* end, float* values, int required, int optional)
-{
-    int optionalParams = 0, requiredParams = 0;
-
-    if (!skipOptionalSVGSpaces(ptr, end) || *ptr != '(')
-        return -1;
-
-    ptr++;
-
-    skipOptionalSVGSpaces(ptr, end);
-
-    while (requiredParams < required) {
-        if (ptr >= end || !parseNumber(ptr, end, values[requiredParams], false))
-            return -1;
-        requiredParams++;
-        if (requiredParams < required)
-            skipOptionalSVGSpacesOrDelimiter(ptr, end);
-    }
-    if (!skipOptionalSVGSpaces(ptr, end))
-        return -1;
-
-    bool delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
-
-    if (ptr >= end)
-        return -1;
-
-    if (*ptr == ')') { // skip optionals
-        ptr++;
-        if (delimParsed)
-            return -1;
-    } else {
-        while (optionalParams < optional) {
-            if (ptr >= end || !parseNumber(ptr, end, values[requiredParams + optionalParams], false))
-                return -1;
-            optionalParams++;
-            if (optionalParams < optional)
-                skipOptionalSVGSpacesOrDelimiter(ptr, end);
-        }
-
-        if (!skipOptionalSVGSpaces(ptr, end))
-            return -1;
-
-        delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
-
-        if (ptr >= end || *ptr != ')' || delimParsed)
-            return -1;
-        ptr++;
-    }
-
-    return requiredParams + optionalParams;
-}
-
-// These should be kept in sync with enum SVGTransformType
-static const int requiredValuesForType[] =  {0, 6, 1, 1, 1, 1, 1};
-static const int optionalValuesForType[] =  {0, 0, 1, 1, 2, 0, 0};
-
-// This destructor is needed in order to link correctly with Intel ICC.
-SVGTransformable::~SVGTransformable()
-{
-}
-
-template<typename CharType>
-static bool parseTransformValueInternal(unsigned type, const CharType*& ptr, const CharType* end, SVGTransform& transform)
-{
-    if (type == SVGTransform::SVG_TRANSFORM_UNKNOWN)
-        return false;
-
-    int valueCount = 0;
-    float values[] = {0, 0, 0, 0, 0, 0};
-    if ((valueCount = parseTransformParamList(ptr, end, values, requiredValuesForType[type], optionalValuesForType[type])) < 0)
-        return false;
-
-    switch (type) {
-    case SVGTransform::SVG_TRANSFORM_SKEWX:
-        transform.setSkewX(values[0]);
-        break;
-    case SVGTransform::SVG_TRANSFORM_SKEWY:
-        transform.setSkewY(values[0]);
-        break;
-    case SVGTransform::SVG_TRANSFORM_SCALE:
-        if (valueCount == 1) // Spec: if only one param given, assume uniform scaling
-            transform.setScale(values[0], values[0]);
-        else
-            transform.setScale(values[0], values[1]);
-        break;
-    case SVGTransform::SVG_TRANSFORM_TRANSLATE:
-        if (valueCount == 1) // Spec: if only one param given, assume 2nd param to be 0
-            transform.setTranslate(values[0], 0);
-        else
-            transform.setTranslate(values[0], values[1]);
-        break;
-    case SVGTransform::SVG_TRANSFORM_ROTATE:
-        if (valueCount == 1)
-            transform.setRotate(values[0], 0, 0);
-        else
-            transform.setRotate(values[0], values[1], values[2]);
-        break;
-    case SVGTransform::SVG_TRANSFORM_MATRIX:
-        transform.setMatrix(AffineTransform(values[0], values[1], values[2], values[3], values[4], values[5]));
-        break;
-    }
-
-    return true;
-}
-
-bool SVGTransformable::parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform& transform)
-{
-    return parseTransformValueInternal(type, ptr, end, transform);
-}
-
-bool SVGTransformable::parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform& transform)
-{
-    return parseTransformValueInternal(type, ptr, end, transform);
-}
-
-static const LChar skewXDesc[] =  {'s', 'k', 'e', 'w', 'X'};
-static const LChar skewYDesc[] =  {'s', 'k', 'e', 'w', 'Y'};
-static const LChar scaleDesc[] =  {'s', 'c', 'a', 'l', 'e'};
-static const LChar translateDesc[] =  {'t', 'r', 'a', 'n', 's', 'l', 'a', 't', 'e'};
-static const LChar rotateDesc[] =  {'r', 'o', 't', 'a', 't', 'e'};
-static const LChar matrixDesc[] =  {'m', 'a', 't', 'r', 'i', 'x'};
-
-template<typename CharType>
-static inline bool parseAndSkipType(const CharType*& ptr, const CharType* end, unsigned short& type)
-{
-    if (ptr >= end)
-        return false;
-
-    if (*ptr == 's') {
-        if (skipString(ptr, end, skewXDesc, WTF_ARRAY_LENGTH(skewXDesc)))
-            type = SVGTransform::SVG_TRANSFORM_SKEWX;
-        else if (skipString(ptr, end, skewYDesc, WTF_ARRAY_LENGTH(skewYDesc)))
-            type = SVGTransform::SVG_TRANSFORM_SKEWY;
-        else if (skipString(ptr, end, scaleDesc, WTF_ARRAY_LENGTH(scaleDesc)))
-            type = SVGTransform::SVG_TRANSFORM_SCALE;
-        else
-            return false;
-    } else if (skipString(ptr, end, translateDesc, WTF_ARRAY_LENGTH(translateDesc)))
-        type = SVGTransform::SVG_TRANSFORM_TRANSLATE;
-    else if (skipString(ptr, end, rotateDesc, WTF_ARRAY_LENGTH(rotateDesc)))
-        type = SVGTransform::SVG_TRANSFORM_ROTATE;
-    else if (skipString(ptr, end, matrixDesc, WTF_ARRAY_LENGTH(matrixDesc)))
-        type = SVGTransform::SVG_TRANSFORM_MATRIX;
-    else
-        return false;
-
-    return true;
-}
-
-SVGTransform::SVGTransformType SVGTransformable::parseTransformType(const String& string)
-{
-    if (string.isEmpty())
-        return SVGTransform::SVG_TRANSFORM_UNKNOWN;
-    unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
-    if (string.is8Bit()) {
-        const LChar* ptr = string.characters8();
-        const LChar* end = ptr + string.length();
-        parseAndSkipType(ptr, end, type);
-    } else {
-        const UChar* ptr = string.characters16();
-        const UChar* end = ptr + string.length();
-        parseAndSkipType(ptr, end, type);
-    }
-    return static_cast<SVGTransform::SVGTransformType>(type);
-}
-
-template<typename CharType>
-bool SVGTransformable::parseTransformAttributeInternal(SVGTransformList& list, const CharType*& ptr, const CharType* end, TransformParsingMode mode)
-{
-    if (mode == ClearList)
-        list.clear();
-
-    bool delimParsed = false;
-    while (ptr < end) {
-        delimParsed = false;
-        unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
-        skipOptionalSVGSpaces(ptr, end);
-
-        if (!parseAndSkipType(ptr, end, type))
-            return false;
-
-        SVGTransform transform;
-        if (!parseTransformValue(type, ptr, end, transform))
-            return false;
-
-        list.append(transform);
-        skipOptionalSVGSpaces(ptr, end);
-        if (ptr < end && *ptr == ',') {
-            delimParsed = true;
-            ++ptr;
-        }
-        skipOptionalSVGSpaces(ptr, end);
-    }
-
-    return !delimParsed;
-}
-
-bool SVGTransformable::parseTransformAttribute(SVGTransformList& list, const LChar*& ptr, const LChar* end, TransformParsingMode mode)
-{
-    return parseTransformAttributeInternal(list, ptr, end, mode);
-}
-
-bool SVGTransformable::parseTransformAttribute(SVGTransformList& list, const UChar*& ptr, const UChar* end, TransformParsingMode mode)
-{
-    return parseTransformAttributeInternal(list, ptr, end, mode);
-}
-
-}
diff --git a/Source/core/svg/SVGTransformable.h b/Source/core/svg/SVGTransformable.h
deleted file mode 100644
index f060545..0000000
--- a/Source/core/svg/SVGTransformable.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
- *
- * 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.
- */
-
-#ifndef SVGTransformable_h
-#define SVGTransformable_h
-
-#include "core/svg/SVGLocatable.h"
-#include "core/svg/SVGTransform.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class AffineTransform;
-class SVGTransformList;
-
-class SVGTransformable : virtual public SVGLocatable {
-public:
-    enum TransformParsingMode {
-        ClearList,
-        DoNotClearList
-    };
-
-    virtual ~SVGTransformable();
-
-    static bool parseTransformAttribute(SVGTransformList&, const LChar*& ptr, const LChar* end, TransformParsingMode = ClearList);
-    static bool parseTransformAttribute(SVGTransformList&, const UChar*& ptr, const UChar* end, TransformParsingMode = ClearList);
-
-    static bool parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform&);
-    static bool parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform&);
-
-    static SVGTransform::SVGTransformType parseTransformType(const String&);
-
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const { return animatedLocalTransform(); }
-    virtual AffineTransform animatedLocalTransform() const = 0;
-
-private:
-    template<typename CharType>
-    static bool parseTransformAttributeInternal(SVGTransformList&, const CharType*& ptr, const CharType* end, TransformParsingMode);
-};
-
-} // namespace WebCore
-
-#endif // SVGTransformable_h
diff --git a/Source/core/svg/SVGURIReference.cpp b/Source/core/svg/SVGURIReference.cpp
index f51aa1c..be2e512 100644
--- a/Source/core/svg/SVGURIReference.cpp
+++ b/Source/core/svg/SVGURIReference.cpp
@@ -24,7 +24,7 @@
 
 #include "XLinkNames.h"
 #include "core/dom/Document.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 
 namespace WebCore {
 
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index 6917554..e09dee8 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -71,8 +71,8 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
-    : SVGGraphicsElement(tagName, document)
+inline SVGUseElement::SVGUseElement(Document& document, bool wasInsertedByParser)
+    : SVGGraphicsElement(SVGNames::useTag, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
@@ -83,15 +83,14 @@
     , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
 {
     ASSERT(hasCustomStyleCallbacks());
-    ASSERT(hasTagName(SVGNames::useTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGUseElement();
 }
 
-PassRefPtr<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
+PassRefPtr<SVGUseElement> SVGUseElement::create(Document& document, bool wasInsertedByParser)
 {
     // Always build a #shadow-root for SVGUseElement.
-    RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(tagName, document, wasInsertedByParser));
+    RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(document, wasInsertedByParser));
     use->ensureUserAgentShadowRoot();
     return use.release();
 }
@@ -159,12 +158,14 @@
     reportAttributeParsingError(parseError, name, value);
 }
 
+#if !ASSERT_DISABLED
 static inline bool isWellFormedDocument(Document* document)
 {
     if (document->isSVGDocument() || document->isXHTMLDocument())
         return static_cast<XMLDocumentParser*>(document->parser())->wellFormed();
     return true;
 }
+#endif
 
 Node::InsertionNotificationRequest SVGUseElement::insertedInto(ContainerNode* rootParent)
 {
@@ -665,18 +666,19 @@
     return false;
 }
 
-static inline void removeDisallowedElementsFromSubtree(Element* subtree)
+static inline void removeDisallowedElementsFromSubtree(Element& subtree)
 {
-    ASSERT(!subtree->inDocument());
+    ASSERT(!subtree.inDocument());
     Element* element = ElementTraversal::firstWithin(subtree);
     while (element) {
         if (isDisallowedElement(element)) {
-            Element* next = ElementTraversal::nextSkippingChildren(element, subtree);
+            Element* next = ElementTraversal::nextSkippingChildren(*element, &subtree);
             // The subtree is not in document so this won't generate events that could mutate the tree.
             element->parentNode()->removeChild(element);
             element = next;
-        } else
-            element = ElementTraversal::next(element, subtree);
+        } else {
+            element = ElementTraversal::next(*element, &subtree);
+        }
     }
 }
 
@@ -694,7 +696,7 @@
     // Though if there are disallowed elements in the subtree, we have to remove them.
     // For instance: <use> on <g> containing <foreignObject> (indirect case).
     if (subtreeContainsDisallowedElement(newChild.get()))
-        removeDisallowedElementsFromSubtree(newChild.get());
+        removeDisallowedElementsFromSubtree(*newChild);
 
     userAgentShadowRoot()->appendChild(newChild.release());
 }
@@ -720,7 +722,7 @@
 
         // Don't ASSERT(target) here, it may be "pending", too.
         // Setup sub-shadow tree root node
-        RefPtr<SVGGElement> cloneParent = SVGGElement::create(SVGNames::gTag, *referencedDocument());
+        RefPtr<SVGGElement> cloneParent = SVGGElement::create(*referencedDocument());
         use->cloneChildNodes(cloneParent.get());
 
         // Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the
@@ -739,7 +741,7 @@
         // Though if there are disallowed elements in the subtree, we have to remove them.
         // For instance: <use> on <g> containing <foreignObject> (indirect case).
         if (subtreeContainsDisallowedElement(cloneParent.get()))
-            removeDisallowedElementsFromSubtree(cloneParent.get());
+            removeDisallowedElementsFromSubtree(*cloneParent);
 
         RefPtr<Node> replacingElement(cloneParent.get());
 
@@ -768,7 +770,7 @@
         // the generated 'svg'. If attributes width and/or height are not specified, the generated
         // 'svg' element will use values of 100% for these attributes.
         ASSERT(referencedDocument());
-        RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(SVGNames::svgTag, *referencedDocument());
+        RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(*referencedDocument());
 
         // Transfer all data (attributes, etc.) from <symbol> to the new <svg> element.
         svgElement->cloneDataFromElement(*toElement(element));
@@ -785,7 +787,7 @@
         // Though if there are disallowed elements in the subtree, we have to remove them.
         // For instance: <use> on <g> containing <foreignObject> (indirect case).
         if (subtreeContainsDisallowedElement(svgElement.get()))
-            removeDisallowedElementsFromSubtree(svgElement.get());
+            removeDisallowedElementsFromSubtree(*svgElement);
 
         RefPtr<Node> replacingElement(svgElement.get());
 
diff --git a/Source/core/svg/SVGUseElement.h b/Source/core/svg/SVGUseElement.h
index 3cc6b6b..800af8f 100644
--- a/Source/core/svg/SVGUseElement.h
+++ b/Source/core/svg/SVGUseElement.h
@@ -39,7 +39,7 @@
                             public SVGURIReference,
                             public DocumentResourceClient {
 public:
-    static PassRefPtr<SVGUseElement> create(const QualifiedName&, Document&, bool wasInsertedByParser);
+    static PassRefPtr<SVGUseElement> create(Document&, bool wasInsertedByParser);
     virtual ~SVGUseElement();
 
     SVGElementInstance* instanceRoot();
@@ -51,7 +51,7 @@
     RenderObject* rendererClipChild() const;
 
 private:
-    SVGUseElement(const QualifiedName&, Document&, bool wasInsertedByParser);
+    SVGUseElement(Document&, bool wasInsertedByParser);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGVKernElement.cpp b/Source/core/svg/SVGVKernElement.cpp
index 0908be7..36d444e 100644
--- a/Source/core/svg/SVGVKernElement.cpp
+++ b/Source/core/svg/SVGVKernElement.cpp
@@ -28,16 +28,15 @@
 
 namespace WebCore {
 
-inline SVGVKernElement::SVGVKernElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGVKernElement::SVGVKernElement(Document& document)
+    : SVGElement(SVGNames::vkernTag, document)
 {
-    ASSERT(hasTagName(SVGNames::vkernTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGVKernElement> SVGVKernElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGVKernElement> SVGVKernElement::create(Document& document)
 {
-    return adoptRef(new SVGVKernElement(tagName, document));
+    return adoptRef(new SVGVKernElement(document));
 }
 
 Node::InsertionNotificationRequest SVGVKernElement::insertedInto(ContainerNode* rootParent)
diff --git a/Source/core/svg/SVGVKernElement.h b/Source/core/svg/SVGVKernElement.h
index 6dfc55d..f8837bf 100644
--- a/Source/core/svg/SVGVKernElement.h
+++ b/Source/core/svg/SVGVKernElement.h
@@ -29,12 +29,12 @@
 
 class SVGVKernElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGVKernElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGVKernElement> create(Document&);
 
     void buildVerticalKerningPair(KerningPairVector&);
 
 private:
-    SVGVKernElement(const QualifiedName&, Document&);
+    explicit SVGVKernElement(Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/svg/SVGViewElement.cpp b/Source/core/svg/SVGViewElement.cpp
index 89d7bc4..55237b6 100644
--- a/Source/core/svg/SVGViewElement.cpp
+++ b/Source/core/svg/SVGViewElement.cpp
@@ -41,19 +41,18 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGViewElement::SVGViewElement(const QualifiedName& tagName, Document& document)
-    : SVGElement(tagName, document)
+inline SVGViewElement::SVGViewElement(Document& document)
+    : SVGElement(SVGNames::viewTag, document)
     , m_zoomAndPan(SVGZoomAndPanMagnify)
     , m_viewTarget(SVGNames::viewTargetAttr)
 {
-    ASSERT(hasTagName(SVGNames::viewTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGViewElement();
 }
 
-PassRefPtr<SVGViewElement> SVGViewElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGViewElement> SVGViewElement::create(Document& document)
 {
-    return adoptRef(new SVGViewElement(tagName, document));
+    return adoptRef(new SVGViewElement(document));
 }
 
 bool SVGViewElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGViewElement.h b/Source/core/svg/SVGViewElement.h
index dc40c62..3069cbf 100644
--- a/Source/core/svg/SVGViewElement.h
+++ b/Source/core/svg/SVGViewElement.h
@@ -38,7 +38,7 @@
                              public SVGFitToViewBox,
                              public SVGZoomAndPan {
 public:
-    static PassRefPtr<SVGViewElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<SVGViewElement> create(Document&);
 
     using SVGElement::ref;
     using SVGElement::deref;
@@ -48,7 +48,7 @@
     void setZoomAndPan(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
 
 private:
-    SVGViewElement(const QualifiedName&, Document&);
+    explicit SVGViewElement(Document&);
 
     // FIXME: svgAttributeChanged missing.
     bool isSupportedAttribute(const QualifiedName&);
diff --git a/Source/core/svg/SVGViewSpec.cpp b/Source/core/svg/SVGViewSpec.cpp
index b63ed50..cc32925 100644
--- a/Source/core/svg/SVGViewSpec.cpp
+++ b/Source/core/svg/SVGViewSpec.cpp
@@ -27,7 +27,6 @@
 #include "core/svg/SVGFitToViewBox.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "core/svg/SVGSVGElement.h"
-#include "core/svg/SVGTransformable.h"
 
 namespace WebCore {
 
@@ -77,7 +76,7 @@
     return s_propertyInfo;
 }
 
-SVGViewSpec::SVGViewSpec(SVGElement* contextElement)
+SVGViewSpec::SVGViewSpec(WeakPtr<SVGSVGElement> contextElement)
     : m_contextElement(contextElement)
     , m_zoomAndPan(SVGZoomAndPanMagnify)
 {
@@ -103,10 +102,10 @@
     return s_identifier;
 }
 
-void SVGViewSpec::setZoomAndPan(unsigned short, ExceptionState& es)
+void SVGViewSpec::setZoomAndPan(unsigned short, ExceptionState& exceptionState)
 {
     // SVGViewSpec and all of its content is read-only.
-    es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
 }
 
 void SVGViewSpec::setTransformString(const String& transform)
@@ -117,7 +116,7 @@
     SVGTransformList newList;
     newList.parse(transform);
 
-    if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGElement, SVGAnimatedTransformList>(m_contextElement, transformPropertyInfo()))
+    if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGElement, SVGAnimatedTransformList>(m_contextElement.get(), transformPropertyInfo()))
         static_cast<SVGAnimatedTransformList*>(wrapper)->detachListWrappers(newList.size());
 
     m_transform = newList;
@@ -142,7 +141,7 @@
 {
     if (!m_contextElement)
         return 0;
-    Element* element = m_contextElement->treeScope().getElementById(m_viewTargetString);
+    Element* element = m_contextElement.get()->treeScope().getElementById(m_viewTargetString);
     if (!element || !element->isSVGElement())
         return 0;
     return toSVGElement(element);
@@ -224,7 +223,7 @@
                     return false;
                 ptr++;
                 SVGRect viewBox;
-                if (!SVGFitToViewBox::parseViewBox(&m_contextElement->document(), ptr, end, viewBox, false))
+                if (!SVGFitToViewBox::parseViewBox(&m_contextElement.get()->document(), ptr, end, viewBox, false))
                     return false;
                 setViewBoxBaseValue(viewBox);
                 if (ptr >= end || *ptr != ')')
@@ -272,7 +271,7 @@
             if (ptr >= end || *ptr != '(')
                 return false;
             ptr++;
-            SVGTransformable::parseTransformAttribute(m_transform, ptr, end, SVGTransformable::DoNotClearList);
+            parseTransformAttribute(m_transform, ptr, end, DoNotClearList);
             if (ptr >= end || *ptr != ')')
                 return false;
             ptr++;
diff --git a/Source/core/svg/SVGViewSpec.h b/Source/core/svg/SVGViewSpec.h
index f738a32..c5d742f 100644
--- a/Source/core/svg/SVGViewSpec.h
+++ b/Source/core/svg/SVGViewSpec.h
@@ -24,13 +24,14 @@
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
 #include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGFitToViewBox.h"
+#include "core/svg/SVGSVGElement.h"
 #include "core/svg/SVGTransformList.h"
 #include "core/svg/SVGZoomAndPan.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
 class ExceptionState;
-class SVGElement;
 class SVGTransformListPropertyTearOff;
 
 class SVGViewSpec FINAL : public RefCounted<SVGViewSpec>, public ScriptWrappable, public SVGZoomAndPan, public SVGFitToViewBox {
@@ -38,7 +39,7 @@
     using RefCounted<SVGViewSpec>::ref;
     using RefCounted<SVGViewSpec>::deref;
 
-    static PassRefPtr<SVGViewSpec> create(SVGElement* contextElement)
+    static PassRefPtr<SVGViewSpec> create(WeakPtr<SVGSVGElement> contextElement)
     {
         return adoptRef(new SVGViewSpec(contextElement));
     }
@@ -62,8 +63,7 @@
     void setZoomAndPan(unsigned short, ExceptionState&);
     void setZoomAndPanBaseValue(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
 
-    SVGElement* contextElement() const { return m_contextElement; }
-    void resetContextElement() { m_contextElement = 0; }
+    SVGElement* contextElement() const { return m_contextElement.get(); }
 
     // Custom non-animated 'transform' property.
     SVGTransformListPropertyTearOff* transform();
@@ -82,7 +82,7 @@
     void setPreserveAspectRatioBaseValue(const SVGPreserveAspectRatio& preserveAspectRatio) { m_preserveAspectRatio = preserveAspectRatio; }
 
 private:
-    explicit SVGViewSpec(SVGElement*);
+    explicit SVGViewSpec(WeakPtr<SVGSVGElement>);
 
     static const SVGPropertyInfo* transformPropertyInfo();
     static const SVGPropertyInfo* viewBoxPropertyInfo();
@@ -99,9 +99,9 @@
     template<typename CharType>
     bool parseViewSpecInternal(const CharType* ptr, const CharType* end);
 
-    SVGElement* m_contextElement;
-    SVGZoomAndPanType m_zoomAndPan;
+    WeakPtr<SVGSVGElement> m_contextElement;
 
+    SVGZoomAndPanType m_zoomAndPan;
     SVGTransformList m_transform;
     SVGRect m_viewBox;
     SVGPreserveAspectRatio m_preserveAspectRatio;
diff --git a/Source/core/svg/SVGViewSpec.idl b/Source/core/svg/SVGViewSpec.idl
index ab57e7e..80b1d80 100644
--- a/Source/core/svg/SVGViewSpec.idl
+++ b/Source/core/svg/SVGViewSpec.idl
@@ -32,7 +32,7 @@
       readonly attribute DOMString viewTargetString;
 
       // SVGZoomAndPan
-      [SetterRaisesException] attribute unsigned short zoomAndPan;
+      [RaisesException=Setter] attribute unsigned short zoomAndPan;
 };
 
 SVGViewSpec implements SVGFitToViewBox;
diff --git a/Source/core/svg/animation/SMILTimeContainer.cpp b/Source/core/svg/animation/SMILTimeContainer.cpp
index 0849327..2f3445d 100644
--- a/Source/core/svg/animation/SMILTimeContainer.cpp
+++ b/Source/core/svg/animation/SMILTimeContainer.cpp
@@ -228,7 +228,7 @@
 void SMILTimeContainer::updateDocumentOrderIndexes()
 {
     unsigned timingElementCount = 0;
-    for (Element* element = m_ownerSVGElement; element; element = ElementTraversal::next(element, m_ownerSVGElement)) {
+    for (Element* element = m_ownerSVGElement; element; element = ElementTraversal::next(*element, m_ownerSVGElement)) {
         if (SVGSMILElement::isSMILElement(element))
             toSVGSMILElement(element)->setDocumentOrderIndex(timingElementCount++);
     }
diff --git a/Source/core/svg/graphics/SVGImage.cpp b/Source/core/svg/graphics/SVGImage.cpp
index 2db1db3..72df2d0 100644
--- a/Source/core/svg/graphics/SVGImage.cpp
+++ b/Source/core/svg/graphics/SVGImage.cpp
@@ -38,7 +38,6 @@
 #include "core/page/Settings.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/ImageObserver.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/svg/SVGDocument.h"
@@ -48,6 +47,7 @@
 #include "core/svg/graphics/SVGImageChromeClient.h"
 #include "platform/LengthFunctions.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/ImageObserver.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/graphics/SVGImageChromeClient.h b/Source/core/svg/graphics/SVGImageChromeClient.h
index b17ca84..914980a 100644
--- a/Source/core/svg/graphics/SVGImageChromeClient.h
+++ b/Source/core/svg/graphics/SVGImageChromeClient.h
@@ -30,7 +30,7 @@
 #define SVGImageChromeClient_h
 
 #include "core/loader/EmptyClients.h"
-#include "core/platform/graphics/ImageObserver.h"
+#include "platform/graphics/ImageObserver.h"
 
 namespace WebCore {
 
diff --git a/Source/core/svg/graphics/filters/SVGFEImage.cpp b/Source/core/svg/graphics/filters/SVGFEImage.cpp
index a14220a..feda6e0 100644
--- a/Source/core/svg/graphics/filters/SVGFEImage.cpp
+++ b/Source/core/svg/graphics/filters/SVGFEImage.cpp
@@ -121,13 +121,12 @@
         SVGElement* contextNode = toSVGElement(renderer->node());
         if (contextNode->hasRelativeLengths()) {
             SVGLengthContext lengthContext(contextNode);
-            float width = 0;
-            float height = 0;
+            FloatSize viewportSize;
 
             // If we're referencing an element with percentage units, eg. <rect with="30%"> those values were resolved against the viewport.
             // Build up a transformation that maps from the viewport space to the filter primitive subregion.
-            if (lengthContext.determineViewport(width, height))
-                resultImage->context()->concatCTM(makeMapBetweenRects(FloatRect(0, 0, width, height), destRect));
+            if (lengthContext.determineViewport(viewportSize))
+                resultImage->context()->concatCTM(makeMapBetweenRects(FloatRect(FloatPoint(), viewportSize), destRect));
         } else {
             const AffineTransform& absoluteTransform = filter()->absoluteTransform();
             resultImage->context()->concatCTM(absoluteTransform);
diff --git a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
index e8a58cc..962e7f3 100644
--- a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
@@ -29,14 +29,14 @@
 template<typename EnumType>
 class SVGAnimatedEnumerationPropertyTearOff : public SVGAnimatedStaticPropertyTearOff<unsigned> {
 public:
-    virtual void setBaseVal(const unsigned& property, ExceptionState& es)
+    virtual void setBaseVal(const unsigned& property, ExceptionState& exceptionState)
     {
         // All SVG enumeration values, that are allowed to be set via SVG DOM start with 1, 0 corresponds to unknown and is not settable through SVG DOM.
         if (!property || property > SVGPropertyTraits<EnumType>::highestEnumValue()) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return;
         }
-        SVGAnimatedStaticPropertyTearOff<unsigned>::setBaseVal(property, es);
+        SVGAnimatedStaticPropertyTearOff<unsigned>::setBaseVal(property, exceptionState);
     }
 
     static PassRefPtr<SVGAnimatedEnumerationPropertyTearOff<EnumType> > create(SVGElement* contextElement, const QualifiedName& attributeName, AnimatedPropertyType animatedPropertyType, EnumType& property)
diff --git a/Source/core/svg/properties/SVGAnimatedProperty.cpp b/Source/core/svg/properties/SVGAnimatedProperty.cpp
index 352f204..2258ad9 100644
--- a/Source/core/svg/properties/SVGAnimatedProperty.cpp
+++ b/Source/core/svg/properties/SVGAnimatedProperty.cpp
@@ -32,6 +32,7 @@
     , m_isAnimating(false)
     , m_isReadOnly(false)
 {
+    contextElement->setContextElement();
 }
 
 SVGAnimatedProperty::~SVGAnimatedProperty()
diff --git a/Source/core/svg/properties/SVGListProperty.h b/Source/core/svg/properties/SVGListProperty.h
index 250b0f5..27e8d66 100644
--- a/Source/core/svg/properties/SVGListProperty.h
+++ b/Source/core/svg/properties/SVGListProperty.h
@@ -49,10 +49,10 @@
     typedef SVGAnimatedListPropertyTearOff<PropertyType> AnimatedListPropertyTearOff;
     typedef typename SVGAnimatedListPropertyTearOff<PropertyType>::ListWrapperCache ListWrapperCache;
 
-    bool canAlterList(ExceptionState& es) const
+    bool canAlterList(ExceptionState& exceptionState) const
     {
         if (m_role == AnimValRole) {
-            es.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+            exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
             return false;
         }
 
@@ -97,18 +97,18 @@
     }
 
     // SVGList::clear()
-    void clearValues(ExceptionState& es)
+    void clearValues(ExceptionState& exceptionState)
     {
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return;
 
         m_values->clear();
         commitChange();
     }
 
-    void clearValuesAndWrappers(ExceptionState& es)
+    void clearValuesAndWrappers(ExceptionState& exceptionState)
     {
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return;
 
         detachListWrappers(0);
@@ -123,9 +123,9 @@
     }
 
     // SVGList::initialize()
-    ListItemType initializeValues(const ListItemType& newItem, ExceptionState& es)
+    ListItemType initializeValues(const ListItemType& newItem, ExceptionState& exceptionState)
     {
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return ListItemType();
 
         // Spec: If the inserted item is already in a list, it is removed from its previous list before it is inserted into this list.
@@ -139,15 +139,15 @@
         return newItem;
     }
 
-    PassListItemTearOff initializeValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& es)
+    PassListItemTearOff initializeValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
     {
         ASSERT(m_wrappers);
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return 0;
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -169,29 +169,29 @@
     }
 
     // SVGList::getItem()
-    bool canGetItem(unsigned index, ExceptionState& es)
+    bool canGetItem(unsigned index, ExceptionState& exceptionState)
     {
         if (index >= m_values->size()) {
-            es.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return false;
         }
 
         return true;
     }
 
-    ListItemType getItemValues(unsigned index, ExceptionState& es)
+    ListItemType getItemValues(unsigned index, ExceptionState& exceptionState)
     {
-        if (!canGetItem(index, es))
+        if (!canGetItem(index, exceptionState))
             return ListItemType();
 
         // Spec: Returns the specified item from the list. The returned item is the item itself and not a copy.
         return m_values->at(index);
     }
 
-    PassListItemTearOff getItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& es)
+    PassListItemTearOff getItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& exceptionState)
     {
         ASSERT(m_wrappers);
-        if (!canGetItem(index, es))
+        if (!canGetItem(index, exceptionState))
             return 0;
 
         // Spec: Returns the specified item from the list. The returned item is the item itself and not a copy.
@@ -210,9 +210,9 @@
     }
 
     // SVGList::insertItemBefore()
-    ListItemType insertItemBeforeValues(const ListItemType& newItem, unsigned index, ExceptionState& es)
+    ListItemType insertItemBeforeValues(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
     {
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return ListItemType();
 
         // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.
@@ -233,15 +233,15 @@
         return newItem;
     }
 
-    PassListItemTearOff insertItemBeforeValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+    PassListItemTearOff insertItemBeforeValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
     {
         ASSERT(m_wrappers);
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return 0;
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -268,22 +268,22 @@
     }
 
     // SVGList::replaceItem()
-    bool canReplaceItem(unsigned index, ExceptionState& es)
+    bool canReplaceItem(unsigned index, ExceptionState& exceptionState)
     {
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return false;
 
         if (index >= m_values->size()) {
-            es.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return false;
         }
 
         return true;
     }
 
-    ListItemType replaceItemValues(const ListItemType& newItem, unsigned index, ExceptionState& es)
+    ListItemType replaceItemValues(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
     {
-        if (!canReplaceItem(index, es))
+        if (!canReplaceItem(index, exceptionState))
             return ListItemType();
 
         // Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
@@ -295,7 +295,7 @@
 
         if (m_values->isEmpty()) {
             // 'newItem' already lived in our list, we removed it, and now we're empty, which means there's nothing to replace.
-            es.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return ListItemType();
         }
 
@@ -306,15 +306,15 @@
         return newItem;
     }
 
-    PassListItemTearOff replaceItemValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+    PassListItemTearOff replaceItemValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
     {
         ASSERT(m_wrappers);
-        if (!canReplaceItem(index, es))
+        if (!canReplaceItem(index, exceptionState))
             return 0;
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -329,7 +329,7 @@
         if (m_values->isEmpty()) {
             ASSERT(m_wrappers->isEmpty());
             // 'passNewItem' already lived in our list, we removed it, and now we're empty, which means there's nothing to replace.
-            es.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return 0;
         }
 
@@ -347,22 +347,22 @@
     }
 
     // SVGList::removeItem()
-    bool canRemoveItem(unsigned index, ExceptionState& es)
+    bool canRemoveItem(unsigned index, ExceptionState& exceptionState)
     {
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return false;
 
         if (index >= m_values->size()) {
-            es.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
             return false;
         }
 
         return true;
     }
 
-    ListItemType removeItemValues(unsigned index, ExceptionState& es)
+    ListItemType removeItemValues(unsigned index, ExceptionState& exceptionState)
     {
-        if (!canRemoveItem(index, es))
+        if (!canRemoveItem(index, exceptionState))
             return ListItemType();
 
         ListItemType oldItem = m_values->at(index);
@@ -372,10 +372,10 @@
         return oldItem;
     }
 
-    PassListItemTearOff removeItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& es)
+    PassListItemTearOff removeItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& exceptionState)
     {
         ASSERT(m_wrappers);
-        if (!canRemoveItem(index, es))
+        if (!canRemoveItem(index, exceptionState))
             return 0;
 
         ASSERT(m_values->size() == m_wrappers->size());
@@ -394,9 +394,9 @@
     }
 
     // SVGList::appendItem()
-    ListItemType appendItemValues(const ListItemType& newItem, ExceptionState& es)
+    ListItemType appendItemValues(const ListItemType& newItem, ExceptionState& exceptionState)
     {
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return ListItemType();
 
         // Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
@@ -409,15 +409,15 @@
         return newItem;
     }
 
-    PassListItemTearOff appendItemValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& es)
+    PassListItemTearOff appendItemValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
     {
         ASSERT(m_wrappers);
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return 0;
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
diff --git a/Source/core/svg/properties/SVGListPropertyTearOff.h b/Source/core/svg/properties/SVGListPropertyTearOff.h
index 2320435..7f14109 100644
--- a/Source/core/svg/properties/SVGListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGListPropertyTearOff.h
@@ -80,41 +80,41 @@
     }
 
     // SVGList API
-    void clear(ExceptionState& es)
+    void clear(ExceptionState& exceptionState)
     {
-        Base::clearValuesAndWrappers(es);
+        Base::clearValuesAndWrappers(exceptionState);
     }
 
-    PassListItemTearOff initialize(PassListItemTearOff passNewItem, ExceptionState& es)
+    PassListItemTearOff initialize(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
     {
-        return Base::initializeValuesAndWrappers(passNewItem, es);
+        return Base::initializeValuesAndWrappers(passNewItem, exceptionState);
     }
 
-    PassListItemTearOff getItem(unsigned index, ExceptionState& es)
+    PassListItemTearOff getItem(unsigned index, ExceptionState& exceptionState)
     {
         ASSERT(m_animatedProperty);
-        return Base::getItemValuesAndWrappers(m_animatedProperty, index, es);
+        return Base::getItemValuesAndWrappers(m_animatedProperty, index, exceptionState);
     }
 
-    PassListItemTearOff insertItemBefore(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+    PassListItemTearOff insertItemBefore(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
     {
-        return Base::insertItemBeforeValuesAndWrappers(passNewItem, index, es);
+        return Base::insertItemBeforeValuesAndWrappers(passNewItem, index, exceptionState);
     }
 
-    PassListItemTearOff replaceItem(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+    PassListItemTearOff replaceItem(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
     {
-        return Base::replaceItemValuesAndWrappers(passNewItem, index, es);
+        return Base::replaceItemValuesAndWrappers(passNewItem, index, exceptionState);
     }
 
-    PassListItemTearOff removeItem(unsigned index, ExceptionState& es)
+    PassListItemTearOff removeItem(unsigned index, ExceptionState& exceptionState)
     {
         ASSERT(m_animatedProperty);
-        return Base::removeItemValuesAndWrappers(m_animatedProperty, index, es);
+        return Base::removeItemValuesAndWrappers(m_animatedProperty, index, exceptionState);
     }
 
-    PassListItemTearOff appendItem(PassListItemTearOff passNewItem, ExceptionState& es)
+    PassListItemTearOff appendItem(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
     {
-        return Base::appendItemValuesAndWrappers(passNewItem, es);
+        return Base::appendItemValuesAndWrappers(passNewItem, exceptionState);
     }
 
     SVGElement* contextElement() const
diff --git a/Source/core/svg/properties/SVGMatrixTearOff.h b/Source/core/svg/properties/SVGMatrixTearOff.h
index 338899d..80ac600 100644
--- a/Source/core/svg/properties/SVGMatrixTearOff.h
+++ b/Source/core/svg/properties/SVGMatrixTearOff.h
@@ -27,6 +27,20 @@
 
 class SVGMatrixTearOff : public SVGPropertyTearOff<SVGMatrix> {
 public:
+    // Used for child types (baseVal/animVal) of a SVGAnimated* property (for example: SVGAnimatedLength::baseVal()).
+    // Also used for list tear offs (for example: text.x.baseVal.getItem(0)).
+    static PassRefPtr<SVGMatrixTearOff> create(SVGAnimatedProperty* animatedProperty, SVGPropertyRole role, SVGMatrix& value)
+    {
+        ASSERT(animatedProperty);
+        return adoptRef(new SVGMatrixTearOff(animatedProperty, role, value));
+    }
+
+    // Used for non-animated POD types (for example: SVGSVGElement::createSVGLength()).
+    static PassRefPtr<SVGMatrixTearOff> create(const SVGMatrix& initialValue)
+    {
+        return adoptRef(new SVGMatrixTearOff(initialValue));
+    }
+
     // Used for non-animated POD types that are not associated with a SVGAnimatedProperty object, nor with a XML DOM attribute
     // and that contain a parent type that's exposed to the bindings via a SVGStaticPropertyTearOff object
     // (for example: SVGTransform::matrix).
@@ -40,11 +54,33 @@
 
     virtual void commitChange()
     {
-        m_parent->propertyReference().updateSVGMatrix();
-        m_parent->commitChange();
+        if (m_parent) {
+            // This is a tear-off from a SVGPropertyTearOff<SVGTransform>.
+            m_parent->propertyReference().updateSVGMatrix();
+            m_parent->commitChange();
+        } else {
+            // This is either a detached tear-off or a reference tear-off from a AnimatedProperty.
+            SVGPropertyTearOff<SVGMatrix>::commitChange();
+        }
     }
 
+    SVGPropertyTearOff<SVGTransform>* parent() { return m_parent; }
+
 private:
+    SVGMatrixTearOff(SVGAnimatedProperty* animatedProperty, SVGPropertyRole role, SVGMatrix& value)
+        : SVGPropertyTearOff<SVGMatrix>(animatedProperty, role, value)
+        , m_parent(0)
+        , m_weakFactory(this)
+    {
+    }
+
+    SVGMatrixTearOff(const SVGMatrix& initialValue)
+        : SVGPropertyTearOff<SVGMatrix>(initialValue)
+        , m_parent(0)
+        , m_weakFactory(this)
+    {
+    }
+
     SVGMatrixTearOff(SVGPropertyTearOff<SVGTransform>* parent, SVGMatrix& value)
         : SVGPropertyTearOff<SVGMatrix>(0, UndefinedRole, value)
         , m_parent(parent)
@@ -52,7 +88,9 @@
     {
     }
 
-    RefPtr<SVGPropertyTearOff<SVGTransform> > m_parent;
+    // m_parent is kept alive from V8 wrapper.
+    SVGPropertyTearOff<SVGTransform>* m_parent;
+
     WeakPtrFactory<SVGPropertyTearOffBase > m_weakFactory;
 };
 
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
index eee1ada..de9dfaf 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -39,19 +39,19 @@
     }
 }
 
-void SVGPathSegListPropertyTearOff::clear(ExceptionState& es)
+void SVGPathSegListPropertyTearOff::clear(ExceptionState& exceptionState)
 {
     ASSERT(m_values);
     if (m_values->isEmpty())
         return;
 
     clearContextAndRoles();
-    SVGPathSegListPropertyTearOff::Base::clearValues(es);
+    SVGPathSegListPropertyTearOff::Base::clearValues(exceptionState);
 }
 
-SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::getItem(unsigned index, ExceptionState& es)
+SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::getItem(unsigned index, ExceptionState& exceptionState)
 {
-    ListItemType returnedItem = Base::getItemValues(index, es);
+    ListItemType returnedItem = Base::getItemValues(index, exceptionState);
     if (returnedItem) {
         ASSERT(static_cast<SVGPathSegWithContext*>(returnedItem.get())->contextElement() == contextElement());
         ASSERT(static_cast<SVGPathSegWithContext*>(returnedItem.get())->role() == m_pathSegRole);
@@ -59,11 +59,11 @@
     return returnedItem.release();
 }
 
-SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::replaceItem(PassListItemType passNewItem, unsigned index, ExceptionState& es)
+SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::replaceItem(PassListItemType passNewItem, unsigned index, ExceptionState& exceptionState)
 {
     // Not specified, but FF/Opera do it this way, and it's just sane.
     if (!passNewItem) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwUninformativeAndGenericTypeError();
         return 0;
     }
 
@@ -74,12 +74,12 @@
     }
 
     ListItemType newItem = passNewItem;
-    return Base::replaceItemValues(newItem, index, es);
+    return Base::replaceItemValues(newItem, index, exceptionState);
 }
 
-SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::removeItem(unsigned index, ExceptionState& es)
+SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::removeItem(unsigned index, ExceptionState& exceptionState)
 {
-    SVGPathSegListPropertyTearOff::ListItemType removedItem = SVGPathSegListPropertyTearOff::Base::removeItemValues(index, es);
+    SVGPathSegListPropertyTearOff::ListItemType removedItem = SVGPathSegListPropertyTearOff::Base::removeItemValues(index, exceptionState);
     if (removedItem)
         static_cast<SVGPathSegWithContext*>(removedItem.get())->setContextAndRole(0, PathSegUndefinedRole);
     return removedItem.release();
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
index b1a874a..4a755f7 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
@@ -42,7 +42,7 @@
     }
 
     SVGPathElement* contextElement() const;
-    SVGAnimatedProperty* animatedProperty() const { return m_animatedProperty.get(); }
+    SVGAnimatedProperty* animatedProperty() const { return m_animatedProperty; }
 
     int findItem(const ListItemType& item) const
     {
@@ -71,47 +71,47 @@
     // SVGList API
     void clear(ExceptionState&);
 
-    PassListItemType initialize(PassListItemType passNewItem, ExceptionState& es)
+    PassListItemType initialize(PassListItemType passNewItem, ExceptionState& exceptionState)
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
         clearContextAndRoles();
         ListItemType newItem = passNewItem;
-        return Base::initializeValues(newItem, es);
+        return Base::initializeValues(newItem, exceptionState);
     }
 
     PassListItemType getItem(unsigned index, ExceptionState&);
 
-    PassListItemType insertItemBefore(PassListItemType passNewItem, unsigned index, ExceptionState& es)
+    PassListItemType insertItemBefore(PassListItemType passNewItem, unsigned index, ExceptionState& exceptionState)
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
         ListItemType newItem = passNewItem;
-        return Base::insertItemBeforeValues(newItem, index, es);
+        return Base::insertItemBeforeValues(newItem, index, exceptionState);
     }
 
     PassListItemType replaceItem(PassListItemType, unsigned index, ExceptionState&);
 
     PassListItemType removeItem(unsigned index, ExceptionState&);
 
-    PassListItemType appendItem(PassListItemType passNewItem, ExceptionState& es)
+    PassListItemType appendItem(PassListItemType passNewItem, ExceptionState& exceptionState)
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwUninformativeAndGenericTypeError();
+            exceptionState.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
         ListItemType newItem = passNewItem;
-        return Base::appendItemValues(newItem, es);
+        return Base::appendItemValues(newItem, exceptionState);
     }
 
 private:
@@ -155,7 +155,7 @@
     }
 
 private:
-    RefPtr<AnimatedListPropertyTearOff> m_animatedProperty;
+    AnimatedListPropertyTearOff* m_animatedProperty;
     SVGPathSegRole m_pathSegRole;
 };
 
diff --git a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
index 1488c59..596a551 100644
--- a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
@@ -46,39 +46,39 @@
     SVGElement* contextElement() const { return m_contextElement; }
 
     // SVGList API
-    void clear(ExceptionState& es)
+    void clear(ExceptionState& exceptionState)
     {
-        Base::clearValues(es);
+        Base::clearValues(exceptionState);
     }
 
-    ListItemType initialize(const ListItemType& newItem, ExceptionState& es)
+    ListItemType initialize(const ListItemType& newItem, ExceptionState& exceptionState)
     {
-        return Base::initializeValues(newItem, es);
+        return Base::initializeValues(newItem, exceptionState);
     }
 
-    ListItemType getItem(unsigned index, ExceptionState& es)
+    ListItemType getItem(unsigned index, ExceptionState& exceptionState)
     {
-        return Base::getItemValues(index, es);
+        return Base::getItemValues(index, exceptionState);
     }
 
-    ListItemType insertItemBefore(const ListItemType& newItem, unsigned index, ExceptionState& es)
+    ListItemType insertItemBefore(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
     {
-        return Base::insertItemBeforeValues(newItem, index, es);
+        return Base::insertItemBeforeValues(newItem, index, exceptionState);
     }
 
-    ListItemType replaceItem(const ListItemType& newItem, unsigned index, ExceptionState& es)
+    ListItemType replaceItem(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
     {
-        return Base::replaceItemValues(newItem, index, es);
+        return Base::replaceItemValues(newItem, index, exceptionState);
     }
 
-    ListItemType removeItem(unsigned index, ExceptionState& es)
+    ListItemType removeItem(unsigned index, ExceptionState& exceptionState)
     {
-        return Base::removeItemValues(index, es);
+        return Base::removeItemValues(index, exceptionState);
     }
 
-    ListItemType appendItem(const ListItemType& newItem, ExceptionState& es)
+    ListItemType appendItem(const ListItemType& newItem, ExceptionState& exceptionState)
     {
-        return Base::appendItemValues(newItem, es);
+        return Base::appendItemValues(newItem, exceptionState);
     }
 
 private:
@@ -86,6 +86,7 @@
         : SVGListProperty<PropertyType>(UndefinedRole, values, 0)
         , m_contextElement(contextElement)
     {
+        m_contextElement->setContextElement();
     }
 
     virtual bool isReadOnly() const
diff --git a/Source/core/svg/properties/SVGStaticPropertyTearOff.h b/Source/core/svg/properties/SVGStaticPropertyTearOff.h
index 7668336..93d1cc5 100644
--- a/Source/core/svg/properties/SVGStaticPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGStaticPropertyTearOff.h
@@ -51,6 +51,7 @@
         , m_update(update)
         , m_contextElement(contextElement)
     {
+        m_contextElement->setContextElement();
     }
 
     UpdateMethod m_update;
diff --git a/Source/core/svg/properties/SVGTransformListPropertyTearOff.h b/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
index d57f887..2ec007f 100644
--- a/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
@@ -39,21 +39,21 @@
         return adoptRef(new SVGTransformListPropertyTearOff(animatedProperty, role, values, wrappers));
     }
 
-    PassRefPtr<SVGPropertyTearOff<SVGTransform> > createSVGTransformFromMatrix(SVGPropertyTearOff<SVGMatrix>* matrix, ExceptionState& es)
+    PassRefPtr<SVGPropertyTearOff<SVGTransform> > createSVGTransformFromMatrix(SVGPropertyTearOff<SVGMatrix>* matrix, ExceptionState& exceptionState)
     {
         ASSERT(m_values);
         if (!matrix) {
-            es.throwUninformativeAndGenericDOMException(TypeMismatchError);
+            exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
             return 0;
         }
         return SVGPropertyTearOff<SVGTransform>::create(m_values->createSVGTransformFromMatrix(matrix->propertyReference()));
     }
 
-    PassRefPtr<SVGPropertyTearOff<SVGTransform> > consolidate(ExceptionState& es)
+    PassRefPtr<SVGPropertyTearOff<SVGTransform> > consolidate(ExceptionState& exceptionState)
     {
         ASSERT(m_values);
         ASSERT(m_wrappers);
-        if (!canAlterList(es))
+        if (!canAlterList(exceptionState))
             return 0;
 
         ASSERT(m_values->size() == m_wrappers->size());
diff --git a/Source/core/testing/DummyPageHolder.cpp b/Source/core/testing/DummyPageHolder.cpp
new file mode 100644
index 0000000..e409550
--- /dev/null
+++ b/Source/core/testing/DummyPageHolder.cpp
@@ -0,0 +1,89 @@
+/*
+ * 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/testing/DummyPageHolder.h"
+
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+PassOwnPtr<DummyPageHolder> DummyPageHolder::create(const IntSize& initialViewSize)
+{
+    return adoptPtr(new DummyPageHolder(initialViewSize));
+}
+
+DummyPageHolder::DummyPageHolder(const IntSize& initialViewSize)
+{
+    m_pageClients.chromeClient = &m_chromeClient;
+    m_pageClients.contextMenuClient = &m_contextMenuClient;
+    m_pageClients.editorClient = &m_editorClient;
+    m_pageClients.dragClient = &m_dragClient;
+    m_pageClients.inspectorClient = &m_inspectorClient;
+    m_pageClients.backForwardClient = &m_backForwardClient;
+
+    m_page = adoptPtr(new Page(m_pageClients));
+
+    m_frame = Frame::create(FrameInit::create(0, m_page.get(), &m_frameLoaderClient));
+    m_frame->setView(FrameView::create(m_frame.get(), initialViewSize));
+    m_frame->init();
+}
+
+DummyPageHolder::~DummyPageHolder()
+{
+    m_page.clear();
+    ASSERT(m_frame->hasOneRef());
+    m_frame.clear();
+}
+
+Page& DummyPageHolder::page() const
+{
+    return *m_page;
+}
+
+Frame& DummyPageHolder::frame() const
+{
+    return *m_frame;
+}
+
+FrameView& DummyPageHolder::frameView() const
+{
+    return *m_frame->view();
+}
+
+Document& DummyPageHolder::document() const
+{
+    return *m_frame->domWindow()->document();
+}
+
+} // namespace WebCore
diff --git a/Source/core/testing/DummyPageHolder.h b/Source/core/testing/DummyPageHolder.h
new file mode 100644
index 0000000..d80f4dc
--- /dev/null
+++ b/Source/core/testing/DummyPageHolder.h
@@ -0,0 +1,88 @@
+/*
+ * 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 DummyPageHolder_h
+#define DummyPageHolder_h
+
+#include "core/loader/EmptyClients.h"
+#include "core/page/Page.h"
+#include "platform/geometry/IntSize.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class Document;
+class Frame;
+class FrameView;
+class IntSize;
+
+// Creates a dummy Page, Frame, and FrameView whose clients are all no-op.
+//
+// This class can be used when you write unit tests for components which do not work correctly without renderers.
+// To make sure the renderers are created, you need to call |frameView().layout()| after you add nodes into
+// |document()|.
+//
+// Since DummyPageHolder stores empty clients in it, it must outlive the Page, Frame, FrameView and any other objects
+// created by it. DummyPageHolder's destructor ensures this condition by checking remaining references to the Frame.
+
+class DummyPageHolder {
+    WTF_MAKE_NONCOPYABLE(DummyPageHolder);
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    static PassOwnPtr<DummyPageHolder> create(const IntSize& initialViewSize = IntSize());
+    ~DummyPageHolder();
+
+    Page& page() const;
+    Frame& frame() const;
+    FrameView& frameView() const;
+    Document& document() const;
+
+private:
+    explicit DummyPageHolder(const IntSize& initialViewSize);
+
+    OwnPtr<Page> m_page;
+    RefPtr<Frame> m_frame;
+
+    Page::PageClients m_pageClients;
+    EmptyChromeClient m_chromeClient;
+    EmptyContextMenuClient m_contextMenuClient;
+    EmptyEditorClient m_editorClient;
+    EmptyDragClient m_dragClient;
+    EmptyInspectorClient m_inspectorClient;
+    EmptyBackForwardClient m_backForwardClient;
+    EmptyFrameLoaderClient m_frameLoaderClient;
+};
+
+} // namespace WebCore
+
+#endif // DummyPageHolder_h
diff --git a/Source/core/testing/InspectorFrontendClientLocal.cpp b/Source/core/testing/InspectorFrontendClientLocal.cpp
index 30c1f7e..1adc4ab 100644
--- a/Source/core/testing/InspectorFrontendClientLocal.cpp
+++ b/Source/core/testing/InspectorFrontendClientLocal.cpp
@@ -32,6 +32,7 @@
 #include "InspectorFrontendClientLocal.h"
 
 #include "bindings/v8/ScriptObject.h"
+#include "bindings/v8/ScriptState.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorFrontendHost.h"
 #include "core/page/Page.h"
@@ -68,7 +69,7 @@
 private:
     void schedule()
     {
-        class TaskImpl : public WebKit::WebThread::Task {
+        class TaskImpl : public blink::WebThread::Task {
         public:
             RefPtr<InspectorBackendMessageQueue> owner;
             virtual void run()
@@ -78,7 +79,7 @@
         };
         TaskImpl* taskImpl = new TaskImpl;
         taskImpl->owner = this;
-        WebKit::Platform::current()->currentThread()->postTask(taskImpl);
+        blink::Platform::current()->currentThread()->postTask(taskImpl);
     }
 
     void deliver()
diff --git a/Source/core/testing/InternalProfilers.cpp b/Source/core/testing/InternalProfilers.cpp
index 4560ee4..95d706f 100644
--- a/Source/core/testing/InternalProfilers.cpp
+++ b/Source/core/testing/InternalProfilers.cpp
@@ -40,22 +40,22 @@
 
 void InternalProfilers::startHeapProfiling(const String& prefix)
 {
-    WebKit::Platform::current()->startHeapProfiling(prefix);
+    blink::Platform::current()->startHeapProfiling(prefix);
 }
 
 void InternalProfilers::stopHeapProfiling()
 {
-    WebKit::Platform::current()->stopHeapProfiling();
+    blink::Platform::current()->stopHeapProfiling();
 }
 
 void InternalProfilers::dumpHeapProfiling(const String& reason)
 {
-    WebKit::Platform::current()->dumpHeapProfiling(reason);
+    blink::Platform::current()->dumpHeapProfiling(reason);
 }
 
 String InternalProfilers::getHeapProfile()
 {
-    String text = WebKit::Platform::current()->getHeapProfile();
+    String text = blink::Platform::current()->getHeapProfile();
     // Only return the first line which contains total numbers
     // because whole dump is too big and too noisy to process in JavaScript.
     return text.substring(0, text.find('\n'));
diff --git a/Source/core/testing/InternalSettings.cpp b/Source/core/testing/InternalSettings.cpp
index 742d778..04abe81 100644
--- a/Source/core/testing/InternalSettings.cpp
+++ b/Source/core/testing/InternalSettings.cpp
@@ -38,19 +38,19 @@
 
 #define InternalSettingsGuardForSettingsReturn(returnValue) \
     if (!settings()) { \
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError); \
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
         return returnValue; \
     }
 
 #define InternalSettingsGuardForSettings()  \
     if (!settings()) { \
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError); \
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
         return; \
     }
 
 #define InternalSettingsGuardForPage() \
     if (!page()) { \
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError); \
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
         return; \
     }
 
@@ -65,7 +65,7 @@
     , m_originalEditingBehavior(settings->editingBehaviorType())
     , m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())
     , m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())
-    , m_originalTextAutosizingFontScaleFactor(settings->textAutosizingFontScaleFactor())
+    , m_originalAccessibilityFontScaleFactor(settings->accessibilityFontScaleFactor())
     , m_originalMediaTypeOverride(settings->mediaTypeOverride())
     , m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())
     , m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
@@ -75,6 +75,7 @@
     , m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())
     , m_defaultVideoPosterURL(settings->defaultVideoPosterURL())
     , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->isCompositorDrivenAcceleratedScrollingEnabled())
+    , m_originalLayerSquashingEnabled(settings->isLayerSquashingEnabled())
     , m_originalPasswordGenerationDecorationEnabled(settings->passwordGenerationDecorationEnabled())
 {
 }
@@ -89,7 +90,7 @@
     settings->setEditingBehaviorType(m_originalEditingBehavior);
     settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);
     settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);
-    settings->setTextAutosizingFontScaleFactor(m_originalTextAutosizingFontScaleFactor);
+    settings->setAccessibilityFontScaleFactor(m_originalAccessibilityFontScaleFactor);
     settings->setMediaTypeOverride(m_originalMediaTypeOverride);
     settings->setMockScrollbarsEnabled(m_originalMockScrollbarsEnabled);
     RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(m_langAttributeAwareFormControlUIEnabled);
@@ -99,6 +100,7 @@
     settings->setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);
     settings->setDefaultVideoPosterURL(m_defaultVideoPosterURL);
     settings->setCompositorDrivenAcceleratedScrollingEnabled(m_originalCompositorDrivenAcceleratedScrollEnabled);
+    settings->setLayerSquashingEnabled(m_originalLayerSquashingEnabled);
     settings->setPasswordGenerationDecorationEnabled(m_originalPasswordGenerationDecorationEnabled);
     settings->resetFontFamilies();
 }
@@ -160,7 +162,7 @@
     return &page()->settings();
 }
 
-void InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setMockScrollbarsEnabled(enabled);
@@ -186,13 +188,13 @@
     RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
 }
 
-void InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setTouchEventEmulationEnabled(enabled);
 }
 
-void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setViewportEnabled(enabled);
@@ -200,12 +202,20 @@
 
 // FIXME: This is a temporary flag and should be removed once accelerated
 // overflow scroll is ready (crbug.com/254111).
-void InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setCompositorDrivenAcceleratedScrollingEnabled(enabled);
 }
 
+// FIXME: This is a temporary flag and should be removed once squashing is
+// ready (crbug.com/261605).
+void InternalSettings::setLayerSquashingEnabled(bool enabled, ExceptionState& exceptionState)
+{
+    InternalSettingsGuardForSettings();
+    settings()->setLayerSquashingEnabled(enabled);
+}
+
 typedef void (Settings::*SetFontFamilyFunction)(const AtomicString&, UScriptCode);
 static void setFontFamily(Settings* settings, const String& family, const String& script, SetFontFamilyFunction setter)
 {
@@ -214,70 +224,70 @@
         (settings->*setter)(family, code);
 }
 
-void InternalSettings::setStandardFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setStandardFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     setFontFamily(settings(), family, script, &Settings::setStandardFontFamily);
 }
 
-void InternalSettings::setSerifFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setSerifFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     setFontFamily(settings(), family, script, &Settings::setSerifFontFamily);
 }
 
-void InternalSettings::setSansSerifFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setSansSerifFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     setFontFamily(settings(), family, script, &Settings::setSansSerifFontFamily);
 }
 
-void InternalSettings::setFixedFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setFixedFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     setFontFamily(settings(), family, script, &Settings::setFixedFontFamily);
 }
 
-void InternalSettings::setCursiveFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setCursiveFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     setFontFamily(settings(), family, script, &Settings::setCursiveFontFamily);
 }
 
-void InternalSettings::setFantasyFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setFantasyFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     setFontFamily(settings(), family, script, &Settings::setFantasyFontFamily);
 }
 
-void InternalSettings::setPictographFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setPictographFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     setFontFamily(settings(), family, script, &Settings::setPictographFontFamily);
 }
 
-void InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setTextAutosizingEnabled(enabled);
 }
 
-void InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& es)
+void InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setTextAutosizingWindowSizeOverride(IntSize(width, height));
 }
 
-void InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& es)
+void InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setMediaTypeOverride(mediaType);
 }
 
-void InternalSettings::setTextAutosizingFontScaleFactor(float fontScaleFactor, ExceptionState& es)
+void InternalSettings::setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
-    settings()->setTextAutosizingFontScaleFactor(fontScaleFactor);
+    settings()->setAccessibilityFontScaleFactor(fontScaleFactor);
 }
 
 void InternalSettings::setCSSExclusionsEnabled(bool enabled)
@@ -285,7 +295,7 @@
     RuntimeEnabledFeatures::setCSSExclusionsEnabled(enabled);
 }
 
-void InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& es)
+void InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     if (equalIgnoringCase(editingBehavior, "win"))
@@ -297,7 +307,7 @@
     else if (equalIgnoringCase(editingBehavior, "android"))
         settings()->setEditingBehaviorType(EditingAndroidBehavior);
     else
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
 }
 
 void InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)
@@ -305,19 +315,19 @@
     RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(enabled);
 }
 
-void InternalSettings::setImagesEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setImagesEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setImagesEnabled(enabled);
 }
 
-void InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& es)
+void InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setDefaultVideoPosterURL(url);
 }
 
-void InternalSettings::setPasswordGenerationDecorationEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setPasswordGenerationDecorationEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setPasswordGenerationDecorationEnabled(enabled);
diff --git a/Source/core/testing/InternalSettings.h b/Source/core/testing/InternalSettings.h
index faf0c16..cc064ba 100644
--- a/Source/core/testing/InternalSettings.h
+++ b/Source/core/testing/InternalSettings.h
@@ -57,7 +57,7 @@
         EditingBehaviorType m_originalEditingBehavior;
         bool m_originalTextAutosizingEnabled;
         IntSize m_originalTextAutosizingWindowSizeOverride;
-        float m_originalTextAutosizingFontScaleFactor;
+        float m_originalAccessibilityFontScaleFactor;
         String m_originalMediaTypeOverride;
         bool m_originalMockScrollbarsEnabled;
         bool m_langAttributeAwareFormControlUIEnabled;
@@ -67,6 +67,7 @@
         bool m_shouldDisplayTextDescriptions;
         String m_defaultVideoPosterURL;
         bool m_originalCompositorDrivenAcceleratedScrollEnabled;
+        bool m_originalLayerSquashingEnabled;
         bool m_originalPasswordGenerationDecorationEnabled;
     };
 
@@ -95,7 +96,7 @@
     void setMockScrollbarsEnabled(bool, ExceptionState&);
     void setPasswordGenerationDecorationEnabled(bool, ExceptionState&);
     void setTextAutosizingEnabled(bool, ExceptionState&);
-    void setTextAutosizingFontScaleFactor(float fontScaleFactor, ExceptionState&);
+    void setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState&);
     void setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState&);
     void setTouchEventEmulationEnabled(bool, ExceptionState&);
     void setViewportEnabled(bool, ExceptionState&);
@@ -104,6 +105,10 @@
     // overflow scroll is ready (crbug.com/254111).
     void setCompositorDrivenAcceleratedScrollingEnabled(bool, ExceptionState&);
 
+    // FIXME: This is a temporary flag and should be removed once squashing is
+    // ready (crbug.com/261605).
+    void setLayerSquashingEnabled(bool, ExceptionState&);
+
     // FIXME: The following are RuntimeEnabledFeatures and likely
     // cannot be changed after process start. These setters should
     // be removed or moved onto internals.runtimeFlags:
diff --git a/Source/core/testing/InternalSettings.idl b/Source/core/testing/InternalSettings.idl
index 5ac9133..d4f5984 100644
--- a/Source/core/testing/InternalSettings.idl
+++ b/Source/core/testing/InternalSettings.idl
@@ -38,7 +38,7 @@
     [RaisesException] void setPictographFontFamily(DOMString family, DOMString script);
     [RaisesException] void setTextAutosizingEnabled(boolean enabled);
     [RaisesException] void setTextAutosizingWindowSizeOverride(long width, long height);
-    [RaisesException] void setTextAutosizingFontScaleFactor(float fontScaleFactor);
+    [RaisesException] void setAccessibilityFontScaleFactor(float fontScaleFactor);
     [RaisesException] void setMediaTypeOverride(DOMString mediaTypeOverride);
     [RaisesException] void setEditingBehavior(DOMString behavior);
     [RaisesException] void setPasswordGenerationDecorationEnabled(boolean enabled);
@@ -50,6 +50,10 @@
     // overflow scroll is ready (crbug.com/254111).
     [RaisesException] void setCompositorDrivenAcceleratedScrollingEnabled(boolean enabled);
 
+    // FIXME: This is a temporary flag and should be removed once squashing is
+    // ready (crbug.com/261605).
+    [RaisesException] void setLayerSquashingEnabled(boolean enabled);
+
     // FIXME: The following are RuntimeEnabledFeatures and likely
     // cannot be changed after process start.  These setters should
     // be removed or moved onto internals.runtimeFlags:
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index 8aa466e..9547c62 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -45,6 +45,7 @@
 #include "core/animation/DocumentTimeline.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverStats.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/ClientRectList.h"
@@ -75,6 +76,7 @@
 #include "core/frame/DOMPoint.h"
 #include "core/frame/Frame.h"
 #include "core/history/HistoryItem.h"
+#include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLMediaElement.h"
 #include "core/html/HTMLSelectElement.h"
@@ -120,8 +122,8 @@
 #include "platform/TraceEvent.h"
 #include "platform/geometry/IntRect.h"
 #include "platform/geometry/LayoutRect.h"
+#include "platform/weborigin/SchemeRegistry.h"
 #include "public/platform/WebLayer.h"
-#include "weborigin/SchemeRegistry.h"
 #include "wtf/dtoa.h"
 #include "wtf/text/StringBuffer.h"
 
@@ -202,6 +204,11 @@
         page->mainFrame()->spellChecker().toggleContinuousSpellChecking();
     if (page->mainFrame()->editor().isOverwriteModeEnabled())
         page->mainFrame()->editor().toggleOverwriteModeEnabled();
+
+    if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+        scrollingCoordinator->reset();
+
+    page->mainFrame()->view()->clear();
 }
 
 Internals::Internals(Document* document)
@@ -271,6 +278,19 @@
     return GCObservation::create(observedValue);
 }
 
+unsigned Internals::updateStyleAndReturnAffectedElementCount(ExceptionState& exceptionState) const
+{
+    Document* document = contextDocument();
+    if (!document) {
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    unsigned beforeCount = document->styleEngine()->resolverAccessCount();
+    document->updateStyleIfNeeded();
+    return document->styleEngine()->resolverAccessCount() - beforeCount;
+}
+
 bool Internals::isPreloaded(const String& url)
 {
     Document* document = contextDocument();
@@ -290,81 +310,110 @@
     CRASH();
 }
 
-PassRefPtr<Element> Internals::createContentElement(ExceptionState& es)
+void Internals::setStyleResolverStatsEnabled(bool enabled)
+{
+    Document* document = contextDocument();
+    if (enabled)
+        document->styleResolver()->enableStats(StyleResolver::ReportSlowStats);
+    else
+        document->styleResolver()->disableStats();
+}
+
+String Internals::styleResolverStatsReport(ExceptionState& exceptionState) const
+{
+    Document* document = contextDocument();
+    if (!document->styleResolver()->stats()) {
+        exceptionState.throwDOMException(InvalidStateError, "Style resolver stats not enabled");
+        return String();
+    }
+    return document->styleResolver()->stats()->report();
+}
+
+String Internals::styleResolverStatsTotalsReport(ExceptionState& exceptionState) const
+{
+    Document* document = contextDocument();
+    if (!document->styleResolver()->statsTotals()) {
+        exceptionState.throwDOMException(InvalidStateError, "Style resolver stats not enabled");
+        return String();
+    }
+    return document->styleResolver()->statsTotals()->report();
+}
+
+PassRefPtr<Element> Internals::createContentElement(ExceptionState& exceptionState)
 {
     Document* document = contextDocument();
     if (!document) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return HTMLContentElement::create(*document);
 }
 
-bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionState& es)
+bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionState& exceptionState)
 {
     if (!insertionPoint || !insertionPoint->isInsertionPoint()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return false;
     }
 
     return isHTMLContentElement(insertionPoint) && toHTMLContentElement(insertionPoint)->isSelectValid();
 }
 
-Node* Internals::treeScopeRootNode(Node* node, ExceptionState& es)
+Node* Internals::treeScopeRootNode(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return node->treeScope().rootNode();
 }
 
-Node* Internals::parentTreeScope(Node* node, ExceptionState& es)
+Node* Internals::parentTreeScope(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     const TreeScope* parentTreeScope = node->treeScope().parentTreeScope();
     return parentTreeScope ? parentTreeScope->rootNode() : 0;
 }
 
-bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionState& es)
+bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return host->shadow()->ensureSelectFeatureSet().hasSelectorForId(idValue);
 }
 
-bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionState& es)
+bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return host->shadow()->ensureSelectFeatureSet().hasSelectorForClass(className);
 }
 
-bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionState& es)
+bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return host->shadow()->ensureSelectFeatureSet().hasSelectorForAttribute(attributeName);
 }
 
-bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState& es)
+bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -388,10 +437,10 @@
     return false;
 }
 
-unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node* node2, ExceptionState& es) const
+unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node* node2, ExceptionState& exceptionState) const
 {
     if (!node1 || !node2) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     const TreeScope* treeScope1 = node1->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node1)) :
@@ -399,7 +448,7 @@
     const TreeScope* treeScope2 = node2->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node2)) :
         node2->isShadowRoot() ? static_cast<const TreeScope*>(toShadowRoot(node2)) : 0;
     if (!treeScope1 || !treeScope2) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     return treeScope1->comparePosition(*treeScope2);
@@ -414,10 +463,10 @@
     return contextFrame->animation().numberOfActiveAnimations(document);
 }
 
-void Internals::pauseAnimations(double pauseTime, ExceptionState& es)
+void Internals::pauseAnimations(double pauseTime, ExceptionState& exceptionState)
 {
     if (pauseTime < 0) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
@@ -429,37 +478,37 @@
     }
 }
 
-bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionState& es) const
+bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionState& exceptionState) const
 {
     if (root && root->isShadowRoot())
         return toShadowRoot(root)->containsShadowElements();
 
-    es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
     return 0;
 }
 
-bool Internals::hasContentElement(const Node* root, ExceptionState& es) const
+bool Internals::hasContentElement(const Node* root, ExceptionState& exceptionState) const
 {
     if (root && root->isShadowRoot())
         return toShadowRoot(root)->containsContentElements();
 
-    es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
     return 0;
 }
 
-size_t Internals::countElementShadow(const Node* root, ExceptionState& es) const
+size_t Internals::countElementShadow(const Node* root, ExceptionState& exceptionState) const
 {
     if (!root || !root->isShadowRoot()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     return toShadowRoot(root)->childShadowRootCount();
 }
 
-Node* Internals::nextSiblingByWalker(Node* node, ExceptionState& es)
+Node* Internals::nextSiblingByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -467,10 +516,10 @@
     return walker.get();
 }
 
-Node* Internals::firstChildByWalker(Node* node, ExceptionState& es)
+Node* Internals::firstChildByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -478,10 +527,10 @@
     return walker.get();
 }
 
-Node* Internals::lastChildByWalker(Node* node, ExceptionState& es)
+Node* Internals::lastChildByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -489,10 +538,10 @@
     return walker.get();
 }
 
-Node* Internals::nextNodeByWalker(Node* node, ExceptionState& es)
+Node* Internals::nextNodeByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -500,10 +549,10 @@
     return walker.get();
 }
 
-Node* Internals::previousNodeByWalker(Node* node, ExceptionState& es)
+Node* Internals::previousNodeByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -511,35 +560,35 @@
     return walker.get();
 }
 
-String Internals::elementRenderTreeAsText(Element* element, ExceptionState& es)
+String Internals::elementRenderTreeAsText(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     String representation = externalRepresentation(element);
     if (representation.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     return representation;
 }
 
-size_t Internals::numberOfScopedHTMLStyleChildren(const Node* scope, ExceptionState& es) const
+size_t Internals::numberOfScopedHTMLStyleChildren(const Node* scope, ExceptionState& exceptionState) const
 {
     if (scope && (scope->isElementNode() || scope->isShadowRoot()))
         return scope->numberOfScopedHTMLStyleChildren();
 
-    es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
     return 0;
 }
 
-PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionState& es) const
+PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionState& exceptionState) const
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -547,30 +596,30 @@
     return CSSComputedStyleDeclaration::create(node, allowVisitedStyle);
 }
 
-ShadowRoot* Internals::ensureShadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::ensureShadowRoot(Element* host, ExceptionState& exceptionState)
 {
     if (!host) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     if (ElementShadow* shadow = host->shadow())
         return shadow->youngestShadowRoot();
 
-    return host->createShadowRoot(es).get();
+    return host->createShadowRoot(exceptionState).get();
 }
 
-ShadowRoot* Internals::shadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::shadowRoot(Element* host, ExceptionState& exceptionState)
 {
     // FIXME: Internals::shadowRoot() in tests should be converted to youngestShadowRoot() or oldestShadowRoot().
     // https://bugs.webkit.org/show_bug.cgi?id=78465
-    return youngestShadowRoot(host, es);
+    return youngestShadowRoot(host, exceptionState);
 }
 
-ShadowRoot* Internals::youngestShadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::youngestShadowRoot(Element* host, ExceptionState& exceptionState)
 {
     if (!host) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -579,10 +628,10 @@
     return 0;
 }
 
-ShadowRoot* Internals::oldestShadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::oldestShadowRoot(Element* host, ExceptionState& exceptionState)
 {
     if (!host) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -591,30 +640,30 @@
     return 0;
 }
 
-ShadowRoot* Internals::youngerShadowRoot(Node* shadow, ExceptionState& es)
+ShadowRoot* Internals::youngerShadowRoot(Node* shadow, ExceptionState& exceptionState)
 {
     if (!shadow || !shadow->isShadowRoot()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return toShadowRoot(shadow)->youngerShadowRoot();
 }
 
-ShadowRoot* Internals::olderShadowRoot(Node* shadow, ExceptionState& es)
+ShadowRoot* Internals::olderShadowRoot(Node* shadow, ExceptionState& exceptionState)
 {
     if (!shadow || !shadow->isShadowRoot()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return toShadowRoot(shadow)->olderShadowRoot();
 }
 
-String Internals::shadowRootType(const Node* root, ExceptionState& es) const
+String Internals::shadowRootType(const Node* root, ExceptionState& exceptionState) const
 {
     if (!root || !root->isShadowRoot()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
@@ -629,24 +678,24 @@
     }
 }
 
-String Internals::shadowPseudoId(Element* element, ExceptionState& es)
+String Internals::shadowPseudoId(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     return element->shadowPseudoId().string();
 }
 
-void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionState& es)
+void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
-    return element->setPart(id);
+    return element->setPseudo(id);
 }
 
 String Internals::visiblePlaceholder(Element* element)
@@ -666,38 +715,27 @@
     toHTMLInputElement(element)->selectColorInColorChooser(Color(colorValue));
 }
 
-Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionState& es)
+Vector<String> Internals::formControlStateOfHistoryItem(ExceptionState& exceptionState)
 {
-    HistoryItem* mainItem = frame()->loader().history()->previousItem();
+    HistoryItem* mainItem = frame()->loader().currentItem();
     if (!mainItem) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return Vector<String>();
     }
-    String uniqueName = frame()->tree().uniqueName();
-    if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return Vector<String>();
-    }
-    return mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState();
+    return mainItem->documentState();
 }
 
-void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionState& es)
+void Internals::setFormControlStateOfHistoryItem(const Vector<String>& state, ExceptionState& exceptionState)
 {
-    HistoryItem* mainItem = frame()->loader().history()->previousItem();
+    HistoryItem* mainItem = frame()->loader().currentItem();
     if (!mainItem) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
-    String uniqueName = frame()->tree().uniqueName();
-    if (mainItem->target() == uniqueName)
-        mainItem->setDocumentState(state);
-    else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
-        subItem->setDocumentState(state);
-    else
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    mainItem->setDocumentState(state);
 }
 
-void Internals::setEnableMockPagePopup(bool enabled, ExceptionState& es)
+void Internals::setEnableMockPagePopup(bool enabled, ExceptionState& exceptionState)
 {
     Document* document = contextDocument();
     if (!document || !document->page())
@@ -717,32 +755,32 @@
     return s_pagePopupDriver ? s_pagePopupDriver->pagePopupController() : 0;
 }
 
-PassRefPtr<ClientRect> Internals::unscaledViewportRect(ExceptionState& es)
+PassRefPtr<ClientRect> Internals::unscaledViewportRect(ExceptionState& exceptionState)
 {
     Document* document = contextDocument();
     if (!document || !document->view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return ClientRect::create();
     }
 
     return ClientRect::create(document->view()->visibleContentRect());
 }
 
-PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionState& es)
+PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionState& exceptionState)
 {
     Document* document = contextDocument();
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return ClientRect::create();
     }
 
     return ClientRect::create(document->frame()->selection().absoluteCaretBounds());
 }
 
-PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionState& es)
+PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return ClientRect::create();
     }
 
@@ -753,10 +791,10 @@
     return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
 }
 
-PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionState& es)
+PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->page()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return ClientRectList::create();
     }
 
@@ -765,26 +803,26 @@
     return ClientRectList::create(highlight.quads);
 }
 
-unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionState& es)
+unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     DocumentMarker::MarkerTypes markerTypes = 0;
     if (!markerTypesFrom(markerType, markerTypes)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return 0;
     }
 
     return node->document().markers()->markersFor(node, markerTypes).size();
 }
 
-unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& es)
+unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -801,16 +839,16 @@
     return activeMarkerCount;
 }
 
-DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionState& es)
+DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     DocumentMarker::MarkerTypes markerTypes = 0;
     if (!markerTypesFrom(markerType, markerTypes)) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return 0;
     }
 
@@ -820,17 +858,17 @@
     return markers[index];
 }
 
-PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionState& es)
+PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
 {
-    DocumentMarker* marker = markerAt(node, markerType, index, es);
+    DocumentMarker* marker = markerAt(node, markerType, index, exceptionState);
     if (!marker)
         return 0;
     return Range::create(node->document(), node, marker->startOffset(), node, marker->endOffset());
 }
 
-String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionState& es)
+String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
 {
-    DocumentMarker* marker = markerAt(node, markerType, index, es);
+    DocumentMarker* marker = markerAt(node, markerType, index, exceptionState);
     if (!marker)
         return String();
     return marker->description();
@@ -842,20 +880,20 @@
     range->ownerDocument().markers()->addTextMatchMarker(range, isActive);
 }
 
-void Internals::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active, ExceptionState& es)
+void Internals::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
     node->document().markers()->setMarkersActive(node, startOffset, endOffset, active);
 }
 
-void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionState& es)
+void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
@@ -870,10 +908,10 @@
     frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
 }
 
-void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionState& es)
+void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionState& exceptionState)
 {
     if (!document || !document->page()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
     Page* page = document->page();
@@ -890,7 +928,7 @@
     else if (mode == "BottomToTopPaginated")
         pagination.mode = Pagination::BottomToTopPaginated;
     else {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
         return;
     }
 
@@ -899,12 +937,15 @@
     page->setPagination(pagination);
 }
 
-String Internals::viewportAsText(Document* document, float, int availableWidth, int availableHeight, ExceptionState& es)
+String Internals::viewportAsText(Document* document, float, int availableWidth, int availableHeight, ExceptionState& exceptionState)
 {
     if (!document || !document->page()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
+
+    document->updateLayoutIgnorePendingStylesheets();
+
     Page* page = document->page();
 
     // Update initial viewport size.
@@ -936,10 +977,10 @@
     return builder.toString();
 }
 
-bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionState& es)
+bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionState& exceptionState)
 {
     if (!textField) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return false;
     }
 
@@ -950,92 +991,92 @@
     if (textField->tagName() == "TEXTAREA")
         return toHTMLTextAreaElement(textField)->lastChangeWasUserEdit();
 
-    es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
     return false;
 }
 
-bool Internals::elementShouldAutoComplete(Element* element, ExceptionState& es)
+bool Internals::elementShouldAutoComplete(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return false;
     }
 
     if (element->hasTagName(inputTag))
         return toHTMLInputElement(element)->shouldAutocomplete();
 
-    es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
     return false;
 }
 
-String Internals::suggestedValue(Element* element, ExceptionState& es)
+String Internals::suggestedValue(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     if (!element->hasTagName(inputTag)) {
-        es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
         return String();
     }
 
     return toHTMLInputElement(element)->suggestedValue();
 }
 
-void Internals::setSuggestedValue(Element* element, const String& value, ExceptionState& es)
+void Internals::setSuggestedValue(Element* element, const String& value, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
     if (!element->hasTagName(inputTag)) {
-        es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
         return;
     }
 
     toHTMLInputElement(element)->setSuggestedValue(value);
 }
 
-void Internals::setEditingValue(Element* element, const String& value, ExceptionState& es)
+void Internals::setEditingValue(Element* element, const String& value, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
     if (!element->hasTagName(inputTag)) {
-        es.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
         return;
     }
 
     toHTMLInputElement(element)->setEditingValue(value);
 }
 
-void Internals::setAutofilled(Element* element, bool enabled, ExceptionState& es)
+void Internals::setAutofilled(Element* element, bool enabled, ExceptionState& exceptionState)
 {
     if (!element->isFormControlElement()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
     toHTMLFormControlElement(element)->setAutofilled(enabled);
 }
 
-void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionState& es)
+void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionState& exceptionState)
 {
     if (!element || !element->document().view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
     FrameView* frameView = element->document().view();
     frameView->scrollElementToRect(element, IntRect(x, y, w, h));
 }
 
-void Internals::paintControlTints(Document* document, ExceptionState& es)
+void Internals::paintControlTints(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
@@ -1043,10 +1084,10 @@
     frameView->paintControlTints();
 }
 
-PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionState& es)
+PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionState& exceptionState)
 {
     if (!scope) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1056,10 +1097,10 @@
     return PlainTextRange(rangeLocation, rangeLocation + rangeLength).createRange(*scope);
 }
 
-unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionState& es)
+unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionState& exceptionState)
 {
     if (!scope || !range) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1069,10 +1110,10 @@
     return PlainTextRange::create(*scope, *range).start();
 }
 
-unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionState& es)
+unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionState& exceptionState)
 {
     if (!scope || !range) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1082,20 +1123,20 @@
     return PlainTextRange::create(*scope, *range).length();
 }
 
-String Internals::rangeAsText(const Range* range, ExceptionState& es)
+String Internals::rangeAsText(const Range* range, ExceptionState& exceptionState)
 {
     if (!range) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     return range->text();
 }
 
-PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1114,10 +1155,10 @@
     return 0;
 }
 
-Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1132,10 +1173,10 @@
     return targetNode;
 }
 
-PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1154,10 +1195,10 @@
     return DOMPoint::create(x, y);
 }
 
-Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1172,10 +1213,10 @@
     return targetNode;
 }
 
-PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionState& es)
+PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1194,24 +1235,24 @@
 }
 
 
-int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionState& es)
+int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionState& exceptionState)
 {
     SpellCheckRequester* requester = spellCheckRequester(document);
 
     if (!requester) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return -1;
     }
 
     return requester->lastRequestSequence();
 }
 
-int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionState& es)
+int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionState& exceptionState)
 {
     SpellCheckRequester* requester = spellCheckRequester(document);
 
     if (!requester) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return -1;
     }
 
@@ -1228,20 +1269,20 @@
     WebCore::overrideUserPreferredLanguages(languages);
 }
 
-unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionState& es)
+unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionState& exceptionState)
 {
     if (!document) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return WheelController::from(document)->wheelEventHandlerCount();
 }
 
-unsigned Internals::touchEventHandlerCount(Document* document, ExceptionState& es)
+unsigned Internals::touchEventHandlerCount(Document* document, ExceptionState& exceptionState)
 {
     if (!document) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1257,7 +1298,7 @@
 
 static RenderLayer* findRenderLayerForGraphicsLayer(RenderLayer* searchRoot, GraphicsLayer* graphicsLayer, String* layerType)
 {
-    if (searchRoot->compositedLayerMapping() && graphicsLayer == searchRoot->compositedLayerMapping()->mainGraphicsLayer())
+    if (searchRoot->hasCompositedLayerMapping() && graphicsLayer == searchRoot->compositedLayerMapping()->mainGraphicsLayer())
         return searchRoot;
 
     GraphicsLayer* layerForScrolling = searchRoot->scrollableArea() ? searchRoot->scrollableArea()->layerForScrolling() : 0;
@@ -1298,7 +1339,7 @@
 // of rects returned by an SkRegion (which have been split apart for sorting
 // purposes). No attempt is made to do this efficiently (eg. by relying on the
 // sort criteria of SkRegion).
-static void mergeRects(WebKit::WebVector<WebKit::WebRect>& rects)
+static void mergeRects(blink::WebVector<blink::WebRect>& rects)
 {
     for (size_t i = 0; i < rects.size(); ++i) {
         if (rects[i].isEmpty())
@@ -1313,23 +1354,23 @@
                 if (rects[i].y == rects[j].y && rects[i].height == rects[j].height) {
                     if (rects[i].x + rects[i].width == rects[j].x) {
                         rects[i].width += rects[j].width;
-                        rects[j] = WebKit::WebRect();
+                        rects[j] = blink::WebRect();
                         updated = true;
                     } else if (rects[i].x == rects[j].x + rects[j].width) {
                         rects[i].x = rects[j].x;
                         rects[i].width += rects[j].width;
-                        rects[j] = WebKit::WebRect();
+                        rects[j] = blink::WebRect();
                         updated = true;
                     }
                 } else if (rects[i].x == rects[j].x && rects[i].width == rects[j].width) {
                     if (rects[i].y + rects[i].height == rects[j].y) {
                         rects[i].height += rects[j].height;
-                        rects[j] = WebKit::WebRect();
+                        rects[j] = blink::WebRect();
                         updated = true;
                     } else if (rects[i].y == rects[j].y + rects[j].height) {
                         rects[i].y = rects[j].y;
                         rects[i].height += rects[j].height;
-                        rects[j] = WebKit::WebRect();
+                        rects[j] = blink::WebRect();
                         updated = true;
                     }
                 }
@@ -1340,7 +1381,7 @@
 
 static void accumulateLayerRectList(RenderLayerCompositor* compositor, GraphicsLayer* graphicsLayer, LayerRectList* rects)
 {
-    WebKit::WebVector<WebKit::WebRect> layerRects = graphicsLayer->platformLayer()->touchEventHandlerRegion();
+    blink::WebVector<blink::WebRect> layerRects = graphicsLayer->platformLayer()->touchEventHandlerRegion();
     if (!layerRects.isEmpty()) {
         mergeRects(layerRects);
         String layerType;
@@ -1357,17 +1398,17 @@
         accumulateLayerRectList(compositor, graphicsLayer->children()[i], rects);
 }
 
-PassRefPtr<LayerRectList> Internals::touchEventTargetLayerRects(Document* document, ExceptionState& es)
+PassRefPtr<LayerRectList> Internals::touchEventTargetLayerRects(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->view() || !document->page() || document != contextDocument()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     // Do any pending layout and compositing update (which may call touchEventTargetRectsChange) to ensure this
     // really takes any previous changes into account.
-    forceCompositingUpdate(document, es);
-    if (es.hadException())
+    forceCompositingUpdate(document, exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
     if (RenderView* view = document->renderView()) {
@@ -1384,10 +1425,10 @@
 }
 
 PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
-    unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionState& es) const
+    unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame() || !document->frame()->view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1550,11 +1591,11 @@
     return result;
 }
 
-void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionState& es)
+void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionState& exceptionState)
 {
     Page* page = contextDocument()->frame()->page();
     if (!page) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
     page->inspectorController().setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize);
@@ -1583,30 +1624,30 @@
     return count;
 }
 
-bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionState& es)
+bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionState& exceptionState)
 {
     if (!document) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return false;
     }
 
     return document->isPageBoxVisible(pageNumber);
 }
 
-String Internals::layerTreeAsText(Document* document, ExceptionState& es) const
+String Internals::layerTreeAsText(Document* document, ExceptionState& exceptionState) const
 {
-    return layerTreeAsText(document, 0, es);
+    return layerTreeAsText(document, 0, exceptionState);
 }
 
-String Internals::elementLayerTreeAsText(Element* element, ExceptionState& es) const
+String Internals::elementLayerTreeAsText(Element* element, ExceptionState& exceptionState) const
 {
-    return elementLayerTreeAsText(element, 0, es);
+    return elementLayerTreeAsText(element, 0, exceptionState);
 }
 
-static PassRefPtr<NodeList> paintOrderList(Element* element, ExceptionState& es, RenderLayerStackingNode::PaintOrderListType type)
+static PassRefPtr<NodeList> paintOrderList(Element* element, ExceptionState& exceptionState, RenderLayerStackingNode::PaintOrderListType type)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1614,13 +1655,13 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1629,20 +1670,20 @@
     return StaticNodeList::adopt(nodes);
 }
 
-PassRefPtr<NodeList> Internals::paintOrderListBeforePromote(Element* element, ExceptionState& es)
+PassRefPtr<NodeList> Internals::paintOrderListBeforePromote(Element* element, ExceptionState& exceptionState)
 {
-    return paintOrderList(element, es, RenderLayerStackingNode::BeforePromote);
+    return paintOrderList(element, exceptionState, RenderLayerStackingNode::BeforePromote);
 }
 
-PassRefPtr<NodeList> Internals::paintOrderListAfterPromote(Element* element, ExceptionState& es)
+PassRefPtr<NodeList> Internals::paintOrderListAfterPromote(Element* element, ExceptionState& exceptionState)
 {
-    return paintOrderList(element, es, RenderLayerStackingNode::AfterPromote);
+    return paintOrderList(element, exceptionState, RenderLayerStackingNode::AfterPromote);
 }
 
-bool Internals::scrollsWithRespectTo(Element* element1, Element* element2, ExceptionState& es)
+bool Internals::scrollsWithRespectTo(Element* element1, Element* element2, ExceptionState& exceptionState)
 {
     if (!element1 || !element2) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1651,24 +1692,24 @@
     RenderObject* renderer1 = element1->renderer();
     RenderObject* renderer2 = element2->renderer();
     if (!renderer1 || !renderer2 || !renderer1->isBox() || !renderer2->isBox()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     RenderLayer* layer1 = toRenderBox(renderer1)->layer();
     RenderLayer* layer2 = toRenderBox(renderer2)->layer();
     if (!layer1 || !layer2) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return layer1->scrollsWithRespectTo(layer2);
 }
 
-bool Internals::isUnclippedDescendant(Element* element, ExceptionState& es)
+bool Internals::isUnclippedDescendant(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1676,23 +1717,23 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return layer->isUnclippedDescendant();
 }
 
-bool Internals::needsCompositedScrolling(Element* element, ExceptionState& es)
+bool Internals::needsCompositedScrolling(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1700,33 +1741,33 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return layer->needsCompositedScrolling();
 }
 
-String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionState& es) const
+String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     return document->frame()->layerTreeAsText(flags);
 }
 
-String Internals::elementLayerTreeAsText(Element* element, unsigned flags, ExceptionState& es) const
+String Internals::elementLayerTreeAsText(Element* element, unsigned flags, ExceptionState& exceptionState) const
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
@@ -1734,13 +1775,13 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer
-        || !layer->compositedLayerMapping()
+        || !layer->hasCompositedLayerMapping()
         || !layer->compositedLayerMapping()->mainGraphicsLayer()) {
         // Don't raise exception in these cases which may be normally used in tests.
         return String();
@@ -1749,59 +1790,59 @@
     return layer->compositedLayerMapping()->mainGraphicsLayer()->layerTreeAsText(flags);
 }
 
-static RenderLayer* getRenderLayerForElement(Element* element, ExceptionState& es)
+static RenderLayer* getRenderLayerForElement(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return layer;
 }
 
-void Internals::setNeedsCompositedScrolling(Element* element, unsigned needsCompositedScrolling, ExceptionState& es)
+void Internals::setNeedsCompositedScrolling(Element* element, unsigned needsCompositedScrolling, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
     element->document().updateLayout();
 
-    if (RenderLayer* layer = getRenderLayerForElement(element, es))
-        layer->setForceNeedsCompositedScrolling(static_cast<RenderLayer::ForceNeedsCompositedScrollingMode>(needsCompositedScrolling));
+    if (RenderLayer* layer = getRenderLayerForElement(element, exceptionState))
+        layer->scrollableArea()->setForceNeedsCompositedScrolling(static_cast<ForceNeedsCompositedScrollingMode>(needsCompositedScrolling));
 }
 
-String Internals::repaintRectsAsText(Document* document, ExceptionState& es) const
+String Internals::repaintRectsAsText(Document* document, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     return document->frame()->trackedRepaintRectsAsText();
 }
 
-PassRefPtr<ClientRectList> Internals::repaintRects(Element* element, ExceptionState& es) const
+PassRefPtr<ClientRectList> Internals::repaintRects(Element* element, ExceptionState& exceptionState) const
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
-    if (RenderLayer* layer = getRenderLayerForElement(element, es)) {
+    if (RenderLayer* layer = getRenderLayerForElement(element, exceptionState)) {
         if (layer->compositingState() == PaintsIntoOwnBacking) {
             OwnPtr<Vector<FloatRect> > rects = layer->collectTrackedRepaintRects();
             ASSERT(rects.get());
@@ -1813,19 +1854,19 @@
     }
 
     // It's an error to call this on an element that's not composited.
-    es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
     return 0;
 }
 
-String Internals::scrollingStateTreeAsText(Document* document, ExceptionState& es) const
+String Internals::scrollingStateTreeAsText(Document* document, ExceptionState& exceptionState) const
 {
     return String();
 }
 
-String Internals::mainThreadScrollingReasons(Document* document, ExceptionState& es) const
+String Internals::mainThreadScrollingReasons(Document* document, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
@@ -1842,10 +1883,10 @@
     return page->mainThreadScrollingReasonsAsText();
 }
 
-PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionState& es) const
+PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
@@ -1856,10 +1897,10 @@
     return page->nonFastScrollableRects(document->frame());
 }
 
-void Internals::garbageCollectDocumentResources(Document* document, ExceptionState& es) const
+void Internals::garbageCollectDocumentResources(Document* document, ExceptionState& exceptionState) const
 {
     if (!document) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
     ResourceFetcher* fetcher = document->fetcher();
@@ -1878,28 +1919,6 @@
     TextRun::setAllowsRoundingHacks(true);
 }
 
-void Internals::insertAuthorCSS(Document* document, const String& css) const
-{
-    if (!document)
-        return;
-
-    RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
-    parsedSheet->setIsUserStyleSheet(false);
-    parsedSheet->parseString(css);
-    document->styleEngine()->addAuthorSheet(parsedSheet);
-}
-
-void Internals::insertUserCSS(Document* document, const String& css) const
-{
-    if (!document)
-        return;
-
-    RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
-    parsedSheet->setIsUserStyleSheet(true);
-    parsedSheet->parseString(css);
-    document->styleEngine()->addUserSheet(parsedSheet);
-}
-
 String Internals::counterValue(Element* element)
 {
     if (!element)
@@ -1946,41 +1965,41 @@
     return PrintContext::numberOfPages(frame(), FloatSize(pageWidth, pageHeight));
 }
 
-String Internals::pageProperty(String propertyName, int pageNumber, ExceptionState& es) const
+String Internals::pageProperty(String propertyName, int pageNumber, ExceptionState& exceptionState) const
 {
     if (!frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
 }
 
-String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionState& es) const
+String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionState& exceptionState) const
 {
     if (!frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
     return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
 }
 
-void Internals::setDeviceScaleFactor(float scaleFactor, ExceptionState& es)
+void Internals::setDeviceScaleFactor(float scaleFactor, ExceptionState& exceptionState)
 {
     Document* document = contextDocument();
     if (!document || !document->page()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
     Page* page = document->page();
     page->setDeviceScaleFactor(scaleFactor);
 }
 
-void Internals::setIsCursorVisible(Document* document, bool isVisible, ExceptionState& es)
+void Internals::setIsCursorVisible(Document* document, bool isVisible, ExceptionState& exceptionState)
 {
     if (!document || !document->page()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
     document->page()->setIsCursorVisible(isVisible);
@@ -2036,14 +2055,14 @@
 
 Vector<String> Internals::getReferencedFilePaths() const
 {
-    frame()->loader().history()->saveDocumentAndScrollState();
-    return FormController::getReferencedFilePaths(frame()->loader().history()->currentItem()->documentState());
+    frame()->loader().saveDocumentAndScrollState();
+    return FormController::getReferencedFilePaths(frame()->loader().currentItem()->documentState());
 }
 
-void Internals::startTrackingRepaints(Document* document, ExceptionState& es)
+void Internals::startTrackingRepaints(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
@@ -2051,10 +2070,10 @@
     frameView->setTracksRepaints(true);
 }
 
-void Internals::stopTrackingRepaints(Document* document, ExceptionState& es)
+void Internals::stopTrackingRepaints(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
@@ -2062,20 +2081,41 @@
     frameView->setTracksRepaints(false);
 }
 
-PassRefPtr<ClientRectList> Internals::draggableRegions(Document* document, ExceptionState& es)
+void Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(ExceptionState& exceptionState)
 {
-    return annotatedRegions(document, true, es);
+    updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(0, exceptionState);
 }
 
-PassRefPtr<ClientRectList> Internals::nonDraggableRegions(Document* document, ExceptionState& es)
+void Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node* node, ExceptionState& exceptionState)
 {
-    return annotatedRegions(document, false, es);
+    Document* document;
+    if (!node) {
+        document = contextDocument();
+    } else if (node->isDocumentNode()) {
+        document = toDocument(node);
+    } else if (node->hasTagName(HTMLNames::iframeTag)) {
+        document = toHTMLIFrameElement(node)->contentDocument();
+    } else {
+        exceptionState.throwUninformativeAndGenericDOMException(TypeError);
+        return;
+    }
+    document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasksSynchronously);
 }
 
-PassRefPtr<ClientRectList> Internals::annotatedRegions(Document* document, bool draggable, ExceptionState& es)
+PassRefPtr<ClientRectList> Internals::draggableRegions(Document* document, ExceptionState& exceptionState)
+{
+    return annotatedRegions(document, true, exceptionState);
+}
+
+PassRefPtr<ClientRectList> Internals::nonDraggableRegions(Document* document, ExceptionState& exceptionState)
+{
+    return annotatedRegions(document, false, exceptionState);
+}
+
+PassRefPtr<ClientRectList> Internals::annotatedRegions(Document* document, bool draggable, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return ClientRectList::create();
     }
 
@@ -2144,10 +2184,10 @@
     return "UNKNOWN";
 }
 
-String Internals::getCurrentCursorInfo(Document* document, ExceptionState& es)
+String Internals::getCurrentCursorInfo(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
@@ -2195,39 +2235,39 @@
     frame()->loader().reload(endToEnd ? EndToEndReload : NormalReload);
 }
 
-PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionState& es)
+PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionState& exceptionState)
 {
     Document* document = contextDocument();
     if (!document || !document->frame()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return 0;
     }
 
     return ClientRect::create(document->frame()->selection().bounds());
 }
 
-String Internals::markerTextForListItem(Element* element, ExceptionState& es)
+String Internals::markerTextForListItem(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
     return WebCore::markerTextForListItem(element);
 }
 
-String Internals::getImageSourceURL(Element* element, ExceptionState& es)
+String Internals::getImageSourceURL(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
     return element->imageSourceURL();
 }
 
-String Internals::baseURL(Document* document, ExceptionState& es)
+String Internals::baseURL(Document* document, ExceptionState& exceptionState)
 {
     if (!document) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return String();
     }
 
@@ -2262,10 +2302,10 @@
     return true;
 }
 
-void Internals::forceCompositingUpdate(Document* document, ExceptionState& es)
+void Internals::forceCompositingUpdate(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->renderView()) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
 
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index d70b6fe..f83d22c 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -85,6 +85,10 @@
 
     void crash();
 
+    void setStyleResolverStatsEnabled(bool);
+    String styleResolverStatsReport(ExceptionState&) const;
+    String styleResolverStatsTotalsReport(ExceptionState&) const;
+
     size_t numberOfScopedHTMLStyleChildren(const Node*, ExceptionState&) const;
     PassRefPtr<CSSComputedStyleDeclaration> computedStyleIncludingVisitedInfo(Node*, ExceptionState&) const;
 
@@ -115,8 +119,6 @@
     bool hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState&);
     unsigned short compareTreeScopePosition(const Node*, const Node*, ExceptionState&) const;
 
-    bool attached(Node*, ExceptionState&);
-
     // FIXME: Rename these functions if walker is prefered.
     Node* nextSiblingByWalker(Node*, ExceptionState&);
     Node* firstChildByWalker(Node*, ExceptionState&);
@@ -124,10 +126,12 @@
     Node* nextNodeByWalker(Node*, ExceptionState&);
     Node* previousNodeByWalker(Node*, ExceptionState&);
 
+    unsigned updateStyleAndReturnAffectedElementCount(ExceptionState&) const;
+
     String visiblePlaceholder(Element*);
     void selectColorInColorChooser(Element*, const String& colorValue);
-    Vector<String> formControlStateOfPreviousHistoryItem(ExceptionState&);
-    void setFormControlStateOfPreviousHistoryItem(const Vector<String>&, ExceptionState&);
+    Vector<String> formControlStateOfHistoryItem(ExceptionState&);
+    void setFormControlStateOfHistoryItem(const Vector<String>&, ExceptionState&);
     void setEnableMockPagePopup(bool, ExceptionState&);
     PassRefPtr<PagePopupController> pagePopupController();
 
@@ -235,9 +239,6 @@
 
     void allowRoundingHacks() const;
 
-    void insertAuthorCSS(Document*, const String&) const;
-    void insertUserCSS(Document*, const String&) const;
-
     unsigned numberOfLiveNodes() const;
     unsigned numberOfLiveDocuments() const;
     Vector<String> consoleMessageArgumentCounts(Document*) const;
@@ -275,6 +276,8 @@
 
     void startTrackingRepaints(Document*, ExceptionState&);
     void stopTrackingRepaints(Document*, ExceptionState&);
+    void updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(ExceptionState&);
+    void updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node*, ExceptionState&);
 
     PassRefPtr<ClientRectList> draggableRegions(Document*, ExceptionState&);
     PassRefPtr<ClientRectList> nonDraggableRegions(Document*, ExceptionState&);
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index 7bffece..3d957e4 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -37,6 +37,10 @@
 
     void crash();
 
+    void setStyleResolverStatsEnabled(boolean enabled);
+    [RaisesException] DOMString styleResolverStatsReport();
+    [RaisesException] DOMString styleResolverStatsTotalsReport();
+
     [RaisesException] unsigned long numberOfScopedHTMLStyleChildren(Node scope);
     [RaisesException] CSSStyleDeclaration computedStyleIncludingVisitedInfo(Node node);
 
@@ -62,6 +66,7 @@
     [RaisesException] boolean hasSelectorForAttributeInShadow(Element host, DOMString attributeName);
     [RaisesException] boolean hasSelectorForPseudoClassInShadow(Element host, DOMString pseudoClass);
     [RaisesException] unsigned short compareTreeScopePosition(Node treeScope1, Node treeScope2);
+    [RaisesException] unsigned long updateStyleAndReturnAffectedElementCount();
 
     // CSS Animation and Transition testing.
     unsigned long numberOfActiveAnimations();
@@ -77,8 +82,8 @@
 
     void selectColorInColorChooser(Element element, DOMString colorValue);
 
-    [RaisesException] DOMString[] formControlStateOfPreviousHistoryItem();
-    [RaisesException] void setFormControlStateOfPreviousHistoryItem(sequence<DOMString> values);
+    [RaisesException] DOMString[] formControlStateOfHistoryItem();
+    [RaisesException] void setFormControlStateOfHistoryItem(sequence<DOMString> values);
     [RaisesException] void setEnableMockPagePopup(boolean enabled);
     readonly attribute PagePopupController pagePopupController;
 
@@ -196,9 +201,6 @@
 
     void allowRoundingHacks();
 
-    void insertAuthorCSS(Document document, DOMString css);
-    void insertUserCSS(Document document, DOMString css);
-
     unsigned long numberOfLiveNodes();
     unsigned long numberOfLiveDocuments();
     sequence<DOMString> consoleMessageArgumentCounts(Document document);
@@ -237,6 +239,11 @@
     [RaisesException] void startTrackingRepaints(Document document);
     [RaisesException] void stopTrackingRepaints(Document document);
 
+    // |node| should be Document, HTMLIFrameElement, or unspecified.
+    // If |node| is an HTMLIFrameElement, it assumes node.contentDocument is
+    // specified without security checks. Unspecified means this document.
+    [RaisesException] void updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(optional Node node);
+
     // Returns a list of draggable/non-draggable regions in the document.
     [RaisesException] ClientRectList draggableRegions(Document document);
     [RaisesException] ClientRectList nonDraggableRegions(Document document);
diff --git a/Source/core/testing/MockPagePopupDriver.cpp b/Source/core/testing/MockPagePopupDriver.cpp
index 4902ca0..ddf20ce 100644
--- a/Source/core/testing/MockPagePopupDriver.cpp
+++ b/Source/core/testing/MockPagePopupDriver.cpp
@@ -62,7 +62,7 @@
 {
     Document* document = mainFrame->document();
     ASSERT(document);
-    m_iframe = HTMLIFrameElement::create(HTMLNames::iframeTag, *document);
+    m_iframe = HTMLIFrameElement::create(*document);
     m_iframe->setIdAttribute("mock-page-popup");
     m_iframe->setInlineStyleProperty(CSSPropertyBorderWidth, 0.0, CSSPrimitiveValue::CSS_PX);
     m_iframe->setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
diff --git a/Source/core/platform/graphics/chromium/LayerPainterChromium.h b/Source/core/testing/UnitTestHelpers.cpp
similarity index 70%
copy from Source/core/platform/graphics/chromium/LayerPainterChromium.h
copy to Source/core/testing/UnitTestHelpers.cpp
index a526f83..8c5bc5b 100644
--- a/Source/core/platform/graphics/chromium/LayerPainterChromium.h
+++ b/Source/core/testing/UnitTestHelpers.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 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
@@ -17,29 +17,35 @@
  * 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
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  * (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/testing/UnitTestHelpers.h"
 
-#ifndef LayerPainterChromium_h
-#define LayerPainterChromium_h
+#include "public/platform/Platform.h"
+#include "public/platform/WebThread.h"
 
-class SkCanvas;
 
 namespace WebCore {
+namespace testing {
 
-class FloatRect;
-class IntRect;
-
-class LayerPainterChromium {
+class QuitTask : public blink::WebThread::Task {
 public:
-    virtual ~LayerPainterChromium() { }
-    virtual void paint(SkCanvas*, const IntRect& contentRect, FloatRect& opaque) = 0;
+    virtual void run()
+    {
+        blink::Platform::current()->currentThread()->exitRunLoop();
+    }
 };
 
-} // namespace WebCore
+void runPendingTasks()
+{
+    blink::Platform::current()->currentThread()->postTask(new QuitTask);
+    blink::Platform::current()->currentThread()->enterRunLoop();
+}
 
-#endif // LayerPainterChromium_h
+}
+}
diff --git a/Source/core/platform/graphics/chromium/LayerPainterChromium.h b/Source/core/testing/UnitTestHelpers.h
similarity index 77%
copy from Source/core/platform/graphics/chromium/LayerPainterChromium.h
copy to Source/core/testing/UnitTestHelpers.h
index a526f83..cb8fe58 100644
--- a/Source/core/platform/graphics/chromium/LayerPainterChromium.h
+++ b/Source/core/testing/UnitTestHelpers.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 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
@@ -23,23 +23,15 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-
-#ifndef LayerPainterChromium_h
-#define LayerPainterChromium_h
-
-class SkCanvas;
+#ifndef UnitTestHelpers_h
+#define UnitTestHelpers_h
 
 namespace WebCore {
+namespace testing {
 
-class FloatRect;
-class IntRect;
+void runPendingTasks();
 
-class LayerPainterChromium {
-public:
-    virtual ~LayerPainterChromium() { }
-    virtual void paint(SkCanvas*, const IntRect& contentRect, FloatRect& opaque) = 0;
-};
-
+} // namespace testing
 } // namespace WebCore
 
-#endif // LayerPainterChromium_h
+#endif
diff --git a/Source/core/timing/Performance.cpp b/Source/core/timing/Performance.cpp
index 7ccabeb..048aec5 100644
--- a/Source/core/timing/Performance.cpp
+++ b/Source/core/timing/Performance.cpp
@@ -41,7 +41,7 @@
 #include "core/timing/PerformanceResourceTiming.h"
 #include "core/timing/PerformanceTiming.h"
 #include "core/timing/PerformanceUserTiming.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/CurrentTime.h"
 
 #include "core/frame/Frame.h"
@@ -248,11 +248,11 @@
     return m_resourceTimingBuffer.size() >= m_resourceTimingBufferSize;
 }
 
-void Performance::mark(const String& markName, ExceptionState& es)
+void Performance::mark(const String& markName, ExceptionState& exceptionState)
 {
     if (!m_userTiming)
         m_userTiming = UserTiming::create(this);
-    m_userTiming->mark(markName, es);
+    m_userTiming->mark(markName, exceptionState);
 }
 
 void Performance::clearMarks(const String& markName)
@@ -262,11 +262,11 @@
     m_userTiming->clearMarks(markName);
 }
 
-void Performance::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& es)
+void Performance::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& exceptionState)
 {
     if (!m_userTiming)
         m_userTiming = UserTiming::create(this);
-    m_userTiming->measure(measureName, startMark, endMark, es);
+    m_userTiming->measure(measureName, startMark, endMark, exceptionState);
 }
 
 void Performance::clearMeasures(const String& measureName)
diff --git a/Source/core/timing/PerformanceEntry.idl b/Source/core/timing/PerformanceEntry.idl
index 6199cce..11918e9 100644
--- a/Source/core/timing/PerformanceEntry.idl
+++ b/Source/core/timing/PerformanceEntry.idl
@@ -30,7 +30,7 @@
 
 // See: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PerformanceTimeline/Overview.html
 [
-    CustomToV8
+    CustomWrap,
 ] interface PerformanceEntry {
     readonly attribute DOMString name;
     readonly attribute DOMString entryType;
diff --git a/Source/core/timing/PerformanceUserTiming.cpp b/Source/core/timing/PerformanceUserTiming.cpp
index d436560..d31f000 100644
--- a/Source/core/timing/PerformanceUserTiming.cpp
+++ b/Source/core/timing/PerformanceUserTiming.cpp
@@ -99,16 +99,16 @@
         performanceEntryMap.remove(name);
 }
 
-void UserTiming::mark(const String& markName, ExceptionState& es)
+void UserTiming::mark(const String& markName, ExceptionState& exceptionState)
 {
     if (restrictedKeyMap().contains(markName)) {
-        es.throwDOMException(SyntaxError, "'" + markName + "' is part of the PerformanceTiming interface, and cannot be used as a mark name.");
+        exceptionState.throwDOMException(SyntaxError, "'" + markName + "' is part of the PerformanceTiming interface, and cannot be used as a mark name.");
         return;
     }
 
     double startTime = m_performance->now();
     insertPerformanceEntry(m_marksMap, PerformanceMark::create(markName, startTime));
-    WebKit::Platform::current()->histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
+    blink::Platform::current()->histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
 }
 
 void UserTiming::clearMarks(const String& markName)
@@ -116,7 +116,7 @@
     clearPeformanceEntries(m_marksMap, markName);
 }
 
-double UserTiming::findExistingMarkStartTime(const String& markName, ExceptionState& es)
+double UserTiming::findExistingMarkStartTime(const String& markName, ExceptionState& exceptionState)
 {
     if (m_marksMap.contains(markName))
         return m_marksMap.get(markName).last()->startTime();
@@ -124,17 +124,17 @@
     if (restrictedKeyMap().contains(markName)) {
         double value = static_cast<double>((m_performance->timing()->*(restrictedKeyMap().get(markName)))());
         if (!value) {
-            es.throwDOMException(InvalidAccessError, "'" + markName + "' is empty: either the event hasn't happened yet, or it would provide cross-origin timing information.");
+            exceptionState.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, "The mark '" + markName + "' does not exist.");
+    exceptionState.throwDOMException(SyntaxError, "The mark '" + markName + "' does not exist.");
     return 0.0;
 }
 
-void UserTiming::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& es)
+void UserTiming::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& exceptionState)
 {
     double startTime = 0.0;
     double endTime = 0.0;
@@ -143,21 +143,21 @@
         endTime = m_performance->now();
     else if (endMark.isNull()) {
         endTime = m_performance->now();
-        startTime = findExistingMarkStartTime(startMark, es);
-        if (es.hadException())
+        startTime = findExistingMarkStartTime(startMark, exceptionState);
+        if (exceptionState.hadException())
             return;
     } else {
-        endTime = findExistingMarkStartTime(endMark, es);
-        if (es.hadException())
+        endTime = findExistingMarkStartTime(endMark, exceptionState);
+        if (exceptionState.hadException())
             return;
-        startTime = findExistingMarkStartTime(startMark, es);
-        if (es.hadException())
+        startTime = findExistingMarkStartTime(startMark, exceptionState);
+        if (exceptionState.hadException())
             return;
     }
 
     insertPerformanceEntry(m_measuresMap, PerformanceMeasure::create(measureName, startTime, endTime));
     if (endTime >= startTime)
-        WebKit::Platform::current()->histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
+        blink::Platform::current()->histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
 }
 
 void UserTiming::clearMeasures(const String& measureName)
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_derived.target.darwin-arm.mk
index a1b9920..ca9666b 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_derived.target.darwin-arm.mk
@@ -91,8 +91,12 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/blink/PickerCommon.cpp
@@ -111,6 +115,8 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
@@ -167,7 +173,9 @@
 	$(gyp_intermediate_dir)/EventTypeNames.cpp \
 	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
 	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
+	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
 	$(gyp_intermediate_dir)/HTMLNames.cpp \
+	$(gyp_intermediate_dir)/InputTypeNames.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
@@ -177,6 +185,7 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
+	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -267,6 +276,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
@@ -286,6 +296,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
@@ -296,7 +307,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
@@ -328,6 +338,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
@@ -387,17 +398,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -411,6 +421,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -445,9 +456,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -463,7 +475,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -542,17 +553,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -566,6 +576,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -601,9 +612,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -619,7 +631,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_derived.target.darwin-mips.mk
index e10f229..d44f7c7 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_derived.target.darwin-mips.mk
@@ -91,8 +91,12 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/blink/PickerCommon.cpp
@@ -111,6 +115,8 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
@@ -167,7 +173,9 @@
 	$(gyp_intermediate_dir)/EventTypeNames.cpp \
 	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
 	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
+	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
 	$(gyp_intermediate_dir)/HTMLNames.cpp \
+	$(gyp_intermediate_dir)/InputTypeNames.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
@@ -177,6 +185,7 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
+	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -267,6 +276,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
@@ -286,6 +296,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
@@ -296,7 +307,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
@@ -328,6 +338,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
@@ -386,17 +397,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -410,6 +420,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -444,9 +455,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -462,7 +474,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -540,17 +551,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -564,6 +574,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -599,9 +610,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -617,7 +629,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_derived.target.darwin-x86.mk
index c364a6c..54fbfa6 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_derived.target.darwin-x86.mk
@@ -91,8 +91,12 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/blink/PickerCommon.cpp
@@ -111,6 +115,8 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
@@ -167,7 +173,9 @@
 	$(gyp_intermediate_dir)/EventTypeNames.cpp \
 	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
 	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
+	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
 	$(gyp_intermediate_dir)/HTMLNames.cpp \
+	$(gyp_intermediate_dir)/InputTypeNames.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
@@ -177,6 +185,7 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
+	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -267,6 +276,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
@@ -286,6 +296,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
@@ -296,7 +307,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
@@ -328,6 +338,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
@@ -389,17 +400,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -413,6 +423,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -447,9 +458,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -465,7 +477,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -547,17 +558,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -571,6 +581,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -606,9 +617,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -624,7 +636,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
index a1b9920..ca9666b 100644
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ b/Source/core/webcore_derived.target.linux-arm.mk
@@ -91,8 +91,12 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/blink/PickerCommon.cpp
@@ -111,6 +115,8 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
@@ -167,7 +173,9 @@
 	$(gyp_intermediate_dir)/EventTypeNames.cpp \
 	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
 	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
+	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
 	$(gyp_intermediate_dir)/HTMLNames.cpp \
+	$(gyp_intermediate_dir)/InputTypeNames.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
@@ -177,6 +185,7 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
+	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -267,6 +276,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
@@ -286,6 +296,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
@@ -296,7 +307,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
@@ -328,6 +338,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
@@ -387,17 +398,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -411,6 +421,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -445,9 +456,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -463,7 +475,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -542,17 +553,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -566,6 +576,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -601,9 +612,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -619,7 +631,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
index e10f229..d44f7c7 100644
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ b/Source/core/webcore_derived.target.linux-mips.mk
@@ -91,8 +91,12 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/blink/PickerCommon.cpp
@@ -111,6 +115,8 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
@@ -167,7 +173,9 @@
 	$(gyp_intermediate_dir)/EventTypeNames.cpp \
 	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
 	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
+	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
 	$(gyp_intermediate_dir)/HTMLNames.cpp \
+	$(gyp_intermediate_dir)/InputTypeNames.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
@@ -177,6 +185,7 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
+	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -267,6 +276,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
@@ -286,6 +296,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
@@ -296,7 +307,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
@@ -328,6 +338,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
@@ -386,17 +397,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -410,6 +420,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -444,9 +455,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -462,7 +474,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -540,17 +551,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -564,6 +574,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -599,9 +610,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -617,7 +629,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
index c364a6c..54fbfa6 100644
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ b/Source/core/webcore_derived.target.linux-x86.mk
@@ -91,8 +91,12 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/blink/PickerCommon.cpp
@@ -111,6 +115,8 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
+$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
+	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
@@ -167,7 +173,9 @@
 	$(gyp_intermediate_dir)/EventTypeNames.cpp \
 	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
 	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
+	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
 	$(gyp_intermediate_dir)/HTMLNames.cpp \
+	$(gyp_intermediate_dir)/InputTypeNames.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
@@ -177,6 +185,7 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
+	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -267,6 +276,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
@@ -286,6 +296,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
@@ -296,7 +307,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
@@ -328,6 +338,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
@@ -389,17 +400,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -413,6 +423,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -447,9 +458,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -465,7 +477,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -547,17 +558,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -571,6 +581,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -606,9 +617,10 @@
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
 	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/angle_dx11/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
@@ -624,7 +636,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index b4fcde7..b24ecb8 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -76,6 +76,7 @@
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
+	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
 	third_party/WebKit/Source/core/dom/IconURL.cpp \
 	third_party/WebKit/Source/core/dom/IdTargetObserver.cpp \
@@ -83,7 +84,6 @@
 	third_party/WebKit/Source/core/dom/LiveNodeList.cpp \
 	third_party/WebKit/Source/core/dom/MessageChannel.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
-	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
 	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserver.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
@@ -147,6 +147,7 @@
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
+	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
@@ -248,17 +249,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -272,6 +272,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -297,9 +298,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -317,7 +319,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -398,17 +399,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -422,6 +422,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -448,9 +449,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -468,7 +470,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index ac1f3c3..a047a49 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -76,6 +76,7 @@
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
+	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
 	third_party/WebKit/Source/core/dom/IconURL.cpp \
 	third_party/WebKit/Source/core/dom/IdTargetObserver.cpp \
@@ -83,7 +84,6 @@
 	third_party/WebKit/Source/core/dom/LiveNodeList.cpp \
 	third_party/WebKit/Source/core/dom/MessageChannel.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
-	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
 	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserver.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
@@ -147,6 +147,7 @@
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
+	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
@@ -247,17 +248,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -271,6 +271,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -296,9 +297,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -316,7 +318,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -396,17 +397,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -420,6 +420,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -446,9 +447,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -466,7 +468,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 4c0b260..919d30e 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -76,6 +76,7 @@
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
+	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
 	third_party/WebKit/Source/core/dom/IconURL.cpp \
 	third_party/WebKit/Source/core/dom/IdTargetObserver.cpp \
@@ -83,7 +84,6 @@
 	third_party/WebKit/Source/core/dom/LiveNodeList.cpp \
 	third_party/WebKit/Source/core/dom/MessageChannel.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
-	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
 	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserver.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
@@ -147,6 +147,7 @@
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
+	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
@@ -250,17 +251,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -274,6 +274,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -299,9 +300,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -319,7 +321,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -403,17 +404,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -427,6 +427,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -453,9 +454,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -473,7 +475,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index b4fcde7..b24ecb8 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -76,6 +76,7 @@
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
+	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
 	third_party/WebKit/Source/core/dom/IconURL.cpp \
 	third_party/WebKit/Source/core/dom/IdTargetObserver.cpp \
@@ -83,7 +84,6 @@
 	third_party/WebKit/Source/core/dom/LiveNodeList.cpp \
 	third_party/WebKit/Source/core/dom/MessageChannel.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
-	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
 	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserver.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
@@ -147,6 +147,7 @@
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
+	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
@@ -248,17 +249,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -272,6 +272,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -297,9 +298,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -317,7 +319,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -398,17 +399,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -422,6 +422,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -448,9 +449,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -468,7 +470,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index ac1f3c3..a047a49 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -76,6 +76,7 @@
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
+	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
 	third_party/WebKit/Source/core/dom/IconURL.cpp \
 	third_party/WebKit/Source/core/dom/IdTargetObserver.cpp \
@@ -83,7 +84,6 @@
 	third_party/WebKit/Source/core/dom/LiveNodeList.cpp \
 	third_party/WebKit/Source/core/dom/MessageChannel.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
-	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
 	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserver.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
@@ -147,6 +147,7 @@
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
+	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
@@ -247,17 +248,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -271,6 +271,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -296,9 +297,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -316,7 +318,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -396,17 +397,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -420,6 +420,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -446,9 +447,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -466,7 +468,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 4c0b260..919d30e 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -76,6 +76,7 @@
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
+	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
 	third_party/WebKit/Source/core/dom/IconURL.cpp \
 	third_party/WebKit/Source/core/dom/IdTargetObserver.cpp \
@@ -83,7 +84,6 @@
 	third_party/WebKit/Source/core/dom/LiveNodeList.cpp \
 	third_party/WebKit/Source/core/dom/MessageChannel.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
-	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
 	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserver.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
@@ -147,6 +147,7 @@
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
+	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
@@ -250,17 +251,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -274,6 +274,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -299,9 +300,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -319,7 +321,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -403,17 +404,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -427,6 +427,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -453,9 +454,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -473,7 +475,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index 7e02531..bc94062 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -199,7 +199,6 @@
 	third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ImageInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/InputType.cpp \
-	third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/forms/InputTypeView.cpp \
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
@@ -277,11 +276,13 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegion.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegionList.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTElement.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTParser.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
+	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -331,17 +332,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -355,6 +355,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -380,9 +381,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -400,7 +402,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -481,17 +482,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -505,6 +505,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -531,9 +532,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -551,7 +553,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index 01c58bb..9c7ce34 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -199,7 +199,6 @@
 	third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ImageInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/InputType.cpp \
-	third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/forms/InputTypeView.cpp \
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
@@ -277,11 +276,13 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegion.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegionList.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTElement.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTParser.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
+	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -330,17 +331,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -354,6 +354,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -379,9 +380,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -399,7 +401,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -479,17 +480,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -503,6 +503,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -529,9 +530,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -549,7 +551,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index 9f33baf..e3b8db1 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -199,7 +199,6 @@
 	third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ImageInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/InputType.cpp \
-	third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/forms/InputTypeView.cpp \
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
@@ -277,11 +276,13 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegion.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegionList.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTElement.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTParser.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
+	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -333,17 +334,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -357,6 +357,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -382,9 +383,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -402,7 +404,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -486,17 +487,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -510,6 +510,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -536,9 +537,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -556,7 +558,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index 7e02531..bc94062 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -199,7 +199,6 @@
 	third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ImageInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/InputType.cpp \
-	third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/forms/InputTypeView.cpp \
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
@@ -277,11 +276,13 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegion.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegionList.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTElement.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTParser.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
+	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -331,17 +332,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -355,6 +355,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -380,9 +381,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -400,7 +402,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -481,17 +482,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -505,6 +505,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -531,9 +532,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -551,7 +553,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index 01c58bb..9c7ce34 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -199,7 +199,6 @@
 	third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ImageInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/InputType.cpp \
-	third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/forms/InputTypeView.cpp \
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
@@ -277,11 +276,13 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegion.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegionList.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTElement.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTParser.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
+	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -330,17 +331,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -354,6 +354,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -379,9 +380,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -399,7 +401,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -479,17 +480,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -503,6 +503,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -529,9 +530,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -549,7 +551,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index 9f33baf..e3b8db1 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -199,7 +199,6 @@
 	third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ImageInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/InputType.cpp \
-	third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/forms/InputTypeView.cpp \
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
@@ -277,11 +276,13 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegion.cpp \
-	third_party/WebKit/Source/core/html/track/VTTRegionList.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTElement.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTParser.cpp \
-	third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
+	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -333,17 +334,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -357,6 +357,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -382,9 +383,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -402,7 +404,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -486,17 +487,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -510,6 +510,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -536,9 +537,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -556,7 +558,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
index 40496ab..98d7e9f 100644
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ b/Source/core/webcore_platform.target.darwin-arm.mk
@@ -24,16 +24,10 @@
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
 LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/ContextMenu.cpp \
-	third_party/WebKit/Source/core/platform/ContextMenuItem.cpp \
 	third_party/WebKit/Source/core/platform/Cursor.cpp \
-	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
@@ -54,19 +48,24 @@
 	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerBridge.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerManager.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DeferredImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DiscardablePixelRef.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
+	third_party/WebKit/Source/core/platform/graphics/FontDataCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GaneshUtils.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Gradient.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
@@ -74,37 +73,21 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageDecodingStore.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageFrameGenerator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/LazyDecodingPixelRef.cpp \
+	third_party/WebKit/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
+	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/VDMXParser.cpp \
 	third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
-	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/android/FontCacheAndroid.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
@@ -132,12 +115,21 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
+	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/gpu/DrawingBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp \
-	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp \
+	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
@@ -148,7 +140,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp \
 	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/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
@@ -164,10 +155,7 @@
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
@@ -223,17 +211,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -247,6 +234,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -272,9 +260,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -292,7 +281,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -374,17 +362,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -398,6 +385,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -424,9 +412,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -444,7 +433,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
index 9ccfafe..14e0dbc 100644
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ b/Source/core/webcore_platform.target.darwin-mips.mk
@@ -24,16 +24,10 @@
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
 LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/ContextMenu.cpp \
-	third_party/WebKit/Source/core/platform/ContextMenuItem.cpp \
 	third_party/WebKit/Source/core/platform/Cursor.cpp \
-	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
@@ -54,19 +48,24 @@
 	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerBridge.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerManager.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DeferredImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DiscardablePixelRef.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
+	third_party/WebKit/Source/core/platform/graphics/FontDataCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GaneshUtils.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Gradient.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
@@ -74,37 +73,21 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageDecodingStore.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageFrameGenerator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/LazyDecodingPixelRef.cpp \
+	third_party/WebKit/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
+	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/VDMXParser.cpp \
 	third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
-	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/android/FontCacheAndroid.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
@@ -132,12 +115,21 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
+	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/gpu/DrawingBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp \
-	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp \
+	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
@@ -148,7 +140,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp \
 	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/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
@@ -164,10 +155,7 @@
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
@@ -222,17 +210,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -246,6 +233,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -271,9 +259,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -291,7 +280,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -372,17 +360,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -396,6 +383,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -422,9 +410,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -442,7 +431,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
index e5329b7..3c0eeba 100644
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ b/Source/core/webcore_platform.target.darwin-x86.mk
@@ -24,16 +24,10 @@
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
 LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/ContextMenu.cpp \
-	third_party/WebKit/Source/core/platform/ContextMenuItem.cpp \
 	third_party/WebKit/Source/core/platform/Cursor.cpp \
-	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
@@ -54,19 +48,24 @@
 	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerBridge.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerManager.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DeferredImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DiscardablePixelRef.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
+	third_party/WebKit/Source/core/platform/graphics/FontDataCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GaneshUtils.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Gradient.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
@@ -74,37 +73,21 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageDecodingStore.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageFrameGenerator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/LazyDecodingPixelRef.cpp \
+	third_party/WebKit/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
+	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/VDMXParser.cpp \
 	third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
-	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/android/FontCacheAndroid.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
@@ -132,12 +115,21 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
+	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/gpu/DrawingBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp \
-	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp \
+	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
@@ -148,7 +140,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp \
 	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/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
@@ -164,10 +155,7 @@
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
@@ -225,17 +213,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -249,6 +236,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -274,9 +262,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -294,7 +283,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -379,17 +367,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -403,6 +390,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -429,9 +417,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -449,7 +438,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
index 40496ab..98d7e9f 100644
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ b/Source/core/webcore_platform.target.linux-arm.mk
@@ -24,16 +24,10 @@
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
 LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/ContextMenu.cpp \
-	third_party/WebKit/Source/core/platform/ContextMenuItem.cpp \
 	third_party/WebKit/Source/core/platform/Cursor.cpp \
-	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
@@ -54,19 +48,24 @@
 	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerBridge.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerManager.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DeferredImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DiscardablePixelRef.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
+	third_party/WebKit/Source/core/platform/graphics/FontDataCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GaneshUtils.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Gradient.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
@@ -74,37 +73,21 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageDecodingStore.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageFrameGenerator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/LazyDecodingPixelRef.cpp \
+	third_party/WebKit/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
+	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/VDMXParser.cpp \
 	third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
-	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/android/FontCacheAndroid.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
@@ -132,12 +115,21 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
+	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/gpu/DrawingBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp \
-	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp \
+	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
@@ -148,7 +140,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp \
 	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/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
@@ -164,10 +155,7 @@
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
@@ -223,17 +211,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -247,6 +234,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -272,9 +260,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -292,7 +281,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -374,17 +362,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -398,6 +385,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -424,9 +412,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -444,7 +433,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
index 9ccfafe..14e0dbc 100644
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ b/Source/core/webcore_platform.target.linux-mips.mk
@@ -24,16 +24,10 @@
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
 LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/ContextMenu.cpp \
-	third_party/WebKit/Source/core/platform/ContextMenuItem.cpp \
 	third_party/WebKit/Source/core/platform/Cursor.cpp \
-	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
@@ -54,19 +48,24 @@
 	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerBridge.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerManager.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DeferredImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DiscardablePixelRef.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
+	third_party/WebKit/Source/core/platform/graphics/FontDataCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GaneshUtils.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Gradient.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
@@ -74,37 +73,21 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageDecodingStore.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageFrameGenerator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/LazyDecodingPixelRef.cpp \
+	third_party/WebKit/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
+	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/VDMXParser.cpp \
 	third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
-	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/android/FontCacheAndroid.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
@@ -132,12 +115,21 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
+	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/gpu/DrawingBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp \
-	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp \
+	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
@@ -148,7 +140,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp \
 	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/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
@@ -164,10 +155,7 @@
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
@@ -222,17 +210,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -246,6 +233,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -271,9 +259,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -291,7 +280,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -372,17 +360,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -396,6 +383,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -422,9 +410,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -442,7 +431,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
index e5329b7..3c0eeba 100644
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ b/Source/core/webcore_platform.target.linux-x86.mk
@@ -24,16 +24,10 @@
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
 LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/ContextMenu.cpp \
-	third_party/WebKit/Source/core/platform/ContextMenuItem.cpp \
 	third_party/WebKit/Source/core/platform/Cursor.cpp \
-	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
@@ -54,19 +48,24 @@
 	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerBridge.cpp \
+	third_party/WebKit/Source/core/platform/graphics/Canvas2DLayerManager.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DeferredImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/graphics/DiscardablePixelRef.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
+	third_party/WebKit/Source/core/platform/graphics/FontDataCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GaneshUtils.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Gradient.cpp \
+	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
@@ -74,37 +73,21 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageDecodingStore.cpp \
+	third_party/WebKit/Source/core/platform/graphics/ImageFrameGenerator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/LazyDecodingPixelRef.cpp \
+	third_party/WebKit/Source/core/platform/graphics/OpaqueRectTrackingContentLayerDelegate.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
+	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/VDMXParser.cpp \
 	third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp \
-	third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
-	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/android/FontCacheAndroid.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
@@ -132,12 +115,21 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp \
+	third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp \
+	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/gpu/DrawingBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp \
-	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp \
+	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
@@ -148,7 +140,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp \
 	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/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
@@ -164,10 +155,7 @@
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
@@ -225,17 +213,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -249,6 +236,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -274,9 +262,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -294,7 +283,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -379,17 +367,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -403,6 +390,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -429,9 +417,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -449,7 +438,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_prerequisites.target.darwin-arm.mk b/Source/core/webcore_prerequisites.target.darwin-arm.mk
index 971c1fe..7df6796 100644
--- a/Source/core/webcore_prerequisites.target.darwin-arm.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-arm.mk
@@ -23,7 +23,6 @@
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.darwin-mips.mk b/Source/core/webcore_prerequisites.target.darwin-mips.mk
index 971c1fe..7df6796 100644
--- a/Source/core/webcore_prerequisites.target.darwin-mips.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-mips.mk
@@ -23,7 +23,6 @@
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.darwin-x86.mk b/Source/core/webcore_prerequisites.target.darwin-x86.mk
index 971c1fe..7df6796 100644
--- a/Source/core/webcore_prerequisites.target.darwin-x86.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-x86.mk
@@ -23,7 +23,6 @@
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.linux-arm.mk b/Source/core/webcore_prerequisites.target.linux-arm.mk
index 971c1fe..7df6796 100644
--- a/Source/core/webcore_prerequisites.target.linux-arm.mk
+++ b/Source/core/webcore_prerequisites.target.linux-arm.mk
@@ -23,7 +23,6 @@
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.linux-mips.mk b/Source/core/webcore_prerequisites.target.linux-mips.mk
index 971c1fe..7df6796 100644
--- a/Source/core/webcore_prerequisites.target.linux-mips.mk
+++ b/Source/core/webcore_prerequisites.target.linux-mips.mk
@@ -23,7 +23,6 @@
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.linux-x86.mk b/Source/core/webcore_prerequisites.target.linux-x86.mk
index 971c1fe..7df6796 100644
--- a/Source/core/webcore_prerequisites.target.linux-x86.mk
+++ b/Source/core/webcore_prerequisites.target.linux-x86.mk
@@ -23,7 +23,6 @@
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index c61d66a..a708df0 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -53,6 +53,7 @@
 	third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableRow.cpp \
+	third_party/WebKit/Source/core/animation/ActiveAnimations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
@@ -75,6 +76,7 @@
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
+	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
@@ -82,6 +84,7 @@
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
@@ -108,9 +111,9 @@
 	third_party/WebKit/Source/core/css/CSSFontValue.cpp \
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
-	third_party/WebKit/Source/core/css/CSSHostRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageValue.cpp \
@@ -126,6 +129,7 @@
 	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
+	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
 	third_party/WebKit/Source/core/css/CSSParserValues.cpp \
 	third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp \
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
@@ -156,7 +160,6 @@
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
-	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
@@ -190,6 +193,8 @@
 	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/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/ViewportStyleAndroid.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 \
@@ -198,11 +203,13 @@
 	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
+	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
@@ -219,6 +226,7 @@
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp \
 	third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp \
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
@@ -257,6 +265,7 @@
 	third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp \
 	third_party/WebKit/Source/core/editing/TextIterator.cpp \
 	third_party/WebKit/Source/core/editing/TypingCommand.cpp \
+	third_party/WebKit/Source/core/editing/UndoStack.cpp \
 	third_party/WebKit/Source/core/editing/UnlinkCommand.cpp \
 	third_party/WebKit/Source/core/editing/VisiblePosition.cpp \
 	third_party/WebKit/Source/core/editing/VisibleSelection.cpp \
@@ -368,7 +377,6 @@
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
-	third_party/WebKit/Source/core/loader/IconController.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -386,10 +394,6 @@
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
-	third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp \
-	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/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -410,6 +414,7 @@
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
+	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
@@ -451,7 +456,7 @@
 	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/page/UseCounter.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
@@ -467,8 +472,6 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/PluginData.cpp \
-	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
 	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInput.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp \
@@ -485,7 +488,7 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -573,17 +576,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -597,6 +599,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -622,9 +625,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -642,7 +646,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -724,17 +727,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -748,6 +750,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -774,9 +777,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -794,7 +798,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index 1a65295..2b5b856 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -53,6 +53,7 @@
 	third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableRow.cpp \
+	third_party/WebKit/Source/core/animation/ActiveAnimations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
@@ -75,6 +76,7 @@
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
+	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
@@ -82,6 +84,7 @@
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
@@ -108,9 +111,9 @@
 	third_party/WebKit/Source/core/css/CSSFontValue.cpp \
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
-	third_party/WebKit/Source/core/css/CSSHostRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageValue.cpp \
@@ -126,6 +129,7 @@
 	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
+	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
 	third_party/WebKit/Source/core/css/CSSParserValues.cpp \
 	third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp \
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
@@ -156,7 +160,6 @@
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
-	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
@@ -190,6 +193,8 @@
 	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/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/ViewportStyleAndroid.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 \
@@ -198,11 +203,13 @@
 	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
+	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
@@ -219,6 +226,7 @@
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp \
 	third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp \
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
@@ -257,6 +265,7 @@
 	third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp \
 	third_party/WebKit/Source/core/editing/TextIterator.cpp \
 	third_party/WebKit/Source/core/editing/TypingCommand.cpp \
+	third_party/WebKit/Source/core/editing/UndoStack.cpp \
 	third_party/WebKit/Source/core/editing/UnlinkCommand.cpp \
 	third_party/WebKit/Source/core/editing/VisiblePosition.cpp \
 	third_party/WebKit/Source/core/editing/VisibleSelection.cpp \
@@ -368,7 +377,6 @@
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
-	third_party/WebKit/Source/core/loader/IconController.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -386,10 +394,6 @@
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
-	third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp \
-	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/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -410,6 +414,7 @@
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
+	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
@@ -451,7 +456,7 @@
 	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/page/UseCounter.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
@@ -467,8 +472,6 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/PluginData.cpp \
-	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
 	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInput.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp \
@@ -485,7 +488,7 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -572,17 +575,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -596,6 +598,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -621,9 +624,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -641,7 +645,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -722,17 +725,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -746,6 +748,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -772,9 +775,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -792,7 +796,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index a2c8038..c13b0ff 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -53,6 +53,7 @@
 	third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableRow.cpp \
+	third_party/WebKit/Source/core/animation/ActiveAnimations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
@@ -75,6 +76,7 @@
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
+	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
@@ -82,6 +84,7 @@
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
@@ -108,9 +111,9 @@
 	third_party/WebKit/Source/core/css/CSSFontValue.cpp \
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
-	third_party/WebKit/Source/core/css/CSSHostRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageValue.cpp \
@@ -126,6 +129,7 @@
 	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
+	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
 	third_party/WebKit/Source/core/css/CSSParserValues.cpp \
 	third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp \
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
@@ -156,7 +160,6 @@
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
-	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
@@ -190,6 +193,8 @@
 	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/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/ViewportStyleAndroid.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 \
@@ -198,11 +203,13 @@
 	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
+	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
@@ -219,6 +226,7 @@
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp \
 	third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp \
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
@@ -257,6 +265,7 @@
 	third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp \
 	third_party/WebKit/Source/core/editing/TextIterator.cpp \
 	third_party/WebKit/Source/core/editing/TypingCommand.cpp \
+	third_party/WebKit/Source/core/editing/UndoStack.cpp \
 	third_party/WebKit/Source/core/editing/UnlinkCommand.cpp \
 	third_party/WebKit/Source/core/editing/VisiblePosition.cpp \
 	third_party/WebKit/Source/core/editing/VisibleSelection.cpp \
@@ -368,7 +377,6 @@
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
-	third_party/WebKit/Source/core/loader/IconController.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -386,10 +394,6 @@
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
-	third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp \
-	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/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -410,6 +414,7 @@
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
+	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
@@ -451,7 +456,7 @@
 	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/page/UseCounter.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
@@ -467,8 +472,6 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/PluginData.cpp \
-	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
 	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInput.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp \
@@ -485,7 +488,7 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -575,17 +578,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -599,6 +601,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -624,9 +627,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -644,7 +648,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -729,17 +732,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -753,6 +755,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -779,9 +782,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -799,7 +803,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index c61d66a..a708df0 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -53,6 +53,7 @@
 	third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableRow.cpp \
+	third_party/WebKit/Source/core/animation/ActiveAnimations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
@@ -75,6 +76,7 @@
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
+	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
@@ -82,6 +84,7 @@
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
@@ -108,9 +111,9 @@
 	third_party/WebKit/Source/core/css/CSSFontValue.cpp \
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
-	third_party/WebKit/Source/core/css/CSSHostRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageValue.cpp \
@@ -126,6 +129,7 @@
 	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
+	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
 	third_party/WebKit/Source/core/css/CSSParserValues.cpp \
 	third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp \
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
@@ -156,7 +160,6 @@
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
-	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
@@ -190,6 +193,8 @@
 	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/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/ViewportStyleAndroid.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 \
@@ -198,11 +203,13 @@
 	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
+	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
@@ -219,6 +226,7 @@
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp \
 	third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp \
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
@@ -257,6 +265,7 @@
 	third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp \
 	third_party/WebKit/Source/core/editing/TextIterator.cpp \
 	third_party/WebKit/Source/core/editing/TypingCommand.cpp \
+	third_party/WebKit/Source/core/editing/UndoStack.cpp \
 	third_party/WebKit/Source/core/editing/UnlinkCommand.cpp \
 	third_party/WebKit/Source/core/editing/VisiblePosition.cpp \
 	third_party/WebKit/Source/core/editing/VisibleSelection.cpp \
@@ -368,7 +377,6 @@
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
-	third_party/WebKit/Source/core/loader/IconController.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -386,10 +394,6 @@
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
-	third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp \
-	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/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -410,6 +414,7 @@
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
+	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
@@ -451,7 +456,7 @@
 	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/page/UseCounter.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
@@ -467,8 +472,6 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/PluginData.cpp \
-	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
 	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInput.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp \
@@ -485,7 +488,7 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -573,17 +576,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -597,6 +599,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -622,9 +625,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -642,7 +646,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -724,17 +727,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -748,6 +750,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -774,9 +777,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -794,7 +798,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index 1a65295..2b5b856 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -53,6 +53,7 @@
 	third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableRow.cpp \
+	third_party/WebKit/Source/core/animation/ActiveAnimations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
@@ -75,6 +76,7 @@
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
+	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
@@ -82,6 +84,7 @@
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
@@ -108,9 +111,9 @@
 	third_party/WebKit/Source/core/css/CSSFontValue.cpp \
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
-	third_party/WebKit/Source/core/css/CSSHostRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageValue.cpp \
@@ -126,6 +129,7 @@
 	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
+	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
 	third_party/WebKit/Source/core/css/CSSParserValues.cpp \
 	third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp \
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
@@ -156,7 +160,6 @@
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
-	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
@@ -190,6 +193,8 @@
 	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/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/ViewportStyleAndroid.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 \
@@ -198,11 +203,13 @@
 	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
+	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
@@ -219,6 +226,7 @@
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp \
 	third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp \
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
@@ -257,6 +265,7 @@
 	third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp \
 	third_party/WebKit/Source/core/editing/TextIterator.cpp \
 	third_party/WebKit/Source/core/editing/TypingCommand.cpp \
+	third_party/WebKit/Source/core/editing/UndoStack.cpp \
 	third_party/WebKit/Source/core/editing/UnlinkCommand.cpp \
 	third_party/WebKit/Source/core/editing/VisiblePosition.cpp \
 	third_party/WebKit/Source/core/editing/VisibleSelection.cpp \
@@ -368,7 +377,6 @@
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
-	third_party/WebKit/Source/core/loader/IconController.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -386,10 +394,6 @@
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
-	third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp \
-	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/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -410,6 +414,7 @@
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
+	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
@@ -451,7 +456,7 @@
 	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/page/UseCounter.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
@@ -467,8 +472,6 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/PluginData.cpp \
-	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
 	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInput.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp \
@@ -485,7 +488,7 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -572,17 +575,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -596,6 +598,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -621,9 +624,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -641,7 +645,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -722,17 +725,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -746,6 +748,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -772,9 +775,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -792,7 +796,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index a2c8038..c13b0ff 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -53,6 +53,7 @@
 	third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AXTableRow.cpp \
+	third_party/WebKit/Source/core/animation/ActiveAnimations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
@@ -75,6 +76,7 @@
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
+	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
@@ -82,6 +84,7 @@
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
@@ -108,9 +111,9 @@
 	third_party/WebKit/Source/core/css/CSSFontValue.cpp \
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
-	third_party/WebKit/Source/core/css/CSSHostRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageValue.cpp \
@@ -126,6 +129,7 @@
 	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
+	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
 	third_party/WebKit/Source/core/css/CSSParserValues.cpp \
 	third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp \
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
@@ -156,7 +160,6 @@
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
-	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
@@ -190,6 +193,8 @@
 	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/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/ViewportStyleAndroid.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 \
@@ -198,11 +203,13 @@
 	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
+	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
@@ -219,6 +226,7 @@
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp \
 	third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp \
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
@@ -257,6 +265,7 @@
 	third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp \
 	third_party/WebKit/Source/core/editing/TextIterator.cpp \
 	third_party/WebKit/Source/core/editing/TypingCommand.cpp \
+	third_party/WebKit/Source/core/editing/UndoStack.cpp \
 	third_party/WebKit/Source/core/editing/UnlinkCommand.cpp \
 	third_party/WebKit/Source/core/editing/VisiblePosition.cpp \
 	third_party/WebKit/Source/core/editing/VisibleSelection.cpp \
@@ -368,7 +377,6 @@
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
-	third_party/WebKit/Source/core/loader/IconController.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -386,10 +394,6 @@
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
-	third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp \
-	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/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -410,6 +414,7 @@
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
+	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
@@ -451,7 +456,7 @@
 	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/page/UseCounter.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
@@ -467,8 +472,6 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/PluginData.cpp \
-	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
 	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInput.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp \
@@ -485,7 +488,7 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -575,17 +578,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -599,6 +601,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -624,9 +627,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -644,7 +648,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -729,17 +732,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -753,6 +755,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -779,9 +782,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -799,7 +803,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index 6481f1d..80ab6f8 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
@@ -103,6 +104,7 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
+	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
 	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
@@ -133,7 +135,6 @@
 	third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTheme.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp \
@@ -141,11 +142,11 @@
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp \
+	third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderVideo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -238,17 +239,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -262,6 +262,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -287,9 +288,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -307,7 +309,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -388,17 +389,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -412,6 +412,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -438,9 +439,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -458,7 +460,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index f8d1cee..ad1272f 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
@@ -103,6 +104,7 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
+	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
 	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
@@ -133,7 +135,6 @@
 	third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTheme.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp \
@@ -141,11 +142,11 @@
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp \
+	third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderVideo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -237,17 +238,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -261,6 +261,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -286,9 +287,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -306,7 +308,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -386,17 +387,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -410,6 +410,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -436,9 +437,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -456,7 +458,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 0450ce0..a899ecb 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
@@ -103,6 +104,7 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
+	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
 	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
@@ -133,7 +135,6 @@
 	third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTheme.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp \
@@ -141,11 +142,11 @@
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp \
+	third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderVideo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -241,17 +242,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -265,6 +265,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -290,9 +291,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -310,7 +312,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -395,17 +396,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -419,6 +419,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -445,9 +446,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -465,7 +467,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index 6481f1d..80ab6f8 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
@@ -103,6 +104,7 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
+	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
 	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
@@ -133,7 +135,6 @@
 	third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTheme.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp \
@@ -141,11 +142,11 @@
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp \
+	third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderVideo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -238,17 +239,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -262,6 +262,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -287,9 +288,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -307,7 +309,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -388,17 +389,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -412,6 +412,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -438,9 +439,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -458,7 +460,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index f8d1cee..ad1272f 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
@@ -103,6 +104,7 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
+	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
 	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
@@ -133,7 +135,6 @@
 	third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTheme.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp \
@@ -141,11 +142,11 @@
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp \
+	third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderVideo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -237,17 +238,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -261,6 +261,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -286,9 +287,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -306,7 +308,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -386,17 +387,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -410,6 +410,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -436,9 +437,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -456,7 +458,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 0450ce0..a899ecb 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
@@ -103,6 +104,7 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
+	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
 	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
@@ -133,7 +135,6 @@
 	third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTheme.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp \
@@ -141,11 +142,11 @@
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp \
 	third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp \
 	third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp \
+	third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp \
 	third_party/WebKit/Source/core/rendering/RenderVideo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -241,17 +242,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -265,6 +265,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -290,9 +291,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -310,7 +312,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -395,17 +396,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -419,6 +419,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -445,9 +446,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -465,7 +467,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 9e3e4da..875dcf1 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -163,6 +163,7 @@
 	third_party/WebKit/Source/core/svg/SVGGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
@@ -174,7 +175,6 @@
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGLocatable.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
@@ -222,7 +222,6 @@
 	third_party/WebKit/Source/core/svg/SVGTransform.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformList.cpp \
-	third_party/WebKit/Source/core/svg/SVGTransformable.cpp \
 	third_party/WebKit/Source/core/svg/SVGURIReference.cpp \
 	third_party/WebKit/Source/core/svg/SVGUnknownElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGUseElement.cpp \
@@ -292,17 +291,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -316,6 +314,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -341,9 +340,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -361,7 +361,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -442,17 +441,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -466,6 +464,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -492,9 +491,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -512,7 +512,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index 5ed2ad4..283333c 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -163,6 +163,7 @@
 	third_party/WebKit/Source/core/svg/SVGGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
@@ -174,7 +175,6 @@
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGLocatable.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
@@ -222,7 +222,6 @@
 	third_party/WebKit/Source/core/svg/SVGTransform.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformList.cpp \
-	third_party/WebKit/Source/core/svg/SVGTransformable.cpp \
 	third_party/WebKit/Source/core/svg/SVGURIReference.cpp \
 	third_party/WebKit/Source/core/svg/SVGUnknownElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGUseElement.cpp \
@@ -291,17 +290,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -315,6 +313,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -340,9 +339,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -360,7 +360,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -440,17 +439,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -464,6 +462,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -490,9 +489,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -510,7 +510,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 542854a..4767811 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -163,6 +163,7 @@
 	third_party/WebKit/Source/core/svg/SVGGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
@@ -174,7 +175,6 @@
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGLocatable.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
@@ -222,7 +222,6 @@
 	third_party/WebKit/Source/core/svg/SVGTransform.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformList.cpp \
-	third_party/WebKit/Source/core/svg/SVGTransformable.cpp \
 	third_party/WebKit/Source/core/svg/SVGURIReference.cpp \
 	third_party/WebKit/Source/core/svg/SVGUnknownElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGUseElement.cpp \
@@ -294,17 +293,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -318,6 +316,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -343,9 +342,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -363,7 +363,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -447,17 +446,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -471,6 +469,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -497,9 +496,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -517,7 +517,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 9e3e4da..875dcf1 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -163,6 +163,7 @@
 	third_party/WebKit/Source/core/svg/SVGGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
@@ -174,7 +175,6 @@
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGLocatable.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
@@ -222,7 +222,6 @@
 	third_party/WebKit/Source/core/svg/SVGTransform.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformList.cpp \
-	third_party/WebKit/Source/core/svg/SVGTransformable.cpp \
 	third_party/WebKit/Source/core/svg/SVGURIReference.cpp \
 	third_party/WebKit/Source/core/svg/SVGUnknownElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGUseElement.cpp \
@@ -292,17 +291,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -316,6 +314,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -341,9 +340,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -361,7 +361,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -442,17 +441,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -466,6 +464,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -492,9 +491,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -512,7 +512,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index 5ed2ad4..283333c 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -163,6 +163,7 @@
 	third_party/WebKit/Source/core/svg/SVGGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
@@ -174,7 +175,6 @@
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGLocatable.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
@@ -222,7 +222,6 @@
 	third_party/WebKit/Source/core/svg/SVGTransform.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformList.cpp \
-	third_party/WebKit/Source/core/svg/SVGTransformable.cpp \
 	third_party/WebKit/Source/core/svg/SVGURIReference.cpp \
 	third_party/WebKit/Source/core/svg/SVGUnknownElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGUseElement.cpp \
@@ -291,17 +290,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -315,6 +313,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -340,9 +339,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -360,7 +360,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -440,17 +439,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -464,6 +462,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -490,9 +489,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -510,7 +510,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 542854a..4767811 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -163,6 +163,7 @@
 	third_party/WebKit/Source/core/svg/SVGGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
@@ -174,7 +175,6 @@
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGLocatable.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
@@ -222,7 +222,6 @@
 	third_party/WebKit/Source/core/svg/SVGTransform.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp \
 	third_party/WebKit/Source/core/svg/SVGTransformList.cpp \
-	third_party/WebKit/Source/core/svg/SVGTransformable.cpp \
 	third_party/WebKit/Source/core/svg/SVGURIReference.cpp \
 	third_party/WebKit/Source/core/svg/SVGUnknownElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGUseElement.cpp \
@@ -294,17 +293,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -318,6 +316,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -343,9 +342,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -363,7 +363,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
@@ -447,17 +446,16 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
+	'-DENABLE_MANAGED_USERS=1' \
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=0' \
+	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
@@ -471,6 +469,7 @@
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
 	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
+	'-DGR_GL_IGNORE_ES3_MSAA=0' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
@@ -497,9 +496,10 @@
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(LOCAL_PATH)/third_party/WebKit/Source \
 	$(gyp_shared_intermediate_dir)/blink \
@@ -517,7 +517,6 @@
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
 	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/skia/ext \
 	$(LOCAL_PATH)/third_party/iccjpeg \
 	$(LOCAL_PATH)/third_party/libpng \
diff --git a/Source/core/workers/AbstractWorker.cpp b/Source/core/workers/AbstractWorker.cpp
index 6d02bb9..301cdf9 100644
--- a/Source/core/workers/AbstractWorker.cpp
+++ b/Source/core/workers/AbstractWorker.cpp
@@ -36,7 +36,7 @@
 #include "core/dom/ExecutionContext.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/frame/ContentSecurityPolicy.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
@@ -49,33 +49,23 @@
 {
 }
 
-void AbstractWorker::contextDestroyed()
+KURL AbstractWorker::resolveURL(const String& url, ExceptionState& exceptionState)
 {
-    ActiveDOMObject::contextDestroyed();
-}
-
-KURL AbstractWorker::resolveURL(const String& url, ExceptionState& es)
-{
-    if (url.isEmpty()) {
-        es.throwDOMException(SyntaxError, "Failed to create a worker: an empty URL was provided.");
-        return KURL();
-    }
-
     // FIXME: This should use the dynamic global scope (bug #27887)
     KURL scriptURL = executionContext()->completeURL(url);
     if (!scriptURL.isValid()) {
-        es.throwDOMException(SyntaxError, "Failed to create a worker: '" + url + "' is not a valid URL.");
+        exceptionState.throwDOMException(SyntaxError, "Failed to create a worker: '" + url + "' is not a valid URL.");
         return KURL();
     }
 
     // We can safely expose the URL in the following exceptions, as these checks happen synchronously before redirection. JavaScript receives no new information.
     if (!executionContext()->securityOrigin()->canRequest(scriptURL)) {
-        es.throwSecurityError("Failed to create a worker: script at '" + scriptURL.elidedString() + "' cannot be accessed from origin '" + executionContext()->securityOrigin()->toString() + "'.");
+        exceptionState.throwSecurityError("Failed to create a worker: script at '" + scriptURL.elidedString() + "' cannot be accessed from origin '" + executionContext()->securityOrigin()->toString() + "'.");
         return KURL();
     }
 
     if (executionContext()->contentSecurityPolicy() && !executionContext()->contentSecurityPolicy()->allowScriptFromSource(scriptURL)) {
-        es.throwSecurityError("Failed to create a worker: access to the script at '" + scriptURL.elidedString() + "' is denied by the document's Content Security Policy.");
+        exceptionState.throwSecurityError("Failed to create a worker: access to the script at '" + scriptURL.elidedString() + "' is denied by the document's Content Security Policy.");
         return KURL();
     }
 
diff --git a/Source/core/workers/AbstractWorker.h b/Source/core/workers/AbstractWorker.h
index 0fb181d..775f2e6 100644
--- a/Source/core/workers/AbstractWorker.h
+++ b/Source/core/workers/AbstractWorker.h
@@ -55,7 +55,6 @@
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
 
-    virtual void contextDestroyed() OVERRIDE;
     AbstractWorker(ExecutionContext*);
     virtual ~AbstractWorker();
 
diff --git a/Source/core/workers/DedicatedWorkerGlobalScope.cpp b/Source/core/workers/DedicatedWorkerGlobalScope.cpp
index ed4fbb1..0605c01 100644
--- a/Source/core/workers/DedicatedWorkerGlobalScope.cpp
+++ b/Source/core/workers/DedicatedWorkerGlobalScope.cpp
@@ -32,6 +32,7 @@
 #include "core/workers/DedicatedWorkerGlobalScope.h"
 
 #include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/SerializedScriptValue.h"
 #include "core/frame/DOMWindow.h"
 #include "core/workers/DedicatedWorkerThread.h"
 #include "core/workers/WorkerClients.h"
@@ -62,18 +63,18 @@
     return EventTargetNames::DedicatedWorkerGlobalScope;
 }
 
-void DedicatedWorkerGlobalScope::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& es)
+void DedicatedWorkerGlobalScope::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
 {
     // Disentangle the port in preparation for sending it to the remote context.
-    OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, es);
-    if (es.hadException())
+    OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
+    if (exceptionState.hadException())
         return;
     thread()->workerObjectProxy().postMessageToWorkerObject(message, channels.release());
 }
 
-void DedicatedWorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& es)
+void DedicatedWorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& exceptionState)
 {
-    Base::importScripts(urls, es);
+    Base::importScripts(urls, exceptionState);
     thread()->workerObjectProxy().reportPendingActivity(hasPendingActivity());
 }
 
diff --git a/Source/core/workers/SharedWorker.cpp b/Source/core/workers/SharedWorker.cpp
index ee37ddd..5667b69 100644
--- a/Source/core/workers/SharedWorker.cpp
+++ b/Source/core/workers/SharedWorker.cpp
@@ -39,10 +39,10 @@
 #include "core/dom/MessagePort.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Page.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/workers/SharedWorkerRepositoryClient.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
@@ -52,7 +52,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SharedWorker> SharedWorker::create(ExecutionContext* context, const String& url, const String& name, ExceptionState& es)
+PassRefPtr<SharedWorker> SharedWorker::create(ExecutionContext* context, const String& url, const String& name, ExceptionState& exceptionState)
 {
     ASSERT(isMainThread());
     ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
@@ -63,7 +63,7 @@
 
     RefPtr<MessageChannel> channel = MessageChannel::create(context);
     worker->m_port = channel->port1();
-    OwnPtr<MessagePortChannel> remotePort = channel->port2()->disentangle();
+    OwnPtr<blink::WebMessagePortChannel> remotePort = channel->port2()->disentangle();
     ASSERT(remotePort);
 
     worker->suspendIfNeeded();
@@ -71,16 +71,16 @@
     // We don't currently support nested workers, so workers can only be created from documents.
     Document* document = toDocument(context);
     if (!document->securityOrigin()->canAccessSharedWorkers()) {
-        es.throwSecurityError("Failed to create 'SharedWorker': access to shared workers is denied to origin '" + document->securityOrigin()->toString() + "'.");
+        exceptionState.throwSecurityError("Failed to create 'SharedWorker': access to shared workers is denied to origin '" + document->securityOrigin()->toString() + "'.");
         return 0;
     }
 
-    KURL scriptURL = worker->resolveURL(url, es);
+    KURL scriptURL = worker->resolveURL(url, exceptionState);
     if (scriptURL.isEmpty())
         return 0;
 
     if (document->page() && document->page()->sharedWorkerRepositoryClient())
-        document->page()->sharedWorkerRepositoryClient()->connect(worker.get(), remotePort.release(), scriptURL, name, es);
+        document->page()->sharedWorkerRepositoryClient()->connect(worker.get(), remotePort.release(), scriptURL, name, exceptionState);
 
     return worker.release();
 }
@@ -94,4 +94,14 @@
     return EventTargetNames::SharedWorker;
 }
 
+void SharedWorker::setPreventGC()
+{
+    setPendingActivity(this);
+}
+
+void SharedWorker::unsetPreventGC()
+{
+    unsetPendingActivity(this);
+}
+
 } // namespace WebCore
diff --git a/Source/core/workers/SharedWorker.h b/Source/core/workers/SharedWorker.h
index d6b54d8..8f7902a 100644
--- a/Source/core/workers/SharedWorker.h
+++ b/Source/core/workers/SharedWorker.h
@@ -47,6 +47,11 @@
 
     virtual const AtomicString& interfaceName() const OVERRIDE;
 
+    // Prevents this SharedWorker + JS wrapper from being garbage collected.
+    void setPreventGC();
+    // Allows this SharedWorker + JS wrapper to be garbage collected.
+    void unsetPreventGC();
+
 private:
     explicit SharedWorker(ExecutionContext*);
 
diff --git a/Source/core/workers/SharedWorker.idl b/Source/core/workers/SharedWorker.idl
index a6e4d02..a797db3 100644
--- a/Source/core/workers/SharedWorker.idl
+++ b/Source/core/workers/SharedWorker.idl
@@ -33,7 +33,7 @@
     RuntimeEnabled=SharedWorker,
     Constructor(DOMString scriptURL, [Default=NullString] optional DOMString name),
     ConstructorCallWith=ExecutionContext,
-    ConstructorRaisesException,
+    RaisesException=Constructor,
     ActiveDOMObject
 ] interface SharedWorker : EventTarget {
     readonly attribute MessagePort port;
diff --git a/Source/core/workers/SharedWorkerRepositoryClient.h b/Source/core/workers/SharedWorkerRepositoryClient.h
index 53504fa..607bc29 100644
--- a/Source/core/workers/SharedWorkerRepositoryClient.h
+++ b/Source/core/workers/SharedWorkerRepositoryClient.h
@@ -34,12 +34,15 @@
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 
+namespace blink {
+class WebMessagePortChannel;
+}
+
 namespace WebCore {
 
 class Document;
 class ExceptionState;
 class KURL;
-class MessagePortChannel;
 class SharedWorker;
 
 class SharedWorkerRepositoryClient {
@@ -48,7 +51,7 @@
     SharedWorkerRepositoryClient() { }
     virtual ~SharedWorkerRepositoryClient() { }
 
-    virtual void connect(PassRefPtr<SharedWorker>, PassOwnPtr<MessagePortChannel>, const KURL&, const String& name, ExceptionState&)  = 0;
+    virtual void connect(PassRefPtr<SharedWorker>, PassOwnPtr<blink::WebMessagePortChannel>, const KURL&, const String& name, ExceptionState&)  = 0;
 
     virtual void documentDetached(Document*) = 0;
 };
diff --git a/Source/core/workers/Worker.cpp b/Source/core/workers/Worker.cpp
index 32bdb3a..b3777cd 100644
--- a/Source/core/workers/Worker.cpp
+++ b/Source/core/workers/Worker.cpp
@@ -36,8 +36,9 @@
 #include "core/fetch/ResourceFetcher.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/frame/DOMWindow.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/workers/WorkerGlobalScopeProxy.h"
+#include "core/workers/WorkerGlobalScopeProxyProvider.h"
 #include "core/workers/WorkerScriptLoader.h"
 #include "core/workers/WorkerThread.h"
 #include "wtf/MainThread.h"
@@ -46,21 +47,25 @@
 
 inline Worker::Worker(ExecutionContext* context)
     : AbstractWorker(context)
-    , m_contextProxy(WorkerGlobalScopeProxy::create(this))
+    , m_contextProxy(0)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<Worker> Worker::create(ExecutionContext* context, const String& url, ExceptionState& es)
+PassRefPtr<Worker> Worker::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
 {
     ASSERT(isMainThread());
-    UseCounter::count(toDocument(context)->domWindow(), UseCounter::WorkerStart);
+    Document* document = toDocument(context);
+    UseCounter::count(document->domWindow(), UseCounter::WorkerStart);
+    ASSERT(document->page());
+    WorkerGlobalScopeProxyProvider* proxyProvider = WorkerGlobalScopeProxyProvider::from(document->page());
+    ASSERT(proxyProvider);
 
     RefPtr<Worker> worker = adoptRef(new Worker(context));
 
     worker->suspendIfNeeded();
 
-    KURL scriptURL = worker->resolveURL(url, es);
+    KURL scriptURL = worker->resolveURL(url, exceptionState);
     if (scriptURL.isEmpty())
         return 0;
 
@@ -69,7 +74,7 @@
 
     worker->m_scriptLoader = WorkerScriptLoader::create();
     worker->m_scriptLoader->loadAsynchronously(context, scriptURL, DenyCrossOriginRequests, worker.get());
-
+    worker->m_contextProxy = proxyProvider->createWorkerGlobalScopeProxy(worker.get());
     return worker.release();
 }
 
@@ -77,7 +82,8 @@
 {
     ASSERT(isMainThread());
     ASSERT(executionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
-    m_contextProxy->workerObjectDestroyed();
+    if (m_contextProxy)
+        m_contextProxy->workerObjectDestroyed();
 }
 
 const AtomicString& Worker::interfaceName() const
@@ -85,11 +91,11 @@
     return EventTargetNames::Worker;
 }
 
-void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& es)
+void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
 {
     // Disentangle the port in preparation for sending it to the remote context.
-    OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, es);
-    if (es.hadException())
+    OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
+    if (exceptionState.hadException())
         return;
     m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release());
 }
diff --git a/Source/core/workers/Worker.idl b/Source/core/workers/Worker.idl
index dc8b019..753b13a 100644
--- a/Source/core/workers/Worker.idl
+++ b/Source/core/workers/Worker.idl
@@ -28,7 +28,7 @@
 [
     Constructor(DOMString scriptUrl),
     ConstructorCallWith=ExecutionContext,
-    ConstructorRaisesException,
+    RaisesException=Constructor,
     ActiveDOMObject
 ] interface Worker : EventTarget {
 
diff --git a/Source/core/workers/WorkerConsole.cpp b/Source/core/workers/WorkerConsole.cpp
index 7d71d73..0a22a33 100644
--- a/Source/core/workers/WorkerConsole.cpp
+++ b/Source/core/workers/WorkerConsole.cpp
@@ -63,7 +63,7 @@
 void WorkerConsole::reportMessageToClient(MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack)
 {
     const ScriptCallFrame& lastCaller = callStack->at(0);
-    m_scope->thread()->workerReportingProxy().postConsoleMessageToWorkerObject(ConsoleAPIMessageSource, level, message, lastCaller.lineNumber(), lastCaller.sourceURL());
+    m_scope->thread()->workerReportingProxy().reportConsoleMessage(ConsoleAPIMessageSource, level, message, lastCaller.lineNumber(), lastCaller.sourceURL());
 }
 
 ExecutionContext* WorkerConsole::context()
@@ -81,4 +81,3 @@
 // FIXME: add memory getter
 
 } // namespace WebCore
-
diff --git a/Source/core/workers/WorkerGlobalScope.cpp b/Source/core/workers/WorkerGlobalScope.cpp
index 3b50908..74e097f 100644
--- a/Source/core/workers/WorkerGlobalScope.cpp
+++ b/Source/core/workers/WorkerGlobalScope.cpp
@@ -52,8 +52,8 @@
 #include "core/workers/WorkerObjectProxy.h"
 #include "core/workers/WorkerScriptLoader.h"
 #include "core/workers/WorkerThread.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/RefPtr.h"
 #include "wtf/UnusedParam.h"
 
@@ -91,6 +91,9 @@
     setClient(this);
     setSecurityOrigin(SecurityOrigin::create(url));
     m_workerClients->reattachThread();
+
+    // Notify proxy that a new WorkerGlobalScope has been created and started.
+    this->thread()->workerReportingProxy().workerGlobalScopeStarted();
 }
 
 WorkerGlobalScope::~WorkerGlobalScope()
@@ -195,7 +198,7 @@
     m_workerInspectorController.clear();
 }
 
-void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& es)
+void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& exceptionState)
 {
     ASSERT(contentSecurityPolicy());
     Vector<String>::const_iterator urlsEnd = urls.end();
@@ -203,7 +206,7 @@
     for (Vector<String>::const_iterator it = urls.begin(); it != urlsEnd; ++it) {
         const KURL& url = executionContext()->completeURL(*it);
         if (!url.isValid()) {
-            es.throwDOMException(SyntaxError, "Failed to execute 'importScripts': the URL '" + *it + "' is invalid.");
+            exceptionState.throwDOMException(SyntaxError, "Failed to execute 'importScripts': the URL '" + *it + "' is invalid.");
             return;
         }
         completedURLs.append(url);
@@ -217,7 +220,7 @@
 
         // If the fetching attempt failed, throw a NetworkError exception and abort all these steps.
         if (scriptLoader->failed()) {
-            es.throwDOMException(NetworkError, "Failed to execute 'importScripts': the script at '" + it->elidedString() + "' failed to load.");
+            exceptionState.throwDOMException(NetworkError, "Failed to execute 'importScripts': the script at '" + it->elidedString() + "' failed to load.");
             return;
         }
 
@@ -239,7 +242,7 @@
 
 void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>)
 {
-    thread()->workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, columnNumber, sourceURL);
+    thread()->workerReportingProxy().reportException(errorMessage, lineNumber, columnNumber, sourceURL);
 }
 
 void WorkerGlobalScope::reportBlockedScriptExecutionToInspector(const String& directiveText)
@@ -253,7 +256,7 @@
         postTask(AddConsoleMessageTask::create(source, level, message));
         return;
     }
-    thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, lineNumber, sourceURL);
+    thread()->workerReportingProxy().reportConsoleMessage(source, level, message, lineNumber, sourceURL);
     addMessageToWorkerConsole(source, level, message, sourceURL, lineNumber, 0, state);
 }
 
diff --git a/Source/core/workers/WorkerGlobalScope.h b/Source/core/workers/WorkerGlobalScope.h
index aa4a7c0..8bdcf17 100644
--- a/Source/core/workers/WorkerGlobalScope.h
+++ b/Source/core/workers/WorkerGlobalScope.h
@@ -69,6 +69,7 @@
 
         virtual bool isSharedWorkerGlobalScope() const { return false; }
         virtual bool isDedicatedWorkerGlobalScope() const { return false; }
+        virtual bool isServiceWorkerGlobalScope() const { return false; }
 
         const KURL& url() const { return m_url; }
         KURL completeURL(const String&) const;
diff --git a/Source/core/workers/WorkerGlobalScope.idl b/Source/core/workers/WorkerGlobalScope.idl
index 0d67095..64f5999 100644
--- a/Source/core/workers/WorkerGlobalScope.idl
+++ b/Source/core/workers/WorkerGlobalScope.idl
@@ -25,9 +25,8 @@
  */
 
 [
-    GlobalContext=WorkerGlobalScope,
     CustomToV8,
-    DoNotGenerateWrap
+    GlobalContext=WorkerGlobalScope,
 ] interface WorkerGlobalScope : EventTarget {
 
     // WorkerGlobalScope
diff --git a/Source/core/workers/WorkerGlobalScopeProxy.h b/Source/core/workers/WorkerGlobalScopeProxy.h
index 67ffca3..f6adc53 100644
--- a/Source/core/workers/WorkerGlobalScopeProxy.h
+++ b/Source/core/workers/WorkerGlobalScopeProxy.h
@@ -44,13 +44,6 @@
     // A proxy to talk to the worker global scope.
     class WorkerGlobalScopeProxy {
     public:
-        typedef WorkerGlobalScopeProxy* CreateDelegate(Worker*);
-
-        // FIXME: Instead of delegating through a static factory function we
-        // should probably go through some client interface like ChromeClient.
-        static WorkerGlobalScopeProxy* create(Worker* worker) { return s_createDelegate(worker); }
-        static void setCreateDelegate(CreateDelegate* delegate) { s_createDelegate = delegate; }
-
         virtual ~WorkerGlobalScopeProxy() { }
 
         virtual void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) = 0;
@@ -71,9 +64,6 @@
         virtual void connectToInspector(PageInspector*) { }
         virtual void disconnectFromInspector() { }
         virtual void sendMessageToInspector(const String&) { }
-
-    private:
-        static CreateDelegate* s_createDelegate;
     };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderingConfiguration.cpp b/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
similarity index 73%
copy from Source/core/rendering/RenderingConfiguration.cpp
copy to Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
index 77060a3..3a539df 100644
--- a/Source/core/rendering/RenderingConfiguration.cpp
+++ b/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
@@ -29,28 +29,23 @@
  */
 
 #include "config.h"
-#include "core/rendering/RenderingConfiguration.h"
-
-#include "core/dom/Document.h"
+#include "WorkerGlobalScopeProxyProvider.h"
 
 namespace WebCore {
 
-RenderingConfiguration::RenderingConfiguration()
-    : m_inQuirksMode(false)
-    , m_paginated(false)
-    , m_printing(false)
+WorkerGlobalScopeProxyProvider* WorkerGlobalScopeProxyProvider::from(Page* page)
 {
+    return static_cast<WorkerGlobalScopeProxyProvider*>(Supplement<Page>::from(page, supplementName()));
 }
 
-RenderingConfiguration::~RenderingConfiguration()
+const char* WorkerGlobalScopeProxyProvider::supplementName()
 {
+    return "WorkerGlobalScopeProxyProvider";
 }
 
-void RenderingConfiguration::update(Document& document)
+void provideWorkerGlobalScopeProxyProviderTo(Page* page, PassOwnPtr<WorkerGlobalScopeProxyProvider> provider)
 {
-    m_inQuirksMode = document.inQuirksMode();
-    m_paginated = document.paginated();
-    m_printing = document.printing();
+    Supplement<Page>::provideTo(page, WorkerGlobalScopeProxyProvider::supplementName(), provider);
 }
 
-}
+} // namespace WebCore
diff --git a/Source/core/platform/graphics/MediaSourcePrivate.h b/Source/core/workers/WorkerGlobalScopeProxyProvider.h
similarity index 67%
copy from Source/core/platform/graphics/MediaSourcePrivate.h
copy to Source/core/workers/WorkerGlobalScopeProxyProvider.h
index e3f606e..54b5f47 100644
--- a/Source/core/platform/graphics/MediaSourcePrivate.h
+++ b/Source/core/workers/WorkerGlobalScopeProxyProvider.h
@@ -27,31 +27,35 @@
  * (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 MediaSourcePrivate_h
-#define MediaSourcePrivate_h
 
+#ifndef WorkerGlobalScopeProxyProvider_h
+#define WorkerGlobalScopeProxyProvider_h
+
+#include "core/page/Page.h"
+#include "platform/Supplementable.h"
 #include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+
 
 namespace WebCore {
 
-class SourceBufferPrivate;
+class WorkerGlobalScopeProxy;
+class Worker;
 
-class MediaSourcePrivate {
+class WorkerGlobalScopeProxyProvider : public Supplement<Page> {
+    WTF_MAKE_NONCOPYABLE(WorkerGlobalScopeProxyProvider);
 public:
-    typedef Vector<String, 0> CodecsArray;
+    WorkerGlobalScopeProxyProvider() { }
+    virtual ~WorkerGlobalScopeProxyProvider() { }
 
-    MediaSourcePrivate() { }
-    virtual ~MediaSourcePrivate() { }
+    virtual WorkerGlobalScopeProxy* createWorkerGlobalScopeProxy(Worker*) = 0;
 
-    enum AddStatus { Ok, NotSupported, ReachedIdLimit };
-    virtual AddStatus addSourceBuffer(const String& type, const CodecsArray&, OwnPtr<SourceBufferPrivate>*) = 0;
-    virtual double duration() = 0;
-    virtual void setDuration(double) = 0;
-    enum EndOfStreamStatus { EosNoError, EosNetworkError, EosDecodeError };
-    virtual void markEndOfStream(EndOfStreamStatus) = 0;
-    virtual void unmarkEndOfStream() = 0;
+    static WorkerGlobalScopeProxyProvider* from(Page*);
+    static const char* supplementName();
 };
 
-}
+void provideWorkerGlobalScopeProxyProviderTo(Page*, PassOwnPtr<WorkerGlobalScopeProxyProvider>);
 
-#endif
+} // namespace WebCore
+
+#endif // WorkerGlobalScopeProxyProvider_h
diff --git a/Source/core/workers/WorkerLoaderProxy.h b/Source/core/workers/WorkerLoaderProxy.h
index 9c00c13..4cb4002 100644
--- a/Source/core/workers/WorkerLoaderProxy.h
+++ b/Source/core/workers/WorkerLoaderProxy.h
@@ -35,10 +35,6 @@
 #include "wtf/Forward.h"
 #include "wtf/PassOwnPtr.h"
 
-namespace WebKit {
-class WebWorkerBase;
-}
-
 namespace WebCore {
 
     // A proxy to talk to the loader context. Normally, the document on the main thread
@@ -57,9 +53,6 @@
         // specific synchronous loading requests so they can be 'nested', per spec.
         // Returns true if the task was posted successfully.
         virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask>, const String& mode) = 0;
-
-        // Spans divergent class hierarchies for dedicated and shared workers.
-        virtual WebKit::WebWorkerBase* toWebWorkerBase() = 0;
     };
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerLocation.h b/Source/core/workers/WorkerLocation.h
index f34cd85..6b5aefb 100644
--- a/Source/core/workers/WorkerLocation.h
+++ b/Source/core/workers/WorkerLocation.h
@@ -29,7 +29,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/DOMURLUtilsReadOnly.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/workers/WorkerMessagingProxy.cpp b/Source/core/workers/WorkerMessagingProxy.cpp
index 58c3756..a8032c9 100644
--- a/Source/core/workers/WorkerMessagingProxy.cpp
+++ b/Source/core/workers/WorkerMessagingProxy.cpp
@@ -49,6 +49,7 @@
 #include "core/workers/WorkerClients.h"
 #include "core/workers/WorkerThreadStartupData.h"
 #include "platform/NotImplemented.h"
+#include "wtf/Functional.h"
 #include "wtf/MainThread.h"
 
 namespace WebCore {
@@ -151,73 +152,6 @@
     WorkerMessagingProxy* m_messagingProxy;
 };
 
-class WorkerGlobalScopeDestroyedTask : public ExecutionContextTask {
-public:
-    static PassOwnPtr<WorkerGlobalScopeDestroyedTask> create(WorkerMessagingProxy* messagingProxy)
-    {
-        return adoptPtr(new WorkerGlobalScopeDestroyedTask(messagingProxy));
-    }
-
-private:
-    WorkerGlobalScopeDestroyedTask(WorkerMessagingProxy* messagingProxy)
-        : m_messagingProxy(messagingProxy)
-    {
-    }
-
-    virtual void performTask(ExecutionContext*)
-    {
-        m_messagingProxy->workerGlobalScopeDestroyedInternal();
-    }
-
-    WorkerMessagingProxy* m_messagingProxy;
-};
-
-class WorkerTerminateTask : public ExecutionContextTask {
-public:
-    static PassOwnPtr<WorkerTerminateTask> create(WorkerMessagingProxy* messagingProxy)
-    {
-        return adoptPtr(new WorkerTerminateTask(messagingProxy));
-    }
-
-private:
-    WorkerTerminateTask(WorkerMessagingProxy* messagingProxy)
-        : m_messagingProxy(messagingProxy)
-    {
-    }
-
-    virtual void performTask(ExecutionContext*)
-    {
-        m_messagingProxy->terminateWorkerGlobalScope();
-    }
-
-    WorkerMessagingProxy* m_messagingProxy;
-};
-
-class WorkerThreadActivityReportTask : public ExecutionContextTask {
-public:
-    static PassOwnPtr<WorkerThreadActivityReportTask> create(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
-    {
-        return adoptPtr(new WorkerThreadActivityReportTask(messagingProxy, confirmingMessage, hasPendingActivity));
-    }
-
-private:
-    WorkerThreadActivityReportTask(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
-        : m_messagingProxy(messagingProxy)
-        , m_confirmingMessage(confirmingMessage)
-        , m_hasPendingActivity(hasPendingActivity)
-    {
-    }
-
-    virtual void performTask(ExecutionContext*)
-    {
-        m_messagingProxy->reportPendingActivityInternal(m_confirmingMessage, m_hasPendingActivity);
-    }
-
-    WorkerMessagingProxy* m_messagingProxy;
-    bool m_confirmingMessage;
-    bool m_hasPendingActivity;
-};
-
 class PostMessageToPageInspectorTask : public ExecutionContextTask {
 public:
     static PassOwnPtr<PostMessageToPageInspectorTask> create(WorkerMessagingProxy* messagingProxy, const String& message)
@@ -313,7 +247,7 @@
     m_executionContext->postTask(task);
 }
 
-void WorkerMessagingProxy::postExceptionToWorkerObject(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
+void WorkerMessagingProxy::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
 {
     m_executionContext->postTask(WorkerExceptionTask::create(errorMessage, lineNumber, columnNumber, sourceURL, this));
 }
@@ -325,7 +259,7 @@
     context->addConsoleMessage(source, level, message, sourceURL, lineNumber);
 }
 
-void WorkerMessagingProxy::postConsoleMessageToWorkerObject(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
+void WorkerMessagingProxy::reportConsoleMessage(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
 {
     m_executionContext->postTask(createCallbackTask(&postConsoleMessageTask, AllowCrossThreadAccess(this), source, level, message, lineNumber, sourceURL));
 }
@@ -404,16 +338,19 @@
     WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(m_workerThread.get());
 }
 
+void WorkerMessagingProxy::workerGlobalScopeStarted()
+{
+}
+
 void WorkerMessagingProxy::workerGlobalScopeDestroyed()
 {
-    m_executionContext->postTask(WorkerGlobalScopeDestroyedTask::create(this));
-    // Will execute workerGlobalScopeDestroyedInternal() on context's thread.
+    m_executionContext->postTask(bind(&WorkerMessagingProxy::workerGlobalScopeDestroyedInternal, this));
 }
 
 void WorkerMessagingProxy::workerGlobalScopeClosed()
 {
     // Executes terminateWorkerGlobalScope() on parent context's thread.
-    m_executionContext->postTask(WorkerTerminateTask::create(this));
+    m_executionContext->postTask(bind(&WorkerMessagingProxy::terminateWorkerGlobalScope, this));
 }
 
 void WorkerMessagingProxy::workerGlobalScopeDestroyedInternal()
@@ -453,14 +390,12 @@
 
 void WorkerMessagingProxy::confirmMessageFromWorkerObject(bool hasPendingActivity)
 {
-    m_executionContext->postTask(WorkerThreadActivityReportTask::create(this, true, hasPendingActivity));
-    // Will execute reportPendingActivityInternal() on context's thread.
+    m_executionContext->postTask(bind(&WorkerMessagingProxy::reportPendingActivityInternal, this, true, hasPendingActivity));
 }
 
 void WorkerMessagingProxy::reportPendingActivity(bool hasPendingActivity)
 {
-    m_executionContext->postTask(WorkerThreadActivityReportTask::create(this, false, hasPendingActivity));
-    // Will execute reportPendingActivityInternal() on context's thread.
+    m_executionContext->postTask(bind(&WorkerMessagingProxy::reportPendingActivityInternal, this, false, hasPendingActivity));
 }
 
 void WorkerMessagingProxy::reportPendingActivityInternal(bool confirmingMessage, bool hasPendingActivity)
diff --git a/Source/core/workers/WorkerMessagingProxy.h b/Source/core/workers/WorkerMessagingProxy.h
index 7146234..6f4da6e 100644
--- a/Source/core/workers/WorkerMessagingProxy.h
+++ b/Source/core/workers/WorkerMessagingProxy.h
@@ -64,12 +64,13 @@
         // Implementations of WorkerObjectProxy.
         // (Only use these methods in the worker context thread.)
         virtual void postMessageToWorkerObject(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) OVERRIDE;
-        virtual void postExceptionToWorkerObject(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) OVERRIDE;
-        virtual void postConsoleMessageToWorkerObject(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) OVERRIDE;
+        virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) OVERRIDE;
+        virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) OVERRIDE;
         virtual void postMessageToPageInspector(const String&) OVERRIDE;
         virtual void updateInspectorStateCookie(const String&) OVERRIDE;
         virtual void confirmMessageFromWorkerObject(bool hasPendingActivity) OVERRIDE;
         virtual void reportPendingActivity(bool hasPendingActivity) OVERRIDE;
+        virtual void workerGlobalScopeStarted() OVERRIDE;
         virtual void workerGlobalScopeClosed() OVERRIDE;
         virtual void workerGlobalScopeDestroyed() OVERRIDE;
 
@@ -90,7 +91,6 @@
     private:
         friend class MessageWorkerTask;
         friend class PostMessageToPageInspectorTask;
-        friend class WorkerGlobalScopeDestroyedTask;
         friend class WorkerExceptionTask;
         friend class WorkerThreadActivityReportTask;
 
diff --git a/Source/core/workers/WorkerReportingProxy.h b/Source/core/workers/WorkerReportingProxy.h
index ee53c1d..75b1389 100644
--- a/Source/core/workers/WorkerReportingProxy.h
+++ b/Source/core/workers/WorkerReportingProxy.h
@@ -41,11 +41,14 @@
     public:
         virtual ~WorkerReportingProxy() {}
 
-        virtual void postExceptionToWorkerObject(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) = 0;
-
-        virtual void postConsoleMessageToWorkerObject(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) = 0;
+        virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) = 0;
+        virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) = 0;
         virtual void postMessageToPageInspector(const String&) = 0;
         virtual void updateInspectorStateCookie(const String&) = 0;
+
+        // Invoked when the new WorkerGlobalScope is started.
+        virtual void workerGlobalScopeStarted() = 0;
+
         // Invoked when close() is invoked on the worker context.
         virtual void workerGlobalScopeClosed() = 0;
 
diff --git a/Source/core/workers/WorkerRunLoop.cpp b/Source/core/workers/WorkerRunLoop.cpp
index 66dfd64..66a6e4b 100644
--- a/Source/core/workers/WorkerRunLoop.cpp
+++ b/Source/core/workers/WorkerRunLoop.cpp
@@ -33,7 +33,6 @@
 
 #include "core/dom/ExecutionContext.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/platform/ThreadGlobalData.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerThread.h"
 #include "platform/PlatformThreadData.h"
@@ -43,6 +42,32 @@
 
 namespace WebCore {
 
+class WorkerRunLoop::Task {
+    WTF_MAKE_NONCOPYABLE(Task); WTF_MAKE_FAST_ALLOCATED;
+public:
+    static PassOwnPtr<Task> create(PassOwnPtr<ExecutionContextTask> task, const String& mode)
+    {
+        return adoptPtr(new Task(task, mode));
+    }
+    const String& mode() const { return m_mode; }
+    void performTask(const WorkerRunLoop& runLoop, ExecutionContext* context)
+    {
+        WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
+        if ((!workerGlobalScope->isClosing() && !runLoop.terminated()) || m_task->isCleanupTask())
+            m_task->performTask(context);
+    }
+
+private:
+    Task(PassOwnPtr<ExecutionContextTask> task, const String& mode)
+        : m_task(task)
+        , m_mode(mode.isolatedCopy())
+    {
+    }
+
+    OwnPtr<ExecutionContextTask> m_task;
+    String m_mode;
+};
+
 class WorkerSharedTimer : public SharedTimer {
 public:
     WorkerSharedTimer()
@@ -230,6 +255,11 @@
     return postTaskForMode(task, defaultMode());
 }
 
+bool WorkerRunLoop::postTask(const Closure& closure)
+{
+    return postTask(CallClosureTask::create(closure));
+}
+
 void WorkerRunLoop::postTaskAndTerminate(PassOwnPtr<ExecutionContextTask> task)
 {
     m_messageQueue.appendAndKill(Task::create(task, defaultMode().isolatedCopy()));
@@ -240,22 +270,9 @@
     return m_messageQueue.append(Task::create(task, mode.isolatedCopy()));
 }
 
-PassOwnPtr<WorkerRunLoop::Task> WorkerRunLoop::Task::create(PassOwnPtr<ExecutionContextTask> task, const String& mode)
+bool WorkerRunLoop::postTaskForMode(const Closure& closure, const String& mode)
 {
-    return adoptPtr(new Task(task, mode));
-}
-
-void WorkerRunLoop::Task::performTask(const WorkerRunLoop& runLoop, ExecutionContext* context)
-{
-    WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
-    if ((!workerGlobalScope->isClosing() && !runLoop.terminated()) || m_task->isCleanupTask())
-        m_task->performTask(context);
-}
-
-WorkerRunLoop::Task::Task(PassOwnPtr<ExecutionContextTask> task, const String& mode)
-    : m_task(task)
-    , m_mode(mode.isolatedCopy())
-{
+    return postTaskForMode(CallClosureTask::create(closure), mode);
 }
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerRunLoop.h b/Source/core/workers/WorkerRunLoop.h
index 5792a3f..88d1b3a 100644
--- a/Source/core/workers/WorkerRunLoop.h
+++ b/Source/core/workers/WorkerRunLoop.h
@@ -33,6 +33,7 @@
 
 #include "core/dom/ExecutionContext.h"
 #include "core/dom/ExecutionContextTask.h"
+#include "wtf/Functional.h"
 #include "wtf/MessageQueue.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -61,28 +62,19 @@
 
         // Returns true if the loop is still alive, false if it has been terminated.
         bool postTask(PassOwnPtr<ExecutionContextTask>);
+        bool postTask(const Closure&);
+
         void postTaskAndTerminate(PassOwnPtr<ExecutionContextTask>);
+
         // Returns true if the loop is still alive, false if it has been terminated.
         bool postTaskForMode(PassOwnPtr<ExecutionContextTask>, const String& mode);
+        bool postTaskForMode(const Closure&, const String& mode);
 
         unsigned long createUniqueId() { return ++m_uniqueId; }
 
         static String defaultMode();
 
-        class Task {
-            WTF_MAKE_NONCOPYABLE(Task); WTF_MAKE_FAST_ALLOCATED;
-        public:
-            static PassOwnPtr<Task> create(PassOwnPtr<ExecutionContextTask>, const String& mode);
-            ~Task() { }
-            const String& mode() const { return m_mode; }
-            void performTask(const WorkerRunLoop&, ExecutionContext*);
-
-        private:
-            Task(PassOwnPtr<ExecutionContextTask>, const String& mode);
-
-            OwnPtr<ExecutionContextTask> m_task;
-            String m_mode;
-        };
+        class Task;
 
     private:
         friend class RunLoopSetup;
diff --git a/Source/core/workers/WorkerScriptLoader.h b/Source/core/workers/WorkerScriptLoader.h
index 296734d..88875f1 100644
--- a/Source/core/workers/WorkerScriptLoader.h
+++ b/Source/core/workers/WorkerScriptLoader.h
@@ -31,7 +31,7 @@
 #include "core/loader/ThreadableLoader.h"
 #include "core/loader/ThreadableLoaderClient.h"
 #include "platform/network/ResourceRequest.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/FastAllocBase.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -84,7 +84,7 @@
         WorkerScriptLoaderClient* m_client;
         RefPtr<ThreadableLoader> m_threadableLoader;
         String m_responseEncoding;
-        RefPtr<TextResourceDecoder> m_decoder;
+        OwnPtr<TextResourceDecoder> m_decoder;
         StringBuilder m_script;
         KURL m_url;
         KURL m_responseURL;
diff --git a/Source/core/workers/WorkerThread.cpp b/Source/core/workers/WorkerThread.cpp
index 10a31a0..6f842e8 100644
--- a/Source/core/workers/WorkerThread.cpp
+++ b/Source/core/workers/WorkerThread.cpp
@@ -30,16 +30,15 @@
 
 #include "bindings/v8/ScriptSourceCode.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/platform/ThreadGlobalData.h"
 #include "core/workers/DedicatedWorkerGlobalScope.h"
 #include "core/workers/WorkerClients.h"
 #include "core/workers/WorkerThreadStartupData.h"
 #include "modules/webdatabase/DatabaseManager.h"
 #include "modules/webdatabase/DatabaseTask.h"
 #include "platform/PlatformThreadData.h"
+#include "platform/weborigin/KURL.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebWorkerRunLoop.h"
-#include "weborigin/KURL.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/text/WTFString.h"
 
@@ -120,7 +119,7 @@
     }
     // The corresponding call to didStopWorkerRunLoop is in
     // ~WorkerScriptController.
-    WebKit::Platform::current()->didStartWorkerRunLoop(WebKit::WebWorkerRunLoop(&m_runLoop));
+    blink::Platform::current()->didStartWorkerRunLoop(blink::WebWorkerRunLoop(&m_runLoop));
 
     WorkerScriptController* script = m_workerGlobalScope->script();
     InspectorInstrumentation::willEvaluateWorkerScript(workerGlobalScope(), startMode);
diff --git a/Source/core/workers/WorkerThread.h b/Source/core/workers/WorkerThread.h
index d65ab0a..83bf3f4 100644
--- a/Source/core/workers/WorkerThread.h
+++ b/Source/core/workers/WorkerThread.h
@@ -29,7 +29,7 @@
 
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/workers/WorkerRunLoop.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Forward.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassRefPtr.h"
diff --git a/Source/core/workers/WorkerThreadStartupData.h b/Source/core/workers/WorkerThreadStartupData.h
index de24ef4..c1b13d7 100644
--- a/Source/core/workers/WorkerThreadStartupData.h
+++ b/Source/core/workers/WorkerThreadStartupData.h
@@ -34,7 +34,7 @@
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/workers/WorkerClients.h"
 #include "core/workers/WorkerThread.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 
diff --git a/Source/core/xml/DOMParser.cpp b/Source/core/xml/DOMParser.cpp
index 29a37da..bc509de 100644
--- a/Source/core/xml/DOMParser.cpp
+++ b/Source/core/xml/DOMParser.cpp
@@ -25,7 +25,7 @@
 
 namespace WebCore {
 
-PassRefPtr<Document> DOMParser::parseFromString(const String& str, const String& contentType, ExceptionState& es)
+PassRefPtr<Document> DOMParser::parseFromString(const String& str, const String& contentType, ExceptionState& exceptionState)
 {
     // HTML5 is very explicit about which types we're allowed to support here:
     // http://domparsing.spec.whatwg.org/#the-domparser-interface
@@ -34,7 +34,7 @@
         && contentType != "application/xml"
         && contentType != "application/xhtml+xml"
         && contentType != "image/svg+xml") {
-        es.throwDOMException(TypeError, "Unsupported mime-type specified.");
+        exceptionState.throwDOMException(TypeError, "Unsupported mime-type specified.");
         return 0;
     }
 
diff --git a/Source/core/xml/DocumentXPathEvaluator.cpp b/Source/core/xml/DocumentXPathEvaluator.cpp
index 9352c4f..c34a7ea 100644
--- a/Source/core/xml/DocumentXPathEvaluator.cpp
+++ b/Source/core/xml/DocumentXPathEvaluator.cpp
@@ -54,12 +54,12 @@
 }
 
 PassRefPtr<XPathExpression> DocumentXPathEvaluator::createExpression(DocumentSupplementable* document,
-    const String& expression, XPathNSResolver* resolver, ExceptionState& es)
+    const String& expression, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
 {
     DocumentXPathEvaluator* suplement = from(document);
     if (!suplement->m_xpathEvaluator)
         suplement->m_xpathEvaluator = XPathEvaluator::create();
-    return suplement->m_xpathEvaluator->createExpression(expression, resolver, es);
+    return suplement->m_xpathEvaluator->createExpression(expression, resolver, exceptionState);
 }
 
 PassRefPtr<XPathNSResolver> DocumentXPathEvaluator::createNSResolver(DocumentSupplementable* document, Node* nodeResolver)
@@ -71,13 +71,13 @@
 }
 
 PassRefPtr<XPathResult> DocumentXPathEvaluator::evaluate(DocumentSupplementable* document, const String& expression,
-    Node* contextNode, XPathNSResolver* resolver, unsigned short type,
-    XPathResult* result, ExceptionState& es)
+    Node* contextNode, PassRefPtr<XPathNSResolver> resolver, unsigned short type,
+    XPathResult* result, ExceptionState& exceptionState)
 {
     DocumentXPathEvaluator* suplement = from(document);
     if (!suplement->m_xpathEvaluator)
         suplement->m_xpathEvaluator = XPathEvaluator::create();
-    return suplement->m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, es);
+    return suplement->m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, exceptionState);
 }
 
 } // namespace WebCore
diff --git a/Source/core/xml/DocumentXPathEvaluator.h b/Source/core/xml/DocumentXPathEvaluator.h
index d081b26..769a449 100644
--- a/Source/core/xml/DocumentXPathEvaluator.h
+++ b/Source/core/xml/DocumentXPathEvaluator.h
@@ -28,12 +28,12 @@
 
 #include "core/dom/DocumentSupplementable.h"
 #include "core/xml/XPathEvaluator.h"
+#include "core/xml/XPathNSResolver.h"
 
 namespace WebCore {
 
 class ExceptionState;
 class XPathExpression;
-class XPathNSResolver;
 class XPathResult;
 
 class DocumentXPathEvaluator : public DocumentSupplement {
@@ -43,10 +43,10 @@
     static DocumentXPathEvaluator* from(DocumentSupplementable*);
 
     static PassRefPtr<XPathExpression> createExpression(DocumentSupplementable*,
-        const String& expression, XPathNSResolver*, ExceptionState&);
+        const String& expression, PassRefPtr<XPathNSResolver>, ExceptionState&);
     static PassRefPtr<XPathNSResolver> createNSResolver(DocumentSupplementable*, Node* nodeResolver);
     static PassRefPtr<XPathResult> evaluate(DocumentSupplementable*,
-        const String& expression, Node* contextNode, XPathNSResolver*,
+        const String& expression, Node* contextNode, PassRefPtr<XPathNSResolver>,
         unsigned short type, XPathResult*, ExceptionState&);
 
 private:
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index 0d4d2fe..777ed7d 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -54,8 +54,8 @@
 #include "platform/network/ParsedContentType.h"
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "public/platform/Platform.h"
-#include "weborigin/SecurityOrigin.h"
 #include "wtf/ArrayBuffer.h"
 #include "wtf/ArrayBufferView.h"
 #include "wtf/RefCountedLeakCounter.h"
@@ -215,10 +215,10 @@
     return m_state;
 }
 
-ScriptString XMLHttpRequest::responseText(ExceptionState& es)
+ScriptString XMLHttpRequest::responseText(ExceptionState& exceptionState)
 {
     if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeText) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("responseText", "XMLHttpRequest", "the value is only accessible if the object's 'responseType' is '' or 'text' (was '" + responseType() + "')."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("responseText", "XMLHttpRequest", "the value is only accessible if the object's 'responseType' is '' or 'text' (was '" + responseType() + "')."));
         return ScriptString();
     }
     if (m_error || (m_state != LOADING && m_state != DONE))
@@ -235,10 +235,10 @@
     return m_responseText;
 }
 
-Document* XMLHttpRequest::responseXML(ExceptionState& es)
+Document* XMLHttpRequest::responseXML(ExceptionState& exceptionState)
 {
     if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeDocument) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("responseXML", "XMLHttpRequest", "the value is only accessible if the object's 'responseType' is '' or 'document' (was '" + responseType() + "')."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("responseXML", "XMLHttpRequest", "the value is only accessible if the object's 'responseType' is '' or 'document' (was '" + responseType() + "')."));
         return 0;
     }
 
@@ -335,21 +335,21 @@
     return m_responseStream.get();
 }
 
-void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& es)
+void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& exceptionState)
 {
     // FIXME: Need to trigger or update the timeout Timer here, if needed. http://webkit.org/b/98156
     // XHR2 spec, 4.7.3. "This implies that the timeout attribute can be set while fetching is in progress. If that occurs it will still be measured relative to the start of fetching."
     if (executionContext()->isDocument() && !m_async) {
-        es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("timeout", "XMLHttpRequest", "timeouts cannot be set for synchronous requests made from a document."));
+        exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("timeout", "XMLHttpRequest", "timeouts cannot be set for synchronous requests made from a document."));
         return;
     }
     m_timeoutMilliseconds = timeout;
 }
 
-void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& es)
+void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& exceptionState)
 {
     if (m_state >= LOADING) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type cannot be set if the object's state is LOADING or DONE."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type cannot be set if the object's state is LOADING or DONE."));
         return;
     }
 
@@ -358,7 +358,7 @@
     // We'll only disable this functionality for HTTP(S) requests since sync requests for local protocols
     // such as file: and data: still make sense to allow.
     if (!m_async && executionContext()->isDocument() && m_url.protocolIsInHTTPFamily()) {
-        es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type can only be changed for asynchronous HTTP requests made from a document."));
+        exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type can only be changed for asynchronous HTTP requests made from a document."));
         return;
     }
 
@@ -427,22 +427,30 @@
 
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRReadyStateChangeEvent(executionContext(), this);
 
-    if (m_async || (m_state <= OPENED || m_state == DONE))
-        m_progressEventThrottle.dispatchReadyStateChangeEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::readystatechange), m_state == DONE ? FlushProgressEvent : DoNotFlushProgressEvent);
+    if (m_async || (m_state <= OPENED || m_state == DONE)) {
+        ProgressEventAction flushAction = DoNotFlushProgressEvent;
+        if (m_state == DONE) {
+            if (m_error)
+                flushAction = FlushDeferredProgressEvent;
+            else
+                flushAction = FlushProgressEvent;
+        }
+        m_progressEventThrottle.dispatchReadyStateChangeEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::readystatechange), flushAction);
+    }
 
     InspectorInstrumentation::didDispatchXHRReadyStateChangeEvent(cookie);
     if (m_state == DONE && !m_error) {
         InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRLoadEvent(executionContext(), this);
-        m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::load));
+        dispatchThrottledProgressEventSnapshot(EventTypeNames::load);
         InspectorInstrumentation::didDispatchXHRLoadEvent(cookie);
-        m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadend));
+        dispatchThrottledProgressEventSnapshot(EventTypeNames::loadend);
     }
 }
 
-void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& es)
+void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& exceptionState)
 {
     if (m_state > OPENED || m_loader) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("withCredentials", "XMLHttpRequest", "the value may only be set if the object's state is UNSENT or OPENED."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("withCredentials", "XMLHttpRequest", "the value may only be set if the object's state is UNSENT or OPENED."));
         return;
     }
 
@@ -492,12 +500,12 @@
         && !name.startsWith(staticData->m_secHeaderPrefix, false);
 }
 
-void XMLHttpRequest::open(const String& method, const KURL& url, ExceptionState& es)
+void XMLHttpRequest::open(const String& method, const KURL& url, ExceptionState& exceptionState)
 {
-    open(method, url, true, es);
+    open(method, url, true, exceptionState);
 }
 
-void XMLHttpRequest::open(const String& method, const KURL& url, bool async, ExceptionState& es)
+void XMLHttpRequest::open(const String& method, const KURL& url, bool async, ExceptionState& exceptionState)
 {
     LOG(Network, "XMLHttpRequest %p open('%s', '%s', %d)", this, method.utf8().data(), url.elidedString().utf8().data(), async);
 
@@ -516,24 +524,24 @@
     ASSERT(m_state == UNSENT);
 
     if (!isValidHTTPToken(method)) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' is not a valid HTTP method."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' is not a valid HTTP method."));
         return;
     }
 
     if (!isAllowedHTTPMethod(method)) {
-        es.throwSecurityError(ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' HTTP method is unsupported."));
+        exceptionState.throwSecurityError(ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' HTTP method is unsupported."));
         return;
     }
 
     if (!ContentSecurityPolicy::shouldBypassMainWorld(executionContext()) && !executionContext()->contentSecurityPolicy()->allowConnectToSource(url)) {
         // We can safely expose the URL to JavaScript, as these checks happen synchronously before redirection. JavaScript receives no new information.
-        es.throwSecurityError("Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy.");
+        exceptionState.throwSecurityError("Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy.");
         return;
     }
 
     if (!async && executionContext()->isDocument()) {
         if (document()->settings() && !document()->settings()->syncXHRInDocumentsEnabled()) {
-            es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests are disabled for this page."));
+            exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests are disabled for this page."));
             return;
         }
 
@@ -542,13 +550,13 @@
         // We'll only disable this functionality for HTTP(S) requests since sync requests for local protocols
         // such as file: and data: still make sense to allow.
         if (url.protocolIsInHTTPFamily() && m_responseTypeCode != ResponseTypeDefault) {
-            es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous HTTP requests from a document must not set a response type."));
+            exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous HTTP requests from a document must not set a response type."));
             return;
         }
 
         // Similarly, timeouts are disabled for synchronous requests as well.
         if (m_timeoutMilliseconds > 0) {
-            es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests must not set a timeout."));
+            exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests must not set a timeout."));
             return;
         }
     }
@@ -569,30 +577,30 @@
         m_state = OPENED;
 }
 
-void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, ExceptionState& es)
+void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, ExceptionState& exceptionState)
 {
     KURL urlWithCredentials(url);
     urlWithCredentials.setUser(user);
 
-    open(method, urlWithCredentials, async, es);
+    open(method, urlWithCredentials, async, exceptionState);
 }
 
-void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, const String& password, ExceptionState& es)
+void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, const String& password, ExceptionState& exceptionState)
 {
     KURL urlWithCredentials(url);
     urlWithCredentials.setUser(user);
     urlWithCredentials.setPass(password);
 
-    open(method, urlWithCredentials, async, es);
+    open(method, urlWithCredentials, async, exceptionState);
 }
 
-bool XMLHttpRequest::initSend(ExceptionState& es)
+bool XMLHttpRequest::initSend(ExceptionState& exceptionState)
 {
     if (!executionContext())
         return false;
 
     if (m_state != OPENED || m_loader) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "the object's state must be OPENED."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "the object's state must be OPENED."));
         return false;
     }
 
@@ -600,9 +608,9 @@
     return true;
 }
 
-void XMLHttpRequest::send(ExceptionState& es)
+void XMLHttpRequest::send(ExceptionState& exceptionState)
 {
-    send(String(), es);
+    send(String(), exceptionState);
 }
 
 bool XMLHttpRequest::areMethodAndURLValidForSend()
@@ -610,13 +618,13 @@
     return m_method != "GET" && m_method != "HEAD" && m_url.protocolIsInHTTPFamily();
 }
 
-void XMLHttpRequest::send(Document* document, ExceptionState& es)
+void XMLHttpRequest::send(Document* document, ExceptionState& exceptionState)
 {
     LOG(Network, "XMLHttpRequest %p send() Document %p", this, document);
 
     ASSERT(document);
 
-    if (!initSend(es))
+    if (!initSend(exceptionState))
         return;
 
     if (areMethodAndURLValidForSend()) {
@@ -636,14 +644,14 @@
             m_requestEntityBody->setAlwaysStream(true);
     }
 
-    createRequest(es);
+    createRequest(exceptionState);
 }
 
-void XMLHttpRequest::send(const String& body, ExceptionState& es)
+void XMLHttpRequest::send(const String& body, ExceptionState& exceptionState)
 {
     LOG(Network, "XMLHttpRequest %p send() String '%s'", this, body.utf8().data());
 
-    if (!initSend(es))
+    if (!initSend(exceptionState))
         return;
 
     if (!body.isNull() && areMethodAndURLValidForSend()) {
@@ -660,14 +668,14 @@
             m_requestEntityBody->setAlwaysStream(true);
     }
 
-    createRequest(es);
+    createRequest(exceptionState);
 }
 
-void XMLHttpRequest::send(Blob* body, ExceptionState& es)
+void XMLHttpRequest::send(Blob* body, ExceptionState& exceptionState)
 {
     LOG(Network, "XMLHttpRequest %p send() Blob '%s'", this, body->uuid().utf8().data());
 
-    if (!initSend(es))
+    if (!initSend(exceptionState))
         return;
 
     if (areMethodAndURLValidForSend()) {
@@ -684,20 +692,20 @@
 
         // FIXME: add support for uploading bundles.
         m_requestEntityBody = FormData::create();
-        if (body->isFile())
+        if (body->hasBackingFile())
             m_requestEntityBody->appendFile(toFile(body)->path());
         else
             m_requestEntityBody->appendBlob(body->uuid(), body->blobDataHandle());
     }
 
-    createRequest(es);
+    createRequest(exceptionState);
 }
 
-void XMLHttpRequest::send(DOMFormData* body, ExceptionState& es)
+void XMLHttpRequest::send(DOMFormData* body, ExceptionState& exceptionState)
 {
     LOG(Network, "XMLHttpRequest %p send() DOMFormData %p", this, body);
 
-    if (!initSend(es))
+    if (!initSend(exceptionState))
         return;
 
     if (areMethodAndURLValidForSend()) {
@@ -710,33 +718,33 @@
         }
     }
 
-    createRequest(es);
+    createRequest(exceptionState);
 }
 
-void XMLHttpRequest::send(ArrayBuffer* body, ExceptionState& es)
+void XMLHttpRequest::send(ArrayBuffer* body, ExceptionState& exceptionState)
 {
     LOG(Network, "XMLHttpRequest %p send() ArrayBuffer %p", this, body);
 
     String consoleMessage("ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.");
     executionContext()->addConsoleMessage(JSMessageSource, WarningMessageLevel, consoleMessage);
 
-    WebKit::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferOrViewMax);
+    blink::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferOrViewMax);
 
-    sendBytesData(body->data(), body->byteLength(), es);
+    sendBytesData(body->data(), body->byteLength(), exceptionState);
 }
 
-void XMLHttpRequest::send(ArrayBufferView* body, ExceptionState& es)
+void XMLHttpRequest::send(ArrayBufferView* body, ExceptionState& exceptionState)
 {
     LOG(Network, "XMLHttpRequest %p send() ArrayBufferView %p", this, body);
 
-    WebKit::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax);
+    blink::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax);
 
-    sendBytesData(body->baseAddress(), body->byteLength(), es);
+    sendBytesData(body->baseAddress(), body->byteLength(), exceptionState);
 }
 
-void XMLHttpRequest::sendBytesData(const void* data, size_t length, ExceptionState& es)
+void XMLHttpRequest::sendBytesData(const void* data, size_t length, ExceptionState& exceptionState)
 {
-    if (!initSend(es))
+    if (!initSend(exceptionState))
         return;
 
     if (areMethodAndURLValidForSend()) {
@@ -745,21 +753,21 @@
             m_requestEntityBody->setAlwaysStream(true);
     }
 
-    createRequest(es);
+    createRequest(exceptionState);
 }
 
-void XMLHttpRequest::sendForInspectorXHRReplay(PassRefPtr<FormData> formData, ExceptionState& es)
+void XMLHttpRequest::sendForInspectorXHRReplay(PassRefPtr<FormData> formData, ExceptionState& exceptionState)
 {
     m_requestEntityBody = formData ? formData->deepCopy() : 0;
-    createRequest(es);
-    m_exceptionCode = es.code();
+    createRequest(exceptionState);
+    m_exceptionCode = exceptionState.code();
 }
 
-void XMLHttpRequest::createRequest(ExceptionState& es)
+void XMLHttpRequest::createRequest(ExceptionState& exceptionState)
 {
     // Only GET request is supported for blob URL.
     if (m_url.protocolIs("blob") && m_method != "GET") {
-        es.throwDOMException(NetworkError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "'GET' is the only method allowed for 'blob:' URLs."));
+        exceptionState.throwDOMException(NetworkError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "'GET' is the only method allowed for 'blob:' URLs."));
         return;
     }
 
@@ -836,7 +844,7 @@
     if (!m_exceptionCode && m_error)
         m_exceptionCode = NetworkError;
     if (m_exceptionCode)
-        es.throwUninformativeAndGenericDOMException(m_exceptionCode);
+        exceptionState.throwUninformativeAndGenericDOMException(m_exceptionCode);
 }
 
 void XMLHttpRequest::abort()
@@ -848,6 +856,10 @@
 
     bool sendFlag = m_loader;
 
+    // Response is cleared next, save needed progress event data.
+    long long expectedLength = m_response.expectedContentLength();
+    long long receivedLength = m_receivedLength;
+
     if (!internalAbort())
         return;
 
@@ -856,27 +868,18 @@
     // Clear headers as required by the spec
     m_requestHeaders.clear();
 
-    if ((m_state <= OPENED && !sendFlag) || m_state == DONE)
-        m_state = UNSENT;
-    else {
+    if (!((m_state <= OPENED && !sendFlag) || m_state == DONE)) {
         ASSERT(!m_loader);
-        changeState(DONE);
-        m_state = UNSENT;
+        handleRequestError(0, EventTypeNames::abort, receivedLength, expectedLength);
     }
-
-    m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(EventTypeNames::abort));
-    if (!m_uploadComplete) {
-        m_uploadComplete = true;
-        if (m_upload && m_uploadEventsAllowed)
-            m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(EventTypeNames::abort));
-    }
+    m_state = UNSENT;
 }
 
 void XMLHttpRequest::clearVariablesForLoading()
 {
     // FIXME: when we add the support for multi-part XHR, we will have to think be careful with this initialization.
     m_receivedLength = 0;
-    m_decoder = 0;
+    m_decoder.clear();
 
     m_responseEncoding = String();
 }
@@ -912,6 +915,12 @@
     // Save to a local variable since we're going to drop protection.
     bool newLoadStarted = m_loader;
 
+    // If abort() called internalAbort() and a nested open() ended up
+    // clearing the error flag, but didn't send(), make sure the error
+    // flag is still set.
+    if (!newLoadStarted)
+        m_error = true;
+
     if (async == DropProtectionAsync)
         dropProtectionSoon();
     else
@@ -953,31 +962,42 @@
     m_error = true;
 }
 
-void XMLHttpRequest::dispatchEventAndLoadEnd(const AtomicString& type)
+void XMLHttpRequest::dispatchEventAndLoadEnd(const AtomicString& type, long long receivedLength, long long expectedLength)
 {
-    if (!m_uploadComplete) {
-        m_uploadComplete = true;
-        if (m_upload && m_uploadEventsAllowed)
-            m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type));
-    }
-    m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type));
+    bool lengthComputable = expectedLength > 0 && receivedLength <= expectedLength;
+    unsigned long long loaded = receivedLength >= 0 ? static_cast<unsigned long long>(receivedLength) : 0;
+    unsigned long long total = lengthComputable ? static_cast<unsigned long long>(expectedLength) : 0;
+
+    m_progressEventThrottle.dispatchEventAndLoadEnd(type, lengthComputable, loaded, total);
+}
+
+void XMLHttpRequest::dispatchThrottledProgressEvent(const AtomicString& type, long long receivedLength, long long expectedLength)
+{
+    bool lengthComputable = expectedLength > 0 && receivedLength <= expectedLength;
+    unsigned long long loaded = receivedLength >= 0 ? static_cast<unsigned long long>(receivedLength) : 0;
+    unsigned long long total = lengthComputable ? static_cast<unsigned long long>(expectedLength) : 0;
+
+    if (type == EventTypeNames::progress)
+        m_progressEventThrottle.dispatchProgressEvent(lengthComputable, loaded, total);
+    else
+        m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(type, lengthComputable, loaded, total));
+}
+
+void XMLHttpRequest::dispatchThrottledProgressEventSnapshot(const AtomicString& type)
+{
+    return dispatchThrottledProgressEvent(type, m_receivedLength, m_response.expectedContentLength());
 }
 
 void XMLHttpRequest::handleNetworkError()
 {
     LOG(Network, "XMLHttpRequest %p handleNetworkError()", this);
 
-    m_exceptionCode = NetworkError;
+    // Response is cleared next, save needed progress event data.
+    long long expectedLength = m_response.expectedContentLength();
+    long long receivedLength = m_receivedLength;
 
     handleDidFailGeneric();
-
-    if (m_async) {
-        changeState(DONE);
-        dispatchEventAndLoadEnd(EventTypeNames::error);
-    } else {
-        m_state = DONE;
-    }
-
+    handleRequestError(NetworkError, EventTypeNames::error, receivedLength, expectedLength);
     internalAbort();
 }
 
@@ -985,17 +1005,40 @@
 {
     LOG(Network, "XMLHttpRequest %p handleDidCancel()", this);
 
-    m_exceptionCode = AbortError;
+    // Response is cleared next, save needed progress event data.
+    long long expectedLength = m_response.expectedContentLength();
+    long long receivedLength = m_receivedLength;
 
     handleDidFailGeneric();
+    handleRequestError(AbortError, EventTypeNames::abort, receivedLength, expectedLength);
+}
 
-    if (!m_async) {
+void XMLHttpRequest::handleRequestError(ExceptionCode exceptionCode, const AtomicString& type, long long receivedLength, long long expectedLength)
+{
+    LOG(Network, "XMLHttpRequest %p handleRequestError()", this);
+
+    // The request error steps for event 'type' and exception 'exceptionCode'.
+
+    if (!m_async && exceptionCode) {
         m_state = DONE;
+        m_exceptionCode = exceptionCode;
         return;
     }
+    // With m_error set, the state change steps are minimal: any pending
+    // progress event is flushed + a readystatechange is dispatched.
+    // No new progress events dispatched; as required, that happens at
+    // the end here.
+    ASSERT(m_error);
     changeState(DONE);
 
-    dispatchEventAndLoadEnd(EventTypeNames::abort);
+    if (!m_uploadComplete) {
+        m_uploadComplete = true;
+        if (m_upload && m_uploadEventsAllowed)
+            m_upload->handleRequestError(type);
+    }
+
+    dispatchThrottledProgressEvent(EventTypeNames::progress, receivedLength, expectedLength);
+    dispatchEventAndLoadEnd(type, receivedLength, expectedLength);
 }
 
 void XMLHttpRequest::dropProtectionSoon()
@@ -1013,20 +1056,20 @@
     m_mimeTypeOverride = override;
 }
 
-void XMLHttpRequest::setRequestHeader(const AtomicString& name, const String& value, ExceptionState& es)
+void XMLHttpRequest::setRequestHeader(const AtomicString& name, const String& value, ExceptionState& exceptionState)
 {
     if (m_state != OPENED || m_loader) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "the object's state must be OPENED."));
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "the object's state must be OPENED."));
         return;
     }
 
     if (!isValidHTTPToken(name)) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "'" + name + "' is not a valid HTTP header field name."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "'" + name + "' is not a valid HTTP header field name."));
         return;
     }
 
     if (!isValidHTTPHeaderValue(value)) {
-        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "'" + value + "' is not a valid HTTP header field value."));
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "'" + value + "' is not a valid HTTP header field value."));
         return;
     }
 
@@ -1051,7 +1094,7 @@
     return m_requestHeaders.get(name);
 }
 
-String XMLHttpRequest::getAllResponseHeaders(ExceptionState& es) const
+String XMLHttpRequest::getAllResponseHeaders(ExceptionState& exceptionState) const
 {
     if (m_state < HEADERS_RECEIVED || m_error)
         return "";
@@ -1085,7 +1128,7 @@
     return stringBuilder.toString();
 }
 
-String XMLHttpRequest::getResponseHeader(const AtomicString& name, ExceptionState& es) const
+String XMLHttpRequest::getResponseHeader(const AtomicString& name, ExceptionState& exceptionState) const
 {
     if (m_state < HEADERS_RECEIVED || m_error)
         return String();
@@ -1128,7 +1171,7 @@
     return DOMImplementation::isXMLMIMEType(responseMIMEType().lower());
 }
 
-int XMLHttpRequest::status(ExceptionState& es) const
+int XMLHttpRequest::status(ExceptionState& exceptionState) const
 {
     if (m_state == UNSENT || m_state == OPENED || m_error)
         return 0;
@@ -1139,7 +1182,7 @@
     return 0;
 }
 
-String XMLHttpRequest::statusText(ExceptionState& es) const
+String XMLHttpRequest::statusText(ExceptionState& exceptionState) const
 {
     if (m_state == UNSENT || m_state == OPENED || m_error)
         return String();
@@ -1195,8 +1238,6 @@
     if (m_decoder)
         m_responseText = m_responseText.concatenateWith(m_decoder->flush());
 
-    clearVariablesForLoading();
-
     if (m_responseStream)
         m_responseStream->finalize();
 
@@ -1211,6 +1252,8 @@
     }
 
     changeState(DONE);
+
+    clearVariablesForLoading();
 }
 
 void XMLHttpRequest::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
@@ -1221,12 +1264,12 @@
         return;
 
     if (m_uploadEventsAllowed)
-        m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::progress, true, bytesSent, totalBytesToBeSent));
+        m_upload->dispatchProgressEvent(bytesSent, totalBytesToBeSent);
 
     if (bytesSent == totalBytesToBeSent && !m_uploadComplete) {
         m_uploadComplete = true;
         if (m_uploadEventsAllowed)
-            m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(EventTypeNames::load));
+            m_upload->dispatchEventAndLoadEnd(EventTypeNames::load, true, bytesSent, totalBytesToBeSent);
     }
 }
 
@@ -1296,13 +1339,8 @@
 
     m_receivedLength += len;
 
-    if (m_async) {
-        long long expectedLength = m_response.expectedContentLength();
-        bool lengthComputable = expectedLength > 0 && m_receivedLength <= expectedLength;
-        unsigned long long total = lengthComputable ? expectedLength : 0;
-
-        m_progressEventThrottle.dispatchProgressEvent(lengthComputable, m_receivedLength, total);
-    }
+    if (m_async)
+        dispatchThrottledProgressEventSnapshot(EventTypeNames::progress);
 
     if (m_state != LOADING) {
         changeState(LOADING);
@@ -1323,20 +1361,15 @@
     // internalAbort() calls dropProtection(), which may release the last reference.
     RefPtr<XMLHttpRequest> protect(this);
 
+    // Response is cleared next, save needed progress event data.
+    long long expectedLength = m_response.expectedContentLength();
+    long long receivedLength = m_receivedLength;
+
     if (!internalAbort())
         return;
 
-    m_exceptionCode = TimeoutError;
-
     handleDidFailGeneric();
-
-    if (!m_async) {
-        m_state = DONE;
-        return;
-    }
-    changeState(DONE);
-
-    dispatchEventAndLoadEnd(EventTypeNames::timeout);
+    handleRequestError(TimeoutError, EventTypeNames::timeout, receivedLength, expectedLength);
 }
 
 void XMLHttpRequest::suspend()
diff --git a/Source/core/xml/XMLHttpRequest.h b/Source/core/xml/XMLHttpRequest.h
index c884c01..11ad783 100644
--- a/Source/core/xml/XMLHttpRequest.h
+++ b/Source/core/xml/XMLHttpRequest.h
@@ -33,7 +33,7 @@
 #include "platform/AsyncMethodRunner.h"
 #include "platform/network/FormData.h"
 #include "platform/network/ResourceResponse.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/text/AtomicStringHash.h"
 #include "wtf/text/StringBuilder.h"
@@ -184,9 +184,16 @@
 
     void createRequest(ExceptionState&);
 
-    // Dispatches an event of the specified type to m_upload and
-    // m_progressEventThrottle.
-    void dispatchEventAndLoadEnd(const AtomicString&);
+    // Dispatches an event of the specified type to m_progressEventThrottle.
+    void dispatchEventAndLoadEnd(const AtomicString&, long long, long long);
+
+    // Dispatches a response progress event to m_progressEventThrottle.
+    void dispatchThrottledProgressEvent(const AtomicString&, long long, long long);
+
+    // Dispatches a response progress event using values sampled from
+    // m_receivedLength and m_response.
+    void dispatchThrottledProgressEventSnapshot(const AtomicString&);
+
     // Does clean up common for all kind of didFail() call.
     void handleDidFailGeneric();
     // Handles didFail() call not caused by cancellation or timeout.
@@ -196,6 +203,8 @@
     // Handles didFail() call for timeout.
     void handleDidTimeout();
 
+    void handleRequestError(ExceptionCode, const AtomicString&, long long, long long);
+
     OwnPtr<XMLHttpRequestUpload> m_upload;
 
     KURL m_url;
@@ -215,7 +224,7 @@
     ResourceResponse m_response;
     String m_responseEncoding;
 
-    RefPtr<TextResourceDecoder> m_decoder;
+    OwnPtr<TextResourceDecoder> m_decoder;
 
     ScriptString m_responseText;
     // Used to skip m_responseDocument creation if it's done previously. We need
diff --git a/Source/core/xml/XMLHttpRequest.idl b/Source/core/xml/XMLHttpRequest.idl
index 305ac87..f0a218f 100644
--- a/Source/core/xml/XMLHttpRequest.idl
+++ b/Source/core/xml/XMLHttpRequest.idl
@@ -53,14 +53,14 @@
     const unsigned short LOADING = 3;
     const unsigned short DONE = 4;
 
-    [SetterRaisesException] attribute unsigned long timeout;
+    [RaisesException=Setter] attribute unsigned long timeout;
     readonly attribute unsigned short readyState;
 
-    [SetterRaisesException] attribute boolean withCredentials;
+    [RaisesException=Setter] attribute boolean withCredentials;
 
-    [Custom, ActivityLogging=AccessForAllWorlds, RaisesException] void open(DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password);
+    [Custom, ActivityLogging=ForAllWorlds, RaisesException] void open(DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password);
 
-    [ActivityLogging=AccessForAllWorlds, RaisesException] void setRequestHeader(DOMString header, DOMString value);
+    [ActivityLogging=ForAllWorlds, RaisesException] void setRequestHeader(DOMString header, DOMString value);
 
     [Custom, RaisesException] void send();
 
@@ -71,14 +71,14 @@
     // response
     [TreatReturnedNullStringAs=Undefined, RaisesException] DOMString getAllResponseHeaders();
     [TreatReturnedNullStringAs=Null, RaisesException] DOMString getResponseHeader(DOMString header);
-    [CustomGetter, GetterRaisesException] readonly attribute DOMString responseText; // The custom getter implements TreatReturnedNullStringAs=Null
-    [GetterRaisesException] readonly attribute Document responseXML;
+    [Custom=Getter, RaisesException=Getter] readonly attribute DOMString responseText; // The custom getter implements TreatReturnedNullStringAs=Null
+    [RaisesException=Getter] readonly attribute Document responseXML;
 
-    [SetterRaisesException] attribute XMLHttpRequestResponseType responseType;
-    [CustomGetter, GetterRaisesException] readonly attribute Object response;
+    [RaisesException=Setter] attribute XMLHttpRequestResponseType responseType;
+    [Custom=Getter, RaisesException=Getter] readonly attribute object response;
 
-    [GetterRaisesException] readonly attribute unsigned short status;
-    [GetterRaisesException] readonly attribute DOMString statusText;
+    [RaisesException=Getter] readonly attribute unsigned short status;
+    [RaisesException=Getter] readonly attribute DOMString statusText;
 
     // Extension
     void overrideMimeType(DOMString override);
diff --git a/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp b/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp
index 212bf9d..9a3c16c 100644
--- a/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp
+++ b/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp
@@ -77,8 +77,10 @@
 
 void XMLHttpRequestProgressEventThrottle::dispatchReadyStateChangeEvent(PassRefPtr<Event> event, ProgressEventAction progressEventAction)
 {
-    if (progressEventAction == FlushProgressEvent)
-        flushProgressEvent();
+    if (progressEventAction == FlushProgressEvent || progressEventAction == FlushDeferredProgressEvent) {
+        if (!flushDeferredProgressEvent() && progressEventAction == FlushProgressEvent)
+            deliverProgressEvent();
+    }
 
     dispatchEvent(event);
 }
@@ -96,23 +98,27 @@
         m_target->dispatchEvent(event);
 }
 
-void XMLHttpRequestProgressEventThrottle::dispatchEventAndLoadEnd(PassRefPtr<Event> event)
+void XMLHttpRequestProgressEventThrottle::dispatchEventAndLoadEnd(const AtomicString& type, bool lengthComputable, unsigned long long bytesSent, unsigned long long total)
 {
-    ASSERT(event->type() == EventTypeNames::load || event->type() == EventTypeNames::abort || event->type() == EventTypeNames::error || event->type() == EventTypeNames::timeout);
+    ASSERT(type == EventTypeNames::load || type == EventTypeNames::abort || type == EventTypeNames::error || type == EventTypeNames::timeout);
 
-    dispatchEvent(event);
-    dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadend));
+    dispatchEvent(XMLHttpRequestProgressEvent::create(type, lengthComputable, bytesSent, total));
+    dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadend, lengthComputable, bytesSent, total));
 }
 
-void XMLHttpRequestProgressEventThrottle::flushProgressEvent()
+bool XMLHttpRequestProgressEventThrottle::flushDeferredProgressEvent()
 {
     if (m_deferEvents && m_deferredProgressEvent) {
         // Move the progress event to the queue, to get it in the right order on resume.
         m_deferredEvents.append(m_deferredProgressEvent);
         m_deferredProgressEvent = 0;
-        return;
+        return true;
     }
+    return false;
+}
 
+void XMLHttpRequestProgressEventThrottle::deliverProgressEvent()
+{
     if (!hasEventToDispatch())
         return;
 
diff --git a/Source/core/xml/XMLHttpRequestProgressEventThrottle.h b/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
index 36eddc5..36f5e3a 100644
--- a/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
+++ b/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
@@ -30,6 +30,7 @@
 #include "platform/Timer.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -38,6 +39,7 @@
 
 enum ProgressEventAction {
     DoNotFlushProgressEvent,
+    FlushDeferredProgressEvent,
     FlushProgressEvent
 };
 
@@ -51,7 +53,7 @@
     void dispatchProgressEvent(bool lengthComputable, unsigned long long loaded, unsigned long long total);
     void dispatchReadyStateChangeEvent(PassRefPtr<Event>, ProgressEventAction = DoNotFlushProgressEvent);
     void dispatchEvent(PassRefPtr<Event>);
-    void dispatchEventAndLoadEnd(PassRefPtr<Event>);
+    void dispatchEventAndLoadEnd(const AtomicString&, bool, unsigned long long, unsigned long long);
 
     void suspend();
     void resume();
@@ -61,7 +63,8 @@
 
     virtual void fired();
     void dispatchDeferredEvents(Timer<XMLHttpRequestProgressEventThrottle>*);
-    void flushProgressEvent();
+    bool flushDeferredProgressEvent();
+    void deliverProgressEvent();
 
     bool hasEventToDispatch() const;
 
diff --git a/Source/core/xml/XMLHttpRequestUpload.cpp b/Source/core/xml/XMLHttpRequestUpload.cpp
index d9fd5f6..5848305 100644
--- a/Source/core/xml/XMLHttpRequestUpload.cpp
+++ b/Source/core/xml/XMLHttpRequestUpload.cpp
@@ -37,6 +37,8 @@
 
 XMLHttpRequestUpload::XMLHttpRequestUpload(XMLHttpRequest* xmlHttpRequest)
     : m_xmlHttpRequest(xmlHttpRequest)
+    , m_lastBytesSent(0)
+    , m_lastTotalBytesToBeSent(0)
 {
     ScriptWrappable::init(this);
 }
@@ -51,14 +53,25 @@
     return m_xmlHttpRequest->executionContext();
 }
 
-void XMLHttpRequestUpload::dispatchEventAndLoadEnd(PassRefPtr<Event> event)
+void XMLHttpRequestUpload::dispatchProgressEvent(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
-    ASSERT(event->type() == EventTypeNames::load || event->type() == EventTypeNames::abort || event->type() == EventTypeNames::error || event->type() == EventTypeNames::timeout);
-
-    dispatchEvent(event);
-    dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadend));
+    m_lastBytesSent = bytesSent;
+    m_lastTotalBytesToBeSent = totalBytesToBeSent;
+    dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::progress, true, bytesSent, totalBytesToBeSent));
 }
 
+void XMLHttpRequestUpload::dispatchEventAndLoadEnd(const AtomicString& type, bool lengthComputable, unsigned long long bytesSent, unsigned long long total)
+{
+    ASSERT(type == EventTypeNames::load || type == EventTypeNames::abort || type == EventTypeNames::error || type == EventTypeNames::timeout);
+    dispatchEvent(XMLHttpRequestProgressEvent::create(type, lengthComputable, bytesSent, total));
+    dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadend, lengthComputable, bytesSent, total));
+}
 
+void XMLHttpRequestUpload::handleRequestError(const AtomicString& type)
+{
+    bool lengthComputable = m_lastTotalBytesToBeSent > 0 && m_lastBytesSent <= m_lastTotalBytesToBeSent;
+    dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::progress, lengthComputable, m_lastBytesSent, m_lastTotalBytesToBeSent));
+    dispatchEventAndLoadEnd(type, lengthComputable, m_lastBytesSent, m_lastTotalBytesToBeSent);
+}
 
 } // namespace WebCore
diff --git a/Source/core/xml/XMLHttpRequestUpload.h b/Source/core/xml/XMLHttpRequestUpload.h
index f9a8d14..d7a63da 100644
--- a/Source/core/xml/XMLHttpRequestUpload.h
+++ b/Source/core/xml/XMLHttpRequestUpload.h
@@ -58,7 +58,10 @@
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE;
 
-    void dispatchEventAndLoadEnd(PassRefPtr<Event>);
+    void dispatchEventAndLoadEnd(const AtomicString&, bool, unsigned long long, unsigned long long);
+    void dispatchProgressEvent(unsigned long long, unsigned long long);
+
+    void handleRequestError(const AtomicString&);
 
 private:
     explicit XMLHttpRequestUpload(XMLHttpRequest*);
@@ -68,6 +71,11 @@
 
     XMLHttpRequest* m_xmlHttpRequest;
     EventTargetData m_eventTargetData;
+
+    // Last progress event values; used when issuing the
+    // required 'progress' event on a request error or abort.
+    unsigned long long m_lastBytesSent;
+    unsigned long long m_lastTotalBytesToBeSent;
 };
 
 } // namespace WebCore
diff --git a/Source/core/xml/XMLSerializer.cpp b/Source/core/xml/XMLSerializer.cpp
index eb17e92..7c42e56 100644
--- a/Source/core/xml/XMLSerializer.cpp
+++ b/Source/core/xml/XMLSerializer.cpp
@@ -29,10 +29,10 @@
 
 namespace WebCore {
 
-String XMLSerializer::serializeToString(Node* node, ExceptionState& es)
+String XMLSerializer::serializeToString(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        es.throwDOMException(TypeError, "Invalid node value.");
+        exceptionState.throwDOMException(TypeError, "Invalid node value.");
         return String();
     }
 
diff --git a/Source/core/xml/XPathEvaluator.cpp b/Source/core/xml/XPathEvaluator.cpp
index 32dce9a..bd478fc 100644
--- a/Source/core/xml/XPathEvaluator.cpp
+++ b/Source/core/xml/XPathEvaluator.cpp
@@ -27,6 +27,7 @@
 #include "config.h"
 #include "core/xml/XPathEvaluator.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Node.h"
@@ -39,9 +40,9 @@
 
 using namespace XPath;
 
-PassRefPtr<XPathExpression> XPathEvaluator::createExpression(const String& expression, XPathNSResolver* resolver, ExceptionState& es)
+PassRefPtr<XPathExpression> XPathEvaluator::createExpression(const String& expression, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
 {
-    return XPathExpression::createExpression(expression, resolver, es);
+    return XPathExpression::createExpression(expression, resolver, exceptionState);
 }
 
 PassRefPtr<XPathNSResolver> XPathEvaluator::createNSResolver(Node* nodeResolver)
@@ -50,18 +51,23 @@
 }
 
 PassRefPtr<XPathResult> XPathEvaluator::evaluate(const String& expression, Node* contextNode,
-    XPathNSResolver* resolver, unsigned short type, XPathResult* result, ExceptionState& es)
+    PassRefPtr<XPathNSResolver> resolver, unsigned short type, XPathResult* result, ExceptionState& exceptionState)
 {
-    if (!isValidContextNode(contextNode)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+    if (!contextNode) {
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("evaluate", "XPathEvaluator", "The context node provided is null."));
         return 0;
     }
 
-    RefPtr<XPathExpression> expr = createExpression(expression, resolver, es);
-    if (es.hadException())
+    if (!isValidContextNode(contextNode)) {
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("evaluate", "XPathEvaluator", "The node provided is '" + contextNode->nodeName() + "', which is not a valid context node type."));
+        return 0;
+    }
+
+    RefPtr<XPathExpression> expr = createExpression(expression, resolver, exceptionState);
+    if (exceptionState.hadException())
         return 0;
 
-    return expr->evaluate(contextNode, type, result, es);
+    return expr->evaluate(contextNode, type, result, exceptionState);
 }
 
 }
diff --git a/Source/core/xml/XPathEvaluator.h b/Source/core/xml/XPathEvaluator.h
index 6ad05dc..0c556e7 100644
--- a/Source/core/xml/XPathEvaluator.h
+++ b/Source/core/xml/XPathEvaluator.h
@@ -44,10 +44,10 @@
 public:
     static PassRefPtr<XPathEvaluator> create() { return adoptRef(new XPathEvaluator); }
 
-    PassRefPtr<XPathExpression> createExpression(const String& expression, XPathNSResolver*, ExceptionState&);
+    PassRefPtr<XPathExpression> createExpression(const String& expression, PassRefPtr<XPathNSResolver>, ExceptionState&);
     PassRefPtr<XPathNSResolver> createNSResolver(Node* nodeResolver);
     PassRefPtr<XPathResult> evaluate(const String& expression, Node* contextNode,
-        XPathNSResolver*, unsigned short type, XPathResult*, ExceptionState&);
+        PassRefPtr<XPathNSResolver>, unsigned short type, XPathResult*, ExceptionState&);
 
 private:
     XPathEvaluator()
diff --git a/Source/core/xml/XPathExpression.cpp b/Source/core/xml/XPathExpression.cpp
index 0c80a54..a89d203 100644
--- a/Source/core/xml/XPathExpression.cpp
+++ b/Source/core/xml/XPathExpression.cpp
@@ -27,6 +27,7 @@
 #include "config.h"
 #include "core/xml/XPathExpression.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/xml/XPathExpressionNode.h"
@@ -40,12 +41,12 @@
 
 using namespace XPath;
 
-PassRefPtr<XPathExpression> XPathExpression::createExpression(const String& expression, XPathNSResolver* resolver, ExceptionState& es)
+PassRefPtr<XPathExpression> XPathExpression::createExpression(const String& expression, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
 {
     RefPtr<XPathExpression> expr = XPathExpression::create();
     Parser parser;
 
-    expr->m_topExpression = parser.parseStatement(expression, resolver, es);
+    expr->m_topExpression = parser.parseStatement(expression, resolver, exceptionState);
     if (!expr->m_topExpression)
         return 0;
 
@@ -57,10 +58,15 @@
     delete m_topExpression;
 }
 
-PassRefPtr<XPathResult> XPathExpression::evaluate(Node* contextNode, unsigned short type, XPathResult*, ExceptionState& es)
+PassRefPtr<XPathResult> XPathExpression::evaluate(Node* contextNode, unsigned short type, XPathResult*, ExceptionState& exceptionState)
 {
+    if (!contextNode) {
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("evaluate", "XPathExpression", "The context node provided is null."));
+        return 0;
+    }
+
     if (!isValidContextNode(contextNode)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("evaluate", "XPathExpression", "The node provided is '" + contextNode->nodeName() + "', which is not a valid context node type."));
         return 0;
     }
 
@@ -74,13 +80,13 @@
 
     if (evaluationContext.hadTypeConversionError) {
         // It is not specified what to do if type conversion fails while evaluating an expression.
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("evaluate", "XPathExpression", "Type conversion failed while evaluating the expression."));
         return 0;
     }
 
     if (type != XPathResult::ANY_TYPE) {
-        result->convertTo(type, es);
-        if (es.hadException())
+        result->convertTo(type, exceptionState);
+        if (exceptionState.hadException())
             return 0;
     }
 
diff --git a/Source/core/xml/XPathExpression.h b/Source/core/xml/XPathExpression.h
index 083a3f5..64a3cd3 100644
--- a/Source/core/xml/XPathExpression.h
+++ b/Source/core/xml/XPathExpression.h
@@ -48,7 +48,7 @@
     static PassRefPtr<XPathExpression> create() { return adoptRef(new XPathExpression); }
     ~XPathExpression();
 
-    static PassRefPtr<XPathExpression> createExpression(const String& expression, XPathNSResolver*, ExceptionState&);
+    static PassRefPtr<XPathExpression> createExpression(const String& expression, PassRefPtr<XPathNSResolver>, ExceptionState&);
     PassRefPtr<XPathResult> evaluate(Node* contextNode, unsigned short type, XPathResult*, ExceptionState&);
 
 private:
diff --git a/Source/core/xml/XPathNodeSet.cpp b/Source/core/xml/XPathNodeSet.cpp
index c621994..fa8d2d7 100644
--- a/Source/core/xml/XPathNodeSet.cpp
+++ b/Source/core/xml/XPathNodeSet.cpp
@@ -207,7 +207,7 @@
     Vector<RefPtr<Node> > sortedNodes;
     sortedNodes.reserveInitialCapacity(nodeCount);
 
-    for (Node* n = findRootNode(m_nodes.first().get()); n; n = NodeTraversal::next(n)) {
+    for (Node* n = findRootNode(m_nodes.first().get()); n; n = NodeTraversal::next(*n)) {
         if (nodes.contains(n))
             sortedNodes.append(n);
 
diff --git a/Source/core/xml/XPathParser.cpp b/Source/core/xml/XPathParser.cpp
index d7339af..fc8354b 100644
--- a/Source/core/xml/XPathParser.cpp
+++ b/Source/core/xml/XPathParser.cpp
@@ -28,6 +28,7 @@
 #include "config.h"
 #include "core/xml/XPathParser.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/xml/XPathEvaluator.h"
@@ -464,7 +465,7 @@
     return true;
 }
 
-Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSResolver> resolver, ExceptionState& es)
+Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
 {
     reset(statement);
 
@@ -498,9 +499,9 @@
         m_topExpr = 0;
 
         if (m_gotNamespaceError)
-            es.throwUninformativeAndGenericDOMException(NamespaceError);
+            exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToExecute("createExpression", "XPathExpression", "The string '" + statement + "' contains unresolvable namespaces."));
         else
-            es.throwUninformativeAndGenericDOMException(SyntaxError);
+            exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("createExpression", "XPathExpression", "The string '" + statement + "' is not a valid XPath expression."));
         return 0;
     }
 
diff --git a/Source/core/xml/XPathResult.cpp b/Source/core/xml/XPathResult.cpp
index 99973d9..7769d94 100644
--- a/Source/core/xml/XPathResult.cpp
+++ b/Source/core/xml/XPathResult.cpp
@@ -27,6 +27,7 @@
 #include "config.h"
 #include "core/xml/XPathResult.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
@@ -67,7 +68,7 @@
 {
 }
 
-void XPathResult::convertTo(unsigned short type, ExceptionState& es)
+void XPathResult::convertTo(unsigned short type, ExceptionState& exceptionState)
 {
     switch (type) {
         case ANY_TYPE:
@@ -89,14 +90,14 @@
         case ANY_UNORDERED_NODE_TYPE:
         case FIRST_ORDERED_NODE_TYPE: // This is correct - singleNodeValue() will take care of ordering.
             if (!m_value.isNodeSet()) {
-                es.throwUninformativeAndGenericTypeError();
+                exceptionState.throwTypeError(ExceptionMessages::failedToExecute("evaluate", "XPathExpression", "The result is not a node set, and therefore cannot be converted to the desired type."));
                 return;
             }
             m_resultType = type;
             break;
         case ORDERED_NODE_ITERATOR_TYPE:
             if (!m_value.isNodeSet()) {
-                es.throwUninformativeAndGenericTypeError();
+                exceptionState.throwTypeError(ExceptionMessages::failedToExecute("evaluate", "XPathExpression", "The result is not a node set, and therefore cannot be converted to the desired type."));
                 return;
             }
             m_nodeSet.sort();
@@ -104,7 +105,7 @@
             break;
         case ORDERED_NODE_SNAPSHOT_TYPE:
             if (!m_value.isNodeSet()) {
-                es.throwUninformativeAndGenericTypeError();
+                exceptionState.throwTypeError(ExceptionMessages::failedToExecute("evaluate", "XPathExpression", "The result is not a node set, and therefore cannot be converted to the desired type."));
                 return;
             }
             m_value.toNodeSet().sort();
@@ -118,37 +119,37 @@
     return m_resultType;
 }
 
-double XPathResult::numberValue(ExceptionState& es) const
+double XPathResult::numberValue(ExceptionState& exceptionState) const
 {
     if (resultType() != NUMBER_TYPE) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError(ExceptionMessages::failedToGet("numberValue", "XPathResult", "The result type is not a number."));
         return 0.0;
     }
     return m_value.toNumber();
 }
 
-String XPathResult::stringValue(ExceptionState& es) const
+String XPathResult::stringValue(ExceptionState& exceptionState) const
 {
     if (resultType() != STRING_TYPE) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError(ExceptionMessages::failedToGet("stringValue", "XPathResult", "The result type is not a string."));
         return String();
     }
     return m_value.toString();
 }
 
-bool XPathResult::booleanValue(ExceptionState& es) const
+bool XPathResult::booleanValue(ExceptionState& exceptionState) const
 {
     if (resultType() != BOOLEAN_TYPE) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError(ExceptionMessages::failedToGet("booleanValue", "XPathResult", "The result type is not a boolean."));
         return false;
     }
     return m_value.toBoolean();
 }
 
-Node* XPathResult::singleNodeValue(ExceptionState& es) const
+Node* XPathResult::singleNodeValue(ExceptionState& exceptionState) const
 {
     if (resultType() != ANY_UNORDERED_NODE_TYPE && resultType() != FIRST_ORDERED_NODE_TYPE) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError(ExceptionMessages::failedToGet("singleNodeValue", "XPathResult", "The result type is not a single node."));
         return 0;
     }
 
@@ -168,25 +169,25 @@
     return m_document->domTreeVersion() != m_domTreeVersion;
 }
 
-unsigned long XPathResult::snapshotLength(ExceptionState& es) const
+unsigned long XPathResult::snapshotLength(ExceptionState& exceptionState) const
 {
     if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError(ExceptionMessages::failedToGet("snapshotLength", "XPathResult", "The result type is not a snapshot."));
         return 0;
     }
 
     return m_value.toNodeSet().size();
 }
 
-Node* XPathResult::iterateNext(ExceptionState& es)
+Node* XPathResult::iterateNext(ExceptionState& exceptionState)
 {
     if (resultType() != UNORDERED_NODE_ITERATOR_TYPE && resultType() != ORDERED_NODE_ITERATOR_TYPE) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError(ExceptionMessages::failedToExecute("iterateNext", "XPathResult", "The result type is not an iterator."));
         return 0;
     }
 
     if (invalidIteratorState()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("iterateNext", "XPathResult", "The document has mutated since the result was returned."));
         return 0;
     }
 
@@ -200,10 +201,10 @@
     return node;
 }
 
-Node* XPathResult::snapshotItem(unsigned long index, ExceptionState& es)
+Node* XPathResult::snapshotItem(unsigned long index, ExceptionState& exceptionState)
 {
     if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
-        es.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError(ExceptionMessages::failedToExecute("snapshotItem", "XPathResult", "The result type is not a snapshot."));
         return 0;
     }
 
diff --git a/Source/core/xml/XPathResult.idl b/Source/core/xml/XPathResult.idl
index 19cfb4c..dd5f9cf 100644
--- a/Source/core/xml/XPathResult.idl
+++ b/Source/core/xml/XPathResult.idl
@@ -31,16 +31,16 @@
     const unsigned short FIRST_ORDERED_NODE_TYPE        = 9;
 
     readonly attribute unsigned short  resultType;
-    [GetterRaisesException] readonly attribute double          numberValue;
+    [RaisesException=Getter] readonly attribute double          numberValue;
 
-    [GetterRaisesException] readonly attribute DOMString       stringValue;
+    [RaisesException=Getter] readonly attribute DOMString       stringValue;
 
-    [GetterRaisesException] readonly attribute boolean         booleanValue;
+    [RaisesException=Getter] readonly attribute boolean         booleanValue;
 
-    [GetterRaisesException] readonly attribute Node            singleNodeValue;
+    [RaisesException=Getter] readonly attribute Node            singleNodeValue;
 
     readonly attribute boolean         invalidIteratorState;
-    [GetterRaisesException] readonly attribute unsigned long   snapshotLength;
+    [RaisesException=Getter] readonly attribute unsigned long   snapshotLength;
 
     [RaisesException] Node iterateNext();
     [RaisesException] Node snapshotItem([Default=Undefined] optional unsigned long index);
diff --git a/Source/core/xml/XPathStep.cpp b/Source/core/xml/XPathStep.cpp
index daf8d30..4687257 100644
--- a/Source/core/xml/XPathStep.cpp
+++ b/Source/core/xml/XPathStep.cpp
@@ -143,6 +143,7 @@
     }
 }
 
+#if !ASSERT_DISABLED
 static inline Node::NodeType primaryNodeType(Step::Axis axis)
 {
     switch (axis) {
@@ -154,6 +155,7 @@
             return Node::ELEMENT_NODE;
     }
 }
+#endif
 
 // Evaluate NodeTest without considering merged predicates.
 static inline bool nodeMatchesBasicTest(Node* node, Step::Axis axis, const Step::NodeTest& nodeTest)
@@ -252,7 +254,7 @@
             if (context->isAttributeNode()) // In XPath model, attribute nodes do not have children.
                 return;
 
-            for (Node* n = context->firstChild(); n; n = NodeTraversal::next(n, context))
+            for (Node* n = context->firstChild(); n; n = NodeTraversal::next(*n, context))
                 if (nodeMatches(n, DescendantAxis, m_nodeTest))
                     nodes.append(n);
             return;
@@ -303,7 +305,7 @@
         case FollowingAxis:
             if (context->isAttributeNode()) {
                 Node* p = toAttr(context)->ownerElement();
-                while ((p = NodeTraversal::next(p))) {
+                while ((p = NodeTraversal::next(*p))) {
                     if (nodeMatches(p, FollowingAxis, m_nodeTest))
                         nodes.append(p);
                 }
@@ -312,7 +314,7 @@
                     for (Node* n = p->nextSibling(); n; n = n->nextSibling()) {
                         if (nodeMatches(n, FollowingAxis, m_nodeTest))
                             nodes.append(n);
-                        for (Node* c = n->firstChild(); c; c = NodeTraversal::next(c, n))
+                        for (Node* c = n->firstChild(); c; c = NodeTraversal::next(*c, n))
                             if (nodeMatches(c, FollowingAxis, m_nodeTest))
                                 nodes.append(c);
                     }
@@ -325,7 +327,7 @@
 
             Node* n = context;
             while (ContainerNode* parent = n->parentNode()) {
-                for (n = NodeTraversal::previous(n); n != parent; n = NodeTraversal::previous(n))
+                for (n = NodeTraversal::previous(*n); n != parent; n = NodeTraversal::previous(*n))
                     if (nodeMatches(n, PrecedingAxis, m_nodeTest))
                         nodes.append(n);
                 n = parent;
@@ -372,7 +374,7 @@
             if (context->isAttributeNode()) // In XPath model, attribute nodes do not have children.
                 return;
 
-            for (Node* n = context->firstChild(); n; n = NodeTraversal::next(n, context))
+            for (Node* n = context->firstChild(); n; n = NodeTraversal::next(*n, context))
             if (nodeMatches(n, DescendantOrSelfAxis, m_nodeTest))
                 nodes.append(n);
             return;
diff --git a/Source/core/xml/XPathUtil.cpp b/Source/core/xml/XPathUtil.cpp
index 5967efa..5e266fa 100644
--- a/Source/core/xml/XPathUtil.cpp
+++ b/Source/core/xml/XPathUtil.cpp
@@ -54,7 +54,7 @@
                 StringBuilder result;
                 result.reserveCapacity(1024);
 
-                for (Node* n = node->firstChild(); n; n = NodeTraversal::next(n, node)) {
+                for (Node* n = node->firstChild(); n; n = NodeTraversal::next(*n, node)) {
                     if (n->isTextNode()) {
                         const String& nodeValue = n->nodeValue();
                         result.append(nodeValue);
diff --git a/Source/core/xml/XSLStyleSheet.h b/Source/core/xml/XSLStyleSheet.h
index 8471795..17f9984 100644
--- a/Source/core/xml/XSLStyleSheet.h
+++ b/Source/core/xml/XSLStyleSheet.h
@@ -120,6 +120,8 @@
     XSLStyleSheet* m_parentStyleSheet;
 };
 
+DEFINE_TYPE_CASTS(XSLStyleSheet, StyleSheet, sheet, !sheet->isCSSStyleSheet(), !sheet.isCSSStyleSheet());
+
 } // namespace WebCore
 
 #endif // XSLStyleSheet_h
diff --git a/Source/core/xml/XSLTProcessor.cpp b/Source/core/xml/XSLTProcessor.cpp
index ea47745..61ca31b 100644
--- a/Source/core/xml/XSLTProcessor.cpp
+++ b/Source/core/xml/XSLTProcessor.cpp
@@ -24,13 +24,14 @@
 #include "core/xml/XSLTProcessor.h"
 
 #include "core/dom/DOMImplementation.h"
+#include "core/dom/DocumentEncodingData.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/editing/markup.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Assertions.h"
 #include "wtf/Vector.h"
 
@@ -90,7 +91,9 @@
         result = DOMWindow::createDocument(sourceMIMEType, init, forceXHTML);
     }
 
-    result->setEncoding(sourceEncoding.isEmpty() ? UTF8Encoding() : WTF::TextEncoding(sourceEncoding));
+    DocumentEncodingData data;
+    data.encoding = sourceEncoding.isEmpty() ? UTF8Encoding() : WTF::TextEncoding(sourceEncoding);
+    result->setEncodingData(data);
     result->setContent(documentSource);
 
     return result.release();
diff --git a/Source/core/xml/XSLTProcessorLibxslt.cpp b/Source/core/xml/XSLTProcessorLibxslt.cpp
index 9e77718..18f571d 100644
--- a/Source/core/xml/XSLTProcessorLibxslt.cpp
+++ b/Source/core/xml/XSLTProcessorLibxslt.cpp
@@ -44,7 +44,7 @@
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Assertions.h"
 #include "wtf/Vector.h"
 #include "wtf/text/CString.h"
@@ -102,8 +102,8 @@
         xmlFree(base);
 
         ResourceLoaderOptions fetchOptions(ResourceFetcher::defaultResourceOptions());
-        fetchOptions.requestOriginPolicy = RestrictToSameOrigin;
         FetchRequest request(ResourceRequest(url), FetchInitiatorTypeNames::xml, fetchOptions);
+        request.setOriginRestriction(FetchRequest::RestrictToSameOrigin);
         ResourcePtr<Resource> resource = globalResourceFetcher->fetchSynchronously(request);
         if (!resource || !globalProcessor)
             return 0;
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index 5d6a1eb..d07e642 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -55,7 +55,7 @@
 #include "core/html/parser/HTMLEntityParser.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ImageLoader.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
 #include "core/xml/XMLErrors.h"
 #include "core/xml/XMLTreeViewer.h"
 #include "core/xml/parser/XMLDocumentParserScope.h"
@@ -64,7 +64,7 @@
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/StringExtras.h"
 #include "wtf/TemporaryChange.h"
 #include "wtf/Threading.h"
@@ -474,8 +474,8 @@
     if (errorOccurred)
         scriptLoader->dispatchErrorEvent();
     else if (!wasCanceled) {
-        scriptLoader->executeScript(sourceCode);
-        scriptLoader->dispatchLoadEvent();
+        if (scriptLoader->executePotentiallyCrossOriginScript(sourceCode))
+            scriptLoader->dispatchLoadEvent();
     }
 
     m_scriptElement = 0;
@@ -885,7 +885,7 @@
     }
 
     // FIXME: Why is this here?  And why is it after we process the passed source?
-    if (document()->decoder() && document()->decoder()->sawError()) {
+    if (document()->sawDecodingError()) {
         // If the decoder saw an error, report it as fatal (stops parsing)
         TextPosition position(OrdinalNumber::fromOneBasedInt(context->context()->input->line), OrdinalNumber::fromOneBasedInt(context->context()->input->col));
         handleError(XMLErrors::fatal, "Encoding error", position);
@@ -898,7 +898,7 @@
 };
 typedef struct _xmlSAX2Namespace xmlSAX2Namespace;
 
-static inline void handleNamespaceAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlNamespaces, int nbNamespaces, ExceptionState& es)
+static inline void handleNamespaceAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlNamespaces, int nbNamespaces, ExceptionState& exceptionState)
 {
     xmlSAX2Namespace* namespaces = reinterpret_cast<xmlSAX2Namespace*>(libxmlNamespaces);
     for (int i = 0; i < nbNamespaces; i++) {
@@ -908,7 +908,7 @@
             namespaceQName = "xmlns:" + toString(namespaces[i].prefix);
 
         QualifiedName parsedName = anyName;
-        if (!Element::parseAttributeName(parsedName, XMLNSNames::xmlnsNamespaceURI, namespaceQName, es))
+        if (!Element::parseAttributeName(parsedName, XMLNSNames::xmlnsNamespaceURI, namespaceQName, exceptionState))
             return;
 
         prefixedAttributes.append(Attribute(parsedName, namespaceURI));
@@ -924,7 +924,7 @@
 };
 typedef struct _xmlSAX2Attributes xmlSAX2Attributes;
 
-static inline void handleElementAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlAttributes, int nbAttributes, ExceptionState& es)
+static inline void handleElementAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlAttributes, int nbAttributes, ExceptionState& exceptionState)
 {
     xmlSAX2Attributes* attributes = reinterpret_cast<xmlSAX2Attributes*>(libxmlAttributes);
     for (int i = 0; i < nbAttributes; i++) {
@@ -935,7 +935,7 @@
         AtomicString attrQName = attrPrefix.isEmpty() ? toAtomicString(attributes[i].localname) : attrPrefix + ":" + toString(attributes[i].localname);
 
         QualifiedName parsedName = anyName;
-        if (!Element::parseAttributeName(parsedName, attrURI, attrQName, es))
+        if (!Element::parseAttributeName(parsedName, attrURI, attrQName, exceptionState))
             return;
 
         prefixedAttributes.append(Attribute(parsedName, attrValue));
@@ -975,17 +975,17 @@
     }
 
     Vector<Attribute> prefixedAttributes;
-    TrackExceptionState es;
-    handleNamespaceAttributes(prefixedAttributes, libxmlNamespaces, nbNamespaces, es);
-    if (es.hadException()) {
+    TrackExceptionState exceptionState;
+    handleNamespaceAttributes(prefixedAttributes, libxmlNamespaces, nbNamespaces, exceptionState);
+    if (exceptionState.hadException()) {
         setAttributes(newElement.get(), prefixedAttributes, parserContentPolicy());
         stopParsing();
         return;
     }
 
-    handleElementAttributes(prefixedAttributes, libxmlAttributes, nbAttributes, es);
+    handleElementAttributes(prefixedAttributes, libxmlAttributes, nbAttributes, exceptionState);
     setAttributes(newElement.get(), prefixedAttributes, parserContentPolicy());
-    if (es.hadException()) {
+    if (exceptionState.hadException()) {
         stopParsing();
         return;
     }
@@ -1142,9 +1142,9 @@
     exitText();
 
     // ### handle exceptions
-    TrackExceptionState es;
-    RefPtr<ProcessingInstruction> pi = m_currentNode->document().createProcessingInstruction(target, data, es);
-    if (es.hadException())
+    TrackExceptionState exceptionState;
+    RefPtr<ProcessingInstruction> pi = m_currentNode->document().createProcessingInstruction(target, data, exceptionState);
+    if (exceptionState.hadException())
         return;
 
     pi->setCreatedByParser(true);