Merge from Chromium at DEPS revision r219274

This commit was generated by merge_to_master.py.

Change-Id: I4217737c165f68da34d720aa074431613911dc68
diff --git a/Source/core/accessibility/AXObjectCache.cpp b/Source/core/accessibility/AXObjectCache.cpp
index cea4bcd..ef76297 100644
--- a/Source/core/accessibility/AXObjectCache.cpp
+++ b/Source/core/accessibility/AXObjectCache.cpp
@@ -943,9 +943,7 @@
     if (!obj || !obj->document() || !obj->documentFrameView() || !obj->documentFrameView()->frame() || !obj->documentFrameView()->frame()->page())
         return;
 
-    ChromeClient* client = obj->documentFrameView()->frame()->page()->chrome().client();
-    if (!client)
-        return;
+    ChromeClient& client = obj->documentFrameView()->frame()->page()->chrome().client();
 
     switch (notification) {
     case AXActiveDescendantChanged:
@@ -978,7 +976,7 @@
         break;
     }
 
-    client->postAccessibilityNotification(obj, notification);
+    client.postAccessibilityNotification(obj, notification);
 }
 
 void AXObjectCache::nodeTextChangePlatformNotification(AccessibilityObject*, AXTextChange, unsigned, const String&)
diff --git a/Source/core/accessibility/AccessibilityImageMapLink.cpp b/Source/core/accessibility/AccessibilityImageMapLink.cpp
index 2868199..91a43e1 100644
--- a/Source/core/accessibility/AccessibilityImageMapLink.cpp
+++ b/Source/core/accessibility/AccessibilityImageMapLink.cpp
@@ -46,6 +46,13 @@
 {
 }
 
+void AccessibilityImageMapLink::detachFromParent()
+{
+    AccessibilityMockObject::detachFromParent();
+    m_areaElement = 0;
+    m_mapElement = 0;
+}
+
 PassRefPtr<AccessibilityImageMapLink> AccessibilityImageMapLink::create()
 {
     return adoptRef(new AccessibilityImageMapLink());
diff --git a/Source/core/accessibility/AccessibilityImageMapLink.h b/Source/core/accessibility/AccessibilityImageMapLink.h
index 83ed57b..92345dc 100644
--- a/Source/core/accessibility/AccessibilityImageMapLink.h
+++ b/Source/core/accessibility/AccessibilityImageMapLink.h
@@ -69,6 +69,8 @@
     RefPtr<HTMLAreaElement> m_areaElement;
     RefPtr<HTMLMapElement> m_mapElement;
 
+    virtual void detachFromParent() OVERRIDE;
+
     virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
     virtual bool isImageMapLink() const OVERRIDE { return true; }
 };
diff --git a/Source/core/accessibility/AccessibilityMenuListPopup.cpp b/Source/core/accessibility/AccessibilityMenuListPopup.cpp
index 82079e3..53fe8fd 100644
--- a/Source/core/accessibility/AccessibilityMenuListPopup.cpp
+++ b/Source/core/accessibility/AccessibilityMenuListPopup.cpp
@@ -66,7 +66,7 @@
 
 AccessibilityMenuListOption* AccessibilityMenuListPopup::menuListOptionAccessibilityObject(HTMLElement* element) const
 {
-    if (!element || !element->hasTagName(optionTag))
+    if (!element || !element->hasTagName(optionTag) || !element->attached())
         return 0;
 
     AccessibilityObject* object = document()->axObjectCache()->getOrCreate(MenuListOptionRole);
diff --git a/Source/core/accessibility/AccessibilityMockObject.h b/Source/core/accessibility/AccessibilityMockObject.h
index b52cdad..6ea6a59 100644
--- a/Source/core/accessibility/AccessibilityMockObject.h
+++ b/Source/core/accessibility/AccessibilityMockObject.h
@@ -46,12 +46,13 @@
 protected:
     AccessibilityObject* m_parent;
 
+    // Must be called when the parent object clears its children.
+    virtual void detachFromParent() OVERRIDE { m_parent = 0; }
+
 private:
     virtual bool isMockObject() const OVERRIDE { return true; }
 
     virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-    // Must be called when the parent object clears its children.
-    virtual void detachFromParent() OVERRIDE { m_parent = 0; }
 };
 
 inline AccessibilityMockObject* toAccessibilityMockObject(AccessibilityObject* object)
diff --git a/Source/core/accessibility/AccessibilityRenderObject.cpp b/Source/core/accessibility/AccessibilityRenderObject.cpp
index 8c32759..bce08a2 100644
--- a/Source/core/accessibility/AccessibilityRenderObject.cpp
+++ b/Source/core/accessibility/AccessibilityRenderObject.cpp
@@ -35,7 +35,8 @@
 #include "core/accessibility/AccessibilitySVGRoot.h"
 #include "core/accessibility/AccessibilitySpinButton.h"
 #include "core/accessibility/AccessibilityTable.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/RenderedPosition.h"
 #include "core/editing/VisibleUnits.h"
@@ -46,6 +47,7 @@
 #include "core/html/HTMLOptionElement.h"
 #include "core/html/HTMLSelectElement.h"
 #include "core/html/HTMLTextAreaElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/loader/ProgressTracker.h"
 #include "core/page/Page.h"
 #include "core/platform/LocalizedStrings.h"
@@ -304,7 +306,7 @@
     if (!box->canBeScrolledAndHasScrollableArea())
         return 0;
 
-    return box->layer();
+    return box->scrollableArea();
 }
 
 AccessibilityRole AccessibilityRenderObject::determineAccessibilityRole()
@@ -776,7 +778,7 @@
                 return true;
         }
 
-        if (isNativeImage()) {
+        if (isNativeImage() && m_renderer->isImage()) {
             // check for one-dimensional image
             RenderImage* image = toRenderImage(m_renderer);
             if (image->height() <= 1 || image->width() <= 1)
@@ -1325,7 +1327,7 @@
         dirty = true;
 
     if (box->canBeScrolledAndHasScrollableArea()) {
-        ScrollableArea* scrollableArea = box->layer();
+        ScrollableArea* scrollableArea = box->scrollableArea();
         if (scrollableArea && scrollableArea->scrollPosition() != m_cachedScrollPosition)
             dirty = true;
     }
@@ -1349,7 +1351,7 @@
     m_cachedFrameRect = box->frameRect();
 
     if (box->canBeScrolledAndHasScrollableArea()) {
-        ScrollableArea* scrollableArea = box->layer();
+        ScrollableArea* scrollableArea = box->scrollableArea();
         if (scrollableArea)
             m_cachedScrollPosition = scrollableArea->scrollPosition();
     }
@@ -1611,11 +1613,9 @@
     if (isLoaded())
         return 1.0;
 
-    Page* page = m_renderer->document()->page();
-    if (!page)
-        return 0;
-
-    return page->progress()->estimatedProgress();
+    if (Page* page = m_renderer->document()->page())
+        return page->progress().estimatedProgress();
+    return 0;
 }
 
 //
@@ -1694,7 +1694,7 @@
         return PlainTextRange();
 
     AccessibilityRole ariaRole = ariaRoleAttribute();
-    if (isNativeTextControl() && ariaRole == UnknownRole) {
+    if (isNativeTextControl() && ariaRole == UnknownRole && m_renderer->isTextControl()) {
         HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
         return PlainTextRange(textControl->selectionStart(), textControl->selectionEnd() - textControl->selectionStart());
     }
@@ -1717,7 +1717,7 @@
     if (isPasswordField())
         return String(); // need to return something distinct from empty string
 
-    if (isNativeTextControl()) {
+    if (isNativeTextControl() && m_renderer->isTextControl()) {
         HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
         return textControl->selectedText();
     }
@@ -1758,7 +1758,7 @@
 
 void AccessibilityRenderObject::setSelectedTextRange(const PlainTextRange& range)
 {
-    if (isNativeTextControl()) {
+    if (isNativeTextControl() && m_renderer->isTextControl()) {
         HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
         textControl->setSelectionRange(range.start, range.start + range.length);
         return;
@@ -1879,7 +1879,7 @@
     if (!m_renderer)
         return VisiblePosition();
 
-    if (isNativeTextControl())
+    if (isNativeTextControl() && m_renderer->isTextControl())
         return toRenderTextControl(m_renderer)->textFormControlElement()->visiblePositionForIndex(index);
 
     if (!allowsTextRanges() && !m_renderer->isText())
@@ -1902,7 +1902,7 @@
 
 int AccessibilityRenderObject::indexForVisiblePosition(const VisiblePosition& pos) const
 {
-    if (isNativeTextControl()) {
+    if (isNativeTextControl() && m_renderer->isTextControl()) {
         HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
         return textControl->indexForVisiblePosition(pos);
     }
@@ -2332,12 +2332,12 @@
         return;
 
     HTMLInputElement* input = toHTMLInputElement(node);
-    HTMLElement* spinButtonElement = input->innerSpinButtonElement();
+    Element* spinButtonElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton());
     if (!spinButtonElement || !spinButtonElement->isSpinButtonElement())
         return;
 
     AccessibilitySpinButton* axSpinButton = static_cast<AccessibilitySpinButton*>(axObjectCache()->getOrCreate(SpinButtonRole));
-    axSpinButton->setSpinButtonElement(static_cast<SpinButtonElement*>(spinButtonElement));
+    axSpinButton->setSpinButtonElement(toSpinButtonElement(spinButtonElement));
     axSpinButton->setParent(this);
     m_children.append(axSpinButton);
 }
diff --git a/Source/core/accessibility/AccessibilityScrollbar.cpp b/Source/core/accessibility/AccessibilityScrollbar.cpp
index b48f386..a7ed3ef 100644
--- a/Source/core/accessibility/AccessibilityScrollbar.cpp
+++ b/Source/core/accessibility/AccessibilityScrollbar.cpp
@@ -39,6 +39,12 @@
     ASSERT(scrollbar);
 }
 
+void AccessibilityScrollbar::detachFromParent()
+{
+    m_scrollbar = 0;
+    AccessibilityMockObject::detachFromParent();
+}
+
 PassRefPtr<AccessibilityScrollbar> AccessibilityScrollbar::create(Scrollbar* scrollbar)
 {
     return adoptRef(new AccessibilityScrollbar(scrollbar));
diff --git a/Source/core/accessibility/AccessibilityScrollbar.h b/Source/core/accessibility/AccessibilityScrollbar.h
index 2b8b7ad..fe0714a 100644
--- a/Source/core/accessibility/AccessibilityScrollbar.h
+++ b/Source/core/accessibility/AccessibilityScrollbar.h
@@ -44,6 +44,8 @@
 private:
     explicit AccessibilityScrollbar(Scrollbar*);
 
+    virtual void detachFromParent();
+
     virtual bool canSetValueAttribute() const OVERRIDE { return true; }
 
     virtual bool isAccessibilityScrollbar() const OVERRIDE { return true; }
diff --git a/Source/core/accessibility/AccessibilitySlider.cpp b/Source/core/accessibility/AccessibilitySlider.cpp
index e5129b0..c96a757 100644
--- a/Source/core/accessibility/AccessibilitySlider.cpp
+++ b/Source/core/accessibility/AccessibilitySlider.cpp
@@ -30,8 +30,10 @@
 #include "core/accessibility/AccessibilitySlider.h"
 
 #include "core/accessibility/AXObjectCache.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/shadow/SliderThumbElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
+#include "core/rendering/RenderObject.h"
 
 namespace WebCore {
 
@@ -161,7 +163,7 @@
     RenderObject* sliderRenderer = m_parent->renderer();
     if (!sliderRenderer || !sliderRenderer->isSlider())
         return LayoutRect();
-    return sliderThumbElementOf(sliderRenderer->node())->boundingBox();
+    return toElement(sliderRenderer->node())->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb())->boundingBox();
 }
 
 bool AccessibilitySliderThumb::computeAccessibilityIsIgnored() const
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/animation/AnimatableTransform.cpp
similarity index 64%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/animation/AnimatableTransform.cpp
index 133dab0..8606a25 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/animation/AnimatableTransform.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,26 +28,27 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
-
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "config.h"
+#include "core/animation/AnimatableTransform.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
-public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
+PassRefPtr<AnimatableTransform> AnimatableTransform::create(const TransformOperations& transform)
+{
+    return adoptRef(new AnimatableTransform(transform));
+}
 
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
-};
+PassRefPtr<AnimatableValue> AnimatableTransform::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+    const AnimatableTransform* transform = toAnimatableTransform(value);
+    return AnimatableTransform::create(transform->m_transform.blend(m_transform, fraction));
+}
+
+PassRefPtr<AnimatableValue> AnimatableTransform::addWith(const AnimatableValue* value) const
+{
+    const AnimatableTransform* transform = toAnimatableTransform(value);
+    return AnimatableTransform::create(m_transform.add(transform->m_transform));
+}
 
 } // namespace WebCore
 
-#endif
diff --git a/Source/core/animation/AnimatableTransform.h b/Source/core/animation/AnimatableTransform.h
new file mode 100644
index 0000000..a0e71df
--- /dev/null
+++ b/Source/core/animation/AnimatableTransform.h
@@ -0,0 +1,70 @@
+/*
+ * 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 AnimatableTransform_h
+#define AnimatableTransform_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/platform/graphics/transforms/TransformOperations.h"
+
+namespace WebCore {
+
+class AnimatableTransform : public AnimatableValue {
+public:
+    virtual ~AnimatableTransform() { }
+    static PassRefPtr<AnimatableTransform> create(const TransformOperations&);
+    const TransformOperations& transformOperations() const
+    {
+        return m_transform;
+    }
+
+protected:
+    virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+    explicit AnimatableTransform(const TransformOperations& transform)
+        : AnimatableValue(TypeTransform)
+        , m_transform(transform)
+    {
+    }
+    const TransformOperations m_transform;
+};
+
+inline const AnimatableTransform* toAnimatableTransform(const AnimatableValue* value)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(value && value->isTransform());
+    return static_cast<const AnimatableTransform*>(value);
+}
+
+} // namespace WebCore
+
+#endif // AnimatableTransform_h
+
diff --git a/Source/core/animation/AnimatableValue.h b/Source/core/animation/AnimatableValue.h
index 3145e0a..94a65d1 100644
--- a/Source/core/animation/AnimatableValue.h
+++ b/Source/core/animation/AnimatableValue.h
@@ -50,12 +50,14 @@
 
     bool isNumber() const { return m_type == TypeNumber; }
     bool isNeutral() const { return m_type == TypeNeutral; }
+    bool isTransform() const { return m_type == TypeTransform; }
     bool isUnknown() const { return m_type == TypeUnknown; }
 
 protected:
     enum AnimatableType {
         TypeNeutral,
         TypeNumber,
+        TypeTransform,
         TypeUnknown,
     };
 
diff --git a/Source/core/animation/Animation.cpp b/Source/core/animation/Animation.cpp
index 99ab654..0e801bb 100644
--- a/Source/core/animation/Animation.cpp
+++ b/Source/core/animation/Animation.cpp
@@ -37,12 +37,12 @@
 
 namespace WebCore {
 
-PassRefPtr<Animation> Animation::create(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<TimedItemEventDelegate> eventDelegate)
+PassRefPtr<Animation> Animation::create(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
 {
     return adoptRef(new Animation(target, effect, timing, eventDelegate));
 }
 
-Animation::Animation(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<TimedItemEventDelegate> eventDelegate)
+Animation::Animation(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
     : TimedItem(timing, eventDelegate)
     , m_target(target)
     , m_effect(effect)
diff --git a/Source/core/animation/Animation.h b/Source/core/animation/Animation.h
index 3401708..2635c9e 100644
--- a/Source/core/animation/Animation.h
+++ b/Source/core/animation/Animation.h
@@ -42,7 +42,7 @@
 class Animation FINAL : public TimedItem {
 
 public:
-    static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<TimedItemEventDelegate> = nullptr);
+    static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<EventDelegate> = nullptr);
 
     const AnimationEffect::CompositableValueMap* compositableValues() const
     {
@@ -57,7 +57,7 @@
     virtual void willDetach() OVERRIDE FINAL;
 
 private:
-    Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<TimedItemEventDelegate>);
+    Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<EventDelegate>);
 
     RefPtr<Element> m_target;
     RefPtr<AnimationEffect> m_effect;
diff --git a/Source/core/animation/DocumentTimeline.cpp b/Source/core/animation/DocumentTimeline.cpp
index 63ce0b3..07c8748 100644
--- a/Source/core/animation/DocumentTimeline.cpp
+++ b/Source/core/animation/DocumentTimeline.cpp
@@ -45,6 +45,7 @@
 DocumentTimeline::DocumentTimeline(Document* document)
     : m_currentTime(nullValue())
     , m_document(document)
+    , m_zeroTimeAsPerfTime(nullValue())
 {
     ASSERT(document);
 }
@@ -62,7 +63,10 @@
 
 void DocumentTimeline::serviceAnimations(double monotonicAnimationStartTime)
 {
-    m_currentTime = monotonicAnimationStartTime;
+    if (!isNull(m_zeroTimeAsPerfTime)) {
+        ASSERT(m_currentTime <= monotonicAnimationStartTime - m_zeroTimeAsPerfTime);
+        m_currentTime = monotonicAnimationStartTime - m_zeroTimeAsPerfTime;
+    }
 
     for (int i = m_players.size() - 1; i >= 0; --i) {
         if (!m_players[i]->update())
@@ -75,6 +79,14 @@
     dispatchEvents();
 }
 
+void DocumentTimeline::setZeroTimeAsPerfTime(double zeroTime)
+{
+    ASSERT(isNull(m_zeroTimeAsPerfTime));
+    m_zeroTimeAsPerfTime = zeroTime;
+    ASSERT(!isNull(m_zeroTimeAsPerfTime));
+    m_currentTime = 0;
+}
+
 void DocumentTimeline::pauseAnimationsForTesting(double pauseTime)
 {
     for (size_t i = 0; i < m_players.size(); i++) {
@@ -85,9 +97,17 @@
 
 void DocumentTimeline::dispatchEvents()
 {
-    for (size_t i = 0; i < m_events.size(); i++)
-        m_events[i].target->dispatchEvent(m_events[i].event.release());
+    Vector<EventToDispatch> events = m_events;
     m_events.clear();
+    for (size_t i = 0; i < events.size(); i++)
+        events[i].target->dispatchEvent(events[i].event.release());
+}
+
+size_t DocumentTimeline::numberOfActiveAnimationsForTesting() const
+{
+    // Includes all players whose directly associated timed items
+    // are current or in effect.
+    return isNull(m_currentTime) ? 0 : m_players.size();
 }
 
 } // namespace
diff --git a/Source/core/animation/DocumentTimeline.h b/Source/core/animation/DocumentTimeline.h
index f5e438f..56c4c38 100644
--- a/Source/core/animation/DocumentTimeline.h
+++ b/Source/core/animation/DocumentTimeline.h
@@ -51,8 +51,12 @@
     static PassRefPtr<DocumentTimeline> create(Document*);
     void serviceAnimations(double);
     PassRefPtr<Player> play(TimedItem*);
+    // Called from setReadyState() in Document.cpp to set m_zeroTimeAsPerfTime to
+    // performance.timing.domInteractive.
+    void setZeroTimeAsPerfTime(double);
     double currentTime() { return m_currentTime; }
     void pauseAnimationsForTesting(double);
+    size_t numberOfActiveAnimationsForTesting() const;
     AnimationStack* animationStack(const Element* element) const
     {
         if (ActiveAnimations* animations = element->activeAnimations())
@@ -68,6 +72,7 @@
     DocumentTimeline(Document*);
     void dispatchEvents();
     double m_currentTime;
+    double m_zeroTimeAsPerfTime;
     Document* m_document;
     Vector<RefPtr<Player> > m_players;
 
diff --git a/Source/core/animation/DocumentTimelineTest.cpp b/Source/core/animation/DocumentTimelineTest.cpp
index ca515be..9c2bf18 100644
--- a/Source/core/animation/DocumentTimelineTest.cpp
+++ b/Source/core/animation/DocumentTimelineTest.cpp
@@ -51,6 +51,8 @@
         document = Document::create();
         element = Element::create(nullQName() , document.get());
         timeline = DocumentTimeline::create(document.get());
+        timeline->setZeroTimeAsPerfTime(0);
+        ASSERT_EQ(0, timeline->currentTime());
     }
 
     RefPtr<Document> document;
@@ -64,10 +66,7 @@
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector());
     RefPtr<Animation> anim = Animation::create(element.get(), effect, timing);
 
-    EXPECT_TRUE(isNull(timeline->currentTime()));
-
     timeline->play(anim.get());
-    EXPECT_TRUE(isNull(timeline->currentTime()));
 
     timeline->serviceAnimations(0);
     EXPECT_FLOAT_EQ(0, timeline->currentTime());
@@ -77,6 +76,24 @@
     EXPECT_FLOAT_EQ(100, timeline->currentTime());
 }
 
+TEST_F(DocumentTimelineTest, ZeroTimeAsPerfTime)
+{
+    timeline = DocumentTimeline::create(document.get());
+
+    timeline->serviceAnimations(100);
+    EXPECT_TRUE(isNull(timeline->currentTime()));
+
+    timeline->serviceAnimations(200);
+    EXPECT_TRUE(isNull(timeline->currentTime()));
+
+    timeline->setZeroTimeAsPerfTime(300);
+    timeline->serviceAnimations(300);
+    EXPECT_EQ(0, timeline->currentTime());
+
+    timeline->serviceAnimations(400);
+    EXPECT_EQ(100, timeline->currentTime());
+}
+
 TEST_F(DocumentTimelineTest, PauseForTesting)
 {
     float seekTime = 1;
@@ -90,4 +107,47 @@
     EXPECT_FLOAT_EQ(seekTime, player2->currentTime());
 }
 
+TEST_F(DocumentTimelineTest, NumberOfActiveAnimations)
+{
+    Timing timingForwardFill;
+    timingForwardFill.hasIterationDuration = true;
+    timingForwardFill.iterationDuration = 2;
+
+    Timing timingNoFill;
+    timingNoFill.hasIterationDuration = true;
+    timingNoFill.iterationDuration = 2;
+    timingNoFill.fillMode = Timing::FillModeNone;
+
+    Timing timingBackwardFillDelay;
+    timingBackwardFillDelay.hasIterationDuration = true;
+    timingBackwardFillDelay.iterationDuration = 1;
+    timingBackwardFillDelay.fillMode = Timing::FillModeBackwards;
+    timingBackwardFillDelay.startDelay = 1;
+
+    Timing timingNoFillDelay;
+    timingNoFillDelay.hasIterationDuration = true;
+    timingNoFillDelay.iterationDuration = 1;
+    timingNoFillDelay.fillMode = Timing::FillModeNone;
+    timingNoFillDelay.startDelay = 1;
+
+    RefPtr<Animation> anim1 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingForwardFill);
+    RefPtr<Animation> anim2 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingNoFill);
+    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->serviceAnimations(0);
+    EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    timeline->serviceAnimations(0.5);
+    EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    timeline->serviceAnimations(1.5);
+    EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    timeline->serviceAnimations(3);
+    EXPECT_EQ(1U, timeline->numberOfActiveAnimationsForTesting());
+}
+
 }
diff --git a/Source/core/animation/Player.cpp b/Source/core/animation/Player.cpp
index 7af07e2..0d44da7 100644
--- a/Source/core/animation/Player.cpp
+++ b/Source/core/animation/Player.cpp
@@ -99,6 +99,7 @@
     if (!m_content)
         return;
 
+    ASSERT(m_content->player() == this);
     m_content->detach();
     m_content = 0;
 }
diff --git a/Source/core/animation/PlayerTest.cpp b/Source/core/animation/PlayerTest.cpp
index 26970a9..c4ff23e 100644
--- a/Source/core/animation/PlayerTest.cpp
+++ b/Source/core/animation/PlayerTest.cpp
@@ -48,6 +48,7 @@
         document = Document::create();
         timeline = DocumentTimeline::create(document.get());
         player = Player::create(timeline.get(), 0);
+        timeline->setZeroTimeAsPerfTime(0);
     }
 
     bool updateTimeline(double time)
@@ -64,7 +65,7 @@
 
 TEST_F(PlayerTest, InitialState)
 {
-    EXPECT_TRUE(isNull(timeline->currentTime()));
+    EXPECT_EQ(0, timeline->currentTime());
     EXPECT_EQ(0, player->currentTime());
     EXPECT_FALSE(player->paused());
     EXPECT_EQ(1, player->playbackRate());
diff --git a/Source/core/animation/TimedItem.cpp b/Source/core/animation/TimedItem.cpp
index 852123f..730a058 100644
--- a/Source/core/animation/TimedItem.cpp
+++ b/Source/core/animation/TimedItem.cpp
@@ -34,13 +34,14 @@
 
 namespace WebCore {
 
-TimedItem::TimedItem(const Timing& timing, PassOwnPtr<TimedItemEventDelegate> eventDelegate)
+TimedItem::TimedItem(const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
     : m_parent(0)
     , m_player(0)
     , m_startTime(0)
     , m_specified(timing)
     , m_calculated()
     , m_eventDelegate(eventDelegate)
+    , m_isFirstSample(true)
 {
     timing.assertValid();
 }
@@ -57,10 +58,10 @@
         ? repeatedDuration / abs(m_specified.playbackRate)
         : std::numeric_limits<double>::infinity();
 
-    const TimedItem::Phase phase = calculatePhase(activeDuration, localTime, m_specified);
+    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, phase, m_specified);
+    const double activeTime = calculateActiveTime(activeDuration, localTime, parentPhase, currentPhase, m_specified);
 
     double currentIteration = nullValue();
     double timeFraction = nullValue();
@@ -77,8 +78,8 @@
         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 phase = calculatePhase(activeDuration, newLocalTime, m_specified);
-        const double activeTime = calculateActiveTime(activeDuration, newLocalTime, parentPhase, phase, m_specified);
+        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);
@@ -87,32 +88,26 @@
         timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified);
     }
 
-    const double lastIteration = m_calculated.currentIteration;
+    const double previousIteration = m_calculated.currentIteration;
     m_calculated.currentIteration = currentIteration;
     m_calculated.activeDuration = activeDuration;
     m_calculated.timeFraction = timeFraction;
 
+    const Phase previousPhase = m_calculated.phase;
     const bool wasInEffect = m_calculated.isInEffect;
-    const bool wasInPlay = m_calculated.isInPlay;
+    m_calculated.phase = currentPhase;
     m_calculated.isInEffect = !isNull(activeTime);
-    m_calculated.isInPlay = phase == PhaseActive && (!m_parent || m_parent->isInPlay());
-    m_calculated.isCurrent = phase == PhaseBefore || isInPlay() || (m_parent && m_parent->isCurrent());
+    m_calculated.isInPlay = phase() == PhaseActive && (!m_parent || m_parent->isInPlay());
+    m_calculated.isCurrent = phase() == PhaseBefore || isInPlay() || (m_parent && m_parent->isCurrent());
 
-    if (m_eventDelegate && (isInPlay() != wasInPlay || (isInPlay() && lastIteration != currentIteration)))
-        m_eventDelegate->onEventCondition(wasInPlay, isInPlay(), lastIteration, currentIteration);
+    // This logic is specific to CSS animation events and assumes that all
+    // animations start after the DocumentTimeline has started.
+    if (m_eventDelegate && (m_isFirstSample || previousPhase != phase() || (phase() == PhaseActive && previousIteration != currentIteration)))
+        m_eventDelegate->onEventCondition(m_isFirstSample, previousPhase, phase(), previousIteration, currentIteration);
+    m_isFirstSample = false;
 
     // FIXME: This probably shouldn't be recursive.
     updateChildrenAndEffects(wasInEffect);
 }
 
-TimedItem::CalculatedTiming::CalculatedTiming()
-    : activeDuration(nullValue())
-    , currentIteration(nullValue())
-    , timeFraction(nullValue())
-    , isCurrent(false)
-    , isInEffect(false)
-    , isInPlay(false)
-{
-}
-
 } // namespace WebCore
diff --git a/Source/core/animation/TimedItem.h b/Source/core/animation/TimedItem.h
index 93b79a7..501a711 100644
--- a/Source/core/animation/TimedItem.h
+++ b/Source/core/animation/TimedItem.h
@@ -49,17 +49,26 @@
     return std::numeric_limits<double>::quiet_NaN();
 }
 
-class TimedItemEventDelegate {
-public:
-    virtual ~TimedItemEventDelegate() { };
-    virtual void onEventCondition(bool wasInPlay, bool isInPlay, double previousIteration, double currentIteration) = 0;
-};
-
 class TimedItem : public RefCounted<TimedItem> {
     friend class Player; // Calls attach/detach, updateInheritedTime.
 public:
+    // Note that logic in CSSAnimations depends on the order of these values.
+    enum Phase {
+        PhaseBefore,
+        PhaseActive,
+        PhaseAfter,
+        PhaseNone,
+    };
+
+    class EventDelegate {
+    public:
+        virtual ~EventDelegate() { };
+        virtual void onEventCondition(bool isFirstSample, Phase previousPhase, Phase currentPhase, double previousIteration, double currentIteration) = 0;
+    };
+
     virtual ~TimedItem() { }
 
+    Phase phase() const { return ensureCalculated().phase; }
     bool isCurrent() const { return ensureCalculated().isCurrent; }
     bool isInEffect() const { return ensureCalculated().isInEffect; }
     bool isInPlay() const { return ensureCalculated().isInPlay; }
@@ -71,15 +80,8 @@
     double timeFraction() const { return ensureCalculated().timeFraction; }
     Player* player() const { return m_player; }
 
-    enum Phase {
-        PhaseBefore,
-        PhaseActive,
-        PhaseAfter,
-        PhaseNone,
-    };
-
 protected:
-    TimedItem(const Timing&, PassOwnPtr<TimedItemEventDelegate> = nullptr);
+    TimedItem(const Timing&, PassOwnPtr<EventDelegate> = nullptr);
 
     // When TimedItem receives a new inherited time via updateInheritedTime
     // it will (if necessary) recalculate timings and (if necessary) call
@@ -103,18 +105,19 @@
     const double m_startTime;
     Player* m_player;
     Timing m_specified;
-    OwnPtr<TimedItemEventDelegate> m_eventDelegate;
+    OwnPtr<EventDelegate> m_eventDelegate;
 
     // FIXME: Should be versioned by monotonic value on player.
     mutable struct CalculatedTiming {
-        CalculatedTiming();
         double activeDuration;
+        Phase phase;
         double currentIteration;
         double timeFraction;
         bool isCurrent;
         bool isInEffect;
         bool isInPlay;
     } m_calculated;
+    mutable bool m_isFirstSample;
 
     // FIXME: Should check the version and reinherit time if inconsistent.
     const CalculatedTiming& ensureCalculated() const { return m_calculated; }
diff --git a/Source/core/animation/TimedItemTest.cpp b/Source/core/animation/TimedItemTest.cpp
index 22c10a4..9a8c630 100644
--- a/Source/core/animation/TimedItemTest.cpp
+++ b/Source/core/animation/TimedItemTest.cpp
@@ -37,30 +37,28 @@
 
 namespace {
 
-class TestTimedItemEventDelegate : public TimedItemEventDelegate {
+class TestTimedItemEventDelegate : public TimedItem::EventDelegate {
 public:
-    void onEventCondition(bool wasInPlay, bool isInPlay, double previousIteration, double currentIteration) OVERRIDE
+    void onEventCondition(bool isFirstSample, TimedItem::Phase previousPhase, TimedItem::Phase phase, double previousIteration, double currentIteration) OVERRIDE
     {
         m_eventTriggered = true;
-        m_playStateChanged = wasInPlay != isInPlay;
-        m_iterationChanged = isInPlay && previousIteration != currentIteration;
-        if (isInPlay)
-            ASSERT(!isNull(currentIteration));
+        m_phaseChanged = previousPhase != phase;
+        m_iterationChanged = previousIteration != currentIteration;
 
     }
     void reset()
     {
         m_eventTriggered = false;
-        m_playStateChanged = false;
+        m_phaseChanged = false;
         m_iterationChanged = false;
     }
     bool eventTriggered() { return m_eventTriggered; }
-    bool playStateChanged() { return m_playStateChanged; }
+    bool phaseChanged() { return m_phaseChanged; }
     bool iterationChanged() { return m_iterationChanged; }
 
 private:
     bool m_eventTriggered;
-    bool m_playStateChanged;
+    bool m_phaseChanged;
     bool m_iterationChanged;
 };
 
@@ -77,11 +75,8 @@
         TimedItem::updateInheritedTime(time);
     }
 
-    void updateChildrenAndEffects(bool wasActiveOrInEffect) const FINAL OVERRIDE {
-    }
-
+    void updateChildrenAndEffects(bool wasActiveOrInEffect) const FINAL OVERRIDE { }
     void willDetach() { }
-
     TestTimedItemEventDelegate* eventDelegate() { return m_eventDelegate; }
 
 private:
@@ -101,16 +96,11 @@
     timing.iterationDuration = 2;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_FALSE(timedItem->isInEffect());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
     ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_TRUE(isNull(timedItem->activeDuration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
 
+    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
     ASSERT_TRUE(timedItem->isInPlay());
     ASSERT_TRUE(timedItem->isCurrent());
     ASSERT_TRUE(timedItem->isInEffect());
@@ -121,6 +111,7 @@
 
     timedItem->updateInheritedTime(1);
 
+    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
     ASSERT_TRUE(timedItem->isInPlay());
     ASSERT_TRUE(timedItem->isCurrent());
     ASSERT_TRUE(timedItem->isInEffect());
@@ -131,6 +122,7 @@
 
     timedItem->updateInheritedTime(2);
 
+    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
     ASSERT_FALSE(timedItem->isInPlay());
     ASSERT_FALSE(timedItem->isCurrent());
     ASSERT_TRUE(timedItem->isInEffect());
@@ -141,6 +133,7 @@
 
     timedItem->updateInheritedTime(3);
 
+    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
     ASSERT_FALSE(timedItem->isInPlay());
     ASSERT_FALSE(timedItem->isCurrent());
     ASSERT_TRUE(timedItem->isInEffect());
@@ -332,16 +325,11 @@
     Timing timing;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_FALSE(timedItem->isInEffect());
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
     ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_TRUE(isNull(timedItem->activeDuration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
 
+    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
     ASSERT_FALSE(timedItem->isInPlay());
     ASSERT_FALSE(timedItem->isCurrent());
     ASSERT_TRUE(timedItem->isInEffect());
@@ -352,6 +340,7 @@
 
     timedItem->updateInheritedTime(1);
 
+    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
     ASSERT_FALSE(timedItem->isInPlay());
     ASSERT_FALSE(timedItem->isCurrent());
     ASSERT_TRUE(timedItem->isInEffect());
@@ -546,32 +535,42 @@
     timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
     timing.iterationCount = 2;
+    timing.startDelay = 1;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    timedItem->updateInheritedTime(0.3);
+    // First sample
+    timedItem->updateInheritedTime(0.0);
     ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
-    EXPECT_TRUE(timedItem->eventDelegate()->playStateChanged());
-    EXPECT_TRUE(timedItem->eventDelegate()->iterationChanged());
 
-    timedItem->updateInheritedTime(0.6);
+    // Before start
+    timedItem->updateInheritedTime(0.5);
     ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
 
+    // First iteration
     timedItem->updateInheritedTime(1.5);
     ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_TRUE(timedItem->eventDelegate()->phaseChanged());
     EXPECT_TRUE(timedItem->eventDelegate()->iterationChanged());
-    EXPECT_FALSE(timedItem->eventDelegate()->playStateChanged());
 
+    timedItem->updateInheritedTime(1.6);
+    ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+
+    // Second iteration
     timedItem->updateInheritedTime(2.5);
     ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
-    EXPECT_FALSE(timedItem->eventDelegate()->iterationChanged());
-    EXPECT_TRUE(timedItem->eventDelegate()->playStateChanged());
+    EXPECT_FALSE(timedItem->eventDelegate()->phaseChanged());
+    EXPECT_TRUE(timedItem->eventDelegate()->iterationChanged());
 
-    timedItem->updateInheritedTime(3);
+    timedItem->updateInheritedTime(2.6);
     ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
 
-    timedItem->updateInheritedTime(1.5);
+    // After end
+    timedItem->updateInheritedTime(3.5);
     ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_TRUE(timedItem->eventDelegate()->phaseChanged());
     EXPECT_FALSE(timedItem->eventDelegate()->iterationChanged());
-    EXPECT_TRUE(timedItem->eventDelegate()->playStateChanged());
+
+    timedItem->updateInheritedTime(3.6);
+    ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
 }
 }
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index 3d97ec3..7aac3b8 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -33,6 +33,7 @@
 
 #include "CSSValueKeywords.h"
 #include "core/animation/AnimatableNumber.h"
+#include "core/animation/AnimatableTransform.h"
 #include "core/animation/AnimatableUnknown.h"
 #include "core/platform/Length.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -50,19 +51,15 @@
 // CSSPropertyBorderBottomColor
 // CSSPropertyBorderBottomLeftRadius
 // CSSPropertyBorderBottomRightRadius
-// CSSPropertyBorderBottomWidth
 // CSSPropertyBorderImageOutset
 // CSSPropertyBorderImageSlice
 // CSSPropertyBorderImageSource
 // CSSPropertyBorderImageWidth
 // CSSPropertyBorderLeftColor
-// CSSPropertyBorderLeftWidth
 // CSSPropertyBorderRightColor
-// CSSPropertyBorderRightWidth
 // CSSPropertyBorderTopColor
 // CSSPropertyBorderTopLeftRadius
 // CSSPropertyBorderTopRightRadius
-// CSSPropertyBorderTopWidth
 // CSSPropertyBoxShadow
 // CSSPropertyClip
 // CSSPropertyColor
@@ -112,7 +109,6 @@
 // CSSPropertyWebkitShapeInside
 // CSSPropertyWebkitTextFillColor
 // CSSPropertyWebkitTextStrokeColor
-// CSSPropertyWebkitTransform
 // CSSPropertyWebkitTransformOriginZ
 // CSSPropertyWidows
 // CSSPropertyWordSpacing
@@ -167,6 +163,14 @@
 PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::create(CSSPropertyID property, const RenderStyle* style)
 {
     switch (property) {
+    case CSSPropertyBorderBottomWidth:
+        return createFromDouble(style->borderBottomWidth());
+    case CSSPropertyBorderLeftWidth:
+        return createFromDouble(style->borderLeftWidth());
+    case CSSPropertyBorderRightWidth:
+        return createFromDouble(style->borderRightWidth());
+    case CSSPropertyBorderTopWidth:
+        return createFromDouble(style->borderTopWidth());
     case CSSPropertyBottom:
         return createFromLength(style->bottom(), style);
     case CSSPropertyHeight:
@@ -207,6 +211,8 @@
         return createFromLength(style->perspectiveOriginX(), style);
     case CSSPropertyWebkitPerspectiveOriginY:
         return createFromLength(style->perspectiveOriginY(), style);
+    case CSSPropertyWebkitTransform:
+        return AnimatableTransform::create(style->transform());
     case CSSPropertyWebkitTransformOriginX:
         return createFromLength(style->transformOriginX(), style);
     case CSSPropertyWebkitTransformOriginY:
diff --git a/Source/core/animation/css/CSSAnimations.cpp b/Source/core/animation/css/CSSAnimations.cpp
index f3d06f2..444d015 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -42,6 +42,26 @@
 #include "core/platform/animation/TimingFunction.h"
 #include "wtf/HashSet.h"
 
+namespace {
+
+using namespace WebCore;
+
+bool isEarlierPhase(TimedItem::Phase target, TimedItem::Phase reference)
+{
+    ASSERT(target != TimedItem::PhaseNone);
+    ASSERT(reference != TimedItem::PhaseNone);
+    return target < reference;
+}
+
+bool isLaterPhase(TimedItem::Phase target, TimedItem::Phase reference)
+{
+    ASSERT(target != TimedItem::PhaseNone);
+    ASSERT(reference != TimedItem::PhaseNone);
+    return target > reference;
+}
+
+} // namespace
+
 namespace WebCore {
 
 void timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing)
@@ -189,6 +209,7 @@
                 Timing timing;
                 timingFromAnimationData(animationData, timing);
                 OwnPtr<CSSAnimations::EventDelegate> eventDelegate = adoptPtr(new EventDelegate(element, animationName));
+                ASSERT(!isNull(element->document()->timeline()->currentTime()));
                 // FIXME: crbug.com/268791 - Keyframes are already normalized, perhaps there should be a flag on KeyframeAnimationEffect to skip normalization.
                 m_animations.set(animationName.impl(), element->document()->timeline()->play(
                     Animation::create(element, KeyframeAnimationEffect::create(keyframes), timing, eventDelegate.release()).get()).get());
@@ -214,7 +235,7 @@
         m_target->document()->timeline()->addEventToDispatch(m_target, AnimationEvent::create(eventName, m_name, elapsedTime));
 }
 
-void CSSAnimations::EventDelegate::onEventCondition(bool wasInPlay, bool isInPlay, double previousIteration, double currentIteration)
+void CSSAnimations::EventDelegate::onEventCondition(bool isFirstSample, TimedItem::Phase previousPhase, TimedItem::Phase currentPhase, double previousIteration, double currentIteration)
 {
     // Events for a single document are queued and dispatched as a group at
     // the end of DocumentTimeline::serviceAnimations.
@@ -222,18 +243,16 @@
     // trigger a timer to dispatch when control is released.
     // FIXME: Receive TimedItem as param in order to produce correct elapsed time value.
     double elapsedTime = 0;
-    if (!wasInPlay && isInPlay) {
-        maybeDispatch(Document::ANIMATIONSTART_LISTENER, eventNames().webkitAnimationStartEvent, elapsedTime);
-        return;
-    }
-    if (wasInPlay && isInPlay && currentIteration != previousIteration) {
+    if (!isFirstSample && previousPhase == TimedItem::PhaseActive && currentPhase == TimedItem::PhaseActive && previousIteration != currentIteration) {
+        ASSERT(!isNull(previousIteration));
+        ASSERT(!isNull(currentIteration));
         maybeDispatch(Document::ANIMATIONITERATION_LISTENER, eventNames().webkitAnimationIterationEvent, elapsedTime);
         return;
     }
-    if (wasInPlay && !isInPlay) {
+    if ((isFirstSample || previousPhase == TimedItem::PhaseBefore) && isLaterPhase(currentPhase, TimedItem::PhaseBefore))
+        maybeDispatch(Document::ANIMATIONSTART_LISTENER, eventNames().webkitAnimationStartEvent, elapsedTime);
+    if ((isFirstSample || isEarlierPhase(previousPhase, TimedItem::PhaseAfter)) && currentPhase == TimedItem::PhaseAfter)
         maybeDispatch(Document::ANIMATIONEND_LISTENER, eventNames().webkitAnimationEndEvent, elapsedTime);
-        return;
-    }
 }
 
 } // namespace WebCore
diff --git a/Source/core/animation/css/CSSAnimations.h b/Source/core/animation/css/CSSAnimations.h
index 45dcf84..2f04c41 100644
--- a/Source/core/animation/css/CSSAnimations.h
+++ b/Source/core/animation/css/CSSAnimations.h
@@ -78,16 +78,16 @@
     bool isEmpty() const { return m_animations.isEmpty(); }
     void cancel();
 private:
-    typedef HashMap<StringImpl*, Player*> AnimationMap;
+    typedef HashMap<StringImpl*, RefPtr<Player> > AnimationMap;
     AnimationMap m_animations;
-    class EventDelegate FINAL : public TimedItemEventDelegate {
+    class EventDelegate FINAL : public TimedItem::EventDelegate {
     public:
         EventDelegate(Element* target, const AtomicString& name)
             : m_target(target)
             , m_name(name)
         {
         }
-        virtual void onEventCondition(bool wasInPlay, bool isInPlay, double previousIteration, double currentIteration) OVERRIDE;
+        virtual void onEventCondition(bool isFirstSample, TimedItem::Phase previousPhase, TimedItem::Phase currentPhase, double previousIteration, double currentIteration) OVERRIDE;
     private:
         void maybeDispatch(Document::ListenerType, AtomicString& eventName, double elapsedTime);
         Element* m_target;
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index 7bf2ad2..3ec89a6 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -623,27 +623,6 @@
         ['exclude', 'platform/graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
       ],
       'conditions': [
-        ['use_default_render_theme==1', {
-          'sources/': [
-            ['exclude', 'platform/chromium/PlatformThemeChromiumWin.h'],
-            ['exclude', 'platform/chromium/PlatformThemeChromiumWin.cpp'],
-            ['exclude', 'platform/chromium/ScrollbarThemeChromiumWin.cpp'],
-            ['exclude', 'platform/chromium/ScrollbarThemeChromiumWin.h'],
-          ],
-        }, { # use_default_render_theme==0
-          'sources/': [
-            ['exclude', 'platform/chromium/PlatformThemeChromiumDefault.cpp'],
-            ['exclude', 'platform/chromium/PlatformThemeChromiumDefault.h'],
-            ['exclude', 'platform/chromium/ScrollbarThemeChromiumDefault.cpp'],
-            ['exclude', 'platform/chromium/ScrollbarThemeChromiumDefault.h'],
-          ],
-        }],
-        ['use_default_render_theme==0 and OS!="android"', {
-          'sources/': [
-            ['exclude', 'platform/chromium/ScrollbarThemeChromiumOverlay.cpp'],
-            ['exclude', 'platform/chromium/ScrollbarThemeChromiumOverlay.h'],
-          ]
-        }],
         ['OS=="linux" or OS=="android"', {
           'sources/': [
             # Cherry-pick files excluded by the broader regular expressions above.
@@ -670,14 +649,9 @@
             ['exclude', 'Linux\\.cpp$'],
           ],
         }],
-        ['toolkit_uses_gtk == 1', {
+        ['toolkit_uses_gtk == 0', {
           'sources/': [
-            # Cherry-pick files excluded by the broader regular expressions above.
-            ['include', 'platform/chromium/KeyCodeConversionGtk\\.cpp$'],
-          ],
-        }, { # toolkit_uses_gtk==0
-          'sources/': [
-            ['exclude', 'Gtk\\.cpp$'],
+            ['exclude', 'platform/chromium/KeyCodeConversionGtk\\.cpp$'],
           ],
         }],
         ['OS=="mac"', {
@@ -716,9 +690,6 @@
             ['include', 'platform/mac/KillRingMac\\.mm$'],
             ['include', 'platform/mac/LocalCurrentGraphicsContext\\.mm$'],
             ['include', 'platform/mac/NSScrollerImpDetails\\.mm$'],
-            ['include', 'platform/mac/ScrollbarThemeMac\\.mm$'],
-            ['include', 'platform/mac/ScrollbarThemeMacNonOverlayAPI\\.mm$'],
-            ['include', 'platform/mac/ScrollbarThemeMacOverlayAPI\\.mm$'],
             ['include', 'platform/mac/ScrollAnimatorMac\\.mm$'],
             ['include', 'platform/mac/ScrollElasticityController\\.mm$'],
             ['include', 'platform/mac/ThemeMac\\.h$'],
@@ -744,9 +715,7 @@
             # included by regex above, instead.
             ['exclude', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
 
-            # The Mac currently uses ScrollbarThemeChromiumMac.mm, which is not
-            # related to ScrollbarThemeChromium.cpp.
-            ['exclude', 'platform/chromium/ScrollbarThemeChromium\\.cpp$'],
+            ['exclude', 'platform/ScrollbarThemeNonMacCommon\\.(cpp|h)$'],
 
             # Mac uses only ScrollAnimatorMac.
             ['exclude', 'platform/ScrollAnimatorNone\\.cpp$'],
@@ -771,6 +740,7 @@
         },{ # OS!="mac"
           'sources/': [
             ['exclude', 'Mac\\.(cpp|mm?)$'],
+            ['exclude', 'ScrollbarThemeMac'],
 
             # FIXME: We will eventually compile this too, but for now it's
             # only used on mac.
@@ -786,11 +756,10 @@
           'sources/': [
             ['exclude', 'Posix\\.cpp$'],
 
-            ['include', '/opentype/'],
-            ['include', '/SkiaFontWin\\.cpp$'],
-            ['include', '/TransparencyWin\\.cpp$'],
-
-            ['exclude', 'platform/graphics/skia/FontCacheSkia\\.cpp$'],
+            ['include', 'platform/ScrollbarThemeWin\\.(cpp|h)$'],
+            ['include', 'platform/graphics/chromium/TransparencyWin\\.(cpp|h)$'],
+            ['include', 'platform/graphics/opentype/'],
+            ['include', 'platform/graphics/skia/SkiaFontWin\\.(cpp|h)$'],
 
             # Windows currently uses FontCustomPlatformDataWin.cpp instead.
             ['exclude', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
@@ -809,13 +778,17 @@
               'sources/': [
                 ['exclude', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
                 ['exclude', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
+                ['exclude', 'platform/graphics/skia/FontCacheSkia\\.cpp$'],
+                ['exclude', 'platform/graphics/skia/FontCacheSkiaWin\\.cpp$'],
               ],
             },{ # ENABLE_GDI_FONTS_ON_WINDOWS!=1
               'sources/': [
-                ['exclude', 'platform/graphics/chromium/SimpleFontDataChromiumWin\\.cpp$'],
                 ['include', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
                 ['include', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
+                ['include', 'platform/graphics/skia/FontCacheSkiaWin\\.cpp$'],
+                ['exclude', 'platform/graphics/chromium/SimpleFontDataChromiumWin\\.cpp$'],
                 ['exclude', 'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin\\.cpp$'],
+                ['exclude', 'platform/graphics/chromium/FontCacheChromiumWin\\.cpp$'],
               ],
             }],
           ],
@@ -844,6 +817,22 @@
             ['exclude', 'Android\\.cpp$'],
           ],
         }],
+        ['use_default_render_theme==1', {
+          'sources/': [
+            ['exclude', 'platform/ScrollbarThemeWin\\.(cpp|h)'],
+            ['exclude', 'platform/chromium/PlatformThemeChromiumWin\\.(cpp|h)'],
+          ],
+        }, { # use_default_render_theme==0
+          'sources/': [
+            ['exclude', 'platform/ScrollbarThemeAuraOrGtk\\.(cpp|h)'],
+            ['exclude', 'platform/chromium/PlatformThemeChromiumDefault\\.(cpp|h)'],
+          ],
+        }],
+        ['use_default_render_theme==0 and OS!="android"', {
+          'sources/': [
+            ['exclude', 'platform/ScrollbarThemeOverlay\\.(cpp|h)'],
+          ]
+        }],
       ],
     },
     {
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index fba11fa..52e8473 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -82,6 +82,7 @@
             'dom/Notation.idl',
             'dom/OverflowEvent.idl',
             'dom/PageTransitionEvent.idl',
+            'dom/ParentNode.idl',
             'dom/PopStateEvent.idl',
             'dom/ProcessingInstruction.idl',
             'dom/ProgressEvent.idl',
@@ -235,16 +236,17 @@
             'inspector/InspectorFrontendHost.idl',
             'inspector/InspectorOverlayHost.idl',
             'inspector/JavaScriptCallFrame.idl',
-            'loader/appcache/DOMApplicationCache.idl',
+            'loader/appcache/ApplicationCache.idl',
             'page/BarProp.idl',
             'page/Console.idl',
             'page/EventSource.idl',
             'page/History.idl',
             'page/ImageBitmap.idl',
-            'page/ImageBitmapFactories.idl',
             'page/Location.idl',
             'page/MemoryInfo.idl',
             'page/Navigator.idl',
+            'page/NavigatorID.idl',
+            'page/NavigatorOnLine.idl',
             'page/PagePopupController.idl',
             'page/Performance.idl',
             'page/PerformanceEntry.idl',
@@ -276,6 +278,7 @@
             'workers/WorkerLocation.idl',
             'xml/DOMParser.idl',
             'xml/XMLHttpRequest.idl',
+            'xml/XMLHttpRequestEventTarget.idl',
             'xml/XMLHttpRequestProgressEvent.idl',
             'xml/XMLHttpRequestUpload.idl',
             'xml/XMLSerializer.idl',
@@ -290,7 +293,6 @@
             'css/Rect.idl',
             'dom/ChildNode.idl',
             'dom/DocumentFullscreen.idl',
-            'dom/ParentNode.idl',
             'dom/RequestAnimationFrameCallback.idl',
             'dom/StringCallback.idl',
             'html/VoidCallback.idl',
@@ -525,6 +527,8 @@
             'animation/AnimatableNeutral.h',
             'animation/AnimatableNumber.cpp',
             'animation/AnimatableNumber.h',
+            'animation/AnimatableTransform.cpp',
+            'animation/AnimatableTransform.h',
             'animation/AnimatableUnknown.h',
             'animation/AnimatableValue.cpp',
             'animation/AnimatableValue.h',
@@ -845,8 +849,8 @@
             'editing/SimplifyMarkupCommand.cpp',
             'editing/SmartReplaceCF.cpp',
             'editing/SmartReplaceICU.cpp',
-            'editing/SpellChecker.cpp',
-            'editing/SpellChecker.h',
+            'editing/SpellCheckRequester.cpp',
+            'editing/SpellCheckRequester.h',
             'editing/SpellingCorrectionCommand.cpp',
             'editing/SpellingCorrectionCommand.h',
             'editing/SplitElementCommand.cpp',
@@ -874,6 +878,42 @@
             'editing/chromium/EditorChromium.cpp',
             'editing/htmlediting.cpp',
             'editing/markup.cpp',
+            'fetch/CSSStyleSheetResource.cpp',
+            'fetch/CSSStyleSheetResource.h',
+            'fetch/DocumentResource.cpp',
+            'fetch/DocumentResource.h',
+            'fetch/FontResource.cpp',
+            'fetch/FontResource.h',
+            'fetch/ImageResource.cpp',
+            'fetch/ImageResource.h',
+            'fetch/RawResource.cpp',
+            'fetch/RawResource.h',
+            'fetch/Resource.cpp',
+            'fetch/Resource.h',
+            'fetch/ResourceClientWalker.h',
+            'fetch/ResourceFetcher.cpp',
+            'fetch/ResourceFetcher.h',
+            'fetch/ResourceLoadNotifier.cpp',
+            'fetch/ResourceLoadNotifier.h',
+            'fetch/ResourceLoader.cpp',
+            'fetch/ResourceLoader.h',
+            'fetch/ResourceLoaderOptions.h',
+            'fetch/ResourcePtr.cpp',
+            'fetch/ResourcePtr.h',
+            'fetch/FetchRequest.cpp',
+            'fetch/FetchRequest.h',
+            'fetch/FetchInitiatorInfo.h',
+            'fetch/ScriptResource.cpp',
+            'fetch/ScriptResource.h',
+            'fetch/ShaderResource.cpp',
+            'fetch/ShaderResource.h',
+            'fetch/DocumentResourceReference.h',
+            'fetch/TextTrackResource.cpp',
+            'fetch/TextTrackResource.h',
+            'fetch/XSLStyleSheetResource.cpp',
+            'fetch/XSLStyleSheetResource.h',
+            'fetch/MemoryCache.cpp',
+            'fetch/MemoryCache.h',
             'fileapi/Blob.cpp',
             'fileapi/Blob.h',
             'fileapi/BlobBuilder.cpp',
@@ -1070,9 +1110,6 @@
             'loader/PrerendererClient.cpp',
             'loader/PrerendererClient.h',
             'loader/ProgressTracker.cpp',
-            'loader/ResourceLoadNotifier.cpp',
-            'loader/ResourceLoader.cpp',
-            'loader/ResourceLoaderOptions.h',
             'loader/SinkDocument.cpp',
             'loader/SinkDocument.h',
             'loader/SubstituteData.h',
@@ -1088,9 +1125,9 @@
             'loader/UniqueIdentifier.h',
             'loader/WorkerThreadableLoader.cpp',
             'loader/WorkerThreadableLoader.h',
+            'loader/appcache/ApplicationCache.cpp',
+            'loader/appcache/ApplicationCache.h',
             'loader/appcache/ApplicationCacheHost.h',
-            'loader/appcache/DOMApplicationCache.cpp',
-            'loader/appcache/DOMApplicationCache.h',
             'loader/archive/ArchiveResource.cpp',
             'loader/archive/ArchiveResourceCollection.cpp',
             'loader/archive/ArchiveResourceCollection.h',
@@ -1098,30 +1135,6 @@
             'loader/archive/MHTMLArchive.h',
             'loader/archive/MHTMLParser.cpp',
             'loader/archive/MHTMLParser.h',
-            'loader/cache/CSSStyleSheetResource.cpp',
-            'loader/cache/CSSStyleSheetResource.h',
-            'loader/cache/DocumentResource.cpp',
-            'loader/cache/DocumentResource.h',
-            'loader/cache/FontResource.cpp',
-            'loader/cache/FontResource.h',
-            'loader/cache/ImageResource.cpp',
-            'loader/cache/RawResource.cpp',
-            'loader/cache/Resource.cpp',
-            'loader/cache/ResourceClientWalker.h',
-            'loader/cache/ResourcePtr.cpp',
-            'loader/cache/ResourceFetcher.cpp',
-            'loader/cache/FetchRequest.cpp',
-            'loader/cache/FetchInitiatorInfo.h',
-            'loader/cache/ScriptResource.cpp',
-            'loader/cache/ScriptResource.h',
-            'loader/cache/ShaderResource.cpp',
-            'loader/cache/ShaderResource.h',
-            'loader/cache/DocumentResourceReference.h',
-            'loader/cache/TextTrackResource.cpp',
-            'loader/cache/TextTrackResource.h',
-            'loader/cache/XSLStyleSheetResource.cpp',
-            'loader/cache/XSLStyleSheetResource.h',
-            'loader/cache/MemoryCache.cpp',
             'page/AutoscrollController.cpp',
             'page/AutoscrollController.h',
             'page/BarProp.cpp',
@@ -1149,6 +1162,10 @@
             'page/DOMWindow.h',
             'page/DOMWindowBase64.cpp',
             'page/DOMWindowBase64.h',
+            'page/DOMWindowLifecycleNotifier.cpp',
+            'page/DOMWindowLifecycleNotifier.h',
+            'page/DOMWindowLifecycleObserver.cpp',
+            'page/DOMWindowLifecycleObserver.h',
             'page/DOMWindowTimers.cpp',
             'page/DOMWindowTimers.h',
             'page/DOMWindowPagePopup.cpp',
@@ -1171,8 +1188,6 @@
             'page/History.h',
             'page/ImageBitmap.cpp',
             'page/ImageBitmap.h',
-            'page/ImageBitmapFactories.cpp',
-            'page/ImageBitmapFactories.h',
             'page/LayoutMilestones.h',
             'page/Location.cpp',
             'page/Location.h',
@@ -1183,6 +1198,9 @@
             'page/Navigator.h',
             'page/NavigatorBase.cpp',
             'page/NavigatorBase.h',
+            'page/NavigatorID.cpp',
+            'page/NavigatorID.h',
+            'page/NavigatorOnLine.h',
             'page/Page.cpp',
             'page/PageConsole.cpp',
             'page/PageGroup.cpp',
@@ -1294,6 +1312,8 @@
             'rendering/FilterEffectRenderer.h',
             'rendering/FixedTableLayout.cpp',
             'rendering/FixedTableLayout.h',
+            'rendering/FloatingObjects.cpp',
+            'rendering/FloatingObjects.h',
             'rendering/FlowThreadController.cpp',
             'rendering/FlowThreadController.h',
             'rendering/TextAutosizer.cpp',
@@ -1370,9 +1390,8 @@
             'rendering/RenderLayerCompositor.h',
             'rendering/RenderLayerFilterInfo.cpp',
             'rendering/RenderLayerFilterInfo.h',
+            'rendering/RenderLayerScrollableArea.cpp',
             'rendering/RenderLayerModelObject.cpp',
-            'rendering/RenderLazyBlock.cpp',
-            'rendering/RenderLazyBlock.h',
             'rendering/RenderLineBoxList.cpp',
             'rendering/RenderListBox.cpp',
             'rendering/RenderListBox.h',
@@ -1482,6 +1501,8 @@
             'rendering/RenderWordBreak.h',
             'rendering/RootInlineBox.cpp',
             'rendering/ScrollBehavior.cpp',
+            'rendering/SubtreeLayoutScope.cpp',
+            'rendering/SubtreeLayoutScope.h',
             'rendering/TableLayout.h',
             'rendering/TrailingFloatsRootInlineBox.h',
             'rendering/VerticalPositionCache.h',
@@ -1489,6 +1510,8 @@
             'rendering/break_lines.h',
             'rendering/shapes/PolygonShape.cpp',
             'rendering/shapes/PolygonShape.h',
+            'rendering/shapes/RasterShape.cpp',
+            'rendering/shapes/RasterShape.h',
             'rendering/shapes/RectangleShape.cpp',
             'rendering/shapes/RectangleShape.h',
             'rendering/shapes/Shape.cpp',
@@ -1643,6 +1666,7 @@
             'xml/XMLErrors.h',
             'xml/XMLHttpRequest.cpp',
             'xml/XMLHttpRequest.h',
+            'xml/XMLHttpRequestEventTarget.h',
             'xml/XMLHttpRequestProgressEvent.h',
             'xml/XMLHttpRequestProgressEventThrottle.cpp',
             'xml/XMLHttpRequestProgressEventThrottle.h',
@@ -1748,7 +1772,11 @@
             'dom/CustomElementDefinition.h',
             'dom/CustomElementDescriptor.h',
             'dom/CustomElementDescriptorHash.h',
+            'dom/CustomElementException.cpp',
+            'dom/CustomElementException.h',
             'dom/CustomElementLifecycleCallbacks.h',
+            'dom/CustomElementObserver.cpp',
+            'dom/CustomElementObserver.h',
             'dom/CustomElementRegistrationContext.cpp',
             'dom/CustomElementRegistrationContext.h',
             'dom/CustomElementRegistry.cpp',
@@ -1798,8 +1826,10 @@
             'dom/DocumentStyleSheetCollection.h',
             'dom/DocumentType.cpp',
             'dom/Element.cpp',
+            'dom/Element.h',
             'dom/ElementRareData.cpp',
             'dom/ElementRareData.h',
+            'dom/ElementTraversal.h',
             'dom/Entity.h',
             'dom/ErrorEvent.cpp',
             'dom/ErrorEvent.h',
@@ -1892,6 +1922,7 @@
             'dom/OverflowEvent.h',
             'dom/PageTransitionEvent.cpp',
             'dom/PageTransitionEvent.h',
+            'dom/ParentNode.h',
             'dom/PendingScript.cpp',
             'dom/PopStateEvent.cpp',
             'dom/PopStateEvent.h',
@@ -1926,6 +1957,8 @@
             'dom/SecurityPolicyViolationEvent.h',
             'dom/SelectorQuery.cpp',
             'dom/SelectorQuery.h',
+            'dom/ShadowTreeStyleSheetCollection.cpp',
+            'dom/ShadowTreeStyleSheetCollection.h',
             'dom/SimulatedClickOptions.h',
             'dom/SpaceSplitString.cpp',
             'dom/StaticNodeList.cpp',
@@ -1983,8 +2016,10 @@
             'dom/default/chromium/PlatformMessagePortChannelChromium.h',
             'dom/shadow/ComposedShadowTreeWalker.cpp',
             'dom/shadow/ComposedShadowTreeWalker.h',
-            'dom/shadow/ContentDistributor.cpp',
-            'dom/shadow/ContentDistributor.h',
+            'dom/shadow/ContentDistribution.cpp',
+            'dom/shadow/ContentDistribution.h',
+            'dom/shadow/ScopeContentDistribution.cpp',
+            'dom/shadow/ScopeContentDistribution.h',
             'dom/shadow/ElementShadow.cpp',
             'dom/shadow/ElementShadow.h',
             'dom/shadow/InsertionPoint.cpp',
@@ -2558,6 +2593,7 @@
             'platform/NotImplemented.cpp',
             'platform/Partitions.cpp',
             'platform/Partitions.h',
+            'platform/Pasteboard.cpp',
             'platform/Pasteboard.h',
             'platform/PlatformEvent.cpp',
             'platform/PlatformEvent.h',
@@ -2583,7 +2619,25 @@
             'platform/ScrollView.cpp',
             'platform/ScrollableArea.cpp',
             'platform/Scrollbar.cpp',
+            'platform/Scrollbar.h',
             'platform/ScrollbarTheme.cpp',
+            'platform/ScrollbarTheme.h',
+            'platform/ScrollbarThemeAndroid.cpp',
+            'platform/ScrollbarThemeAuraOrGtk.cpp',
+            'platform/ScrollbarThemeAuraOrGtk.h',
+            'platform/ScrollbarThemeClient.h',
+            'platform/ScrollbarThemeMacCommon.h',
+            'platform/ScrollbarThemeMacCommon.mm',
+            'platform/ScrollbarThemeMacNonOverlayAPI.h',
+            'platform/ScrollbarThemeMacNonOverlayAPI.mm',
+            'platform/ScrollbarThemeMacOverlayAPI.h',
+            'platform/ScrollbarThemeMacOverlayAPI.mm',
+            'platform/ScrollbarThemeNonMacCommon.cpp',
+            'platform/ScrollbarThemeNonMacCommon.h',
+            'platform/ScrollbarThemeOverlay.cpp',
+            'platform/ScrollbarThemeOverlay.h',
+            'platform/ScrollbarThemeWin.cpp',
+            'platform/ScrollbarThemeWin.h',
             'platform/SecureTextInput.cpp',
             'platform/SecureTextInput.h',
             'platform/SerializedResource.h',
@@ -2715,7 +2769,6 @@
             'platform/chromium/LocalizedStringsChromium.cpp',
             'platform/chromium/MemoryUsageSupportChromium.cpp',
             'platform/chromium/MIMETypeRegistryChromium.cpp',
-            'platform/chromium/PasteboardChromium.cpp',
             'platform/chromium/PlatformKeyboardEventChromium.cpp',
             'platform/chromium/PlatformScreenChromium.cpp',
             'platform/chromium/PlatformThemeChromiumDefault.cpp',
@@ -2725,15 +2778,6 @@
             'platform/chromium/Prerender.h',
             'platform/chromium/PrerenderHandle.cpp',
             'platform/chromium/SSLKeyGeneratorChromium.cpp',
-            'platform/chromium/ScrollbarThemeChromium.cpp',
-            'platform/chromium/ScrollbarThemeChromium.h',
-            'platform/chromium/ScrollbarThemeChromiumAndroid.cpp',
-            'platform/chromium/ScrollbarThemeChromiumDefault.cpp',
-            'platform/chromium/ScrollbarThemeChromiumDefault.h',
-            'platform/chromium/ScrollbarThemeChromiumOverlay.cpp',
-            'platform/chromium/ScrollbarThemeChromiumOverlay.h',
-            'platform/chromium/ScrollbarThemeChromiumWin.cpp',
-            'platform/chromium/ScrollbarThemeChromiumWin.h',
             'platform/chromium/SharedTimerChromium.cpp',
             'platform/chromium/SoundChromiumPosix.cpp',
             'platform/chromium/SoundChromiumWin.cpp',
@@ -2987,6 +3031,7 @@
             'platform/graphics/opentype/OpenTypeVerticalData.cpp',
             'platform/graphics/opentype/OpenTypeVerticalData.h',
             'platform/graphics/skia/FontCacheSkia.cpp',
+            'platform/graphics/skia/FontCacheSkiaWin.cpp',
             'platform/graphics/skia/FontCustomPlatformDataSkia.cpp',
             'platform/graphics/skia/FontPlatformDataSkia.cpp',
             'platform/graphics/skia/GlyphPageTreeNodeSkia.cpp',
@@ -3057,12 +3102,6 @@
             'platform/mac/ScrollAnimatorMac.mm',
             'platform/mac/ScrollElasticityController.h',
             'platform/mac/ScrollElasticityController.mm',
-            'platform/mac/ScrollbarThemeMac.h',
-            'platform/mac/ScrollbarThemeMac.mm',
-            'platform/mac/ScrollbarThemeMacNonOverlayAPI.h',
-            'platform/mac/ScrollbarThemeMacNonOverlayAPI.mm',
-            'platform/mac/ScrollbarThemeMacOverlayAPI.h',
-            'platform/mac/ScrollbarThemeMacOverlayAPI.mm',
             'platform/mac/ThemeMac.h',
             'platform/mac/ThemeMac.mm',
             'platform/mac/WebFontCache.mm',
@@ -3093,6 +3132,8 @@
             'platform/midi/MIDIAccessorClient.h',
             'platform/mock/DeviceOrientationClientMock.cpp',
             'platform/mock/GeolocationClientMock.cpp',
+            'platform/mock/MIDIClientMock.cpp',
+            'platform/mock/MIDIClientMock.h',
             'platform/mock/PlatformSpeechSynthesizerMock.cpp',
             'platform/mock/PlatformSpeechSynthesizerMock.h',
             'platform/mock/ScrollbarThemeMock.cpp',
@@ -3740,10 +3781,10 @@
             'animation/TimedItemCalculationsTest.cpp',
             'animation/TimedItemTest.cpp',
             'css/CSSParserValuesTest.cpp',
+            'fetch/ImageResourceTest.cpp',
+            'fetch/MemoryCacheTest.cpp',
+            'fetch/ResourceFetcherTest.cpp',
             'html/TimeRangesTest.cpp',
-            'loader/cache/ImageResourceTest.cpp',
-            'loader/cache/MemoryCacheTest.cpp',
-            'loader/cache/ResourceFetcherTest.cpp',
             'page/ImageBitmapTest.cpp',
             'platform/DecimalTest.cpp',
             'platform/SharedBufferTest.cpp',
diff --git a/Source/core/core_derived_sources.gyp b/Source/core/core_derived_sources.gyp
index 7e09172..e89bab6 100644
--- a/Source/core/core_derived_sources.gyp
+++ b/Source/core/core_derived_sources.gyp
@@ -481,7 +481,7 @@
             'scripts/Hasher.pm',
             'scripts/StaticString.pm',
             'scripts/make_names.pl',
-            'loader/cache/FetchInitiatorTypeNames.in',
+            'fetch/FetchInitiatorTypeNames.in',
           ],
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/blink/FetchInitiatorTypeNames.cpp',
diff --git a/Source/core/css/CSSArrayFunctionValue.h b/Source/core/css/CSSArrayFunctionValue.h
index 2e25e9c..9325207 100644
--- a/Source/core/css/CSSArrayFunctionValue.h
+++ b/Source/core/css/CSSArrayFunctionValue.h
@@ -50,7 +50,7 @@
 
 private:
     CSSArrayFunctionValue();
-    CSSArrayFunctionValue(const CSSArrayFunctionValue& cloneFrom);
+    explicit CSSArrayFunctionValue(const CSSArrayFunctionValue& cloneFrom);
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSCanvasValue.h b/Source/core/css/CSSCanvasValue.h
index c2e7b77..8283adb 100644
--- a/Source/core/css/CSSCanvasValue.h
+++ b/Source/core/css/CSSCanvasValue.h
@@ -50,7 +50,7 @@
     bool equals(const CSSCanvasValue&) const;
 
 private:
-    CSSCanvasValue(const String& name)
+    explicit CSSCanvasValue(const String& name)
         : CSSImageGeneratorValue(CanvasClass)
         , m_canvasObserver(this)
         , m_name(name)
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index 5484ae5..9764aa9 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -83,6 +83,14 @@
 // NOTE: Do not use this list, use computableProperties() instead
 // to respect runtime enabling of CSS properties.
 static const CSSPropertyID staticComputableProperties[] = {
+    CSSPropertyAnimationDelay,
+    CSSPropertyAnimationDirection,
+    CSSPropertyAnimationDuration,
+    CSSPropertyAnimationFillMode,
+    CSSPropertyAnimationIterationCount,
+    CSSPropertyAnimationName,
+    CSSPropertyAnimationPlayState,
+    CSSPropertyAnimationTimingFunction,
     CSSPropertyBackgroundAttachment,
     CSSPropertyBackgroundBlendMode,
     CSSPropertyBackgroundClip,
@@ -278,7 +286,6 @@
     CSSPropertyWebkitLocale,
     CSSPropertyWebkitMarginBeforeCollapse,
     CSSPropertyWebkitMarginAfterCollapse,
-    CSSPropertyWebkitMarqueeDirection,
     CSSPropertyWebkitMarqueeIncrement,
     CSSPropertyWebkitMarqueeRepetition,
     CSSPropertyWebkitMarqueeStyle,
@@ -372,7 +379,8 @@
     CSSPropertyWritingMode,
     CSSPropertyGlyphOrientationHorizontal,
     CSSPropertyGlyphOrientationVertical,
-    CSSPropertyVectorEffect
+    CSSPropertyVectorEffect,
+    CSSPropertyPaintOrder
 };
 
 static const Vector<CSSPropertyID>& computableProperties()
@@ -603,7 +611,7 @@
     return positionList.release();
 }
 
-static PassRefPtr<CSSValue> getPositionOffsetValue(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;
@@ -669,7 +677,7 @@
     return cssValuePool().createColorValue(color.rgb());
 }
 
-static PassRefPtr<CSSValueList> getBorderRadiusCornerValues(LengthSize radius, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderView* renderView)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     if (radius.width().type() == Percent)
@@ -683,17 +691,17 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> getBorderRadiusCornerValue(LengthSize radius, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderView* renderView)
 {
     if (radius.width() == radius.height()) {
         if (radius.width().type() == Percent)
             return cssValuePool().createValue(radius.width().percent(), CSSPrimitiveValue::CSS_PERCENTAGE);
         return zoomAdjustedPixelValue(valueForLength(radius.width(), 0, renderView), style);
     }
-    return getBorderRadiusCornerValues(radius, style, renderView);
+    return valuesForBorderRadiusCorner(radius, style, renderView);
 }
 
-static PassRefPtr<CSSValueList> getBorderRadiusShorthandValue(const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle* style, RenderView* renderView)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
     bool showHorizontalBottomLeft = style->borderTopRightRadius().width() != style->borderBottomLeftRadius().width();
@@ -705,10 +713,10 @@
     bool showVerticalTopRight = (style->borderTopRightRadius().height() != style->borderTopLeftRadius().height()) || showVerticalBottomRight;
     bool showVerticalTopLeft = (style->borderTopLeftRadius().width() != style->borderTopLeftRadius().height());
 
-    RefPtr<CSSValueList> topLeftRadius = getBorderRadiusCornerValues(style->borderTopLeftRadius(), style, renderView);
-    RefPtr<CSSValueList> topRightRadius = getBorderRadiusCornerValues(style->borderTopRightRadius(), style, renderView);
-    RefPtr<CSSValueList> bottomRightRadius = getBorderRadiusCornerValues(style->borderBottomRightRadius(), style, renderView);
-    RefPtr<CSSValueList> bottomLeftRadius = getBorderRadiusCornerValues(style->borderBottomLeftRadius(), style, renderView);
+    RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style->borderTopLeftRadius(), style, renderView);
+    RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style->borderTopRightRadius(), style, renderView);
+    RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style->borderBottomRightRadius(), style, renderView);
+    RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style->borderBottomLeftRadius(), style, renderView);
 
     RefPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
     horizontalRadii->append(topLeftRadius->item(0));
@@ -744,7 +752,7 @@
     return box->style()->boxSizing() == BORDER_BOX ? box->borderBoxRect() : box->computedCSSContentBoxRect();
 }
 
-static PassRefPtr<CSSTransformValue> matrixTransformValue(const TransformationMatrix& transform, const RenderStyle* style)
+static PassRefPtr<CSSTransformValue> valueForMatrixTransform(const TransformationMatrix& transform, const RenderStyle* style)
 {
     RefPtr<CSSTransformValue> transformValue;
     if (transform.isAffine()) {
@@ -797,7 +805,7 @@
 
     // FIXME: Need to print out individual functions (https://bugs.webkit.org/show_bug.cgi?id=23924)
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    list->append(matrixTransformValue(transform, style));
+    list->append(valueForMatrixTransform(transform, style));
 
     return list.release();
 }
@@ -827,7 +835,7 @@
     TransformationMatrix transform;
     transformParameter->applyTransform(transform, size);
     // FIXME: Need to print out individual functions (https://bugs.webkit.org/show_bug.cgi?id=23924)
-    return matrixTransformValue(transform, style);
+    return valueForMatrixTransform(transform, style);
 }
 
 static PassRefPtr<CSSValue> valueForCustomFilterParameter(const RenderObject* renderer, const RenderStyle* style, const CustomFilterParameter* parameter)
@@ -1030,39 +1038,28 @@
     return 0;
 }
 
-static void addValuesForNamedGridLinesAtIndex(const NamedGridLinesMap& namedGridLines, size_t i, CSSValueList& list)
+static void addValuesForNamedGridLinesAtIndex(const OrderedNamedGridLines& orderedNamedGridLines, size_t i, CSSValueList& list)
 {
-    // Note that this won't return the results in the order specified in the style sheet,
-    // which is probably fine as we stil *do* return all the expected values.
-    NamedGridLinesMap::const_iterator it = namedGridLines.begin();
-    NamedGridLinesMap::const_iterator end = namedGridLines.end();
-    for (; it != end; ++it) {
-        const Vector<size_t>& linesIndexes = it->value;
-        for (size_t j = 0; j < linesIndexes.size(); ++j) {
-            if (linesIndexes[j] != i)
-                continue;
-
-            list.append(cssValuePool().createValue(it->key, CSSPrimitiveValue::CSS_STRING));
-            break;
-        }
-    }
+    const Vector<String>& namedGridLines = orderedNamedGridLines.get(i);
+    for (size_t j = 0; j < namedGridLines.size(); ++j)
+        list.append(cssValuePool().createValue(namedGridLines[j], CSSPrimitiveValue::CSS_STRING));
 }
 
-static PassRefPtr<CSSValue> valueForGridTrackList(const Vector<GridTrackSize>& trackSizes, const NamedGridLinesMap& namedGridLines, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForGridTrackList(const Vector<GridTrackSize>& trackSizes, const OrderedNamedGridLines& orderedNamedGridLines, const RenderStyle* style, RenderView* renderView)
 {
     // Handle the 'none' case here.
     if (!trackSizes.size()) {
-        ASSERT(namedGridLines.isEmpty());
+        ASSERT(orderedNamedGridLines.isEmpty());
         return cssValuePool().createIdentifierValue(CSSValueNone);
     }
 
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     for (size_t i = 0; i < trackSizes.size(); ++i) {
-        addValuesForNamedGridLinesAtIndex(namedGridLines, i, *list);
+        addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, i, *list);
         list->append(valueForGridTrackSize(trackSizes[i], style, renderView));
     }
     // Those are the trailing <string>* allowed in the syntax.
-    addValuesForNamedGridLinesAtIndex(namedGridLines, trackSizes.size(), *list);
+    addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, trackSizes.size(), *list);
     return list.release();
 }
 
@@ -1096,7 +1093,7 @@
         propertyValue = cssValuePool().createValue(getPropertyNameString(animation->property()), CSSPrimitiveValue::CSS_STRING);
     return propertyValue.release();
 }
-static PassRefPtr<CSSValue> getTransitionPropertyValue(const CSSAnimationDataList* animList)
+static PassRefPtr<CSSValue> valueForTransitionProperty(const CSSAnimationDataList* animList)
 {
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
@@ -1107,7 +1104,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> getDelayValue(const CSSAnimationDataList* animList)
+static PassRefPtr<CSSValue> valueForAnimationDelay(const CSSAnimationDataList* animList)
 {
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
@@ -1120,7 +1117,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> getDurationValue(const CSSAnimationDataList* animList)
+static PassRefPtr<CSSValue> valueForAnimationDuration(const CSSAnimationDataList* animList)
 {
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
@@ -1169,7 +1166,7 @@
     return CSSLinearTimingFunctionValue::create();
 }
 
-static PassRefPtr<CSSValue> getTimingFunctionValue(const CSSAnimationDataList* animList)
+static PassRefPtr<CSSValue> valueForAnimationTimingFunction(const CSSAnimationDataList* animList)
 {
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
@@ -1181,6 +1178,40 @@
     return list.release();
 }
 
+static PassRefPtr<CSSValue> valueForAnimationFillMode(unsigned fillMode)
+{
+    switch (fillMode) {
+    case AnimationFillModeNone:
+        return cssValuePool().createIdentifierValue(CSSValueNone);
+    case AnimationFillModeForwards:
+        return cssValuePool().createIdentifierValue(CSSValueForwards);
+    case AnimationFillModeBackwards:
+        return cssValuePool().createIdentifierValue(CSSValueBackwards);
+    case AnimationFillModeBoth:
+        return cssValuePool().createIdentifierValue(CSSValueBoth);
+    default:
+        ASSERT_NOT_REACHED();
+        return 0;
+    }
+}
+
+static PassRefPtr<CSSValue> valueForAnimationDirection(CSSAnimationData::AnimationDirection direction)
+{
+    switch (direction) {
+    case CSSAnimationData::AnimationDirectionNormal:
+        return cssValuePool().createIdentifierValue(CSSValueNormal);
+    case CSSAnimationData::AnimationDirectionAlternate:
+        return cssValuePool().createIdentifierValue(CSSValueAlternate);
+    case CSSAnimationData::AnimationDirectionReverse:
+        return cssValuePool().createIdentifierValue(CSSValueReverse);
+    case CSSAnimationData::AnimationDirectionAlternateReverse:
+        return cssValuePool().createIdentifierValue(CSSValueAlternateReverse);
+    default:
+        ASSERT_NOT_REACHED();
+        return 0;
+    }
+}
+
 static PassRefPtr<CSSValue> createLineBoxContainValue(unsigned lineBoxContain)
 {
     if (!lineBoxContain)
@@ -1336,7 +1367,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> renderTextDecorationStyleFlagsToCSSValue(TextDecorationStyle textDecorationStyle)
+static PassRefPtr<CSSValue> valueForTextDecorationStyle(TextDecorationStyle textDecorationStyle)
 {
     switch (textDecorationStyle) {
     case TextDecorationStyleSolid:
@@ -1355,7 +1386,7 @@
     return cssValuePool().createExplicitInitialValue();
 }
 
-static PassRefPtr<CSSValue> fillRepeatToCSSValue(EFillRepeat xRepeat, EFillRepeat yRepeat)
+static PassRefPtr<CSSValue> valueForFillRepeat(EFillRepeat xRepeat, EFillRepeat yRepeat)
 {
     // For backwards compatibility, if both values are equal, just return one of them. And
     // if the two values are equivalent to repeat-x or repeat-y, just return the shorthand.
@@ -1372,7 +1403,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> fillSizeToCSSValue(const FillSize& fillSize, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const RenderStyle* style)
 {
     if (fillSize.type == Contain)
         return cssValuePool().createIdentifierValue(CSSValueContain);
@@ -1389,7 +1420,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> contentToCSSValue(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()) {
@@ -1409,7 +1440,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> counterToCSSValue(const RenderStyle* style, CSSPropertyID propertyID)
+static PassRefPtr<CSSValue> valueForCounterDirectives(const RenderStyle* style, CSSPropertyID propertyID)
 {
     const CounterDirectiveMap* map = style->counterDirectives();
     if (!map)
@@ -1433,7 +1464,7 @@
     LOG_ERROR("WebKit does not yet implement getComputedStyle for '%s'.", getPropertyName(propertyID));
 }
 
-static PassRefPtr<CSSValueList> fontFamilyFromStyle(RenderStyle* style)
+static PassRefPtr<CSSValueList> valueForFontFamily(RenderStyle* style)
 {
     const FontFamily& firstFamily = style->fontDescription().family();
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
@@ -1442,7 +1473,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSPrimitiveValue> lineHeightFromStyle(RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSPrimitiveValue> valueForLineHeight(RenderStyle* style, RenderView* renderView)
 {
     Length length = style->lineHeight();
     if (length.isNegative())
@@ -1456,26 +1487,26 @@
     return zoomAdjustedPixelValue(valueForLength(length, 0, renderView), style);
 }
 
-static PassRefPtr<CSSPrimitiveValue> fontSizeFromStyle(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontSize(RenderStyle* style)
 {
     return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), style);
 }
 
-static PassRefPtr<CSSPrimitiveValue> fontStyleFromStyle(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontStyle(RenderStyle* style)
 {
     if (style->fontDescription().italic())
         return cssValuePool().createIdentifierValue(CSSValueItalic);
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static PassRefPtr<CSSPrimitiveValue> fontVariantFromStyle(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontVariant(RenderStyle* style)
 {
     if (style->fontDescription().smallCaps())
         return cssValuePool().createIdentifierValue(CSSValueSmallCaps);
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static PassRefPtr<CSSPrimitiveValue> fontWeightFromStyle(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle* style)
 {
     switch (style->fontDescription().weight()) {
     case FontWeight100:
@@ -1646,11 +1677,11 @@
         case CSSPropertyWebkitMaskSize: {
             const FillLayer* layers = propertyID == CSSPropertyWebkitMaskSize ? style->maskLayers() : style->backgroundLayers();
             if (!layers->next())
-                return fillSizeToCSSValue(layers->size(), style.get());
+                return valueForFillSize(layers->size(), style.get());
 
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
-                list->append(fillSizeToCSSValue(currLayer->size(), style.get()));
+                list->append(valueForFillSize(currLayer->size(), style.get()));
 
             return list.release();
         }
@@ -1658,11 +1689,11 @@
         case CSSPropertyWebkitMaskRepeat: {
             const FillLayer* layers = propertyID == CSSPropertyWebkitMaskRepeat ? style->maskLayers() : style->backgroundLayers();
             if (!layers->next())
-                return fillRepeatToCSSValue(layers->repeatX(), layers->repeatY());
+                return valueForFillRepeat(layers->repeatX(), layers->repeatY());
 
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
-                list->append(fillRepeatToCSSValue(currLayer->repeatX(), currLayer->repeatY()));
+                list->append(valueForFillRepeat(currLayer->repeatX(), currLayer->repeatY()));
 
             return list.release();
         }
@@ -1788,7 +1819,7 @@
         case CSSPropertyBorderLeftWidth:
             return zoomAdjustedPixelValue(style->borderLeftWidth(), style.get());
         case CSSPropertyBottom:
-            return getPositionOffsetValue(style.get(), CSSPropertyBottom, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyBottom, renderer, m_node->document()->renderView());
         case CSSPropertyWebkitBoxAlign:
             return cssValuePool().createValue(style->boxAlign());
         case CSSPropertyWebkitBoxDecorationBreak:
@@ -1895,13 +1926,13 @@
             }
             return cssValuePool().createValue(style->alignSelf());
         case CSSPropertyFlex:
-            return getCSSPropertyValuesForShorthandProperties(flexShorthand());
+            return valuesForShorthandProperty(flexShorthand());
         case CSSPropertyFlexBasis:
             return cssValuePool().createValue(style->flexBasis());
         case CSSPropertyFlexDirection:
             return cssValuePool().createValue(style->flexDirection());
         case CSSPropertyFlexFlow:
-            return getCSSPropertyValuesForShorthandProperties(flexFlowShorthand());
+            return valuesForShorthandProperty(flexFlowShorthand());
         case CSSPropertyFlexGrow:
             return cssValuePool().createValue(style->flexGrow());
         case CSSPropertyFlexShrink:
@@ -1918,16 +1949,16 @@
             return cssValuePool().createValue(style->floating());
         case CSSPropertyFont: {
             RefPtr<FontValue> computedFont = FontValue::create();
-            computedFont->style = fontStyleFromStyle(style.get());
-            computedFont->variant = fontVariantFromStyle(style.get());
-            computedFont->weight = fontWeightFromStyle(style.get());
-            computedFont->size = fontSizeFromStyle(style.get());
-            computedFont->lineHeight = lineHeightFromStyle(style.get(), m_node->document()->renderView());
-            computedFont->family = fontFamilyFromStyle(style.get());
+            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());
             return computedFont.release();
         }
         case CSSPropertyFontFamily: {
-            RefPtr<CSSValueList> fontFamilyList = fontFamilyFromStyle(style.get());
+            RefPtr<CSSValueList> fontFamilyList = valueForFontFamily(style.get());
             // 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)
@@ -1935,13 +1966,13 @@
             return fontFamilyList.release();
         }
         case CSSPropertyFontSize:
-            return fontSizeFromStyle(style.get());
+            return valueForFontSize(style.get());
         case CSSPropertyFontStyle:
-            return fontStyleFromStyle(style.get());
+            return valueForFontStyle(style.get());
         case CSSPropertyFontVariant:
-            return fontVariantFromStyle(style.get());
+            return valueForFontVariant(style.get());
         case CSSPropertyFontWeight:
-            return fontWeightFromStyle(style.get());
+            return valueForFontWeight(style.get());
         case CSSPropertyWebkitFontFeatureSettings: {
             const FontFeatureSettings* featureSettings = style->fontDescription().featureSettings();
             if (!featureSettings || !featureSettings->size())
@@ -1961,9 +1992,9 @@
         case CSSPropertyGridAutoRows:
             return valueForGridTrackSize(style->gridAutoRows(), style.get(), m_node->document()->renderView());
         case CSSPropertyGridDefinitionColumns:
-            return valueForGridTrackList(style->gridDefinitionColumns(), style->namedGridColumnLines(), style.get(), m_node->document()->renderView());
+            return valueForGridTrackList(style->gridDefinitionColumns(), style->orderedNamedGridColumnLines(), style.get(), m_node->document()->renderView());
         case CSSPropertyGridDefinitionRows:
-            return valueForGridTrackList(style->gridDefinitionRows(), style->namedGridRowLines(), style.get(), m_node->document()->renderView());
+            return valueForGridTrackList(style->gridDefinitionRows(), style->orderedNamedGridRowLines(), style.get(), m_node->document()->renderView());
 
         case CSSPropertyGridColumnStart:
             return valueForGridPosition(style->gridColumnStart());
@@ -1974,11 +2005,11 @@
         case CSSPropertyGridRowEnd:
             return valueForGridPosition(style->gridRowEnd());
         case CSSPropertyGridColumn:
-            return getCSSPropertyValuesForGridShorthand(gridColumnShorthand());
+            return valuesForGridShorthand(gridColumnShorthand());
         case CSSPropertyGridRow:
-            return getCSSPropertyValuesForGridShorthand(gridRowShorthand());
+            return valuesForGridShorthand(gridRowShorthand());
         case CSSPropertyGridArea:
-            return getCSSPropertyValuesForGridShorthand(gridAreaShorthand());
+            return valuesForGridShorthand(gridAreaShorthand());
 
         case CSSPropertyGridTemplate:
             if (!style->namedGridAreaRowCount()) {
@@ -2012,7 +2043,7 @@
         case CSSPropertyImageRendering:
             return CSSPrimitiveValue::create(style->imageRendering());
         case CSSPropertyLeft:
-            return getPositionOffsetValue(style.get(), CSSPropertyLeft, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyLeft, renderer, m_node->document()->renderView());
         case CSSPropertyLetterSpacing:
             if (!style->letterSpacing())
                 return cssValuePool().createIdentifierValue(CSSValueNormal);
@@ -2022,7 +2053,7 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             return cssValuePool().createValue(style->lineClamp().value(), style->lineClamp().isPercentage() ? CSSPrimitiveValue::CSS_PERCENTAGE : CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyLineHeight:
-            return lineHeightFromStyle(style.get(), m_node->document()->renderView());
+            return valueForLineHeight(style.get(), m_node->document()->renderView());
         case CSSPropertyListStyleImage:
             if (style->listStyleImage())
                 return style->listStyleImage()->cssValue();
@@ -2067,8 +2098,6 @@
                 return zoomAdjustedPixelValueForLength(marginLeft, style.get());
             return zoomAdjustedPixelValue(toRenderBox(renderer)->marginLeft(), style.get());
         }
-        case CSSPropertyWebkitMarqueeDirection:
-            return cssValuePool().createValue(style->marqueeDirection());
         case CSSPropertyWebkitMarqueeIncrement:
             return cssValuePool().createValue(style->marqueeIncrement());
         case CSSPropertyWebkitMarqueeRepetition:
@@ -2101,6 +2130,8 @@
             if (style->minWidth().isAuto())
                 return zoomAdjustedPixelValue(0, style.get());
             return zoomAdjustedPixelValueForLength(style->minWidth(), style.get());
+        case CSSPropertyObjectFit:
+            return cssValuePool().createValue(style->objectFit());
         case CSSPropertyOpacity:
             return cssValuePool().createValue(style->opacity(), CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyOrphans:
@@ -2163,7 +2194,7 @@
         case CSSPropertyPosition:
             return cssValuePool().createValue(style->position());
         case CSSPropertyRight:
-            return getPositionOffsetValue(style.get(), CSSPropertyRight, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyRight, renderer, m_node->document()->renderView());
         case CSSPropertyWebkitRubyPosition:
             return cssValuePool().createValue(style->rubyPosition());
         case CSSPropertyTableLayout:
@@ -2173,10 +2204,11 @@
         case CSSPropertyTextAlignLast:
             return cssValuePool().createValue(style->textAlignLast());
         case CSSPropertyTextDecoration:
+            return valuesForShorthandProperty(textDecorationShorthand());
         case CSSPropertyTextDecorationLine:
             return renderTextDecorationFlagsToCSSValue(style->textDecoration());
         case CSSPropertyTextDecorationStyle:
-            return renderTextDecorationStyleFlagsToCSSValue(style->textDecorationStyle());
+            return valueForTextDecorationStyle(style->textDecorationStyle());
         case CSSPropertyTextDecorationColor:
             return currentColorOrValidColor(style.get(), style->textDecorationColor());
 #if ENABLE(CSS3_TEXT)
@@ -2240,7 +2272,7 @@
         case CSSPropertyTextTransform:
             return cssValuePool().createValue(style->textTransform());
         case CSSPropertyTop:
-            return getPositionOffsetValue(style.get(), CSSPropertyTop, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyTop, renderer, m_node->document()->renderView());
         case CSSPropertyTouchAction:
             return cssValuePool().createValue(style->touchAction());
         case CSSPropertyUnicodeBidi:
@@ -2330,48 +2362,45 @@
             return cssValuePool().createIdentifierValue(CSSValueBorderBox);
         case CSSPropertyWebkitAppRegion:
             return cssValuePool().createIdentifierValue(style->getDraggableRegionMode() == DraggableRegionDrag ? CSSValueDrag : CSSValueNoDrag);
+        case CSSPropertyAnimationDelay:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationDelay:
-            return getDelayValue(style->animations());
+            return valueForAnimationDelay(style->animations());
+        case CSSPropertyAnimationDirection:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationDirection: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
             if (t) {
-                for (size_t i = 0; i < t->size(); ++i) {
-                    if (t->animation(i)->direction())
-                        list->append(cssValuePool().createIdentifierValue(CSSValueAlternate));
-                    else
-                        list->append(cssValuePool().createIdentifierValue(CSSValueNormal));
-                }
+                for (size_t i = 0; i < t->size(); ++i)
+                    list->append(valueForAnimationDirection(t->animation(i)->direction()));
             } else
                 list->append(cssValuePool().createIdentifierValue(CSSValueNormal));
             return list.release();
         }
+        case CSSPropertyAnimationDuration:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationDuration:
-            return getDurationValue(style->animations());
+            return valueForAnimationDuration(style->animations());
+        case CSSPropertyAnimationFillMode:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationFillMode: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
             if (t) {
-                for (size_t i = 0; i < t->size(); ++i) {
-                    switch (t->animation(i)->fillMode()) {
-                    case AnimationFillModeNone:
-                        list->append(cssValuePool().createIdentifierValue(CSSValueNone));
-                        break;
-                    case AnimationFillModeForwards:
-                        list->append(cssValuePool().createIdentifierValue(CSSValueForwards));
-                        break;
-                    case AnimationFillModeBackwards:
-                        list->append(cssValuePool().createIdentifierValue(CSSValueBackwards));
-                        break;
-                    case AnimationFillModeBoth:
-                        list->append(cssValuePool().createIdentifierValue(CSSValueBoth));
-                        break;
-                    }
-                }
+                for (size_t i = 0; i < t->size(); ++i)
+                    list->append(valueForAnimationFillMode(t->animation(i)->fillMode()));
             } else
                 list->append(cssValuePool().createIdentifierValue(CSSValueNone));
             return list.release();
         }
+        case CSSPropertyAnimationIterationCount:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationIterationCount: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2387,6 +2416,9 @@
                 list->append(cssValuePool().createValue(CSSAnimationData::initialAnimationIterationCount(), CSSPrimitiveValue::CSS_NUMBER));
             return list.release();
         }
+        case CSSPropertyAnimationName:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationName: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2397,6 +2429,9 @@
                 list->append(cssValuePool().createIdentifierValue(CSSValueNone));
             return list.release();
         }
+        case CSSPropertyAnimationPlayState:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationPlayState: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2412,8 +2447,51 @@
                 list->append(cssValuePool().createIdentifierValue(CSSValueRunning));
             return list.release();
         }
+        case CSSPropertyAnimationTimingFunction:
+            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+                break;
         case CSSPropertyWebkitAnimationTimingFunction:
-            return getTimingFunctionValue(style->animations());
+            return valueForAnimationTimingFunction(style->animations());
+        case CSSPropertyAnimation:
+        case CSSPropertyWebkitAnimation: {
+            const CSSAnimationDataList* animations = style->animations();
+            if (animations) {
+                RefPtr<CSSValueList> animationsList = CSSValueList::createCommaSeparated();
+                for (size_t i = 0; i < animations->size(); ++i) {
+                    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+                    const CSSAnimationData* animation = animations->animation(i);
+                    list->append(cssValuePool().createValue(animation->name(), CSSPrimitiveValue::CSS_STRING));
+                    list->append(cssValuePool().createValue(animation->duration(), CSSPrimitiveValue::CSS_S));
+                    list->append(createTimingFunctionValue(animation->timingFunction().get()));
+                    list->append(cssValuePool().createValue(animation->delay(), CSSPrimitiveValue::CSS_S));
+                    if (animation->iterationCount() == CSSAnimationData::IterationCountInfinite)
+                        list->append(cssValuePool().createIdentifierValue(CSSValueInfinite));
+                    else
+                        list->append(cssValuePool().createValue(animation->iterationCount(), CSSPrimitiveValue::CSS_NUMBER));
+                    list->append(valueForAnimationDirection(animation->direction()));
+                    list->append(valueForAnimationFillMode(animation->fillMode()));
+                    if (animation->playState() == AnimPlayStatePaused)
+                        list->append(cssValuePool().createIdentifierValue(CSSValuePaused));
+                    else
+                        list->append(cssValuePool().createIdentifierValue(CSSValueRunning));
+                    animationsList->append(list);
+                }
+                return animationsList.release();
+            }
+
+            RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            // animation-name default value.
+            list->append(cssValuePool().createIdentifierValue(CSSValueNone));
+            list->append(cssValuePool().createValue(CSSAnimationData::initialAnimationDuration(), CSSPrimitiveValue::CSS_S));
+            list->append(createTimingFunctionValue(CSSAnimationData::initialAnimationTimingFunction().get()));
+            list->append(cssValuePool().createValue(CSSAnimationData::initialAnimationDelay(), CSSPrimitiveValue::CSS_S));
+            list->append(cssValuePool().createValue(CSSAnimationData::initialAnimationIterationCount(), CSSPrimitiveValue::CSS_NUMBER));
+            list->append(valueForAnimationDirection(CSSAnimationData::initialAnimationDirection()));
+            list->append(valueForAnimationFillMode(CSSAnimationData::initialAnimationFillMode()));
+            // Initial animation-play-state.
+            list->append(cssValuePool().createIdentifierValue(CSSValueRunning));
+            return list.release();
+        }
         case CSSPropertyWebkitAppearance:
             return cssValuePool().createValue(style->appearance());
         case CSSPropertyWebkitAspectRatio:
@@ -2486,13 +2564,13 @@
         case CSSPropertyWebkitUserSelect:
             return cssValuePool().createValue(style->userSelect());
         case CSSPropertyBorderBottomLeftRadius:
-            return getBorderRadiusCornerValue(style->borderBottomLeftRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), style.get(), m_node->document()->renderView());
         case CSSPropertyBorderBottomRightRadius:
-            return getBorderRadiusCornerValue(style->borderBottomRightRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderBottomRightRadius(), style.get(), m_node->document()->renderView());
         case CSSPropertyBorderTopLeftRadius:
-            return getBorderRadiusCornerValue(style->borderTopLeftRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderTopLeftRadius(), style.get(), m_node->document()->renderView());
         case CSSPropertyBorderTopRightRadius:
-            return getBorderRadiusCornerValue(style->borderTopRightRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderTopRightRadius(), style.get(), m_node->document()->renderView());
         case CSSPropertyClip: {
             if (!style->hasClip())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -2531,16 +2609,16 @@
             return cssValuePool().createIdentifierValue((style->transformStyle3D() == TransformStyle3DPreserve3D) ? CSSValuePreserve3d : CSSValueFlat);
         case CSSPropertyTransitionDelay:
         case CSSPropertyWebkitTransitionDelay:
-            return getDelayValue(style->transitions());
+            return valueForAnimationDelay(style->transitions());
         case CSSPropertyTransitionDuration:
         case CSSPropertyWebkitTransitionDuration:
-            return getDurationValue(style->transitions());
+            return valueForAnimationDuration(style->transitions());
         case CSSPropertyTransitionProperty:
         case CSSPropertyWebkitTransitionProperty:
-            return getTransitionPropertyValue(style->transitions());
+            return valueForTransitionProperty(style->transitions());
         case CSSPropertyTransitionTimingFunction:
         case CSSPropertyWebkitTransitionTimingFunction:
-            return getTimingFunctionValue(style->transitions());
+            return valueForAnimationTimingFunction(style->transitions());
         case CSSPropertyTransition:
         case CSSPropertyWebkitTransition: {
             const CSSAnimationDataList* animList = style->transitions();
@@ -2585,11 +2663,11 @@
         case CSSPropertyWebkitLineBoxContain:
             return createLineBoxContainValue(style->lineBoxContain());
         case CSSPropertyContent:
-            return contentToCSSValue(style.get());
+            return valueForContentData(style.get());
         case CSSPropertyCounterIncrement:
-            return counterToCSSValue(style.get(), propertyID);
+            return valueForCounterDirectives(style.get(), propertyID);
         case CSSPropertyCounterReset:
-            return counterToCSSValue(style.get(), propertyID);
+            return valueForCounterDirectives(style.get(), propertyID);
         case CSSPropertyWebkitClipPath:
             if (ClipPathOperation* operation = style->clipPath()) {
                 if (operation->getOperationType() == ClipPathOperation::SHAPE)
@@ -2657,7 +2735,7 @@
             return list.release();
         }
         case CSSPropertyBackground:
-            return getBackgroundShorthandValue();
+            return valuesForBackgroundShorthand();
         case CSSPropertyBorder: {
             RefPtr<CSSValue> value = getPropertyCSSValue(CSSPropertyBorderTop, DoNotUpdateLayout);
             const CSSPropertyID properties[3] = { CSSPropertyBorderRight, CSSPropertyBorderBottom,
@@ -2669,35 +2747,35 @@
             return value.release();
         }
         case CSSPropertyBorderBottom:
-            return getCSSPropertyValuesForShorthandProperties(borderBottomShorthand());
+            return valuesForShorthandProperty(borderBottomShorthand());
         case CSSPropertyBorderColor:
-            return getCSSPropertyValuesForSidesShorthand(borderColorShorthand());
+            return valuesForSidesShorthand(borderColorShorthand());
         case CSSPropertyBorderLeft:
-            return getCSSPropertyValuesForShorthandProperties(borderLeftShorthand());
+            return valuesForShorthandProperty(borderLeftShorthand());
         case CSSPropertyBorderImage:
             return valueForNinePieceImage(style->borderImage());
         case CSSPropertyBorderRadius:
-            return getBorderRadiusShorthandValue(style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusShorthand(style.get(), m_node->document()->renderView());
         case CSSPropertyBorderRight:
-            return getCSSPropertyValuesForShorthandProperties(borderRightShorthand());
+            return valuesForShorthandProperty(borderRightShorthand());
         case CSSPropertyBorderStyle:
-            return getCSSPropertyValuesForSidesShorthand(borderStyleShorthand());
+            return valuesForSidesShorthand(borderStyleShorthand());
         case CSSPropertyBorderTop:
-            return getCSSPropertyValuesForShorthandProperties(borderTopShorthand());
+            return valuesForShorthandProperty(borderTopShorthand());
         case CSSPropertyBorderWidth:
-            return getCSSPropertyValuesForSidesShorthand(borderWidthShorthand());
+            return valuesForSidesShorthand(borderWidthShorthand());
         case CSSPropertyWebkitColumnRule:
-            return getCSSPropertyValuesForShorthandProperties(webkitColumnRuleShorthand());
+            return valuesForShorthandProperty(webkitColumnRuleShorthand());
         case CSSPropertyWebkitColumns:
-            return getCSSPropertyValuesForShorthandProperties(webkitColumnsShorthand());
+            return valuesForShorthandProperty(webkitColumnsShorthand());
         case CSSPropertyListStyle:
-            return getCSSPropertyValuesForShorthandProperties(listStyleShorthand());
+            return valuesForShorthandProperty(listStyleShorthand());
         case CSSPropertyMargin:
-            return getCSSPropertyValuesForSidesShorthand(marginShorthand());
+            return valuesForSidesShorthand(marginShorthand());
         case CSSPropertyOutline:
-            return getCSSPropertyValuesForShorthandProperties(outlineShorthand());
+            return valuesForShorthandProperty(outlineShorthand());
         case CSSPropertyPadding:
-            return getCSSPropertyValuesForSidesShorthand(paddingShorthand());
+            return valuesForSidesShorthand(paddingShorthand());
         /* Individual properties not part of the spec */
         case CSSPropertyBackgroundRepeatX:
         case CSSPropertyBackgroundRepeatY:
@@ -2766,10 +2844,8 @@
             break;
 
         /* Unimplemented -webkit- properties */
-        case CSSPropertyWebkitAnimation:
         case CSSPropertyWebkitBorderRadius:
         case CSSPropertyWebkitMarginCollapse:
-        case CSSPropertyWebkitMarquee:
         case CSSPropertyWebkitMarqueeSpeed:
         case CSSPropertyWebkitMask:
         case CSSPropertyWebkitMaskRepeatX:
@@ -2789,6 +2865,11 @@
         case CSSPropertyUserZoom:
             break;
 
+        // Internal properties that shouldn't be exposed throught getComputedStyle.
+        case CSSPropertyInternalMarqueeDirection:
+            ASSERT_NOT_REACHED();
+            return 0;
+
         case CSSPropertyBufferedRendering:
         case CSSPropertyClipPath:
         case CSSPropertyClipRule:
@@ -2829,6 +2910,7 @@
         case CSSPropertyKerning:
         case CSSPropertyTextAnchor:
         case CSSPropertyVectorEffect:
+        case CSSPropertyPaintOrder:
         case CSSPropertyWritingMode:
             return getSVGPropertyCSSValue(propertyID, DoNotUpdateLayout);
     }
@@ -2888,7 +2970,7 @@
     return copyPropertiesInSet(computableProperties());
 }
 
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::getCSSPropertyValuesForShorthandProperties(const StylePropertyShorthand& shorthand) const
+PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForShorthandProperty(const StylePropertyShorthand& shorthand) const
 {
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     for (size_t i = 0; i < shorthand.length(); ++i) {
@@ -2898,7 +2980,7 @@
     return list.release();
 }
 
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::getCSSPropertyValuesForSidesShorthand(const StylePropertyShorthand& shorthand) const
+PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForSidesShorthand(const StylePropertyShorthand& shorthand) const
 {
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     // Assume the properties are in the usual order top, right, bottom, left.
@@ -2926,7 +3008,7 @@
     return list.release();
 }
 
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::getCSSPropertyValuesForGridShorthand(const StylePropertyShorthand& shorthand) const
+PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForGridShorthand(const StylePropertyShorthand& shorthand) const
 {
     RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
     for (size_t i = 0; i < shorthand.length(); ++i) {
@@ -2962,10 +3044,12 @@
     return value ? value->cloneForCSSOM() : 0;
 }
 
-String CSSComputedStyleDeclaration::getPropertyValue(const String &propertyName)
+String CSSComputedStyleDeclaration::getPropertyValue(const String& propertyName)
 {
     CSSPropertyID propertyID = cssPropertyID(propertyName);
-    if (!propertyID)
+    // FIXME: This should check RuntimeEnabledFeature::isCSSPropertyEnabled instead of just
+    // isInternalProperty. However we need to test that which requires crbug.com/234853 to be fixed.
+    if (!propertyID || isInternalProperty(propertyID))
         return String();
     return getPropertyValue(propertyID);
 }
@@ -3063,7 +3147,7 @@
     es.throwDOMException(NoModificationAllowedError, "Failed to clear variables from a computed 'CSSStyleDeclaration': computed styles are read-only.");
 }
 
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::getBackgroundShorthandValue() const
+PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForBackgroundShorthand() const
 {
     static const CSSPropertyID propertiesBeforeSlashSeperator[5] = { CSSPropertyBackgroundColor, CSSPropertyBackgroundImage,
                                                                      CSSPropertyBackgroundRepeat, CSSPropertyBackgroundAttachment,
@@ -3072,8 +3156,8 @@
                                                                     CSSPropertyBackgroundClip };
 
     RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
-    list->append(getCSSPropertyValuesForShorthandProperties(StylePropertyShorthand(CSSPropertyBackground, propertiesBeforeSlashSeperator, WTF_ARRAY_LENGTH(propertiesBeforeSlashSeperator))));
-    list->append(getCSSPropertyValuesForShorthandProperties(StylePropertyShorthand(CSSPropertyBackground, propertiesAfterSlashSeperator, WTF_ARRAY_LENGTH(propertiesAfterSlashSeperator))));
+    list->append(valuesForShorthandProperty(StylePropertyShorthand(CSSPropertyBackground, propertiesBeforeSlashSeperator, WTF_ARRAY_LENGTH(propertiesBeforeSlashSeperator))));
+    list->append(valuesForShorthandProperty(StylePropertyShorthand(CSSPropertyBackground, propertiesAfterSlashSeperator, WTF_ARRAY_LENGTH(propertiesAfterSlashSeperator))));
     return list.release();
 }
 
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index 3e461e2..a42ca6e 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -117,10 +117,10 @@
 
     PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle*) const;
 
-    PassRefPtr<CSSValueList> getCSSPropertyValuesForShorthandProperties(const StylePropertyShorthand&) const;
-    PassRefPtr<CSSValueList> getCSSPropertyValuesForSidesShorthand(const StylePropertyShorthand&) const;
-    PassRefPtr<CSSValueList> getBackgroundShorthandValue() const;
-    PassRefPtr<CSSValueList> getCSSPropertyValuesForGridShorthand(const StylePropertyShorthand&) const;
+    PassRefPtr<CSSValueList> valuesForShorthandProperty(const StylePropertyShorthand&) const;
+    PassRefPtr<CSSValueList> valuesForSidesShorthand(const StylePropertyShorthand&) const;
+    PassRefPtr<CSSValueList> valuesForBackgroundShorthand() const;
+    PassRefPtr<CSSValueList> valuesForGridShorthand(const StylePropertyShorthand&) const;
 
     RefPtr<Node> m_node;
     PseudoId m_pseudoElementSpecifier;
diff --git a/Source/core/css/CSSCrossfadeValue.cpp b/Source/core/css/CSSCrossfadeValue.cpp
index c48eaf2..d409f79 100644
--- a/Source/core/css/CSSCrossfadeValue.cpp
+++ b/Source/core/css/CSSCrossfadeValue.cpp
@@ -27,7 +27,7 @@
 #include "core/css/CSSCrossfadeValue.h"
 
 #include "core/css/CSSImageValue.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/platform/graphics/CrossfadeGeneratedImage.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/style/StyleFetchedImage.h"
diff --git a/Source/core/css/CSSCrossfadeValue.h b/Source/core/css/CSSCrossfadeValue.h
index 450b615..4df7520 100644
--- a/Source/core/css/CSSCrossfadeValue.h
+++ b/Source/core/css/CSSCrossfadeValue.h
@@ -28,9 +28,9 @@
 
 #include "core/css/CSSImageGeneratorValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ImageResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ImageResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/graphics/Image.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSCursorImageValue.cpp b/Source/core/css/CSSCursorImageValue.cpp
index 21deed7..dd68e0b 100644
--- a/Source/core/css/CSSCursorImageValue.cpp
+++ b/Source/core/css/CSSCursorImageValue.cpp
@@ -25,8 +25,8 @@
 #include "SVGNames.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSImageValue.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/rendering/style/StyleFetchedImage.h"
 #include "core/rendering/style/StyleFetchedImageSet.h"
 #include "core/rendering/style/StyleImage.h"
diff --git a/Source/core/css/CSSFilterValue.h b/Source/core/css/CSSFilterValue.h
index d937e0c..3398cfa 100644
--- a/Source/core/css/CSSFilterValue.h
+++ b/Source/core/css/CSSFilterValue.h
@@ -66,8 +66,8 @@
     bool equals(const CSSFilterValue&) const;
 
 private:
-    CSSFilterValue(FilterOperationType);
-    CSSFilterValue(const CSSFilterValue& cloneFrom);
+    explicit CSSFilterValue(FilterOperationType);
+    explicit CSSFilterValue(const CSSFilterValue& cloneFrom);
 
     FilterOperationType m_type;
 };
diff --git a/Source/core/css/CSSFontFace.cpp b/Source/core/css/CSSFontFace.cpp
index 0acd552..efb19e2 100644
--- a/Source/core/css/CSSFontFace.cpp
+++ b/Source/core/css/CSSFontFace.cpp
@@ -55,36 +55,30 @@
     return false;
 }
 
-void CSSFontFace::addedToSegmentedFontFace(CSSSegmentedFontFace* segmentedFontFace)
-{
-    m_segmentedFontFaces.add(segmentedFontFace);
-}
-
-void CSSFontFace::removedFromSegmentedFontFace(CSSSegmentedFontFace* segmentedFontFace)
-{
-    m_segmentedFontFaces.remove(segmentedFontFace);
-}
-
 void CSSFontFace::addSource(PassOwnPtr<CSSFontFaceSource> source)
 {
     source->setFontFace(this);
     m_sources.append(source);
 }
 
+void CSSFontFace::setSegmentedFontFace(CSSSegmentedFontFace* segmentedFontFace)
+{
+    ASSERT(!m_segmentedFontFace);
+    m_segmentedFontFace = segmentedFontFace;
+}
+
 void CSSFontFace::fontLoaded(CSSFontFaceSource* source)
 {
     if (source != m_activeSource)
         return;
 
-    // FIXME: Can we assert that m_segmentedFontFaces is not empty? That may
+    // FIXME: Can we assert that m_segmentedFontFace is non-null? That may
     // require stopping in-progress font loading when the last
     // CSSSegmentedFontFace is removed.
-    if (m_segmentedFontFaces.isEmpty())
+    if (!m_segmentedFontFace)
         return;
 
-    // Use one of the CSSSegmentedFontFaces' font selector. They all have
-    // the same font selector, so it's wasteful to store it in the CSSFontFace.
-    CSSFontSelector* fontSelector = (*m_segmentedFontFaces.begin())->fontSelector();
+    CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
     fontSelector->fontLoaded();
 
     if (fontSelector->document() && m_loadState == Loading) {
@@ -94,9 +88,7 @@
             setLoadState(Error);
     }
 
-    HashSet<CSSSegmentedFontFace*>::iterator end = m_segmentedFontFaces.end();
-    for (HashSet<CSSSegmentedFontFace*>::iterator it = m_segmentedFontFaces.begin(); it != end; ++it)
-        (*it)->fontLoaded(this);
+    m_segmentedFontFace->fontLoaded(this);
 }
 
 PassRefPtr<SimpleFontData> CSSFontFace::getFontData(const FontDescription& fontDescription, bool syntheticBold, bool syntheticItalic)
@@ -105,8 +97,8 @@
     if (!isValid())
         return 0;
 
-    ASSERT(!m_segmentedFontFaces.isEmpty());
-    CSSFontSelector* fontSelector = (*m_segmentedFontFaces.begin())->fontSelector();
+    ASSERT(m_segmentedFontFace);
+    CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
 
     if (m_loadState == NotLoaded)
         setLoadState(Loading);
@@ -126,11 +118,29 @@
     return 0;
 }
 
+void CSSFontFace::willUseFontData(const FontDescription& fontDescription)
+{
+    if (m_loadState != NotLoaded)
+        return;
+
+    ASSERT(m_segmentedFontFace);
+    CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
+
+    size_t size = m_sources.size();
+    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())
+            m_sources[i]->willUseFontData();
+        break;
+    }
+}
+
 void CSSFontFace::setLoadState(LoadState newState)
 {
     m_loadState = newState;
 
-    Document* document = (*m_segmentedFontFaces.begin())->fontSelector()->document();
+    Document* document = m_segmentedFontFace->fontSelector()->document();
     if (!document)
         return;
 
diff --git a/Source/core/css/CSSFontFace.h b/Source/core/css/CSSFontFace.h
index 31bf1b5..1b40b34 100644
--- a/Source/core/css/CSSFontFace.h
+++ b/Source/core/css/CSSFontFace.h
@@ -28,9 +28,7 @@
 
 #include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSFontFaceSource.h"
-#include "core/platform/graphics/FontTraitsMask.h"
 #include "wtf/Forward.h"
-#include "wtf/HashSet.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
@@ -43,23 +41,19 @@
 
 class CSSFontFace : public RefCounted<CSSFontFace> {
 public:
-    static PassRefPtr<CSSFontFace> create(FontTraitsMask traitsMask, PassRefPtr<CSSFontFaceRule> rule, bool isLocalFallback = false) { return adoptRef(new CSSFontFace(traitsMask, rule, isLocalFallback)); }
-
-    FontTraitsMask traitsMask() const { return m_traitsMask; }
+    static PassRefPtr<CSSFontFace> create(PassRefPtr<CSSFontFaceRule> rule, bool isLocalFallback = false) { return adoptRef(new CSSFontFace(rule, isLocalFallback)); }
 
     struct UnicodeRange;
 
     void addRange(UChar32 from, UChar32 to) { m_ranges.append(UnicodeRange(from, to)); }
     const Vector<UnicodeRange>& ranges() const { return m_ranges; }
 
-    void addedToSegmentedFontFace(CSSSegmentedFontFace*);
-    void removedFromSegmentedFontFace(CSSSegmentedFontFace*);
+    void setSegmentedFontFace(CSSSegmentedFontFace*);
+    void clearSegmentedFontFace() { m_segmentedFontFace = 0; }
 
     bool isLoaded() const;
     bool isValid() const;
 
-    bool isLocalFallback() const { return m_isLocalFallback; }
-
     void addSource(PassOwnPtr<CSSFontFaceSource>);
 
     void fontLoaded(CSSFontFaceSource*);
@@ -87,12 +81,12 @@
 
     enum LoadState { NotLoaded, Loading, Loaded, Error };
     LoadState loadState() const { return m_loadState; }
+    void willUseFontData(const FontDescription&);
 
 private:
-    CSSFontFace(FontTraitsMask traitsMask, PassRefPtr<CSSFontFaceRule> rule, bool isLocalFallback)
-        : m_traitsMask(traitsMask)
+    CSSFontFace(PassRefPtr<CSSFontFaceRule> rule, bool isLocalFallback)
+        : m_segmentedFontFace(0)
         , m_activeSource(0)
-        , m_isLocalFallback(isLocalFallback)
         , m_loadState(isLocalFallback ? Loaded : NotLoaded)
         , m_rule(rule)
     {
@@ -100,12 +94,10 @@
     }
     void setLoadState(LoadState);
 
-    FontTraitsMask m_traitsMask;
     Vector<UnicodeRange> m_ranges;
-    HashSet<CSSSegmentedFontFace*> m_segmentedFontFaces;
+    CSSSegmentedFontFace* m_segmentedFontFace;
     Vector<OwnPtr<CSSFontFaceSource> > m_sources;
     CSSFontFaceSource* m_activeSource;
-    bool m_isLocalFallback;
     LoadState m_loadState;
     RefPtr<CSSFontFaceRule> m_rule;
 };
diff --git a/Source/core/css/CSSFontFaceSource.cpp b/Source/core/css/CSSFontFaceSource.cpp
index 1f160aa..106a66b 100644
--- a/Source/core/css/CSSFontFaceSource.cpp
+++ b/Source/core/css/CSSFontFaceSource.cpp
@@ -28,7 +28,7 @@
 
 #include "core/css/CSSFontFace.h"
 #include "core/css/CSSFontSelector.h"
-#include "core/loader/cache/FontResource.h"
+#include "core/fetch/FontResource.h"
 #include "core/platform/HistogramSupport.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/FontDescription.h"
@@ -71,6 +71,17 @@
     m_fontDataTable.clear();
 }
 
+bool CSSFontFaceSource::isLocal() const
+{
+    if (m_font)
+        return false;
+#if ENABLE(SVG_FONTS)
+    if (m_svgFontFaceElement)
+        return false;
+#endif
+    return true;
+}
+
 bool CSSFontFaceSource::isLoaded() const
 {
     if (m_font)
@@ -109,11 +120,7 @@
     if (!isValid())
         return 0;
 
-    if (!m_font
-#if ENABLE(SVG_FONTS)
-            && !m_svgFontFaceElement
-#endif
-    ) {
+    if (isLocal()) {
         // We're local. Just return a SimpleFontData from the normal cache.
         // We don't want to check alternate font family names here, so pass true as the checkingAlternateName parameter.
         RefPtr<SimpleFontData> fontData = fontCache()->getFontResourceData(fontDescription, m_string, true);
@@ -234,10 +241,46 @@
     return m_font->ensureCustomFontData();
 }
 
+bool CSSFontFaceSource::isLocalFontAvailable(const FontDescription& fontDescription)
+{
+    if (!isLocal())
+        return false;
+    return fontCache()->isPlatformFontAvailable(fontDescription, m_string, true);
+}
+
+void CSSFontFaceSource::willUseFontData()
+{
+    if (!isLoaded())
+        m_histograms.willUseFontData();
+}
+
+CSSFontFaceSource::FontLoadHistograms::~FontLoadHistograms()
+{
+    if (m_styledTime > 0)
+        HistogramSupport::histogramEnumeration("WebFont.UsageType", StyledButNotUsed, UsageTypeMax);
+}
+
+void CSSFontFaceSource::FontLoadHistograms::willUseFontData()
+{
+    if (!m_styledTime)
+        m_styledTime = currentTimeMS();
+}
+
 void CSSFontFaceSource::FontLoadHistograms::loadStarted()
 {
     if (!m_loadStartTime)
         m_loadStartTime = currentTimeMS();
+
+    if (m_styledTime < 0)
+        return;
+    if (!m_styledTime) {
+        HistogramSupport::histogramEnumeration("WebFont.UsageType", NotStyledButUsed, UsageTypeMax);
+    } else {
+        int duration = static_cast<int>(currentTimeMS() - m_styledTime);
+        HistogramSupport::histogramCustomCounts("WebFont.StyleRecalcToDownloadLatency", duration, 0, 10000, 50);
+        HistogramSupport::histogramEnumeration("WebFont.UsageType", StyledAndUsed, UsageTypeMax);
+    }
+    m_styledTime = -1;
 }
 
 void CSSFontFaceSource::FontLoadHistograms::recordLocalFont(bool loadSuccess)
diff --git a/Source/core/css/CSSFontFaceSource.h b/Source/core/css/CSSFontFaceSource.h
index aea2ac5..ebb733b 100644
--- a/Source/core/css/CSSFontFaceSource.h
+++ b/Source/core/css/CSSFontFaceSource.h
@@ -26,8 +26,8 @@
 #ifndef CSSFontFaceSource_h
 #define CSSFontFaceSource_h
 
-#include "core/loader/cache/FontResource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "wtf/HashMap.h"
 #include "wtf/text/AtomicString.h"
@@ -50,6 +50,7 @@
     CSSFontFaceSource(const String&, FontResource* = 0);
     virtual ~CSSFontFaceSource();
 
+    bool isLocal() const;
     bool isLoaded() const;
     bool isValid() const;
 
@@ -73,16 +74,27 @@
 
     bool isDecodeError() const;
     bool ensureFontData();
+    bool isLocalFontAvailable(const FontDescription&);
+    void willUseFontData();
 
 private:
     class FontLoadHistograms {
     public:
-        FontLoadHistograms() : m_loadStartTime(0) { }
+        enum UsageType {
+            StyledAndUsed,
+            StyledButNotUsed,
+            NotStyledButUsed,
+            UsageTypeMax
+        };
+        FontLoadHistograms() : m_styledTime(0), m_loadStartTime(0) { }
+        ~FontLoadHistograms();
+        void willUseFontData();
         void loadStarted();
         void recordLocalFont(bool loadSuccess);
         void recordRemoteFont(const FontResource*);
     private:
         const char* histogramName(const FontResource*);
+        double m_styledTime;
         double m_loadStartTime;
     };
 
diff --git a/Source/core/css/CSSFontFaceSrcValue.cpp b/Source/core/css/CSSFontFaceSrcValue.cpp
index 46fd349..7b3cef6 100644
--- a/Source/core/css/CSSFontFaceSrcValue.cpp
+++ b/Source/core/css/CSSFontFaceSrcValue.cpp
@@ -30,9 +30,9 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/dom/Node.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/FontResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/platform/graphics/FontCustomPlatformData.h"
 #include "core/svg/SVGFontFaceElement.h"
 #include "wtf/text/StringBuilder.h"
diff --git a/Source/core/css/CSSFontFaceSrcValue.h b/Source/core/css/CSSFontFaceSrcValue.h
index 023e38e..9129f1c 100644
--- a/Source/core/css/CSSFontFaceSrcValue.h
+++ b/Source/core/css/CSSFontFaceSrcValue.h
@@ -27,7 +27,7 @@
 #define CSSFontFaceSrcValue_h
 
 #include "core/css/CSSValue.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourcePtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/css/CSSFontSelector.cpp b/Source/core/css/CSSFontSelector.cpp
index f721acd..b608878 100644
--- a/Source/core/css/CSSFontSelector.cpp
+++ b/Source/core/css/CSSFontSelector.cpp
@@ -43,9 +43,9 @@
 #include "core/css/StyleRule.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/FontResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Frame.h"
 #include "core/page/Settings.h"
 #include "core/platform/graphics/FontCache.h"
@@ -229,7 +229,7 @@
             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=112116 - This CSSFontFaceRule has no parent.
             if (RuntimeEnabledFeatures::fontLoadEventsEnabled())
                 rule = static_pointer_cast<CSSFontFaceRule>(fontFaceRule->createCSSOMWrapper());
-            fontFace = CSSFontFace::create(static_cast<FontTraitsMask>(traitsMask), rule);
+            fontFace = CSSFontFace::create(rule);
         }
 
         if (source) {
@@ -287,29 +287,36 @@
     if (familyName.isEmpty())
         return;
 
-    OwnPtr<Vector<RefPtr<CSSFontFace> > >& familyFontFaces = m_fontFaces.add(familyName, nullptr).iterator->value;
+    OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& familyFontFaces = m_fontFaces.add(familyName, nullptr).iterator->value;
     if (!familyFontFaces) {
-        familyFontFaces = adoptPtr(new Vector<RefPtr<CSSFontFace> >);
+        familyFontFaces = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);
 
         ASSERT(!m_locallyInstalledFontFaces.contains(familyName));
 
         Vector<unsigned> locallyInstalledFontsTraitsMasks;
         fontCache()->getTraitsInFamily(familyName, locallyInstalledFontsTraitsMasks);
         if (unsigned numLocallyInstalledFaces = locallyInstalledFontsTraitsMasks.size()) {
-            OwnPtr<Vector<RefPtr<CSSFontFace> > > familyLocallyInstalledFaces = adoptPtr(new Vector<RefPtr<CSSFontFace> >);
+            OwnPtr<Vector<RefPtr<CSSSegmentedFontFace> > > familyLocallyInstalledFaces = adoptPtr(new Vector<RefPtr<CSSSegmentedFontFace> >);
 
             for (unsigned i = 0; i < numLocallyInstalledFaces; ++i) {
-                RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]), 0, true);
+                RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(0);
                 locallyInstalledFontFace->addSource(adoptPtr(new CSSFontFaceSource(familyName)));
                 ASSERT(locallyInstalledFontFace->isValid());
-                familyLocallyInstalledFaces->append(locallyInstalledFontFace);
+
+                RefPtr<CSSSegmentedFontFace> segmentedFontFace = CSSSegmentedFontFace::create(this, static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]), true);
+                segmentedFontFace->appendFontFace(locallyInstalledFontFace.release());
+                familyLocallyInstalledFaces->append(segmentedFontFace);
             }
 
             m_locallyInstalledFontFaces.set(familyName, familyLocallyInstalledFaces.release());
         }
     }
 
-    familyFontFaces->append(fontFace);
+    RefPtr<CSSSegmentedFontFace>& segmentedFontFace = familyFontFaces->add(traitsMask, 0).iterator->value;
+    if (!segmentedFontFace)
+        segmentedFontFace = CSSSegmentedFontFace::create(this, static_cast<FontTraitsMask>(traitsMask), false);
+
+    segmentedFontFace->appendFontFace(fontFace);
 
     ++m_version;
 }
@@ -384,21 +391,19 @@
     return 0;
 }
 
-static FontTraitsMask desiredTraitsMaskForComparison;
-
-static inline bool compareFontFaces(CSSFontFace* first, CSSFontFace* second)
+static inline bool compareFontFaces(CSSSegmentedFontFace* first, CSSSegmentedFontFace* second, FontTraitsMask desiredTraitsMask)
 {
     FontTraitsMask firstTraitsMask = first->traitsMask();
     FontTraitsMask secondTraitsMask = second->traitsMask();
 
-    bool firstHasDesiredVariant = firstTraitsMask & desiredTraitsMaskForComparison & FontVariantMask;
-    bool secondHasDesiredVariant = secondTraitsMask & desiredTraitsMaskForComparison & FontVariantMask;
+    bool firstHasDesiredVariant = firstTraitsMask & desiredTraitsMask & FontVariantMask;
+    bool secondHasDesiredVariant = secondTraitsMask & desiredTraitsMask & FontVariantMask;
 
     if (firstHasDesiredVariant != secondHasDesiredVariant)
         return firstHasDesiredVariant;
 
     // We need to check font-variant css property for CSS2.1 compatibility.
-    if ((desiredTraitsMaskForComparison & FontVariantSmallCapsMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
+    if ((desiredTraitsMask & FontVariantSmallCapsMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
         // 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);
@@ -407,13 +412,13 @@
             return firstRequiresSmallCaps;
     }
 
-    bool firstHasDesiredStyle = firstTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
-    bool secondHasDesiredStyle = secondTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
+    bool firstHasDesiredStyle = firstTraitsMask & desiredTraitsMask & FontStyleMask;
+    bool secondHasDesiredStyle = secondTraitsMask & desiredTraitsMask & FontStyleMask;
 
     if (firstHasDesiredStyle != secondHasDesiredStyle)
         return firstHasDesiredStyle;
 
-    if ((desiredTraitsMaskForComparison & FontStyleItalicMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
+    if ((desiredTraitsMask & FontStyleItalicMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
         // 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);
@@ -422,9 +427,9 @@
             return firstRequiresItalics;
     }
 
-    if (secondTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
+    if (secondTraitsMask & desiredTraitsMask & FontWeightMask)
         return false;
-    if (firstTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
+    if (firstTraitsMask & desiredTraitsMask & FontWeightMask)
         return true;
 
     // http://www.w3.org/TR/2011/WD-css3-fonts-20111004/#font-matching-algorithm says :
@@ -449,7 +454,7 @@
 
     unsigned ruleSetIndex = 0;
     unsigned w = FontWeight100Bit;
-    while (!(desiredTraitsMaskForComparison & (1 << w))) {
+    while (!(desiredTraitsMask & (1 << w))) {
         w++;
         ruleSetIndex++;
     }
@@ -492,7 +497,7 @@
 
 CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& family)
 {
-    Vector<RefPtr<CSSFontFace> >* familyFontFaces = m_fontFaces.get(family);
+    HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >* familyFontFaces = m_fontFaces.get(family);
     if (!familyFontFaces || familyFontFaces->isEmpty())
         return 0;
 
@@ -504,12 +509,8 @@
 
     RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).iterator->value;
     if (!face) {
-        face = CSSSegmentedFontFace::create(this);
-
-        // Collect all matching faces and sort them in order of preference.
-        Vector<CSSFontFace*, 32> candidateFontFaces;
-        for (int i = familyFontFaces->size() - 1; i >= 0; --i) {
-            CSSFontFace* candidate = familyFontFaces->at(i).get();
+        for (HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >::const_iterator i = familyFontFaces->begin(); i != familyFontFaces->end(); ++i) {
+            CSSSegmentedFontFace* candidate = i->value.get();
             unsigned candidateTraitsMask = candidate->traitsMask();
             if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                 continue;
@@ -521,31 +522,34 @@
             if (candidate->hasSVGFontFaceSource() && (traitsMask & FontVariantSmallCapsMask) && !(candidateTraitsMask & FontVariantSmallCapsMask))
                 continue;
 #endif
-            candidateFontFaces.append(candidate);
+            if (!face || compareFontFaces(candidate, face.get(), traitsMask))
+                face = candidate;
         }
 
-        if (Vector<RefPtr<CSSFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
+        if (Vector<RefPtr<CSSSegmentedFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
             unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
             for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
-                CSSFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
+                CSSSegmentedFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
                 unsigned candidateTraitsMask = candidate->traitsMask();
                 if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                     continue;
                 if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
                     continue;
-                candidateFontFaces.append(candidate);
+                if (!face || compareFontFaces(candidate, face.get(), traitsMask))
+                    face = candidate;
             }
         }
-
-        desiredTraitsMaskForComparison = traitsMask;
-        stable_sort(candidateFontFaces.begin(), candidateFontFaces.end(), compareFontFaces);
-        unsigned numCandidates = candidateFontFaces.size();
-        for (unsigned i = 0; i < numCandidates; ++i)
-            face->appendFontFace(candidateFontFaces[i]);
     }
     return face.get();
 }
 
+void CSSFontSelector::willUseFontData(const FontDescription& fontDescription, const AtomicString& family)
+{
+    CSSSegmentedFontFace* face = getFontFace(fontDescription, family);
+    if (face)
+        face->willUseFontData(fontDescription);
+}
+
 void CSSFontSelector::clearDocument()
 {
     if (!m_document) {
diff --git a/Source/core/css/CSSFontSelector.h b/Source/core/css/CSSFontSelector.h
index 8d41ad2..559fa38 100644
--- a/Source/core/css/CSSFontSelector.h
+++ b/Source/core/css/CSSFontSelector.h
@@ -26,7 +26,7 @@
 #ifndef CSSFontSelector_h
 #define CSSFontSelector_h
 
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "core/platform/graphics/FontSelector.h"
 #include "wtf/Forward.h"
@@ -56,6 +56,7 @@
 
     virtual PassRefPtr<FontData> getFontData(const FontDescription&, const AtomicString&);
     CSSSegmentedFontFace* getFontFace(const FontDescription&, const AtomicString& family);
+    virtual void willUseFontData(const FontDescription&, const AtomicString& family) OVERRIDE;
 
     void clearDocument();
 
@@ -74,15 +75,15 @@
     void beginLoadingFontSoon(FontResource*);
 
 private:
-    CSSFontSelector(Document*);
+    explicit CSSFontSelector(Document*);
 
     void dispatchInvalidationCallbacks();
 
     void beginLoadTimerFired(Timer<CSSFontSelector>*);
 
     Document* m_document;
-    HashMap<String, OwnPtr<Vector<RefPtr<CSSFontFace> > >, CaseFoldingHash> m_fontFaces;
-    HashMap<String, OwnPtr<Vector<RefPtr<CSSFontFace> > >, CaseFoldingHash> m_locallyInstalledFontFaces;
+    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;
     HashSet<FontSelectorClient*> m_clients;
 
diff --git a/Source/core/css/CSSGradientValue.h b/Source/core/css/CSSGradientValue.h
index 5c3c631..2eed10b 100644
--- a/Source/core/css/CSSGradientValue.h
+++ b/Source/core/css/CSSGradientValue.h
@@ -164,7 +164,7 @@
     {
     }
 
-    CSSLinearGradientValue(const CSSLinearGradientValue& other)
+    explicit CSSLinearGradientValue(const CSSLinearGradientValue& other)
         : CSSGradientValue(other, LinearGradientClass, other.gradientType())
         , m_angle(other.m_angle)
     {
@@ -207,7 +207,7 @@
     {
     }
 
-    CSSRadialGradientValue(const CSSRadialGradientValue& other)
+    explicit CSSRadialGradientValue(const CSSRadialGradientValue& other)
         : CSSGradientValue(other, RadialGradientClass, other.gradientType())
         , m_firstRadius(other.m_firstRadius)
         , m_secondRadius(other.m_secondRadius)
diff --git a/Source/core/css/CSSGrammar.y.in b/Source/core/css/CSSGrammar.y.in
index adb38a6..024f514 100644
--- a/Source/core/css/CSSGrammar.y.in
+++ b/Source/core/css/CSSGrammar.y.in
@@ -142,6 +142,7 @@
 %token INTERNAL_VALUE_SYM
 %token INTERNAL_KEYFRAME_RULE_SYM
 %token INTERNAL_SUPPORTS_CONDITION_SYM
+%token KEYFRAMES_SYM
 %token WEBKIT_KEYFRAMES_SYM
 %token WEBKIT_REGION_RULE_SYM
 %token WEBKIT_FILTER_RULE_SYM
@@ -822,8 +823,16 @@
     ;
 
 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));
+        $$ = 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;
diff --git a/Source/core/css/CSSGroupingRule.cpp b/Source/core/css/CSSGroupingRule.cpp
index 46bf42d..b6728c0 100644
--- a/Source/core/css/CSSGroupingRule.cpp
+++ b/Source/core/css/CSSGroupingRule.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/css/CSSGroupingRule.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/CSSParser.h"
 #include "core/css/CSSRuleList.h"
@@ -62,7 +63,7 @@
     ASSERT(m_childRuleCSSOMWrappers.size() == m_groupRule->childRules().size());
 
     if (index > m_groupRule->childRules().size()) {
-        es.throwDOMException(IndexSizeError, "Failed to execute 'insertRule' on a 'CSSGroupingRule' object: the index " + String::number(index) + " must be less than or equal to the length of the rule list.");
+        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."));
         return 0;
     }
 
@@ -70,7 +71,7 @@
     CSSParser parser(parserContext(), UseCounter::getFrom(styleSheet));
     RefPtr<StyleRuleBase> newRule = parser.parseRule(styleSheet ? styleSheet->contents() : 0, ruleString);
     if (!newRule) {
-        es.throwDOMException(SyntaxError, "Failed to execute 'insertRule' on a 'CSSGroupingRule' object: the rule '" + ruleString + "' is invalid and cannot be parsed.");
+        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "the rule '" + ruleString + "' is invalid and cannot be parsed."));
         return 0;
     }
 
@@ -78,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, "Failed to execute 'insertRule' on a 'CSSGroupingRule' object: '@import' rules cannot be inserted inside a group rule.");
+        es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "'@import' rules cannot be inserted inside a group rule."));
         return 0;
     }
     CSSStyleSheet::RuleMutationScope mutationScope(this);
@@ -94,7 +95,7 @@
     ASSERT(m_childRuleCSSOMWrappers.size() == m_groupRule->childRules().size());
 
     if (index >= m_groupRule->childRules().size()) {
-        es.throwDOMException(IndexSizeError, "Failed to execute 'deleteRule' on a 'CSSGroupingRule' object: the index " + String::number(index) + " is greated than the length of the rule list.");
+        es.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/CSSImageGeneratorValue.h b/Source/core/css/CSSImageGeneratorValue.h
index 8a16024..4d96768 100644
--- a/Source/core/css/CSSImageGeneratorValue.h
+++ b/Source/core/css/CSSImageGeneratorValue.h
@@ -68,7 +68,7 @@
     void loadSubimages(ResourceFetcher*);
 
 protected:
-    CSSImageGeneratorValue(ClassType);
+    explicit CSSImageGeneratorValue(ClassType);
 
     Image* getImage(RenderObject*, const IntSize&);
     void putImage(const IntSize&, PassRefPtr<Image>);
diff --git a/Source/core/css/CSSImageSetValue.cpp b/Source/core/css/CSSImageSetValue.cpp
index efae646..231244d 100644
--- a/Source/core/css/CSSImageSetValue.cpp
+++ b/Source/core/css/CSSImageSetValue.cpp
@@ -30,9 +30,9 @@
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/rendering/style/StyleFetchedImageSet.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include "wtf/text/StringBuilder.h"
diff --git a/Source/core/css/CSSImageSetValue.h b/Source/core/css/CSSImageSetValue.h
index 42fdae9..7f5a377 100644
--- a/Source/core/css/CSSImageSetValue.h
+++ b/Source/core/css/CSSImageSetValue.h
@@ -66,7 +66,7 @@
 
 private:
     CSSImageSetValue();
-    CSSImageSetValue(const CSSImageSetValue& cloneFrom);
+    explicit CSSImageSetValue(const CSSImageSetValue& cloneFrom);
 
     void fillImageSet();
     static inline bool compareByScaleFactor(ImageWithScale first, ImageWithScale second) { return first.scaleFactor < second.scaleFactor; }
diff --git a/Source/core/css/CSSImageValue.cpp b/Source/core/css/CSSImageValue.cpp
index afd9659..c2b4cde 100644
--- a/Source/core/css/CSSImageValue.cpp
+++ b/Source/core/css/CSSImageValue.cpp
@@ -24,9 +24,9 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/CSSParser.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/rendering/style/StyleFetchedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
 
diff --git a/Source/core/css/CSSImageValue.h b/Source/core/css/CSSImageValue.h
index 1a9b3ea..0e66982 100644
--- a/Source/core/css/CSSImageValue.h
+++ b/Source/core/css/CSSImageValue.h
@@ -22,7 +22,7 @@
 #define CSSImageValue_h
 
 #include "core/css/CSSValue.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSInitialValue.h b/Source/core/css/CSSInitialValue.h
index 4a0f53f..f2bc029 100644
--- a/Source/core/css/CSSInitialValue.h
+++ b/Source/core/css/CSSInitialValue.h
@@ -44,7 +44,7 @@
     bool equals(const CSSInitialValue&) const { return true; }
 
 private:
-    CSSInitialValue(bool implicit)
+    explicit CSSInitialValue(bool implicit)
         : CSSValue(InitialClass)
         , m_isImplicit(implicit)
     {
diff --git a/Source/core/css/CSSKeyframeRule.cpp b/Source/core/css/CSSKeyframeRule.cpp
index 6024c87..672b726 100644
--- a/Source/core/css/CSSKeyframeRule.cpp
+++ b/Source/core/css/CSSKeyframeRule.cpp
@@ -54,14 +54,14 @@
 }
 
 /* static */
-void StyleKeyframe::parseKeyString(const String& s, Vector<float>& keys)
+void StyleKeyframe::parseKeyString(const String& s, Vector<double>& keys)
 {
     keys.clear();
     Vector<String> strings;
     s.split(',', strings);
 
     for (size_t i = 0; i < strings.size(); ++i) {
-        float key = -1;
+        double key = -1;
         String cur = strings[i].stripWhiteSpace();
 
         // For now the syntax MUST be 'xxx%' or 'from' or 'to', where xxx is a legal floating point number
@@ -70,7 +70,7 @@
         else if (cur == "to")
             key = 1;
         else if (cur.endsWith('%')) {
-            float k = cur.substring(0, cur.length() - 1).toFloat();
+            double k = cur.substring(0, cur.length() - 1).toDouble();
             if (k >= 0 && k <= 100)
                 key = k / 100;
         }
diff --git a/Source/core/css/CSSKeyframeRule.h b/Source/core/css/CSSKeyframeRule.h
index 17a4482..a2833a2 100644
--- a/Source/core/css/CSSKeyframeRule.h
+++ b/Source/core/css/CSSKeyframeRule.h
@@ -51,7 +51,7 @@
     // invalid string?
     void setKeyText(const String& s) { m_key = s; }
 
-    void getKeys(Vector<float>& keys) const   { parseKeyString(m_key, keys); }
+    void getKeys(Vector<double>& keys) const { parseKeyString(m_key, keys); }
 
     const StylePropertySet* properties() const { return m_properties.get(); }
     MutableStylePropertySet* mutableProperties();
@@ -62,7 +62,7 @@
 private:
     StyleKeyframe();
 
-    static void parseKeyString(const String&, Vector<float>& keys);
+    static void parseKeyString(const String&, Vector<double>& keys);
 
     RefPtr<StylePropertySet> m_properties;
     // FIXME: This should be a parsed vector of floats.
diff --git a/Source/core/css/CSSKeyframesRule.cpp b/Source/core/css/CSSKeyframesRule.cpp
index 80c6928..b4fbb0e 100644
--- a/Source/core/css/CSSKeyframesRule.cpp
+++ b/Source/core/css/CSSKeyframesRule.cpp
@@ -43,6 +43,7 @@
     : StyleRuleBase(o)
     , m_keyframes(o.m_keyframes)
     , m_name(o.m_name)
+    , m_isPrefixed(o.m_isPrefixed)
 {
 }
 
@@ -88,6 +89,7 @@
     : CSSRule(parent)
     , m_keyframesRule(keyframesRule)
     , m_childRuleCSSOMWrappers(keyframesRule->keyframes().size())
+    , m_isPrefixed(keyframesRule->isVendorPrefixed())
 {
 }
 
@@ -151,7 +153,10 @@
 String CSSKeyframesRule::cssText() const
 {
     StringBuilder result;
-    result.append("@-webkit-keyframes ");
+    if (isVendorPrefixed())
+        result.append("@-webkit-keyframes ");
+    else
+        result.append("@keyframes ");
     result.append(name());
     result.append(" { \n");
 
diff --git a/Source/core/css/CSSKeyframesRule.h b/Source/core/css/CSSKeyframesRule.h
index cae53c6..47978f4 100644
--- a/Source/core/css/CSSKeyframesRule.h
+++ b/Source/core/css/CSSKeyframesRule.h
@@ -52,16 +52,20 @@
     String name() const { return m_name; }
     void setName(const String& name) { m_name = AtomicString(name); }
 
+    bool isVendorPrefixed() const { return m_isPrefixed; }
+    void setVendorPrefixed(bool isPrefixed) { m_isPrefixed = isPrefixed; }
+
     int findKeyframeIndex(const String& key) const;
 
     PassRefPtr<StyleRuleKeyframes> copy() const { return adoptRef(new StyleRuleKeyframes(*this)); }
 
 private:
     StyleRuleKeyframes();
-    StyleRuleKeyframes(const StyleRuleKeyframes&);
+    explicit StyleRuleKeyframes(const StyleRuleKeyframes&);
 
     Vector<RefPtr<StyleKeyframe> > m_keyframes;
     AtomicString m_name;
+    bool m_isPrefixed;
 };
 
 class CSSKeyframesRule : public CSSRule {
@@ -87,12 +91,16 @@
     unsigned length() const;
     CSSKeyframeRule* item(unsigned index) const;
 
+    bool isVendorPrefixed() const { return m_isPrefixed; }
+    void setVendorPrefixed(bool isPrefixed) { m_isPrefixed = isPrefixed; }
+
 private:
     CSSKeyframesRule(StyleRuleKeyframes*, CSSStyleSheet* parent);
 
     RefPtr<StyleRuleKeyframes> m_keyframesRule;
     mutable Vector<RefPtr<CSSKeyframeRule> > m_childRuleCSSOMWrappers;
     mutable OwnPtr<CSSRuleList> m_ruleListCSSOMWrapper;
+    bool m_isPrefixed;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSLineBoxContainValue.h b/Source/core/css/CSSLineBoxContainValue.h
index de63049..6e5a050 100644
--- a/Source/core/css/CSSLineBoxContainValue.h
+++ b/Source/core/css/CSSLineBoxContainValue.h
@@ -53,7 +53,7 @@
     LineBoxContain m_value;
 
 private:
-    CSSLineBoxContainValue(LineBoxContain);
+    explicit CSSLineBoxContainValue(LineBoxContain);
 };
 
 } // namespace
diff --git a/Source/core/css/CSSParser-in.cpp b/Source/core/css/CSSParser-in.cpp
index 0e45c5c..2ced634 100644
--- a/Source/core/css/CSSParser-in.cpp
+++ b/Source/core/css/CSSParser-in.cpp
@@ -488,7 +488,7 @@
     case CSSPropertyWebkitShapeMargin:
     case CSSPropertyWebkitShapePadding:
         acceptsNegativeNumbers = false;
-        return RuntimeEnabledFeatures::cssExclusionsEnabled();
+        return RuntimeEnabledFeatures::cssShapesEnabled();
     case CSSPropertyBottom:
     case CSSPropertyLeft:
     case CSSPropertyMarginBottom:
@@ -606,8 +606,6 @@
             return true;
         if (valueID == CSSValueGrid || valueID == CSSValueInlineGrid)
             return RuntimeEnabledFeatures::cssGridLayoutEnabled();
-        if (valueID == CSSValueLazyBlock)
-            return RuntimeEnabledFeatures::lazyLayoutEnabled();
         break;
 
     case CSSPropertyEmptyCells: // show | hide | inherit
@@ -636,6 +634,12 @@
         if ((valueID >= CSSValueDisc && valueID <= CSSValueKatakanaIroha) || valueID == CSSValueNone)
             return true;
         break;
+    case CSSPropertyObjectFit:
+        if (RuntimeEnabledFeatures::objectFitPositionEnabled()) {
+            if (valueID == CSSValueFill || valueID == CSSValueContain || valueID == CSSValueCover || valueID == CSSValueNone || valueID == CSSValueScaleDown)
+                return true;
+        }
+        break;
     case CSSPropertyOutlineStyle: // (<border-style> except hidden) | auto | inherit
         if (valueID == CSSValueAuto || valueID == CSSValueNone || (valueID >= CSSValueInset && valueID <= CSSValueDouble))
             return true;
@@ -825,7 +829,7 @@
         if (valueID == CSSValueCollapse || valueID == CSSValueSeparate || valueID == CSSValueDiscard)
             return true;
         break;
-    case CSSPropertyWebkitMarqueeDirection:
+    case CSSPropertyInternalMarqueeDirection:
         if (valueID == CSSValueForwards || valueID == CSSValueBackwards || valueID == CSSValueAhead || valueID == CSSValueReverse || valueID == CSSValueLeft || valueID == CSSValueRight || valueID == CSSValueDown
             || valueID == CSSValueUp || valueID == CSSValueAuto)
             return true;
@@ -944,6 +948,7 @@
     case CSSPropertyImageRendering:
     case CSSPropertyListStylePosition:
     case CSSPropertyListStyleType:
+    case CSSPropertyObjectFit:
     case CSSPropertyOutlineStyle:
     case CSSPropertyOverflowWrap:
     case CSSPropertyOverflowX:
@@ -1000,7 +1005,7 @@
     case CSSPropertyWebkitMarginBeforeCollapse:
     case CSSPropertyWebkitMarginBottomCollapse:
     case CSSPropertyWebkitMarginTopCollapse:
-    case CSSPropertyWebkitMarqueeDirection:
+    case CSSPropertyInternalMarqueeDirection:
     case CSSPropertyWebkitMarqueeStyle:
     case CSSPropertyWebkitPrintColorAdjust:
     case CSSPropertyWebkitRegionBreakAfter:
@@ -1656,6 +1661,9 @@
 
 bool CSSParser::parseValue(CSSPropertyID propId, bool important)
 {
+    if (m_context.mode != UASheetMode && isInternalProperty(propId))
+        return false;
+
     if (m_useCounter)
         m_useCounter->count(propId);
 
@@ -2113,6 +2121,12 @@
     }
 
     case CSSPropertyTextDecoration:
+        // Fall through 'text-decoration-line' parsing if CSS 3 Text Decoration
+        // is disabled to match CSS 2.1 rules for parsing 'text-decoration'.
+        if (RuntimeEnabledFeatures::css3TextDecorationsEnabled()) {
+            // [ <text-decoration-line> || <text-decoration-style> || <text-decoration-color> ] | inherit
+            return parseShorthand(CSSPropertyTextDecoration, textDecorationShorthand(), important);
+        }
     case CSSPropertyWebkitTextDecorationsInEffect:
     case CSSPropertyTextDecorationLine:
         // none | [ underline || overline || line-through || blink ] | inherit
@@ -2315,8 +2329,6 @@
             }
         }
         break;
-    case CSSPropertyWebkitMarquee:
-        return parseShorthand(propId, webkitMarqueeShorthand(), important);
     case CSSPropertyWebkitMarqueeIncrement:
         if (id == CSSValueSmall || id == CSSValueLarge || id == CSSValueMedium)
             validPrimitive = true;
@@ -2402,6 +2414,16 @@
         }
         return false;
     }
+    case CSSPropertyAnimationDelay:
+    case CSSPropertyAnimationDirection:
+    case CSSPropertyAnimationDuration:
+    case CSSPropertyAnimationFillMode:
+    case CSSPropertyAnimationName:
+    case CSSPropertyAnimationPlayState:
+    case CSSPropertyAnimationIterationCount:
+    case CSSPropertyAnimationTimingFunction:
+        if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+            break;
     case CSSPropertyWebkitAnimationDelay:
     case CSSPropertyWebkitAnimationDirection:
     case CSSPropertyWebkitAnimationDuration:
@@ -2593,7 +2615,7 @@
     case CSSPropertyBorder:
         // [ 'border-width' || 'border-style' || <color> ] | inherit
     {
-        if (parseShorthand(propId, borderShorthandForParsing(), important)) {
+        if (parseShorthand(propId, parsingShorthandForProperty(CSSPropertyBorder), important)) {
             // The CSS3 Borders and Backgrounds specification says that border also resets border-image. It's as
             // though a value of none was specified for the image.
             addExpandedPropertyForValue(CSSPropertyBorderImage, cssValuePool().createImplicitInitialValue(), important);
@@ -2657,8 +2679,11 @@
         return parseShorthand(propId, webkitColumnRuleShorthand(), important);
     case CSSPropertyWebkitTextStroke:
         return parseShorthand(propId, webkitTextStrokeShorthand(), important);
+    case CSSPropertyAnimation:
+        if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+            break;
     case CSSPropertyWebkitAnimation:
-        return parseAnimationShorthand(important);
+        return parseAnimationShorthand(propId, important);
     case CSSPropertyTransition:
     case CSSPropertyWebkitTransition:
         return parseTransitionShorthand(propId, important);
@@ -2713,7 +2738,7 @@
         break;
     case CSSPropertyWebkitShapeInside:
     case CSSPropertyWebkitShapeOutside:
-        if (!RuntimeEnabledFeatures::cssExclusionsEnabled())
+        if (!RuntimeEnabledFeatures::cssShapesEnabled())
             return false;
         if (id == CSSValueAuto)
             validPrimitive = true;
@@ -2728,7 +2753,7 @@
         break;
     case CSSPropertyWebkitShapeMargin:
     case CSSPropertyWebkitShapePadding:
-        validPrimitive = (RuntimeEnabledFeatures::cssExclusionsEnabled() && !id && validUnit(value, FLength | FNonNeg));
+        validPrimitive = (RuntimeEnabledFeatures::cssShapesEnabled() && !id && validUnit(value, FLength | FNonNeg));
         break;
     case CSSPropertyBorderBottomStyle:
     case CSSPropertyBorderCollapse:
@@ -2746,6 +2771,7 @@
     case CSSPropertyImageRendering:
     case CSSPropertyListStylePosition:
     case CSSPropertyListStyleType:
+    case CSSPropertyObjectFit:
     case CSSPropertyOutlineStyle:
     case CSSPropertyOverflowWrap:
     case CSSPropertyOverflowX:
@@ -2804,7 +2830,7 @@
     case CSSPropertyWebkitMarginBeforeCollapse:
     case CSSPropertyWebkitMarginBottomCollapse:
     case CSSPropertyWebkitMarginTopCollapse:
-    case CSSPropertyWebkitMarqueeDirection:
+    case CSSPropertyInternalMarqueeDirection:
     case CSSPropertyWebkitMarqueeStyle:
     case CSSPropertyWebkitPrintColorAdjust:
     case CSSPropertyWebkitRegionBreakAfter:
@@ -3073,18 +3099,18 @@
         lval = rval;
 }
 
-bool CSSParser::parseAnimationShorthand(bool important)
+bool CSSParser::parseAnimationShorthand(CSSPropertyID propId, bool important)
 {
-    const StylePropertyShorthand& animationProperties = webkitAnimationShorthandForParsing();
-    const unsigned numProperties = 7;
+    const StylePropertyShorthand& animationProperties = parsingShorthandForProperty(propId);
+    const unsigned numProperties = 8;
 
     // The list of properties in the shorthand should be the same
     // length as the list with animation name in last position, even though they are
     // in a different order.
-    ASSERT(numProperties == webkitAnimationShorthandForParsing().length());
-    ASSERT(numProperties == webkitAnimationShorthand().length());
+    ASSERT(numProperties == animationProperties.length());
+    ASSERT(numProperties == shorthandForProperty(propId).length());
 
-    ShorthandScope scope(this, CSSPropertyWebkitAnimation);
+    ShorthandScope scope(this, propId);
 
     bool parsedProperty[numProperties] = { false };
     AnimationParseContext context;
@@ -3116,10 +3142,6 @@
                     break;
                 }
             }
-
-            // There are more values to process but 'none' or 'all' were already defined as the animation property, the declaration becomes invalid.
-            if (!context.animationPropertyKeywordAllowed() && context.hasCommittedFirstAnimation())
-                return false;
         }
 
         // if we didn't find at least one match, this is an
@@ -4450,6 +4472,7 @@
         }
         else {
             switch (propId) {
+                case CSSPropertyAnimationDelay:
                 case CSSPropertyWebkitAnimationDelay:
                 case CSSPropertyTransitionDelay:
                 case CSSPropertyWebkitTransitionDelay:
@@ -4457,11 +4480,13 @@
                     if (currValue)
                         m_valueList->next();
                     break;
+                case CSSPropertyAnimationDirection:
                 case CSSPropertyWebkitAnimationDirection:
                     currValue = parseAnimationDirection();
                     if (currValue)
                         m_valueList->next();
                     break;
+                case CSSPropertyAnimationDuration:
                 case CSSPropertyWebkitAnimationDuration:
                 case CSSPropertyTransitionDuration:
                 case CSSPropertyWebkitTransitionDuration:
@@ -4469,21 +4494,25 @@
                     if (currValue)
                         m_valueList->next();
                     break;
+                case CSSPropertyAnimationFillMode:
                 case CSSPropertyWebkitAnimationFillMode:
                     currValue = parseAnimationFillMode();
                     if (currValue)
                         m_valueList->next();
                     break;
+                case CSSPropertyAnimationIterationCount:
                 case CSSPropertyWebkitAnimationIterationCount:
                     currValue = parseAnimationIterationCount();
                     if (currValue)
                         m_valueList->next();
                     break;
+                case CSSPropertyAnimationName:
                 case CSSPropertyWebkitAnimationName:
                     currValue = parseAnimationName();
                     if (currValue)
                         m_valueList->next();
                     break;
+                case CSSPropertyAnimationPlayState:
                 case CSSPropertyWebkitAnimationPlayState:
                     currValue = parseAnimationPlayState();
                     if (currValue)
@@ -4497,6 +4526,7 @@
                     if (currValue)
                         m_valueList->next();
                     break;
+                case CSSPropertyAnimationTimingFunction:
                 case CSSPropertyWebkitAnimationTimingFunction:
                 case CSSPropertyTransitionTimingFunction:
                 case CSSPropertyWebkitTransitionTimingFunction:
@@ -9013,7 +9043,8 @@
             value = m_valueList->next();
     }
 
-    if (list->length() && isValid) {
+    // Values are either valid or in shorthand scope.
+    if (list->length() && (isValid || inShorthand())) {
         addTextDecorationProperty(propId, list.release(), important);
         return true;
     }
@@ -10205,7 +10236,7 @@
     --length;
 
     // charset, font-face, import, media, namespace, page, supports,
-    // -webkit-keyframes, and -webkit-mediaquery are not affected by hasEscape.
+    // -webkit-keyframes, keyframes, and -webkit-mediaquery are not affected by hasEscape.
     SWITCH(name, length) {
         CASE("bottom-left") {
             if (LIKELY(!hasEscape))
@@ -10241,6 +10272,10 @@
             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;
@@ -11157,7 +11192,7 @@
 {
     unsigned lineNumberInStyleSheet;
     unsigned columnNumber = 0;
-    PageConsole* console = m_styleSheet->singleOwnerDocument()->page()->console();
+    PageConsole& console = m_styleSheet->singleOwnerDocument()->page()->console();
     if (InspectorInstrumentation::hasFrontends()) {
         ensureLineEndings();
         TextPosition tokenPosition = TextPosition::fromOffsetAndLineEndings(location.offset, *m_lineEndings);
@@ -11166,10 +11201,10 @@
     } else {
         lineNumberInStyleSheet = location.lineNumber;
     }
-    console->addMessage(CSSMessageSource, WarningMessageLevel, message, m_styleSheet->baseURL().string(), lineNumberInStyleSheet + m_startPosition.m_line.zeroBasedInt() + 1, columnNumber + 1);
+    console.addMessage(CSSMessageSource, WarningMessageLevel, message, m_styleSheet->baseURL().string(), lineNumberInStyleSheet + m_startPosition.m_line.zeroBasedInt() + 1, columnNumber + 1);
 }
 
-StyleRuleKeyframes* CSSParser::createKeyframesRule(const String& name, PassOwnPtr<Vector<RefPtr<StyleKeyframe> > > popKeyframes)
+StyleRuleKeyframes* CSSParser::createKeyframesRule(const String& name, PassOwnPtr<Vector<RefPtr<StyleKeyframe> > > popKeyframes, bool isPrefixed)
 {
     OwnPtr<Vector<RefPtr<StyleKeyframe> > > keyframes = popKeyframes;
     m_allowImportRules = m_allowNamespaceDeclarations = false;
@@ -11177,6 +11212,7 @@
     for (size_t i = 0; i < keyframes->size(); ++i)
         rule->parserAppendKeyframe(keyframes->at(i));
     rule->setName(name);
+    rule->setVendorPrefixed(isPrefixed);
     StyleRuleKeyframes* rulePtr = rule.get();
     m_parsedRules.append(rule.release());
     endRuleBody();
@@ -11484,7 +11520,7 @@
     StringBuilder keyString;
     for (unsigned i = 0; i < keys->size(); ++i) {
         ASSERT(keys->valueAt(i)->unit == CSSPrimitiveValue::CSS_NUMBER);
-        float key = static_cast<float>(keys->valueAt(i)->fValue);
+        double key = keys->valueAt(i)->fValue;
         if (key < 0 || key > 100) {
             // As per http://www.w3.org/TR/css3-animations/#keyframes,
             // "If a keyframe selector specifies negative percentage values
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/CSSParser.h
index 1f0ff6a..4a0f3fe 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/CSSParser.h
@@ -167,7 +167,7 @@
     bool parseCubicBezierTimingFunctionValue(CSSParserValueList*& args, double& result);
     bool parseAnimationProperty(CSSPropertyID, RefPtr<CSSValue>&, AnimationParseContext&);
     bool parseTransitionShorthand(CSSPropertyID, bool important);
-    bool parseAnimationShorthand(bool important);
+    bool parseAnimationShorthand(CSSPropertyID, bool important);
 
     PassRefPtr<CSSValue> parseColumnWidth();
     PassRefPtr<CSSValue> parseColumnCount();
@@ -220,6 +220,8 @@
     PassRefPtr<CSSValue> parseSVGColor();
     PassRefPtr<CSSValue> parseSVGStrokeDasharray();
 
+    PassRefPtr<CSSValue> parsePaintOrder() const;
+
     // CSS3 Parsing Routines (for properties specific to CSS3)
     PassRefPtr<CSSValueList> parseShadow(CSSParserValueList*, CSSPropertyID);
     bool parseBorderImage(CSSPropertyID, RefPtr<CSSValue>&, bool important = false);
@@ -310,7 +312,7 @@
     MediaQuerySet* createMediaQuerySet();
     StyleRuleBase* createImportRule(const CSSParserString&, MediaQuerySet*);
     StyleKeyframe* createKeyframe(CSSParserValueList*);
-    StyleRuleKeyframes* createKeyframesRule(const String&, PassOwnPtr<Vector<RefPtr<StyleKeyframe> > >);
+    StyleRuleKeyframes* createKeyframesRule(const String&, PassOwnPtr<Vector<RefPtr<StyleKeyframe> > >, bool isPrefixed);
 
     typedef Vector<RefPtr<StyleRuleBase> > RuleList;
     StyleRuleBase* createMediaRule(MediaQuerySet*, RuleList*);
diff --git a/Source/core/css/CSSPrimitiveValueMappings.h b/Source/core/css/CSSPrimitiveValueMappings.h
index 394702c..418f87d 100644
--- a/Source/core/css/CSSPrimitiveValueMappings.h
+++ b/Source/core/css/CSSPrimitiveValueMappings.h
@@ -1273,9 +1273,6 @@
     case INLINE_GRID:
         m_value.valueID = CSSValueInlineGrid;
         break;
-    case LAZY_BLOCK:
-        m_value.valueID = CSSValueLazyBlock;
-        break;
     case NONE:
         m_value.valueID = CSSValueNone;
         break;
@@ -3359,6 +3356,48 @@
     return FontDescription::AutoKerning;
 }
 
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ObjectFit fit)
+    : CSSValue(PrimitiveClass)
+{
+    m_primitiveUnitType = CSS_VALUE_ID;
+    switch (fit) {
+    case ObjectFitFill:
+        m_value.valueID = CSSValueFill;
+        break;
+    case ObjectFitContain:
+        m_value.valueID = CSSValueContain;
+        break;
+    case ObjectFitCover:
+        m_value.valueID = CSSValueCover;
+        break;
+    case ObjectFitNone:
+        m_value.valueID = CSSValueNone;
+        break;
+    case ObjectFitScaleDown:
+        m_value.valueID = CSSValueScaleDown;
+        break;
+    }
+}
+
+template<> inline CSSPrimitiveValue::operator ObjectFit() const
+{
+    switch (m_value.valueID) {
+    case CSSValueFill:
+        return ObjectFitFill;
+    case CSSValueContain:
+        return ObjectFitContain;
+    case CSSValueCover:
+        return ObjectFitCover;
+    case CSSValueNone:
+        return ObjectFitNone;
+    case CSSValueScaleDown:
+        return ObjectFitScaleDown;
+    default:
+        ASSERT_NOT_REACHED();
+        return ObjectFitFill;
+    }
+}
+
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(FontSmoothingMode smoothing)
     : CSSValue(PrimitiveClass)
 {
@@ -4688,6 +4727,45 @@
     return VE_NONE;
 }
 
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EPaintOrderType e)
+    : CSSValue(PrimitiveClass)
+{
+    m_primitiveUnitType = CSS_VALUE_ID;
+    switch (e) {
+    case PT_FILL:
+        m_value.valueID = CSSValueFill;
+        break;
+    case PT_STROKE:
+        m_value.valueID = CSSValueStroke;
+        break;
+    case PT_MARKERS:
+        m_value.valueID = CSSValueMarkers;
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+        m_value.valueID = CSSValueFill;
+        break;
+    }
+}
+
+template<> inline CSSPrimitiveValue::operator EPaintOrderType() const
+{
+    ASSERT(isValueID());
+    switch (m_value.valueID) {
+    case CSSValueFill:
+        return PT_FILL;
+    case CSSValueStroke:
+        return PT_STROKE;
+    case CSSValueMarkers:
+        return PT_MARKERS;
+    default:
+        break;
+    }
+
+    ASSERT_NOT_REACHED();
+    return PT_NONE;
+}
+
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EMaskType e)
     : CSSValue(PrimitiveClass)
 {
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index 1520238..340f0cc 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -80,6 +80,7 @@
 min-height type_name=Length, initial=initialMinSize, converter=convertLengthSizing
 min-width type_name=Length, initial=initialMinSize, converter=convertLengthSizing
 mix-blend-mode type_name=BlendMode, name_for_methods=BlendMode
+object-fit type_name=ObjectFit
 opacity type_name=float
 order type_name=int
 orphans type_name=short, custom_all
@@ -187,7 +188,7 @@
 -webkit-margin-before-collapse type_name=EMarginCollapse
 -webkit-margin-bottom-collapse type_name=EMarginCollapse, name_for_methods=MarginAfterCollapse
 -webkit-margin-top-collapse type_name=EMarginCollapse, name_for_methods=MarginBeforeCollapse
--webkit-marquee-direction
+-internal-marquee-direction type_name=EMarqueeDirection, name_for_methods=MarqueeDirection
 -webkit-marquee-increment custom_value
 -webkit-marquee-repetition type_name=int, name_for_methods=MarqueeLoopCount, custom_value
 -webkit-marquee-speed custom_value
diff --git a/Source/core/css/CSSProperty.cpp b/Source/core/css/CSSProperty.cpp
index 9fee7be..930f3ab 100644
--- a/Source/core/css/CSSProperty.cpp
+++ b/Source/core/css/CSSProperty.cpp
@@ -361,6 +361,15 @@
     case CSSPropertyWordWrap:
     case CSSPropertyWritingMode:
         return true;
+    case CSSPropertyAnimation:
+    case CSSPropertyAnimationDelay:
+    case CSSPropertyAnimationDirection:
+    case CSSPropertyAnimationDuration:
+    case CSSPropertyAnimationFillMode:
+    case CSSPropertyAnimationIterationCount:
+    case CSSPropertyAnimationName:
+    case CSSPropertyAnimationPlayState:
+    case CSSPropertyAnimationTimingFunction:
     case CSSPropertyAlignmentBaseline:
     case CSSPropertyBackground:
     case CSSPropertyBackgroundAttachment:
@@ -442,6 +451,7 @@
     case CSSPropertyMinHeight:
     case CSSPropertyMinWidth:
     case CSSPropertyMixBlendMode:
+    case CSSPropertyObjectFit:
     case CSSPropertyOpacity:
     case CSSPropertyOutline:
     case CSSPropertyOutlineColor:
@@ -461,6 +471,7 @@
     case CSSPropertyPageBreakAfter:
     case CSSPropertyPageBreakBefore:
     case CSSPropertyPageBreakInside:
+    case CSSPropertyPaintOrder:
     case CSSPropertyPosition:
     case CSSPropertyRight:
     case CSSPropertySize:
@@ -593,8 +604,7 @@
     case CSSPropertyWebkitMarginEnd:
     case CSSPropertyWebkitMarginStart:
     case CSSPropertyWebkitMarginTopCollapse:
-    case CSSPropertyWebkitMarquee:
-    case CSSPropertyWebkitMarqueeDirection:
+    case CSSPropertyInternalMarqueeDirection:
     case CSSPropertyWebkitMarqueeIncrement:
     case CSSPropertyWebkitMarqueeRepetition:
     case CSSPropertyWebkitMarqueeSpeed:
diff --git a/Source/core/css/CSSProperty.h b/Source/core/css/CSSProperty.h
index a400af1..fd802ec 100644
--- a/Source/core/css/CSSProperty.h
+++ b/Source/core/css/CSSProperty.h
@@ -22,6 +22,7 @@
 #define CSSProperty_h
 
 #include "CSSPropertyNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSValue.h"
 #include "core/platform/text/TextDirection.h"
 #include "core/platform/text/WritingMode.h"
@@ -89,8 +90,38 @@
 
 inline CSSPropertyID prefixingVariantForPropertyId(CSSPropertyID propId)
 {
+    if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && (propId >= CSSPropertyWebkitAnimation && propId <= CSSPropertyAnimationTimingFunction))
+        return propId;
+
     CSSPropertyID propertyId = CSSPropertyInvalid;
     switch (propId) {
+    case CSSPropertyAnimation:
+        propertyId = CSSPropertyWebkitAnimation;
+        break;
+    case CSSPropertyAnimationDelay:
+        propertyId = CSSPropertyWebkitAnimationDelay;
+        break;
+    case CSSPropertyAnimationDirection:
+        propertyId = CSSPropertyWebkitAnimationDirection;
+        break;
+    case CSSPropertyAnimationDuration:
+        propertyId = CSSPropertyWebkitAnimationDuration;
+        break;
+    case CSSPropertyAnimationFillMode:
+        propertyId = CSSPropertyWebkitAnimationFillMode;
+        break;
+    case CSSPropertyAnimationIterationCount:
+        propertyId = CSSPropertyWebkitAnimationIterationCount;
+        break;
+    case CSSPropertyAnimationName:
+        propertyId = CSSPropertyWebkitAnimationName;
+        break;
+    case CSSPropertyAnimationPlayState:
+        propertyId = CSSPropertyWebkitAnimationPlayState;
+        break;
+    case CSSPropertyAnimationTimingFunction:
+        propertyId = CSSPropertyWebkitAnimationTimingFunction;
+        break;
     case CSSPropertyTransitionDelay:
         propertyId = CSSPropertyWebkitTransitionDelay;
         break;
@@ -106,6 +137,33 @@
     case CSSPropertyTransition:
         propertyId = CSSPropertyWebkitTransition;
         break;
+    case CSSPropertyWebkitAnimation:
+        propertyId = CSSPropertyAnimation;
+        break;
+    case CSSPropertyWebkitAnimationDelay:
+        propertyId = CSSPropertyAnimationDelay;
+        break;
+    case CSSPropertyWebkitAnimationDirection:
+        propertyId = CSSPropertyAnimationDirection;
+        break;
+    case CSSPropertyWebkitAnimationDuration:
+        propertyId = CSSPropertyAnimationDuration;
+        break;
+    case CSSPropertyWebkitAnimationFillMode:
+        propertyId = CSSPropertyAnimationFillMode;
+        break;
+    case CSSPropertyWebkitAnimationIterationCount:
+        propertyId = CSSPropertyAnimationIterationCount;
+        break;
+    case CSSPropertyWebkitAnimationName:
+        propertyId = CSSPropertyAnimationName;
+        break;
+    case CSSPropertyWebkitAnimationPlayState:
+        propertyId = CSSPropertyAnimationPlayState;
+        break;
+    case CSSPropertyWebkitAnimationTimingFunction:
+        propertyId = CSSPropertyAnimationTimingFunction;
+        break;
     case CSSPropertyWebkitTransitionDelay:
         propertyId = CSSPropertyTransitionDelay;
         break;
diff --git a/Source/core/css/CSSPropertyNames.in b/Source/core/css/CSSPropertyNames.in
index 11f385b..95d21f6 100644
--- a/Source/core/css/CSSPropertyNames.in
+++ b/Source/core/css/CSSPropertyNames.in
@@ -19,6 +19,15 @@
 -webkit-animation-name
 -webkit-animation-play-state
 -webkit-animation-timing-function
+animation
+animation-delay
+animation-direction
+animation-duration
+animation-fill-mode
+animation-iteration-count
+animation-name
+animation-play-state
+animation-timing-function
 -webkit-transition
 -webkit-transition-delay
 -webkit-transition-duration
@@ -152,6 +161,7 @@
 outline-offset
 outline-style
 outline-width
+object-fit
 overflow
 overflow-wrap
 overflow-x
@@ -328,8 +338,6 @@
 -webkit-margin-before
 -webkit-margin-end
 -webkit-margin-start
--webkit-marquee
--webkit-marquee-direction
 -webkit-marquee-increment
 -webkit-marquee-repetition
 -webkit-marquee-speed
@@ -412,3 +420,6 @@
 user-zoom
 -webkit-tap-highlight-color
 -webkit-app-region
+
+// Internal properties.
+-internal-marquee-direction
diff --git a/Source/core/css/CSSSVGDocumentValue.cpp b/Source/core/css/CSSSVGDocumentValue.cpp
index 38a9874..85886e2 100644
--- a/Source/core/css/CSSSVGDocumentValue.cpp
+++ b/Source/core/css/CSSSVGDocumentValue.cpp
@@ -29,9 +29,9 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/CSSParser.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/DocumentResource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSSVGDocumentValue.h b/Source/core/css/CSSSVGDocumentValue.h
index 5f13221..7e43406 100644
--- a/Source/core/css/CSSSVGDocumentValue.h
+++ b/Source/core/css/CSSSVGDocumentValue.h
@@ -26,8 +26,8 @@
 #define CSSSVGDocumentValue_h
 
 #include "core/css/CSSValue.h"
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/DocumentResource.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSSegmentedFontFace.cpp b/Source/core/css/CSSSegmentedFontFace.cpp
index a5ebc16..515d6f6 100644
--- a/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/Source/core/css/CSSSegmentedFontFace.cpp
@@ -34,8 +34,10 @@
 
 namespace WebCore {
 
-CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector)
+CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector, FontTraitsMask traitsMask, bool isLocalFallback)
     : m_fontSelector(fontSelector)
+    , m_traitsMask(traitsMask)
+    , m_isLocalFallback(isLocalFallback)
 {
 }
 
@@ -44,7 +46,7 @@
     pruneTable();
     unsigned size = m_fontFaces.size();
     for (unsigned i = 0; i < size; i++)
-        m_fontFaces[i]->removedFromSegmentedFontFace(this);
+        m_fontFaces[i]->clearSegmentedFontFace();
 }
 
 void CSSSegmentedFontFace::pruneTable()
@@ -86,7 +88,7 @@
 void CSSSegmentedFontFace::appendFontFace(PassRefPtr<CSSFontFace> fontFace)
 {
     pruneTable();
-    fontFace->addedToSegmentedFontFace(this);
+    fontFace->setSegmentedFontFace(this);
     m_fontFaces.append(fontFace);
 }
 
@@ -126,13 +128,12 @@
     if (!fontData)
         fontData = SegmentedFontData::create();
 
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++) {
+    bool syntheticBold = !(m_traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask));
+    bool syntheticItalic = !(m_traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask);
+
+    for (int i = m_fontFaces.size() - 1; i >= 0; --i) {
         if (!m_fontFaces[i]->isValid())
             continue;
-        FontTraitsMask traitsMask = m_fontFaces[i]->traitsMask();
-        bool syntheticBold = !(traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask));
-        bool syntheticItalic = !(traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask);
         if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(fontDescription, syntheticBold, syntheticItalic)) {
             ASSERT(!faceFontData->isSegmented());
             appendFontDataWithInvalidUnicodeRangeIfLoading(fontData.get(), faceFontData.release(), m_fontFaces[i]->ranges());
@@ -144,6 +145,16 @@
     return 0;
 }
 
+bool CSSSegmentedFontFace::hasSVGFontFaceSource() const
+{
+    unsigned size = m_fontFaces.size();
+    for (unsigned i = 0; i < size; i++) {
+        if (m_fontFaces[i]->hasSVGFontFaceSource())
+            return true;
+    }
+    return false;
+}
+
 bool CSSSegmentedFontFace::isLoading() const
 {
     unsigned size = m_fontFaces.size();
@@ -154,6 +165,13 @@
     return false;
 }
 
+void CSSSegmentedFontFace::willUseFontData(const FontDescription& fontDescription)
+{
+    unsigned size = m_fontFaces.size();
+    for (unsigned i = 0; i < size; i++)
+        m_fontFaces[i]->willUseFontData(fontDescription);
+}
+
 bool CSSSegmentedFontFace::checkFont() const
 {
     unsigned size = m_fontFaces.size();
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 662045d..214a052 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -26,6 +26,7 @@
 #ifndef CSSSegmentedFontFace_h
 #define CSSSegmentedFontFace_h
 
+#include "core/platform/graphics/FontTraitsMask.h"
 #include "wtf/HashMap.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -41,10 +42,12 @@
 
 class CSSSegmentedFontFace : public RefCounted<CSSSegmentedFontFace> {
 public:
-    static PassRefPtr<CSSSegmentedFontFace> create(CSSFontSelector* selector) { return adoptRef(new CSSSegmentedFontFace(selector)); }
+    static PassRefPtr<CSSSegmentedFontFace> create(CSSFontSelector* selector, FontTraitsMask traitsMask, bool isLocalFallback) { return adoptRef(new CSSSegmentedFontFace(selector, traitsMask, isLocalFallback)); }
     ~CSSSegmentedFontFace();
 
     CSSFontSelector* fontSelector() const { return m_fontSelector; }
+    FontTraitsMask traitsMask() const { return m_traitsMask; }
+    bool isLocalFallback() const { return m_isLocalFallback; }
 
     void fontLoaded(CSSFontFace*);
 
@@ -52,6 +55,10 @@
 
     PassRefPtr<FontData> getFontData(const FontDescription&);
 
+#if ENABLE(SVG_FONTS)
+    bool hasSVGFontFaceSource() const;
+#endif
+
     class LoadFontCallback : public RefCounted<LoadFontCallback> {
     public:
         virtual ~LoadFontCallback() { }
@@ -61,15 +68,18 @@
 
     bool checkFont() const;
     void loadFont(const FontDescription&, PassRefPtr<LoadFontCallback> loadCallback);
+    void willUseFontData(const FontDescription&);
 
 private:
-    CSSSegmentedFontFace(CSSFontSelector*);
+    CSSSegmentedFontFace(CSSFontSelector*, FontTraitsMask, bool isLocalFallback);
 
     void pruneTable();
     bool isValid() const;
     bool isLoading() const;
 
     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/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index df2a968..3874329 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -431,7 +431,7 @@
             nameToPseudoType->set(hostWithParams.impl(), CSSSelector::PseudoHost);
             nameToPseudoType->set(content.impl(), CSSSelector::PseudoContent);
         }
-        if (RuntimeEnabledFeatures::customDOMElementsEnabled())
+        if (RuntimeEnabledFeatures::customElementsEnabled() || RuntimeEnabledFeatures::embedderCustomElementsEnabled())
             nameToPseudoType->set(unresolved.impl(), CSSSelector::PseudoUnresolved);
     }
     return nameToPseudoType;
diff --git a/Source/core/css/CSSSelectorList.cpp b/Source/core/css/CSSSelectorList.cpp
index bf79681..30ac8eb 100644
--- a/Source/core/css/CSSSelectorList.cpp
+++ b/Source/core/css/CSSSelectorList.cpp
@@ -165,20 +165,6 @@
     return forEachSelector(functor, this);
 }
 
-class SelectorHasInvalidSelectorFunctor {
-public:
-    bool operator()(const CSSSelector* selector)
-    {
-        return selector->isUnknownPseudoElement() || selector->isCustomPseudoElement();
-    }
-};
-
-bool CSSSelectorList::hasInvalidSelector() const
-{
-    SelectorHasInvalidSelectorFunctor functor;
-    return forEachSelector(functor, this);
-}
-
 class SelectorHasShadowDistributed {
 public:
     bool operator()(const CSSSelector* selector)
diff --git a/Source/core/css/CSSSelectorList.h b/Source/core/css/CSSSelectorList.h
index 29761bd..060082b 100644
--- a/Source/core/css/CSSSelectorList.h
+++ b/Source/core/css/CSSSelectorList.h
@@ -59,7 +59,6 @@
     }
 
     bool selectorsNeedNamespaceResolution();
-    bool hasInvalidSelector() const;
 
     bool hasShadowDistributedAt(size_t index) const;
 
diff --git a/Source/core/css/CSSShaderValue.cpp b/Source/core/css/CSSShaderValue.cpp
index a21af14..bc8ce08 100644
--- a/Source/core/css/CSSShaderValue.cpp
+++ b/Source/core/css/CSSShaderValue.cpp
@@ -34,8 +34,8 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/CSSParser.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/rendering/style/StyleFetchedShader.h"
 #include "core/rendering/style/StylePendingShader.h"
 #include "wtf/text/StringBuilder.h"
diff --git a/Source/core/css/CSSShorthands.in b/Source/core/css/CSSShorthands.in
index 04f9a63..ea55299 100644
--- a/Source/core/css/CSSShorthands.in
+++ b/Source/core/css/CSSShorthands.in
@@ -3,6 +3,7 @@
 // followed by the longhands associated to the shorthand.
 // Note: Mandatory blank line to skip parameter parsing phase
 
+animation longhands=animation-name;animation-duration;animation-timing-function;animation-delay;animation-iteration-count;animation-direction;animation-fill-mode;animation-play-state, runtimeEnabledShorthand=CSSAnimationUnprefixed
 background longhands=background-image;background-position-x;background-position-y;background-size;background-repeat-x;background-repeat-y;background-attachment;background-origin;background-clip;background-color
 background-position longhands=background-position-x;background-position-y
 background-repeat longhands=background-repeat-x;background-repeat-y
@@ -30,8 +31,9 @@
 outline longhands=outline-color;outline-style;outline-width
 overflow longhands=overflow-x;overflow-y
 padding longhands=padding-top;padding-right;padding-bottom;padding-left
+text-decoration longhands=text-decoration-line;text-decoration-style;text-decoration-color, runtimeEnabledShorthand=CSS3TextDecorations
 transition longhands=transition-property;transition-duration;transition-timing-function;transition-delay
--webkit-animation longhands=-webkit-animation-name;-webkit-animation-duration;-webkit-animation-timing-function;-webkit-animation-delay;-webkit-animation-iteration-count;-webkit-animation-direction;-webkit-animation-fill-mode
+-webkit-animation longhands=-webkit-animation-name;-webkit-animation-duration;-webkit-animation-timing-function;-webkit-animation-delay;-webkit-animation-iteration-count;-webkit-animation-direction;-webkit-animation-fill-mode;-webkit-animation-play-state
 -webkit-border-after longhands=-webkit-border-after-width;-webkit-border-after-style;-webkit-border-after-color
 -webkit-border-before longhands=-webkit-border-before-width;-webkit-border-before-style;-webkit-border-before-color
 -webkit-border-end longhands=-webkit-border-end-width;-webkit-border-end-style;-webkit-border-end-color
@@ -40,7 +42,6 @@
 -webkit-columns longhands=-webkit-column-width;-webkit-column-count
 -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-marquee longhands=-webkit-marquee-direction;-webkit-marquee-increment;-webkit-marquee-repetition;-webkit-marquee-style;-webkit-marquee-speed
 -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-position longhands=-webkit-mask-position-x;-webkit-mask-position-y
 -webkit-mask-repeat longhands=-webkit-mask-repeat-x;-webkit-mask-repeat-y
diff --git a/Source/core/css/CSSValueKeywords.in b/Source/core/css/CSSValueKeywords.in
index 82e507f..e2347f0 100644
--- a/Source/core/css/CSSValueKeywords.in
+++ b/Source/core/css/CSSValueKeywords.in
@@ -966,6 +966,9 @@
 color
 luminosity
 
+// object-fit
+scale-down
+
 // overflow
 -webkit-paged-x
 -webkit-paged-y
@@ -984,6 +987,12 @@
 progressive
 interlace
 
+// CSS_PROP_PAINT_ORDER
+// normal
+// fill
+// stroke
+markers
+
 //
 // CSS3 viewport-length keywords
 //
diff --git a/Source/core/css/MediaQueryEvaluator.cpp b/Source/core/css/MediaQueryEvaluator.cpp
index 413c80e..42e71e5 100644
--- a/Source/core/css/MediaQueryEvaluator.cpp
+++ b/Source/core/css/MediaQueryEvaluator.cpp
@@ -272,8 +272,8 @@
 
 static bool evalResolution(CSSValue* value, Frame* frame, MediaFeaturePrefix op)
 {
-    // FIXME: Possible handle other media types than 'screen' and 'print'.
-    float deviceScaleFactor = 0;
+    // FIXME: Possibly handle other media types than 'screen' and 'print'.
+    float actualResolution = 0;
 
     // This checks the actual media type applied to the document, and we know
     // this method only got called if this media type matches the one defined
@@ -281,16 +281,16 @@
     // media type of the query will either be "print" or "all".
     String mediaType = frame->view()->mediaType();
     if (equalIgnoringCase(mediaType, "screen"))
-        deviceScaleFactor = frame->page()->deviceScaleFactor();
+        actualResolution = clampTo<float>(frame->devicePixelRatio());
     else if (equalIgnoringCase(mediaType, "print")) {
         // The resolution of images while printing should not depend on the DPI
         // of the screen. Until we support proper ways of querying this info
         // we use 300px which is considered minimum for current printers.
-        deviceScaleFactor = 300 / cssPixelsPerInch;
+        actualResolution = 300 / cssPixelsPerInch;
     }
 
     if (!value)
-        return !!deviceScaleFactor;
+        return !!actualResolution;
 
     if (!value->isPrimitiveValue())
         return false;
@@ -298,7 +298,7 @@
     CSSPrimitiveValue* resolution = toCSSPrimitiveValue(value);
 
     if (resolution->isNumber())
-        return compareValue(deviceScaleFactor, resolution->getFloatValue(), op);
+        return compareValue(actualResolution, resolution->getFloatValue(), op);
 
     if (!resolution->isResolution())
         return false;
@@ -310,11 +310,11 @@
         // approximates the reference pixel". With that in mind, allowing 2 decimal
         // point precision seems appropriate.
         return compareValue(
-            floorf(0.5 + 100 * deviceScaleFactor) / 100,
+            floorf(0.5 + 100 * actualResolution) / 100,
             floorf(0.5 + 100 * resolution->getFloatValue(CSSPrimitiveValue::CSS_DPPX)) / 100, op);
     }
 
-    return compareValue(deviceScaleFactor, resolution->getFloatValue(CSSPrimitiveValue::CSS_DPPX), op);
+    return compareValue(actualResolution, resolution->getFloatValue(CSSPrimitiveValue::CSS_DPPX), op);
 }
 
 static bool devicePixelRatioMediaFeatureEval(CSSValue *value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
diff --git a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
index 4b774c2..b773e4f 100644
--- a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
@@ -59,6 +59,27 @@
     return list.release();
 }
 
+static PassRefPtr<CSSValue> paintOrderToCSSValueList(EPaintOrder paintorder)
+{
+    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    do {
+        EPaintOrderType paintOrderType = (EPaintOrderType)(paintorder & ((1 << kPaintOrderBitwidth) - 1));
+        switch (paintOrderType) {
+        case PT_FILL:
+        case PT_STROKE:
+        case PT_MARKERS:
+            list->append(CSSPrimitiveValue::create(paintOrderType));
+            break;
+        case PT_NONE:
+        default:
+            ASSERT_NOT_REACHED();
+            break;
+        }
+    } while (paintorder >>= kPaintOrderBitwidth);
+
+    return list.release();
+}
+
 PassRefPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint> newPaint, RenderStyle* style) const
 {
     RefPtr<SVGPaint> paint = newPaint;
@@ -192,6 +213,8 @@
 
             return 0;
         }
+        case CSSPropertyPaintOrder:
+            return paintOrderToCSSValueList(svgStyle->paintOrder());
         case CSSPropertyVectorEffect:
             return CSSPrimitiveValue::create(svgStyle->vectorEffect());
         case CSSPropertyMaskType:
diff --git a/Source/core/css/SVGCSSParser.cpp b/Source/core/css/SVGCSSParser.cpp
index 6595cf7..ba70fcb 100644
--- a/Source/core/css/SVGCSSParser.cpp
+++ b/Source/core/css/SVGCSSParser.cpp
@@ -24,6 +24,7 @@
 
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
+#include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSParser.h"
 #include "core/css/CSSValueList.h"
 #include "core/rendering/RenderTheme.h"
@@ -225,6 +226,16 @@
 
         break;
 
+    case CSSPropertyPaintOrder:
+        if (!RuntimeEnabledFeatures::svgPaintOrderEnabled())
+            return false;
+
+        if (m_valueList->size() == 1 && id == CSSValueNormal)
+            valid_primitive = true;
+        else if ((parsedValue = parsePaintOrder()))
+            m_valueList->next();
+        break;
+
     case CSSPropertyVectorEffect: // none | non-scaling-stroke | inherit
         if (id == CSSValueNone || id == CSSValueNonScalingStroke)
             valid_primitive = true;
@@ -355,4 +366,62 @@
     return SVGColor::createFromColor(Color(c));
 }
 
+// normal | [ fill || stroke || markers ]
+PassRefPtr<CSSValue> CSSParser::parsePaintOrder() const
+{
+    if (m_valueList->size() > 3)
+        return 0;
+
+    CSSParserValue* value = m_valueList->current();
+    if (!value)
+        return 0;
+
+    RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
+
+    // The default paint-order is: Fill, Stroke, Markers.
+    bool seenFill = false,
+         seenStroke = false,
+         seenMarkers = false;
+
+    do {
+        switch (value->id) {
+        case CSSValueNormal:
+            // normal inside [fill || stroke || markers] not valid
+            return 0;
+        case CSSValueFill:
+            if (seenFill)
+                return 0;
+
+            seenFill = true;
+            break;
+        case CSSValueStroke:
+            if (seenStroke)
+                return 0;
+
+            seenStroke = true;
+            break;
+        case CSSValueMarkers:
+            if (seenMarkers)
+                return 0;
+
+            seenMarkers = true;
+            break;
+        default:
+            return 0;
+        }
+
+        parsedValues->append(CSSPrimitiveValue::createIdentifier(value->id));
+    } while ((value = m_valueList->next()));
+
+    // fill out the rest of the paint order
+    if (!seenFill)
+        parsedValues->append(CSSPrimitiveValue::createIdentifier(CSSValueFill));
+    if (!seenStroke)
+        parsedValues->append(CSSPrimitiveValue::createIdentifier(CSSValueStroke));
+    if (!seenMarkers)
+        parsedValues->append(CSSPrimitiveValue::createIdentifier(CSSValueMarkers));
+
+    return parsedValues.release();
+}
+
 }
diff --git a/Source/core/css/SVGCSSPropertyNames.in b/Source/core/css/SVGCSSPropertyNames.in
index de4d1df..1cf2871 100644
--- a/Source/core/css/SVGCSSPropertyNames.in
+++ b/Source/core/css/SVGCSSPropertyNames.in
@@ -49,4 +49,5 @@
 text-anchor
 vector-effect
 writing-mode
+paint-order
 
diff --git a/Source/core/css/SVGCSSValueKeywords.in b/Source/core/css/SVGCSSValueKeywords.in
index 3fd3642..ccfad3c 100644
--- a/Source/core/css/SVGCSSValueKeywords.in
+++ b/Source/core/css/SVGCSSValueKeywords.in
@@ -273,3 +273,9 @@
 // CSS_PROP_VECTOR_EFFECT
 // none
 non-scaling-stroke
+
+// CSS_PROP_PAINT_ORDER
+// normal
+// fill
+// stroke
+// markers
diff --git a/Source/core/css/StyleInvalidationAnalysis.cpp b/Source/core/css/StyleInvalidationAnalysis.cpp
index 2577372..ab0389d 100644
--- a/Source/core/css/StyleInvalidationAnalysis.cpp
+++ b/Source/core/css/StyleInvalidationAnalysis.cpp
@@ -31,7 +31,7 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/Document.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLStyleElement.h"
 
@@ -88,18 +88,34 @@
     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());
 
-    if (ownerElement->isInShadowTree() && hasDistributedRule(styleSheetContents)) {
-        ContainerNode* scope = ownerElement;
-        do {
-            scope = scope->containingShadowRoot()->shadowHost();
-        } while (scope->isInShadowTree());
+    if (ownerElement->isInShadowTree()) {
+        if (hasDistributedRule(styleSheetContents)) {
+            ContainerNode* scope = ownerElement;
+            do {
+                scope = scope->containingShadowRoot()->shadowHost();
+            } while (scope->isInShadowTree());
 
-        return scope;
+            return scope;
+        }
+        if (ownerElement->isRegisteredAsScoped() && hasAtHostRule(styleSheetContents))
+            return ownerElement->containingShadowRoot()->shadowHost();
     }
+
     return ownerElement->isRegisteredInShadowRoot() ? ownerElement->containingShadowRoot()->shadowHost() : ownerElement->parentNode();
 }
 
diff --git a/Source/core/css/StylePropertySerializer.cpp b/Source/core/css/StylePropertySerializer.cpp
index c6f298f..66008fe 100644
--- a/Source/core/css/StylePropertySerializer.cpp
+++ b/Source/core/css/StylePropertySerializer.cpp
@@ -312,6 +312,8 @@
 {
     // Shorthand and 4-values properties
     switch (propertyID) {
+    case CSSPropertyAnimation:
+        return getLayeredShorthandValue(animationShorthand());
     case CSSPropertyBorderSpacing:
         return borderSpacingValue(borderSpacingShorthand());
     case CSSPropertyBackgroundPosition:
@@ -366,8 +368,6 @@
         return getLayeredShorthandValue(transitionShorthand());
     case CSSPropertyListStyle:
         return getShorthandValue(listStyleShorthand());
-    case CSSPropertyWebkitMarquee:
-        return getShorthandValue(webkitMarqueeShorthand());
     case CSSPropertyWebkitMaskPosition:
         return getLayeredShorthandValue(webkitMaskPositionShorthand());
     case CSSPropertyWebkitMaskRepeat:
diff --git a/Source/core/css/StylePropertyShorthandCustom.cpp b/Source/core/css/StylePropertyShorthandCustom.cpp
index e49efe5..c3d44ac 100644
--- a/Source/core/css/StylePropertyShorthandCustom.cpp
+++ b/Source/core/css/StylePropertyShorthandCustom.cpp
@@ -36,6 +36,31 @@
     return borderForParsingLonghands;
 }
 
+const StylePropertyShorthand& animationShorthandForParsing()
+{
+    // When we parse the animation shorthand we need to look for animation-name
+    // last because otherwise it might match against the keywords for fill mode,
+    // timing functions and infinite iteration. This means that animation names
+    // that are the same as keywords (e.g. 'forwards') won't always match in the
+    // shorthand. In that case the authors should be using longhands (or
+    // reconsidering their approach). This is covered by the animations spec
+    // bug: https://www.w3.org/Bugs/Public/show_bug.cgi?id=14790
+    // And in the spec (editor's draft) at:
+    // http://dev.w3.org/csswg/css3-animations/#animation-shorthand-property
+    static const CSSPropertyID animationPropertiesForParsing[] = {
+        CSSPropertyAnimationDuration,
+        CSSPropertyAnimationTimingFunction,
+        CSSPropertyAnimationDelay,
+        CSSPropertyAnimationIterationCount,
+        CSSPropertyAnimationDirection,
+        CSSPropertyAnimationFillMode,
+        CSSPropertyAnimationPlayState,
+        CSSPropertyAnimationName
+    };
+    DEFINE_STATIC_LOCAL(StylePropertyShorthand, webkitAnimationLonghandsForParsing, (CSSPropertyAnimation, animationPropertiesForParsing, WTF_ARRAY_LENGTH(animationPropertiesForParsing)));
+    return webkitAnimationLonghandsForParsing;
+}
+
 const StylePropertyShorthand& webkitAnimationShorthandForParsing()
 {
     // When we parse the animation shorthand we need to look for animation-name
@@ -54,12 +79,28 @@
         CSSPropertyWebkitAnimationIterationCount,
         CSSPropertyWebkitAnimationDirection,
         CSSPropertyWebkitAnimationFillMode,
+        CSSPropertyWebkitAnimationPlayState,
         CSSPropertyWebkitAnimationName
     };
     DEFINE_STATIC_LOCAL(StylePropertyShorthand, webkitAnimationLonghandsForParsing, (CSSPropertyWebkitAnimation, animationPropertiesForParsing, WTF_ARRAY_LENGTH(animationPropertiesForParsing)));
     return webkitAnimationLonghandsForParsing;
 }
 
+// Returns an empty list if the property is not a shorthand, otherwise the list of longhands for parsing.
+const StylePropertyShorthand& parsingShorthandForProperty(CSSPropertyID propertyID)
+{
+    switch (propertyID) {
+    case CSSPropertyAnimation:
+        return animationShorthandForParsing();
+    case CSSPropertyBorder:
+        return borderShorthandForParsing();
+    case CSSPropertyWebkitAnimation:
+        return webkitAnimationShorthandForParsing();
+    default:
+        return shorthandForProperty(propertyID);
+    }
+}
+
 bool isExpandedShorthand(CSSPropertyID id)
 {
     // The system fonts bypass the normal style resolution by using RenderTheme,
diff --git a/Source/core/css/StyleRuleImport.cpp b/Source/core/css/StyleRuleImport.cpp
index cf72813..15d3d5b 100644
--- a/Source/core/css/StyleRuleImport.cpp
+++ b/Source/core/css/StyleRuleImport.cpp
@@ -25,9 +25,9 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CSSStyleSheetResource.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/CSSStyleSheetResource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/StyleRuleImport.h b/Source/core/css/StyleRuleImport.h
index 40412e3..c44253f 100644
--- a/Source/core/css/StyleRuleImport.h
+++ b/Source/core/css/StyleRuleImport.h
@@ -23,8 +23,8 @@
 #define StyleRuleImport_h
 
 #include "core/css/StyleRule.h"
-#include "core/loader/cache/ResourcePtr.h"
-#include "core/loader/cache/StyleSheetResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResourceClient.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/StyleSheetContents.cpp b/Source/core/css/StyleSheetContents.cpp
index 163276b..b99216d 100644
--- a/Source/core/css/StyleSheetContents.cpp
+++ b/Source/core/css/StyleSheetContents.cpp
@@ -28,7 +28,7 @@
 #include "core/css/StyleRule.h"
 #include "core/css/StyleRuleImport.h"
 #include "core/dom/Node.h"
-#include "core/loader/cache/CSSStyleSheetResource.h"
+#include "core/fetch/CSSStyleSheetResource.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/Deque.h"
 
diff --git a/Source/core/css/html.css b/Source/core/css/html.css
index e9f2b6d..dff2fce 100644
--- a/Source/core/css/html.css
+++ b/Source/core/css/html.css
@@ -143,6 +143,10 @@
     display: inline
 }
 
+video {
+    object-fit: contain;
+}
+
 /* heading elements */
 
 h1 {
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index 8fc9535..bbdfc59 100644
--- a/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -32,11 +32,13 @@
 #include "core/css/resolver/AnimatedStyleBuilder.h"
 
 #include "core/animation/AnimatableNumber.h"
+#include "core/animation/AnimatableTransform.h"
 #include "core/animation/AnimatableUnknown.h"
 #include "core/animation/AnimatableValue.h"
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/rendering/style/RenderStyle.h"
+#include "wtf/MathExtras.h"
 
 namespace WebCore {
 
@@ -48,6 +50,11 @@
     return toAnimatableNumber(value)->toLength(style, state.rootElementStyle(), style->effectiveZoom());
 }
 
+unsigned animatableValueToUnsigned(const AnimatableValue* value)
+{
+    return clampTo<unsigned>(round(toAnimatableNumber(value)->toDouble()));
+}
+
 } // namespace
 
 // FIXME: This should handle all animatable properties
@@ -62,6 +69,18 @@
     }
     RenderStyle* style = state.style();
     switch (property) {
+    case CSSPropertyBorderBottomWidth:
+        style->setBorderBottomWidth(animatableValueToUnsigned(value));
+        return;
+    case CSSPropertyBorderLeftWidth:
+        style->setBorderLeftWidth(animatableValueToUnsigned(value));
+        return;
+    case CSSPropertyBorderRightWidth:
+        style->setBorderRightWidth(animatableValueToUnsigned(value));
+        return;
+    case CSSPropertyBorderTopWidth:
+        style->setBorderTopWidth(animatableValueToUnsigned(value));
+        return;
     case CSSPropertyBottom:
         style->setBottom(animatableValueToLength(value, state));
         return;
@@ -122,6 +141,9 @@
     case CSSPropertyWebkitPerspectiveOriginY:
         style->setPerspectiveOriginY(animatableValueToLength(value, state));
         return;
+    case CSSPropertyWebkitTransform:
+        style->setTransform(toAnimatableTransform(value)->transformOperations());
+        return;
     case CSSPropertyWebkitTransformOriginX:
         style->setTransformOriginX(animatableValueToLength(value, state));
         return;
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index 1100570..261d458 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -35,7 +35,6 @@
 #include "core/css/StyleRule.h"
 #include "core/css/resolver/StyleResolver.h" // For MatchRequest.
 #include "core/dom/Document.h"
-#include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLStyleElement.h"
@@ -336,7 +335,15 @@
 void ScopedStyleResolver::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
 {
     AtomicString s(rule->name());
-    m_keyframesRuleMap.set(s.impl(), rule);
+    if (rule->isVendorPrefixed()) {
+        KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(rule->name().impl());
+        if (it == m_keyframesRuleMap.end())
+            m_keyframesRuleMap.set(s.impl(), rule);
+        else if (it->value->isVendorPrefixed())
+            m_keyframesRuleMap.set(s.impl(), rule);
+    } else {
+        m_keyframesRuleMap.set(s.impl(), rule);
+    }
 }
 
 inline RuleSet* ScopedStyleResolver::atHostRuleSetFor(const ShadowRoot* shadowRoot) const
diff --git a/Source/core/css/resolver/SharedStyleFinder.cpp b/Source/core/css/resolver/SharedStyleFinder.cpp
index ee83ce2..781998a 100644
--- a/Source/core/css/resolver/SharedStyleFinder.cpp
+++ b/Source/core/css/resolver/SharedStyleFinder.cpp
@@ -39,7 +39,6 @@
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/SpaceSplitString.h"
 #include "core/dom/shadow/ElementShadow.h"
diff --git a/Source/core/css/resolver/StyleAdjuster.cpp b/Source/core/css/resolver/StyleAdjuster.cpp
index dcc4fd7..4be738e 100644
--- a/Source/core/css/resolver/StyleAdjuster.cpp
+++ b/Source/core/css/resolver/StyleAdjuster.cpp
@@ -95,7 +95,6 @@
     case BOX:
     case FLEX:
     case GRID:
-    case LAZY_BLOCK:
         return display;
 
     case LIST_ITEM:
@@ -274,7 +273,7 @@
         || style->hasFilter()
         || style->hasBlendMode()
         || style->position() == StickyPosition
-        || (style->position() == FixedPosition && e && e->document()->page() && e->document()->page()->settings()->fixedPositionCreatesStackingContext())
+        || (style->position() == FixedPosition && e && e->document()->page() && e->document()->page()->settings().fixedPositionCreatesStackingContext())
         || isInTopLayer(e, style)
         ))
         style->setZIndex(0);
diff --git a/Source/core/css/resolver/StyleBuilderCustom.cpp b/Source/core/css/resolver/StyleBuilderCustom.cpp
index f49afb1..6b9c63b 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -982,7 +982,7 @@
     return true;
 }
 
-static bool createGridTrackList(CSSValue* value, Vector<GridTrackSize>& trackSizes, NamedGridLinesMap& namedGridLines, const StyleResolverState& state)
+static bool createGridTrackList(CSSValue* value, Vector<GridTrackSize>& trackSizes, NamedGridLinesMap& namedGridLines, OrderedNamedGridLines& orderedNamedGridLines, const StyleResolverState& state)
 {
     // Handle 'none'.
     if (value->isPrimitiveValue()) {
@@ -999,8 +999,11 @@
         if (currValue->isPrimitiveValue()) {
             CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(currValue);
             if (primitiveValue->isString()) {
-                NamedGridLinesMap::AddResult result = namedGridLines.add(primitiveValue->getStringValue(), Vector<size_t>());
+                String namedGridLine = primitiveValue->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;
             }
         }
@@ -1109,6 +1112,38 @@
     return color;
 }
 
+static EPaintOrder paintOrderFlattened(CSSValue* cssPaintOrder)
+{
+    if (cssPaintOrder->isValueList()) {
+        int paintOrder = 0;
+        CSSValueListInspector iter(cssPaintOrder);
+        for (size_t i = 0; i < iter.length(); i++) {
+            CSSPrimitiveValue* value = static_cast<CSSPrimitiveValue*>(iter.item(i));
+
+            EPaintOrderType paintOrderType = PT_NONE;
+            switch (value->getValueID()) {
+            case CSSValueFill:
+                paintOrderType = PT_FILL;
+                break;
+            case CSSValueStroke:
+                paintOrderType = PT_STROKE;
+                break;
+            case CSSValueMarkers:
+                paintOrderType = PT_MARKERS;
+                break;
+            default:
+                ASSERT_NOT_REACHED();
+                break;
+            }
+
+            paintOrder |= (paintOrderType << kPaintOrderBitwidth*i);
+        }
+        return (EPaintOrder)paintOrder;
+    }
+
+    return PO_NORMAL;
+}
+
 static bool numberToFloat(const CSSPrimitiveValue* primitiveValue, float& out)
 {
     if (!primitiveValue)
@@ -1395,6 +1430,7 @@
         state.setLineHeightValue(0);
         state.fontBuilder().fromSystemFont(primitiveValue->getValueID(), state.style()->effectiveZoom());
         return;
+    case CSSPropertyAnimation:
     case CSSPropertyBackground:
     case CSSPropertyBackgroundPosition:
     case CSSPropertyBackgroundRepeat:
@@ -1429,7 +1465,6 @@
     case CSSPropertyGridRow:
     case CSSPropertyGridArea:
     case CSSPropertyWebkitMarginCollapse:
-    case CSSPropertyWebkitMarquee:
     case CSSPropertyWebkitMask:
     case CSSPropertyWebkitMaskPosition:
     case CSSPropertyWebkitMaskRepeat:
@@ -1724,40 +1759,48 @@
         if (isInherit) {
             state.style()->setGridDefinitionColumns(state.parentStyle()->gridDefinitionColumns());
             state.style()->setNamedGridColumnLines(state.parentStyle()->namedGridColumnLines());
+            state.style()->setOrderedNamedGridColumnLines(state.parentStyle()->orderedNamedGridColumnLines());
             return;
         }
         if (isInitial) {
             state.style()->setGridDefinitionColumns(RenderStyle::initialGridDefinitionColumns());
             state.style()->setNamedGridColumnLines(RenderStyle::initialNamedGridColumnLines());
+            state.style()->setOrderedNamedGridColumnLines(RenderStyle::initialOrderedNamedGridColumnLines());
             return;
         }
 
         Vector<GridTrackSize> trackSizes;
         NamedGridLinesMap namedGridLines;
-        if (!createGridTrackList(value, trackSizes, namedGridLines, state))
+        OrderedNamedGridLines orderedNamedGridLines;
+        if (!createGridTrackList(value, trackSizes, namedGridLines, orderedNamedGridLines, state))
             return;
         state.style()->setGridDefinitionColumns(trackSizes);
         state.style()->setNamedGridColumnLines(namedGridLines);
+        state.style()->setOrderedNamedGridColumnLines(orderedNamedGridLines);
         return;
     }
     case CSSPropertyGridDefinitionRows: {
         if (isInherit) {
             state.style()->setGridDefinitionRows(state.parentStyle()->gridDefinitionRows());
             state.style()->setNamedGridRowLines(state.parentStyle()->namedGridRowLines());
+            state.style()->setOrderedNamedGridRowLines(state.parentStyle()->orderedNamedGridRowLines());
             return;
         }
         if (isInitial) {
             state.style()->setGridDefinitionRows(RenderStyle::initialGridDefinitionRows());
             state.style()->setNamedGridRowLines(RenderStyle::initialNamedGridRowLines());
+            state.style()->setOrderedNamedGridRowLines(RenderStyle::initialOrderedNamedGridRowLines());
             return;
         }
 
         Vector<GridTrackSize> trackSizes;
         NamedGridLinesMap namedGridLines;
-        if (!createGridTrackList(value, trackSizes, namedGridLines, state))
+        OrderedNamedGridLines orderedNamedGridLines;
+        if (!createGridTrackList(value, trackSizes, namedGridLines, orderedNamedGridLines, state))
             return;
         state.style()->setGridDefinitionRows(trackSizes);
         state.style()->setNamedGridRowLines(namedGridLines);
+        state.style()->setOrderedNamedGridRowLines(orderedNamedGridLines);
         return;
     }
 
@@ -1822,6 +1865,14 @@
     }
 
     // These properties are aliased and we already applied the property on the prefixed version.
+    case CSSPropertyAnimationDelay:
+    case CSSPropertyAnimationDirection:
+    case CSSPropertyAnimationDuration:
+    case CSSPropertyAnimationFillMode:
+    case CSSPropertyAnimationIterationCount:
+    case CSSPropertyAnimationName:
+    case CSSPropertyAnimationPlayState:
+    case CSSPropertyAnimationTimingFunction:
     case CSSPropertyTransitionDelay:
     case CSSPropertyTransitionDuration:
     case CSSPropertyTransitionProperty:
@@ -1895,6 +1946,7 @@
     case CSSPropertyMinHeight:
     case CSSPropertyMixBlendMode:
     case CSSPropertyMinWidth:
+    case CSSPropertyObjectFit:
     case CSSPropertyOpacity:
     case CSSPropertyOrphans:
     case CSSPropertyOutlineColor:
@@ -1997,7 +2049,7 @@
     case CSSPropertyWebkitLineClamp:
     case CSSPropertyWebkitLineGrid:
     case CSSPropertyWebkitLineSnap:
-    case CSSPropertyWebkitMarqueeDirection:
+    case CSSPropertyInternalMarqueeDirection:
     case CSSPropertyWebkitMarqueeIncrement:
     case CSSPropertyWebkitMarqueeRepetition:
     case CSSPropertyWebkitMarqueeSpeed:
@@ -2316,6 +2368,12 @@
             state.style()->accessSVGStyle()->setGlyphOrientationHorizontal(orientation);
         break;
     }
+    case CSSPropertyPaintOrder: {
+        HANDLE_SVG_INHERIT_AND_INITIAL(paintOrder, PaintOrder)
+        if (value->isValueList())
+            state.style()->accessSVGStyle()->setPaintOrder(paintOrderFlattened(value));
+        break;
+    }
     case CSSPropertyGlyphOrientationVertical:
     {
         HANDLE_SVG_INHERIT_AND_INITIAL(glyphOrientationVertical, GlyphOrientationVertical)
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index 4ce361f..717880f 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -67,7 +67,6 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
-#include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLIFrameElement.h"
@@ -149,8 +148,8 @@
             fontSelector()->addFontFaceRule((*it)->fontFaceRule());
     }
 #endif
-    m_styleTree.setBuildInDocumentOrder(!styleSheetCollection->hasScopedStyleSheet());
-    appendAuthorStyleSheets(0, styleSheetCollection->activeAuthorStyleSheets());
+
+    styleSheetCollection->appendActiveAuthorStyleSheets(this);
 }
 
 void StyleResolver::appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
@@ -170,7 +169,10 @@
         resolver->addRulesFromSheet(sheet, *m_medium, this);
         m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
     }
+}
 
+void StyleResolver::finishAppendAuthorStyleSheets()
+{
     collectFeatures();
 
     if (document()->renderer() && document()->renderer()->style())
@@ -182,7 +184,6 @@
 
 void StyleResolver::resetAuthorStyle(const ContainerNode* scopingNode)
 {
-    m_styleTree.clear();
     ScopedStyleResolver* resolver = scopingNode ? m_styleTree.scopedStyleResolverFor(scopingNode) : m_styleTree.scopedStyleResolverForDocument();
     if (!resolver)
         return;
@@ -190,8 +191,13 @@
     m_ruleSets.shadowDistributedRules().reset(scopingNode);
 
     resolver->resetAuthorStyle();
+    if (!scopingNode)
+        return;
 
-    if (!scopingNode || !resolver->hasOnlyEmptyRuleSets())
+    if (scopingNode->isShadowRoot())
+        resetAtHostRules(scopingNode);
+
+    if (!resolver->hasOnlyEmptyRuleSets())
         return;
 
     m_styleTree.remove(scopingNode);
@@ -275,13 +281,6 @@
     m_styleTree.popStyleCache(shadowRoot);
 }
 
-// This is a simplified style setting function for keyframe styles
-void StyleResolver::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
-{
-    AtomicString s(rule->name());
-    m_keyframesRuleMap.set(s.impl(), rule);
-}
-
 StyleResolver::~StyleResolver()
 {
     m_fontSelector->clearDocument();
@@ -770,7 +769,7 @@
         keyframeValue.addProperties(keyframe->properties());
 
         // Add this keyframe style to all the indicated key times
-        Vector<float> keys;
+        Vector<double> keys;
         keyframe->getKeys(keys);
         for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
             keyframeValue.setKey(keys[keyIndex]);
@@ -818,7 +817,7 @@
     for (size_t i = 0; i < styleKeyframes.size(); ++i) {
         const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
         RefPtr<RenderStyle> keyframeStyle = styleForKeyframe(element, style, styleKeyframe);
-        Vector<float> offsets;
+        Vector<double> offsets;
         styleKeyframe->getKeys(offsets);
         RefPtr<Keyframe> firstOffsetKeyframe;
         for (size_t j = 0; j < offsets.size(); ++j) {
@@ -827,6 +826,9 @@
             const StylePropertySet* properties = styleKeyframe->properties();
             for (unsigned k = 0; k < properties->propertyCount(); k++) {
                 CSSPropertyID property = properties->propertyAt(k).id();
+                // FIXME: Build the correct chained timing function when this property is specified.
+                if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction)
+                    continue;
                 keyframe->setPropertyValue(property, firstOffsetKeyframe ? firstOffsetKeyframe->propertyValue(property) : CSSAnimatableValueFactory::create(property, keyframeStyle.get()).get());
             }
             if (!firstOffsetKeyframe)
@@ -902,7 +904,7 @@
     for (unsigned i = 0; i < styleKeyframes.size(); ++i) {
         const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
 
-        Vector<float> offsets;
+        Vector<double> offsets;
         styleKeyframe->getKeys(offsets);
         for (size_t j = 0; j < offsets.size(); ++j) {
             if (!offsets[j]) {
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index d9d14e9..d952547 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -212,10 +212,9 @@
     // FIXME: It could be better to call m_ruleSets.appendAuthorStyleSheets() directly after we factor StyleRsolver further.
     // https://bugs.webkit.org/show_bug.cgi?id=108890
     void appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >&);
-    // FIXME: resetAuthorStyle() will be removed when rulesets are reset in a per-scoping node manner.
-    void resetAuthorStyle();
     void resetAuthorStyle(const ContainerNode*);
     void resetAtHostRules(const ContainerNode*);
+    void finishAppendAuthorStyleSheets();
 
     DocumentRuleSets& ruleSets() { return m_ruleSets; }
     const DocumentRuleSets& ruleSets() const { return m_ruleSets; }
@@ -255,9 +254,6 @@
     bool hasViewportDependentMediaQueries() const { return !m_viewportDependentMediaQueryResults.isEmpty(); }
     bool affectedByViewportChange() const;
 
-    // FIXME: This likely belongs on RuleSet.
-    void addKeyframeStyle(PassRefPtr<StyleRuleKeyframes>);
-
     // FIXME: Regions should not require special logic in StyleResolver.
     bool checkRegionStyle(Element* regionElement);
 
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
index bec0985..3158763 100644
--- a/Source/core/css/resolver/StyleResourceLoader.cpp
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -29,7 +29,7 @@
 #include "core/css/CSSSVGDocumentValue.h"
 #include "core/css/CSSShaderValue.h"
 #include "core/css/resolver/ElementStyleResources.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/CursorList.h"
diff --git a/Source/core/dom/Attr.h b/Source/core/dom/Attr.h
index 3673be2..21b3685 100644
--- a/Source/core/dom/Attr.h
+++ b/Source/core/dom/Attr.h
@@ -63,6 +63,12 @@
     void attachToElement(Element*);
     void detachFromElementWithValue(const AtomicString&);
 
+    virtual const AtomicString& localName() const OVERRIDE { return m_name.localName(); }
+    virtual const AtomicString& namespaceURI() const OVERRIDE { return m_name.namespaceURI(); }
+    virtual const AtomicString& prefix() const OVERRIDE { return m_name.prefix(); }
+
+    virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE;
+
 private:
     Attr(Element*, const QualifiedName&);
     Attr(Document*, const QualifiedName&, const AtomicString& value);
@@ -72,12 +78,6 @@
     virtual String nodeName() const OVERRIDE { return name(); }
     virtual NodeType nodeType() const OVERRIDE { return ATTRIBUTE_NODE; }
 
-    virtual const AtomicString& localName() const OVERRIDE { return m_name.localName(); }
-    virtual const AtomicString& namespaceURI() const OVERRIDE { return m_name.namespaceURI(); }
-    virtual const AtomicString& prefix() const OVERRIDE { return m_name.prefix(); }
-
-    virtual void setPrefix(const AtomicString&, ExceptionState&);
-
     virtual String nodeValue() const OVERRIDE { return value(); }
     virtual void setNodeValue(const String&);
     virtual PassRefPtr<Node> cloneNode(bool deep = true);
diff --git a/Source/core/dom/Attr.idl b/Source/core/dom/Attr.idl
index 97c7c46..0dcdb02 100644
--- a/Source/core/dom/Attr.idl
+++ b/Source/core/dom/Attr.idl
@@ -35,5 +35,11 @@
     // DOM Level 3
 
     readonly attribute boolean isId;
+
+    // DOM 4
+
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException] attribute DOMString prefix;
+    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
+    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
 };
 
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index 7221496..50b44c3 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -29,6 +29,7 @@
 #include "core/dom/MutationEvent.h"
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
+#include "core/dom/ProcessingInstruction.h"
 #include "core/dom/Text.h"
 #include "core/editing/FrameSelection.h"
 #include "core/inspector/InspectorInstrumentation.h"
@@ -97,7 +98,7 @@
 
     ASSERT(!renderer() || isTextNode());
     if (isTextNode())
-        toText(this)->updateTextRenderer(oldLength, 0);
+        toText(this)->updateTextRenderer(oldLength, 0, DeprecatedAttachNow);
 
     document()->incDOMTreeVersion();
 
@@ -107,16 +108,16 @@
     return characterLengthLimit;
 }
 
-void CharacterData::appendData(const String& data)
+void CharacterData::appendData(const String& data, AttachBehavior attachBehavior)
 {
     String newStr = m_data + data;
 
-    setDataAndUpdate(newStr, m_data.length(), 0, data.length());
+    setDataAndUpdate(newStr, m_data.length(), 0, data.length(), attachBehavior);
 
     // FIXME: Should we call textInserted here?
 }
 
-void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es)
+void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es, AttachBehavior attachBehavior)
 {
     if (offset > length()) {
         es.throwDOMException(IndexSizeError);
@@ -126,12 +127,12 @@
     String newStr = m_data;
     newStr.insert(data, offset);
 
-    setDataAndUpdate(newStr, offset, 0, data.length());
+    setDataAndUpdate(newStr, offset, 0, data.length(), attachBehavior);
 
     document()->textInserted(this, offset, data.length());
 }
 
-void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es)
+void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es, AttachBehavior attachBehavior)
 {
     if (offset > length()) {
         es.throwDOMException(IndexSizeError);
@@ -147,12 +148,12 @@
     String newStr = m_data;
     newStr.remove(offset, realCount);
 
-    setDataAndUpdate(newStr, offset, count, 0);
+    setDataAndUpdate(newStr, offset, count, 0, attachBehavior);
 
     document()->textRemoved(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& es, AttachBehavior attachBehavior)
 {
     if (offset > length()) {
         es.throwDOMException(IndexSizeError);
@@ -169,7 +170,7 @@
     newStr.remove(offset, realCount);
     newStr.insert(data, offset);
 
-    setDataAndUpdate(newStr, offset, count, data.length());
+    setDataAndUpdate(newStr, offset, count, data.length(), attachBehavior);
 
     // update the markers for spell checking and grammar checking
     document()->textRemoved(this, offset, realCount);
@@ -191,14 +192,17 @@
     setData(nodeValue);
 }
 
-void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength)
+void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength, AttachBehavior attachBehavior)
 {
     String oldData = m_data;
     m_data = newData;
 
     ASSERT(!renderer() || isTextNode());
     if (isTextNode())
-        toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength);
+        toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength, attachBehavior);
+
+    if (nodeType() == PROCESSING_INSTRUCTION_NODE)
+        toProcessingInstruction(this)->checkStyleSheet();
 
     if (document()->frame())
         document()->frame()->selection()->textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);
diff --git a/Source/core/dom/CharacterData.h b/Source/core/dom/CharacterData.h
index 8077364..473456e 100644
--- a/Source/core/dom/CharacterData.h
+++ b/Source/core/dom/CharacterData.h
@@ -37,10 +37,10 @@
     void setData(const String&);
     unsigned length() const { return m_data.length(); }
     String substringData(unsigned offset, unsigned count, ExceptionState&);
-    void appendData(const String&);
-    void insertData(unsigned offset, const String&, ExceptionState&);
-    void deleteData(unsigned offset, unsigned count, ExceptionState&);
-    void replaceData(unsigned offset, unsigned count, const String&, ExceptionState&);
+    void appendData(const String&, AttachBehavior = AttachLazily);
+    void insertData(unsigned offset, const String&, ExceptionState&, AttachBehavior = AttachLazily);
+    void deleteData(unsigned offset, unsigned count, ExceptionState&, AttachBehavior = AttachLazily);
+    void replaceData(unsigned offset, unsigned count, const String&, ExceptionState&, AttachBehavior = AttachLazily);
 
     bool containsOnlyWhitespace() const;
 
@@ -66,15 +66,15 @@
     }
     void didModifyData(const String& oldValue);
 
+    String m_data;
+
 private:
     virtual String nodeValue() const OVERRIDE FINAL;
     virtual void setNodeValue(const String&) OVERRIDE FINAL;
     virtual bool isCharacterDataNode() const OVERRIDE FINAL { return true; }
     virtual int maxCharacterOffset() const OVERRIDE FINAL;
     virtual bool offsetInCharacters() const OVERRIDE FINAL;
-    void setDataAndUpdate(const String&, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength);
-
-    String m_data;
+    void setDataAndUpdate(const String&, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength, AttachBehavior = AttachLazily);
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/Clipboard.cpp b/Source/core/dom/Clipboard.cpp
index 0c7f725..ee98d9f 100644
--- a/Source/core/dom/Clipboard.cpp
+++ b/Source/core/dom/Clipboard.cpp
@@ -26,8 +26,8 @@
 #include "config.h"
 #include "core/dom/Clipboard.h"
 
+#include "core/fetch/ImageResource.h"
 #include "core/fileapi/FileList.h"
-#include "core/loader/cache/ImageResource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Clipboard.h b/Source/core/dom/Clipboard.h
index a32134b..bc861de 100644
--- a/Source/core/dom/Clipboard.h
+++ b/Source/core/dom/Clipboard.h
@@ -27,7 +27,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/ClipboardAccessPolicy.h"
 #include "core/dom/Node.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/page/DragActions.h"
 #include "core/platform/DragImage.h"
 #include "core/platform/graphics/IntPoint.h"
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index 1b26b71..c184a5e 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -27,6 +27,7 @@
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ChildListMutationScope.h"
 #include "core/dom/ContainerNodeAlgorithms.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/FullscreenElementStack.h"
@@ -173,10 +174,6 @@
         return false;
     }
 
-    if (newChild->inDocument() && newChild->isDocumentTypeNode()) {
-        es.throwDOMException(HierarchyRequestError);
-        return false;
-    }
     if (containsConsideringHostElements(newChild, newParent)) {
         es.throwDOMException(HierarchyRequestError);
         return false;
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index 86f37de..f795436 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -87,6 +87,9 @@
     Node* lastChild() const { return m_lastChild; }
     bool hasChildNodes() const { return m_firstChild; }
 
+    bool hasOneChild() const { return m_firstChild && !m_firstChild->nextSibling(); }
+    bool hasOneTextChild() const { return hasOneChild() && m_firstChild->isTextNode(); }
+
     // ParentNode interface API
     PassRefPtr<HTMLCollection> children();
     Element* firstElementChild() const;
@@ -96,10 +99,10 @@
     unsigned childNodeCount() const;
     Node* childNode(unsigned index) const;
 
-    void insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachNow);
-    void replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachNow);
+    void insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachLazily);
+    void replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachLazily);
     void removeChild(Node* child, ExceptionState& = ASSERT_NO_EXCEPTION);
-    void appendChild(PassRefPtr<Node> newChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachNow);
+    void appendChild(PassRefPtr<Node> newChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachLazily);
 
     // These methods are only used during parsing.
     // They don't send DOM mutation events or handle reparenting.
diff --git a/Source/core/dom/ContainerNodeAlgorithms.cpp b/Source/core/dom/ContainerNodeAlgorithms.cpp
index 59d65ed..9f4eeac 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.cpp
+++ b/Source/core/dom/ContainerNodeAlgorithms.cpp
@@ -28,10 +28,20 @@
 
 #include "core/dom/Element.h"
 #include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 
 namespace WebCore {
 
+class ShadowRootVector : public Vector<RefPtr<ShadowRoot> > {
+public:
+    explicit ShadowRootVector(ElementShadow* tree)
+    {
+        for (ShadowRoot* root = tree->youngestShadowRoot(); root; root = root->olderShadowRoot())
+            append(root);
+    }
+};
+
 void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoDocument(ContainerNode* node)
 {
     ChildNodesLazySnapshot snapshot(node);
@@ -121,7 +131,7 @@
     unsigned count = 0;
 
     if (node->isElementNode()) {
-        if (node->isFrameOwnerElement() && toFrameOwnerElement(node)->contentFrame())
+        if (node->isFrameOwnerElement() && toHTMLFrameOwnerElement(node)->contentFrame())
             count++;
 
         if (ElementShadow* shadow = toElement(node)->shadow()) {
diff --git a/Source/core/dom/ContainerNodeAlgorithms.h b/Source/core/dom/ContainerNodeAlgorithms.h
index f02eb7f..ebd5263 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.h
+++ b/Source/core/dom/ContainerNodeAlgorithms.h
@@ -23,7 +23,6 @@
 #define ContainerNodeAlgorithms_h
 
 #include "core/dom/Document.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "wtf/Assertions.h"
@@ -289,7 +288,7 @@
         return;
 
     if (root->isHTMLElement() && root->isFrameOwnerElement())
-        m_frameOwners.append(toFrameOwnerElement(root));
+        m_frameOwners.append(toHTMLFrameOwnerElement(root));
 
     for (Node* child = root->firstChild(); child; child = child->nextSibling())
         collectFrameOwners(child);
diff --git a/Source/core/dom/CustomElement.cpp b/Source/core/dom/CustomElement.cpp
index 6ffcd2a..0529882 100644
--- a/Source/core/dom/CustomElement.cpp
+++ b/Source/core/dom/CustomElement.cpp
@@ -33,78 +33,103 @@
 
 #include "HTMLNames.h"
 #include "MathMLNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "core/dom/CustomElementCallbackScheduler.h"
-#include "core/dom/CustomElementUpgradeCandidateMap.h"
+#include "core/dom/CustomElementObserver.h"
 #include "core/dom/Element.h"
 
 namespace WebCore {
 
-Vector<AtomicString>& CustomElement::allowedCustomTagNames()
+Vector<AtomicString>& CustomElement::embedderCustomElementNames()
 {
-    DEFINE_STATIC_LOCAL(Vector<AtomicString>, tagNames, ());
-    return tagNames;
+    DEFINE_STATIC_LOCAL(Vector<AtomicString>, names, ());
+    return names;
 }
 
-void CustomElement::allowTagName(const AtomicString& localName)
+void CustomElement::addEmbedderCustomElementName(const AtomicString& name)
 {
-    AtomicString lower = localName.lower();
-    if (isCustomTagName(lower))
+    AtomicString lower = name.lower();
+    if (isValidName(lower, EmbedderNames))
         return;
-    allowedCustomTagNames().append(lower);
+    embedderCustomElementNames().append(lower);
 }
 
-bool CustomElement::isValidTypeName(const AtomicString& name)
+static CustomElement::NameSet enabledNameSet()
 {
-    if (notFound != allowedCustomTagNames().find(name))
-        return true;
+    return CustomElement::NameSet((RuntimeEnabledFeatures::customElementsEnabled() ? CustomElement::StandardNames : 0) | (RuntimeEnabledFeatures::embedderCustomElementsEnabled() ? CustomElement::EmbedderNames : 0));
+}
 
-    if (allowedCustomTagNames().size() > 0)
-        return false;
+bool CustomElement::isValidName(const AtomicString& name, NameSet validNames)
+{
+    validNames = NameSet(validNames & enabledNameSet());
 
-    if (notFound == name.find('-'))
-        return false;
+    if ((validNames & EmbedderNames) && notFound != embedderCustomElementNames().find(name))
+        return Document::isValidName(name);
 
-    DEFINE_STATIC_LOCAL(Vector<AtomicString>, reservedNames, ());
-    if (reservedNames.isEmpty()) {
-        reservedNames.append(MathMLNames::annotation_xmlTag.localName());
-        reservedNames.append(SVGNames::color_profileTag.localName());
-        reservedNames.append(SVGNames::font_faceTag.localName());
-        reservedNames.append(SVGNames::font_face_srcTag.localName());
-        reservedNames.append(SVGNames::font_face_uriTag.localName());
-        reservedNames.append(SVGNames::font_face_formatTag.localName());
-        reservedNames.append(SVGNames::font_face_nameTag.localName());
-        reservedNames.append(SVGNames::missing_glyphTag.localName());
+    if ((validNames & StandardNames) && notFound != name.find('-')) {
+        DEFINE_STATIC_LOCAL(Vector<AtomicString>, reservedNames, ());
+        if (reservedNames.isEmpty()) {
+            reservedNames.append(MathMLNames::annotation_xmlTag.localName());
+            reservedNames.append(SVGNames::color_profileTag.localName());
+            reservedNames.append(SVGNames::font_faceTag.localName());
+            reservedNames.append(SVGNames::font_face_srcTag.localName());
+            reservedNames.append(SVGNames::font_face_uriTag.localName());
+            reservedNames.append(SVGNames::font_face_formatTag.localName());
+            reservedNames.append(SVGNames::font_face_nameTag.localName());
+            reservedNames.append(SVGNames::missing_glyphTag.localName());
+        }
+
+        if (notFound == reservedNames.find(name))
+            return Document::isValidName(name.string());
     }
 
-    if (notFound != reservedNames.find(name))
-        return false;
-
-    return Document::isValidName(name.string());
-}
-
-bool CustomElement::isCustomTagName(const AtomicString& localName)
-{
-    return isValidTypeName(localName);
+    return false;
 }
 
 void CustomElement::define(Element* element, PassRefPtr<CustomElementDefinition> passDefinition)
 {
     RefPtr<CustomElementDefinition> definition(passDefinition);
-    element->setCustomElementState(Element::Defined);
-    definitions().add(element, definition);
-    CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
+
+    switch (element->customElementState()) {
+    case Element::NotCustomElement:
+    case Element::Upgraded:
+        ASSERT_NOT_REACHED();
+        break;
+
+    case Element::WaitingForParser:
+        definitions().add(element, definition);
+        break;
+
+    case Element::WaitingForUpgrade:
+        definitions().add(element, definition);
+        CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
+        break;
+    }
 }
 
 CustomElementDefinition* CustomElement::definitionFor(Element* element)
 {
-    return definitions().get(element);
+    CustomElementDefinition* definition = definitions().get(element);
+    ASSERT(definition);
+    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);
-    CustomElementCallbackScheduler::scheduleAttributeChangedCallback(definitions().get(element)->callbacks(), element, name, oldValue, newValue);
+    CustomElementCallbackScheduler::scheduleAttributeChangedCallback(definitionFor(element)->callbacks(), element, name, oldValue, newValue);
 }
 
 void CustomElement::didEnterDocument(Element* element, Document* document)
@@ -112,7 +137,7 @@
     ASSERT(element->customElementState() == Element::Upgraded);
     if (!document->defaultView())
         return;
-    CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(definitions().get(element)->callbacks(), element);
+    CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(definitionFor(element)->callbacks(), element);
 }
 
 void CustomElement::didLeaveDocument(Element* element, Document* document)
@@ -120,7 +145,7 @@
     ASSERT(element->customElementState() == Element::Upgraded);
     if (!document->defaultView())
         return;
-    CustomElementCallbackScheduler::scheduleLeftDocumentCallback(definitions().get(element)->callbacks(), element);
+    CustomElementCallbackScheduler::scheduleLeftDocumentCallback(definitionFor(element)->callbacks(), element);
 }
 
 void CustomElement::wasDestroyed(Element* element)
@@ -130,13 +155,11 @@
         ASSERT_NOT_REACHED();
         break;
 
-    case Element::UpgradeCandidate:
-        CustomElementUpgradeCandidateMap::elementWasDestroyed(element);
-        break;
-
-    case Element::Defined:
+    case Element::WaitingForParser:
+    case Element::WaitingForUpgrade:
     case Element::Upgraded:
         definitions().remove(element);
+        CustomElementObserver::notifyElementWasDestroyed(element);
         break;
     }
 }
@@ -148,18 +171,6 @@
     ASSERT(result.isNewEntry);
 }
 
-void CustomElement::DefinitionMap::remove(Element* element)
-{
-    m_definitions.remove(element);
-}
-
-CustomElementDefinition* CustomElement::DefinitionMap::get(Element* element)
-{
-    DefinitionMap::ElementDefinitionHashMap::const_iterator it = m_definitions.find(element);
-    ASSERT(it != m_definitions.end());
-    return it->value.get();
-}
-
 CustomElement::DefinitionMap& CustomElement::definitions()
 {
     DEFINE_STATIC_LOCAL(DefinitionMap, map, ());
diff --git a/Source/core/dom/CustomElement.h b/Source/core/dom/CustomElement.h
index 4fc4b57..07ba3c0 100644
--- a/Source/core/dom/CustomElement.h
+++ b/Source/core/dom/CustomElement.h
@@ -46,13 +46,13 @@
 
 class CustomElement {
 public:
-    // FIXME: CustomElementRegistry requires isValidTypeName to be a
-    // superset of isCustomTagName; consider either merging these or
-    // separating them completely into
-    // isCustomTagName/isTypeExtensionName.
-    static bool isValidTypeName(const AtomicString& type);
-    static bool isCustomTagName(const AtomicString& localName);
-    static void allowTagName(const AtomicString& localName);
+    enum NameSet {
+        EmbedderNames = 1 << 0,
+        StandardNames = 1 << 1,
+        AllNames = EmbedderNames | StandardNames
+    };
+    static bool isValidName(const AtomicString& name, NameSet validNames = AllNames);
+    static void addEmbedderCustomElementName(const AtomicString& name);
 
     // API for registration contexts
     static void define(Element*, PassRefPtr<CustomElementDefinition>);
@@ -62,6 +62,7 @@
 
     // API for Element to kick off changes
 
+    static void didFinishParsingChildren(Element*);
     static void attributeDidChange(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
     static void didEnterDocument(Element*, Document*);
     static void didLeaveDocument(Element*, Document*);
@@ -70,7 +71,7 @@
 private:
     CustomElement();
 
-    static Vector<AtomicString>& allowedCustomTagNames();
+    static Vector<AtomicString>& embedderCustomElementNames();
 
     // Maps resolved elements to their definitions
 
@@ -81,8 +82,8 @@
         ~DefinitionMap() { }
 
         void add(Element*, PassRefPtr<CustomElementDefinition>);
-        void remove(Element*);
-        CustomElementDefinition* get(Element*);
+        void remove(Element* element) { m_definitions.remove(element); }
+        CustomElementDefinition* get(Element* element) const { return m_definitions.get(element); }
 
     private:
         typedef HashMap<Element*, RefPtr<CustomElementDefinition> > ElementDefinitionHashMap;
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.cpp b/Source/core/dom/CustomElementCallbackDispatcher.cpp
index 405d7cf..41d5ecf 100644
--- a/Source/core/dom/CustomElementCallbackDispatcher.cpp
+++ b/Source/core/dom/CustomElementCallbackDispatcher.cpp
@@ -113,14 +113,6 @@
     }
 }
 
-CustomElementCallbackQueue* CustomElementCallbackDispatcher::createCallbackQueue(PassRefPtr<Element> element)
-{
-    Element* key = element.get();
-    ElementCallbackQueueMap::AddResult result = m_elementCallbackQueueMap.add(key, CustomElementCallbackQueue::create(element));
-    ASSERT(result.isNewEntry);
-    return result.iterator->value.get();
-}
-
 CustomElementCallbackQueue* CustomElementCallbackDispatcher::ensureCallbackQueue(PassRefPtr<Element> element)
 {
     Element* key = element.get();
@@ -130,34 +122,38 @@
     return it->value.get();
 }
 
+// Finds or creates the callback queue for element. If the
+// createdCallback has not finished running, the callback queue is not
+// moved to the top-of-stack. Otherwise like
+// scheduleInCurrentElementQueue.
+CustomElementCallbackQueue* CustomElementCallbackDispatcher::schedule(PassRefPtr<Element> element)
+{
+    CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
+    if (!callbackQueue->inCreatedCallback())
+        ensureInCurrentElementQueue(callbackQueue);
+    return callbackQueue;
+}
+
 // Finds or creates the callback queue for element. If the element's
 // callback queue is scheduled in an earlier processing stack frame,
 // its owner is set to the element queue on the top of the processing
 // stack. Because callback queues are processed exhaustively, this
 // effectively moves the callback queue to the top of the stack.
-CustomElementCallbackQueue* CustomElementCallbackDispatcher::ensureInCurrentElementQueue(PassRefPtr<Element> element)
+CustomElementCallbackQueue* CustomElementCallbackDispatcher::scheduleInCurrentElementQueue(PassRefPtr<Element> element)
 {
-    CustomElementCallbackQueue* queue = ensureCallbackQueue(element);
-    bool isInCurrentQueue = queue->owner() == currentElementQueue();
-    if (!isInCurrentQueue) {
-        queue->setOwner(currentElementQueue());
-        m_flattenedProcessingStack.append(queue);
-        ++s_elementQueueEnd;
-    }
-    return queue;
+    CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
+    ensureInCurrentElementQueue(callbackQueue);
+    return callbackQueue;
 }
 
-CustomElementCallbackQueue* CustomElementCallbackDispatcher::createAtFrontOfCurrentElementQueue(PassRefPtr<Element> element)
+void CustomElementCallbackDispatcher::ensureInCurrentElementQueue(CustomElementCallbackQueue* callbackQueue)
 {
-    CustomElementCallbackQueue* queue = createCallbackQueue(element);
-    queue->setOwner(currentElementQueue());
+    if (callbackQueue->owner() == currentElementQueue())
+        return;
 
-    // The created callback is unique in being prepended to the front
-    // of the element queue
-    m_flattenedProcessingStack.insert(inCallbackDeliveryScope() ? s_elementQueueStart : kNumSentinels, queue);
+    callbackQueue->setOwner(currentElementQueue());
+    m_flattenedProcessingStack.append(callbackQueue);
     ++s_elementQueueEnd;
-
-    return queue;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.h b/Source/core/dom/CustomElementCallbackDispatcher.h
index 74c0ae7..f26ec9b 100644
--- a/Source/core/dom/CustomElementCallbackDispatcher.h
+++ b/Source/core/dom/CustomElementCallbackDispatcher.h
@@ -73,8 +73,8 @@
 protected:
     friend class CustomElementCallbackScheduler;
 
-    CustomElementCallbackQueue* createAtFrontOfCurrentElementQueue(PassRefPtr<Element>);
-    CustomElementCallbackQueue* ensureInCurrentElementQueue(PassRefPtr<Element>);
+    CustomElementCallbackQueue* schedule(PassRefPtr<Element>);
+    CustomElementCallbackQueue* scheduleInCurrentElementQueue(PassRefPtr<Element>);
 
 private:
     CustomElementCallbackDispatcher()
@@ -106,8 +106,8 @@
     static void processElementQueueAndPop();
     void processElementQueueAndPop(size_t start, size_t end);
 
-    CustomElementCallbackQueue* createCallbackQueue(PassRefPtr<Element>);
     CustomElementCallbackQueue* ensureCallbackQueue(PassRefPtr<Element>);
+    void ensureInCurrentElementQueue(CustomElementCallbackQueue*);
 
     // The processing stack, flattened. Element queues lower in the
     // stack appear toward the head of the vector. The first element
diff --git a/Source/core/dom/CustomElementCallbackInvocation.cpp b/Source/core/dom/CustomElementCallbackInvocation.cpp
index 82e50e1..4974dc0 100644
--- a/Source/core/dom/CustomElementCallbackInvocation.cpp
+++ b/Source/core/dom/CustomElementCallbackInvocation.cpp
@@ -45,6 +45,7 @@
 
 private:
     virtual void dispatch(Element*) OVERRIDE;
+    virtual bool isCreated() const OVERRIDE { return true; }
 };
 
 void CreatedInvocation::dispatch(Element* element)
diff --git a/Source/core/dom/CustomElementCallbackInvocation.h b/Source/core/dom/CustomElementCallbackInvocation.h
index c6f0818..d2f8135 100644
--- a/Source/core/dom/CustomElementCallbackInvocation.h
+++ b/Source/core/dom/CustomElementCallbackInvocation.h
@@ -49,6 +49,7 @@
 
     virtual ~CustomElementCallbackInvocation() { }
     virtual void dispatch(Element*) = 0;
+    virtual bool isCreated() const { return false; }
 
 protected:
     CustomElementCallbackInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
diff --git a/Source/core/dom/CustomElementCallbackQueue.cpp b/Source/core/dom/CustomElementCallbackQueue.cpp
index d5641bd..7078364 100644
--- a/Source/core/dom/CustomElementCallbackQueue.cpp
+++ b/Source/core/dom/CustomElementCallbackQueue.cpp
@@ -44,16 +44,22 @@
     : m_element(element)
     , m_owner(-1)
     , m_index(0)
+    , m_inCreatedCallback(false)
 {
 }
 
 void CustomElementCallbackQueue::processInElementQueue(ElementQueue caller)
 {
+    ASSERT(!m_inCreatedCallback);
+
     while (m_index < m_queue.size() && owner() == caller) {
+        m_inCreatedCallback = m_queue[m_index]->isCreated();
+
         // dispatch() may cause recursion which steals this callback
         // queue and reenters processInQueue. owner() == caller
         // detects this recursion and cedes processing.
         m_queue[m_index++]->dispatch(m_element.get());
+        m_inCreatedCallback = false;
     }
 
     if (owner() == caller && m_index == m_queue.size()) {
diff --git a/Source/core/dom/CustomElementCallbackQueue.h b/Source/core/dom/CustomElementCallbackQueue.h
index 7e39486..430766f 100644
--- a/Source/core/dom/CustomElementCallbackQueue.h
+++ b/Source/core/dom/CustomElementCallbackQueue.h
@@ -56,6 +56,7 @@
 
     void append(PassOwnPtr<CustomElementCallbackInvocation> invocation) { m_queue.append(invocation); }
     void processInElementQueue(ElementQueue);
+    bool inCreatedCallback() const { return m_inCreatedCallback; }
 
 private:
     CustomElementCallbackQueue(PassRefPtr<Element>);
@@ -64,6 +65,7 @@
     Vector<OwnPtr<CustomElementCallbackInvocation> > m_queue;
     ElementQueue m_owner;
     size_t m_index;
+    bool m_inCreatedCallback;
 };
 
 }
diff --git a/Source/core/dom/CustomElementCallbackScheduler.cpp b/Source/core/dom/CustomElementCallbackScheduler.cpp
index 4a95d2b..79252ba 100644
--- a/Source/core/dom/CustomElementCallbackScheduler.cpp
+++ b/Source/core/dom/CustomElementCallbackScheduler.cpp
@@ -43,7 +43,7 @@
     if (!callbacks->hasAttributeChangedCallback())
         return;
 
-    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().ensureInCurrentElementQueue(element);
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().schedule(element);
     queue->append(CustomElementCallbackInvocation::createAttributeChangedInvocation(callbacks, name, oldValue, newValue));
 }
 
@@ -52,7 +52,7 @@
     if (!callbacks->hasCreatedCallback())
         return;
 
-    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().createAtFrontOfCurrentElementQueue(element);
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().scheduleInCurrentElementQueue(element);
     queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
 }
 
@@ -61,7 +61,7 @@
     if (!callbacks->hasEnteredDocumentCallback())
         return;
 
-    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().ensureInCurrentElementQueue(element);
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().schedule(element);
     queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::EnteredDocument));
 }
 
@@ -70,7 +70,7 @@
     if (!callbacks->hasLeftDocumentCallback())
         return;
 
-    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().ensureInCurrentElementQueue(element);
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().schedule(element);
     queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::LeftDocument));
 }
 
diff --git a/Source/core/dom/CustomElementException.cpp b/Source/core/dom/CustomElementException.cpp
new file mode 100644
index 0000000..b5752a8
--- /dev/null
+++ b/Source/core/dom/CustomElementException.cpp
@@ -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:
+ *
+ * 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/dom/CustomElementException.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+
+namespace WebCore {
+
+String CustomElementException::preamble(const AtomicString& type)
+{
+    return "Failed to call 'register' on 'Document' for type '" + type + "': ";
+}
+
+void CustomElementException::throwException(Reason reason, const AtomicString& type, ExceptionState& es)
+{
+    switch (reason) {
+    case CannotRegisterFromExtension:
+        es.throwDOMException(NotSupportedError, preamble(type) + "elements cannot be registered from extensions.");
+        return;
+
+    case ConstructorPropertyNotConfigurable:
+        es.throwDOMException(NotSupportedError, preamble(type) + "prototype constructor property is not configurable.");
+        return;
+
+    case ContextDestroyedCheckingPrototype:
+        es.throwDOMException(InvalidStateError, preamble(type) + "the context is no longer valid.");
+        return;
+
+    case ContextDestroyedCreatingCallbacks:
+        es.throwDOMException(InvalidStateError);
+        return;
+
+    case ContextDestroyedRegisteringDefinition:
+        es.throwDOMException(NotSupportedError);
+        return;
+
+    case InvalidName:
+        es.throwDOMException(InvalidCharacterError, preamble(type) + ": '" + type + "' is not a valid name.");
+        return;
+
+    case NotYetImplemented:
+        es.throwDOMException(InvalidStateError);
+        return;
+
+    case PrototypeDoesNotExtendHTMLElementSVGElementNamespace:
+        es.throwDOMException(NamespaceError, preamble(type) + "the prototype does not extend an HTML or SVG element.");
+        return;
+
+    case PrototypeDoesNotExtendHTMLElementSVGElementPrototype:
+        es.throwDOMException(InvalidStateError, preamble(type) + "the prototype does not extend an HTML or SVG element.");
+        return;
+
+    case PrototypeInUse:
+        es.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.");
+        return;
+
+    case TypeAlreadyRegistered:
+        es.throwDOMException(InvalidStateError, preamble(type) + "a type with that name is already registered.");
+        return;
+    }
+
+    ASSERT_NOT_REACHED();
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/CustomElementException.h b/Source/core/dom/CustomElementException.h
new file mode 100644
index 0000000..622ef22
--- /dev/null
+++ b/Source/core/dom/CustomElementException.h
@@ -0,0 +1,68 @@
+/*
+ * 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 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 CustomElementException_h
+#define CustomElementException_h
+
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class ExceptionState;
+
+class CustomElementException {
+public:
+    enum Reason {
+        CannotRegisterFromExtension,
+        ConstructorPropertyNotConfigurable,
+        ContextDestroyedCheckingPrototype,
+        ContextDestroyedCreatingCallbacks,
+        ContextDestroyedRegisteringDefinition,
+        InvalidName,
+        NotYetImplemented,
+        PrototypeDoesNotExtendHTMLElementSVGElementNamespace,
+        PrototypeDoesNotExtendHTMLElementSVGElementPrototype,
+        PrototypeInUse,
+        PrototypeNotAnObject,
+        TypeAlreadyRegistered
+    };
+
+    static void throwException(Reason, const AtomicString& type, ExceptionState&);
+
+private:
+    CustomElementException();
+
+    static String preamble(const AtomicString& type);
+};
+
+}
+
+#endif // CustomElementException_h
diff --git a/Source/core/dom/CustomElementObserver.cpp b/Source/core/dom/CustomElementObserver.cpp
new file mode 100644
index 0000000..45f1350
--- /dev/null
+++ b/Source/core/dom/CustomElementObserver.cpp
@@ -0,0 +1,70 @@
+/*
+ * 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 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/CustomElementObserver.h"
+
+namespace WebCore {
+
+CustomElementObserver::ElementObserverMap& CustomElementObserver::elementObservers()
+{
+    DEFINE_STATIC_LOCAL(ElementObserverMap, map, ());
+    return map;
+}
+
+void CustomElementObserver::notifyElementDidFinishParsingChildren(Element* element)
+{
+    ElementObserverMap::iterator it = elementObservers().find(element);
+    if (it == elementObservers().end())
+        return;
+    it->value->elementDidFinishParsingChildren(element);
+}
+
+void CustomElementObserver::notifyElementWasDestroyed(Element* element)
+{
+    ElementObserverMap::iterator it = elementObservers().find(element);
+    if (it == elementObservers().end())
+        return;
+    it->value->elementWasDestroyed(element);
+}
+
+void CustomElementObserver::observe(Element* element)
+{
+    ElementObserverMap::AddResult result = elementObservers().add(element, this);
+    ASSERT(result.isNewEntry);
+}
+
+void CustomElementObserver::unobserve(Element* element)
+{
+    CustomElementObserver* observer = elementObservers().take(element);
+    ASSERT(observer == this);
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/CustomElementObserver.h b/Source/core/dom/CustomElementObserver.h
new file mode 100644
index 0000000..ab7c57d
--- /dev/null
+++ b/Source/core/dom/CustomElementObserver.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:
+ *
+ * 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 CustomElementObserver_h
+#define CustomElementObserver_h
+
+#include "wtf/HashMap.h"
+
+namespace WebCore {
+
+class Element;
+
+class CustomElementObserver {
+public:
+    CustomElementObserver() { }
+    virtual ~CustomElementObserver() { }
+
+    // API for CustomElement to kick off notifications
+
+    static void notifyElementDidFinishParsingChildren(Element*);
+    static void notifyElementWasDestroyed(Element*);
+
+protected:
+    void observe(Element*);
+    void unobserve(Element*);
+
+    virtual void elementDidFinishParsingChildren(Element*) = 0;
+    virtual void elementWasDestroyed(Element* element) { unobserve(element); }
+
+private:
+    // Maps elements to the observer watching them. At most one per
+    // element at a time.
+    typedef HashMap<Element*, CustomElementObserver*> ElementObserverMap;
+    static ElementObserverMap& elementObservers();
+};
+
+}
+
+#endif // CustomElementObserver_h
diff --git a/Source/core/dom/CustomElementRegistrationContext.cpp b/Source/core/dom/CustomElementRegistrationContext.cpp
index 4589e7e..bedaf5e 100644
--- a/Source/core/dom/CustomElementRegistrationContext.cpp
+++ b/Source/core/dom/CustomElementRegistrationContext.cpp
@@ -35,6 +35,7 @@
 #include "SVGNames.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/CustomElement.h"
+#include "core/dom/CustomElementCallbackScheduler.h"
 #include "core/dom/CustomElementDefinition.h"
 #include "core/dom/Element.h"
 #include "core/html/HTMLElement.h"
@@ -44,9 +45,9 @@
 
 namespace WebCore {
 
-void CustomElementRegistrationContext::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& type, ExceptionState& es)
+void CustomElementRegistrationContext::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState& es)
 {
-    CustomElementDefinition* definition = m_registry.registerElement(document, constructorBuilder, type, es);
+    CustomElementDefinition* definition = m_registry.registerElement(document, constructorBuilder, type, validNames, es);
 
     if (!definition)
         return;
@@ -57,9 +58,9 @@
         didResolveElement(definition, *it);
 }
 
-PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document* document, const QualifiedName& tagName)
+PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document* document, const QualifiedName& tagName, CreationMode mode)
 {
-    ASSERT(CustomElement::isCustomTagName(tagName.localName()));
+    ASSERT(CustomElement::isValidName(tagName.localName()));
 
     if (!document)
         return 0;
@@ -75,6 +76,7 @@
         return Element::create(tagName, document);
     }
 
+    element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
     resolve(element.get(), nullAtom);
     return element.release();
 }
@@ -88,7 +90,7 @@
 {
     // If an element has a custom tag name it takes precedence over
     // the "is" attribute (if any).
-    const AtomicString& type = CustomElement::isCustomTagName(element->localName())
+    const AtomicString& type = CustomElement::isValidName(element->localName())
         ? element->localName()
         : typeExtension;
     ASSERT(!type.isNull());
@@ -108,14 +110,10 @@
 
 void CustomElementRegistrationContext::didCreateUnresolvedElement(const CustomElementDescriptor& descriptor, Element* element)
 {
+    ASSERT(element->customElementState() == Element::WaitingForParser || element->customElementState() == Element::WaitingForUpgrade);
     m_candidates.add(descriptor, element);
 }
 
-void CustomElementRegistrationContext::customElementWasDestroyed(Element* element)
-{
-    m_candidates.remove(element);
-}
-
 PassRefPtr<CustomElementRegistrationContext> CustomElementRegistrationContext::create()
 {
     return adoptRef(new CustomElementRegistrationContext());
@@ -129,7 +127,7 @@
     setTypeExtension(element, type);
 }
 
-void CustomElementRegistrationContext::setTypeExtension(Element* element, const AtomicString& type)
+void CustomElementRegistrationContext::setTypeExtension(Element* element, const AtomicString& type, CreationMode mode)
 {
     if (!element->isHTMLElement() && !element->isSVGElement())
         return;
@@ -144,7 +142,9 @@
     }
 
     // Custom tags take precedence over type extensions
-    ASSERT(!CustomElement::isCustomTagName(element->localName()));
+    ASSERT(!CustomElement::isValidName(element->localName()));
+
+    element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
 
     if (CustomElementRegistrationContext* context = element->document()->registrationContext())
         context->didGiveTypeExtension(element, type);
diff --git a/Source/core/dom/CustomElementRegistrationContext.h b/Source/core/dom/CustomElementRegistrationContext.h
index 64099d3..7b8449f 100644
--- a/Source/core/dom/CustomElementRegistrationContext.h
+++ b/Source/core/dom/CustomElementRegistrationContext.h
@@ -54,15 +54,17 @@
     ~CustomElementRegistrationContext() { }
 
     // Definitions
-    void registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& type, ExceptionState&);
+    void registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState&);
 
     // Instance creation
-    PassRefPtr<Element> createCustomTagElement(Document*, const QualifiedName&);
-    static void setIsAttributeAndTypeExtension(Element*, const AtomicString& type);
-    static void setTypeExtension(Element*, const AtomicString& type);
+    enum CreationMode {
+        CreatedByParser,
+        NotCreatedByParser
+    };
 
-    // Instance lifecycle
-    void customElementWasDestroyed(Element*);
+    PassRefPtr<Element> createCustomTagElement(Document*, const QualifiedName&, CreationMode = NotCreatedByParser);
+    static void setIsAttributeAndTypeExtension(Element*, const AtomicString& type);
+    static void setTypeExtension(Element*, const AtomicString& type, CreationMode = NotCreatedByParser);
 
 protected:
     CustomElementRegistrationContext() { }
diff --git a/Source/core/dom/CustomElementRegistry.cpp b/Source/core/dom/CustomElementRegistry.cpp
index 9d9195c..b734c82 100644
--- a/Source/core/dom/CustomElementRegistry.cpp
+++ b/Source/core/dom/CustomElementRegistry.cpp
@@ -34,12 +34,11 @@
 #include "HTMLNames.h"
 #include "SVGNames.h"
 #include "bindings/v8/CustomElementConstructorBuilder.h"
-#include "bindings/v8/ExceptionState.h"
 #include "core/dom/CustomElement.h"
 #include "core/dom/CustomElementDefinition.h"
+#include "core/dom/CustomElementException.h"
 #include "core/dom/CustomElementRegistrationContext.h"
 #include "core/dom/DocumentLifecycleObserver.h"
-#include "core/dom/ExceptionCode.h"
 
 namespace WebCore {
 
@@ -59,7 +58,7 @@
     bool m_wentAway;
 };
 
-CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, ExceptionState& es)
+CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, CustomElement::NameSet validNames, ExceptionState& es)
 {
     // FIXME: In every instance except one it is the
     // CustomElementConstructorBuilder that observes document
@@ -67,31 +66,30 @@
     // consolidated in one place.
     RegistrationContextObserver observer(document);
 
-    if (!constructorBuilder->isFeatureAllowed()) {
-        es.throwDOMException(NotSupportedError);
-        return 0;
-    }
-
     AtomicString type = userSuppliedName.lower();
-    if (!CustomElement::isValidTypeName(type)) {
-        es.throwDOMException(InvalidCharacterError);
+
+    if (!constructorBuilder->isFeatureAllowed()) {
+        CustomElementException::throwException(CustomElementException::CannotRegisterFromExtension, type, es);
         return 0;
     }
 
-    if (!constructorBuilder->validateOptions()) {
-        es.throwDOMException(InvalidStateError);
+    if (!CustomElement::isValidName(type, validNames)) {
+        CustomElementException::throwException(CustomElementException::InvalidName, type, es);
         return 0;
     }
 
+    if (!constructorBuilder->validateOptions(type, es))
+        return 0;
+
     QualifiedName tagName = nullQName();
     if (!constructorBuilder->findTagName(type, tagName)) {
-        es.throwDOMException(NamespaceError);
+        CustomElementException::throwException(CustomElementException::PrototypeDoesNotExtendHTMLElementSVGElementNamespace, type, es);
         return 0;
     }
     ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
 
     if (m_registeredTypeNames.contains(type)) {
-        es.throwDOMException(InvalidStateError);
+        CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, es);
         return 0;
     }
 
@@ -102,23 +100,21 @@
     // Consulting the constructor builder could execute script and
     // kill the document.
     if (observer.registrationContextWentAway()) {
-        es.throwDOMException(InvalidStateError);
+        CustomElementException::throwException(CustomElementException::ContextDestroyedCreatingCallbacks, type, es);
         return 0;
     }
 
     const CustomElementDescriptor descriptor(type, tagName.namespaceURI(), tagName.localName());
     RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(descriptor, lifecycleCallbacks);
 
-    if (!constructorBuilder->createConstructor(document, definition.get())) {
-        es.throwDOMException(NotSupportedError);
+    if (!constructorBuilder->createConstructor(document, definition.get(), es))
         return 0;
-    }
 
     m_definitions.add(descriptor, definition);
     m_registeredTypeNames.add(descriptor.type());
 
     if (!constructorBuilder->didRegisterDefinition(definition.get())) {
-        es.throwDOMException(NotSupportedError);
+        CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, type, es);
         return 0;
     }
 
diff --git a/Source/core/dom/CustomElementRegistry.h b/Source/core/dom/CustomElementRegistry.h
index c9ff8db..d1a79bd 100644
--- a/Source/core/dom/CustomElementRegistry.h
+++ b/Source/core/dom/CustomElementRegistry.h
@@ -31,6 +31,7 @@
 #ifndef CustomElementRegistry_h
 #define CustomElementRegistry_h
 
+#include "core/dom/CustomElement.h"
 #include "core/dom/CustomElementDefinition.h"
 #include "core/dom/CustomElementDescriptor.h"
 #include "core/dom/CustomElementDescriptorHash.h"
@@ -54,7 +55,7 @@
     CustomElementRegistry() { }
     virtual ~CustomElementRegistry() { }
 
-    CustomElementDefinition* registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& name, ExceptionState&);
+    CustomElementDefinition* registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& name, CustomElement::NameSet validNames, ExceptionState&);
     CustomElementDefinition* find(const CustomElementDescriptor&) const;
 
 private:
diff --git a/Source/core/dom/CustomElementUpgradeCandidateMap.cpp b/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
index c84bcb7..8583eb2 100644
--- a/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
+++ b/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
@@ -39,14 +39,12 @@
 {
     UpgradeCandidateMap::const_iterator::Keys end = m_upgradeCandidates.end().keys();
     for (UpgradeCandidateMap::const_iterator::Keys it = m_upgradeCandidates.begin().keys(); it != end; ++it)
-        unregisterForElementDestructionNotification(*it, this);
+        unobserve(*it);
 }
 
 void CustomElementUpgradeCandidateMap::add(const CustomElementDescriptor& descriptor, Element* element)
 {
-    element->setCustomElementState(Element::UpgradeCandidate);
-
-    registerForElementDestructionNotification(element, this);
+    observe(element);
 
     UpgradeCandidateMap::AddResult result = m_upgradeCandidates.add(element, descriptor);
     ASSERT(result.isNewEntry);
@@ -59,8 +57,18 @@
 
 void CustomElementUpgradeCandidateMap::remove(Element* element)
 {
-    unregisterForElementDestructionNotification(element, this);
+    unobserve(element);
+    removeCommon(element);
+}
 
+void CustomElementUpgradeCandidateMap::elementWasDestroyed(Element* element)
+{
+    CustomElementObserver::elementWasDestroyed(element);
+    removeCommon(element);
+}
+
+void CustomElementUpgradeCandidateMap::removeCommon(Element* element)
+{
     UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
     ASSERT(candidate != m_upgradeCandidates.end());
 
@@ -70,42 +78,33 @@
     m_upgradeCandidates.remove(candidate);
 }
 
+void CustomElementUpgradeCandidateMap::elementDidFinishParsingChildren(Element* element)
+{
+    // An upgrade candidate finished parsing; reorder so that eventual
+    // upgrade order matches finished-parsing order.
+    moveToEnd(element);
+}
+
+void CustomElementUpgradeCandidateMap::moveToEnd(Element* element)
+{
+    UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
+    ASSERT(candidate != m_upgradeCandidates.end());
+
+    UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
+    ASSERT(elements != m_unresolvedDefinitions.end());
+    elements->value.appendOrMoveToLast(element);
+}
+
 ListHashSet<Element*> CustomElementUpgradeCandidateMap::takeUpgradeCandidatesFor(const CustomElementDescriptor& descriptor)
 {
     const ListHashSet<Element*>& candidates = m_unresolvedDefinitions.take(descriptor);
 
     for (ElementSet::const_iterator candidate = candidates.begin(); candidate != candidates.end(); ++candidate) {
-        unregisterForElementDestructionNotification(*candidate, this);
+        unobserve(*candidate);
         m_upgradeCandidates.remove(*candidate);
     }
 
     return candidates;
 }
 
-void CustomElementUpgradeCandidateMap::elementWasDestroyed(Element* element)
-{
-    DestructionObserverMap::iterator it = destructionObservers().find(element);
-    if (it == destructionObservers().end())
-        return;
-    it->value->remove(element); // will also remove the destruction observer
-}
-
-CustomElementUpgradeCandidateMap::DestructionObserverMap& CustomElementUpgradeCandidateMap::destructionObservers()
-{
-    DEFINE_STATIC_LOCAL(DestructionObserverMap, map, ());
-    return map;
-}
-
-void CustomElementUpgradeCandidateMap::registerForElementDestructionNotification(Element* element, CustomElementUpgradeCandidateMap* observer)
-{
-    DestructionObserverMap::AddResult result = destructionObservers().add(element, observer);
-    ASSERT(result.isNewEntry);
-}
-
-void CustomElementUpgradeCandidateMap::unregisterForElementDestructionNotification(Element* element, CustomElementUpgradeCandidateMap* observer)
-{
-    CustomElementUpgradeCandidateMap* map = destructionObservers().take(element);
-    ASSERT(map == observer);
-}
-
 }
diff --git a/Source/core/dom/CustomElementUpgradeCandidateMap.h b/Source/core/dom/CustomElementUpgradeCandidateMap.h
index 2814c0a..f9f2311 100644
--- a/Source/core/dom/CustomElementUpgradeCandidateMap.h
+++ b/Source/core/dom/CustomElementUpgradeCandidateMap.h
@@ -33,6 +33,7 @@
 
 #include "core/dom/CustomElementDescriptor.h"
 #include "core/dom/CustomElementDescriptorHash.h"
+#include "core/dom/CustomElementObserver.h"
 #include "wtf/HashMap.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/Noncopyable.h"
@@ -41,26 +42,26 @@
 
 class Element;
 
-class CustomElementUpgradeCandidateMap {
+class CustomElementUpgradeCandidateMap : CustomElementObserver {
     WTF_MAKE_NONCOPYABLE(CustomElementUpgradeCandidateMap);
 public:
     CustomElementUpgradeCandidateMap() { }
     ~CustomElementUpgradeCandidateMap();
 
-    static void elementWasDestroyed(Element*);
+    // API for CustomElementRegistrationContext to save and take candidates
+
+    typedef ListHashSet<Element*> ElementSet;
 
     void add(const CustomElementDescriptor&, Element*);
     void remove(Element*);
-
-    typedef ListHashSet<Element*> ElementSet;
     ElementSet takeUpgradeCandidatesFor(const CustomElementDescriptor&);
 
 private:
-    // Maps elements to upgrade candidate maps observing their destruction
-    typedef HashMap<Element*, CustomElementUpgradeCandidateMap*> DestructionObserverMap;
-    static DestructionObserverMap& destructionObservers();
-    static void registerForElementDestructionNotification(Element*, CustomElementUpgradeCandidateMap*);
-    static void unregisterForElementDestructionNotification(Element*, CustomElementUpgradeCandidateMap*);
+    virtual void elementWasDestroyed(Element*) OVERRIDE;
+    void removeCommon(Element*);
+
+    virtual void elementDidFinishParsingChildren(Element*) OVERRIDE;
+    void moveToEnd(Element*);
 
     typedef HashMap<Element*, CustomElementDescriptor> UpgradeCandidateMap;
     UpgradeCandidateMap m_upgradeCandidates;
diff --git a/Source/core/dom/DOMError.h b/Source/core/dom/DOMError.h
index 74d4d17..a66d0e2 100644
--- a/Source/core/dom/DOMError.h
+++ b/Source/core/dom/DOMError.h
@@ -59,10 +59,11 @@
     const String& name() const { return m_name; }
     const String& message() const { return m_message; }
 
-private:
+protected:
     explicit DOMError(const String& name);
-    explicit DOMError(const String& name, const String& message);
+    DOMError(const String& name, const String& message);
 
+private:
     const String m_name;
     const String m_message;
 };
diff --git a/Source/core/dom/DOMException.cpp b/Source/core/dom/DOMException.cpp
index 7510e27..348a94e 100644
--- a/Source/core/dom/DOMException.cpp
+++ b/Source/core/dom/DOMException.cpp
@@ -86,22 +86,24 @@
     return tableIndex < tableSize ? &coreExceptions[tableIndex] : 0;
 }
 
-DOMException::DOMException(unsigned short code, const String& name, const String& message)
+DOMException::DOMException(unsigned short code, const String& name, const String& sanitizedMessage, const String& unsanitizedMessage)
 {
     ASSERT(name);
     m_code = code;
     m_name = name;
-    m_message = message;
+    m_sanitizedMessage = sanitizedMessage;
+    m_unsanitizedMessage = unsanitizedMessage;
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<DOMException> DOMException::create(ExceptionCode ec, const String& message)
+PassRefPtr<DOMException> DOMException::create(ExceptionCode ec, const String& sanitizedMessage, const String& unsanitizedMessage)
 {
     const CoreException* entry = getErrorEntry(ec);
     ASSERT(entry);
     return adoptRef(new DOMException(entry->code,
         entry->name ? entry->name : "Error",
-        message.isNull() ? String(entry->message) : message));
+        sanitizedMessage.isNull() ? String(entry->message) : sanitizedMessage,
+        unsanitizedMessage));
 }
 
 String DOMException::toString() const
@@ -109,6 +111,11 @@
     return name() + ": " + message();
 }
 
+String DOMException::toStringForConsole() const
+{
+    return name() + ": " + messageForConsole();
+}
+
 String DOMException::getErrorName(ExceptionCode ec)
 {
     const CoreException* entry = getErrorEntry(ec);
diff --git a/Source/core/dom/DOMException.h b/Source/core/dom/DOMException.h
index ca96483..825cf50 100644
--- a/Source/core/dom/DOMException.h
+++ b/Source/core/dom/DOMException.h
@@ -40,24 +40,30 @@
 
 class DOMException : public RefCounted<DOMException>, public ScriptWrappable {
 public:
-    static PassRefPtr<DOMException> create(ExceptionCode, const String& message = String());
+    static PassRefPtr<DOMException> create(ExceptionCode, const String& sanitizedMessage = String(), const String& unsanitizedMessage = String());
 
     unsigned short code() const { return m_code; }
     String name() const { return m_name; }
-    String message() const { return m_message; }
 
+    // This is the message that's exposed to JavaScript: never return unsanitized data.
+    String message() const { return m_sanitizedMessage; }
     String toString() const;
 
+    // This is the message that's exposed to the console: if an unsanitized message is present, we prefer it.
+    String messageForConsole() const { return !m_unsanitizedMessage.isEmpty() ? m_unsanitizedMessage : m_sanitizedMessage; }
+    String toStringForConsole() const;
+
     static String getErrorName(ExceptionCode);
     static String getErrorMessage(ExceptionCode);
     static unsigned short getLegacyErrorCode(ExceptionCode);
 
 private:
-    DOMException(unsigned short m_code, const String& name, const String& message);
+    DOMException(unsigned short m_code, const String& name, const String& sanitizedMessage, const String& unsanitizedMessage);
 
     unsigned short m_code;
     String m_name;
-    String m_message;
+    String m_sanitizedMessage;
+    String m_unsanitizedMessage;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 14c51fe..3b888bc 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -184,7 +184,7 @@
     if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
         return 0;
 
-    return DocumentType::create(0, qualifiedName, publicId, systemId);
+    return DocumentType::create(m_document, qualifiedName, publicId, systemId);
 }
 
 DOMImplementation* DOMImplementation::getInterface(const String& /*feature*/)
@@ -213,16 +213,6 @@
             return 0;
     }
 
-    // WrongDocumentError: Raised if doctype has already been used with a different document or was
-    // created from a different implementation.
-    // Hixie's interpretation of the DOM Core spec suggests we should prefer
-    // other exceptions to WrongDocumentError (based on order mentioned in spec),
-    // but this matches the new DOM Core spec (http://www.w3.org/TR/domcore/).
-    if (doctype && doctype->document()) {
-        es.throwDOMException(WrongDocumentError);
-        return 0;
-    }
-
     if (doctype)
         doc->appendChild(doctype);
     if (documentElement)
diff --git a/Source/core/dom/DOMImplementation.idl b/Source/core/dom/DOMImplementation.idl
index 0d627f5..c110cb4 100644
--- a/Source/core/dom/DOMImplementation.idl
+++ b/Source/core/dom/DOMImplementation.idl
@@ -29,12 +29,12 @@
 
     // DOM Level 2
 
-     [RaisesException] DocumentType createDocumentType([TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString qualifiedName,
-                                                   [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString publicId,
-                                                   [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString systemId);
-     [RaisesException] Document createDocument([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                           [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName,
-                                           [TreatNullAs=NullString,Default=Undefined] optional DocumentType doctype);
+     [RaisesException] DocumentType createDocumentType([TreatNullAs=NullString] DOMString qualifiedName,
+                                                       [TreatNullAs=NullString] DOMString publicId,
+                                                       [TreatNullAs=NullString] DOMString systemId);
+     [RaisesException] Document createDocument([TreatNullAs=NullString] DOMString namespaceURI,
+                                               [TreatNullAs=NullString] DOMString qualifiedName,
+                                               [Default=Undefined] optional DocumentType doctype);
 
     // DOMImplementationCSS interface from DOM Level 2 CSS
 
diff --git a/Source/core/dom/DataTransferItemList.h b/Source/core/dom/DataTransferItemList.h
index 91fd967..90d847f 100644
--- a/Source/core/dom/DataTransferItemList.h
+++ b/Source/core/dom/DataTransferItemList.h
@@ -56,8 +56,8 @@
     virtual PassRefPtr<DataTransferItem> item(unsigned long index) = 0;
     virtual void deleteItem(unsigned long index, ExceptionState&) = 0;
     virtual void clear() = 0;
-    virtual void add(const String& data, const String& type, ExceptionState&) = 0;
-    virtual void add(PassRefPtr<File>) = 0;
+    virtual PassRefPtr<DataTransferItem> add(const String& data, const String& type, ExceptionState&) = 0;
+    virtual PassRefPtr<DataTransferItem> add(PassRefPtr<File>) = 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/DataTransferItemList.idl b/Source/core/dom/DataTransferItemList.idl
index eec5c0c..0babe03 100644
--- a/Source/core/dom/DataTransferItemList.idl
+++ b/Source/core/dom/DataTransferItemList.idl
@@ -28,15 +28,13 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    NoInterfaceObject
-] interface DataTransferItemList {
+interface DataTransferItemList {
     readonly attribute long length;
-    getter DataTransferItem item([Default=Undefined] optional unsigned long index);
+    [ImplementedAs=item] getter DataTransferItem (unsigned long index);
 
+    [RaisesException, ImplementedAs=deleteItem] void remove(unsigned long index);
     void clear();
-    void add(File? file);
-    [RaisesException] void add([Default=Undefined] optional DOMString data,
-             [Default=Undefined] optional DOMString type);
+    DataTransferItem add(File? file);
+    [RaisesException] DataTransferItem add(DOMString data, DOMString type);
 };
 
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 62dee7a..9dfe1b6 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -37,6 +37,7 @@
 #include "XMLNames.h"
 #include "bindings/v8/CustomElementConstructorBuilder.h"
 #include "bindings/v8/Dictionary.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "bindings/v8/ScriptController.h"
@@ -51,10 +52,10 @@
 #include "core/css/StyleSheetList.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
+#include "core/dom/BeforeUnloadEvent.h"
 #include "core/dom/CDATASection.h"
 #include "core/dom/Comment.h"
 #include "core/dom/ContextFeatures.h"
-#include "core/dom/CustomElement.h"
 #include "core/dom/CustomElementRegistrationContext.h"
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/DOMNamedFlowCollection.h"
@@ -66,6 +67,7 @@
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventFactory.h"
 #include "core/dom/EventListener.h"
@@ -97,6 +99,7 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/FormController.h"
 #include "core/html/HTMLAllCollection.h"
 #include "core/html/HTMLAnchorElement.h"
@@ -108,6 +111,7 @@
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLImport.h"
+#include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLNameCollection.h"
 #include "core/html/HTMLScriptElement.h"
@@ -128,7 +132,6 @@
 #include "core/loader/Prerenderer.h"
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/ContentSecurityPolicy.h"
@@ -144,7 +147,6 @@
 #include "core/page/PageConsole.h"
 #include "core/page/PointerLockController.h"
 #include "core/page/Settings.h"
-#include "core/page/ValidationMessageClient.h"
 #include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/DateComponents.h"
@@ -401,7 +403,6 @@
     , m_bParsing(false)
     , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
     , m_inStyleRecalc(false)
-    , m_closeAfterStyleRecalc(false)
     , m_gotoAnchorNeededAfterStylesheetsLoad(false)
     , m_containsValidityStyleRules(false)
     , m_updateFocusAppearanceRestoresSelection(false)
@@ -435,6 +436,7 @@
     , m_referrerPolicy(ReferrerPolicyDefault)
     , m_directionSetOnDocumentElement(false)
     , m_writingModeSetOnDocumentElement(false)
+    , m_didAllowNavigationViaBeforeUnloadConfirmationPanel(false)
     , m_writeRecursionIsTooDeep(false)
     , m_writeRecursionDepth(0)
     , m_wheelEventHandlerCount(0)
@@ -715,7 +717,7 @@
 
     RefPtr<Element> element;
 
-    if (CustomElement::isCustomTagName(localName) && registrationContext())
+    if (CustomElement::isValidName(localName) && registrationContext())
         element = registrationContext()->createCustomTagElement(this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
     else
         element = createElement(localName, es);
@@ -739,7 +741,7 @@
     }
 
     RefPtr<Element> element;
-    if (CustomElement::isCustomTagName(qName.localName()) && registrationContext())
+    if (CustomElement::isValidName(qName.localName()) && registrationContext())
         element = registrationContext()->createCustomTagElement(this, qName);
     else
         element = createElementNS(namespaceURI, qualifiedName, es);
@@ -755,7 +757,7 @@
     return registerElement(state, name, Dictionary(), es);
 }
 
-ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& es)
+ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& es, CustomElement::NameSet validNames)
 {
     if (!registrationContext()) {
         es.throwDOMException(NotSupportedError);
@@ -763,7 +765,7 @@
     }
 
     CustomElementConstructorBuilder constructorBuilder(state, &options);
-    registrationContext()->registerElement(this, &constructorBuilder, name, es);
+    registrationContext()->registerElement(this, &constructorBuilder, name, validNames, es);
     return constructorBuilder.bindingsReturnValue();
 }
 
@@ -939,7 +941,7 @@
         }
 
         if (source->isFrameOwnerElement()) {
-            HTMLFrameOwnerElement* frameOwnerElement = toFrameOwnerElement(source.get());
+            HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
             if (frame() && frame()->tree()->isDescendantOf(frameOwnerElement->contentFrame())) {
                 es.throwDOMException(HierarchyRequestError);
                 return 0;
@@ -1082,8 +1084,11 @@
 
     switch (readyState) {
     case Loading:
-        if (!m_documentTiming.domLoading)
+        if (!m_documentTiming.domLoading) {
             m_documentTiming.domLoading = monotonicallyIncreasingTime();
+            if (RuntimeEnabledFeatures::webAnimationsEnabled())
+                m_timeline->setZeroTimeAsPerfTime(m_documentTiming.domLoading);
+        }
         break;
     case Interactive:
         if (!m_documentTiming.domInteractive)
@@ -1293,6 +1298,7 @@
 
     m_rawTitle = title;
 
+    StringWithDirection oldTitle = m_title;
     if (m_rawTitle.string().isEmpty())
         m_title = StringWithDirection();
     else {
@@ -1301,8 +1307,11 @@
         else
             m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
     }
-    if (Frame* f = frame())
-        f->loader()->setTitle(m_title);
+
+    if (!m_frame || oldTitle == m_title)
+        return;
+    m_frame->loader()->history()->setCurrentItemTitle(m_title);
+    m_frame->loader()->client()->dispatchDidReceiveTitle(m_title);
 }
 
 void Document::setTitle(const String& title)
@@ -1314,7 +1323,7 @@
     else if (!m_titleElement) {
         if (HTMLElement* headElement = head()) {
             m_titleElement = createElement(titleTag, false);
-            headElement->appendChild(m_titleElement, ASSERT_NO_EXCEPTION, AttachLazily);
+            headElement->appendChild(m_titleElement);
         }
     }
 
@@ -1680,12 +1689,6 @@
         }
     }
 
-    // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
-    if (m_closeAfterStyleRecalc) {
-        m_closeAfterStyleRecalc = false;
-        implicitClose();
-    }
-
     STYLE_STATS_PRINT();
     STYLE_STATS_CLEAR();
 
@@ -1888,11 +1891,8 @@
 {
     ASSERT(attached());
 
-    if (page()) {
-        page()->pointerLockController()->documentDetached(this);
-        if (ValidationMessageClient* client = page()->validationMessageClient())
-            client->documentDetached(*this);
-    }
+    if (page())
+        page()->documentDetached(this);
 
     if (this == topDocument())
         clearAXObjectCache();
@@ -1953,6 +1953,12 @@
 void Document::prepareForDestruction()
 {
     disconnectDescendantFrames();
+
+    // The process of disconnecting descendant frames could have already
+    // detached us.
+    if (!attached())
+        return;
+
     if (DOMWindow* window = this->domWindow())
         window->willDetachDocumentFromFrame();
     detach();
@@ -2122,7 +2128,7 @@
     // collection update in order to ensure they inherit all the relevant data
     // from their parent.
     if (shouldDisplaySeamlesslyWithParent())
-        styleResolverChanged(DeferRecalcStyle);
+        styleResolverChanged(RecalcStyleDeferred);
 
     m_parser = createParser();
     setParsing(true);
@@ -2163,9 +2169,9 @@
         return;
 
     if (oldBody)
-        documentElement()->replaceChild(newBody.release(), oldBody, es, AttachLazily);
+        documentElement()->replaceChild(newBody.release(), oldBody, es);
     else
-        documentElement()->appendChild(newBody.release(), es, AttachLazily);
+        documentElement()->appendChild(newBody.release(), es);
 }
 
 HTMLHeadElement* Document::head()
@@ -2210,11 +2216,7 @@
 
 void Document::implicitClose()
 {
-    // If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
-    if (m_inStyleRecalc) {
-        m_closeAfterStyleRecalc = true;
-        return;
-    }
+    ASSERT(!inStyleRecalc());
 
     bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
     bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
@@ -2322,6 +2324,95 @@
         accessSVGExtensions()->startAnimations();
 }
 
+bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, Document* navigatingDocument)
+{
+    if (!m_domWindow)
+        return true;
+
+    if (!body())
+        return true;
+
+    RefPtr<Document> protect(this);
+
+    RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
+    m_loadEventProgress = BeforeUnloadEventInProgress;
+    dispatchWindowEvent(beforeUnloadEvent.get(), this);
+    m_loadEventProgress = BeforeUnloadEventCompleted;
+    if (!beforeUnloadEvent->defaultPrevented())
+        defaultEventHandler(beforeUnloadEvent.get());
+    if (beforeUnloadEvent->result().isNull())
+        return true;
+
+    if (navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel) {
+        addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
+        return true;
+    }
+
+    String text = displayStringModifiedByEncoding(beforeUnloadEvent->result());
+    if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
+        navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel = true;
+        return true;
+    }
+    return false;
+}
+
+void Document::dispatchUnloadEvents()
+{
+    RefPtr<Document> protect(this);
+    if (m_parser)
+        m_parser->stopParsing();
+
+    if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
+        Element* currentFocusedElement = focusedElement();
+        if (currentFocusedElement && currentFocusedElement->hasTagName(inputTag))
+            toHTMLInputElement(currentFocusedElement)->endEditing();
+        if (m_loadEventProgress < PageHideInProgress) {
+            m_loadEventProgress = PageHideInProgress;
+            dispatchWindowEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), this);
+            if (!m_frame)
+                return;
+
+            // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
+            // while dispatching the event, so protect it to prevent writing the end
+            // time into freed memory.
+            RefPtr<DocumentLoader> documentLoader =  m_frame->loader()->provisionalDocumentLoader();
+            m_loadEventProgress = UnloadEventInProgress;
+            RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
+            if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
+                DocumentLoadTiming* timing = documentLoader->timing();
+                ASSERT(timing->navigationStart());
+                timing->markUnloadEventStart();
+                dispatchWindowEvent(unloadEvent, this);
+                timing->markUnloadEventEnd();
+            } else {
+                m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
+            }
+        }
+        updateStyleIfNeeded();
+        m_loadEventProgress = UnloadEventHandled;
+    }
+
+    if (!m_frame)
+        return;
+
+    // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
+    bool keepEventListeners = m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader()->provisionalDocumentLoader()
+        && isSecureTransitionTo(m_frame->loader()->provisionalDocumentLoader()->url());
+    if (!keepEventListeners)
+        removeAllEventListeners();
+}
+
+Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
+{
+    if (m_loadEventProgress == BeforeUnloadEventInProgress)
+        return BeforeUnloadDismissal;
+    if (m_loadEventProgress == PageHideInProgress)
+        return PageHideDismissal;
+    if (m_loadEventProgress == UnloadEventInProgress)
+        return UnloadDismissal;
+    return NoDismissal;
+}
+
 void Document::setParsing(bool b)
 {
     m_bParsing = b;
@@ -2424,7 +2515,7 @@
 
 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
 {
-    addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
+    internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
 }
 
 void Document::setURL(const KURL& url)
@@ -2613,6 +2704,7 @@
 
 void Document::seamlessParentUpdatedStylesheets()
 {
+    m_styleSheetCollection->didModifySeamlessParentStyleSheet();
     styleResolverChanged(RecalcStyleImmediately);
 }
 
@@ -2690,7 +2782,7 @@
     // -dwh
     m_styleSheetCollection->setSelectedStylesheetSetName(content);
     m_styleSheetCollection->setPreferredStylesheetSetName(content);
-    styleResolverChanged(DeferRecalcStyle);
+    styleResolverChanged(RecalcStyleDeferred);
 }
 
 void Document::processHttpEquivRefresh(const String& content)
@@ -2751,10 +2843,15 @@
         // intent, we must navigate away from the possibly partially-rendered document to a location that
         // doesn't inherit the parent's SecurityOrigin.
         frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
-        addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
+        addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
     }
 }
 
+static bool isInvalidSeparator(UChar c)
+{
+    return c == ';';
+}
+
 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
 static bool isSeparator(UChar c)
 {
@@ -2763,6 +2860,8 @@
 
 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
 {
+    bool error = false;
+
     // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
     int keyBegin, keyEnd;
     int valueBegin, valueEnd;
@@ -2780,12 +2879,15 @@
         keyBegin = i;
 
         // skip to first separator
-        while (!isSeparator(buffer[i]))
+        while (!isSeparator(buffer[i])) {
+            error |= isInvalidSeparator(buffer[i]);
             i++;
+        }
         keyEnd = i;
 
         // skip to first '=', but don't skip past a ',' or the end of the string
         while (buffer[i] != '=') {
+            error |= isInvalidSeparator(buffer[i]);
             if (buffer[i] == ',' || i >= length)
                 break;
             i++;
@@ -2800,8 +2902,10 @@
         valueBegin = i;
 
         // skip to first separator
-        while (!isSeparator(buffer[i]))
+        while (!isSeparator(buffer[i])) {
+            error |= isInvalidSeparator(buffer[i]);
             i++;
+        }
         valueEnd = i;
 
         ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
@@ -2810,6 +2914,8 @@
         String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
         callback(keyString, valueString, this, data);
     }
+    if (error)
+        reportViewportWarning(this, InvalidKeyValuePairSeparatorError, String(), String());
 }
 
 void Document::processViewport(const String& features, ViewportArguments::Type origin)
@@ -2982,31 +3088,11 @@
     return true;
 }
 
-PassRefPtr<Node> Document::cloneNode(bool deep)
+PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
 {
-    RefPtr<Document> clone = cloneDocumentWithoutChildren();
-    clone->cloneDataFromDocument(*this);
-    if (deep)
-        cloneChildNodes(clone.get());
-    return clone.release();
-}
-
-PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
-{
-    return create();
-}
-
-void Document::cloneDataFromDocument(const Document& other)
-{
-    m_url = other.url();
-    m_baseURL = other.baseURL();
-    m_baseURLOverride = other.baseURLOverride();
-    m_documentURI = other.documentURI();
-
-    setCompatibilityMode(other.compatibilityMode());
-    setContextFeatures(other.contextFeatures());
-    setSecurityOrigin(other.securityOrigin());
-    setDecoder(other.decoder());
+    // Spec says cloning Document nodes is "implementation dependent"
+    // so we do not support it...
+    return 0;
 }
 
 StyleSheetList* Document::styleSheets()
@@ -3029,7 +3115,7 @@
 void Document::setSelectedStylesheetSet(const String& aString)
 {
     m_styleSheetCollection->setSelectedStylesheetSetName(aString);
-    styleResolverChanged(DeferRecalcStyle);
+    styleResolverChanged(RecalcStyleDeferred);
 }
 
 void Document::evaluateMediaQueryList()
@@ -3050,7 +3136,7 @@
 
     bool needsRecalc = m_styleSheetCollection->updateActiveStyleSheets(updateMode);
 
-    if (updateType >= DeferRecalcStyle) {
+    if (updateType >= RecalcStyleDeferred) {
         setNeedsStyleRecalc();
         return;
     }
@@ -3276,7 +3362,7 @@
         m_focusedElement->setFocus(true);
 
         if (m_focusedElement->isRootEditableElement())
-            frame()->editor()->didBeginEditing();
+            frame()->editor()->didBeginEditing(m_focusedElement.get());
 
         // eww, I suck. set the qt focus correctly
         // ### find a better place in the code for this
@@ -3571,7 +3657,7 @@
 
 String Document::cookie(ExceptionState& es) const
 {
-    if (page() && !page()->settings()->cookieEnabled())
+    if (page() && !page()->settings().cookieEnabled())
         return String();
 
     // FIXME: The HTML5 DOM spec states that this attribute can raise an
@@ -3579,7 +3665,13 @@
     // browsing context.
 
     if (!securityOrigin()->canAccessCookies()) {
-        es.throwDOMException(SecurityError);
+        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.");
+        else if (url().protocolIs("data"))
+            es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+        else
+            es.throwSecurityError(accessDeniedMessage);
         return String();
     }
 
@@ -3592,7 +3684,7 @@
 
 void Document::setCookie(const String& value, ExceptionState& es)
 {
-    if (page() && !page()->settings()->cookieEnabled())
+    if (page() && !page()->settings().cookieEnabled())
         return;
 
     // FIXME: The HTML5 DOM spec states that this attribute can raise an
@@ -3600,7 +3692,13 @@
     // browsing context.
 
     if (!securityOrigin()->canAccessCookies()) {
-        es.throwDOMException(SecurityError);
+        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.");
+        else if (url().protocolIs("data"))
+            es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+        else
+            es.throwSecurityError(accessDeniedMessage);
         return;
     }
 
@@ -3613,8 +3711,8 @@
 
 String Document::referrer() const
 {
-    if (frame())
-        return frame()->loader()->referrer();
+    if (loader())
+        return loader()->request().httpReferrer();
     return String();
 }
 
@@ -3626,7 +3724,7 @@
 void Document::setDomain(const String& newDomain, ExceptionState& es)
 {
     if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
-        es.throwDOMException(SecurityError, "'document.domain' assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
+        es.throwSecurityError(ExceptionMessages::failedToSet("domain", "Document", "assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme."));
         return;
     }
 
@@ -3648,17 +3746,17 @@
 
     int oldLength = domain().length();
     int newLength = newDomain.length();
-    String exceptionMessage =  "'document.domain' assignment failed: '" + newDomain + "' is not a suffix of '" + domain() + "'.";
+    String exceptionMessage =  ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is not a suffix of '" + domain() + "'.");
     // e.g. newDomain = subdomain.www.example.com (25) and domain() = www.example.com (15)
     if (newLength >= oldLength) {
-        es.throwDOMException(SecurityError, exceptionMessage);
+        es.throwSecurityError(exceptionMessage);
         return;
     }
 
     String test = domain();
     // Check that it's a complete suffix, not e.g. "ample.com"
     if (test[oldLength - newLength - 1] != '.') {
-        es.throwDOMException(SecurityError, exceptionMessage);
+        es.throwSecurityError(exceptionMessage);
         return;
     }
 
@@ -3666,7 +3764,7 @@
     // and we check that it's the same thing as newDomain
     test.remove(0, oldLength - newLength);
     if (test != newDomain) {
-        es.throwDOMException(SecurityError, exceptionMessage);
+        es.throwSecurityError(exceptionMessage);
         return;
     }
 
@@ -4447,18 +4545,34 @@
     m_haveExplicitlyDisabledDNSPrefetch = true;
 }
 
-void Document::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
+void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
 {
-    if (!isContextThread()) {
-        postTask(AddConsoleMessageTask::create(source, level, message));
-        return;
-    }
-
-    if (Page* page = this->page())
-        page->console()->addMessage(source, level, message, requestIdentifier, this);
+    internalAddMessage(source, level, message, sourceURL, lineNumber, 0, state);
 }
 
-void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
+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));
+        return;
+    }
+    Page* page = this->page();
+    if (!page)
+        return;
+
+    String messageURL = sourceURL;
+    if (!state && sourceURL.isNull() && !lineNumber) {
+        messageURL = url().string();
+        if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
+            ScriptableDocumentParser* parser = scriptableDocumentParser();
+            if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
+                lineNumber = parser->lineNumber().oneBasedInt();
+        }
+    }
+    page->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, state, 0);
+}
+
+void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
 {
     if (!isContextThread()) {
         postTask(AddConsoleMessageTask::create(source, level, message));
@@ -4466,7 +4580,7 @@
     }
 
     if (Page* page = this->page())
-        page->console()->addMessage(source, level, message, sourceURL, lineNumber, 0, callStack, state, requestIdentifier);
+        page->console().addMessage(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
 }
 
 struct PerformTaskContext {
@@ -4632,18 +4746,18 @@
 {
     if (!page())
         return;
-    if (Element* target = page()->pointerLockController()->element()) {
+    if (Element* target = page()->pointerLockController().element()) {
         if (target->document() != this)
             return;
     }
-    page()->pointerLockController()->requestPointerUnlock();
+    page()->pointerLockController().requestPointerUnlock();
 }
 
 Element* Document::webkitPointerLockElement() const
 {
-    if (!page() || page()->pointerLockController()->lockPending())
+    if (!page() || page()->pointerLockController().lockPending())
         return 0;
-    if (Element* element = page()->pointerLockController()->element()) {
+    if (Element* element = page()->pointerLockController().element()) {
         if (element->document() == this)
             return element;
     }
@@ -4752,7 +4866,7 @@
         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
             scrollingCoordinator->touchEventTargetRectsDidChange(this);
         if (m_touchEventTargets->size() == 1)
-            page->chrome().client()->needTouchEvents(true);
+            page->chrome().client().needTouchEvents(true);
     }
 }
 
@@ -4760,7 +4874,9 @@
 {
     if (!m_touchEventTargets.get())
         return;
-    ASSERT(m_touchEventTargets->contains(handler));
+    // TODO(rbyers): Re-enable this ASSERT - http://crbug.com/254203.
+    // The known failure is benign, but the fix somehow causes a perf regression.
+    // ASSERT(m_touchEventTargets->contains(handler));
     m_touchEventTargets->remove(handler);
     if (Document* parent = parentDocument()) {
         parent->didRemoveTouchEventHandler(this);
@@ -4778,17 +4894,14 @@
         if (frame->document() && frame->document()->hasTouchEventHandlers())
             return;
     }
-    page->chrome().client()->needTouchEvents(false);
+    page->chrome().client().needTouchEvents(false);
 }
 
 void Document::didRemoveEventTargetNode(Node* handler)
 {
     if (m_touchEventTargets) {
-        if (handler == this)
-            m_touchEventTargets->clear();
-        else
-            m_touchEventTargets->removeAll(handler);
-        if (m_touchEventTargets->isEmpty() && parentDocument())
+        m_touchEventTargets->removeAll(handler);
+        if ((handler == this || m_touchEventTargets->isEmpty()) && parentDocument())
             parentDocument()->didRemoveEventTargetNode(this);
     }
 }
@@ -5121,7 +5234,7 @@
     Vector<RefPtr<Element> > associatedFormControls;
     copyToVector(m_associatedFormControls, associatedFormControls);
 
-    frame()->page()->chrome().client()->didAssociateFormControls(associatedFormControls);
+    frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
     m_associatedFormControls.clear();
 }
 
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index cd90543..f0145de 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -30,6 +30,7 @@
 
 #include "bindings/v8/ScriptValue.h"
 #include "core/dom/ContainerNode.h"
+#include "core/dom/CustomElement.h"
 #include "core/dom/DOMTimeStamp.h"
 #include "core/dom/DocumentEventQueue.h"
 #include "core/dom/DocumentInit.h"
@@ -67,6 +68,7 @@
 class ScriptResource;
 class CanvasRenderingContext;
 class CharacterData;
+class Chrome;
 class Comment;
 class ContentSecurityPolicyResponseHeaders;
 class ContextFeatures;
@@ -168,9 +170,7 @@
     PageshowEventPersisted = 1
 };
 
-// FIXME: We should rename DeferRecalcStyle to RecalcStyleDeferred to be consitent.
-
-enum StyleResolverUpdateType { RecalcStyleImmediately, DeferRecalcStyle };
+enum StyleResolverUpdateType { RecalcStyleImmediately, RecalcStyleDeferred };
 
 enum StyleResolverUpdateMode {
     // Discards the StyleResolver and rebuilds it.
@@ -259,6 +259,7 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
@@ -448,9 +449,9 @@
 
     // FIXME: Switch all callers of styleResolverChanged to these or better ones and then make them
     // do something smarter.
-    void removedStyleSheet(StyleSheet*, StyleResolverUpdateType type = DeferRecalcStyle) { styleResolverChanged(type); }
-    void addedStyleSheet(StyleSheet*, StyleResolverUpdateType type = DeferRecalcStyle) { styleResolverChanged(type); }
-    void modifiedStyleSheet(StyleSheet*, StyleResolverUpdateType type = DeferRecalcStyle) { styleResolverChanged(type); }
+    void removedStyleSheet(StyleSheet*, StyleResolverUpdateType type = RecalcStyleDeferred) { styleResolverChanged(type); }
+    void addedStyleSheet(StyleSheet*, StyleResolverUpdateType type = RecalcStyleDeferred) { styleResolverChanged(type); }
+    void modifiedStyleSheet(StyleSheet*, StyleResolverUpdateType type = RecalcStyleDeferred) { styleResolverChanged(type); }
 
     void didAccessStyleResolver();
 
@@ -545,6 +546,17 @@
     // implicitClose() actually does the work of closing the input stream.
     void implicitClose();
 
+    bool dispatchBeforeUnloadEvent(Chrome&, Document* navigatingDocument);
+    void dispatchUnloadEvents();
+
+    enum PageDismissalType {
+        NoDismissal = 0,
+        BeforeUnloadDismissal = 1,
+        PageHideDismissal = 2,
+        UnloadDismissal = 3
+    };
+    PageDismissalType pageDismissalEventBeingDispatched() const;
+
     void cancelParsing();
 
     void write(const SegmentedString& text, Document* ownerDocument = 0);
@@ -754,6 +766,8 @@
     String title() const { return m_title.string(); }
     void setTitle(const String&);
 
+    const StringWithDirection& titleWithDirection() const { return m_title; }
+
     Element* titleElement() const { return m_titleElement.get(); }
     void setTitleElement(const StringWithDirection&, Element* titleElement);
     void removeTitle(Element* titleElement);
@@ -914,15 +928,15 @@
         LoadEventTried,
         LoadEventInProgress,
         LoadEventCompleted,
+        BeforeUnloadEventInProgress,
+        BeforeUnloadEventCompleted,
+        PageHideInProgress,
         UnloadEventInProgress,
         UnloadEventHandled
     };
     bool loadEventStillNeeded() const { return m_loadEventProgress == LoadEventNotRun; }
     bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
     bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
-    bool unloadEventStillNeeded() const { return m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress; }
-    void unloadEventStarted() { m_loadEventProgress = UnloadEventInProgress; }
-    void unloadEventWasHandled() { m_loadEventProgress = UnloadEventHandled; }
 
     virtual bool isContextThread() const;
     virtual bool isJSExecutionForbidden() const { return false; }
@@ -994,7 +1008,8 @@
     PassRefPtr<Element> createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState&);
     PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
     ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, ExceptionState&);
-    ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&);
+    // FIXME: When embedders switch to using WebDocument::registerEmbedderCustomElement, make the default name set StandardNames.
+    ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&, CustomElement::NameSet validNames = CustomElement::AllNames);
     CustomElementRegistrationContext* registrationContext() { return m_registrationContext.get(); }
 
     void setImport(HTMLImport*);
@@ -1011,7 +1026,7 @@
     void decrementActiveParserCount();
 
     void setContextFeatures(PassRefPtr<ContextFeatures>);
-    ContextFeatures* contextFeatures() const { return m_contextFeatures.get(); }
+    ContextFeatures* contextFeatures() { return m_contextFeatures.get(); }
 
     DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
 
@@ -1039,7 +1054,7 @@
 
     void didAssociateFormControl(Element*);
 
-    virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0);
+    void addConsoleMessageWithRequestIdentifier(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier);
 
     virtual DOMWindow* executingWindow() OVERRIDE { return domWindow(); }
     virtual void userEventWasHandled() OVERRIDE { resetLastHandledUserGestureTimestamp(); }
@@ -1062,8 +1077,6 @@
 
     virtual void dispose() OVERRIDE;
 
-    virtual PassRefPtr<Document> cloneDocumentWithoutChildren();
-
 private:
     friend class Node;
     friend class IgnoreDestructiveWriteCountIncrementer;
@@ -1083,7 +1096,6 @@
     virtual NodeType nodeType() const;
     virtual bool childTypeAllowed(NodeType) const;
     virtual PassRefPtr<Node> cloneNode(bool deep = true);
-    void cloneDataFromDocument(const Document&);
 
     virtual void refScriptExecutionContext() { ref(); }
     virtual void derefScriptExecutionContext() { deref(); }
@@ -1092,7 +1104,8 @@
     virtual const KURL& virtualURL() const; // Same as url(), but needed for ScriptExecutionContext to implement it without a performance loss for direct calls.
     virtual KURL virtualCompleteURL(const String&) const; // Same as completeURL() for the same reason as above.
 
-    virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState* = 0, unsigned long requestIdentifier = 0);
+    virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*);
+    void internalAddMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
 
     virtual double timerAlignmentInterval() const;
 
@@ -1226,7 +1239,6 @@
 
     Timer<Document> m_styleRecalcTimer;
     bool m_inStyleRecalc;
-    bool m_closeAfterStyleRecalc;
 
     bool m_gotoAnchorNeededAfterStylesheetsLoad;
     bool m_isDNSPrefetchEnabled;
@@ -1317,6 +1329,8 @@
     bool m_directionSetOnDocumentElement;
     bool m_writingModeSetOnDocumentElement;
 
+    bool m_didAllowNavigationViaBeforeUnloadConfirmationPanel;
+
     DocumentTiming m_documentTiming;
     RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
     bool m_writeRecursionIsTooDeep;
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index 0fc91ba..bea2b66 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -33,10 +33,10 @@
     DocumentFragment   createDocumentFragment();
     [PerWorldBindings] Text createTextNode([Default=Undefined] optional DOMString data);
     Comment createComment([Default=Undefined] optional DOMString data);
-    [RaisesException] CDATASection createCDATASection([Default=Undefined] optional DOMString data);
+    [RaisesException, MeasureAs=DocumentCreateCDATASection] CDATASection createCDATASection([Default=Undefined] optional DOMString data); // Removed from DOM4.
     [RaisesException] ProcessingInstruction createProcessingInstruction([Default=Undefined] optional DOMString target,
                                                                                  [Default=Undefined] optional DOMString data);
-    [RaisesException] Attr createAttribute([Default=Undefined] optional DOMString name);
+    [RaisesException, MeasureAs=DocumentCreateAttribute] Attr createAttribute([Default=Undefined] optional DOMString name); // Removed from DOM4.
     [PerWorldBindings] NodeList           getElementsByTagName([Default=Undefined] optional DOMString tagname);
 
     // Introduced in DOM Level 2:
@@ -45,19 +45,19 @@
                     optional boolean deep);
     [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                             [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName);
-    [RaisesException] Attr createAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                                                          [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName);
+    [RaisesException, MeasureAs=DocumentCreateAttributeNS] Attr createAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+                                                                                  [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName); // Removed from DOM4.
      NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                    [Default=Undefined] optional DOMString localName);
     [PerWorldBindings] Element            getElementById([Default=Undefined] optional DOMString elementId);
 
     // DOM Level 3 Core
 
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString inputEncoding;
+    [TreatReturnedNullStringAs=Null, MeasureAs=DocumentInputEncoding] readonly attribute DOMString inputEncoding; // Removed from DOM4.
 
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString xmlEncoding;
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString xmlVersion;
-             [SetterRaisesException] attribute boolean xmlStandalone;
+    [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.
 
     [RaisesException, CustomElementCallbacks=Enable] Node               adoptNode([Default=Undefined] optional Node source);
 
@@ -133,9 +133,8 @@
     [Custom, Replaceable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] readonly attribute Location location;
 
     // IE extensions
-
-             [TreatReturnedNullStringAs=Undefined, TreatNullAs=NullString] attribute DOMString charset;
-    [TreatReturnedNullStringAs=Undefined] readonly attribute DOMString defaultCharset;
+    [MeasureAs=DocumentCharset, TreatReturnedNullStringAs=Undefined, TreatNullAs=NullString] attribute DOMString charset;
+    [MeasureAs=DocumentCharset, TreatReturnedNullStringAs=Undefined] readonly attribute DOMString defaultCharset;
     [TreatReturnedNullStringAs=Undefined] readonly attribute DOMString readyState;
 
     Element            elementFromPoint([Default=Undefined] optional long x,
@@ -199,7 +198,8 @@
     [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
     [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
     [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel; // Deprecated in favor of onwheel.
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onwheel;
     [NotEnumerable] attribute EventHandler onreadystatechange;
     [NotEnumerable] attribute EventHandler onscroll;
     [NotEnumerable] attribute EventHandler onselect;
@@ -261,8 +261,8 @@
                                                [Default=Undefined] optional float webkitForce);
     [EnabledAtRuntime=touch, Custom, RaisesException] TouchList createTouchList();
 
-    [DeprecateAs=PrefixedDocumentRegister, EnabledAtRuntime=customDOMElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
-    [EnabledAtRuntime=customDOMElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
+    [DeprecateAs=PrefixedDocumentRegister, EnabledAtRuntime=customElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
+    [EnabledAtRuntime=customElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
     [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
     [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
                             [TreatNullAs=NullString] DOMString typeExtension);
diff --git a/Source/core/dom/DocumentInit.cpp b/Source/core/dom/DocumentInit.cpp
index 8c508d4..caa4f8f 100644
--- a/Source/core/dom/DocumentInit.cpp
+++ b/Source/core/dom/DocumentInit.cpp
@@ -88,7 +88,7 @@
 
 PassRefPtr<CustomElementRegistrationContext> DocumentInit::registrationContext(Document* document) const
 {
-    if (!RuntimeEnabledFeatures::customDOMElementsEnabled())
+    if (!RuntimeEnabledFeatures::customElementsEnabled() && !RuntimeEnabledFeatures::embedderCustomElementsEnabled())
         return 0;
 
     if (!document->isHTMLDocument() && !document->isXHTMLDocument())
diff --git a/Source/core/dom/DocumentMarkerController.cpp b/Source/core/dom/DocumentMarkerController.cpp
index c47e8b8..168772b 100644
--- a/Source/core/dom/DocumentMarkerController.cpp
+++ b/Source/core/dom/DocumentMarkerController.cpp
@@ -160,7 +160,7 @@
             DocumentMarker marker = list->at(i);
             if (marker.startOffset() > toInsert.startOffset())
                 break;
-            if (marker.type() == toInsert.type() && marker.endOffset() >= toInsert.startOffset()) {
+            if (marker.type() == toInsert.type() && marker.type() != DocumentMarker::TextMatch && marker.endOffset() >= toInsert.startOffset()) {
                 toInsert.setStartOffset(marker.startOffset());
                 list->remove(i);
                 numMarkers--;
@@ -175,7 +175,7 @@
             DocumentMarker marker = list->at(j);
             if (marker.startOffset() > toInsert.endOffset())
                 break;
-            if (marker.type() == toInsert.type()) {
+            if (marker.type() == toInsert.type() && marker.type() != DocumentMarker::TextMatch) {
                 list->remove(j);
                 if (toInsert.endOffset() <= marker.endOffset()) {
                     toInsert.setEndOffset(marker.endOffset());
@@ -608,7 +608,7 @@
             break;
 
         // Skip marker that is wrong type or before target.
-        if (marker.endOffset() < startOffset || marker.type() != DocumentMarker::TextMatch)
+        if (marker.endOffset() <= startOffset || marker.type() != DocumentMarker::TextMatch)
             continue;
 
         marker.setActiveMatch(active);
diff --git a/Source/core/dom/DocumentOrderedMap.cpp b/Source/core/dom/DocumentOrderedMap.cpp
index ee4c389..bd58170 100644
--- a/Source/core/dom/DocumentOrderedMap.cpp
+++ b/Source/core/dom/DocumentOrderedMap.cpp
@@ -33,11 +33,10 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Element.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/TreeScope.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLMapElement.h"
-#include "core/html/HTMLNameCollection.h"
 
 namespace WebCore {
 
@@ -48,11 +47,6 @@
     return element->getIdAttribute().impl() == key;
 }
 
-inline bool keyMatchesName(StringImpl* key, Element* element)
-{
-    return element->getNameAttribute().impl() == key;
-}
-
 inline bool keyMatchesMapName(StringImpl* key, Element* element)
 {
     return element->hasTagName(mapTag) && toHTMLMapElement(element)->getName().impl() == key;
@@ -71,6 +65,7 @@
 void DocumentOrderedMap::clear()
 {
     m_map.clear();
+    m_duplicateCounts.clear();
 }
 
 void DocumentOrderedMap::add(StringImpl* key, Element* element)
@@ -78,15 +73,29 @@
     ASSERT(key);
     ASSERT(element);
 
-    Map::AddResult addResult = m_map.add(key, MapEntry(element));
-    if (addResult.isNewEntry)
-        return;
+    if (!m_duplicateCounts.contains(key)) {
+        // Fast path. The key is not already in m_duplicateCounts, so we assume that it's
+        // also not already in m_map and try to add it. If that add succeeds, we're done.
+        Map::AddResult addResult = m_map.add(key, element);
+        if (addResult.isNewEntry)
+            return;
 
-    MapEntry& entry = addResult.iterator->value;
-    ASSERT(entry.count);
-    entry.element = 0;
-    entry.count++;
-    entry.orderedList.clear();
+        // The add failed, so this key was already cached in m_map.
+        // There are multiple elements with this key. Remove the m_map
+        // cache for this key so get searches for it next time it is called.
+        m_map.remove(addResult.iterator);
+        m_duplicateCounts.add(key);
+    } else {
+        // There are multiple elements with this key. Remove the m_map
+        // cache for this key so get will search for it next time it is called.
+        Map::iterator cachedItem = m_map.find(key);
+        if (cachedItem != m_map.end()) {
+            m_map.remove(cachedItem);
+            m_duplicateCounts.add(key);
+        }
+    }
+
+    m_duplicateCounts.add(key);
 }
 
 void DocumentOrderedMap::remove(StringImpl* key, Element* element)
@@ -94,20 +103,11 @@
     ASSERT(key);
     ASSERT(element);
 
-    Map::iterator it = m_map.find(key);
-    ASSERT(it != m_map.end());
-    MapEntry& entry = it->value;
-
-    ASSERT(entry.count);
-    if (entry.count == 1) {
-        ASSERT(!entry.element || entry.element == element);
-        m_map.remove(it);
-    } else {
-        if (entry.element == element)
-            entry.element = 0;
-        entry.count--;
-        entry.orderedList.clear(); // FIXME: Remove the element instead if there are only few items left.
-    }
+    Map::iterator cachedItem = m_map.find(key);
+    if (cachedItem != m_map.end() && cachedItem->value == element)
+        m_map.remove(cachedItem);
+    else
+        m_duplicateCounts.remove(key);
 }
 
 template<bool keyMatches(StringImpl*, Element*)>
@@ -116,23 +116,22 @@
     ASSERT(key);
     ASSERT(scope);
 
-    Map::iterator it = m_map.find(key);
-    if (it == m_map.end())
-        return 0;
-
-    MapEntry& entry = it->value;
-    ASSERT(entry.count);
-    if (entry.element)
-        return entry.element;
-
-    // We know there's at least one node that matches; iterate to find the first one.
-    for (Element* element = ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(element)) {
-        if (!keyMatches(key, element))
-            continue;
-        entry.element = element;
+    Element* element = m_map.get(key);
+    if (element)
         return element;
+
+    if (m_duplicateCounts.contains(key)) {
+        // We know there's at least one node that matches; iterate to find the first one.
+        for (element = ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(element)) {
+            if (!keyMatches(key, element))
+                continue;
+            m_duplicateCounts.remove(key);
+            m_map.set(key, element);
+            return element;
+        }
+        ASSERT_NOT_REACHED();
     }
-    ASSERT_NOT_REACHED();
+
     return 0;
 }
 
@@ -141,11 +140,6 @@
     return get<keyMatchesId>(key, scope);
 }
 
-Element* DocumentOrderedMap::getElementByName(StringImpl* key, const TreeScope* scope) const
-{
-    return get<keyMatchesName>(key, scope);
-}
-
 Element* DocumentOrderedMap::getElementByMapName(StringImpl* key, const TreeScope* scope) const
 {
     return get<keyMatchesMapName>(key, scope);
@@ -161,31 +155,4 @@
     return get<keyMatchesLabelForAttribute>(key, scope);
 }
 
-const Vector<Element*>* DocumentOrderedMap::getAllElementsById(StringImpl* key, const TreeScope* scope) const
-{
-    ASSERT(key);
-    ASSERT(scope);
-
-    Map::iterator it = m_map.find(key);
-    if (it == m_map.end())
-        return 0;
-
-    MapEntry& entry = it->value;
-    ASSERT(entry.count);
-    if (!entry.count)
-        return 0;
-
-    if (entry.orderedList.isEmpty()) {
-        entry.orderedList.reserveCapacity(entry.count);
-        for (Element* element = entry.element ? entry.element : ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(element)) {
-            if (!keyMatchesId(key, element))
-                continue;
-            entry.orderedList.append(element);
-        }
-        ASSERT(entry.orderedList.size() == entry.count);
-    }
-
-    return &entry.orderedList;
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentOrderedMap.h b/Source/core/dom/DocumentOrderedMap.h
index a86caf0..b6fc8e0 100644
--- a/Source/core/dom/DocumentOrderedMap.h
+++ b/Source/core/dom/DocumentOrderedMap.h
@@ -33,7 +33,6 @@
 
 #include "wtf/HashCountedSet.h"
 #include "wtf/HashMap.h"
-#include "wtf/Vector.h"
 #include "wtf/text/StringImpl.h"
 
 namespace WebCore {
@@ -48,60 +47,35 @@
     void clear();
 
     bool contains(StringImpl*) const;
-    bool containsSingle(StringImpl*) const;
     bool containsMultiple(StringImpl*) const;
-
     // concrete instantiations of the get<>() method template
     Element* getElementById(StringImpl*, const TreeScope*) const;
-    Element* getElementByName(StringImpl*, const TreeScope*) const;
     Element* getElementByMapName(StringImpl*, const TreeScope*) const;
     Element* getElementByLowercasedMapName(StringImpl*, const TreeScope*) const;
     Element* getElementByLabelForAttribute(StringImpl*, const TreeScope*) const;
 
-    const Vector<Element*>* getAllElementsById(StringImpl*, const TreeScope*) const;
-
     void checkConsistency() const;
 
 private:
     template<bool keyMatches(StringImpl*, Element*)> Element* get(StringImpl*, const TreeScope*) const;
 
-    struct MapEntry {
-        MapEntry()
-            : element(0)
-            , count(0)
-        {
-        }
-        explicit MapEntry(Element* firstElement)
-            : element(firstElement)
-            , count(1)
-        {
-        }
+    typedef HashMap<StringImpl*, Element*> Map;
 
-        Element* element;
-        unsigned count;
-        Vector<Element*> orderedList;
-    };
-
-    typedef HashMap<StringImpl*, MapEntry> Map;
-
+    // We maintain the invariant that m_duplicateCounts is the count of all elements with a given key
+    // excluding the one referenced in m_map, if any. This means it one less than the total count
+    // when the first node with a given key is cached, otherwise the same as the total count.
     mutable Map m_map;
+    mutable HashCountedSet<StringImpl*> m_duplicateCounts;
 };
 
-inline bool DocumentOrderedMap::containsSingle(StringImpl* id) const
-{
-    Map::const_iterator it = m_map.find(id);
-    return it != m_map.end() && it->value.count == 1;
-}
-
 inline bool DocumentOrderedMap::contains(StringImpl* id) const
 {
-    return m_map.contains(id);
+    return m_map.contains(id) || m_duplicateCounts.contains(id);
 }
 
 inline bool DocumentOrderedMap::containsMultiple(StringImpl* id) const
 {
-    Map::const_iterator it = m_map.find(id);
-    return it != m_map.end() && it->value.count > 1;
+    return m_duplicateCounts.contains(id);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index 74ef2b1..bbcbe43 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -37,6 +37,8 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
+#include "core/dom/ShadowTreeStyleSheetCollection.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
@@ -63,6 +65,7 @@
     , m_usesBeforeAfterRulesOverride(false)
     , m_usesRemUnits(false)
     , m_collectionForDocument(document)
+    , m_needsDocumentStyleSheetsUpdate(true)
 {
 }
 
@@ -80,6 +83,55 @@
         m_authorStyleSheets[i]->clearOwnerNode();
 }
 
+void DocumentStyleSheetCollection::insertTreeScopeInDocumentOrder(TreeScopeSet& treeScopes, TreeScope* treeScope)
+{
+    if (treeScopes.isEmpty()) {
+        treeScopes.add(treeScope);
+        return;
+    }
+    if (treeScopes.contains(treeScope))
+        return;
+
+    TreeScopeSet::iterator begin = treeScopes.begin();
+    TreeScopeSet::iterator end = treeScopes.end();
+    TreeScopeSet::iterator it = end;
+    TreeScope* followingTreeScope = 0;
+    do {
+        --it;
+        TreeScope* n = *it;
+        unsigned short position = n->comparePosition(treeScope);
+        if (position & Node::DOCUMENT_POSITION_FOLLOWING) {
+            treeScopes.insertBefore(followingTreeScope, treeScope);
+            return;
+        }
+        followingTreeScope = n;
+    } while (it != begin);
+
+    treeScopes.insertBefore(followingTreeScope, treeScope);
+}
+
+StyleSheetCollection* DocumentStyleSheetCollection::ensureStyleSheetCollectionFor(TreeScope* treeScope)
+{
+    if (treeScope == m_document)
+        return &m_collectionForDocument;
+
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(treeScope, nullptr);
+    if (result.isNewEntry)
+        result.iterator->value = adoptPtr(new ShadowTreeStyleSheetCollection(toShadowRoot(treeScope)));
+    return result.iterator->value.get();
+}
+
+StyleSheetCollection* DocumentStyleSheetCollection::styleSheetCollectionFor(TreeScope* treeScope)
+{
+    if (treeScope == m_document)
+        return &m_collectionForDocument;
+
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(treeScope);
+    if (it == m_styleSheetCollectionMap.end())
+        return 0;
+    return it->value.get();
+}
+
 const Vector<RefPtr<StyleSheet> >& DocumentStyleSheetCollection::styleSheetsForStyleSheetList()
 {
     return m_collectionForDocument.styleSheetsForStyleSheetList();
@@ -90,6 +142,19 @@
     return m_collectionForDocument.activeAuthorStyleSheets();
 }
 
+void DocumentStyleSheetCollection::getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const
+{
+    activeAuthorStyleSheets.append(&m_collectionForDocument.activeAuthorStyleSheets());
+
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::const_iterator::Values begin = m_styleSheetCollectionMap.values().begin();
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::const_iterator::Values end = m_styleSheetCollectionMap.values().end();
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::const_iterator::Values it = begin;
+    for (; it != end; ++it) {
+        const StyleSheetCollection* collection = it->get();
+        activeAuthorStyleSheets.append(&collection->activeAuthorStyleSheets());
+    }
+}
+
 void DocumentStyleSheetCollection::combineCSSFeatureFlags(const RuleFeatureSet& features)
 {
     // Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
@@ -188,9 +253,10 @@
 void DocumentStyleSheetCollection::invalidateInjectedStyleSheetCache()
 {
     m_injectedStyleSheetCacheValid = false;
+    m_needsDocumentStyleSheetsUpdate = true;
     // FIXME: updateInjectedStyleSheetCache is called inside StyleSheetCollection::updateActiveStyleSheets
     // and batch updates lots of sheets so we can't call addedStyleSheet() or removedStyleSheet().
-    m_document->styleResolverChanged(DeferRecalcStyle);
+    m_document->styleResolverChanged(RecalcStyleDeferred);
 }
 
 void DocumentStyleSheetCollection::addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet)
@@ -198,6 +264,7 @@
     ASSERT(!authorSheet->isUserStyleSheet());
     m_authorStyleSheets.append(CSSStyleSheet::create(authorSheet, m_document));
     m_document->addedStyleSheet(m_authorStyleSheets.last().get(), RecalcStyleImmediately);
+    m_needsDocumentStyleSheetsUpdate = true;
 }
 
 void DocumentStyleSheetCollection::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
@@ -205,16 +272,23 @@
     ASSERT(userSheet->isUserStyleSheet());
     m_userStyleSheets.append(CSSStyleSheet::create(userSheet, m_document));
     m_document->addedStyleSheet(m_userStyleSheets.last().get(), RecalcStyleImmediately);
+    m_needsDocumentStyleSheetsUpdate = true;
 }
 
 // This method is called whenever a top-level stylesheet has finished loading.
-void DocumentStyleSheetCollection::removePendingSheet(RemovePendingSheetNotificationType notification)
+void DocumentStyleSheetCollection::removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType notification)
 {
     // Make sure we knew this sheet was pending, and that our count isn't out of sync.
     ASSERT(m_pendingStylesheets > 0);
 
     m_pendingStylesheets--;
 
+    TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? styleSheetCandidateNode->treeScope() : m_document;
+    if (treeScope == m_document)
+        m_needsDocumentStyleSheetsUpdate = true;
+    else
+        m_dirtyTreeScopes.add(treeScope);
+
     if (m_pendingStylesheets)
         return;
 
@@ -230,21 +304,59 @@
 
 void DocumentStyleSheetCollection::addStyleSheetCandidateNode(Node* node, bool createdByParser)
 {
-    m_collectionForDocument.addStyleSheetCandidateNode(node, createdByParser);
+    if (!node->inDocument())
+        return;
+
+    TreeScope* treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
+    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+
+    StyleSheetCollection* collection = ensureStyleSheetCollectionFor(treeScope);
+    ASSERT(collection);
+    collection->addStyleSheetCandidateNode(node, createdByParser);
+
+    if (treeScope == m_document) {
+        m_needsDocumentStyleSheetsUpdate = true;
+        return;
+    }
+
+    insertTreeScopeInDocumentOrder(m_activeTreeScopes, treeScope);
+    m_dirtyTreeScopes.add(treeScope);
 }
 
 void DocumentStyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
 {
-    m_collectionForDocument.removeStyleSheetCandidateNode(node, scopingNode);
+    TreeScope* treeScope = scopingNode ? scopingNode->treeScope() : m_document;
+    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+
+    StyleSheetCollection* collection = styleSheetCollectionFor(treeScope);
+    ASSERT(collection);
+    collection->removeStyleSheetCandidateNode(node, scopingNode);
+
+    if (treeScope == m_document) {
+        m_needsDocumentStyleSheetsUpdate = true;
+        return;
+    }
+    m_dirtyTreeScopes.add(treeScope);
+    m_activeTreeScopes.remove(treeScope);
 }
 
-static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets)
+void DocumentStyleSheetCollection::modifiedStyleSheetCandidateNode(Node* node)
 {
-    for (unsigned i = 0; i < sheets.size(); ++i) {
-        if (sheets[i]->contents()->usesRemUnits())
-            return true;
+    if (!node->inDocument())
+        return;
+
+    TreeScope* treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
+    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+    if (treeScope == m_document) {
+        m_needsDocumentStyleSheetsUpdate = true;
+        return;
     }
-    return false;
+    m_dirtyTreeScopes.add(treeScope);
+}
+
+bool DocumentStyleSheetCollection::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode updateMode)
+{
+    return !m_dirtyTreeScopes.isEmpty() || updateMode == FullStyleUpdate;
 }
 
 bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
@@ -260,18 +372,91 @@
     if (!m_document->renderer() || !m_document->attached())
         return false;
 
-    StyleSheetCollection::StyleResolverUpdateType styleResolverUpdateType;
-    bool requiresFullStyleRecalc = m_collectionForDocument.updateActiveStyleSheets(this, updateMode, styleResolverUpdateType);
+    bool requiresFullStyleRecalc = false;
+    if (m_needsDocumentStyleSheetsUpdate || updateMode == FullStyleUpdate)
+        requiresFullStyleRecalc = m_collectionForDocument.updateActiveStyleSheets(this, updateMode);
+
+    if (shouldUpdateShadowTreeStyleSheetCollection(updateMode)) {
+        TreeScopeSet treeScopes = updateMode == FullStyleUpdate ? m_activeTreeScopes : m_dirtyTreeScopes;
+        HashSet<TreeScope*> treeScopesRemoved;
+
+        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->updateActiveStyleSheets(this, updateMode);
+            if (!collection->hasStyleSheetCandidateNodes())
+                treeScopesRemoved.add(treeScope);
+        }
+        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_collectionForDocument.usesRemUnits();
 
-    if (styleResolverUpdateType != StyleSheetCollection::Reconstruct)
-        resetCSSFeatureFlags(m_document->styleResolver()->ruleFeatureSet());
-
-    InspectorInstrumentation::activeStyleSheetsUpdated(m_document, m_collectionForDocument.styleSheetsForStyleSheetList());
-    m_usesRemUnits = styleSheetsUseRemUnits(m_collectionForDocument.activeAuthorStyleSheets());
-    m_document->notifySeamlessChildDocumentsOfStylesheetUpdate();
+    if (m_needsDocumentStyleSheetsUpdate || updateMode == FullStyleUpdate) {
+        m_document->notifySeamlessChildDocumentsOfStylesheetUpdate();
+        m_needsDocumentStyleSheetsUpdate = false;
+    }
 
     return requiresFullStyleRecalc;
 }
 
+void DocumentStyleSheetCollection::activeStyleSheetsUpdatedForInspector()
+{
+    if (m_activeTreeScopes.isEmpty()) {
+        InspectorInstrumentation::activeStyleSheetsUpdated(m_document, m_collectionForDocument.styleSheetsForStyleSheetList());
+        return;
+    }
+    Vector<RefPtr<StyleSheet> > activeStyleSheets;
+
+    activeStyleSheets.append(m_collectionForDocument.styleSheetsForStyleSheetList());
+
+    TreeScopeSet::iterator begin = m_activeTreeScopes.begin();
+    TreeScopeSet::iterator end = m_activeTreeScopes.end();
+    for (TreeScopeSet::iterator it = begin; it != end; ++it) {
+        if (StyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it))
+            activeStyleSheets.append(collection->styleSheetsForStyleSheetList());
+    }
+
+    // FIXME: Inspector needs a vector which has all active stylesheets.
+    // However, creating such a large vector might cause performance regression.
+    // Need to implement some smarter solution.
+    InspectorInstrumentation::activeStyleSheetsUpdated(m_document, activeStyleSheets);
+}
+
+void DocumentStyleSheetCollection::didRemoveShadowRoot(ShadowRoot* shadowRoot)
+{
+    m_styleSheetCollectionMap.remove(shadowRoot);
+}
+
+void DocumentStyleSheetCollection::appendActiveAuthorStyleSheets(StyleResolver* styleResolver)
+{
+    ASSERT(styleResolver);
+
+    styleResolver->setBuildScopedStyleTreeInDocumentOrder(true);
+    styleResolver->appendAuthorStyleSheets(0, m_collectionForDocument.activeAuthorStyleSheets());
+
+    TreeScopeSet::iterator begin = m_activeTreeScopes.begin();
+    TreeScopeSet::iterator end = m_activeTreeScopes.end();
+    for (TreeScopeSet::iterator it = begin; it != end; ++it) {
+        if (StyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it)) {
+            styleResolver->setBuildScopedStyleTreeInDocumentOrder(!collection->scopingNodesForStyleScoped());
+            styleResolver->appendAuthorStyleSheets(0, collection->activeAuthorStyleSheets());
+        }
+    }
+    styleResolver->finishAppendAuthorStyleSheets();
+    styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
+}
+
 }
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index bbafeb8..2dd47c5 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -64,6 +64,7 @@
 
     void addStyleSheetCandidateNode(Node*, bool createdByParser);
     void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode = 0);
+    void modifiedStyleSheetCandidateNode(Node*);
 
     void clearPageUserSheet();
     void updatePageUserSheet();
@@ -87,7 +88,7 @@
         RemovePendingSheetNotifyImmediately,
         RemovePendingSheetNotifyLater
     };
-    void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
+    void removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
 
     bool hasPendingSheets() const { return m_pendingStylesheets > 0; }
 
@@ -105,9 +106,22 @@
     void combineCSSFeatureFlags(const RuleFeatureSet&);
     void resetCSSFeatureFlags(const RuleFeatureSet&);
 
+    void didModifySeamlessParentStyleSheet() { m_needsDocumentStyleSheetsUpdate = true; }
+    void didRemoveShadowRoot(ShadowRoot*);
+    void appendActiveAuthorStyleSheets(StyleResolver*);
+    void getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const;
+
 private:
     DocumentStyleSheetCollection(Document*);
 
+    StyleSheetCollection* ensureStyleSheetCollectionFor(TreeScope*);
+    StyleSheetCollection* styleSheetCollectionFor(TreeScope*);
+    void activeStyleSheetsUpdatedForInspector();
+    bool shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode);
+
+    typedef ListHashSet<TreeScope*, 16> TreeScopeSet;
+    static void insertTreeScopeInDocumentOrder(TreeScopeSet&, TreeScope*);
+
     Document* m_document;
 
     // Track the number of currently loading top-level stylesheets needed for rendering.
@@ -125,10 +139,14 @@
     Vector<RefPtr<CSSStyleSheet> > m_userStyleSheets;
     Vector<RefPtr<CSSStyleSheet> > m_authorStyleSheets;
 
-    bool m_hadActiveLoadingStylesheet;
     bool m_needsUpdateActiveStylesheetsOnStyleRecalc;
 
-    StyleSheetCollection m_collectionForDocument;
+    StyleSheetCollectionForDocument m_collectionForDocument;
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> > m_styleSheetCollectionMap;
+
+    TreeScopeSet m_dirtyTreeScopes;
+    TreeScopeSet m_activeTreeScopes;
+    bool m_needsDocumentStyleSheetsUpdate;
 
     String m_preferredStylesheetSetName;
     String m_selectedStylesheetSetName;
diff --git a/Source/core/dom/DocumentType.idl b/Source/core/dom/DocumentType.idl
index 8f192f3..510240a 100644
--- a/Source/core/dom/DocumentType.idl
+++ b/Source/core/dom/DocumentType.idl
@@ -22,14 +22,14 @@
     // DOM Level 1
 
     readonly attribute DOMString name;
-    readonly attribute NamedNodeMap entities;
-    readonly attribute NamedNodeMap notations;
+    [MeasureAs=DocumentTypeEntities] readonly attribute NamedNodeMap entities; // Removed from DOM4.
+    [MeasureAs=DocumentTypeNotations] readonly attribute NamedNodeMap notations; // Removed from DOM4.
 
     // DOM Level 2
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString publicId;
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString systemId;
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString internalSubset;
+    [TreatReturnedNullStringAs=Null, MeasureAs=DocumentTypeInternalSubset] readonly attribute DOMString internalSubset; // Removed from DOM4.
 };
 
 DocumentType implements ChildNode;
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index b7147bc..9577774 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -953,7 +953,7 @@
 inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
 {
     if (name == isAttr)
-        CustomElementRegistrationContext::setTypeExtension(this, newValue);
+        CustomElementRegistrationContext::setTypeExtension(this, newValue, reason == ModifiedDirectly ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
     attributeChanged(name, newValue, reason);
 }
 
@@ -1053,7 +1053,7 @@
 bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
 {
     ASSERT(elementShadow);
-    const SelectRuleFeatureSet& featureSet = elementShadow->distributor().ensureSelectFeatureSet(elementShadow);
+    const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
 
     if (isIdAttributeName(name)) {
         AtomicString oldId = elementData()->idForStyleResolution();
@@ -1206,14 +1206,6 @@
     return RenderObject::createObject(this, style);
 }
 
-bool Element::isInert() const
-{
-    const Element* dialog = document()->activeModalDialog();
-    if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
-        return true;
-    return document()->ownerElement() && document()->ownerElement()->isInert();
-}
-
 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
 {
     // need to do superclass processing first so inDocument() is true
@@ -1229,6 +1221,9 @@
     if (Element* after = pseudoElement(AFTER))
         after->insertedInto(insertionPoint);
 
+    if (Element* backdrop = pseudoElement(BACKDROP))
+        backdrop->insertedInto(insertionPoint);
+
     if (!insertionPoint->isInTreeScope())
         return InsertionDone;
 
@@ -1279,7 +1274,7 @@
         setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
 
     if (document()->page())
-        document()->page()->pointerLockController()->elementRemoved(this);
+        document()->page()->pointerLockController().elementRemoved(this);
 
     setSavedLayerScrollOffset(IntSize());
 
@@ -1318,6 +1313,16 @@
     StyleResolverParentPusher parentPusher(this);
     WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
 
+    // We've already been through detach when doing a lazyAttach, but we might
+    // need to clear any state that's been added since then.
+    if (hasRareData() && styleChangeType() == LazyAttachStyleChange) {
+        ElementRareData* data = elementRareData();
+        data->clearComputedStyle();
+        data->resetDynamicRestyleObservations();
+        if (!context.resolvedStyle)
+            data->resetStyleState();
+    }
+
     NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
 
     createPseudoElementIfNeeded(BEFORE);
@@ -1534,10 +1539,11 @@
         } else if (child->isElementNode()) {
             Element* element = toElement(child);
 
+            bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
+
             if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
                 element->setNeedsStyleRecalc();
 
-            bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
             forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
             forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
 
@@ -1550,8 +1556,10 @@
         forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
     }
 
-    if (shouldRecalcStyle(change, this))
+    if (shouldRecalcStyle(change, this)) {
         updatePseudoElement(AFTER, change);
+        updatePseudoElement(BACKDROP, change);
+    }
 
     clearNeedsStyleRecalc();
     clearChildNeedsStyleRecalc();
@@ -1628,12 +1636,6 @@
     return shadowRoot;
 }
 
-Element* Element::uaShadowElementById(const AtomicString& id) const
-{
-    ShadowRoot* shadowRoot = userAgentShadowRoot();
-    return shadowRoot ? shadowRoot->getElementById(id) : 0;
-}
-
 bool Element::supportsShadowElementForUserAgentShadow() const
 {
     return true;
@@ -1770,6 +1772,8 @@
     checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
     if (StyleResolver* styleResolver = document()->styleResolverIfExists())
         styleResolver->popParentElement(this);
+    if (isCustomElement())
+        CustomElement::didFinishParsingChildren(this);
 }
 
 #ifndef NDEBUG
@@ -1827,7 +1831,7 @@
     synchronizeAllAttributes();
     UniqueElementData* elementData = ensureUniqueElementData();
 
-    size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
+    size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase(this));
     if (index != notFound) {
         if (oldAttrNode)
             detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
@@ -2630,7 +2634,7 @@
 void Element::webkitRequestPointerLock()
 {
     if (document()->page())
-        document()->page()->pointerLockController()->requestPointerLock(this);
+        document()->page()->pointerLockController().requestPointerLock(this);
 }
 
 SpellcheckAttributeState Element::spellcheckAttributeState() const
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index 7b075ce..556fe4f 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -87,7 +87,7 @@
 
     const Attribute* attributeItem(unsigned index) const;
     const Attribute* getAttributeItem(const QualifiedName&) const;
-    size_t getAttributeItemIndex(const QualifiedName&) const;
+    size_t getAttributeItemIndex(const QualifiedName&, bool shouldIgnoreCase = false) const;
     size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
     size_t getAttrIndex(Attr*) const;
 
@@ -216,6 +216,7 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
 
     // These four attribute event handler attributes are overridden by HTMLBodyElement
     // and HTMLFrameSetElement to forward to the DOMWindow.
@@ -446,7 +447,6 @@
 
     ShadowRoot* userAgentShadowRoot() const;
     ShadowRoot* ensureUserAgentShadowRoot();
-    Element* uaShadowElementById(const AtomicString& id) const;
     virtual bool supportsShadowElementForUserAgentShadow() const;
     virtual const AtomicString& shadowPseudoId() const { return !part().isEmpty() ? part() : pseudo(); }
 
@@ -594,7 +594,6 @@
     // to event listeners, and prevents DOMActivate events from being sent at all.
     virtual bool isDisabledFormControl() const { return false; }
 
-    bool isInert() const;
     virtual bool shouldBeReparentedUnderRenderView(const RenderStyle*) const { return isInTopLayer(); }
 
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
@@ -644,6 +643,8 @@
 
     InputMethodContext* inputMethodContext();
 
+    virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE FINAL;
+
 protected:
     Element(const QualifiedName& tagName, Document* document, ConstructionType type)
         : ContainerNode(document, type)
@@ -663,7 +664,7 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
-    virtual void removeAllEventListeners() OVERRIDE;
+    virtual void removeAllEventListeners() OVERRIDE FINAL;
 
     virtual void willRecalcStyle(StyleChange);
     virtual void didRecalcStyle(StyleChange);
@@ -728,7 +729,6 @@
 
     void scrollByUnits(int units, ScrollGranularity);
 
-    virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE FINAL;
     virtual NodeType nodeType() const OVERRIDE FINAL;
     virtual bool childTypeAllowed(NodeType) const OVERRIDE FINAL;
 
@@ -1037,12 +1037,12 @@
     return static_cast<const ShareableElementData*>(this)->m_attributeArray;
 }
 
-inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name) const
+inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name, bool shouldIgnoreCase) const
 {
     const Attribute* begin = attributeBase();
     for (unsigned i = 0; i < length(); ++i) {
         const Attribute& attribute = begin[i];
-        if (attribute.name().matches(name))
+        if (attribute.name().matchesPossiblyIgnoringCase(name, shouldIgnoreCase))
             return i;
     }
     return notFound;
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 0137af9..9af4c05 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -30,12 +30,11 @@
     [RaisesException, CustomElementCallbacks=Enable] void setAttribute([Default=Undefined] optional DOMString name,
                                      [Default=Undefined] optional DOMString value);
     [CustomElementCallbacks=Enable] void removeAttribute([Default=Undefined] optional DOMString name);
-    Attr getAttributeNode([Default=Undefined] optional DOMString name);
-    [RaisesException, CustomElementCallbacks=Enable] Attr setAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
-    [RaisesException, CustomElementCallbacks=Enable] Attr removeAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr oldAttr);
+    [MeasureAs=ElementGetAttributeNode] Attr getAttributeNode([Default=Undefined] optional DOMString name); // Removed from DOM4.
+    [RaisesException, CustomElementCallbacks=Enable, MeasureAs=ElementSetAttributeNode] Attr setAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr newAttr); // Removed from DOM4.
+    [RaisesException, CustomElementCallbacks=Enable, MeasureAs=ElementRemoveAttributeNode] Attr removeAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr oldAttr); // Removed from DOM4.
     [PerWorldBindings] NodeList getElementsByTagName([Default=Undefined] optional DOMString name);
 
-    // For ObjC this is defined on Node for legacy support.
     [PerWorldBindings] readonly attribute NamedNodeMap     attributes;
     boolean            hasAttributes();
 
@@ -50,8 +49,8 @@
                                           DOMString localName);
      NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                    [Default=Undefined] optional DOMString localName);
-     Attr getAttributeNodeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                           [Default=Undefined] optional DOMString localName);
+     [MeasureAs=ElementGetAttributeNodeNS] Attr getAttributeNodeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+                                                                   [Default=Undefined] optional DOMString localName); // Removed from DOM4.
     [RaisesException, CustomElementCallbacks=Enable] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
     boolean hasAttribute(DOMString name);
      boolean hasAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
@@ -63,6 +62,9 @@
     // iht.com relies on id returning the empty string when no id is present.
     // Other browsers do this as well. So we don't convert null to JS null.
     [Reflect] attribute DOMString id;
+    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException] attribute DOMString prefix;
+    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
 
     // Common extensions
 
@@ -162,7 +164,8 @@
     [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
     [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
     [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel; // Deprecated in favor of onwheel.
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onwheel;
     [NotEnumerable, PerWorldBindings] attribute EventHandler onscroll;
     [NotEnumerable, PerWorldBindings] attribute EventHandler onselect;
     [NotEnumerable, PerWorldBindings] attribute EventHandler onsubmit;
diff --git a/Source/core/dom/ElementTraversal.h b/Source/core/dom/ElementTraversal.h
new file mode 100644
index 0000000..0278732
--- /dev/null
+++ b/Source/core/dom/ElementTraversal.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.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.
+ *
+ */
+
+#ifndef ElementTraversal_h
+#define ElementTraversal_h
+
+#include "core/dom/Element.h"
+#include "core/dom/NodeTraversal.h"
+
+namespace WebCore {
+
+namespace ElementTraversal {
+
+// First element child of the node.
+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);
+
+// 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);
+
+// 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);
+
+// Utility function to traverse only the element and pseudo-element siblings of a node.
+Element* pseudoAwarePreviousSibling(const Node*);
+
+template <class NodeType>
+inline Element* firstElementWithinTemplate(NodeType* current)
+{
+    // Except for the root containers, only elements can have element children.
+    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); }
+
+template <class NodeType>
+inline Element* traverseNextElementTemplate(NodeType* current)
+{
+    Node* node = NodeTraversal::next(current);
+    while (node && !node->isElementNode())
+        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); }
+
+template <class NodeType>
+inline Element* traverseNextElementTemplate(NodeType* current, const Node* stayWithin)
+{
+    Node* node = NodeTraversal::next(current, stayWithin);
+    while (node && !node->isElementNode())
+        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); }
+
+template <class NodeType>
+inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current)
+{
+    Node* node = NodeTraversal::nextSkippingChildren(current);
+    while (node && !node->isElementNode())
+        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); }
+
+template <class NodeType>
+inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current, const Node* stayWithin)
+{
+    Node* node = NodeTraversal::nextSkippingChildren(current, stayWithin);
+    while (node && !node->isElementNode())
+        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* previousIncludingPseudo(const Node* current, const Node* stayWithin)
+{
+    Node* node = NodeTraversal::previousIncludingPseudo(current, stayWithin);
+    while (node && !node->isElementNode())
+        node = NodeTraversal::previousIncludingPseudo(node, stayWithin);
+    return toElement(node);
+}
+
+inline Element* nextIncludingPseudo(const Node* current, const Node* stayWithin)
+{
+    Node* node = NodeTraversal::nextIncludingPseudo(current, stayWithin);
+    while (node && !node->isElementNode())
+        node = NodeTraversal::nextIncludingPseudo(node, stayWithin);
+    return toElement(node);
+}
+
+inline Element* nextIncludingPseudoSkippingChildren(const Node* current, const Node* stayWithin)
+{
+    Node* node = NodeTraversal::nextIncludingPseudoSkippingChildren(current, stayWithin);
+    while (node && !node->isElementNode())
+        node = NodeTraversal::nextIncludingPseudoSkippingChildren(node, stayWithin);
+    return toElement(node);
+}
+
+inline Element* pseudoAwarePreviousSibling(const Node* current)
+{
+    Node* node = current->pseudoAwarePreviousSibling();
+    while (node && !node->isElementNode())
+        node = node->pseudoAwarePreviousSibling();
+    return toElement(node);
+}
+
+}
+
+}
+
+#endif
diff --git a/Source/core/dom/ErrorEvent.cpp b/Source/core/dom/ErrorEvent.cpp
index 7c4b3c1..ecb3d4b 100644
--- a/Source/core/dom/ErrorEvent.cpp
+++ b/Source/core/dom/ErrorEvent.cpp
@@ -50,7 +50,7 @@
 
 ErrorEvent::ErrorEvent(const AtomicString& type, const ErrorEventInit& initializer)
     : Event(type, initializer)
-    , m_message(initializer.message)
+    , m_sanitizedMessage(initializer.message)
     , m_fileName(initializer.filename)
     , m_lineNumber(initializer.lineno)
     , m_columnNumber(initializer.colno)
@@ -60,7 +60,7 @@
 
 ErrorEvent::ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber)
     : Event(eventNames().errorEvent, false, true)
-    , m_message(message)
+    , m_sanitizedMessage(message)
     , m_fileName(fileName)
     , m_lineNumber(lineNumber)
     , m_columnNumber(columnNumber)
@@ -68,6 +68,12 @@
     ScriptWrappable::init(this);
 }
 
+void ErrorEvent::setUnsanitizedMessage(const String& message)
+{
+    ASSERT(m_unsanitizedMessage.isEmpty());
+    m_unsanitizedMessage = message;
+}
+
 ErrorEvent::~ErrorEvent()
 {
 }
diff --git a/Source/core/dom/ErrorEvent.h b/Source/core/dom/ErrorEvent.h
index 8215544..583f07f 100644
--- a/Source/core/dom/ErrorEvent.h
+++ b/Source/core/dom/ErrorEvent.h
@@ -65,19 +65,26 @@
     }
     virtual ~ErrorEvent();
 
-    const String& message() const { return m_message; }
+    // As 'message' is exposed to JavaScript, never return unsanitizedMessage.
+    const String& message() const { return m_sanitizedMessage; }
     const String& filename() const { return m_fileName; }
     unsigned lineno() const { return m_lineNumber; }
     unsigned colno() const { return m_columnNumber; }
 
+    // 'messageForConsole' is not exposed to JavaScript, and prefers 'm_unsanitizedMessage'.
+    const String& messageForConsole() const { return !m_unsanitizedMessage.isEmpty() ? m_unsanitizedMessage : m_sanitizedMessage; }
+
     virtual const AtomicString& interfaceName() const;
 
+    void setUnsanitizedMessage(const String&);
+
 private:
     ErrorEvent();
     ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber);
     ErrorEvent(const AtomicString&, const ErrorEventInit&);
 
-    String m_message;
+    String m_unsanitizedMessage;
+    String m_sanitizedMessage;
     String m_fileName;
     unsigned m_lineNumber;
     unsigned m_columnNumber;
diff --git a/Source/core/dom/EventNames.h b/Source/core/dom/EventNames.h
index 0c01af9..098071d 100644
--- a/Source/core/dom/EventNames.h
+++ b/Source/core/dom/EventNames.h
@@ -125,6 +125,7 @@
     macro(upgradeneeded) \
     macro(versionchange) \
     macro(webkitvisibilitychange) \
+    macro(wheel) \
     macro(write) \
     macro(writeend) \
     macro(writestart) \
diff --git a/Source/core/dom/EventPathWalker.cpp b/Source/core/dom/EventPathWalker.cpp
index 4853df6..de1d4d0 100644
--- a/Source/core/dom/EventPathWalker.cpp
+++ b/Source/core/dom/EventPathWalker.cpp
@@ -27,7 +27,7 @@
 #include "config.h"
 #include "core/dom/EventPathWalker.h"
 
-#include "core/dom/shadow/ContentDistributor.h"
+#include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
@@ -58,7 +58,7 @@
     ASSERT(m_node);
     ASSERT(m_distributedNode);
     if (ElementShadow* shadow = shadowOfParent(m_node)) {
-        if (InsertionPoint* insertionPoint = shadow->distributor().findInsertionPointFor(m_distributedNode)) {
+        if (InsertionPoint* insertionPoint = shadow->findInsertionPointFor(m_distributedNode)) {
             m_node = insertionPoint;
             m_isVisitingInsertionPointInReprojection = true;
             return;
diff --git a/Source/core/dom/EventTarget.cpp b/Source/core/dom/EventTarget.cpp
index db40321..30c6854 100644
--- a/Source/core/dom/EventTarget.cpp
+++ b/Source/core/dom/EventTarget.cpp
@@ -68,6 +68,11 @@
     return 0;
 }
 
+MessagePort* EventTarget::toMessagePort()
+{
+    return 0;
+}
+
 inline DOMWindow* EventTarget::executingWindow()
 {
     if (ScriptExecutionContext* context = scriptExecutionContext())
@@ -176,11 +181,14 @@
 {
 }
 
-static AtomicString prefixedType(const Event* event)
+static AtomicString legacyType(const Event* event)
 {
     if (event->type() == eventNames().transitionendEvent)
         return eventNames().webkitTransitionEndEvent;
 
+    if (event->type() == eventNames().wheelEvent)
+        return eventNames().mousewheelEvent;
+
     return emptyString();
 }
 
@@ -193,30 +201,30 @@
     if (!d)
         return true;
 
-    EventListenerVector* listenerPrefixedVector = 0;
-    AtomicString prefixedTypeName = prefixedType(event);
-    if (!prefixedTypeName.isEmpty())
-        listenerPrefixedVector = d->eventListenerMap.find(prefixedTypeName);
+    EventListenerVector* legacyListenersVector = 0;
+    AtomicString legacyTypeName = legacyType(event);
+    if (!legacyTypeName.isEmpty())
+        legacyListenersVector = d->eventListenerMap.find(legacyTypeName);
 
-    EventListenerVector* listenerUnprefixedVector = d->eventListenerMap.find(event->type());
+    EventListenerVector* listenersVector = d->eventListenerMap.find(event->type());
 
-    if (listenerUnprefixedVector)
-        fireEventListeners(event, d, *listenerUnprefixedVector);
-    else if (listenerPrefixedVector) {
+    if (listenersVector) {
+        fireEventListeners(event, d, *listenersVector);
+    } else if (legacyListenersVector) {
         AtomicString unprefixedTypeName = event->type();
-        event->setType(prefixedTypeName);
-        fireEventListeners(event, d, *listenerPrefixedVector);
+        event->setType(legacyTypeName);
+        fireEventListeners(event, d, *legacyListenersVector);
         event->setType(unprefixedTypeName);
     }
 
-    if (!prefixedTypeName.isEmpty()) {
+    if (legacyTypeName == eventNames().webkitTransitionEndEvent) {
         if (DOMWindow* executingWindow = this->executingWindow()) {
-            if (listenerPrefixedVector) {
-                if (listenerUnprefixedVector)
+            if (legacyListenersVector) {
+                if (listenersVector)
                     UseCounter::count(executingWindow, UseCounter::PrefixedAndUnprefixedTransitionEndEvent);
                 else
                     UseCounter::count(executingWindow, UseCounter::PrefixedTransitionEndEvent);
-            } else if (listenerUnprefixedVector) {
+            } else if (listenersVector) {
                 UseCounter::count(executingWindow, UseCounter::UnprefixedTransitionEndEvent);
             }
         }
diff --git a/Source/core/dom/EventTarget.h b/Source/core/dom/EventTarget.h
index 633d2d2..267306a 100644
--- a/Source/core/dom/EventTarget.h
+++ b/Source/core/dom/EventTarget.h
@@ -38,8 +38,8 @@
 
 namespace WebCore {
 
+    class ApplicationCache;
     class AudioContext;
-    class DOMApplicationCache;
     class DOMWindow;
     class DedicatedWorkerGlobalScope;
     class Event;
@@ -106,6 +106,7 @@
 
         virtual Node* toNode();
         virtual DOMWindow* toDOMWindow();
+        virtual MessagePort* toMessagePort();
 
         virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
         virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
diff --git a/Source/core/dom/EventTargetFactory.in b/Source/core/dom/EventTargetFactory.in
index 1929c1e..abe0c16 100644
--- a/Source/core/dom/EventTargetFactory.in
+++ b/Source/core/dom/EventTargetFactory.in
@@ -9,7 +9,7 @@
 core/html/track/TextTrack
 core/html/track/TextTrackCue
 core/html/track/TextTrackList
-core/loader/appcache/DOMApplicationCache
+core/loader/appcache/ApplicationCache
 core/page/EventSource
 core/page/Performance
 core/page/Window ImplementedAs=DOMWindow
diff --git a/Source/core/dom/FullscreenElementStack.cpp b/Source/core/dom/FullscreenElementStack.cpp
index 78dfe24..b72b25b 100644
--- a/Source/core/dom/FullscreenElementStack.cpp
+++ b/Source/core/dom/FullscreenElementStack.cpp
@@ -188,7 +188,7 @@
             break;
 
         // There is a previously-established user preference, security risk, or platform limitation.
-        if (!document()->page() || !document()->page()->settings()->fullScreenEnabled())
+        if (!document()->page() || !document()->page()->settings().fullScreenEnabled())
             break;
 
         // 2. Let doc be element's node document. (i.e. "this")
@@ -240,7 +240,7 @@
         // 5. Return, and run the remaining steps asynchronously.
         // 6. Optionally, perform some animation.
         m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
-        document()->page()->chrome().client()->enterFullScreenForElement(element);
+        document()->page()->chrome().client().enterFullScreenForElement(element);
 
         // 7. Optionally, display a message indicating how the user can exit displaying the context object fullscreen.
         return;
@@ -331,12 +331,12 @@
     // Only exit out of full screen window mode if there are no remaining elements in the
     // full screen stack.
     if (!newTop) {
-        document()->page()->chrome().client()->exitFullScreenForElement(m_fullScreenElement.get());
+        document()->page()->chrome().client().exitFullScreenForElement(m_fullScreenElement.get());
         return;
     }
 
     // Otherwise, notify the chrome of the new full screen element.
-    document()->page()->chrome().client()->enterFullScreenForElement(newTop);
+    document()->page()->chrome().client().enterFullScreenForElement(newTop);
 }
 
 bool FullscreenElementStack::webkitFullscreenEnabled(Document* document)
@@ -360,7 +360,7 @@
     if (!document()->page())
         return;
 
-    ASSERT(document()->page()->settings()->fullScreenEnabled());
+    ASSERT(document()->page()->settings().fullScreenEnabled());
 
     if (m_fullScreenRenderer)
         m_fullScreenRenderer->unwrapRenderer();
diff --git a/Source/core/dom/GestureEvent.cpp b/Source/core/dom/GestureEvent.cpp
index a4f5cf8..6423c0a 100644
--- a/Source/core/dom/GestureEvent.cpp
+++ b/Source/core/dom/GestureEvent.cpp
@@ -115,9 +115,6 @@
 
 bool GestureEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
 {
-    if (isDisabledFormControl(dispatcher->node()))
-        return true;
-
     dispatcher->dispatch();
     ASSERT(!event()->defaultPrevented());
     return event()->defaultHandled() || event()->defaultPrevented();
diff --git a/Source/core/dom/MessageChannel.idl b/Source/core/dom/MessageChannel.idl
index 3d62729..f5b5165 100644
--- a/Source/core/dom/MessageChannel.idl
+++ b/Source/core/dom/MessageChannel.idl
@@ -26,13 +26,9 @@
 
 [
     GlobalContext=Window&WorkerGlobalScope,
-    Constructor,
-    ConstructorCallWith=ScriptExecutionContext,
     CustomConstructor
 ] interface MessageChannel {
-
     readonly attribute MessagePort port1;
     readonly attribute MessagePort port2;
-
 };
 
diff --git a/Source/core/dom/MessageEvent.cpp b/Source/core/dom/MessageEvent.cpp
index ce6e8fa..351275c 100644
--- a/Source/core/dom/MessageEvent.cpp
+++ b/Source/core/dom/MessageEvent.cpp
@@ -33,6 +33,11 @@
 
 namespace WebCore {
 
+static inline bool isValidSource(EventTarget* source)
+{
+    return !source || source->toDOMWindow() || source->toMessagePort();
+}
+
 MessageEventInit::MessageEventInit()
 {
 }
@@ -48,13 +53,14 @@
     , m_dataType(DataTypeScriptValue)
     , m_origin(initializer.origin)
     , m_lastEventId(initializer.lastEventId)
-    , m_source(initializer.source)
+    , m_source(isValidSource(initializer.source.get()) ? initializer.source : 0)
     , m_ports(adoptPtr(new MessagePortArray(initializer.ports)))
 {
     ScriptWrappable::init(this);
+    ASSERT(isValidSource(m_source.get()));
 }
 
-MessageEvent::MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortArray> ports)
+MessageEvent::MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray> ports)
     : Event(eventNames().messageEvent, false, false)
     , m_dataType(DataTypeScriptValue)
     , m_origin(origin)
@@ -63,9 +69,10 @@
     , m_ports(ports)
 {
     ScriptWrappable::init(this);
+    ASSERT(isValidSource(m_source.get()));
 }
 
-MessageEvent::MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortArray> ports)
+MessageEvent::MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray> ports)
     : Event(eventNames().messageEvent, false, false)
     , m_dataType(DataTypeSerializedScriptValue)
     , m_dataAsSerializedScriptValue(data)
@@ -77,6 +84,7 @@
     ScriptWrappable::init(this);
     if (m_dataAsSerializedScriptValue)
         m_dataAsSerializedScriptValue->registerMemoryAllocatedWithCurrentScriptContext();
+    ASSERT(isValidSource(m_source.get()));
 }
 
 MessageEvent::MessageEvent(const String& data, const String& origin)
diff --git a/Source/core/dom/MessageEvent.h b/Source/core/dom/MessageEvent.h
index 7f54232..e6647c1 100644
--- a/Source/core/dom/MessageEvent.h
+++ b/Source/core/dom/MessageEvent.h
@@ -30,6 +30,7 @@
 
 #include "bindings/v8/SerializedScriptValue.h"
 #include "core/dom/Event.h"
+#include "core/dom/EventTarget.h"
 #include "core/dom/MessagePort.h"
 #include "core/fileapi/Blob.h"
 #include "core/page/DOMWindow.h"
@@ -37,14 +38,12 @@
 
 namespace WebCore {
 
-class DOMWindow;
-
 struct MessageEventInit : public EventInit {
     MessageEventInit();
 
     String origin;
     String lastEventId;
-    RefPtr<DOMWindow> source;
+    RefPtr<EventTarget> source;
     MessagePortArray ports;
 };
 
@@ -54,11 +53,11 @@
     {
         return adoptRef(new MessageEvent);
     }
-    static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, const String& origin = "", const String& lastEventId = "", PassRefPtr<DOMWindow> source = 0)
+    static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, const String& origin = "", const String& lastEventId = "", PassRefPtr<EventTarget> source = 0)
     {
         return adoptRef(new MessageEvent(origin, lastEventId, source, ports));
     }
-    static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, PassRefPtr<SerializedScriptValue> data, const String& origin = "", const String& lastEventId = "", PassRefPtr<DOMWindow> source = 0)
+    static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, PassRefPtr<SerializedScriptValue> data, const String& origin = "", const String& lastEventId = "", PassRefPtr<EventTarget> source = 0)
     {
         return adoptRef(new MessageEvent(data, origin, lastEventId, source, ports));
     }
@@ -85,7 +84,7 @@
 
     const String& origin() const { return m_origin; }
     const String& lastEventId() const { return m_lastEventId; }
-    DOMWindow* source() const { return m_source.get(); }
+    EventTarget* source() const { return m_source.get(); }
     MessagePortArray ports() const { return m_ports ? *m_ports : MessagePortArray(); }
 
     virtual const AtomicString& interfaceName() const;
@@ -112,8 +111,8 @@
 private:
     MessageEvent();
     MessageEvent(const AtomicString&, const MessageEventInit&);
-    MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortArray>);
-    MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortArray>);
+    MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray>);
+    MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray>);
 
     explicit MessageEvent(const String& data, const String& origin);
     explicit MessageEvent(PassRefPtr<Blob> data, const String& origin);
@@ -126,7 +125,7 @@
     RefPtr<ArrayBuffer> m_dataAsArrayBuffer;
     String m_origin;
     String m_lastEventId;
-    RefPtr<DOMWindow> m_source;
+    RefPtr<EventTarget> m_source;
     OwnPtr<MessagePortArray> m_ports;
 };
 
diff --git a/Source/core/dom/MessageEvent.idl b/Source/core/dom/MessageEvent.idl
index 3bc8866..33d1c33 100644
--- a/Source/core/dom/MessageEvent.idl
+++ b/Source/core/dom/MessageEvent.idl
@@ -31,7 +31,7 @@
 ] interface MessageEvent : Event {
     [InitializedByEventConstructor] readonly attribute DOMString origin;
     [InitializedByEventConstructor] readonly attribute DOMString lastEventId;
-    [InitializedByEventConstructor] readonly attribute Window source;
+    [InitializedByEventConstructor] readonly attribute EventTarget source; // May be a Window or a MessagePort
     [InitializedByEventConstructor, CustomGetter] readonly attribute any data;
     [InitializedByEventConstructor] readonly attribute MessagePort[] ports;
 
diff --git a/Source/core/dom/MessagePort.h b/Source/core/dom/MessagePort.h
index 337e225..34773c9 100644
--- a/Source/core/dom/MessagePort.h
+++ b/Source/core/dom/MessagePort.h
@@ -75,6 +75,7 @@
 
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
+    MessagePort* toMessagePort() OVERRIDE { return this; }
 
     void dispatchMessages();
 
diff --git a/Source/core/dom/MessagePort.idl b/Source/core/dom/MessagePort.idl
index 4324172..17ae449 100644
--- a/Source/core/dom/MessagePort.idl
+++ b/Source/core/dom/MessagePort.idl
@@ -28,8 +28,6 @@
 [
     ActiveDOMObject
 ] interface MessagePort : EventTarget {
-// We need to have something as an ObjC binding, because MessagePort is used in MessageEvent, which already has one,
-// but we don't want to actually expose the API while it is in flux.
     [Custom, RaisesException] void postMessage(any message, optional Array messagePorts);
 
     void start();
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 3936024..c4eebe4 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -71,6 +71,7 @@
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/htmlediting.h"
+#include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/html/RadioNodeList.h"
@@ -83,6 +84,7 @@
 #include "core/platform/Partitions.h"
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/RenderBox.h"
+#include "core/svg/graphics/SVGImage.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCountedLeakCounter.h"
@@ -782,6 +784,11 @@
     clearChildNeedsDistributionRecalc();
 }
 
+void Node::setIsLink(bool isLink)
+{
+    setFlag(isLink && !SVGImage::isInSVGImage(toElement(this)), IsLinkFlag);
+}
+
 void Node::markAncestorsWithChildNeedsDistributionRecalc()
 {
     for (Node* node = this; node && !node->childNeedsDistributionRecalc(); node = node->parentOrShadowHostNode())
@@ -833,25 +840,14 @@
 
 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
 {
-    // It's safe to synchronously attach here because we're in the middle of style recalc
-    // while it's not safe to mark nodes as needing style recalc except in the loop in
-    // Element::recalcStyle because we may mark an ancestor as not needing recalc and
-    // then the node would never get updated. One place this currently happens is
-    // HTMLObjectElement::renderFallbackContent which may call lazyAttach from inside
-    // attach which was triggered by a recalcStyle.
-    if (document()->inStyleRecalc()) {
-        attach();
-        return;
-    }
     markAncestorsWithChildNeedsStyleRecalc();
     for (Node* node = this; node; node = NodeTraversal::next(node, this)) {
         node->setStyleChange(LazyAttachStyleChange);
-        node->setChildNeedsStyleRecalc();
+        if (node->isContainerNode())
+            node->setChildNeedsStyleRecalc();
         // FIXME: This flag is only used by HTMLFrameElementBase and doesn't look needed.
         if (shouldSetAttached == SetAttached)
             node->setAttached();
-        if (isActiveInsertionPoint(node))
-            toInsertionPoint(node)->lazyAttachDistribution(shouldSetAttached);
         for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
             root->lazyAttach(shouldSetAttached);
     }
@@ -868,6 +864,14 @@
     return true;
 }
 
+bool Node::isInert() const
+{
+    const Element* dialog = document()->activeModalDialog();
+    if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
+        return true;
+    return document()->ownerElement() && document()->ownerElement()->isInert();
+}
+
 unsigned Node::nodeIndex() const
 {
     Node *_tempNode = previousSibling();
@@ -1030,6 +1034,33 @@
     return false;
 }
 
+inline void Node::detachNode(Node* root, const AttachContext& context)
+{
+    Node* node = root;
+    while (node) {
+        if (node->styleChangeType() == LazyAttachStyleChange) {
+            // FIXME: This is needed because Node::lazyAttach marks nodes as being attached even
+            // though they've never been through attach(). This allows us to avoid doing all the
+            // virtual calls to detach() and other associated work.
+            node->clearAttached();
+            node->clearChildNeedsStyleRecalc();
+
+            for (ShadowRoot* shadowRoot = node->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
+                detachNode(shadowRoot, context);
+
+            node = NodeTraversal::next(node, root);
+            continue;
+        }
+        // Handle normal reattaches from style recalc (ex. display type changes)
+        // or descendants of lazy attached nodes that got actually attached, for example,
+        // by innerHTML or editing.
+        // FIXME: innerHTML and editing should also lazyAttach.
+        if (node->attached())
+            node->detach(context);
+        node = NodeTraversal::nextSkippingChildren(node, root);
+    }
+}
+
 void Node::reattach(const AttachContext& context)
 {
     // FIXME: Text::updateTextRenderer calls reattach outside a style recalc.
@@ -1037,8 +1068,7 @@
     AttachContext reattachContext(context);
     reattachContext.performingReattach = true;
 
-    if (attached())
-        detach(reattachContext);
+    detachNode(this, reattachContext);
     attach(reattachContext);
 }
 
@@ -1110,7 +1140,7 @@
         }
     }
 
-    clearFlag(IsAttachedFlag);
+    clearAttached();
 
 #ifndef NDEBUG
     detachingNode = 0;
@@ -1681,7 +1711,7 @@
             ChildListMutationScope mutation(this);
             container->removeChildren();
             if (!text.isEmpty())
-                container->appendChild(document()->createTextNode(text), es, AttachLazily);
+                container->appendChild(document()->createTextNode(text), es);
             return;
         }
         case DOCUMENT_NODE:
@@ -1867,8 +1897,6 @@
     return p;
 }
 
-#ifndef NDEBUG
-
 String Node::debugName() const
 {
     StringBuilder name;
@@ -1893,6 +1921,8 @@
     return name.toString();
 }
 
+#ifndef NDEBUG
+
 static void appendAttributeDesc(const Node* node, StringBuilder& stringBuilder, const QualifiedName& name, const char* attrDesc)
 {
     if (!node->isElementNode())
@@ -2125,7 +2155,13 @@
         if (AXObjectCache* cache = oldDocument->existingAXObjectCache())
             cache->remove(this);
 
-    const EventListenerVector& wheelListeners = getEventListeners(eventNames().mousewheelEvent);
+    const EventListenerVector& mousewheelListeners = getEventListeners(eventNames().mousewheelEvent);
+    for (size_t i = 0; i < mousewheelListeners.size(); ++i) {
+        oldDocument->didRemoveWheelEventHandler();
+        document()->didAddWheelEventHandler();
+    }
+
+    const EventListenerVector& wheelListeners = getEventListeners(eventNames().wheelEvent);
     for (size_t i = 0; i < wheelListeners.size(); ++i) {
         oldDocument->didRemoveWheelEventHandler();
         document()->didAddWheelEventHandler();
@@ -2158,7 +2194,7 @@
 
     if (Document* document = targetNode->document()) {
         document->addListenerTypeIfNeeded(eventType);
-        if (eventType == eventNames().mousewheelEvent)
+        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
             document->didAddWheelEventHandler();
         else if (eventNames().isTouchEventType(eventType))
             document->didAddTouchEventHandler(targetNode);
@@ -2180,7 +2216,7 @@
     // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
     // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
     if (Document* document = targetNode->document()) {
-        if (eventType == eventNames().mousewheelEvent)
+        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
             document->didRemoveWheelEventHandler();
         else if (eventNames().isTouchEventType(eventType))
             document->didRemoveTouchEventHandler(targetNode);
@@ -2464,9 +2500,8 @@
         if (dispatchDOMActivateEvent(detail, event))
             event->setDefaultHandled();
     } else if (eventType == eventNames().contextmenuEvent) {
-        if (Frame* frame = document()->frame())
-            if (Page* page = frame->page())
-                page->contextMenuController()->handleContextMenuEvent(event);
+        if (Page* page = document()->page())
+            page->contextMenuController().handleContextMenuEvent(event);
     } else if (eventType == eventNames().textInputEvent) {
         if (event->hasInterface(eventNames().interfaceForTextEvent))
             if (Frame* frame = document()->frame())
@@ -2488,7 +2523,7 @@
             }
         }
 #endif
-    } else if (eventType == eventNames().mousewheelEvent && event->hasInterface(eventNames().interfaceForWheelEvent)) {
+    } else if ((eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent) && event->hasInterface(eventNames().interfaceForWheelEvent)) {
         WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
 
         // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
@@ -2623,15 +2658,14 @@
     document()->updateDistributionForNodeIfNeeded(this);
     Vector<InsertionPoint*, 8> insertionPoints;
     collectInsertionPointsWhereNodeIsDistributed(this, insertionPoints);
+    Vector<RefPtr<Node> > filteredInsertionPoints;
     for (size_t i = 0; i < insertionPoints.size(); ++i) {
         InsertionPoint* insertionPoint = insertionPoints[i];
         ASSERT(insertionPoint->containingShadowRoot());
-        if (insertionPoint->containingShadowRoot()->type() == ShadowRoot::UserAgentShadowRoot)
-            return StaticNodeList::createEmpty();
+        if (insertionPoint->containingShadowRoot()->type() != ShadowRoot::UserAgentShadowRoot)
+            filteredInsertionPoints.append(insertionPoint);
     }
-    Vector<RefPtr<Node> > asNodes;
-    asNodes.appendRange(insertionPoints.begin(), insertionPoints.end());
-    return StaticNodeList::adopt(asNodes);
+    return StaticNodeList::adopt(filteredInsertionPoints);
 }
 
 void Node::registerScopedHTMLStyleChild()
@@ -2707,22 +2741,22 @@
         ASSERT_NOT_REACHED(); // Everything starts in this state
         return;
 
-    case UpgradeCandidate:
+    case WaitingForParser:
         ASSERT(NotCustomElement == oldState);
         break;
 
-    case Defined:
-        ASSERT(UpgradeCandidate == oldState || NotCustomElement == oldState);
+    case WaitingForUpgrade:
+        ASSERT(NotCustomElement == oldState || WaitingForParser == oldState);
         break;
 
     case Upgraded:
-        ASSERT(Defined == oldState);
+        ASSERT(WaitingForParser == oldState || WaitingForUpgrade == oldState);
         break;
     }
 
     ASSERT(isHTMLElement() || isSVGElement());
-    setFlag(newState & 1, CustomElementIsUpgradeCandidateOrUpgraded);
-    setFlag(newState & 2, CustomElementHasDefinitionOrIsUpgraded);
+    setFlag(newState & 1, CustomElementWaitingForParserOrIsUpgraded);
+    setFlag(newState & 2, CustomElementWaitingForUpgradeOrIsUpgraded);
 
     if (oldState == NotCustomElement || newState == Upgraded)
         setNeedsStyleRecalc(); // :unresolved has changed
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index a651d06..bdfdb4c 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -25,6 +25,7 @@
 #ifndef Node_h
 #define Node_h
 
+#include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/EventTarget.h"
 #include "core/dom/MutationObserver.h"
@@ -114,7 +115,7 @@
 };
 
 enum AttachBehavior {
-    AttachNow,
+    DeprecatedAttachNow,
     AttachLazily,
 };
 
@@ -204,10 +205,10 @@
     // These should all actually return a node, but this is only important for language bindings,
     // which will already know and hold a ref on the right node to return. Returning bool allows
     // these methods to be more efficient since they don't need to return a ref
-    void insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState&, AttachBehavior = AttachNow);
-    void replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState&, AttachBehavior = AttachNow);
+    void insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachLazily);
+    void replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachLazily);
     void removeChild(Node* child, ExceptionState&);
-    void appendChild(PassRefPtr<Node> newChild, ExceptionState&, AttachBehavior = AttachNow);
+    void appendChild(PassRefPtr<Node> newChild, ExceptionState& = ASSERT_NO_EXCEPTION, AttachBehavior = AttachLazily);
 
     bool hasChildNodes() const { return firstChild(); }
     virtual PassRefPtr<Node> cloneNode(bool deep = true) = 0;
@@ -245,12 +246,12 @@
 
     enum CustomElementState {
         NotCustomElement,
-        UpgradeCandidate,
-        Defined,
+        WaitingForParser,
+        WaitingForUpgrade,
         Upgraded
     };
     bool isCustomElement() const { return customElementState() != NotCustomElement; }
-    CustomElementState customElementState() const { return CustomElementState((getFlag(CustomElementHasDefinitionOrIsUpgraded) ? 2 : 0) | (getFlag(CustomElementIsUpgradeCandidateOrUpgraded) ? 1 : 0)); }
+    CustomElementState customElementState() const { return CustomElementState((getFlag(CustomElementWaitingForParserOrIsUpgraded) ? 1 : 0) | (getFlag(CustomElementWaitingForUpgradeOrIsUpgraded) ? 2 : 0)); }
     void setCustomElementState(CustomElementState newState);
 
     virtual bool isMediaControlElement() const { return false; }
@@ -400,9 +401,7 @@
 
     bool shouldNotifyRendererWithIdenticalStyles() const { return getFlag(NotifyRendererWithIdenticalStyles); }
 
-    void setIsLink(bool f) { setFlag(f, IsLinkFlag); }
-    void setIsLink() { setFlag(IsLinkFlag); }
-    void clearIsLink() { clearFlag(IsLinkFlag); }
+    void setIsLink(bool f);
 
     void setInNamedFlow() { setFlag(InNamedFlowFlag); }
     void clearInNamedFlow() { clearFlag(InNamedFlowFlag); }
@@ -433,6 +432,10 @@
     // This is called only when the node is focused.
     virtual bool shouldHaveFocusAppearance() const;
 
+    // Whether the node is inert. This can't be in Element because text nodes
+    // must be recognized as inert to prevent text selection.
+    bool isInert() const;
+
     enum UserSelectAllTreatment {
         UserSelectAllDoesNotAffectEditability,
         UserSelectAllIsAlwaysNonEditable
@@ -608,9 +611,9 @@
     //
     virtual void removedFrom(ContainerNode* insertionPoint);
 
-#ifndef NDEBUG
     String debugName() const;
 
+#ifndef NDEBUG
     virtual void formatForDebugger(char* buffer, unsigned length) const;
 
     void showNode(const char* prefix = "") const;
@@ -713,6 +716,9 @@
 
     PassRefPtr<NodeList> getDestinationInsertionPoints();
 
+    void setAlreadySpellChecked(bool flag) { setFlag(flag, AlreadySpellCheckedFlag); }
+    bool isAlreadySpellChecked() { return getFlag(AlreadySpellCheckedFlag); }
+
 private:
     enum NodeFlags {
         IsTextFlag = 1,
@@ -750,10 +756,11 @@
 
         NotifyRendererWithIdenticalStyles = 1 << 26,
 
-        CustomElementIsUpgradeCandidateOrUpgraded = 1 << 27,
-        CustomElementHasDefinitionOrIsUpgraded = 1 << 28,
+        CustomElementWaitingForParserOrIsUpgraded = 1 << 27,
+        CustomElementWaitingForUpgradeOrIsUpgraded = 1 << 28,
 
         ChildNeedsDistributionRecalc = 1 << 29,
+        AlreadySpellCheckedFlag = 1 << 30,
 
         DefaultNodeFlags = IsParsingChildrenFinishedFlag
     };
@@ -839,6 +846,9 @@
 
     void setStyleChange(StyleChangeType);
 
+    void detachNode(Node*, const AttachContext&);
+    void clearAttached() { clearFlag(IsAttachedFlag); }
+
     // Used to share code between lazyAttach and setNeedsStyleRecalc.
     void markAncestorsWithChildNeedsStyleRecalc();
 
diff --git a/Source/core/dom/Node.idl b/Source/core/dom/Node.idl
index 0c7c5a1..3d774a2 100644
--- a/Source/core/dom/Node.idl
+++ b/Source/core/dom/Node.idl
@@ -61,12 +61,12 @@
     [CustomElementCallbacks=Enable] void normalize();
 
     // Introduced in DOM Level 2:
-     boolean isSupported([Default=Undefined] optional DOMString feature,
-                                       [TreatNullAs=NullString,Default=Undefined] optional DOMString version);
+    [MeasureAs=NodeIsSupported] boolean isSupported([Default=Undefined] optional DOMString feature,
+                                                    [TreatNullAs=NullString,Default=Undefined] optional DOMString version); // Removed in DOM4.
 
-    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString        namespaceURI;
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException] attribute DOMString        prefix;
-    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString        localName;
+    [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, 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;
@@ -74,7 +74,7 @@
              // FIXME: the spec says this can also raise on retrieval.
              [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString       textContent;
 
-    boolean            isSameNode([Default=Undefined] optional Node other);
+    [MeasureAs=NodeIsSameNode] boolean isSameNode([Default=Undefined] optional Node other); // Removed in DOM4.
     boolean            isEqualNode([Default=Undefined] optional Node other);
     [TreatReturnedNullStringAs=Null] DOMString          lookupPrefix([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI);
     boolean            isDefaultNamespace([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI);
diff --git a/Source/core/dom/NodeTraversal.h b/Source/core/dom/NodeTraversal.h
index c9d5208..c6966a6 100644
--- a/Source/core/dom/NodeTraversal.h
+++ b/Source/core/dom/NodeTraversal.h
@@ -25,38 +25,10 @@
 #ifndef NodeTraversal_h
 #define NodeTraversal_h
 
-#include "core/dom/Element.h"
+#include "core/dom/Node.h"
 
 namespace WebCore {
 
-namespace ElementTraversal {
-
-// First element child of the node.
-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);
-
-// 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);
-
-// 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);
-
-// Utility function to traverse only the element and pseudo-element siblings of a node.
-Element* pseudoAwarePreviousSibling(const Node*);
-
-}
-
 namespace NodeTraversal {
 
 // Does a pre-order traversal of the tree to find the next node after this one.
@@ -92,101 +64,6 @@
 Node* nextIncludingPseudo(const Node*, const Node* stayWithin = 0);
 Node* nextIncludingPseudoSkippingChildren(const Node*, const Node* stayWithin = 0);
 
-}
-
-namespace ElementTraversal {
-template <class NodeType>
-inline Element* firstElementWithinTemplate(NodeType* current)
-{
-    // Except for the root containers, only elements can have element children.
-    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); }
-
-template <class NodeType>
-inline Element* traverseNextElementTemplate(NodeType* current)
-{
-    Node* node = NodeTraversal::next(current);
-    while (node && !node->isElementNode())
-        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); }
-
-template <class NodeType>
-inline Element* traverseNextElementTemplate(NodeType* current, const Node* stayWithin)
-{
-    Node* node = NodeTraversal::next(current, stayWithin);
-    while (node && !node->isElementNode())
-        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); }
-
-template <class NodeType>
-inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current)
-{
-    Node* node = NodeTraversal::nextSkippingChildren(current);
-    while (node && !node->isElementNode())
-        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); }
-
-template <class NodeType>
-inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current, const Node* stayWithin)
-{
-    Node* node = NodeTraversal::nextSkippingChildren(current, stayWithin);
-    while (node && !node->isElementNode())
-        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* previousIncludingPseudo(const Node* current, const Node* stayWithin)
-{
-    Node* node = NodeTraversal::previousIncludingPseudo(current, stayWithin);
-    while (node && !node->isElementNode())
-        node = NodeTraversal::previousIncludingPseudo(node, stayWithin);
-    return toElement(node);
-}
-
-inline Element* nextIncludingPseudo(const Node* current, const Node* stayWithin)
-{
-    Node* node = NodeTraversal::nextIncludingPseudo(current, stayWithin);
-    while (node && !node->isElementNode())
-        node = NodeTraversal::nextIncludingPseudo(node, stayWithin);
-    return toElement(node);
-}
-
-inline Element* nextIncludingPseudoSkippingChildren(const Node* current, const Node* stayWithin)
-{
-    Node* node = NodeTraversal::nextIncludingPseudoSkippingChildren(current, stayWithin);
-    while (node && !node->isElementNode())
-        node = NodeTraversal::nextIncludingPseudoSkippingChildren(node, stayWithin);
-    return toElement(node);
-}
-
-inline Element* pseudoAwarePreviousSibling(const Node* current)
-{
-    Node* node = current->pseudoAwarePreviousSibling();
-    while (node && !node->isElementNode())
-        node = node->pseudoAwarePreviousSibling();
-    return toElement(node);
-}
-
-}
-
-namespace NodeTraversal {
-
 Node* nextAncestorSibling(const Node*);
 Node* nextAncestorSibling(const Node*, const Node* stayWithin);
 
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/dom/ParentNode.h
similarity index 64%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/dom/ParentNode.h
index 133dab0..9fb949a 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/dom/ParentNode.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 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,26 +28,36 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#ifndef ParentNode_h
+#define ParentNode_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "core/dom/ContainerNode.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
+class ParentNode {
 public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
+    static PassRefPtr<HTMLCollection> children(ContainerNode* node)
+    {
+        return node->children();
+    }
 
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+    static Element* firstElementChild(ContainerNode* node)
+    {
+        return node->firstElementChild();
+    }
+
+    static Element* lastElementChild(ContainerNode* node)
+    {
+        return node->lastElementChild();
+    }
+
+    static unsigned childElementCount(ContainerNode* node)
+    {
+        return node->childElementCount();
+    }
 };
 
 } // namespace WebCore
 
-#endif
+#endif // ParentNode_h
diff --git a/Source/core/dom/ParentNode.idl b/Source/core/dom/ParentNode.idl
index 358271b..8de54f8 100644
--- a/Source/core/dom/ParentNode.idl
+++ b/Source/core/dom/ParentNode.idl
@@ -1,6 +1,5 @@
 [
     NoInterfaceObject,
-    LegacyImplementedInBaseClass
 ] interface ParentNode {
     [PerWorldBindings] readonly attribute HTMLCollection children;
     [PerWorldBindings] readonly attribute Element firstElementChild;
diff --git a/Source/core/dom/PendingScript.cpp b/Source/core/dom/PendingScript.cpp
index aab3343..6ad05cf 100644
--- a/Source/core/dom/PendingScript.cpp
+++ b/Source/core/dom/PendingScript.cpp
@@ -27,7 +27,7 @@
 #include "core/dom/PendingScript.h"
 
 #include "core/dom/Element.h"
-#include "core/loader/cache/ScriptResource.h"
+#include "core/fetch/ScriptResource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/PendingScript.h b/Source/core/dom/PendingScript.h
index bf902b2..0f169a9 100644
--- a/Source/core/dom/PendingScript.h
+++ b/Source/core/dom/PendingScript.h
@@ -26,8 +26,8 @@
 #ifndef PendingScript_h
 #define PendingScript_h
 
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 #include "wtf/text/TextPosition.h"
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index c71c102..02f46bc 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -844,7 +844,7 @@
 
 bool Position::nodeIsUserSelectNone(Node* node)
 {
-    return node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_NONE && node->renderer()->style()->userModify() == READ_ONLY;
+    return node && node->renderer() && !node->renderer()->isSelectable();
 }
 
 ContainerNode* Position::findParent(const Node* node)
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index def6f8e..033c043 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -27,19 +27,18 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/loader/cache/CSSStyleSheetResource.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/XSLStyleSheetResource.h"
+#include "core/fetch/CSSStyleSheetResource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/XSLStyleSheetResource.h"
 #include "core/xml/XSLStyleSheet.h"
 #include "core/xml/parser/XMLDocumentParser.h" // for parseAttributes()
 
 namespace WebCore {
 
 inline ProcessingInstruction::ProcessingInstruction(Document* document, const String& target, const String& data)
-    : Node(document, CreateOther)
+    : CharacterData(document, data, CreateOther)
     , m_target(target)
-    , m_data(data)
     , m_resource(0)
     , m_loading(false)
     , m_alternate(false)
@@ -67,14 +66,6 @@
         document()->styleSheetCollection()->removeStyleSheetCandidateNode(this);
 }
 
-void ProcessingInstruction::setData(const String& data)
-{
-    int oldLength = m_data.length();
-    m_data = data;
-    document()->textRemoved(this, 0, oldLength);
-    checkStyleSheet();
-}
-
 String ProcessingInstruction::nodeName() const
 {
     return m_target;
@@ -85,16 +76,6 @@
     return PROCESSING_INSTRUCTION_NODE;
 }
 
-String ProcessingInstruction::nodeValue() const
-{
-    return m_data;
-}
-
-void ProcessingInstruction::setNodeValue(const String& nodeValue)
-{
-    setData(nodeValue);
-}
-
 PassRefPtr<Node> ProcessingInstruction::cloneNode(bool /*deep*/)
 {
     // FIXME: Is it a problem that this does not copy m_localHref?
@@ -170,7 +151,7 @@
             else {
                 // The request may have been denied if (for example) the stylesheet is local and the document is remote.
                 m_loading = false;
-                document()->styleSheetCollection()->removePendingSheet();
+                document()->styleSheetCollection()->removePendingSheet(this);
             }
         }
     }
@@ -188,7 +169,7 @@
 bool ProcessingInstruction::sheetLoaded()
 {
     if (!isLoading()) {
-        document()->styleSheetCollection()->removePendingSheet();
+        document()->styleSheetCollection()->removePendingSheet(this);
         return true;
     }
     return false;
@@ -254,16 +235,6 @@
     sheet->setDisabled(m_alternate);
 }
 
-bool ProcessingInstruction::offsetInCharacters() const
-{
-    return true;
-}
-
-int ProcessingInstruction::maxCharacterOffset() const
-{
-    return static_cast<int>(m_data.length());
-}
-
 void ProcessingInstruction::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
 {
     if (!sheet())
@@ -274,7 +245,7 @@
 
 Node::InsertionNotificationRequest ProcessingInstruction::insertedInto(ContainerNode* insertionPoint)
 {
-    Node::insertedInto(insertionPoint);
+    CharacterData::insertedInto(insertionPoint);
     if (!insertionPoint->inDocument())
         return InsertionDone;
     document()->styleSheetCollection()->addStyleSheetCandidateNode(this, m_createdByParser);
@@ -284,7 +255,7 @@
 
 void ProcessingInstruction::removedFrom(ContainerNode* insertionPoint)
 {
-    Node::removedFrom(insertionPoint);
+    CharacterData::removedFrom(insertionPoint);
     if (!insertionPoint->inDocument())
         return;
 
@@ -306,7 +277,7 @@
 void ProcessingInstruction::finishParsingChildren()
 {
     m_createdByParser = false;
-    Node::finishParsingChildren();
+    CharacterData::finishParsingChildren();
 }
 
 } // namespace
diff --git a/Source/core/dom/ProcessingInstruction.h b/Source/core/dom/ProcessingInstruction.h
index 1ae7976..7b216f0 100644
--- a/Source/core/dom/ProcessingInstruction.h
+++ b/Source/core/dom/ProcessingInstruction.h
@@ -22,23 +22,21 @@
 #ifndef ProcessingInstruction_h
 #define ProcessingInstruction_h
 
-#include "core/dom/Node.h"
-#include "core/loader/cache/ResourcePtr.h"
-#include "core/loader/cache/StyleSheetResourceClient.h"
+#include "core/dom/CharacterData.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResourceClient.h"
 
 namespace WebCore {
 
 class StyleSheet;
 class CSSStyleSheet;
 
-class ProcessingInstruction FINAL : public Node, private StyleSheetResourceClient {
+class ProcessingInstruction FINAL : public CharacterData, private StyleSheetResourceClient {
 public:
     static PassRefPtr<ProcessingInstruction> create(Document*, const String& target, const String& data);
     virtual ~ProcessingInstruction();
 
     const String& target() const { return m_target; }
-    const String& data() const { return m_data; }
-    void setData(const String&);
 
     void setCreatedByParser(bool createdByParser) { m_createdByParser = createdByParser; }
 
@@ -54,15 +52,12 @@
     bool isLoading() const;
 
 private:
+    friend class CharacterData;
     ProcessingInstruction(Document*, const String& target, const String& data);
 
     virtual String nodeName() const;
     virtual NodeType nodeType() const;
-    virtual String nodeValue() const;
-    virtual void setNodeValue(const String&);
     virtual PassRefPtr<Node> cloneNode(bool deep = true);
-    virtual bool offsetInCharacters() const;
-    virtual int maxCharacterOffset() const;
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -78,7 +73,6 @@
     void parseStyleSheet(const String& sheet);
 
     String m_target;
-    String m_data;
     String m_localHref;
     String m_title;
     String m_media;
@@ -91,6 +85,12 @@
     bool m_isXSL;
 };
 
+inline ProcessingInstruction* toProcessingInstruction(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::PROCESSING_INSTRUCTION_NODE);
+    return static_cast<ProcessingInstruction*>(node);
+}
+
 } //namespace
 
 #endif
diff --git a/Source/core/dom/ProcessingInstruction.idl b/Source/core/dom/ProcessingInstruction.idl
index 1767ee5..80aace5 100644
--- a/Source/core/dom/ProcessingInstruction.idl
+++ b/Source/core/dom/ProcessingInstruction.idl
@@ -18,12 +18,11 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface ProcessingInstruction : Node {
+interface ProcessingInstruction : CharacterData {
 
     // DOM Level 1
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString target;
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString] attribute DOMString data;
 
     // interface LinkStyle from DOM Level 2 Style Sheets
     readonly attribute StyleSheet sheet;
diff --git a/Source/core/dom/Promise.idl b/Source/core/dom/Promise.idl
index 2550866..d2fa864 100644
--- a/Source/core/dom/Promise.idl
+++ b/Source/core/dom/Promise.idl
@@ -28,6 +28,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+// FIXME: |PromiseValue| should be changed to |Promise|. http://crbug.com/266700
+// IDLs using |Promise| should be written with "typedef any PromiseValue;" and |PromiseValue|.
+
 callback PromiseInit = void (PromiseResolver resolver);
 callback AnyCallback = any (optional any value);
 [
diff --git a/Source/core/dom/QualifiedName.h b/Source/core/dom/QualifiedName.h
index 355ceeb..b42f9e4 100644
--- a/Source/core/dom/QualifiedName.h
+++ b/Source/core/dom/QualifiedName.h
@@ -82,6 +82,8 @@
 
     bool matches(const QualifiedName& other) const { return m_impl == other.m_impl || (localName() == other.localName() && namespaceURI() == other.namespaceURI()); }
 
+    bool matchesPossiblyIgnoringCase(const QualifiedName& other, bool shouldIgnoreCase) const { return m_impl == other.m_impl || (equalPossiblyIgnoringCase(localName(), other.localName(), shouldIgnoreCase) && namespaceURI() == other.namespaceURI()); }
+
     bool hasPrefix() const { return m_impl->m_prefix != nullAtom; }
     void setPrefix(const AtomicString& prefix) { *this = QualifiedName(prefix, localName(), namespaceURI()); }
 
diff --git a/Source/core/dom/ScriptExecutionContext.cpp b/Source/core/dom/ScriptExecutionContext.cpp
index 13191d8..2cc9e4b 100644
--- a/Source/core/dom/ScriptExecutionContext.cpp
+++ b/Source/core/dom/ScriptExecutionContext.cpp
@@ -205,13 +205,13 @@
     if (m_inDispatchErrorEvent) {
         if (!m_pendingExceptions)
             m_pendingExceptions = adoptPtr(new Vector<OwnPtr<PendingException> >());
-        m_pendingExceptions->append(adoptPtr(new PendingException(errorEvent->message(), errorEvent->lineno(), errorEvent->colno(), errorEvent->filename(), callStack)));
+        m_pendingExceptions->append(adoptPtr(new PendingException(errorEvent->messageForConsole(), errorEvent->lineno(), errorEvent->colno(), errorEvent->filename(), callStack)));
         return;
     }
 
     // First report the original exception and only then all the nested ones.
     if (!dispatchErrorEvent(errorEvent, corsStatus))
-        logExceptionToConsole(errorEvent->message(), errorEvent->filename(), errorEvent->lineno(), errorEvent->colno(), callStack);
+        logExceptionToConsole(errorEvent->messageForConsole(), errorEvent->filename(), errorEvent->lineno(), errorEvent->colno(), callStack);
 
     if (!m_pendingExceptions)
         return;
@@ -223,9 +223,14 @@
     m_pendingExceptions.clear();
 }
 
-void ScriptExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state, unsigned long requestIdentifier)
+void ScriptExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber)
 {
-    addMessage(source, level, message, sourceURL, lineNumber, 0, state, requestIdentifier);
+    addMessage(source, level, message, sourceURL, lineNumber, 0);
+}
+
+void ScriptExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, ScriptState* state)
+{
+    addMessage(source, level, message, String(), 0, state);
 }
 
 bool ScriptExecutionContext::dispatchErrorEvent(PassRefPtr<ErrorEvent> event, AccessControlStatus corsStatus)
diff --git a/Source/core/dom/ScriptExecutionContext.h b/Source/core/dom/ScriptExecutionContext.h
index ee4a312..1bcf0ab 100644
--- a/Source/core/dom/ScriptExecutionContext.h
+++ b/Source/core/dom/ScriptExecutionContext.h
@@ -77,8 +77,8 @@
     bool shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus);
     void reportException(PassRefPtr<ErrorEvent>, PassRefPtr<ScriptCallStack>, AccessControlStatus);
 
-    void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* = 0, unsigned long requestIdentifier = 0);
-    virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0) = 0;
+    void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber);
+    void addConsoleMessage(MessageSource, MessageLevel, const String& message, ScriptState* = 0);
 
     PublicURLManager& publicURLManager();
 
@@ -159,7 +159,7 @@
     virtual const KURL& virtualURL() const = 0;
     virtual KURL virtualCompleteURL(const String&) const = 0;
 
-    virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState* = 0, unsigned long requestIdentifier = 0) = 0;
+    virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) = 0;
     virtual EventTarget* errorEventTarget() = 0;
     virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) = 0;
     bool dispatchErrorEvent(PassRefPtr<ErrorEvent>, AccessControlStatus);
diff --git a/Source/core/dom/ScriptLoader.cpp b/Source/core/dom/ScriptLoader.cpp
index 6d1c06b..55d6844 100644
--- a/Source/core/dom/ScriptLoader.cpp
+++ b/Source/core/dom/ScriptLoader.cpp
@@ -35,12 +35,12 @@
 #include "core/dom/ScriptRunner.h"
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/dom/Text.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ScriptResource.h"
 #include "core/html/HTMLImport.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/ScriptResource.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Frame.h"
 #include "core/platform/MIMETypeRegistry.h"
diff --git a/Source/core/dom/ScriptLoader.h b/Source/core/dom/ScriptLoader.h
index 390d83a..dfa8818 100644
--- a/Source/core/dom/ScriptLoader.h
+++ b/Source/core/dom/ScriptLoader.h
@@ -21,8 +21,8 @@
 #ifndef ScriptLoader_h
 #define ScriptLoader_h
 
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "wtf/text/TextPosition.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/dom/ScriptRunner.cpp b/Source/core/dom/ScriptRunner.cpp
index d25001e..f63ab50 100644
--- a/Source/core/dom/ScriptRunner.cpp
+++ b/Source/core/dom/ScriptRunner.cpp
@@ -30,7 +30,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/PendingScript.h"
 #include "core/dom/ScriptLoader.h"
-#include "core/loader/cache/ScriptResource.h"
+#include "core/fetch/ScriptResource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ScriptRunner.h b/Source/core/dom/ScriptRunner.h
index ef9e270..b793589 100644
--- a/Source/core/dom/ScriptRunner.h
+++ b/Source/core/dom/ScriptRunner.h
@@ -26,7 +26,7 @@
 #ifndef ScriptRunner_h
 #define ScriptRunner_h
 
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
diff --git a/Source/core/dom/SelectorQuery.cpp b/Source/core/dom/SelectorQuery.cpp
index 9e99139..db7afdf 100644
--- a/Source/core/dom/SelectorQuery.cpp
+++ b/Source/core/dom/SelectorQuery.cpp
@@ -33,7 +33,7 @@
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/dom/Document.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/StaticNodeList.h"
 
 namespace WebCore {
@@ -490,7 +490,7 @@
     CSSSelectorList selectorList;
     parser.parseSelector(selectors, selectorList);
 
-    if (!selectorList.first() || selectorList.hasInvalidSelector()) {
+    if (!selectorList.first()) {
         es.throwDOMException(SyntaxError);
         return 0;
     }
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
new file mode 100644
index 0000000..2c53a05
--- /dev/null
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * 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/dom/ShadowTreeStyleSheetCollection.h"
+
+#include "HTMLNames.h"
+#include "core/css/CSSStyleSheet.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/Document.h"
+#include "core/dom/DocumentStyleSheetCollection.h"
+#include "core/dom/Element.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/HTMLStyleElement.h"
+#include "core/page/Settings.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+ShadowTreeStyleSheetCollection::ShadowTreeStyleSheetCollection(ShadowRoot* shadowRoot)
+    : StyleSheetCollection(shadowRoot)
+{
+}
+
+void ShadowTreeStyleSheetCollection::collectStyleSheets(DocumentStyleSheetCollection* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+{
+    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) {
+        Node* node = *it;
+        StyleSheet* sheet = 0;
+        CSSStyleSheet* activeSheet = 0;
+
+        if (!node->isHTMLElement() || !node->hasTagName(styleTag))
+            continue;
+
+        Element* element = toElement(node);
+        AtomicString title = element->getAttribute(titleAttr);
+        bool enabledViaScript = false;
+
+        sheet = static_cast<HTMLStyleElement*>(node)->sheet();
+        if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
+            activeSheet = static_cast<CSSStyleSheet*>(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 (element->hasLocalName(styleTag) || !rel.contains("alternate")) {
+                    collections->setPreferredStylesheetSetName(title);
+                    collections->setSelectedStylesheetSetName(title);
+                }
+            }
+            if (title != collections->preferredStylesheetSetName())
+                activeSheet = 0;
+        }
+
+        if (rel.contains("alternate") && title.isEmpty())
+            activeSheet = 0;
+
+        if (sheet)
+            styleSheets.append(sheet);
+        if (activeSheet)
+            activeSheets.append(activeSheet);
+    }
+}
+
+bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(DocumentStyleSheetCollection* collections, StyleResolverUpdateMode updateMode)
+{
+    Vector<RefPtr<StyleSheet> > styleSheets;
+    Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
+    collectStyleSheets(collections, styleSheets, activeCSSStyleSheets);
+
+    bool requiresFullStyleRecalc = true;
+
+    // If we have already decided to destroy StyleResolver, we don't need to analyze. Reconstruction will take care.
+    if (StyleResolver* styleResolver = document()->styleResolverIfExists()) {
+        StyleResolverUpdateType styleResolverUpdateType;
+
+        analyzeStyleSheetChange(updateMode, activeAuthorStyleSheets(), activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
+
+        // 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) {
+            // 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);
+        } else {
+            ASSERT(styleResolverUpdateType == Additive);
+            styleResolver->appendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), activeCSSStyleSheets);
+        }
+    }
+    m_scopingNodesForStyleScoped.didRemoveScopingNodes();
+    m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
+    m_styleSheetsForStyleSheetList.swap(styleSheets);
+    updateUsesRemUnits();
+
+    return requiresFullStyleRecalc;
+}
+
+}
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.h b/Source/core/dom/ShadowTreeStyleSheetCollection.h
new file mode 100644
index 0000000..e398440
--- /dev/null
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * 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.
+ *
+ */
+
+#ifndef ShadowTreeStyleSheetCollection_h
+#define ShadowTreeStyleSheetCollection_h
+
+#include "core/dom/StyleSheetCollection.h"
+
+namespace WebCore {
+
+class CSSStyleSheet;
+class DocumentStyleSheetCollection;
+class ShadowRoot;
+class StyleSheet;
+class StyleSheetCollection;
+
+class ShadowTreeStyleSheetCollection FINAL : public StyleSheetCollection {
+    WTF_MAKE_NONCOPYABLE(ShadowTreeStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
+public:
+    explicit ShadowTreeStyleSheetCollection(ShadowRoot*);
+
+    bool updateActiveStyleSheets(DocumentStyleSheetCollection*, StyleResolverUpdateMode);
+
+private:
+    void collectStyleSheets(DocumentStyleSheetCollection*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+};
+
+}
+
+#endif
+
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 0320d16..8f31ee4 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -127,7 +127,7 @@
     Document* document = e->document();
     if (m_sheet) {
         if (m_sheet->isLoading())
-            document->styleSheetCollection()->removePendingSheet();
+            document->styleSheetCollection()->removePendingSheet(e);
         clearSheet();
     }
 
@@ -169,7 +169,7 @@
     if (isLoading())
         return false;
 
-    document->styleSheetCollection()->removePendingSheet();
+    document->styleSheetCollection()->removePendingSheet(m_sheet->ownerNode());
     return true;
 }
 
diff --git a/Source/core/dom/StyleSheetCollection.cpp b/Source/core/dom/StyleSheetCollection.cpp
index 80ca3d2..a665b80 100644
--- a/Source/core/dom/StyleSheetCollection.cpp
+++ b/Source/core/dom/StyleSheetCollection.cpp
@@ -37,13 +37,11 @@
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
-#include "core/page/Page.h"
-#include "core/page/PageGroup.h"
 #include "core/page/Settings.h"
-#include "core/page/UserContentURLPattern.h"
 #include "core/svg/SVGStyleElement.h"
 
 namespace WebCore {
@@ -86,7 +84,115 @@
         m_scopingNodesForStyleScoped.remove(scopingNode);
 }
 
-void StyleSheetCollection::collectStyleSheets(DocumentStyleSheetCollection* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
+{
+    // Find out which stylesheets are new.
+    unsigned newStylesheetCount = newStylesheets.size();
+    unsigned oldStylesheetCount = oldStyleSheets.size();
+    if (newStylesheetCount < oldStylesheetCount)
+        return Reconstruct;
+
+    unsigned newIndex = 0;
+    for (unsigned oldIndex = 0; oldIndex < oldStylesheetCount; ++oldIndex) {
+        if (newIndex >= newStylesheetCount)
+            return Reconstruct;
+        while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
+            addedSheets.append(newStylesheets[newIndex]->contents());
+            ++newIndex;
+            if (newIndex == newStylesheetCount)
+                return Reconstruct;
+        }
+        ++newIndex;
+    }
+    bool hasInsertions = !addedSheets.isEmpty();
+    while (newIndex < newStylesheetCount) {
+        addedSheets.append(newStylesheets[newIndex]->contents());
+        ++newIndex;
+    }
+    // If all new sheets were added at the end of the list we can just add them to existing StyleResolver.
+    // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly.
+    return hasInsertions ? Reset : Additive;
+}
+
+bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets)
+{
+    // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
+    bool hasActiveLoadingStylesheet = false;
+    unsigned newStylesheetCount = newStyleSheets.size();
+    for (unsigned i = 0; i < newStylesheetCount; ++i) {
+        if (newStyleSheets[i]->isLoading())
+            hasActiveLoadingStylesheet = true;
+    }
+    if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
+        m_hadActiveLoadingStylesheet = false;
+        return true;
+    }
+    m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
+    return false;
+}
+
+void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
+{
+    styleResolverUpdateType = Reconstruct;
+    requiresFullStyleRecalc = true;
+
+    if (activeLoadingStyleSheetLoaded(newStyleSheets))
+        return;
+
+    if (updateMode != AnalyzedStyleUpdate)
+        return;
+    if (!document()->styleResolverIfExists())
+        return;
+
+    // Find out which stylesheets are new.
+    Vector<StyleSheetContents*> addedSheets;
+    styleResolverUpdateType = compareStyleSheets(oldStyleSheets, newStyleSheets, 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())
+        return;
+    StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
+    if (invalidationAnalysis.dirtiesAllStyle())
+        return;
+    invalidationAnalysis.invalidateStyle(document());
+    requiresFullStyleRecalc = false;
+}
+
+void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver)
+{
+    // FIXME: If many web developers use style scoped, implement reset RuleSets in per-scoping node manner.
+    if (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) {
+        for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it)
+            styleResolver->resetAuthorStyle(toContainerNode(*it));
+    }
+    if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) {
+        for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it)
+            styleResolver->resetAuthorStyle(toContainerNode(*it));
+    }
+    styleResolver->resetAuthorStyle(toContainerNode(m_treeScope->rootNode()));
+}
+
+static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets)
+{
+    for (unsigned i = 0; i < sheets.size(); ++i) {
+        if (sheets[i]->contents()->usesRemUnits())
+            return true;
+    }
+    return false;
+}
+
+void StyleSheetCollection::updateUsesRemUnits()
+{
+    m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets);
+}
+
+StyleSheetCollectionForDocument::StyleSheetCollectionForDocument(TreeScope* treeScope)
+    : StyleSheetCollection(treeScope)
+{
+    ASSERT(treeScope->rootNode() == treeScope->rootNode()->document());
+}
+
+void StyleSheetCollectionForDocument::collectStyleSheets(DocumentStyleSheetCollection* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
 {
     if (document()->settings() && !document()->settings()->authorAndUserStylesEnabled())
         return;
@@ -173,80 +279,6 @@
     }
 }
 
-StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
-{
-    // Find out which stylesheets are new.
-    unsigned newStylesheetCount = newStylesheets.size();
-    unsigned oldStylesheetCount = oldStyleSheets.size();
-    if (newStylesheetCount < oldStylesheetCount)
-        return Reconstruct;
-
-    unsigned newIndex = 0;
-    for (unsigned oldIndex = 0; oldIndex < oldStylesheetCount; ++oldIndex) {
-        if (newIndex >= newStylesheetCount)
-            return Reconstruct;
-        while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
-            addedSheets.append(newStylesheets[newIndex]->contents());
-            ++newIndex;
-            if (newIndex == newStylesheetCount)
-                return Reconstruct;
-        }
-        ++newIndex;
-    }
-    bool hasInsertions = !addedSheets.isEmpty();
-    while (newIndex < newStylesheetCount) {
-        addedSheets.append(newStylesheets[newIndex]->contents());
-        ++newIndex;
-    }
-    // If all new sheets were added at the end of the list we can just add them to existing StyleResolver.
-    // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly.
-    return hasInsertions ? Reset : Additive;
-}
-
-bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets)
-{
-    // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
-    bool hasActiveLoadingStylesheet = false;
-    unsigned newStylesheetCount = newStyleSheets.size();
-    for (unsigned i = 0; i < newStylesheetCount; ++i) {
-        if (newStyleSheets[i]->isLoading())
-            hasActiveLoadingStylesheet = true;
-    }
-    if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
-        m_hadActiveLoadingStylesheet = false;
-        return true;
-    }
-    m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
-    return false;
-}
-
-void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
-{
-    styleResolverUpdateType = Reconstruct;
-    requiresFullStyleRecalc = true;
-
-    if (activeLoadingStyleSheetLoaded(newStyleSheets))
-        return;
-
-    if (updateMode != AnalyzedStyleUpdate)
-        return;
-    if (!document()->styleResolverIfExists())
-        return;
-
-    // Find out which stylesheets are new.
-    Vector<StyleSheetContents*> addedSheets;
-    styleResolverUpdateType = compareStyleSheets(oldStyleSheets, newStyleSheets, 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())
-        return;
-    StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
-    if (invalidationAnalysis.dirtiesAllStyle())
-        return;
-    invalidationAnalysis.invalidateStyle(document());
-    requiresFullStyleRecalc = false;
-}
-
 static void collectActiveCSSStyleSheetsFromSeamlessParents(Vector<RefPtr<CSSStyleSheet> >& sheets, Document* document)
 {
     HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
@@ -255,7 +287,7 @@
     sheets.append(seamlessParentIFrame->document()->styleSheetCollection()->activeAuthorStyleSheets());
 }
 
-bool StyleSheetCollection::updateActiveStyleSheets(DocumentStyleSheetCollection* collections, StyleResolverUpdateMode updateMode, StyleResolverUpdateType& styleResolverUpdateType)
+bool StyleSheetCollectionForDocument::updateActiveStyleSheets(DocumentStyleSheetCollection* collections, StyleResolverUpdateMode updateMode)
 {
     Vector<RefPtr<StyleSheet> > styleSheets;
     Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
@@ -264,25 +296,20 @@
     collectActiveCSSStyleSheetsFromSeamlessParents(activeCSSStyleSheets, document());
     collectStyleSheets(collections, styleSheets, activeCSSStyleSheets);
 
+    StyleResolverUpdateType styleResolverUpdateType;
     bool requiresFullStyleRecalc;
     analyzeStyleSheetChange(updateMode, activeAuthorStyleSheets(), activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
 
     if (styleResolverUpdateType == Reconstruct) {
         document()->clearStyleResolver();
     } else {
-        StyleResolver* styleResolver = document()->styleResolver();
-        styleResolver->setBuildScopedStyleTreeInDocumentOrder(!scopingNodesForStyleScoped());
+        StyleResolver* styleResolver = document()->styleResolverIfExists();
+        ASSERT(styleResolver);
+        // 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 (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) {
-                for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it)
-                    styleResolver->resetAuthorStyle(toContainerNode(*it));
-            }
-            if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) {
-                for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it)
-                    styleResolver->resetAuthorStyle(toContainerNode(*it));
-            }
-            ASSERT(m_treeScope->rootNode() == document());
-            styleResolver->resetAuthorStyle(toContainerNode(m_treeScope->rootNode()));
+            resetAllRuleSetsInTreeScope(styleResolver);
             styleResolver->appendAuthorStyleSheets(0, activeCSSStyleSheets);
         } else {
             ASSERT(styleResolverUpdateType == Additive);
@@ -292,6 +319,7 @@
     m_scopingNodesForStyleScoped.didRemoveScopingNodes();
     m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
     m_styleSheetsForStyleSheetList.swap(styleSheets);
+    updateUsesRemUnits();
 
     return requiresFullStyleRecalc;
 }
diff --git a/Source/core/dom/StyleSheetCollection.h b/Source/core/dom/StyleSheetCollection.h
index 91da785..ce41034 100644
--- a/Source/core/dom/StyleSheetCollection.h
+++ b/Source/core/dom/StyleSheetCollection.h
@@ -52,47 +52,63 @@
 class StyleSheetCollection {
     WTF_MAKE_NONCOPYABLE(StyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit StyleSheetCollection(TreeScope*);
-
     void addStyleSheetCandidateNode(Node*, bool createdByParser);
     void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
+    bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
 
     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; }
 
+    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(); }
 
+protected:
+    explicit StyleSheetCollection(TreeScope*);
+
+    Document* document() { return m_treeScope->documentScope(); }
+
     enum StyleResolverUpdateType {
         Reconstruct,
         Reset,
         Additive
     };
-    bool updateActiveStyleSheets(DocumentStyleSheetCollection*, StyleResolverUpdateMode, StyleResolverUpdateType&);
+    void analyzeStyleSheetChange(StyleResolverUpdateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
+    void resetAllRuleSetsInTreeScope(StyleResolver*);
+    void updateUsesRemUnits();
 
 private:
-    Document* document() { return m_treeScope->documentScope(); }
-
-    void collectStyleSheets(DocumentStyleSheetCollection* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
-
     StyleResolverUpdateType compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets);
     bool activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets);
 
-    void analyzeStyleSheetChange(StyleResolverUpdateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
-
+protected:
     Vector<RefPtr<StyleSheet> > m_styleSheetsForStyleSheetList;
     Vector<RefPtr<CSSStyleSheet> > m_activeAuthorStyleSheets;
 
     TreeScope* m_treeScope;
     bool m_hadActiveLoadingStylesheet;
+    bool m_usesRemUnits;
 
     DocumentOrderedList m_styleSheetCandidateNodes;
     StyleSheetScopingNodeList m_scopingNodesForStyleScoped;
 };
 
+// FIXME: rename this class to DocumentStyleSheetCollection.
+class StyleSheetCollectionForDocument FINAL : public StyleSheetCollection {
+    WTF_MAKE_NONCOPYABLE(StyleSheetCollectionForDocument); WTF_MAKE_FAST_ALLOCATED;
+public:
+    explicit StyleSheetCollectionForDocument(TreeScope*);
+
+    bool updateActiveStyleSheets(DocumentStyleSheetCollection*, StyleResolverUpdateMode);
+
+private:
+    void collectStyleSheets(DocumentStyleSheetCollection*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+};
+
 }
 
 #endif
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index 6a7878e..425aabd 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -292,13 +292,16 @@
     return false;
 }
 
-void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData)
+void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, AttachBehavior attachBehavior)
 {
     if (!attached())
         return;
     RenderText* textRenderer = toRenderText(renderer());
     if (!textRenderer || !textRendererIsNeeded(NodeRenderingContext(this, textRenderer->style()))) {
-        reattach();
+        if (attachBehavior == DeprecatedAttachNow)
+            reattach();
+        else
+            lazyReattach();
         return;
     }
     textRenderer->setTextWithOffset(dataImpl(), offsetOfReplacedData, lengthOfReplacedData);
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index 1001eff..33a459a 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -49,7 +49,7 @@
     bool recalcTextStyle(StyleChange);
     bool textRendererIsNeeded(const NodeRenderingContext&);
     virtual RenderText* createTextRenderer(RenderStyle*);
-    void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData);
+    void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, AttachBehavior = AttachLazily);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
 
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index e54c9be..2a4ae34 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -31,9 +31,9 @@
 #include "core/dom/ContainerNode.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/EventPathWalker.h"
 #include "core/dom/IdTargetObserverRegistry.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/dom/TreeScopeAdopter.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
diff --git a/Source/core/dom/ViewportArguments.cpp b/Source/core/dom/ViewportArguments.cpp
index 92ae2cf..0a2708d 100644
--- a/Source/core/dom/ViewportArguments.cpp
+++ b/Source/core/dom/ViewportArguments.cpp
@@ -68,7 +68,7 @@
     return value;
 }
 
-PageScaleConstraints ViewportArguments::resolve(const FloatSize& initialViewportSize, const FloatSize& deviceSize, int defaultWidth) const
+PageScaleConstraints ViewportArguments::resolve(const FloatSize& initialViewportSize, int defaultWidth) const
 {
     float resultWidth = width;
     float resultMaxWidth = maxWidth;
@@ -168,19 +168,19 @@
 
     switch (static_cast<int>(resultWidth)) {
     case ViewportArguments::ValueDeviceWidth:
-        resultWidth = deviceSize.width();
+        resultWidth = initialViewportSize.width();
         break;
     case ViewportArguments::ValueDeviceHeight:
-        resultWidth = deviceSize.height();
+        resultWidth = initialViewportSize.height();
         break;
     }
 
     switch (static_cast<int>(resultHeight)) {
     case ViewportArguments::ValueDeviceWidth:
-        resultHeight = deviceSize.width();
+        resultHeight = initialViewportSize.width();
         break;
     case ViewportArguments::ValueDeviceHeight:
-        resultHeight = deviceSize.height();
+        resultHeight = initialViewportSize.height();
         break;
     }
 
@@ -396,11 +396,12 @@
 static const char* viewportErrorMessageTemplate(ViewportErrorCode errorCode)
 {
     static const char* const errors[] = {
-        "Viewport argument key \"%replacement1\" not recognized and ignored.",
-        "Viewport argument value \"%replacement1\" for key \"%replacement2\" is invalid, and has been ignored.",
-        "Viewport argument value \"%replacement1\" for key \"%replacement2\" was truncated to its numeric prefix.",
-        "Viewport maximum-scale cannot be larger than 10.0. The maximum-scale will be set to 10.0.",
-        "Viewport target-densitydpi is not supported.",
+        "Note that ';' is not a key-value pair separator. The list should be comma-separated.",
+        "The key \"%replacement1\" is not recognized and ignored.",
+        "The value \"%replacement1\" for key \"%replacement2\" is invalid, and has been ignored.",
+        "The value \"%replacement1\" for key \"%replacement2\" was truncated to its numeric prefix.",
+        "The value for key \"maximum-scale\" is out of bounds and the value has been clamped.",
+        "The key \"target-densitydpi\" is not supported.",
     };
 
     return errors[errorCode];
@@ -409,6 +410,7 @@
 static MessageLevel viewportErrorMessageLevel(ViewportErrorCode errorCode)
 {
     switch (errorCode) {
+    case InvalidKeyValuePairSeparatorError:
     case TruncatedViewportArgumentValueError:
     case TargetDensityDpiUnsupported:
         return WarningMessageLevel;
@@ -434,9 +436,6 @@
     if (!replacement2.isNull())
         message.replace("%replacement2", replacement2);
 
-    if ((errorCode == UnrecognizedViewportArgumentValueError || errorCode == TruncatedViewportArgumentValueError) && replacement1.find(';') != WTF::notFound)
-        message.append(" Note that ';' is not a separator in viewport values. The list should be comma-separated.");
-
     // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
     document->addConsoleMessage(RenderingMessageSource, viewportErrorMessageLevel(errorCode), message);
 }
diff --git a/Source/core/dom/ViewportArguments.h b/Source/core/dom/ViewportArguments.h
index 5afacfe..6533441 100644
--- a/Source/core/dom/ViewportArguments.h
+++ b/Source/core/dom/ViewportArguments.h
@@ -37,6 +37,7 @@
 class Document;
 
 enum ViewportErrorCode {
+    InvalidKeyValuePairSeparatorError,
     UnrecognizedViewportArgumentKeyError,
     UnrecognizedViewportArgumentValueError,
     TruncatedViewportArgumentValueError,
@@ -87,7 +88,7 @@
     }
 
     // All arguments are in CSS units.
-    PageScaleConstraints resolve(const FloatSize& initialViewportSize, const FloatSize& deviceSize, int defaultWidth) const;
+    PageScaleConstraints resolve(const FloatSize& initialViewportSize, int defaultWidth) const;
 
     float width;
     float minWidth;
diff --git a/Source/core/dom/VisitedLinkState.cpp b/Source/core/dom/VisitedLinkState.cpp
index 77e8fd1..cf1d417 100644
--- a/Source/core/dom/VisitedLinkState.cpp
+++ b/Source/core/dom/VisitedLinkState.cpp
@@ -30,7 +30,7 @@
 #include "core/dom/VisitedLinkState.h"
 
 #include "HTMLNames.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/page/Page.h"
 #include "public/platform/Platform.h"
diff --git a/Source/core/dom/WheelEvent.cpp b/Source/core/dom/WheelEvent.cpp
index c7bdf0d..bcb3d69 100644
--- a/Source/core/dom/WheelEvent.cpp
+++ b/Source/core/dom/WheelEvent.cpp
@@ -3,6 +3,7 @@
  * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
  * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
  * Copyright (C) 2003, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. 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
@@ -29,15 +30,29 @@
 
 namespace WebCore {
 
+static inline double wheelTicksToPixels(double ticks)
+{
+    // Make sure we use +0 for all zeros.
+    if (!ticks)
+        return 0;
+    return -ticks * WheelEvent::TickMultiplier;
+}
+
 WheelEventInit::WheelEventInit()
-    : wheelDeltaX(0)
+    : deltaX(0)
+    , deltaY(0)
+    , deltaZ(0)
+    , wheelDeltaX(0)
     , wheelDeltaY(0)
     , deltaMode(WheelEvent::DOM_DELTA_PIXEL)
 {
 }
 
 WheelEvent::WheelEvent()
-    : m_deltaMode(DOM_DELTA_PIXEL)
+    : m_deltaX(0)
+    , m_deltaY(0)
+    , m_deltaZ(0)
+    , m_deltaMode(DOM_DELTA_PIXEL)
     , m_directionInvertedFromDevice(false)
 {
     ScriptWrappable::init(this);
@@ -45,7 +60,9 @@
 
 WheelEvent::WheelEvent(const AtomicString& type, const WheelEventInit& initializer)
     : MouseEvent(type, initializer)
-    , m_wheelDelta(IntPoint(initializer.wheelDeltaX, initializer.wheelDeltaY))
+    , m_deltaX(initializer.deltaX ? initializer.deltaX : -initializer.wheelDeltaX)
+    , m_deltaY(initializer.deltaY ? initializer.deltaY : -initializer.wheelDeltaY)
+    , m_deltaZ(initializer.deltaZ)
     , m_deltaMode(initializer.deltaMode)
 {
     ScriptWrappable::init(this);
@@ -54,12 +71,14 @@
 WheelEvent::WheelEvent(const FloatPoint& wheelTicks, const FloatPoint& rawDelta, unsigned deltaMode,
     PassRefPtr<AbstractView> view, const IntPoint& screenLocation, const IntPoint& pageLocation,
     bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice)
-    : MouseEvent(eventNames().mousewheelEvent,
+    : MouseEvent(eventNames().wheelEvent,
                  true, true, view, 0, screenLocation.x(), screenLocation.y(),
                  pageLocation.x(), pageLocation.y(),
                  0, 0,
                  ctrlKey, altKey, shiftKey, metaKey, 0, 0, 0, false)
-    , m_wheelDelta(IntPoint(static_cast<int>(wheelTicks.x() * TickMultiplier), static_cast<int>(wheelTicks.y() * TickMultiplier)))
+    , m_deltaX(wheelTicksToPixels(wheelTicks.x()))
+    , m_deltaY(wheelTicksToPixels(wheelTicks.y()))
+    , m_deltaZ(0) // FIXME: Not supported.
     , m_rawDelta(roundedIntPoint(rawDelta))
     , m_deltaMode(deltaMode)
     , m_directionInvertedFromDevice(directionInvertedFromDevice)
@@ -74,7 +93,7 @@
     if (dispatched())
         return;
 
-    initUIEvent(eventNames().mousewheelEvent, true, true, view, 0);
+    initUIEvent(eventNames().wheelEvent, true, true, view, 0);
 
     m_screenLocation = IntPoint(screenX, screenY);
     m_ctrlKey = ctrlKey;
@@ -82,9 +101,8 @@
     m_shiftKey = shiftKey;
     m_metaKey = metaKey;
 
-    // Normalize to the Windows 120 multiple
-    m_wheelDelta = IntPoint(rawDeltaX * TickMultiplier, rawDeltaY * TickMultiplier);
-
+    m_deltaX = wheelTicksToPixels(rawDeltaX);
+    m_deltaY = wheelTicksToPixels(rawDeltaY);
     m_rawDelta = IntPoint(rawDeltaX, rawDeltaY);
     m_deltaMode = DOM_DELTA_PIXEL;
     m_directionInvertedFromDevice = false;
diff --git a/Source/core/dom/WheelEvent.h b/Source/core/dom/WheelEvent.h
index ba17ab4..870c9b6 100644
--- a/Source/core/dom/WheelEvent.h
+++ b/Source/core/dom/WheelEvent.h
@@ -3,6 +3,7 @@
  * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
  * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
  * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. 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
@@ -35,8 +36,11 @@
 struct WheelEventInit : public MouseEventInit {
     WheelEventInit();
 
-    int wheelDeltaX;
-    int wheelDeltaY;
+    double deltaX;
+    double deltaY;
+    double deltaZ;
+    int wheelDeltaX; // Deprecated.
+    int wheelDeltaY; // Deprecated.
     unsigned deltaMode;
 };
 
@@ -77,9 +81,12 @@
         int screenX, int screenY, int pageX, int pageY,
         bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
 
-    int wheelDelta() const { return m_wheelDelta.y() ? m_wheelDelta.y() : m_wheelDelta.x(); }
-    int wheelDeltaX() const { return m_wheelDelta.x(); }
-    int wheelDeltaY() const { return m_wheelDelta.y(); }
+    double deltaX() const { return m_deltaX; } // Positive when scrolling right.
+    double deltaY() const { return m_deltaY; } // Positive when scrolling down.
+    double deltaZ() const { return m_deltaZ; }
+    int wheelDelta() const { return wheelDeltaY() ? wheelDeltaY() : wheelDeltaX(); } // Deprecated.
+    int wheelDeltaX() const { return -m_deltaX; } // Deprecated, negative when scrolling right.
+    int wheelDeltaY() const { return -m_deltaY; } // Deprecated, negative when scrolling down.
     int rawDeltaX() const { return m_rawDelta.x(); }
     int rawDeltaY() const { return m_rawDelta.y(); }
     unsigned deltaMode() const { return m_deltaMode; }
@@ -96,7 +103,9 @@
         unsigned, PassRefPtr<AbstractView>, const IntPoint& screenLocation, const IntPoint& pageLocation,
         bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice);
 
-    IntPoint m_wheelDelta;
+    double m_deltaX;
+    double m_deltaY;
+    double m_deltaZ;
     IntPoint m_rawDelta;
     unsigned m_deltaMode;
     bool m_directionInvertedFromDevice;
diff --git a/Source/core/dom/WheelEvent.idl b/Source/core/dom/WheelEvent.idl
index 9dc0e4a..8ee63ae 100644
--- a/Source/core/dom/WheelEvent.idl
+++ b/Source/core/dom/WheelEvent.idl
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2006, 2007, 2010 Apple Inc. All rights reserved.
  * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ * Copyright (C) 2013 Samsung Electronics. 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
@@ -18,17 +19,23 @@
  * Boston, MA 02110-1301, USA.
  */
 
+// Introduced in DOM Level 3:
 [
     ConstructorTemplate=Event
 ] interface WheelEvent : MouseEvent {
+    // DeltaModeCode
     const unsigned long              DOM_DELTA_PIXEL = 0x00;
     const unsigned long              DOM_DELTA_LINE  = 0x01;
     const unsigned long              DOM_DELTA_PAGE  = 0x02;
 
-    [InitializedByEventConstructor] readonly attribute long wheelDeltaX;
-    [InitializedByEventConstructor] readonly attribute long wheelDeltaY;
+    [InitializedByEventConstructor] readonly attribute double deltaX;
+    [InitializedByEventConstructor] readonly attribute double deltaY;
+    [InitializedByEventConstructor] readonly attribute double deltaZ;
     [InitializedByEventConstructor] readonly attribute unsigned long deltaMode;
 
+    // Non standard API.
+    [InitializedByEventConstructor] readonly attribute long wheelDeltaX;
+    [InitializedByEventConstructor] readonly attribute long wheelDeltaY;
     readonly attribute long wheelDelta;
 
     // WebKit Extension
diff --git a/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp b/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
index c5a64fa..80ff995 100644
--- a/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
@@ -29,7 +29,6 @@
 #include "core/dom/shadow/ComposedShadowTreeWalker.h"
 
 #include "core/dom/Element.h"
-#include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
 
diff --git a/Source/core/dom/shadow/ContentDistribution.cpp b/Source/core/dom/shadow/ContentDistribution.cpp
new file mode 100644
index 0000000..405ce56
--- /dev/null
+++ b/Source/core/dom/shadow/ContentDistribution.cpp
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+#include "config.h"
+#include "core/dom/shadow/ContentDistribution.h"
+
+namespace WebCore {
+
+void ContentDistribution::swap(ContentDistribution& other)
+{
+    m_nodes.swap(other.m_nodes);
+    m_indices.swap(other.m_indices);
+}
+
+void ContentDistribution::append(PassRefPtr<Node> node)
+{
+    size_t size = m_nodes.size();
+    m_indices.set(node.get(), size);
+    m_nodes.append(node);
+}
+
+size_t ContentDistribution::find(const Node* node) const
+{
+    HashMap<const Node*, size_t>::const_iterator it = m_indices.find(node);
+    if (it == m_indices.end())
+        return notFound;
+
+    return it.get()->value;
+}
+
+Node* ContentDistribution::nextTo(const Node* node) const
+{
+    size_t index = find(node);
+    if (index == notFound || index + 1 == size())
+        return 0;
+    return at(index + 1).get();
+}
+
+Node* ContentDistribution::previousTo(const Node* node) const
+{
+    size_t index = find(node);
+    if (index == notFound || !index)
+        return 0;
+    return at(index - 1).get();
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/shadow/ContentDistribution.h b/Source/core/dom/shadow/ContentDistribution.h
new file mode 100644
index 0000000..2fd8fc1
--- /dev/null
+++ b/Source/core/dom/shadow/ContentDistribution.h
@@ -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.
+ */
+
+#ifndef ContentDistribution_h
+#define ContentDistribution_h
+
+#include "core/dom/Node.h"
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class ContentDistribution {
+public:
+    PassRefPtr<Node> first() const { return m_nodes.first(); }
+    PassRefPtr<Node> last() const { return m_nodes.last(); }
+    PassRefPtr<Node> at(size_t index) const { return m_nodes.at(index); }
+
+    size_t size() const { return m_nodes.size(); }
+    bool isEmpty() const { return m_nodes.isEmpty(); }
+
+    void append(PassRefPtr<Node>);
+    void clear() { m_nodes.clear(); m_indices.clear(); }
+
+    bool contains(const Node* node) const { return m_indices.contains(node); }
+    size_t find(const Node*) const;
+    Node* nextTo(const Node*) const;
+    Node* previousTo(const Node*) const;
+
+    void swap(ContentDistribution& other);
+
+    const Vector<RefPtr<Node> >& nodes() const { return m_nodes; }
+
+private:
+    Vector<RefPtr<Node> > m_nodes;
+    HashMap<const Node*, size_t> m_indices;
+};
+
+}
+
+#endif
diff --git a/Source/core/dom/shadow/ContentDistributor.cpp b/Source/core/dom/shadow/ContentDistributor.cpp
deleted file mode 100644
index 9bbccdc..0000000
--- a/Source/core/dom/shadow/ContentDistributor.cpp
+++ /dev/null
@@ -1,337 +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.
- *     * 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/shadow/ContentDistributor.h"
-
-#include "core/dom/NodeTraversal.h"
-#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/shadow/HTMLContentElement.h"
-#include "core/html/shadow/HTMLShadowElement.h"
-
-
-namespace WebCore {
-
-void ContentDistribution::swap(ContentDistribution& other)
-{
-    m_nodes.swap(other.m_nodes);
-    m_indices.swap(other.m_indices);
-}
-
-void ContentDistribution::append(PassRefPtr<Node> node)
-{
-    size_t size = m_nodes.size();
-    m_indices.set(node.get(), size);
-    m_nodes.append(node);
-}
-
-size_t ContentDistribution::find(const Node* node) const
-{
-    HashMap<const Node*, size_t>::const_iterator it = m_indices.find(node);
-    if (it == m_indices.end())
-        return notFound;
-
-    return it.get()->value;
-}
-
-Node* ContentDistribution::nextTo(const Node* node) const
-{
-    size_t index = find(node);
-    if (index == notFound || index + 1 == size())
-        return 0;
-    return at(index + 1).get();
-}
-
-Node* ContentDistribution::previousTo(const Node* node) const
-{
-    size_t index = find(node);
-    if (index == notFound || !index)
-        return 0;
-    return at(index - 1).get();
-}
-
-
-ScopeContentDistribution::ScopeContentDistribution()
-    : m_insertionPointAssignedTo(0)
-    , m_numberOfShadowElementChildren(0)
-    , m_numberOfContentElementChildren(0)
-    , m_numberOfElementShadowChildren(0)
-    , m_insertionPointListIsValid(false)
-{
-}
-
-void ScopeContentDistribution::setInsertionPointAssignedTo(PassRefPtr<InsertionPoint> insertionPoint)
-{
-    m_insertionPointAssignedTo = insertionPoint;
-}
-
-void ScopeContentDistribution::invalidateInsertionPointList()
-{
-    m_insertionPointListIsValid = false;
-    m_insertionPointList.clear();
-}
-
-const Vector<RefPtr<InsertionPoint> >& ScopeContentDistribution::ensureInsertionPointList(ShadowRoot* shadowRoot)
-{
-    if (m_insertionPointListIsValid)
-        return m_insertionPointList;
-
-    m_insertionPointListIsValid = true;
-    ASSERT(m_insertionPointList.isEmpty());
-
-    if (!shadowRoot->containsInsertionPoints())
-        return m_insertionPointList;
-
-    for (Element* element = ElementTraversal::firstWithin(shadowRoot); element; element = ElementTraversal::next(element, shadowRoot)) {
-        if (element->isInsertionPoint())
-            m_insertionPointList.append(toInsertionPoint(element));
-    }
-
-    return m_insertionPointList;
-}
-
-void ScopeContentDistribution::registerInsertionPoint(InsertionPoint* point)
-{
-    if (isHTMLShadowElement(point))
-        ++m_numberOfShadowElementChildren;
-    else if (isHTMLContentElement(point))
-        ++m_numberOfContentElementChildren;
-    else
-        ASSERT_NOT_REACHED();
-
-    invalidateInsertionPointList();
-}
-
-void ScopeContentDistribution::unregisterInsertionPoint(InsertionPoint* point)
-{
-    if (isHTMLShadowElement(point))
-        --m_numberOfShadowElementChildren;
-    else if (isHTMLContentElement(point))
-        --m_numberOfContentElementChildren;
-    else
-        ASSERT_NOT_REACHED();
-
-    ASSERT(m_numberOfContentElementChildren >= 0);
-    ASSERT(m_numberOfShadowElementChildren >= 0);
-
-    invalidateInsertionPointList();
-}
-
-ContentDistributor::ContentDistributor()
-    : m_needsSelectFeatureSet(false)
-{
-}
-
-ContentDistributor::~ContentDistributor()
-{
-}
-
-InsertionPoint* ContentDistributor::findInsertionPointFor(const Node* key) const
-{
-    return m_nodeToInsertionPoint.get(key);
-}
-
-void ContentDistributor::populate(Node* node, Vector<Node*>& pool)
-{
-    node->lazyReattachIfAttached();
-
-    if (!isActiveInsertionPoint(node)) {
-        pool.append(node);
-        return;
-    }
-
-    InsertionPoint* insertionPoint = toInsertionPoint(node);
-    if (insertionPoint->hasDistribution()) {
-        for (size_t i = 0; i < insertionPoint->size(); ++i)
-            populate(insertionPoint->at(i), pool);
-    } else {
-        for (Node* fallbackNode = insertionPoint->firstChild(); fallbackNode; fallbackNode = fallbackNode->nextSibling())
-            pool.append(fallbackNode);
-    }
-}
-
-void ContentDistributor::distribute(Element* host)
-{
-    Vector<Node*> pool;
-    for (Node* node = host->firstChild(); node; node = node->nextSibling())
-        populate(node, pool);
-
-    host->setNeedsStyleRecalc();
-
-    Vector<bool> distributed(pool.size());
-    distributed.fill(false);
-
-    Vector<HTMLShadowElement*, 8> activeShadowInsertionPoints;
-    for (ShadowRoot* root = host->youngestShadowRoot(); root; root = root->olderShadowRoot()) {
-        HTMLShadowElement* firstActiveShadowInsertionPoint = 0;
-
-        if (ScopeContentDistribution* scope = root->scopeDistribution()) {
-            const Vector<RefPtr<InsertionPoint> >& insertionPoints = scope->ensureInsertionPointList(root);
-            for (size_t i = 0; i < insertionPoints.size(); ++i) {
-                InsertionPoint* point = insertionPoints[i].get();
-                if (!point->isActive())
-                    continue;
-
-                if (isHTMLShadowElement(point)) {
-                    if (!firstActiveShadowInsertionPoint)
-                        firstActiveShadowInsertionPoint = toHTMLShadowElement(point);
-                } else {
-                    distributeSelectionsTo(point, pool, distributed);
-                    if (ElementShadow* shadow = shadowOfParentForDistribution(point))
-                        shadow->setNeedsDistributionRecalc();
-                }
-            }
-        }
-
-        if (firstActiveShadowInsertionPoint)
-            activeShadowInsertionPoints.append(firstActiveShadowInsertionPoint);
-    }
-
-    for (size_t i = activeShadowInsertionPoints.size(); i > 0; --i) {
-        HTMLShadowElement* shadowElement = activeShadowInsertionPoints[i - 1];
-        ShadowRoot* root = shadowElement->containingShadowRoot();
-        ASSERT(root);
-        if (!shadowElement->shouldSelect()) {
-            if (root->olderShadowRoot())
-                root->olderShadowRoot()->ensureScopeDistribution()->setInsertionPointAssignedTo(shadowElement);
-        } else if (root->olderShadowRoot()) {
-            distributeNodeChildrenTo(shadowElement, root->olderShadowRoot());
-            root->olderShadowRoot()->ensureScopeDistribution()->setInsertionPointAssignedTo(shadowElement);
-        } else {
-            distributeSelectionsTo(shadowElement, pool, distributed);
-        }
-        if (ElementShadow* shadow = shadowOfParentForDistribution(shadowElement))
-            shadow->setNeedsDistributionRecalc();
-    }
-}
-
-void ContentDistributor::distributeSelectionsTo(InsertionPoint* insertionPoint, const Vector<Node*>& pool, Vector<bool>& distributed)
-{
-    ContentDistribution distribution;
-
-    for (size_t i = 0; i < pool.size(); ++i) {
-        if (distributed[i])
-            continue;
-
-        if (isHTMLContentElement(insertionPoint) && !toHTMLContentElement(insertionPoint)->canSelectNode(pool, i))
-            continue;
-
-        Node* child = pool[i];
-        distribution.append(child);
-        m_nodeToInsertionPoint.add(child, insertionPoint);
-        distributed[i] = true;
-    }
-
-    insertionPoint->lazyReattachIfAttached();
-    insertionPoint->setDistribution(distribution);
-}
-
-void ContentDistributor::distributeNodeChildrenTo(InsertionPoint* insertionPoint, ContainerNode* containerNode)
-{
-    ContentDistribution distribution;
-    for (Node* node = containerNode->firstChild(); node; node = node->nextSibling()) {
-        node->lazyReattachIfAttached();
-        if (isActiveInsertionPoint(node)) {
-            InsertionPoint* innerInsertionPoint = toInsertionPoint(node);
-            if (innerInsertionPoint->hasDistribution()) {
-                for (size_t i = 0; i < innerInsertionPoint->size(); ++i) {
-                    distribution.append(innerInsertionPoint->at(i));
-                    m_nodeToInsertionPoint.add(innerInsertionPoint->at(i), insertionPoint);
-                }
-            } else {
-                for (Node* child = innerInsertionPoint->firstChild(); child; child = child->nextSibling()) {
-                    distribution.append(child);
-                    m_nodeToInsertionPoint.add(child, insertionPoint);
-                }
-            }
-        } else {
-            distribution.append(node);
-            m_nodeToInsertionPoint.add(node, insertionPoint);
-        }
-    }
-
-    insertionPoint->lazyReattachIfAttached();
-    insertionPoint->setDistribution(distribution);
-}
-
-const SelectRuleFeatureSet& ContentDistributor::ensureSelectFeatureSet(ElementShadow* shadow)
-{
-    if (!m_needsSelectFeatureSet)
-        return m_selectFeatures;
-
-    m_selectFeatures.clear();
-    for (ShadowRoot* root = shadow->oldestShadowRoot(); root; root = root->youngerShadowRoot())
-        collectSelectFeatureSetFrom(root);
-    m_needsSelectFeatureSet = false;
-    return m_selectFeatures;
-}
-
-void ContentDistributor::collectSelectFeatureSetFrom(ShadowRoot* root)
-{
-    if (!root->containsShadowRoots() && !root->containsContentElements())
-        return;
-
-    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))
-            continue;
-        const CSSSelectorList& list = toHTMLContentElement(element)->selectorList();
-        for (const CSSSelector* selector = list.first(); selector; selector = CSSSelectorList::next(selector)) {
-            for (const CSSSelector* component = selector; component; component = component->tagHistory())
-                m_selectFeatures.collectFeaturesFromSelector(component);
-        }
-    }
-}
-
-void ContentDistributor::didAffectSelector(Element* host, AffectedSelectorMask mask)
-{
-    if (ensureSelectFeatureSet(host->shadow()).hasSelectorFor(mask))
-        host->shadow()->setNeedsDistributionRecalc();
-}
-
-void ContentDistributor::willAffectSelector(Element* host)
-{
-    for (ElementShadow* shadow = host->shadow(); shadow; shadow = shadow->containingShadow()) {
-        if (shadow->distributor().needsSelectFeatureSet())
-            break;
-        shadow->distributor().setNeedsSelectFeatureSet();
-    }
-    host->shadow()->setNeedsDistributionRecalc();
-}
-
-void ContentDistributor::clearDistribution(Element* host)
-{
-    m_nodeToInsertionPoint.clear();
-
-    for (ShadowRoot* root = host->youngestShadowRoot(); root; root = root->olderShadowRoot()) {
-        if (ScopeContentDistribution* scope = root->scopeDistribution())
-            scope->setInsertionPointAssignedTo(0);
-    }
-}
-
-}
diff --git a/Source/core/dom/shadow/ContentDistributor.h b/Source/core/dom/shadow/ContentDistributor.h
deleted file mode 100644
index e98b40b..0000000
--- a/Source/core/dom/shadow/ContentDistributor.h
+++ /dev/null
@@ -1,135 +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 ContentDistributor_h
-#define ContentDistributor_h
-
-#include "core/dom/shadow/SelectRuleFeatureSet.h"
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class ContainerNode;
-class Element;
-class InsertionPoint;
-class Node;
-class ShadowRoot;
-
-class ContentDistribution {
-public:
-    PassRefPtr<Node> first() const { return m_nodes.first(); }
-    PassRefPtr<Node> last() const { return m_nodes.last(); }
-    PassRefPtr<Node> at(size_t index) const { return m_nodes.at(index); }
-
-    size_t size() const { return m_nodes.size(); }
-    bool isEmpty() const { return m_nodes.isEmpty(); }
-
-    void append(PassRefPtr<Node>);
-    void clear() { m_nodes.clear(); m_indices.clear(); }
-
-    bool contains(const Node* node) const { return m_indices.contains(node); }
-    size_t find(const Node*) const;
-    Node* nextTo(const Node*) const;
-    Node* previousTo(const Node*) const;
-
-    void swap(ContentDistribution& other);
-
-    const Vector<RefPtr<Node> >& nodes() const { return m_nodes; }
-
-private:
-    Vector<RefPtr<Node> > m_nodes;
-    HashMap<const Node*, size_t> m_indices;
-};
-
-class ScopeContentDistribution {
-public:
-    ScopeContentDistribution();
-
-    InsertionPoint* insertionPointAssignedTo() const { return m_insertionPointAssignedTo.get(); }
-    void setInsertionPointAssignedTo(PassRefPtr<InsertionPoint>);
-
-    void registerInsertionPoint(InsertionPoint*);
-    void unregisterInsertionPoint(InsertionPoint*);
-    bool hasShadowElementChildren() const { return m_numberOfShadowElementChildren > 0; }
-    bool hasContentElementChildren() const { return m_numberOfContentElementChildren > 0; }
-
-    void registerElementShadow() { ++m_numberOfElementShadowChildren; }
-    void unregisterElementShadow() { ASSERT(m_numberOfElementShadowChildren > 0); --m_numberOfElementShadowChildren; }
-    unsigned numberOfElementShadowChildren() const { return m_numberOfElementShadowChildren; }
-    bool hasElementShadowChildren() const { return m_numberOfElementShadowChildren > 0; }
-
-    void invalidateInsertionPointList();
-    const Vector<RefPtr<InsertionPoint> >& ensureInsertionPointList(ShadowRoot*);
-
-private:
-    RefPtr<InsertionPoint> m_insertionPointAssignedTo;
-    unsigned m_numberOfShadowElementChildren;
-    unsigned m_numberOfContentElementChildren;
-    unsigned m_numberOfElementShadowChildren;
-    bool m_insertionPointListIsValid;
-    Vector<RefPtr<InsertionPoint> > m_insertionPointList;
-};
-
-class ContentDistributor {
-    WTF_MAKE_NONCOPYABLE(ContentDistributor);
-public:
-    ContentDistributor();
-    ~ContentDistributor();
-
-    InsertionPoint* findInsertionPointFor(const Node* key) const;
-    const SelectRuleFeatureSet& ensureSelectFeatureSet(ElementShadow*);
-
-    void distributeSelectionsTo(InsertionPoint*, const Vector<Node*>& pool, Vector<bool>& distributed);
-    void distributeNodeChildrenTo(InsertionPoint*, ContainerNode*);
-
-    void didAffectSelector(Element* host, AffectedSelectorMask);
-    void willAffectSelector(Element* host);
-
-    void distribute(Element* host);
-    void clearDistribution(Element* host);
-
-private:
-    void populate(Node*, Vector<Node*>&);
-
-    void collectSelectFeatureSetFrom(ShadowRoot*);
-    bool needsSelectFeatureSet() const { return m_needsSelectFeatureSet; }
-    void setNeedsSelectFeatureSet() { m_needsSelectFeatureSet = true; }
-
-    typedef HashMap<const Node*, RefPtr<InsertionPoint> > NodeInsertionPointMap;
-    NodeInsertionPointMap m_nodeToInsertionPoint;
-    SelectRuleFeatureSet m_selectFeatures;
-    bool m_needsSelectFeatureSet;
-};
-
-}
-
-#endif
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 380a5f7..b6eef01 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -28,9 +28,34 @@
 #include "core/dom/shadow/ElementShadow.h"
 
 #include "core/dom/ContainerNodeAlgorithms.h"
+#include "core/dom/ElementTraversal.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/dom/shadow/ContentDistribution.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ScopeContentDistribution.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/shadow/HTMLContentElement.h"
+#include "core/html/shadow/HTMLShadowElement.h"
 
 namespace WebCore {
 
+PassOwnPtr<ElementShadow> ElementShadow::create()
+{
+    return adoptPtr(new ElementShadow());
+}
+
+ElementShadow::ElementShadow()
+    : m_needsDistributionRecalc(false)
+    , m_applyAuthorStyles(false)
+    , m_needsSelectFeatureSet(false)
+{
+}
+
+ElementShadow::~ElementShadow()
+{
+    removeAllShadowRoots();
+}
+
 ShadowRoot* ElementShadow::addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType type)
 {
     RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(shadowHost->document(), type);
@@ -146,4 +171,191 @@
     return false;
 }
 
+InsertionPoint* ElementShadow::findInsertionPointFor(const Node* key) const
+{
+    return m_nodeToInsertionPoint.get(key);
+}
+
+void ElementShadow::populate(Node* node, Vector<Node*>& pool)
+{
+    if (!isActiveInsertionPoint(node)) {
+        pool.append(node);
+        return;
+    }
+
+    InsertionPoint* insertionPoint = toInsertionPoint(node);
+    if (insertionPoint->hasDistribution()) {
+        for (size_t i = 0; i < insertionPoint->size(); ++i)
+            populate(insertionPoint->at(i), pool);
+    } else {
+        for (Node* fallbackNode = insertionPoint->firstChild(); fallbackNode; fallbackNode = fallbackNode->nextSibling())
+            pool.append(fallbackNode);
+    }
+}
+
+void ElementShadow::distribute()
+{
+    Vector<Node*> pool;
+    for (Node* node = host()->firstChild(); node; node = node->nextSibling())
+        populate(node, pool);
+
+    host()->setNeedsStyleRecalc();
+
+    Vector<bool> distributed(pool.size());
+    distributed.fill(false);
+
+    Vector<HTMLShadowElement*, 8> activeShadowInsertionPoints;
+    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
+        HTMLShadowElement* firstActiveShadowInsertionPoint = 0;
+
+        if (ScopeContentDistribution* scope = root->scopeDistribution()) {
+            const Vector<RefPtr<InsertionPoint> >& insertionPoints = scope->ensureInsertionPointList(root);
+            for (size_t i = 0; i < insertionPoints.size(); ++i) {
+                InsertionPoint* point = insertionPoints[i].get();
+                if (!point->isActive())
+                    continue;
+
+                if (isHTMLShadowElement(point)) {
+                    if (!firstActiveShadowInsertionPoint)
+                        firstActiveShadowInsertionPoint = toHTMLShadowElement(point);
+                } else {
+                    distributeSelectionsTo(point, pool, distributed);
+                    if (ElementShadow* shadow = shadowOfParentForDistribution(point))
+                        shadow->setNeedsDistributionRecalc();
+                }
+            }
+        }
+
+        if (firstActiveShadowInsertionPoint)
+            activeShadowInsertionPoints.append(firstActiveShadowInsertionPoint);
+    }
+
+    for (size_t i = activeShadowInsertionPoints.size(); i > 0; --i) {
+        HTMLShadowElement* shadowElement = activeShadowInsertionPoints[i - 1];
+        ShadowRoot* root = shadowElement->containingShadowRoot();
+        ASSERT(root);
+        if (!shadowElement->shouldSelect()) {
+            if (root->olderShadowRoot())
+                root->olderShadowRoot()->ensureScopeDistribution()->setInsertionPointAssignedTo(shadowElement);
+        } else if (root->olderShadowRoot()) {
+            distributeNodeChildrenTo(shadowElement, root->olderShadowRoot());
+            root->olderShadowRoot()->ensureScopeDistribution()->setInsertionPointAssignedTo(shadowElement);
+        } else {
+            distributeSelectionsTo(shadowElement, pool, distributed);
+        }
+        if (ElementShadow* shadow = shadowOfParentForDistribution(shadowElement))
+            shadow->setNeedsDistributionRecalc();
+    }
+
+    // Detach all nodes that were not distributed and have a renderer.
+    for (size_t i = 0; i < pool.size(); ++i) {
+        if (distributed[i])
+            continue;
+        if (pool[i]->renderer())
+            pool[i]->lazyReattachIfAttached();
+    }
+}
+
+void ElementShadow::distributeSelectionsTo(InsertionPoint* insertionPoint, const Vector<Node*>& pool, Vector<bool>& distributed)
+{
+    ContentDistribution distribution;
+
+    for (size_t i = 0; i < pool.size(); ++i) {
+        if (distributed[i])
+            continue;
+
+        if (isHTMLContentElement(insertionPoint) && !toHTMLContentElement(insertionPoint)->canSelectNode(pool, i))
+            continue;
+
+        Node* child = pool[i];
+        distribution.append(child);
+        m_nodeToInsertionPoint.add(child, insertionPoint);
+        distributed[i] = true;
+    }
+
+    insertionPoint->setDistribution(distribution);
+}
+
+void ElementShadow::distributeNodeChildrenTo(InsertionPoint* insertionPoint, ContainerNode* containerNode)
+{
+    ContentDistribution distribution;
+    for (Node* node = containerNode->firstChild(); node; node = node->nextSibling()) {
+        if (isActiveInsertionPoint(node)) {
+            InsertionPoint* innerInsertionPoint = toInsertionPoint(node);
+            if (innerInsertionPoint->hasDistribution()) {
+                for (size_t i = 0; i < innerInsertionPoint->size(); ++i) {
+                    distribution.append(innerInsertionPoint->at(i));
+                    m_nodeToInsertionPoint.add(innerInsertionPoint->at(i), insertionPoint);
+                }
+            } else {
+                for (Node* child = innerInsertionPoint->firstChild(); child; child = child->nextSibling()) {
+                    distribution.append(child);
+                    m_nodeToInsertionPoint.add(child, insertionPoint);
+                }
+            }
+        } else {
+            distribution.append(node);
+            m_nodeToInsertionPoint.add(node, insertionPoint);
+        }
+    }
+
+    insertionPoint->setDistribution(distribution);
+}
+
+const SelectRuleFeatureSet& ElementShadow::ensureSelectFeatureSet()
+{
+    if (!m_needsSelectFeatureSet)
+        return m_selectFeatures;
+
+    m_selectFeatures.clear();
+    for (ShadowRoot* root = oldestShadowRoot(); root; root = root->youngerShadowRoot())
+        collectSelectFeatureSetFrom(root);
+    m_needsSelectFeatureSet = false;
+    return m_selectFeatures;
+}
+
+void ElementShadow::collectSelectFeatureSetFrom(ShadowRoot* root)
+{
+    if (!root->containsShadowRoots() && !root->containsContentElements())
+        return;
+
+    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))
+            continue;
+        const CSSSelectorList& list = toHTMLContentElement(element)->selectorList();
+        for (const CSSSelector* selector = list.first(); selector; selector = CSSSelectorList::next(selector)) {
+            for (const CSSSelector* component = selector; component; component = component->tagHistory())
+                m_selectFeatures.collectFeaturesFromSelector(component);
+        }
+    }
+}
+
+void ElementShadow::didAffectSelector(AffectedSelectorMask mask)
+{
+    if (ensureSelectFeatureSet().hasSelectorFor(mask))
+        setNeedsDistributionRecalc();
+}
+
+void ElementShadow::willAffectSelector()
+{
+    for (ElementShadow* shadow = this; shadow; shadow = shadow->containingShadow()) {
+        if (shadow->needsSelectFeatureSet())
+            break;
+        shadow->setNeedsSelectFeatureSet();
+    }
+    setNeedsDistributionRecalc();
+}
+
+void ElementShadow::clearDistribution()
+{
+    m_nodeToInsertionPoint.clear();
+
+    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
+        if (ScopeContentDistribution* scope = root->scopeDistribution())
+            scope->setInsertionPointAssignedTo(0);
+    }
+}
+
 } // namespace
diff --git a/Source/core/dom/shadow/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
index 3f16157..8ac38e9 100644
--- a/Source/core/dom/shadow/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -27,27 +27,24 @@
 #ifndef ElementShadow_h
 #define ElementShadow_h
 
-#include "core/dom/shadow/ContentDistributor.h"
+#include "core/dom/shadow/SelectRuleFeatureSet.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "wtf/DoublyLinkedList.h"
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
+class InsertionPoint;
+
 class ElementShadow {
     WTF_MAKE_NONCOPYABLE(ElementShadow); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<ElementShadow> create()
-    {
-        return adoptPtr(new ElementShadow());
-    }
-
-    ~ElementShadow()
-    {
-        removeAllShadowRoots();
-    }
+    static PassOwnPtr<ElementShadow> create();
+    ~ElementShadow();
 
     Element* host() const;
     ShadowRoot* youngestShadowRoot() const { return m_shadowRoots.head(); }
@@ -55,47 +52,47 @@
     ElementShadow* containingShadow() const;
 
     ShadowRoot* addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType);
+
     bool applyAuthorStyles() const { return m_applyAuthorStyles; }
+    bool didAffectApplyAuthorStyles();
+    bool containsActiveStyles() const;
 
     void attach(const Node::AttachContext&);
     void detach(const Node::AttachContext&);
 
     void removeAllEventListeners();
 
-    void didAffectSelector(AffectedSelectorMask mask) { m_distributor.didAffectSelector(host(), mask); }
-    void willAffectSelector() { m_distributor.willAffectSelector(host()); }
-    const SelectRuleFeatureSet& ensureSelectFeatureSet() { return m_distributor.ensureSelectFeatureSet(this); }
+    void didAffectSelector(AffectedSelectorMask);
+    void willAffectSelector();
+    const SelectRuleFeatureSet& ensureSelectFeatureSet();
 
-    // FIXME: Move all callers of this to APIs on ElementShadow and remove it.
-    ContentDistributor& distributor() { return m_distributor; }
-    const ContentDistributor& distributor() const { return m_distributor; }
-
-    void distributeIfNeeded()
-    {
-        if (m_needsDistributionRecalc)
-            m_distributor.distribute(host());
-        m_needsDistributionRecalc = false;
-    }
-    void clearDistribution() { m_distributor.clearDistribution(host()); }
-
+    void distributeIfNeeded();
     void setNeedsDistributionRecalc();
 
-    bool didAffectApplyAuthorStyles();
-    bool containsActiveStyles() const;
+    InsertionPoint* findInsertionPointFor(const Node*) const;
 
 private:
-    ElementShadow()
-        : m_needsDistributionRecalc(false)
-        , m_applyAuthorStyles(false)
-    { }
+    ElementShadow();
 
     void removeAllShadowRoots();
     bool resolveApplyAuthorStyles() const;
 
+    void distribute();
+    void clearDistribution();
+    void populate(Node*, Vector<Node*>&);
+    void collectSelectFeatureSetFrom(ShadowRoot*);
+    void distributeSelectionsTo(InsertionPoint*, const Vector<Node*>& pool, Vector<bool>& distributed);
+    void distributeNodeChildrenTo(InsertionPoint*, ContainerNode*);
+
+    bool needsSelectFeatureSet() const { return m_needsSelectFeatureSet; }
+    void setNeedsSelectFeatureSet() { m_needsSelectFeatureSet = true; }
+
+    HashMap<const Node*, RefPtr<InsertionPoint> > m_nodeToInsertionPoint;
+    SelectRuleFeatureSet m_selectFeatures;
     DoublyLinkedList<ShadowRoot> m_shadowRoots;
-    ContentDistributor m_distributor;
     bool m_needsDistributionRecalc;
     bool m_applyAuthorStyles;
+    bool m_needsSelectFeatureSet;
 };
 
 inline Element* ElementShadow::host() const
@@ -120,14 +117,12 @@
     return 0;
 }
 
-class ShadowRootVector : public Vector<RefPtr<ShadowRoot> > {
-public:
-    explicit ShadowRootVector(ElementShadow* tree)
-    {
-        for (ShadowRoot* root = tree->youngestShadowRoot(); root; root = root->olderShadowRoot())
-            append(root);
-    }
-};
+inline void ElementShadow::distributeIfNeeded()
+{
+    if (m_needsDistributionRecalc)
+        distribute();
+    m_needsDistributionRecalc = false;
+}
 
 inline ElementShadow* shadowOfParent(const Node* node)
 {
@@ -139,7 +134,6 @@
     return 0;
 }
 
-
 } // namespace
 
 #endif
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index b4626d7..f2447c4 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -35,6 +35,7 @@
 #include "core/dom/QualifiedName.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ScopeContentDistribution.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
 namespace WebCore {
@@ -52,8 +53,52 @@
 {
 }
 
+void InsertionPoint::setDistribution(ContentDistribution& distribution)
+{
+    if (shouldUseFallbackElements()) {
+        for (Node* child = firstChild(); child; child = child->nextSibling())
+            child->lazyReattachIfAttached();
+    }
+
+    // Attempt not to reattach nodes that would be distributed to the exact same
+    // location by comparing the old and new distributions.
+
+    size_t i = 0;
+    size_t j = 0;
+
+    for ( ; i < m_distribution.size() && j < distribution.size(); ++i, ++j) {
+        if (m_distribution.size() < distribution.size()) {
+            // If the new distribution is larger than the old one, reattach all nodes in
+            // the new distribution that were inserted.
+            for ( ; j < distribution.size() && m_distribution.at(i) != distribution.at(j); ++j)
+                distribution.at(j)->lazyReattachIfAttached();
+        } else if (m_distribution.size() > distribution.size()) {
+            // If the old distribution is larger than the new one, reattach all nodes in
+            // the old distribution that were removed.
+            for ( ; i < m_distribution.size() && m_distribution.at(i) != distribution.at(j); ++i)
+                m_distribution.at(i)->lazyReattachIfAttached();
+        } else if (m_distribution.at(i) != distribution.at(j)) {
+            // If both distributions are the same length reattach both old and new.
+            m_distribution.at(i)->lazyReattachIfAttached();
+            distribution.at(j)->lazyReattachIfAttached();
+        }
+    }
+
+    // If we hit the end of either list above we need to reattach all remaining nodes.
+
+    for ( ; i < m_distribution.size(); ++i)
+        m_distribution.at(i)->lazyReattachIfAttached();
+
+    for ( ; j < distribution.size(); ++j)
+        distribution.at(j)->lazyReattachIfAttached();
+
+    m_distribution.swap(distribution);
+}
+
 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.
     for (size_t i = 0; i < m_distribution.size(); ++i) {
         if (!m_distribution.at(i)->attached())
             m_distribution.at(i)->attach(context);
@@ -64,20 +109,12 @@
 
 void InsertionPoint::detach(const AttachContext& context)
 {
-    for (size_t i = 0; i < m_distribution.size(); ++i) {
-        if (m_distribution.at(i)->attached())
-            m_distribution.at(i)->detach(context);
-    }
+    for (size_t i = 0; i < m_distribution.size(); ++i)
+        m_distribution.at(i)->lazyReattachIfAttached();
 
     HTMLElement::detach(context);
 }
 
-void InsertionPoint::lazyAttachDistribution(ShouldSetAttached shouldSetAttached)
-{
-    for (size_t i = 0; i < m_distribution.size(); ++i)
-        m_distribution.at(i)->lazyAttach(shouldSetAttached);
-}
-
 void InsertionPoint::willRecalcStyle(StyleChange change)
 {
     if (change < Inherit)
@@ -208,7 +245,7 @@
 
     while (current) {
         if (ElementShadow* shadow = shadowOfParentForDistribution(current)) {
-            if (InsertionPoint* insertedTo = shadow->distributor().findInsertionPointFor(projectedNode)) {
+            if (InsertionPoint* insertedTo = shadow->findInsertionPointFor(projectedNode)) {
                 current = insertedTo;
                 insertionPoint = insertedTo;
                 continue;
@@ -234,7 +271,7 @@
     const Node* current = node;
     while (true) {
         if (ElementShadow* shadow = shadowOfParentForDistribution(current)) {
-            if (InsertionPoint* insertedTo = shadow->distributor().findInsertionPointFor(node)) {
+            if (InsertionPoint* insertedTo = shadow->findInsertionPointFor(node)) {
                 current = insertedTo;
                 results.append(insertedTo);
                 continue;
diff --git a/Source/core/dom/shadow/InsertionPoint.h b/Source/core/dom/shadow/InsertionPoint.h
index 993ea34..aeb3243 100644
--- a/Source/core/dom/shadow/InsertionPoint.h
+++ b/Source/core/dom/shadow/InsertionPoint.h
@@ -32,8 +32,7 @@
 #define InsertionPoint_h
 
 #include "core/css/CSSSelectorList.h"
-#include "core/dom/shadow/ContentDistributor.h"
-#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ContentDistribution.h"
 #include "core/html/HTMLElement.h"
 #include "wtf/Forward.h"
 
@@ -44,7 +43,7 @@
     virtual ~InsertionPoint();
 
     bool hasDistribution() const { return !m_distribution.isEmpty(); }
-    void setDistribution(ContentDistribution& distribution) { m_distribution.swap(distribution); }
+    void setDistribution(ContentDistribution&);
     void clearDistribution() { m_distribution.clear(); }
     bool isActive() const;
 
@@ -67,8 +66,6 @@
     Node* nextTo(const Node* node) const { return m_distribution.nextTo(node); }
     Node* previousTo(const Node* node) const { return m_distribution.previousTo(node); }
 
-    void lazyAttachDistribution(ShouldSetAttached);
-
 protected:
     InsertionPoint(const QualifiedName&, Document*);
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
diff --git a/Source/core/dom/shadow/ScopeContentDistribution.cpp b/Source/core/dom/shadow/ScopeContentDistribution.cpp
new file mode 100644
index 0000000..b20ee65
--- /dev/null
+++ b/Source/core/dom/shadow/ScopeContentDistribution.cpp
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+#include "config.h"
+#include "core/dom/shadow/ScopeContentDistribution.h"
+
+#include "core/dom/ElementTraversal.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/shadow/HTMLContentElement.h"
+#include "core/html/shadow/HTMLShadowElement.h"
+
+namespace WebCore {
+
+ScopeContentDistribution::ScopeContentDistribution()
+    : m_insertionPointAssignedTo(0)
+    , m_numberOfShadowElementChildren(0)
+    , m_numberOfContentElementChildren(0)
+    , m_numberOfElementShadowChildren(0)
+    , m_insertionPointListIsValid(false)
+{
+}
+
+void ScopeContentDistribution::setInsertionPointAssignedTo(PassRefPtr<InsertionPoint> insertionPoint)
+{
+    m_insertionPointAssignedTo = insertionPoint;
+}
+
+void ScopeContentDistribution::invalidateInsertionPointList()
+{
+    m_insertionPointListIsValid = false;
+    m_insertionPointList.clear();
+}
+
+const Vector<RefPtr<InsertionPoint> >& ScopeContentDistribution::ensureInsertionPointList(ShadowRoot* shadowRoot)
+{
+    if (m_insertionPointListIsValid)
+        return m_insertionPointList;
+
+    m_insertionPointListIsValid = true;
+    ASSERT(m_insertionPointList.isEmpty());
+
+    if (!shadowRoot->containsInsertionPoints())
+        return m_insertionPointList;
+
+    for (Element* element = ElementTraversal::firstWithin(shadowRoot); element; element = ElementTraversal::next(element, shadowRoot)) {
+        if (element->isInsertionPoint())
+            m_insertionPointList.append(toInsertionPoint(element));
+    }
+
+    return m_insertionPointList;
+}
+
+void ScopeContentDistribution::registerInsertionPoint(InsertionPoint* point)
+{
+    if (isHTMLShadowElement(point))
+        ++m_numberOfShadowElementChildren;
+    else if (isHTMLContentElement(point))
+        ++m_numberOfContentElementChildren;
+    else
+        ASSERT_NOT_REACHED();
+
+    invalidateInsertionPointList();
+}
+
+void ScopeContentDistribution::unregisterInsertionPoint(InsertionPoint* point)
+{
+    if (isHTMLShadowElement(point))
+        --m_numberOfShadowElementChildren;
+    else if (isHTMLContentElement(point))
+        --m_numberOfContentElementChildren;
+    else
+        ASSERT_NOT_REACHED();
+
+    ASSERT(m_numberOfContentElementChildren >= 0);
+    ASSERT(m_numberOfShadowElementChildren >= 0);
+
+    invalidateInsertionPointList();
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/shadow/ScopeContentDistribution.h b/Source/core/dom/shadow/ScopeContentDistribution.h
new file mode 100644
index 0000000..43ed09f
--- /dev/null
+++ b/Source/core/dom/shadow/ScopeContentDistribution.h
@@ -0,0 +1,73 @@
+/*
+ * 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 ScopeContentDistribution_h
+#define ScopeContentDistribution_h
+
+#include "wtf/Forward.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class InsertionPoint;
+class ShadowRoot;
+
+class ScopeContentDistribution {
+public:
+    ScopeContentDistribution();
+
+    InsertionPoint* insertionPointAssignedTo() const { return m_insertionPointAssignedTo.get(); }
+    void setInsertionPointAssignedTo(PassRefPtr<InsertionPoint>);
+
+    void registerInsertionPoint(InsertionPoint*);
+    void unregisterInsertionPoint(InsertionPoint*);
+    bool hasShadowElementChildren() const { return m_numberOfShadowElementChildren > 0; }
+    bool hasContentElementChildren() const { return m_numberOfContentElementChildren > 0; }
+
+    void registerElementShadow() { ++m_numberOfElementShadowChildren; }
+    void unregisterElementShadow() { ASSERT(m_numberOfElementShadowChildren > 0); --m_numberOfElementShadowChildren; }
+    unsigned numberOfElementShadowChildren() const { return m_numberOfElementShadowChildren; }
+    bool hasElementShadowChildren() const { return m_numberOfElementShadowChildren > 0; }
+
+    void invalidateInsertionPointList();
+    const Vector<RefPtr<InsertionPoint> >& ensureInsertionPointList(ShadowRoot*);
+
+private:
+    RefPtr<InsertionPoint> m_insertionPointAssignedTo;
+    unsigned m_numberOfShadowElementChildren;
+    unsigned m_numberOfContentElementChildren;
+    unsigned m_numberOfElementShadowChildren;
+    bool m_insertionPointListIsValid;
+    Vector<RefPtr<InsertionPoint> > m_insertionPointList;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index a218b17..b9f9ce1 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -29,10 +29,11 @@
 
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Text.h"
-#include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ScopeContentDistribution.h"
 #include "core/editing/markup.h"
 #include "core/platform/HistogramSupport.h"
 
@@ -76,6 +77,8 @@
     ASSERT(!m_prev);
     ASSERT(!m_next);
 
+    documentInternal()->styleSheetCollection()->didRemoveShadowRoot(this);
+
     // We cannot let ContainerNode destructor call willBeDeletedFrom()
     // for this ShadowRoot instance because TreeScope destructor
     // clears Node::m_treeScope thus ContainerNode is no longer able
diff --git a/Source/core/dom/shadow/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
index 3bfcc3d..993fdb2 100644
--- a/Source/core/dom/shadow/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -149,6 +149,17 @@
     return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const Node*>(node)));
 }
 
+inline const ShadowRoot* toShadowRoot(const TreeScope* treeScope)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!treeScope || (treeScope->rootNode() && treeScope->rootNode()->isShadowRoot()));
+    return static_cast<const ShadowRoot*>(treeScope);
+}
+
+inline ShadowRoot* toShadowRoot(TreeScope* treeScope)
+{
+    return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const TreeScope*>(treeScope)));
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/editing/AppendNodeCommand.cpp b/Source/core/editing/AppendNodeCommand.cpp
index 75afcbd..6e5d65d 100644
--- a/Source/core/editing/AppendNodeCommand.cpp
+++ b/Source/core/editing/AppendNodeCommand.cpp
@@ -60,7 +60,7 @@
     if (!m_parent->rendererIsEditable() && m_parent->attached())
         return;
 
-    m_parent->appendChild(m_node.get(), IGNORE_EXCEPTION, AttachLazily);
+    m_parent->appendChild(m_node.get(), IGNORE_EXCEPTION);
 
     if (AXObjectCache::accessibilityEnabled())
         sendAXTextChangedIgnoringLineBreaks(m_node.get(), AXObjectCache::AXTextInserted);
diff --git a/Source/core/editing/CompositeEditCommand.cpp b/Source/core/editing/CompositeEditCommand.cpp
index 7485702..2823754 100644
--- a/Source/core/editing/CompositeEditCommand.cpp
+++ b/Source/core/editing/CompositeEditCommand.cpp
@@ -890,7 +890,7 @@
 PassRefPtr<Node> CompositeEditCommand::insertNewDefaultParagraphElementAt(const Position& position)
 {
     RefPtr<Element> paragraphElement = createDefaultParagraphElement(document());
-    paragraphElement->appendChild(createBreakElement(document()), IGNORE_EXCEPTION);
+    paragraphElement->appendChild(createBreakElement(document()));
     insertNodeAt(paragraphElement, position);
     return paragraphElement.release();
 }
@@ -1052,7 +1052,7 @@
         Node* node = position.deprecatedNode();
 
         // Bail if we'd remove an ancestor of our destination.
-        if (destinationNode->isDescendantOf(node))
+        if (destinationNode && destinationNode->isDescendantOf(node))
             return;
 
         // Normally deletion will leave a br as a placeholder.
diff --git a/Source/core/editing/DeleteFromTextNodeCommand.cpp b/Source/core/editing/DeleteFromTextNodeCommand.cpp
index e0e52d4..dc5736b 100644
--- a/Source/core/editing/DeleteFromTextNodeCommand.cpp
+++ b/Source/core/editing/DeleteFromTextNodeCommand.cpp
@@ -61,7 +61,7 @@
     if (AXObjectCache* cache = document()->existingAXObjectCache())
         cache->nodeTextChangeNotification(m_node.get(), AXObjectCache::AXTextDeleted, m_offset, m_text);
 
-    m_node->deleteData(m_offset, m_count, es);
+    m_node->deleteData(m_offset, m_count, es, DeprecatedAttachNow);
 }
 
 void DeleteFromTextNodeCommand::doUnapply()
@@ -71,7 +71,7 @@
     if (!m_node->rendererIsEditable())
         return;
 
-    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION);
+    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION, DeprecatedAttachNow);
 
     if (AXObjectCache* cache = document()->existingAXObjectCache())
         cache->nodeTextChangeNotification(m_node.get(), AXObjectCache::AXTextInserted, m_offset, m_text);
diff --git a/Source/core/editing/DeleteSelectionCommand.cpp b/Source/core/editing/DeleteSelectionCommand.cpp
index 112cb1e..cf7b3be 100644
--- a/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/Source/core/editing/DeleteSelectionCommand.cpp
@@ -814,6 +814,14 @@
 
     removePreviouslySelectedEmptyTableRows();
 
+    if (!m_needPlaceholder && rootWillStayOpenWithoutPlaceholder) {
+        VisiblePosition visualEnding(m_endingPosition);
+        m_needPlaceholder = !isStartOfParagraph(visualEnding, CanCrossEditingBoundary)
+            && isEndOfParagraph(visualEnding, CanCrossEditingBoundary)
+            && lineBreakExistsAtVisiblePosition(visualEnding)
+            && visualEnding.next(CannotCrossEditingBoundary).isNull();
+    }
+
     RefPtr<Node> placeholder = m_needPlaceholder ? createBreakElement(document()).get() : 0;
 
     if (placeholder) {
diff --git a/Source/core/editing/EditingStyle.cpp b/Source/core/editing/EditingStyle.cpp
index 614038c..c568fcc 100644
--- a/Source/core/editing/EditingStyle.cpp
+++ b/Source/core/editing/EditingStyle.cpp
@@ -56,6 +56,12 @@
 
 namespace WebCore {
 
+static const CSSPropertyID& textDecorationPropertyForEditing()
+{
+    static const CSSPropertyID property = RuntimeEnabledFeatures::css3TextDecorationsEnabled() ? CSSPropertyTextDecorationLine : CSSPropertyTextDecoration;
+    return property;
+}
+
 // Editing style properties must be preserved during editing operation.
 // e.g. when a user inserts a new paragraph, all properties listed here must be copied to the new paragraph.
 // NOTE: Use either allEditingProperties() or inheritableEditingProperties() to
@@ -72,7 +78,10 @@
     CSSPropertyLineHeight,
     CSSPropertyOrphans,
     CSSPropertyTextAlign,
+    // FIXME: CSSPropertyTextDecoration needs to be removed when CSS3 Text
+    // Decoration feature is no longer experimental.
     CSSPropertyTextDecoration,
+    CSSPropertyTextDecorationLine,
     CSSPropertyTextIndent,
     CSSPropertyTextTransform,
     CSSPropertyWhiteSpace,
@@ -89,8 +98,11 @@
 static const Vector<CSSPropertyID>& allEditingProperties()
 {
     DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, properties, ());
-    if (properties.isEmpty())
+    if (properties.isEmpty()) {
         RuntimeCSSEnabled::filterEnabledCSSPropertiesIntoVector(staticEditingProperties, WTF_ARRAY_LENGTH(staticEditingProperties), properties);
+        if (RuntimeEnabledFeatures::css3TextDecorationsEnabled())
+            properties.remove(properties.find(CSSPropertyTextDecoration));
+    }
     return properties;
 }
 
@@ -207,21 +219,22 @@
 };
 
 HTMLTextDecorationEquivalent::HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const QualifiedName& tagName)
-    : HTMLElementEquivalent(CSSPropertyTextDecoration, primitiveValue, tagName)
+    : HTMLElementEquivalent(textDecorationPropertyForEditing(), primitiveValue, tagName)
     // m_propertyID is used in HTMLElementEquivalent::addToStyle
 {
 }
 
 bool HTMLTextDecorationEquivalent::propertyExistsInStyle(const StylePropertySet* style) const
 {
-    return style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect) || style->getPropertyCSSValue(CSSPropertyTextDecoration);
+    return style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect)
+        || style->getPropertyCSSValue(textDecorationPropertyForEditing());
 }
 
 bool HTMLTextDecorationEquivalent::valueIsPresentInStyle(Element* element, StylePropertySet* style) const
 {
     RefPtr<CSSValue> styleValue = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
     if (!styleValue)
-        styleValue = style->getPropertyCSSValue(CSSPropertyTextDecoration);
+        styleValue = style->getPropertyCSSValue(textDecorationPropertyForEditing());
     return matches(element) && styleValue && styleValue->isValueList() && toCSSValueList(styleValue.get())->hasValue(m_primitiveValue.get());
 }
 
@@ -649,15 +662,18 @@
         return;
 
     if (textDecorationsInEffect->isValueList())
-        m_mutableStyle->setProperty(CSSPropertyTextDecoration, textDecorationsInEffect->cssText(), m_mutableStyle->propertyIsImportant(CSSPropertyTextDecoration));
+        m_mutableStyle->setProperty(textDecorationPropertyForEditing(), textDecorationsInEffect->cssText(), m_mutableStyle->propertyIsImportant(textDecorationPropertyForEditing()));
     else
-        m_mutableStyle->removeProperty(CSSPropertyTextDecoration);
+        m_mutableStyle->removeProperty(textDecorationPropertyForEditing());
     m_mutableStyle->removeProperty(CSSPropertyWebkitTextDecorationsInEffect);
 }
 
 // CSS properties that create a visual difference only when applied to text.
 static const CSSPropertyID textOnlyProperties[] = {
+    // FIXME: CSSPropertyTextDecoration needs to be removed when CSS3 Text
+    // Decoration feature is no longer experimental.
     CSSPropertyTextDecoration,
+    CSSPropertyTextDecorationLine,
     CSSPropertyWebkitTextDecorationsInEffect,
     CSSPropertyFontStyle,
     CSSPropertyFontWeight,
@@ -734,12 +750,16 @@
         if (propertyID == CSSPropertyWhiteSpace && isTabSpanNode(element))
             continue;
 
-        if (propertyID == CSSPropertyWebkitTextDecorationsInEffect && inlineStyle->getPropertyCSSValue(CSSPropertyTextDecoration)) {
+        if (propertyID == CSSPropertyWebkitTextDecorationsInEffect && inlineStyle->getPropertyCSSValue(textDecorationPropertyForEditing())) {
             if (!conflictingProperties)
                 return true;
             conflictingProperties->append(CSSPropertyTextDecoration);
+            // Because text-decoration expands to text-decoration-line when CSS3
+            // Text Decoration is enabled, we also state it as conflicting.
+            if (RuntimeEnabledFeatures::css3TextDecorationsEnabled())
+                conflictingProperties->append(CSSPropertyTextDecorationLine);
             if (extractedStyle)
-                extractedStyle->setProperty(CSSPropertyTextDecoration, inlineStyle->getPropertyValue(CSSPropertyTextDecoration), inlineStyle->propertyIsImportant(CSSPropertyTextDecoration));
+                extractedStyle->setProperty(textDecorationPropertyForEditing(), inlineStyle->getPropertyValue(textDecorationPropertyForEditing()), inlineStyle->propertyIsImportant(textDecorationPropertyForEditing()));
             continue;
         }
 
@@ -1097,7 +1117,7 @@
         RefPtr<CSSValue> value = m_mutableStyle->getPropertyCSSValue(property.id());
 
         // text decorations never override values
-        if ((property.id() == CSSPropertyTextDecoration || property.id() == CSSPropertyWebkitTextDecorationsInEffect) && property.value()->isValueList() && value) {
+        if ((property.id() == textDecorationPropertyForEditing() || property.id() == CSSPropertyWebkitTextDecorationsInEffect) && property.value()->isValueList() && value) {
             if (value->isValueList()) {
                 mergeTextDecorationValues(toCSSValueList(value.get()), toCSSValueList(property.value()));
                 continue;
@@ -1352,18 +1372,18 @@
 static void reconcileTextDecorationProperties(MutableStylePropertySet* style)
 {
     RefPtr<CSSValue> textDecorationsInEffect = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
-    RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(CSSPropertyTextDecoration);
+    RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(textDecorationPropertyForEditing());
     // We shouldn't have both text-decoration and -webkit-text-decorations-in-effect because that wouldn't make sense.
     ASSERT(!textDecorationsInEffect || !textDecoration);
     if (textDecorationsInEffect) {
-        style->setProperty(CSSPropertyTextDecoration, textDecorationsInEffect->cssText());
+        style->setProperty(textDecorationPropertyForEditing(), textDecorationsInEffect->cssText());
         style->removeProperty(CSSPropertyWebkitTextDecorationsInEffect);
         textDecoration = textDecorationsInEffect;
     }
 
     // If text-decoration is set to "none", remove the property because we don't want to add redundant "text-decoration: none".
     if (textDecoration && !textDecoration->isValueList())
-        style->removeProperty(CSSPropertyTextDecoration);
+        style->removeProperty(textDecorationPropertyForEditing());
 }
 
 StyleChange::StyleChange(EditingStyle* style, const Position& position)
@@ -1427,7 +1447,7 @@
 
     // Assuming reconcileTextDecorationProperties has been called, there should not be -webkit-text-decorations-in-effect
     // Furthermore, text-decoration: none has been trimmed so that text-decoration property is always a CSSValueList.
-    RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(CSSPropertyTextDecoration);
+    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)));
@@ -1439,7 +1459,7 @@
             m_applyLineThrough = true;
 
         // If trimTextDecorations, delete underline and line-through
-        setTextDecorationProperty(style, newTextDecoration.get(), CSSPropertyTextDecoration);
+        setTextDecorationProperty(style, newTextDecoration.get(), textDecorationPropertyForEditing());
     }
 
     int verticalAlign = getIdentifierValue(style, CSSPropertyVerticalAlign);
@@ -1492,8 +1512,6 @@
 
 static bool fontWeightIsBold(CSSValue* fontWeight)
 {
-    if (!fontWeight)
-        return false;
     if (!fontWeight->isPrimitiveValue())
         return false;
 
@@ -1521,18 +1539,13 @@
     return false;
 }
 
-static bool fontWeightIsBold(CSSStyleDeclaration* style)
+static bool fontWeightNeedsResolving(CSSValue* fontWeight)
 {
-    ASSERT(style);
-    RefPtr<CSSValue> fontWeight = style->getPropertyCSSValueInternal(CSSPropertyFontWeight);
-    return fontWeightIsBold(fontWeight.get());
-}
+    if (!fontWeight->isPrimitiveValue())
+        return true;
 
-static bool fontWeightIsBold(StylePropertySet* style)
-{
-    ASSERT(style);
-    RefPtr<CSSValue> fontWeight = style->getPropertyCSSValue(CSSPropertyFontWeight);
-    return fontWeightIsBold(fontWeight.get());
+    CSSValueID value = toCSSPrimitiveValue(fontWeight)->getValueID();
+    return value == CSSValueLighter || value == CSSValueBolder;
 }
 
 PassRefPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, CSSStyleDeclaration* baseStyle)
@@ -1544,11 +1557,15 @@
     result->removeEquivalentProperties(baseStyle);
 
     RefPtr<CSSValue> baseTextDecorationsInEffect = baseStyle->getPropertyCSSValueInternal(CSSPropertyWebkitTextDecorationsInEffect);
-    diffTextDecorations(result.get(), CSSPropertyTextDecoration, baseTextDecorationsInEffect.get());
+    diffTextDecorations(result.get(), textDecorationPropertyForEditing(), baseTextDecorationsInEffect.get());
     diffTextDecorations(result.get(), CSSPropertyWebkitTextDecorationsInEffect, baseTextDecorationsInEffect.get());
 
-    if (baseStyle->getPropertyCSSValueInternal(CSSPropertyFontWeight) && fontWeightIsBold(result.get()) == fontWeightIsBold(baseStyle))
-        result->removeProperty(CSSPropertyFontWeight);
+    if (RefPtr<CSSValue> baseFontWeight = baseStyle->getPropertyCSSValueInternal(CSSPropertyFontWeight)) {
+        if (RefPtr<CSSValue> fontWeight = result->getPropertyCSSValue(CSSPropertyFontWeight)) {
+            if (!fontWeightNeedsResolving(fontWeight.get()) && (fontWeightIsBold(fontWeight.get()) == fontWeightIsBold(baseFontWeight.get())))
+                result->removeProperty(CSSPropertyFontWeight);
+        }
+    }
 
     if (baseStyle->getPropertyCSSValueInternal(CSSPropertyColor) && getRGBAFontColor(result.get()) == getRGBAFontColor(baseStyle))
         result->removeProperty(CSSPropertyColor);
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index 5931025..556bf22 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -53,17 +53,18 @@
 #include "core/editing/RenderedPosition.h"
 #include "core/editing/ReplaceSelectionCommand.h"
 #include "core/editing/SimplifyMarkupCommand.h"
-#include "core/editing/SpellChecker.h"
+#include "core/editing/SpellCheckRequester.h"
 #include "core/editing/TextCheckingHelper.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/TypingCommand.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLTextAreaElement.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/loader/EmptyClients.h"
 #include "core/page/EditorClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
@@ -138,25 +139,27 @@
     return EditingBehavior(m_frame->settings()->editingBehaviorType());
 }
 
-EditorClient* Editor::client() const
+static EditorClient& emptyEditorClient()
+{
+    DEFINE_STATIC_LOCAL(EmptyEditorClient, client, ());
+    return client;
+}
+
+EditorClient& Editor::client() const
 {
     if (Page* page = m_frame->page())
         return page->editorClient();
-    return 0;
+    return emptyEditorClient();
 }
 
-
-TextCheckerClient* Editor::textChecker() const
+TextCheckerClient& Editor::textChecker() const
 {
-    if (EditorClient* owner = client())
-        return owner->textChecker();
-    return 0;
+    return client().textChecker();
 }
 
 void Editor::handleKeyboardEvent(KeyboardEvent* event)
 {
-    if (EditorClient* c = client())
-        c->handleKeyboardEvent(event);
+    client().handleKeyboardEvent(event);
 }
 
 bool Editor::handleTextEvent(TextEvent* event)
@@ -279,17 +282,17 @@
 
 bool Editor::smartInsertDeleteEnabled()
 {
-    return client() && client()->smartInsertDeleteEnabled();
+    return client().smartInsertDeleteEnabled();
 }
 
 bool Editor::canSmartCopyOrDelete()
 {
-    return client() && client()->smartInsertDeleteEnabled() && m_frame->selection()->granularity() == WordGranularity;
+    return client().smartInsertDeleteEnabled() && m_frame->selection()->granularity() == WordGranularity;
 }
 
 bool Editor::isSelectTrailingWhitespaceEnabled()
 {
-    return client() && client()->isSelectTrailingWhitespaceEnabled();
+    return client().isSelectTrailingWhitespaceEnabled();
 }
 
 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
@@ -366,8 +369,8 @@
 
 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard* pasteboard)
 {
-    String text = pasteboard->plainText(m_frame);
-    if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
+    String text = pasteboard->plainText();
+    if (client().shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
         pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
 }
 
@@ -382,21 +385,18 @@
 
 bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard)
 {
-    return client() && client()->smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
+    return client().smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
 }
 
 bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
 {
-    if (!client())
-        return false;
-
     if (fragment) {
         Node* child = fragment->firstChild();
         if (child && fragment->lastChild() == child && child->isCharacterDataNode())
-            return client()->shouldInsertText(static_cast<CharacterData*>(child)->data(), replacingDOMRange.get(), givenAction);
+            return client().shouldInsertText(static_cast<CharacterData*>(child)->data(), replacingDOMRange.get(), givenAction);
     }
 
-    return client()->shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
+    return client().shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
 }
 
 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
@@ -421,7 +421,7 @@
         return;
 
     RefPtr<Range> rangeToCheck = Range::create(m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
-    m_spellChecker->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
+    m_spellCheckRequester->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
 }
 
 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
@@ -444,7 +444,7 @@
     if (!canDeleteRange(range))
         return false;
 
-    return client() && client()->shouldDeleteRange(range);
+    return client().shouldDeleteRange(range);
 }
 
 bool Editor::tryDHTMLCopy()
@@ -470,13 +470,12 @@
 
 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
 {
-    return client() && client()->shouldInsertText(text, range, action);
+    return client().shouldInsertText(text, range, action);
 }
 
 void Editor::notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
 {
-    if (client())
-        client()->respondToChangedSelection(m_frame);
+    client().respondToChangedSelection(m_frame);
     setStartNewKillRingSequence(true);
 }
 
@@ -489,9 +488,7 @@
     }
 
     updateMarkersForWordsAffectedByEditing(true);
-
-    if (client())
-        client()->respondToChangedContents();
+    client().respondToChangedContents();
 }
 
 TriState Editor::selectionUnorderedListState() const
@@ -616,11 +613,8 @@
     RefPtr<Event> evt = ClipboardEvent::create(eventType, true, true, clipboard);
     target->dispatchEvent(evt, IGNORE_EXCEPTION);
     bool noDefaultProcessing = evt->defaultPrevented();
-    if (noDefaultProcessing && policy == ClipboardWritable) {
-        Pasteboard* pasteboard = Pasteboard::generalPasteboard();
-        pasteboard->clear();
-        pasteboard->writeClipboard(clipboard.get());
-    }
+    if (noDefaultProcessing && policy == ClipboardWritable)
+        Pasteboard::generalPasteboard()->writeClipboard(clipboard.get());
 
     // invalidate clipboard here for security
     clipboard->setAccessPolicy(ClipboardNumb);
@@ -662,7 +656,7 @@
 
 bool Editor::shouldApplyStyle(StylePropertySet* style, Range* range)
 {
-    return client()->shouldApplyStyle(style, range);
+    return client().shouldApplyStyle(style, range);
 }
 
 void Editor::applyParagraphStyle(StylePropertySet* style, EditAction editingAction)
@@ -684,7 +678,7 @@
     if (!style || style->isEmpty() || !canEditRichly())
         return;
 
-    if (client() && client()->shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
+    if (client().shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
         applyStyle(style, editingAction);
 }
 
@@ -693,7 +687,7 @@
     if (!style || style->isEmpty() || !canEditRichly())
         return;
 
-    if (client() && client()->shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
+    if (client().shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
         applyParagraphStyle(style, editingAction);
 }
 
@@ -760,8 +754,7 @@
         // Only register a new undo command if the command passed in is
         // different from the last command
         m_lastEditCommand = cmd;
-        if (client())
-            client()->registerUndoStep(m_lastEditCommand->ensureComposition());
+        client().registerUndoStep(m_lastEditCommand->ensureComposition());
     }
 
     respondToChangedContents(newSelection);
@@ -776,8 +769,7 @@
     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
 
     m_lastEditCommand = 0;
-    if (client())
-        client()->registerRedoStep(cmd);
+    client().registerRedoStep(cmd);
     respondToChangedContents(newSelection);
 }
 
@@ -790,8 +782,7 @@
     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
 
     m_lastEditCommand = 0;
-    if (client())
-        client()->registerUndoStep(cmd);
+    client().registerUndoStep(cmd);
     respondToChangedContents(newSelection);
 }
 
@@ -802,7 +793,7 @@
     // This is off by default, since most editors want this behavior (this matches IE but not FF).
     , m_shouldStyleWithCSS(false)
     , m_killRing(adoptPtr(new KillRing))
-    , m_spellChecker(adoptPtr(new SpellChecker(frame)))
+    , m_spellCheckRequester(adoptPtr(new SpellCheckRequester(frame)))
     , m_areMarkedTextMatchesHighlighted(false)
     , m_defaultParagraphSeparator(EditorParagraphSeparatorIsDiv)
     , m_overwriteModeEnabled(false)
@@ -912,11 +903,13 @@
     RefPtr<Range> selection = selectedRange();
     if (shouldDeleteRange(selection.get())) {
         updateMarkersForWordsAffectedByEditing(true);
+        String plainText = m_frame->selectedTextForClipboard();
         if (enclosingTextFormControl(m_frame->selection()->start())) {
-            Pasteboard::generalPasteboard()->writePlainText(m_frame->selectedTextForClipboard(),
+            Pasteboard::generalPasteboard()->writePlainText(plainText,
                 canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
-        } else
-            Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
+        } else {
+            Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), plainText);
+        }
         deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
     }
 }
@@ -938,7 +931,7 @@
         if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
             Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
         else
-            Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
+            Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame->selectedTextForClipboard());
     }
 }
 
@@ -1003,7 +996,7 @@
 
 void Editor::copyURL(const KURL& url, const String& title)
 {
-    Pasteboard::generalPasteboard()->writeURL(url, title, m_frame);
+    Pasteboard::generalPasteboard()->writeURL(url, title);
 }
 
 void Editor::copyImage(const HitTestResult& result)
@@ -1017,68 +1010,96 @@
 
 bool Editor::isContinuousSpellCheckingEnabled() const
 {
-    return client() && client()->isContinuousSpellCheckingEnabled();
+    return client().isContinuousSpellCheckingEnabled();
 }
 
 void Editor::toggleContinuousSpellChecking()
 {
-    if (client())
-        client()->toggleContinuousSpellChecking();
+    client().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)) {
+            node->setAlreadySpellChecked(false);
+        }
+    }
 }
 
 bool Editor::isGrammarCheckingEnabled()
 {
-    return client() && client()->isGrammarCheckingEnabled();
+    return client().isGrammarCheckingEnabled();
 }
 
 bool Editor::shouldEndEditing(Range* range)
 {
-    return client() && client()->shouldEndEditing(range);
+    return client().shouldEndEditing(range);
 }
 
 bool Editor::shouldBeginEditing(Range* range)
 {
-    return client() && client()->shouldBeginEditing(range);
+    return client().shouldBeginEditing(range);
 }
 
 void Editor::clearUndoRedoOperations()
 {
-    if (client())
-        client()->clearUndoRedoOperations();
+    client().clearUndoRedoOperations();
 }
 
 bool Editor::canUndo()
 {
-    return client() && client()->canUndo();
+    return client().canUndo();
 }
 
 void Editor::undo()
 {
-    if (client())
-        client()->undo();
+    client().undo();
 }
 
 bool Editor::canRedo()
 {
-    return client() && client()->canRedo();
+    return client().canRedo();
 }
 
 void Editor::redo()
 {
-    if (client())
-        client()->redo();
+    client().redo();
 }
 
-void Editor::didBeginEditing()
+void Editor::elementDidBeginEditing(Element* element)
 {
-    if (client())
-        client()->didBeginEditing();
+    if (isContinuousSpellCheckingEnabled() && unifiedTextCheckerEnabled()) {
+        bool isTextField = false;
+        HTMLTextFormControlElement* enclosingHTMLTextFormControlElement = 0;
+        if (!isHTMLTextFormControlElement(element))
+            enclosingHTMLTextFormControlElement = enclosingTextFormControl(firstPositionInNode(element));
+        element = enclosingHTMLTextFormControlElement ? enclosingHTMLTextFormControlElement : element;
+        Element* parent = element;
+        if (isHTMLTextFormControlElement(element)) {
+            HTMLTextFormControlElement* textControl = toHTMLTextFormControlElement(element);
+            parent = textControl;
+            element = textControl->innerTextElement();
+            isTextField = textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isTextField();
+        }
+
+        if (isTextField || !parent->isAlreadySpellChecked()) {
+            // We always recheck textfields because markers are removed from them on blur.
+            VisibleSelection selection = VisibleSelection::selectionFromContentsOfNode(element);
+            markMisspellingsAndBadGrammar(selection);
+            if (!isTextField)
+                parent->setAlreadySpellChecked(true);
+        }
+    }
+}
+
+void Editor::didBeginEditing(Element* rootEditableElement)
+{
+    elementDidBeginEditing(rootEditableElement);
+    client().didBeginEditing();
 }
 
 void Editor::didEndEditing()
 {
-    if (client())
-        client()->didEndEditing();
+    client().didEndEditing();
 }
 
 void Editor::setBaseWritingDirection(WritingDirection direction)
@@ -1133,9 +1154,6 @@
 
 void Editor::ignoreSpelling()
 {
-    if (!client())
-        return;
-
     RefPtr<Range> selectedRange = frame()->selection()->toNormalizedRange();
     if (selectedRange)
         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
@@ -1197,10 +1215,6 @@
     if (spellingSearchRange->collapsed(IGNORE_EXCEPTION))
         return; // nothing to search in
 
-    // Get the spell checker if it is available
-    if (!client())
-        return;
-
     // We go to the end of our first range instead of the start of it, just to be sure
     // we don't get foiled by any word boundary problems at the start.  It means we might
     // do a tiny bit more searching.
@@ -1296,7 +1310,7 @@
         frame()->selection()->setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
         frame()->selection()->revealSelection();
 
-        client()->updateSpellingUIWithMisspelledWord(misspelledWord);
+        client().updateSpellingUIWithMisspelledWord(misspelledWord);
         frame()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
     }
 }
@@ -1320,31 +1334,26 @@
         return String();
 
     String word = wordRange->text();
-    if (word.isEmpty() || !client())
+    if (word.isEmpty())
         return String();
 
     int wordLength = word.length();
     int misspellingLocation = -1;
     int misspellingLength = 0;
-    textChecker()->checkSpellingOfString(word, &misspellingLocation, &misspellingLength);
+    textChecker().checkSpellingOfString(word, &misspellingLocation, &misspellingLength);
 
     return misspellingLength == wordLength ? word : String();
 }
 
 void Editor::showSpellingGuessPanel()
 {
-    if (!client()) {
-        LOG_ERROR("No NSSpellChecker");
-        return;
-    }
-
-    if (client()->spellingUIIsShowing()) {
-        client()->showSpellingUI(false);
+    if (client().spellingUIIsShowing()) {
+        client().showSpellingUI(false);
         return;
     }
 
     advanceToNextMisspelling(true);
-    client()->showSpellingUI(true);
+    client().showSpellingUI(true);
 }
 
 void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
@@ -1397,7 +1406,7 @@
 
     // Get the misspelled word.
     const String misspelledWord = plainText(misspellingRange.get());
-    String autocorrectedString = textChecker()->getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
+    String autocorrectedString = textChecker().getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
 
     // If autocorrected word is non empty, replace the misspelled word by this word.
     if (!autocorrectedString.isEmpty()) {
@@ -1446,10 +1455,6 @@
     if (!isSpellCheckingEnabledFor(editableNode))
         return;
 
-    // Get the spell checker if it is available
-    if (!client())
-        return;
-
     TextCheckingHelper checker(client(), searchRange);
     if (checkSpelling)
         checker.markAllMisspellings(firstMisspellingRange);
@@ -1491,7 +1496,7 @@
     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
 
     // This function is called with selections already expanded to word boundaries.
-    if (!client() || !spellingRange || (shouldMarkGrammar && !grammarRange))
+    if (!spellingRange || (shouldMarkGrammar && !grammarRange))
         return;
 
     // If we're not in an editable node, bail.
@@ -1503,24 +1508,53 @@
         return;
 
     Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
-    TextCheckingParagraph paragraphToCheck(rangeToCheck);
-    if (paragraphToCheck.isRangeEmpty() || paragraphToCheck.isEmpty())
+    TextCheckingParagraph fullParagraphToCheck(rangeToCheck);
+    if (fullParagraphToCheck.isRangeEmpty() || fullParagraphToCheck.isEmpty())
         return;
-    RefPtr<Range> paragraphRange = paragraphToCheck.paragraphRange();
 
+    // Since the text may be quite big chunk it up and adjust to the sentence boundary.
+    const int kChunkSize = 16 * 1024;
+    int start = fullParagraphToCheck.checkingStart();
+    int end = fullParagraphToCheck.checkingEnd();
+    start = std::min(start, end);
+    end = std::max(start, end);
     bool asynchronous = m_frame && m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled();
-
-    // In asynchronous mode, we intentionally check paragraph-wide sentence.
-    RefPtr<SpellCheckRequest> request = SpellCheckRequest::create(resolveTextCheckingTypeMask(textCheckingOptions), TextCheckingProcessIncremental, asynchronous ? paragraphRange : rangeToCheck, paragraphRange);
-
-    if (asynchronous) {
-        m_spellChecker->requestCheckingFor(request);
+    const int kNumChunksToCheck = asynchronous ? (end - start + kChunkSize - 1) / (kChunkSize) : 1;
+    int currentChunkStart = start;
+    RefPtr<Range> checkRange = asynchronous ? fullParagraphToCheck.paragraphRange() : rangeToCheck;
+    RefPtr<Range> paragraphRange = fullParagraphToCheck.paragraphRange();
+    if (kNumChunksToCheck == 1 && asynchronous) {
+        markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), paragraphRange.get(), asynchronous, 0);
         return;
     }
 
-    Vector<TextCheckingResult> results;
-    checkTextOfParagraph(textChecker(), paragraphToCheck.text(), resolveTextCheckingTypeMask(textCheckingOptions), results);
-    markAndReplaceFor(request, results);
+    for (int iter = 0; iter < kNumChunksToCheck; ++iter) {
+        checkRange = fullParagraphToCheck.subrange(currentChunkStart, kChunkSize);
+        setStart(checkRange.get(), startOfSentence(checkRange->startPosition()));
+        setEnd(checkRange.get(), endOfSentence(checkRange->endPosition()));
+        paragraphRange = checkRange;
+
+        int checkingLength = 0;
+        markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), paragraphRange.get(), asynchronous, iter, &checkingLength);
+        currentChunkStart += checkingLength;
+    }
+}
+
+void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* checkRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength)
+{
+    TextCheckingParagraph sentenceToCheck(checkRange, paragraphRange);
+    if (checkingLength)
+        *checkingLength = sentenceToCheck.checkingLength();
+
+    RefPtr<SpellCheckRequest> request = SpellCheckRequest::create(resolveTextCheckingTypeMask(textCheckingOptions), TextCheckingProcessBatch, checkRange, paragraphRange, requestNumber);
+
+    if (asynchronous) {
+        m_spellCheckRequester->requestCheckingFor(request);
+    } else {
+        Vector<TextCheckingResult> results;
+        checkTextOfParagraph(textChecker(), sentenceToCheck.text(), resolveTextCheckingTypeMask(textCheckingOptions), results);
+        markAndReplaceFor(request, results);
+    }
 }
 
 void Editor::markAndReplaceFor(PassRefPtr<SpellCheckRequest> request, const Vector<TextCheckingResult>& results)
@@ -1556,7 +1590,7 @@
     for (unsigned i = 0; i < results.size(); i++) {
         int spellingRangeEndOffset = paragraph.checkingEnd();
         const TextCheckingResult* result = &results[i];
-        int resultLocation = result->location;
+        int resultLocation = result->location + paragraph.checkingStart();
         int resultLength = result->length;
         bool resultEndsAtAmbiguousBoundary = ambiguousBoundaryOffset >= 0 && resultLocation + resultLength == ambiguousBoundaryOffset;
 
@@ -1621,7 +1655,7 @@
 
 void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
 {
-    if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling))
+    if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling))
         return;
 
     // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
@@ -1802,8 +1836,8 @@
     // change the caret's DOM position (["hello", 0]). In these situations the above FrameSelection::setSelection call
     // 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())
-        client()->respondToChangedSelection(m_frame);
+    if (selectionDidNotChangeDOMPosition)
+        client().respondToChangedSelection(m_frame);
 }
 
 IntRect Editor::firstRectForRange(Range* range) const
@@ -1837,7 +1871,7 @@
 
 bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
 {
-    return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
+    return client().shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
 }
 
 void Editor::computeAndSetTypingStyle(StylePropertySet* style, EditAction editingAction)
@@ -1866,21 +1900,16 @@
     m_frame->selection()->setTypingStyle(typingStyle);
 }
 
-
-void Editor::textFieldDidBeginEditing(Element* e)
+void Editor::textAreaOrTextFieldDidBeginEditing(Element* e)
 {
-    if (isContinuousSpellCheckingEnabled()) {
-        Element* element = toHTMLTextFormControlElement(e)->innerTextElement();
-        VisibleSelection selection = VisibleSelection::selectionFromContentsOfNode(element);
-        markMisspellingsAndBadGrammar(selection);
-    }
+    elementDidBeginEditing(e);
 }
 
 void Editor::textFieldDidEndEditing(Element* e)
 {
     // Remove markers when deactivating a selection in an <input type="text"/>.
     // Prevent new ones from appearing too.
-    m_spellChecker->cancelCheck();
+    m_spellCheckRequester->cancelCheck();
     HTMLTextFormControlElement* textFormControlElement = toHTMLTextFormControlElement(e);
     HTMLElement* innerText = textFormControlElement->innerTextElement();
     DocumentMarker::MarkerTypes markerTypes(DocumentMarker::Spelling);
@@ -1890,22 +1919,17 @@
         m_frame->document()->markers()->removeMarkers(node, markerTypes);
     }
 
-    if (client())
-        client()->textFieldDidEndEditing(e);
+    client().textFieldDidEndEditing(e);
 }
 
 void Editor::textDidChangeInTextField(Element* e)
 {
-    if (client())
-        client()->textDidChangeInTextField(e);
+    client().textDidChangeInTextField(e);
 }
 
 bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
 {
-    if (client())
-        return client()->doTextFieldCommandFromEvent(e, ke);
-
-    return false;
+    return client().doTextFieldCommandFromEvent(e, ke);
 }
 
 void Editor::applyEditingStyleToBodyElement() const
@@ -2074,11 +2098,11 @@
             spellCheckOldSelection(oldSelection, newAdjacentWords, newSelectedSentence);
         }
 
-        if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
+        if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
             if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
                 m_frame->document()->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling);
         }
-        if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
+        if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
             if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
                 m_frame->document()->markers()->removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
         }
diff --git a/Source/core/editing/Editor.h b/Source/core/editing/Editor.h
index 7fabdd4..4330222 100644
--- a/Source/core/editing/Editor.h
+++ b/Source/core/editing/Editor.h
@@ -52,10 +52,10 @@
 class HitTestResult;
 class KillRing;
 class Pasteboard;
-class SimpleFontData;
-class SpellChecker;
-class SpellCheckRequest;
 class SharedBuffer;
+class SimpleFontData;
+class SpellCheckRequest;
+class SpellCheckRequester;
 class StylePropertySet;
 class Text;
 class TextCheckerClient;
@@ -70,8 +70,8 @@
     explicit Editor(Frame*);
     ~Editor();
 
-    EditorClient* client() const;
-    TextCheckerClient* textChecker() const;
+    EditorClient& client() const;
+    TextCheckerClient& textChecker() const;
 
     Frame* frame() const { return m_frame; }
 
@@ -214,7 +214,7 @@
     bool canRedo();
     void redo();
 
-    void didBeginEditing();
+    void didBeginEditing(Element*);
     void didEndEditing();
 
     void setBaseWritingDirection(WritingDirection);
@@ -237,7 +237,7 @@
     VisibleSelection selectionForCommand(Event*);
 
     KillRing* killRing() const { return m_killRing.get(); }
-    SpellChecker* spellChecker() const { return m_spellChecker.get(); }
+    SpellCheckRequester& spellCheckRequester() const { return *m_spellCheckRequester; }
 
     EditingBehavior behavior() const;
 
@@ -281,7 +281,7 @@
     bool markedTextMatchesAreHighlighted() const;
     void setMarkedTextMatchesAreHighlighted(bool);
 
-    void textFieldDidBeginEditing(Element*);
+    void textAreaOrTextFieldDidBeginEditing(Element*);
     void textFieldDidEndEditing(Element*);
     void textDidChangeInTextField(Element*);
     bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*);
@@ -309,6 +309,8 @@
     };
     friend class RevealSelectionScope;
 
+    void elementDidBeginEditing(Element*);
+
 private:
     RefPtr<CompositeEditCommand> m_lastEditCommand;
     RefPtr<Node> m_removedAnchor;
@@ -316,7 +318,7 @@
     bool m_shouldStartNewKillRingSequence;
     bool m_shouldStyleWithCSS;
     OwnPtr<KillRing> m_killRing;
-    OwnPtr<SpellChecker> m_spellChecker;
+    const OwnPtr<SpellCheckRequester> m_spellCheckRequester;
     VisibleSelection m_mark;
     bool m_areMarkedTextMatchesHighlighted;
     EditorParagraphSeparator m_defaultParagraphSeparator;
@@ -338,6 +340,8 @@
     Node* findEventTargetFromSelection() const;
 
     bool unifiedTextCheckerEnabled() const;
+
+    void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingMask, Range* checkingRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength = 0);
 };
 
 inline void Editor::setStartNewKillRingSequence(bool flag)
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index b32e2ff..645f7f4 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -217,7 +217,7 @@
         return false;
     RefPtr<Range> oldRange = frame->selection()->selection().toNormalizedRange();
     EAffinity affinity = frame->selection()->affinity();
-    if (!frame->editor()->client()->shouldChangeSelectedRange(oldRange.get(), newRange.get(), affinity, false))
+    if (!frame->editor()->client().shouldChangeSelectedRange(oldRange.get(), newRange.get(), affinity, false))
         return false;
     frame->selection()->setSelectedRange(newRange.get(), affinity, true);
     return true;
@@ -931,7 +931,7 @@
 
 static bool executePasteGlobalSelection(Frame* frame, Event*, EditorCommandSource source, const String&)
 {
-    if (!frame->editor()->client()->supportsGlobalSelection())
+    if (!frame->editor()->client().supportsGlobalSelection())
         return false;
     ASSERT_UNUSED(source, source == CommandFromMenuOrKeyBinding);
     UserTypingGestureIndicator typingGestureIndicator(frame);
@@ -1177,9 +1177,7 @@
 
     Settings* settings = frame->settings();
     bool defaultValue = settings && settings->javaScriptCanAccessClipboard();
-
-    EditorClient* client = frame->editor()->client();
-    return client ? client->canCopyCut(frame, defaultValue) : defaultValue;
+    return frame->editor()->client().canCopyCut(frame, defaultValue);
 }
 
 static bool supportedPaste(Frame* frame)
@@ -1189,9 +1187,7 @@
 
     Settings* settings = frame->settings();
     bool defaultValue = settings && settings->javaScriptCanAccessClipboard() && settings->DOMPasteAllowed();
-
-    EditorClient* client = frame->editor()->client();
-    return client ? client->canPaste(frame, defaultValue) : defaultValue;
+    return frame->editor()->client().canPaste(frame, defaultValue);
 }
 
 // Enabled functions
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 4aa52a2..e55f134 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -34,6 +34,7 @@
 #include "core/dom/CharacterData.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Range.h"
 #include "core/editing/Editor.h"
@@ -1761,7 +1762,7 @@
 
 bool FrameSelection::shouldDeleteSelection(const VisibleSelection& selection) const
 {
-    return m_frame->editor()->client()->shouldDeleteRange(selection.toNormalizedRange().get());
+    return m_frame->editor()->client().shouldDeleteRange(selection.toNormalizedRange().get());
 }
 
 FloatRect FrameSelection::bounds(bool clipToVisibleContent) const
@@ -1806,7 +1807,7 @@
         if (element->isHTMLElement() && toHTMLElement(element)->isFormControlElement())
             return toHTMLFormControlElement(element)->form();
         if (element->hasTagName(frameTag) || element->hasTagName(iframeTag)) {
-            Node* childDocument = static_cast<HTMLFrameElementBase*>(element)->contentDocument();
+            Node* childDocument = toHTMLFrameElementBase(element)->contentDocument();
             if (HTMLFormElement* frameResult = scanForForm(childDocument))
                 return frameResult;
         }
diff --git a/Source/core/editing/InputMethodController.cpp b/Source/core/editing/InputMethodController.cpp
index 402a8c2..afd8b3c 100644
--- a/Source/core/editing/InputMethodController.cpp
+++ b/Source/core/editing/InputMethodController.cpp
@@ -35,6 +35,7 @@
 #include "core/dom/UserTypingGestureIndicator.h"
 #include "core/editing/Editor.h"
 #include "core/editing/TypingCommand.h"
+#include "core/html/HTMLTextAreaElement.h"
 #include "core/page/EditorClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
@@ -42,6 +43,36 @@
 
 namespace WebCore {
 
+PlainTextOffsets::PlainTextOffsets()
+    : m_start(notFound)
+    , m_end(notFound)
+{
+}
+
+PlainTextOffsets::PlainTextOffsets(int start, int end)
+    : m_start(start)
+    , m_end(end)
+{
+    ASSERT(start != notFound);
+    ASSERT(end != notFound);
+    ASSERT(start <= end);
+}
+
+// ----------------------------
+
+InputMethodController::SelectionOffsetsScope::SelectionOffsetsScope(InputMethodController* inputMethodController)
+    : m_inputMethodController(inputMethodController)
+    , m_offsets(inputMethodController->getSelectionOffsets())
+{
+}
+
+InputMethodController::SelectionOffsetsScope::~SelectionOffsetsScope()
+{
+    m_inputMethodController->setSelectionOffsets(m_offsets);
+}
+
+// ----------------------------
+
 PassOwnPtr<InputMethodController> InputMethodController::create(Frame* frame)
 {
     return adoptPtr(new InputMethodController(frame));
@@ -63,7 +94,7 @@
     return *m_frame->editor();
 }
 
-inline EditorClient* InputMethodController::editorClient() const
+inline EditorClient& InputMethodController::editorClient() const
 {
     return editor().client();
 }
@@ -121,8 +152,7 @@
     }
 
     // EditorClient::willSetInputMethodState() resets input method and the composition string is committed.
-    if (EditorClient* client = editorClient())
-        client->willSetInputMethodState();
+    editorClient().willSetInputMethodState();
 }
 
 void InputMethodController::cancelComposition()
@@ -147,8 +177,7 @@
         return;
 
     cancelComposition();
-    if (editorClient())
-        editorClient()->didCancelCompositionOnSelectionChange();
+    editorClient().didCancelCompositionOnSelectionChange();
 }
 
 void InputMethodController::finishComposition(const String& text, FinishCompositionMode mode)
@@ -282,28 +311,36 @@
 
 void InputMethodController::setCompositionFromExistingText(const Vector<CompositionUnderline>& underlines, unsigned compositionStart, unsigned compositionEnd)
 {
-    m_compositionNode = 0;
-    m_customCompositionUnderlines.clear();
-
+    Node* editable = m_frame->selection()->rootEditableElement();
     Position base = m_frame->selection()->base().downstream();
-    if (base.anchorType() != Position::PositionIsOffsetInAnchor)
-        return;
     Node* baseNode = base.anchorNode();
-    unsigned baseOffset = base.offsetInContainerNode();
-    if (!baseNode || baseNode != m_frame->selection()->extent().anchorNode() || !baseNode->isTextNode())
-        return;
+    if (editable->firstChild() == baseNode && editable->lastChild() == baseNode && baseNode->isTextNode()) {
+        m_compositionNode = 0;
+        m_customCompositionUnderlines.clear();
 
-    m_compositionNode = toText(baseNode);
-    m_compositionStart = compositionStart;
-    m_compositionEnd = compositionEnd;
-    m_customCompositionUnderlines = underlines;
-    size_t numUnderlines = m_customCompositionUnderlines.size();
-    for (size_t i = 0; i < numUnderlines; ++i) {
-        m_customCompositionUnderlines[i].startOffset += baseOffset;
-        m_customCompositionUnderlines[i].endOffset += baseOffset;
+        if (base.anchorType() != Position::PositionIsOffsetInAnchor)
+            return;
+        if (!baseNode || baseNode != m_frame->selection()->extent().anchorNode())
+            return;
+
+        m_compositionNode = toText(baseNode);
+        m_compositionStart = compositionStart;
+        m_compositionEnd = compositionEnd;
+        m_customCompositionUnderlines = underlines;
+        size_t numUnderlines = m_customCompositionUnderlines.size();
+        for (size_t i = 0; i < numUnderlines; ++i) {
+            m_customCompositionUnderlines[i].startOffset += compositionStart;
+            m_customCompositionUnderlines[i].endOffset += compositionStart;
+        }
+        if (baseNode->renderer())
+            baseNode->renderer()->repaint();
+        return;
     }
-    if (baseNode->renderer())
-        baseNode->renderer()->repaint();
+
+    Editor::RevealSelectionScope revealSelectionScope(&editor());
+    SelectionOffsetsScope selectionOffsetsScope(this);
+    setSelectionOffsets(PlainTextOffsets(compositionStart, compositionEnd));
+    setComposition(m_frame->selectedText(), underlines, 0, 0);
 }
 
 PassRefPtr<Range> InputMethodController::compositionRange() const
@@ -318,4 +355,25 @@
     return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
 }
 
+PlainTextOffsets InputMethodController::getSelectionOffsets() const
+{
+    RefPtr<Range> range = m_frame->selection()->selection().firstRange();
+    if (!range)
+        return PlainTextOffsets();
+    size_t location;
+    size_t length;
+    // FIXME: We should change TextIterator::getLocationAndLengthFromRange() returns PlainTextOffsets.
+    if (TextIterator::getLocationAndLengthFromRange(m_frame->selection()->rootEditableElementOrTreeScopeRootNode(), range.get(), location, length))
+        return PlainTextOffsets(location, location + length);
+    return PlainTextOffsets();
+}
+
+bool InputMethodController::setSelectionOffsets(const PlainTextOffsets& selectionOffsets)
+{
+    if (selectionOffsets.isNull())
+        return false;
+    // FIXME: We should move Editor::setSelectionOffsets() into InputMethodController class.
+    return editor().setSelectionOffsets(selectionOffsets.start(), selectionOffsets.end());
+}
+
 } // namespace WebCore
diff --git a/Source/core/editing/InputMethodController.h b/Source/core/editing/InputMethodController.h
index 2351d67..f62cc43 100644
--- a/Source/core/editing/InputMethodController.h
+++ b/Source/core/editing/InputMethodController.h
@@ -37,6 +37,20 @@
 class Range;
 class Text;
 
+// FIXME: We should move PlainTextOffsets to own file for using InputMethodController
+// and TextIterator and unify PlainTextRange defined in AccessibilityObject.h.
+class PlainTextOffsets {
+public:
+    PlainTextOffsets();
+    PlainTextOffsets(int start, int length);
+    size_t end() const { return m_end; }
+    size_t start() const { return m_start; }
+    bool isNull() const { return m_start == notFound; }
+private:
+    size_t m_start;
+    size_t m_end;
+};
+
 class InputMethodController {
 public:
     static PassOwnPtr<InputMethodController> create(Frame*);
@@ -67,19 +81,36 @@
     void clear();
 
 private:
+    class SelectionOffsetsScope {
+        WTF_MAKE_NONCOPYABLE(SelectionOffsetsScope);
+    public:
+        SelectionOffsetsScope(InputMethodController*);
+        ~SelectionOffsetsScope();
+    private:
+        InputMethodController* m_inputMethodController;
+        PlainTextOffsets m_offsets;
+    };
+    friend class SelectionOffsetsScope;
+
     Frame* m_frame;
     RefPtr<Text> m_compositionNode;
+    // FIXME: We should use PlainTextOffsets m_compositionRange instead of
+    // m_compositionStart/m_compositionEnd.
     unsigned m_compositionStart;
     unsigned m_compositionEnd;
+    // startOffset and endOffset of CompositionUnderline are based on
+    // m_compositionNode.
     Vector<CompositionUnderline> m_customCompositionUnderlines;
 
     explicit InputMethodController(Frame*);
     Editor& editor() const;
-    EditorClient* editorClient() const;
+    EditorClient& editorClient() const;
     bool insertTextForConfirmedComposition(const String& text);
     void selectComposition() const;
     enum FinishCompositionMode { ConfirmComposition, CancelComposition };
     void finishComposition(const String&, FinishCompositionMode);
+    PlainTextOffsets getSelectionOffsets() const;
+    bool setSelectionOffsets(const PlainTextOffsets&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/InsertIntoTextNodeCommand.cpp b/Source/core/editing/InsertIntoTextNodeCommand.cpp
index 75a68b5..4ce67f2 100644
--- a/Source/core/editing/InsertIntoTextNodeCommand.cpp
+++ b/Source/core/editing/InsertIntoTextNodeCommand.cpp
@@ -61,7 +61,7 @@
             renderText->momentarilyRevealLastTypedCharacter(m_offset + m_text.length() - 1);
     }
 
-    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION);
+    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION, DeprecatedAttachNow);
 
     if (AXObjectCache* cache = document()->existingAXObjectCache())
         cache->nodeTextChangeNotification(m_node.get(), AXObjectCache::AXTextInserted, m_offset, m_text);
@@ -76,7 +76,7 @@
     if (AXObjectCache* cache = document()->existingAXObjectCache())
         cache->nodeTextChangeNotification(m_node.get(), AXObjectCache::AXTextDeleted, m_offset, m_text);
 
-    m_node->deleteData(m_offset, m_text.length(), IGNORE_EXCEPTION);
+    m_node->deleteData(m_offset, m_text.length(), IGNORE_EXCEPTION, DeprecatedAttachNow);
 }
 
 #ifndef NDEBUG
diff --git a/Source/core/editing/InsertNodeBeforeCommand.cpp b/Source/core/editing/InsertNodeBeforeCommand.cpp
index 989f32b..f2ba9b2 100644
--- a/Source/core/editing/InsertNodeBeforeCommand.cpp
+++ b/Source/core/editing/InsertNodeBeforeCommand.cpp
@@ -54,7 +54,7 @@
         return;
     ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable));
 
-    parent->insertBefore(m_insertChild.get(), m_refChild.get(), IGNORE_EXCEPTION, AttachLazily);
+    parent->insertBefore(m_insertChild.get(), m_refChild.get(), IGNORE_EXCEPTION);
 
     if (AXObjectCache* cache = document()->existingAXObjectCache())
         cache->nodeTextChangeNotification(m_insertChild.get(), AXObjectCache::AXTextInserted, 0, m_insertChild->nodeValue());
diff --git a/Source/core/editing/MergeIdenticalElementsCommand.cpp b/Source/core/editing/MergeIdenticalElementsCommand.cpp
index e94a7fb..6d8ccfc 100644
--- a/Source/core/editing/MergeIdenticalElementsCommand.cpp
+++ b/Source/core/editing/MergeIdenticalElementsCommand.cpp
@@ -55,7 +55,7 @@
 
     size_t size = children.size();
     for (size_t i = 0; i < size; ++i)
-        m_element2->insertBefore(children[i].release(), m_atChild.get(), IGNORE_EXCEPTION);
+        m_element2->insertBefore(children[i].release(), m_atChild.get(), IGNORE_EXCEPTION, DeprecatedAttachNow);
 
     m_element1->remove(IGNORE_EXCEPTION);
 }
@@ -73,7 +73,7 @@
 
     TrackExceptionState es;
 
-    parent->insertBefore(m_element1.get(), m_element2.get(), es);
+    parent->insertBefore(m_element1.get(), m_element2.get(), es, DeprecatedAttachNow);
     if (es.hadException())
         return;
 
@@ -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(), es, DeprecatedAttachNow);
 }
 
 #ifndef NDEBUG
diff --git a/Source/core/editing/ReplaceNodeWithSpanCommand.cpp b/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
index 3c262ae..0d9d5f7 100644
--- a/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
+++ b/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
@@ -52,12 +52,12 @@
 {
     ASSERT(nodeToReplace->inDocument());
     RefPtr<ContainerNode> parentNode = nodeToReplace->parentNode();
-    parentNode->insertBefore(newNode, nodeToReplace, ASSERT_NO_EXCEPTION);
+    parentNode->insertBefore(newNode, nodeToReplace, ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
 
     NodeVector children;
     getChildNodes(nodeToReplace, children);
     for (size_t i = 0; i < children.size(); ++i)
-        newNode->appendChild(children[i], ASSERT_NO_EXCEPTION);
+        newNode->appendChild(children[i], ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
 
     // FIXME: Fix this to send the proper MutationRecords when MutationObservers are present.
     newNode->cloneDataFromElement(*nodeToReplace);
diff --git a/Source/core/editing/ReplaceSelectionCommand.cpp b/Source/core/editing/ReplaceSelectionCommand.cpp
index af2d661..d09ae47 100644
--- a/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -241,15 +241,15 @@
     if (!parent)
         return;
 
-    parent->insertBefore(node, refNode, ASSERT_NO_EXCEPTION);
+    parent->insertBefore(node, refNode, ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
 }
 
 PassRefPtr<Element> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
 {
     RefPtr<Element> holder = createDefaultParagraphElement(m_document.get());
 
-    holder->appendChild(m_fragment, ASSERT_NO_EXCEPTION);
-    rootEditableElement->appendChild(holder.get(), ASSERT_NO_EXCEPTION);
+    holder->appendChild(m_fragment, ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
+    rootEditableElement->appendChild(holder.get(), ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
     m_document->updateLayoutIgnorePendingStylesheets();
 
     return holder.release();
@@ -262,7 +262,7 @@
 
     while (RefPtr<Node> node = holder->firstChild()) {
         holder->removeChild(node.get(), ASSERT_NO_EXCEPTION);
-        m_fragment->appendChild(node.get(), ASSERT_NO_EXCEPTION);
+        m_fragment->appendChild(node.get(), ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
     }
 
     removeNode(holder);
diff --git a/Source/core/editing/SpellCheckRequester.cpp b/Source/core/editing/SpellCheckRequester.cpp
index af2ad11..4010d38 100644
--- a/Source/core/editing/SpellCheckRequester.cpp
+++ b/Source/core/editing/SpellCheckRequester.cpp
@@ -46,12 +46,14 @@
     TextCheckingTypeMask mask,
     TextCheckingProcessType processType,
     const Vector<uint32_t>& documentMarkersInRange,
-    const Vector<unsigned>& documentMarkerOffsets)
-    : m_checker(0)
+    const Vector<unsigned>& documentMarkerOffsets,
+    int requestNumber)
+    : m_requester(0)
     , m_checkingRange(checkingRange)
     , m_paragraphRange(paragraphRange)
     , m_rootEditableElement(m_checkingRange->startContainer()->rootEditableElement())
     , m_requestData(unrequestedTextCheckingSequence, text, mask, processType, documentMarkersInRange, documentMarkerOffsets)
+    , m_requestNumber(requestNumber)
 {
 }
 
@@ -60,7 +62,7 @@
 }
 
 // static
-PassRefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask textCheckingOptions, TextCheckingProcessType processType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange)
+PassRefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask textCheckingOptions, TextCheckingProcessType processType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, int requestNubmer)
 {
     ASSERT(checkingRange);
     ASSERT(paragraphRange);
@@ -77,7 +79,7 @@
         offsets[i] = markers[i]->startOffset();
     }
 
-    return adoptRef(new SpellCheckRequest(checkingRange, paragraphRange, text, textCheckingOptions, processType, hashes, offsets));
+    return adoptRef(new SpellCheckRequest(checkingRange, paragraphRange, text, textCheckingOptions, processType, hashes, offsets, requestNubmer));
 }
 
 const TextCheckingRequestData& SpellCheckRequest::data() const
@@ -87,44 +89,44 @@
 
 void SpellCheckRequest::didSucceed(const Vector<TextCheckingResult>& results)
 {
-    if (!m_checker)
+    if (!m_requester)
         return;
-    SpellChecker* checker = m_checker;
-    m_checker = 0;
-    checker->didCheckSucceed(m_requestData.sequence(), results);
+    SpellCheckRequester* requester = m_requester;
+    m_requester = 0;
+    requester->didCheckSucceed(m_requestData.sequence(), results);
 }
 
 void SpellCheckRequest::didCancel()
 {
-    if (!m_checker)
+    if (!m_requester)
         return;
-    SpellChecker* checker = m_checker;
-    m_checker = 0;
-    checker->didCheckCancel(m_requestData.sequence());
+    SpellCheckRequester* requester = m_requester;
+    m_requester = 0;
+    requester->didCheckCancel(m_requestData.sequence());
 }
 
-void SpellCheckRequest::setCheckerAndSequence(SpellChecker* requester, int sequence)
+void SpellCheckRequest::setCheckerAndSequence(SpellCheckRequester* requester, int sequence)
 {
-    ASSERT(!m_checker);
+    ASSERT(!m_requester);
     ASSERT(m_requestData.sequence() == unrequestedTextCheckingSequence);
-    m_checker = requester;
+    m_requester = requester;
     m_requestData.m_sequence = sequence;
 }
 
 void SpellCheckRequest::requesterDestroyed()
 {
-    m_checker = 0;
+    m_requester = 0;
 }
 
-SpellChecker::SpellChecker(Frame* frame)
+SpellCheckRequester::SpellCheckRequester(Frame* frame)
     : m_frame(frame)
     , m_lastRequestSequence(0)
     , m_lastProcessedSequence(0)
-    , m_timerToProcessQueuedRequest(this, &SpellChecker::timerFiredToProcessQueuedRequest)
+    , m_timerToProcessQueuedRequest(this, &SpellCheckRequester::timerFiredToProcessQueuedRequest)
 {
 }
 
-SpellChecker::~SpellChecker()
+SpellCheckRequester::~SpellCheckRequester()
 {
     if (m_processingRequest)
         m_processingRequest->requesterDestroyed();
@@ -132,15 +134,12 @@
         (*i)->requesterDestroyed();
 }
 
-TextCheckerClient* SpellChecker::client() const
+TextCheckerClient& SpellCheckRequester::client() const
 {
-    Page* page = m_frame->page();
-    if (!page)
-        return 0;
-    return page->editorClient()->textChecker();
+    return m_frame->editor()->client().textChecker();
 }
 
-void SpellChecker::timerFiredToProcessQueuedRequest(Timer<SpellChecker>*)
+void SpellCheckRequester::timerFiredToProcessQueuedRequest(Timer<SpellCheckRequester>*)
 {
     ASSERT(!m_requestQueue.isEmpty());
     if (m_requestQueue.isEmpty())
@@ -149,17 +148,17 @@
     invokeRequest(m_requestQueue.takeFirst());
 }
 
-bool SpellChecker::isAsynchronousEnabled() const
+bool SpellCheckRequester::isAsynchronousEnabled() const
 {
     return m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled();
 }
 
-bool SpellChecker::canCheckAsynchronously(Range* range) const
+bool SpellCheckRequester::canCheckAsynchronously(Range* range) const
 {
-    return client() && isCheckable(range) && isAsynchronousEnabled();
+    return isCheckable(range) && isAsynchronousEnabled();
 }
 
-bool SpellChecker::isCheckable(Range* range) const
+bool SpellCheckRequester::isCheckable(Range* range) const
 {
     if (!range || !range->firstNode() || !range->firstNode()->renderer())
         return false;
@@ -169,7 +168,7 @@
     return true;
 }
 
-void SpellChecker::requestCheckingFor(PassRefPtr<SpellCheckRequest> request)
+void SpellCheckRequester::requestCheckingFor(PassRefPtr<SpellCheckRequest> request)
 {
     if (!request || !canCheckAsynchronously(request->paragraphRange().get()))
         return;
@@ -189,37 +188,46 @@
     invokeRequest(request);
 }
 
-void SpellChecker::cancelCheck()
+void SpellCheckRequester::cancelCheck()
 {
     if (m_processingRequest)
         m_processingRequest->didCancel();
 }
 
-void SpellChecker::invokeRequest(PassRefPtr<SpellCheckRequest> request)
+void SpellCheckRequester::invokeRequest(PassRefPtr<SpellCheckRequest> request)
 {
     ASSERT(!m_processingRequest);
-    if (!client())
-        return;
     m_processingRequest = request;
-    client()->requestCheckingOfString(m_processingRequest);
+    client().requestCheckingOfString(m_processingRequest);
 }
 
-void SpellChecker::enqueueRequest(PassRefPtr<SpellCheckRequest> request)
+void SpellCheckRequester::enqueueRequest(PassRefPtr<SpellCheckRequest> request)
 {
     ASSERT(request);
+    bool continuation = false;
+    if (!m_requestQueue.isEmpty()) {
+        RefPtr<SpellCheckRequest> lastRequest = m_requestQueue.last();
+        // It's a continuation if the number of the last request got incremented in the new one and
+        // both apply to the same editable.
+        continuation = request->rootEditableElement() == lastRequest->rootEditableElement()
+            && request->requestNumber() == lastRequest->requestNumber() + 1;
+    }
 
-    for (RequestQueue::iterator it = m_requestQueue.begin(); it != m_requestQueue.end(); ++it) {
-        if (request->rootEditableElement() != (*it)->rootEditableElement())
-            continue;
+    // Spellcheck requests for chunks of text in the same element should not overwrite each other.
+    if (!continuation) {
+        for (RequestQueue::iterator it = m_requestQueue.begin(); it != m_requestQueue.end(); ++it) {
+            if (request->rootEditableElement() != (*it)->rootEditableElement())
+                continue;
 
-        *it = request;
-        return;
+            *it = request;
+            return;
+        }
     }
 
     m_requestQueue.append(request);
 }
 
-void SpellChecker::didCheck(int sequence, const Vector<TextCheckingResult>& results)
+void SpellCheckRequester::didCheck(int sequence, const Vector<TextCheckingResult>& results)
 {
     ASSERT(m_processingRequest);
     ASSERT(m_processingRequest->data().sequence() == sequence);
@@ -238,7 +246,7 @@
         m_timerToProcessQueuedRequest.startOneShot(0);
 }
 
-void SpellChecker::didCheckSucceed(int sequence, const Vector<TextCheckingResult>& results)
+void SpellCheckRequester::didCheckSucceed(int sequence, const Vector<TextCheckingResult>& results)
 {
     TextCheckingRequestData requestData = m_processingRequest->data();
     if (requestData.sequence() == sequence) {
@@ -253,7 +261,7 @@
     didCheck(sequence, results);
 }
 
-void SpellChecker::didCheckCancel(int sequence)
+void SpellCheckRequester::didCheckCancel(int sequence)
 {
     Vector<TextCheckingResult> results;
     didCheck(sequence, results);
diff --git a/Source/core/editing/SpellCheckRequester.h b/Source/core/editing/SpellCheckRequester.h
index 0165f32..0d9c3ce 100644
--- a/Source/core/editing/SpellCheckRequester.h
+++ b/Source/core/editing/SpellCheckRequester.h
@@ -40,43 +40,46 @@
 
 class Frame;
 class Node;
+class SpellCheckRequester;
 class TextCheckerClient;
-class SpellChecker;
 
 class SpellCheckRequest : public TextCheckingRequest {
 public:
-    static PassRefPtr<SpellCheckRequest> create(TextCheckingTypeMask, TextCheckingProcessType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange);
+    static PassRefPtr<SpellCheckRequest> create(TextCheckingTypeMask, TextCheckingProcessType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, int requestNumber = 0);
     virtual ~SpellCheckRequest();
 
     PassRefPtr<Range> checkingRange() const { return m_checkingRange; }
     PassRefPtr<Range> paragraphRange() const { return m_paragraphRange; }
     PassRefPtr<Element> rootEditableElement() const { return m_rootEditableElement; }
 
-    void setCheckerAndSequence(SpellChecker*, int sequence);
+    void setCheckerAndSequence(SpellCheckRequester*, int sequence);
     void requesterDestroyed();
-    bool isStarted() const { return m_checker; }
+    bool isStarted() const { return m_requester; }
 
     virtual const TextCheckingRequestData& data() const OVERRIDE;
     virtual void didSucceed(const Vector<TextCheckingResult>&) OVERRIDE;
     virtual void didCancel() OVERRIDE;
 
-private:
-    SpellCheckRequest(PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, const String&, TextCheckingTypeMask, TextCheckingProcessType, const Vector<uint32_t>& documentMarkersInRange, const Vector<unsigned>& documentMarkerOffsets);
+    int requestNumber() const { return m_requestNumber; }
 
-    SpellChecker* m_checker;
+private:
+    SpellCheckRequest(PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, const String&, TextCheckingTypeMask, TextCheckingProcessType, const Vector<uint32_t>& documentMarkersInRange, const Vector<unsigned>& documentMarkerOffsets, int requestNumber);
+
+    SpellCheckRequester* m_requester;
     RefPtr<Range> m_checkingRange;
     RefPtr<Range> m_paragraphRange;
     RefPtr<Element> m_rootEditableElement;
     TextCheckingRequestData m_requestData;
+    int m_requestNumber;
 };
 
-class SpellChecker {
-    WTF_MAKE_NONCOPYABLE(SpellChecker); WTF_MAKE_FAST_ALLOCATED;
+class SpellCheckRequester {
+    WTF_MAKE_NONCOPYABLE(SpellCheckRequester); WTF_MAKE_FAST_ALLOCATED;
 public:
     friend class SpellCheckRequest;
 
-    explicit SpellChecker(Frame*);
-    ~SpellChecker();
+    explicit SpellCheckRequester(Frame*);
+    ~SpellCheckRequester();
 
     bool isAsynchronousEnabled() const;
     bool isCheckable(Range*) const;
@@ -98,8 +101,8 @@
     typedef Deque<RefPtr<SpellCheckRequest> > RequestQueue;
 
     bool canCheckAsynchronously(Range*) const;
-    TextCheckerClient* client() const;
-    void timerFiredToProcessQueuedRequest(Timer<SpellChecker>*);
+    TextCheckerClient& client() const;
+    void timerFiredToProcessQueuedRequest(Timer<SpellCheckRequester>*);
     void invokeRequest(PassRefPtr<SpellCheckRequest>);
     void enqueueRequest(PassRefPtr<SpellCheckRequest>);
     void didCheckSucceed(int sequence, const Vector<TextCheckingResult>&);
@@ -110,7 +113,7 @@
     int m_lastRequestSequence;
     int m_lastProcessedSequence;
 
-    Timer<SpellChecker> m_timerToProcessQueuedRequest;
+    Timer<SpellCheckRequester> m_timerToProcessQueuedRequest;
 
     RefPtr<SpellCheckRequest> m_processingRequest;
     RequestQueue m_requestQueue;
diff --git a/Source/core/editing/SpellChecker.cpp b/Source/core/editing/SpellChecker.cpp
deleted file mode 100644
index 97c1fd8..0000000
--- a/Source/core/editing/SpellChecker.cpp
+++ /dev/null
@@ -1,262 +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.
- */
-
-#include "config.h"
-#include "core/editing/SpellChecker.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/DocumentMarkerController.h"
-#include "core/dom/Node.h"
-#include "core/dom/Range.h"
-#include "core/editing/Editor.h"
-#include "core/page/EditorClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/text/TextCheckerClient.h"
-
-namespace WebCore {
-
-SpellCheckRequest::SpellCheckRequest(
-        PassRefPtr<Range> checkingRange,
-        PassRefPtr<Range> paragraphRange,
-        const String& text,
-        TextCheckingTypeMask mask,
-        TextCheckingProcessType processType,
-        const Vector<uint32_t>& documentMarkersInRange,
-        const Vector<unsigned>& documentMarkerOffsets)
-    : m_checker(0)
-    , m_checkingRange(checkingRange)
-    , m_paragraphRange(paragraphRange)
-    , m_rootEditableElement(m_checkingRange->startContainer()->rootEditableElement())
-    , m_requestData(unrequestedTextCheckingSequence, text, mask, processType, documentMarkersInRange, documentMarkerOffsets)
-{
-}
-
-SpellCheckRequest::~SpellCheckRequest()
-{
-}
-
-// static
-PassRefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask textCheckingOptions, TextCheckingProcessType processType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange)
-{
-    ASSERT(checkingRange);
-    ASSERT(paragraphRange);
-
-    String text = checkingRange->text();
-    if (!text.length())
-        return PassRefPtr<SpellCheckRequest>();
-
-    const Vector<DocumentMarker*>& markers = checkingRange->ownerDocument()->markers()->markersInRange(checkingRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar);
-    Vector<uint32_t> hashes(markers.size());
-    Vector<unsigned> offsets(markers.size());
-    for (size_t i = 0; i < markers.size(); i++) {
-        hashes[i] = markers[i]->hash();
-        offsets[i] = markers[i]->startOffset();
-    }
-
-    return adoptRef(new SpellCheckRequest(checkingRange, paragraphRange, text, textCheckingOptions, processType, hashes, offsets));
-}
-
-const TextCheckingRequestData& SpellCheckRequest::data() const
-{
-    return m_requestData;
-}
-
-void SpellCheckRequest::didSucceed(const Vector<TextCheckingResult>& results)
-{
-    if (!m_checker)
-        return;
-    SpellChecker* checker = m_checker;
-    m_checker = 0;
-    checker->didCheckSucceed(m_requestData.sequence(), results);
-}
-
-void SpellCheckRequest::didCancel()
-{
-    if (!m_checker)
-        return;
-    SpellChecker* checker = m_checker;
-    m_checker = 0;
-    checker->didCheckCancel(m_requestData.sequence());
-}
-
-void SpellCheckRequest::setCheckerAndSequence(SpellChecker* requester, int sequence)
-{
-    ASSERT(!m_checker);
-    ASSERT(m_requestData.sequence() == unrequestedTextCheckingSequence);
-    m_checker = requester;
-    m_requestData.m_sequence = sequence;
-}
-
-void SpellCheckRequest::requesterDestroyed()
-{
-    m_checker = 0;
-}
-
-SpellChecker::SpellChecker(Frame* frame)
-    : m_frame(frame)
-    , m_lastRequestSequence(0)
-    , m_lastProcessedSequence(0)
-    , m_timerToProcessQueuedRequest(this, &SpellChecker::timerFiredToProcessQueuedRequest)
-{
-}
-
-SpellChecker::~SpellChecker()
-{
-    if (m_processingRequest)
-        m_processingRequest->requesterDestroyed();
-    for (RequestQueue::iterator i = m_requestQueue.begin(); i != m_requestQueue.end(); ++i)
-        (*i)->requesterDestroyed();
-}
-
-TextCheckerClient* SpellChecker::client() const
-{
-    Page* page = m_frame->page();
-    if (!page)
-        return 0;
-    return page->editorClient()->textChecker();
-}
-
-void SpellChecker::timerFiredToProcessQueuedRequest(Timer<SpellChecker>*)
-{
-    ASSERT(!m_requestQueue.isEmpty());
-    if (m_requestQueue.isEmpty())
-        return;
-
-    invokeRequest(m_requestQueue.takeFirst());
-}
-
-bool SpellChecker::isAsynchronousEnabled() const
-{
-    return m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled();
-}
-
-bool SpellChecker::canCheckAsynchronously(Range* range) const
-{
-    return client() && isCheckable(range) && isAsynchronousEnabled();
-}
-
-bool SpellChecker::isCheckable(Range* range) const
-{
-    if (!range || !range->firstNode() || !range->firstNode()->renderer())
-        return false;
-    const Node* node = range->startContainer();
-    if (node && node->isElementNode() && !toElement(node)->isSpellCheckingEnabled())
-        return false;
-    return true;
-}
-
-void SpellChecker::requestCheckingFor(PassRefPtr<SpellCheckRequest> request)
-{
-    if (!request || !canCheckAsynchronously(request->paragraphRange().get()))
-        return;
-
-    ASSERT(request->data().sequence() == unrequestedTextCheckingSequence);
-    int sequence = ++m_lastRequestSequence;
-    if (sequence == unrequestedTextCheckingSequence)
-        sequence = ++m_lastRequestSequence;
-
-    request->setCheckerAndSequence(this, sequence);
-
-    if (m_timerToProcessQueuedRequest.isActive() || m_processingRequest) {
-        enqueueRequest(request);
-        return;
-    }
-
-    invokeRequest(request);
-}
-
-void SpellChecker::cancelCheck()
-{
-    if (m_processingRequest)
-        m_processingRequest->didCancel();
-}
-
-void SpellChecker::invokeRequest(PassRefPtr<SpellCheckRequest> request)
-{
-    ASSERT(!m_processingRequest);
-    if (!client())
-        return;
-    m_processingRequest = request;
-    client()->requestCheckingOfString(m_processingRequest);
-}
-
-void SpellChecker::enqueueRequest(PassRefPtr<SpellCheckRequest> request)
-{
-    ASSERT(request);
-
-    for (RequestQueue::iterator it = m_requestQueue.begin(); it != m_requestQueue.end(); ++it) {
-        if (request->rootEditableElement() != (*it)->rootEditableElement())
-            continue;
-
-        *it = request;
-        return;
-    }
-
-    m_requestQueue.append(request);
-}
-
-void SpellChecker::didCheck(int sequence, const Vector<TextCheckingResult>& results)
-{
-    ASSERT(m_processingRequest);
-    ASSERT(m_processingRequest->data().sequence() == sequence);
-    if (m_processingRequest->data().sequence() != sequence) {
-        m_requestQueue.clear();
-        return;
-    }
-
-    m_frame->editor()->markAndReplaceFor(m_processingRequest, results);
-
-    if (m_lastProcessedSequence < sequence)
-        m_lastProcessedSequence = sequence;
-
-    m_processingRequest.clear();
-    if (!m_requestQueue.isEmpty())
-        m_timerToProcessQueuedRequest.startOneShot(0);
-}
-
-void SpellChecker::didCheckSucceed(int sequence, const Vector<TextCheckingResult>& results)
-{
-    TextCheckingRequestData requestData = m_processingRequest->data();
-    if (requestData.sequence() == sequence) {
-        unsigned markers = 0;
-        if (requestData.mask() & TextCheckingTypeSpelling)
-            markers |= DocumentMarker::Spelling;
-        if (requestData.mask() & TextCheckingTypeGrammar)
-            markers |= DocumentMarker::Grammar;
-        if (markers)
-            m_frame->document()->markers()->removeMarkers(m_processingRequest->checkingRange().get(), markers);
-    }
-    didCheck(sequence, results);
-}
-
-void SpellChecker::didCheckCancel(int sequence)
-{
-    Vector<TextCheckingResult> results;
-    didCheck(sequence, results);
-}
-
-} // namespace WebCore
diff --git a/Source/core/editing/SpellChecker.h b/Source/core/editing/SpellChecker.h
deleted file mode 100644
index 44a6b5a..0000000
--- a/Source/core/editing/SpellChecker.h
+++ /dev/null
@@ -1,121 +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 SpellChecker_h
-#define SpellChecker_h
-
-#include "core/dom/Element.h"
-#include "core/dom/Range.h"
-#include "core/platform/Timer.h"
-#include "core/platform/text/TextChecking.h"
-#include "wtf/Deque.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Frame;
-class Node;
-class TextCheckerClient;
-class SpellChecker;
-
-class SpellCheckRequest : public TextCheckingRequest {
-public:
-    static PassRefPtr<SpellCheckRequest> create(TextCheckingTypeMask, TextCheckingProcessType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange);
-    virtual ~SpellCheckRequest();
-
-    PassRefPtr<Range> checkingRange() const { return m_checkingRange; }
-    PassRefPtr<Range> paragraphRange() const { return m_paragraphRange; }
-    PassRefPtr<Element> rootEditableElement() const { return m_rootEditableElement; }
-
-    void setCheckerAndSequence(SpellChecker*, int sequence);
-    void requesterDestroyed();
-    bool isStarted() const { return m_checker; }
-
-    virtual const TextCheckingRequestData& data() const OVERRIDE;
-    virtual void didSucceed(const Vector<TextCheckingResult>&) OVERRIDE;
-    virtual void didCancel() OVERRIDE;
-
-private:
-    SpellCheckRequest(PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, const String&, TextCheckingTypeMask, TextCheckingProcessType, const Vector<uint32_t>& documentMarkersInRange, const Vector<unsigned>& documentMarkerOffsets);
-
-    SpellChecker* m_checker;
-    RefPtr<Range> m_checkingRange;
-    RefPtr<Range> m_paragraphRange;
-    RefPtr<Element> m_rootEditableElement;
-    TextCheckingRequestData m_requestData;
-};
-
-class SpellChecker {
-    WTF_MAKE_NONCOPYABLE(SpellChecker); WTF_MAKE_FAST_ALLOCATED;
-public:
-    friend class SpellCheckRequest;
-
-    explicit SpellChecker(Frame*);
-    ~SpellChecker();
-
-    bool isAsynchronousEnabled() const;
-    bool isCheckable(Range*) const;
-
-    void requestCheckingFor(PassRefPtr<SpellCheckRequest>);
-    void cancelCheck();
-
-    int lastRequestSequence() const
-    {
-        return m_lastRequestSequence;
-    }
-
-    int lastProcessedSequence() const
-    {
-        return m_lastProcessedSequence;
-    }
-
-private:
-    typedef Deque<RefPtr<SpellCheckRequest> > RequestQueue;
-
-    bool canCheckAsynchronously(Range*) const;
-    TextCheckerClient* client() const;
-    void timerFiredToProcessQueuedRequest(Timer<SpellChecker>*);
-    void invokeRequest(PassRefPtr<SpellCheckRequest>);
-    void enqueueRequest(PassRefPtr<SpellCheckRequest>);
-    void didCheckSucceed(int sequence, const Vector<TextCheckingResult>&);
-    void didCheckCancel(int sequence);
-    void didCheck(int sequence, const Vector<TextCheckingResult>&);
-
-    Frame* m_frame;
-    int m_lastRequestSequence;
-    int m_lastProcessedSequence;
-
-    Timer<SpellChecker> m_timerToProcessQueuedRequest;
-
-    RefPtr<SpellCheckRequest> m_processingRequest;
-    RequestQueue m_requestQueue;
-};
-
-} // namespace WebCore
-
-#endif // SpellChecker_h
diff --git a/Source/core/editing/SplitTextNodeCommand.cpp b/Source/core/editing/SplitTextNodeCommand.cpp
index 723cf71..0a57ef7 100644
--- a/Source/core/editing/SplitTextNodeCommand.cpp
+++ b/Source/core/editing/SplitTextNodeCommand.cpp
@@ -76,7 +76,7 @@
 
     String prefixText = m_text1->data();
 
-    m_text2->insertData(0, prefixText, ASSERT_NO_EXCEPTION);
+    m_text2->insertData(0, prefixText, ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
 
     document()->markers()->copyMarkers(m_text1.get(), 0, prefixText.length(), m_text2.get(), 0);
     m_text1->remove(ASSERT_NO_EXCEPTION);
@@ -100,7 +100,7 @@
     m_text2->parentNode()->insertBefore(m_text1.get(), m_text2.get(), es);
     if (es.hadException())
         return;
-    m_text2->deleteData(0, m_offset, es);
+    m_text2->deleteData(0, m_offset, es, DeprecatedAttachNow);
 }
 
 #ifndef NDEBUG
diff --git a/Source/core/editing/TextCheckingHelper.cpp b/Source/core/editing/TextCheckingHelper.cpp
index 88d171b..c6e89bd 100644
--- a/Source/core/editing/TextCheckingHelper.cpp
+++ b/Source/core/editing/TextCheckingHelper.cpp
@@ -42,7 +42,7 @@
 
 namespace WebCore {
 
-static void findBadGrammars(TextCheckerClient* client, const UChar* text, int start, int length, Vector<TextCheckingResult>& results)
+static void findBadGrammars(TextCheckerClient& client, const UChar* text, int start, int length, Vector<TextCheckingResult>& results)
 {
     int checkLocation = start;
     int checkLength = length;
@@ -51,7 +51,7 @@
         int badGrammarLocation = -1;
         int badGrammarLength = 0;
         Vector<GrammarDetail> badGrammarDetails;
-        client->checkGrammarOfString(String(text + checkLocation, checkLength), badGrammarDetails, &badGrammarLocation, &badGrammarLength);
+        client.checkGrammarOfString(String(text + checkLocation, checkLength), badGrammarDetails, &badGrammarLocation, &badGrammarLength);
         if (!badGrammarLength)
             break;
         ASSERT(0 <= badGrammarLocation && badGrammarLocation <= checkLength);
@@ -68,7 +68,7 @@
     }
 }
 
-static void findMisspellings(TextCheckerClient* client, const UChar* text, int start, int length, Vector<TextCheckingResult>& results)
+static void findMisspellings(TextCheckerClient& client, const UChar* text, int start, int length, Vector<TextCheckingResult>& results)
 {
     TextBreakIterator* iterator = wordBreakIterator(text + start, length);
     if (!iterator)
@@ -81,7 +81,7 @@
         int wordLength = wordEnd - wordStart;
         int misspellingLocation = -1;
         int misspellingLength = 0;
-        client->checkSpellingOfString(String(text + start + wordStart, wordLength), &misspellingLocation, &misspellingLength);
+        client.checkSpellingOfString(String(text + start + wordStart, wordLength), &misspellingLocation, &misspellingLength);
         if (0 < misspellingLength) {
             ASSERT(0 <= misspellingLocation && misspellingLocation <= wordLength);
             ASSERT(0 < misspellingLength && misspellingLocation + misspellingLength <= wordLength);
@@ -89,7 +89,7 @@
             misspelling.type = TextCheckingTypeSpelling;
             misspelling.location = start + wordStart + misspellingLocation;
             misspelling.length = misspellingLength;
-            misspelling.replacement = client->getAutoCorrectSuggestionForMisspelledWord(String(text + misspelling.location, misspelling.length));
+            misspelling.replacement = client.getAutoCorrectSuggestionForMisspelledWord(String(text + misspelling.location, misspelling.length));
             results.append(misspelling);
         }
 
@@ -218,11 +218,10 @@
     return m_checkingLength;
 }
 
-TextCheckingHelper::TextCheckingHelper(EditorClient* client, PassRefPtr<Range> range)
-    : m_client(client)
+TextCheckingHelper::TextCheckingHelper(EditorClient& client, PassRefPtr<Range> range)
+    : m_client(&client)
     , m_range(range)
 {
-    ASSERT_ARG(m_client, m_client);
     ASSERT_ARG(m_range, m_range);
 }
 
@@ -246,7 +245,7 @@
 
             int misspellingLocation = -1;
             int misspellingLength = 0;
-            m_client->textChecker()->checkSpellingOfString(it.substring(0, length), &misspellingLocation, &misspellingLength);
+            m_client->textChecker().checkSpellingOfString(it.substring(0, length), &misspellingLocation, &misspellingLength);
 
             // 5490627 shows that there was some code path here where the String constructor below crashes.
             // We don't know exactly what combination of bad input caused this, so we're making this much
@@ -467,7 +466,7 @@
         Vector<GrammarDetail> grammarDetails;
         int badGrammarPhraseLocation = -1;
         int badGrammarPhraseLength = 0;
-        m_client->textChecker()->checkGrammarOfString(paragraph.textSubstring(startOffset), grammarDetails, &badGrammarPhraseLocation, &badGrammarPhraseLength);
+        m_client->textChecker().checkGrammarOfString(paragraph.textSubstring(startOffset), grammarDetails, &badGrammarPhraseLocation, &badGrammarPhraseLength);
 
         if (!badGrammarPhraseLength) {
             ASSERT(badGrammarPhraseLocation == -1);
@@ -533,7 +532,7 @@
     return WebCore::unifiedTextCheckerEnabled(doc->frame());
 }
 
-void checkTextOfParagraph(TextCheckerClient* client, const String& text, TextCheckingTypeMask checkingTypes, Vector<TextCheckingResult>& results)
+void checkTextOfParagraph(TextCheckerClient& client, const String& text, TextCheckingTypeMask checkingTypes, Vector<TextCheckingResult>& results)
 {
     Vector<UChar> characters;
     text.appendTo(characters);
diff --git a/Source/core/editing/TextCheckingHelper.h b/Source/core/editing/TextCheckingHelper.h
index 853e089..b67e217 100644
--- a/Source/core/editing/TextCheckingHelper.h
+++ b/Source/core/editing/TextCheckingHelper.h
@@ -77,7 +77,7 @@
 class TextCheckingHelper {
     WTF_MAKE_NONCOPYABLE(TextCheckingHelper);
 public:
-    TextCheckingHelper(EditorClient*, PassRefPtr<Range>);
+    TextCheckingHelper(EditorClient&, PassRefPtr<Range>);
     ~TextCheckingHelper();
 
     String findFirstMisspelling(int& firstMisspellingOffset, bool markAll, RefPtr<Range>& firstMisspellingRange);
@@ -94,7 +94,7 @@
     bool unifiedTextCheckerEnabled() const;
 };
 
-void checkTextOfParagraph(TextCheckerClient*, const String&, TextCheckingTypeMask, Vector<TextCheckingResult>&);
+void checkTextOfParagraph(TextCheckerClient&, const String&, TextCheckingTypeMask, Vector<TextCheckingResult>&);
 
 bool unifiedTextCheckerEnabled(const Frame*);
 
diff --git a/Source/core/editing/TypingCommand.cpp b/Source/core/editing/TypingCommand.cpp
index 6c52965..7ae6b05 100644
--- a/Source/core/editing/TypingCommand.cpp
+++ b/Source/core/editing/TypingCommand.cpp
@@ -35,7 +35,7 @@
 #include "core/editing/InsertLineBreakCommand.h"
 #include "core/editing/InsertParagraphSeparatorCommand.h"
 #include "core/editing/InsertTextCommand.h"
-#include "core/editing/SpellChecker.h"
+#include "core/editing/SpellCheckRequester.h"
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
@@ -299,7 +299,7 @@
     if (!frame->editor()->isContinuousSpellCheckingEnabled())
         return;
 
-    frame->editor()->spellChecker()->cancelCheck();
+    frame->editor()->spellCheckRequester().cancelCheck();
 
     // Take a look at the selection that results after typing and determine whether we need to spellcheck.
     // Since the word containing the current selection is never marked, this does a check to
diff --git a/Source/core/editing/htmlediting.cpp b/Source/core/editing/htmlediting.cpp
index 72bf50d..df4b4b4 100644
--- a/Source/core/editing/htmlediting.cpp
+++ b/Source/core/editing/htmlediting.cpp
@@ -904,7 +904,7 @@
     if (!tabTextNode)
         tabTextNode = document->createEditingTextNode("\t");
 
-    spanElement->appendChild(tabTextNode.release(), ASSERT_NO_EXCEPTION);
+    spanElement->appendChild(tabTextNode.release());
 
     return spanElement.release();
 }
diff --git a/Source/core/editing/markup.cpp b/Source/core/editing/markup.cpp
index a716b90..f505c54 100644
--- a/Source/core/editing/markup.cpp
+++ b/Source/core/editing/markup.cpp
@@ -40,6 +40,7 @@
 #include "core/dom/ChildListMutationScope.h"
 #include "core/dom/ContextFeatures.h"
 #include "core/dom/DocumentFragment.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Range.h"
@@ -728,7 +729,7 @@
     // TD, we need to include the enclosing TABLE tag as well.
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
     if (specialCommonAncestor)
-        fragment->appendChild(specialCommonAncestor, ASSERT_NO_EXCEPTION);
+        fragment->appendChild(specialCommonAncestor);
     else
         fragment->takeAllChildrenFrom(toContainerNode(commonAncestor));
 
@@ -751,7 +752,7 @@
     Document* document = paragraph->document();
 
     if (string.isEmpty()) {
-        paragraph->appendChild(createBlockPlaceholderElement(document), ASSERT_NO_EXCEPTION);
+        paragraph->appendChild(createBlockPlaceholderElement(document));
         return;
     }
 
@@ -768,11 +769,11 @@
         // append the non-tab textual part
         if (!s.isEmpty()) {
             if (!tabText.isEmpty()) {
-                paragraph->appendChild(createTabSpanElement(document, tabText), ASSERT_NO_EXCEPTION);
+                paragraph->appendChild(createTabSpanElement(document, tabText));
                 tabText = emptyString();
             }
             RefPtr<Node> textNode = document->createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
-            paragraph->appendChild(textNode.release(), ASSERT_NO_EXCEPTION);
+            paragraph->appendChild(textNode.release());
         }
 
         // there is a tab after every entry, except the last entry
@@ -780,7 +781,7 @@
         if (i + 1 != numEntries)
             tabText.append('\t');
         else if (!tabText.isEmpty())
-            paragraph->appendChild(createTabSpanElement(document, tabText), ASSERT_NO_EXCEPTION);
+            paragraph->appendChild(createTabSpanElement(document, tabText));
 
         first = false;
     }
@@ -828,11 +829,11 @@
     string.replace('\r', '\n');
 
     if (shouldPreserveNewline(*context)) {
-        fragment->appendChild(document->createTextNode(string), ASSERT_NO_EXCEPTION);
+        fragment->appendChild(document->createTextNode(string));
         if (string.endsWith('\n')) {
             RefPtr<Element> element = createBreakElement(document);
             element->setAttribute(classAttr, AppleInterchangeNewline);
-            fragment->appendChild(element.release(), ASSERT_NO_EXCEPTION);
+            fragment->appendChild(element.release());
         }
         return fragment.release();
     }
@@ -874,7 +875,7 @@
                 element = createDefaultParagraphElement(document);
             fillContainerFromString(element.get(), s);
         }
-        fragment->appendChild(element.release(), ASSERT_NO_EXCEPTION);
+        fragment->appendChild(element.release());
     }
     return fragment.release();
 }
@@ -889,8 +890,8 @@
     size_t size = nodes.size();
     for (size_t i = 0; i < size; ++i) {
         RefPtr<Element> element = createDefaultParagraphElement(document);
-        element->appendChild(nodes[i], ASSERT_NO_EXCEPTION);
-        fragment->appendChild(element.release(), ASSERT_NO_EXCEPTION);
+        element->appendChild(nodes[i]);
+        fragment->appendChild(element.release());
     }
 
     return fragment.release();
@@ -997,10 +998,10 @@
     RefPtr<Node> nextChild;
     for (RefPtr<Node> child = element->firstChild(); child; child = nextChild) {
         nextChild = child->nextSibling();
-        element->removeChild(child.get(), ASSERT_NO_EXCEPTION);
-        fragment->insertBefore(child, element, ASSERT_NO_EXCEPTION);
+        element->removeChild(child.get());
+        fragment->insertBefore(child, element);
     }
-    fragment->removeChild(element, ASSERT_NO_EXCEPTION);
+    fragment->removeChild(element);
 }
 
 PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& es)
@@ -1038,17 +1039,6 @@
     return fragment.release();
 }
 
-static inline bool hasOneChild(ContainerNode* node)
-{
-    Node* firstChild = node->firstChild();
-    return firstChild && !firstChild->nextSibling();
-}
-
-static inline bool hasOneTextChild(ContainerNode* node)
-{
-    return hasOneChild(node) && node->firstChild()->isTextNode();
-}
-
 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& es)
 {
     RefPtr<ContainerNode> containerNode(container);
@@ -1060,12 +1050,12 @@
         return;
     }
 
-    if (hasOneTextChild(containerNode.get()) && hasOneTextChild(fragment.get())) {
+    if (containerNode->hasOneTextChild() && fragment->hasOneTextChild()) {
         toText(containerNode->firstChild())->setData(toText(fragment->firstChild())->data());
         return;
     }
 
-    if (hasOneChild(containerNode.get())) {
+    if (containerNode->hasOneChild()) {
         containerNode->replaceChild(fragment, containerNode->firstChild(), es);
         return;
     }
@@ -1080,14 +1070,14 @@
 
     ChildListMutationScope mutation(containerNode.get());
 
-    if (hasOneTextChild(containerNode.get())) {
+    if (containerNode->hasOneTextChild()) {
         toText(containerNode->firstChild())->setData(text);
         return;
     }
 
     RefPtr<Text> textNode = Text::create(containerNode->document(), text);
 
-    if (hasOneChild(containerNode.get())) {
+    if (containerNode->hasOneChild()) {
         containerNode->replaceChild(textNode.release(), containerNode->firstChild(), es);
         return;
     }
diff --git a/Source/core/features.gypi b/Source/core/features.gypi
index 3ed82e7..40a89de 100644
--- a/Source/core/features.gypi
+++ b/Source/core/features.gypi
@@ -63,7 +63,6 @@
           'ENABLE_MEDIA_CAPTURE=1',
           'ENABLE_NOTIFICATIONS=0',
           'ENABLE_ORIENTATION_EVENTS=1',
-          'ENABLE_PRINTING=0',
           'ENABLE_NAVIGATOR_CONTENT_UTILS=0',
           'WTF_USE_NATIVE_FULLSCREEN_VIDEO=1',
         ],
@@ -78,7 +77,6 @@
           'ENABLE_NAVIGATOR_CONTENT_UTILS=1',
           'ENABLE_NOTIFICATIONS=1',
           'ENABLE_ORIENTATION_EVENTS=0',
-          'ENABLE_PRINTING=1',
           'ENABLE_WEB_AUDIO=1',
         ],
       }],
diff --git a/Source/core/loader/cache/CSSStyleSheetResource.cpp b/Source/core/fetch/CSSStyleSheetResource.cpp
similarity index 97%
rename from Source/core/loader/cache/CSSStyleSheetResource.cpp
rename to Source/core/fetch/CSSStyleSheetResource.cpp
index 53398a2..20be517 100644
--- a/Source/core/loader/cache/CSSStyleSheetResource.cpp
+++ b/Source/core/fetch/CSSStyleSheetResource.cpp
@@ -25,12 +25,12 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/CSSStyleSheetResource.h"
+#include "core/fetch/CSSStyleSheetResource.h"
 
 #include "core/css/StyleSheetContents.h"
+#include "core/fetch/ResourceClientWalker.h"
+#include "core/fetch/StyleSheetResourceClient.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/ResourceClientWalker.h"
-#include "core/loader/cache/StyleSheetResourceClient.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/HTTPParsers.h"
 #include "wtf/CurrentTime.h"
diff --git a/Source/core/loader/cache/CSSStyleSheetResource.h b/Source/core/fetch/CSSStyleSheetResource.h
similarity index 97%
rename from Source/core/loader/cache/CSSStyleSheetResource.h
rename to Source/core/fetch/CSSStyleSheetResource.h
index b01fa86..3ecf34b 100644
--- a/Source/core/loader/cache/CSSStyleSheetResource.h
+++ b/Source/core/fetch/CSSStyleSheetResource.h
@@ -26,7 +26,7 @@
 #ifndef CSSStyleSheetResource_h
 #define CSSStyleSheetResource_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachePolicy.h b/Source/core/fetch/CachePolicy.h
similarity index 88%
rename from Source/core/loader/cache/CachePolicy.h
rename to Source/core/fetch/CachePolicy.h
index a44c32d..bffddfe 100644
--- a/Source/core/loader/cache/CachePolicy.h
+++ b/Source/core/fetch/CachePolicy.h
@@ -28,13 +28,13 @@
 
 namespace WebCore {
 
-    enum CachePolicy {
-        CachePolicyCache,
-        CachePolicyVerify,
-        CachePolicyRevalidate,
-        CachePolicyReload,
-        CachePolicyHistoryBuffer
-    };
+enum CachePolicy {
+    CachePolicyCache,
+    CachePolicyVerify,
+    CachePolicyRevalidate,
+    CachePolicyReload,
+    CachePolicyHistoryBuffer
+};
 
 }
 
diff --git a/Source/core/loader/cache/DocumentResource.cpp b/Source/core/fetch/DocumentResource.cpp
similarity index 94%
rename from Source/core/loader/cache/DocumentResource.cpp
rename to Source/core/fetch/DocumentResource.cpp
index 2750341..5c18d84 100644
--- a/Source/core/loader/cache/DocumentResource.cpp
+++ b/Source/core/fetch/DocumentResource.cpp
@@ -22,10 +22,10 @@
 
 #include "config.h"
 
-#include "core/loader/cache/DocumentResource.h"
+#include "core/fetch/DocumentResource.h"
 
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/svg/SVGDocument.h"
 #include "wtf/text/StringBuilder.h"
diff --git a/Source/core/loader/cache/DocumentResource.h b/Source/core/fetch/DocumentResource.h
similarity index 93%
rename from Source/core/loader/cache/DocumentResource.h
rename to Source/core/fetch/DocumentResource.h
index 62379d7..58b8ac0 100644
--- a/Source/core/loader/cache/DocumentResource.h
+++ b/Source/core/fetch/DocumentResource.h
@@ -23,10 +23,10 @@
 #ifndef DocumentResource_h
 #define DocumentResource_h
 
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/Resource.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/DocumentResourceReference.h b/Source/core/fetch/DocumentResourceReference.h
similarity index 94%
rename from Source/core/loader/cache/DocumentResourceReference.h
rename to Source/core/fetch/DocumentResourceReference.h
index 4d7009c..9e84335 100644
--- a/Source/core/loader/cache/DocumentResourceReference.h
+++ b/Source/core/fetch/DocumentResourceReference.h
@@ -26,8 +26,8 @@
 #ifndef DocumentResourceReference_h
 #define DocumentResourceReference_h
 
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/DocumentResource.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/FetchInitiatorInfo.h b/Source/core/fetch/FetchInitiatorInfo.h
similarity index 100%
rename from Source/core/loader/cache/FetchInitiatorInfo.h
rename to Source/core/fetch/FetchInitiatorInfo.h
diff --git a/Source/core/loader/cache/FetchInitiatorTypeNames.in b/Source/core/fetch/FetchInitiatorTypeNames.in
similarity index 100%
rename from Source/core/loader/cache/FetchInitiatorTypeNames.in
rename to Source/core/fetch/FetchInitiatorTypeNames.in
diff --git a/Source/core/loader/cache/FetchRequest.cpp b/Source/core/fetch/FetchRequest.cpp
similarity index 95%
rename from Source/core/loader/cache/FetchRequest.cpp
rename to Source/core/fetch/FetchRequest.cpp
index 57268b2..ba22c78 100644
--- a/Source/core/loader/cache/FetchRequest.cpp
+++ b/Source/core/fetch/FetchRequest.cpp
@@ -24,12 +24,12 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/FetchRequest.h"
+#include "core/fetch/FetchRequest.h"
 
 #include "core/dom/Element.h"
+#include "core/fetch/FetchInitiatorInfo.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/cache/FetchInitiatorInfo.h"
-#include "core/loader/cache/ResourceFetcher.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/FetchRequest.h b/Source/core/fetch/FetchRequest.h
similarity index 96%
rename from Source/core/loader/cache/FetchRequest.h
rename to Source/core/fetch/FetchRequest.h
index 974fff2..b9d5fec 100644
--- a/Source/core/loader/cache/FetchRequest.h
+++ b/Source/core/fetch/FetchRequest.h
@@ -27,8 +27,8 @@
 #define FetchRequest_h
 
 #include "core/dom/Element.h"
-#include "core/loader/ResourceLoaderOptions.h"
-#include "core/loader/cache/FetchInitiatorInfo.h"
+#include "core/fetch/FetchInitiatorInfo.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "core/platform/network/ResourceLoadPriority.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "wtf/text/AtomicString.h"
diff --git a/Source/core/loader/cache/FontResource.cpp b/Source/core/fetch/FontResource.cpp
similarity index 96%
rename from Source/core/loader/cache/FontResource.cpp
rename to Source/core/fetch/FontResource.cpp
index 90b5277..23eb76a 100644
--- a/Source/core/loader/cache/FontResource.cpp
+++ b/Source/core/fetch/FontResource.cpp
@@ -25,11 +25,11 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/FontResource.h"
+#include "core/fetch/FontResource.h"
 
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourceClientWalker.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourceClientWalker.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/graphics/FontCustomPlatformData.h"
 #include "core/platform/graphics/FontPlatformData.h"
@@ -63,6 +63,7 @@
 void FontResource::didAddClient(ResourceClient* c)
 {
     ASSERT(c->resourceClientType() == FontResourceClient::expectedType());
+    Resource::didAddClient(c);
     if (!isLoading())
         static_cast<FontResourceClient*>(c)->fontLoaded(this);
 }
diff --git a/Source/core/loader/cache/FontResource.h b/Source/core/fetch/FontResource.h
similarity index 96%
rename from Source/core/loader/cache/FontResource.h
rename to Source/core/fetch/FontResource.h
index 5997f1e..42b4f70 100644
--- a/Source/core/loader/cache/FontResource.h
+++ b/Source/core/fetch/FontResource.h
@@ -26,8 +26,8 @@
 #ifndef FontResource_h
 #define FontResource_h
 
-#include "core/loader/cache/Resource.h"
-#include "core/loader/cache/ResourceClient.h"
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceClient.h"
 #include "core/platform/graphics/FontOrientation.h"
 #include "core/platform/graphics/FontWidthVariant.h"
 #include "wtf/OwnPtr.h"
diff --git a/Source/core/loader/cache/ImageResource.cpp b/Source/core/fetch/ImageResource.cpp
similarity index 93%
rename from Source/core/loader/cache/ImageResource.cpp
rename to Source/core/fetch/ImageResource.cpp
index c07d864..b7b906c 100644
--- a/Source/core/loader/cache/ImageResource.cpp
+++ b/Source/core/fetch/ImageResource.cpp
@@ -22,13 +22,13 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 
-#include "core/loader/cache/ImageResourceClient.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourceClientWalker.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ImageResourceClient.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourceClientWalker.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/page/FrameView.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/graphics/BitmapImage.h"
@@ -52,7 +52,7 @@
 }
 
 ImageResource::ImageResource(WebCore::Image* image)
-    : Resource(ResourceRequest(), Image)
+    : Resource(ResourceRequest(""), Image)
     , m_image(image)
 {
     setStatus(Cached);
@@ -127,15 +127,15 @@
     Resource::allClientsRemoved();
 }
 
-pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor) const
+pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
 {
     if (deviceScaleFactor >= 2) {
-        DEFINE_STATIC_LOCAL(WebCore::Image*, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x").leakRef()));
-        return std::make_pair(brokenImageHiRes, 2);
+        DEFINE_STATIC_LOCAL(RefPtr<WebCore::Image>, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
+        return std::make_pair(brokenImageHiRes.get(), 2);
     }
 
-    DEFINE_STATIC_LOCAL(WebCore::Image*, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage").leakRef()));
-    return std::make_pair(brokenImageLoRes, 1);
+    DEFINE_STATIC_LOCAL(RefPtr<WebCore::Image>, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
+    return std::make_pair(brokenImageLoRes.get(), 1);
 }
 
 bool ImageResource::willPaintBrokenImage() const
@@ -225,7 +225,7 @@
     return false;
 }
 
-LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier)
+LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier, SizeType sizeType)
 {
     ASSERT(!isPurgeable());
 
@@ -236,7 +236,7 @@
 
     if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
         imageSize = static_cast<BitmapImage*>(m_image.get())->sizeRespectingOrientation();
-    else if (m_image->isSVGImage())
+    else if (m_image->isSVGImage() && sizeType == NormalSize)
         imageSize = m_svgImageCache->imageSizeForRenderer(renderer);
     else
         imageSize = m_image->size();
@@ -405,7 +405,7 @@
     if (!image || image != m_image)
         return;
 
-    double timeStamp = FrameView::currentPaintTimeStamp();
+    double timeStamp = FrameView::currentFrameTimeStamp();
     if (!timeStamp) // If didDraw is called outside of a Frame paint.
         timeStamp = currentTime();
 
diff --git a/Source/core/loader/cache/ImageResource.h b/Source/core/fetch/ImageResource.h
similarity index 90%
rename from Source/core/loader/cache/ImageResource.h
rename to Source/core/fetch/ImageResource.h
index 5bee694..15fc953 100644
--- a/Source/core/loader/cache/ImageResource.h
+++ b/Source/core/fetch/ImageResource.h
@@ -23,7 +23,7 @@
 #ifndef ImageResource_h
 #define ImageResource_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 #include "core/platform/graphics/ImageObserver.h"
 #include "core/platform/graphics/IntRect.h"
 #include "core/platform/graphics/IntSizeHash.h"
@@ -55,7 +55,7 @@
     bool hasImage() const { return m_image.get(); }
     bool currentFrameKnownToBeOpaque(const RenderObject*); // Side effect: ensures decoded image is in cache, therefore should only be called when about to draw the image.
 
-    std::pair<WebCore::Image*, float> brokenImage(float deviceScaleFactor) const; // Returns an image and the image's resolution scale factor.
+    static std::pair<WebCore::Image*, float> brokenImage(float deviceScaleFactor); // Returns an image and the image's resolution scale factor.
     bool willPaintBrokenImage() const;
 
     bool canRender(const RenderObject* renderer, float multiplier) { return !errorOccurred() && !imageSizeForRenderer(renderer, multiplier).isEmpty(); }
@@ -65,8 +65,12 @@
     bool imageHasRelativeWidth() const;
     bool imageHasRelativeHeight() const;
 
+    enum SizeType {
+        NormalSize, // Report the size of the image associated with a certain renderer
+        IntrinsicSize // Report the intrinsic size, i.e. ignore whatever has been set extrinsically.
+    };
     // This method takes a zoom multiplier that can be used to increase the natural size of the image by the zoom.
-    LayoutSize imageSizeForRenderer(const RenderObject*, float multiplier); // returns the size of the complete image.
+    LayoutSize imageSizeForRenderer(const RenderObject*, float multiplier, SizeType = NormalSize); // returns the size of the complete image.
     void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);
 
     virtual void didAddClient(ResourceClient*);
diff --git a/Source/core/loader/cache/ImageResourceClient.h b/Source/core/fetch/ImageResourceClient.h
similarity index 97%
rename from Source/core/loader/cache/ImageResourceClient.h
rename to Source/core/fetch/ImageResourceClient.h
index 4cea375..900550e 100644
--- a/Source/core/loader/cache/ImageResourceClient.h
+++ b/Source/core/fetch/ImageResourceClient.h
@@ -23,7 +23,7 @@
 #ifndef ImageResourceClient_h
 #define ImageResourceClient_h
 
-#include "core/loader/cache/ResourceClient.h"
+#include "core/fetch/ResourceClient.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/ImageResourceTest.cpp b/Source/core/fetch/ImageResourceTest.cpp
similarity index 95%
rename from Source/core/loader/cache/ImageResourceTest.cpp
rename to Source/core/fetch/ImageResourceTest.cpp
index 37d558b..f1a269a 100644
--- a/Source/core/loader/cache/ImageResourceTest.cpp
+++ b/Source/core/fetch/ImageResourceTest.cpp
@@ -29,15 +29,15 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.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/loader/EmptyClients.h"
-#include "core/loader/cache/ImageResourceClient.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/MockImageResourceClient.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/ResourcePtr.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
diff --git a/Source/core/loader/cache/MemoryCache.cpp b/Source/core/fetch/MemoryCache.cpp
similarity index 85%
rename from Source/core/loader/cache/MemoryCache.cpp
rename to Source/core/fetch/MemoryCache.cpp
index c51f544..8c51bb6 100644
--- a/Source/core/loader/cache/MemoryCache.cpp
+++ b/Source/core/fetch/MemoryCache.cpp
@@ -21,19 +21,18 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/MemoryCache.h"
+#include "core/fetch/MemoryCache.h"
 
-#include <stdio.h>
 #include "core/dom/CrossThreadTask.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/Resource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/page/FrameView.h"
 #include "core/platform/Logging.h"
-#include "core/platform/chromium/TraceEvent.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerLoaderProxy.h"
 #include "core/workers/WorkerThread.h"
+#include "public/platform/Platform.h"
 #include "weborigin/SecurityOrigin.h"
 #include "weborigin/SecurityOriginHash.h"
 #include "wtf/Assertions.h"
@@ -41,6 +40,7 @@
 #include "wtf/MathExtras.h"
 #include "wtf/TemporaryChange.h"
 #include "wtf/text/CString.h"
+#include <stdio.h>
 
 using namespace std;
 
@@ -48,8 +48,10 @@
 
 static MemoryCache* gMemoryCache;
 
-static const int cDefaultCacheCapacity = 8192 * 1024;
-static const double cMinDelayBeforeLiveDecodedPrune = 1; // Seconds.
+static const unsigned cDefaultCacheCapacity = 8192 * 1024;
+static const unsigned cDeferredPruneDeadCapacityFactor = 2;
+static const int cMinDelayBeforeLiveDecodedPrune = 1; // Seconds.
+static const double cMaxPruneDeferralDelay = 0.5; // Seconds.
 static const float cTargetPrunePercentage = .95f; // Percentage of capacity toward which we prune, to avoid immediately pruning again.
 
 MemoryCache* memoryCache()
@@ -67,9 +69,12 @@
 
 MemoryCache::MemoryCache()
     : m_inPruneResources(false)
+    , m_prunePending(false)
+    , m_maxPruneDeferralDelay(cMaxPruneDeferralDelay)
     , m_capacity(cDefaultCacheCapacity)
     , m_minDeadCapacity(0)
     , m_maxDeadCapacity(cDefaultCacheCapacity)
+    , m_maxDeferredPruneDeadCapacity(cDeferredPruneDeadCapacityFactor * cDefaultCacheCapacity)
     , m_liveSize(0)
     , m_deadSize(0)
     , m_delayBeforeLiveDecodedPrune(cMinDelayBeforeLiveDecodedPrune)
@@ -81,6 +86,13 @@
     const double statsIntervalInSeconds = 15;
     m_statsTimer.startRepeating(statsIntervalInSeconds);
 #endif
+    m_pruneTimeStamp = m_pruneFrameTimeStamp = FrameView::currentFrameTimeStamp();
+}
+
+MemoryCache::~MemoryCache()
+{
+    if (m_prunePending)
+        WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
 }
 
 KURL MemoryCache::removeFragmentIdentifierIfNeeded(const KURL& originalURL)
@@ -151,24 +163,21 @@
 
 void MemoryCache::pruneLiveResources()
 {
+    ASSERT(!m_prunePending);
     unsigned capacity = liveCapacity();
     if (!m_liveSize || (capacity && m_liveSize <= capacity))
         return;
 
     unsigned targetSize = static_cast<unsigned>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
 
-    double currentTime = FrameView::currentPaintTimeStamp();
-    if (!currentTime) // In case prune is called directly, outside of a Frame paint.
-        currentTime = WTF::currentTime();
-
     // Destroy any decoded data in live objects that we can.
     // Start from the tail, since this is the lowest priority
     // and least recently accessed of the objects.
 
-    // The list might not be sorted by the m_lastDecodedAccessTime. The impact
+    // The list might not be sorted by the m_lastDecodedFrameTimeStamp. The impact
     // of this weaker invariant is minor as the below if statement to check the
-    // elapsedTime will evaluate to false as the currentTime will be a lot
-    // greater than the current->m_lastDecodedAccessTime.
+    // elapsedTime will evaluate to false as the current time will be a lot
+    // greater than the current->m_lastDecodedFrameTimeStamp.
     // For more details see: https://bugs.webkit.org/show_bug.cgi?id=30209
 
     // Start pruning from the lowest priority list.
@@ -179,7 +188,7 @@
             ASSERT(current->hasClients());
             if (current->isLoaded() && current->decodedSize()) {
                 // Check to see if the remaining resources are too new to prune.
-                double elapsedTime = currentTime - current->m_lastDecodedAccessTime;
+                double elapsedTime = m_pruneFrameTimeStamp - current->m_lastDecodedAccessTime;
                 if (elapsedTime < m_delayBeforeLiveDecodedPrune)
                     return;
 
@@ -278,6 +287,7 @@
     ASSERT(maxDeadBytes <= totalBytes);
     m_minDeadCapacity = minDeadBytes;
     m_maxDeadCapacity = maxDeadBytes;
+    m_maxDeferredPruneDeadCapacity = cDeferredPruneDeadCapacityFactor * maxDeadBytes;
     m_capacity = totalBytes;
     prune();
 }
@@ -297,8 +307,9 @@
         removeFromLRUList(resource);
         removeFromLiveDecodedResourcesList(resource);
         adjustSize(resource->hasClients(), -static_cast<int>(resource->size()));
-    } else
+    } else {
         ASSERT(m_resources.get(resource->url()) != resource);
+    }
 
     resource->deleteIfPossible();
 }
@@ -318,7 +329,7 @@
 void MemoryCache::removeFromLRUList(Resource* resource)
 {
     // If we've never been accessed, then we're brand new and not in any list.
-    if (resource->accessCount() == 0)
+    if (!resource->accessCount())
         return;
 
 #if !ASSERT_DISABLED
@@ -345,7 +356,7 @@
     Resource* next = resource->m_nextInAllResourcesList;
     Resource* prev = resource->m_prevInAllResourcesList;
 
-    if (next == 0 && prev == 0 && list->m_head != resource)
+    if (!next && !prev && list->m_head != resource)
         return;
 
     resource->m_nextInAllResourcesList = 0;
@@ -558,19 +569,76 @@
     }
 }
 
-void MemoryCache::prune()
+void MemoryCache::prune(Resource* justReleasedResource)
 {
-    TRACE_EVENT0("renderer", "MemoryCache::prune()");
-    if (m_liveSize + m_deadSize <= m_capacity && m_maxDeadCapacity && m_deadSize <= m_maxDeadCapacity) // Fast path.
-        return;
+    ASSERT(WebKit::Platform::current()); // This method should not be called after WebKit::shutdown().
+
     if (m_inPruneResources)
         return;
-    TemporaryChange<bool> reentrancyProtector(m_inPruneResources, true);
+    if (m_liveSize + m_deadSize <= m_capacity && m_maxDeadCapacity && m_deadSize <= m_maxDeadCapacity) // Fast path.
+        return;
 
-    pruneDeadResources(); // Prune dead first, in case it was "borrowing" capacity from live.
-    pruneLiveResources();
+    // To avoid burdening the current thread with repetitive pruning jobs,
+    // pruning is postponed until the end of the current task. If it has
+    // been more that m_maxPruneDeferralDelay since the last prune,
+    // then we prune immediately.
+    // If the current thread's run loop is not active, then pruning will happen
+    // immediately only if it has been over m_maxPruneDeferralDelay
+    // since the last prune.
+    double currentTime = WTF::currentTime();
+    if (m_prunePending) {
+        if (currentTime - m_pruneTimeStamp >= m_maxPruneDeferralDelay) {
+            pruneNow(currentTime);
+        }
+    } else {
+        if (currentTime - m_pruneTimeStamp >= m_maxPruneDeferralDelay) {
+            pruneNow(currentTime); // Delay exceeded, prune now.
+        } else {
+            // Defer.
+            WebKit::Platform::current()->currentThread()->addTaskObserver(this);
+            m_prunePending = true;
+        }
+    }
+
+    if (m_prunePending && m_deadSize > m_maxDeferredPruneDeadCapacity && justReleasedResource) {
+        // The following eviction does not respect LRU order, but it can be done
+        // immediately in constant time, as opposed to pruneDeadResources, which
+        // we would rather defer because it is O(N), which would make tear-down of N
+        // objects O(N^2) if we pruned immediately. This immediate eviction is a
+        // safeguard against runaway memory consumption by dead resources
+        // while a prune is pending.
+        evict(justReleasedResource);
+
+        // As a last resort, prune immediately
+        if (m_deadSize > m_maxDeferredPruneDeadCapacity)
+            pruneNow(currentTime);
+    }
 }
 
+void MemoryCache::willProcessTask()
+{
+}
+
+void MemoryCache::didProcessTask()
+{
+    // Perform deferred pruning
+    ASSERT(m_prunePending);
+    pruneNow(WTF::currentTime());
+}
+
+void MemoryCache::pruneNow(double currentTime)
+{
+    if (m_prunePending) {
+        m_prunePending = false;
+        WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
+    }
+
+    TemporaryChange<bool> reentrancyProtector(m_inPruneResources, true);
+    pruneDeadResources(); // Prune dead first, in case it was "borrowing" capacity from live.
+    pruneLiveResources();
+    m_pruneFrameTimeStamp = FrameView::currentFrameTimeStamp();
+    m_pruneTimeStamp = currentTime;
+}
 
 #ifdef MEMORY_CACHE_STATS
 
diff --git a/Source/core/loader/cache/MemoryCache.h b/Source/core/fetch/MemoryCache.h
similarity index 88%
rename from Source/core/loader/cache/MemoryCache.h
rename to Source/core/fetch/MemoryCache.h
index f174a11..f038244 100644
--- a/Source/core/loader/cache/MemoryCache.h
+++ b/Source/core/fetch/MemoryCache.h
@@ -22,10 +22,11 @@
     pages from the web. It has a memory cache for these objects.
 */
 
-#ifndef Cache_h
-#define Cache_h
+#ifndef MemoryCache_h
+#define MemoryCache_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
+#include "public/platform/WebThread.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/Vector.h"
@@ -58,11 +59,11 @@
 // Enable this macro to periodically log information about the memory cache.
 #undef MEMORY_CACHE_STATS
 
-class MemoryCache {
+class MemoryCache : public WebKit::WebThread::TaskObserver {
     WTF_MAKE_NONCOPYABLE(MemoryCache); WTF_MAKE_FAST_ALLOCATED;
 public:
     MemoryCache();
-    ~MemoryCache() { }
+    virtual ~MemoryCache();
 
     typedef HashMap<String, Resource*> ResourceMap;
 
@@ -120,11 +121,12 @@
     //  - maxDeadBytes: The maximum number of bytes that dead resources should consume when the cache is not under pressure.
     //  - totalBytes: The maximum number of bytes that the cache should consume overall.
     void setCapacities(unsigned minDeadBytes, unsigned maxDeadBytes, unsigned totalBytes);
-    void setDelayBeforeLiveDecodedPrune(unsigned seconds) { m_delayBeforeLiveDecodedPrune = seconds; }
+    void setDelayBeforeLiveDecodedPrune(double seconds) { m_delayBeforeLiveDecodedPrune = seconds; }
+    void setMaxPruneDeferralDelay(double seconds) { m_maxPruneDeferralDelay = seconds; }
 
     void evictResources();
 
-    void prune();
+    void prune(Resource* justReleasedResource = 0);
 
     // Calls to put the cached resource into and out of LRU lists.
     void insertInLRUList(Resource*);
@@ -150,6 +152,10 @@
     unsigned liveSize() const { return m_liveSize; }
     unsigned deadSize() const { return m_deadSize; }
 
+    // TaskObserver implementation
+    virtual void willProcessTask() OVERRIDE;
+    virtual void didProcessTask() OVERRIDE;
+
 private:
     LRUList* lruListFor(Resource*);
 
@@ -165,23 +171,30 @@
     // pruneLiveResources() - Flush decoded data from resources still referenced by Web pages.
     void pruneDeadResources(); // Automatically decide how much to prune.
     void pruneLiveResources();
+    void pruneNow(double currentTime);
 
     void evict(Resource*);
 
     static void removeURLFromCacheInternal(ScriptExecutionContext*, const KURL&);
 
     bool m_inPruneResources;
+    bool m_prunePending;
+    bool m_prePainting;
+    double m_maxPruneDeferralDelay;
+    double m_pruneTimeStamp;
+    double m_pruneFrameTimeStamp;
 
     unsigned m_capacity;
     unsigned m_minDeadCapacity;
     unsigned m_maxDeadCapacity;
-    unsigned m_delayBeforeLiveDecodedPrune;
+    unsigned m_maxDeferredPruneDeadCapacity;
+    double m_delayBeforeLiveDecodedPrune;
     double m_deadDecodedDataDeletionInterval;
 
     unsigned m_liveSize; // The number of bytes currently consumed by "live" resources in the cache.
     unsigned m_deadSize; // The number of bytes currently consumed by "dead" resources in the cache.
 
-    // Size-adjusted and popularity-aware LRU list collection for cache objects.  This collection can hold
+    // Size-adjusted and popularity-aware LRU list collection for cache objects. This collection can hold
     // more resources than the cached resource map, since it can also hold "stale" multiple versions of objects that are
     // waiting to die when the clients referencing them go away.
     Vector<LRUList, 32> m_allResources;
@@ -194,6 +207,7 @@
     // referenced by a Web page).
     HashMap<String, Resource*> m_resources;
 
+    friend class MemoryCacheTest;
 #ifdef MEMORY_CACHE_STATS
     Timer<MemoryCache> m_statsTimer;
 #endif
diff --git a/Source/core/fetch/MemoryCacheTest.cpp b/Source/core/fetch/MemoryCacheTest.cpp
new file mode 100644
index 0000000..b5a4dfa
--- /dev/null
+++ b/Source/core/fetch/MemoryCacheTest.cpp
@@ -0,0 +1,326 @@
+/*
+ * 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/fetch/MemoryCache.h"
+
+#include "core/fetch/MockImageResourceClient.h"
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/platform/network/ResourceRequest.h"
+#include "public/platform/Platform.h"
+#include "wtf/OwnPtr.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+class MemoryCacheTest : public ::testing::Test {
+public:
+    class FakeDecodedResource : public WebCore::Resource {
+    public:
+        FakeDecodedResource(const ResourceRequest& request, Type type)
+            : Resource(request, type)
+        {
+        }
+
+        virtual void appendData(const char* data, int len)
+        {
+            Resource::appendData(data, len);
+            setDecodedSize(this->size());
+        }
+
+        virtual void destroyDecodedData()
+        {
+            setDecodedSize(0);
+        }
+    };
+
+protected:
+    virtual void SetUp()
+    {
+        // Save the global memory cache to restore it upon teardown.
+        m_globalMemoryCache = adoptPtr(memoryCache());
+        // Create the test memory cache instance and hook it in.
+        m_testingMemoryCache = adoptPtr(new MemoryCache());
+        setMemoryCacheForTesting(m_testingMemoryCache.leakPtr());
+    }
+
+    virtual void TearDown()
+    {
+        // Regain the ownership of testing memory cache, so that it will be
+        // destroyed.
+        m_testingMemoryCache = adoptPtr(memoryCache());
+        // Yield the ownership of the global memory cache back.
+        setMemoryCacheForTesting(m_globalMemoryCache.leakPtr());
+    }
+
+    OwnPtr<MemoryCache> m_testingMemoryCache;
+    OwnPtr<MemoryCache> m_globalMemoryCache;
+};
+
+// Verifies that setters and getters for cache capacities work correcty.
+TEST_F(MemoryCacheTest, CapacityAccounting)
+{
+    const unsigned totalCapacity = 100;
+    const unsigned minDeadCapacity = 10;
+    const unsigned maxDeadCapacity = 50;
+    memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
+
+    ASSERT_EQ(totalCapacity, memoryCache()->capacity());
+    ASSERT_EQ(minDeadCapacity, memoryCache()->minDeadCapacity());
+    ASSERT_EQ(maxDeadCapacity, memoryCache()->maxDeadCapacity());
+}
+
+// Verifies that dead resources that exceed dead resource capacity are evicted
+// from cache when pruning.
+TEST_F(MemoryCacheTest, DeadResourceEviction)
+{
+    memoryCache()->setDelayBeforeLiveDecodedPrune(0);
+    memoryCache()->setMaxPruneDeferralDelay(0);
+    const unsigned totalCapacity = 1000000;
+    const unsigned minDeadCapacity = 0;
+    const unsigned maxDeadCapacity = 0;
+    memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
+
+    ResourcePtr<Resource> cachedResource =
+        new Resource(ResourceRequest(""), Resource::Raw);
+    const char data[5] = "abcd";
+    cachedResource->appendData(data, 3);
+    // The resource size has to be nonzero for this test to be meaningful, but
+    // we do not rely on it having any particular value.
+    ASSERT_GT(cachedResource->size(), 0u);
+
+    ASSERT_EQ(0u, memoryCache()->deadSize());
+    ASSERT_EQ(0u, memoryCache()->liveSize());
+
+    memoryCache()->add(cachedResource.get());
+    ASSERT_EQ(cachedResource->size(), memoryCache()->deadSize());
+    ASSERT_EQ(0u, memoryCache()->liveSize());
+
+    memoryCache()->prune();
+    ASSERT_EQ(0u, memoryCache()->deadSize());
+    ASSERT_EQ(0u, memoryCache()->liveSize());
+}
+
+// Verified that when ordering a prune in a runLoop task, the prune
+// is deferred to the end of the task.
+TEST_F(MemoryCacheTest, LiveResourceEvictionAtEndOfTask)
+{
+    memoryCache()->setDelayBeforeLiveDecodedPrune(0);
+    const unsigned totalCapacity = 1;
+    const unsigned minDeadCapacity = 0;
+    const unsigned maxDeadCapacity = 0;
+    memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
+    const char data[6] = "abcde";
+    ResourcePtr<Resource> cachedDeadResource =
+        new Resource(ResourceRequest(""), Resource::Raw);
+    cachedDeadResource->appendData(data, 3);
+    ResourcePtr<Resource> cachedLiveResource =
+        new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
+    MockImageResourceClient client;
+    cachedLiveResource->addClient(&client);
+    cachedLiveResource->appendData(data, 4);
+
+    class Task1 : public WebKit::WebThread::Task {
+    public:
+        Task1(const ResourcePtr<Resource>& live, const ResourcePtr<Resource>& dead)
+            : m_live(live)
+            , m_dead(dead)
+        { }
+
+        virtual void run() OVERRIDE
+        {
+            // The resource size has to be nonzero for this test to be meaningful, but
+            // we do not rely on it having any particular value.
+            ASSERT_GT(m_live->size(), 0u);
+            ASSERT_GT(m_dead->size(), 0u);
+
+            ASSERT_EQ(0u, memoryCache()->deadSize());
+            ASSERT_EQ(0u, memoryCache()->liveSize());
+
+            memoryCache()->add(m_dead.get());
+            memoryCache()->add(m_live.get());
+            memoryCache()->insertInLiveDecodedResourcesList(m_live.get());
+            ASSERT_EQ(m_dead->size(), memoryCache()->deadSize());
+            ASSERT_EQ(m_live->size(), memoryCache()->liveSize());
+            ASSERT_GT(m_live->decodedSize(), 0u);
+
+            memoryCache()->prune(); // Dead resources are pruned immediately
+            ASSERT_EQ(m_dead->size(), memoryCache()->deadSize());
+            ASSERT_EQ(m_live->size(), memoryCache()->liveSize());
+            ASSERT_GT(m_live->decodedSize(), 0u);
+        }
+
+    private:
+        ResourcePtr<Resource> m_live, m_dead;
+    };
+
+    class Task2 : public WebKit::WebThread::Task {
+    public:
+        Task2(unsigned liveSizeWithoutDecode)
+            : m_liveSizeWithoutDecode(liveSizeWithoutDecode) { }
+
+        virtual void run() OVERRIDE
+        {
+            // Next task: now, the live resource was evicted.
+            ASSERT_EQ(0u, memoryCache()->deadSize());
+            ASSERT_EQ(m_liveSizeWithoutDecode, memoryCache()->liveSize());
+            WebKit::Platform::current()->currentThread()->exitRunLoop();
+        }
+
+    private:
+        unsigned m_liveSizeWithoutDecode;
+    };
+
+
+    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();
+    cachedLiveResource->removeClient(&client);
+}
+
+// Verifies that cached resources are evicted immediately after release when
+// the total dead resource size is more than double the dead resource capacity.
+TEST_F(MemoryCacheTest, ClientRemoval)
+{
+    const char data[6] = "abcde";
+    ResourcePtr<Resource> resource1 =
+        new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
+    MockImageResourceClient client1;
+    resource1->addClient(&client1);
+    resource1->appendData(data, 4);
+    ResourcePtr<Resource> resource2 =
+        new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
+    MockImageResourceClient client2;
+    resource2->addClient(&client2);
+    resource2->appendData(data, 4);
+
+    const unsigned minDeadCapacity = 0;
+    const unsigned maxDeadCapacity = resource1->size() - 1;
+    const unsigned totalCapacity = maxDeadCapacity;
+    memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
+    memoryCache()->add(resource1.get());
+    memoryCache()->add(resource2.get());
+    // Call prune. There is nothing to prune, but this will initialize
+    // the prune timestamp, allowing future prunes to be deferred.
+    memoryCache()->prune();
+    ASSERT_GT(resource1->decodedSize(), 0u);
+    ASSERT_GT(resource2->decodedSize(), 0u);
+    ASSERT_EQ(memoryCache()->deadSize(), 0u);
+    ASSERT_EQ(memoryCache()->liveSize(), resource1->size() + resource2->size());
+
+    // Removing the client from resource1 should result in all resources
+    // remaining in cache since the prune is deferred.
+    resource1->removeClient(&client1);
+    ASSERT_GT(resource1->decodedSize(), 0u);
+    ASSERT_GT(resource2->decodedSize(), 0u);
+    ASSERT_EQ(memoryCache()->deadSize(), resource1->size());
+    ASSERT_EQ(memoryCache()->liveSize(), resource2->size());
+    ASSERT_TRUE(resource1->inCache());
+    ASSERT_TRUE(resource2->inCache());
+
+    // Removing the client from resource2 should result in immediate
+    // eviction of resource2 because we are over the prune deferral limit.
+    resource2->removeClient(&client2);
+    ASSERT_GT(resource1->decodedSize(), 0u);
+    ASSERT_GT(resource2->decodedSize(), 0u);
+    ASSERT_EQ(memoryCache()->deadSize(), resource1->size());
+    ASSERT_EQ(memoryCache()->liveSize(), 0u);
+    ASSERT_TRUE(resource1->inCache());
+    ASSERT_FALSE(resource2->inCache());
+}
+
+// Verifies that CachedResources are evicted from the decode cache
+// according to their DecodeCachePriority.
+TEST_F(MemoryCacheTest, DecodeCacheOrder)
+{
+    memoryCache()->setDelayBeforeLiveDecodedPrune(0);
+    memoryCache()->setMaxPruneDeferralDelay(0);
+    ResourcePtr<FakeDecodedResource> cachedImageLowPriority =
+        new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
+    ResourcePtr<FakeDecodedResource> cachedImageHighPriority =
+        new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
+
+    MockImageResourceClient clientLowPriority;
+    MockImageResourceClient clientHighPriority;
+    cachedImageLowPriority->addClient(&clientLowPriority);
+    cachedImageHighPriority->addClient(&clientHighPriority);
+
+    const char data[5] = "abcd";
+    cachedImageLowPriority->appendData(data, 1);
+    cachedImageHighPriority->appendData(data, 4);
+    const unsigned lowPrioritySize = cachedImageLowPriority->size();
+    const unsigned highPrioritySize = cachedImageHighPriority->size();
+    const unsigned lowPriorityMockDecodeSize = cachedImageLowPriority->decodedSize();
+    const unsigned highPriorityMockDecodeSize = cachedImageHighPriority->decodedSize();
+    const unsigned totalSize = lowPrioritySize + highPrioritySize;
+
+    // Verify that the sizes are different to ensure that we can test eviction order.
+    ASSERT_GT(lowPrioritySize, 0u);
+    ASSERT_NE(lowPrioritySize, highPrioritySize);
+    ASSERT_GT(lowPriorityMockDecodeSize, 0u);
+    ASSERT_NE(lowPriorityMockDecodeSize, highPriorityMockDecodeSize);
+
+    ASSERT_EQ(memoryCache()->deadSize(), 0u);
+    ASSERT_EQ(memoryCache()->liveSize(), 0u);
+
+    // Add the items. The item added first would normally be evicted first.
+    memoryCache()->add(cachedImageHighPriority.get());
+    ASSERT_EQ(memoryCache()->deadSize(), 0u);
+    ASSERT_EQ(memoryCache()->liveSize(), highPrioritySize);
+
+    memoryCache()->add(cachedImageLowPriority.get());
+    ASSERT_EQ(memoryCache()->deadSize(), 0u);
+    ASSERT_EQ(memoryCache()->liveSize(), highPrioritySize + lowPrioritySize);
+
+    // Insert all items in the decoded items list with the same priority
+    memoryCache()->insertInLiveDecodedResourcesList(cachedImageHighPriority.get());
+    memoryCache()->insertInLiveDecodedResourcesList(cachedImageLowPriority.get());
+    ASSERT_EQ(memoryCache()->deadSize(), 0u);
+    ASSERT_EQ(memoryCache()->liveSize(), totalSize);
+
+    // Now we will assign their priority and make sure they are moved to the correct buckets.
+    cachedImageLowPriority->setCacheLiveResourcePriority(Resource::CacheLiveResourcePriorityLow);
+    cachedImageHighPriority->setCacheLiveResourcePriority(Resource::CacheLiveResourcePriorityHigh);
+
+    // Should first prune the LowPriority item.
+    memoryCache()->setCapacities(memoryCache()->minDeadCapacity(), memoryCache()->liveSize() - 10, memoryCache()->liveSize() - 10);
+    memoryCache()->prune();
+    ASSERT_EQ(memoryCache()->deadSize(), 0u);
+    ASSERT_EQ(memoryCache()->liveSize(), totalSize - lowPriorityMockDecodeSize);
+
+    // Should prune the HighPriority item.
+    memoryCache()->setCapacities(memoryCache()->minDeadCapacity(), memoryCache()->liveSize() - 10, memoryCache()->liveSize() - 10);
+    memoryCache()->prune();
+    ASSERT_EQ(memoryCache()->deadSize(), 0u);
+    ASSERT_EQ(memoryCache()->liveSize(), totalSize - lowPriorityMockDecodeSize - highPriorityMockDecodeSize);
+}
+} // namespace
diff --git a/Source/core/loader/cache/MockImageResourceClient.h b/Source/core/fetch/MockImageResourceClient.h
similarity index 97%
rename from Source/core/loader/cache/MockImageResourceClient.h
rename to Source/core/fetch/MockImageResourceClient.h
index adaa90f..676c95a 100644
--- a/Source/core/loader/cache/MockImageResourceClient.h
+++ b/Source/core/fetch/MockImageResourceClient.h
@@ -31,7 +31,7 @@
 #ifndef MockImageResourceClient_h
 #define MockImageResourceClient_h
 
-#include "core/loader/cache/ImageResourceClient.h"
+#include "core/fetch/ImageResourceClient.h"
 #include "core/page/Frame.h"
 #include "core/platform/graphics/Image.h"
 
diff --git a/Source/core/loader/cache/RawResource.cpp b/Source/core/fetch/RawResource.cpp
similarity index 96%
rename from Source/core/loader/cache/RawResource.cpp
rename to Source/core/fetch/RawResource.cpp
index a2a0dc4..5745d93 100644
--- a/Source/core/loader/cache/RawResource.cpp
+++ b/Source/core/fetch/RawResource.cpp
@@ -24,12 +24,12 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/RawResource.h"
+#include "core/fetch/RawResource.h"
 
-#include "core/loader/ResourceLoader.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourceClientWalker.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourceClientWalker.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ResourceLoader.h"
 #include "core/platform/SharedBuffer.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/cache/RawResource.h b/Source/core/fetch/RawResource.h
similarity index 97%
rename from Source/core/loader/cache/RawResource.h
rename to Source/core/fetch/RawResource.h
index 05cf3f4..0ed0bc0 100644
--- a/Source/core/loader/cache/RawResource.h
+++ b/Source/core/fetch/RawResource.h
@@ -23,8 +23,8 @@
 #ifndef RawResource_h
 #define RawResource_h
 
-#include "core/loader/cache/Resource.h"
-#include "core/loader/cache/ResourceClient.h"
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceClient.h"
 
 namespace WebCore {
 class RawResourceCallback;
diff --git a/Source/core/loader/cache/Resource.cpp b/Source/core/fetch/Resource.cpp
similarity index 89%
rename from Source/core/loader/cache/Resource.cpp
rename to Source/core/fetch/Resource.cpp
index ae832e1..c5abd6f 100644
--- a/Source/core/loader/cache/Resource.cpp
+++ b/Source/core/fetch/Resource.cpp
@@ -22,17 +22,17 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourceClientWalker.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ResourceLoader.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/CachedMetadata.h"
 #include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/ResourceLoader.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourceClientWalker.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/Logging.h"
 #include "core/platform/PurgeableBuffer.h"
 #include "core/platform/SharedBuffer.h"
@@ -367,14 +367,29 @@
 
 void Resource::didAddClient(ResourceClient* c)
 {
-    if (m_clientsAwaitingCallback.contains(c)) {
-        m_clients.add(c);
-        m_clientsAwaitingCallback.remove(c);
-    }
     if (!isLoading() && !stillNeedsLoad())
         c->notifyFinished(this);
 }
 
+static bool shouldSendCachedDataSynchronouslyForType(Resource::Type type)
+{
+    // Some resources types default to return data synchronously.
+    // For most of these, it's because there are layout tests that
+    // expect data to return synchronously in case of cache hit. In
+    // the case of fonts, there was a performance regression.
+    // FIXME: Get to the point where we don't need to special-case sync/async
+    // behavior for different resource types.
+    if (type == Resource::Image)
+        return true;
+    if (type == Resource::CSSStyleSheet)
+        return true;
+    if (type == Resource::Script)
+        return true;
+    if (type == Resource::Font)
+        return true;
+    return false;
+}
+
 bool Resource::addClientToSet(ResourceClient* client)
 {
     ASSERT(!isPurgeable());
@@ -390,13 +405,10 @@
     if (!hasClients() && inCache())
         memoryCache()->addToLiveResourcesSize(this);
 
-    if ((m_type == Raw || m_type == MainResource) && !m_response.isNull() && !m_proxyResource) {
-        // Certain resources (especially XHRs and main resources) do crazy things if an asynchronous load returns
-        // synchronously (e.g., scripts may not have set all the state they need to handle the load).
-        // Therefore, rather than immediately sending callbacks on a cache hit like other Resources,
-        // we schedule the callbacks and ensure we never finish synchronously.
-        ASSERT(!m_clientsAwaitingCallback.contains(client));
-        m_clientsAwaitingCallback.add(client, ResourceCallback::schedule(this, client));
+    // If we have existing data to send to the new client and the resource type supprts it, send it asynchronously.
+    if (!m_response.isNull() && !m_proxyResource && !shouldSendCachedDataSynchronouslyForType(type())) {
+        m_clientsAwaitingCallback.add(client);
+        ResourceCallback::callbackHandler()->schedule(this);
         return false;
     }
 
@@ -406,11 +418,11 @@
 
 void Resource::removeClient(ResourceClient* client)
 {
-    OwnPtr<ResourceCallback> callback = m_clientsAwaitingCallback.take(client);
-    if (callback) {
+    if (m_clientsAwaitingCallback.contains(client)) {
         ASSERT(!m_clients.contains(client));
-        callback->cancel();
-        callback.clear();
+        m_clientsAwaitingCallback.remove(client);
+        if (m_clientsAwaitingCallback.isEmpty())
+            ResourceCallback::callbackHandler()->cancel(this);
     } else {
         ASSERT(m_clients.contains(client));
         m_clients.remove(client);
@@ -433,7 +445,7 @@
             if (url().protocolIs("https"))
                 memoryCache()->remove(this);
         } else {
-            memoryCache()->prune();
+            memoryCache()->prune(this);
         }
     }
     // This object may be dead here.
@@ -542,6 +554,16 @@
     }
 }
 
+void Resource::finishPendingClients()
+{
+    while (!m_clientsAwaitingCallback.isEmpty()) {
+        ResourceClient* client = m_clientsAwaitingCallback.begin()->key;
+        m_clientsAwaitingCallback.remove(client);
+        m_clients.add(client);
+        didAddClient(client);
+    }
+}
+
 void Resource::setResourceToRevalidate(Resource* resource)
 {
     ASSERT(resource);
@@ -816,23 +838,40 @@
         m_loader->didChangePriority(loadPriority);
 }
 
-Resource::ResourceCallback::ResourceCallback(Resource* resource, ResourceClient* client)
-    : m_resource(resource)
-    , m_client(client)
-    , m_callbackTimer(this, &ResourceCallback::timerFired)
+Resource::ResourceCallback* Resource::ResourceCallback::callbackHandler()
 {
-    m_callbackTimer.startOneShot(0);
+    DEFINE_STATIC_LOCAL(ResourceCallback, callbackHandler, ());
+    return &callbackHandler;
 }
 
-void Resource::ResourceCallback::cancel()
+Resource::ResourceCallback::ResourceCallback()
+    : m_callbackTimer(this, &ResourceCallback::timerFired)
 {
-    if (m_callbackTimer.isActive())
+}
+
+void Resource::ResourceCallback::schedule(Resource* resource)
+{
+    if (!m_callbackTimer.isActive())
+        m_callbackTimer.startOneShot(0);
+    m_resourcesWithPendingClients.add(resource);
+}
+
+void Resource::ResourceCallback::cancel(Resource* resource)
+{
+    m_resourcesWithPendingClients.remove(resource);
+    if (m_callbackTimer.isActive() && m_resourcesWithPendingClients.isEmpty())
         m_callbackTimer.stop();
 }
 
 void Resource::ResourceCallback::timerFired(Timer<ResourceCallback>*)
 {
-    m_resource->didAddClient(m_client);
+    HashSet<Resource*>::iterator end = m_resourcesWithPendingClients.end();
+    Vector<ResourcePtr<Resource> > resources;
+    for (HashSet<Resource*>::iterator it = m_resourcesWithPendingClients.begin(); it != end; ++it)
+        resources.append(*it);
+    m_resourcesWithPendingClients.clear();
+    for (size_t i = 0; i < resources.size(); i++)
+        resources[i]->finishPendingClients();
 }
 
 }
diff --git a/Source/core/loader/cache/Resource.h b/Source/core/fetch/Resource.h
similarity index 96%
rename from Source/core/loader/cache/Resource.h
rename to Source/core/fetch/Resource.h
index dd092e3..ec640d8 100644
--- a/Source/core/loader/cache/Resource.h
+++ b/Source/core/fetch/Resource.h
@@ -23,8 +23,8 @@
 #ifndef Resource_h
 #define Resource_h
 
-#include "core/loader/ResourceLoaderOptions.h"
-#include "core/loader/cache/CachePolicy.h"
+#include "core/fetch/CachePolicy.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "core/platform/Timer.h"
 #include "core/platform/network/ResourceError.h"
 #include "core/platform/network/ResourceLoadPriority.h"
@@ -260,21 +260,22 @@
     void clearResourceToRevalidate();
     void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
 
+    void finishPendingClients();
+
     HashCountedSet<ResourceClient*> m_clients;
+    HashCountedSet<ResourceClient*> m_clientsAwaitingCallback;
 
     class ResourceCallback {
     public:
-        static PassOwnPtr<ResourceCallback> schedule(Resource* resource, ResourceClient* client) { return adoptPtr(new ResourceCallback(resource, client)); }
-        void cancel();
+        static ResourceCallback* callbackHandler();
+        void schedule(Resource*);
+        void cancel(Resource*);
     private:
-        ResourceCallback(Resource*, ResourceClient*);
+        ResourceCallback();
         void timerFired(Timer<ResourceCallback>*);
-
-        Resource* m_resource;
-        ResourceClient* m_client;
         Timer<ResourceCallback> m_callbackTimer;
+        HashSet<Resource*> m_resourcesWithPendingClients;
     };
-    HashMap<ResourceClient*, OwnPtr<ResourceCallback> > m_clientsAwaitingCallback;
 
     bool hasClient(ResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
 
diff --git a/Source/core/loader/cache/ResourceClient.h b/Source/core/fetch/ResourceClient.h
similarity index 100%
rename from Source/core/loader/cache/ResourceClient.h
rename to Source/core/fetch/ResourceClient.h
diff --git a/Source/core/loader/cache/ResourceClientWalker.h b/Source/core/fetch/ResourceClientWalker.h
similarity index 97%
rename from Source/core/loader/cache/ResourceClientWalker.h
rename to Source/core/fetch/ResourceClientWalker.h
index aff5f1d..cd24b82 100644
--- a/Source/core/loader/cache/ResourceClientWalker.h
+++ b/Source/core/fetch/ResourceClientWalker.h
@@ -25,7 +25,7 @@
 #ifndef ResourceClientWalker_h
 #define ResourceClientWalker_h
 
-#include "core/loader/cache/ResourceClient.h"
+#include "core/fetch/ResourceClient.h"
 #include "wtf/HashCountedSet.h"
 #include "wtf/Vector.h"
 
diff --git a/Source/core/loader/cache/ResourceFetcher.cpp b/Source/core/fetch/ResourceFetcher.cpp
similarity index 97%
rename from Source/core/loader/cache/ResourceFetcher.cpp
rename to Source/core/fetch/ResourceFetcher.cpp
index 28d7c8c..79663db 100644
--- a/Source/core/loader/cache/ResourceFetcher.cpp
+++ b/Source/core/fetch/ResourceFetcher.cpp
@@ -25,10 +25,21 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ResourceFetcher.h"
 
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/Document.h"
+#include "core/fetch/CSSStyleSheetResource.h"
+#include "core/fetch/DocumentResource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ScriptResource.h"
+#include "core/fetch/ShaderResource.h"
+#include "core/fetch/TextTrackResource.h"
+#include "core/fetch/XSLStyleSheetResource.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLImport.h"
@@ -39,17 +50,6 @@
 #include "core/loader/PingLoader.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/loader/cache/CSSStyleSheetResource.h"
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/FontResource.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/RawResource.h"
-#include "core/loader/cache/ScriptResource.h"
-#include "core/loader/cache/ShaderResource.h"
-#include "core/loader/cache/TextTrackResource.h"
-#include "core/loader/cache/XSLStyleSheetResource.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
@@ -204,7 +204,7 @@
 ResourcePtr<ImageResource> ResourceFetcher::requestImage(FetchRequest& request)
 {
     if (Frame* f = frame()) {
-        if (f->loader()->pageDismissalEventBeingDispatched() != FrameLoader::NoDismissal) {
+        if (f->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal) {
             KURL requestURL = request.resourceRequest().url();
             if (requestURL.isValid() && canRequest(Resource::Image, requestURL, request.options(), request.forPreload()))
                 PingLoader::loadImage(f, requestURL);
@@ -472,14 +472,9 @@
 {
     if (!frame())
         return false;
-    if (m_documentLoader) {
-        if (m_documentLoader != frame()->loader()->activeDocumentLoader())
-            return false;
-        if (m_documentLoader->isStopping())
-            return false;
-    }
-
-    return true;
+    if (!m_documentLoader)
+        return true;
+    return m_documentLoader == frame()->loader()->activeDocumentLoader();
 }
 
 ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, FetchRequest& request)
diff --git a/Source/core/loader/cache/ResourceFetcher.h b/Source/core/fetch/ResourceFetcher.h
similarity index 96%
rename from Source/core/loader/cache/ResourceFetcher.h
rename to Source/core/fetch/ResourceFetcher.h
index c2ffa7a..4f46710 100644
--- a/Source/core/loader/cache/ResourceFetcher.h
+++ b/Source/core/fetch/ResourceFetcher.h
@@ -26,12 +26,12 @@
 #ifndef ResourceFetcher_h
 #define ResourceFetcher_h
 
-#include "core/loader/ResourceLoaderHost.h"
-#include "core/loader/cache/CachePolicy.h"
-#include "core/loader/cache/FetchInitiatorInfo.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/Resource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/CachePolicy.h"
+#include "core/fetch/FetchInitiatorInfo.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceLoaderHost.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "wtf/Deque.h"
 #include "wtf/HashMap.h"
diff --git a/Source/core/loader/cache/ResourceFetcherTest.cpp b/Source/core/fetch/ResourceFetcherTest.cpp
similarity index 92%
rename from Source/core/loader/cache/ResourceFetcherTest.cpp
rename to Source/core/fetch/ResourceFetcherTest.cpp
index 977f519..951dbfb 100644
--- a/Source/core/loader/cache/ResourceFetcherTest.cpp
+++ b/Source/core/fetch/ResourceFetcherTest.cpp
@@ -29,14 +29,14 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ResourceFetcher.h"
 
+#include "core/fetch/FetchInitiatorInfo.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/html/HTMLDocument.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/loader/cache/FetchInitiatorInfo.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/network/ResourceRequest.h"
 #include <gtest/gtest.h>
 
diff --git a/Source/core/loader/ResourceLoadNotifier.cpp b/Source/core/fetch/ResourceLoadNotifier.cpp
similarity index 78%
rename from Source/core/loader/ResourceLoadNotifier.cpp
rename to Source/core/fetch/ResourceLoadNotifier.cpp
index 2804a0d..4e6b266 100644
--- a/Source/core/loader/ResourceLoadNotifier.cpp
+++ b/Source/core/fetch/ResourceLoadNotifier.cpp
@@ -29,7 +29,7 @@
  */
 
 #include "config.h"
-#include "core/loader/ResourceLoadNotifier.h"
+#include "core/fetch/ResourceLoadNotifier.h"
 
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/DocumentLoader.h"
@@ -46,57 +46,67 @@
 {
 }
 
+
+// FIXME(http://crbug.com/274173):
+// |loader| can be null if the resource is loaded from imported document.
+// This means inspector, which uses DocumentLoader as an grouping entity,
+// cannot see imported documents.
+inline DocumentLoader* ResourceLoadNotifier::ensureLoader(DocumentLoader* loader)
+{
+    return loader ? loader : m_frame->loader()->activeDocumentLoader();
+}
+
 void ResourceLoadNotifier::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
 {
     m_frame->loader()->applyUserAgent(request);
     m_frame->loader()->client()->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
-    InspectorInstrumentation::willSendRequest(m_frame, identifier, loader, request, redirectResponse, initiatorInfo);
+    InspectorInstrumentation::willSendRequest(m_frame, identifier, ensureLoader(loader), request, redirectResponse, initiatorInfo);
 }
 
 void ResourceLoadNotifier::dispatchDidReceiveResponse(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, ResourceLoader* resourceLoader)
 {
     if (Page* page = m_frame->page())
-        page->progress()->incrementProgress(identifier, r);
+        page->progress().incrementProgress(identifier, r);
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame, identifier, r);
     m_frame->loader()->client()->dispatchDidReceiveResponse(loader, identifier, r);
-    InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, loader, r, resourceLoader);
+    InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, ensureLoader(loader), r, resourceLoader);
 }
 
 void ResourceLoadNotifier::dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength)
 {
     if (Page* page = m_frame->page())
-        page->progress()->incrementProgress(identifier, data, dataLength);
+        page->progress().incrementProgress(identifier, data, dataLength);
     InspectorInstrumentation::didReceiveData(m_frame, identifier, data, dataLength, encodedDataLength);
 }
 
 void ResourceLoadNotifier::dispatchDidFinishLoading(DocumentLoader* loader, unsigned long identifier, double finishTime)
 {
     if (Page* page = m_frame->page())
-        page->progress()->completeProgress(identifier);
+        page->progress().completeProgress(identifier);
     m_frame->loader()->client()->dispatchDidFinishLoading(loader, identifier);
 
-    InspectorInstrumentation::didFinishLoading(m_frame, identifier, loader, finishTime);
+    InspectorInstrumentation::didFinishLoading(m_frame, identifier, ensureLoader(loader), finishTime);
 }
 
 void ResourceLoadNotifier::dispatchDidFail(DocumentLoader* loader, unsigned long identifier, const ResourceError& error)
 {
     if (Page* page = m_frame->page())
-        page->progress()->completeProgress(identifier);
-    InspectorInstrumentation::didFailLoading(m_frame, identifier, loader, error);
+        page->progress().completeProgress(identifier);
+    InspectorInstrumentation::didFailLoading(m_frame, identifier, ensureLoader(loader), error);
 }
 
 void ResourceLoadNotifier::sendRemainingDelegateMessages(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& response, const char* data, int dataLength, int encodedDataLength, const ResourceError& error)
 {
     if (!response.isNull())
-        dispatchDidReceiveResponse(loader, identifier, response);
+        dispatchDidReceiveResponse(ensureLoader(loader), identifier, response);
 
     if (dataLength > 0)
-        dispatchDidReceiveData(loader, identifier, data, dataLength, encodedDataLength);
+        dispatchDidReceiveData(ensureLoader(loader), identifier, data, dataLength, encodedDataLength);
 
     if (error.isNull())
-        dispatchDidFinishLoading(loader, identifier, 0);
+        dispatchDidFinishLoading(ensureLoader(loader), identifier, 0);
     else
-        dispatchDidFail(loader, identifier, error);
+        dispatchDidFail(ensureLoader(loader), identifier, error);
 }
 
 } // namespace WebCore
diff --git a/Source/core/loader/ResourceLoadNotifier.h b/Source/core/fetch/ResourceLoadNotifier.h
similarity index 96%
rename from Source/core/loader/ResourceLoadNotifier.h
rename to Source/core/fetch/ResourceLoadNotifier.h
index 5e1c5a4..6dd11d8 100644
--- a/Source/core/loader/ResourceLoadNotifier.h
+++ b/Source/core/fetch/ResourceLoadNotifier.h
@@ -30,7 +30,7 @@
 #ifndef ResourceLoadNotifier_h
 #define ResourceLoadNotifier_h
 
-#include "core/loader/cache/FetchInitiatorInfo.h"
+#include "core/fetch/FetchInitiatorInfo.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
@@ -57,6 +57,8 @@
     void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, const char* data, int dataLength, int encodedDataLength, const ResourceError&);
 
 private:
+    inline DocumentLoader* ensureLoader(DocumentLoader*);
+
     Frame* m_frame;
 };
 
diff --git a/Source/core/loader/ResourceLoader.cpp b/Source/core/fetch/ResourceLoader.cpp
similarity index 98%
rename from Source/core/loader/ResourceLoader.cpp
rename to Source/core/fetch/ResourceLoader.cpp
index 389cab4..987cbc5 100644
--- a/Source/core/loader/ResourceLoader.cpp
+++ b/Source/core/fetch/ResourceLoader.cpp
@@ -28,11 +28,11 @@
  */
 
 #include "config.h"
-#include "core/loader/ResourceLoader.h"
+#include "core/fetch/ResourceLoader.h"
 
-#include "core/loader/ResourceLoaderHost.h"
-#include "core/loader/cache/Resource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceLoaderHost.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/Logging.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/chromium/support/WrappedResourceRequest.h"
diff --git a/Source/core/loader/ResourceLoader.h b/Source/core/fetch/ResourceLoader.h
similarity index 98%
rename from Source/core/loader/ResourceLoader.h
rename to Source/core/fetch/ResourceLoader.h
index f7615bb..d298e95 100644
--- a/Source/core/loader/ResourceLoader.h
+++ b/Source/core/fetch/ResourceLoader.h
@@ -29,7 +29,7 @@
 #ifndef ResourceLoader_h
 #define ResourceLoader_h
 
-#include "core/loader/ResourceLoaderOptions.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "public/platform/WebURLLoader.h"
 #include "public/platform/WebURLLoaderClient.h"
diff --git a/Source/core/loader/ResourceLoaderHost.h b/Source/core/fetch/ResourceLoaderHost.h
similarity index 100%
rename from Source/core/loader/ResourceLoaderHost.h
rename to Source/core/fetch/ResourceLoaderHost.h
diff --git a/Source/core/loader/ResourceLoaderOptions.h b/Source/core/fetch/ResourceLoaderOptions.h
similarity index 98%
rename from Source/core/loader/ResourceLoaderOptions.h
rename to Source/core/fetch/ResourceLoaderOptions.h
index 423519b..187efc3 100644
--- a/Source/core/loader/ResourceLoaderOptions.h
+++ b/Source/core/fetch/ResourceLoaderOptions.h
@@ -31,7 +31,7 @@
 #ifndef ResourceLoaderOptions_h
 #define ResourceLoaderOptions_h
 
-#include "core/loader/cache/FetchInitiatorInfo.h"
+#include "core/fetch/FetchInitiatorInfo.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/ResourcePtr.cpp b/Source/core/fetch/ResourcePtr.cpp
similarity index 97%
rename from Source/core/loader/cache/ResourcePtr.cpp
rename to Source/core/fetch/ResourcePtr.cpp
index bbb4352..4ae11a5 100644
--- a/Source/core/loader/cache/ResourcePtr.cpp
+++ b/Source/core/fetch/ResourcePtr.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourcePtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/ResourcePtr.h b/Source/core/fetch/ResourcePtr.h
similarity index 98%
rename from Source/core/loader/cache/ResourcePtr.h
rename to Source/core/fetch/ResourcePtr.h
index dda4d2d..a9bdd5f 100644
--- a/Source/core/loader/cache/ResourcePtr.h
+++ b/Source/core/fetch/ResourcePtr.h
@@ -26,7 +26,7 @@
 #ifndef ResourcePtr_h
 #define ResourcePtr_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/ScriptResource.cpp b/Source/core/fetch/ScriptResource.cpp
similarity index 98%
rename from Source/core/loader/cache/ScriptResource.cpp
rename to Source/core/fetch/ScriptResource.cpp
index b6e9189..330a1bf 100644
--- a/Source/core/loader/cache/ScriptResource.cpp
+++ b/Source/core/fetch/ScriptResource.cpp
@@ -25,7 +25,7 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/ScriptResource.h"
+#include "core/fetch/ScriptResource.h"
 
 #include "core/loader/TextResourceDecoder.h"
 #include "core/platform/MIMETypeRegistry.h"
diff --git a/Source/core/loader/cache/ScriptResource.h b/Source/core/fetch/ScriptResource.h
similarity index 97%
rename from Source/core/loader/cache/ScriptResource.h
rename to Source/core/fetch/ScriptResource.h
index 02d90ca..441a3b0 100644
--- a/Source/core/loader/cache/ScriptResource.h
+++ b/Source/core/fetch/ScriptResource.h
@@ -26,7 +26,7 @@
 #ifndef ScriptResource_h
 #define ScriptResource_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/ShaderResource.cpp b/Source/core/fetch/ShaderResource.cpp
similarity index 97%
rename from Source/core/loader/cache/ShaderResource.cpp
rename to Source/core/fetch/ShaderResource.cpp
index ec60ae1..bacaef9 100644
--- a/Source/core/loader/cache/ShaderResource.cpp
+++ b/Source/core/fetch/ShaderResource.cpp
@@ -28,7 +28,7 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/ShaderResource.h"
+#include "core/fetch/ShaderResource.h"
 
 #include "core/loader/TextResourceDecoder.h"
 #include "core/platform/SharedBuffer.h"
diff --git a/Source/core/loader/cache/ShaderResource.h b/Source/core/fetch/ShaderResource.h
similarity index 97%
rename from Source/core/loader/cache/ShaderResource.h
rename to Source/core/fetch/ShaderResource.h
index f7d2ffe..9485663 100644
--- a/Source/core/loader/cache/ShaderResource.h
+++ b/Source/core/fetch/ShaderResource.h
@@ -30,7 +30,7 @@
 #ifndef ShaderResource_h
 #define ShaderResource_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/StyleSheetResourceClient.h b/Source/core/fetch/StyleSheetResourceClient.h
similarity index 97%
rename from Source/core/loader/cache/StyleSheetResourceClient.h
rename to Source/core/fetch/StyleSheetResourceClient.h
index 02dc5bc..6c12bf3 100644
--- a/Source/core/loader/cache/StyleSheetResourceClient.h
+++ b/Source/core/fetch/StyleSheetResourceClient.h
@@ -26,7 +26,7 @@
 #ifndef StyleSheetResourceClient_h
 #define StyleSheetResourceClient_h
 
-#include "core/loader/cache/ResourceClient.h"
+#include "core/fetch/ResourceClient.h"
 #include "weborigin/KURL.h"
 #include "wtf/Forward.h"
 
diff --git a/Source/core/loader/cache/TextTrackResource.cpp b/Source/core/fetch/TextTrackResource.cpp
similarity index 92%
rename from Source/core/loader/cache/TextTrackResource.cpp
rename to Source/core/fetch/TextTrackResource.cpp
index cf5e4a1..5093d7e 100644
--- a/Source/core/loader/cache/TextTrackResource.cpp
+++ b/Source/core/fetch/TextTrackResource.cpp
@@ -25,10 +25,10 @@
 
 #include "config.h"
 
-#include "core/loader/cache/TextTrackResource.h"
+#include "core/fetch/TextTrackResource.h"
 
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourceClientWalker.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourceClientWalker.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/TextTrackResource.h b/Source/core/fetch/TextTrackResource.h
similarity index 97%
rename from Source/core/loader/cache/TextTrackResource.h
rename to Source/core/fetch/TextTrackResource.h
index c3c0eba..3599f0b 100644
--- a/Source/core/loader/cache/TextTrackResource.h
+++ b/Source/core/fetch/TextTrackResource.h
@@ -26,7 +26,7 @@
 #ifndef TextTrackResource_h
 #define TextTrackResource_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/XSLStyleSheetResource.cpp b/Source/core/fetch/XSLStyleSheetResource.cpp
similarity index 94%
rename from Source/core/loader/cache/XSLStyleSheetResource.cpp
rename to Source/core/fetch/XSLStyleSheetResource.cpp
index 9d9a014..7a165b7 100644
--- a/Source/core/loader/cache/XSLStyleSheetResource.cpp
+++ b/Source/core/fetch/XSLStyleSheetResource.cpp
@@ -25,11 +25,11 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/XSLStyleSheetResource.h"
+#include "core/fetch/XSLStyleSheetResource.h"
 
+#include "core/fetch/ResourceClientWalker.h"
+#include "core/fetch/StyleSheetResourceClient.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/ResourceClientWalker.h"
-#include "core/loader/cache/StyleSheetResourceClient.h"
 #include "core/platform/SharedBuffer.h"
 #include "wtf/Vector.h"
 
@@ -49,6 +49,7 @@
 void XSLStyleSheetResource::didAddClient(ResourceClient* c)
 {
     ASSERT(c->resourceClientType() == StyleSheetResourceClient::expectedType());
+    Resource::didAddClient(c);
     if (!isLoading())
         static_cast<StyleSheetResourceClient*>(c)->setXSLStyleSheet(m_resourceRequest.url(), m_response.url(), m_sheet);
 }
diff --git a/Source/core/loader/cache/XSLStyleSheetResource.h b/Source/core/fetch/XSLStyleSheetResource.h
similarity index 97%
rename from Source/core/loader/cache/XSLStyleSheetResource.h
rename to Source/core/fetch/XSLStyleSheetResource.h
index 4cab515..52e6814 100644
--- a/Source/core/loader/cache/XSLStyleSheetResource.h
+++ b/Source/core/fetch/XSLStyleSheetResource.h
@@ -26,7 +26,7 @@
 #ifndef XSLStyleSheetResource_h
 #define XSLStyleSheetResource_h
 
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/Resource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/fileapi/FileError.cpp b/Source/core/fileapi/FileError.cpp
index 82b6a81..2fa8576 100644
--- a/Source/core/fileapi/FileError.cpp
+++ b/Source/core/fileapi/FileError.cpp
@@ -48,68 +48,100 @@
 const char FileError::syntaxErrorMessage[] = "An invalid or unsupported argument was given, like an invalid line ending specifier.";
 const char FileError::typeMismatchErrorMessage[] = "The path supplied exists, but was not an entry of requested type.";
 
+namespace {
+
+ExceptionCode errorCodeToExceptionCode(FileError::ErrorCode code)
+{
+    switch (code) {
+    case FileError::OK:
+        return 0;
+    case FileError::NOT_FOUND_ERR:
+        return NotFoundError;
+    case FileError::SECURITY_ERR:
+        return SecurityError;
+    case FileError::ABORT_ERR:
+        return AbortError;
+    case FileError::NOT_READABLE_ERR:
+        return NotReadableError;
+    case FileError::ENCODING_ERR:
+        return EncodingError;
+    case FileError::NO_MODIFICATION_ALLOWED_ERR:
+        return NoModificationAllowedError;
+    case FileError::INVALID_STATE_ERR:
+        return InvalidStateError;
+    case FileError::SYNTAX_ERR:
+        return SyntaxError;
+    case FileError::INVALID_MODIFICATION_ERR:
+        return InvalidModificationError;
+    case FileError::QUOTA_EXCEEDED_ERR:
+        return QuotaExceededError;
+    case FileError::TYPE_MISMATCH_ERR:
+        return TypeMismatchError;
+    case FileError::PATH_EXISTS_ERR:
+        return PathExistsError;
+    default:
+        ASSERT_NOT_REACHED();
+        return code;
+    }
+}
+
+const char* errorCodeToMessage(FileError::ErrorCode code)
+{
+    // Note that some of these do not set message. If message is 0 then the default message is used.
+    switch (code) {
+    case FileError::OK:
+        return 0;
+    case FileError::SECURITY_ERR:
+        return FileError::securityErrorMessage;
+    case FileError::NOT_FOUND_ERR:
+        return FileError::notFoundErrorMessage;
+    case FileError::ABORT_ERR:
+        return FileError::abortErrorMessage;
+    case FileError::NOT_READABLE_ERR:
+        return FileError::notReadableErrorMessage;
+    case FileError::ENCODING_ERR:
+        return FileError::encodingErrorMessage;
+    case FileError::NO_MODIFICATION_ALLOWED_ERR:
+        return FileError::noModificationAllowedErrorMessage;
+    case FileError::INVALID_STATE_ERR:
+        return FileError::invalidStateErrorMessage;
+    case FileError::SYNTAX_ERR:
+        return FileError::syntaxErrorMessage;
+    case FileError::INVALID_MODIFICATION_ERR:
+        return 0;
+    case FileError::QUOTA_EXCEEDED_ERR:
+        return FileError::quotaExceededErrorMessage;
+    case FileError::TYPE_MISMATCH_ERR:
+        return 0;
+    case FileError::PATH_EXISTS_ERR:
+        return FileError::pathExistsErrorMessage;
+    default:
+        ASSERT_NOT_REACHED();
+        return 0;
+    }
+}
+
+} // namespace
+
 void FileError::throwDOMException(ExceptionState& es, ErrorCode code)
 {
     if (code == FileError::OK)
         return;
 
-    ExceptionCode ec;
-    const char* message = 0;
-
-    // Note that some of these do not set message. If message is 0 then the default message is used.
-    switch (code) {
-    case FileError::NOT_FOUND_ERR:
-        ec = NotFoundError;
-        message = FileError::notFoundErrorMessage;
-        break;
-    case FileError::SECURITY_ERR:
-        ec = SecurityError;
-        message = FileError::securityErrorMessage;
-        break;
-    case FileError::ABORT_ERR:
-        ec = AbortError;
-        message = FileError::abortErrorMessage;
-        break;
-    case FileError::NOT_READABLE_ERR:
-        ec = NotReadableError;
-        message = FileError::notReadableErrorMessage;
-        break;
-    case FileError::ENCODING_ERR:
-        ec = EncodingError;
-        message = FileError::encodingErrorMessage;
-        break;
-    case FileError::NO_MODIFICATION_ALLOWED_ERR:
-        ec = NoModificationAllowedError;
-        message = FileError::noModificationAllowedErrorMessage;
-        break;
-    case FileError::INVALID_STATE_ERR:
-        ec = InvalidStateError;
-        message = FileError::invalidStateErrorMessage;
-        break;
-    case FileError::SYNTAX_ERR:
-        ec = SyntaxError;
-        message = FileError::syntaxErrorMessage;
-        break;
-    case FileError::INVALID_MODIFICATION_ERR:
-        ec = InvalidModificationError;
-        break;
-    case FileError::QUOTA_EXCEEDED_ERR:
-        ec = QuotaExceededError;
-        message = FileError::quotaExceededErrorMessage;
-        break;
-    case FileError::TYPE_MISMATCH_ERR:
-        ec = TypeMismatchError;
-        break;
-    case FileError::PATH_EXISTS_ERR:
-        ec = PathExistsError;
-        message = FileError::pathExistsErrorMessage;
-        break;
-    default:
-        ASSERT_NOT_REACHED();
+    // SecurityError is special-cased, as we want to route those exceptions through ExceptionState::throwSecurityError.
+    if (code == FileError::SECURITY_ERR) {
+        es.throwSecurityError(FileError::securityErrorMessage);
         return;
     }
 
-    es.throwDOMException(ec, message);
+    es.throwDOMException(errorCodeToExceptionCode(code), errorCodeToMessage(code));
+}
+
+FileError::FileError(ErrorCode code)
+    : DOMError(DOMException::getErrorName(errorCodeToExceptionCode(code)), errorCodeToMessage(code))
+    , m_code(code)
+{
+    ScriptWrappable::init(this);
 }
 
 } // namespace WebCore
diff --git a/Source/core/fileapi/FileError.h b/Source/core/fileapi/FileError.h
index 2dcf68c..26dd392 100644
--- a/Source/core/fileapi/FileError.h
+++ b/Source/core/fileapi/FileError.h
@@ -32,6 +32,7 @@
 #define FileError_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/DOMError.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
@@ -39,7 +40,7 @@
 
 class ExceptionState;
 
-class FileError : public RefCounted<FileError>, public ScriptWrappable {
+class FileError : public DOMError {
 public:
     enum ErrorCode {
         OK = 0,
@@ -76,11 +77,7 @@
     static void throwDOMException(ExceptionState&, ErrorCode);
 
 private:
-    FileError(ErrorCode code)
-        : m_code(code)
-    {
-        ScriptWrappable::init(this);
-    }
+    explicit FileError(ErrorCode);
 
     ErrorCode m_code;
 };
diff --git a/Source/core/fileapi/FileError.idl b/Source/core/fileapi/FileError.idl
index 7e5542a..4f40dc8 100644
--- a/Source/core/fileapi/FileError.idl
+++ b/Source/core/fileapi/FileError.idl
@@ -29,7 +29,7 @@
  */
 
 [
-] interface FileError {
+] interface FileError : DOMError {
     const unsigned short NOT_FOUND_ERR = 1;
     const unsigned short SECURITY_ERR = 2;
     const unsigned short ABORT_ERR = 3;
@@ -42,5 +42,6 @@
     const unsigned short QUOTA_EXCEEDED_ERR = 10;
     const unsigned short TYPE_MISMATCH_ERR = 11;
     const unsigned short PATH_EXISTS_ERR = 12;
-    readonly attribute unsigned short code;
+
+    [DeprecateAs=FileError] readonly attribute unsigned short code;
 };
diff --git a/Source/core/fileapi/FileReader.cpp b/Source/core/fileapi/FileReader.cpp
index 1bdefdb..612c072 100644
--- a/Source/core/fileapi/FileReader.cpp
+++ b/Source/core/fileapi/FileReader.cpp
@@ -231,10 +231,11 @@
     if (m_aborting)
         return;
 
+    fireEvent(eventNames().progressEvent);
+
     ASSERT(m_state != DONE);
     m_state = DONE;
 
-    fireEvent(eventNames().progressEvent);
     fireEvent(eventNames().loadEvent);
     fireEvent(eventNames().loadendEvent);
 
diff --git a/Source/core/history/BackForwardClient.h b/Source/core/history/BackForwardClient.h
index 3bbc8bc..0a3cf73 100644
--- a/Source/core/history/BackForwardClient.h
+++ b/Source/core/history/BackForwardClient.h
@@ -38,17 +38,9 @@
 public:
     virtual ~BackForwardClient() { }
 
-    virtual void addItem(PassRefPtr<HistoryItem>) = 0;
-
-    virtual void goToItem(HistoryItem*) = 0;
-
-    virtual HistoryItem* itemAtIndex(int) = 0;
+    virtual void didAddItem() = 0;
     virtual int backListCount() = 0;
     virtual int forwardListCount() = 0;
-
-    virtual bool isActive() = 0;
-
-    virtual void close() = 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/history/BackForwardController.cpp b/Source/core/history/BackForwardController.cpp
index 5e59897..45fde04 100644
--- a/Source/core/history/BackForwardController.cpp
+++ b/Source/core/history/BackForwardController.cpp
@@ -28,6 +28,9 @@
 
 #include "core/history/BackForwardClient.h"
 #include "core/history/HistoryItem.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/page/Frame.h"
 #include "core/page/Page.h"
 
 namespace WebCore {
@@ -48,58 +51,29 @@
     return adoptPtr(new BackForwardController(page, client));
 }
 
-void BackForwardController::goBackOrForward(int distance)
+bool BackForwardController::goBackOrForward(int distance)
 {
-    if (distance == 0)
-        return;
+    ASSERT(distance);
+    if (distance > forwardCount())
+        distance = forwardCount();
+    else if (distance < -backCount())
+        distance = backCount();
 
-    HistoryItem* item = itemAtIndex(distance);
-    if (!item) {
-        if (distance > 0) {
-            if (forwardCount())
-                item = itemAtIndex(forwardCount());
-        } else {
-            if (backCount())
-                item = itemAtIndex(-backCount());
-        }
-    }
-
-    if (!item)
-        return;
-
-    m_page->goToItem(item);
-}
-
-bool BackForwardController::goBack()
-{
-    HistoryItem* item = backItem();
-
-    if (item) {
-        m_page->goToItem(item);
-        return true;
-    }
-    return false;
-}
-
-bool BackForwardController::goForward()
-{
-    HistoryItem* item = forwardItem();
-
-    if (item) {
-        m_page->goToItem(item);
-        return true;
-    }
-    return false;
+    if (!distance)
+        return false;
+    m_page->mainFrame()->loader()->client()->navigateBackForward(distance);
+    return true;
 }
 
 void BackForwardController::addItem(PassRefPtr<HistoryItem> item)
 {
-    m_client->addItem(item);
+    m_currentItem = item;
+    m_client->didAddItem();
 }
 
 void BackForwardController::setCurrentItem(HistoryItem* item)
 {
-    m_client->goToItem(item);
+    m_currentItem = item;
 }
 
 int BackForwardController::count() const
@@ -117,19 +91,4 @@
     return m_client->forwardListCount();
 }
 
-HistoryItem* BackForwardController::itemAtIndex(int i)
-{
-    return m_client->itemAtIndex(i);
-}
-
-bool BackForwardController::isActive()
-{
-    return m_client->isActive();
-}
-
-void BackForwardController::close()
-{
-    m_client->close();
-}
-
 } // namespace WebCore
diff --git a/Source/core/history/BackForwardController.h b/Source/core/history/BackForwardController.h
index d315fd6..79c48a0 100644
--- a/Source/core/history/BackForwardController.h
+++ b/Source/core/history/BackForwardController.h
@@ -46,33 +46,26 @@
 
     BackForwardClient* client() const { return m_client; }
 
-    void goBackOrForward(int distance);
-
-    bool goBack();
-    bool goForward();
+    bool goBackOrForward(int distance);
+    bool goBack() { return goBackOrForward(-1); }
+    bool goForward() { return goBackOrForward(1); }
 
     void addItem(PassRefPtr<HistoryItem>);
     void setCurrentItem(HistoryItem*);
+    HistoryItem* currentItem() { return m_currentItem.get(); }
 
     int count() const;
     int backCount() const;
     int forwardCount() const;
 
-    HistoryItem* itemAtIndex(int);
-
-    bool isActive();
-
-    void close();
-
-    HistoryItem* backItem() { return itemAtIndex(-1); }
-    HistoryItem* currentItem() { return itemAtIndex(0); }
-    HistoryItem* forwardItem() { return itemAtIndex(1); }
-
 private:
     BackForwardController(Page*, BackForwardClient*);
 
     Page* m_page;
     BackForwardClient* m_client;
+
+    // FIXME: Ideally, we could derive this from HistoryController, but the rules for setting it are non-obvious.
+    RefPtr<HistoryItem> m_currentItem;
 };
 
 } // namespace WebCore
diff --git a/Source/core/history/HistoryItem.cpp b/Source/core/history/HistoryItem.cpp
index 1a2c317..4db012d 100644
--- a/Source/core/history/HistoryItem.cpp
+++ b/Source/core/history/HistoryItem.cpp
@@ -53,18 +53,6 @@
 {
 }
 
-HistoryItem::HistoryItem(const String& urlString)
-    : m_urlString(urlString)
-    , m_originalURLString(urlString)
-    , m_lastVisitedTime(0)
-    , m_pageScaleFactor(0)
-    , m_isTargetItem(false)
-    , m_visitCount(0)
-    , m_itemSequenceNumber(generateSequenceNumber())
-    , m_documentSequenceNumber(generateSequenceNumber())
-{
-}
-
 HistoryItem::~HistoryItem()
 {
 }
diff --git a/Source/core/history/HistoryItem.h b/Source/core/history/HistoryItem.h
index 5b7119c..8ac78ab 100644
--- a/Source/core/history/HistoryItem.h
+++ b/Source/core/history/HistoryItem.h
@@ -46,10 +46,6 @@
 class HistoryItem : public RefCounted<HistoryItem> {
 public:
     static PassRefPtr<HistoryItem> create() { return adoptRef(new HistoryItem); }
-    static PassRefPtr<HistoryItem> create(const String& urlString)
-    {
-        return adoptRef(new HistoryItem(urlString));
-    }
 
     ~HistoryItem();
 
@@ -136,8 +132,6 @@
 
 private:
     HistoryItem();
-    explicit HistoryItem(const String& urlString);
-
     explicit HistoryItem(const HistoryItem&);
 
     void recordVisitAtTime(double);
diff --git a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
index 8ea2d94..e059b27 100644
--- a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -130,22 +130,22 @@
 
 DateTimeEditElement* BaseMultipleFieldsDateAndTimeInputType::dateTimeEditElement() const
 {
-    return toDateTimeEditElement(element()->uaShadowElementById(ShadowElementNames::dateTimeEdit()));
+    return toDateTimeEditElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::dateTimeEdit()));
 }
 
 SpinButtonElement* BaseMultipleFieldsDateAndTimeInputType::spinButtonElement() const
 {
-    return toSpinButtonElement(element()->uaShadowElementById(ShadowElementNames::spinButton()));
+    return toSpinButtonElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
 }
 
 ClearButtonElement* BaseMultipleFieldsDateAndTimeInputType::clearButtonElement() const
 {
-    return toClearButtonElement(element()->uaShadowElementById(ShadowElementNames::clearButton()));
+    return toClearButtonElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton()));
 }
 
 PickerIndicatorElement* BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorElement() const
 {
-    return toPickerIndicatorElement(element()->uaShadowElementById(ShadowElementNames::pickerIndicator()));
+    return toPickerIndicatorElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::pickerIndicator()));
 }
 
 inline bool BaseMultipleFieldsDateAndTimeInputType::containsFocusedShadowElement() const
@@ -380,7 +380,7 @@
     if (direction == FocusDirectionBackward) {
         if (element()->document()->page())
             element()->document()->page()->focusController().advanceFocus(direction);
-    } else if (direction == FocusDirectionNone || direction == FocusDirectionMouse) {
+    } else if (direction == FocusDirectionNone || direction == FocusDirectionMouse || direction == FocusDirectionPage) {
         edit->focusByOwner(oldFocusedElement);
     } else
         edit->focusByOwner();
diff --git a/Source/core/html/ColorInputType.cpp b/Source/core/html/ColorInputType.cpp
index 46e741a..d689d6c 100644
--- a/Source/core/html/ColorInputType.cpp
+++ b/Source/core/html/ColorInputType.cpp
@@ -76,7 +76,7 @@
     endColorChooser();
 }
 
-void ColorInputType::attach()
+void ColorInputType::countUsage()
 {
     observeFeatureIfVisible(UseCounter::InputTypeColor);
 }
@@ -123,8 +123,8 @@
     wrapperElement->setPart(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
     RefPtr<HTMLDivElement> colorSwatch = HTMLDivElement::create(document);
     colorSwatch->setPart(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
-    wrapperElement->appendChild(colorSwatch.release(), ASSERT_NO_EXCEPTION);
-    element()->userAgentShadowRoot()->appendChild(wrapperElement.release(), ASSERT_NO_EXCEPTION);
+    wrapperElement->appendChild(colorSwatch.release());
+    element()->userAgentShadowRoot()->appendChild(wrapperElement.release());
 
     updateColorSwatch();
 }
diff --git a/Source/core/html/ColorInputType.h b/Source/core/html/ColorInputType.h
index fedaac7..a82429b 100644
--- a/Source/core/html/ColorInputType.h
+++ b/Source/core/html/ColorInputType.h
@@ -51,7 +51,7 @@
 
 private:
     ColorInputType(HTMLInputElement* element) : BaseClickableWithKeyInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual bool isColorControl() const OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool supportsRequired() const OVERRIDE;
diff --git a/Source/core/html/DOMURL.cpp b/Source/core/html/DOMURL.cpp
index 360cc2f..a7b7f71 100644
--- a/Source/core/html/DOMURL.cpp
+++ b/Source/core/html/DOMURL.cpp
@@ -29,10 +29,10 @@
 #include "core/html/DOMURL.h"
 
 #include "core/dom/ScriptExecutionContext.h"
+#include "core/fetch/MemoryCache.h"
 #include "core/fileapi/Blob.h"
 #include "core/fileapi/BlobURL.h"
 #include "core/html/PublicURLManager.h"
-#include "core/loader/cache/MemoryCache.h"
 #include "weborigin/KURL.h"
 #include "wtf/MainThread.h"
 
diff --git a/Source/core/html/DateInputType.cpp b/Source/core/html/DateInputType.cpp
index b18edd8..49779fd 100644
--- a/Source/core/html/DateInputType.cpp
+++ b/Source/core/html/DateInputType.cpp
@@ -58,7 +58,7 @@
     return adoptPtr(new DateInputType(element));
 }
 
-void DateInputType::attach()
+void DateInputType::countUsage()
 {
     observeFeatureIfVisible(UseCounter::InputTypeDate);
 }
diff --git a/Source/core/html/DateInputType.h b/Source/core/html/DateInputType.h
index 3c25c9b..d339a25 100644
--- a/Source/core/html/DateInputType.h
+++ b/Source/core/html/DateInputType.h
@@ -50,7 +50,7 @@
 
 private:
     DateInputType(HTMLInputElement*);
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
diff --git a/Source/core/html/DateTimeLocalInputType.cpp b/Source/core/html/DateTimeLocalInputType.cpp
index 10769fb..1428ae5 100644
--- a/Source/core/html/DateTimeLocalInputType.cpp
+++ b/Source/core/html/DateTimeLocalInputType.cpp
@@ -58,7 +58,7 @@
     return adoptPtr(new DateTimeLocalInputType(element));
 }
 
-void DateTimeLocalInputType::attach()
+void DateTimeLocalInputType::countUsage()
 {
     observeFeatureIfVisible(UseCounter::InputTypeDateTimeLocal);
 }
diff --git a/Source/core/html/DateTimeLocalInputType.h b/Source/core/html/DateTimeLocalInputType.h
index 6a06c24..0e25195 100644
--- a/Source/core/html/DateTimeLocalInputType.h
+++ b/Source/core/html/DateTimeLocalInputType.h
@@ -50,7 +50,7 @@
 
 private:
     DateTimeLocalInputType(HTMLInputElement* element) : BaseDateTimeLocalInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual double valueAsDate() const OVERRIDE;
diff --git a/Source/core/html/EmailInputType.cpp b/Source/core/html/EmailInputType.cpp
index 086af07..76aecd5 100644
--- a/Source/core/html/EmailInputType.cpp
+++ b/Source/core/html/EmailInputType.cpp
@@ -80,11 +80,10 @@
     if (address.find("xn--", atPosition + 1) == notFound)
         return address;
 
-    ChromeClient* chromeClient = chrome() ? chrome()->client() : 0;
-    if (!chromeClient)
+    if (!chrome())
         return address;
 
-    String languages = chromeClient->acceptLanguages();
+    String languages = chrome()->client().acceptLanguages();
     String unicodeHost = WebKit::Platform::current()->convertIDNToUnicode(address.substring(atPosition + 1), languages);
     StringBuilder builder;
     builder.append(address, 0, atPosition + 1);
@@ -111,9 +110,8 @@
     return adoptPtr(new EmailInputType(element));
 }
 
-void EmailInputType::attach()
+void EmailInputType::countUsage()
 {
-    TextFieldInputType::attach();
     observeFeatureIfVisible(UseCounter::InputTypeEmail);
 }
 
diff --git a/Source/core/html/EmailInputType.h b/Source/core/html/EmailInputType.h
index a4cc34c..955a77d 100644
--- a/Source/core/html/EmailInputType.h
+++ b/Source/core/html/EmailInputType.h
@@ -41,7 +41,7 @@
 
 private:
     EmailInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool typeMismatchFor(const String&) const OVERRIDE;
     virtual bool typeMismatch() const OVERRIDE;
diff --git a/Source/core/html/FileInputType.cpp b/Source/core/html/FileInputType.cpp
index 8db9fad..da4a247 100644
--- a/Source/core/html/FileInputType.cpp
+++ b/Source/core/html/FileInputType.cpp
@@ -260,7 +260,7 @@
     button->setType(InputTypeNames::button());
     button->setAttribute(valueAttr, element()->multiple() ? fileButtonChooseMultipleFilesLabel() : fileButtonChooseFileLabel());
     button->setPart(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
-    element()->userAgentShadowRoot()->appendChild(button.release(), IGNORE_EXCEPTION);
+    element()->userAgentShadowRoot()->appendChild(button.release());
 }
 
 void FileInputType::disabledAttributeChanged()
diff --git a/Source/core/html/FormAssociatedElement.cpp b/Source/core/html/FormAssociatedElement.cpp
index a31e058..58f6654 100644
--- a/Source/core/html/FormAssociatedElement.cpp
+++ b/Source/core/html/FormAssociatedElement.cpp
@@ -75,6 +75,9 @@
 
 void FormAssociatedElement::insertedInto(ContainerNode* insertionPoint)
 {
+    if (m_form && insertionPoint->highestAncestor() != m_form->highestAncestor())
+        setForm(0);
+
     resetFormOwner();
     if (!insertionPoint->inDocument())
         return;
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index efbacc2..ca3767e 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -48,6 +48,7 @@
 #include "core/platform/network/DNS.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "core/rendering/RenderImage.h"
+#include "core/svg/graphics/SVGImage.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebPrescientNetworking.h"
 #include "public/platform/WebURL.h"
@@ -172,7 +173,7 @@
     if (!page)
         return false;
 
-    if (!page->chrome().client()->tabsToLinks())
+    if (!page->chrome().client().tabsToLinks())
         return false;
 
     if (isInCanvasSubtree())
diff --git a/Source/core/html/HTMLAttributeNames.in b/Source/core/html/HTMLAttributeNames.in
index 7ca6ac1..fc59f67 100644
--- a/Source/core/html/HTMLAttributeNames.in
+++ b/Source/core/html/HTMLAttributeNames.in
@@ -265,6 +265,7 @@
 onwebkitsourceended
 onwebkitsourceopen
 onwebkittransitionend
+onwheel
 open
 optimum
 part
diff --git a/Source/core/html/HTMLBodyElement.cpp b/Source/core/html/HTMLBodyElement.cpp
index e9a386b..692855b 100644
--- a/Source/core/html/HTMLBodyElement.cpp
+++ b/Source/core/html/HTMLBodyElement.cpp
@@ -172,7 +172,7 @@
     // FIXME: Perhaps this code should be in attach() instead of here.
     Element* ownerElement = document()->ownerElement();
     if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
-        HTMLFrameElementBase* ownerFrameElement = static_cast<HTMLFrameElementBase*>(ownerElement);
+        HTMLFrameElementBase* ownerFrameElement = toHTMLFrameElementBase(ownerElement);
         int marginWidth = ownerFrameElement->marginWidth();
         if (marginWidth != -1)
             setAttribute(marginwidthAttr, String::number(marginWidth));
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index 9a68a4d..bb12fa4 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -31,6 +31,7 @@
 #include <math.h>
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/Document.h"
@@ -342,12 +343,6 @@
     return m_context && m_context->is3d();
 }
 
-void HTMLCanvasElement::makeRenderingResultsAvailable()
-{
-    if (m_context)
-        m_context->paintRenderingResultsToCanvas();
-}
-
 void HTMLCanvasElement::makePresentationCopy()
 {
     if (!m_presentedImage) {
@@ -385,7 +380,7 @@
 String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionState& es)
 {
     if (!m_originClean) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError(ExceptionMessages::failedToExecute("toDataURL", "HTMLCanvasElement", "tainted canvases may not be exported."));
         return String();
     }
 
@@ -400,7 +395,8 @@
     if (imageData)
         return ImageDataToDataURL(*imageData, encodingMimeType, quality);
 
-    makeRenderingResultsAvailable();
+    if (m_context)
+        m_context->paintRenderingResultsToCanvas();
 
     return buffer()->toDataURL(encodingMimeType, quality);
 }
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index 1de3401..1ff23b2 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -126,7 +126,6 @@
 
     bool is3D() const;
 
-    void makeRenderingResultsAvailable();
     bool hasCreatedImageBuffer() const { return m_hasCreatedImageBuffer; }
 
     bool shouldAccelerate(const IntSize&) const;
diff --git a/Source/core/html/HTMLCollection.cpp b/Source/core/html/HTMLCollection.cpp
index 613c57a..ee988d6 100644
--- a/Source/core/html/HTMLCollection.cpp
+++ b/Source/core/html/HTMLCollection.cpp
@@ -25,6 +25,7 @@
 
 #include "HTMLNames.h"
 #include "core/dom/ClassNodeList.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeList.h"
 #include "core/dom/NodeRareData.h"
 #include "core/dom/NodeTraversal.h"
@@ -211,7 +212,7 @@
     case MapAreas:
         return element->hasLocalName(areaTag);
     case DocApplets:
-        return element->hasLocalName(appletTag) || (element->hasLocalName(objectTag) && static_cast<HTMLObjectElement*>(element)->containsJavaApplet());
+        return element->hasLocalName(appletTag) || (element->hasLocalName(objectTag) && toHTMLObjectElement(element)->containsJavaApplet());
     case DocEmbeds:
         return element->hasLocalName(embedTag);
     case DocLinks:
diff --git a/Source/core/html/HTMLDetailsElement.cpp b/Source/core/html/HTMLDetailsElement.cpp
index 77e35fa..0db492d 100644
--- a/Source/core/html/HTMLDetailsElement.cpp
+++ b/Source/core/html/HTMLDetailsElement.cpp
@@ -60,14 +60,14 @@
     DEFINE_STATIC_LOCAL(AtomicString, summarySelector, ("summary:first-of-type", AtomicString::ConstructFromLiteral));
 
     RefPtr<HTMLSummaryElement> defaultSummary = HTMLSummaryElement::create(summaryTag, document());
-    defaultSummary->appendChild(Text::create(document(), defaultDetailsSummaryText()), ASSERT_NO_EXCEPTION);
+    defaultSummary->appendChild(Text::create(document(), defaultDetailsSummaryText()));
 
     RefPtr<HTMLContentElement> content = HTMLContentElement::create(document());
     content->setAttribute(selectAttr, summarySelector);
     content->appendChild(defaultSummary);
 
-    root->appendChild(content, ASSERT_NO_EXCEPTION, AttachLazily);
-    root->appendChild(HTMLContentElement::create(document()), ASSERT_NO_EXCEPTION, AttachLazily);
+    root->appendChild(content);
+    root->appendChild(HTMLContentElement::create(document()));
 }
 
 Element* HTMLDetailsElement::findMainSummary() const
diff --git a/Source/core/html/HTMLDialogElement.idl b/Source/core/html/HTMLDialogElement.idl
index 2cf7e38..d95f10f 100644
--- a/Source/core/html/HTMLDialogElement.idl
+++ b/Source/core/html/HTMLDialogElement.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledPerContext=dialogElement
+    EnabledAtRuntime=dialogElement
 ] interface HTMLDialogElement : HTMLElement {
     [Reflect] attribute boolean open;
     attribute DOMString returnValue;
diff --git a/Source/core/html/HTMLDivElement.h b/Source/core/html/HTMLDivElement.h
index a927fab..ab96714 100644
--- a/Source/core/html/HTMLDivElement.h
+++ b/Source/core/html/HTMLDivElement.h
@@ -40,6 +40,12 @@
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 };
 
+inline HTMLDivElement* toHTMLDivElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::divTag));
+    return static_cast<HTMLDivElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // HTMLDivElement_h
diff --git a/Source/core/html/HTMLDocument.cpp b/Source/core/html/HTMLDocument.cpp
index 704547f..0280bdf 100644
--- a/Source/core/html/HTMLDocument.cpp
+++ b/Source/core/html/HTMLDocument.cpp
@@ -216,11 +216,6 @@
     }
 }
 
-PassRefPtr<Document> HTMLDocument::cloneDocumentWithoutChildren()
-{
-    return create();
-}
-
 // --------------------------------------------------------------------------
 // not part of the DOM
 // --------------------------------------------------------------------------
diff --git a/Source/core/html/HTMLDocument.h b/Source/core/html/HTMLDocument.h
index 993fbc0..6990a78 100644
--- a/Source/core/html/HTMLDocument.h
+++ b/Source/core/html/HTMLDocument.h
@@ -24,7 +24,7 @@
 #define HTMLDocument_h
 
 #include "core/dom/Document.h"
-#include "core/loader/cache/ResourceClient.h"
+#include "core/fetch/ResourceClient.h"
 #include "wtf/HashCountedSet.h"
 
 namespace WebCore {
@@ -76,8 +76,6 @@
 
     static bool isCaseSensitiveAttribute(const QualifiedName&);
 
-    virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
-
 protected:
     HTMLDocument(const DocumentInit&, DocumentClassFlags extendedDocumentClasses = DefaultDocumentClass);
 
diff --git a/Source/core/html/HTMLElement.cpp b/Source/core/html/HTMLElement.cpp
index 6692228..7dec05b 100644
--- a/Source/core/html/HTMLElement.cpp
+++ b/Source/core/html/HTMLElement.cpp
@@ -212,6 +212,7 @@
         attributeNameToEventNameMap.set(onmouseoverAttr.localName(), eventNames().mouseoverEvent);
         attributeNameToEventNameMap.set(onmouseupAttr.localName(), eventNames().mouseupEvent);
         attributeNameToEventNameMap.set(onmousewheelAttr.localName(), eventNames().mousewheelEvent);
+        attributeNameToEventNameMap.set(onwheelAttr.localName(), eventNames().wheelEvent);
         attributeNameToEventNameMap.set(onfocusAttr.localName(), eventNames().focusEvent);
         attributeNameToEventNameMap.set(onfocusinAttr.localName(), eventNames().focusinEvent);
         attributeNameToEventNameMap.set(onfocusoutAttr.localName(), eventNames().focusoutEvent);
@@ -499,7 +500,7 @@
 
     if (equalIgnoringCase(where, "beforeBegin")) {
         if (ContainerNode* parent = this->parentNode()) {
-            parent->insertBefore(newChild, this, es, AttachLazily);
+            parent->insertBefore(newChild, this, es);
             if (!es.hadException())
                 return newChild;
         }
@@ -507,18 +508,18 @@
     }
 
     if (equalIgnoringCase(where, "afterBegin")) {
-        insertBefore(newChild, firstChild(), es, AttachLazily);
+        insertBefore(newChild, firstChild(), es);
         return es.hadException() ? 0 : newChild;
     }
 
     if (equalIgnoringCase(where, "beforeEnd")) {
-        appendChild(newChild, es, AttachLazily);
+        appendChild(newChild, es);
         return es.hadException() ? 0 : newChild;
     }
 
     if (equalIgnoringCase(where, "afterEnd")) {
         if (ContainerNode* parent = this->parentNode()) {
-            parent->insertBefore(newChild, nextSibling(), es, AttachLazily);
+            parent->insertBefore(newChild, nextSibling(), es);
             if (!es.hadException())
                 return newChild;
         }
@@ -1080,6 +1081,11 @@
 {
     if (!document()->settings() || !document()->settings()->spatialNavigationEnabled() || !supportsFocus())
         return;
+    // if the element is a text form control (like <input type=text> or <textarea>)
+    // or has contentEditable attribute on, we should enter a space or newline
+    // even in spatial navigation mode instead of handling it as a "click" action.
+    if (isTextFormControl() || isContentEditable())
+        return;
     int charCode = event->charCode();
     if (charCode == '\r' || charCode == ' ') {
         dispatchSimulatedClick(event);
diff --git a/Source/core/html/HTMLEmbedElement.cpp b/Source/core/html/HTMLEmbedElement.cpp
index e0c1e7e..f0c48b1 100644
--- a/Source/core/html/HTMLEmbedElement.cpp
+++ b/Source/core/html/HTMLEmbedElement.cpp
@@ -52,6 +52,11 @@
     return adoptRef(new HTMLEmbedElement(tagName, document, createdByParser));
 }
 
+PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(Document* document)
+{
+    return create(embedTag, document, false);
+}
+
 static inline RenderWidget* findWidgetRenderer(const Node* n)
 {
     if (!n->renderer())
@@ -183,7 +188,7 @@
     ContainerNode* p = parentNode();
     if (p && p->hasTagName(objectTag)) {
         ASSERT(p->renderer());
-        if (!static_cast<HTMLObjectElement*>(p)->useFallbackContent()) {
+        if (!toHTMLObjectElement(p)->useFallbackContent()) {
             ASSERT(!p->renderer()->isEmbeddedObject());
             return false;
         }
diff --git a/Source/core/html/HTMLEmbedElement.h b/Source/core/html/HTMLEmbedElement.h
index a5acdc8..90153dc 100644
--- a/Source/core/html/HTMLEmbedElement.h
+++ b/Source/core/html/HTMLEmbedElement.h
@@ -29,6 +29,7 @@
 
 class HTMLEmbedElement FINAL : public HTMLPlugInImageElement {
 public:
+    static PassRefPtr<HTMLEmbedElement> create(Document*);
     static PassRefPtr<HTMLEmbedElement> create(const QualifiedName&, Document*, bool createdByParser);
 
 private:
diff --git a/Source/core/html/HTMLFieldSetElement.cpp b/Source/core/html/HTMLFieldSetElement.cpp
index b3f3e9c..083b0cb 100644
--- a/Source/core/html/HTMLFieldSetElement.cpp
+++ b/Source/core/html/HTMLFieldSetElement.cpp
@@ -26,7 +26,7 @@
 #include "core/html/HTMLFieldSetElement.h"
 
 #include "HTMLNames.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLLegendElement.h"
 #include "core/html/HTMLObjectElement.h"
@@ -116,7 +116,7 @@
 
     for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element, this)) {
         if (element->hasTagName(objectTag)) {
-            m_associatedElements.append(static_cast<HTMLObjectElement*>(element));
+            m_associatedElements.append(toHTMLObjectElement(element));
             continue;
         }
 
diff --git a/Source/core/html/HTMLFormControlElement.cpp b/Source/core/html/HTMLFormControlElement.cpp
index 4958a8d..012251d 100644
--- a/Source/core/html/HTMLFormControlElement.cpp
+++ b/Source/core/html/HTMLFormControlElement.cpp
@@ -334,7 +334,8 @@
 
 void HTMLFormControlElement::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection direction)
 {
-    m_wasFocusedByMouse = direction == FocusDirectionMouse;
+    if (direction != FocusDirectionPage)
+        m_wasFocusedByMouse = direction == FocusDirectionMouse;
     HTMLElement::dispatchFocusEvent(oldFocusedElement, direction);
 }
 
diff --git a/Source/core/html/HTMLFormControlElementWithState.cpp b/Source/core/html/HTMLFormControlElementWithState.cpp
index 4e4acd2..9e862f5 100644
--- a/Source/core/html/HTMLFormControlElementWithState.cpp
+++ b/Source/core/html/HTMLFormControlElementWithState.cpp
@@ -71,7 +71,7 @@
         return;
 
     if (Page* page = frame->page())
-        page->chrome().client()->formStateDidChange(this);
+        page->chrome().client().formStateDidChange(this);
 }
 
 bool HTMLFormControlElementWithState::shouldSaveAndRestoreFormControlState() const
diff --git a/Source/core/html/HTMLFormElement.cpp b/Source/core/html/HTMLFormElement.cpp
index 1941b31..69fd3f3 100644
--- a/Source/core/html/HTMLFormElement.cpp
+++ b/Source/core/html/HTMLFormElement.cpp
@@ -32,11 +32,11 @@
 #include "core/dom/Attribute.h"
 #include "core/dom/AutocompleteErrorEvent.h"
 #include "core/dom/Document.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/NamedNodesCollection.h"
 #include "core/dom/NodeRenderingContext.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/html/FormController.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLImageElement.h"
@@ -657,36 +657,9 @@
     return hasInvalidControls;
 }
 
-Node* HTMLFormElement::elementForAlias(const AtomicString& alias)
-{
-    if (alias.isEmpty() || !m_elementAliases)
-        return 0;
-    return m_elementAliases->get(alias.impl());
-}
-
-void HTMLFormElement::addElementAlias(Node* element, const AtomicString& alias)
-{
-    if (alias.isEmpty())
-        return;
-    if (!m_elementAliases)
-        m_elementAliases = adoptPtr(new AliasMap);
-    m_elementAliases->set(alias.impl(), element);
-}
-
 void HTMLFormElement::getNamedElements(const AtomicString& name, Vector<RefPtr<Node> >& namedItems)
 {
     elements()->namedItems(name, namedItems);
-
-    Node* aliasElement = elementForAlias(name);
-    if (aliasElement) {
-        if (namedItems.find(aliasElement) == notFound) {
-            // We have seen it before but it is gone now. Still, we need to return it.
-            // FIXME: The above comment is not clear enough; it does not say why we need to do this.
-            namedItems.append(aliasElement);
-        }
-    }
-    if (namedItems.size() && namedItems.first() != aliasElement)
-        addElementAlias(namedItems.first().get(), name);
 }
 
 bool HTMLFormElement::shouldAutocomplete() const
diff --git a/Source/core/html/HTMLFormElement.h b/Source/core/html/HTMLFormElement.h
index a0bd172..2d84db7 100644
--- a/Source/core/html/HTMLFormElement.h
+++ b/Source/core/html/HTMLFormElement.h
@@ -116,9 +116,6 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocomplete);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocompleteerror);
 
-    Node* elementForAlias(const AtomicString&);
-    void addElementAlias(Node*, const AtomicString& alias);
-
     CheckedRadioButtons& checkedRadioButtons() { return m_checkedRadioButtons; }
 
     const Vector<FormAssociatedElement*>& associatedElements() const { return m_associatedElements; }
@@ -157,11 +154,7 @@
     // are any invalid controls in this form.
     bool checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >*, HTMLFormControlElement::CheckValidityDispatchEvents = HTMLFormControlElement::CheckValidityDispatchEventsAllowed);
 
-    typedef HashMap<AtomicString, RefPtr<Node> > AliasMap;
-
     FormSubmission::Attributes m_attributes;
-    OwnPtr<AliasMap> m_elementAliases;
-
     CheckedRadioButtons m_checkedRadioButtons;
 
     unsigned m_associatedElementsBeforeIndex;
diff --git a/Source/core/html/HTMLFrameElementBase.h b/Source/core/html/HTMLFrameElementBase.h
index e3d9fd6..f4eb3eb 100644
--- a/Source/core/html/HTMLFrameElementBase.h
+++ b/Source/core/html/HTMLFrameElementBase.h
@@ -79,6 +79,12 @@
     int m_marginHeight;
 };
 
+inline HTMLFrameElementBase* toHTMLFrameElementBase(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isElementNode() && toElement(node)->isFrameElementBase()));
+    return static_cast<HTMLFrameElementBase*>(node);
+}
+
 } // namespace WebCore
 
 #endif // HTMLFrameElementBase_h
diff --git a/Source/core/html/HTMLFrameOwnerElement.h b/Source/core/html/HTMLFrameOwnerElement.h
index bf8ef0c..aa5db05 100644
--- a/Source/core/html/HTMLFrameOwnerElement.h
+++ b/Source/core/html/HTMLFrameOwnerElement.h
@@ -22,6 +22,7 @@
 #define HTMLFrameOwnerElement_h
 
 #include "core/html/HTMLElement.h"
+#include "wtf/HashCountedSet.h"
 
 namespace WebCore {
 
@@ -76,7 +77,7 @@
     SandboxFlags m_sandboxFlags;
 };
 
-inline HTMLFrameOwnerElement* toFrameOwnerElement(Node* node)
+inline HTMLFrameOwnerElement* toHTMLFrameOwnerElement(Node* node)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isFrameOwnerElement());
     return static_cast<HTMLFrameOwnerElement*>(node);
@@ -105,9 +106,9 @@
     }
 
 private:
-    static HashSet<Node*>& disabledSubtreeRoots()
+    static HashCountedSet<Node*>& disabledSubtreeRoots()
     {
-        DEFINE_STATIC_LOCAL(HashSet<Node*>, nodes, ());
+        DEFINE_STATIC_LOCAL(HashCountedSet<Node*>, nodes, ());
         return nodes;
     }
 
diff --git a/Source/core/html/HTMLIFrameElement.cpp b/Source/core/html/HTMLIFrameElement.cpp
index 7e25c2a..1fac054 100644
--- a/Source/core/html/HTMLIFrameElement.cpp
+++ b/Source/core/html/HTMLIFrameElement.cpp
@@ -92,7 +92,7 @@
     } else if (name == seamlessAttr) {
         // If we're adding or removing the seamless attribute, we need to force the content document to recalculate its StyleResolver.
         if (contentDocument())
-            contentDocument()->styleResolverChanged(DeferRecalcStyle);
+            contentDocument()->styleResolverChanged(RecalcStyleDeferred);
     } else
         HTMLFrameElementBase::parseAttribute(name, value);
 }
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index 571462b..4b96259 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -28,9 +28,10 @@
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/EventNames.h"
+#include "core/fetch/ImageResource.h"
+#include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderImage.h"
 
 using namespace std;
@@ -179,6 +180,11 @@
 Node::InsertionNotificationRequest HTMLImageElement::insertedInto(ContainerNode* insertionPoint)
 {
     // m_form can be non-null if it was set in constructor.
+    if (m_form && insertionPoint->highestAncestor() != m_form->highestAncestor()) {
+        m_form->removeImgElement(this);
+        m_form = 0;
+    }
+
     if (!m_form) {
         m_form = findFormAncestor();
         if (m_form)
diff --git a/Source/core/html/HTMLImageLoader.cpp b/Source/core/html/HTMLImageLoader.cpp
index 6b966ac..f4954f7 100644
--- a/Source/core/html/HTMLImageLoader.cpp
+++ b/Source/core/html/HTMLImageLoader.cpp
@@ -26,10 +26,10 @@
 #include "core/dom/Element.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/ImageResource.h"
 
 namespace WebCore {
 
@@ -69,7 +69,7 @@
     bool loadError = cachedImage->errorOccurred() || cachedImage->response().httpStatusCode() >= 400;
 
     if (loadError && element->hasTagName(HTMLNames::objectTag))
-        static_cast<HTMLObjectElement*>(element.get())->renderFallbackContent();
+        toHTMLObjectElement(element.get())->renderFallbackContent();
 }
 
 }
diff --git a/Source/core/html/HTMLImportLoader.cpp b/Source/core/html/HTMLImportLoader.cpp
index ef2d766..7cfbd29 100644
--- a/Source/core/html/HTMLImportLoader.cpp
+++ b/Source/core/html/HTMLImportLoader.cpp
@@ -32,21 +32,19 @@
 #include "core/html/HTMLImportLoader.h"
 
 #include "core/dom/Document.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLImportLoaderClient.h"
 #include "core/loader/DocumentWriter.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/ContentSecurityPolicyResponseHeaders.h"
 
 namespace WebCore {
 
-HTMLImportLoader::HTMLImportLoader(HTMLImport* parent, const KURL& url, const ResourcePtr<RawResource>& resource)
+HTMLImportLoader::HTMLImportLoader(HTMLImport* parent, const KURL& url)
     : m_parent(parent)
     , m_state(StateLoading)
-    , m_resource(resource)
     , m_url(url)
 {
-    m_resource->addClient(this);
 }
 
 HTMLImportLoader::~HTMLImportLoader()
@@ -58,6 +56,12 @@
         m_resource->removeClient(this);
 }
 
+void HTMLImportLoader::setResource(const ResourcePtr<RawResource>& resource)
+{
+    m_resource = resource;
+    m_resource->addClient(this);
+}
+
 void HTMLImportLoader::responseReceived(Resource*, const ResourceResponse& response)
 {
     setState(startWritingAndParsing(response));
diff --git a/Source/core/html/HTMLImportLoader.h b/Source/core/html/HTMLImportLoader.h
index 4b9b399..5406049 100644
--- a/Source/core/html/HTMLImportLoader.h
+++ b/Source/core/html/HTMLImportLoader.h
@@ -31,9 +31,9 @@
 #ifndef HTMLImportLoader_h
 #define HTMLImportLoader_h
 
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/html/HTMLImport.h"
-#include "core/loader/cache/RawResource.h"
-#include "core/loader/cache/ResourcePtr.h"
 #include "weborigin/KURL.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
@@ -52,12 +52,13 @@
         StateReady
     };
 
-    HTMLImportLoader(HTMLImport*, const KURL&, const ResourcePtr<RawResource>&);
+    HTMLImportLoader(HTMLImport*, const KURL&);
     virtual ~HTMLImportLoader();
 
     Document* importedDocument() const;
     const KURL& url() const { return m_url; }
 
+    void setResource(const ResourcePtr<RawResource>&);
     void addClient(HTMLImportLoaderClient*);
     void removeClient(HTMLImportLoaderClient*);
     void importDestroyed();
diff --git a/Source/core/html/HTMLImportsController.cpp b/Source/core/html/HTMLImportsController.cpp
index cb2107a..9ebaa5c 100644
--- a/Source/core/html/HTMLImportsController.cpp
+++ b/Source/core/html/HTMLImportsController.cpp
@@ -32,9 +32,9 @@
 #include "core/html/HTMLImportsController.h"
 
 #include "core/dom/Document.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLImportLoader.h"
 #include "core/html/HTMLImportLoaderClient.h"
-#include "core/loader/cache/ResourceFetcher.h"
 
 namespace WebCore {
 
@@ -78,9 +78,14 @@
     if (!resource)
         return 0;
 
-    RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(parent, request.url(), resource));
+    RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(parent, request.url()));
     parent->appendChild(loader.get());
     m_imports.append(loader);
+
+    // We set resource after the import tree is built since
+    // Resource::addClient() immediately calls back to feed the bytes when the resource is cached.
+    loader->setResource(resource);
+
     return loader.release();
 }
 
diff --git a/Source/core/html/HTMLImportsController.h b/Source/core/html/HTMLImportsController.h
index b106d8a..0a06c4e 100644
--- a/Source/core/html/HTMLImportsController.h
+++ b/Source/core/html/HTMLImportsController.h
@@ -31,9 +31,9 @@
 #ifndef HTMLImportsController_h
 #define HTMLImportsController_h
 
+#include "core/fetch/RawResource.h"
 #include "core/html/HTMLImport.h"
 #include "core/html/LinkResource.h"
-#include "core/loader/cache/RawResource.h"
 #include "core/platform/Supplementable.h"
 #include "core/platform/Timer.h"
 #include "wtf/FastAllocBase.h"
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index 236c653..456f71c 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -183,33 +183,11 @@
     return m_inputType->innerBlockElement();
 }
 
-HTMLElement* HTMLInputElement::innerSpinButtonElement() const
-{
-    return m_inputType->innerSpinButtonElement();
-}
-
-#if ENABLE(INPUT_SPEECH)
-HTMLElement* HTMLInputElement::speechButtonElement() const
-{
-    return m_inputType->speechButtonElement();
-}
-#endif
-
 HTMLElement* HTMLInputElement::passwordGeneratorButtonElement() const
 {
     return m_inputType->passwordGeneratorButtonElement();
 }
 
-HTMLElement* HTMLInputElement::sliderThumbElement() const
-{
-    return m_inputType->sliderThumbElement();
-}
-
-HTMLElement* HTMLInputElement::sliderTrackElement() const
-{
-    return m_inputType->sliderTrackElement();
-}
-
 HTMLElement* HTMLInputElement::placeholderElement() const
 {
     return m_inputType->placeholderElement();
@@ -385,7 +363,7 @@
         return;
 
     if (Frame* frame = document()->frame())
-        frame->editor()->textFieldDidBeginEditing(this);
+        frame->editor()->textAreaOrTextFieldDidBeginEditing(this);
 }
 
 void HTMLInputElement::endEditing()
@@ -405,10 +383,12 @@
 void HTMLInputElement::handleFocusEvent(Element* oldFocusedElement, FocusDirection direction)
 {
     m_inputType->handleFocusEvent(oldFocusedElement, direction);
+    m_inputType->enableSecureTextInput();
 }
 
 void HTMLInputElement::handleBlurEvent()
 {
+    m_inputType->disableSecureTextInput();
     m_inputType->handleBlurEvent();
 }
 
@@ -722,6 +702,7 @@
         UseCounter::count(document(), UseCounter::IncrementalAttribute);
     } else if (name == minAttr) {
         m_inputType->minOrMaxAttributeChanged();
+        m_inputType->sanitizeValueInResponseToMinOrMaxAttributeChange();
         setNeedsValidityCheck();
         UseCounter::count(document(), UseCounter::MinAttribute);
     } else if (name == maxAttr) {
@@ -812,6 +793,7 @@
     HTMLTextFormControlElement::attach(context);
 
     m_inputType->attach();
+    m_inputType->countUsage();
 
     if (document()->focusedElement() == this)
         document()->updateFocusAppearanceSoon(true /* restore selection */);
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index faa6b8e..269c902 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -121,12 +121,6 @@
     HTMLElement* containerElement() const;
     virtual HTMLElement* innerTextElement() const;
     HTMLElement* innerBlockElement() const;
-    HTMLElement* innerSpinButtonElement() const;
-#if ENABLE(INPUT_SPEECH)
-    HTMLElement* speechButtonElement() const;
-#endif
-    HTMLElement* sliderThumbElement() const;
-    HTMLElement* sliderTrackElement() const;
     HTMLElement* passwordGeneratorButtonElement() const;
     virtual HTMLElement* placeholderElement() const;
 
diff --git a/Source/core/html/HTMLKeygenElement.cpp b/Source/core/html/HTMLKeygenElement.cpp
index 590e677..18e1494 100644
--- a/Source/core/html/HTMLKeygenElement.cpp
+++ b/Source/core/html/HTMLKeygenElement.cpp
@@ -62,11 +62,11 @@
     select->setPart(keygenSelectPseudoId);
     for (size_t i = 0; i < keys.size(); ++i) {
         RefPtr<HTMLOptionElement> option = HTMLOptionElement::create(document());
-        option->appendChild(Text::create(document(), keys[i]), ASSERT_NO_EXCEPTION);
-        select->appendChild(option, ASSERT_NO_EXCEPTION);
+        option->appendChild(Text::create(document(), keys[i]));
+        select->appendChild(option);
     }
 
-    root->appendChild(select, ASSERT_NO_EXCEPTION);
+    root->appendChild(select);
 }
 
 void HTMLKeygenElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/html/HTMLLabelElement.cpp b/Source/core/html/HTMLLabelElement.cpp
index 20e18c8..1de8acd 100644
--- a/Source/core/html/HTMLLabelElement.cpp
+++ b/Source/core/html/HTMLLabelElement.cpp
@@ -26,9 +26,9 @@
 #include "core/html/HTMLLabelElement.h"
 
 #include "HTMLNames.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/html/FormAssociatedElement.h"
 
 namespace WebCore {
diff --git a/Source/core/html/HTMLLegendElement.cpp b/Source/core/html/HTMLLegendElement.cpp
index 9589512..118238e 100644
--- a/Source/core/html/HTMLLegendElement.cpp
+++ b/Source/core/html/HTMLLegendElement.cpp
@@ -26,7 +26,7 @@
 #include "core/html/HTMLLegendElement.h"
 
 #include "HTMLNames.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLFieldSetElement.h"
 #include "core/html/HTMLFormControlElement.h"
 
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index cf9220a..e9dd421 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -37,12 +37,12 @@
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventSender.h"
+#include "core/fetch/CSSStyleSheetResource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/LinkImport.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/cache/CSSStyleSheetResource.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
@@ -507,6 +507,8 @@
     if (type == None)
         return;
     if (type == NonBlocking) {
+        // Tell StyleSheetCollections to re-compute styleSheets of this m_owner's treescope.
+        m_owner->document()->styleSheetCollection()->modifiedStyleSheetCandidateNode(m_owner);
         // Document::removePendingSheet() triggers the style selector recalc for blocking sheets.
         // FIXME: We don't have enough knowledge at this point to know if we're adding or removing a sheet
         // so we can't call addedStyleSheet() or removedStyleSheet().
@@ -514,7 +516,7 @@
         return;
     }
 
-    m_owner->document()->styleSheetCollection()->removePendingSheet(
+    m_owner->document()->styleSheetCollection()->removePendingSheet(m_owner,
         notification == RemovePendingSheetNotifyImmediately
         ? DocumentStyleSheetCollection::RemovePendingSheetNotifyImmediately
         : DocumentStyleSheetCollection::RemovePendingSheetNotifyLater);
@@ -557,7 +559,7 @@
                 process();
         } else {
             // FIXME: We don't have enough knowledge here to know if we should call addedStyleSheet() or removedStyleSheet().
-            m_owner->document()->styleResolverChanged(DeferRecalcStyle);
+            m_owner->document()->styleResolverChanged(RecalcStyleDeferred);
         }
     }
 }
diff --git a/Source/core/html/HTMLLinkElement.h b/Source/core/html/HTMLLinkElement.h
index 9d10b26..213a40d 100644
--- a/Source/core/html/HTMLLinkElement.h
+++ b/Source/core/html/HTMLLinkElement.h
@@ -26,14 +26,14 @@
 
 #include "core/css/CSSStyleSheet.h"
 #include "core/dom/IconURL.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResourceClient.h"
 #include "core/html/DOMSettableTokenList.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/LinkRelAttribute.h"
 #include "core/html/LinkResource.h"
 #include "core/loader/LinkLoader.h"
 #include "core/loader/LinkLoaderClient.h"
-#include "core/loader/cache/ResourcePtr.h"
-#include "core/loader/cache/StyleSheetResourceClient.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/HTMLMapElement.cpp b/Source/core/html/HTMLMapElement.cpp
index 2d5d65f..ee6b009 100644
--- a/Source/core/html/HTMLMapElement.cpp
+++ b/Source/core/html/HTMLMapElement.cpp
@@ -24,7 +24,7 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLAreaElement.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLImageElement.h"
diff --git a/Source/core/html/HTMLMarqueeElement.cpp b/Source/core/html/HTMLMarqueeElement.cpp
index aa7963d..e4c0347 100644
--- a/Source/core/html/HTMLMarqueeElement.cpp
+++ b/Source/core/html/HTMLMarqueeElement.cpp
@@ -104,7 +104,7 @@
             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitMarqueeStyle, value);
     } else if (name == directionAttr) {
         if (!value.isEmpty())
-            addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitMarqueeDirection, value);
+            addPropertyToPresentationAttributeStyle(style, CSSPropertyInternalMarqueeDirection, value);
     } else
         HTMLElement::collectStyleForPresentationAttribute(name, value, style);
 }
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index ba7d02b..381dbe7 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -2751,7 +2751,7 @@
     LOG(Media, "HTMLMediaElement::configureTextTrackGroup(%d)", group.kind);
 
     Page* page = document()->page();
-    Settings* settings = page ? page->settings() : 0;
+    Settings* settings = page ? &page->settings() : 0;
 
     // First, find the track in the group that should be enabled (if any).
     Vector<RefPtr<TextTrack> > currentlyEnabledTracks;
@@ -3177,6 +3177,16 @@
         playInternal();
 }
 
+void HTMLMediaElement::mediaPlayerRequestSeek(double time)
+{
+    // The player is the source of this seek request.
+    if (m_mediaController) {
+        m_mediaController->setCurrentTime(time, IGNORE_EXCEPTION);
+        return;
+    }
+    setCurrentTime(time, IGNORE_EXCEPTION);
+}
+
 // MediaPlayerPresentation methods
 void HTMLMediaElement::mediaPlayerRepaint()
 {
@@ -3688,7 +3698,7 @@
     if (isFullscreen())
         mediaControls->enteredFullscreen();
 
-    ensureUserAgentShadowRoot()->appendChild(mediaControls, ASSERT_NO_EXCEPTION);
+    ensureUserAgentShadowRoot()->appendChild(mediaControls);
 
     if (!controls() || !inDocument())
         mediaControls->hide();
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index bbc957d..6d562ce 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -362,6 +362,7 @@
     virtual void mediaPlayerTimeChanged() OVERRIDE;
     virtual void mediaPlayerDurationChanged() OVERRIDE;
     virtual void mediaPlayerPlaybackStateChanged() OVERRIDE;
+    virtual void mediaPlayerRequestSeek(double) OVERRIDE;
     virtual void mediaPlayerRepaint() OVERRIDE;
     virtual void mediaPlayerSizeChanged() OVERRIDE;
     virtual void mediaPlayerEngineUpdated() OVERRIDE;
@@ -600,14 +601,14 @@
 };
 #endif
 
-inline bool isMediaElement(Node* node)
+inline bool isHTMLMediaElement(Node* node)
 {
     return node && node->isElementNode() && toElement(node)->isMediaElement();
 }
 
-inline HTMLMediaElement* toMediaElement(Node* node)
+inline HTMLMediaElement* toHTMLMediaElement(Node* node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isMediaElement(node));
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLMediaElement(node));
     return static_cast<HTMLMediaElement*>(node);
 }
 
diff --git a/Source/core/html/HTMLMeterElement.cpp b/Source/core/html/HTMLMeterElement.cpp
index 2359e87..41b987e 100644
--- a/Source/core/html/HTMLMeterElement.cpp
+++ b/Source/core/html/HTMLMeterElement.cpp
@@ -233,9 +233,9 @@
     m_value = MeterValueElement::create(document());
     m_value->setWidthPercentage(0);
     m_value->updatePseudo();
-    bar->appendChild(m_value, ASSERT_NO_EXCEPTION);
+    bar->appendChild(m_value);
 
-    inner->appendChild(bar, ASSERT_NO_EXCEPTION);
+    inner->appendChild(bar);
 }
 
 } // namespace
diff --git a/Source/core/html/HTMLNameCollection.cpp b/Source/core/html/HTMLNameCollection.cpp
index 6e637b2..57a181d 100644
--- a/Source/core/html/HTMLNameCollection.cpp
+++ b/Source/core/html/HTMLNameCollection.cpp
@@ -25,8 +25,8 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeRareData.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLObjectElement.h"
 
 namespace WebCore {
@@ -87,7 +87,7 @@
                     return current;
             } else if (current->hasTagName(objectTag)) {
                 if ((current->getNameAttribute() == m_name || current->getIdAttribute() == m_name)
-                    && static_cast<HTMLObjectElement*>(current)->isDocNamedItem())
+                    && toHTMLObjectElement(current)->isDocNamedItem())
                     return current;
             } else if (current->hasTagName(imgTag)) {
                 if (current->getNameAttribute() == m_name || (current->getIdAttribute() == m_name && current->hasName()))
diff --git a/Source/core/html/HTMLObjectElement.cpp b/Source/core/html/HTMLObjectElement.cpp
index 0dd38fd..732937a 100644
--- a/Source/core/html/HTMLObjectElement.cpp
+++ b/Source/core/html/HTMLObjectElement.cpp
@@ -27,17 +27,17 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/dom/Attribute.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/NodeList.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/html/HTMLMetaElement.h"
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
@@ -232,7 +232,7 @@
     // fallback content, which ensures the quirk will disable itself if Wiki
     // Server is updated to generate an alternate embed tag as fallback content.
     if (!document()->page()
-        || !document()->page()->settings()->needsSiteSpecificQuirks()
+        || !document()->page()->settings().needsSiteSpecificQuirks()
         || hasFallbackContent()
         || !equalIgnoringCase(classId(), "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"))
         return false;
@@ -356,6 +356,17 @@
     return getAttribute(dataAttr);
 }
 
+// FIXME: Remove this hack.
+void HTMLObjectElement::reattachFallbackContent()
+{
+    // This can happen inside of attach() in the middle of a recalcStyle so we need to
+    // reattach synchronously here.
+    if (document()->inStyleRecalc())
+        reattach();
+    else
+        lazyReattach();
+}
+
 void HTMLObjectElement::renderFallbackContent()
 {
     if (useFallbackContent())
@@ -370,7 +381,7 @@
         if (!isImageType()) {
             // If we don't think we have an image type anymore, then clear the image from the loader.
             m_imageLoader->setImage(0);
-            lazyReattach();
+            reattachFallbackContent();
             return;
         }
     }
@@ -378,7 +389,7 @@
     m_useFallbackContent = true;
 
     // FIXME: Style gets recalculated which is suboptimal.
-    lazyReattach();
+    reattachFallbackContent();
 }
 
 // FIXME: This should be removed, all callers are almost certainly wrong.
@@ -450,8 +461,7 @@
                 && equalIgnoringCase(child->getNameAttribute(), "type")
                 && MIMETypeRegistry::isJavaAppletMIMEType(child->getAttribute(valueAttr).string()))
             return true;
-        if (child->hasTagName(objectTag)
-                && static_cast<HTMLObjectElement*>(child)->containsJavaApplet())
+        if (child->hasTagName(objectTag) && toHTMLObjectElement(child)->containsJavaApplet())
             return true;
         if (child->hasTagName(appletTag))
             return true;
diff --git a/Source/core/html/HTMLObjectElement.h b/Source/core/html/HTMLObjectElement.h
index 5b8d1d2..9248969 100644
--- a/Source/core/html/HTMLObjectElement.h
+++ b/Source/core/html/HTMLObjectElement.h
@@ -88,6 +88,8 @@
     virtual void updateWidget(PluginCreationOption);
     void updateDocNamedItem();
 
+    void reattachFallbackContent();
+
     bool hasFallbackContent() const;
 
     // FIXME: This function should not deal with url or serviceType
@@ -109,6 +111,12 @@
     bool m_useFallbackContent : 1;
 };
 
+inline HTMLObjectElement* toHTMLObjectElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::objectTag));
+    return static_cast<HTMLObjectElement*>(node);
+}
+
 }
 
 #endif
diff --git a/Source/core/html/HTMLOptionElement.cpp b/Source/core/html/HTMLOptionElement.cpp
index ba69902..6a94760 100644
--- a/Source/core/html/HTMLOptionElement.cpp
+++ b/Source/core/html/HTMLOptionElement.cpp
@@ -145,7 +145,7 @@
         toText(child)->setData(text);
     else {
         removeChildren();
-        appendChild(Text::create(document(), text), es, AttachLazily);
+        appendChild(Text::create(document(), text), es);
     }
 
     if (selectIsMenuList && select->selectedIndex() != oldSelectedIndex)
diff --git a/Source/core/html/HTMLPlugInElement.cpp b/Source/core/html/HTMLPlugInElement.cpp
index 2f1c8b7..14ba749 100644
--- a/Source/core/html/HTMLPlugInElement.cpp
+++ b/Source/core/html/HTMLPlugInElement.cpp
@@ -79,13 +79,6 @@
     return true;
 }
 
-void HTMLPlugInElement::removeAllEventListeners()
-{
-    HTMLFrameOwnerElement::removeAllEventListeners();
-    if (Widget* widget = pluginWidget())
-        widget->eventListenersRemoved();
-}
-
 void HTMLPlugInElement::detach(const AttachContext& context)
 {
     m_instance.clear();
diff --git a/Source/core/html/HTMLPlugInElement.h b/Source/core/html/HTMLPlugInElement.h
index 9584710..f6a4563 100644
--- a/Source/core/html/HTMLPlugInElement.h
+++ b/Source/core/html/HTMLPlugInElement.h
@@ -66,8 +66,6 @@
 
     virtual bool isPlugInImageElement() const { return false; }
 
-    virtual void removeAllEventListeners() OVERRIDE;
-
 protected:
     HTMLPlugInElement(const QualifiedName& tagName, Document*);
 
diff --git a/Source/core/html/HTMLProgressElement.cpp b/Source/core/html/HTMLProgressElement.cpp
index 6c57809..ccf931f 100644
--- a/Source/core/html/HTMLProgressElement.cpp
+++ b/Source/core/html/HTMLProgressElement.cpp
@@ -157,9 +157,9 @@
     RefPtr<ProgressValueElement> value = ProgressValueElement::create(document());
     m_value = value.get();
     m_value->setWidthPercentage(HTMLProgressElement::IndeterminatePosition * 100);
-    bar->appendChild(m_value, ASSERT_NO_EXCEPTION);
+    bar->appendChild(m_value);
 
-    inner->appendChild(bar, ASSERT_NO_EXCEPTION);
+    inner->appendChild(bar);
 }
 
 bool HTMLProgressElement::shouldAppearIndeterminate() const
diff --git a/Source/core/html/HTMLScriptElement.cpp b/Source/core/html/HTMLScriptElement.cpp
index a5faf75..a51ccae 100644
--- a/Source/core/html/HTMLScriptElement.cpp
+++ b/Source/core/html/HTMLScriptElement.cpp
@@ -84,16 +84,12 @@
 {
     RefPtr<Node> protectFromMutationEvents(this);
 
-    int numChildren = childNodeCount();
-
-    if (numChildren == 1 && firstChild()->isTextNode()) {
+    if (hasOneTextChild()) {
         toText(firstChild())->setData(value);
         return;
     }
 
-    if (numChildren > 0)
-        removeChildren();
-
+    removeChildren();
     appendChild(document()->createTextNode(value.impl()), IGNORE_EXCEPTION);
 }
 
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index f625e4d..ad9eeb5 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -33,6 +33,7 @@
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/Attribute.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/KeyboardEvent.h"
 #include "core/dom/MouseEvent.h"
@@ -219,7 +220,7 @@
     if (!element || !(element->hasLocalName(optionTag) || element->hasLocalName(hrTag)))
         return;
 
-    insertBefore(element, before, es, AttachLazily);
+    insertBefore(element, before, es);
     setNeedsValidityCheck();
 }
 
diff --git a/Source/core/html/HTMLSourceElement.cpp b/Source/core/html/HTMLSourceElement.cpp
index f3e1024..b47dcb6 100644
--- a/Source/core/html/HTMLSourceElement.cpp
+++ b/Source/core/html/HTMLSourceElement.cpp
@@ -57,7 +57,7 @@
     HTMLElement::insertedInto(insertionPoint);
     Element* parent = parentElement();
     if (parent && parent->isMediaElement())
-        static_cast<HTMLMediaElement*>(parentNode())->sourceWasAdded(this);
+        toHTMLMediaElement(parentNode())->sourceWasAdded(this);
     return InsertionDone;
 }
 
@@ -67,7 +67,7 @@
     if (!parent && removalRoot->isElementNode())
         parent = toElement(removalRoot);
     if (parent && parent->isMediaElement())
-        toMediaElement(parent)->sourceWasRemoved(this);
+        toHTMLMediaElement(parent)->sourceWasRemoved(this);
     HTMLElement::removedFrom(removalRoot);
 }
 
diff --git a/Source/core/html/HTMLStyleElement.cpp b/Source/core/html/HTMLStyleElement.cpp
index 2d981d6..c62aa58 100644
--- a/Source/core/html/HTMLStyleElement.cpp
+++ b/Source/core/html/HTMLStyleElement.cpp
@@ -77,7 +77,7 @@
         scopedAttributeChanged(!value.isNull());
     } else if (name == mediaAttr && inDocument() && document()->renderer() && m_sheet) {
         m_sheet->setMediaQueries(MediaQuerySet::create(value));
-        // FIXME: This shold be DeferRecalcStyle.
+        // FIXME: This shold be RecalcStyleDeferred.
         document()->modifiedStyleSheet(m_sheet.get(), RecalcStyleImmediately);
     } else {
         HTMLElement::parseAttribute(name, value);
diff --git a/Source/core/html/HTMLSummaryElement.cpp b/Source/core/html/HTMLSummaryElement.cpp
index 4a1aeb1..635dd55 100644
--- a/Source/core/html/HTMLSummaryElement.cpp
+++ b/Source/core/html/HTMLSummaryElement.cpp
@@ -55,8 +55,8 @@
 
 void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot* root)
 {
-    root->appendChild(DetailsMarkerControl::create(document()), ASSERT_NO_EXCEPTION, AttachLazily);
-    root->appendChild(HTMLContentElement::create(document()), ASSERT_NO_EXCEPTION, AttachLazily);
+    root->appendChild(DetailsMarkerControl::create(document()));
+    root->appendChild(HTMLContentElement::create(document()));
 }
 
 HTMLDetailsElement* HTMLSummaryElement::detailsElement() const
diff --git a/Source/core/html/HTMLTableElement.cpp b/Source/core/html/HTMLTableElement.cpp
index 70b4a97..81620b3 100644
--- a/Source/core/html/HTMLTableElement.cpp
+++ b/Source/core/html/HTMLTableElement.cpp
@@ -158,7 +158,7 @@
     RefPtr<HTMLTableSectionElement> body = HTMLTableSectionElement::create(tbodyTag, document());
     Node* referenceElement = lastBody() ? lastBody()->nextSibling() : 0;
 
-    insertBefore(body, referenceElement, ASSERT_NO_EXCEPTION);
+    insertBefore(body, referenceElement);
     return body.release();
 }
 
@@ -221,13 +221,13 @@
             RefPtr<HTMLTableSectionElement> newBody = HTMLTableSectionElement::create(tbodyTag, document());
             RefPtr<HTMLTableRowElement> newRow = HTMLTableRowElement::create(document());
             newBody->appendChild(newRow, es);
-            appendChild(newBody.release(), es, AttachLazily);
+            appendChild(newBody.release(), es);
             return newRow.release();
         }
     }
 
     RefPtr<HTMLTableRowElement> newRow = HTMLTableRowElement::create(document());
-    parent->insertBefore(newRow, row.get(), es, AttachLazily);
+    parent->insertBefore(newRow, row.get(), es);
     return newRow.release();
 }
 
diff --git a/Source/core/html/HTMLTableRowElement.cpp b/Source/core/html/HTMLTableRowElement.cpp
index 09e364f..cb18a6e 100644
--- a/Source/core/html/HTMLTableRowElement.cpp
+++ b/Source/core/html/HTMLTableRowElement.cpp
@@ -129,14 +129,14 @@
 
     RefPtr<HTMLTableCellElement> cell = HTMLTableCellElement::create(tdTag, document());
     if (index < 0 || index >= numCells)
-        appendChild(cell, es, AttachLazily);
+        appendChild(cell, es);
     else {
         Node* n;
         if (index < 1)
             n = firstChild();
         else
             n = children->item(index);
-        insertBefore(cell, n, es, AttachLazily);
+        insertBefore(cell, n, es);
     }
     return cell.release();
 }
diff --git a/Source/core/html/HTMLTableSectionElement.cpp b/Source/core/html/HTMLTableSectionElement.cpp
index 29f7a20..4a1d90e 100644
--- a/Source/core/html/HTMLTableSectionElement.cpp
+++ b/Source/core/html/HTMLTableSectionElement.cpp
@@ -66,14 +66,14 @@
     else {
         row = HTMLTableRowElement::create(trTag, document());
         if (numRows == index || index == -1)
-            appendChild(row, es, AttachLazily);
+            appendChild(row, es);
         else {
             Node* n;
             if (index < 1)
                 n = firstChild();
             else
                 n = children->item(index);
-            insertBefore(row, n, es, AttachLazily);
+            insertBefore(row, n, es);
         }
     }
     return row.release();
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index 03dd058..c02e8fb 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -37,6 +37,7 @@
 #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/TextIterator.h"
 #include "core/html/FormController.h"
@@ -101,7 +102,7 @@
 
 void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot* root)
 {
-    root->appendChild(TextControlInnerTextElement::create(document()), ASSERT_NO_EXCEPTION);
+    root->appendChild(TextControlInnerTextElement::create(document()));
 }
 
 const AtomicString& HTMLTextAreaElement::formControlType() const
@@ -266,6 +267,12 @@
     HTMLTextFormControlElement::defaultEventHandler(event);
 }
 
+void HTMLTextAreaElement::handleFocusEvent(Element*, FocusDirection)
+{
+    if (Frame* frame = document()->frame())
+        frame->editor()->textAreaOrTextFieldDidBeginEditing(this);
+}
+
 void HTMLTextAreaElement::subtreeHasChanged()
 {
     setChangedSinceLastFormControlChangeEvent(true);
@@ -542,7 +549,7 @@
         RefPtr<HTMLDivElement> placeholder = HTMLDivElement::create(document());
         m_placeholder = placeholder.get();
         m_placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
-        userAgentShadowRoot()->insertBefore(m_placeholder, innerTextElement()->nextSibling(), ASSERT_NO_EXCEPTION);
+        userAgentShadowRoot()->insertBefore(m_placeholder, innerTextElement()->nextSibling(), ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
     }
     m_placeholder->setInnerText(placeholderText, ASSERT_NO_EXCEPTION);
     fixPlaceholderRenderer(m_placeholder, innerTextElement());
diff --git a/Source/core/html/HTMLTextAreaElement.h b/Source/core/html/HTMLTextAreaElement.h
index 2331bc1..9efd5bc 100644
--- a/Source/core/html/HTMLTextAreaElement.h
+++ b/Source/core/html/HTMLTextAreaElement.h
@@ -83,6 +83,7 @@
     virtual bool isRequiredFormControl() const { return isRequired(); }
 
     virtual void defaultEventHandler(Event*);
+    virtual void handleFocusEvent(Element* oldFocusedNode, FocusDirection) OVERRIDE;
 
     virtual void subtreeHasChanged();
 
diff --git a/Source/core/html/HTMLTextFormControlElement.cpp b/Source/core/html/HTMLTextFormControlElement.cpp
index 3a86925..0ce84dd 100644
--- a/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/Source/core/html/HTMLTextFormControlElement.cpp
@@ -40,8 +40,7 @@
 #include "core/html/HTMLBRElement.h"
 #include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
-#include "core/rendering/RenderBox.h"
-#include "core/rendering/RenderTextControl.h"
+#include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderTheme.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -211,10 +210,10 @@
     setChangedSinceLastFormControlChangeEvent(false);
 }
 
-static inline bool hasVisibleTextArea(RenderTextControl* textControl, HTMLElement* innerText)
+static inline bool hasVisibleTextArea(RenderObject* renderer, HTMLElement* innerText)
 {
-    ASSERT(textControl);
-    return textControl->style()->visibility() != HIDDEN && innerText && innerText->renderer() && innerText->renderBox()->height();
+    ASSERT(renderer);
+    return renderer->style()->visibility() != HIDDEN && innerText && innerText->renderer() && innerText->renderBox()->height();
 }
 
 
@@ -298,7 +297,7 @@
     end = max(end, 0);
     start = min(max(start, 0), end);
 
-    if (!hasVisibleTextArea(toRenderTextControl(renderer()), innerTextElement())) {
+    if (!hasVisibleTextArea(renderer(), innerTextElement())) {
         cacheSelection(start, end, direction);
         return;
     }
@@ -528,7 +527,7 @@
         innerTextElement()->setInnerText(value, ASSERT_NO_EXCEPTION);
 
         if (value.endsWith('\n') || value.endsWith('\r'))
-            innerTextElement()->appendChild(HTMLBRElement::create(document()), ASSERT_NO_EXCEPTION, AttachLazily);
+            innerTextElement()->appendChild(HTMLBRElement::create(document()));
     }
 
     setFormControlValueMatchesRenderer(true);
diff --git a/Source/core/html/HTMLTrackElement.cpp b/Source/core/html/HTMLTrackElement.cpp
index bd7f1c4..ae7d048 100644
--- a/Source/core/html/HTMLTrackElement.cpp
+++ b/Source/core/html/HTMLTrackElement.cpp
@@ -87,8 +87,8 @@
 
 void HTMLTrackElement::removedFrom(ContainerNode* insertionPoint)
 {
-    if (!parentNode() && WebCore::isMediaElement(insertionPoint))
-        toMediaElement(insertionPoint)->didRemoveTrack(this);
+    if (!parentNode() && isHTMLMediaElement(insertionPoint))
+        toHTMLMediaElement(insertionPoint)->didRemoveTrack(this);
     HTMLElement::removedFrom(insertionPoint);
 }
 
@@ -358,8 +358,7 @@
 {
     Element* parent = parentElement();
     if (parent && parent->isMediaElement())
-        return static_cast<HTMLMediaElement*>(parentNode());
-
+        return toHTMLMediaElement(parentNode());
     return 0;
 }
 
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 64a0dc1..57a97d0 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -31,6 +31,7 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/MouseEvent.h"
 #include "core/dom/RawDataDocumentParser.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLBodyElement.h"
 #include "core/html/HTMLHeadElement.h"
 #include "core/html/HTMLHtmlElement.h"
@@ -39,7 +40,6 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
@@ -167,7 +167,7 @@
 void ImageDocument::createDocumentStructure()
 {
     RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(this);
-    appendChild(rootElement, ASSERT_NO_EXCEPTION, AttachLazily);
+    appendChild(rootElement);
     rootElement->insertedByParser();
 
     if (frame() && frame()->loader())
@@ -177,7 +177,7 @@
     RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(this);
     meta->setAttribute(nameAttr, "viewport");
     meta->setAttribute(contentAttr, "width=device-width");
-    head->appendChild(meta, ASSERT_NO_EXCEPTION, AttachLazily);
+    head->appendChild(meta);
 
     RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(this);
     body->setAttribute(styleAttr, "margin: 0px;");
@@ -186,7 +186,7 @@
     m_imageElement->setAttribute(styleAttr, "-webkit-user-select: none");
     m_imageElement->setLoadManually(true);
     m_imageElement->setSrc(url().string());
-    body->appendChild(m_imageElement.get(), ASSERT_NO_EXCEPTION, AttachLazily);
+    body->appendChild(m_imageElement.get());
 
     if (shouldShrinkToFit()) {
         // Add event listeners
@@ -196,8 +196,8 @@
         m_imageElement->addEventListener("click", listener.release(), false);
     }
 
-    rootElement->appendChild(head, ASSERT_NO_EXCEPTION, AttachLazily);
-    rootElement->appendChild(body, ASSERT_NO_EXCEPTION, AttachLazily);
+    rootElement->appendChild(head);
+    rootElement->appendChild(body);
 }
 
 float ImageDocument::scale() const
@@ -220,7 +220,7 @@
 
 void ImageDocument::resizeImageToFit()
 {
-    if (!m_imageElement || m_imageElement->document() != this)
+    if (!m_imageElement || m_imageElement->document() != this || pageZoomFactor(this) > 1)
         return;
 
     LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this));
@@ -275,7 +275,7 @@
 
 void ImageDocument::restoreImageSize()
 {
-    if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this)
+    if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this || pageZoomFactor(this) < 1)
         return;
 
     LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), 1.0f);
@@ -348,8 +348,7 @@
 
 bool ImageDocument::shouldShrinkToFit() const
 {
-    return frame()->page()->settings()->shrinksStandaloneImagesToFit() &&
-        frame()->page()->mainFrame() == frame();
+    return frame()->page()->settings().shrinksStandaloneImagesToFit() && frame()->page()->mainFrame() == frame();
 }
 
 void ImageDocument::dispose()
diff --git a/Source/core/html/ImageInputType.cpp b/Source/core/html/ImageInputType.cpp
index 2ad3d90..85b049e 100644
--- a/Source/core/html/ImageInputType.cpp
+++ b/Source/core/html/ImageInputType.cpp
@@ -25,13 +25,13 @@
 
 #include "HTMLNames.h"
 #include "core/dom/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/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderImage.h"
 #include "wtf/PassOwnPtr.h"
 
diff --git a/Source/core/html/InputType.cpp b/Source/core/html/InputType.cpp
index 940982f..95c44e3 100644
--- a/Source/core/html/InputType.cpp
+++ b/Source/core/html/InputType.cpp
@@ -28,8 +28,8 @@
 #include "config.h"
 #include "core/html/InputType.h"
 
-#include <limits>
 #include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
@@ -69,7 +69,6 @@
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 #include "core/page/Page.h"
-#include "RuntimeEnabledFeatures.h"
 #include "core/platform/DateComponents.h"
 #include "core/platform/LocalizedStrings.h"
 #include "core/platform/text/TextBreakIterator.h"
@@ -78,6 +77,7 @@
 #include "wtf/Assertions.h"
 #include "wtf/HashMap.h"
 #include "wtf/text/StringHash.h"
+#include <limits>
 
 namespace WebCore {
 
@@ -120,7 +120,7 @@
 PassOwnPtr<InputType> InputType::create(HTMLInputElement* element, const AtomicString& typeName)
 {
     static const InputTypeFactoryMap* factoryMap = createInputTypeFactoryMap().leakPtr();
-    PassOwnPtr<InputType> (*factory)(HTMLInputElement*) = typeName.isEmpty() ? 0 : factoryMap->get(typeName);
+    InputTypeFactoryFunction factory = typeName.isEmpty() ? 0 : factoryMap->get(typeName);
     if (!factory)
         factory = TextInputType::create;
     return factory(element);
@@ -468,6 +468,7 @@
     // It's ok to clear contents of all other ShadowRoots because they must have
     // been created by InputFieldPasswordGeneratorButtonElement, and we don't allow adding
     // AuthorShadowRoot to HTMLInputElement.
+    // FIXME: Remove the PasswordGeneratorButtonElement's shadow root and then remove this loop.
     while ((root = root->youngerShadowRoot())) {
         root->removeChildren();
         root->appendChild(HTMLShadowElement::create(shadowTag, element()->document()));
@@ -544,6 +545,14 @@
 {
 }
 
+void InputType::enableSecureTextInput()
+{
+}
+
+void InputType::disableSecureTextInput()
+{
+}
+
 void InputType::accessKeyAction(bool)
 {
     element()->focus(false);
@@ -557,6 +566,10 @@
 {
 }
 
+void InputType::countUsage()
+{
+}
+
 void InputType::altAttributeChanged()
 {
 }
@@ -579,6 +592,10 @@
 {
 }
 
+void InputType::sanitizeValueInResponseToMinOrMaxAttributeChange()
+{
+}
+
 void InputType::stepAttributeChanged()
 {
 }
@@ -1043,7 +1060,7 @@
     // FIXME: Not any changes after stepping, even if it is an invalid value, may be better.
     // (e.g. Stepping-up for <input type="number" value="foo" step="any" /> => "foo")
     if (!stepRange.hasStep())
-      return;
+        return;
 
     EventQueueScope scope;
     const Decimal step = stepRange.step();
@@ -1067,9 +1084,9 @@
             current = stepRange.maximum() - nextDiff;
         setValueAsDecimal(current, DispatchNoEvent, IGNORE_EXCEPTION);
     }
-    if ((sign > 0 && current < stepRange.minimum()) || (sign < 0 && current > stepRange.maximum()))
+    if ((sign > 0 && current < stepRange.minimum()) || (sign < 0 && current > stepRange.maximum())) {
         setValueAsDecimal(sign > 0 ? stepRange.minimum() : stepRange.maximum(), DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
-    else {
+    } else {
         if (stepMismatch(element()->value())) {
             ASSERT(!step.isZero());
             const Decimal base = stepRange.stepBase();
diff --git a/Source/core/html/InputType.h b/Source/core/html/InputType.h
index ab9d248..c8197f1 100644
--- a/Source/core/html/InputType.h
+++ b/Source/core/html/InputType.h
@@ -195,6 +195,8 @@
     virtual bool isKeyboardFocusable() const;
     virtual bool shouldShowFocusRingOnMouseFocus() const;
     virtual bool shouldUseInputMethod() const;
+    virtual void enableSecureTextInput();
+    virtual void disableSecureTextInput();
     virtual void handleFocusEvent(Element* oldFocusedElement, FocusDirection);
     virtual void handleBlurEvent();
     virtual void accessKeyAction(bool sendMouseEvents);
@@ -212,13 +214,7 @@
     virtual HTMLElement* containerElement() const { return 0; }
     virtual HTMLElement* innerBlockElement() const { return 0; }
     virtual HTMLElement* innerTextElement() const { return 0; }
-    virtual HTMLElement* innerSpinButtonElement() const { return 0; }
-#if ENABLE(INPUT_SPEECH)
-    virtual HTMLElement* speechButtonElement() const { return 0; }
-#endif
     virtual HTMLElement* passwordGeneratorButtonElement() const { return 0; }
-    virtual HTMLElement* sliderThumbElement() const { return 0; }
-    virtual HTMLElement* sliderTrackElement() const { return 0; }
     virtual HTMLElement* placeholderElement() const;
 
     // Miscellaneous functions
@@ -228,7 +224,9 @@
     virtual PassRefPtr<RenderStyle> customStyleForRenderer(PassRefPtr<RenderStyle>);
     virtual void attach();
     virtual void detach();
+    virtual void countUsage();
     virtual void minOrMaxAttributeChanged();
+    virtual void sanitizeValueInResponseToMinOrMaxAttributeChange();
     virtual void stepAttributeChanged();
     virtual void altAttributeChanged();
     virtual void srcAttributeChanged();
diff --git a/Source/core/html/InputTypeUI.cpp b/Source/core/html/InputTypeUI.cpp
new file mode 100644
index 0000000..dcdc106
--- /dev/null
+++ b/Source/core/html/InputTypeUI.cpp
@@ -0,0 +1,1125 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ *           (C) 2006 Alexey Proskuryakov (ap@nypop.com)
+ * Copyright (C) 2007 Samuel Weinig (sam@webkit.org)
+ * Copyright (C) 2009, 2010, 2011, 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Samsung Electronics. 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/InputTypeUI.h"
+
+#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/accessibility/AXObjectCache.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/dom/KeyboardEvent.h"
+#include "core/dom/NodeRenderStyle.h"
+#include "core/dom/ScopedEventQueue.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/fileapi/FileList.h"
+#include "core/html/ButtonInputType.h"
+#include "core/html/CheckboxInputType.h"
+#include "core/html/ColorInputType.h"
+#include "core/html/DateInputType.h"
+#include "core/html/DateTimeLocalInputType.h"
+#include "core/html/EmailInputType.h"
+#include "core/html/FileInputType.h"
+#include "core/html/FormController.h"
+#include "core/html/FormDataList.h"
+#include "core/html/HTMLFormElement.h"
+#include "core/html/HTMLInputElement.h"
+#include "core/html/HiddenInputType.h"
+#include "core/html/ImageInputType.h"
+#include "core/html/InputTypeNames.h"
+#include "core/html/MonthInputType.h"
+#include "core/html/NumberInputType.h"
+#include "core/html/PasswordInputType.h"
+#include "core/html/RadioInputType.h"
+#include "core/html/RangeInputType.h"
+#include "core/html/ResetInputType.h"
+#include "core/html/SearchInputType.h"
+#include "core/html/SubmitInputType.h"
+#include "core/html/TelephoneInputType.h"
+#include "core/html/TextInputType.h"
+#include "core/html/TimeInputType.h"
+#include "core/html/URLInputType.h"
+#include "core/html/WeekInputType.h"
+#include "core/html/parser/HTMLParserIdioms.h"
+#include "core/html/shadow/HTMLShadowElement.h"
+#include "core/page/Page.h"
+#include "core/platform/DateComponents.h"
+#include "core/platform/LocalizedStrings.h"
+#include "core/platform/text/TextBreakIterator.h"
+#include "core/rendering/RenderObject.h"
+#include "core/rendering/RenderTheme.h"
+#include "wtf/Assertions.h"
+#include "wtf/HashMap.h"
+#include "wtf/text/StringHash.h"
+#include <limits>
+
+namespace WebCore {
+
+using namespace HTMLNames;
+using namespace std;
+
+typedef PassOwnPtr<InputType> (*InputTypeFactoryFunction)(HTMLInputElement*);
+typedef HashMap<AtomicString, InputTypeFactoryFunction, CaseFoldingHash> InputTypeFactoryMap;
+
+static PassOwnPtr<InputTypeFactoryMap> createInputTypeFactoryMap()
+{
+    OwnPtr<InputTypeFactoryMap> map = adoptPtr(new InputTypeFactoryMap);
+    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);
+    if (RuntimeEnabledFeatures::inputTypeWeekEnabled())
+        map->add(InputTypeNames::week(), WeekInputType::create);
+    // No need to register "text" because it is the default type.
+    return map.release();
+}
+
+PassOwnPtr<InputType> InputType::create(HTMLInputElement* element, const AtomicString& typeName)
+{
+    static const InputTypeFactoryMap* factoryMap = createInputTypeFactoryMap().leakPtr();
+    InputTypeFactoryFunction factory = typeName.isEmpty() ? 0 : factoryMap->get(typeName);
+    if (!factory)
+        factory = TextInputType::create;
+    return factory(element);
+}
+
+PassOwnPtr<InputType> InputType::createText(HTMLInputElement* element)
+{
+    return TextInputType::create(element);
+}
+
+InputTypeUI::~InputTypeUI()
+{
+}
+
+bool InputTypeUI::themeSupportsDataListUI(InputType* type)
+{
+    Document* document = type->element()->document();
+    RefPtr<RenderTheme> theme = document->page() ? document->page()->theme() : RenderTheme::defaultTheme();
+    return theme->supportsDataListUI(type->formControlType());
+}
+
+bool InputTypeUI::isTextField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isTextType() const
+{
+    return false;
+}
+
+bool InputTypeUI::isRangeControl() const
+{
+    return false;
+}
+
+bool InputTypeUI::shouldSaveAndRestoreFormControlState() const
+{
+    return true;
+}
+
+FormControlState InputTypeUI::saveFormControlState() const
+{
+    String currentValue = element()->value();
+    if (currentValue == element()->defaultValue())
+        return FormControlState();
+    return FormControlState(currentValue);
+}
+
+void InputTypeUI::restoreFormControlState(const FormControlState& state)
+{
+    element()->setValue(state[0]);
+}
+
+bool InputTypeUI::isFormDataAppendable() const
+{
+    // There is no form data unless there's a name for non-image types.
+    return !element()->name().isEmpty();
+}
+
+bool InputTypeUI::appendFormData(FormDataList& encoding, bool) const
+{
+    // Always successful.
+    encoding.appendData(element()->name(), element()->value());
+    return true;
+}
+
+double InputTypeUI::valueAsDate() const
+{
+    return DateComponents::invalidMilliseconds();
+}
+
+void InputTypeUI::setValueAsDate(double, ExceptionState& es) const
+{
+    es.throwDOMException(InvalidStateError);
+}
+
+double InputTypeUI::valueAsDouble() const
+{
+    return numeric_limits<double>::quiet_NaN();
+}
+
+void InputTypeUI::setValueAsDouble(double doubleValue, TextFieldEventBehavior eventBehavior, ExceptionState& es) const
+{
+    setValueAsDecimal(Decimal::fromDouble(doubleValue), eventBehavior, es);
+}
+
+void InputTypeUI::setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState& es) const
+{
+    es.throwDOMException(InvalidStateError);
+}
+
+bool InputTypeUI::supportsValidation() const
+{
+    return true;
+}
+
+bool InputTypeUI::typeMismatchFor(const String&) const
+{
+    return false;
+}
+
+bool InputTypeUI::typeMismatch() const
+{
+    return false;
+}
+
+bool InputTypeUI::supportsRequired() const
+{
+    // Almost all validatable types support @required.
+    return supportsValidation();
+}
+
+bool InputTypeUI::valueMissing(const String&) const
+{
+    return false;
+}
+
+bool InputTypeUI::hasBadInput() const
+{
+    return false;
+}
+
+bool InputTypeUI::patternMismatch(const String&) const
+{
+    return false;
+}
+
+bool InputTypeUI::rangeUnderflow(const String& value) const
+{
+    if (!isSteppable())
+        return false;
+
+    const Decimal numericValue = parseToNumberOrNaN(value);
+    if (!numericValue.isFinite())
+        return false;
+
+    return numericValue < createStepRange(RejectAny).minimum();
+}
+
+bool InputTypeUI::rangeOverflow(const String& value) const
+{
+    if (!isSteppable())
+        return false;
+
+    const Decimal numericValue = parseToNumberOrNaN(value);
+    if (!numericValue.isFinite())
+        return false;
+
+    return numericValue > createStepRange(RejectAny).maximum();
+}
+
+Decimal InputTypeUI::defaultValueForStepUp() const
+{
+    return 0;
+}
+
+double InputTypeUI::minimum() const
+{
+    return createStepRange(RejectAny).minimum().toDouble();
+}
+
+double InputTypeUI::maximum() const
+{
+    return createStepRange(RejectAny).maximum().toDouble();
+}
+
+bool InputTypeUI::sizeShouldIncludeDecoration(int, int& preferredSize) const
+{
+    preferredSize = element()->size();
+    return false;
+}
+
+bool InputTypeUI::isInRange(const String& value) const
+{
+    if (!isSteppable())
+        return false;
+
+    const Decimal numericValue = parseToNumberOrNaN(value);
+    if (!numericValue.isFinite())
+        return true;
+
+    StepRange stepRange(createStepRange(RejectAny));
+    return numericValue >= stepRange.minimum() && numericValue <= stepRange.maximum();
+}
+
+bool InputTypeUI::isOutOfRange(const String& value) const
+{
+    if (!isSteppable())
+        return false;
+
+    const Decimal numericValue = parseToNumberOrNaN(value);
+    if (!numericValue.isFinite())
+        return true;
+
+    StepRange stepRange(createStepRange(RejectAny));
+    return numericValue < stepRange.minimum() || numericValue > stepRange.maximum();
+}
+
+bool InputTypeUI::stepMismatch(const String& value) const
+{
+    if (!isSteppable())
+        return false;
+
+    const Decimal numericValue = parseToNumberOrNaN(value);
+    if (!numericValue.isFinite())
+        return false;
+
+    return createStepRange(RejectAny).stepMismatch(numericValue);
+}
+
+String InputTypeUI::badInputText() const
+{
+    ASSERT_NOT_REACHED();
+    return validationMessageTypeMismatchText();
+}
+
+String InputTypeUI::typeMismatchText() const
+{
+    return validationMessageTypeMismatchText();
+}
+
+String InputTypeUI::valueMissingText() const
+{
+    return validationMessageValueMissingText();
+}
+
+String InputTypeUI::validationMessage() const
+{
+    const String value = element()->value();
+
+    // The order of the following checks is meaningful. e.g. We'd like to show the
+    // badInput message even if the control has other validation errors.
+    if (hasBadInput())
+        return badInputText();
+
+    if (valueMissing(value))
+        return valueMissingText();
+
+    if (typeMismatch())
+        return typeMismatchText();
+
+    if (patternMismatch(value))
+        return validationMessagePatternMismatchText();
+
+    if (element()->tooLong())
+        return validationMessageTooLongText(numGraphemeClusters(value), element()->maxLength());
+
+    if (!isSteppable())
+        return emptyString();
+
+    const Decimal numericValue = parseToNumberOrNaN(value);
+    if (!numericValue.isFinite())
+        return emptyString();
+
+    StepRange stepRange(createStepRange(RejectAny));
+
+    if (numericValue < stepRange.minimum())
+        return validationMessageRangeUnderflowText(serialize(stepRange.minimum()));
+
+    if (numericValue > stepRange.maximum())
+        return validationMessageRangeOverflowText(serialize(stepRange.maximum()));
+
+    if (stepRange.stepMismatch(numericValue)) {
+        const String stepString = stepRange.hasStep() ? serializeForNumberType(stepRange.step() / stepRange.stepScaleFactor()) : emptyString();
+        return validationMessageStepMismatchText(serialize(stepRange.stepBase()), stepString);
+    }
+
+    return emptyString();
+}
+
+void InputTypeUI::handleClickEvent(MouseEvent*)
+{
+}
+
+void InputTypeUI::handleMouseDownEvent(MouseEvent*)
+{
+}
+
+void InputTypeUI::handleDOMActivateEvent(Event*)
+{
+}
+
+void InputTypeUI::handleKeydownEvent(KeyboardEvent*)
+{
+}
+
+void InputTypeUI::handleKeypressEvent(KeyboardEvent*)
+{
+}
+
+void InputTypeUI::handleKeyupEvent(KeyboardEvent*)
+{
+}
+
+void InputTypeUI::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*)
+{
+}
+
+void InputTypeUI::handleTouchEvent(TouchEvent*)
+{
+}
+
+void InputTypeUI::forwardEvent(Event*)
+{
+}
+
+bool InputTypeUI::shouldSubmitImplicitly(Event* event)
+{
+    return event->isKeyboardEvent() && event->type() == eventNames().keypressEvent && toKeyboardEvent(event)->charCode() == '\r';
+}
+
+PassRefPtr<HTMLFormElement> InputTypeUI::formForSubmission() const
+{
+    return element()->form();
+}
+
+RenderObject* InputTypeUI::createRenderer(RenderStyle* style) const
+{
+    return RenderObject::createObject(element(), style);
+}
+
+PassRefPtr<RenderStyle> InputTypeUI::customStyleForRenderer(PassRefPtr<RenderStyle> originalStyle)
+{
+    return originalStyle;
+}
+
+void InputTypeUI::blur()
+{
+    element()->defaultBlur();
+}
+
+void InputTypeUI::createShadowSubtree()
+{
+}
+
+void InputTypeUI::destroyShadowSubtree()
+{
+    ShadowRoot* root = element()->userAgentShadowRoot();
+    if (!root)
+        return;
+
+    root->removeChildren();
+
+    // It's ok to clear contents of all other ShadowRoots because they must have
+    // been created by InputFieldPasswordGeneratorButtonElement, and we don't allow adding
+    // AuthorShadowRoot to HTMLInputElement.
+    // FIXME: Remove the PasswordGeneratorButtonElement's shadow root and then remove this loop.
+    while ((root = root->youngerShadowRoot())) {
+        root->removeChildren();
+        root->appendChild(HTMLShadowElement::create(shadowTag, element()->document()));
+    }
+}
+
+Decimal InputTypeUI::parseToNumber(const String&, const Decimal& defaultValue) const
+{
+    ASSERT_NOT_REACHED();
+    return defaultValue;
+}
+
+Decimal InputTypeUI::parseToNumberOrNaN(const String& string) const
+{
+    return parseToNumber(string, Decimal::nan());
+}
+
+bool InputTypeUI::parseToDateComponents(const String&, DateComponents*) const
+{
+    ASSERT_NOT_REACHED();
+    return false;
+}
+
+String InputTypeUI::serialize(const Decimal&) const
+{
+    ASSERT_NOT_REACHED();
+    return String();
+}
+
+void InputTypeUI::dispatchSimulatedClickIfActive(KeyboardEvent* event) const
+{
+    if (element()->active())
+        element()->dispatchSimulatedClick(event);
+    event->setDefaultHandled();
+}
+
+Chrome* InputTypeUI::chrome() const
+{
+    if (Page* page = element()->document()->page())
+        return &page->chrome();
+    return 0;
+}
+
+bool InputTypeUI::canSetStringValue() const
+{
+    return true;
+}
+
+bool InputTypeUI::hasCustomFocusLogic() const
+{
+    return true;
+}
+
+bool InputTypeUI::isKeyboardFocusable() const
+{
+    return element()->isFocusable();
+}
+
+bool InputTypeUI::shouldShowFocusRingOnMouseFocus() const
+{
+    return false;
+}
+
+bool InputTypeUI::shouldUseInputMethod() const
+{
+    return false;
+}
+
+void InputTypeUI::handleFocusEvent(Element*, FocusDirection)
+{
+}
+
+void InputTypeUI::handleBlurEvent()
+{
+}
+
+void InputTypeUI::enableSecureTextInput()
+{
+}
+
+void InputTypeUI::disableSecureTextInput()
+{
+}
+
+void InputTypeUI::accessKeyAction(bool)
+{
+    element()->focus(false);
+}
+
+void InputTypeUI::attach()
+{
+}
+
+void InputTypeUI::detach()
+{
+}
+
+void InputTypeUI::countUsage()
+{
+}
+
+void InputTypeUI::altAttributeChanged()
+{
+}
+
+void InputTypeUI::srcAttributeChanged()
+{
+}
+
+bool InputTypeUI::shouldRespectAlignAttribute()
+{
+    return false;
+}
+
+bool InputTypeUI::canChangeFromAnotherType() const
+{
+    return true;
+}
+
+void InputTypeUI::minOrMaxAttributeChanged()
+{
+}
+
+void InputTypeUI::sanitizeValueInResponseToMinOrMaxAttributeChange()
+{
+}
+
+void InputTypeUI::stepAttributeChanged()
+{
+}
+
+bool InputTypeUI::canBeSuccessfulSubmitButton()
+{
+    return false;
+}
+
+HTMLElement* InputTypeUI::placeholderElement() const
+{
+    return 0;
+}
+
+bool InputTypeUI::rendererIsNeeded()
+{
+    return true;
+}
+
+FileList* InputTypeUI::files()
+{
+    return 0;
+}
+
+void InputTypeUI::setFiles(PassRefPtr<FileList>)
+{
+}
+
+bool InputTypeUI::getTypeSpecificValue(String&)
+{
+    return false;
+}
+
+String InputTypeUI::fallbackValue() const
+{
+    return String();
+}
+
+String InputTypeUI::defaultValue() const
+{
+    return String();
+}
+
+bool InputTypeUI::canSetSuggestedValue()
+{
+    return false;
+}
+
+bool InputTypeUI::shouldSendChangeEventAfterCheckedChanged()
+{
+    return true;
+}
+
+bool InputTypeUI::storesValueSeparateFromAttribute()
+{
+    return true;
+}
+
+void InputTypeUI::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
+{
+    element()->setValueInternal(sanitizedValue, eventBehavior);
+    element()->setNeedsStyleRecalc();
+    if (!valueChanged)
+        return;
+    switch (eventBehavior) {
+    case DispatchChangeEvent:
+        element()->dispatchFormControlChangeEvent();
+        break;
+    case DispatchInputAndChangeEvent:
+        element()->dispatchFormControlInputEvent();
+        element()->dispatchFormControlChangeEvent();
+        break;
+    case DispatchNoEvent:
+        break;
+    }
+}
+
+bool InputTypeUI::canSetValue(const String&)
+{
+    return true;
+}
+
+PassOwnPtr<ClickHandlingState> InputTypeUI::willDispatchClick()
+{
+    return nullptr;
+}
+
+void InputTypeUI::didDispatchClick(Event*, const ClickHandlingState&)
+{
+}
+
+String InputTypeUI::localizeValue(const String& proposedValue) const
+{
+    return proposedValue;
+}
+
+String InputTypeUI::visibleValue() const
+{
+    return element()->value();
+}
+
+String InputTypeUI::sanitizeValue(const String& proposedValue) const
+{
+    return proposedValue;
+}
+
+bool InputTypeUI::receiveDroppedFiles(const DragData*)
+{
+    ASSERT_NOT_REACHED();
+    return false;
+}
+
+String InputTypeUI::droppedFileSystemId()
+{
+    ASSERT_NOT_REACHED();
+    return String();
+}
+
+bool InputTypeUI::shouldResetOnDocumentActivation()
+{
+    return false;
+}
+
+bool InputTypeUI::shouldRespectListAttribute()
+{
+    return false;
+}
+
+bool InputTypeUI::shouldRespectSpeechAttribute()
+{
+    return false;
+}
+
+bool InputTypeUI::isTextButton() const
+{
+    return false;
+}
+
+bool InputTypeUI::isRadioButton() const
+{
+    return false;
+}
+
+bool InputTypeUI::isSearchField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isHiddenType() const
+{
+    return false;
+}
+
+bool InputTypeUI::isPasswordField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isCheckbox() const
+{
+    return false;
+}
+
+bool InputTypeUI::isEmailField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isFileUpload() const
+{
+    return false;
+}
+
+bool InputTypeUI::isImageButton() const
+{
+    return false;
+}
+
+bool InputTypeUI::supportLabels() const
+{
+    return true;
+}
+
+bool InputTypeUI::isNumberField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isSubmitButton() const
+{
+    return false;
+}
+
+bool InputTypeUI::isTelephoneField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isURLField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isDateField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isDateTimeLocalField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isMonthField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isTimeField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isWeekField() const
+{
+    return false;
+}
+
+bool InputTypeUI::isEnumeratable()
+{
+    return true;
+}
+
+bool InputTypeUI::isCheckable()
+{
+    return false;
+}
+
+bool InputTypeUI::isSteppable() const
+{
+    return false;
+}
+
+bool InputTypeUI::isColorControl() const
+{
+    return false;
+}
+
+bool InputTypeUI::shouldRespectHeightAndWidthAttributes()
+{
+    return false;
+}
+
+bool InputTypeUI::supportsPlaceholder() const
+{
+    return false;
+}
+
+bool InputTypeUI::supportsReadOnly() const
+{
+    return false;
+}
+
+void InputTypeUI::updateInnerTextValue()
+{
+}
+
+void InputTypeUI::updatePlaceholderText()
+{
+}
+
+void InputTypeUI::attributeChanged()
+{
+}
+
+void InputTypeUI::multipleAttributeChanged()
+{
+}
+
+void InputTypeUI::disabledAttributeChanged()
+{
+}
+
+void InputTypeUI::readonlyAttributeChanged()
+{
+}
+
+void InputTypeUI::requiredAttributeChanged()
+{
+}
+
+void InputTypeUI::valueAttributeChanged()
+{
+}
+
+void InputTypeUI::subtreeHasChanged()
+{
+    ASSERT_NOT_REACHED();
+}
+
+bool InputTypeUI::hasTouchEventHandler() const
+{
+    return false;
+}
+
+String InputTypeUI::defaultToolTip() const
+{
+    return String();
+}
+
+void InputTypeUI::listAttributeTargetChanged()
+{
+}
+
+Decimal InputTypeUI::findClosestTickMarkValue(const Decimal&)
+{
+    ASSERT_NOT_REACHED();
+    return Decimal::nan();
+}
+
+void InputTypeUI::updateClearButtonVisibility()
+{
+}
+
+bool InputTypeUI::supportsIndeterminateAppearance() const
+{
+    return false;
+}
+
+bool InputTypeUI::supportsInputModeAttribute() const
+{
+    return false;
+}
+
+bool InputTypeUI::supportsSelectionAPI() const
+{
+    return false;
+}
+
+unsigned InputTypeUI::height() const
+{
+    return 0;
+}
+
+unsigned InputTypeUI::width() const
+{
+    return 0;
+}
+
+void InputTypeUI::applyStep(int count, AnyStepHandling anyStepHandling, TextFieldEventBehavior eventBehavior, ExceptionState& es)
+{
+    StepRange stepRange(createStepRange(anyStepHandling));
+    if (!stepRange.hasStep()) {
+        es.throwDOMException(InvalidStateError);
+        return;
+    }
+
+    const Decimal current = parseToNumberOrNaN(element()->value());
+    if (!current.isFinite()) {
+        es.throwDOMException(InvalidStateError);
+        return;
+    }
+    Decimal newValue = current + stepRange.step() * count;
+    if (!newValue.isFinite()) {
+        es.throwDOMException(InvalidStateError);
+        return;
+    }
+
+    const Decimal acceptableErrorValue = stepRange.acceptableError();
+    if (newValue - stepRange.minimum() < -acceptableErrorValue) {
+        es.throwDOMException(InvalidStateError);
+        return;
+    }
+    if (newValue < stepRange.minimum())
+        newValue = stepRange.minimum();
+
+    const AtomicString& stepString = element()->fastGetAttribute(stepAttr);
+    if (!equalIgnoringCase(stepString, "any"))
+        newValue = stepRange.alignValueForStep(current, newValue);
+
+    if (newValue - stepRange.maximum() > acceptableErrorValue) {
+        es.throwDOMException(InvalidStateError);
+        return;
+    }
+    if (newValue > stepRange.maximum())
+        newValue = stepRange.maximum();
+
+    setValueAsDecimal(newValue, eventBehavior, es);
+
+    if (AXObjectCache* cache = element()->document()->existingAXObjectCache())
+        cache->postNotification(element(), AXObjectCache::AXValueChanged, true);
+}
+
+bool InputTypeUI::getAllowedValueStep(Decimal* step) const
+{
+    StepRange stepRange(createStepRange(RejectAny));
+    *step = stepRange.step();
+    return stepRange.hasStep();
+}
+
+StepRange InputTypeUI::createStepRange(AnyStepHandling) const
+{
+    ASSERT_NOT_REACHED();
+    return StepRange();
+}
+
+void InputTypeUI::stepUp(int n, ExceptionState& es)
+{
+    if (!isSteppable()) {
+        es.throwDOMException(InvalidStateError);
+        return;
+    }
+    applyStep(n, RejectAny, DispatchNoEvent, es);
+}
+
+void InputTypeUI::stepUpFromRenderer(int n)
+{
+    // The differences from stepUp()/stepDown():
+    //
+    // Difference 1: the current value
+    // If the current value is not a number, including empty, the current value is assumed as 0.
+    //   * If 0 is in-range, and matches to step value
+    //     - The value should be the +step if n > 0
+    //     - The value should be the -step if n < 0
+    //     If -step or +step is out of range, new value should be 0.
+    //   * If 0 is smaller than the minimum value
+    //     - The value should be the minimum value for any n
+    //   * If 0 is larger than the maximum value
+    //     - The value should be the maximum value for any n
+    //   * If 0 is in-range, but not matched to step value
+    //     - The value should be the larger matched value nearest to 0 if n > 0
+    //       e.g. <input type=number min=-100 step=3> -> 2
+    //     - The value should be the smaler matched value nearest to 0 if n < 0
+    //       e.g. <input type=number min=-100 step=3> -> -1
+    //   As for date/datetime-local/month/time/week types, the current value is assumed as "the current local date/time".
+    //   As for datetime type, the current value is assumed as "the current date/time in UTC".
+    // If the current value is smaller than the minimum value:
+    //  - The value should be the minimum value if n > 0
+    //  - Nothing should happen if n < 0
+    // If the current value is larger than the maximum value:
+    //  - The value should be the maximum value if n < 0
+    //  - Nothing should happen if n > 0
+    //
+    // Difference 2: clamping steps
+    // If the current value is not matched to step value:
+    // - The value should be the larger matched value nearest to 0 if n > 0
+    //   e.g. <input type=number value=3 min=-100 step=3> -> 5
+    // - The value should be the smaler matched value nearest to 0 if n < 0
+    //   e.g. <input type=number value=3 min=-100 step=3> -> 2
+    //
+    // n is assumed as -n if step < 0.
+
+    ASSERT(isSteppable());
+    if (!isSteppable())
+        return;
+    ASSERT(n);
+    if (!n)
+        return;
+
+    StepRange stepRange(createStepRange(AnyIsDefaultStep));
+
+    // FIXME: Not any changes after stepping, even if it is an invalid value, may be better.
+    // (e.g. Stepping-up for <input type="number" value="foo" step="any" /> => "foo")
+    if (!stepRange.hasStep())
+        return;
+
+    EventQueueScope scope;
+    const Decimal step = stepRange.step();
+
+    int sign;
+    if (step > 0)
+        sign = n;
+    else if (step < 0)
+        sign = -n;
+    else
+        sign = 0;
+
+    String currentStringValue = element()->value();
+    Decimal current = parseToNumberOrNaN(currentStringValue);
+    if (!current.isFinite()) {
+        current = defaultValueForStepUp();
+        const Decimal nextDiff = step * n;
+        if (current < stepRange.minimum() - nextDiff)
+            current = stepRange.minimum() - nextDiff;
+        if (current > stepRange.maximum() - nextDiff)
+            current = stepRange.maximum() - nextDiff;
+        setValueAsDecimal(current, DispatchNoEvent, IGNORE_EXCEPTION);
+    }
+    if ((sign > 0 && current < stepRange.minimum()) || (sign < 0 && current > stepRange.maximum())) {
+        setValueAsDecimal(sign > 0 ? stepRange.minimum() : stepRange.maximum(), DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
+    } else {
+        if (stepMismatch(element()->value())) {
+            ASSERT(!step.isZero());
+            const Decimal base = stepRange.stepBase();
+            Decimal newValue;
+            if (sign < 0)
+                newValue = base + ((current - base) / step).floor() * step;
+            else if (sign > 0)
+                newValue = base + ((current - base) / step).ceiling() * step;
+            else
+                newValue = current;
+
+            if (newValue < stepRange.minimum())
+                newValue = stepRange.minimum();
+            if (newValue > stepRange.maximum())
+                newValue = stepRange.maximum();
+
+            setValueAsDecimal(newValue, n == 1 || n == -1 ? DispatchInputAndChangeEvent : DispatchNoEvent, IGNORE_EXCEPTION);
+            if (n > 1)
+                applyStep(n - 1, AnyIsDefaultStep, DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
+            else if (n < -1)
+                applyStep(n + 1, AnyIsDefaultStep, DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
+        } else {
+            applyStep(n, AnyIsDefaultStep, DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
+        }
+    }
+}
+
+void InputTypeUI::observeFeatureIfVisible(UseCounter::Feature feature) const
+{
+    if (RenderStyle* style = element()->renderStyle()) {
+        if (style->visibility() != HIDDEN)
+            UseCounter::count(element()->document(), feature);
+    }
+}
+
+} // namespace WebCore
diff --git a/Source/core/html/InputTypeUI.h b/Source/core/html/InputTypeUI.h
new file mode 100644
index 0000000..3e835a5
--- /dev/null
+++ b/Source/core/html/InputTypeUI.h
@@ -0,0 +1,313 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2012 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.
+ */
+
+#ifndef InputTypeUI_h
+#define InputTypeUI_h
+
+#include "core/html/HTMLTextFormControlElement.h"
+#include "core/html/StepRange.h"
+#include "core/page/UseCounter.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class BeforeTextInsertedEvent;
+class Chrome;
+class Color;
+class DateComponents;
+class DragData;
+class Event;
+class ExceptionState;
+class FileList;
+class FormDataList;
+class HTMLElement;
+class HTMLFormElement;
+class HTMLInputElement;
+class KeyboardEvent;
+class MouseEvent;
+class Node;
+class RenderObject;
+class RenderStyle;
+class TouchEvent;
+
+struct ClickHandlingState {
+    WTF_MAKE_FAST_ALLOCATED;
+
+public:
+    bool checked;
+    bool indeterminate;
+    RefPtr<HTMLInputElement> checkedRadioButton;
+};
+
+// An InputType object represents the type-specific part of an HTMLInputElement.
+// Do not expose instances of InputType and classes derived from it to classes
+// other than HTMLInputElement.
+class InputTypeUI {
+    WTF_MAKE_NONCOPYABLE(InputTypeUI);
+    WTF_MAKE_FAST_ALLOCATED;
+
+public:
+    static PassOwnPtr<InputTypeUI> create(HTMLInputElement*, const AtomicString&);
+    static PassOwnPtr<InputTypeUI> createText(HTMLInputElement*);
+    virtual ~InputTypeUI();
+
+    static bool themeSupportsDataListUI(InputTypeUI*);
+
+    virtual const AtomicString& formControlType() const = 0;
+    virtual bool canChangeFromAnotherType() const;
+
+    // Type query functions
+
+    // Any time we are using one of these functions it's best to refactor
+    // to add a virtual function to allow the input type object to do the
+    // work instead, or at least make a query function that asks a higher
+    // level question. These functions make the HTMLInputElement class
+    // inflexible because it's harder to add new input types if there is
+    // scattered code with special cases for various types.
+
+    virtual bool isCheckbox() const;
+    virtual bool isColorControl() const;
+    virtual bool isDateField() const;
+    virtual bool isDateTimeLocalField() const;
+    virtual bool isEmailField() const;
+    virtual bool isFileUpload() const;
+    virtual bool isHiddenType() const;
+    virtual bool isImageButton() const;
+    virtual bool supportLabels() const;
+    virtual bool isMonthField() const;
+    virtual bool isNumberField() const;
+    virtual bool isPasswordField() const;
+    virtual bool isRadioButton() const;
+    virtual bool isRangeControl() const;
+    virtual bool isSearchField() const;
+    virtual bool isSubmitButton() const;
+    virtual bool isTelephoneField() const;
+    virtual bool isTextButton() const;
+    virtual bool isTextField() const;
+    virtual bool isTextType() const;
+    virtual bool isTimeField() const;
+    virtual bool isURLField() const;
+    virtual bool isWeekField() const;
+
+    // Form value functions
+
+    virtual bool shouldSaveAndRestoreFormControlState() const;
+    virtual FormControlState saveFormControlState() const;
+    virtual void restoreFormControlState(const FormControlState&);
+    virtual bool isFormDataAppendable() const;
+    virtual bool appendFormData(FormDataList&, bool multipart) const;
+
+    // DOM property functions
+
+    virtual bool getTypeSpecificValue(String&); // Checked first, before internal storage or the value attribute.
+    virtual String fallbackValue() const; // Checked last, if both internal storage and value attribute are missing.
+    virtual String defaultValue() const; // Checked after even fallbackValue, only when the valueWithDefault function is called.
+    virtual double valueAsDate() const;
+    virtual void setValueAsDate(double, ExceptionState&) const;
+    virtual double valueAsDouble() const;
+    virtual void setValueAsDouble(double, TextFieldEventBehavior, ExceptionState&) const;
+    virtual void setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState&) const;
+
+    // Validation functions
+    virtual String validationMessage() const;
+    virtual bool supportsValidation() const;
+    virtual bool typeMismatchFor(const String&) const;
+    // Type check for the current input value. We do nothing for some types
+    // though typeMismatchFor() does something for them because of value
+    // sanitization.
+    virtual bool typeMismatch() const;
+    virtual bool supportsRequired() const;
+    virtual bool valueMissing(const String&) const;
+    virtual bool hasBadInput() const;
+    virtual bool patternMismatch(const String&) const;
+    bool rangeUnderflow(const String&) const;
+    bool rangeOverflow(const String&) const;
+    bool isInRange(const String&) const;
+    bool isOutOfRange(const String&) const;
+    virtual Decimal defaultValueForStepUp() const;
+    double minimum() const;
+    double maximum() const;
+    virtual bool sizeShouldIncludeDecoration(int defaultSize, int& preferredSize) const;
+    bool stepMismatch(const String&) const;
+    virtual bool getAllowedValueStep(Decimal*) const;
+    virtual StepRange createStepRange(AnyStepHandling) const;
+    virtual void stepUp(int, ExceptionState&);
+    virtual void stepUpFromRenderer(int);
+    virtual String badInputText() const;
+    virtual String typeMismatchText() const;
+    virtual String valueMissingText() const;
+    virtual bool canSetStringValue() const;
+    virtual String localizeValue(const String&) const;
+    virtual String visibleValue() const;
+    // Returing the null string means "use the default value."
+    // This function must be called only by HTMLInputElement::sanitizeValue().
+    virtual String sanitizeValue(const String&) const;
+
+    // Event handlers
+
+    virtual void handleClickEvent(MouseEvent*);
+    virtual void handleMouseDownEvent(MouseEvent*);
+    virtual PassOwnPtr<ClickHandlingState> willDispatchClick();
+    virtual void didDispatchClick(Event*, const ClickHandlingState&);
+    virtual void handleDOMActivateEvent(Event*);
+    virtual void handleKeydownEvent(KeyboardEvent*);
+    virtual void handleKeypressEvent(KeyboardEvent*);
+    virtual void handleKeyupEvent(KeyboardEvent*);
+    virtual void handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*);
+    virtual void handleTouchEvent(TouchEvent*);
+    virtual void forwardEvent(Event*);
+    // Helpers for event handlers.
+    virtual bool shouldSubmitImplicitly(Event*);
+    virtual PassRefPtr<HTMLFormElement> formForSubmission() const;
+    virtual bool hasCustomFocusLogic() const;
+    virtual bool isKeyboardFocusable() const;
+    virtual bool shouldShowFocusRingOnMouseFocus() const;
+    virtual bool shouldUseInputMethod() const;
+    virtual void enableSecureTextInput();
+    virtual void disableSecureTextInput();
+    virtual void handleFocusEvent(Element* oldFocusedElement, FocusDirection);
+    virtual void handleBlurEvent();
+    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual bool canBeSuccessfulSubmitButton();
+    virtual void subtreeHasChanged();
+    virtual bool hasTouchEventHandler() const;
+
+    virtual void blur();
+
+    // Shadow tree handling
+
+    virtual void createShadowSubtree();
+    virtual void destroyShadowSubtree();
+
+    virtual HTMLElement* containerElement() const { return 0; }
+    virtual HTMLElement* innerBlockElement() const { return 0; }
+    virtual HTMLElement* innerTextElement() const { return 0; }
+    virtual HTMLElement* passwordGeneratorButtonElement() const { return 0; }
+    virtual HTMLElement* placeholderElement() const;
+
+    // Miscellaneous functions
+
+    virtual bool rendererIsNeeded();
+    virtual RenderObject* createRenderer(RenderStyle*) const;
+    virtual PassRefPtr<RenderStyle> customStyleForRenderer(PassRefPtr<RenderStyle>);
+    virtual void attach();
+    virtual void detach();
+    virtual void countUsage();
+    virtual void minOrMaxAttributeChanged();
+    virtual void sanitizeValueInResponseToMinOrMaxAttributeChange();
+    virtual void stepAttributeChanged();
+    virtual void altAttributeChanged();
+    virtual void srcAttributeChanged();
+    virtual bool shouldRespectAlignAttribute();
+    virtual FileList* files();
+    virtual void setFiles(PassRefPtr<FileList>);
+    // Should return true if the given DragData has more than one dropped files.
+    virtual bool receiveDroppedFiles(const DragData*);
+    virtual String droppedFileSystemId();
+    // Should return true if the corresponding renderer for a type can display a suggested value.
+    virtual bool canSetSuggestedValue();
+    virtual bool shouldSendChangeEventAfterCheckedChanged();
+    virtual bool canSetValue(const String&);
+    virtual bool storesValueSeparateFromAttribute();
+    virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior);
+    virtual bool shouldResetOnDocumentActivation();
+    virtual bool shouldRespectListAttribute();
+    virtual bool shouldRespectSpeechAttribute();
+    virtual bool isEnumeratable();
+    virtual bool isCheckable();
+    virtual bool isSteppable() const;
+    virtual bool shouldRespectHeightAndWidthAttributes();
+    virtual bool supportsPlaceholder() const;
+    virtual bool supportsReadOnly() const;
+    virtual void updateInnerTextValue();
+    virtual void updatePlaceholderText();
+    virtual void attributeChanged();
+    virtual void multipleAttributeChanged();
+    virtual void disabledAttributeChanged();
+    virtual void readonlyAttributeChanged();
+    virtual void requiredAttributeChanged();
+    virtual void valueAttributeChanged();
+    virtual String defaultToolTip() const;
+    virtual void listAttributeTargetChanged();
+    virtual Decimal findClosestTickMarkValue(const Decimal&);
+    virtual void updateClearButtonVisibility();
+
+    // Parses the specified string for the type, and return
+    // the Decimal value for the parsing result if the parsing
+    // succeeds; Returns defaultValue otherwise. This function can
+    // return NaN or Infinity only if defaultValue is NaN or Infinity.
+    virtual Decimal parseToNumber(const String&, const Decimal& defaultValue) const;
+
+    // Parses the specified string for this InputTypeUI, and returns true if it
+    // is successfully parsed. An instance pointed by the DateComponents*
+    // parameter will have parsed values and be modified even if the parsing
+    // fails. The DateComponents* parameter may be 0.
+    virtual bool parseToDateComponents(const String&, DateComponents*) const;
+
+    // Create a string representation of the specified Decimal value for the
+    // input type. If NaN or Infinity is specified, this returns an empty
+    // string. This should not be called for types without valueAsNumber.
+    virtual String serialize(const Decimal&) const;
+
+    virtual bool supportsIndeterminateAppearance() const;
+
+    virtual bool supportsInputModeAttribute() const;
+
+    virtual bool supportsSelectionAPI() const;
+
+    // Gets width and height of the input element if the type of the
+    // element is image. It returns 0 if the element is not image type.
+    virtual unsigned height() const;
+    virtual unsigned width() const;
+
+    void dispatchSimulatedClickIfActive(KeyboardEvent*) const;
+
+protected:
+    InputTypeUI(HTMLInputElement* element) : m_element(element) { }
+    HTMLInputElement* element() const { return m_element; }
+    Chrome* chrome() const;
+    Decimal parseToNumberOrNaN(const String&) const;
+    void observeFeatureIfVisible(UseCounter::Feature) const;
+
+private:
+    // Helper for stepUp()/stepDown(). Adds step value * count to the current value.
+    void applyStep(int count, AnyStepHandling, TextFieldEventBehavior, ExceptionState&);
+
+    // Raw pointer because the HTMLInputElement object owns this InputTypeUI object.
+    HTMLInputElement* m_element;
+};
+
+} // namespace WebCore
+#endif
diff --git a/Source/core/html/LinkResource.h b/Source/core/html/LinkResource.h
index 8c6c84e..b4eeb3d 100644
--- a/Source/core/html/LinkResource.h
+++ b/Source/core/html/LinkResource.h
@@ -31,7 +31,7 @@
 #ifndef LinkResource_h
 #define LinkResource_h
 
-#include "core/loader/cache/FetchRequest.h"
+#include "core/fetch/FetchRequest.h"
 #include "weborigin/KURL.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/html/MediaDocument.cpp b/Source/core/html/MediaDocument.cpp
index fe77533..f913bf7 100644
--- a/Source/core/html/MediaDocument.cpp
+++ b/Source/core/html/MediaDocument.cpp
@@ -74,6 +74,7 @@
 {
     RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(document());
     rootElement->insertedByParser();
+    document()->appendChild(rootElement);
 
     if (document()->frame())
         document()->frame()->loader()->dispatchDocumentElementAvailable();
@@ -82,7 +83,7 @@
     RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(document());
     meta->setAttribute(nameAttr, "viewport");
     meta->setAttribute(contentAttr, "width=device-width");
-    head->appendChild(meta.release(), ASSERT_NO_EXCEPTION);
+    head->appendChild(meta.release());
 
     RefPtr<HTMLVideoElement> media = HTMLVideoElement::create(document());
     media->setAttribute(controlsAttr, "");
@@ -95,15 +96,14 @@
     if (DocumentLoader* loader = document()->loader())
         source->setType(loader->responseMIMEType());
 
-    media->appendChild(source.release(), ASSERT_NO_EXCEPTION);
+    media->appendChild(source.release());
 
     RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(document());
-    body->appendChild(media.release(), ASSERT_NO_EXCEPTION);
+    body->appendChild(media.release());
 
-    rootElement->appendChild(head.release(), ASSERT_NO_EXCEPTION);
-    rootElement->appendChild(body.release(), ASSERT_NO_EXCEPTION);
+    rootElement->appendChild(head.release());
+    rootElement->appendChild(body.release());
 
-    document()->appendChild(rootElement.release(), ASSERT_NO_EXCEPTION, AttachLazily);
     m_didBuildDocumentStructure = true;
 }
 
diff --git a/Source/core/html/MonthInputType.cpp b/Source/core/html/MonthInputType.cpp
index 3de0be5..b7fd518 100644
--- a/Source/core/html/MonthInputType.cpp
+++ b/Source/core/html/MonthInputType.cpp
@@ -59,7 +59,7 @@
     return adoptPtr(new MonthInputType(element));
 }
 
-void MonthInputType::attach()
+void MonthInputType::countUsage()
 {
     observeFeatureIfVisible(UseCounter::InputTypeMonth);
 }
diff --git a/Source/core/html/MonthInputType.h b/Source/core/html/MonthInputType.h
index 9fbfd33..ca682e7 100644
--- a/Source/core/html/MonthInputType.h
+++ b/Source/core/html/MonthInputType.h
@@ -48,7 +48,7 @@
 
 private:
     MonthInputType(HTMLInputElement* element) : BaseMonthInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual double valueAsDate() const OVERRIDE;
diff --git a/Source/core/html/NumberInputType.cpp b/Source/core/html/NumberInputType.cpp
index a1d0ada..ad93f17 100644
--- a/Source/core/html/NumberInputType.cpp
+++ b/Source/core/html/NumberInputType.cpp
@@ -100,9 +100,8 @@
     return adoptPtr(new NumberInputType(element));
 }
 
-void NumberInputType::attach()
+void NumberInputType::countUsage()
 {
-    TextFieldInputType::attach();
     observeFeatureIfVisible(UseCounter::InputTypeNumber);
 }
 
diff --git a/Source/core/html/NumberInputType.h b/Source/core/html/NumberInputType.h
index 866e873..4ed9d25 100644
--- a/Source/core/html/NumberInputType.h
+++ b/Source/core/html/NumberInputType.h
@@ -43,7 +43,7 @@
 
 private:
     NumberInputType(HTMLInputElement* element) : TextFieldInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
     virtual double valueAsDouble() const OVERRIDE;
diff --git a/Source/core/html/PasswordInputType.cpp b/Source/core/html/PasswordInputType.cpp
index 94518ed..19f2df4 100644
--- a/Source/core/html/PasswordInputType.cpp
+++ b/Source/core/html/PasswordInputType.cpp
@@ -55,9 +55,9 @@
 
 bool PasswordInputType::isPasswordGenerationEnabled() const
 {
-    Document* document = element()->document();
-    ChromeClient* chromeClient = document->page() ? document->page()->chrome().client() : 0;
-    return chromeClient && chromeClient->isPasswordGenerationEnabled();
+    if (Page* page = element()->document()->page())
+        return page->chrome().client().isPasswordGenerationEnabled();
+    return false;
 }
 
 bool PasswordInputType::needsContainer() const
@@ -130,18 +130,16 @@
     return true;
 }
 
-void PasswordInputType::handleFocusEvent(Element* oldFocusedElement, FocusDirection direction)
+void PasswordInputType::enableSecureTextInput()
 {
-    BaseTextInputType::handleFocusEvent(oldFocusedElement, direction);
     if (element()->document()->frame())
         element()->document()->setUseSecureKeyboardEntryWhenActive(true);
 }
 
-void PasswordInputType::handleBlurEvent()
+void PasswordInputType::disableSecureTextInput()
 {
     if (element()->document()->frame())
         element()->document()->setUseSecureKeyboardEntryWhenActive(false);
-    BaseTextInputType::handleBlurEvent();
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/PasswordInputType.h b/Source/core/html/PasswordInputType.h
index 0b0def1..84a8409 100644
--- a/Source/core/html/PasswordInputType.h
+++ b/Source/core/html/PasswordInputType.h
@@ -55,8 +55,8 @@
     virtual bool shouldRespectListAttribute() OVERRIDE;
     virtual bool shouldRespectSpeechAttribute() OVERRIDE;
     virtual bool isPasswordField() const OVERRIDE;
-    virtual void handleFocusEvent(Element* oldFocusedElement, FocusDirection) OVERRIDE;
-    virtual void handleBlurEvent() OVERRIDE;
+    virtual void enableSecureTextInput() OVERRIDE;
+    virtual void disableSecureTextInput() OVERRIDE;
 
     bool isPasswordGenerationEnabled() const;
 
diff --git a/Source/core/html/PluginDocument.cpp b/Source/core/html/PluginDocument.cpp
index 03db07b..0a53906 100644
--- a/Source/core/html/PluginDocument.cpp
+++ b/Source/core/html/PluginDocument.cpp
@@ -28,6 +28,7 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/RawDataDocumentParser.h"
+#include "core/html/HTMLBodyElement.h"
 #include "core/html/HTMLEmbedElement.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/loader/DocumentLoader.h"
@@ -65,57 +66,48 @@
 
     PluginView* pluginView() const;
 
-    HTMLEmbedElement* m_embedElement;
+    RefPtr<HTMLEmbedElement> m_embedElement;
 };
 
 void PluginDocumentParser::createDocumentStructure()
 {
-    RefPtr<Element> rootElement = document()->createElement(htmlTag, false);
-    document()->appendChild(rootElement, IGNORE_EXCEPTION);
-    toHTMLHtmlElement(rootElement.get())->insertedByParser();
-
-    if (document()->frame() && document()->frame()->loader())
-        document()->frame()->loader()->dispatchDocumentElementAvailable();
-
-    RefPtr<Element> body = document()->createElement(bodyTag, false);
-    body->setAttribute(marginwidthAttr, "0");
-    body->setAttribute(marginheightAttr, "0");
-    body->setAttribute(styleAttr, "background-color: rgb(38,38,38)");
-
-    rootElement->appendChild(body, IGNORE_EXCEPTION);
-
-    RefPtr<Element> embedElement = document()->createElement(embedTag, false);
-
-    m_embedElement = static_cast<HTMLEmbedElement*>(embedElement.get());
-    m_embedElement->setAttribute(widthAttr, "100%");
-    m_embedElement->setAttribute(heightAttr, "100%");
-
-    m_embedElement->setAttribute(nameAttr, "plugin");
-    m_embedElement->setAttribute(srcAttr, document()->url().string());
-
-    DocumentLoader* loader = document()->loader();
-    ASSERT(loader);
-    if (loader)
-        m_embedElement->setAttribute(typeAttr, loader->mimeType());
-
-    toPluginDocument(document())->setPluginNode(m_embedElement);
-
-    body->appendChild(embedElement, IGNORE_EXCEPTION);
+    // FIXME: Assert we have a loader to figure out why the original null checks
+    // and assert were added for the security bug in http://trac.webkit.org/changeset/87566
+    RELEASE_ASSERT(document()->loader());
 
     Frame* frame = document()->frame();
     if (!frame)
         return;
-    Settings* settings = frame->settings();
-    if (!settings || !frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+
+    // FIXME: Why does this check settings?
+    if (!frame->settings() || !frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
         return;
 
+    RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(document());
+    rootElement->insertedByParser();
+    document()->appendChild(rootElement);
+    frame->loader()->dispatchDocumentElementAvailable();
+
+    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(document());
+    body->setAttribute(marginwidthAttr, "0");
+    body->setAttribute(marginheightAttr, "0");
+    body->setAttribute(styleAttr, "background-color: rgb(38,38,38)");
+    rootElement->appendChild(body);
+
+    m_embedElement = HTMLEmbedElement::create(document());
+    m_embedElement->setAttribute(widthAttr, "100%");
+    m_embedElement->setAttribute(heightAttr, "100%");
+    m_embedElement->setAttribute(nameAttr, "plugin");
+    m_embedElement->setAttribute(srcAttr, document()->url().string());
+    m_embedElement->setAttribute(typeAttr, document()->loader()->mimeType());
+    body->appendChild(m_embedElement);
+
+    toPluginDocument(document())->setPluginNode(m_embedElement.get());
+
     document()->updateLayout();
 
-    // Below we assume that renderer->widget() to have been created by
-    // document()->updateLayout(). However, in some cases, updateLayout() will
-    // recurse too many times and delay its post-layout tasks (such as creating
-    // the widget). Here we kick off the pending post-layout tasks so that we
-    // can synchronously redirect data to the plugin.
+    // We need the plugin to load synchronously so we can get the PluginView
+    // below so flush the layout tasks now instead of waiting on the timer.
     frame->view()->flushAnyPendingPostLayoutTasks();
 
     if (PluginView* view = pluginView())
@@ -143,6 +135,7 @@
             view->didFinishLoading();
         else
             view->didFailLoading(error);
+        m_embedElement = 0;
     }
     RawDataDocumentParser::finish();
 }
diff --git a/Source/core/html/RadioNodeList.cpp b/Source/core/html/RadioNodeList.cpp
index 5768dcf..0522f12 100644
--- a/Source/core/html/RadioNodeList.cpp
+++ b/Source/core/html/RadioNodeList.cpp
@@ -90,7 +90,7 @@
     if (ownerNode()->hasTagName(formTag)) {
         HTMLFormElement* formElement = 0;
         if (testElement->hasTagName(objectTag))
-            formElement = static_cast<HTMLObjectElement*>(testElement)->form();
+            formElement = toHTMLObjectElement(testElement)->form();
         else
             formElement = toHTMLFormControlElement(testElement)->form();
         if (!formElement || formElement != ownerNode())
diff --git a/Source/core/html/RangeInputType.cpp b/Source/core/html/RangeInputType.cpp
index d65d553..e4b14fe 100644
--- a/Source/core/html/RangeInputType.cpp
+++ b/Source/core/html/RangeInputType.cpp
@@ -50,6 +50,7 @@
 #include "core/html/InputTypeNames.h"
 #include "core/html/StepRange.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/SliderThumbElement.h"
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/rendering/RenderSlider.h"
@@ -84,7 +85,7 @@
 {
 }
 
-void RangeInputType::attach()
+void RangeInputType::countUsage()
 {
     observeFeatureIfVisible(UseCounter::InputTypeRange);
 }
@@ -152,7 +153,7 @@
     ASSERT(element()->shadow());
     if (targetNode != element() && !targetNode->isDescendantOf(element()->userAgentShadowRoot()))
         return;
-    SliderThumbElement* thumb = sliderThumbElementOf(element());
+    SliderThumbElement* thumb = sliderThumbElement();
     if (targetNode == thumb)
         return;
     thumb->dragFrom(event->absoluteLocation());
@@ -170,9 +171,7 @@
 
     TouchList* touches = event->targetTouches();
     if (touches->length() == 1) {
-        Touch* touch = touches->item(0);
-        SliderThumbElement* thumb = sliderThumbElementOf(element());
-        thumb->setPositionFromPoint(touch->absoluteLocation());
+        sliderThumbElement()->setPositionFromPoint(touches->item(0)->absoluteLocation());
         event->setDefaultHandled();
     }
 }
@@ -248,10 +247,11 @@
     Document* document = element()->document();
     RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
     track->setPart(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
-    track->appendChild(SliderThumbElement::create(document), IGNORE_EXCEPTION);
+    track->setAttribute(idAttr, ShadowElementNames::sliderTrack());
+    track->appendChild(SliderThumbElement::create(document));
     RefPtr<HTMLElement> container = SliderContainerElement::create(document);
-    container->appendChild(track.release(), IGNORE_EXCEPTION);
-    element()->userAgentShadowRoot()->appendChild(container.release(), IGNORE_EXCEPTION);
+    container->appendChild(track.release());
+    element()->userAgentShadowRoot()->appendChild(container.release());
 }
 
 RenderObject* RangeInputType::createRenderer(RenderStyle*) const
@@ -279,15 +279,12 @@
     element()->dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
 }
 
-void RangeInputType::minOrMaxAttributeChanged()
+void RangeInputType::sanitizeValueInResponseToMinOrMaxAttributeChange()
 {
-    InputType::minOrMaxAttributeChanged();
-
-    // Sanitize the value.
     if (element()->hasDirtyValue())
         element()->setValue(element()->value());
 
-    sliderThumbElementOf(element())->setPositionFromValue();
+    sliderThumbElement()->setPositionFromValue();
 }
 
 void RangeInputType::setValue(const String& value, bool valueChanged, TextFieldEventBehavior eventBehavior)
@@ -297,7 +294,7 @@
     if (!valueChanged)
         return;
 
-    sliderThumbElementOf(element())->setPositionFromValue();
+    sliderThumbElement()->setPositionFromValue();
 }
 
 String RangeInputType::fallbackValue() const
@@ -317,20 +314,20 @@
     return InputType::themeSupportsDataListUI(this);
 }
 
-HTMLElement* RangeInputType::sliderThumbElement() const
+inline SliderThumbElement* RangeInputType::sliderThumbElement() const
 {
-    return sliderThumbElementOf(element());
+    return toSliderThumbElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb()));
 }
 
-HTMLElement* RangeInputType::sliderTrackElement() const
+inline Element* RangeInputType::sliderTrackElement() const
 {
-    return sliderTrackElementOf(element());
+    return element()->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
 }
 
 void RangeInputType::listAttributeTargetChanged()
 {
     m_tickMarkValuesDirty = true;
-    HTMLElement* sliderTrackElement = sliderTrackElementOf(element());
+    Element* sliderTrackElement = this->sliderTrackElement();
     if (sliderTrackElement->renderer())
         sliderTrackElement->renderer()->setNeedsLayout();
 }
diff --git a/Source/core/html/RangeInputType.h b/Source/core/html/RangeInputType.h
index d08863e..a280758 100644
--- a/Source/core/html/RangeInputType.h
+++ b/Source/core/html/RangeInputType.h
@@ -44,7 +44,7 @@
 
 private:
     RangeInputType(HTMLInputElement*);
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual bool isRangeControl() const OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual double valueAsDouble() const OVERRIDE;
@@ -62,13 +62,13 @@
     virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE;
     virtual String serialize(const Decimal&) const OVERRIDE;
     virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
-    virtual void minOrMaxAttributeChanged() OVERRIDE;
+    virtual void sanitizeValueInResponseToMinOrMaxAttributeChange() OVERRIDE;
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
     virtual String fallbackValue() const OVERRIDE;
     virtual String sanitizeValue(const String& proposedValue) const OVERRIDE;
     virtual bool shouldRespectListAttribute() OVERRIDE;
-    virtual HTMLElement* sliderThumbElement() const OVERRIDE;
-    virtual HTMLElement* sliderTrackElement() const OVERRIDE;
+    SliderThumbElement* sliderThumbElement() const;
+    Element* sliderTrackElement() const;
     virtual void listAttributeTargetChanged() OVERRIDE;
     void updateTickMarkValues();
     virtual Decimal findClosestTickMarkValue(const Decimal&) OVERRIDE;
diff --git a/Source/core/html/SearchInputType.cpp b/Source/core/html/SearchInputType.cpp
index 3982770..757fa0b 100644
--- a/Source/core/html/SearchInputType.cpp
+++ b/Source/core/html/SearchInputType.cpp
@@ -34,6 +34,7 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/KeyboardEvent.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/InputTypeNames.h"
 #include "core/html/shadow/ShadowElementNames.h"
@@ -56,9 +57,8 @@
     return adoptPtr(new SearchInputType(element));
 }
 
-void SearchInputType::attach()
+void SearchInputType::countUsage()
 {
-    TextFieldInputType::attach();
     observeFeatureIfVisible(UseCounter::InputTypeSearch);
 }
 
@@ -95,8 +95,8 @@
     ASSERT(container);
     ASSERT(textWrapper);
 
-    container->insertBefore(SearchFieldDecorationElement::create(element()->document()), textWrapper, IGNORE_EXCEPTION);
-    container->insertBefore(SearchFieldCancelButtonElement::create(element()->document()), textWrapper->nextSibling(), IGNORE_EXCEPTION);
+    container->insertBefore(SearchFieldDecorationElement::create(element()->document()), textWrapper);
+    container->insertBefore(SearchFieldCancelButtonElement::create(element()->document()), textWrapper->nextSibling());
 }
 
 void SearchInputType::handleKeydownEvent(KeyboardEvent* event)
@@ -150,8 +150,7 @@
 
 void SearchInputType::didSetValueByUserEdit(ValueChangeState state)
 {
-    if (element()->uaShadowElementById(ShadowElementNames::clearButton()))
-        toRenderSearchField(element()->renderer())->updateCancelButtonVisibility();
+    updateCancelButtonVisibility();
 
     // If the incremental attribute is set, then dispatch the search event
     if (searchEventsShouldBeDispatched())
@@ -160,6 +159,23 @@
     TextFieldInputType::didSetValueByUserEdit(state);
 }
 
+void SearchInputType::updateInnerTextValue()
+{
+    BaseTextInputType::updateInnerTextValue();
+    updateCancelButtonVisibility();
+}
+
+void SearchInputType::updateCancelButtonVisibility()
+{
+    Element* button = element()->userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton());
+    if (!button)
+        return;
+    if (element()->value().isEmpty())
+        button->setInlineStyleProperty(CSSPropertyVisibility, CSSValueHidden);
+    else
+        button->removeInlineStyleProperty(CSSPropertyVisibility);
+}
+
 bool SearchInputType::supportsInputModeAttribute() const
 {
     return true;
diff --git a/Source/core/html/SearchInputType.h b/Source/core/html/SearchInputType.h
index 2065c39..c0c122b 100644
--- a/Source/core/html/SearchInputType.h
+++ b/Source/core/html/SearchInputType.h
@@ -47,7 +47,7 @@
 
 private:
     SearchInputType(HTMLInputElement*);
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool shouldRespectSpeechAttribute() OVERRIDE;
@@ -57,12 +57,12 @@
     virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
     virtual void didSetValueByUserEdit(ValueChangeState) OVERRIDE;
     virtual bool supportsInputModeAttribute() const OVERRIDE;
+    virtual void updateInnerTextValue() OVERRIDE;
 
     void searchEventTimerFired(Timer<SearchInputType>*);
     bool searchEventsShouldBeDispatched() const;
     void startSearchEventTimer();
-    HTMLElement* searchDecorationElement() const;
-    HTMLElement* cancelButtonElement() const;
+    void updateCancelButtonVisibility();
 
     Timer<SearchInputType> m_searchEventTimer;
 };
diff --git a/Source/core/html/TelephoneInputType.cpp b/Source/core/html/TelephoneInputType.cpp
index 815fd8d..e0f99c6 100644
--- a/Source/core/html/TelephoneInputType.cpp
+++ b/Source/core/html/TelephoneInputType.cpp
@@ -41,9 +41,8 @@
     return adoptPtr(new TelephoneInputType(element));
 }
 
-void TelephoneInputType::attach()
+void TelephoneInputType::countUsage()
 {
-    TextFieldInputType::attach();
     observeFeatureIfVisible(UseCounter::InputTypeTel);
 }
 
diff --git a/Source/core/html/TelephoneInputType.h b/Source/core/html/TelephoneInputType.h
index 264d5a9..054325a 100644
--- a/Source/core/html/TelephoneInputType.h
+++ b/Source/core/html/TelephoneInputType.h
@@ -41,7 +41,7 @@
 
 private:
     TelephoneInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool shouldRespectSpeechAttribute() OVERRIDE;
     virtual bool isTelephoneField() const OVERRIDE;
diff --git a/Source/core/html/TextFieldInputType.cpp b/Source/core/html/TextFieldInputType.cpp
index 9b127b0..a407555 100644
--- a/Source/core/html/TextFieldInputType.cpp
+++ b/Source/core/html/TextFieldInputType.cpp
@@ -44,6 +44,7 @@
 #include "core/editing/TextIterator.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLInputElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/TextControlInnerElements.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
@@ -64,8 +65,13 @@
 
 TextFieldInputType::~TextFieldInputType()
 {
-    if (m_innerSpinButton)
-        m_innerSpinButton->removeSpinButtonOwner();
+    if (SpinButtonElement* spinButton = spinButtonElement())
+        spinButton->removeSpinButtonOwner();
+}
+
+SpinButtonElement* TextFieldInputType::spinButtonElement() const
+{
+    return toSpinButtonElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
 }
 
 bool TextFieldInputType::shouldShowFocusRingOnMouseFocus() const
@@ -170,8 +176,8 @@
 
 void TextFieldInputType::forwardEvent(Event* event)
 {
-    if (m_innerSpinButton) {
-        m_innerSpinButton->forwardEvent(event);
+    if (SpinButtonElement* spinButton = spinButtonElement()) {
+        spinButton->forwardEvent(event);
         if (event->defaultHandled())
             return;
     }
@@ -238,7 +244,6 @@
 
     ASSERT(!m_innerText);
     ASSERT(!m_innerBlock);
-    ASSERT(!m_innerSpinButton);
 
     Document* document = element()->document();
     bool shouldHaveSpinButton = this->shouldHaveSpinButton();
@@ -246,31 +251,26 @@
 
     m_innerText = TextControlInnerTextElement::create(document);
     if (!createsContainer) {
-        element()->userAgentShadowRoot()->appendChild(m_innerText, IGNORE_EXCEPTION);
+        element()->userAgentShadowRoot()->appendChild(m_innerText);
         return;
     }
 
     ShadowRoot* shadowRoot = element()->userAgentShadowRoot();
     m_container = TextControlInnerContainer::create(document);
     m_container->setPart(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
-    shadowRoot->appendChild(m_container, IGNORE_EXCEPTION);
+    shadowRoot->appendChild(m_container);
 
     m_innerBlock = TextControlInnerElement::create(document);
-    m_innerBlock->appendChild(m_innerText, IGNORE_EXCEPTION);
-    m_container->appendChild(m_innerBlock, IGNORE_EXCEPTION);
+    m_innerBlock->appendChild(m_innerText);
+    m_container->appendChild(m_innerBlock);
 
 #if ENABLE(INPUT_SPEECH)
-    ASSERT(!m_speechButton);
-    if (element()->isSpeechEnabled()) {
-        m_speechButton = InputFieldSpeechButtonElement::create(document);
-        m_container->appendChild(m_speechButton, IGNORE_EXCEPTION);
-    }
+    if (element()->isSpeechEnabled())
+        m_container->appendChild(InputFieldSpeechButtonElement::create(document));
 #endif
 
-    if (shouldHaveSpinButton) {
-        m_innerSpinButton = SpinButtonElement::create(document, *this);
-        m_container->appendChild(m_innerSpinButton, IGNORE_EXCEPTION);
-    }
+    if (shouldHaveSpinButton)
+        m_container->appendChild(SpinButtonElement::create(document, *this));
 }
 
 HTMLElement* TextFieldInputType::containerElement() const
@@ -289,18 +289,6 @@
     return m_innerText.get();
 }
 
-HTMLElement* TextFieldInputType::innerSpinButtonElement() const
-{
-    return m_innerSpinButton.get();
-}
-
-#if ENABLE(INPUT_SPEECH)
-HTMLElement* TextFieldInputType::speechButtonElement() const
-{
-    return m_speechButton.get();
-}
-#endif
-
 HTMLElement* TextFieldInputType::placeholderElement() const
 {
     return m_placeholder.get();
@@ -312,12 +300,8 @@
     m_innerText.clear();
     m_placeholder.clear();
     m_innerBlock.clear();
-#if ENABLE(INPUT_SPEECH)
-    m_speechButton.clear();
-#endif
-    if (m_innerSpinButton)
-        m_innerSpinButton->removeSpinButtonOwner();
-    m_innerSpinButton.clear();
+    if (SpinButtonElement* spinButton = spinButtonElement())
+        spinButton->removeSpinButtonOwner();
     m_container.clear();
 }
 
@@ -330,14 +314,14 @@
 
 void TextFieldInputType::disabledAttributeChanged()
 {
-    if (m_innerSpinButton)
-        m_innerSpinButton->releaseCapture();
+    if (SpinButtonElement* spinButton = spinButtonElement())
+        spinButton->releaseCapture();
 }
 
 void TextFieldInputType::readonlyAttributeChanged()
 {
-    if (m_innerSpinButton)
-        m_innerSpinButton->releaseCapture();
+    if (SpinButtonElement* spinButton = spinButtonElement())
+        spinButton->releaseCapture();
 }
 
 bool TextFieldInputType::supportsReadOnly() const
@@ -432,7 +416,7 @@
     if (!m_placeholder) {
         m_placeholder = HTMLDivElement::create(element()->document());
         m_placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
-        element()->userAgentShadowRoot()->insertBefore(m_placeholder, m_container ? m_container->nextSibling() : innerTextElement()->nextSibling(), ASSERT_NO_EXCEPTION);
+        element()->userAgentShadowRoot()->insertBefore(m_placeholder, m_container ? m_container->nextSibling() : innerTextElement()->nextSibling(), ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
     }
     m_placeholder->setInnerText(placeholderText, ASSERT_NO_EXCEPTION);
     element()->fixPlaceholderRenderer(m_placeholder.get(), m_container ? m_container.get() : m_innerText.get());
diff --git a/Source/core/html/TextFieldInputType.h b/Source/core/html/TextFieldInputType.h
index fd13350..bc93ea3 100644
--- a/Source/core/html/TextFieldInputType.h
+++ b/Source/core/html/TextFieldInputType.h
@@ -51,10 +51,6 @@
     virtual HTMLElement* containerElement() const OVERRIDE;
     virtual HTMLElement* innerBlockElement() const OVERRIDE;
     virtual HTMLElement* innerTextElement() const OVERRIDE;
-    virtual HTMLElement* innerSpinButtonElement() const OVERRIDE;
-#if ENABLE(INPUT_SPEECH)
-    virtual HTMLElement* speechButtonElement() const OVERRIDE;
-#endif
 
 protected:
     virtual void attach() OVERRIDE;
@@ -101,14 +97,12 @@
     virtual void spinButtonStepDown() OVERRIDE;
     virtual void spinButtonStepUp() OVERRIDE;
 
+    SpinButtonElement* spinButtonElement() const;
+
     RefPtr<HTMLElement> m_container;
     RefPtr<HTMLElement> m_innerBlock;
     RefPtr<HTMLElement> m_innerText;
     RefPtr<HTMLElement> m_placeholder;
-    RefPtr<SpinButtonElement> m_innerSpinButton;
-#if ENABLE(INPUT_SPEECH)
-    RefPtr<HTMLElement> m_speechButton;
-#endif
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/TextInputType.cpp b/Source/core/html/TextInputType.cpp
index cfdfd9a..de0ebdf 100644
--- a/Source/core/html/TextInputType.cpp
+++ b/Source/core/html/TextInputType.cpp
@@ -44,9 +44,8 @@
     return adoptPtr(new TextInputType(element));
 }
 
-void TextInputType::attach()
+void TextInputType::countUsage()
 {
-    TextFieldInputType::attach();
     const AtomicString& type = element()->fastGetAttribute(typeAttr);
     if (equalIgnoringCase(type, InputTypeNames::datetime()))
         observeFeatureIfVisible(UseCounter::InputTypeDateTimeFallback);
diff --git a/Source/core/html/TextInputType.h b/Source/core/html/TextInputType.h
index bb9e6b3..c646636 100644
--- a/Source/core/html/TextInputType.h
+++ b/Source/core/html/TextInputType.h
@@ -41,7 +41,7 @@
 
 private:
     TextInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool shouldRespectSpeechAttribute() OVERRIDE;
     virtual bool supportsInputModeAttribute() const OVERRIDE;
diff --git a/Source/core/html/TimeInputType.cpp b/Source/core/html/TimeInputType.cpp
index 916761c..6a5fdf6 100644
--- a/Source/core/html/TimeInputType.cpp
+++ b/Source/core/html/TimeInputType.cpp
@@ -64,7 +64,7 @@
     return adoptPtr(new TimeInputType(element));
 }
 
-void TimeInputType::attach()
+void TimeInputType::countUsage()
 {
     observeFeatureIfVisible(UseCounter::InputTypeTime);
 }
diff --git a/Source/core/html/TimeInputType.h b/Source/core/html/TimeInputType.h
index 31a968b..1028fcc 100644
--- a/Source/core/html/TimeInputType.h
+++ b/Source/core/html/TimeInputType.h
@@ -48,7 +48,7 @@
 
 private:
     TimeInputType(HTMLInputElement*);
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual Decimal defaultValueForStepUp() const OVERRIDE;
diff --git a/Source/core/html/URLInputType.cpp b/Source/core/html/URLInputType.cpp
index ca8dc54..d8fa418 100644
--- a/Source/core/html/URLInputType.cpp
+++ b/Source/core/html/URLInputType.cpp
@@ -43,9 +43,8 @@
     return adoptPtr(new URLInputType(element));
 }
 
-void URLInputType::attach()
+void URLInputType::countUsage()
 {
-    TextFieldInputType::attach();
     observeFeatureIfVisible(UseCounter::InputTypeURL);
 }
 
diff --git a/Source/core/html/URLInputType.h b/Source/core/html/URLInputType.h
index 1adc39b..439d5e9 100644
--- a/Source/core/html/URLInputType.h
+++ b/Source/core/html/URLInputType.h
@@ -41,7 +41,7 @@
 
 private:
     URLInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool typeMismatchFor(const String&) const OVERRIDE;
     virtual bool typeMismatch() const OVERRIDE;
diff --git a/Source/core/html/WeekInputType.cpp b/Source/core/html/WeekInputType.cpp
index 4676696..eb2bc1f 100644
--- a/Source/core/html/WeekInputType.cpp
+++ b/Source/core/html/WeekInputType.cpp
@@ -56,7 +56,7 @@
     return adoptPtr(new WeekInputType(element));
 }
 
-void WeekInputType::attach()
+void WeekInputType::countUsage()
 {
     observeFeatureIfVisible(UseCounter::InputTypeWeek);
 }
diff --git a/Source/core/html/WeekInputType.h b/Source/core/html/WeekInputType.h
index 5aa3ea7..10818a4 100644
--- a/Source/core/html/WeekInputType.h
+++ b/Source/core/html/WeekInputType.h
@@ -48,7 +48,7 @@
 
 private:
     WeekInputType(HTMLInputElement* element) : BaseWeekInputType(element) { }
-    virtual void attach() OVERRIDE;
+    virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
diff --git a/Source/core/html/canvas/CanvasRenderingContext.cpp b/Source/core/html/canvas/CanvasRenderingContext.cpp
index 71580c9..4f362bc 100644
--- a/Source/core/html/canvas/CanvasRenderingContext.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext.cpp
@@ -26,11 +26,11 @@
 #include "config.h"
 #include "core/html/canvas/CanvasRenderingContext.h"
 
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/canvas/CanvasPattern.h"
-#include "core/loader/cache/ImageResource.h"
 #include "weborigin/SecurityOrigin.h"
 
 namespace WebCore {
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index feff097..f774c4a 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -34,6 +34,7 @@
 #include "core/html/canvas/CanvasRenderingContext2D.h"
 
 #include "CSSPropertyNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
@@ -42,6 +43,7 @@
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLMediaElement.h"
@@ -53,7 +55,6 @@
 #include "core/html/canvas/CanvasPattern.h"
 #include "core/html/canvas/CanvasStyle.h"
 #include "core/html/canvas/DOMPath.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/ImageBitmap.h"
 #include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/FloatQuad.h"
@@ -1308,6 +1309,9 @@
         return;
 
     RefPtr<Image> imageForRendering = bitmap->bitmapImage();
+    if (!imageForRendering)
+        return;
+
     drawImageInternal(imageForRendering.get(), actualSrcRect, actualDstRect, state().m_globalComposite, state().m_globalBlend);
 }
 
@@ -1457,8 +1461,8 @@
     // as that will do a readback to software.
     CanvasRenderingContext* sourceContext = sourceCanvas->renderingContext();
     // FIXME: Implement an accelerated path for drawing from a WebGL canvas to a 2d canvas when possible.
-    if (!isAccelerated() || !sourceContext || !sourceContext->isAccelerated() || !sourceContext->is2d())
-        sourceCanvas->makeRenderingResultsAvailable();
+    if (sourceContext && sourceContext->is3d())
+        sourceContext->paintRenderingResultsToCanvas();
 
     if (rectContainsCanvas(normalizedDstRect)) {
         c->drawImageBuffer(buffer, normalizedDstRect, normalizedSrcRect, state().m_globalComposite, state().m_globalBlend);
@@ -1896,9 +1900,7 @@
 PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::CoordinateSystem coordinateSystem, float sx, float sy, float sw, float sh, ExceptionState& es) const
 {
     if (!canvas()->originClean()) {
-        DEFINE_STATIC_LOCAL(String, consoleMessage, ("Unable to get image data from canvas because the canvas has been tainted by cross-origin data."));
-        canvas()->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError(ExceptionMessages::failedToExecute("getImageData", "CanvasRenderingContext2D", "the canvas has been tainted by cross-origin data."));
         return 0;
     }
 
@@ -2379,16 +2381,33 @@
 
 void CanvasRenderingContext2D::updateFocusRingAccessibility(const Path& path, Element* element)
 {
+    if (!canvas()->renderer())
+        return;
+
     // If accessibility is already enabled in this frame, associate this path's
     // bounding box with the accessible object. Do this even if the element
     // isn't focused because assistive technology might try to explore the object's
     // location before it gets focus.
     if (AXObjectCache* axObjectCache = element->document()->existingAXObjectCache()) {
         if (AccessibilityObject* obj = axObjectCache->getOrCreate(element)) {
+            // Get the bounding rect and apply transformations.
+            FloatRect bounds = m_path.boundingRect();
+            AffineTransform ctm = state().m_transform;
+            FloatRect transformedBounds = ctm.mapRect(bounds);
+            LayoutRect elementRect = LayoutRect(transformedBounds);
+
+            // Offset by the canvas rect and set the bounds of the accessible element.
             IntRect canvasRect = canvas()->renderer()->absoluteBoundingBoxRect();
-            LayoutRect rect = LayoutRect(path.boundingRect());
-            rect.moveBy(canvasRect.location());
-            obj->setElementRect(rect);
+            elementRect.moveBy(canvasRect.location());
+            obj->setElementRect(elementRect);
+
+            // Set the bounds of any ancestor accessible elements, up to the canvas element,
+            // otherwise this element will appear to not be within its parent element.
+            obj = obj->parentObject();
+            while (obj && obj->node() != canvas()) {
+                obj->setElementRect(elementRect);
+                obj = obj->parentObject();
+            }
         }
     }
 }
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index 01e667d..97b2d6d 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -27,8 +27,10 @@
 #include "core/html/canvas/WebGLRenderingContext.h"
 
 #include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLVideoElement.h"
@@ -66,7 +68,6 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
@@ -553,6 +554,8 @@
     , m_numGLErrorsToConsoleAllowed(maxGLErrorsAllowedToConsole)
     , m_multisamplingAllowed(false)
     , m_multisamplingObserverRegistered(false)
+    , m_onePlusMaxEnabledAttribIndex(0)
+    , m_onePlusMaxNonDefaultTextureUnit(0)
 {
     ASSERT(m_context);
     ScriptWrappable::init(this);
@@ -576,32 +579,31 @@
     }
 
     // Register extensions.
-    static const char* unprefixed[] = { "", 0, };
     static const char* webkitPrefix[] = { "WEBKIT_", 0, };
     static const char* bothPrefixes[] = { "", "WEBKIT_", 0, };
 
-    registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, false, false, true, webkitPrefix);
-    registerExtension<OESElementIndexUint>(m_oesElementIndexUint, false, false, false, unprefixed);
-    registerExtension<OESStandardDerivatives>(m_oesStandardDerivatives, false, false, false, unprefixed);
-    registerExtension<OESTextureFloat>(m_oesTextureFloat, false, false, false, unprefixed);
-    registerExtension<OESTextureFloatLinear>(m_oesTextureFloatLinear, false, false, false, unprefixed);
-    registerExtension<OESTextureHalfFloat>(m_oesTextureHalfFloat, false, false, false, unprefixed);
-    registerExtension<OESTextureHalfFloatLinear>(m_oesTextureHalfFloatLinear, false, false, false, unprefixed);
-    registerExtension<OESVertexArrayObject>(m_oesVertexArrayObject, false, false, false, unprefixed);
-    registerExtension<WebGLCompressedTextureATC>(m_webglCompressedTextureATC, false, false, true, webkitPrefix);
-    registerExtension<WebGLCompressedTexturePVRTC>(m_webglCompressedTexturePVRTC, false, false, true, webkitPrefix);
-    registerExtension<WebGLCompressedTextureS3TC>(m_webglCompressedTextureS3TC, false, false, true, bothPrefixes);
-    registerExtension<WebGLDepthTexture>(m_webglDepthTexture, false, false, true, bothPrefixes);
-    registerExtension<WebGLLoseContext>(m_webglLoseContext, false, false, false, bothPrefixes);
+    registerExtension<ANGLEInstancedArrays>(m_angleInstancedArrays);
+    registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, PrefixedExtension, webkitPrefix);
+    registerExtension<OESElementIndexUint>(m_oesElementIndexUint);
+    registerExtension<OESStandardDerivatives>(m_oesStandardDerivatives);
+    registerExtension<OESTextureFloat>(m_oesTextureFloat);
+    registerExtension<OESTextureFloatLinear>(m_oesTextureFloatLinear);
+    registerExtension<OESTextureHalfFloat>(m_oesTextureHalfFloat);
+    registerExtension<OESTextureHalfFloatLinear>(m_oesTextureHalfFloatLinear);
+    registerExtension<OESVertexArrayObject>(m_oesVertexArrayObject);
+    registerExtension<WebGLCompressedTextureATC>(m_webglCompressedTextureATC, PrefixedExtension, webkitPrefix);
+    registerExtension<WebGLCompressedTexturePVRTC>(m_webglCompressedTexturePVRTC, PrefixedExtension, webkitPrefix);
+    registerExtension<WebGLCompressedTextureS3TC>(m_webglCompressedTextureS3TC, PrefixedExtension, bothPrefixes);
+    registerExtension<WebGLDepthTexture>(m_webglDepthTexture, PrefixedExtension, bothPrefixes);
+    registerExtension<WebGLLoseContext>(m_webglLoseContext, ApprovedExtension, bothPrefixes);
 
     // Register draft extensions.
-    registerExtension<ANGLEInstancedArrays>(m_angleInstancedArrays, false, true, false, unprefixed);
-    registerExtension<EXTFragDepth>(m_extFragDepth, false, true, false, unprefixed);
-    registerExtension<WebGLDrawBuffers>(m_webglDrawBuffers, false, true, false, unprefixed);
+    registerExtension<EXTFragDepth>(m_extFragDepth, DraftExtension);
+    registerExtension<WebGLDrawBuffers>(m_webglDrawBuffers, DraftExtension);
 
     // Register privileged extensions.
-    registerExtension<WebGLDebugRendererInfo>(m_webglDebugRendererInfo, true, false, false, unprefixed);
-    registerExtension<WebGLDebugShaders>(m_webglDebugShaders, true, false, false, unprefixed);
+    registerExtension<WebGLDebugRendererInfo>(m_webglDebugRendererInfo, PrivilegedExtension);
+    registerExtension<WebGLDebugShaders>(m_webglDebugShaders, PrivilegedExtension);
 }
 
 void WebGLRenderingContext::initializeNewContext()
@@ -683,10 +685,8 @@
 void WebGLRenderingContext::setupFlags()
 {
     ASSERT(m_context);
-
-    Page* p = canvas()->document()->page();
-    if (p) {
-        m_synthesizedErrorsToConsole = p->settings()->webGLErrorsToConsoleEnabled();
+    if (Page* p = canvas()->document()->page()) {
+        m_synthesizedErrorsToConsole = p->settings().webGLErrorsToConsoleEnabled();
 
         if (!m_multisamplingObserverRegistered && m_requestedAttributes.antialias) {
             m_multisamplingAllowed = m_drawingBuffer->multisample();
@@ -701,9 +701,8 @@
 
 bool WebGLRenderingContext::allowPrivilegedExtensions() const
 {
-    Page* p = canvas()->document()->page();
-    if (p && p->settings())
-        return p->settings()->privilegedWebGLExtensionsEnabled();
+    if (Page* p = canvas()->document()->page())
+        return p->settings().privilegedWebGLExtensionsEnabled();
     return false;
 }
 
@@ -1139,9 +1138,17 @@
         synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindTexture", "invalid target");
         return;
     }
+
     m_context->bindTexture(target, objectOrZero(texture));
-    if (texture)
+    if (texture) {
         texture->setTarget(target, maxLevel);
+        m_onePlusMaxNonDefaultTextureUnit = max(m_activeTextureUnit + 1, m_onePlusMaxNonDefaultTextureUnit);
+    } else {
+        // If the disabled index is the current maximum, trace backwards to find the new max enabled texture index
+        if (m_onePlusMaxNonDefaultTextureUnit == m_activeTextureUnit + 1) {
+            findNewMaxNonDefaultTextureUnit();
+        }
+    }
 
     // Note: previously we used to automatically set the TEXTURE_WRAP_R
     // repeat mode to CLAMP_TO_EDGE for cube map textures, because OpenGL
@@ -1380,7 +1387,7 @@
         synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "compressedTexImage2D", "border not 0");
         return;
     }
-    if (!validateCompressedTexDimensions("compressedTexImage2D", level, width, height, internalformat))
+    if (!validateCompressedTexDimensions("compressedTexImage2D", NotTexSubImage2D, target, level, width, height, internalformat))
         return;
     if (!validateCompressedTexFuncData("compressedTexImage2D", width, height, internalformat, data))
         return;
@@ -1656,17 +1663,27 @@
 {
     if (!deleteObject(texture))
         return;
-    for (size_t i = 0; i < m_textureUnits.size(); ++i) {
+
+    int maxBoundTextureIndex = -1;
+    for (size_t i = 0; i < m_onePlusMaxNonDefaultTextureUnit; ++i) {
         if (texture == m_textureUnits[i].m_texture2DBinding) {
             m_textureUnits[i].m_texture2DBinding = 0;
+            maxBoundTextureIndex = i;
             if (!i)
                 m_drawingBuffer->setTexture2DBinding(0);
         }
-        if (texture == m_textureUnits[i].m_textureCubeMapBinding)
+        if (texture == m_textureUnits[i].m_textureCubeMapBinding) {
             m_textureUnits[i].m_textureCubeMapBinding = 0;
+            maxBoundTextureIndex = i;
+        }
     }
     if (m_framebufferBinding)
         m_framebufferBinding->removeAttachmentFromBoundFramebuffer(texture);
+
+    // If the deleted was bound to the the current maximum index, trace backwards to find the new max texture index
+    if (m_onePlusMaxNonDefaultTextureUnit == maxBoundTextureIndex + 1) {
+        findNewMaxNonDefaultTextureUnit();
+    }
 }
 
 void WebGLRenderingContext::depthFunc(GC3Denum func)
@@ -1736,6 +1753,12 @@
 
     WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(index);
     state.enabled = false;
+
+    // If the disabled index is the current maximum, trace backwards to find the new max enabled attrib index
+    if (m_onePlusMaxEnabledAttribIndex == index + 1) {
+        findNewMaxEnabledAttribIndex();
+    }
+
     m_context->disableVertexAttribArray(index);
 }
 
@@ -1745,7 +1768,7 @@
         return false;
 
     // Look in each enabled vertex attrib and check if they've been bound to a buffer.
-    for (unsigned i = 0; i < m_maxVertexAttribs; ++i) {
+    for (unsigned i = 0; i < m_onePlusMaxEnabledAttribIndex; ++i) {
         const WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(i);
         if (state.enabled
             && (!state.bufferBinding || !state.bufferBinding->object()))
@@ -1854,6 +1877,8 @@
     WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(index);
     state.enabled = true;
 
+    m_onePlusMaxEnabledAttribIndex = max(index + 1, m_onePlusMaxEnabledAttribIndex);
+
     m_context->enableVertexAttribArray(index);
 }
 
@@ -2110,7 +2135,9 @@
 
 bool WebGLRenderingContext::ExtensionTracker::matchesNameWithPrefixes(const String& name) const
 {
-    const char** prefixes = m_prefixes;
+    static const char* unprefixed[] = { "", 0, };
+
+    const char** prefixes = m_prefixes ? m_prefixes : unprefixed;
     for (; *prefixes; ++prefixes) {
         String prefixedName = String(*prefixes) + getExtensionName();
         if (equalIgnoringCase(prefixedName, name)) {
@@ -4278,7 +4305,7 @@
     bool resetActiveUnit = false;
     WebGLTexture::TextureExtensionFlag flag = static_cast<WebGLTexture::TextureExtensionFlag>((m_oesTextureFloatLinear ? WebGLTexture::TextureFloatLinearExtensionEnabled : 0)
         | (m_oesTextureHalfFloatLinear ? WebGLTexture::TextureHalfFloatLinearExtensionEnabled : 0));
-    for (unsigned ii = 0; ii < m_textureUnits.size(); ++ii) {
+    for (unsigned ii = 0; ii < m_onePlusMaxNonDefaultTextureUnit; ++ii) {
         if ((m_textureUnits[ii].m_texture2DBinding.get() && m_textureUnits[ii].m_texture2DBinding->needToUseBlackTexture(flag))
             || (m_textureUnits[ii].m_textureCubeMapBinding.get() && m_textureUnits[ii].m_textureCubeMapBinding->needToUseBlackTexture(flag))) {
             if (ii != m_activeTextureUnit) {
@@ -4556,7 +4583,7 @@
     }
     switch (target) {
     case GraphicsContext3D::TEXTURE_2D:
-        if (level > m_maxTextureLevel) {
+        if (level >= m_maxTextureLevel) {
             synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level out of range");
             return false;
         }
@@ -4567,7 +4594,7 @@
     case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
     case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
     case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
-        if (level > m_maxCubeMapTextureLevel) {
+        if (level >= m_maxCubeMapTextureLevel) {
             synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level out of range");
             return false;
         }
@@ -4578,19 +4605,9 @@
     return true;
 }
 
-bool WebGLRenderingContext::validateTexFuncParameters(const char* functionName,
-                                                      TexFuncValidationFunctionType functionType,
-                                                      GC3Denum target, GC3Dint level,
-                                                      GC3Denum internalformat,
-                                                      GC3Dsizei width, GC3Dsizei height, GC3Dint border,
-                                                      GC3Denum format, GC3Denum type)
+bool WebGLRenderingContext::validateTexFuncDimensions(const char* functionName, TexFuncValidationFunctionType functionType,
+    GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height)
 {
-    // We absolutely have to validate the format and type combination.
-    // The texImage2D entry points taking HTMLImage, etc. will produce
-    // temporary data based on this combination, so it must be legal.
-    if (!validateTexFuncFormatAndType(functionName, format, type, level) || !validateTexFuncLevel(functionName, target, level))
-        return false;
-
     if (width < 0 || height < 0) {
         synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height < 0");
         return false;
@@ -4598,7 +4615,7 @@
 
     switch (target) {
     case GraphicsContext3D::TEXTURE_2D:
-        if (width > m_maxTextureSize || height > m_maxTextureSize) {
+        if (width > (m_maxTextureSize >> level) || height > (m_maxTextureSize >> level)) {
             synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height out of range");
             return false;
         }
@@ -4615,7 +4632,7 @@
         }
         // No need to check height here. For texImage width == height.
         // For texSubImage that will be checked when checking yoffset + height is in range.
-        if (width > m_maxCubeMapTextureSize) {
+        if (width > (m_maxCubeMapTextureSize >> level)) {
             synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height out of range for cube map");
             return false;
         }
@@ -4624,6 +4641,20 @@
         synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid target");
         return false;
     }
+    return true;
+}
+
+bool WebGLRenderingContext::validateTexFuncParameters(const char* functionName, TexFuncValidationFunctionType functionType, GC3Denum target,
+    GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type)
+{
+    // We absolutely have to validate the format and type combination.
+    // The texImage2D entry points taking HTMLImage, etc. will produce
+    // temporary data based on this combination, so it must be legal.
+    if (!validateTexFuncFormatAndType(functionName, format, type, level) || !validateTexFuncLevel(functionName, target, level))
+        return false;
+
+    if (!validateTexFuncDimensions(functionName, functionType, target, level, width, height))
+        return false;
 
     if (format != internalformat) {
         synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "format != internalformat");
@@ -4790,8 +4821,11 @@
     return true;
 }
 
-bool WebGLRenderingContext::validateCompressedTexDimensions(const char* functionName, GC3Dint level, GC3Dsizei width, GC3Dsizei height, GC3Denum format)
+bool WebGLRenderingContext::validateCompressedTexDimensions(const char* functionName, TexFuncValidationFunctionType functionType, GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height, GC3Denum format)
 {
+    if (!validateTexFuncDimensions(functionName, functionType, target, level, width, height))
+        return false;
+
     switch (format) {
     case Extensions3D::COMPRESSED_RGB_S3TC_DXT1_EXT:
     case Extensions3D::COMPRESSED_RGBA_S3TC_DXT1_EXT:
@@ -4836,7 +4870,7 @@
             synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "dimensions out of range");
             return false;
         }
-        return validateCompressedTexDimensions(functionName, level, width, height, format);
+        return validateCompressedTexDimensions(functionName, TexSubImage2D, target, level, width, height, format);
     }
     default:
         return false;
@@ -5073,7 +5107,7 @@
         return false;
     }
     if (wouldTaintOrigin(image)) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the cross-origin image at " + url.elidedString() + " may not be loaded."));
         return false;
     }
     return true;
@@ -5086,7 +5120,7 @@
         return false;
     }
     if (wouldTaintOrigin(canvas)) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "tainted canvases may not be loded."));
         return false;
     }
     return true;
@@ -5099,7 +5133,7 @@
         return false;
     }
     if (wouldTaintOrigin(video)) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the video element contains cross-origin data, and may not be loaded."));
         return false;
     }
     return true;
@@ -5197,7 +5231,7 @@
     }
 
     // Ensure at least one enabled vertex attrib has a divisor of 0.
-    for (unsigned i = 0; i < m_maxVertexAttribs; ++i) {
+    for (unsigned i = 0; i < m_onePlusMaxEnabledAttribIndex; ++i) {
         const WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(i);
         if (state.enabled && !state.divisor)
             return true;
@@ -5522,4 +5556,31 @@
     }
 }
 
+void WebGLRenderingContext::findNewMaxEnabledAttribIndex()
+{
+    // Trace backwards from the current max to find the new max enabled attrib index
+    int startIndex = m_onePlusMaxEnabledAttribIndex - 1;
+    for (int i = startIndex; i >= 0; --i) {
+        if (m_boundVertexArrayObject->getVertexAttribState(i).enabled) {
+            m_onePlusMaxEnabledAttribIndex = i + 1;
+            return;
+        }
+    }
+    m_onePlusMaxEnabledAttribIndex = 0;
+}
+
+void WebGLRenderingContext::findNewMaxNonDefaultTextureUnit()
+{
+    // Trace backwards from the current max to find the new max non-default texture unit
+    int startIndex = m_onePlusMaxNonDefaultTextureUnit - 1;
+    for (int i = startIndex; i >= 0; --i) {
+        if (m_textureUnits[i].m_texture2DBinding
+            || m_textureUnits[i].m_textureCubeMapBinding) {
+            m_onePlusMaxNonDefaultTextureUnit = i + 1;
+            return;
+        }
+    }
+    m_onePlusMaxNonDefaultTextureUnit = 0;
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/canvas/WebGLRenderingContext.h b/Source/core/html/canvas/WebGLRenderingContext.h
index 39aeae7..386bb37 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.h
+++ b/Source/core/html/canvas/WebGLRenderingContext.h
@@ -506,6 +506,12 @@
     bool m_synthesizedErrorsToConsole;
     int m_numGLErrorsToConsoleAllowed;
 
+    bool m_multisamplingAllowed;
+    bool m_multisamplingObserverRegistered;
+
+    GC3Duint m_onePlusMaxEnabledAttribIndex;
+    unsigned long m_onePlusMaxNonDefaultTextureUnit;
+
     // Enabled extension objects.
     RefPtr<ANGLEInstancedArrays> m_angleInstancedArrays;
     RefPtr<EXTFragDepth> m_extFragDepth;
@@ -526,12 +532,19 @@
     RefPtr<WebGLCompressedTextureS3TC> m_webglCompressedTextureS3TC;
     RefPtr<WebGLDepthTexture> m_webglDepthTexture;
 
+    enum ExtensionFlags {
+        ApprovedExtension   = 0x00,
+        DraftExtension      = 0x01,
+        PrivilegedExtension = 0x02,
+        PrefixedExtension   = 0x04,
+    };
+
     class ExtensionTracker {
     public:
-        ExtensionTracker(bool privileged, bool draft, bool prefixed, const char** prefixes)
-            : m_privileged(privileged)
-            , m_draft(draft)
-            , m_prefixed(prefixed)
+        ExtensionTracker(ExtensionFlags flags, const char** prefixes)
+            : m_privileged(flags & PrivilegedExtension)
+            , m_draft(flags & DraftExtension)
+            , m_prefixed(flags & PrefixedExtension)
             , m_prefixes(prefixes)
         {
         }
@@ -572,8 +585,8 @@
     template <typename T>
     class TypedExtensionTracker : public ExtensionTracker {
     public:
-        TypedExtensionTracker(RefPtr<T>& extensionField, bool privileged, bool draft, bool prefixed, const char** prefixes)
-            : ExtensionTracker(privileged, draft, prefixed, prefixes)
+        TypedExtensionTracker(RefPtr<T>& extensionField, ExtensionFlags flags, const char** prefixes)
+            : ExtensionTracker(flags, prefixes)
             , m_extensionField(extensionField)
         {
         }
@@ -620,9 +633,9 @@
     Vector<ExtensionTracker*> m_extensions;
 
     template <typename T>
-    void registerExtension(RefPtr<T>& extensionPtr, bool privileged, bool draft, bool prefixed, const char** prefixes)
+    void registerExtension(RefPtr<T>& extensionPtr, ExtensionFlags flags = ApprovedExtension, const char** prefixes = 0)
     {
-        m_extensions.append(new TypedExtensionTracker<T>(extensionPtr, privileged, draft, prefixed, prefixes));
+        m_extensions.append(new TypedExtensionTracker<T>(extensionPtr, flags, prefixes));
     }
 
     // Errors raised by synthesizeGLError() while the context is lost.
@@ -710,6 +723,11 @@
     bool validateTexFunc(const char* functionName, TexFuncValidationFunctionType, TexFuncValidationSourceType, GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width,
         GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint xoffset, GC3Dint yoffset);
 
+    // Helper function to check input width and height for functions {copy, compressed}Tex{Sub}Image.
+    // Generates GL error and returns false if width or height is invalid.
+    bool validateTexFuncDimensions(const char* functionName, TexFuncValidationFunctionType,
+        GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height);
+
     // Helper function to check input parameters for functions {copy}Tex{Sub}Image.
     // Generates GL error and returns false if parameters are invalid.
     bool validateTexFuncParameters(const char* functionName,
@@ -750,7 +768,7 @@
 
     // Helper function to validate compressed texture dimensions are valid for
     // the given format.
-    bool validateCompressedTexDimensions(const char* functionName, GC3Dint level, GC3Dsizei width, GC3Dsizei height, GC3Denum format);
+    bool validateCompressedTexDimensions(const char* functionName, TexFuncValidationFunctionType, GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height, GC3Denum format);
 
     // Helper function to validate compressed texture dimensions are valid for
     // the given format.
@@ -873,8 +891,9 @@
     void restoreCurrentTexture2D();
 
     virtual void multisamplingChanged(bool);
-    bool m_multisamplingAllowed;
-    bool m_multisamplingObserverRegistered;
+
+    void findNewMaxEnabledAttribIndex();
+    void findNewMaxNonDefaultTextureUnit();
 
     friend class WebGLStateRestorer;
     friend class WebGLRenderingContextEvictionManager;
diff --git a/Source/core/html/parser/HTMLDocumentParser.h b/Source/core/html/parser/HTMLDocumentParser.h
index 1a1e2d7..a305714 100644
--- a/Source/core/html/parser/HTMLDocumentParser.h
+++ b/Source/core/html/parser/HTMLDocumentParser.h
@@ -28,6 +28,7 @@
 
 #include "core/dom/ParserContentPolicy.h"
 #include "core/dom/ScriptableDocumentParser.h"
+#include "core/fetch/ResourceClient.h"
 #include "core/html/parser/BackgroundHTMLInputStream.h"
 #include "core/html/parser/CompactHTMLToken.h"
 #include "core/html/parser/HTMLInputStream.h"
@@ -40,7 +41,6 @@
 #include "core/html/parser/HTMLTreeBuilderSimulator.h"
 #include "core/html/parser/XSSAuditor.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
-#include "core/loader/cache/ResourceClient.h"
 #include "core/platform/text/SegmentedString.h"
 #include "wtf/Deque.h"
 #include "wtf/OwnPtr.h"
diff --git a/Source/core/html/parser/HTMLResourcePreloader.cpp b/Source/core/html/parser/HTMLResourcePreloader.cpp
index 4960d81..1d5317c 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.cpp
+++ b/Source/core/html/parser/HTMLResourcePreloader.cpp
@@ -27,9 +27,9 @@
 #include "core/html/parser/HTMLResourcePreloader.h"
 
 #include "core/dom/Document.h"
+#include "core/fetch/FetchInitiatorInfo.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLImport.h"
-#include "core/loader/cache/FetchInitiatorInfo.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/css/MediaList.h"
 #include "core/css/MediaQueryEvaluator.h"
 #include "core/platform/HistogramSupport.h"
diff --git a/Source/core/html/parser/HTMLResourcePreloader.h b/Source/core/html/parser/HTMLResourcePreloader.h
index 1b94671..75c620d 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.h
+++ b/Source/core/html/parser/HTMLResourcePreloader.h
@@ -26,8 +26,8 @@
 #ifndef HTMLResourcePreloader_h
 #define HTMLResourcePreloader_h
 
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/Resource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/Resource.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/text/TextPosition.h"
 
diff --git a/Source/core/html/parser/HTMLScriptRunner.cpp b/Source/core/html/parser/HTMLScriptRunner.cpp
index 5141c82..9fd7510 100644
--- a/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -32,10 +32,10 @@
 #include "core/dom/IgnoreDestructiveWriteCountIncrementer.h"
 #include "core/dom/Microtask.h"
 #include "core/dom/ScriptLoader.h"
+#include "core/fetch/ScriptResource.h"
 #include "core/html/parser/HTMLInputStream.h"
 #include "core/html/parser/HTMLScriptRunnerHost.h"
 #include "core/html/parser/NestingLevelIncrementer.h"
-#include "core/loader/cache/ScriptResource.h"
 #include "core/page/Frame.h"
 #include "core/platform/NotImplemented.h"
 
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index 47efdac..a4fa294 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -231,9 +231,8 @@
     ASSERT(m_state == Uninitialized);
     m_state = Initialized;
 
-    if (Frame* frame = document->frame())
-        if (Settings* settings = frame->settings())
-            m_isEnabled = settings->xssAuditorEnabled();
+    if (Settings* settings = document->settings())
+        m_isEnabled = settings->xssAuditorEnabled();
 
     if (!m_isEnabled)
         return;
diff --git a/Source/core/html/shadow/DateTimeEditElement.cpp b/Source/core/html/shadow/DateTimeEditElement.cpp
index a8e0222..c50cab9 100644
--- a/Source/core/html/shadow/DateTimeEditElement.cpp
+++ b/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -410,7 +410,7 @@
             element->appendChild(Text::create(m_editElement.document(), String(&rightToLeftMark, 1)));
     }
     element->appendChild(Text::create(m_editElement.document(), text));
-    m_editElement.fieldsWrapperElement()->appendChild(element, ASSERT_NO_EXCEPTION, AttachLazily);
+    m_editElement.fieldsWrapperElement()->appendChild(element);
 }
 
 DateTimeNumericFieldElement::Step DateTimeEditBuilder::createStep(double msPerFieldUnit, double msPerFieldSize) const
@@ -464,7 +464,7 @@
     if (m_fields.size() == m_fields.capacity())
         return;
     m_fields.append(field.get());
-    fieldsWrapperElement()->appendChild(field, ASSERT_NO_EXCEPTION, AttachLazily);
+    fieldsWrapperElement()->appendChild(field);
 }
 
 bool DateTimeEditElement::anyEditableFieldsHaveValues() const
@@ -653,7 +653,7 @@
     if (!firstChild()) {
         RefPtr<HTMLDivElement> element = HTMLDivElement::create(document());
         element->setPart(fieldsWrapperPseudoId);
-        appendChild(element.get(), ASSERT_NO_EXCEPTION, AttachLazily);
+        appendChild(element.get());
     }
     Element* fieldsWrapper = fieldsWrapperElement();
 
diff --git a/Source/core/html/shadow/DateTimeFieldElements.cpp b/Source/core/html/shadow/DateTimeFieldElements.cpp
index fda494d..d9b59c6 100644
--- a/Source/core/html/shadow/DateTimeFieldElements.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElements.cpp
@@ -141,10 +141,9 @@
         return;
     }
 
-    if (dateTimeFieldsState.ampm() == DateTimeFieldsState::AMPMValuePM)
-        setValueAsInteger((hour12 + 12) % 24);
-    else
-        setValueAsInteger(hour12 % 12);
+    const int hour11 = hour12 == 12 ? 0 : hour12;
+    const int hour23 = dateTimeFieldsState.ampm() == DateTimeFieldsState::AMPMValuePM ? hour11 + 12 : hour11;
+    setValueAsInteger(hour23);
 }
 // ----------------------------
 
@@ -256,7 +255,7 @@
 
     const int value = valueAsInteger();
 
-    dateTimeFieldsState.setHour(value ? value % 12 : 12);
+    dateTimeFieldsState.setHour(value % 12 ? value % 12 : 12);
     dateTimeFieldsState.setAMPM(value >= 12 ? DateTimeFieldsState::AMPMValuePM : DateTimeFieldsState::AMPMValueAM);
 }
 
diff --git a/Source/core/html/shadow/HTMLContentElement.cpp b/Source/core/html/shadow/HTMLContentElement.cpp
index b2e81f6..5f5554b 100644
--- a/Source/core/html/shadow/HTMLContentElement.cpp
+++ b/Source/core/html/shadow/HTMLContentElement.cpp
@@ -33,6 +33,7 @@
 #include "core/css/SelectorChecker.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/dom/QualifiedName.h"
+#include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
 namespace WebCore {
diff --git a/Source/core/html/shadow/MediaControlElementTypes.cpp b/Source/core/html/shadow/MediaControlElementTypes.cpp
index 571693f..78b1687 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.cpp
+++ b/Source/core/html/shadow/MediaControlElementTypes.cpp
@@ -53,7 +53,7 @@
     if (!mediaNode || !mediaNode->isElementNode() || !toElement(mediaNode)->isMediaElement())
         return 0;
 
-    return static_cast<HTMLMediaElement*>(mediaNode);
+    return toHTMLMediaElement(mediaNode);
 }
 
 MediaControlElementType mediaControlElementType(Node* node)
diff --git a/Source/core/html/shadow/MediaControlElements.cpp b/Source/core/html/shadow/MediaControlElements.cpp
index 9167b9c..4de6b48 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -751,7 +751,7 @@
 #endif
             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, ASSERT_NO_EXCEPTION, AttachNow);
+                appendChild(displayBox);
             }
 #if ENABLE(WEBVTT_REGIONS)
         } else {
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index d14e0c5..4ab86cd 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -359,7 +359,7 @@
         m_textDisplayContainer->setMediaController(m_mediaController);
 
     // Insert it before the first controller element so it always displays behind the controls.
-    insertBefore(textDisplayContainer.release(), m_panel, IGNORE_EXCEPTION, AttachLazily);
+    insertBefore(textDisplayContainer.release(), m_panel, IGNORE_EXCEPTION);
 }
 
 void MediaControls::showTextTrackDisplay()
diff --git a/Source/core/html/shadow/MediaControlsChromium.cpp b/Source/core/html/shadow/MediaControlsChromium.cpp
index df7e997..33bff6f 100644
--- a/Source/core/html/shadow/MediaControlsChromium.cpp
+++ b/Source/core/html/shadow/MediaControlsChromium.cpp
@@ -73,63 +73,63 @@
 
     RefPtr<MediaControlPlayButtonElement> playButton = MediaControlPlayButtonElement::create(document);
     m_playButton = playButton.get();
-    panel->appendChild(playButton.release(), es, AttachLazily);
+    panel->appendChild(playButton.release(), es);
     if (es.hadException())
         return false;
 
     RefPtr<MediaControlTimelineElement> timeline = MediaControlTimelineElement::create(document, this);
     m_timeline = timeline.get();
-    panel->appendChild(timeline.release(), es, AttachLazily);
+    panel->appendChild(timeline.release(), es);
     if (es.hadException())
         return false;
 
     RefPtr<MediaControlCurrentTimeDisplayElement> currentTimeDisplay = MediaControlCurrentTimeDisplayElement::create(document);
     m_currentTimeDisplay = currentTimeDisplay.get();
     m_currentTimeDisplay->hide();
-    panel->appendChild(currentTimeDisplay.release(), es, AttachLazily);
+    panel->appendChild(currentTimeDisplay.release(), es);
     if (es.hadException())
         return false;
 
     RefPtr<MediaControlTimeRemainingDisplayElement> durationDisplay = MediaControlTimeRemainingDisplayElement::create(document);
     m_durationDisplay = durationDisplay.get();
-    panel->appendChild(durationDisplay.release(), es, AttachLazily);
+    panel->appendChild(durationDisplay.release(), es);
     if (es.hadException())
         return false;
 
     RefPtr<MediaControlPanelMuteButtonElement> panelMuteButton = MediaControlPanelMuteButtonElement::create(document, this);
     m_panelMuteButton = panelMuteButton.get();
-    panel->appendChild(panelMuteButton.release(), es, AttachLazily);
+    panel->appendChild(panelMuteButton.release(), es);
     if (es.hadException())
         return false;
 
     RefPtr<MediaControlPanelVolumeSliderElement> slider = MediaControlPanelVolumeSliderElement::create(document);
     m_volumeSlider = slider.get();
     m_volumeSlider->setClearMutedOnUserInteraction(true);
-    panel->appendChild(slider.release(), es, AttachLazily);
+    panel->appendChild(slider.release(), es);
     if (es.hadException())
         return false;
 
     if (document->page()->theme()->supportsClosedCaptioning()) {
         RefPtr<MediaControlToggleClosedCaptionsButtonElement> toggleClosedCaptionsButton = MediaControlToggleClosedCaptionsButtonElement::create(document, this);
         m_toggleClosedCaptionsButton = toggleClosedCaptionsButton.get();
-        panel->appendChild(toggleClosedCaptionsButton.release(), es, AttachLazily);
+        panel->appendChild(toggleClosedCaptionsButton.release(), es);
         if (es.hadException())
             return false;
     }
 
     RefPtr<MediaControlFullscreenButtonElement> fullscreenButton = MediaControlFullscreenButtonElement::create(document);
     m_fullScreenButton = fullscreenButton.get();
-    panel->appendChild(fullscreenButton.release(), es, AttachLazily);
+    panel->appendChild(fullscreenButton.release(), es);
     if (es.hadException())
         return false;
 
     m_panel = panel.get();
-    enclosure->appendChild(panel.release(), es, AttachLazily);
+    enclosure->appendChild(panel.release(), es);
     if (es.hadException())
         return false;
 
     m_enclosure = enclosure.get();
-    appendChild(enclosure.release(), es, AttachLazily);
+    appendChild(enclosure.release(), es);
     if (es.hadException())
         return false;
 
@@ -218,7 +218,7 @@
 {
     // Insert it before the first controller element so it always displays behind the controls.
     // In the Chromium case, that's the enclosure element.
-    insertBefore(textTrackContainer, m_enclosure, ASSERT_NO_EXCEPTION, AttachLazily);
+    insertBefore(textTrackContainer, m_enclosure);
 }
 
 
diff --git a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp b/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
index 07ff8dd..77adeaf 100644
--- a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
+++ b/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
@@ -55,12 +55,12 @@
     RefPtr<MediaControlOverlayEnclosureElement> overlayEnclosure = MediaControlOverlayEnclosureElement::create(document);
     RefPtr<MediaControlOverlayPlayButtonElement> overlayPlayButton = MediaControlOverlayPlayButtonElement::create(document);
     controls->m_overlayPlayButton = overlayPlayButton.get();
-    overlayEnclosure->appendChild(overlayPlayButton.release(), es, AttachLazily);
+    overlayEnclosure->appendChild(overlayPlayButton.release(), es);
     if (es.hadException())
         return 0;
 
     controls->m_overlayEnclosure = overlayEnclosure.get();
-    controls->appendChild(overlayEnclosure.release(), es, AttachLazily);
+    controls->appendChild(overlayEnclosure.release(), es);
     if (es.hadException())
         return 0;
 
@@ -94,6 +94,6 @@
 void MediaControlsChromiumAndroid::insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement> textTrackContainer)
 {
     // Insert it before the overlay play button so it always displays behind it.
-    m_overlayEnclosure->insertBefore(textTrackContainer, m_overlayPlayButton, ASSERT_NO_EXCEPTION, AttachLazily);
+    m_overlayEnclosure->insertBefore(textTrackContainer, m_overlayPlayButton);
 }
 }
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
index 81b52fb..bcc124f 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
@@ -37,9 +37,9 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/Page.h"
@@ -171,8 +171,8 @@
 
     RefPtr<PasswordGeneratorButtonElement> protector(this);
     if (event->type() == eventNames().clickEvent) {
-        if (ChromeClient* chromeClient = document()->page() ? document()->page()->chrome().client() : 0)
-            chromeClient->openPasswordGenerator(input.get());
+        if (Page* page = document()->page())
+            page->chrome().client().openPasswordGenerator(input.get());
         event->setDefaultHandled();
     }
 
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.h b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
index 2032034..3a3d7c1 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.h
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
@@ -31,8 +31,8 @@
 #ifndef PasswordGeneratorButtonElement_h
 #define PasswordGeneratorButtonElement_h
 
+#include "core/fetch/ResourcePtr.h"
 #include "core/html/HTMLDivElement.h"
-#include "core/loader/cache/ResourcePtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/shadow/ShadowElementNames.cpp b/Source/core/html/shadow/ShadowElementNames.cpp
index 238be25..1c5421a 100644
--- a/Source/core/html/shadow/ShadowElementNames.cpp
+++ b/Source/core/html/shadow/ShadowElementNames.cpp
@@ -65,6 +65,24 @@
     return name;
 }
 
+const AtomicString& sliderThumb()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("thumb", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
+const AtomicString& sliderTrack()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("track", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
+const AtomicString& speechButton()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("speech", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
 }
 
 }
diff --git a/Source/core/html/shadow/ShadowElementNames.h b/Source/core/html/shadow/ShadowElementNames.h
index ed2f49c..6b5e54d 100644
--- a/Source/core/html/shadow/ShadowElementNames.h
+++ b/Source/core/html/shadow/ShadowElementNames.h
@@ -42,6 +42,9 @@
 const AtomicString& clearButton();
 const AtomicString& pickerIndicator();
 const AtomicString& searchDecoration();
+const AtomicString& sliderThumb();
+const AtomicString& sliderTrack();
+const AtomicString& speechButton();
 
 }
 
diff --git a/Source/core/html/shadow/SliderThumbElement.cpp b/Source/core/html/shadow/SliderThumbElement.cpp
index 178307d..0b343b1 100644
--- a/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/Source/core/html/shadow/SliderThumbElement.cpp
@@ -39,6 +39,7 @@
 #include "core/html/HTMLInputElement.h"
 #include "core/html/StepRange.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
 #include "core/rendering/RenderFlexibleBox.h"
@@ -69,26 +70,6 @@
     return sliderStyle->appearance() == SliderVerticalPart;
 }
 
-SliderThumbElement* sliderThumbElementOf(Node* node)
-{
-    RELEASE_ASSERT(node->hasTagName(inputTag));
-    ShadowRoot* shadow = toHTMLInputElement(node)->userAgentShadowRoot();
-    ASSERT(shadow);
-    Node* thumb = shadow->firstChild()->firstChild()->firstChild();
-    ASSERT(thumb);
-    return toSliderThumbElement(thumb);
-}
-
-HTMLElement* sliderTrackElementOf(Node* node)
-{
-    RELEASE_ASSERT(node->hasTagName(inputTag));
-    ShadowRoot* shadow = toHTMLInputElement(node)->userAgentShadowRoot();
-    ASSERT(shadow);
-    Node* track = shadow->firstChild()->firstChild();
-    ASSERT(track);
-    return toHTMLElement(track);
-}
-
 // --------------------------------
 
 RenderSliderThumb::RenderSliderThumb(SliderThumbElement* element)
@@ -171,12 +152,16 @@
         style()->setDirection(LTR);
     }
 
-    RenderBox* thumb = input->sliderThumbElement() ? input->sliderThumbElement()->renderBox() : 0;
-    RenderBox* track = input->sliderTrackElement() ? input->sliderTrackElement()->renderBox() : 0;
+    Element* thumbElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb());
+    Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
+    RenderBox* thumb = thumbElement ? thumbElement->renderBox() : 0;
+    RenderBox* track = trackElement ? trackElement->renderBox() : 0;
+
+    SubtreeLayoutScope layoutScope(this);
     // Force a layout to reset the position of the thumb so the code below doesn't move the thumb to the wrong place.
     // FIXME: Make a custom Render class for the track and move the thumb positioning code there.
     if (track)
-        track->setChildNeedsLayout(MarkOnlyThis);
+        layoutScope.setChildNeedsLayout(track);
 
     RenderFlexibleBox::layout();
 
@@ -210,6 +195,19 @@
 
 // --------------------------------
 
+inline SliderThumbElement::SliderThumbElement(Document* document)
+    : HTMLDivElement(HTMLNames::divTag, document)
+    , m_inDragMode(false)
+{
+}
+
+PassRefPtr<SliderThumbElement> SliderThumbElement::create(Document* document)
+{
+    RefPtr<SliderThumbElement> element = adoptRef(new SliderThumbElement(document));
+    element->setAttribute(idAttr, ShadowElementNames::sliderThumb());
+    return element.release();
+}
+
 void SliderThumbElement::setPositionFromValue()
 {
     // Since the code to calculate position is in the RenderSliderThumb layout
@@ -253,7 +251,7 @@
 void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
 {
     RefPtr<HTMLInputElement> input(hostInput());
-    HTMLElement* trackElement = sliderTrackElementOf(input.get());
+    Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
 
     if (!input->renderer() || !renderBox() || !trackElement->renderBox())
         return;
diff --git a/Source/core/html/shadow/SliderThumbElement.h b/Source/core/html/shadow/SliderThumbElement.h
index 585c1d6..9e8bc8b 100644
--- a/Source/core/html/shadow/SliderThumbElement.h
+++ b/Source/core/html/shadow/SliderThumbElement.h
@@ -73,17 +73,6 @@
     bool m_inDragMode;
 };
 
-inline SliderThumbElement::SliderThumbElement(Document* document)
-    : HTMLDivElement(HTMLNames::divTag, document)
-    , m_inDragMode(false)
-{
-}
-
-inline PassRefPtr<SliderThumbElement> SliderThumbElement::create(Document* document)
-{
-    return adoptRef(new SliderThumbElement(document));
-}
-
 inline PassRefPtr<Element> SliderThumbElement::cloneElementWithoutAttributesAndChildren()
 {
     return create(document());
@@ -95,11 +84,6 @@
     return static_cast<SliderThumbElement*>(node);
 }
 
-// This always return a valid pointer.
-// An assertion fails if the specified node is not a range input.
-SliderThumbElement* sliderThumbElementOf(Node*);
-HTMLElement* sliderTrackElementOf(Node*);
-
 // --------------------------------
 
 class RenderSliderThumb FINAL : public RenderBlock {
diff --git a/Source/core/html/shadow/TextControlInnerElements.cpp b/Source/core/html/shadow/TextControlInnerElements.cpp
index b1ff5c1..7dc3244 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -32,6 +32,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/MouseEvent.h"
+#include "core/dom/NodeRenderStyle.h"
 #include "core/dom/TextEvent.h"
 #include "core/dom/TextEventInputType.h"
 #include "core/html/HTMLInputElement.h"
@@ -40,8 +41,7 @@
 #include "core/page/Frame.h"
 #include "core/page/SpeechInput.h"
 #include "core/page/SpeechInputEvent.h"
-#include "core/rendering/RenderSearchField.h"
-#include "core/rendering/RenderTextControl.h"
+#include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderView.h"
 
 namespace WebCore {
@@ -76,8 +76,23 @@
 
 PassRefPtr<RenderStyle> TextControlInnerElement::customStyleForRenderer()
 {
-    RenderTextControlSingleLine* parentRenderer = toRenderTextControlSingleLine(shadowHost()->renderer());
-    return parentRenderer->createInnerBlockStyle(parentRenderer->style());
+    // FXIME: Move these styles to html.css.
+
+    RefPtr<RenderStyle> innerBlockStyle = RenderStyle::create();
+    innerBlockStyle->inheritFrom(shadowHost()->renderStyle());
+
+    innerBlockStyle->setFlexGrow(1);
+    // min-width: 0; is needed for correct shrinking.
+    // FIXME: Remove this line when https://bugs.webkit.org/show_bug.cgi?id=111790 is fixed.
+    innerBlockStyle->setMinWidth(Length(0, Fixed));
+    innerBlockStyle->setDisplay(BLOCK);
+    innerBlockStyle->setDirection(LTR);
+
+    // We don't want the shadow dom to be editable, so we set this block to
+    // read-only in case the input itself is editable.
+    innerBlockStyle->setUserModify(READ_ONLY);
+
+    return innerBlockStyle.release();
 }
 
 // ---------------------------
@@ -119,8 +134,11 @@
 
 PassRefPtr<RenderStyle> TextControlInnerTextElement::customStyleForRenderer()
 {
-    RenderTextControl* parentRenderer = toRenderTextControl(shadowHost()->renderer());
-    return parentRenderer->createInnerTextStyle(parentRenderer->style());
+    RenderObject* parentRenderer = shadowHost()->renderer();
+    if (!parentRenderer || !parentRenderer->isTextControl())
+        return originalStyleForRenderer();
+    RenderTextControl* textControlRenderer = toRenderTextControl(parentRenderer);
+    return textControlRenderer->createInnerTextStyle(textControlRenderer->style());
 }
 
 // ----------------------------
@@ -159,7 +177,6 @@
     if (input && event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         input->focus();
         input->select();
-        RenderSearchField* renderer = toRenderSearchField(input->renderer());
         event->setDefaultHandled();
     }
 
@@ -273,6 +290,7 @@
 {
     RefPtr<InputFieldSpeechButtonElement> element = adoptRef(new InputFieldSpeechButtonElement(document));
     element->setPart(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
+    element->setAttribute(idAttr, ShadowElementNames::speechButton());
     return element.release();
 }
 
diff --git a/Source/core/html/track/TextTrackCue.cpp b/Source/core/html/track/TextTrackCue.cpp
index 7c42af0..1625698 100644
--- a/Source/core/html/track/TextTrackCue.cpp
+++ b/Source/core/html/track/TextTrackCue.cpp
@@ -506,7 +506,7 @@
             clonedNode = toWebVTTElement(node)->createEquivalentHTMLElement(ownerDocument());
         else
             clonedNode = node->cloneNode(false);
-        parent->appendChild(clonedNode, ASSERT_NO_EXCEPTION);
+        parent->appendChild(clonedNode);
         if (node->isContainerNode())
             copyWebVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode.get()));
     }
@@ -780,7 +780,7 @@
     // Update the two sets containing past and future WebVTT objects.
     RefPtr<DocumentFragment> referenceTree = createCueRenderingTree();
     markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
-    m_cueBackgroundBox->appendChild(referenceTree);
+    m_cueBackgroundBox->appendChild(referenceTree, ASSERT_NO_EXCEPTION);
 }
 
 PassRefPtr<TextTrackCueBox> TextTrackCue::getDisplayTree(const IntSize& videoSize)
@@ -805,7 +805,7 @@
 
     // Note: This is contained by default in m_cueBackgroundBox.
     m_cueBackgroundBox->setPart(cueShadowPseudoId());
-    displayTree->appendChild(m_cueBackgroundBox, ASSERT_NO_EXCEPTION, AttachLazily);
+    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
diff --git a/Source/core/html/track/TextTrackRegion.cpp b/Source/core/html/track/TextTrackRegion.cpp
index 51a91b6..cc59fc8 100644
--- a/Source/core/html/track/TextTrackRegion.cpp
+++ b/Source/core/html/track/TextTrackRegion.cpp
@@ -373,7 +373,7 @@
     double boxHeight = box->getBoundingClientRect()->bottom() - box->getBoundingClientRect()->top();
     float regionBottom = m_regionDisplayTree->getBoundingClientRect()->bottom();
 
-    m_cueContainer->classList()->remove(textTrackCueContainerScrollingClass(), IGNORE_EXCEPTION);
+    m_cueContainer->classList()->remove(textTrackCueContainerScrollingClass(), ASSERT_NO_EXCEPTION);
 
     m_currentTop += boxHeight;
     m_cueContainer->setInlineStyleProperty(CSSPropertyTop, m_currentTop, CSSPrimitiveValue::CSS_PX);
@@ -385,7 +385,7 @@
     if (m_cueContainer->contains(displayBox.get()))
         return;
 
-    m_cueContainer->appendChild(displayBox, ASSERT_NO_EXCEPTION, AttachNow);
+    m_cueContainer->appendChild(displayBox);
     displayLastTextTrackCueBox();
 }
 
@@ -394,20 +394,23 @@
     LOG(Media, "TextTrackRegion::displayLastTextTrackCueBox");
     ASSERT(m_cueContainer);
 
-    // The container needs to be rendered, if it is not empty and the region is not currently scrolling.
-    if (!m_cueContainer->renderer() || !m_cueContainer->childNodeCount() || m_scrollTimer.isActive())
+    // FIXME: This should not be causing recalc styles in a loop to set the "top" css
+    // property to move elements. We should just scroll the text track cues on the
+    // compositor with an animation.
+
+    if (!m_scrollTimer.isActive())
         return;
 
     // If it's a scrolling region, add the scrolling class.
     if (isScrollingRegion())
-        m_cueContainer->classList()->add(textTrackCueContainerScrollingClass(), IGNORE_EXCEPTION);
+        m_cueContainer->classList()->add(textTrackCueContainerScrollingClass(), ASSERT_NO_EXCEPTION);
 
     float regionBottom = m_regionDisplayTree->getBoundingClientRect()->bottom();
 
     // Find first cue that is not entirely displayed and scroll it upwards.
     for (int i = 0; i < m_cueContainer->childNodeCount() && !m_scrollTimer.isActive(); ++i) {
-        float childTop = static_cast<HTMLDivElement*>(m_cueContainer->childNode(i))->getBoundingClientRect()->top();
-        float childBottom = static_cast<HTMLDivElement*>(m_cueContainer->childNode(i))->getBoundingClientRect()->bottom();
+        float childTop = toHTMLDivElement(m_cueContainer->childNode(i))->getBoundingClientRect()->top();
+        float childBottom = toHTMLDivElement(m_cueContainer->childNode(i))->getBoundingClientRect()->bottom();
 
         if (regionBottom >= childBottom)
             continue;
diff --git a/Source/core/inspector/InjectedScriptCanvasModuleSource.js b/Source/core/inspector/InjectedScriptCanvasModuleSource.js
index c4bd77f..00d50cf 100644
--- a/Source/core/inspector/InjectedScriptCanvasModuleSource.js
+++ b/Source/core/inspector/InjectedScriptCanvasModuleSource.js
@@ -185,6 +185,16 @@
     },
 
     /**
+     * @param {string} property
+     * @param {!Object} obj
+     * @return {boolean}
+     */
+    isEnumPropertyName: function(property, obj)
+    {
+        return (/^[A-Z][A-Z0-9_]+$/.test(property) && typeof obj[property] === "number");
+    },
+
+    /**
      * @return {CanvasRenderingContext2D}
      */
     _dummyCanvas2dContext: function()
@@ -199,7 +209,7 @@
     }
 }
 
-/** @typedef {{name: string, value: *, values: (!Array.<TypeUtils.InternalResourceStateDescriptor>|undefined)}} */
+/** @typedef {{name:string, valueIsEnum:(boolean|undefined), value:*, values:(!Array.<TypeUtils.InternalResourceStateDescriptor>|undefined), isArray:(boolean|undefined)}} */
 TypeUtils.InternalResourceStateDescriptor;
 
 /**
@@ -485,6 +495,13 @@
      */
     replay: function(replayableCall, cache)
     {
+        var replayableResult = replayableCall.result();
+        if (replayableResult instanceof ReplayableResource && !cache.has(replayableResult.id())) {
+            var resource = replayableResult.replay(cache);
+            console.assert(resource.calls().length > 0, "Expected create* call for the Resource");
+            return resource.calls()[0];
+        }
+
         var replayObject = ReplayableResource.replay(replayableCall.replayableResource(), cache);
         var replayArgs = replayableCall.args().map(function(obj) {
             return ReplayableResource.replay(obj, cache);
@@ -497,8 +514,9 @@
             var replayFunction = replayObject[replayableCall.functionName()];
             console.assert(typeof replayFunction === "function", "Expected a function to replay");
             replayResult = replayFunction.apply(replayObject, replayArgs);
-            if (replayableCall.result() instanceof ReplayableResource) {
-                var resource = replayableCall.result().replay(cache);
+
+            if (replayableResult instanceof ReplayableResource) {
+                var resource = replayableResult.replay(cache);
                 if (!resource.wrappedObject())
                     resource.setWrappedObject(replayResult);
             }
@@ -513,6 +531,11 @@
         var attachments = replayableCall.attachments();
         if (attachments)
             this._attachments = TypeUtils.cloneObject(attachments);
+
+        var thisResource = Resource.forObject(replayObject);
+        if (thisResource)
+            thisResource.onCallReplayed(this);
+
         return this;
     }
 }
@@ -778,7 +801,7 @@
     },
 
     /**
-     * @return {!Array.<Call>}
+     * @return {!Array.<!Call>}
      */
     calls: function()
     {
@@ -822,6 +845,7 @@
             var pname = statePropertyNames[i];
             result.push({ name: pname, value: proxyObject[pname] });
         }
+        result.push({ name: "context", value: this.contextResource() });
         return result;
     },
 
@@ -911,6 +935,14 @@
     },
 
     /**
+     * @param {!Call} call
+     */
+    onCallReplayed: function(call)
+    {
+        // Ignore by default.
+    },
+
+    /**
      * @param {!Object} object
      */
     _bindObjectToResource: function(object)
@@ -961,7 +993,7 @@
                     proxy[property] = this._wrapCustomFunction(this, wrappedObject, wrappedObject[property], property, customWrapFunction);
                 else
                     proxy[property] = this._wrapFunction(this, wrappedObject, wrappedObject[property], property);
-            } else if (/^[A-Z0-9_]+$/.test(property) && typeof wrappedObject[property] === "number") {
+            } else if (TypeUtils.isEnumPropertyName(property, wrappedObject)) {
                 // Fast access to enums and constants.
                 proxy[property] = wrappedObject[property];
             } else {
@@ -1357,8 +1389,8 @@
      */
     pushBinding: function(target, bindMethodName)
     {
-        if (this._state.BINDING !== target) {
-            this._state.BINDING = target;
+        if (this._state.bindTarget !== target) {
+            this._state.bindTarget = target;
             this.pushCall(new Call(WebGLRenderingContextResource.forObject(this), bindMethodName, [target, this]));
         }
     },
@@ -1379,6 +1411,66 @@
 
 WebGLTextureResource.prototype = {
     /**
+     * @override (overrides @return type)
+     * @return {WebGLTexture}
+     */
+    wrappedObject: function()
+    {
+        return this._wrappedObject;
+    },
+
+    /**
+     * @override
+     * @return {!Array.<TypeUtils.InternalResourceStateDescriptor>}
+     */
+    currentState: function()
+    {
+        var result = [];
+        var glResource = WebGLRenderingContextResource.forObject(this);
+        var gl = glResource.wrappedObject();
+        var texture = this.wrappedObject();
+        if (!gl || !texture)
+            return result;
+        result.push({ name: "isTexture", value: gl.isTexture(texture) });
+        result.push({ name: "context", value: this.contextResource() });
+
+        var target = this._state.bindTarget;
+        if (typeof target !== "number")
+            return result;
+
+        var bindingParameter;
+        switch (target) {
+        case gl.TEXTURE_2D:
+            bindingParameter = gl.TEXTURE_BINDING_2D;
+            break;
+        case gl.TEXTURE_CUBE_MAP:
+            bindingParameter = gl.TEXTURE_BINDING_CUBE_MAP;
+            break;
+        default:
+            console.error("ASSERT_NOT_REACHED: unknown texture target " + target);
+            return result;
+        }
+        result.push({ name: "target", value: target, valueIsEnum: true });
+
+        var oldTexture = /** @type {WebGLTexture} */ (gl.getParameter(bindingParameter));
+        if (oldTexture !== texture)
+            gl.bindTexture(target, texture);
+
+        var textureParameters = [
+            "TEXTURE_MAG_FILTER",
+            "TEXTURE_MIN_FILTER",
+            "TEXTURE_WRAP_S",
+            "TEXTURE_WRAP_T",
+            "TEXTURE_MAX_ANISOTROPY_EXT" // EXT_texture_filter_anisotropic extension
+        ];
+        glResource.queryStateValues(gl.getTexParameter, target, textureParameters, result);
+
+        if (oldTexture !== texture)
+            gl.bindTexture(target, oldTexture);
+        return result;
+    },
+
+    /**
      * @override
      * @param {!Object} data
      * @param {!Cache.<Resource>} cache
@@ -1480,18 +1572,83 @@
 
     /**
      * @override
-     * @param {!Object} data
-     * @param {!Cache.<ReplayableResource>} cache
+     * @return {!Array.<TypeUtils.InternalResourceStateDescriptor>}
      */
-    _populateReplayableData: function(data, cache)
+    currentState: function()
     {
+        /**
+         * @param {!Object} obj
+         * @param {!Array.<TypeUtils.InternalResourceStateDescriptor>} output
+         */
+        function convertToStateDescriptors(obj, output)
+        {
+            for (var pname in obj)
+                output.push({ name: pname, value: obj[pname], valueIsEnum: (pname === "type") });
+        }
+
+        var result = [];
+        var program = this.wrappedObject();
+        if (!program)
+            return result;
         var glResource = WebGLRenderingContextResource.forObject(this);
         var gl = glResource.wrappedObject();
-        var program = this.wrappedObject();
+        var programParameters = ["DELETE_STATUS", "LINK_STATUS", "VALIDATE_STATUS"];
+        glResource.queryStateValues(gl.getProgramParameter, program, programParameters, result);
+        result.push({ name: "getProgramInfoLog", value: gl.getProgramInfoLog(program) });
+        result.push({ name: "isProgram", value: gl.isProgram(program) });
+        result.push({ name: "context", value: this.contextResource() });
 
-        var originalErrors = glResource.getAllErrors();
+        // ATTACHED_SHADERS
+        var callFormatter = CallFormatter.forResource(this);
+        var shaders = gl.getAttachedShaders(program) || [];
+        var shaderDescriptors = [];
+        for (var i = 0, n = shaders.length; i < n; ++i) {
+            var shaderResource = Resource.forObject(shaders[i]);
+            var pname = callFormatter.enumNameForValue(shaderResource.type());
+            shaderDescriptors.push({ name: pname, value: shaderResource });
+        }
+        result.push({ name: "ATTACHED_SHADERS", values: shaderDescriptors, isArray: true });
 
+        // ACTIVE_UNIFORMS
+        var uniformDescriptors = [];
+        var uniforms = this._activeUniforms(true);
+        for (var i = 0, n = uniforms.length; i < n; ++i) {
+            var pname = "" + i;
+            var values = [];
+            convertToStateDescriptors(uniforms[i], values);
+            uniformDescriptors.push({ name: pname, values: values });
+        }
+        result.push({ name: "ACTIVE_UNIFORMS", values: uniformDescriptors, isArray: true });
+
+        // ACTIVE_ATTRIBUTES
+        var attributesCount = /** @type {number} */ (gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES));
+        var attributeDescriptors = [];
+        for (var i = 0; i < attributesCount; ++i) {
+            var activeInfo = gl.getActiveAttrib(program, i);
+            if (!activeInfo)
+                continue;
+            var pname = "" + i;
+            var values = [];
+            convertToStateDescriptors(activeInfo, values);
+            attributeDescriptors.push({ name: pname, values: values });
+        }
+        result.push({ name: "ACTIVE_ATTRIBUTES", values: attributeDescriptors, isArray: true });
+
+        return result;
+    },
+
+    /**
+     * @param {boolean=} includeAllInfo
+     * @return {!Array.<{name:string, type:number, value:*, size:(number|undefined)}>}
+     */
+    _activeUniforms: function(includeAllInfo)
+    {
         var uniforms = [];
+        var program = this.wrappedObject();
+        if (!program)
+            return uniforms;
+
+        var gl = WebGLRenderingContextResource.forObject(this).wrappedObject();
         var uniformsCount = /** @type {number} */ (gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS));
         for (var i = 0; i < uniformsCount; ++i) {
             var activeInfo = gl.getActiveUniform(program, i);
@@ -1501,14 +1658,27 @@
             if (!uniformLocation)
                 continue;
             var value = gl.getUniform(program, uniformLocation);
-            uniforms.push({
-                name: activeInfo.name,
-                type: activeInfo.type,
-                value: value
-            });
+            var item = Object.create(null);
+            item.name = activeInfo.name;
+            item.type = activeInfo.type;
+            item.value = value;
+            if (includeAllInfo)
+                item.size = activeInfo.size;
+            uniforms.push(item);
         }
-        data.uniforms = uniforms;
+        return uniforms;
+    },
 
+    /**
+     * @override
+     * @param {!Object} data
+     * @param {!Cache.<ReplayableResource>} cache
+     */
+    _populateReplayableData: function(data, cache)
+    {
+        var glResource = WebGLRenderingContextResource.forObject(this);
+        var originalErrors = glResource.getAllErrors();
+        data.uniforms = this._activeUniforms();
         glResource.restoreErrors(originalErrors);
     },
 
@@ -1605,6 +1775,15 @@
 
 WebGLShaderResource.prototype = {
     /**
+     * @override (overrides @return type)
+     * @return {WebGLShader}
+     */
+    wrappedObject: function()
+    {
+        return this._wrappedObject;
+    },
+
+    /**
      * @return {number}
      */
     type: function()
@@ -1618,6 +1797,36 @@
 
     /**
      * @override
+     * @return {!Array.<TypeUtils.InternalResourceStateDescriptor>}
+     */
+    currentState: function()
+    {
+        var result = [];
+        var shader = this.wrappedObject();
+        if (!shader)
+            return result;
+        var glResource = WebGLRenderingContextResource.forObject(this);
+        var gl = glResource.wrappedObject();
+        var shaderParameters = ["SHADER_TYPE", "DELETE_STATUS", "COMPILE_STATUS"];
+        glResource.queryStateValues(gl.getShaderParameter, shader, shaderParameters, result);
+        result.push({ name: "getShaderInfoLog", value: gl.getShaderInfoLog(shader) });
+        result.push({ name: "getShaderSource", value: gl.getShaderSource(shader) });
+        result.push({ name: "isShader", value: gl.isShader(shader) });
+        result.push({ name: "context", value: this.contextResource() });
+
+        // getShaderPrecisionFormat
+        var shaderType = this.type();
+        var precisionValues = [];
+        var precisionParameters = ["LOW_FLOAT", "MEDIUM_FLOAT", "HIGH_FLOAT", "LOW_INT", "MEDIUM_INT", "HIGH_INT"];
+        for (var i = 0, pname; pname = precisionParameters[i]; ++i)
+            precisionValues.push({ name: pname, value: gl.getShaderPrecisionFormat(shaderType, gl[pname]) });
+        result.push({ name: "getShaderPrecisionFormat", values: precisionValues });
+
+        return result;
+    },
+
+    /**
+     * @override
      * @param {!Call} call
      */
     pushCall: function(call)
@@ -1643,6 +1852,60 @@
 
 WebGLBufferResource.prototype = {
     /**
+     * @override (overrides @return type)
+     * @return {WebGLBuffer}
+     */
+    wrappedObject: function()
+    {
+        return this._wrappedObject;
+    },
+
+    /**
+     * @override
+     * @return {!Array.<TypeUtils.InternalResourceStateDescriptor>}
+     */
+    currentState: function()
+    {
+        var result = [];
+        var glResource = WebGLRenderingContextResource.forObject(this);
+        var gl = glResource.wrappedObject();
+        var buffer = this.wrappedObject();
+        if (!gl || !buffer)
+            return result;
+        result.push({ name: "isBuffer", value: gl.isBuffer(buffer) });
+        result.push({ name: "context", value: this.contextResource() });
+
+        var target = this._state.bindTarget;
+        if (typeof target !== "number")
+            return result;
+
+        var bindingParameter;
+        switch (target) {
+        case gl.ARRAY_BUFFER:
+            bindingParameter = gl.ARRAY_BUFFER_BINDING;
+            break;
+        case gl.ELEMENT_ARRAY_BUFFER:
+            bindingParameter = gl.ELEMENT_ARRAY_BUFFER_BINDING;
+            break;
+        default:
+            console.error("ASSERT_NOT_REACHED: unknown buffer target " + target);
+            return result;
+        }
+        result.push({ name: "target", value: target, valueIsEnum: true });
+
+        var oldBuffer = /** @type {WebGLBuffer} */ (gl.getParameter(bindingParameter));
+        if (oldBuffer !== buffer)
+            gl.bindBuffer(target, buffer);
+
+        var bufferParameters = ["BUFFER_SIZE", "BUFFER_USAGE"];
+        glResource.queryStateValues(gl.getBufferParameter, target, bufferParameters, result);
+
+        if (oldBuffer !== buffer)
+            gl.bindBuffer(target, oldBuffer);
+        return result;
+    },
+
+    /**
      * @override
      * @param {!Call} call
      */
@@ -1669,6 +1932,50 @@
 
 WebGLFramebufferResource.prototype = {
     /**
+     * @override (overrides @return type)
+     * @return {WebGLFramebuffer}
+     */
+    wrappedObject: function()
+    {
+        return this._wrappedObject;
+    },
+
+    /**
+     * @override
+     * @return {!Array.<TypeUtils.InternalResourceStateDescriptor>}
+     */
+    currentState: function()
+    {
+        var result = [];
+        var framebuffer = this.wrappedObject();
+        if (!framebuffer)
+            return result;
+        var gl = WebGLRenderingContextResource.forObject(this).wrappedObject();
+
+        var oldFramebuffer = /** @type {WebGLFramebuffer} */ (gl.getParameter(gl.FRAMEBUFFER_BINDING));
+        if (oldFramebuffer !== framebuffer)
+            gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+
+        var attachmentParameters = ["COLOR_ATTACHMENT0", "DEPTH_ATTACHMENT", "STENCIL_ATTACHMENT"];
+        var framebufferParameters = ["FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE"];
+        for (var i = 0, attachment; attachment = attachmentParameters[i]; ++i) {
+            var values = [];
+            for (var j = 0, pname; pname = framebufferParameters[j]; ++j) {
+                var value = gl.getFramebufferAttachmentParameter(gl.FRAMEBUFFER, gl[attachment], gl[pname]);
+                value = Resource.forObject(value) || value;
+                values.push({ name: pname, value: value, valueIsEnum: WebGLRenderingContextResource.GetResultIsEnum[pname] });
+            }
+            result.push({ name: attachment, values: values });
+        }
+        result.push({ name: "isFramebuffer", value: gl.isFramebuffer(framebuffer) });
+        result.push({ name: "context", value: this.contextResource() });
+
+        if (oldFramebuffer !== framebuffer)
+            gl.bindFramebuffer(gl.FRAMEBUFFER, oldFramebuffer);
+        return result;
+    },
+
+    /**
      * @override
      * @param {!Call} call
      */
@@ -1694,6 +2001,42 @@
 
 WebGLRenderbufferResource.prototype = {
     /**
+     * @override (overrides @return type)
+     * @return {WebGLRenderbuffer}
+     */
+    wrappedObject: function()
+    {
+        return this._wrappedObject;
+    },
+
+    /**
+     * @override
+     * @return {!Array.<TypeUtils.InternalResourceStateDescriptor>}
+     */
+    currentState: function()
+    {
+        var result = [];
+        var renderbuffer = this.wrappedObject();
+        if (!renderbuffer)
+            return result;
+        var glResource = WebGLRenderingContextResource.forObject(this);
+        var gl = glResource.wrappedObject();
+
+        var oldRenderbuffer = /** @type {WebGLRenderbuffer} */ (gl.getParameter(gl.RENDERBUFFER_BINDING));
+        if (oldRenderbuffer !== renderbuffer)
+            gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);
+
+        var renderbufferParameters = ["RENDERBUFFER_WIDTH", "RENDERBUFFER_HEIGHT", "RENDERBUFFER_INTERNAL_FORMAT", "RENDERBUFFER_RED_SIZE", "RENDERBUFFER_GREEN_SIZE", "RENDERBUFFER_BLUE_SIZE", "RENDERBUFFER_ALPHA_SIZE", "RENDERBUFFER_DEPTH_SIZE", "RENDERBUFFER_STENCIL_SIZE"];
+        glResource.queryStateValues(gl.getRenderbufferParameter, gl.RENDERBUFFER, renderbufferParameters, result);
+        result.push({ name: "isRenderbuffer", value: gl.isRenderbuffer(renderbuffer) });
+        result.push({ name: "context", value: this.contextResource() });
+
+        if (oldRenderbuffer !== renderbuffer)
+            gl.bindRenderbuffer(gl.RENDERBUFFER, oldRenderbuffer);
+        return result;
+    },
+
+    /**
      * @override
      * @param {!Call} call
      */
@@ -1708,6 +2051,122 @@
 
 /**
  * @constructor
+ * @extends {Resource}
+ * @param {!Object} wrappedObject
+ * @param {string} name
+ */
+function WebGLUniformLocationResource(wrappedObject, name)
+{
+    Resource.call(this, wrappedObject, name);
+}
+
+WebGLUniformLocationResource.prototype = {
+    /**
+     * @override (overrides @return type)
+     * @return {WebGLUniformLocation}
+     */
+    wrappedObject: function()
+    {
+        return this._wrappedObject;
+    },
+
+    /**
+     * @return {WebGLProgramResource}
+     */
+    program: function()
+    {
+        var call = this._calls[0];
+        if (call && call.functionName() === "getUniformLocation")
+            return /** @type {WebGLProgramResource} */ (Resource.forObject(call.args()[0]));
+        console.error("ASSERT_NOT_REACHED: Failed to restore WebGLUniformLocation from the log.", call);
+        return null;
+    },
+
+    /**
+     * @return {string}
+     */
+    name: function()
+    {
+        var call = this._calls[0];
+        if (call && call.functionName() === "getUniformLocation")
+            return call.args()[1];
+        console.error("ASSERT_NOT_REACHED: Failed to restore WebGLUniformLocation from the log.", call);
+        return "";
+    },
+
+    /**
+     * @override
+     * @return {!Array.<TypeUtils.InternalResourceStateDescriptor>}
+     */
+    currentState: function()
+    {
+        var result = [];
+        var location = this.wrappedObject();
+        if (!location)
+            return result;
+        var programResource = this.program();
+        var program = programResource && programResource.wrappedObject();
+        if (!program)
+            return result;
+        var gl = WebGLRenderingContextResource.forObject(this).wrappedObject();
+        var uniformValue = gl.getUniform(program, location);
+        var name = this.name();
+        result.push({ name: "name", value: name });
+        result.push({ name: "program", value: programResource });
+        result.push({ name: "value", value: uniformValue });
+        result.push({ name: "context", value: this.contextResource() });
+
+        if (typeof this._type !== "number") {
+            var altName = name + "[0]";
+            var uniformsCount = /** @type {number} */ (gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS));
+            for (var i = 0; i < uniformsCount; ++i) {
+                var activeInfo = gl.getActiveUniform(program, i);
+                if (!activeInfo)
+                    continue;
+                if (activeInfo.name === name || activeInfo.name === altName) {
+                    this._type = activeInfo.type;
+                    this._size = activeInfo.size;
+                    if (activeInfo.name === name)
+                        break;
+                }
+            }
+        }
+        if (typeof this._type === "number")
+            result.push({ name: "type", value: this._type, valueIsEnum: true });
+        if (typeof this._size === "number")
+            result.push({ name: "size", value: this._size });
+
+        return result;
+    },
+
+    /**
+     * @override
+     * @param {!Object} data
+     * @param {!Cache.<ReplayableResource>} cache
+     */
+    _populateReplayableData: function(data, cache)
+    {
+        data.type = this._type;
+        data.size = this._size;
+    },
+
+    /**
+     * @override
+     * @param {!Object} data
+     * @param {!Cache.<Resource>} cache
+     */
+    _doReplayCalls: function(data, cache)
+    {
+        this._type = data.type;
+        this._size = data.size;
+        Resource.prototype._doReplayCalls.call(this, data, cache);
+    },
+
+    __proto__: Resource.prototype
+}
+
+/**
+ * @constructor
  * @extends {ContextResource}
  * @param {!WebGLRenderingContext} glContext
  */
@@ -1716,8 +2175,10 @@
     ContextResource.call(this, glContext, "WebGLRenderingContext");
     /** @type {Object.<number, boolean>} */
     this._customErrors = null;
-    /** @type {!Object.<string, boolean>} */
+    /** @type {!Object.<string, string>} */
     this._extensions = {};
+    /** @type {!Object.<string, number>} */
+    this._extensionEnums = {};
 }
 
 /**
@@ -1771,6 +2232,7 @@
     "DEPTH_RANGE",
     "DEPTH_WRITEMASK",
     "ELEMENT_ARRAY_BUFFER_BINDING",
+    "FRAGMENT_SHADER_DERIVATIVE_HINT_OES", // OES_standard_derivatives extension
     "FRAMEBUFFER_BINDING",
     "FRONT_FACE",
     "GENERATE_MIPMAP_HINT",
@@ -1801,10 +2263,56 @@
     "UNPACK_COLORSPACE_CONVERSION_WEBGL",
     "UNPACK_FLIP_Y_WEBGL",
     "UNPACK_PREMULTIPLY_ALPHA_WEBGL",
+    "VERTEX_ARRAY_BINDING_OES", // OES_vertex_array_object extension
     "VIEWPORT"
 ];
 
 /**
+ * True for those enums that return also an enum via a getter API method (e.g. getParameter, getShaderParameter, etc.).
+ * @const
+ * @type {!Object.<string, boolean>}
+ */
+WebGLRenderingContextResource.GetResultIsEnum = TypeUtils.createPrefixedPropertyNamesSet([
+    // gl.getParameter()
+    "ACTIVE_TEXTURE",
+    "BLEND_DST_ALPHA",
+    "BLEND_DST_RGB",
+    "BLEND_EQUATION_ALPHA",
+    "BLEND_EQUATION_RGB",
+    "BLEND_SRC_ALPHA",
+    "BLEND_SRC_RGB",
+    "CULL_FACE_MODE",
+    "DEPTH_FUNC",
+    "FRONT_FACE",
+    "GENERATE_MIPMAP_HINT",
+    "FRAGMENT_SHADER_DERIVATIVE_HINT_OES",
+    "STENCIL_BACK_FAIL",
+    "STENCIL_BACK_FUNC",
+    "STENCIL_BACK_PASS_DEPTH_FAIL",
+    "STENCIL_BACK_PASS_DEPTH_PASS",
+    "STENCIL_FAIL",
+    "STENCIL_FUNC",
+    "STENCIL_PASS_DEPTH_FAIL",
+    "STENCIL_PASS_DEPTH_PASS",
+    "UNPACK_COLORSPACE_CONVERSION_WEBGL",
+    // gl.getBufferParameter()
+    "BUFFER_USAGE",
+    // gl.getFramebufferAttachmentParameter()
+    "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",
+    // gl.getRenderbufferParameter()
+    "RENDERBUFFER_INTERNAL_FORMAT",
+    // gl.getTexParameter()
+    "TEXTURE_MAG_FILTER",
+    "TEXTURE_MIN_FILTER",
+    "TEXTURE_WRAP_S",
+    "TEXTURE_WRAP_T",
+    // gl.getShaderParameter()
+    "SHADER_TYPE",
+    // gl.getVertexAttrib()
+    "VERTEX_ATTRIB_ARRAY_TYPE"
+]);
+
+/**
  * @const
  * @type {!Object.<string, boolean>}
  */
@@ -1921,11 +2429,51 @@
 
     /**
      * @param {string} name
+     * @param {Object} obj
      */
-    addExtension: function(name)
+    registerWebGLExtension: function(name, obj)
     {
         // FIXME: Wrap OES_vertex_array_object extension.
-        this._extensions[name.toLowerCase()] = true;
+        var lowerName = name.toLowerCase();
+        if (obj && !this._extensions[lowerName]) {
+            this._extensions[lowerName] = name;
+            for (var property in obj) {
+                if (TypeUtils.isEnumPropertyName(property, obj))
+                    this._extensionEnums[property] = /** @type {number} */ (obj[property]);
+            }
+        }
+    },
+
+    /**
+     * @param {string} name
+     * @return {number|undefined}
+     */
+    _enumValueForName: function(name)
+    {
+        if (typeof this._extensionEnums[name] === "number")
+            return this._extensionEnums[name];
+        var gl = this.wrappedObject();
+        return (typeof gl[name] === "number" ? gl[name] : undefined);
+    },
+
+    /**
+     * @param {function(this:WebGLRenderingContext, T, number):*} func
+     * @param {T} targetOrWebGLObject
+     * @param {!Array.<string>} pnames
+     * @param {!Array.<TypeUtils.InternalResourceStateDescriptor>} output
+     * @template T
+     */
+    queryStateValues: function(func, targetOrWebGLObject, pnames, output)
+    {
+        var gl = this.wrappedObject();
+        for (var i = 0, pname; pname = pnames[i]; ++i) {
+            var enumValue = this._enumValueForName(pname);
+            if (typeof enumValue !== "number")
+                continue;
+            var value = func.call(gl, targetOrWebGLObject, enumValue);
+            value = Resource.forObject(value) || value;
+            output.push({ name: pname, value: value, valueIsEnum: WebGLRenderingContextResource.GetResultIsEnum[pname] });
+        }
     },
 
     /**
@@ -1941,9 +2489,10 @@
         function convertToStateDescriptors(obj, output)
         {
             for (var pname in obj)
-                output.push({ name: pname, value: obj[pname] });
+                output.push({ name: pname, value: obj[pname], valueIsEnum: WebGLRenderingContextResource.GetResultIsEnum[pname] });
         }
 
+        var gl = this.wrappedObject();
         var glState = this._internalCurrentState(null);
 
         // VERTEX_ATTRIB_ARRAYS
@@ -1968,13 +2517,30 @@
 
         var result = [];
         convertToStateDescriptors(glState, result);
-        result.push({ name: "VERTEX_ATTRIB_ARRAYS[" + vertexAttribStates.length + "]", values: vertexAttribStates });
-        result.push({ name: "TEXTURE_UNITS[" + textureUnits.length + "]", values: textureUnits });
+        result.push({ name: "VERTEX_ATTRIB_ARRAYS", values: vertexAttribStates, isArray: true });
+        result.push({ name: "TEXTURE_UNITS", values: textureUnits, isArray: true });
+
+        var textureBindingParameters = ["TEXTURE_BINDING_2D", "TEXTURE_BINDING_CUBE_MAP"];
+        for (var i = 0, pname; pname = textureBindingParameters[i]; ++i) {
+            var value = gl.getParameter(gl[pname]);
+            value = Resource.forObject(value) || value;
+            result.push({ name: pname, value: value });
+        }
+
+        // ENABLED_EXTENSIONS
+        var enabledExtensions = [];
+        for (var lowerName in this._extensions) {
+            var pname = this._extensions[lowerName];
+            var value = gl.getExtension(pname);
+            value = Resource.forObject(value) || value;
+            enabledExtensions.push({ name: pname, value: value });
+        }
+        result.push({ name: "ENABLED_EXTENSIONS", values: enabledExtensions, isArray: true });
+
         return result;
     },
 
     /**
-     * @override
      * @param {?Cache.<ReplayableResource>} cache
      * @return {!Object.<string, *>}
      */
@@ -1997,20 +2563,33 @@
         WebGLRenderingContextResource.GLCapabilities.forEach(function(parameter) {
             glState[parameter] = gl.isEnabled(gl[parameter]);
         });
-        WebGLRenderingContextResource.StateParameters.forEach(function(parameter) {
-            glState[parameter] = maybeToReplayable(gl.getParameter(gl[parameter]));
-        });
+        for (var i = 0, pname; pname = WebGLRenderingContextResource.StateParameters[i]; ++i) {
+            var enumValue = this._enumValueForName(pname);
+            if (typeof enumValue === "number")
+                glState[pname] = maybeToReplayable(gl.getParameter(enumValue));
+        }
 
         // VERTEX_ATTRIB_ARRAYS
         var maxVertexAttribs = /** @type {number} */ (gl.getParameter(gl.MAX_VERTEX_ATTRIBS));
-        var vertexAttribParameters = ["VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", "VERTEX_ATTRIB_ARRAY_ENABLED", "VERTEX_ATTRIB_ARRAY_SIZE", "VERTEX_ATTRIB_ARRAY_STRIDE", "VERTEX_ATTRIB_ARRAY_TYPE", "VERTEX_ATTRIB_ARRAY_NORMALIZED", "CURRENT_VERTEX_ATTRIB"];
+        var vertexAttribParameters = [
+            "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",
+            "VERTEX_ATTRIB_ARRAY_ENABLED",
+            "VERTEX_ATTRIB_ARRAY_SIZE",
+            "VERTEX_ATTRIB_ARRAY_STRIDE",
+            "VERTEX_ATTRIB_ARRAY_TYPE",
+            "VERTEX_ATTRIB_ARRAY_NORMALIZED",
+            "CURRENT_VERTEX_ATTRIB",
+            "VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE" // ANGLE_instanced_arrays extension
+        ];
         var vertexAttribStates = [];
-        for (var i = 0; i < maxVertexAttribs; ++i) {
+        for (var index = 0; index < maxVertexAttribs; ++index) {
             var state = Object.create(null);
-            vertexAttribParameters.forEach(function(attribParameter) {
-                state[attribParameter] = maybeToReplayable(gl.getVertexAttrib(i, gl[attribParameter]));
-            });
-            state.VERTEX_ATTRIB_ARRAY_POINTER = gl.getVertexAttribOffset(i, gl.VERTEX_ATTRIB_ARRAY_POINTER);
+            for (var i = 0, pname; pname = vertexAttribParameters[i]; ++i) {
+                var enumValue = this._enumValueForName(pname);
+                if (typeof enumValue === "number")
+                    state[pname] = maybeToReplayable(gl.getVertexAttrib(index, enumValue));
+            }
+            state.VERTEX_ATTRIB_ARRAY_POINTER = gl.getVertexAttribOffset(index, gl.VERTEX_ATTRIB_ARRAY_POINTER);
             vertexAttribStates.push(state);
         }
         glState.VERTEX_ATTRIB_ARRAYS = vertexAttribStates;
@@ -2044,6 +2623,7 @@
         data.originalCanvas = gl.canvas;
         data.originalContextAttributes = gl.getContextAttributes();
         data.extensions = TypeUtils.cloneObject(this._extensions);
+        data.extensionEnums = TypeUtils.cloneObject(this._extensionEnums);
         data.glState = this._internalCurrentState(cache);
     },
 
@@ -2056,6 +2636,7 @@
     {
         this._customErrors = null;
         this._extensions = TypeUtils.cloneObject(data.extensions) || {};
+        this._extensionEnums = TypeUtils.cloneObject(data.extensionEnums) || {};
 
         var canvas = data.originalCanvas.cloneNode(true);
         var replayContext = null;
@@ -2103,6 +2684,10 @@
         gl.hint(gl.GENERATE_MIPMAP_HINT, glState.GENERATE_MIPMAP_HINT);
         gl.lineWidth(glState.LINE_WIDTH);
 
+        var enumValue = this._enumValueForName("FRAGMENT_SHADER_DERIVATIVE_HINT_OES");
+        if (typeof enumValue === "number")
+            gl.hint(enumValue, glState.FRAGMENT_SHADER_DERIVATIVE_HINT_OES);
+
         WebGLRenderingContextResource.PixelStoreParameters.forEach(function(parameter) {
             gl.pixelStorei(gl[parameter], glState[parameter]);
         });
@@ -2210,6 +2795,30 @@
 
     /**
      * @override
+     * @param {!Call} call
+     */
+    onCallReplayed: function(call)
+    {
+        var functionName = call.functionName();
+        var args = call.args();
+        switch (functionName) {
+        case "bindBuffer":
+        case "bindFramebuffer":
+        case "bindRenderbuffer":
+        case "bindTexture":
+            // Update BINDING state for Resources in the replay world.
+            var resource = Resource.forObject(args[1]);
+            if (resource)
+                resource.pushBinding(args[0], functionName);
+            break;
+        case "getExtension":
+            this.registerWebGLExtension(args[0], /** @type {Object} */ (call.result()));
+            break;
+        }
+    },
+
+    /**
+     * @override
      * @return {!Object.<string, Function>}
      */
     _customWrapFunctions: function()
@@ -2224,7 +2833,7 @@
             wrapFunctions["createTexture"] = Resource.WrapFunction.resourceFactoryMethod(WebGLTextureResource, "WebGLTexture");
             wrapFunctions["createFramebuffer"] = Resource.WrapFunction.resourceFactoryMethod(WebGLFramebufferResource, "WebGLFramebuffer");
             wrapFunctions["createRenderbuffer"] = Resource.WrapFunction.resourceFactoryMethod(WebGLRenderbufferResource, "WebGLRenderbuffer");
-            wrapFunctions["getUniformLocation"] = Resource.WrapFunction.resourceFactoryMethod(Resource, "WebGLUniformLocation");
+            wrapFunctions["getUniformLocation"] = Resource.WrapFunction.resourceFactoryMethod(WebGLUniformLocationResource, "WebGLUniformLocation");
 
             /**
              * @param {string} methodName
@@ -2294,7 +2903,7 @@
              */
             wrapFunctions["getExtension"] = function(name)
             {
-                this._resource.addExtension(name);
+                this._resource.registerWebGLExtension(name, this.result());
             }
 
             //
@@ -2340,6 +2949,7 @@
              */
             wrapFunctions["bindBuffer"] = wrapFunctions["bindFramebuffer"] = wrapFunctions["bindRenderbuffer"] = function(target, obj)
             {
+                this._resource.currentBinding(target); // To call WebGLBoundResource.prototype.pushBinding().
                 this._resource._registerBoundResource("__bindBuffer_" + target, obj);
             }
             /**
@@ -2349,6 +2959,7 @@
              */
             wrapFunctions["bindTexture"] = function(target, obj)
             {
+                this._resource.currentBinding(target); // To call WebGLBoundResource.prototype.pushBinding().
                 var gl = /** @type {WebGLRenderingContext} */ (this._originalObject);
                 var currentTextureBinding = /** @type {number} */ (gl.getParameter(gl.ACTIVE_TEXTURE));
                 this._resource._registerBoundResource("__bindTexture_" + target + "_" + currentTextureBinding, obj);
@@ -2497,6 +3108,7 @@
         var state = this._internalCurrentState(null);
         for (var pname in state)
             result.push({ name: pname, value: state[pname] });
+        result.push({ name: "context", value: this.contextResource() });
         return result;
     },
 
@@ -2816,31 +3428,36 @@
 CallFormatter.prototype = {
     /**
      * @param {!ReplayableCall} replayableCall
+     * @param {string=} objectGroup
      * @return {!Object}
      */
-    formatCall: function(replayableCall)
+    formatCall: function(replayableCall, objectGroup)
     {
         var result = {};
         var functionName = replayableCall.functionName();
         if (functionName) {
             result.functionName = functionName;
-            result.arguments = replayableCall.args().map(this.formatValue.bind(this));
+            result.arguments = [];
+            var args = replayableCall.args();
+            for (var i = 0, n = args.length; i < n; ++i)
+                result.arguments.push(this.formatValue(args[i], objectGroup));
             if (replayableCall.result() !== undefined)
-                result.result = this.formatValue(replayableCall.result());
+                result.result = this.formatValue(replayableCall.result(), objectGroup);
             if (this._drawingMethodNames[functionName])
                 result.isDrawingCall = true;
         } else {
             result.property = replayableCall.propertyName();
-            result.value = this.formatValue(replayableCall.propertyValue());
+            result.value = this.formatValue(replayableCall.propertyValue(), objectGroup);
         }
         return result;
     },
 
     /**
      * @param {*} value
+     * @param {string=} objectGroup
      * @return {!CanvasAgent.CallArgument}
      */
-    formatValue: function(value)
+    formatValue: function(value, objectGroup)
     {
         if (value instanceof Resource || value instanceof ReplayableResource) {
             return {
@@ -2849,31 +3466,70 @@
             };
         }
 
-        var remoteObject = injectedScript.wrapObject(value, "", true, false);
+        var remoteObject = injectedScript.wrapObject(value, objectGroup || "", true, false);
+        var description = remoteObject.description || ("" + value);
+
         var result = {
-            description: remoteObject.description || ("" + value),
+            description: description,
             type: /** @type {CanvasAgent.CallArgumentType} */ (remoteObject.type)
         };
         if (remoteObject.subtype)
             result.subtype = /** @type {CanvasAgent.CallArgumentSubtype} */ (remoteObject.subtype);
-        if (remoteObject.objectId)
-            injectedScript.releaseObject(remoteObject.objectId);
+        if (remoteObject.objectId) {
+            if (objectGroup)
+                result.remoteObject = remoteObject;
+            else
+                injectedScript.releaseObject(remoteObject.objectId);
+        }
         return result;
     },
 
     /**
+     * @param {string} name
+     * @return {?string}
+     */
+    enumValueForName: function(name)
+    {
+        return null;
+    },
+
+    /**
+     * @param {number} value
+     * @param {Array.<string>=} options
+     * @return {?string}
+     */
+    enumNameForValue: function(value, options)
+    {
+        return null;
+    },
+
+    /**
      * @param {!Array.<TypeUtils.InternalResourceStateDescriptor>} descriptors
+     * @param {string=} objectGroup
      * @return {!Array.<!CanvasAgent.ResourceStateDescriptor>}
      */
-    convertResourceStateDescriptors: function(descriptors)
+    formatResourceStateDescriptors: function(descriptors, objectGroup)
     {
         var result = [];
         for (var i = 0, n = descriptors.length; i < n; ++i) {
             var d = descriptors[i];
+            var item;
             if (d.values)
-                result.push({ name: d.name, values: this.convertResourceStateDescriptors(d.values) });
-            else
-                result.push({ name: d.name, value: this.formatValue(d.value) });
+                item = { name: d.name, values: this.formatResourceStateDescriptors(d.values, objectGroup) };
+            else {
+                item = { name: d.name, value: this.formatValue(d.value, objectGroup) };
+                if (d.valueIsEnum && typeof d.value === "number") {
+                    var enumName = this.enumNameForValue(d.value);
+                    if (enumName)
+                        item.value.enumName = enumName;
+                }
+            }
+            var enumValue = this.enumValueForName(d.name);
+            if (enumValue)
+                item.enumValueForName = enumValue;
+            if (d.isArray)
+                item.isArray = true;
+            result.push(item);
         }
         return result;
     }
@@ -2996,11 +3652,12 @@
     /**
      * @override
      * @param {!ReplayableCall} replayableCall
+     * @param {string=} objectGroup
      * @return {!Object}
      */
-    formatCall: function(replayableCall)
+    formatCall: function(replayableCall, objectGroup)
     {
-        var result = CallFormatter.prototype.formatCall.call(this, replayableCall);
+        var result = CallFormatter.prototype.formatCall.call(this, replayableCall, objectGroup);
         if (!result.functionName)
             return result;
         var enumsInfo = this._findEnumsInfo(replayableCall);
@@ -3010,26 +3667,55 @@
         for (var i = 0, n = enumArgsIndexes.length; i < n; ++i) {
             var index = enumArgsIndexes[i];
             var callArgument = result.arguments[index];
-            if (callArgument && !isNaN(callArgument.description))
-                callArgument.description = this._enumValueToString(+callArgument.description, enumsInfo["hints"]) || callArgument.description;
+            this._formatEnumValue(callArgument, enumsInfo["hints"]);
         }
         var bitfieldArgsIndexes = enumsInfo["bitfield"] || [];
         for (var i = 0, n = bitfieldArgsIndexes.length; i < n; ++i) {
             var index = bitfieldArgsIndexes[i];
             var callArgument = result.arguments[index];
-            if (callArgument && !isNaN(callArgument.description))
-                callArgument.description = this._enumBitmaskToString(+callArgument.description, enumsInfo["hints"]) || callArgument.description;
+            this._formatEnumBitmaskValue(callArgument, enumsInfo["hints"]);
         }
-        if (enumsInfo.returnType && result.result) {
-            if (enumsInfo.returnType === "enum")
-                result.result.description = this._enumValueToString(+result.result.description, enumsInfo["hints"]) || result.result.description;
-            else if (enumsInfo.returnType === "bitfield")
-                result.result.description = this._enumBitmaskToString(+result.result.description, enumsInfo["hints"]) || result.result.description;
-        }
+        if (enumsInfo.returnType === "enum")
+            this._formatEnumValue(result.result, enumsInfo["hints"]);
+        else if (enumsInfo.returnType === "bitfield")
+            this._formatEnumBitmaskValue(result.result, enumsInfo["hints"]);
         return result;
     },
 
     /**
+     * @override
+     * @param {string} name
+     * @return {?string}
+     */
+    enumValueForName: function(name)
+    {
+        this._initialize();
+        if (name in this._enumNameToValue)
+            return "" + this._enumNameToValue[name];
+        return null;
+    },
+
+    /**
+     * @override
+     * @param {number} value
+     * @param {Array.<string>=} options
+     * @return {?string}
+     */
+    enumNameForValue: function(value, options)
+    {
+        this._initialize();
+        options = options || [];
+        for (var i = 0, n = options.length; i < n; ++i) {
+            if (this._enumNameToValue[options[i]] === value)
+                return options[i];
+        }
+        var names = this._enumValueToNames[value];
+        if (!names || names.length !== 1)
+            return null;
+        return names[0];
+    },
+
+    /**
      * @param {!ReplayableCall} replayableCall
      * @return {Object}
      */
@@ -3063,34 +3749,30 @@
     },
 
     /**
-     * @param {number} value
+     * @param {?CanvasAgent.CallArgument|undefined} callArgument
      * @param {Array.<string>=} options
-     * @return {string}
      */
-    _enumValueToString: function(value, options)
+    _formatEnumValue: function(callArgument, options)
     {
+        if (!callArgument || isNaN(callArgument.description))
+            return;
         this._initialize();
-        options = options || [];
-        for (var i = 0, n = options.length; i < n; ++i) {
-            if (this._enumNameToValue[options[i]] === value)
-                return options[i];
-        }
-        var names = this._enumValueToNames[value];
-        if (!names || names.length !== 1) {
-            console.warn("Ambiguous WebGL enum names for value " + value + ": " + names);
-            return "";
-        }
-        return names[0];
+        var value = +callArgument.description;
+        var enumName = this.enumNameForValue(value, options);
+        if (enumName)
+            callArgument.enumName = enumName;
     },
 
     /**
-     * @param {number} value
+     * @param {?CanvasAgent.CallArgument|undefined} callArgument
      * @param {Array.<string>=} options
-     * @return {string}
      */
-    _enumBitmaskToString: function(value, options)
+    _formatEnumBitmaskValue: function(callArgument, options)
     {
+        if (!callArgument || isNaN(callArgument.description))
+            return;
         this._initialize();
+        var value = +callArgument.description;
         options = options || [];
         /** @type {!Array.<string>} */
         var result = [];
@@ -3107,13 +3789,13 @@
             var names = this._enumValueToNames[bitValue];
             if (!names || names.length !== 1) {
                 console.warn("Ambiguous WebGL enum names for value " + bitValue + ": " + names);
-                return "";
+                return;
             }
             result.push(names[0]);
             value = nextValue;
         }
         result.sort();
-        return result.join(" | ");
+        callArgument.enumName = result.join(" | ");
     },
 
     _initialize: function()
@@ -3135,7 +3817,7 @@
             if (!obj)
                 return;
             for (var property in obj) {
-                if (/^[A-Z0-9_]+$/.test(property) && typeof obj[property] === "number") {
+                if (TypeUtils.isEnumPropertyName(property, obj)) {
                     var value = /** @type {number} */ (obj[property]);
                     this._enumNameToValue[property] = value;
                     var names = this._enumValueToNames[value];
@@ -3571,6 +4253,7 @@
             this._manager.dropTraceLog(traceLog);
         delete this._traceLogs[id];
         delete this._traceLogPlayers[id];
+        injectedScript.releaseObjectGroup(id);
     },
 
     /**
@@ -3643,6 +4326,8 @@
             return "Error: Trace log with the given ID not found.";
         this._traceLogPlayers[traceLogId] = this._traceLogPlayers[traceLogId] || new TraceLogPlayer(traceLog);
 
+        injectedScript.releaseObjectGroup(traceLogId);
+
         var beforeTime = TypeUtils.now();
         var lastCall = this._traceLogPlayers[traceLogId].stepTo(stepNo);
         var replayTime = Math.max(0, TypeUtils.now() - beforeTime);
@@ -3747,7 +4432,7 @@
         };
         if (resource) {
             result.imageURL = overrideImageURL || resource.toDataURL();
-            result.descriptors = CallFormatter.forResource(resource).convertResourceStateDescriptors(resource.currentState());
+            result.descriptors = CallFormatter.forResource(resource).formatResourceStateDescriptors(resource.currentState(), traceLogId);
         }
         return result;
     },
diff --git a/Source/core/inspector/InjectedScriptSource.js b/Source/core/inspector/InjectedScriptSource.js
index 437ea48..1af5713 100644
--- a/Source/core/inspector/InjectedScriptSource.js
+++ b/Source/core/inspector/InjectedScriptSource.js
@@ -848,7 +848,7 @@
             case 1 /* Node.ELEMENT_NODE */:
                 description += obj.id ? "#" + obj.id : "";
                 var className = obj.className;
-                description += className ? "." + className : "";
+                description += (className && typeof className === "string") ? "." + className : "";
                 break;
             case 10 /*Node.DOCUMENT_TYPE_NODE */:
                 description = "<!DOCTYPE " + description + ">";
@@ -939,7 +939,7 @@
      * @param {Object} object
      * @param {Array.<string>=} firstLevelKeys
      * @param {?Array.<string>=} secondLevelKeys
-     * @return {Object} preview
+     * @return {!RuntimeAgent.ObjectPreview} preview
      */
     _generatePreview: function(object, firstLevelKeys, secondLevelKeys)
     {
@@ -956,20 +956,20 @@
             indexes: isTableRowsRequest ? 1000 : Math.max(100, firstLevelKeysCount)
         };
         for (var o = object; injectedScript._isDefined(o); o = o.__proto__)
-            this._generateProtoPreview(o, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys);
+            this._generateProtoPreview(/** @type {!Object} */ (o), preview, propertiesThreshold, firstLevelKeys, secondLevelKeys);
         return preview;
     },
 
     /**
-     * @param {Object} object
-     * @param {Object} preview
-     * @param {Object} propertiesThreshold
+     * @param {!Object} object
+     * @param {!RuntimeAgent.ObjectPreview} preview
+     * @param {!Object} propertiesThreshold
      * @param {Array.<string>=} firstLevelKeys
      * @param {Array.<string>=} secondLevelKeys
      */
     _generateProtoPreview: function(object, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys)
     {
-        var propertyNames = firstLevelKeys ? firstLevelKeys : Object.keys(/** @type {!Object} */ (object));
+        var propertyNames = firstLevelKeys ? firstLevelKeys : Object.keys(object);
         try {
             for (var i = 0; i < propertyNames.length; ++i) {
                 if (!propertiesThreshold.properties || !propertiesThreshold.indexes) {
@@ -981,7 +981,7 @@
                 if (this.subtype === "array" && name === "length")
                     continue;
 
-                var descriptor = Object.getOwnPropertyDescriptor(/** @type {!Object} */ (object), name);
+                var descriptor = Object.getOwnPropertyDescriptor(object, name);
                 if (!("value" in descriptor) || !descriptor.enumerable) {
                     preview.lossless = false;
                     continue;
@@ -1036,9 +1036,9 @@
     },
 
     /**
-     * @param {Object} preview
-     * @param {Object} property
-     * @param {Object} propertiesThreshold
+     * @param {!RuntimeAgent.ObjectPreview} preview
+     * @param {!Object} property
+     * @param {!Object} propertiesThreshold
      */
     _appendPropertyPreview: function(preview, property, propertiesThreshold)
     {
diff --git a/Source/core/inspector/InspectorAgent.cpp b/Source/core/inspector/InspectorAgent.cpp
index 51436c3..e988353 100644
--- a/Source/core/inspector/InspectorAgent.cpp
+++ b/Source/core/inspector/InspectorAgent.cpp
@@ -130,7 +130,7 @@
 
 void InspectorAgent::reset(ErrorString*)
 {
-    m_inspectedPage->inspectorController()->reconnectFrontend();
+    m_inspectedPage->inspectorController().reconnectFrontend();
 }
 
 void InspectorAgent::domContentLoadedEventFired(Frame* frame)
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index 45205fe..5021fc9 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -58,7 +58,15 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/platform/JSONValues.h"
+#include "core/platform/graphics/Font.h"
+#include "core/platform/graphics/GlyphBuffer.h"
+#include "core/platform/graphics/TextRun.h"
+#include "core/platform/graphics/WidthIterator.h"
+#include "core/rendering/InlineTextBox.h"
+#include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderRegion.h"
+#include "core/rendering/RenderText.h"
+#include "core/rendering/RenderTextFragment.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/HashSet.h"
 #include "wtf/Vector.h"
@@ -1030,15 +1038,74 @@
 
 void InspectorCSSAgent::getComputedStyleForNode(ErrorString* errorString, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSComputedStyleProperty> >& style)
 {
-    Element* element = elementForId(errorString, nodeId);
-    if (!element)
+    Node* node = m_domAgent->assertNode(errorString, nodeId);
+    if (!node)
         return;
 
-    RefPtr<CSSComputedStyleDeclaration> computedStyleInfo = CSSComputedStyleDeclaration::create(element, true);
+    RefPtr<CSSComputedStyleDeclaration> computedStyleInfo = CSSComputedStyleDeclaration::create(node, true);
     RefPtr<InspectorStyle> inspectorStyle = InspectorStyle::create(InspectorCSSId(), computedStyleInfo, 0);
     style = inspectorStyle->buildArrayForComputedStyle();
 }
 
+void InspectorCSSAgent::collectPlatformFontsForRenderer(RenderText* renderer, HashMap<String, int>* fontStats)
+{
+    for (InlineTextBox* box = renderer->firstTextBox(); box; box = box->nextTextBox()) {
+        RenderStyle* style = renderer->style(box->isFirstLineStyle());
+        const Font& font = style->font();
+        TextRun run = box->constructTextRunForInspector(style, font);
+        WidthIterator it(&font, run, 0, false);
+        GlyphBuffer glyphBuffer;
+        it.advance(run.length(), &glyphBuffer);
+        for (int i = 0; i < glyphBuffer.size(); ++i) {
+            String familyName = glyphBuffer.fontDataAt(i)->platformData().fontFamilyName();
+            int value = fontStats->contains(familyName) ? fontStats->get(familyName) : 0;
+            fontStats->set(familyName, value + 1);
+        }
+    }
+}
+
+void InspectorCSSAgent::getPlatformFontsForNode(ErrorString* errorString, int nodeId,
+    RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage> >& platformFontUsage)
+{
+    Node* node = m_domAgent->assertNode(errorString, nodeId);
+    if (!node)
+        return;
+    Vector<Node*> textNodes;
+    if (node->nodeType() == Node::TEXT_NODE) {
+        if (node->renderer())
+            textNodes.append(node);
+    } else {
+        for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+            if (child->nodeType() == Node::TEXT_NODE && child->renderer())
+                textNodes.append(child);
+        }
+    }
+
+    HashMap<String, int> fontStats;
+    for (size_t i = 0; i < textNodes.size(); ++i) {
+        RenderText* renderer = toRenderText(textNodes[i]->renderer());
+        collectPlatformFontsForRenderer(renderer, &fontStats);
+        if (renderer->isTextFragment()) {
+            RenderTextFragment* textFragment = toRenderTextFragment(renderer);
+            if (textFragment->firstLetter()) {
+                RenderObject* firstLetter = textFragment->firstLetter();
+                for (RenderObject* current = firstLetter->firstChild(); current; current = current->nextSibling()) {
+                    if (current->isText())
+                        collectPlatformFontsForRenderer(toRenderText(current), &fontStats);
+                }
+            }
+        }
+    }
+
+    platformFontUsage = TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage>::create();
+    for (HashMap<String, int>::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);
+        platformFontUsage->addItem(platformFont);
+    }
+}
+
 void InspectorCSSAgent::getAllStyleSheets(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSStyleSheetHeader> >& styleInfos)
 {
     styleInfos = TypeBuilder::Array<TypeBuilder::CSS::CSSStyleSheetHeader>::create();
@@ -1468,7 +1535,7 @@
 
         InlineStyleOverrideScope overrideScope(document);
         m_creatingViaInspectorStyleSheet = true;
-        targetNode->appendChild(styleElement, es, AttachLazily);
+        targetNode->appendChild(styleElement, es);
         // 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;
diff --git a/Source/core/inspector/InspectorCSSAgent.h b/Source/core/inspector/InspectorCSSAgent.h
index 8f60701..ea7b7bb 100644
--- a/Source/core/inspector/InspectorCSSAgent.h
+++ b/Source/core/inspector/InspectorCSSAgent.h
@@ -54,6 +54,7 @@
 class MediaList;
 class Node;
 class NodeList;
+class PlatformFontUsage;
 class StyleResolver;
 class UpdateRegionLayoutTask;
 
@@ -125,6 +126,7 @@
     void frameDetachedFromParent(Frame*);
 
     virtual void getComputedStyleForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSComputedStyleProperty> >&);
+    virtual void getPlatformFontsForNode(ErrorString*, int, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage> >&);
     virtual void getInlineStylesForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::CSS::CSSStyle>& inlineStyle, RefPtr<TypeBuilder::CSS::CSSStyle>& attributes);
     virtual void getMatchedStylesForNode(ErrorString*, int nodeId, const bool* includePseudo, const bool* includeInherited, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> >& matchedCSSRules, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches> >& pseudoIdMatches, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::InheritedStyleEntry> >& inheritedEntries);
     virtual void getAllStyleSheets(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSStyleSheetHeader> >& styleSheetInfos);
@@ -166,6 +168,8 @@
     void collectAllStyleSheets(Vector<InspectorStyleSheet*>&);
     void collectStyleSheets(CSSStyleSheet*, Vector<InspectorStyleSheet*>&);
 
+    void collectPlatformFontsForRenderer(RenderText*, HashMap<String, int>*);
+
     InspectorStyleSheet* bindStyleSheet(CSSStyleSheet*);
     String unbindStyleSheet(InspectorStyleSheet*);
     InspectorStyleSheet* viaInspectorStyleSheet(Document*, bool createIfAbsent);
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index a9cb37b..fdb31a5 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -322,6 +322,15 @@
     return m_overlay->highlightedNode();
 }
 
+bool InspectorController::handleGestureEvent(Frame* frame, const PlatformGestureEvent& event)
+{
+    // Overlay should not consume events.
+    m_overlay->handleGestureEvent(event);
+    if (InspectorDOMAgent* domAgent = m_instrumentingAgents->inspectorDOMAgent())
+        return domAgent->handleGestureEvent(frame, event);
+    return false;
+}
+
 bool InspectorController::handleMouseEvent(Frame* frame, const PlatformMouseEvent& event)
 {
     // Overlay should not consume events.
diff --git a/Source/core/inspector/InspectorController.h b/Source/core/inspector/InspectorController.h
index 42f224a..95f0368 100644
--- a/Source/core/inspector/InspectorController.h
+++ b/Source/core/inspector/InspectorController.h
@@ -55,6 +55,7 @@
 class InstrumentingAgents;
 class IntSize;
 class Page;
+class PlatformGestureEvent;
 class PlatformMouseEvent;
 class PlatformTouchEvent;
 class PostWorkerNotificationToFrontendTask;
@@ -94,6 +95,7 @@
     void hideHighlight();
     Node* highlightedNode() const;
 
+    bool handleGestureEvent(Frame*, const PlatformGestureEvent&);
     bool handleMouseEvent(Frame*, const PlatformMouseEvent&);
     bool handleTouchEvent(Frame*, const PlatformTouchEvent&);
 
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index a4f32e2..2cf05dd 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -70,6 +70,7 @@
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
+#include "core/platform/PlatformGestureEvent.h"
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/platform/PlatformTouchEvent.h"
 #include "core/rendering/HitTestResult.h"
@@ -162,6 +163,11 @@
     return node;
 }
 
+static Node* hoveredNodeForEvent(Frame* frame, const PlatformGestureEvent& event, bool ignorePointerEventsNone)
+{
+    return hoveredNodeForPoint(frame, event.position(), ignorePointerEventsNone);
+}
+
 static Node* hoveredNodeForEvent(Frame* frame, const PlatformMouseEvent& event, bool ignorePointerEventsNone)
 {
     return hoveredNodeForPoint(frame, event.position(), ignorePointerEventsNone);
@@ -343,8 +349,7 @@
     m_idToNode.remove(id);
 
     if (node->isFrameOwnerElement()) {
-        const HTMLFrameOwnerElement* frameOwner = static_cast<const HTMLFrameOwnerElement*>(node);
-        Document* contentDocument = frameOwner->contentDocument();
+        Document* contentDocument = toHTMLFrameOwnerElement(node)->contentDocument();
         if (m_domListener)
             m_domListener->didRemoveDocument(contentDocument);
         if (contentDocument)
@@ -1053,6 +1058,19 @@
     return false;
 }
 
+bool InspectorDOMAgent::handleGestureEvent(Frame* frame, const PlatformGestureEvent& event)
+{
+    if (m_searchingForNode == NotSearching || event.type() != PlatformEvent::GestureTap)
+        return false;
+    Node* node = hoveredNodeForEvent(frame, event, false);
+    if (node && m_inspectModeHighlightConfig) {
+        m_overlay->highlightNode(node, 0 /* eventTarget */, *m_inspectModeHighlightConfig);
+        inspect(node);
+        return true;
+    }
+    return false;
+}
+
 bool InspectorDOMAgent::handleTouchEvent(Frame* frame, const PlatformTouchEvent& event)
 {
     if (m_searchingForNode == NotSearching)
@@ -1380,12 +1398,10 @@
         Element* element = toElement(node);
         value->setAttributes(buildArrayForElementAttributes(element));
         if (node->isFrameOwnerElement()) {
-            HTMLFrameOwnerElement* frameOwner = static_cast<HTMLFrameOwnerElement*>(node);
-            Frame* frame = frameOwner->contentFrame();
-            if (frame)
+            HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(node);
+            if (Frame* frame = frameOwner->contentFrame())
                 value->setFrameId(m_pageAgent->frameId(frame));
-            Document* doc = frameOwner->contentDocument();
-            if (doc)
+            if (Document* doc = frameOwner->contentDocument())
                 value->setContentDocument(buildObjectForNode(doc, 0, nodesMap));
         }
 
diff --git a/Source/core/inspector/InspectorDOMAgent.h b/Source/core/inspector/InspectorDOMAgent.h
index e0a0362..6cba33d 100644
--- a/Source/core/inspector/InspectorDOMAgent.h
+++ b/Source/core/inspector/InspectorDOMAgent.h
@@ -60,6 +60,7 @@
 class InspectorState;
 class InstrumentingAgents;
 class Node;
+class PlatformGestureEvent;
 class PlatformTouchEvent;
 class RevalidateStyleAttributeTask;
 class ShadowRoot;
@@ -180,6 +181,7 @@
 
     PassRefPtr<TypeBuilder::Runtime::RemoteObject> resolveNode(Node*, const String& objectGroup);
     bool handleMousePress();
+    bool handleGestureEvent(Frame*, const PlatformGestureEvent&);
     bool handleTouchEvent(Frame*, const PlatformTouchEvent&);
     void handleMouseMove(Frame*, const PlatformMouseEvent&);
 
diff --git a/Source/core/inspector/InspectorDebuggerAgent.cpp b/Source/core/inspector/InspectorDebuggerAgent.cpp
index 9f260a4..2900027 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -34,6 +34,8 @@
 #include "InspectorFrontend.h"
 #include "bindings/v8/ScriptDebugServer.h"
 #include "bindings/v8/ScriptObject.h"
+#include "bindings/v8/ScriptSourceCode.h"
+#include "core/fetch/Resource.h"
 #include "core/inspector/ContentSearchUtils.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptManager.h"
@@ -42,7 +44,6 @@
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/ScriptArguments.h"
 #include "core/inspector/ScriptCallStack.h"
-#include "core/loader/cache/Resource.h"
 #include "core/platform/JSONValues.h"
 #include "core/platform/text/RegularExpression.h"
 #include "wtf/text/WTFString.h"
@@ -236,6 +237,15 @@
     addMessageToConsole(source, type);
 }
 
+String InspectorDebuggerAgent::preprocessEventListener(Frame* frame, const String& source, const String& url, const String& functionName)
+{
+    return scriptDebugServer().preprocessEventListener(frame, source, url, functionName);
+}
+
+PassOwnPtr<ScriptSourceCode> InspectorDebuggerAgent::preprocess(Frame* frame, const ScriptSourceCode& sourceCode)
+{
+    return scriptDebugServer().preprocess(frame, sourceCode);
+}
 
 static PassRefPtr<JSONObject> buildObjectForBreakpointCookie(const String& url, int lineNumber, int columnNumber, const String& condition, bool isRegex, bool isAnti)
 {
diff --git a/Source/core/inspector/InspectorDebuggerAgent.h b/Source/core/inspector/InspectorDebuggerAgent.h
index 04dd19f..e0f583d 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.h
+++ b/Source/core/inspector/InspectorDebuggerAgent.h
@@ -53,6 +53,7 @@
 class ScriptArguments;
 class ScriptCallStack;
 class ScriptDebugServer;
+class ScriptSourceCode;
 class ScriptValue;
 class RegularExpression;
 
@@ -82,6 +83,9 @@
     void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String&, PassRefPtr<ScriptCallStack>, unsigned long);
     void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String&, ScriptState*, PassRefPtr<ScriptArguments>, unsigned long);
 
+    String preprocessEventListener(Frame*, const String& source, const String& url, const String& functionName);
+    PassOwnPtr<ScriptSourceCode> preprocess(Frame*, const ScriptSourceCode&);
+
     // Part of the protocol.
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
@@ -156,7 +160,6 @@
     virtual void unmuteConsole() = 0;
     InjectedScriptManager* injectedScriptManager() { return m_injectedScriptManager; }
     virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) = 0;
-    virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL) = 0;
 
     virtual void enable();
     virtual void disable();
diff --git a/Source/core/inspector/InspectorFrontendHost.cpp b/Source/core/inspector/InspectorFrontendHost.cpp
index 333afc2..634398d 100644
--- a/Source/core/inspector/InspectorFrontendHost.cpp
+++ b/Source/core/inspector/InspectorFrontendHost.cpp
@@ -187,8 +187,7 @@
 
 void InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script)
 {
-    ASSERT(m_frontendPage->inspectorController());
-    m_frontendPage->inspectorController()->setInjectedScriptForOrigin(origin, script);
+    m_frontendPage->inspectorController().setInjectedScriptForOrigin(origin, script);
 }
 
 String InspectorFrontendHost::localizedStringsURL()
@@ -247,8 +246,7 @@
         return;
     }
     RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);
-    ContextMenuController* menuController = m_frontendPage->contextMenuController();
-    menuController->showContextMenu(event, menuProvider);
+    m_frontendPage->contextMenuController().showContextMenu(event, menuProvider);
     m_menuProvider = menuProvider.get();
 }
 
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
index 017b547..3eb79b8 100644
--- a/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ b/Source/core/inspector/InspectorIndexedDBAgent.cpp
@@ -407,7 +407,7 @@
         return this == &other;
     }
 
-    virtual void handleEvent(ScriptExecutionContext*, Event* event) OVERRIDE
+    virtual void handleEvent(ScriptExecutionContext* context, Event* event) OVERRIDE
     {
         if (event->type() != eventNames().successEvent) {
             m_requestCallback->sendFailure("Unexpected event type.");
@@ -454,9 +454,9 @@
         }
 
         RefPtr<DataEntry> dataEntry = DataEntry::create()
-            .setKey(m_injectedScript.wrapObject(idbCursor->key(), String()))
-            .setPrimaryKey(m_injectedScript.wrapObject(idbCursor->primaryKey(), String()))
-            .setValue(m_injectedScript.wrapObject(idbCursor->value(), String()));
+            .setKey(m_injectedScript.wrapObject(idbCursor->key(context), String()))
+            .setPrimaryKey(m_injectedScript.wrapObject(idbCursor->primaryKey(context), String()))
+            .setValue(m_injectedScript.wrapObject(idbCursor->value(context), String()));
         m_result->addItem(dataEntry);
 
     }
diff --git a/Source/core/inspector/InspectorInputAgent.cpp b/Source/core/inspector/InspectorInputAgent.cpp
index 346f640..4af9187 100644
--- a/Source/core/inspector/InspectorInputAgent.cpp
+++ b/Source/core/inspector/InspectorInputAgent.cpp
@@ -133,8 +133,12 @@
     m_client->dispatchKeyEvent(event);
 }
 
-void InspectorInputAgent::dispatchMouseEvent(ErrorString* error, const String& type, int x, int y, const int* modifiers, const double* timestamp, const String* button, const int* clickCount)
+void InspectorInputAgent::dispatchMouseEvent(ErrorString* error, const String& type, int x, int y, const int* modifiers, const double* timestamp, const String* button, const int* clickCount, const bool* deviceSpace)
 {
+    if (deviceSpace && *deviceSpace) {
+        *error = "Internal error: events with device coordinates should be processed on the embedder level.";
+        return;
+    }
     PlatformEvent::Type convertedType;
     if (type == "mousePressed")
         convertedType = PlatformEvent::MousePressed;
@@ -270,5 +274,10 @@
     handler->handleTouchEvent(event);
 }
 
+void InspectorInputAgent::dispatchGestureEvent(ErrorString*, const String& type, int x, int y, const double* timestamp, const int* deltaX, const int* deltaY, const double* scale)
+{
+    // Handled on the browser level.
+}
+
 } // namespace WebCore
 
diff --git a/Source/core/inspector/InspectorInputAgent.h b/Source/core/inspector/InspectorInputAgent.h
index 4ded65c..4ae8753 100644
--- a/Source/core/inspector/InspectorInputAgent.h
+++ b/Source/core/inspector/InspectorInputAgent.h
@@ -54,9 +54,9 @@
 
     // Methods called from the frontend for simulating input.
     virtual void dispatchKeyEvent(ErrorString*, const String& type, const int* modifiers, const double* timestamp, const String* text, const String* unmodifiedText, const String* keyIdentifier, const int* windowsVirtualKeyCode, const int* nativeVirtualKeyCode, const int* macCharCode, const bool* autoRepeat, const bool* isKeypad, const bool* isSystemKey);
-    virtual void dispatchMouseEvent(ErrorString*, const String& type, int x, int y, const int* modifiers, const double* timestamp, const String* button, const int* clickCount);
+    virtual void dispatchMouseEvent(ErrorString*, const String& type, int x, int y, const int* modifiers, const double* timestamp, const String* button, const int* clickCount, const bool* deviceSpace);
     virtual void dispatchTouchEvent(ErrorString*, const String& type, const RefPtr<JSONArray>& touchPoints, const int* modifiers, const double* timestamp);
-
+    virtual void dispatchGestureEvent(ErrorString*, const String& type, int x, int y, const double* timestamp, const int* deltaX, const int* deltaY, const double* scale);
 private:
     InspectorInputAgent(InstrumentingAgents*, InspectorCompositeState*, Page*, InspectorClient*);
 
diff --git a/Source/core/inspector/InspectorInstrumentation.cpp b/Source/core/inspector/InspectorInstrumentation.cpp
index 5cffed0..246b9c3 100644
--- a/Source/core/inspector/InspectorInstrumentation.cpp
+++ b/Source/core/inspector/InspectorInstrumentation.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/inspector/InspectorInstrumentation.h"
 
+#include "core/fetch/FetchInitiatorInfo.h"
 #include "core/inspector/InspectorAgent.h"
 #include "core/inspector/InspectorCSSAgent.h"
 #include "core/inspector/InspectorConsoleAgent.h"
@@ -41,7 +42,6 @@
 #include "core/inspector/InspectorTimelineAgent.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/WorkerInspectorController.h"
-#include "core/loader/cache/FetchInitiatorInfo.h"
 #include "core/workers/WorkerGlobalScope.h"
 
 namespace WebCore {
@@ -146,6 +146,20 @@
     return false;
 }
 
+PassOwnPtr<ScriptSourceCode> preprocessImpl(InstrumentingAgents* instrumentingAgents, Frame* frame, const ScriptSourceCode& sourceCode)
+{
+    if (InspectorDebuggerAgent* debuggerAgent = instrumentingAgents->inspectorDebuggerAgent())
+        return debuggerAgent->preprocess(frame, sourceCode);
+    return PassOwnPtr<ScriptSourceCode>();
+}
+
+String preprocessEventListenerImpl(InstrumentingAgents* instrumentingAgents, Frame* frame, const String& source, const String& url, const String& functionName)
+{
+    if (InspectorDebuggerAgent* debuggerAgent = instrumentingAgents->inspectorDebuggerAgent())
+        return debuggerAgent->preprocessEventListener(frame, source, url, functionName);
+    return source;
+}
+
 bool canvasAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
 {
     InstrumentingAgents* instrumentingAgents = instrumentingAgentsForScriptExecutionContext(scriptExecutionContext);
@@ -247,9 +261,7 @@
 InstrumentingAgents* instrumentationForPage(Page* page)
 {
     ASSERT(isMainThread());
-    if (InspectorController* controller = page->inspectorController())
-        return controller->m_instrumentingAgents.get();
-    return 0;
+    return page->inspectorController().m_instrumentingAgents.get();
 }
 
 InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope* workerGlobalScope)
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index a9bd1ae..9ec16ae 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -336,10 +336,10 @@
     [Page]
     void frameStoppedLoading([Keep] Frame*);
 
-    [Page]
+    [Page, Resource]
     void frameScheduledNavigation([Keep] Frame*, double delay);
 
-    [Page]
+    [Page, Resource]
     void frameClearedScheduledNavigation([Keep] Frame*);
 
     [Page, Inline=FastReturn]
@@ -381,6 +381,18 @@
     [Worker]
     void workerGlobalScopeTerminated(ScriptExecutionContext*, WorkerGlobalScopeProxy* proxy);
 
+    [Profiler, Timeline]
+    void willProcessTask(WorkerGlobalScope* context);
+
+    [Profiler, Timeline]
+    void didProcessTask(WorkerGlobalScope* context);
+
+    [Profiler]
+    void willEnterNestedRunLoop(WorkerGlobalScope* context);
+
+    [Profiler]
+    void didLeaveNestedRunLoop(WorkerGlobalScope* context);
+
     [Resource, Timeline]
     void didCreateWebSocket([Keep] Document*, unsigned long identifier, const KURL& requestURL, const String& protocol);
 
diff --git a/Source/core/inspector/InspectorInstrumentationCustomInl.h b/Source/core/inspector/InspectorInstrumentationCustomInl.h
index 4a181f6..a04b669 100644
--- a/Source/core/inspector/InspectorInstrumentationCustomInl.h
+++ b/Source/core/inspector/InspectorInstrumentationCustomInl.h
@@ -38,6 +38,8 @@
 bool profilerEnabledImpl(InstrumentingAgents*);
 bool isDebuggerPausedImpl(InstrumentingAgents*);
 bool collectingHTMLParseErrorsImpl(InstrumentingAgents*);
+PassOwnPtr<ScriptSourceCode> preprocessImpl(InstrumentingAgents*, Frame*, const ScriptSourceCode&);
+String preprocessEventListenerImpl(InstrumentingAgents*, Frame*, const String& source, const String& url, const String& functionName);
 
 bool canvasAgentEnabled(ScriptExecutionContext*);
 bool consoleAgentEnabled(ScriptExecutionContext*);
@@ -66,6 +68,22 @@
     return false;
 }
 
+inline String preprocessEventListener(Frame* frame, const String& source, const String& url, const String& functionName)
+{
+    FAST_RETURN_IF_NO_FRONTENDS(source);
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForFrame(frame))
+        return preprocessEventListenerImpl(instrumentingAgents, frame, source, url, functionName);
+    return source;
+}
+
+inline PassOwnPtr<ScriptSourceCode> preprocess(Frame* frame, const ScriptSourceCode& sourceCode)
+{
+    FAST_RETURN_IF_NO_FRONTENDS(PassOwnPtr<ScriptSourceCode>());
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForFrame(frame))
+        return preprocessImpl(instrumentingAgents, frame, sourceCode);
+    return PassOwnPtr<ScriptSourceCode>();
+}
+
 } // namespace InspectorInstrumentation
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.cpp b/Source/core/inspector/InspectorLayerTreeAgent.cpp
index 3c0fb1f..3a7ab1d 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.cpp
+++ b/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -41,6 +41,7 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/IntRect.h"
+#include "core/platform/graphics/transforms/TransformationMatrix.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
@@ -69,6 +70,19 @@
     if (graphicsLayer->parent() && !forceRoot)
         layerObject->setParentLayerId(String::number(graphicsLayer->parent()->platformLayer()->id()));
 
+    const TransformationMatrix& transform = graphicsLayer->transform();
+    if (!transform.isIdentity()) {
+        TransformationMatrix::FloatMatrix4 flattenedMatrix;
+        transform.toColumnMajorFloatArray(flattenedMatrix);
+        RefPtr<TypeBuilder::Array<double> > transformArray = TypeBuilder::Array<double>::create();
+        for (size_t i = 0; i < WTF_ARRAY_LENGTH(flattenedMatrix); ++i)
+            transformArray->addItem(flattenedMatrix[i]);
+        layerObject->setTransform(transformArray);
+        const FloatPoint3D& anchor = graphicsLayer->anchorPoint();
+        layerObject->setAnchorX(anchor.x());
+        layerObject->setAnchorY(anchor.y());
+        layerObject->setAnchorZ(anchor.z());
+    }
     return layerObject;
 }
 
diff --git a/Source/core/inspector/InspectorOverlay.cpp b/Source/core/inspector/InspectorOverlay.cpp
index 25ea756..3daeda5 100644
--- a/Source/core/inspector/InspectorOverlay.cpp
+++ b/Source/core/inspector/InspectorOverlay.cpp
@@ -59,19 +59,19 @@
 
 class InspectorOverlayChromeClient: public EmptyChromeClient {
 public:
-    InspectorOverlayChromeClient(ChromeClient* client, InspectorOverlay* overlay)
+    InspectorOverlayChromeClient(ChromeClient& client, InspectorOverlay* overlay)
         : m_client(client)
         , m_overlay(overlay)
     { }
 
     virtual void setCursor(const Cursor& cursor)
     {
-        m_client->setCursor(cursor);
+        m_client.setCursor(cursor);
     }
 
     virtual void setToolTip(const String& tooltip, TextDirection direction)
     {
-        m_client->setToolTip(tooltip, direction);
+        m_client.setToolTip(tooltip, direction);
     }
 
     virtual void invalidateRootView(const IntRect& rect)
@@ -88,8 +88,9 @@
     {
         m_overlay->invalidate();
     }
+
 private:
-    ChromeClient* m_client;
+    ChromeClient& m_client;
     InspectorOverlay* m_overlay;
 };
 
@@ -255,6 +256,14 @@
     m_client->highlight();
 }
 
+bool InspectorOverlay::handleGestureEvent(const PlatformGestureEvent& event)
+{
+    if (isEmpty())
+        return false;
+
+    return overlayPage()->mainFrame()->eventHandler()->handleGestureEvent(event);
+}
+
 bool InspectorOverlay::handleMouseEvent(const PlatformMouseEvent& event)
 {
     if (isEmpty())
@@ -580,21 +589,21 @@
     m_overlayPage = adoptPtr(new Page(pageClients));
     m_overlayPage->setGroupType(Page::InspectorPageGroup);
 
-    Settings* settings = m_page->settings();
-    Settings* overlaySettings = m_overlayPage->settings();
+    Settings& settings = m_page->settings();
+    Settings& overlaySettings = m_overlayPage->settings();
 
-    overlaySettings->setStandardFontFamily(settings->standardFontFamily());
-    overlaySettings->setSerifFontFamily(settings->serifFontFamily());
-    overlaySettings->setSansSerifFontFamily(settings->sansSerifFontFamily());
-    overlaySettings->setCursiveFontFamily(settings->cursiveFontFamily());
-    overlaySettings->setFantasyFontFamily(settings->fantasyFontFamily());
-    overlaySettings->setPictographFontFamily(settings->pictographFontFamily());
-    overlaySettings->setMinimumFontSize(settings->minimumFontSize());
-    overlaySettings->setMinimumLogicalFontSize(settings->minimumLogicalFontSize());
-    overlaySettings->setMediaEnabled(false);
-    overlaySettings->setScriptEnabled(true);
-    overlaySettings->setPluginsEnabled(false);
-    overlaySettings->setLoadsImagesAutomatically(true);
+    overlaySettings.setStandardFontFamily(settings.standardFontFamily());
+    overlaySettings.setSerifFontFamily(settings.serifFontFamily());
+    overlaySettings.setSansSerifFontFamily(settings.sansSerifFontFamily());
+    overlaySettings.setCursiveFontFamily(settings.cursiveFontFamily());
+    overlaySettings.setFantasyFontFamily(settings.fantasyFontFamily());
+    overlaySettings.setPictographFontFamily(settings.pictographFontFamily());
+    overlaySettings.setMinimumFontSize(settings.minimumFontSize());
+    overlaySettings.setMinimumLogicalFontSize(settings.minimumLogicalFontSize());
+    overlaySettings.setMediaEnabled(false);
+    overlaySettings.setScriptEnabled(true);
+    overlaySettings.setPluginsEnabled(false);
+    overlaySettings.setLoadsImagesAutomatically(true);
 
     RefPtr<Frame> frame = Frame::create(m_overlayPage.get(), 0, dummyFrameLoaderClient);
     frame->setView(FrameView::create(frame.get()));
diff --git a/Source/core/inspector/InspectorOverlay.h b/Source/core/inspector/InspectorOverlay.h
index a9863ee..2defc50 100644
--- a/Source/core/inspector/InspectorOverlay.h
+++ b/Source/core/inspector/InspectorOverlay.h
@@ -49,6 +49,7 @@
 class JSONValue;
 class Node;
 class Page;
+class PlatformGestureEvent;
 class PlatformMouseEvent;
 class PlatformTouchEvent;
 
@@ -126,6 +127,7 @@
     void drawOutline(GraphicsContext*, const LayoutRect&, const Color&);
     void getHighlight(Highlight*) const;
     void resize(const IntSize&);
+    bool handleGestureEvent(const PlatformGestureEvent&);
     bool handleMouseEvent(const PlatformMouseEvent&);
     bool handleTouchEvent(const PlatformTouchEvent&);
 
diff --git a/Source/core/inspector/InspectorPageAgent.cpp b/Source/core/inspector/InspectorPageAgent.cpp
index 9a939cd..8103dc6 100644
--- a/Source/core/inspector/InspectorPageAgent.cpp
+++ b/Source/core/inspector/InspectorPageAgent.cpp
@@ -39,6 +39,13 @@
 #include "core/dom/DeviceOrientationController.h"
 #include "core/dom/Document.h"
 #include "core/dom/UserGestureIndicator.h"
+#include "core/fetch/CSSStyleSheetResource.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ScriptResource.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/ContentSearchUtils.h"
 #include "core/inspector/DOMPatchSupport.h"
@@ -54,13 +61,6 @@
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CSSStyleSheetResource.h"
-#include "core/loader/cache/FontResource.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/Resource.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/ScriptResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
@@ -396,7 +396,7 @@
     setShowPaintRects(0, false);
     setShowDebugBorders(0, false);
     setShowFPSCounter(0, false);
-    setEmulatedMedia(0, "");
+    setEmulatedMedia(0, String());
     setContinuousPaintingEnabled(0, false);
     setShowScrollBottleneckRects(0, false);
     setShowViewportSizeOnResize(0, false, 0);
@@ -693,7 +693,7 @@
     // These two always fit an int.
     int currentWidth = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenWidthOverride));
     int currentHeight = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenHeightOverride));
-    double currentFontScaleFactor = m_state->getDouble(PageAgentState::pageAgentFontScaleFactorOverride);
+    double currentFontScaleFactor = m_state->getDouble(PageAgentState::pageAgentFontScaleFactorOverride, 1);
     bool currentFitWindow = m_state->getBoolean(PageAgentState::pageAgentFitWindow);
 
     return width != currentWidth || height != currentHeight || fontScaleFactor != currentFontScaleFactor || fitWindow != currentFitWindow;
@@ -823,7 +823,7 @@
 {
     if (loader->frame() == m_page->mainFrame()) {
         m_scriptToEvaluateOnLoadOnce = m_pendingScriptToEvaluateOnLoadOnce;
-        m_scriptPreprocessor = m_pendingScriptPreprocessor;
+        m_scriptPreprocessorSource = m_pendingScriptPreprocessor;
         m_pendingScriptToEvaluateOnLoadOnce = String();
         m_pendingScriptPreprocessor = String();
     }
@@ -1247,24 +1247,34 @@
 
 void InspectorPageAgent::setForceCompositingMode(ErrorString* errorString, bool force)
 {
-    Settings* settings = m_page->settings();
-    if (force && !settings->acceleratedCompositingEnabled()) {
+    Settings& settings = m_page->settings();
+    if (force && !settings.acceleratedCompositingEnabled()) {
         if (errorString)
             *errorString = "Compositing mode is not supported";
         return;
     }
     m_state->setBoolean(PageAgentState::forceCompositingMode, force);
-    if (settings->forceCompositingMode() == force)
+    if (settings.forceCompositingMode() == force)
         return;
     m_didForceCompositingMode = force;
-    settings->setForceCompositingMode(force);
+    settings.setForceCompositingMode(force);
     Frame* mainFrame = m_page->mainFrame();
     if (!mainFrame)
         return;
     mainFrame->view()->updateCompositingLayersAfterStyleChange();
 }
 
-void InspectorPageAgent::captureScreenshot(ErrorString*, String*)
+void InspectorPageAgent::captureScreenshot(ErrorString*, const String*, const int*, const double*, String*)
+{
+    // Handled on the browser level.
+}
+
+void InspectorPageAgent::startScreencast(ErrorString*, const String*, const int*, const double*)
+{
+    // Handled on the browser level.
+}
+
+void InspectorPageAgent::stopScreencast(ErrorString*)
 {
     // Handled on the browser level.
 }
diff --git a/Source/core/inspector/InspectorPageAgent.h b/Source/core/inspector/InspectorPageAgent.h
index 5b945f5..c07e03a 100644
--- a/Source/core/inspector/InspectorPageAgent.h
+++ b/Source/core/inspector/InspectorPageAgent.h
@@ -115,7 +115,9 @@
     virtual void setTouchEmulationEnabled(ErrorString*, bool);
     virtual void setEmulatedMedia(ErrorString*, const String&);
     virtual void setForceCompositingMode(ErrorString*, bool force);
-    virtual void captureScreenshot(ErrorString*, String* data);
+    virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const double* scale, String* data);
+    virtual void startScreencast(ErrorString*, const String* format, const int* quality, const double* scale);
+    virtual void stopScreencast(ErrorString*);
     virtual void handleJavaScriptDialog(ErrorString*, bool accept, const String* promptText);
     virtual void setShowViewportSizeOnResize(ErrorString*, bool show, const bool* showGrid);
 
@@ -168,7 +170,7 @@
     String loaderId(DocumentLoader*);
     Frame* findFrameWithSecurityOrigin(const String& originRawString);
     Frame* assertFrame(ErrorString*, const String& frameId);
-    String scriptPreprocessor() { return m_scriptPreprocessor; }
+    String scriptPreprocessorSource() { return m_scriptPreprocessorSource; }
     String resourceSourceMapURL(const String& url);
     static DocumentLoader* assertDocumentLoader(ErrorString*, Frame*);
 
@@ -192,7 +194,7 @@
     String m_pendingScriptToEvaluateOnLoadOnce;
     String m_scriptToEvaluateOnLoadOnce;
     String m_pendingScriptPreprocessor;
-    String m_scriptPreprocessor;
+    String m_scriptPreprocessorSource;
     HashMap<Frame*, String> m_frameToIdentifier;
     HashMap<String, Frame*> m_identifierToFrame;
     HashMap<DocumentLoader*, String> m_loaderToIdentifier;
diff --git a/Source/core/inspector/InspectorProfilerAgent.cpp b/Source/core/inspector/InspectorProfilerAgent.cpp
index d0375e7..4af9715 100644
--- a/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -69,7 +69,7 @@
     , m_currentUserInitiatedProfileNumber(-1)
     , m_nextUserInitiatedProfileNumber(1)
     , m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
-    , m_previousTaskEndTime(0.0)
+    , m_idleStartTime(0.0)
 {
 }
 
@@ -162,7 +162,6 @@
     }
     profileObject = TypeBuilder::Profiler::CPUProfile::create()
         .setHead(it->value->buildInspectorObjectForHead())
-        .setIdleTime(it->value->idleTime())
         .setStartTime(it->value->startTime())
         .setEndTime(it->value->endTime());
     profileObject->setSamples(it->value->buildInspectorObjectForSamples());
@@ -265,25 +264,47 @@
         m_frontend->setRecordingProfile(isProfiling);
 }
 
-void InspectorProfilerAgent::willProcessTask()
+void InspectorProfilerAgent::idleFinished()
 {
     if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
         return;
-    if (!m_previousTaskEndTime)
+    ScriptProfiler::setIdle(false);
+    if (!m_idleStartTime)
         return;
 
-    double idleTime = WTF::monotonicallyIncreasingTime() - m_previousTaskEndTime;
-    m_previousTaskEndTime = 0.0;
+    double idleTime = WTF::monotonicallyIncreasingTime() - m_idleStartTime;
+    m_idleStartTime = 0.0;
     ProfileNameIdleTimeMap::iterator end = m_profileNameIdleTimeMap->end();
     for (ProfileNameIdleTimeMap::iterator it = m_profileNameIdleTimeMap->begin(); it != end; ++it)
         it->value += idleTime;
 }
 
-void InspectorProfilerAgent::didProcessTask()
+void InspectorProfilerAgent::idleStarted()
 {
     if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
         return;
-    m_previousTaskEndTime = WTF::monotonicallyIncreasingTime();
+    m_idleStartTime = WTF::monotonicallyIncreasingTime();
+    ScriptProfiler::setIdle(true);
+}
+
+void InspectorProfilerAgent::willProcessTask()
+{
+    idleFinished();
+}
+
+void InspectorProfilerAgent::didProcessTask()
+{
+    idleStarted();
+}
+
+void InspectorProfilerAgent::willEnterNestedRunLoop()
+{
+    idleStarted();
+}
+
+void InspectorProfilerAgent::didLeaveNestedRunLoop()
+{
+    idleFinished();
 }
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorProfilerAgent.h b/Source/core/inspector/InspectorProfilerAgent.h
index 9b3913a..3308c1e 100644
--- a/Source/core/inspector/InspectorProfilerAgent.h
+++ b/Source/core/inspector/InspectorProfilerAgent.h
@@ -79,6 +79,8 @@
 
     void willProcessTask();
     void didProcessTask();
+    void willEnterNestedRunLoop();
+    void didLeaveNestedRunLoop();
 
 private:
     InspectorProfilerAgent(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*);
@@ -101,7 +103,10 @@
 
     typedef HashMap<String, double> ProfileNameIdleTimeMap;
     ProfileNameIdleTimeMap* m_profileNameIdleTimeMap;
-    double m_previousTaskEndTime;
+    double m_idleStartTime;
+
+    void idleStarted();
+    void idleFinished();
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorResourceAgent.cpp b/Source/core/inspector/InspectorResourceAgent.cpp
index 14c54bb..3f1acd6 100644
--- a/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/Source/core/inspector/InspectorResourceAgent.cpp
@@ -31,11 +31,16 @@
 #include "config.h"
 #include "core/inspector/InspectorResourceAgent.h"
 
+#include "FetchInitiatorTypeNames.h"
 #include "InspectorFrontend.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "bindings/v8/ScriptCallStackFactory.h"
 #include "core/dom/Document.h"
 #include "core/dom/ScriptableDocumentParser.h"
+#include "core/fetch/FetchInitiatorInfo.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceLoader.h"
 #include "core/inspector/IdentifiersFactory.h"
 #include "core/inspector/InspectorClient.h"
 #include "core/inspector/InspectorOverlay.h"
@@ -47,12 +52,8 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/DocumentThreadableLoader.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/ResourceLoader.h"
 #include "core/loader/ThreadableLoader.h"
 #include "core/loader/ThreadableLoaderClient.h"
-#include "core/loader/cache/FetchInitiatorInfo.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/Resource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/JSONValues.h"
@@ -308,8 +309,16 @@
         request.setHTTPHeaderField("Cache-Control", "no-cache");
     }
 
+    String frameId = m_pageAgent->frameId(loader->frame());
+
     RefPtr<TypeBuilder::Network::Initiator> initiatorObject = buildInitiatorObject(loader->frame() ? loader->frame()->document() : 0, initiatorInfo);
-    m_frontend->requestWillBeSent(requestId, m_pageAgent->frameId(loader->frame()), m_pageAgent->loaderId(loader), urlWithoutFragment(loader->url()).string(), buildObjectForResourceRequest(request), currentTime(), initiatorObject, buildObjectForResourceResponse(redirectResponse, loader));
+    if (initiatorInfo.name == FetchInitiatorTypeNames::document) {
+        FrameNavigationInitiatorMap::iterator it = m_frameNavigationInitiatorMap.find(frameId);
+        if (it != m_frameNavigationInitiatorMap.end())
+            initiatorObject = it->value;
+    }
+
+    m_frontend->requestWillBeSent(requestId, frameId, m_pageAgent->loaderId(loader), urlWithoutFragment(loader->url()).string(), buildObjectForResourceRequest(request), currentTime(), initiatorObject, buildObjectForResourceResponse(redirectResponse, loader));
 }
 
 void InspectorResourceAgent::markResourceAsCached(unsigned long identifier)
@@ -755,6 +764,17 @@
     m_resourcesData->clear(m_pageAgent->loaderId(loader));
 }
 
+void InspectorResourceAgent::frameScheduledNavigation(Frame* frame, double)
+{
+    RefPtr<TypeBuilder::Network::Initiator> initiator = buildInitiatorObject(frame->document(), FetchInitiatorInfo());
+    m_frameNavigationInitiatorMap.set(m_pageAgent->frameId(frame), initiator);
+}
+
+void InspectorResourceAgent::frameClearedScheduledNavigation(Frame* frame)
+{
+    m_frameNavigationInitiatorMap.remove(m_pageAgent->frameId(frame));
+}
+
 InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state, InspectorOverlay* overlay)
     : InspectorBaseAgent<InspectorResourceAgent>("Network", instrumentingAgents, state)
     , m_pageAgent(pageAgent)
diff --git a/Source/core/inspector/InspectorResourceAgent.h b/Source/core/inspector/InspectorResourceAgent.h
index 7cd0165..9ddfe39 100644
--- a/Source/core/inspector/InspectorResourceAgent.h
+++ b/Source/core/inspector/InspectorResourceAgent.h
@@ -115,6 +115,9 @@
     void didRecalculateStyle();
     void didScheduleStyleRecalculation(Document*);
 
+    void frameScheduledNavigation(Frame*, double);
+    void frameClearedScheduledNavigation(Frame*);
+
     PassRefPtr<TypeBuilder::Network::Initiator> buildInitiatorObject(Document*, const FetchInitiatorInfo&);
 
     void didCreateWebSocket(Document*, unsigned long identifier, const KURL& requestURL, const String&);
@@ -160,6 +163,10 @@
 
     typedef HashMap<ThreadableLoaderClient*, RefPtr<XHRReplayData> > PendingXHRReplayDataMap;
     PendingXHRReplayDataMap m_pendingXHRReplayData;
+
+    typedef HashMap<String, RefPtr<TypeBuilder::Network::Initiator> > FrameNavigationInitiatorMap;
+    FrameNavigationInitiatorMap m_frameNavigationInitiatorMap;
+
     // FIXME: InspectorResourceAgent should now be aware of style recalculation.
     RefPtr<TypeBuilder::Network::Initiator> m_styleRecalculationInitiator;
     bool m_isRecalculatingStyle;
diff --git a/Source/core/inspector/InspectorState.cpp b/Source/core/inspector/InspectorState.cpp
index 2ed6d20..8e25c28 100644
--- a/Source/core/inspector/InspectorState.cpp
+++ b/Source/core/inspector/InspectorState.cpp
@@ -84,8 +84,14 @@
 
 long InspectorState::getLong(const String& propertyName)
 {
+    return getLong(propertyName, 0);
+}
+
+
+long InspectorState::getLong(const String& propertyName, long defaultValue)
+{
     JSONObject::iterator it = m_properties->find(propertyName);
-    long value = 0;
+    long value = defaultValue;
     if (it != m_properties->end())
         it->value->asNumber(&value);
     return value;
@@ -93,8 +99,13 @@
 
 double InspectorState::getDouble(const String& propertyName)
 {
+    return getDouble(propertyName, 0);
+}
+
+double InspectorState::getDouble(const String& propertyName, double defaultValue)
+{
     JSONObject::iterator it = m_properties->find(propertyName);
-    double value = 0;
+    double value = defaultValue;
     if (it != m_properties->end())
         it->value->asNumber(&value);
     return value;
diff --git a/Source/core/inspector/InspectorState.h b/Source/core/inspector/InspectorState.h
index 7fe1f50..0679736 100644
--- a/Source/core/inspector/InspectorState.h
+++ b/Source/core/inspector/InspectorState.h
@@ -60,7 +60,9 @@
     bool getBoolean(const String& propertyName);
     String getString(const String& propertyName);
     long getLong(const String& propertyName);
+    long getLong(const String& propertyName, long defaultValue);
     double getDouble(const String& propertyName);
+    double getDouble(const String& propertyName, double defaultValue);
     PassRefPtr<JSONObject> getObject(const String& propertyName);
 
     void setBoolean(const String& propertyName, bool value) { setValue(propertyName, JSONBasicValue::create(value)); }
diff --git a/Source/core/inspector/NetworkResourcesData.cpp b/Source/core/inspector/NetworkResourcesData.cpp
index cc210a9..f5c8abe 100644
--- a/Source/core/inspector/NetworkResourcesData.cpp
+++ b/Source/core/inspector/NetworkResourcesData.cpp
@@ -30,8 +30,8 @@
 #include "core/inspector/NetworkResourcesData.h"
 
 #include "core/dom/DOMImplementation.h"
+#include "core/fetch/Resource.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/Resource.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/ResourceResponse.h"
 
diff --git a/Source/core/inspector/PageDebuggerAgent.cpp b/Source/core/inspector/PageDebuggerAgent.cpp
index 72bd983..dc1b432 100644
--- a/Source/core/inspector/PageDebuggerAgent.cpp
+++ b/Source/core/inspector/PageDebuggerAgent.cpp
@@ -33,9 +33,12 @@
 
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/PageScriptDebugServer.h"
+#include "bindings/v8/ScriptController.h"
+#include "bindings/v8/ScriptSourceCode.h"
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InstrumentingAgents.h"
+#include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
 
@@ -108,11 +111,6 @@
     stepOver(&error);
 }
 
-void PageDebuggerAgent::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL)
-{
-    m_pageAgent->page()->console()->addMessage(source, level, message, sourceURL, 0);
-}
-
 InjectedScript PageDebuggerAgent::injectedScriptForEval(ErrorString* errorString, const int* executionContextId)
 {
     if (!executionContextId) {
@@ -136,7 +134,25 @@
         return;
 
     reset();
-    scriptDebugServer().setScriptPreprocessor(m_pageAgent->scriptPreprocessor());
+
+    scriptDebugServer().setPreprocessorSource(String());
+    ASSERT(m_pageAgent);
+    if (!m_pageAgent->scriptPreprocessorSource().isEmpty())
+        scriptDebugServer().setPreprocessorSource(m_pageAgent->scriptPreprocessorSource());
+}
+
+String PageDebuggerAgent::preprocessEventListener(Frame* frame, const String& source, const String& url, const String& functionName)
+{
+    ASSERT(frame);
+    ASSERT(m_pageScriptDebugServer);
+    return m_pageScriptDebugServer->preprocessEventListener(frame, source, url, functionName);
+}
+
+PassOwnPtr<ScriptSourceCode> PageDebuggerAgent::preprocess(Frame* frame, const ScriptSourceCode& sourceCode)
+{
+    ASSERT(m_pageScriptDebugServer);
+    ASSERT(frame);
+    return m_pageScriptDebugServer->preprocess(frame, sourceCode);
 }
 
 } // namespace WebCore
diff --git a/Source/core/inspector/PageDebuggerAgent.h b/Source/core/inspector/PageDebuggerAgent.h
index eff108c..161b55f 100644
--- a/Source/core/inspector/PageDebuggerAgent.h
+++ b/Source/core/inspector/PageDebuggerAgent.h
@@ -41,6 +41,7 @@
 class InspectorPageAgent;
 class Page;
 class PageScriptDebugServer;
+class ScriptSourceCode;
 
 class PageDebuggerAgent :
     public InspectorDebuggerAgent,
@@ -52,6 +53,8 @@
     virtual ~PageDebuggerAgent();
 
     void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
+    String preprocessEventListener(Frame*, const String& source, const String& url, const String& functionName);
+    PassOwnPtr<ScriptSourceCode> preprocess(Frame*, const ScriptSourceCode&);
 
 protected:
     virtual void enable();
@@ -63,7 +66,6 @@
     virtual PageScriptDebugServer& scriptDebugServer();
     virtual void muteConsole();
     virtual void unmuteConsole();
-    virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL);
 
     // InspectorOverlayHost::Listener implementation.
     virtual void overlayResumed();
diff --git a/Source/core/inspector/ScriptProfile.cpp b/Source/core/inspector/ScriptProfile.cpp
index 513586b..5db3af7 100644
--- a/Source/core/inspector/ScriptProfile.cpp
+++ b/Source/core/inspector/ScriptProfile.cpp
@@ -85,7 +85,7 @@
         .setScriptId(String::number(node->GetScriptId()))
         .setUrl(toWebCoreString(node->GetScriptResourceName()))
         .setLineNumber(node->GetLineNumber())
-        .setHitCount(node->GetSelfSamplesCount())
+        .setHitCount(node->GetHitCount())
         .setCallUID(node->GetCallUid())
         .setChildren(children.release());
     result->setId(node->GetNodeId());
diff --git a/Source/core/inspector/WorkerDebuggerAgent.cpp b/Source/core/inspector/WorkerDebuggerAgent.cpp
index 89ee4b8..0af72ef 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.cpp
+++ b/Source/core/inspector/WorkerDebuggerAgent.cpp
@@ -142,10 +142,4 @@
     // We don't need to mute console for workers.
 }
 
-void WorkerDebuggerAgent::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL)
-{
-    ScriptExecutionContext* context = m_inspectedWorkerGlobalScope;
-    context->addConsoleMessage(source, level, message, sourceURL, 0);
-}
-
 } // namespace WebCore
diff --git a/Source/core/inspector/WorkerDebuggerAgent.h b/Source/core/inspector/WorkerDebuggerAgent.h
index f51b390..3974ade 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.h
+++ b/Source/core/inspector/WorkerDebuggerAgent.h
@@ -58,7 +58,6 @@
     virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId);
     virtual void muteConsole();
     virtual void unmuteConsole();
-    virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL);
 
     WorkerScriptDebugServer* m_scriptDebugServer;
     WorkerGlobalScope* m_inspectedWorkerGlobalScope;
diff --git a/Source/core/loader/CrossOriginAccessControl.cpp b/Source/core/loader/CrossOriginAccessControl.cpp
index 6c4fbf0..edfbb62 100644
--- a/Source/core/loader/CrossOriginAccessControl.cpp
+++ b/Source/core/loader/CrossOriginAccessControl.cpp
@@ -148,17 +148,24 @@
 
     // FIXME: Access-Control-Allow-Origin can contain a list of origins.
     if (accessControlOriginString != securityOrigin->toString()) {
-        if (accessControlOriginString == "*")
-            errorDescription = "Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.";
-        else
-            errorDescription =  "Origin " + securityOrigin->toString() + " is not allowed by Access-Control-Allow-Origin.";
+        if (accessControlOriginString == "*") {
+            errorDescription = "Wildcards cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
+        } else if (accessControlOriginString.isEmpty()) {
+            errorDescription = "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
+        } else {
+            KURL headerOrigin(KURL(), accessControlOriginString);
+            if (!headerOrigin.isValid())
+                errorDescription = "The 'Access-Control-Allow-Origin' header contains the invalid value '" + accessControlOriginString + "'. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
+            else
+                errorDescription = "The 'Access-Control-Allow-Origin' whitelists only '" + accessControlOriginString + "'. Origin '" + securityOrigin->toString() + "' is not in the list, and is therefore not allowed access.";
+        }
         return false;
     }
 
     if (includeCredentials == AllowStoredCredentials) {
         const String& accessControlCredentialsString = response.httpHeaderField(accessControlAllowCredentials);
         if (accessControlCredentialsString != "true") {
-            errorDescription = "Credentials flag is true, but Access-Control-Allow-Credentials is not \"true\".";
+            errorDescription = "Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is '" + accessControlCredentialsString + "'. It must be 'true' to allow credentials.";
             return false;
         }
     }
diff --git a/Source/core/loader/CrossOriginAccessControl.h b/Source/core/loader/CrossOriginAccessControl.h
index a660e01..0d58400 100644
--- a/Source/core/loader/CrossOriginAccessControl.h
+++ b/Source/core/loader/CrossOriginAccessControl.h
@@ -27,7 +27,7 @@
 #ifndef CrossOriginAccessControl_h
 #define CrossOriginAccessControl_h
 
-#include "core/loader/ResourceLoaderOptions.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "wtf/Forward.h"
 #include "wtf/HashSet.h"
diff --git a/Source/core/loader/CrossOriginPreflightResultCache.h b/Source/core/loader/CrossOriginPreflightResultCache.h
index 0006d48..3911a2c 100644
--- a/Source/core/loader/CrossOriginPreflightResultCache.h
+++ b/Source/core/loader/CrossOriginPreflightResultCache.h
@@ -27,7 +27,7 @@
 #ifndef CrossOriginPreflightResultCache_h
 #define CrossOriginPreflightResultCache_h
 
-#include "core/loader/ResourceLoaderOptions.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "weborigin/KURLHash.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index bb5a318..c855dfd 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -36,20 +36,20 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentParser.h"
 #include "core/dom/Event.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ResourceLoader.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/DocumentWriter.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/ResourceLoader.h"
 #include "core/loader/SinkDocument.h"
 #include "core/loader/TextResourceDecoder.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/loader/cache/MemoryCache.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
@@ -98,7 +98,6 @@
     , m_originalRequestCopy(req)
     , m_request(req)
     , m_committed(false)
-    , m_isStopping(false)
     , m_isClientRedirect(false)
     , m_replacesCurrentHistoryItem(false)
     , m_loadingMainResource(false)
@@ -240,7 +239,7 @@
         Document* doc = m_frame->document();
 
         if (loading || doc->parsing())
-            m_frame->loader()->stopLoading(UnloadEventPolicyNone);
+            m_frame->loader()->stopLoading();
     }
 
     // Always cancel multipart loaders
@@ -248,20 +247,8 @@
 
     clearArchiveResources();
 
-    if (!loading) {
-        // If something above restarted loading we might run into mysterious crashes like
-        // https://bugs.webkit.org/show_bug.cgi?id=62764 and <rdar://problem/9328684>
-        ASSERT(!isLoading());
+    if (!loading)
         return;
-    }
-
-    // We might run in to infinite recursion if we're stopping loading as the result of
-    // detaching from the frame, so break out of that recursion here.
-    // See <rdar://problem/9673866> for more details.
-    if (m_isStopping)
-        return;
-
-    m_isStopping = true;
 
     if (isLoadingMainResource()) {
         // Stop the main resource loader and let it send the cancelled message.
@@ -277,8 +264,6 @@
     }
 
     stopLoadingSubresources();
-
-    m_isStopping = false;
 }
 
 void DocumentLoader::commitIfReady()
@@ -379,8 +364,6 @@
     RefPtr<DocumentLoader> protect(this);
     ResourceResponse response(m_request.url(), m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
     responseReceived(0, response);
-    if (isStopping())
-        return;
     if (m_substituteData.content()->size())
         dataReceived(0, m_substituteData.content()->data(), m_substituteData.content()->size());
     if (isLoadingMainResource())
@@ -417,7 +400,8 @@
 
     NavigationPolicy policy = NavigationPolicyCurrentTab;
     m_triggeringAction.specifiesNavigationPolicy(&policy);
-    policy = frameLoader()->client()->decidePolicyForNavigation(request, m_triggeringAction.type(), policy, policyCheckLoadType == PolicyCheckRedirect);
+    if (policyCheckLoadType != PolicyCheckFragment)
+        policy = frameLoader()->client()->decidePolicyForNavigation(request, this, policy);
     if (policy == NavigationPolicyCurrentTab)
         return true;
     if (policy == NavigationPolicyIgnore)
@@ -487,7 +471,7 @@
 
     appendRedirect(newRequest.url());
     frameLoader()->client()->dispatchDidReceiveServerRedirectForProvisionalLoad();
-    if (!shouldContinueForNavigationPolicy(newRequest, PolicyCheckRedirect))
+    if (!shouldContinueForNavigationPolicy(newRequest, PolicyCheckStandard))
         stopLoadingForPolicyChange();
 }
 
@@ -550,7 +534,7 @@
         if (frameLoader()->shouldInterruptLoadForXFrameOptions(content, response.url(), identifier)) {
             InspectorInstrumentation::continueAfterXFrameOptionsDenied(m_frame, this, identifier, response);
             String message = "Refused to display '" + response.url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
-            frame()->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, identifier);
+            frame()->document()->addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, identifier);
             frame()->document()->enforceSandboxFlags(SandboxOrigin);
             if (HTMLFrameOwnerElement* ownerElement = frame()->ownerElement())
                 ownerElement->dispatchEvent(Event::create(eventNames().loadEvent, false, false));
@@ -701,7 +685,7 @@
     // frame have any loads active, so go ahead and kill all the loads.
     stopLoading();
 
-    m_applicationCacheHost->setDOMApplicationCache(0);
+    m_applicationCacheHost->setApplicationCache(0);
     InspectorInstrumentation::loaderDetachedFromFrame(m_frame, this);
     m_frame = 0;
 }
@@ -807,15 +791,6 @@
     return true;
 }
 
-void DocumentLoader::setTitle(const StringWithDirection& title)
-{
-    if (m_pageTitle == title)
-        return;
-
-    m_pageTitle = title;
-    frameLoader()->didChangeTitle(this);
-}
-
 KURL DocumentLoader::urlForHistory() const
 {
     // Return the URL to be used for history and B/F list.
@@ -991,7 +966,6 @@
     m_writer.clear();
 }
 
-
 PassRefPtr<DocumentWriter> DocumentLoader::createWriterFor(Frame* frame, const Document* ownerDocument, const KURL& url, const String& mimeType, const String& encoding, bool userChosen, bool dispatch)
 {
     // Create a new document before clearing the frame, because it may need to
@@ -1001,19 +975,16 @@
         document = SinkDocument::create(DocumentInit(url, frame));
     bool shouldReuseDefaultView = frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && frame->document()->isSecureTransitionTo(url);
 
-    RefPtr<DOMWindow> originalDOMWindow;
-    if (shouldReuseDefaultView)
-        originalDOMWindow = frame->domWindow();
-    frame->loader()->clear(!shouldReuseDefaultView, !shouldReuseDefaultView);
+    ClearOptions options = 0;
+    if (!shouldReuseDefaultView)
+        options = ClearWindowProperties | ClearScriptObjects;
+    frame->loader()->clear(options);
 
-    if (!shouldReuseDefaultView) {
+    if (frame->document() && frame->document()->attached())
+        frame->document()->prepareForDestruction();
+
+    if (!shouldReuseDefaultView)
         frame->setDOMWindow(DOMWindow::create(frame));
-    } else {
-        // Note that the old Document is still attached to the DOMWindow; the
-        // setDocument() call below will detach the old Document.
-        ASSERT(originalDOMWindow);
-        frame->setDOMWindow(originalDOMWindow);
-    }
 
     frame->loader()->setOutgoingReferrer(url);
     frame->domWindow()->setDocument(document);
diff --git a/Source/core/loader/DocumentLoader.h b/Source/core/loader/DocumentLoader.h
index 112292e..d85908e 100644
--- a/Source/core/loader/DocumentLoader.h
+++ b/Source/core/loader/DocumentLoader.h
@@ -30,13 +30,13 @@
 #ifndef DocumentLoader_h
 #define DocumentLoader_h
 
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourceLoaderOptions.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/loader/DocumentLoadTiming.h"
 #include "core/loader/DocumentWriter.h"
 #include "core/loader/NavigationAction.h"
-#include "core/loader/ResourceLoaderOptions.h"
 #include "core/loader/SubstituteData.h"
-#include "core/loader/cache/RawResource.h"
-#include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "core/platform/network/ResourceError.h"
 #include "core/platform/network/ResourceRequest.h"
@@ -108,7 +108,6 @@
         const String& responseMIMEType() const;
 
         void replaceRequestURLForSameDocumentNavigation(const KURL&);
-        bool isStopping() const { return m_isStopping; }
         void stopLoading();
         void setCommitted(bool committed) { m_committed = committed; }
         bool isCommitted() const { return m_committed; }
@@ -120,7 +119,6 @@
         bool replacesCurrentHistoryItem() const { return m_replacesCurrentHistoryItem; }
         void setReplacesCurrentHistoryItem(bool replacesCurrentHistoryItem) { m_replacesCurrentHistoryItem = replacesCurrentHistoryItem; }
         bool isLoadingInAPISense() const;
-        void setTitle(const StringWithDirection&);
         const String& overrideEncoding() const { return m_overrideEncoding; }
 
         bool scheduleArchiveLoad(Resource*, const ResourceRequest&);
@@ -128,14 +126,13 @@
 
         enum PolicyCheckLoadType {
             PolicyCheckStandard,
-            PolicyCheckRedirect
+            PolicyCheckFragment
         };
         bool shouldContinueForNavigationPolicy(const ResourceRequest&, PolicyCheckLoadType);
         const NavigationAction& triggeringAction() const { return m_triggeringAction; }
         void setTriggeringAction(const NavigationAction& action) { m_triggeringAction = action; }
 
         void setOverrideEncoding(const String& encoding) { m_overrideEncoding = encoding; }
-        const StringWithDirection& title() const { return m_pageTitle; }
 
         KURL urlForHistory() const;
 
@@ -247,12 +244,9 @@
         ResourceError m_mainDocumentError;
 
         bool m_committed;
-        bool m_isStopping;
         bool m_isClientRedirect;
         bool m_replacesCurrentHistoryItem;
 
-        StringWithDirection m_pageTitle;
-
         String m_overrideEncoding;
 
         // The action that triggered loading - we keep this around for the
diff --git a/Source/core/loader/DocumentThreadableLoader.cpp b/Source/core/loader/DocumentThreadableLoader.cpp
index f7e0544..f8e5c83 100644
--- a/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/Source/core/loader/DocumentThreadableLoader.cpp
@@ -33,15 +33,15 @@
 #include "core/loader/DocumentThreadableLoader.h"
 
 #include "core/dom/Document.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/CrossOriginAccessControl.h"
 #include "core/loader/CrossOriginPreflightResultCache.h"
 #include "core/loader/DocumentThreadableLoaderClient.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ThreadableLoaderClient.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/RawResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Frame.h"
 #include "core/platform/network/ResourceError.h"
diff --git a/Source/core/loader/DocumentThreadableLoader.h b/Source/core/loader/DocumentThreadableLoader.h
index 06e85eb..4e44cfb 100644
--- a/Source/core/loader/DocumentThreadableLoader.h
+++ b/Source/core/loader/DocumentThreadableLoader.h
@@ -32,9 +32,9 @@
 #ifndef DocumentThreadableLoader_h
 #define DocumentThreadableLoader_h
 
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/loader/ThreadableLoader.h"
-#include "core/loader/cache/RawResource.h"
-#include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "core/platform/network/ResourceError.h"
 #include "wtf/Forward.h"
diff --git a/Source/core/loader/EmptyClients.cpp b/Source/core/loader/EmptyClients.cpp
index d6570ea..f55f0a8 100644
--- a/Source/core/loader/EmptyClients.cpp
+++ b/Source/core/loader/EmptyClients.cpp
@@ -91,7 +91,7 @@
     return String();
 }
 
-NavigationPolicy EmptyFrameLoaderClient::decidePolicyForNavigation(const ResourceRequest&, NavigationType, NavigationPolicy, bool)
+NavigationPolicy EmptyFrameLoaderClient::decidePolicyForNavigation(const ResourceRequest&, DocumentLoader*, NavigationPolicy)
 {
     return NavigationPolicyIgnore;
 }
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index 09da78f..a415c44 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -84,7 +84,7 @@
     virtual void takeFocus(FocusDirection) OVERRIDE { }
 
     virtual void focusedNodeChanged(Node*) OVERRIDE { }
-    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&, NavigationPolicy) OVERRIDE { return 0; }
+    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy) OVERRIDE { return 0; }
     virtual void show(NavigationPolicy) OVERRIDE { }
 
     virtual bool canRunModal() OVERRIDE { return false; }
@@ -207,7 +207,7 @@
     virtual void dispatchDidFinishLoad() OVERRIDE { }
     virtual void dispatchDidLayout(LayoutMilestones) OVERRIDE { }
 
-    virtual NavigationPolicy decidePolicyForNavigation(const ResourceRequest&, NavigationType, NavigationPolicy, bool isRedirect) OVERRIDE;
+    virtual NavigationPolicy decidePolicyForNavigation(const ResourceRequest&, DocumentLoader*, NavigationPolicy) OVERRIDE;
 
     virtual void dispatchWillSendSubmitEvent(PassRefPtr<FormState>) OVERRIDE;
     virtual void dispatchWillSubmitForm(PassRefPtr<FormState>) OVERRIDE;
@@ -228,8 +228,7 @@
 
     virtual void transitionToCommittedForNewPage() OVERRIDE { }
 
-    virtual bool shouldGoToHistoryItem(HistoryItem*) const OVERRIDE { return false; }
-    virtual bool shouldStopLoadingForHistoryItem(HistoryItem*) const OVERRIDE { return false; }
+    virtual void navigateBackForward(int offset) const OVERRIDE { }
     virtual void didDisplayInsecureContent() OVERRIDE { }
     virtual void didRunInsecureContent(SecurityOrigin*, const KURL&) OVERRIDE { }
     virtual void didDetectXSS(const KURL&, bool) OVERRIDE { }
@@ -306,7 +305,7 @@
     virtual void textDidChangeInTextField(Element*) OVERRIDE { }
     virtual bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*) OVERRIDE { return false; }
 
-    TextCheckerClient* textChecker() { return &m_textCheckerClient; }
+    TextCheckerClient& textChecker() { return m_textCheckerClient; }
 
     virtual void updateSpellingUIWithMisspelledWord(const String&) OVERRIDE { }
     virtual void showSpellingUI(bool) OVERRIDE { }
@@ -324,6 +323,7 @@
     EmptyContextMenuClient() { }
     virtual ~EmptyContextMenuClient() {  }
     virtual void showContextMenu(const ContextMenu*) OVERRIDE { }
+    virtual void clearContextMenu() OVERRIDE { }
 };
 
 class EmptyDragClient : public DragClient {
@@ -360,13 +360,9 @@
 
 class EmptyBackForwardClient : public BackForwardClient {
 public:
-    virtual void addItem(PassRefPtr<HistoryItem>) OVERRIDE { }
-    virtual void goToItem(HistoryItem*) OVERRIDE { }
-    virtual HistoryItem* itemAtIndex(int) OVERRIDE { return 0; }
+    virtual void didAddItem() OVERRIDE { }
     virtual int backListCount() OVERRIDE { return 0; }
     virtual int forwardListCount() OVERRIDE { return 0; }
-    virtual bool isActive() OVERRIDE { return false; }
-    virtual void close() OVERRIDE { }
 };
 
 void fillWithEmptyClients(Page::PageClients&);
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index 1cfc5ca..7f8aa5f 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -39,17 +39,17 @@
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ScriptController.h"
 #include "bindings/v8/SerializedScriptValue.h"
-#include "core/dom/BeforeUnloadEvent.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/PageTransitionEvent.h"
 #include "core/editing/Editor.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ResourceLoader.h"
 #include "core/history/BackForwardController.h"
 #include "core/history/HistoryItem.h"
 #include "core/html/HTMLFormElement.h"
-#include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/inspector/InspectorController.h"
@@ -62,10 +62,8 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/IconController.h"
 #include "core/loader/ProgressTracker.h"
-#include "core/loader/ResourceLoader.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/ContentSecurityPolicy.h"
@@ -120,14 +118,14 @@
     {
         ASSERT(!m_inProgress || m_frame->page());
         if (m_inProgress)
-            m_frame->page()->progress()->progressCompleted(m_frame);
+            m_frame->page()->progress().progressCompleted(m_frame);
     }
 
     void progressStarted()
     {
         ASSERT(m_frame->page());
         if (!m_inProgress)
-            m_frame->page()->progress()->progressStarted(m_frame);
+            m_frame->page()->progress().progressStarted(m_frame);
         m_inProgress = true;
     }
 
@@ -136,7 +134,7 @@
         ASSERT(m_inProgress);
         ASSERT(m_frame->page());
         m_inProgress = false;
-        m_frame->page()->progress()->progressCompleted(m_frame);
+        m_frame->page()->progress().progressCompleted(m_frame);
     }
 
 private:
@@ -160,20 +158,16 @@
     , m_state(FrameStateProvisional)
     , m_loadType(FrameLoadTypeStandard)
     , m_inStopAllLoaders(false)
-    , m_pageDismissalEventBeingDispatched(NoDismissal)
     , m_isComplete(false)
     , m_containsPlugins(false)
-    , m_needsClear(false)
     , m_checkTimer(this, &FrameLoader::checkTimerFired)
     , m_shouldCallCheckCompleted(false)
-    , m_shouldCallCheckLoadComplete(false)
     , m_opener(0)
     , m_didAccessInitialDocument(false)
     , m_didAccessInitialDocumentTimer(this, &FrameLoader::didAccessInitialDocumentTimerFired)
     , m_suppressOpenerInNewFrame(false)
     , m_startingClientRedirect(false)
     , m_forcedSandboxFlags(SandboxNone)
-    , m_hasAllowedNavigationViaBeforeUnloadConfirmationPanel(false)
 {
 }
 
@@ -279,58 +273,8 @@
     targetFrame->navigationScheduler()->scheduleFormSubmission(submission);
 }
 
-void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
+void FrameLoader::stopLoading()
 {
-    if (m_frame->document() && m_frame->document()->parser())
-        m_frame->document()->parser()->stopParsing();
-
-    if (unloadEventPolicy != UnloadEventPolicyNone) {
-        if (m_frame->document()) {
-            if (m_frame->document()->unloadEventStillNeeded()) {
-                m_frame->document()->unloadEventStarted();
-                Element* currentFocusedElement = m_frame->document()->focusedElement();
-                if (currentFocusedElement && currentFocusedElement->hasTagName(inputTag))
-                    toHTMLInputElement(currentFocusedElement)->endEditing();
-                if (m_pageDismissalEventBeingDispatched == NoDismissal) {
-                    if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
-                        m_pageDismissalEventBeingDispatched = PageHideDismissal;
-                        m_frame->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), m_frame->document());
-                    }
-                    RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
-                    // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
-                    // while dispatching the event, so protect it to prevent writing the end
-                    // time into freed memory.
-                    RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
-                    m_pageDismissalEventBeingDispatched = UnloadDismissal;
-                    if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
-                        DocumentLoadTiming* timing = documentLoader->timing();
-                        ASSERT(timing->navigationStart());
-                        timing->markUnloadEventStart();
-                        m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
-                        timing->markUnloadEventEnd();
-                    } else {
-                        m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
-                    }
-                }
-                m_pageDismissalEventBeingDispatched = NoDismissal;
-                if (m_frame->document()) {
-                    m_frame->document()->updateStyleIfNeeded();
-                    m_frame->document()->unloadEventWasHandled();
-                }
-            }
-        }
-
-        // Dispatching the unload event could have made m_frame->document() null.
-        if (m_frame->document()) {
-            // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
-            bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
-                && m_frame->document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
-
-            if (!keepEventListeners)
-                m_frame->document()->removeAllEventListeners();
-        }
-    }
-
     m_isComplete = true; // to avoid calling completed() in finishedParsing()
 
     if (m_frame->document() && m_frame->document()->parsing()) {
@@ -351,25 +295,14 @@
     m_frame->navigationScheduler()->cancel();
 }
 
-void FrameLoader::stop()
-{
-    // http://bugs.webkit.org/show_bug.cgi?id=10854
-    // The frame's last ref may be removed and it will be deleted by checkCompleted().
-    RefPtr<Frame> protector(m_frame);
-
-    if (DocumentParser* parser = m_frame->document()->parser()) {
-        parser->stopParsing();
-        parser->finish();
-    }
-}
-
 bool FrameLoader::closeURL()
 {
     history()->saveDocumentState();
 
     // Should only send the pagehide event here if the current document exists.
-    Document* currentDocument = m_frame->document();
-    stopLoading(currentDocument ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
+    if (m_frame->document())
+        m_frame->document()->dispatchUnloadEvents();
+    stopLoading();
 
     m_frame->editor()->clearUndoRedoOperations();
     return true;
@@ -381,7 +314,7 @@
 
     // Calling document.open counts as committing the first real document load.
     if (!m_stateMachine.committedFirstRealDocumentLoad())
-        m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
+        m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
 
     // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
     // from a subsequent window.document.open / window.document.write call.
@@ -390,25 +323,12 @@
     m_frame->navigationScheduler()->cancel();
 }
 
-
-void FrameLoader::cancelAndClear()
+void FrameLoader::clear(ClearOptions options)
 {
-    m_frame->navigationScheduler()->cancel();
-
-    if (!m_isComplete)
-        closeURL();
-
-    clear(false);
-}
-
-void FrameLoader::clear(bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
-{
-    m_frame->editor()->clear();
-
-    if (!m_needsClear)
+    if (m_stateMachine.creatingInitialEmptyDocument())
         return;
-    m_needsClear = false;
 
+    m_frame->editor()->clear();
     m_frame->document()->cancelParsing();
     m_frame->document()->stopActiveDOMObjects();
     if (m_frame->document()->attached()) {
@@ -417,7 +337,7 @@
     }
 
     // Do this after detaching the document so that the unload event works.
-    if (clearWindowProperties) {
+    if (options & ClearWindowProperties) {
         InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame->domWindow());
         m_frame->domWindow()->reset();
         m_frame->script()->clearWindowShell();
@@ -425,16 +345,18 @@
 
     m_frame->selection()->prepareForDestruction();
     m_frame->eventHandler()->clear();
-    if (clearFrameView && m_frame->view())
+    if (m_frame->view())
         m_frame->view()->clear();
 
-    // Do not drop the DOMWindow (and Document) before the ScriptController and view are cleared
-    // as some destructors might still try to access the document.
-    m_frame->setDOMWindow(0);
+    if (options & ClearWindowObject) {
+        // Do not drop the DOMWindow (and Document) before the ScriptController and view are cleared
+        // as some destructors might still try to access the document.
+        m_frame->setDOMWindow(0);
+    }
 
     m_containsPlugins = false;
 
-    if (clearScriptObjects)
+    if (options & ClearScriptObjects)
         m_frame->script()->clearScriptObjects();
 
     m_frame->script()->enableEval();
@@ -443,9 +365,8 @@
 
     m_checkTimer.stop();
     m_shouldCallCheckCompleted = false;
-    m_shouldCallCheckLoadComplete = false;
 
-    if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
+    if (m_stateMachine.isDisplayingInitialEmptyDocument())
         m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
 }
 
@@ -453,16 +374,10 @@
 {
     if (m_stateMachine.creatingInitialEmptyDocument())
         return;
-
-    dispatchDidCommitLoad();
+    m_client->dispatchDidCommitLoad();
+    InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
+    m_frame->page()->didCommitLoad(m_frame);
     dispatchDidClearWindowObjectsInAllWorlds();
-
-    if (m_documentLoader) {
-        StringWithDirection ptitle = m_documentLoader->title();
-        // If we have a title let the WebView know about it.
-        if (!ptitle.isNull())
-            m_client->dispatchDidReceiveTitle(ptitle);
-    }
 }
 
 void FrameLoader::setOutgoingReferrer(const KURL& url)
@@ -472,7 +387,6 @@
 
 void FrameLoader::didBeginDocument(bool dispatch)
 {
-    m_needsClear = true;
     m_isComplete = false;
     m_frame->document()->setReadyState(Document::Loading);
 
@@ -548,7 +462,7 @@
 bool FrameLoader::allAncestorsAreComplete() const
 {
     for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
-        if (!ancestor->loader()->m_isComplete)
+        if (!ancestor->document()->loadEventFinished())
             return false;
     }
     return true;
@@ -609,13 +523,11 @@
     }
     if (m_shouldCallCheckCompleted)
         checkCompleted();
-    if (m_shouldCallCheckLoadComplete)
-        checkLoadComplete();
 }
 
 void FrameLoader::startCheckCompleteTimer()
 {
-    if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
+    if (!m_shouldCallCheckCompleted)
         return;
     if (m_checkTimer.isActive())
         return;
@@ -628,12 +540,6 @@
     startCheckCompleteTimer();
 }
 
-void FrameLoader::scheduleCheckLoadComplete()
-{
-    m_shouldCallCheckLoadComplete = true;
-    startCheckCompleteTimer();
-}
-
 String FrameLoader::outgoingReferrer() const
 {
     // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
@@ -687,7 +593,7 @@
     HTMLFrameOwnerElement* owner = m_frame->ownerElement();
     if (!owner || !owner->hasTagName(objectTag))
         return;
-    static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
+    toHTMLObjectElement(owner)->renderFallbackContent();
 }
 
 bool FrameLoader::allowPlugins(ReasonForCallingAllowPlugins reason)
@@ -733,6 +639,7 @@
     m_documentLoader->appendRedirect(newURL);
 
     m_client->dispatchDidNavigateWithinPage();
+    m_client->dispatchDidReceiveTitle(m_frame->document()->titleWithDirection());
 
     if (m_frame->document()->loadEventFinished())
         m_client->postProgressFinishedNotification();
@@ -769,11 +676,6 @@
     m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
 }
 
-bool FrameLoader::isComplete() const
-{
-    return m_isComplete;
-}
-
 void FrameLoader::completed()
 {
     RefPtr<Frame> protect(m_frame);
@@ -803,10 +705,7 @@
     RefPtr<HistoryItem> currentItem = history()->currentItem();
     if (!currentItem) {
         insertDummyHistoryItem();
-
         ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
-        stateMachine()->advanceTo(FrameLoaderStateMachine::StartedFirstRealLoad);
-        stateMachine()->advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
         stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
     }
 }
@@ -984,7 +883,7 @@
 
 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
 {
-    if (m_pageDismissalEventBeingDispatched != NoDismissal)
+    if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
         return;
 
     // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
@@ -1018,18 +917,6 @@
     m_inStopAllLoaders = false;
 }
 
-void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
-{
-    // stopAllLoaders can detach the Frame, so protect it.
-    RefPtr<Frame> protect(m_frame);
-    stopAllLoaders();
-
-    if (deferCheckLoadComplete)
-        scheduleCheckLoadComplete();
-    else if (m_frame->page())
-        checkLoadComplete();
-}
-
 DocumentLoader* FrameLoader::activeDocumentLoader() const
 {
     if (m_state == FrameStateProvisional)
@@ -1075,8 +962,6 @@
         pdl->timing()->setHasSameOriginAsPreviousDocument(securityOrigin->canRequest(m_frame->document()->url()));
     }
 
-    clearAllowNavigationViaBeforeUnloadConfirmationPanel();
-
     // The call to closeURL() invokes the unload event handler, which can execute arbitrary
     // JavaScript. If the script initiates a new load, we need to abandon the current load,
     // or the two will stomp each other.
@@ -1098,18 +983,11 @@
     m_state = FrameStateCommittedPage;
 
     if (isLoadingMainFrame())
-        m_frame->page()->chrome().client()->needTouchEvents(false);
+        m_frame->page()->chrome().client().needTouchEvents(false);
 
     history()->updateForCommit();
     m_client->transitionToCommittedForNewPage();
 
-    if (!m_stateMachine.creatingInitialEmptyDocument() && !m_stateMachine.committedFirstRealDocumentLoad())
-        m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
-
-    // A redirect was scheduled before the first real document was committed.
-    // This can happen when one frame changes another frame's location.
-    if (m_frame->navigationScheduler()->redirectScheduledDuringLoad())
-        return;
     m_frame->navigationScheduler()->cancel();
     m_frame->editor()->clearLastEditCommand();
 
@@ -1173,7 +1051,7 @@
 
 CachePolicy FrameLoader::subresourceCachePolicy() const
 {
-    if (m_isComplete)
+    if (m_frame->document()->loadEventFinished())
         return CachePolicyVerify;
 
     if (m_loadType == FrameLoadTypeReloadFromOrigin)
@@ -1202,7 +1080,7 @@
     if (m_state != FrameStateCommittedPage)
         return;
 
-    if (!m_documentLoader || (m_documentLoader->isLoadingInAPISense() && !m_documentLoader->isStopping()))
+    if (!m_documentLoader || (m_documentLoader->isLoadingInAPISense() && !m_inStopAllLoaders))
         return;
 
     m_state = FrameStateComplete;
@@ -1275,8 +1153,6 @@
 {
     ASSERT(m_client->hasWebView());
 
-    m_shouldCallCheckLoadComplete = false;
-
     // FIXME: Always traversing the entire frame tree is a bit inefficient, but
     // is currently needed in order to null out the previous history item for all frames.
     if (Page* page = m_frame->page()) {
@@ -1445,9 +1321,8 @@
     RefPtr<Frame> protect(m_frame);
 
     RefPtr<DocumentLoader> loader = activeDocumentLoader();
-    // FIXME: Don't want to do this if an entirely new load is going, so should check
-    // that both data sources on the frame are either this or nil.
-    stop();
+    if (m_frame->document()->parser())
+        m_frame->document()->parser()->stopParsing();
 
     // FIXME: We really ought to be able to just check for isCancellation() here, but there are some
     // ResourceErrors that setIsCancellation() but aren't created by ResourceError::cancelledError().
@@ -1470,7 +1345,7 @@
         // Reset the back forward list to the last committed history item at the top level.
         RefPtr<HistoryItem> item = m_frame->page()->mainFrame()->loader()->history()->currentItem();
         if (isBackForwardLoadType(loadType()) && !history()->provisionalItem() && item)
-            m_frame->page()->backForward()->setCurrentItem(item.get());
+            m_frame->page()->backForward().setCurrentItem(item.get());
     }
 
     checkCompleted();
@@ -1483,7 +1358,7 @@
     m_documentLoader->setTriggeringAction(action);
 
     const ResourceRequest& request = action.resourceRequest();
-    if (!m_documentLoader->shouldContinueForNavigationPolicy(request, DocumentLoader::PolicyCheckStandard))
+    if (!m_documentLoader->shouldContinueForNavigationPolicy(request, DocumentLoader::PolicyCheckFragment))
         return;
 
     // If we have a provisional request for a different document, a fragment scroll should cancel it.
@@ -1552,7 +1427,7 @@
         for (i = 0; i < targetFrames.size(); i++) {
             if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
                 continue;
-            if (!targetFrames[i]->loader()->fireBeforeUnloadEvent(page->chrome(), this))
+            if (!targetFrames[i]->document()->dispatchBeforeUnloadEvent(page->chrome(), m_frame->document()))
                 break;
         }
 
@@ -1566,43 +1441,10 @@
     return shouldClose;
 }
 
-bool FrameLoader::fireBeforeUnloadEvent(Chrome& chrome, FrameLoader* navigatingFrameLoader)
-{
-    DOMWindow* domWindow = m_frame->domWindow();
-    if (!domWindow)
-        return true;
-
-    RefPtr<Document> document = m_frame->document();
-    if (!document->body())
-        return true;
-
-    RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
-    m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
-    domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
-    m_pageDismissalEventBeingDispatched = NoDismissal;
-
-    if (!beforeUnloadEvent->defaultPrevented())
-        document->defaultEventHandler(beforeUnloadEvent.get());
-    if (beforeUnloadEvent->result().isNull())
-        return true;
-
-    if (navigatingFrameLoader->hasAllowedNavigationViaBeforeUnloadConfirmationPanel()) {
-        m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
-        return true;
-    }
-
-    String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->result());
-    if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
-        navigatingFrameLoader->didAllowNavigationViaBeforeUnloadConfirmationPanel();
-        return true;
-    }
-    return false;
-}
-
 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, const String& overrideEncoding)
 {
     ASSERT(m_client->hasWebView());
-    if (m_pageDismissalEventBeingDispatched != NoDismissal)
+    if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
         return;
 
     // We skip dispatching the beforeload event on the frame owner if we've already committed a real
@@ -1630,7 +1472,7 @@
 
     // stopAllLoaders can detach the Frame, so protect it.
     RefPtr<Frame> protect(m_frame);
-    if (!m_policyDocumentLoader->shouldContinueForNavigationPolicy(request, DocumentLoader::PolicyCheckStandard) || !shouldClose()) {
+    if ((!m_policyDocumentLoader->shouldContinueForNavigationPolicy(request, DocumentLoader::PolicyCheckStandard) || !shouldClose()) && m_policyDocumentLoader) {
         m_policyDocumentLoader->detachFromFrame();
         m_policyDocumentLoader = 0;
         return;
@@ -1641,11 +1483,11 @@
 
     // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
     // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
-    if (!m_frame->page())
+    if (!m_frame->page() || !m_policyDocumentLoader)
         return;
 
     if (isLoadingMainFrame())
-        m_frame->page()->inspectorController()->resume();
+        m_frame->page()->inspectorController().resume();
     m_frame->navigationScheduler()->cancel();
 
     m_provisionalDocumentLoader = m_policyDocumentLoader.release();
@@ -1666,7 +1508,7 @@
 
 void FrameLoader::checkNewWindowPolicyAndContinue(PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action)
 {
-    if (m_pageDismissalEventBeingDispatched != NoDismissal)
+    if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
         return;
 
     if (m_frame->document() && m_frame->document()->isSandboxed(SandboxPopups))
@@ -1688,8 +1530,8 @@
 
     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()),
-            features, action, navigationPolicy);
+        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)
@@ -1790,10 +1632,10 @@
     case XFrameOptionsAllowAll:
         return false;
     case XFrameOptionsConflict:
-        m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.elidedString() + "'. Falling back to 'DENY'.", requestIdentifier);
+        m_frame->document()->addConsoleMessageWithRequestIdentifier(JSMessageSource, ErrorMessageLevel, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.elidedString() + "'. Falling back to 'DENY'.", requestIdentifier);
         return true;
     case XFrameOptionsInvalid:
-        m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Invalid 'X-Frame-Options' header encountered when loading '" + url.elidedString() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
+        m_frame->document()->addConsoleMessageWithRequestIdentifier(JSMessageSource, ErrorMessageLevel, "Invalid 'X-Frame-Options' header encountered when loading '" + url.elidedString() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
         return false;
     default:
         ASSERT_NOT_REACHED();
@@ -1856,30 +1698,17 @@
     return frame;
 }
 
-void FrameLoader::loadSameDocumentItem(HistoryItem* item)
+void FrameLoader::loadHistoryItem(HistoryItem* item)
 {
-    ASSERT(item->documentSequenceNumber() == history()->currentItem()->documentSequenceNumber());
+    m_requestedHistoryItem = item;
+    HistoryItem* currentItem = history()->currentItem();
 
-    // Save user view state to the current history item here since we don't do a normal load.
-    // FIXME: Does form state need to be saved here too?
-    history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
-    if (FrameView* view = m_frame->view())
-        view->setWasScrolledByUser(false);
+    if (currentItem && item->shouldDoSameDocumentNavigationTo(currentItem)) {
+        history()->setCurrentItem(item);
+        loadInSameDocument(item->url(), item->stateObject(), false);
+        return;
+    }
 
-    history()->setCurrentItem(item);
-
-    // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
-    loadInSameDocument(item->url(), item->stateObject(), false);
-
-    // Restore user view state from the current history item here since we don't do a normal load.
-    history()->restoreScrollPositionAndViewState();
-}
-
-// FIXME: This function should really be split into a couple pieces, some of
-// which should be methods of HistoryController and some of which should be
-// methods of FrameLoader.
-void FrameLoader::loadDifferentDocumentItem(HistoryItem* item)
-{
     // Remember this item so we can traverse any child items as child frames load
     history()->setProvisionalItem(item);
 
@@ -1897,33 +1726,11 @@
     loadWithNavigationAction(request, NavigationAction(request, FrameLoadTypeBackForward, false), FrameLoadTypeBackForward, 0, SubstituteData());
 }
 
-void FrameLoader::loadHistoryItem(HistoryItem* item)
-{
-    m_requestedHistoryItem = item;
-    HistoryItem* currentItem = history()->currentItem();
-    bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
-
-    if (sameDocumentNavigation)
-        loadSameDocumentItem(item);
-    else
-        loadDifferentDocumentItem(item);
-}
-
 void FrameLoader::insertDummyHistoryItem()
 {
     RefPtr<HistoryItem> currentItem = HistoryItem::create();
     history()->setCurrentItem(currentItem.get());
-    frame()->page()->backForward()->setCurrentItem(currentItem.get());
-}
-
-void FrameLoader::setTitle(const StringWithDirection& title)
-{
-    documentLoader()->setTitle(title);
-}
-
-String FrameLoader::referrer() const
-{
-    return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
+    frame()->page()->backForward().setCurrentItem(currentItem.get());
 }
 
 void FrameLoader::dispatchDocumentElementAvailable()
@@ -1950,7 +1757,7 @@
     m_client->dispatchDidClearWindowObjectInWorld(world);
 
     if (Page* page = m_frame->page())
-        page->inspectorController()->didClearWindowObjectInWorld(m_frame, world);
+        page->inspectorController().didClearWindowObjectInWorld(m_frame, world);
 
     InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
 }
@@ -1965,26 +1772,4 @@
     return flags;
 }
 
-void FrameLoader::didChangeTitle(DocumentLoader* loader)
-{
-    if (loader == m_documentLoader) {
-        // Must update the entries in the back-forward list too.
-        history()->setCurrentItemTitle(loader->title());
-        m_client->dispatchDidReceiveTitle(loader->title());
-    }
-}
-
-void FrameLoader::dispatchDidCommitLoad()
-{
-    m_client->dispatchDidCommitLoad();
-
-    InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
-
-    m_frame->page()->didCommitLoad(m_frame);
-
-    if (m_frame->page()->mainFrame() == m_frame)
-        m_frame->page()->useCounter()->didCommitLoad();
-
-}
-
 } // namespace WebCore
diff --git a/Source/core/loader/FrameLoader.h b/Source/core/loader/FrameLoader.h
index 9fb2527..8d07545 100644
--- a/Source/core/loader/FrameLoader.h
+++ b/Source/core/loader/FrameLoader.h
@@ -34,13 +34,13 @@
 
 #include "core/dom/IconURL.h"
 #include "core/dom/SecurityContext.h"
+#include "core/fetch/CachePolicy.h"
+#include "core/fetch/ResourceLoadNotifier.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "core/loader/FrameLoaderStateMachine.h"
 #include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/HistoryController.h"
 #include "core/loader/MixedContentChecker.h"
-#include "core/loader/ResourceLoadNotifier.h"
-#include "core/loader/ResourceLoaderOptions.h"
-#include "core/loader/cache/CachePolicy.h"
 #include "core/page/LayoutMilestones.h"
 #include "core/platform/Timer.h"
 #include "wtf/Forward.h"
@@ -107,13 +107,10 @@
     // Warning: stopAllLoaders can and will detach the Frame out from under you. All callers need to either protect the Frame
     // or guarantee they won't in any way access the Frame after stopAllLoaders returns.
     void stopAllLoaders(ClearProvisionalItemPolicy = ShouldClearProvisionalItem);
-    void stopForUserCancel(bool deferCheckLoadComplete = false);
-    void stop();
-    void stopLoading(UnloadEventPolicy);
+    void stopLoading();
     bool closeURL();
-    void cancelAndClear();
-    // FIXME: clear() is trying to do too many things. We should break it down into smaller functions (ideally with fewer raw Boolean parameters).
-    void clear(bool clearWindowProperties = true, bool clearScriptObjects = true, bool clearFrameView = true);
+    // FIXME: clear() is trying to do too many things. We should break it down into smaller functions.
+    void clear(ClearOptions);
 
     void didAccessInitialDocument();
     void didAccessInitialDocumentTimerFired(Timer<FrameLoader>*);
@@ -121,7 +118,6 @@
     bool isLoading() const;
 
     int numPendingOrLoadingRequests(bool recurse) const;
-    String referrer() const;
     String outgoingReferrer() const;
     String outgoingOrigin() const;
 
@@ -142,7 +138,6 @@
     bool isLoadingMainFrame() const;
 
     bool subframeIsLoading() const;
-    void didChangeTitle(DocumentLoader*);
 
     bool shouldTreatURLAsSrcdocDocument(const KURL&) const;
 
@@ -200,10 +195,6 @@
     void finishedParsing();
     void checkCompleted();
 
-    bool isComplete() const;
-
-    void setTitle(const StringWithDirection&);
-
     void commitProvisionalLoad();
 
     FrameLoaderStateMachine* stateMachine() const { return &m_stateMachine; }
@@ -214,7 +205,6 @@
 
     bool shouldInterruptLoadForXFrameOptions(const String&, const KURL&, unsigned long requestIdentifier);
 
-    void completed();
     bool allAncestorsAreComplete() const; // including this
 
     bool suppressOpenerInNewFrame() const { return m_suppressOpenerInNewFrame; }
@@ -227,23 +217,15 @@
     bool containsPlugins() const { return m_containsPlugins; }
     bool allowPlugins(ReasonForCallingAllowPlugins);
 
-    enum PageDismissalType {
-        NoDismissal = 0,
-        BeforeUnloadDismissal = 1,
-        PageHideDismissal = 2,
-        UnloadDismissal = 3
-    };
-    PageDismissalType pageDismissalEventBeingDispatched() const { return m_pageDismissalEventBeingDispatched; }
-
     void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, const String& title);
 
 private:
     bool allChildrenAreComplete() const; // immediate children, not all descendants
 
+    void completed();
+
     void checkTimerFired(Timer<FrameLoader>*);
 
-    void loadSameDocumentItem(HistoryItem*);
-    void loadDifferentDocumentItem(HistoryItem*);
     void insertDummyHistoryItem();
 
     bool prepareRequestForThisFrame(FrameLoadRequest&);
@@ -252,11 +234,6 @@
 
     SubstituteData defaultSubstituteDataForURL(const KURL&);
 
-    bool fireBeforeUnloadEvent(Chrome&, FrameLoader*);
-    bool hasAllowedNavigationViaBeforeUnloadConfirmationPanel() const { return m_hasAllowedNavigationViaBeforeUnloadConfirmationPanel; }
-    void didAllowNavigationViaBeforeUnloadConfirmationPanel() { m_hasAllowedNavigationViaBeforeUnloadConfirmationPanel = true; }
-    void clearAllowNavigationViaBeforeUnloadConfirmationPanel() { m_hasAllowedNavigationViaBeforeUnloadConfirmationPanel = false; }
-
     void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&, bool isNewNavigation);
     void checkNewWindowPolicyAndContinue(PassRefPtr<FormState>, const String& frameName, const NavigationAction&);
 
@@ -267,8 +244,6 @@
 
     void closeOldDataSources();
 
-    void dispatchDidCommitLoad();
-
     // Calls continueLoadAfterNavigationPolicy
     void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&,
         FrameLoadType, PassRefPtr<FormState>, const SubstituteData&, const String& overrideEncoding = String());
@@ -281,7 +256,6 @@
     void loadInSameDocument(const KURL&, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation);
 
     void scheduleCheckCompleted();
-    void scheduleCheckLoadComplete();
     void startCheckCompleteTimer();
 
     bool shouldTreatURLAsSameAsCurrent(const KURL&) const;
@@ -316,17 +290,15 @@
 
     String m_outgoingReferrer;
 
-    PageDismissalType m_pageDismissalEventBeingDispatched;
+    // FIXME: This is only used in checkCompleted(). Figure out a way to disentangle it.
     bool m_isComplete;
 
-    bool m_needsClear;
     bool m_containsPlugins;
 
     KURL m_submittedFormURL;
 
     Timer<FrameLoader> m_checkTimer;
     bool m_shouldCallCheckCompleted;
-    bool m_shouldCallCheckLoadComplete;
 
     Frame* m_opener;
     HashSet<Frame*> m_openedFrames;
@@ -338,8 +310,6 @@
 
     SandboxFlags m_forcedSandboxFlags;
 
-    bool m_hasAllowedNavigationViaBeforeUnloadConfirmationPanel;
-
     RefPtr<HistoryItem> m_requestedHistoryItem;
 };
 
diff --git a/Source/core/loader/FrameLoaderClient.h b/Source/core/loader/FrameLoaderClient.h
index f02a306..1e7c6ac 100644
--- a/Source/core/loader/FrameLoaderClient.h
+++ b/Source/core/loader/FrameLoaderClient.h
@@ -114,7 +114,7 @@
 
         virtual void dispatchDidLayout(LayoutMilestones) { }
 
-        virtual NavigationPolicy decidePolicyForNavigation(const ResourceRequest&, NavigationType, NavigationPolicy, bool isRedirect) = 0;
+        virtual NavigationPolicy decidePolicyForNavigation(const ResourceRequest&, DocumentLoader*, NavigationPolicy) = 0;
 
         virtual void dispatchWillRequestResource(FetchRequest*) { }
 
@@ -128,8 +128,7 @@
 
         virtual void loadURLExternally(const ResourceRequest&, NavigationPolicy, const String& suggestedName = String()) = 0;
 
-        virtual bool shouldGoToHistoryItem(HistoryItem*) const = 0;
-        virtual bool shouldStopLoadingForHistoryItem(HistoryItem*) const = 0;
+        virtual void navigateBackForward(int offset) const = 0;
 
         // Another page has accessed the initial empty document of this frame.
         // It is no longer safe to display a provisional URL, since a URL spoof
diff --git a/Source/core/loader/FrameLoaderStateMachine.cpp b/Source/core/loader/FrameLoaderStateMachine.cpp
index 4cff5c7..2ad0e23 100644
--- a/Source/core/loader/FrameLoaderStateMachine.cpp
+++ b/Source/core/loader/FrameLoaderStateMachine.cpp
@@ -46,7 +46,7 @@
 
 bool FrameLoaderStateMachine::committedFirstRealDocumentLoad() const
 {
-    return m_state >= DisplayingInitialEmptyDocumentPostCommit;
+    return m_state == CommittedFirstRealLoad;
 }
 
 bool FrameLoaderStateMachine::creatingInitialEmptyDocument() const
@@ -56,12 +56,12 @@
 
 bool FrameLoaderStateMachine::isDisplayingInitialEmptyDocument() const
 {
-    return m_state >= DisplayingInitialEmptyDocument && m_state <= DisplayingInitialEmptyDocumentPostCommit;
+    return m_state >= DisplayingInitialEmptyDocument && m_state < CommittedFirstRealLoad;
 }
 
 void FrameLoaderStateMachine::advanceTo(State state)
 {
-    ASSERT(State(m_state + 1) == state);
+    ASSERT(m_state < state);
     m_state = state;
 }
 
diff --git a/Source/core/loader/FrameLoaderStateMachine.h b/Source/core/loader/FrameLoaderStateMachine.h
index b20ad6b..e8d1a2a 100644
--- a/Source/core/loader/FrameLoaderStateMachine.h
+++ b/Source/core/loader/FrameLoaderStateMachine.h
@@ -47,7 +47,6 @@
         CreatingInitialEmptyDocument,
         DisplayingInitialEmptyDocument,
         StartedFirstRealLoad,
-        DisplayingInitialEmptyDocumentPostCommit,
         CommittedFirstRealLoad
     };
 
diff --git a/Source/core/loader/FrameLoaderTypes.h b/Source/core/loader/FrameLoaderTypes.h
index a7444ba..53c6f0d 100644
--- a/Source/core/loader/FrameLoaderTypes.h
+++ b/Source/core/loader/FrameLoaderTypes.h
@@ -71,11 +71,12 @@
         ObjectContentOtherPlugin
     };
 
-    enum UnloadEventPolicy {
-        UnloadEventPolicyNone,
-        UnloadEventPolicyUnloadOnly,
-        UnloadEventPolicyUnloadAndPageHide
+    enum ClearOption {
+        ClearWindowProperties = 1 << 0,
+        ClearScriptObjects = 1 << 1,
+        ClearWindowObject = 1 << 2,
     };
+    typedef int ClearOptions;
 
     enum ShouldSendReferrer {
         MaybeSendReferrer,
diff --git a/Source/core/loader/HistoryController.cpp b/Source/core/loader/HistoryController.cpp
index 900765c..2a93d71 100644
--- a/Source/core/loader/HistoryController.cpp
+++ b/Source/core/loader/HistoryController.cpp
@@ -196,12 +196,8 @@
 {
     if (!m_currentItem)
         return false;
-
     // Don't abort the current load if we're navigating within the current document.
-    if (m_currentItem->shouldDoSameDocumentNavigationTo(targetItem))
-        return false;
-
-    return m_frame->loader()->client()->shouldStopLoadingForHistoryItem(targetItem);
+    return !m_currentItem->shouldDoSameDocumentNavigationTo(targetItem);
 }
 
 // Main funnel for navigating to a previous location (back/forward, non-search snap-back)
@@ -217,8 +213,6 @@
     Page* page = m_frame->page();
     if (!page)
         return;
-    if (!m_frame->loader()->client()->shouldGoToHistoryItem(targetItem))
-        return;
     if (m_defersLoading) {
         m_deferredItem = targetItem;
         return;
@@ -227,8 +221,8 @@
     // Set the BF cursor before commit, which lets the user quickly click back/forward again.
     // - plus, it only makes sense for the top level of the operation through the frametree,
     // as opposed to happening for some/one of the page commits that might happen soon
-    RefPtr<HistoryItem> currentItem = page->backForward()->currentItem();
-    page->backForward()->setCurrentItem(targetItem);
+    RefPtr<HistoryItem> currentItem = page->backForward().currentItem();
+    page->backForward().setCurrentItem(targetItem);
 
     // 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
@@ -251,8 +245,7 @@
 void HistoryController::updateForBackForwardNavigation()
 {
 #if !LOG_DISABLED
-    if (m_frame->loader()->documentLoader())
-        LOG(History, "WebCoreHistory: Updating History for back/forward navigation in frame %s", m_frame->loader()->documentLoader()->title().string().utf8().data());
+    LOG(History, "WebCoreHistory: Updating History for back/forward navigation in frame %s", m_frame->document()->title().utf8().data());
 #endif
 
     saveScrollPositionAndViewStateToItem(m_previousItem.get());
@@ -265,8 +258,7 @@
 void HistoryController::updateForReload()
 {
 #if !LOG_DISABLED
-    if (m_frame->loader()->documentLoader())
-        LOG(History, "WebCoreHistory: Updating History for reload in frame %s", m_frame->loader()->documentLoader()->title().string().utf8().data());
+    LOG(History, "WebCoreHistory: Updating History for reload in frame %s", m_frame->document()->title().utf8().data());
 #endif
 
     if (m_currentItem) {
@@ -295,7 +287,7 @@
 void HistoryController::updateForRedirectWithLockedBackForwardList()
 {
 #if !LOG_DISABLED
-    LOG(History, "WebCoreHistory: Updating History for redirect load in frame %s", m_frame->loader()->documentLoader()->title().string().utf8().data());
+    LOG(History, "WebCoreHistory: Updating History for redirect load in frame %s", m_frame->document()->title().utf8().data());
 #endif
 
     if (!m_currentItem && !m_frame->tree()->parent()) {
@@ -317,8 +309,8 @@
 {
     FrameLoader* frameLoader = m_frame->loader();
 #if !LOG_DISABLED
-    if (frameLoader->documentLoader())
-        LOG(History, "WebCoreHistory: Updating History for commit in frame %s", frameLoader->documentLoader()->title().string().utf8().data());
+    if (m_frame->document())
+        LOG(History, "WebCoreHistory: Updating History for commit in frame %s", m_frame->document()->title().utf8().data());
 #endif
     FrameLoadType type = frameLoader->loadType();
     if (isBackForwardLoadType(type) || (isReloadTypeWithProvisionalItem(type) && !frameLoader->documentLoader()->unreachableURL().isEmpty())) {
@@ -495,13 +487,12 @@
 
     Frame* parentFrame = m_frame->tree()->parent();
     String parent = parentFrame ? parentFrame->tree()->uniqueName() : "";
-    StringWithDirection title = documentLoader->title();
 
     item->setURL(url);
     item->setTarget(m_frame->tree()->uniqueName());
     item->setParent(parent);
     // FIXME: should store title directionality in history as well.
-    item->setTitle(title.string());
+    item->setTitle(m_frame->document()->title());
     item->setOriginalURLString(originalURL.string());
 
     // Save form state if this is a POST
@@ -660,7 +651,7 @@
 
     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());
-    page->backForward()->addItem(topItem.release());
+    page->backForward().addItem(topItem.release());
 }
 
 void HistoryController::updateCurrentItem()
@@ -704,8 +695,7 @@
     m_currentItem->setTitle(title);
     m_currentItem->setStateObject(stateObject);
     m_currentItem->setURLString(urlString);
-
-    page->backForward()->addItem(topItem.release());
+    page->backForward().addItem(topItem.release());
 }
 
 void HistoryController::replaceState(PassRefPtr<SerializedScriptValue> stateObject, const String& title, const String& urlString)
diff --git a/Source/core/loader/ImageLoader.cpp b/Source/core/loader/ImageLoader.cpp
index 668cb97..84132cf 100644
--- a/Source/core/loader/ImageLoader.cpp
+++ b/Source/core/loader/ImageLoader.cpp
@@ -27,12 +27,12 @@
 #include "core/dom/Element.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventSender.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Frame.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderVideo.h"
@@ -61,8 +61,7 @@
 
 static inline bool pageIsBeingDismissed(Document* document)
 {
-    Frame* frame = document->frame();
-    return frame && frame->loader()->pageDismissalEventBeingDispatched() != FrameLoader::NoDismissal;
+    return document->pageDismissalEventBeingDispatched() != Document::NoDismissal;
 }
 
 ImageLoader::ImageLoader(Element* element)
@@ -395,7 +394,7 @@
     m_hasPendingLoadEvent = false;
 
     if (m_element->hasTagName(HTMLNames::objectTag))
-        static_cast<HTMLObjectElement*>(m_element)->renderFallbackContent();
+        toHTMLObjectElement(m_element)->renderFallbackContent();
 
     // Only consider updating the protection ref-count of the Element immediately before returning
     // from this function as doing so might result in the destruction of this ImageLoader.
diff --git a/Source/core/loader/ImageLoader.h b/Source/core/loader/ImageLoader.h
index dfb6ad0..6c1274f 100644
--- a/Source/core/loader/ImageLoader.h
+++ b/Source/core/loader/ImageLoader.h
@@ -23,9 +23,9 @@
 #ifndef ImageLoader_h
 #define ImageLoader_h
 
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ImageResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ImageResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "wtf/HashSet.h"
 #include "wtf/text/AtomicString.h"
 
diff --git a/Source/core/loader/LinkLoader.cpp b/Source/core/loader/LinkLoader.cpp
index 256de17..c487098 100644
--- a/Source/core/loader/LinkLoader.cpp
+++ b/Source/core/loader/LinkLoader.cpp
@@ -34,10 +34,10 @@
 
 #include "FetchInitiatorTypeNames.h"
 #include "core/dom/Document.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/LinkRelAttribute.h"
 #include "core/loader/Prerenderer.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Settings.h"
 #include "core/platform/PrerenderHandle.h"
 #include "core/platform/network/DNS.h"
diff --git a/Source/core/loader/LinkLoader.h b/Source/core/loader/LinkLoader.h
index 21a6281..086be49 100644
--- a/Source/core/loader/LinkLoader.h
+++ b/Source/core/loader/LinkLoader.h
@@ -32,9 +32,9 @@
 #ifndef LinkLoader_h
 #define LinkLoader_h
 
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/loader/LinkLoaderClient.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/PrerenderClient.h"
 #include "core/platform/Timer.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/loader/MixedContentChecker.cpp b/Source/core/loader/MixedContentChecker.cpp
index 707de33..ac812e0 100644
--- a/Source/core/loader/MixedContentChecker.cpp
+++ b/Source/core/loader/MixedContentChecker.cpp
@@ -91,7 +91,7 @@
 
 void MixedContentChecker::logWarning(bool allowed, const String& action, const KURL& target) const
 {
-    String message = String(allowed ? "" : "[blocked] ") + "The page at " + m_frame->document()->url().elidedString() + " " + action + " insecure content from " + target.elidedString() + ".\n";
+    String message = String(allowed ? "" : "[blocked] ") + "The page at '" + m_frame->document()->url().elidedString() + "' was loaded over HTTPS, but " + action + " insecure content from '" + target.elidedString() + "': this content should also be loaded over HTTPS.\n";
     m_frame->document()->addConsoleMessage(SecurityMessageSource, WarningMessageLevel, message);
 }
 
diff --git a/Source/core/loader/NavigationAction.cpp b/Source/core/loader/NavigationAction.cpp
index bf0107c..603f40a 100644
--- a/Source/core/loader/NavigationAction.cpp
+++ b/Source/core/loader/NavigationAction.cpp
@@ -53,32 +53,6 @@
 {
 }
 
-NavigationAction::NavigationAction(const ResourceRequest& resourceRequest)
-    : m_resourceRequest(resourceRequest)
-    , m_type(NavigationTypeOther)
-{
-}
-
-NavigationAction::NavigationAction(const ResourceRequest& resourceRequest, NavigationType type)
-    : m_resourceRequest(resourceRequest)
-    , m_type(type)
-{
-}
-
-NavigationAction::NavigationAction(const ResourceRequest& resourceRequest, FrameLoadType frameLoadType,
-        bool isFormSubmission)
-    : m_resourceRequest(resourceRequest)
-    , m_type(navigationType(frameLoadType, isFormSubmission, 0))
-{
-}
-
-NavigationAction::NavigationAction(const ResourceRequest& resourceRequest, NavigationType type, PassRefPtr<Event> event)
-    : m_resourceRequest(resourceRequest)
-    , m_type(type)
-    , m_event(event)
-{
-}
-
 NavigationAction::NavigationAction(const ResourceRequest& resourceRequest, FrameLoadType frameLoadType,
         bool isFormSubmission, PassRefPtr<Event> event)
     : m_resourceRequest(resourceRequest)
diff --git a/Source/core/loader/NavigationAction.h b/Source/core/loader/NavigationAction.h
index a402d95..5ba25f3 100644
--- a/Source/core/loader/NavigationAction.h
+++ b/Source/core/loader/NavigationAction.h
@@ -41,11 +41,7 @@
     class NavigationAction {
     public:
         NavigationAction();
-        explicit NavigationAction(const ResourceRequest&);
-        NavigationAction(const ResourceRequest&, NavigationType);
-        NavigationAction(const ResourceRequest&, FrameLoadType, bool isFormSubmission);
-        NavigationAction(const ResourceRequest&, NavigationType, PassRefPtr<Event>);
-        NavigationAction(const ResourceRequest&, FrameLoadType, bool isFormSubmission, PassRefPtr<Event>);
+        NavigationAction(const ResourceRequest&, FrameLoadType = FrameLoadTypeStandard, bool isFormSubmission = false, PassRefPtr<Event> = 0);
 
         const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
         NavigationType type() const { return m_type; }
diff --git a/Source/core/loader/NavigationScheduler.cpp b/Source/core/loader/NavigationScheduler.cpp
index 9547744..7a42972 100644
--- a/Source/core/loader/NavigationScheduler.cpp
+++ b/Source/core/loader/NavigationScheduler.cpp
@@ -55,10 +55,9 @@
 class ScheduledNavigation {
     WTF_MAKE_NONCOPYABLE(ScheduledNavigation); WTF_MAKE_FAST_ALLOCATED;
 public:
-    ScheduledNavigation(double delay, bool lockBackForwardList, bool wasDuringLoad, bool isLocationChange)
+    ScheduledNavigation(double delay, bool lockBackForwardList, bool isLocationChange)
         : m_delay(delay)
         , m_lockBackForwardList(lockBackForwardList)
-        , m_wasDuringLoad(wasDuringLoad)
         , m_isLocationChange(isLocationChange)
         , m_wasUserGesture(ScriptController::processingUserGesture())
     {
@@ -75,7 +74,6 @@
     double delay() const { return m_delay; }
     bool lockBackForwardList() const { return m_lockBackForwardList; }
     void setLockBackForwardList(bool lockBackForwardList) { m_lockBackForwardList = lockBackForwardList; }
-    bool wasDuringLoad() const { return m_wasDuringLoad; }
     bool isLocationChange() const { return m_isLocationChange; }
     PassOwnPtr<UserGestureIndicator> createUserGestureIndicator()
     {
@@ -90,7 +88,6 @@
 private:
     double m_delay;
     bool m_lockBackForwardList;
-    bool m_wasDuringLoad;
     bool m_isLocationChange;
     bool m_wasUserGesture;
     RefPtr<UserGestureToken> m_userGestureToken;
@@ -98,8 +95,8 @@
 
 class ScheduledURLNavigation : public ScheduledNavigation {
 protected:
-    ScheduledURLNavigation(double delay, SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList, bool duringLoad, bool isLocationChange)
-        : ScheduledNavigation(delay, lockBackForwardList, duringLoad, isLocationChange)
+    ScheduledURLNavigation(double delay, SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList, bool isLocationChange)
+        : ScheduledNavigation(delay, lockBackForwardList, isLocationChange)
         , m_securityOrigin(securityOrigin)
         , m_url(url)
         , m_referrer(referrer)
@@ -141,7 +138,7 @@
 class ScheduledRedirect : public ScheduledURLNavigation {
 public:
     ScheduledRedirect(double delay, SecurityOrigin* securityOrigin, const String& url, bool lockBackForwardList)
-        : ScheduledURLNavigation(delay, securityOrigin, url, String(), lockBackForwardList, false, false)
+        : ScheduledURLNavigation(delay, securityOrigin, url, String(), lockBackForwardList, false)
     {
         clearUserGesture();
     }
@@ -162,14 +159,14 @@
 
 class ScheduledLocationChange : public ScheduledURLNavigation {
 public:
-    ScheduledLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList, bool duringLoad)
-        : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, lockBackForwardList, duringLoad, true) { }
+    ScheduledLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList)
+        : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, lockBackForwardList, true) { }
 };
 
 class ScheduledRefresh : public ScheduledURLNavigation {
 public:
     ScheduledRefresh(SecurityOrigin* securityOrigin, const String& url, const String& referrer)
-        : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, true, false, true)
+        : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, true, true)
     {
     }
 
@@ -186,7 +183,7 @@
 class ScheduledHistoryNavigation : public ScheduledNavigation {
 public:
     explicit ScheduledHistoryNavigation(int historySteps)
-        : ScheduledNavigation(0, false, false, true)
+        : ScheduledNavigation(0, false, true)
         , m_historySteps(historySteps)
     {
     }
@@ -205,7 +202,7 @@
         }
         // go(i!=0) from a frame navigates into the history of the frame only,
         // in both IE and NS (but not in Mozilla). We can't easily do that.
-        frame->page()->backForward()->goBackOrForward(m_historySteps);
+        frame->page()->backForward().goBackOrForward(m_historySteps);
     }
 
 private:
@@ -214,8 +211,8 @@
 
 class ScheduledFormSubmission : public ScheduledNavigation {
 public:
-    ScheduledFormSubmission(PassRefPtr<FormSubmission> submission, bool lockBackForwardList, bool duringLoad)
-        : ScheduledNavigation(0, lockBackForwardList, duringLoad, true)
+    ScheduledFormSubmission(PassRefPtr<FormSubmission> submission, bool lockBackForwardList)
+        : ScheduledNavigation(0, lockBackForwardList, true)
         , m_submission(submission)
         , m_haveToldClient(false)
     {
@@ -267,11 +264,6 @@
 {
 }
 
-bool NavigationScheduler::redirectScheduledDuringLoad()
-{
-    return m_redirect && m_redirect->wasDuringLoad();
-}
-
 bool NavigationScheduler::locationChangePending()
 {
     return m_redirect && m_redirect->isLocationChange();
@@ -319,12 +311,7 @@
     // 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.
-    for (Frame* ancestor = targetFrame->tree()->parent(); ancestor; ancestor = ancestor->tree()->parent()) {
-        Document* document = ancestor->document();
-        if (!ancestor->loader()->isComplete() || (document && document->processingLoadEvent()))
-            return true;
-    }
-    return false;
+    return targetFrame->tree()->parent() && !targetFrame->tree()->parent()->loader()->allAncestorsAreComplete();
 }
 
 void NavigationScheduler::scheduleLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList)
@@ -353,11 +340,7 @@
         }
     }
 
-    // Handle a location change of a page with no document as a special case.
-    // This may happen when a frame changes the location of another frame.
-    bool duringLoad = !loader->stateMachine()->committedFirstRealDocumentLoad();
-
-    schedule(adoptPtr(new ScheduledLocationChange(securityOrigin, url, referrer, lockBackForwardList, duringLoad)));
+    schedule(adoptPtr(new ScheduledLocationChange(securityOrigin, url, referrer, lockBackForwardList)));
 }
 
 void NavigationScheduler::scheduleFormSubmission(PassRefPtr<FormSubmission> submission)
@@ -367,10 +350,6 @@
     // FIXME: Do we need special handling for form submissions where the URL is the same
     // as the current one except for the fragment part? See scheduleLocationChange above.
 
-    // Handle a location change of a page with no document as a special case.
-    // This may happen when a frame changes the location of another frame.
-    bool duringLoad = !m_frame->loader()->stateMachine()->committedFirstRealDocumentLoad();
-
     // If this is a child frame and the form submission was triggered by a script, lock the back/forward list
     // to match IE and Opera.
     // See https://bugs.webkit.org/show_bug.cgi?id=32383 for the original motivation for this.
@@ -378,7 +357,7 @@
         || (submission->state()->formSubmissionTrigger() == SubmittedByJavaScript
             && m_frame->tree()->parent() && !ScriptController::processingUserGesture());
 
-    schedule(adoptPtr(new ScheduledFormSubmission(submission, lockBackForwardList, duringLoad)));
+    schedule(adoptPtr(new ScheduledFormSubmission(submission, lockBackForwardList)));
 }
 
 void NavigationScheduler::scheduleRefresh()
@@ -399,8 +378,8 @@
 
     // Invalid history navigations (such as history.forward() during a new load) have the side effect of cancelling any scheduled
     // redirects. We also avoid the possibility of cancelling the current load by avoiding the scheduled redirection altogether.
-    BackForwardController* backForward = m_frame->page()->backForward();
-    if (steps > backForward->forwardCount() || -steps > backForward->backCount()) {
+    BackForwardController& backForward = m_frame->page()->backForward();
+    if (steps > backForward.forwardCount() || -steps > backForward.backCount()) {
         cancel();
         return;
     }
@@ -428,27 +407,8 @@
 void NavigationScheduler::schedule(PassOwnPtr<ScheduledNavigation> redirect)
 {
     ASSERT(m_frame->page());
-
-    RefPtr<Frame> protect(m_frame);
-
-    // If a redirect was scheduled during a load, then stop the current load.
-    // Otherwise when the current load transitions from a provisional to a
-    // committed state, pending redirects may be cancelled.
-    if (redirect->wasDuringLoad()) {
-        if (DocumentLoader* provisionalDocumentLoader = m_frame->loader()->provisionalDocumentLoader())
-            provisionalDocumentLoader->stopLoading();
-        m_frame->loader()->stopLoading(UnloadEventPolicyUnloadAndPageHide);
-    }
-
     cancel();
     m_redirect = redirect;
-
-    if (!m_frame->loader()->isComplete() && m_redirect->isLocationChange())
-        m_frame->loader()->completed();
-
-    if (!m_frame->page())
-        return;
-
     startTimer();
 }
 
diff --git a/Source/core/loader/NavigationScheduler.h b/Source/core/loader/NavigationScheduler.h
index 5af364d..741cacd 100644
--- a/Source/core/loader/NavigationScheduler.h
+++ b/Source/core/loader/NavigationScheduler.h
@@ -71,7 +71,6 @@
     explicit NavigationScheduler(Frame*);
     ~NavigationScheduler();
 
-    bool redirectScheduledDuringLoad();
     bool locationChangePending();
 
     void scheduleRedirect(double delay, const String& url);
diff --git a/Source/core/loader/PingLoader.h b/Source/core/loader/PingLoader.h
index a25a5c6..80f7070 100644
--- a/Source/core/loader/PingLoader.h
+++ b/Source/core/loader/PingLoader.h
@@ -32,7 +32,7 @@
 #ifndef PingLoader_h
 #define PingLoader_h
 
-#include "core/loader/ResourceLoaderOptions.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "core/platform/Timer.h"
 #include "public/platform/WebURLLoaderClient.h"
 #include "wtf/Noncopyable.h"
diff --git a/Source/core/loader/TextTrackLoader.cpp b/Source/core/loader/TextTrackLoader.cpp
index 9c548eb..a8e1b70 100644
--- a/Source/core/loader/TextTrackLoader.cpp
+++ b/Source/core/loader/TextTrackLoader.cpp
@@ -29,11 +29,11 @@
 
 #include "FetchInitiatorTypeNames.h"
 #include "core/dom/Document.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/TextTrackResource.h"
 #include "core/html/track/WebVTTParser.h"
 #include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/TextTrackResource.h"
 #include "core/platform/Logging.h"
 #include "core/platform/SharedBuffer.h"
 #include "weborigin/SecurityOrigin.h"
diff --git a/Source/core/loader/TextTrackLoader.h b/Source/core/loader/TextTrackLoader.h
index dd2feeb..4eb68a8 100644
--- a/Source/core/loader/TextTrackLoader.h
+++ b/Source/core/loader/TextTrackLoader.h
@@ -26,10 +26,10 @@
 #ifndef TextTrackLoader_h
 #define TextTrackLoader_h
 
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/TextTrackResource.h"
 #include "core/html/track/WebVTTParser.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
-#include "core/loader/cache/TextTrackResource.h"
 #include "core/platform/Timer.h"
 #include "wtf/OwnPtr.h"
 
diff --git a/Source/core/loader/ThreadableLoader.h b/Source/core/loader/ThreadableLoader.h
index 6df1a5c..a2afdd1 100644
--- a/Source/core/loader/ThreadableLoader.h
+++ b/Source/core/loader/ThreadableLoader.h
@@ -31,7 +31,7 @@
 #ifndef ThreadableLoader_h
 #define ThreadableLoader_h
 
-#include "core/loader/ResourceLoaderOptions.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/PassRefPtr.h"
diff --git a/Source/core/loader/appcache/DOMApplicationCache.cpp b/Source/core/loader/appcache/ApplicationCache.cpp
similarity index 74%
rename from Source/core/loader/appcache/DOMApplicationCache.cpp
rename to Source/core/loader/appcache/ApplicationCache.cpp
index 7c4e6d1..786c8fd 100644
--- a/Source/core/loader/appcache/DOMApplicationCache.cpp
+++ b/Source/core/loader/appcache/ApplicationCache.cpp
@@ -24,8 +24,9 @@
  */
 
 #include "config.h"
-#include "core/loader/appcache/DOMApplicationCache.h"
+#include "core/loader/appcache/ApplicationCache.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/EventListener.h"
@@ -38,30 +39,30 @@
 
 namespace WebCore {
 
-DOMApplicationCache::DOMApplicationCache(Frame* frame)
+ApplicationCache::ApplicationCache(Frame* frame)
     : DOMWindowProperty(frame)
 {
     ScriptWrappable::init(this);
     ApplicationCacheHost* cacheHost = applicationCacheHost();
     if (cacheHost)
-        cacheHost->setDOMApplicationCache(this);
+        cacheHost->setApplicationCache(this);
 }
 
-void DOMApplicationCache::willDestroyGlobalObjectInFrame()
+void ApplicationCache::willDestroyGlobalObjectInFrame()
 {
     if (ApplicationCacheHost* cacheHost = applicationCacheHost())
-        cacheHost->setDOMApplicationCache(0);
+        cacheHost->setApplicationCache(0);
     DOMWindowProperty::willDestroyGlobalObjectInFrame();
 }
 
-ApplicationCacheHost* DOMApplicationCache::applicationCacheHost() const
+ApplicationCacheHost* ApplicationCache::applicationCacheHost() const
 {
     if (!m_frame || !m_frame->loader()->documentLoader())
         return 0;
     return m_frame->loader()->documentLoader()->applicationCacheHost();
 }
 
-unsigned short DOMApplicationCache::status() const
+unsigned short ApplicationCache::status() const
 {
     ApplicationCacheHost* cacheHost = applicationCacheHost();
     if (!cacheHost)
@@ -69,40 +70,40 @@
     return cacheHost->status();
 }
 
-void DOMApplicationCache::update(ExceptionState& es)
+void ApplicationCache::update(ExceptionState& es)
 {
     ApplicationCacheHost* cacheHost = applicationCacheHost();
     if (!cacheHost || !cacheHost->update())
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("update", "ApplicationCache", "there is no application cache to update."));
 }
 
-void DOMApplicationCache::swapCache(ExceptionState& es)
+void ApplicationCache::swapCache(ExceptionState& es)
 {
     ApplicationCacheHost* cacheHost = applicationCacheHost();
     if (!cacheHost || !cacheHost->swapCache())
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("swapCache", "ApplicationCache", "there is no newer application cache to swap to."));
 }
 
-void DOMApplicationCache::abort()
+void ApplicationCache::abort()
 {
     ApplicationCacheHost* cacheHost = applicationCacheHost();
     if (cacheHost)
         cacheHost->abort();
 }
 
-const AtomicString& DOMApplicationCache::interfaceName() const
+const AtomicString& ApplicationCache::interfaceName() const
 {
-    return eventNames().interfaceForDOMApplicationCache;
+    return eventNames().interfaceForApplicationCache;
 }
 
-ScriptExecutionContext* DOMApplicationCache::scriptExecutionContext() const
+ScriptExecutionContext* ApplicationCache::scriptExecutionContext() const
 {
     if (m_frame)
         return m_frame->document();
     return 0;
 }
 
-const AtomicString& DOMApplicationCache::toEventType(ApplicationCacheHost::EventID id)
+const AtomicString& ApplicationCache::toEventType(ApplicationCacheHost::EventID id)
 {
     switch (id) {
     case ApplicationCacheHost::CHECKING_EVENT:
@@ -126,12 +127,12 @@
     return eventNames().errorEvent;
 }
 
-EventTargetData* DOMApplicationCache::eventTargetData()
+EventTargetData* ApplicationCache::eventTargetData()
 {
     return &m_eventTargetData;
 }
 
-EventTargetData* DOMApplicationCache::ensureEventTargetData()
+EventTargetData* ApplicationCache::ensureEventTargetData()
 {
     return &m_eventTargetData;
 }
diff --git a/Source/core/loader/appcache/DOMApplicationCache.h b/Source/core/loader/appcache/ApplicationCache.h
similarity index 83%
rename from Source/core/loader/appcache/DOMApplicationCache.h
rename to Source/core/loader/appcache/ApplicationCache.h
index ee7d452..680f9c4 100644
--- a/Source/core/loader/appcache/DOMApplicationCache.h
+++ b/Source/core/loader/appcache/ApplicationCache.h
@@ -23,8 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef DOMApplicationCache_h
-#define DOMApplicationCache_h
+#ifndef ApplicationCache_h
+#define ApplicationCache_h
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/EventNames.h"
@@ -41,10 +41,10 @@
 class Frame;
 class KURL;
 
-class DOMApplicationCache : public ScriptWrappable, public RefCounted<DOMApplicationCache>, public EventTarget, public DOMWindowProperty {
+class ApplicationCache : public ScriptWrappable, public RefCounted<ApplicationCache>, public EventTarget, public DOMWindowProperty {
 public:
-    static PassRefPtr<DOMApplicationCache> create(Frame* frame) { return adoptRef(new DOMApplicationCache(frame)); }
-    ~DOMApplicationCache() { ASSERT(!m_frame); }
+    static PassRefPtr<ApplicationCache> create(Frame* frame) { return adoptRef(new ApplicationCache(frame)); }
+    ~ApplicationCache() { ASSERT(!m_frame); }
 
     virtual void willDestroyGlobalObjectInFrame() OVERRIDE;
 
@@ -55,8 +55,8 @@
 
     // EventTarget impl
 
-    using RefCounted<DOMApplicationCache>::ref;
-    using RefCounted<DOMApplicationCache>::deref;
+    using RefCounted<ApplicationCache>::ref;
+    using RefCounted<ApplicationCache>::deref;
 
     // Explicitly named attribute event listener helpers
 
@@ -72,10 +72,10 @@
     virtual const AtomicString& interfaceName() const;
     virtual ScriptExecutionContext* scriptExecutionContext() const;
 
-    static const AtomicString& toEventType(ApplicationCacheHost::EventID id);
+    static const AtomicString& toEventType(ApplicationCacheHost::EventID);
 
 private:
-    explicit DOMApplicationCache(Frame*);
+    explicit ApplicationCache(Frame*);
 
     virtual void refEventTarget() { ref(); }
     virtual void derefEventTarget() { deref(); }
@@ -89,4 +89,4 @@
 
 } // namespace WebCore
 
-#endif // DOMApplicationCache_h
+#endif // ApplicationCache_h
diff --git a/Source/core/loader/appcache/DOMApplicationCache.idl b/Source/core/loader/appcache/ApplicationCache.idl
similarity index 96%
rename from Source/core/loader/appcache/DOMApplicationCache.idl
rename to Source/core/loader/appcache/ApplicationCache.idl
index 8dc4c23..0082d60 100644
--- a/Source/core/loader/appcache/DOMApplicationCache.idl
+++ b/Source/core/loader/appcache/ApplicationCache.idl
@@ -24,9 +24,8 @@
  */
 
 [
-    NoInterfaceObject,
     DoNotCheckConstants
-] interface DOMApplicationCache : EventTarget {
+] interface ApplicationCache : EventTarget {
     // update status
     const unsigned short UNCACHED = 0;
     const unsigned short IDLE = 1;
diff --git a/Source/core/loader/appcache/ApplicationCacheHost.h b/Source/core/loader/appcache/ApplicationCacheHost.h
index 4d4490a..48d7b23 100644
--- a/Source/core/loader/appcache/ApplicationCacheHost.h
+++ b/Source/core/loader/appcache/ApplicationCacheHost.h
@@ -39,7 +39,7 @@
 #include "wtf/Vector.h"
 
 namespace WebCore {
-    class DOMApplicationCache;
+    class ApplicationCache;
     class DocumentLoader;
     class Frame;
     class ResourceLoader;
@@ -125,8 +125,8 @@
         bool swapCache();
         void abort();
 
-        void setDOMApplicationCache(DOMApplicationCache*);
-        void notifyDOMApplicationCache(EventID, int progressTotal, int progressDone);
+        void setApplicationCache(ApplicationCache*);
+        void notifyApplicationCache(EventID, int progressTotal, int progressDone);
 
         void stopDeferringEvents(); // Also raises the events that have been queued up.
 
@@ -144,7 +144,7 @@
             DeferredEvent(EventID id, int total, int done) : eventID(id), progressTotal(total), progressDone(done) { }
         };
 
-        DOMApplicationCache* m_domApplicationCache;
+        ApplicationCache* m_domApplicationCache;
         DocumentLoader* m_documentLoader;
         bool m_defersEvents; // Events are deferred until after document onload.
         Vector<DeferredEvent> m_deferredEvents;
diff --git a/Source/core/loader/cache/MemoryCacheTest.cpp b/Source/core/loader/cache/MemoryCacheTest.cpp
deleted file mode 100644
index 1a36517..0000000
--- a/Source/core/loader/cache/MemoryCacheTest.cpp
+++ /dev/null
@@ -1,194 +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/loader/cache/MemoryCache.h"
-
-#include "core/loader/cache/MockImageResourceClient.h"
-#include "core/loader/cache/RawResource.h"
-#include "core/loader/cache/ResourcePtr.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "wtf/OwnPtr.h"
-
-#include <gtest/gtest.h>
-
-namespace WebCore {
-
-class MemoryCacheTest : public ::testing::Test {
-public:
-    class MockImageResource : public WebCore::Resource {
-    public:
-        MockImageResource(const ResourceRequest& request, Type type)
-            : Resource(request, type)
-        {
-        }
-
-        virtual void appendData(const char* data, int len)
-        {
-            Resource::appendData(data, len);
-            setDecodedSize(this->size());
-        }
-
-        virtual void destroyDecodedData()
-        {
-            setDecodedSize(0);
-        }
-    };
-
-protected:
-    virtual void SetUp()
-    {
-        // Save the global memory cache to restore it upon teardown.
-        m_globalMemoryCache = adoptPtr(memoryCache());
-        // Create the test memory cache instance and hook it in.
-        m_testingMemoryCache = adoptPtr(new MemoryCache());
-        setMemoryCacheForTesting(m_testingMemoryCache.leakPtr());
-    }
-
-    virtual void TearDown()
-    {
-        // Regain the ownership of testing memory cache, so that it will be
-        // destroyed.
-        m_testingMemoryCache = adoptPtr(memoryCache());
-        // Yield the ownership of the global memory cache back.
-        setMemoryCacheForTesting(m_globalMemoryCache.leakPtr());
-    }
-
-    OwnPtr<MemoryCache> m_testingMemoryCache;
-    OwnPtr<MemoryCache> m_globalMemoryCache;
-};
-
-// Verifies that setters and getters for cache capacities work correcty.
-TEST_F(MemoryCacheTest, CapacityAccounting)
-{
-    const unsigned totalCapacity = 100;
-    const unsigned minDeadCapacity = 10;
-    const unsigned maxDeadCapacity = 50;
-    memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
-
-    ASSERT_EQ(totalCapacity, memoryCache()->capacity());
-    ASSERT_EQ(minDeadCapacity, memoryCache()->minDeadCapacity());
-    ASSERT_EQ(maxDeadCapacity, memoryCache()->maxDeadCapacity());
-}
-
-// Verifies that dead resources that exceed dead resource capacity are evicted
-// from cache when pruning.
-TEST_F(MemoryCacheTest, DeadResourceEviction)
-{
-    const unsigned totalCapacity = 1000000;
-    const unsigned minDeadCapacity = 0;
-    const unsigned maxDeadCapacity = 0;
-    memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
-
-    ResourcePtr<Resource> cachedResource =
-        new Resource(ResourceRequest(""), Resource::Raw);
-    const char data[5] = "abcd";
-    cachedResource->appendData(data, 3);
-    // The resource size has to be nonzero for this test to be meaningful, but
-    // we do not rely on it having any particular value.
-    ASSERT_GT(cachedResource->size(), 0u);
-
-    ASSERT_EQ(0u, memoryCache()->deadSize());
-    ASSERT_EQ(0u, memoryCache()->liveSize());
-
-    memoryCache()->add(cachedResource.get());
-    ASSERT_EQ(cachedResource->size(), memoryCache()->deadSize());
-    ASSERT_EQ(0u, memoryCache()->liveSize());
-
-    memoryCache()->prune();
-    ASSERT_EQ(0u, memoryCache()->deadSize());
-    ASSERT_EQ(0u, memoryCache()->liveSize());
-}
-
-// Verifies that CachedResources are evicted from the decode cache
-// according to their DecodeCachePriority.
-TEST_F(MemoryCacheTest, DecodeCacheOrder)
-{
-    memoryCache()->setDelayBeforeLiveDecodedPrune(0);
-    ResourcePtr<MockImageResource> cachedImageLowPriority =
-        new MockImageResource(ResourceRequest(""), Resource::Raw);
-    ResourcePtr<MockImageResource> cachedImageHighPriority =
-        new MockImageResource(ResourceRequest(""), Resource::Raw);
-
-    MockImageResourceClient clientLowPriority;
-    MockImageResourceClient clientHighPriority;
-    cachedImageLowPriority->addClient(&clientLowPriority);
-    cachedImageHighPriority->addClient(&clientHighPriority);
-
-    const char data[5] = "abcd";
-    cachedImageLowPriority->appendData(data, 1);
-    cachedImageHighPriority->appendData(data, 4);
-    const unsigned lowPrioritySize = cachedImageLowPriority->size();
-    const unsigned highPrioritySize = cachedImageHighPriority->size();
-    const unsigned lowPriorityMockDecodeSize = cachedImageLowPriority->decodedSize();
-    const unsigned highPriorityMockDecodeSize = cachedImageHighPriority->decodedSize();
-    const unsigned totalSize = lowPrioritySize + highPrioritySize;
-
-    // Verify that the sizes are different to ensure that we can test eviction order.
-    ASSERT_GT(lowPrioritySize, 0u);
-    ASSERT_NE(lowPrioritySize, highPrioritySize);
-    ASSERT_GT(lowPriorityMockDecodeSize, 0u);
-    ASSERT_NE(lowPriorityMockDecodeSize, highPriorityMockDecodeSize);
-
-    ASSERT_EQ(memoryCache()->deadSize(), 0u);
-    ASSERT_EQ(memoryCache()->liveSize(), 0u);
-
-    // Add the items. The item added first would normally be evicted first.
-    memoryCache()->add(cachedImageHighPriority.get());
-    ASSERT_EQ(memoryCache()->deadSize(), 0u);
-    ASSERT_EQ(memoryCache()->liveSize(), highPrioritySize);
-
-    memoryCache()->add(cachedImageLowPriority.get());
-    ASSERT_EQ(memoryCache()->deadSize(), 0u);
-    ASSERT_EQ(memoryCache()->liveSize(), highPrioritySize + lowPrioritySize);
-
-    // Insert all items in the decoded items list with the same priority
-    memoryCache()->insertInLiveDecodedResourcesList(cachedImageHighPriority.get());
-    memoryCache()->insertInLiveDecodedResourcesList(cachedImageLowPriority.get());
-    ASSERT_EQ(memoryCache()->deadSize(), 0u);
-    ASSERT_EQ(memoryCache()->liveSize(), totalSize);
-
-    // Now we will assign their priority and make sure they are moved to the correct buckets.
-    cachedImageLowPriority->setCacheLiveResourcePriority(Resource::CacheLiveResourcePriorityLow);
-    cachedImageHighPriority->setCacheLiveResourcePriority(Resource::CacheLiveResourcePriorityHigh);
-
-    // Should first prune the LowPriority item.
-    memoryCache()->setCapacities(memoryCache()->minDeadCapacity(), memoryCache()->liveSize() - 10, memoryCache()->liveSize() - 10);
-    memoryCache()->prune();
-    ASSERT_EQ(memoryCache()->deadSize(), 0u);
-    ASSERT_EQ(memoryCache()->liveSize(), totalSize - lowPriorityMockDecodeSize);
-
-    // Should prune the HighPriority item.
-    memoryCache()->setCapacities(memoryCache()->minDeadCapacity(), memoryCache()->liveSize() - 10, memoryCache()->liveSize() - 10);
-    memoryCache()->prune();
-    ASSERT_EQ(memoryCache()->deadSize(), 0u);
-    ASSERT_EQ(memoryCache()->liveSize(), totalSize - lowPriorityMockDecodeSize - highPriorityMockDecodeSize);
-}
-} // namespace
diff --git a/Source/core/make_derived_sources.target.darwin-arm.mk b/Source/core/make_derived_sources.target.darwin-arm.mk
index 1d9f1f4..7886a99 100644
--- a/Source/core/make_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_derived_sources.target.darwin-arm.mk
@@ -72,7 +72,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -180,7 +180,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/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -191,7 +191,7 @@
 $(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/core/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 $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -200,9 +200,9 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/loader/cache/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl loader/cache/FetchInitiatorTypeNames.in -- --resourceTypes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl fetch/FetchInitiatorTypeNames.in -- --resourceTypes
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
diff --git a/Source/core/make_derived_sources.target.darwin-mips.mk b/Source/core/make_derived_sources.target.darwin-mips.mk
index 69f79e1..fdf170b 100644
--- a/Source/core/make_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_derived_sources.target.darwin-mips.mk
@@ -72,7 +72,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -180,7 +180,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/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -191,7 +191,7 @@
 $(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/core/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 $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -200,9 +200,9 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/loader/cache/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl loader/cache/FetchInitiatorTypeNames.in -- --resourceTypes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl fetch/FetchInitiatorTypeNames.in -- --resourceTypes
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
diff --git a/Source/core/make_derived_sources.target.darwin-x86.mk b/Source/core/make_derived_sources.target.darwin-x86.mk
index 898a25c..d377080 100644
--- a/Source/core/make_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_derived_sources.target.darwin-x86.mk
@@ -72,7 +72,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -180,7 +180,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/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -191,7 +191,7 @@
 $(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/core/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 $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -200,9 +200,9 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/loader/cache/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl loader/cache/FetchInitiatorTypeNames.in -- --resourceTypes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl fetch/FetchInitiatorTypeNames.in -- --resourceTypes
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
diff --git a/Source/core/make_derived_sources.target.linux-arm.mk b/Source/core/make_derived_sources.target.linux-arm.mk
index 1d9f1f4..7886a99 100644
--- a/Source/core/make_derived_sources.target.linux-arm.mk
+++ b/Source/core/make_derived_sources.target.linux-arm.mk
@@ -72,7 +72,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -180,7 +180,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/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -191,7 +191,7 @@
 $(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/core/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 $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -200,9 +200,9 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/loader/cache/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl loader/cache/FetchInitiatorTypeNames.in -- --resourceTypes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl fetch/FetchInitiatorTypeNames.in -- --resourceTypes
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
diff --git a/Source/core/make_derived_sources.target.linux-mips.mk b/Source/core/make_derived_sources.target.linux-mips.mk
index 69f79e1..fdf170b 100644
--- a/Source/core/make_derived_sources.target.linux-mips.mk
+++ b/Source/core/make_derived_sources.target.linux-mips.mk
@@ -72,7 +72,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -180,7 +180,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/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -191,7 +191,7 @@
 $(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/core/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 $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -200,9 +200,9 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/loader/cache/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl loader/cache/FetchInitiatorTypeNames.in -- --resourceTypes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl fetch/FetchInitiatorTypeNames.in -- --resourceTypes
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
diff --git a/Source/core/make_derived_sources.target.linux-x86.mk b/Source/core/make_derived_sources.target.linux-x86.mk
index 898a25c..d377080 100644
--- a/Source/core/make_derived_sources.target.linux-x86.mk
+++ b/Source/core/make_derived_sources.target.linux-x86.mk
@@ -72,7 +72,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,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/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/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_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -180,7 +180,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/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -191,7 +191,7 @@
 $(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/core/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 $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python 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/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -200,9 +200,9 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/loader/cache/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl loader/cache/FetchInitiatorTypeNames.in -- --resourceTypes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp" "$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl fetch/FetchInitiatorTypeNames.in -- --resourceTypes
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
diff --git a/Source/core/page/AutoscrollController.cpp b/Source/core/page/AutoscrollController.cpp
index 71f922e..c7174c1 100644
--- a/Source/core/page/AutoscrollController.cpp
+++ b/Source/core/page/AutoscrollController.cpp
@@ -132,11 +132,14 @@
 
 void AutoscrollController::updateDragAndDrop(Node* dropTargetNode, const IntPoint& eventPosition, double eventTime)
 {
-    if (!dropTargetNode) {
+    if (!dropTargetNode || !dropTargetNode->renderer()) {
         stopAutoscrollTimer();
         return;
     }
 
+    if (m_autoscrollRenderer && m_autoscrollRenderer->frame() != dropTargetNode->renderer()->frame())
+        return;
+
     RenderBox* scrollable = RenderBox::findAutoscrollable(dropTargetNode->renderer());
     if (!scrollable) {
         stopAutoscrollTimer();
diff --git a/Source/core/page/Chrome.cpp b/Source/core/page/Chrome.cpp
index 9fed91c..1972ef5 100644
--- a/Source/core/page/Chrome.cpp
+++ b/Source/core/page/Chrome.cpp
@@ -159,9 +159,9 @@
 static bool canRunModalIfDuringPageDismissal(Page* page, ChromeClient::DialogType dialog, const String& message)
 {
     for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
-        FrameLoader::PageDismissalType dismissal = frame->loader()->pageDismissalEventBeingDispatched();
-        if (dismissal != FrameLoader::NoDismissal)
-            return page->chrome().client()->shouldRunModalDialogDuringPageDismissal(dialog, message, dismissal);
+        Document::PageDismissalType dismissal = frame->document()->pageDismissalEventBeingDispatched();
+        if (dismissal != Document::NoDismissal)
+            return page->chrome().client().shouldRunModalDialogDuringPageDismissal(dialog, message, dismissal);
     }
     return true;
 }
diff --git a/Source/core/page/Chrome.h b/Source/core/page/Chrome.h
index 0d1a127..f9171c2 100644
--- a/Source/core/page/Chrome.h
+++ b/Source/core/page/Chrome.h
@@ -58,7 +58,7 @@
 
     static PassOwnPtr<Chrome> create(Page*, ChromeClient*);
 
-    ChromeClient* client() { return m_client; }
+    ChromeClient& client() { return *m_client; }
 
     // HostWindow methods.
     virtual void invalidateContentsAndRootView(const IntRect&) OVERRIDE;
diff --git a/Source/core/page/ChromeClient.h b/Source/core/page/ChromeClient.h
index d97cbff..f2b4e22 100644
--- a/Source/core/page/ChromeClient.h
+++ b/Source/core/page/ChromeClient.h
@@ -65,7 +65,6 @@
 class HitTestResult;
 class HTMLInputElement;
 class IntRect;
-class NavigationAction;
 class Node;
 class Page;
 class PagePopup;
@@ -105,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&, const NavigationAction&, NavigationPolicy = NavigationPolicyIgnore) = 0;
+    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy = NavigationPolicyIgnore) = 0;
     virtual void show(NavigationPolicy) = 0;
 
     virtual bool canRunModal() = 0;
@@ -155,9 +154,7 @@
     virtual IntRect rootViewToScreen(const IntRect&) const = 0;
     virtual WebKit::WebScreenInfo screenInfo() const = 0;
     virtual void setCursor(const Cursor&) = 0;
-#if !USE(REQUEST_ANIMATION_FRAME_TIMER)
     virtual void scheduleAnimation() = 0;
-#endif
     // End methods used by HostWindow.
 
     virtual void dispatchViewportPropertiesDidChange(const ViewportArguments&) const { }
@@ -255,7 +252,7 @@
         PromptDialog = 2,
         HTMLDialog = 3
     };
-    virtual bool shouldRunModalDialogDuringPageDismissal(const DialogType&, const String& dialogMessage, FrameLoader::PageDismissalType) const { UNUSED_PARAM(dialogMessage); return true; }
+    virtual bool shouldRunModalDialogDuringPageDismissal(const DialogType&, const String& dialogMessage, Document::PageDismissalType) const { UNUSED_PARAM(dialogMessage); return true; }
 
     virtual void numWheelEventHandlersChanged(unsigned) = 0;
 
diff --git a/Source/core/page/Console.cpp b/Source/core/page/Console.cpp
index bd34162..c857310 100644
--- a/Source/core/page/Console.cpp
+++ b/Source/core/page/Console.cpp
@@ -78,7 +78,7 @@
     InspectorInstrumentation::addMessageToConsole(page, ConsoleAPIMessageSource, type, level, message, state, arguments);
 
     if (gotMessage)
-        page->chrome().client()->addMessageToConsole(ConsoleAPIMessageSource, type, level, message, lastCaller.lineNumber(), lastCaller.sourceURL());
+        page->chrome().client().addMessageToConsole(ConsoleAPIMessageSource, type, level, message, lastCaller.lineNumber(), lastCaller.sourceURL());
 }
 
 void Console::debug(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
diff --git a/Source/core/page/ContentSecurityPolicy.cpp b/Source/core/page/ContentSecurityPolicy.cpp
index e03b6bb..7f5d434 100644
--- a/Source/core/page/ContentSecurityPolicy.cpp
+++ b/Source/core/page/ContentSecurityPolicy.cpp
@@ -851,7 +851,9 @@
     void setCSPDirective(const String& name, const String& value, OwnPtr<CSPDirectiveType>&);
 
     SourceListDirective* operativeDirective(SourceListDirective*) const;
-    void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL = KURL(), const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), ScriptState* = 0) const;
+    void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const;
+    void reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const;
+    void reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState*) const;
 
     bool checkEval(SourceListDirective*) const;
     bool checkInline(SourceListDirective*) const;
@@ -861,7 +863,7 @@
 
     void setEvalDisabledErrorMessage(const String& errorMessage) { m_evalDisabledErrorMessage = errorMessage; }
 
-    bool checkEvalAndReportViolation(SourceListDirective*, const String& consoleMessage, const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), ScriptState* = 0) const;
+    bool checkEvalAndReportViolation(SourceListDirective*, const String& consoleMessage, ScriptState*) const;
     bool checkInlineAndReportViolation(SourceListDirective*, const String& consoleMessage, const String& contextURL, const WTF::OrdinalNumber& contextLine, bool isScript) const;
 
     bool checkSourceAndReportViolation(SourceListDirective*, const KURL&, const String& effectiveDirective) const;
@@ -922,10 +924,25 @@
     return directives.release();
 }
 
-void CSPDirectiveList::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine, ScriptState* state) const
+void CSPDirectiveList::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const
 {
     String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
-    m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header, contextURL, contextLine, state);
+    m_policy->scriptExecutionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+    m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
+}
+
+void CSPDirectiveList::reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const
+{
+    String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
+    m_policy->scriptExecutionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, contextURL, contextLine.oneBasedInt());
+    m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
+}
+
+void CSPDirectiveList::reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState* state) const
+{
+    String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
+    m_policy->scriptExecutionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, state);
+    m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
 }
 
 bool CSPDirectiveList::checkEval(SourceListDirective* directive) const
@@ -962,7 +979,7 @@
     return directive ? directive : m_defaultSrc.get();
 }
 
-bool CSPDirectiveList::checkEvalAndReportViolation(SourceListDirective* directive, const String& consoleMessage, const String& contextURL, const WTF::OrdinalNumber& contextLine, ScriptState* state) const
+bool CSPDirectiveList::checkEvalAndReportViolation(SourceListDirective* directive, const String& consoleMessage, ScriptState* state) const
 {
     if (checkEval(directive))
         return true;
@@ -971,7 +988,7 @@
     if (directive == m_defaultSrc)
         suffix = " Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.";
 
-    reportViolation(directive->text(), scriptSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), contextURL, contextLine, state);
+    reportViolationWithState(directive->text(), scriptSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), state);
     if (!m_reportOnly) {
         m_policy->reportBlockedScriptExecutionToInspector(directive->text());
         return false;
@@ -1001,7 +1018,7 @@
     if (directive == m_defaultSrc)
         suffix = " Note that '" + String(isScript ? "script" : "style") + "-src' was not explicitly set, so 'default-src' is used as a fallback.";
 
-    reportViolation(directive->text(), isScript ? scriptSrc : styleSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), contextURL, contextLine);
+    reportViolationWithLocation(directive->text(), isScript ? scriptSrc : styleSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), contextURL, contextLine);
 
     if (!m_reportOnly) {
         if (isScript)
@@ -1087,7 +1104,7 @@
     DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "));
 
     return reportingStatus == ContentSecurityPolicy::SendReport ?
-        checkEvalAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, String(), WTF::OrdinalNumber::beforeFirst(), state) :
+        checkEvalAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, state) :
         checkEval(operativeDirective(m_scriptSrc.get()));
 }
 
@@ -1725,10 +1742,8 @@
     }
 }
 
-void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header, const String& contextURL, const WTF::OrdinalNumber& contextLine, ScriptState* state)
+void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header)
 {
-    logToConsole(consoleMessage, contextURL, contextLine, state);
-
     // FIXME: Support sending reports from worker.
     if (!m_scriptExecutionContext->isDocument())
         return;
@@ -1875,9 +1890,9 @@
     logToConsole("The Content Security Policy '" + policy + "' was delivered in report-only mode, but does not specify a 'report-uri'; the policy will have no effect. Please either add a 'report-uri' directive, or deliver the policy via the 'Content-Security-Policy' header.");
 }
 
-void ContentSecurityPolicy::logToConsole(const String& message, const String& contextURL, const WTF::OrdinalNumber& contextLine, ScriptState* state) const
+void ContentSecurityPolicy::logToConsole(const String& message) const
 {
-    m_scriptExecutionContext->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, contextURL, contextLine.oneBasedInt(), state);
+    m_scriptExecutionContext->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
 }
 
 void ContentSecurityPolicy::reportBlockedScriptExecutionToInspector(const String& directiveText) const
diff --git a/Source/core/page/ContentSecurityPolicy.h b/Source/core/page/ContentSecurityPolicy.h
index 13f007f..ad5c6b0 100644
--- a/Source/core/page/ContentSecurityPolicy.h
+++ b/Source/core/page/ContentSecurityPolicy.h
@@ -128,7 +128,7 @@
     void reportInvalidReflectedXSS(const String&) const;
     void reportMissingReportURI(const String&) const;
     void reportUnsupportedDirective(const String&) const;
-    void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header, const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), ScriptState* = 0);
+    void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header);
 
     void reportBlockedScriptExecutionToInspector(const String& directiveText) const;
 
@@ -142,10 +142,12 @@
 
     static bool shouldBypassMainWorld(ScriptExecutionContext*);
 
+    ScriptExecutionContext* scriptExecutionContext() { return m_scriptExecutionContext; }
+
 private:
     explicit ContentSecurityPolicy(ScriptExecutionContext*);
 
-    void logToConsole(const String& message, const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), ScriptState* = 0) const;
+    void logToConsole(const String& message) const;
     void addPolicyFromHeaderValue(const String&, HeaderType);
 
     bool shouldSendViolationReport(const String&) const;
diff --git a/Source/core/page/ContextMenuClient.h b/Source/core/page/ContextMenuClient.h
index 964924b..76a2ee4 100644
--- a/Source/core/page/ContextMenuClient.h
+++ b/Source/core/page/ContextMenuClient.h
@@ -34,6 +34,7 @@
 public:
     virtual ~ContextMenuClient() {  }
     virtual void showContextMenu(const ContextMenu*) = 0;
+    virtual void clearContextMenu() = 0;
 };
 
 }
diff --git a/Source/core/page/ContextMenuController.cpp b/Source/core/page/ContextMenuController.cpp
index c12a904..77797e3 100644
--- a/Source/core/page/ContextMenuController.cpp
+++ b/Source/core/page/ContextMenuController.cpp
@@ -64,6 +64,17 @@
     if (m_menuProvider)
         m_menuProvider->contextMenuCleared();
     m_menuProvider = 0;
+    m_hitTestResult = HitTestResult();
+    m_client->clearContextMenu();
+}
+
+void ContextMenuController::documentDetached(Document* document)
+{
+    if (Node* innerNode = m_hitTestResult.innerNode()) {
+        // Invalidate the context menu info if its target document is detached.
+        if (innerNode->document() == document)
+            clearContextMenu();
+    }
 }
 
 void ContextMenuController::handleContextMenuEvent(Event* event)
diff --git a/Source/core/page/ContextMenuController.h b/Source/core/page/ContextMenuController.h
index a2b6ae6..e36bedb 100644
--- a/Source/core/page/ContextMenuController.h
+++ b/Source/core/page/ContextMenuController.h
@@ -38,6 +38,7 @@
     class ContextMenuClient;
     class ContextMenuItem;
     class ContextMenuProvider;
+    class Document;
     class Event;
     class Page;
 
@@ -51,6 +52,8 @@
         ContextMenu* contextMenu() const { return m_contextMenu.get(); }
         void clearContextMenu();
 
+        void documentDetached(Document*);
+
         void handleContextMenuEvent(Event*);
         void showContextMenu(Event*, PassRefPtr<ContextMenuProvider>);
 
diff --git a/Source/core/page/CreateWindow.cpp b/Source/core/page/CreateWindow.cpp
index aa70c85..7549750 100644
--- a/Source/core/page/CreateWindow.cpp
+++ b/Source/core/page/CreateWindow.cpp
@@ -29,7 +29,6 @@
 
 #include "core/dom/Document.h"
 #include "core/loader/FrameLoadRequest.h"
-#include "core/loader/NavigationAction.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/Frame.h"
@@ -65,13 +64,6 @@
         return 0;
     }
 
-    // FIXME: Setting the referrer should be the caller's responsibility.
-    FrameLoadRequest requestWithReferrer = request;
-    String referrer = SecurityPolicy::generateReferrerHeader(openerFrame->document()->referrerPolicy(), request.resourceRequest().url(), openerFrame->loader()->outgoingReferrer());
-    if (!referrer.isEmpty())
-        requestWithReferrer.resourceRequest().setHTTPReferrer(referrer);
-    FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader()->outgoingOrigin());
-
     if (openerFrame->settings() && !openerFrame->settings()->supportsMultipleWindows()) {
         created = false;
         return openerFrame;
@@ -81,8 +73,7 @@
     if (!oldPage)
         return 0;
 
-    NavigationAction action(requestWithReferrer.resourceRequest());
-    Page* page = oldPage->chrome().client()->createWindow(openerFrame, requestWithReferrer, features, action);
+    Page* page = oldPage->chrome().client().createWindow(openerFrame, request, features);
     if (!page)
         return 0;
 
diff --git a/Source/core/page/DOMSelection.cpp b/Source/core/page/DOMSelection.cpp
index f26d1fa..2bc803c 100644
--- a/Source/core/page/DOMSelection.cpp
+++ b/Source/core/page/DOMSelection.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/page/DOMSelection.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
@@ -199,7 +200,7 @@
         return;
 
     if (offset < 0) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("collapse", "Selection", String::number(offset) + " is not a valid offset."));
         return;
     }
 
@@ -218,7 +219,7 @@
     const VisibleSelection& selection = m_frame->selection()->selection();
 
     if (selection.isNone()) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToEnd", "Selection", "there is no selection."));
         return;
     }
 
@@ -233,7 +234,7 @@
     const VisibleSelection& selection = m_frame->selection()->selection();
 
     if (selection.isNone()) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToStart", "Selection", "there is no selection."));
         return;
     }
 
@@ -252,8 +253,13 @@
     if (!m_frame)
         return;
 
-    if (baseOffset < 0 || extentOffset < 0) {
-        es.throwDOMException(IndexSizeError);
+    if (baseOffset < 0) {
+        es.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."));
         return;
     }
 
@@ -272,7 +278,7 @@
     if (!m_frame)
         return;
     if (offset < 0) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setPosition", "Selection", String::number(offset) + " is not a valid offset."));
         return;
     }
 
@@ -339,12 +345,16 @@
         return;
 
     if (!node) {
-        es.throwDOMException(TypeMismatchError);
+        es.throwDOMException(TypeMismatchError, ExceptionMessages::failedToExecute("extend", "Selection", "The node provided is invalid."));
         return;
     }
 
-    if (offset < 0 || offset > (node->offsetInCharacters() ? caretMaxOffset(node) : (int)node->childNodeCount())) {
-        es.throwDOMException(IndexSizeError);
+    if (offset < 0) {
+        es.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."));
         return;
     }
 
@@ -361,7 +371,7 @@
         return 0;
 
     if (index < 0 || index >= rangeCount()) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("getRangeAt", "Selection", String::number(index) + " is not a valid index."));
         return 0;
     }
 
diff --git a/Source/core/page/DOMWindow.cpp b/Source/core/page/DOMWindow.cpp
index aac917c..809193d 100644
--- a/Source/core/page/DOMWindow.cpp
+++ b/Source/core/page/DOMWindow.cpp
@@ -63,13 +63,14 @@
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/appcache/DOMApplicationCache.h"
+#include "core/loader/appcache/ApplicationCache.h"
 #include "core/page/BarProp.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/Console.h"
 #include "core/page/CreateWindow.h"
 #include "core/page/DOMPoint.h"
+#include "core/page/DOMWindowLifecycleNotifier.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
@@ -264,7 +265,7 @@
     if (!std::isnan(pendingChanges.height()))
         window.setHeight(pendingChanges.height());
 
-    FloatSize minimumSize = page->chrome().client()->minimumWindowSize();
+    FloatSize minimumSize = page->chrome().client().minimumWindowSize();
     // Let size 0 pass through, since that indicates default size, not minimum size.
     if (window.width())
         window.setWidth(min(max(minimumSize.width(), window.width()), screen.width()));
@@ -328,6 +329,11 @@
     if (m_document) {
         if (m_document->attached()) {
             // FIXME: We don't call willRemove here. Why is that OK?
+            // This detach() call is also mostly redundant. Most of the calls to
+            // this function come via DocumentLoader::createWriterFor, which
+            // always detaches the previous Document first. Only XSLTProcessor
+            // depends on this detach() call, so it seems like there's some room
+            // for cleanup.
             m_document->detach();
         }
         m_document->setDOMWindow(0);
@@ -361,7 +367,7 @@
     if (m_frame->page() && m_frame->page()->mainFrame() == m_frame) {
         m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
         if (m_document->hasTouchEventHandlers())
-            m_frame->page()->chrome().client()->needTouchEvents(true);
+            m_frame->page()->chrome().client().needTouchEvents(true);
     }
 }
 
@@ -388,7 +394,7 @@
 
     removeAllEventListeners();
 
-    // Unparent any attached Document so Document won't try to use a destroyed DOMWindow.
+    ASSERT(!m_document->attached());
     setDocument(0);
 }
 
@@ -590,15 +596,15 @@
 {
     if (!isCurrentlyDisplayedInFrame())
         return 0;
-    return m_frame->page() ? m_frame->page()->console() : 0;
+    return m_frame->page() ? &m_frame->page()->console() : 0;
 }
 
-DOMApplicationCache* DOMWindow::applicationCache() const
+ApplicationCache* DOMWindow::applicationCache() const
 {
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_applicationCache)
-        m_applicationCache = DOMApplicationCache::create(m_frame);
+        m_applicationCache = ApplicationCache::create(m_frame);
     return m_applicationCache.get();
 }
 
@@ -638,14 +644,20 @@
     if (!document)
         return 0;
 
+    String accessDeniedMessage = "Access to 'sessionStorage' is denied for this document.";
     if (!document->securityOrigin()->canAccessLocalStorage()) {
-        es.throwDOMException(SecurityError);
+        if (document->isSandboxed(SandboxOrigin))
+            es.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.");
+        else
+            es.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
     if (m_sessionStorage) {
         if (!m_sessionStorage->area()->canAccessStorage(m_frame)) {
-            es.throwDOMException(SecurityError);
+            es.throwSecurityError(accessDeniedMessage);
             return 0;
         }
         return m_sessionStorage.get();
@@ -657,7 +669,7 @@
 
     OwnPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
@@ -674,14 +686,20 @@
     if (!document)
         return 0;
 
+    String accessDeniedMessage = "Access to 'localStorage' is denied for this document.";
     if (!document->securityOrigin()->canAccessLocalStorage()) {
-        es.throwDOMException(SecurityError);
+        if (document->isSandboxed(SandboxOrigin))
+            es.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.");
+        else
+            es.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
     if (m_localStorage) {
         if (!m_localStorage->area()->canAccessStorage(m_frame)) {
-            es.throwDOMException(SecurityError);
+            es.throwSecurityError(accessDeniedMessage);
             return 0;
         }
         return m_localStorage.get();
@@ -691,12 +709,12 @@
     if (!page)
         return 0;
 
-    if (!page->settings()->localStorageEnabled())
+    if (!page->settings().localStorageEnabled())
         return 0;
 
     OwnPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError(accessDeniedMessage);
         return 0;
     }
 
@@ -723,7 +741,7 @@
         // 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);
+            es.throwDOMException(SyntaxError, "Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
             return;
         }
     }
@@ -853,7 +871,7 @@
     Settings* settings = m_frame->settings();
     bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
 
-    if (!(page->openedByDOM() || page->backForward()->count() <= 1 || allowScriptsToCloseWindows))
+    if (!(page->openedByDOM() || page->backForward().count() <= 1 || allowScriptsToCloseWindows))
         return;
 
     if (!m_frame->loader()->shouldClose())
@@ -883,10 +901,7 @@
 {
     if (!m_frame)
         return;
-
-    // We must check whether the load is complete asynchronously, because we might still be parsing
-    // the document until the callstack unwinds.
-    m_frame->loader()->stopForUserCancel(true);
+    m_frame->loader()->stopAllLoaders();
 }
 
 void DOMWindow::alert(const String& message)
@@ -1241,11 +1256,7 @@
     if (!m_frame)
         return 0.0;
 
-    Page* page = m_frame->page();
-    if (!page)
-        return 0.0;
-
-    return page->deviceScaleFactor();
+    return m_frame->devicePixelRatio();
 }
 
 void DOMWindow::scrollBy(int x, int y) const
@@ -1400,7 +1411,7 @@
 
     if (Document* document = this->document()) {
         document->addListenerTypeIfNeeded(eventType);
-        if (eventType == eventNames().mousewheelEvent)
+        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
             document->didAddWheelEventHandler();
         else if (eventNames().isTouchEventType(eventType))
             document->didAddTouchEventHandler(document);
@@ -1437,7 +1448,7 @@
         return false;
 
     if (Document* document = this->document()) {
-        if (eventType == eventNames().mousewheelEvent)
+        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
             document->didRemoveWheelEventHandler();
         else if (eventNames().isTouchEventType(eventType))
             document->didRemoveTouchEventHandler(document);
@@ -1504,8 +1515,7 @@
 {
     EventTarget::removeAllEventListeners();
 
-    if (DeviceMotionController* controller = DeviceMotionController::from(document()))
-        controller->stopUpdating();
+    lifecycleNotifier()->notifyRemoveAllEventListeners();
     if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
         controller->removeAllDeviceEventListeners(this);
     if (Document* document = this->document())
@@ -1571,6 +1581,27 @@
     pageConsole()->addMessage(JSMessageSource, ErrorMessageLevel, message);
 }
 
+// FIXME: Once we're throwing exceptions for cross-origin access violations, we will always sanitize the target
+// frame details, so we can safely combine 'crossDomainAccessErrorMessage' with this method after considering
+// exactly which details may be exposed to JavaScript.
+//
+// http://crbug.com/17325
+String DOMWindow::sanitizedCrossDomainAccessErrorMessage(DOMWindow* activeWindow)
+{
+    const KURL& activeWindowURL = activeWindow->document()->url();
+    if (activeWindowURL.isNull())
+        return String();
+
+    ASSERT(!activeWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
+
+    SecurityOrigin* activeOrigin = activeWindow->document()->securityOrigin();
+    String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a cross-origin frame.";
+
+    // FIXME: Evaluate which details from 'crossDomainAccessErrorMessage' may safely be reported to JavaScript.
+
+    return message;
+}
+
 String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
 {
     const KURL& activeWindowURL = activeWindow->document()->url();
@@ -1730,5 +1761,15 @@
     return 0;
 }
 
+DOMWindowLifecycleNotifier* DOMWindow::lifecycleNotifier()
+{
+    return static_cast<DOMWindowLifecycleNotifier*>(LifecycleContext::lifecycleNotifier());
+}
+
+PassOwnPtr<LifecycleNotifier> DOMWindow::createLifecycleNotifier()
+{
+    return DOMWindowLifecycleNotifier::create(this);
+}
+
 
 } // namespace WebCore
diff --git a/Source/core/page/DOMWindow.h b/Source/core/page/DOMWindow.h
index ae98cf0..6644dc3 100644
--- a/Source/core/page/DOMWindow.h
+++ b/Source/core/page/DOMWindow.h
@@ -30,16 +30,17 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/EventTarget.h"
 #include "core/page/FrameDestructionObserver.h"
+#include "core/platform/LifecycleContext.h"
 #include "core/platform/Supplementable.h"
 
 #include "wtf/Forward.h"
 
 namespace WebCore {
+    class ApplicationCache;
     class BarProp;
     class CSSRuleList;
     class CSSStyleDeclaration;
     class Console;
-    class DOMApplicationCache;
     class DOMPoint;
     class DOMSelection;
     class DOMURL;
@@ -47,6 +48,7 @@
     class Database;
     class DatabaseCallback;
     class Document;
+    class DOMWindowLifecycleNotifier;
     class Element;
     class EventListener;
     class ExceptionState;
@@ -79,7 +81,7 @@
 
     enum SetLocationLocking { LockHistoryBasedOnGestureState, LockHistoryAndBackForwardList };
 
-    class DOMWindow : public RefCounted<DOMWindow>, public ScriptWrappable, public EventTarget, public FrameDestructionObserver, public Supplementable<DOMWindow> {
+    class DOMWindow : public RefCounted<DOMWindow>, public ScriptWrappable, public EventTarget, public FrameDestructionObserver, public Supplementable<DOMWindow>, public LifecycleContext {
     public:
         static PassRefPtr<DOMWindow> create(Frame* frame) { return adoptRef(new DOMWindow(frame)); }
         virtual ~DOMWindow();
@@ -220,6 +222,7 @@
 
         void printErrorMessage(const String&);
         String crossDomainAccessErrorMessage(DOMWindow* activeWindow);
+        String sanitizedCrossDomainAccessErrorMessage(DOMWindow* activeWindow);
 
         void postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray*, const String& targetOrigin, DOMWindow* source, ExceptionState&);
         void postMessageTimerFired(PassOwnPtr<PostMessageTimer>);
@@ -318,6 +321,7 @@
         DEFINE_ATTRIBUTE_EVENT_LISTENER(unload);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(volumechange);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(waiting);
+        DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
 
         DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationstart, webkitAnimationStart);
         DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationiteration, webkitAnimationIteration);
@@ -342,8 +346,8 @@
         Storage* optionalSessionStorage() const { return m_sessionStorage.get(); }
         Storage* optionalLocalStorage() const { return m_localStorage.get(); }
 
-        DOMApplicationCache* applicationCache() const;
-        DOMApplicationCache* optionalApplicationCache() const { return m_applicationCache.get(); }
+        ApplicationCache* applicationCache() const;
+        ApplicationCache* optionalApplicationCache() const { return m_applicationCache.get(); }
 
 #if ENABLE(ORIENTATION_EVENTS)
         // This is the interface orientation in degrees. Some examples are:
@@ -372,11 +376,16 @@
 
         bool isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString);
 
+    protected:
+        DOMWindowLifecycleNotifier* lifecycleNotifier();
+
     private:
         explicit DOMWindow(Frame*);
 
         Page* page();
 
+        virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
+
         virtual void frameDestroyed() OVERRIDE;
         virtual void willDetachPage() OVERRIDE;
 
@@ -414,7 +423,7 @@
 
         mutable RefPtr<Storage> m_sessionStorage;
         mutable RefPtr<Storage> m_localStorage;
-        mutable RefPtr<DOMApplicationCache> m_applicationCache;
+        mutable RefPtr<ApplicationCache> m_applicationCache;
 
         mutable RefPtr<Performance> m_performance;
 
diff --git a/Source/core/page/DOMWindowBase64.cpp b/Source/core/page/DOMWindowBase64.cpp
index 78c0ea1..6411d14 100644
--- a/Source/core/page/DOMWindowBase64.cpp
+++ b/Source/core/page/DOMWindowBase64.cpp
@@ -65,7 +65,7 @@
     }
 
     Vector<char> out;
-    if (!base64Decode(encodedString, out, Base64FailOnInvalidCharacter, Base64StrictPaddingValidation)) {
+    if (!base64Decode(encodedString, out, Base64FailOnInvalidCharacterOrExcessPadding)) {
         es.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded is not correctly encoded.");
         return String();
     }
diff --git a/Source/core/page/DOMWindowLifecycleNotifier.cpp b/Source/core/page/DOMWindowLifecycleNotifier.cpp
new file mode 100644
index 0000000..782198a
--- /dev/null
+++ b/Source/core/page/DOMWindowLifecycleNotifier.cpp
@@ -0,0 +1,57 @@
+/*
+ * 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 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/page/DOMWindowLifecycleNotifier.h"
+
+namespace WebCore {
+
+DOMWindowLifecycleNotifier::DOMWindowLifecycleNotifier(LifecycleContext* context)
+    : LifecycleNotifier(context)
+{
+}
+
+void DOMWindowLifecycleNotifier::addObserver(LifecycleObserver* observer, LifecycleObserver::Type type)
+{
+    if (type == LifecycleObserver::DOMWindowLifecycleObserverType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
+        m_windowObservers.add(static_cast<DOMWindowLifecycleObserver*>(observer));
+    }
+
+    LifecycleNotifier::addObserver(observer, type);
+}
+
+void DOMWindowLifecycleNotifier::removeObserver(LifecycleObserver* observer, LifecycleObserver::Type type)
+{
+    if (type == LifecycleObserver::DOMWindowLifecycleObserverType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
+        m_windowObservers.remove(static_cast<DOMWindowLifecycleObserver*>(observer));
+    }
+
+    LifecycleNotifier::removeObserver(observer, type);
+}
+
+} // namespace WebCore
diff --git a/Source/core/page/DOMWindowLifecycleNotifier.h b/Source/core/page/DOMWindowLifecycleNotifier.h
new file mode 100644
index 0000000..49e1aa0
--- /dev/null
+++ b/Source/core/page/DOMWindowLifecycleNotifier.h
@@ -0,0 +1,68 @@
+/*
+ * 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 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 DOMWindowLifecycleNotifier_h
+#define DOMWindowLifecycleNotifier_h
+
+#include "core/page/DOMWindowLifecycleObserver.h"
+#include "core/platform/LifecycleNotifier.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/TemporaryChange.h"
+
+namespace WebCore {
+
+class DOMWindow;
+
+class DOMWindowLifecycleNotifier : public LifecycleNotifier {
+public:
+    static PassOwnPtr<DOMWindowLifecycleNotifier> create(LifecycleContext*);
+
+    void notifyRemoveAllEventListeners();
+
+    virtual void addObserver(LifecycleObserver*, LifecycleObserver::Type) OVERRIDE;
+    virtual void removeObserver(LifecycleObserver*, LifecycleObserver::Type) OVERRIDE;
+
+private:
+    explicit DOMWindowLifecycleNotifier(LifecycleContext*);
+
+    typedef HashSet<DOMWindowLifecycleObserver*> DOMWindowObserverSet;
+    DOMWindowObserverSet m_windowObservers;
+};
+
+inline PassOwnPtr<DOMWindowLifecycleNotifier> DOMWindowLifecycleNotifier::create(LifecycleContext* context)
+{
+    return adoptPtr(new DOMWindowLifecycleNotifier(context));
+}
+
+inline void DOMWindowLifecycleNotifier::notifyRemoveAllEventListeners()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDOMWindowObservers);
+    for (DOMWindowObserverSet::iterator it = m_windowObservers.begin(); it != m_windowObservers.end(); ++it)
+        (*it)->removeAllEventListeners();
+}
+
+} // namespace WebCore
+
+#endif // DOMWindowLifecycleNotifier_h
diff --git a/Source/core/loader/cache/ResourcePtr.cpp b/Source/core/page/DOMWindowLifecycleObserver.cpp
similarity index 70%
copy from Source/core/loader/cache/ResourcePtr.cpp
copy to Source/core/page/DOMWindowLifecycleObserver.cpp
index bbb4352..bd939d2 100644
--- a/Source/core/loader/cache/ResourcePtr.cpp
+++ b/Source/core/page/DOMWindowLifecycleObserver.cpp
@@ -1,5 +1,5 @@
 /*
- * 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
@@ -23,20 +23,27 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+
 #include "config.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/page/DOMWindowLifecycleObserver.h"
+
+#include "core/page/DOMWindow.h"
 
 namespace WebCore {
 
-void ResourcePtrBase::setResource(Resource* resource)
+DOMWindowLifecycleObserver::DOMWindowLifecycleObserver(DOMWindow* window)
+    : LifecycleObserver(window, DOMWindowLifecycleObserverType)
 {
-    if (resource == m_resource)
-        return;
-    if (m_resource)
-        m_resource->unregisterHandle(this);
-    m_resource = resource;
-    if (m_resource)
-        m_resource->registerHandle(this);
 }
 
+DOMWindowLifecycleObserver::~DOMWindowLifecycleObserver()
+{
+    observeContext(0, DOMWindowLifecycleObserverType);
 }
+
+DOMWindow* DOMWindowLifecycleObserver::window() const
+{
+    return static_cast<DOMWindow*>(lifecycleContext());
+}
+
+} // namespace WebCore
diff --git a/Source/core/loader/cache/ResourcePtr.cpp b/Source/core/page/DOMWindowLifecycleObserver.h
similarity index 71%
copy from Source/core/loader/cache/ResourcePtr.cpp
copy to Source/core/page/DOMWindowLifecycleObserver.h
index bbb4352..79aa153 100644
--- a/Source/core/loader/cache/ResourcePtr.cpp
+++ b/Source/core/page/DOMWindowLifecycleObserver.h
@@ -1,5 +1,6 @@
+
 /*
- * 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
@@ -23,20 +24,25 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/loader/cache/ResourcePtr.h"
+#ifndef DOMWindowLifecycleObserver_h
+#define DOMWindowLifecycleObserver_h
+
+#include "core/platform/LifecycleObserver.h"
 
 namespace WebCore {
 
-void ResourcePtrBase::setResource(Resource* resource)
-{
-    if (resource == m_resource)
-        return;
-    if (m_resource)
-        m_resource->unregisterHandle(this);
-    m_resource = resource;
-    if (m_resource)
-        m_resource->registerHandle(this);
-}
+class DOMWindow;
 
-}
+class DOMWindowLifecycleObserver : public LifecycleObserver {
+public:
+    explicit DOMWindowLifecycleObserver(DOMWindow*);
+    virtual ~DOMWindowLifecycleObserver();
+
+    DOMWindow* window() const;
+
+    virtual void removeAllEventListeners() { }
+};
+
+} // namespace WebCore
+
+#endif // DOMWindowLifecycleObserver_h
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index bf38105..0dfed59 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -44,14 +44,14 @@
 #include "core/editing/ReplaceSelectionCommand.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLPlugInElement.h"
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/DragActions.h"
 #include "core/page/DragClient.h"
 #include "core/page/DragSession.h"
@@ -169,10 +169,10 @@
                         title = url;
                 }
                 RefPtr<Node> anchorText = document->createTextNode(title);
-                anchor->appendChild(anchorText, IGNORE_EXCEPTION);
+                anchor->appendChild(anchorText);
                 RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
-                fragment->appendChild(anchor, IGNORE_EXCEPTION);
-                return fragment.get();
+                fragment->appendChild(anchor);
+                return fragment.release();
             }
         }
     }
diff --git a/Source/core/page/EditorClient.h b/Source/core/page/EditorClient.h
index 4263ca9..5b866af 100644
--- a/Source/core/page/EditorClient.h
+++ b/Source/core/page/EditorClient.h
@@ -47,7 +47,6 @@
 class Node;
 class Range;
 class SharedBuffer;
-class SpellChecker;
 class StylePropertySet;
 class TextCheckerClient;
 class VisibleSelection;
@@ -98,7 +97,7 @@
     virtual void textDidChangeInTextField(Element*) = 0;
     virtual bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*) = 0;
 
-    virtual TextCheckerClient* textChecker() = 0;
+    virtual TextCheckerClient& textChecker() = 0;
 
     virtual void updateSpellingUIWithMisspelledWord(const String&) = 0;
     virtual void showSpellingUI(bool show) = 0;
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 8ab18af..45fe206 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -50,12 +50,12 @@
 #include "core/editing/FrameSelection.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/htmlediting.h"
+#include "core/fetch/ImageResource.h"
 #include "core/history/BackForwardController.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLFrameSetElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Chrome.h"
 #include "core/page/DragController.h"
 #include "core/page/DragState.h"
@@ -1178,7 +1178,7 @@
         if (renderer) {
             if (RenderLayer* layer = renderer->enclosingLayer()) {
                 if (FrameView* view = m_frame->view())
-                    inResizer = layer->isPointInResizeControl(view->windowToContents(event.event().position()), RenderLayer::ResizerForPointer);
+                    inResizer = layer->isPointInResizeControl(view->windowToContents(event.event().position()), ResizerForPointer);
             }
         }
         if ((editable || (renderer && renderer->isText() && node->canStartSelection())) && !inResizer && !scrollbar)
@@ -1344,7 +1344,7 @@
     if (FrameView* view = m_frame->view()) {
         RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
         IntPoint p = view->windowToContents(mouseEvent.position());
-        if (layer && layer->isPointInResizeControl(p, RenderLayer::ResizerForPointer)) {
+        if (layer && layer->isPointInResizeControl(p, ResizerForPointer)) {
             layer->setInResizeMode(true);
             m_resizeLayer = layer;
             m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
@@ -1414,6 +1414,20 @@
     return layer;
 }
 
+ScrollableArea* EventHandler::associatedScrollableArea(const RenderLayer* layer) const
+{
+    ScrollableArea* layerScrollableArea = layer->scrollableArea();
+    if (!layerScrollableArea)
+        return 0;
+
+    if (FrameView* frameView = m_frame->view()) {
+        if (frameView->containsScrollableArea(layerScrollableArea))
+            return layerScrollableArea;
+    }
+
+    return 0;
+}
+
 bool EventHandler::mouseMoved(const PlatformMouseEvent& event)
 {
     RefPtr<FrameView> protector(m_frame->view());
@@ -1427,10 +1441,8 @@
         return result;
 
     if (RenderLayer* layer = layerForNode(hoveredNode.innerNode())) {
-        if (FrameView* frameView = m_frame->view()) {
-            if (frameView->containsScrollableArea(layer))
-                layer->mouseMovedInContentArea();
-        }
+        if (ScrollableArea* layerScrollableArea = associatedScrollableArea(layer))
+            layerScrollableArea->mouseMovedInContentArea();
     }
 
     if (FrameView* frameView = m_frame->view())
@@ -1685,7 +1697,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()->client().supportsGlobalSelection())
         return m_frame->editor()->command("PasteGlobalSelection").execute();
 
     return false;
@@ -1720,8 +1732,7 @@
     if (!target->hasTagName(frameTag) && !target->hasTagName(iframeTag))
         return false;
 
-    frame = static_cast<HTMLFrameElementBase*>(target)->contentFrame();
-
+    frame = toHTMLFrameElementBase(target)->contentFrame();
     return true;
 }
 
@@ -1958,12 +1969,8 @@
             }
         } else if (page && (layerForLastNode && (!layerForNodeUnderMouse || layerForNodeUnderMouse != layerForLastNode))) {
             // The mouse has moved between layers.
-            if (Frame* frame = m_lastNodeUnderMouse->document()->frame()) {
-                if (FrameView* frameView = frame->view()) {
-                    if (frameView->containsScrollableArea(layerForLastNode))
-                        layerForLastNode->mouseExitedContentArea();
-                }
-            }
+            if (ScrollableArea* scrollableAreaForLastNode = associatedScrollableArea(layerForLastNode))
+                scrollableAreaForLastNode->mouseExitedContentArea();
         }
 
         if (m_nodeUnderMouse && (!m_lastNodeUnderMouse || m_lastNodeUnderMouse->document() != m_frame->document())) {
@@ -1974,12 +1981,8 @@
             }
         } else if (page && (layerForNodeUnderMouse && (!layerForLastNode || layerForNodeUnderMouse != layerForLastNode))) {
             // The mouse has moved between layers.
-            if (Frame* frame = m_nodeUnderMouse->document()->frame()) {
-                if (FrameView* frameView = frame->view()) {
-                    if (frameView->containsScrollableArea(layerForNodeUnderMouse))
-                        layerForNodeUnderMouse->mouseEnteredContentArea();
-                }
-            }
+            if (ScrollableArea* scrollableAreaForNodeUnderMouse = associatedScrollableArea(layerForNodeUnderMouse))
+                scrollableAreaForNodeUnderMouse->mouseEnteredContentArea();
         }
 
         if (m_lastNodeUnderMouse && m_lastNodeUnderMouse->document() != m_frame->document()) {
@@ -2420,7 +2423,7 @@
     if (gestureEvent.type() == PlatformEvent::GestureScrollBegin) {
         RenderLayer* layer = eventTarget->renderer() ? eventTarget->renderer()->enclosingLayer() : 0;
         IntPoint p = m_frame->view()->windowToContents(gestureEvent.position());
-        if (layer && layer->isPointInResizeControl(p, RenderLayer::ResizerForTouch)) {
+        if (layer && layer->isPointInResizeControl(p, ResizerForTouch)) {
             layer->setInResizeMode(true);
             m_resizeLayer = layer;
             m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
@@ -2498,11 +2501,17 @@
     m_scrollGestureHandlingNode = result.innerNode();
     m_previousGestureScrolledNode = 0;
 
-    Node* node = m_scrollGestureHandlingNode.get();
-    if (node)
-        passGestureEventToWidgetIfPossible(gestureEvent, node->renderer());
+    // If there's no renderer on the node, send the event to the nearest ancestor with a renderer.
+    // Needed for <option> and <optgroup> elements so we can touch scroll <select>s
+    while (m_scrollGestureHandlingNode && !m_scrollGestureHandlingNode->renderer())
+        m_scrollGestureHandlingNode = m_scrollGestureHandlingNode->parentOrShadowHostNode();
 
-    return node && node->renderer();
+    if (!m_scrollGestureHandlingNode)
+        return false;
+
+    passGestureEventToWidgetIfPossible(gestureEvent, m_scrollGestureHandlingNode->renderer());
+
+    return true;
 }
 
 bool EventHandler::handleGestureScrollUpdate(const PlatformGestureEvent& gestureEvent)
@@ -3381,9 +3390,9 @@
     bool handledEvent = false;
 
     if (event->shiftKey())
-        handledEvent = page->backForward()->goForward();
+        handledEvent = page->backForward().goForward();
     else
-        handledEvent = page->backForward()->goBack();
+        handledEvent = page->backForward().goBack();
 
     if (handledEvent)
         event->setDefaultHandled();
diff --git a/Source/core/page/EventHandler.h b/Source/core/page/EventHandler.h
index 22f62e9..131b990 100644
--- a/Source/core/page/EventHandler.h
+++ b/Source/core/page/EventHandler.h
@@ -67,6 +67,7 @@
 class RenderObject;
 class RenderWidget;
 class SVGElementInstance;
+class ScrollableArea;
 class Scrollbar;
 class TextEvent;
 class TouchEvent;
@@ -231,6 +232,8 @@
 
     bool isInsideScrollbar(const IntPoint&) const;
 
+    ScrollableArea* associatedScrollableArea(const RenderLayer*) const;
+
     bool dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent&);
     HitTestResult hitTestResultInFrame(Frame*, const LayoutPoint&, HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
 
diff --git a/Source/core/page/EventSource.cpp b/Source/core/page/EventSource.cpp
index 24b9608..f9cb1c5 100644
--- a/Source/core/page/EventSource.cpp
+++ b/Source/core/page/EventSource.cpp
@@ -92,7 +92,8 @@
         shouldBypassMainWorldContentSecurityPolicy = document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
     }
     if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
-        es.throwDOMException(SecurityError, "Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
+        // 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.");
         return 0;
     }
 
diff --git a/Source/core/page/FocusController.cpp b/Source/core/page/FocusController.cpp
index b6dbab5..e35e406 100644
--- a/Source/core/page/FocusController.cpp
+++ b/Source/core/page/FocusController.cpp
@@ -32,10 +32,10 @@
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/NodeRenderingTraversal.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/dom/Range.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -124,7 +124,7 @@
         document->focusedElement()->dispatchBlurEvent(0);
     document->dispatchWindowEvent(Event::create(focused ? eventNames().focusEvent : eventNames().blurEvent, false, false));
     if (focused && document->focusedElement())
-        document->focusedElement()->dispatchFocusEvent(0, FocusDirectionNone);
+        document->focusedElement()->dispatchFocusEvent(0, FocusDirectionPage);
 }
 
 static inline bool hasCustomFocusLogic(Element* element)
@@ -244,7 +244,7 @@
     // 1) a focusable node, or
     // 2) the deepest-nested HTMLFrameOwnerElement.
     while (node && node->isFrameOwnerElement()) {
-        HTMLFrameOwnerElement* owner = static_cast<HTMLFrameOwnerElement*>(node);
+        HTMLFrameOwnerElement* owner = toHTMLFrameOwnerElement(node);
         if (!owner->contentFrame())
             break;
         Node* foundNode = findFocusableNode(direction, FocusNavigationScope::focusNavigationScopeOwnedByIFrame(owner), 0);
@@ -335,7 +335,7 @@
     if (element->isFrameOwnerElement() && (!element->isPluginElement() || !element->isKeyboardFocusable())) {
         // We focus frames rather than frame owners.
         // FIXME: We should not focus frames that have no scrollbars, as focusing them isn't useful to the user.
-        HTMLFrameOwnerElement* owner = static_cast<HTMLFrameOwnerElement*>(element);
+        HTMLFrameOwnerElement* owner = toHTMLFrameOwnerElement(element);
         if (!owner->contentFrame())
             return false;
 
@@ -603,7 +603,7 @@
     if (oldFocusedElement && oldFocusedElement->isRootEditableElement() && !relinquishesEditingFocus(oldFocusedElement))
         return false;
 
-    m_page->editorClient()->willSetInputMethodState();
+    m_page->editorClient().willSetInputMethodState();
 
     clearSelectionIfNeeded(oldFocusedFrame.get(), newFocusedFrame.get(), element);
 
diff --git a/Source/core/page/FocusDirection.h b/Source/core/page/FocusDirection.h
index fc0ded3..c972e11 100644
--- a/Source/core/page/FocusDirection.h
+++ b/Source/core/page/FocusDirection.h
@@ -27,15 +27,22 @@
 #define FocusDirection_h
 
 namespace WebCore {
+// FIXME: Rename FocusDirection to FocusType or something.
     enum FocusDirection {
+        // Element::focus(), etc.
         FocusDirectionNone = 0,
+        // TAB, or Shift + TAB
         FocusDirectionForward,
         FocusDirectionBackward,
+        // Spatial navigation.
         FocusDirectionUp,
         FocusDirectionDown,
         FocusDirectionLeft,
         FocusDirectionRight,
-        FocusDirectionMouse
+        // Mouse press
+        FocusDirectionMouse,
+        // Re-focus by a page focus
+        FocusDirectionPage
     };
 }
 
diff --git a/Source/core/page/Frame.cpp b/Source/core/page/Frame.cpp
index a3e42b6..b7edcf8 100644
--- a/Source/core/page/Frame.cpp
+++ b/Source/core/page/Frame.cpp
@@ -39,10 +39,10 @@
 #include "core/editing/InputMethodController.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/DOMWindow.h"
@@ -139,7 +139,7 @@
 Frame::~Frame()
 {
     setView(0);
-    loader()->cancelAndClear();
+    loader()->clear(ClearScriptObjects | ClearWindowObject);
 
     // FIXME: We should not be doing all this work inside the destructor
 
@@ -219,7 +219,7 @@
 
 Settings* Frame::settings() const
 {
-    return m_page ? m_page->settings() : 0;
+    return m_page ? &m_page->settings() : 0;
 }
 
 void Frame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot shouldAdjustViewSize)
@@ -579,7 +579,7 @@
     for (RefPtr<Frame> child = tree()->firstChild(); child; child = child->tree()->nextSibling())
         child->deviceOrPageScaleFactorChanged();
 
-    m_page->chrome().client()->deviceOrPageScaleFactorChanged();
+    m_page->chrome().client().deviceOrPageScaleFactorChanged();
 }
 
 void Frame::notifyChromeClientWheelEventHandlerCountChanged() const
@@ -593,7 +593,7 @@
             count += frame->document()->wheelEventHandlerCount();
     }
 
-    m_page->chrome().client()->numWheelEventHandlersChanged(count);
+    m_page->chrome().client().numWheelEventHandlersChanged(count);
 }
 
 bool Frame::isURLAllowed(const KURL& url) const
@@ -709,4 +709,15 @@
     return DragImage::create(image.get());
 }
 
+double Frame::devicePixelRatio() const
+{
+    if (!m_page)
+        return 0;
+
+    double ratio = m_page->deviceScaleFactor();
+    if (RuntimeEnabledFeatures::devicePixelRatioIncludesZoomEnabled())
+        ratio *= pageZoomFactor();
+    return ratio;
+}
+
 } // namespace WebCore
diff --git a/Source/core/page/Frame.h b/Source/core/page/Frame.h
index 47fdc5a..3590900 100644
--- a/Source/core/page/Frame.h
+++ b/Source/core/page/Frame.h
@@ -135,6 +135,7 @@
         void setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor);
 
         void deviceOrPageScaleFactorChanged();
+        double devicePixelRatio() const;
 
 #if ENABLE(ORIENTATION_EVENTS)
         // Orientation is the interface orientation in degrees. Some examples are:
diff --git a/Source/core/page/FrameActionScheduler.h b/Source/core/page/FrameActionScheduler.h
index a4282e7..a4143be 100644
--- a/Source/core/page/FrameActionScheduler.h
+++ b/Source/core/page/FrameActionScheduler.h
@@ -53,6 +53,8 @@
     ~FrameActionScheduler();
 
     bool isEmpty() const;
+    // FIXME: Why is this < m_enqueueActions, does this
+    // mean that the steady state of m_enqueueActions should be -1?
     bool isScheduled() const { return 0 < m_enqueueActions; }
     void clear();
     void pause();
diff --git a/Source/core/page/FrameView.cpp b/Source/core/page/FrameView.cpp
index 72c0b02..8ed4152 100644
--- a/Source/core/page/FrameView.cpp
+++ b/Source/core/page/FrameView.cpp
@@ -36,6 +36,7 @@
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/OverflowEvent.h"
 #include "core/editing/FrameSelection.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLFrameElement.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLPlugInImageElement.h"
@@ -43,7 +44,6 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
@@ -63,7 +63,6 @@
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderLazyBlock.h"
 #include "core/rendering/RenderPart.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderScrollbarPart.h"
@@ -84,7 +83,8 @@
 
 using namespace HTMLNames;
 
-double FrameView::sCurrentPaintTimeStamp = 0.0;
+double FrameView::s_currentFrameTimeStamp = 0.0;
+bool FrameView::s_inPaintContents = false;
 
 
 // REPAINT_THROTTLING now chooses default values for throttling parameters.
@@ -315,7 +315,7 @@
     // Propagate the marginwidth/height and scrolling modes to the view.
     Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
     if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
-        HTMLFrameElementBase* frameElt = static_cast<HTMLFrameElementBase*>(ownerElement);
+        HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
         if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
             setCanHaveScrollbars(false);
         LayoutUnit marginWidth = frameElt->marginWidth();
@@ -430,7 +430,7 @@
     // Autosized font sizes depend on the width of the viewing area.
     if (newRect.width() != oldRect.width()) {
         Page* page = m_frame ? m_frame->page() : 0;
-        if (page && page->mainFrame() == m_frame && page->settings()->textAutosizingEnabled()) {
+        if (page && page->mainFrame() == m_frame && page->settings().textAutosizingEnabled()) {
             for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
                 m_frame->document()->textAutosizer()->recalculateMultipliers();
         }
@@ -444,6 +444,8 @@
         if (renderView->usesCompositing())
             renderView->compositor()->frameViewDidChangeSize();
     }
+
+    sendResizeEventIfNeeded();
 }
 
 bool FrameView::scheduleAnimation()
@@ -676,6 +678,7 @@
 
 void FrameView::updateCompositingLayersAfterStyleChange()
 {
+    TRACE_EVENT0("webkit", "FrameView::updateCompositingLayersAfterStyleChange");
     RenderView* renderView = this->renderView();
     if (!renderView)
         return;
@@ -698,6 +701,7 @@
 
 void FrameView::updateCompositingLayersAfterLayout()
 {
+    TRACE_EVENT0("webkit", "FrameView::updateCompositingLayersAfterLayout");
     RenderView* renderView = this->renderView();
     if (!renderView)
         return;
@@ -834,6 +838,104 @@
     frameView->layout();
 }
 
+void FrameView::performPreLayoutTasks()
+{
+    // Don't schedule more layouts, we're in one.
+    TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
+
+    if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !frame()->document()->shouldDisplaySeamlesslyWithParent()) {
+        // This is a new top-level layout. If there are any remaining tasks from the previous layout, finish them now.
+        m_inSynchronousPostLayout = true;
+        performPostLayoutTasks();
+        m_inSynchronousPostLayout = false;
+    }
+
+    // Viewport-dependent media queries may cause us to need completely different style information.
+    Document* document = m_frame->document();
+    if (!document->styleResolverIfExists() || document->styleResolverIfExists()->affectedByViewportChange()) {
+        document->styleResolverChanged(RecalcStyleDeferred);
+        // FIXME: This instrumentation event is not strictly accurate since cached media query results
+        //        do not persist across StyleResolver rebuilds.
+        InspectorInstrumentation::mediaQueryResultChanged(document);
+    } else {
+        document->evaluateMediaQueryList();
+    }
+
+    // If there is any pagination to apply, it will affect the RenderView's style, so we should
+    // take care of that now.
+    applyPaginationToViewport();
+
+    // Always ensure our style info is up-to-date. This can happen in situations where
+    // the layout beats any sort of style recalc update that needs to occur.
+    TemporaryChange<bool> changeDoingPreLayoutStyleUpdate(m_doingPreLayoutStyleUpdate, true);
+    document->updateStyleIfNeeded();
+}
+
+void FrameView::performLayout(RenderObject* rootForThisLayout, bool inSubtreeLayout)
+{
+    // performLayout is the actual guts of layout().
+    // FIXME: The 300 other lines in layout() probably belong in other helper functions
+    // so that a single human could understand what layout() is actually doing.
+
+    bool disableLayoutState = false;
+    if (inSubtreeLayout) {
+        RenderView* view = rootForThisLayout->view();
+        disableLayoutState = view->shouldDisableLayoutStateForSubtree(rootForThisLayout);
+        view->pushLayoutState(rootForThisLayout);
+    }
+    LayoutStateDisabler layoutStateDisabler(disableLayoutState ? rootForThisLayout->view() : 0);
+
+    m_inLayout = true;
+    beginDeferredRepaints();
+    forceLayoutParentViewIfNeeded();
+
+    rootForThisLayout->layout(); // THIS IS WHERE LAYOUT ACTUALLY HAPPENS.
+
+    bool autosized = frame()->document()->textAutosizer()->processSubtree(rootForThisLayout);
+    if (autosized && rootForThisLayout->needsLayout()) {
+        TRACE_EVENT0("webkit", "2nd layout due to Text Autosizing");
+        rootForThisLayout->layout();
+    }
+
+    endDeferredRepaints();
+    m_inLayout = false;
+
+    if (inSubtreeLayout)
+        rootForThisLayout->view()->popLayoutState(rootForThisLayout);
+}
+
+void FrameView::scheduleOrPerformPostLayoutTasks()
+{
+    if (m_postLayoutTasksTimer.isActive()) {
+        m_actionScheduler->resume();
+        return;
+    }
+
+    if (!m_inSynchronousPostLayout) {
+        if (frame()->document()->shouldDisplaySeamlesslyWithParent()) {
+            if (RenderView* renderView = this->renderView())
+                renderView->updateWidgetPositions();
+        } else {
+            m_inSynchronousPostLayout = true;
+            // Calls resumeScheduledEvents()
+            performPostLayoutTasks();
+            m_inSynchronousPostLayout = false;
+        }
+    }
+
+    if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || frame()->document()->shouldDisplaySeamlesslyWithParent())) {
+        // If we need layout or are already in a synchronous call to postLayoutTasks(),
+        // defer widget updates and event dispatch until after we return. postLayoutTasks()
+        // 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 (needsLayout()) {
+            m_actionScheduler->pause();
+            layout();
+        }
+    }
+}
+
 void FrameView::layout(bool allowSubtree)
 {
     // We should never layout a Document which is not in a Frame.
@@ -869,54 +971,21 @@
         m_layoutRoot = 0;
     }
 
+    performPreLayoutTasks();
+
+    // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
+    // so there's no point to continuing to layout
+    if (protector->hasOneRef())
+        return;
+
     Document* document = m_frame->document();
-    bool inSubtreeLayout = false;
-    RenderObject* rootForThisLayout = 0;
-
-    {
-        TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
-
-        if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !frame()->document()->shouldDisplaySeamlesslyWithParent()) {
-            // This is a new top-level layout. If there are any remaining tasks from the previous layout, finish them now.
-            m_inSynchronousPostLayout = true;
-            performPostLayoutTasks();
-            m_inSynchronousPostLayout = false;
-        }
-
-        // Viewport-dependent media queries may cause us to need completely different style information.
-        if (!document->styleResolverIfExists() || document->styleResolverIfExists()->affectedByViewportChange()) {
-            document->styleResolverChanged(DeferRecalcStyle);
-            // FIXME: This instrumentation event is not strictly accurate since cached media query results
-            //        do not persist across StyleResolver rebuilds.
-            InspectorInstrumentation::mediaQueryResultChanged(document);
-        } else {
-            document->evaluateMediaQueryList();
-        }
-
-        // If there is any pagination to apply, it will affect the RenderView's style, so we should
-        // take care of that now.
-        applyPaginationToViewport();
-
-        // Always ensure our style info is up-to-date. This can happen in situations where
-        // the layout beats any sort of style recalc update that needs to occur.
-        TemporaryChange<bool> changeDoingPreLayoutStyleUpdate(m_doingPreLayoutStyleUpdate, true);
-        document->updateStyleIfNeeded();
-
-        inSubtreeLayout = m_layoutRoot;
-
-        // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
-        // so there's no point to continuing to layout
-        if (protector->hasOneRef())
-            return;
-
-        rootForThisLayout = inSubtreeLayout ? m_layoutRoot : document->renderer();
-        if (!rootForThisLayout) {
-            // FIXME: Do we need to set m_size here?
-            return;
-        }
-    } // Reset m_layoutSchedulingEnabled to its previous value.
-    // The only reason the scoping was closed here is allow fontCachePurgePreventer
-    // to outlive the change and reset of m_layoutSchedulingEnabled.
+    bool inSubtreeLayout = m_layoutRoot;
+    RenderObject* rootForThisLayout = inSubtreeLayout ? m_layoutRoot : document->renderer();
+    if (!rootForThisLayout) {
+        // FIXME: Do we need to set m_size here?
+        ASSERT_NOT_REACHED();
+        return;
+    }
 
     FontCachePurgePreventer fontCachePurgePreventer;
     RenderLayer* layer;
@@ -980,33 +1049,7 @@
         layer = rootForThisLayout->enclosingLayer();
 
         m_actionScheduler->pause();
-
-        {
-            bool disableLayoutState = false;
-            if (inSubtreeLayout) {
-                RenderView* view = rootForThisLayout->view();
-                disableLayoutState = view->shouldDisableLayoutStateForSubtree(rootForThisLayout);
-                view->pushLayoutState(rootForThisLayout);
-            }
-            LayoutStateDisabler layoutStateDisabler(disableLayoutState ? rootForThisLayout->view() : 0);
-
-            m_inLayout = true;
-            beginDeferredRepaints();
-            forceLayoutParentViewIfNeeded();
-            rootForThisLayout->layout();
-
-            bool autosized = document->textAutosizer()->processSubtree(rootForThisLayout);
-            if (autosized && rootForThisLayout->needsLayout()) {
-                TRACE_EVENT0("webkit", "2nd layout due to Text Autosizing");
-                rootForThisLayout->layout();
-            }
-
-            endDeferredRepaints();
-            m_inLayout = false;
-
-            if (inSubtreeLayout)
-                rootForThisLayout->view()->popLayoutState(rootForThisLayout);
-        }
+        performLayout(rootForThisLayout, inSubtreeLayout);
         m_layoutRoot = 0;
     } // Reset m_layoutSchedulingEnabled to its previous value.
 
@@ -1019,9 +1062,12 @@
 
     // Now update the positions of all layers.
     beginDeferredRepaints();
-    if (m_doFullRepaint)
-        rootForThisLayout->view()->repaint(); // FIXME: This isn't really right, since the RenderView doesn't fully encompass the visibleContentRect(). It just happens
-                                 // to work out most of the time, since first layouts and printing don't have you scrolled anywhere.
+    if (m_doFullRepaint) {
+        // FIXME: This isn't really right, since the RenderView doesn't fully encompass
+        // 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();
+    }
 
     layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, inSubtreeLayout, m_doFullRepaint));
 
@@ -1035,8 +1081,6 @@
         cache->postNotification(rootForThisLayout, AXObjectCache::AXLayoutComplete, true);
     updateAnnotatedRegions();
 
-    layoutLazyBlocks();
-
     ASSERT(!rootForThisLayout->needsLayout());
 
     updateCanBlitOnScrollRecursively();
@@ -1044,33 +1088,9 @@
     if (document->hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
         updateOverflowStatus(layoutWidth() < contentsWidth(), layoutHeight() < contentsHeight());
 
-    if (!m_postLayoutTasksTimer.isActive()) {
-        if (!m_inSynchronousPostLayout) {
-            if (frame()->document()->shouldDisplaySeamlesslyWithParent()) {
-                if (RenderView* renderView = this->renderView())
-                    renderView->updateWidgetPositions();
-            } else {
-                m_inSynchronousPostLayout = true;
-                // Calls resumeScheduledEvents()
-                performPostLayoutTasks();
-                m_inSynchronousPostLayout = false;
-            }
-        }
-
-        if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || frame()->document()->shouldDisplaySeamlesslyWithParent())) {
-            // If we need layout or are already in a synchronous call to postLayoutTasks(),
-            // defer widget updates and event dispatch until after we return. postLayoutTasks()
-            // 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 (needsLayout()) {
-                m_actionScheduler->pause();
-                layout();
-            }
-        }
-    } else {
-        m_actionScheduler->resume();
-    }
+    // Resume scheduled events (FrameActionScheduler m_actionScheduler)
+    // and ensure post layout tasks are executed or scheduled to be.
+    scheduleOrPerformPostLayoutTasks();
 
     InspectorInstrumentation::didLayout(cookie, rootForThisLayout);
 
@@ -1092,36 +1112,7 @@
     ASSERT(frame());
     // ASSERT(frame()->page());
     if (frame() && frame()->page())
-        frame()->page()->chrome().client()->layoutUpdated(frame());
-}
-
-void FrameView::layoutLazyBlocks()
-{
-    // FIXME: This infinite recursion protection would seem to break plugins
-    // doing things that require lazy blocks to layout.
-    if (m_nestedLayoutCount != 1)
-        return;
-
-    if (!renderView()->firstLazyBlock())
-        return;
-
-    // First mark all lazy blocks as needing layout and perform another layout.
-    for (RenderLazyBlock* block = renderView()->firstLazyBlock(); block; block = block->next())
-        block->markForNestedLayout();
-
-    layout();
-
-    // FIXME: This is pretty awful if you start nesting lazy blocks, we should
-    // signal to the nested blocks to avoid doing work until the second pass.
-
-    // Next walk all lazy blocks and find nested ones, these need another layout
-    // since the first one would not have placed them correctly inside the viewport.
-    for (RenderLazyBlock* block = renderView()->firstLazyBlock(); block; block = block->next()) {
-        if (!block->isNested())
-            continue;
-        block->setNeedsLayout();
-        layout();
-    }
+        frame()->page()->chrome().client().layoutUpdated(frame());
 }
 
 RenderBox* FrameView::embeddedContentBox() const
@@ -1542,7 +1533,7 @@
 
     Page* page = m_frame->page();
     if (page && RuntimeEnabledFeatures::programmaticScrollNotificationsEnabled())
-        page->chrome().client()->didProgrammaticallyScroll(m_frame.get(), newScrollPosition);
+        page->chrome().client().didProgrammaticallyScroll(m_frame.get(), newScrollPosition);
 
     if (requestScrollPositionUpdate(newScrollPosition))
         return;
@@ -1582,8 +1573,6 @@
     if (RenderView* renderView = this->renderView()) {
         if (renderView->usesCompositing())
             renderView->compositor()->frameViewDidScroll();
-
-        renderView->markLazyBlocksForLayout();
     }
 }
 
@@ -1612,7 +1601,7 @@
     Page* page = frame() ? frame()->page() : 0;
     if (!page)
         return ScrollView::shouldRubberBandInDirection(direction);
-    return page->chrome().client()->shouldRubberBandInDirection(direction);
+    return page->chrome().client().shouldRubberBandInDirection(direction);
 }
 
 bool FrameView::isRubberBandInProgress() const
@@ -1798,7 +1787,7 @@
 bool FrameView::shouldUseLoadTimeDeferredRepaintDelay() const
 {
     // Don't defer after the initial load of the page has been completed.
-    if (m_frame->tree()->top()->loader()->isComplete())
+    if (m_frame->tree()->top()->document()->loadEventFinished())
         return false;
     Document* document = m_frame->document();
     if (!document)
@@ -1879,7 +1868,7 @@
     // When frame seamless is enabled, the contents of the frame could affect the layout of the parent frames.
     // Also invalidate parent frame starting from the owner element of this frame.
     if (m_frame->ownerRenderer() && frame()->document()->shouldDisplaySeamlesslyWithParent())
-        m_frame->ownerRenderer()->setNeedsLayout(MarkContainingBlockChain);
+        m_frame->ownerRenderer()->setNeedsLayout();
 
     int delay = m_frame->document()->minimumLayoutDelay();
     if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
@@ -2181,6 +2170,7 @@
 
 void FrameView::performPostLayoutTasks()
 {
+    TRACE_EVENT0("webkit", "FrameView::performPostLayoutTasks");
     // updateWidgets() call below can blow us away from underneath.
     RefPtr<FrameView> protect(this);
 
@@ -2240,20 +2230,33 @@
 
     m_actionScheduler->resume();
 
-    // Refetch render view since it can be destroyed by updateWidget() call above.
-    renderView = this->renderView();
-    if (renderView && !renderView->printing()) {
-        IntSize currentSize = layoutSize(IncludeScrollbars);
-        float currentZoomFactor = renderView->style()->zoom();
-        bool resized = !m_firstLayout && (currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor);
-        m_lastViewportSize = currentSize;
-        m_lastZoomFactor = currentZoomFactor;
-        if (resized) {
-            m_frame->eventHandler()->sendResizeEvent();
-            if (page && page->mainFrame() == m_frame)
-                InspectorInstrumentation::didResizeMainFrame(page);
-        }
-    }
+    sendResizeEventIfNeeded();
+}
+
+void FrameView::sendResizeEventIfNeeded()
+{
+    ASSERT(m_frame);
+
+    RenderView* renderView = this->renderView();
+    if (!renderView || renderView->printing())
+        return;
+
+    IntSize currentSize = layoutSize(IncludeScrollbars);
+    float currentZoomFactor = renderView->style()->zoom();
+
+    bool shouldSendResizeEvent = currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor;
+
+    m_lastViewportSize = currentSize;
+    m_lastZoomFactor = currentZoomFactor;
+
+    if (!shouldSendResizeEvent)
+        return;
+
+    m_frame->eventHandler()->sendResizeEvent();
+
+    Page* page = m_frame->page();
+    if (page && page->mainFrame() == m_frame)
+        InspectorInstrumentation::didResizeMainFrame(page);
 }
 
 void FrameView::postLayoutTimerFired(Timer<FrameView>*)
@@ -2345,7 +2348,7 @@
         // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
         // unless autoresize has just been turned on or the maximum size is smaller than the current size.
         if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
-            && !frame()->loader()->isComplete() && (newSize.height() < size.height() || newSize.width() < size.width()))
+            && !frame()->document()->loadEventFinished() && (newSize.height() < size.height() || newSize.width() < size.width()))
             break;
 
         resize(newSize.width(), newSize.height());
@@ -2405,7 +2408,7 @@
     m_pagination = pagination;
 
     if (m_frame)
-        m_frame->document()->styleResolverChanged(DeferRecalcStyle);
+        m_frame->document()->styleResolverChanged(RecalcStyleDeferred);
 }
 
 IntRect FrameView::windowClipRect(bool clipToContents) const
@@ -2626,7 +2629,7 @@
 bool FrameView::scrollAnimatorEnabled() const
 {
     if (Page* page = m_frame->page())
-        return page->settings()->scrollAnimatorEnabled();
+        return page->settings().scrollAnimatorEnabled();
     return false;
 }
 
@@ -2640,10 +2643,8 @@
     if (newRegions == document->annotatedRegions())
         return;
     document->setAnnotatedRegions(newRegions);
-    Page* page = m_frame->page();
-    if (!page)
-        return;
-    page->chrome().client()->annotatedRegionsChanged();
+    if (Page* page = m_frame->page())
+        page->chrome().client().annotatedRegionsChanged();
 }
 
 void FrameView::updateScrollCorner()
@@ -2864,9 +2865,8 @@
 
     InspectorInstrumentation::willPaint(renderView);
 
-    bool isTopLevelPainter = !sCurrentPaintTimeStamp;
-    if (isTopLevelPainter)
-        sCurrentPaintTimeStamp = currentTime();
+    bool isTopLevelPainter = !s_inPaintContents;
+    s_inPaintContents = true;
 
     FontCachePurgePreventer fontCachePurgePreventer;
 
@@ -2908,8 +2908,12 @@
     if (document->annotatedRegionsDirty())
         updateAnnotatedRegions();
 
-    if (isTopLevelPainter)
-        sCurrentPaintTimeStamp = 0;
+    if (isTopLevelPainter) {
+        // Everythin that happens after paintContents completions is considered
+        // to be part of the next frame.
+        s_currentFrameTimeStamp = currentTime();
+        s_inPaintContents = false;
+    }
 
     InspectorInstrumentation::didPaint(renderView, p, rect);
 }
@@ -2944,7 +2948,7 @@
 
     Page* page = m_frame->page();
     if (page->mainFrame() == m_frame) {
-        if (page->chrome().client()->paintCustomOverhangArea(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect))
+        if (page->chrome().client().paintCustomOverhangArea(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect))
             return;
     }
 
@@ -3305,11 +3309,11 @@
     return true;
 }
 
-bool FrameView::containsScrollableArea(ScrollableArea* scrollableArea) const
+bool FrameView::containsScrollableArea(const ScrollableArea* scrollableArea) const
 {
     if (!m_scrollableAreas)
         return false;
-    return m_scrollableAreas->contains(scrollableArea);
+    return m_scrollableAreas->contains(const_cast<ScrollableArea*>(scrollableArea));
 }
 
 void FrameView::removeChild(Widget* widget)
diff --git a/Source/core/page/FrameView.h b/Source/core/page/FrameView.h
index 6440cc9..a17b47b 100644
--- a/Source/core/page/FrameView.h
+++ b/Source/core/page/FrameView.h
@@ -102,8 +102,6 @@
     bool layoutPending() const;
     bool isInLayout() const { return m_inLayout; }
 
-    void layoutLazyBlocks();
-
     RenderObject* layoutRoot(bool onlyDuringLayout = false) const;
     void clearLayoutRoot() { m_layoutRoot = 0; }
     int layoutCount() const { return m_layoutCount; }
@@ -234,7 +232,7 @@
 
     StyleColor documentBackgroundColor() const;
 
-    static double currentPaintTimeStamp() { return sCurrentPaintTimeStamp; } // returns 0 if not painting
+    static double currentFrameTimeStamp() { return s_currentFrameTimeStamp; }
 
     void updateLayoutAndStyleIfNeededRecursive();
 
@@ -299,7 +297,7 @@
     bool addScrollableArea(ScrollableArea*);
     // Returns whether the scrollable area has just been removed.
     bool removeScrollableArea(ScrollableArea*);
-    bool containsScrollableArea(ScrollableArea*) const;
+    bool containsScrollableArea(const ScrollableArea*) const;
     const ScrollableAreaSet* scrollableAreas() const { return m_scrollableAreas.get(); }
 
     // With CSS style "resize:" enabled, a little resizer handle will appear at the bottom
@@ -365,9 +363,12 @@
 
     void paintControlTints();
 
-    void forceLayoutParentViewIfNeeded();
-    void performPostLayoutTasks();
     void autoSizeIfEnabled();
+    void forceLayoutParentViewIfNeeded();
+    void performPreLayoutTasks();
+    void performLayout(RenderObject* rootForThisLayout, bool inSubtreeLayout);
+    void scheduleOrPerformPostLayoutTasks();
+    void performPostLayoutTasks();
 
     virtual void repaintContentRectangle(const IntRect&);
     virtual void contentsResized() OVERRIDE;
@@ -396,6 +397,8 @@
     virtual GraphicsLayer* layerForOverhangAreas() const OVERRIDE;
 #endif
 
+    void sendResizeEventIfNeeded();
+
     void updateScrollableAreaSet();
 
     virtual void notifyPageThatContentAreaWillPaint() const;
@@ -420,7 +423,8 @@
     virtual AXObjectCache* axObjectCache() const;
     void removeFromAXObjectCache();
 
-    static double sCurrentPaintTimeStamp; // used for detecting decoded resource thrash in the cache
+    static double s_currentFrameTimeStamp; // used for detecting decoded resource thrash in the cache
+    static bool s_inPaintContents;
 
     LayoutSize m_size;
     LayoutSize m_margins;
diff --git a/Source/core/page/History.cpp b/Source/core/page/History.cpp
index cbda2a6..ee9109a 100644
--- a/Source/core/page/History.cpp
+++ b/Source/core/page/History.cpp
@@ -56,7 +56,7 @@
         return 0;
     if (!m_frame->page())
         return 0;
-    return m_frame->page()->backForward()->count();
+    return m_frame->page()->backForward().count();
 }
 
 SerializedScriptValue* History::state()
@@ -146,7 +146,8 @@
 
     KURL fullURL = urlForState(urlString);
     if (!fullURL.isValid() || !m_frame->document()->securityOrigin()->canRequest(fullURL)) {
-        es.throwDOMException(SecurityError, "A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
+        // 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() + "'.");
         return;
     }
     m_frame->loader()->updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, title);
diff --git a/Source/core/page/ImageBitmap.cpp b/Source/core/page/ImageBitmap.cpp
index a4301c0..a64ea0d 100644
--- a/Source/core/page/ImageBitmap.cpp
+++ b/Source/core/page/ImageBitmap.cpp
@@ -9,8 +9,10 @@
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/ImageData.h"
+#include "core/html/canvas/CanvasRenderingContext.h"
 #include "core/platform/graphics/BitmapImage.h"
 #include "core/platform/graphics/GraphicsContext.h"
+#include "core/platform/graphics/ImageBuffer.h"
 #include "wtf/RefPtr.h"
 
 using namespace std;
@@ -27,8 +29,12 @@
 
 static inline PassRefPtr<Image> cropImage(Image* image, const IntRect& cropRect)
 {
+    IntRect intersectRect = intersection(IntRect(IntPoint(), image->size()), cropRect);
+    if (!intersectRect.width() || !intersectRect.height())
+        return 0;
+
     SkBitmap cropped;
-    image->nativeImageForCurrentFrame()->bitmap().extractSubset(&cropped, cropRect);
+    image->nativeImageForCurrentFrame()->bitmap().extractSubset(&cropped, intersectRect);
     return BitmapImage::create(NativeImageSkia::create(cropped));
 }
 
@@ -58,12 +64,12 @@
     IntRect srcRect = intersection(cropRect, videoRect);
     IntRect dstRect(IntPoint(), srcRect.size());
 
-    m_buffer = ImageBuffer::create(videoRect.size());
-    GraphicsContext* c = m_buffer->context();
+    OwnPtr<ImageBuffer> buf = ImageBuffer::create(videoRect.size(), 1, UnacceleratedNonPlatformBuffer);
+    GraphicsContext* c = buf->context();
     c->clip(dstRect);
     c->translate(-srcRect.x(), -srcRect.y());
     video->paintCurrentFrameInContext(c, videoRect);
-    m_bitmap = m_buffer->copyImage(DontCopyBackingStore);
+    m_bitmap = buf->copyImage(DontCopyBackingStore);
     m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
 
     ScriptWrappable::init(this);
@@ -74,14 +80,13 @@
     , m_imageElement(0)
     , m_bitmapOffset(IntPoint())
 {
-    IntSize canvasSize = canvas->size();
-    IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), canvasSize));
-    IntRect dstRect(IntPoint(), srcRect.size());
+    CanvasRenderingContext* sourceContext = canvas->renderingContext();
+    if (sourceContext && sourceContext->is3d())
+        sourceContext->paintRenderingResultsToCanvas();
 
-    m_buffer = ImageBuffer::create(canvasSize);
-    m_buffer->context()->drawImageBuffer(canvas->buffer(), dstRect, srcRect);
-    m_bitmap = m_buffer->copyImage(DontCopyBackingStore);
+    IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), canvas->size()));
     m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
+    m_bitmap = cropImage(canvas->buffer()->copyImage(CopyBackingStore).get(), cropRect);
 
     ScriptWrappable::init(this);
 }
@@ -93,11 +98,11 @@
 {
     IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), data->size()));
 
-    m_buffer = ImageBuffer::create(data->size());
+    OwnPtr<ImageBuffer> buf = ImageBuffer::create(data->size(), 1, UnacceleratedNonPlatformBuffer);
     if (srcRect.width() > 0 && srcRect.height() > 0)
-        m_buffer->putByteArray(Unmultiplied, data->data(), data->size(), srcRect, IntPoint(min(0, -cropRect.x()), min(0, -cropRect.y())));
+        buf->putByteArray(Premultiplied, data->data(), data->size(), srcRect, IntPoint(min(0, -cropRect.x()), min(0, -cropRect.y())));
 
-    m_bitmap = m_buffer->copyImage(DontCopyBackingStore);
+    m_bitmap = buf->copyImage(DontCopyBackingStore);
     m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())),  srcRect.size());
 
     ScriptWrappable::init(this);
@@ -124,6 +129,17 @@
     ScriptWrappable::init(this);
 }
 
+ImageBitmap::ImageBitmap(Image* image, const IntRect& cropRect)
+    : m_cropRect(cropRect)
+    , m_imageElement(0)
+{
+    IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), image->size()));
+    m_bitmap = cropImage(image, cropRect);
+    m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())),  srcRect.size());
+
+    ScriptWrappable::init(this);
+}
+
 ImageBitmap::~ImageBitmap()
 {
     if (m_imageElement)
@@ -133,36 +149,37 @@
 PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLImageElement* image, const IntRect& cropRect)
 {
     IntRect normalizedCropRect = normalizeRect(cropRect);
-    RefPtr<ImageBitmap> imageBitmap(adoptRef(new ImageBitmap(image, normalizedCropRect)));
-    return imageBitmap.release();
+    return adoptRef(new ImageBitmap(image, normalizedCropRect));
 }
 
 PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLVideoElement* video, const IntRect& cropRect)
 {
     IntRect normalizedCropRect = normalizeRect(cropRect);
-    RefPtr<ImageBitmap> imageBitmap(adoptRef(new ImageBitmap(video, normalizedCropRect)));
-    return imageBitmap.release();
+    return adoptRef(new ImageBitmap(video, normalizedCropRect));
 }
 
 PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLCanvasElement* canvas, const IntRect& cropRect)
 {
     IntRect normalizedCropRect = normalizeRect(cropRect);
-    RefPtr<ImageBitmap> imageBitmap(adoptRef(new ImageBitmap(canvas, normalizedCropRect)));
-    return imageBitmap.release();
+    return adoptRef(new ImageBitmap(canvas, normalizedCropRect));
 }
 
 PassRefPtr<ImageBitmap> ImageBitmap::create(ImageData* data, const IntRect& cropRect)
 {
     IntRect normalizedCropRect = normalizeRect(cropRect);
-    RefPtr<ImageBitmap> imageBitmap(adoptRef(new ImageBitmap(data, normalizedCropRect)));
-    return imageBitmap.release();
+    return adoptRef(new ImageBitmap(data, normalizedCropRect));
 }
 
 PassRefPtr<ImageBitmap> ImageBitmap::create(ImageBitmap* bitmap, const IntRect& cropRect)
 {
     IntRect normalizedCropRect = normalizeRect(cropRect);
-    RefPtr<ImageBitmap> imageBitmap(adoptRef(new ImageBitmap(bitmap, normalizedCropRect)));
-    return imageBitmap.release();
+    return adoptRef(new ImageBitmap(bitmap, normalizedCropRect));
+}
+
+PassRefPtr<ImageBitmap> ImageBitmap::create(Image* image, const IntRect& cropRect)
+{
+    IntRect normalizedCropRect = normalizeRect(cropRect);
+    return adoptRef(new ImageBitmap(image, normalizedCropRect));
 }
 
 void ImageBitmap::notifyImageSourceChanged()
diff --git a/Source/core/page/ImageBitmap.h b/Source/core/page/ImageBitmap.h
index 9ad5e76..604d87c 100644
--- a/Source/core/page/ImageBitmap.h
+++ b/Source/core/page/ImageBitmap.h
@@ -8,7 +8,6 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageBuffer.h"
 #include "core/platform/graphics/IntRect.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -27,6 +26,7 @@
     static PassRefPtr<ImageBitmap> create(HTMLCanvasElement*, const IntRect&);
     static PassRefPtr<ImageBitmap> create(ImageData*, const IntRect&);
     static PassRefPtr<ImageBitmap> create(ImageBitmap*, const IntRect&);
+    static PassRefPtr<ImageBitmap> create(Image*, const IntRect&);
 
     PassRefPtr<Image> bitmapImage() const;
     PassRefPtr<HTMLImageElement> imageElement() const { return m_imageElement; }
@@ -46,6 +46,7 @@
     ImageBitmap(HTMLCanvasElement*, const IntRect&);
     ImageBitmap(ImageData*, const IntRect&);
     ImageBitmap(ImageBitmap*, const IntRect&);
+    ImageBitmap(Image*, const IntRect&);
 
     // ImageLoaderClient
     virtual void notifyImageSourceChanged();
@@ -55,7 +56,6 @@
     // the image source changes.
     RefPtr<HTMLImageElement> m_imageElement;
     RefPtr<Image> m_bitmap;
-    OwnPtr<ImageBuffer> m_buffer;
 
     IntRect m_bitmapRect; // The rect where the underlying Image should be placed in reference to the ImageBitmap.
     IntRect m_cropRect;
diff --git a/Source/core/page/ImageBitmapFactories.cpp b/Source/core/page/ImageBitmapFactories.cpp
deleted file mode 100644
index a68e94e..0000000
--- a/Source/core/page/ImageBitmapFactories.cpp
+++ /dev/null
@@ -1,223 +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/page/ImageBitmapFactories.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "V8ImageBitmap.h"
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/html/HTMLCanvasElement.h"
-#include "core/html/HTMLImageElement.h"
-#include "core/html/HTMLVideoElement.h"
-#include "core/html/ImageData.h"
-#include "core/html/canvas/CanvasRenderingContext2D.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/ImageBitmap.h"
-
-namespace WebCore {
-
-namespace ImageBitmapFactories {
-
-static LayoutSize sizeFor(HTMLImageElement* image)
-{
-    if (ImageResource* cachedImage = image->cachedImage())
-        return cachedImage->imageSizeForRenderer(image->renderer(), 1.0f); // FIXME: Not sure about this.
-    return IntSize();
-}
-
-static IntSize sizeFor(HTMLVideoElement* video)
-{
-    if (MediaPlayer* player = video->player())
-        return player->naturalSize();
-    return IntSize();
-}
-
-static ScriptObject resolveImageBitmap(PassRefPtr<ImageBitmap> imageBitmap)
-{
-    // Promises must be enabled.
-    ASSERT(RuntimeEnabledFeatures::promiseEnabled());
-
-    RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create();
-    resolver->fulfill(imageBitmap);
-    return resolver->promise();
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, HTMLImageElement* image, ExceptionState& es)
-{
-    LayoutSize s = sizeFor(image);
-    return createImageBitmap(eventTarget, image, 0, 0, s.width(), s.height(), es);
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, HTMLImageElement* image, int sx, int sy, int sw, int sh, ExceptionState& es)
-{
-    if (!image) {
-        es.throwTypeError();
-        return ScriptObject();
-    }
-    if (!image->cachedImage()) {
-        es.throwDOMException(InvalidStateError);
-        return ScriptObject();
-    }
-    if (image->cachedImage()->image()->isSVGImage()) {
-        es.throwDOMException(InvalidStateError);
-        return ScriptObject();
-    }
-    if (!sw || !sh) {
-        es.throwDOMException(IndexSizeError);
-        return ScriptObject();
-    }
-    if (!image->cachedImage()->image()->hasSingleSecurityOrigin()) {
-        es.throwDOMException(SecurityError);
-        return ScriptObject();
-    }
-    if (!image->cachedImage()->passesAccessControlCheck(eventTarget->toDOMWindow()->document()->securityOrigin())
-    && eventTarget->toDOMWindow()->document()->securityOrigin()->taintsCanvas(image->src())) {
-        es.throwDOMException(SecurityError);
-        return ScriptObject();
-    }
-    // FIXME: make ImageBitmap creation asynchronous crbug.com/258082
-    return resolveImageBitmap(ImageBitmap::create(image, IntRect(sx, sy, sw, sh)));
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, HTMLVideoElement* video, ExceptionState& es)
-{
-    IntSize s = sizeFor(video);
-    return createImageBitmap(eventTarget, video, 0, 0, s.width(), s.height(), es);
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, HTMLVideoElement* video, int sx, int sy, int sw, int sh, ExceptionState& es)
-{
-    if (!video) {
-        es.throwTypeError();
-        return ScriptObject();
-    }
-    if (!video->player()) {
-        es.throwDOMException(InvalidStateError);
-        return ScriptObject();
-    }
-    if (video->networkState() == HTMLMediaElement::NETWORK_EMPTY) {
-        es.throwDOMException(InvalidStateError);
-        return ScriptObject();
-    }
-    if (video->player()->readyState() <= MediaPlayer::HaveMetadata) {
-        es.throwDOMException(InvalidStateError);
-        return ScriptObject();
-    }
-    if (!sw || !sh) {
-        es.throwDOMException(IndexSizeError);
-        return ScriptObject();
-    }
-    if (!video->hasSingleSecurityOrigin()) {
-        es.throwDOMException(SecurityError);
-        return ScriptObject();
-    }
-    if (!video->player()->didPassCORSAccessCheck() && eventTarget->toDOMWindow()->document()->securityOrigin()->taintsCanvas(video->currentSrc())) {
-        es.throwDOMException(SecurityError);
-        return ScriptObject();
-    }
-    // FIXME: make ImageBitmap creation asynchronous crbug.com/258082
-    return resolveImageBitmap(ImageBitmap::create(video, IntRect(sx, sy, sw, sh)));
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, CanvasRenderingContext2D* context, ExceptionState& es)
-{
-    return createImageBitmap(eventTarget, context->canvas(), es);
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, CanvasRenderingContext2D* context, int sx, int sy, int sw, int sh, ExceptionState& es)
-{
-    return createImageBitmap(eventTarget, context->canvas(), sx, sy, sw, sh, es);
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, HTMLCanvasElement* canvas, ExceptionState& es)
-{
-    return createImageBitmap(eventTarget, canvas, 0, 0, canvas->width(), canvas->height(), es);
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& es)
-{
-    if (!canvas) {
-        es.throwTypeError();
-        return ScriptObject();
-    }
-    if (!canvas->originClean()) {
-        es.throwDOMException(InvalidStateError);
-        return ScriptObject();
-    }
-    if (!sw || !sh) {
-        es.throwDOMException(IndexSizeError);
-        return ScriptObject();
-    }
-    // FIXME: make ImageBitmap creation asynchronous crbug.com/258082
-    return resolveImageBitmap(ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)));
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, ImageData* data, ExceptionState& es)
-{
-    return createImageBitmap(eventTarget, data, 0, 0, data->width(), data->height(), es);
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, ImageData* data, int sx, int sy, int sw, int sh, ExceptionState& es)
-{
-    if (!data) {
-        es.throwTypeError();
-        return ScriptObject();
-    }
-    if (!sw || !sh) {
-        es.throwDOMException(IndexSizeError);
-        return ScriptObject();
-    }
-    // FIXME: make ImageBitmap creation asynchronous crbug.com/258082
-    return resolveImageBitmap(ImageBitmap::create(data, IntRect(sx, sy, sw, sh)));
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, ImageBitmap* bitmap, ExceptionState& es)
-{
-    return createImageBitmap(eventTarget, bitmap, 0, 0, bitmap->width(), bitmap->height(), es);
-}
-
-ScriptObject createImageBitmap(EventTarget* eventTarget, ImageBitmap* bitmap, int sx, int sy, int sw, int sh, ExceptionState& es)
-{
-    if (!bitmap) {
-        es.throwTypeError();
-        return ScriptObject();
-    }
-    if (!sw || !sh) {
-        es.throwDOMException(IndexSizeError);
-        return ScriptObject();
-    }
-    // FIXME: make ImageBitmap creation asynchronous crbug.com/258082
-    return resolveImageBitmap(ImageBitmap::create(bitmap, IntRect(sx, sy, sw, sh)));
-}
-
-} // namespace ImageBitmapFactories
-} // namespace WebCore
diff --git a/Source/core/page/ImageBitmapFactories.h b/Source/core/page/ImageBitmapFactories.h
deleted file mode 100644
index 05feca4..0000000
--- a/Source/core/page/ImageBitmapFactories.h
+++ /dev/null
@@ -1,65 +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 ImageBitmapFactories_h
-#define ImageBitmapFactories_h
-
-#include "bindings/v8/ScriptPromiseResolver.h"
-
-namespace WebCore {
-
-class CanvasRenderingContext2D;
-class EventTarget;
-class ExceptionState;
-class HTMLCanvasElement;
-class HTMLImageElement;
-class HTMLVideoElement;
-class ImageBitmap;
-class ImageData;
-
-namespace ImageBitmapFactories {
-
-ScriptObject createImageBitmap(EventTarget*, HTMLImageElement*, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, HTMLImageElement*, int sx, int sy, int sw, int sh, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, HTMLVideoElement*, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, HTMLVideoElement*, int sx, int sy, int sw, int sh, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, CanvasRenderingContext2D*, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, CanvasRenderingContext2D*, int sx, int sy, int sw, int sh, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, HTMLCanvasElement*, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, HTMLCanvasElement*, int sx, int sy, int sw, int sh, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, ImageData*, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, ImageData*, int sx, int sy, int sw, int sh, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, ImageBitmap*, ExceptionState&);
-ScriptObject createImageBitmap(EventTarget*, ImageBitmap*, int sx, int sy, int sw, int sh, ExceptionState&);
-
-} // namesapce ImageBitmapFactories
-} // namespace WebCore
-
-#endif // ImageBitmapFactories_h
diff --git a/Source/core/page/ImageBitmapFactories.idl b/Source/core/page/ImageBitmapFactories.idl
deleted file mode 100644
index 65c0dc6..0000000
--- a/Source/core/page/ImageBitmapFactories.idl
+++ /dev/null
@@ -1,48 +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.
- */
-
-[
-    NoInterfaceObject,
-    EnabledAtRuntime=experimentalCanvasFeatures
-] interface ImageBitmapFactories {
-    // FIXME: these methods should return |Promise|. http://crbug.com/266700
-    [RaisesException] any createImageBitmap(HTMLImageElement image);
-    [RaisesException] any createImageBitmap(HTMLImageElement image, long sx, long sy, long sw, long sh);
-    [RaisesException] any createImageBitmap(HTMLVideoElement video);
-    [RaisesException] any createImageBitmap(HTMLVideoElement video, long sx, long sy, long sw, long sh);
-    [RaisesException] any createImageBitmap(CanvasRenderingContext2D context);
-    [RaisesException] any createImageBitmap(CanvasRenderingContext2D context, long sx, long sy, long sw, long sh);
-    [RaisesException] any createImageBitmap(HTMLCanvasElement canvas);
-    [RaisesException] any createImageBitmap(HTMLCanvasElement canvas, long sx, long sy, long sw, long sh);
-    [RaisesException] any createImageBitmap(ImageData data);
-    [RaisesException] any createImageBitmap(ImageData data, long sx, long sy, long sw, long sh);
-    [RaisesException] any createImageBitmap(ImageBitmap bitmap);
-    [RaisesException] any createImageBitmap(ImageBitmap bitmap, long sx, long sy, long sw, long sh);
-};
\ No newline at end of file
diff --git a/Source/core/page/ImageBitmapTest.cpp b/Source/core/page/ImageBitmapTest.cpp
index 91b363b..ef0dbfc 100644
--- a/Source/core/page/ImageBitmapTest.cpp
+++ b/Source/core/page/ImageBitmapTest.cpp
@@ -32,34 +32,66 @@
 #include "core/page/ImageBitmap.h"
 
 #include "core/dom/Document.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/MockImageResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLImageElement.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/html/canvas/CanvasRenderingContext2D.h"
 #include "core/platform/graphics/BitmapImage.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
+#include "core/platform/network/ResourceRequest.h"
+#include "third_party/skia/include/core/SkPixelRef.h"
+#include "wtf/OwnPtr.h"
 
 #include <gtest/gtest.h>
 
 namespace WebCore {
 
 class ImageBitmapTest : public ::testing::Test {
+protected:
+    virtual void SetUp()
+    {
+        m_bitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
+        m_bitmap.allocPixels();
+        m_bitmap.eraseColor(0xFFFFFFFF);
+
+        m_bitmap2.setConfig(SkBitmap::kARGB_8888_Config, 5, 5);
+        m_bitmap2.allocPixels();
+        m_bitmap2.eraseColor(0xAAAAAAAA);
+
+        // Save the global memory cache to restore it upon teardown.
+        m_globalMemoryCache = adoptPtr(memoryCache());
+        // Create the test memory cache instance and hook it in.
+        m_testingMemoryCache = adoptPtr(new MemoryCache());
+        setMemoryCacheForTesting(m_testingMemoryCache.leakPtr());
+    }
+    virtual void TearDown()
+    {
+        // Regain the ownership of testing memory cache, so that it will be
+        // destroyed.
+        m_testingMemoryCache = adoptPtr(memoryCache());
+        // Yield the ownership of the global memory cache back.
+        setMemoryCacheForTesting(m_globalMemoryCache.leakPtr());
+    }
+
+    SkBitmap m_bitmap, m_bitmap2;
+    OwnPtr<MemoryCache> m_testingMemoryCache;
+    OwnPtr<MemoryCache> m_globalMemoryCache;
 };
 
-// Verifies that the cached image held by an ImageBitmap is the same as the
+// Verifies that the image resource held by an ImageBitmap is the same as the
 // one held by the HTMLImageElement.
 TEST_F(ImageBitmapTest, ImageResourceConsistency)
 {
-    SkBitmap bitmap;
-    bitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
-    bitmap.allocPixels();
-    bitmap.eraseColor(0xFFFFFFFF);
-
     RefPtr<HTMLImageElement> imageElement = HTMLImageElement::create(Document::create().get());
-    imageElement->setImageResource(new ImageResource(BitmapImage::create(NativeImageSkia::create(bitmap)).get()));
+    imageElement->setImageResource(new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get()));
 
-    RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageElement.get(), IntRect(0, 0, bitmap.width(), bitmap.height()));
-    RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(bitmap.width() / 2, bitmap.height() / 2, bitmap.width() / 2, bitmap.height() / 2));
-    RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(-bitmap.width() / 2, -bitmap.height() / 2, bitmap.width(), bitmap.height()));
-    RefPtr<ImageBitmap> imageBitmapOutsideCrop = ImageBitmap::create(imageElement.get(), IntRect(-bitmap.width(), -bitmap.height(), bitmap.width(), bitmap.height()));
+    RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageElement.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
+    RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width() / 2, m_bitmap.height() / 2));
+    RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(-m_bitmap.width() / 2, -m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+    RefPtr<ImageBitmap> imageBitmapOutsideCrop = ImageBitmap::create(imageElement.get(), IntRect(-m_bitmap.width(), -m_bitmap.height(), m_bitmap.width(), m_bitmap.height()));
 
     ASSERT_EQ(imageBitmapNoCrop->bitmapImage().get(), imageElement->cachedImage()->image());
     ASSERT_EQ(imageBitmapInteriorCrop->bitmapImage().get(), imageElement->cachedImage()->image());
@@ -69,4 +101,109 @@
     ASSERT_NE(emptyImage.get(), imageElement->cachedImage()->image());
 }
 
+// Verifies that HTMLImageElements are given an elevated CacheLiveResourcePriority when used to construct an ImageBitmap.
+// ImageBitmaps that have crop rects outside of the bounds of the HTMLImageElement do not have elevated CacheLiveResourcePriority.
+TEST_F(ImageBitmapTest, ImageBitmapLiveResourcePriority)
+{
+    RefPtr<HTMLImageElement> imageNoCrop = HTMLImageElement::create(Document::create().get());
+    ResourcePtr<ImageResource> cachedImageNoCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    imageNoCrop->setImageResource(cachedImageNoCrop.get());
+
+    RefPtr<HTMLImageElement> imageInteriorCrop = HTMLImageElement::create(Document::create().get());
+    ResourcePtr<ImageResource> cachedImageInteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    imageInteriorCrop->setImageResource(cachedImageInteriorCrop.get());
+
+    RefPtr<HTMLImageElement> imageExteriorCrop = HTMLImageElement::create(Document::create().get());
+    ResourcePtr<ImageResource> cachedImageExteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    imageExteriorCrop->setImageResource(cachedImageExteriorCrop.get());
+
+    RefPtr<HTMLImageElement> imageOutsideCrop = HTMLImageElement::create(Document::create().get());
+    ResourcePtr<ImageResource> cachedImageOutsideCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    imageOutsideCrop->setImageResource(cachedImageOutsideCrop.get());
+
+    MockImageResourceClient mockClient1, mockClient2, mockClient3, mockClient4;
+    cachedImageNoCrop->addClient(&mockClient1);
+    cachedImageInteriorCrop->addClient(&mockClient2);
+    cachedImageExteriorCrop->addClient(&mockClient3);
+    cachedImageOutsideCrop->addClient(&mockClient4);
+
+    memoryCache()->add(cachedImageNoCrop.get());
+    memoryCache()->add(cachedImageInteriorCrop.get());
+    memoryCache()->add(cachedImageExteriorCrop.get());
+    memoryCache()->add(cachedImageOutsideCrop.get());
+    memoryCache()->insertInLiveDecodedResourcesList(cachedImageNoCrop.get());
+    memoryCache()->insertInLiveDecodedResourcesList(cachedImageInteriorCrop.get());
+    memoryCache()->insertInLiveDecodedResourcesList(cachedImageExteriorCrop.get());
+    memoryCache()->insertInLiveDecodedResourcesList(cachedImageOutsideCrop.get());
+
+    // HTMLImageElements should default to CacheLiveResourcePriorityLow.
+    ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+    ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+    ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+    ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+
+    RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageInteriorCrop.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+    {
+        RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageNoCrop.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
+        RefPtr<ImageBitmap> imageBitmapInteriorCrop2 = ImageBitmap::create(imageInteriorCrop.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+        RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageExteriorCrop.get(), IntRect(-m_bitmap.width() / 2, -m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+        RefPtr<ImageBitmap> imageBitmapOutsideCrop = ImageBitmap::create(imageOutsideCrop.get(), IntRect(-m_bitmap.width(), -m_bitmap.height(), m_bitmap.width(), m_bitmap.height()));
+
+        // Images that are referenced by ImageBitmaps have CacheLiveResourcePriorityHigh.
+        ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+        ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+        ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+
+        // ImageBitmaps that do not contain any of the source image do not elevate CacheLiveResourcePriority.
+        ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+    }
+
+    // CacheLiveResourcePriroity should return to CacheLiveResourcePriorityLow when no ImageBitmaps reference the image.
+    ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+    ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+    ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+
+    // There is still an ImageBitmap that references this image.
+    ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+}
+
+// Verifies that ImageBitmaps constructed from HTMLImageElements hold a reference to the original Image if the HTMLImageElement src is changed.
+TEST_F(ImageBitmapTest, ImageBitmapSourceChanged)
+{
+    RefPtr<HTMLImageElement> image = HTMLImageElement::create(Document::create().get());
+    ResourcePtr<ImageResource> originalImageResource = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    image->setImageResource(originalImageResource.get());
+
+    RefPtr<ImageBitmap> imageBitmap = ImageBitmap::create(image.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
+    ASSERT_EQ(imageBitmap->bitmapImage().get(), originalImageResource->image());
+
+    ResourcePtr<ImageResource> newImageResource = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap2)).get());
+    image->setImageResource(newImageResource.get());
+
+    // The ImageBitmap should contain the same data as the original cached image but should no longer hold a reference.
+    ASSERT_NE(imageBitmap->bitmapImage().get(), originalImageResource->image());
+    ASSERT_EQ(imageBitmap->bitmapImage()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels(),
+        originalImageResource->image()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels());
+
+    ASSERT_NE(imageBitmap->bitmapImage().get(), newImageResource->image());
+    ASSERT_NE(imageBitmap->bitmapImage()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels(),
+        newImageResource->image()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels());
+}
+
+// Verifies that ImageBitmaps constructed from ImageBitmaps hold onto their own Image.
+TEST_F(ImageBitmapTest, ImageResourceLifetime)
+{
+    RefPtr<HTMLCanvasElement> canvasElement = HTMLCanvasElement::create(Document::create().get());
+    canvasElement->setHeight(40);
+    canvasElement->setWidth(40);
+    RefPtr<ImageBitmap> imageBitmapDerived;
+    {
+        RefPtr<ImageBitmap> imageBitmapFromCanvas = ImageBitmap::create(canvasElement.get(), IntRect(0, 0, canvasElement->width(), canvasElement->height()));
+        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);
+}
+
 } // namespace
diff --git a/Source/core/page/Location.cpp b/Source/core/page/Location.cpp
index a7aaac0..4937756 100644
--- a/Source/core/page/Location.cpp
+++ b/Source/core/page/Location.cpp
@@ -29,6 +29,7 @@
 #include "config.h"
 #include "core/page/Location.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
@@ -158,7 +159,7 @@
         return;
     KURL url = m_frame->document()->url();
     if (!url.setProtocol(protocol)) {
-        es.throwDOMException(SyntaxError);
+        es.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("protocol", "Location", "'" + protocol + "' is an invalid protocol."));
         return;
     }
     setLocation(url.string(), activeWindow, firstWindow);
diff --git a/Source/core/page/Navigator.cpp b/Source/core/page/Navigator.cpp
index 76020db..646468b 100644
--- a/Source/core/page/Navigator.cpp
+++ b/Source/core/page/Navigator.cpp
@@ -28,12 +28,25 @@
 #include "core/loader/CookieJar.h"
 #include "core/loader/FrameLoader.h"
 #include "core/page/Frame.h"
+#include "core/page/NavigatorID.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/platform/Language.h"
 #include "core/plugins/DOMMimeTypeArray.h"
 #include "core/plugins/DOMPluginArray.h"
 
+#ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
+#define WEBCORE_NAVIGATOR_PRODUCT_SUB "20030107"
+#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
+
+#ifndef WEBCORE_NAVIGATOR_VENDOR
+#define WEBCORE_NAVIGATOR_VENDOR "Apple Computer, Inc."
+#endif // ifndef WEBCORE_NAVIGATOR_VENDOR
+
+#ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
+#define WEBCORE_NAVIGATOR_VENDOR_SUB ""
+#endif // ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
+
 namespace WebCore {
 
 Navigator::Navigator(Frame* frame)
@@ -67,7 +80,7 @@
 {
     if (!m_frame)
         return String();
-    String appVersion = NavigatorBase::appVersion();
+    String appVersion = NavigatorID::appVersion(this);
     if (shouldHideFourDot(m_frame))
         appVersion.replace("4.", "4_");
     return appVersion;
@@ -78,6 +91,21 @@
     return defaultLanguage();
 }
 
+String Navigator::productSub() const
+{
+    return WEBCORE_NAVIGATOR_PRODUCT_SUB;
+}
+
+String Navigator::vendor() const
+{
+    return WEBCORE_NAVIGATOR_VENDOR;
+}
+
+String Navigator::vendorSub() const
+{
+    return WEBCORE_NAVIGATOR_VENDOR_SUB;
+}
+
 String Navigator::userAgent() const
 {
     if (!m_frame)
@@ -110,7 +138,7 @@
     if (!m_frame)
         return false;
 
-    if (m_frame->page() && !m_frame->page()->settings()->cookieEnabled())
+    if (m_frame->page() && !m_frame->page()->settings().cookieEnabled())
         return false;
 
     return cookiesEnabled(m_frame->document());
diff --git a/Source/core/page/Navigator.h b/Source/core/page/Navigator.h
index 0d279bd..3f417d7 100644
--- a/Source/core/page/Navigator.h
+++ b/Source/core/page/Navigator.h
@@ -50,7 +50,11 @@
     bool cookieEnabled() const;
     bool javaEnabled() const;
 
-    virtual String userAgent() const;
+    String productSub() const;
+    String vendor() const;
+    String vendorSub() const;
+
+    virtual String userAgent() const OVERRIDE;
 
     // Relinquishes the storage lock, if one exists.
     void getStorageUpdates();
diff --git a/Source/core/page/Navigator.idl b/Source/core/page/Navigator.idl
index 0c3e09d..79f322d 100644
--- a/Source/core/page/Navigator.idl
+++ b/Source/core/page/Navigator.idl
@@ -19,22 +19,20 @@
 
 interface Navigator {
     readonly attribute DOMString appCodeName;
-    readonly attribute DOMString appName;
-    readonly attribute DOMString appVersion;
     readonly attribute DOMString language;
-    readonly attribute DOMString userAgent;
-    readonly attribute DOMString platform;
     readonly attribute PluginArray plugins;
     readonly attribute MimeTypeArray mimeTypes;
     readonly attribute DOMString product;
-    readonly attribute DOMString productSub;
-    readonly attribute DOMString vendor;
-    readonly attribute DOMString vendorSub;
     readonly attribute boolean cookieEnabled;
     boolean javaEnabled();
 
-    readonly attribute boolean onLine;
-
     void getStorageUpdates(); // FIXME: Remove this method or rename to yieldForStorageUpdates.
+
+    // Non-standard.
+    [MeasureAs=NavigatorProductSub] readonly attribute DOMString productSub;
+    [MeasureAs=NavigatorVendor] readonly attribute DOMString vendor;
+    [MeasureAs=NavigatorVendorSub] readonly attribute DOMString vendorSub;
 };
 
+Navigator implements NavigatorID;
+Navigator implements NavigatorOnLine;
diff --git a/Source/core/page/NavigatorBase.cpp b/Source/core/page/NavigatorBase.cpp
index dc89ad5..e03c733 100644
--- a/Source/core/page/NavigatorBase.cpp
+++ b/Source/core/page/NavigatorBase.cpp
@@ -27,75 +27,18 @@
 #include "config.h"
 #include "core/page/NavigatorBase.h"
 
-#include "core/platform/network/NetworkStateNotifier.h"
-#include "wtf/CPU.h"
 #include "wtf/text/WTFString.h"
 
-#if OS(LINUX)
-#include "sys/utsname.h"
-#include "wtf/StdLibExtras.h"
-#endif
-
-#ifndef WEBCORE_NAVIGATOR_PLATFORM
-#if OS(DARWIN) && (CPU(PPC) || CPU(PPC64))
-#define WEBCORE_NAVIGATOR_PLATFORM "MacPPC"
-#elif OS(DARWIN) && (CPU(X86) || CPU(X86_64))
-#define WEBCORE_NAVIGATOR_PLATFORM "MacIntel"
-#elif OS(WINDOWS)
-#define WEBCORE_NAVIGATOR_PLATFORM "Win32"
-#else
-#define WEBCORE_NAVIGATOR_PLATFORM ""
-#endif
-#endif // ifndef WEBCORE_NAVIGATOR_PLATFORM
-
 #ifndef WEBCORE_NAVIGATOR_PRODUCT
 #define WEBCORE_NAVIGATOR_PRODUCT "Gecko"
 #endif // ifndef WEBCORE_NAVIGATOR_PRODUCT
 
-#ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
-#define WEBCORE_NAVIGATOR_PRODUCT_SUB "20030107"
-#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
-
-#ifndef WEBCORE_NAVIGATOR_VENDOR
-#define WEBCORE_NAVIGATOR_VENDOR "Apple Computer, Inc."
-#endif // ifndef WEBCORE_NAVIGATOR_VENDOR
-
-#ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
-#define WEBCORE_NAVIGATOR_VENDOR_SUB ""
-#endif // ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
-
-
 namespace WebCore {
 
 NavigatorBase::~NavigatorBase()
 {
 }
 
-String NavigatorBase::appName() const
-{
-    return "Netscape";
-}
-
-String NavigatorBase::appVersion() const
-{
-    // Version is everything in the user agent string past the "Mozilla/" prefix.
-    const String& agent = userAgent();
-    return agent.substring(agent.find('/') + 1);
-}
-
-String NavigatorBase::platform() const
-{
-#if OS(LINUX)
-    if (!String(WEBCORE_NAVIGATOR_PLATFORM).isEmpty())
-        return WEBCORE_NAVIGATOR_PLATFORM;
-    struct utsname osname;
-    DEFINE_STATIC_LOCAL(String, platformName, (uname(&osname) >= 0 ? String(osname.sysname) + String(" ") + String(osname.machine) : emptyString()));
-    return platformName;
-#else
-    return WEBCORE_NAVIGATOR_PLATFORM;
-#endif
-}
-
 String NavigatorBase::appCodeName() const
 {
     return "Mozilla";
@@ -106,24 +49,4 @@
     return WEBCORE_NAVIGATOR_PRODUCT;
 }
 
-String NavigatorBase::productSub() const
-{
-    return WEBCORE_NAVIGATOR_PRODUCT_SUB;
-}
-
-String NavigatorBase::vendor() const
-{
-    return WEBCORE_NAVIGATOR_VENDOR;
-}
-
-String NavigatorBase::vendorSub() const
-{
-    return WEBCORE_NAVIGATOR_VENDOR_SUB;
-}
-
-bool NavigatorBase::onLine() const
-{
-    return networkStateNotifier().onLine();
-}
-
 } // namespace WebCore
diff --git a/Source/core/page/NavigatorBase.h b/Source/core/page/NavigatorBase.h
index dcc9d06..cb6c81f 100644
--- a/Source/core/page/NavigatorBase.h
+++ b/Source/core/page/NavigatorBase.h
@@ -32,18 +32,12 @@
 
     class NavigatorBase {
     public:
-        String appName() const;
-        String appVersion() const;
         virtual String userAgent() const = 0;
-        String platform() const;
 
+        // FIXME: The following should be moved to NavigatorID and
+        // exposed on WorkerNavigator as well.
         String appCodeName() const;
         String product() const;
-        String productSub() const;
-        String vendor() const;
-        String vendorSub() const;
-
-        bool onLine() const;
 
     protected:
         virtual ~NavigatorBase();
diff --git a/Source/core/page/NavigatorID.cpp b/Source/core/page/NavigatorID.cpp
new file mode 100644
index 0000000..593d59e
--- /dev/null
+++ b/Source/core/page/NavigatorID.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2008 Apple 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
+ * 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 "NavigatorID.h"
+
+#include "core/page/NavigatorBase.h"
+#include "wtf/CPU.h"
+
+#if OS(LINUX)
+#include "sys/utsname.h"
+#include "wtf/StdLibExtras.h"
+#endif
+
+#ifndef WEBCORE_NAVIGATOR_PLATFORM
+#if OS(DARWIN) && (CPU(PPC) || CPU(PPC64))
+#define WEBCORE_NAVIGATOR_PLATFORM "MacPPC"
+#elif OS(DARWIN) && (CPU(X86) || CPU(X86_64))
+#define WEBCORE_NAVIGATOR_PLATFORM "MacIntel"
+#elif OS(WINDOWS)
+#define WEBCORE_NAVIGATOR_PLATFORM "Win32"
+#else
+#define WEBCORE_NAVIGATOR_PLATFORM ""
+#endif
+#endif // ifndef WEBCORE_NAVIGATOR_PLATFORM
+
+namespace WebCore {
+
+String NavigatorID::appName(const NavigatorBase*)
+{
+    return "Netscape";
+}
+
+String NavigatorID::appVersion(const NavigatorBase* navigator)
+{
+    // Version is everything in the user agent string past the "Mozilla/" prefix.
+    const String& agent = navigator->userAgent();
+    return agent.substring(agent.find('/') + 1);
+}
+
+String NavigatorID::userAgent(const NavigatorBase* navigator)
+{
+    return navigator->userAgent();
+}
+
+String NavigatorID::platform(const NavigatorBase*)
+{
+#if OS(LINUX)
+    if (!String(WEBCORE_NAVIGATOR_PLATFORM).isEmpty())
+        return WEBCORE_NAVIGATOR_PLATFORM;
+    struct utsname osname;
+    DEFINE_STATIC_LOCAL(String, platformName, (uname(&osname) >= 0 ? String(osname.sysname) + String(" ") + String(osname.machine) : emptyString()));
+    return platformName;
+#else
+    return WEBCORE_NAVIGATOR_PLATFORM;
+#endif
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/page/NavigatorID.h
similarity index 64%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/page/NavigatorID.h
index 133dab0..c235fe0 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/page/NavigatorID.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 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,26 +28,23 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#ifndef NavigatorID_h
+#define NavigatorID_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
-public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
+class NavigatorBase;
 
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+class NavigatorID {
+public:
+    static String appName(const NavigatorBase*);
+    static String appVersion(const NavigatorBase*);
+    static String userAgent(const NavigatorBase*);
+    static String platform(const NavigatorBase*);
 };
 
 } // namespace WebCore
 
-#endif
+#endif // NavigatorID_h
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/page/NavigatorID.idl
similarity index 62%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/page/NavigatorID.idl
index 133dab0..a0333ba 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/page/NavigatorID.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 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,26 +28,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
-
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
-
-namespace WebCore {
-
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
-public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
-
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+[
+    NoInterfaceObject
+] interface NavigatorID {
+    readonly attribute DOMString appName;
+    readonly attribute DOMString appVersion;
+    readonly attribute DOMString platform;
+    readonly attribute DOMString userAgent;
 };
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/page/NavigatorOnLine.h
similarity index 63%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/page/NavigatorOnLine.h
index 133dab0..934cecb 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/page/NavigatorOnLine.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 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,26 +28,21 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#ifndef NavigatorOnLine_h
+#define NavigatorOnLine_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "core/platform/network/NetworkStateNotifier.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
+class NavigatorOnLine {
 public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
-
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+    static bool onLine(void*)
+    {
+        return networkStateNotifier().onLine();
+    }
 };
 
-} // namespace WebCore
+}
 
-#endif
+#endif // NavigatorOnLine_h
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/page/NavigatorOnLine.idl
similarity index 62%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/page/NavigatorOnLine.idl
index 133dab0..db4b08c 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/page/NavigatorOnLine.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 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,26 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
-
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
-
-namespace WebCore {
-
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
-public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
-
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+[
+    NoInterfaceObject
+] interface NavigatorOnLine {
+    readonly attribute boolean onLine;
 };
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/page/Page.cpp b/Source/core/page/Page.cpp
index 0631555..1e13908 100644
--- a/Source/core/page/Page.cpp
+++ b/Source/core/page/Page.cpp
@@ -47,6 +47,7 @@
 #include "core/page/PageLifecycleNotifier.h"
 #include "core/page/PointerLockController.h"
 #include "core/page/Settings.h"
+#include "core/page/ValidationMessageClient.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/network/NetworkStateNotifier.h"
 #include "core/plugins/PluginData.h"
@@ -156,8 +157,6 @@
     if (m_scrollingCoordinator)
         m_scrollingCoordinator->pageDestroyed();
 
-    backForward()->close();
-
 #ifndef NDEBUG
     pageCounter.decrement();
 #endif
@@ -262,6 +261,14 @@
     m_mainFrame = mainFrame;
 }
 
+void Page::documentDetached(Document* document)
+{
+    m_pointerLockController->documentDetached(document);
+    m_contextMenuController->documentDetached(document);
+    if (m_validationMessageClient)
+        m_validationMessageClient->documentDetached(*document);
+}
+
 bool Page::openedByDOM() const
 {
     return m_openedByDOM;
@@ -324,7 +331,7 @@
 void Page::setNeedsRecalcStyleInAllFrames()
 {
     for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
-        frame->document()->styleResolverChanged(DeferRecalcStyle);
+        frame->document()->styleResolverChanged(RecalcStyleDeferred);
 }
 
 void Page::refreshPlugins(bool reload)
@@ -722,6 +729,8 @@
 void Page::didCommitLoad(Frame* frame)
 {
     lifecycleNotifier()->notifyDidCommitLoad(frame);
+    if (m_mainFrame == frame)
+        useCounter().didCommitLoad();
 }
 
 PageLifecycleNotifier* Page::lifecycleNotifier()
diff --git a/Source/core/page/Page.h b/Source/core/page/Page.h
index 2b85d1b..d2d4039 100644
--- a/Source/core/page/Page.h
+++ b/Source/core/page/Page.h
@@ -113,11 +113,13 @@
     static void refreshPlugins(bool reload);
     PluginData* pluginData() const;
 
-    EditorClient* editorClient() const { return m_editorClient; }
+    EditorClient& editorClient() const { return *m_editorClient; }
 
     void setMainFrame(PassRefPtr<Frame>);
     Frame* mainFrame() const { return m_mainFrame.get(); }
 
+    void documentDetached(Document*);
+
     bool openedByDOM() const;
     void setOpenedByDOM();
 
@@ -143,9 +145,9 @@
     DragCaretController& dragCaretController() const { return *m_dragCaretController; }
     DragController& dragController() const { return *m_dragController; }
     FocusController& focusController() const { return *m_focusController; }
-    ContextMenuController* contextMenuController() const { return m_contextMenuController.get(); }
-    InspectorController* inspectorController() const { return m_inspectorController.get(); }
-    PointerLockController* pointerLockController() const { return m_pointerLockController.get(); }
+    ContextMenuController& contextMenuController() const { return *m_contextMenuController; }
+    InspectorController& inspectorController() const { return *m_inspectorController; }
+    PointerLockController& pointerLockController() const { return *m_pointerLockController; }
     ValidationMessageClient* validationMessageClient() const { return m_validationMessageClient; }
     void setValidationMessageClient(ValidationMessageClient* client) { m_validationMessageClient = client; }
 
@@ -167,11 +169,11 @@
     String mainThreadScrollingReasonsAsText();
     PassRefPtr<ClientRectList> nonFastScrollableRects(const Frame*);
 
-    Settings* settings() const { return m_settings.get(); }
-    ProgressTracker* progress() const { return m_progress.get(); }
-    BackForwardController* backForward() const { return m_backForwardController.get(); }
+    Settings& settings() const { return *m_settings; }
+    ProgressTracker& progress() const { return *m_progress; }
+    BackForwardController& backForward() const { return *m_backForwardController; }
 
-    UseCounter* useCounter() { return &m_UseCounter; }
+    UseCounter& useCounter() { return m_useCounter; }
 
     void setTabKeyCyclesThroughElements(bool b) { m_tabKeyCyclesThroughElements = b; }
     bool tabKeyCyclesThroughElements() const { return m_tabKeyCyclesThroughElements; }
@@ -230,7 +232,7 @@
     bool isPainting() const { return m_isPainting; }
 #endif
 
-    PageConsole* console() { return m_console.get(); }
+    PageConsole& console() { return *m_console; }
 
     double timerAlignmentInterval() const;
 
@@ -261,30 +263,30 @@
 
     virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
 
-    OwnPtr<AutoscrollController> m_autoscrollController;
-    OwnPtr<Chrome> m_chrome;
+    const OwnPtr<AutoscrollController> m_autoscrollController;
+    const OwnPtr<Chrome> m_chrome;
     const OwnPtr<DragCaretController> m_dragCaretController;
     const OwnPtr<DragController> m_dragController;
-    OwnPtr<FocusController> m_focusController;
-    OwnPtr<ContextMenuController> m_contextMenuController;
-    OwnPtr<InspectorController> m_inspectorController;
-    OwnPtr<PointerLockController> m_pointerLockController;
+    const OwnPtr<FocusController> m_focusController;
+    const OwnPtr<ContextMenuController> m_contextMenuController;
+    const OwnPtr<InspectorController> m_inspectorController;
+    const OwnPtr<PointerLockController> m_pointerLockController;
     RefPtr<ScrollingCoordinator> m_scrollingCoordinator;
 
-    OwnPtr<Settings> m_settings;
-    OwnPtr<ProgressTracker> m_progress;
+    const OwnPtr<Settings> m_settings;
+    const OwnPtr<ProgressTracker> m_progress;
 
-    OwnPtr<BackForwardController> m_backForwardController;
+    const OwnPtr<BackForwardController> m_backForwardController;
     RefPtr<Frame> m_mainFrame;
 
     mutable RefPtr<PluginData> m_pluginData;
 
-    RefPtr<RenderTheme> m_theme;
+    const RefPtr<RenderTheme> m_theme;
 
-    EditorClient* m_editorClient;
+    EditorClient* const m_editorClient;
     ValidationMessageClient* m_validationMessageClient;
 
-    UseCounter m_UseCounter;
+    UseCounter m_useCounter;
 
     int m_subframeCount;
     bool m_openedByDOM;
diff --git a/Source/core/page/PageConsole.cpp b/Source/core/page/PageConsole.cpp
index 07bbb25..c79ae49 100644
--- a/Source/core/page/PageConsole.cpp
+++ b/Source/core/page/PageConsole.cpp
@@ -55,18 +55,9 @@
 
 PageConsole::~PageConsole() { }
 
-void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier, Document* document)
+void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message)
 {
-    String url;
-    if (document)
-        url = document->url().string();
-    unsigned line = 0;
-    if (document && document->parsing() && !document->isInDocumentWrite() && document->scriptableDocumentParser()) {
-        ScriptableDocumentParser* parser = document->scriptableDocumentParser();
-        if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
-            line = parser->lineNumber().oneBasedInt();
-    }
-    addMessage(source, level, message, url, line, 0, 0, 0, requestIdentifier);
+    addMessage(source, level, message, String(), 0, 0, 0, 0, 0);
 }
 
 void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack)
@@ -91,7 +82,7 @@
     if (source == CSSMessageSource)
         return;
 
-    page->chrome().client()->addMessageToConsole(source, level, message, lineNumber, url);
+    page->chrome().client().addMessageToConsole(source, level, message, lineNumber, url);
 }
 
 // static
diff --git a/Source/core/page/PageConsole.h b/Source/core/page/PageConsole.h
index 622ecf1..c4bccff 100644
--- a/Source/core/page/PageConsole.h
+++ b/Source/core/page/PageConsole.h
@@ -47,9 +47,9 @@
     static PassOwnPtr<PageConsole> create(Page* page) { return adoptPtr(new PageConsole(page)); }
     virtual ~PageConsole();
 
+    void addMessage(MessageSource, MessageLevel, const String& message);
     void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber = 0, PassRefPtr<ScriptCallStack> = 0, ScriptState* = 0, unsigned long requestIdentifier = 0);
     void addMessage(MessageSource, MessageLevel, const String& message, PassRefPtr<ScriptCallStack>);
-    void addMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0, Document* = 0);
 
     static void mute();
     static void unmute();
diff --git a/Source/core/page/PageScaleConstraintsSet.cpp b/Source/core/page/PageScaleConstraintsSet.cpp
index 294a9be..e0d185b 100644
--- a/Source/core/page/PageScaleConstraintsSet.cpp
+++ b/Source/core/page/PageScaleConstraintsSet.cpp
@@ -51,7 +51,7 @@
 
 void PageScaleConstraintsSet::updatePageDefinedConstraints(const ViewportArguments& arguments, IntSize viewSize, int layoutFallbackWidth)
 {
-    m_pageDefinedConstraints = arguments.resolve(viewSize, viewSize, layoutFallbackWidth);
+    m_pageDefinedConstraints = arguments.resolve(viewSize, layoutFallbackWidth);
 
     m_constraintsDirty = true;
 }
diff --git a/Source/core/page/PageSerializer.cpp b/Source/core/page/PageSerializer.cpp
index 16ed102..7c61b39 100644
--- a/Source/core/page/PageSerializer.cpp
+++ b/Source/core/page/PageSerializer.cpp
@@ -42,13 +42,13 @@
 #include "core/dom/Element.h"
 #include "core/dom/Text.h"
 #include "core/editing/MarkupAccumulator.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/html/parser/HTMLMetaCharsetParser.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/SerializedResource.h"
@@ -150,7 +150,7 @@
     if (!element->isFrameOwnerElement())
         return;
 
-    HTMLFrameOwnerElement* frameOwner = toFrameOwnerElement(element);
+    HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element);
     Frame* frame = frameOwner->contentFrame();
     if (!frame)
         return;
diff --git a/Source/core/page/PerformanceMeasure.h b/Source/core/page/PerformanceMeasure.h
index 57a8438..9708d33 100644
--- a/Source/core/page/PerformanceMeasure.h
+++ b/Source/core/page/PerformanceMeasure.h
@@ -34,12 +34,12 @@
 
 class PerformanceMeasure : public PerformanceEntry {
 public:
-    static PassRefPtr<PerformanceMeasure> create(const String& name, double startTime, double duration) { return adoptRef(new PerformanceMeasure(name, startTime, duration)); }
+    static PassRefPtr<PerformanceMeasure> create(const String& name, double startTime, double endTime) { return adoptRef(new PerformanceMeasure(name, startTime, endTime)); }
 
     virtual bool isMeasure() { return true; }
 
 private:
-    PerformanceMeasure(const String& name, double startTime, double duration) : PerformanceEntry(name, "measure", startTime, duration)
+    PerformanceMeasure(const String& name, double startTime, double endTime) : PerformanceEntry(name, "measure", startTime, endTime)
     {
         ScriptWrappable::init(this);
     }
diff --git a/Source/core/page/PerformanceUserTiming.cpp b/Source/core/page/PerformanceUserTiming.cpp
index a365c6a..568fa35 100644
--- a/Source/core/page/PerformanceUserTiming.cpp
+++ b/Source/core/page/PerformanceUserTiming.cpp
@@ -31,6 +31,7 @@
 #include "core/page/Performance.h"
 #include "core/page/PerformanceMark.h"
 #include "core/page/PerformanceMeasure.h"
+#include "core/platform/HistogramSupport.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -107,6 +108,7 @@
 
     double startTime = m_performance->now();
     insertPerformanceEntry(m_marksMap, PerformanceMark::create(markName, startTime));
+    HistogramSupport::histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
 }
 
 void UserTiming::clearMarks(const String& markName)
@@ -154,6 +156,8 @@
     }
 
     insertPerformanceEntry(m_measuresMap, PerformanceMeasure::create(measureName, startTime, endTime));
+    if (endTime >= startTime)
+        HistogramSupport::histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
 }
 
 void UserTiming::clearMeasures(const String& measureName)
diff --git a/Source/core/page/PointerLockController.cpp b/Source/core/page/PointerLockController.cpp
index 5eb25ba..26c4c9d 100644
--- a/Source/core/page/PointerLockController.cpp
+++ b/Source/core/page/PointerLockController.cpp
@@ -65,7 +65,7 @@
         }
         enqueueEvent(eventNames().webkitpointerlockchangeEvent, target);
         m_element = target;
-    } else if (m_page->chrome().client()->requestPointerLock()) {
+    } else if (m_page->chrome().client().requestPointerLock()) {
         m_lockPending = true;
         m_element = target;
     } else {
@@ -75,7 +75,7 @@
 
 void PointerLockController::requestPointerUnlock()
 {
-    return m_page->chrome().client()->requestPointerUnlock();
+    return m_page->chrome().client().requestPointerUnlock();
 }
 
 void PointerLockController::elementRemoved(Element* element)
diff --git a/Source/core/page/RuntimeCSSEnabled.cpp b/Source/core/page/RuntimeCSSEnabled.cpp
index 7259c13..3906efa 100644
--- a/Source/core/page/RuntimeCSSEnabled.cpp
+++ b/Source/core/page/RuntimeCSSEnabled.cpp
@@ -56,13 +56,16 @@
     setCSSPropertiesEnabled(regionProperites, WTF_ARRAY_LENGTH(regionProperites), RuntimeEnabledFeatures::cssRegionsEnabled());
     CSSPropertyID exclusionProperties[] = {
         CSSPropertyWebkitWrapFlow,
+        CSSPropertyWebkitWrapThrough,
+    };
+    setCSSPropertiesEnabled(exclusionProperties, WTF_ARRAY_LENGTH(exclusionProperties), RuntimeEnabledFeatures::cssExclusionsEnabled());
+    CSSPropertyID shapeProperties[] = {
         CSSPropertyWebkitShapeMargin,
         CSSPropertyWebkitShapePadding,
-        CSSPropertyWebkitWrapThrough,
         CSSPropertyWebkitShapeInside,
         CSSPropertyWebkitShapeOutside,
     };
-    setCSSPropertiesEnabled(exclusionProperties, WTF_ARRAY_LENGTH(exclusionProperties), RuntimeEnabledFeatures::cssExclusionsEnabled());
+    setCSSPropertiesEnabled(shapeProperties, WTF_ARRAY_LENGTH(shapeProperties), RuntimeEnabledFeatures::cssShapesEnabled());
     CSSPropertyID css3TextDecorationProperties[] = {
         CSSPropertyTextDecorationColor,
         CSSPropertyTextDecorationLine,
@@ -92,7 +95,9 @@
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyBackgroundBlendMode, RuntimeEnabledFeatures::cssCompositingEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMixBlendMode, RuntimeEnabledFeatures::cssCompositingEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyTouchAction, RuntimeEnabledFeatures::cssTouchActionEnabled());
+    RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyPaintOrder, RuntimeEnabledFeatures::svgPaintOrderEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyVariable, RuntimeEnabledFeatures::cssVariablesEnabled());
+    RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyObjectFit, RuntimeEnabledFeatures::objectFitPositionEnabled());
 }
 
 static BoolVector& propertySwitches()
@@ -116,6 +121,11 @@
 
 bool RuntimeCSSEnabled::isCSSPropertyEnabled(CSSPropertyID propertyId)
 {
+    // Internal properties shouldn't be exposed to the web
+    // so they are considered to be always disabled.
+    if (isInternalProperty(propertyId))
+        return false;
+
     return propertySwitches()[indexForProperty(propertyId)];
 }
 
diff --git a/Source/core/page/RuntimeEnabledFeatures.in b/Source/core/page/RuntimeEnabledFeatures.in
index 85faaec..945e6f6 100644
--- a/Source/core/page/RuntimeEnabledFeatures.in
+++ b/Source/core/page/RuntimeEnabledFeatures.in
@@ -19,21 +19,26 @@
 ApplicationCache status=stable
 AuthorShadowDOMForAnyElement
 Crypto status=test
+CSSAnimationUnprefixed status=experimental
 CSSCompositing status=experimental
 CSSExclusions status=experimental
 CSSGridLayout status=experimental
 CSSRegions status=experimental
+CSSShapes status=experimental, writeable=True
 CSSTouchAction status=test
 CSSVariables status=experimental
 CSS3Text status=experimental
 CSS3TextDecorations status=experimental
-CustomDOMElements status=experimental
+CustomElements status=experimental
 Database status=stable
 DataListElement status=stable
 DeviceMotion status=test
 DeviceOrientation status=stable
+DevicePixelRatioIncludesZoom status=experimental
 DialogElement status=experimental
 DirectoryUpload status=stable
+// FIXME: Remove this separate feature when CustomElements are always enabled
+EmbedderCustomElements
 EncodingAPI status=experimental
 EncryptedMedia status=experimental
 EncryptedMediaAnyVersion status=stable
@@ -53,13 +58,13 @@
 InputTypeColor status=stable
 InputTypeWeek status=stable
 LangAttributeAwareFormControlUI
-LazyLayout
 LegacyEncryptedMedia status=stable
 LocalStorage status=stable
 Media status=stable
 MediaSource status=experimental
 MediaStream status=stable
 Notifications status=stable
+ObjectFitPosition status=experimental
 PagePopup status=stable
 ParseSVGAsHTML
 PathOpsSVGClipping
@@ -79,6 +84,7 @@
 SpeechSynthesis status=experimental
 Stream status=experimental
 StyleScoped status=experimental
+SVGPaintOrder status=experimental
 Touch status=stable
 UserSelectAll status=experimental
 Vibration status=experimental
diff --git a/Source/core/page/Settings.cpp b/Source/core/page/Settings.cpp
index 68a69d3..148aacf 100644
--- a/Source/core/page/Settings.cpp
+++ b/Source/core/page/Settings.cpp
@@ -28,8 +28,8 @@
 
 #include <limits>
 #include "core/dom/Document.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Chrome.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
@@ -44,8 +44,8 @@
 static void setImageLoadingSettings(Page* page)
 {
     for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
-        frame->document()->fetcher()->setImagesEnabled(page->settings()->areImagesEnabled());
-        frame->document()->fetcher()->setAutoLoadImages(page->settings()->loadsImagesAutomatically());
+        frame->document()->fetcher()->setImagesEnabled(page->settings().areImagesEnabled());
+        frame->document()->fetcher()->setAutoLoadImages(page->settings().loadsImagesAutomatically());
     }
 }
 
@@ -137,7 +137,9 @@
     , m_cssStickyPositionEnabled(true)
     , m_dnsPrefetchingEnabled(false)
     , m_touchEventEmulationEnabled(false)
+    , m_viewportEnabled(false)
     , m_setImageLoadingSettingsTimer(this, &Settings::imageLoadingSettingsTimerFired)
+    , m_compositorDrivenAcceleratedScrollingEnabled(false)
 {
     m_page = page; // Page is not yet fully initialized wen constructing Settings, so keeping m_page null over initializeDefaultFontFamilies() call.
 }
@@ -380,4 +382,14 @@
     return m_openGLMultisamplingEnabled;
 }
 
+void Settings::setViewportEnabled(bool enabled)
+{
+    if (m_viewportEnabled == enabled)
+        return;
+
+    m_viewportEnabled = enabled;
+    if (m_page->mainFrame())
+        m_page->mainFrame()->document()->updateViewportArguments();
+}
+
 } // namespace WebCore
diff --git a/Source/core/page/Settings.h b/Source/core/page/Settings.h
index b8ad9e7..9fe3bfa 100644
--- a/Source/core/page/Settings.h
+++ b/Source/core/page/Settings.h
@@ -151,6 +151,9 @@
     void setOpenGLMultisamplingEnabled(bool flag);
     bool openGLMultisamplingEnabled();
 
+    void setViewportEnabled(bool);
+    bool viewportEnabled() const { return m_viewportEnabled; }
+
     // 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; }
@@ -189,6 +192,7 @@
 
     bool m_touchEventEmulationEnabled : 1;
     bool m_openGLMultisamplingEnabled : 1;
+    bool m_viewportEnabled : 1;
 
     // FIXME: This is a temporary flag and should be removed once accelerated
     // overflow scroll is ready (crbug.com/254111).
diff --git a/Source/core/page/SpatialNavigation.cpp b/Source/core/page/SpatialNavigation.cpp
index cb014f9..2b68c5c 100644
--- a/Source/core/page/SpatialNavigation.cpp
+++ b/Source/core/page/SpatialNavigation.cpp
@@ -378,18 +378,18 @@
         LayoutUnit dy = 0;
         switch (direction) {
         case FocusDirectionLeft:
-            dx = - min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollLeft());
+            dx = - std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollLeft());
             break;
         case FocusDirectionRight:
             ASSERT(container->renderBox()->scrollWidth() > (container->renderBox()->scrollLeft() + container->renderBox()->clientWidth()));
-            dx = min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollWidth() - (container->renderBox()->scrollLeft() + container->renderBox()->clientWidth()));
+            dx = std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollWidth() - (container->renderBox()->scrollLeft() + container->renderBox()->clientWidth()));
             break;
         case FocusDirectionUp:
-            dy = - min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollTop());
+            dy = - std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollTop());
             break;
         case FocusDirectionDown:
             ASSERT(container->renderBox()->scrollHeight() - (container->renderBox()->scrollTop() + container->renderBox()->clientHeight()));
-            dy = min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollHeight() - (container->renderBox()->scrollTop() + container->renderBox()->clientHeight()));
+            dy = std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollHeight() - (container->renderBox()->scrollTop() + container->renderBox()->clientHeight()));
             break;
         default:
             ASSERT_NOT_REACHED();
@@ -733,7 +733,7 @@
 
 HTMLFrameOwnerElement* frameOwnerElement(FocusCandidate& candidate)
 {
-    return candidate.isFrameOwnerElement() ? static_cast<HTMLFrameOwnerElement*>(candidate.visibleNode) : 0;
+    return candidate.isFrameOwnerElement() ? toHTMLFrameOwnerElement(candidate.visibleNode) : 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/page/SpatialNavigation.h b/Source/core/page/SpatialNavigation.h
index c740efe..77dd3b0 100644
--- a/Source/core/page/SpatialNavigation.h
+++ b/Source/core/page/SpatialNavigation.h
@@ -36,11 +36,9 @@
 class IntRect;
 class RenderObject;
 
-using namespace std;
-
 inline long long maxDistance()
 {
-    return numeric_limits<long long>::max();
+    return std::numeric_limits<long long>::max();
 }
 
 inline int fudgeFactor()
diff --git a/Source/core/page/UseCounter.cpp b/Source/core/page/UseCounter.cpp
index 7737be9..885d9b8 100644
--- a/Source/core/page/UseCounter.cpp
+++ b/Source/core/page/UseCounter.cpp
@@ -323,8 +323,8 @@
     case CSSPropertyWebkitMarginBefore: return 271;
     case CSSPropertyWebkitMarginEnd: return 272;
     case CSSPropertyWebkitMarginStart: return 273;
-    case CSSPropertyWebkitMarquee: return 274;
-    case CSSPropertyWebkitMarqueeDirection: return 275;
+    // CSSPropertyWebkitMarquee was 274.
+    case CSSPropertyInternalMarqueeDirection: return 275;
     case CSSPropertyWebkitMarqueeIncrement: return 276;
     case CSSPropertyWebkitMarqueeRepetition: return 277;
     case CSSPropertyWebkitMarqueeSpeed: return 278;
@@ -469,9 +469,7 @@
     case CSSPropertyMinZoom: return 407;
     case CSSPropertyOrientation: return 408;
     case CSSPropertyUserZoom: return 409;
-#if defined(ENABLE_DASHBOARD_SUPPORT) && ENABLE_DASHBOARD_SUPPORT
-    case CSSPropertyWebkitDashboardRegion: return 410;
-#endif
+    // CSSPropertyWebkitDashboardRegion was 410.
     // CSSPropertyWebkitOverflowScrolling was 411.
     case CSSPropertyWebkitAppRegion: return 412;
     case CSSPropertyWebkitFilter: return 413;
@@ -485,6 +483,17 @@
     case CSSPropertyTouchAction: return 421;
     case CSSPropertyGridArea: return 422;
     case CSSPropertyGridTemplate: return 423;
+    case CSSPropertyAnimation: return 424;
+    case CSSPropertyAnimationDelay: return 425;
+    case CSSPropertyAnimationDirection: return 426;
+    case CSSPropertyAnimationDuration: return 427;
+    case CSSPropertyAnimationFillMode: return 428;
+    case CSSPropertyAnimationIterationCount: return 429;
+    case CSSPropertyAnimationName: return 430;
+    case CSSPropertyAnimationPlayState: return 431;
+    case CSSPropertyAnimationTimingFunction: return 432;
+    case CSSPropertyObjectFit: return 433;
+    case CSSPropertyPaintOrder: return 434;
 
     // Add new features above this line (don't change the assigned numbers of the existing
     // items) and update maximumCSSSampleId() with the new maximum value.
@@ -499,7 +508,7 @@
     return 0;
 }
 
-static int maximumCSSSampleId() { return 423; }
+static int maximumCSSSampleId() { return 434; }
 
 UseCounter::UseCounter()
 {
@@ -560,8 +569,8 @@
     if (!page)
         return;
 
-    ASSERT(page->useCounter()->deprecationMessage(feature).isEmpty());
-    page->useCounter()->recordMeasurement(feature);
+    ASSERT(page->useCounter().deprecationMessage(feature).isEmpty());
+    page->useCounter().recordMeasurement(feature);
 }
 
 void UseCounter::count(DOMWindow* domWindow, Feature feature)
@@ -593,9 +602,9 @@
     if (!page)
         return;
 
-    if (page->useCounter()->recordMeasurement(feature)) {
-        ASSERT(!page->useCounter()->deprecationMessage(feature).isEmpty());
-        page->console()->addMessage(DeprecationMessageSource, WarningMessageLevel, page->useCounter()->deprecationMessage(feature));
+    if (page->useCounter().recordMeasurement(feature)) {
+        ASSERT(!page->useCounter().deprecationMessage(feature).isEmpty());
+        page->console().addMessage(DeprecationMessageSource, WarningMessageLevel, page->useCounter().deprecationMessage(feature));
     }
 }
 
@@ -654,6 +663,9 @@
     case ConsoleMarkTimeline:
         return "console.markTimeline is deprecated. Please use the console.timeStamp instead.";
 
+    case FileError:
+        return "FileError is deprecated. Please use the 'name' or 'message' attributes of DOMError rather than 'code'.";
+
     // Features that aren't deprecated don't have a deprecation message.
     default:
         return String();
@@ -676,7 +688,7 @@
 UseCounter* UseCounter::getFrom(const Document* document)
 {
     if (document && document->page())
-        return document->page()->useCounter();
+        return &document->page()->useCounter();
     return 0;
 }
 
diff --git a/Source/core/page/UseCounter.h b/Source/core/page/UseCounter.h
index fdfd830..db744f5 100644
--- a/Source/core/page/UseCounter.h
+++ b/Source/core/page/UseCounter.h
@@ -163,6 +163,30 @@
         PrefixedShadowRootConstructor,
         ConsoleMarkTimeline,
         CSSPseudoElementUserAgentCustomPseudo,
+        DocumentTypeEntities, // Removed from DOM4.
+        DocumentTypeInternalSubset, // Removed from DOM4.
+        DocumentTypeNotations, // Removed from DOM4.
+        ElementGetAttributeNode, // Removed from DOM4.
+        ElementSetAttributeNode, // Removed from DOM4.
+        ElementRemoveAttributeNode, // Removed from DOM4.
+        ElementGetAttributeNodeNS, // Removed from DOM4.
+        DocumentCreateAttribute, // Removed from DOM4.
+        DocumentCreateAttributeNS, // Removed from DOM4.
+        DocumentCreateCDATASection, // Removed from DOM4.
+        DocumentInputEncoding, // Removed from DOM4.
+        DocumentXMLEncoding, // Removed from DOM4.
+        DocumentXMLStandalone, // Removed from DOM4.
+        DocumentXMLVersion, // Removed from DOM4.
+        NodeIsSameNode, // Removed from DOM4.
+        NodeIsSupported, // Removed from DOM4.
+        NodeNamespaceURI, // Removed from DOM4.
+        NodePrefix, // Removed from DOM4.
+        NodeLocalName, // Removed from DOM4.
+        NavigatorProductSub,
+        NavigatorVendor,
+        NavigatorVendorSub,
+        FileError,
+        DocumentCharset, // Documented as IE extensions, from KHTML days.
         // Add new features immediately above this line. Don't change assigned
         // numbers of each items, and don't reuse unused slots.
         NumberOfFeatures, // This enum value must be last.
diff --git a/Source/core/page/Window.idl b/Source/core/page/Window.idl
index cbfa00a..976699e 100644
--- a/Source/core/page/Window.idl
+++ b/Source/core/page/Window.idl
@@ -143,7 +143,7 @@
     WebKitPoint webkitConvertPointFromNodeToPage([Default=Undefined] optional Node node,
                                                  [Default=Undefined] optional WebKitPoint p);
 
-    [EnabledAtRuntime, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds] readonly attribute DOMApplicationCache applicationCache;
+    [EnabledAtRuntime, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds] readonly attribute ApplicationCache applicationCache;
 
     [EnabledAtRuntime, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage sessionStorage;
     [EnabledAtRuntime, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage localStorage;
@@ -208,7 +208,8 @@
     [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
     [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
     [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel; // Deprecated in favor of onwheel.
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onwheel;
     attribute EventHandler onoffline;
     attribute EventHandler ononline;
     attribute EventHandler onpagehide;
diff --git a/Source/core/page/WorkerNavigator.h b/Source/core/page/WorkerNavigator.h
index 2152785..710f307 100644
--- a/Source/core/page/WorkerNavigator.h
+++ b/Source/core/page/WorkerNavigator.h
@@ -40,7 +40,7 @@
     static PassRefPtr<WorkerNavigator> create(const String& userAgent) { return adoptRef(new WorkerNavigator(userAgent)); }
     virtual ~WorkerNavigator();
 
-    virtual String userAgent() const;
+    virtual String userAgent() const OVERRIDE;
 
 private:
     explicit WorkerNavigator(const String&);
diff --git a/Source/core/page/WorkerNavigator.idl b/Source/core/page/WorkerNavigator.idl
index 1a1a77c..3debfca 100644
--- a/Source/core/page/WorkerNavigator.idl
+++ b/Source/core/page/WorkerNavigator.idl
@@ -27,13 +27,9 @@
  */
 
 [
-    NoInterfaceObject
+    GlobalContext=WorkerGlobalScope
 ] interface WorkerNavigator {
-    readonly attribute DOMString appName;
-    readonly attribute DOMString appVersion;
-    readonly attribute DOMString platform;
-    readonly attribute DOMString userAgent;
-
-    readonly attribute boolean onLine;
 };
 
+WorkerNavigator implements NavigatorID;
+WorkerNavigator implements NavigatorOnLine;
diff --git a/Source/core/page/animation/AnimationController.cpp b/Source/core/page/animation/AnimationController.cpp
index 9c8ecef..eefc99b 100644
--- a/Source/core/page/animation/AnimationController.cpp
+++ b/Source/core/page/animation/AnimationController.cpp
@@ -149,8 +149,12 @@
 
     bool visible = m_frame->page()->visibilityState() == WebCore::PageVisibilityStateVisible;
 
+    // This std::max to 1 second limits how often we service animations on background tabs.
+    // Without this, plus and gmail were recalculating style as every 200ms or even more
+    // often, burning CPU needlessly for background tabs.
+    // FIXME: Do we want to fire events at all on background tabs?
     if (!visible)
-        timeToNextService = timeToNextEvent;
+        timeToNextService = std::max(timeToNextEvent, 1.0);
 
     if (visible && !timeToNextService) {
         m_frame->document()->view()->scheduleAnimation();
diff --git a/Source/core/page/animation/CSSPropertyAnimation.cpp b/Source/core/page/animation/CSSPropertyAnimation.cpp
index 5bf3bb6..a0f8894 100644
--- a/Source/core/page/animation/CSSPropertyAnimation.cpp
+++ b/Source/core/page/animation/CSSPropertyAnimation.cpp
@@ -36,7 +36,7 @@
 #include "core/css/CSSCrossfadeValue.h"
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/page/animation/AnimationBase.h"
 #include "core/platform/FloatConversion.h"
 #include "core/rendering/ClipPathOperation.h"
diff --git a/Source/core/page/animation/KeyframeAnimation.cpp b/Source/core/page/animation/KeyframeAnimation.cpp
index d298f15..ec8ea2e 100644
--- a/Source/core/page/animation/KeyframeAnimation.cpp
+++ b/Source/core/page/animation/KeyframeAnimation.cpp
@@ -108,7 +108,7 @@
     // Find keyframe that is closest to elapsed time.
     while (distance > 1) {
         currentIndex = (lastIndex + firstIndex) >> 1;
-        float key = m_keyframes[currentIndex].key();
+        double key = m_keyframes[currentIndex].key();
         distance = lastIndex - currentIndex;
 
         if (key < fractionalTime) {
diff --git a/Source/core/page/make_settings.pl b/Source/core/page/make_settings.pl
index b4c5d75..dd29711 100755
--- a/Source/core/page/make_settings.pl
+++ b/Source/core/page/make_settings.pl
@@ -465,7 +465,7 @@
         if ($conditional) {
             print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
         }
-        print $file "    , m_$settingName(page->settings()->$settingName())\n";
+        print $file "    , m_$settingName(page->settings().$settingName())\n";
         if ($conditional) {
             print $file "#endif\n";
         }
@@ -492,7 +492,7 @@
         if ($conditional) {
             print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
         }
-        print $file "    m_page->settings()->$setterFunctionName(m_$settingName);\n";
+        print $file "    m_page->settings().$setterFunctionName(m_$settingName);\n";
         if ($conditional) {
             print $file "#endif\n";
         }
@@ -515,7 +515,7 @@
         if ($conditional) {
             print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
         }
-        print $file "    m_page->settings()->$setterFunctionName($settingName);\n";
+        print $file "    m_page->settings().$setterFunctionName($settingName);\n";
         if ($conditional) {
             print $file "#else\n";
             print $file "    UNUSED_PARAM($settingName);\n";
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index 30975d1..df6f35f 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -48,6 +48,7 @@
 #include "core/platform/mac/ScrollAnimatorMac.h"
 #endif
 #include "core/plugins/PluginView.h"
+#include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderView.h"
@@ -313,13 +314,35 @@
     return !!webLayer;
 }
 
-static void convertLayerRectsToEnclosingCompositedLayer(const LayerHitTestRects& layerRects, LayerHitTestRects& compositorRects)
+// In order to do a DFS cross-frame walk of the RenderLayer tree, we need to know which
+// RenderLayers have child frames inside of them. This computes a mapping for the
+// current frame which we can consult while walking the layers of that frame.
+// Whenever we descend into a new frame, a new map will be created.
+typedef HashMap<const RenderLayer*, Vector<const Frame*> > LayerFrameMap;
+static void makeLayerChildFrameMap(const Frame* currentFrame, LayerFrameMap* map)
 {
-    TRACE_EVENT0("input", "ScrollingCoordinator::convertLayerRectsToEnclosingCompositedLayer");
+    map->clear();
+    const FrameTree* tree = currentFrame->tree();
+    for (const Frame* child = tree->firstChild(); child; child = child->tree()->nextSibling()) {
+        const RenderLayer* containingLayer = child->ownerRenderer()->enclosingLayer();
+        LayerFrameMap::iterator iter = map->find(containingLayer);
+        if (iter == map->end())
+            iter = map->add(containingLayer, Vector<const Frame*>()).iterator;
+        iter->value.append(child);
+    }
+}
 
-    // We have a set of rects per RenderLayer, we need to map them to their bounding boxes in their
-    // enclosing composited layer.
-    for (LayerHitTestRects::const_iterator layerIter = layerRects.begin(); layerIter != layerRects.end(); ++layerIter) {
+static void convertLayerRectsToEnclosingCompositedLayerRecursive(
+    const RenderLayer* curLayer,
+    const LayerHitTestRects& layerRects,
+    LayerHitTestRects& compositorRects,
+    RenderGeometryMap& geometryMap,
+    HashSet<const RenderLayer*>& layersWithRects,
+    LayerFrameMap& layerChildFrameMap)
+{
+    // Project any rects for the current layer
+    LayerHitTestRects::const_iterator layerIter = layerRects.find(curLayer);
+    if (layerIter != layerRects.end()) {
         // Find the enclosing composited layer when it's in another document (for non-composited iframes).
         RenderLayer* compositedLayer = 0;
         for (const RenderLayer* layer = layerIter->key; !compositedLayer;) {
@@ -335,26 +358,82 @@
             // Since this machinery is used only when accelerated compositing is enabled, we expect
             // that every layer should have an enclosing composited layer.
             ASSERT_NOT_REACHED();
-            continue;
+            return;
         }
 
         LayerHitTestRects::iterator compIter = compositorRects.find(compositedLayer);
         if (compIter == compositorRects.end())
             compIter = compositorRects.add(compositedLayer, Vector<LayoutRect>()).iterator;
         // Transform each rect to the co-ordinate space of it's enclosing composited layer.
-        // Ideally we'd compute a transformation matrix once and re-use it for each rect.
-        // RenderGeometryMap can be used for this (but needs to be updated to support crossing
-        // iframe boundaries), but in practice doesn't appear to provide much performance benefit.
         for (size_t i = 0; i < layerIter->value.size(); ++i) {
-            FloatQuad localQuad(layerIter->value[i]);
-            TransformState transformState(TransformState::ApplyTransformDirection, localQuad);
-            MapCoordinatesFlags flags = ApplyContainerFlip | UseTransforms | TraverseDocumentBoundaries;
-            layerIter->key->renderer()->mapLocalToContainer(compositedLayer->renderer(), transformState, flags);
-            transformState.flatten();
-            LayoutRect compositorRect = LayoutRect(transformState.lastPlanarQuad().boundingBox());
-            compIter->value.append(compositorRect);
+            LayoutRect rect = layerIter->value[i];
+            if (compositedLayer != curLayer) {
+                FloatQuad compositorQuad = geometryMap.mapToContainer(rect, compositedLayer->renderer());
+                rect = LayoutRect(compositorQuad.boundingBox());
+            }
+            compIter->value.append(rect);
         }
     }
+
+    // Walk child layers of interest
+    for (const RenderLayer* childLayer = curLayer->firstChild(); childLayer; childLayer = childLayer->nextSibling()) {
+        if (layersWithRects.contains(childLayer)) {
+            geometryMap.pushMappingsToAncestor(childLayer, curLayer);
+            convertLayerRectsToEnclosingCompositedLayerRecursive(childLayer, layerRects, compositorRects, geometryMap, layersWithRects, layerChildFrameMap);
+            geometryMap.popMappingsToAncestor(curLayer);
+        }
+    }
+
+    // If this layer has any frames of interest as a child of it, walk those (with an updated frame map).
+    LayerFrameMap::iterator mapIter = layerChildFrameMap.find(curLayer);
+    if (mapIter != layerChildFrameMap.end()) {
+        for (size_t i = 0; i < mapIter->value.size(); i++) {
+            const Frame* childFrame = mapIter->value[i];
+            const RenderLayer* childLayer = childFrame->view()->renderView()->layer();
+            if (layersWithRects.contains(childLayer)) {
+                LayerFrameMap newLayerChildFrameMap;
+                makeLayerChildFrameMap(childFrame, &newLayerChildFrameMap);
+                geometryMap.pushMappingsToAncestor(childLayer, curLayer);
+                convertLayerRectsToEnclosingCompositedLayerRecursive(childLayer, layerRects, compositorRects, geometryMap, layersWithRects, newLayerChildFrameMap);
+                geometryMap.popMappingsToAncestor(curLayer);
+            }
+        }
+    }
+}
+
+static void convertLayerRectsToEnclosingCompositedLayer(Frame* mainFrame, const LayerHitTestRects& layerRects, LayerHitTestRects& compositorRects)
+{
+    TRACE_EVENT0("input", "ScrollingCoordinator::convertLayerRectsToEnclosingCompositedLayer");
+    bool touchHandlerInChildFrame = false;
+
+    // We have a set of rects per RenderLayer, we need to map them to their bounding boxes in their
+    // enclosing composited layer. To do this most efficiently we'll walk the RenderLayer tree using
+    // RenderGeometryMap. First record all the branches we should traverse in the tree (including
+    // all documents on the page).
+    HashSet<const RenderLayer*> layersWithRects;
+    for (LayerHitTestRects::const_iterator layerIter = layerRects.begin(); layerIter != layerRects.end(); ++layerIter) {
+        const RenderLayer* layer = layerIter->key;
+        do {
+            if (!layersWithRects.add(layer).isNewEntry)
+                break;
+
+            if (layer->parent()) {
+                layer = layer->parent();
+            } else if (RenderObject* parentDocRenderer = layer->renderer()->frame()->ownerRenderer()) {
+                layer = parentDocRenderer->enclosingLayer();
+                touchHandlerInChildFrame = true;
+            }
+        } while (layer);
+    }
+
+    // Now walk the layer projecting rects while maintaining a RenderGeometryMap
+    MapCoordinatesFlags flags = UseTransforms;
+    if (touchHandlerInChildFrame)
+        flags |= TraverseDocumentBoundaries;
+    RenderGeometryMap geometryMap(flags);
+    LayerFrameMap layerChildFrameMap;
+    makeLayerChildFrameMap(mainFrame, &layerChildFrameMap);
+    convertLayerRectsToEnclosingCompositedLayerRecursive(mainFrame->contentRenderer()->layer(), layerRects, compositorRects, geometryMap, layersWithRects, layerChildFrameMap);
 }
 
 // Note that in principle this could be called more often than computeTouchEventTargetRects, for
@@ -364,27 +443,37 @@
     TRACE_EVENT0("input", "ScrollingCoordinator::setTouchEventTargetRects");
 
     LayerHitTestRects compositorRects;
-    convertLayerRectsToEnclosingCompositedLayer(layerRects, compositorRects);
+    convertLayerRectsToEnclosingCompositedLayer(m_page->mainFrame(), layerRects, compositorRects);
 
-    // Inform any observers (i.e. for testing) of these new rects.
-    HashSet<TouchEventTargetRectsObserver*>::iterator stop = m_touchEventTargetRectsObservers.end();
-    for (HashSet<TouchEventTargetRectsObserver*>::iterator it = m_touchEventTargetRectsObservers.begin(); it != stop; ++it)
-        (*it)->touchEventTargetRectsChanged(compositorRects);
+    HashSet<const RenderLayer*> oldLayersWithTouchRects;
+    m_layersWithTouchRects.swap(oldLayersWithTouchRects);
 
     // Note that ideally we'd clear the touch event handler region on all layers first,
     // in case there are others that no longer have any handlers. But it's unlikely to
     // matter much in practice (just makes us more conservative).
     for (LayerHitTestRects::const_iterator iter = compositorRects.begin(); iter != compositorRects.end(); ++iter) {
+        const RenderLayer* layer = iter->key;
         WebVector<WebRect> webRects(iter->value.size());
         for (size_t i = 0; i < iter->value.size(); ++i)
             webRects[i] = enclosingIntRect(iter->value[i]);
-        RenderLayerBacking* backing = iter->key->backing();
+        RenderLayerBacking* backing = layer->backing();
         // If the layer is using composited scrolling, then it's the contents that these
         // rects apply to.
         GraphicsLayer* graphicsLayer = backing->scrollingContentsLayer();
         if (!graphicsLayer)
             graphicsLayer = backing->graphicsLayer();
         graphicsLayer->platformLayer()->setTouchEventHandlerRegion(webRects);
+        oldLayersWithTouchRects.remove(layer);
+        m_layersWithTouchRects.add(layer);
+    }
+
+    // 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) {
+        RenderLayerBacking* backing = (*it)->backing();
+        GraphicsLayer* graphicsLayer = backing->scrollingContentsLayer();
+        if (!graphicsLayer)
+            graphicsLayer = backing->graphicsLayer();
+        graphicsLayer->platformLayer()->setTouchEventHandlerRegion(WebVector<WebRect>());
     }
 }
 
@@ -404,6 +493,11 @@
     setTouchEventTargetRects(touchEventTargetRects);
 }
 
+void ScrollingCoordinator::willDestroyRenderLayer(RenderLayer* layer)
+{
+    m_layersWithTouchRects.remove(layer);
+}
+
 void ScrollingCoordinator::setWheelEventHandlerCount(unsigned count)
 {
     if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(m_page->mainFrame()->view()))
@@ -474,7 +568,7 @@
         for (FrameView::ResizerAreaSet::const_iterator it = resizerAreas->begin(), end = resizerAreas->end(); it != end; ++it) {
             RenderLayer* layer = *it;
             IntRect bounds = layer->renderer()->absoluteBoundingBoxRect();
-            IntRect corner = layer->resizerCornerRect(bounds, RenderLayer::ResizerForTouch);
+            IntRect corner = layer->resizerCornerRect(bounds, ResizerForTouch);
             corner.moveBy(offset);
             shouldHandleScrollGestureOnMainThreadRegion.unite(corner);
         }
@@ -498,16 +592,6 @@
     return shouldHandleScrollGestureOnMainThreadRegion;
 }
 
-void ScrollingCoordinator::addTouchEventTargetRectsObserver(TouchEventTargetRectsObserver* observer)
-{
-    m_touchEventTargetRectsObservers.add(observer);
-}
-
-void ScrollingCoordinator::removeTouchEventTargetRectsObserver(TouchEventTargetRectsObserver* observer)
-{
-    m_touchEventTargetRectsObservers.remove(observer);
-}
-
 static void accumulateDocumentTouchEventTargetRects(LayerHitTestRects& rects, const Document* document)
 {
     ASSERT(document);
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.h b/Source/core/page/scrolling/ScrollingCoordinator.h
index acb13c6..175c97d 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -97,19 +97,12 @@
     void setLayerIsContainerForFixedPositionLayers(GraphicsLayer*, bool);
     void updateLayerPositionConstraint(RenderLayer*);
     void touchEventTargetRectsDidChange(const Document*);
+    void willDestroyRenderLayer(RenderLayer*);
 
     static String mainThreadScrollingReasonsAsText(MainThreadScrollingReasons);
     String mainThreadScrollingReasonsAsText() const;
     Region computeShouldHandleScrollGestureOnMainThreadRegion(const Frame*, const IntPoint& frameLocation) const;
 
-    class TouchEventTargetRectsObserver {
-    public:
-        virtual void touchEventTargetRectsChanged(const LayerHitTestRects&) = 0;
-    };
-
-    void addTouchEventTargetRectsObserver(TouchEventTargetRectsObserver*);
-    void removeTouchEventTargetRectsObserver(TouchEventTargetRectsObserver*);
-
 protected:
     explicit ScrollingCoordinator(Page*);
 
@@ -147,8 +140,7 @@
     typedef HashMap<ScrollableArea*, OwnPtr<WebKit::WebScrollbarLayer> > ScrollbarMap;
     ScrollbarMap m_horizontalScrollbars;
     ScrollbarMap m_verticalScrollbars;
-
-    HashSet<TouchEventTargetRectsObserver*> m_touchEventTargetRectsObservers;
+    HashSet<const RenderLayer*> m_layersWithTouchRects;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/AsyncFileSystem.h b/Source/core/platform/AsyncFileSystem.h
index 2a408f8..a505175 100644
--- a/Source/core/platform/AsyncFileSystem.h
+++ b/Source/core/platform/AsyncFileSystem.h
@@ -36,11 +36,12 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/WTFString.h"
 
+namespace WebKit { class WebFileWriterClient; }
+
 namespace WebCore {
 
 class AsyncFileSystem;
 class AsyncFileSystemCallbacks;
-class AsyncFileWriterClient;
 class KURL;
 
 // This class provides async interface for platform-specific file system implementation.  Note that all the methods take platform paths.
@@ -54,17 +55,11 @@
 
     // Subclass must implement this if it supports synchronous operations.
     // This should return false if there are no pending operations.
-    virtual bool waitForOperationToComplete() { return false; }
+    virtual bool waitForOperationToComplete() { return true; }
 
     // Creates and returns a new platform-specific AsyncFileSystem instance if the platform has its own implementation.
     static PassOwnPtr<AsyncFileSystem> create();
 
-    // Opens a new file system. The create parameter specifies whether or not to create the path if it does not already exists.
-    static void openFileSystem(const String& basePath, const String& storageIdentifier, FileSystemType, bool create, PassOwnPtr<AsyncFileSystemCallbacks>);
-
-    // Deletes the file system.
-    static void deleteFileSystem(const String& basePath, const String& storageIdentifier, FileSystemType, PassOwnPtr<AsyncFileSystemCallbacks>);
-
     // Moves a file or directory from srcPath to destPath.
     // AsyncFileSystemCallbacks::didSucceed() is called when the operation is completed successfully.
     // AsyncFileSystemCallbacks::didFail() is called otherwise.
@@ -116,10 +111,10 @@
     // AsyncFileSystemCallbacks::didFail() is when there is an error.
     virtual void readDirectory(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
 
-    // Creates an AsyncFileWriter for a given file path.
+    // Creates an WebFileWriter for a given file path.
     // AsyncFileSystemCallbacks::didCreateFileWriter() is called when an AsyncFileWriter is created successfully.
     // AsyncFileSystemCallbacks::didFail() is called otherwise.
-    virtual void createWriter(AsyncFileWriterClient*, const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
+    virtual void createWriter(WebKit::WebFileWriterClient*, const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
 
     // Creates a snapshot file and read its metadata for a new File object.
     // In local filesystem cases the backend may simply return the metadata of the file itself (as well as readMetadata does),
diff --git a/Source/core/platform/AsyncFileSystemCallbacks.h b/Source/core/platform/AsyncFileSystemCallbacks.h
index 18c4961..7134297 100644
--- a/Source/core/platform/AsyncFileSystemCallbacks.h
+++ b/Source/core/platform/AsyncFileSystemCallbacks.h
@@ -34,7 +34,7 @@
 #include "core/platform/AsyncFileSystem.h"
 #include "core/platform/FileMetadata.h"
 #include "core/platform/network/BlobData.h"
-#include "modules/filesystem/AsyncFileWriter.h"
+#include "public/platform/WebFileWriter.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -63,7 +63,7 @@
     virtual void didReadDirectoryEntries(bool hasMore) { ASSERT_NOT_REACHED(); }
 
     // Called when an AsyncFileWrter has been created successfully.
-    virtual void didCreateFileWriter(PassOwnPtr<AsyncFileWriter>, long long length) { ASSERT_NOT_REACHED(); }
+    virtual void didCreateFileWriter(PassOwnPtr<WebKit::WebFileWriter>, long long length) { ASSERT_NOT_REACHED(); }
 
     // Called when there was an error.
     virtual void didFail(int code) = 0;
diff --git a/Source/core/platform/DEPS b/Source/core/platform/DEPS
index f1e4fe8..cfd697d 100644
--- a/Source/core/platform/DEPS
+++ b/Source/core/platform/DEPS
@@ -17,7 +17,7 @@
     "!core/fileapi",
     "!core/html",
     "!core/inspector",
-    "!core/loader/cache",
+    "!core/fetch",
     "!core/page",
     "!core/plugins",
     "!core/rendering",
diff --git a/Source/core/platform/LifecycleNotifier.h b/Source/core/platform/LifecycleNotifier.h
index fd48353..cc12be2 100644
--- a/Source/core/platform/LifecycleNotifier.h
+++ b/Source/core/platform/LifecycleNotifier.h
@@ -55,7 +55,8 @@
         IteratingOverActiveDOMObjects,
         IteratingOverContextObservers,
         IteratingOverDocumentObservers,
-        IteratingOverPageObservers
+        IteratingOverPageObservers,
+        IteratingOverDOMWindowObservers
     };
 
     IterationType m_iterating;
diff --git a/Source/core/platform/LifecycleObserver.h b/Source/core/platform/LifecycleObserver.h
index 5e3ca2c..3e2d0a4 100644
--- a/Source/core/platform/LifecycleObserver.h
+++ b/Source/core/platform/LifecycleObserver.h
@@ -37,7 +37,8 @@
         ActiveDOMObjectType,
         DocumentLifecycleObserverType,
         GenericType,
-        PageLifecycleObserverType
+        PageLifecycleObserverType,
+        DOMWindowLifecycleObserverType
     };
 
     explicit LifecycleObserver(LifecycleContext*, Type = GenericType);
diff --git a/Source/core/platform/chromium/PasteboardChromium.cpp b/Source/core/platform/Pasteboard.cpp
similarity index 90%
rename from Source/core/platform/chromium/PasteboardChromium.cpp
rename to Source/core/platform/Pasteboard.cpp
index d06f207..1aa983a 100644
--- a/Source/core/platform/chromium/PasteboardChromium.cpp
+++ b/Source/core/platform/Pasteboard.cpp
@@ -39,8 +39,8 @@
 #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/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/platform/chromium/ClipboardChromium.h"
 #include "core/platform/chromium/ClipboardUtilitiesChromium.h"
@@ -65,12 +65,6 @@
 {
 }
 
-void Pasteboard::clear()
-{
-    // The ScopedClipboardWriter class takes care of clearing the clipboard's
-    // previous contents.
-}
-
 bool Pasteboard::isSelectionMode() const
 {
     return m_selectionMode;
@@ -81,11 +75,11 @@
     m_selectionMode = selectionMode;
 }
 
-void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, Frame* frame, ShouldSerializeSelectedTextForClipboard shouldSerializeSelectedTextForClipboard)
+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 = shouldSerializeSelectedTextForClipboard == IncludeImageAltTextForClipboard ? frame->selectedTextForClipboard() : frame->selectedText();
+    String plainText = text;
 #if OS(WINDOWS)
     replaceNewlinesWithWindowsStyleNewlines(plainText);
 #endif
@@ -106,7 +100,7 @@
 #endif
 }
 
-void Pasteboard::writeURL(const KURL& url, const String& titleStr, Frame* frame)
+void Pasteboard::writeURL(const KURL& url, const String& titleStr)
 {
     ASSERT(!url.isEmpty());
 
@@ -139,16 +133,14 @@
         return;
 
     // If the image is wrapped in a link, |url| points to the target of the
-    // link.  This isn't useful to us, so get the actual image URL.
+    // link. This isn't useful to us, so get the actual image URL.
     AtomicString urlString;
     if (node->hasTagName(HTMLNames::imgTag) || node->hasTagName(HTMLNames::inputTag))
         urlString = toElement(node)->getAttribute(HTMLNames::srcAttr);
     else if (node->hasTagName(SVGNames::imageTag))
         urlString = toElement(node)->getAttribute(XLinkNames::hrefAttr);
-    else if (node->hasTagName(HTMLNames::embedTag) || node->hasTagName(HTMLNames::objectTag)) {
-        Element* element = toElement(node);
-        urlString = element->imageSourceURL();
-    }
+    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));
@@ -165,7 +157,7 @@
     return WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatSmartPaste, m_selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard);
 }
 
-String Pasteboard::plainText(Frame* frame)
+String Pasteboard::plainText()
 {
     return WebKit::Platform::current()->clipboard()->readPlainText(m_selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard);
 }
diff --git a/Source/core/platform/Pasteboard.h b/Source/core/platform/Pasteboard.h
index db02978..ecacf55 100644
--- a/Source/core/platform/Pasteboard.h
+++ b/Source/core/platform/Pasteboard.h
@@ -48,8 +48,6 @@
 class Range;
 class SharedBuffer;
 
-enum ShouldSerializeSelectedTextForClipboard { DefaultSelectedTextType, IncludeImageAltTextForClipboard };
-
 class Pasteboard {
     WTF_MAKE_NONCOPYABLE(Pasteboard); WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -59,15 +57,14 @@
     };
 
     static Pasteboard* generalPasteboard();
-    void writeSelection(Range*, bool canSmartCopyOrDelete, Frame*, ShouldSerializeSelectedTextForClipboard = DefaultSelectedTextType);
+    void writeSelection(Range*, bool canSmartCopyOrDelete, const String& text);
     void writePlainText(const String&, SmartReplaceOption);
-    void writeURL(const KURL&, const String&, Frame* = 0);
+    void writeURL(const KURL&, const String&);
     void writeImage(Node*, const KURL&, const String& title);
     void writeClipboard(Clipboard*);
-    void clear();
     bool canSmartReplace();
     PassRefPtr<DocumentFragment> documentFragment(Frame*, PassRefPtr<Range>, bool allowPlainText, bool& chosePlainText);
-    String plainText(Frame* = 0);
+    String plainText();
 
     bool isSelectionMode() const;
     void setSelectionMode(bool);
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp b/Source/core/platform/ScrollbarThemeAndroid.cpp
similarity index 91%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp
rename to Source/core/platform/ScrollbarThemeAndroid.cpp
index ca8b507..bbceb46 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp
+++ b/Source/core/platform/ScrollbarThemeAndroid.cpp
@@ -24,16 +24,15 @@
  */
 
 #include "config.h"
-
 #include "core/platform/ScrollbarTheme.h"
 
-#include "core/platform/chromium/ScrollbarThemeChromiumOverlay.h"
+#include "core/platform/ScrollbarThemeOverlay.h"
 
 namespace WebCore {
 
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
-    DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumOverlay, theme, ());
+    DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (3, 4));
     return &theme;
 }
 
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.cpp b/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
similarity index 84%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.cpp
rename to Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
index 721870a..f75829e 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.cpp
+++ b/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
@@ -29,38 +29,38 @@
  */
 
 #include "config.h"
-#include "core/platform/chromium/ScrollbarThemeChromiumDefault.h"
+#include "core/platform/ScrollbarThemeAuraOrGtk.h"
 
 #include "RuntimeEnabledFeatures.h"
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/platform/Scrollbar.h"
-#include "core/platform/chromium/ScrollbarThemeChromiumOverlay.h"
+#include "core/platform/ScrollbarThemeOverlay.h"
 #include "core/platform/graphics/GraphicsContext.h"
-#include "public/platform/default/WebThemeEngine.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebRect.h"
+#include "public/platform/default/WebThemeEngine.h"
 
 namespace WebCore {
 
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
     if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) {
-        DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumOverlay, theme, ());
+        DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (7, 0));
         return &theme;
     }
 
-    DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumDefault, theme, ());
+    DEFINE_STATIC_LOCAL(ScrollbarThemeAuraOrGtk, theme, ());
     return &theme;
 }
 
-int ScrollbarThemeChromiumDefault::scrollbarThickness(ScrollbarControlSize controlSize)
+int ScrollbarThemeAuraOrGtk::scrollbarThickness(ScrollbarControlSize controlSize)
 {
     // Horiz and Vert scrollbars are the same thickness.
     IntSize scrollbarSize = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarVerticalTrack);
     return scrollbarSize.width();
 }
 
-void ScrollbarThemeChromiumDefault::paintTrackPiece(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart partType)
+void ScrollbarThemeAuraOrGtk::paintTrackPiece(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart partType)
 {
     WebKit::WebThemeEngine::State state = scrollbar->hoveredPart() == partType ? WebKit::WebThemeEngine::StateHover : WebKit::WebThemeEngine::StateNormal;
     IntRect alignRect = trackRect(scrollbar, false);
@@ -73,7 +73,7 @@
     WebKit::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::PartScrollbarHorizontalTrack : WebKit::WebThemeEngine::PartScrollbarVerticalTrack, state, WebKit::WebRect(rect), &extraParams);
 }
 
-void ScrollbarThemeChromiumDefault::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
+void ScrollbarThemeAuraOrGtk::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
 {
     WebKit::WebThemeEngine::Part paintPart;
     WebKit::WebThemeEngine::State state = WebKit::WebThemeEngine::StateNormal;
@@ -109,7 +109,7 @@
     WebKit::Platform::current()->themeEngine()->paint(canvas, paintPart, state, WebKit::WebRect(rect), 0);
 }
 
-void ScrollbarThemeChromiumDefault::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
+void ScrollbarThemeAuraOrGtk::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
     WebKit::WebThemeEngine::State state;
     WebKit::WebCanvas* canvas = gc->canvas();
@@ -122,12 +122,12 @@
     WebKit::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::PartScrollbarHorizontalThumb : WebKit::WebThemeEngine::PartScrollbarVerticalThumb, state, WebKit::WebRect(rect), 0);
 }
 
-bool ScrollbarThemeChromiumDefault::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
+bool ScrollbarThemeAuraOrGtk::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
 {
     return (evt.shiftKey() && evt.button() == LeftButton) || (evt.button() == MiddleButton);
 }
 
-IntSize ScrollbarThemeChromiumDefault::buttonSize(ScrollbarThemeClient* scrollbar)
+IntSize ScrollbarThemeAuraOrGtk::buttonSize(ScrollbarThemeClient* scrollbar)
 {
     if (scrollbar->orientation() == VerticalScrollbar) {
         IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarUpArrow);
@@ -139,7 +139,7 @@
     return IntSize(scrollbar->width() < 2 * size.width() ? scrollbar->width() / 2 : size.width(), size.height());
 }
 
-int ScrollbarThemeChromiumDefault::minimumThumbLength(ScrollbarThemeClient* scrollbar)
+int ScrollbarThemeAuraOrGtk::minimumThumbLength(ScrollbarThemeClient* scrollbar)
 {
     if (scrollbar->orientation() == VerticalScrollbar) {
         IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarVerticalThumb);
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/platform/ScrollbarThemeAuraOrGtk.h
similarity index 90%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
rename to Source/core/platform/ScrollbarThemeAuraOrGtk.h
index 133dab0..ec37c2c 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/platform/ScrollbarThemeAuraOrGtk.h
@@ -28,14 +28,14 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#ifndef ScrollbarThemeAuraOrGtk_h
+#define ScrollbarThemeAuraOrGtk_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "core/platform/ScrollbarThemeNonMacCommon.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
+class ScrollbarThemeAuraOrGtk : public ScrollbarThemeNonMacCommon {
 public:
     virtual int scrollbarThickness(ScrollbarControlSize);
 
diff --git a/Source/core/platform/mac/ScrollbarThemeMac.h b/Source/core/platform/ScrollbarThemeMacCommon.h
similarity index 95%
rename from Source/core/platform/mac/ScrollbarThemeMac.h
rename to Source/core/platform/ScrollbarThemeMacCommon.h
index fac25ec..8a62dd9 100644
--- a/Source/core/platform/mac/ScrollbarThemeMac.h
+++ b/Source/core/platform/ScrollbarThemeMacCommon.h
@@ -23,8 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeMac_h
-#define ScrollbarThemeMac_h
+#ifndef ScrollbarThemeMacCommon_h
+#define ScrollbarThemeMacCommon_h
 
 #include "core/platform/ScrollbarTheme.h"
 
@@ -63,4 +63,4 @@
 
 }
 
-#endif
+#endif // ScrollbarThemeMacCommon_h
diff --git a/Source/core/platform/mac/ScrollbarThemeMac.mm b/Source/core/platform/ScrollbarThemeMacCommon.mm
similarity index 98%
rename from Source/core/platform/mac/ScrollbarThemeMac.mm
rename to Source/core/platform/ScrollbarThemeMacCommon.mm
index 6b7975a..5577f96 100644
--- a/Source/core/platform/mac/ScrollbarThemeMac.mm
+++ b/Source/core/platform/ScrollbarThemeMacCommon.mm
@@ -20,16 +20,18 @@
  * 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. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include "config.h"
-#include "core/platform/mac/ScrollbarThemeMac.h"
+#include "core/platform/ScrollbarThemeMacCommon.h"
 
 #include <Carbon/Carbon.h>
 #include "core/page/FrameView.h"
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/platform/ScrollView.h"
+#include "core/platform/ScrollbarThemeMacNonOverlayAPI.h"
+#include "core/platform/ScrollbarThemeMacOverlayAPI.h"
 #include "core/platform/graphics/Gradient.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
@@ -39,8 +41,6 @@
 #include "core/platform/mac/LocalCurrentGraphicsContext.h"
 #include "core/platform/mac/NSScrollerImpDetails.h"
 #include "core/platform/mac/ScrollAnimatorMac.h"
-#include "core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h"
-#include "core/platform/mac/ScrollbarThemeMacOverlayAPI.h"
 #include "public/platform/mac/WebThemeEngine.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebRect.h"
diff --git a/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h b/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.h
similarity index 97%
rename from Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h
rename to Source/core/platform/ScrollbarThemeMacNonOverlayAPI.h
index 2806605..e513800 100644
--- a/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h
+++ b/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.h
@@ -31,7 +31,7 @@
 #ifndef ScrollbarThemeMacNonOverlayAPI_h
 #define ScrollbarThemeMacNonOverlayAPI_h
 
-#include "core/platform/mac/ScrollbarThemeMac.h"
+#include "core/platform/ScrollbarThemeMacCommon.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.mm b/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
similarity index 99%
rename from Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.mm
rename to Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
index 62e2db5..dc85400 100644
--- a/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.mm
+++ b/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
@@ -29,7 +29,7 @@
  */
 
 #include "config.h"
-#include "core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h"
+#include "core/platform/ScrollbarThemeMacNonOverlayAPI.h"
 
 #include <Carbon/Carbon.h>
 #include "core/platform/ScrollbarThemeClient.h"
diff --git a/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.h b/Source/core/platform/ScrollbarThemeMacOverlayAPI.h
similarity index 98%
rename from Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.h
rename to Source/core/platform/ScrollbarThemeMacOverlayAPI.h
index f1712a0..b0c5aef 100644
--- a/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.h
+++ b/Source/core/platform/ScrollbarThemeMacOverlayAPI.h
@@ -31,7 +31,7 @@
 #ifndef ScrollbarThemeMacOverlayAPI_h
 #define ScrollbarThemeMacOverlayAPI_h
 
-#include "core/platform/mac/ScrollbarThemeMac.h"
+#include "core/platform/ScrollbarThemeMacCommon.h"
 
 typedef id ScrollbarPainter;
 
diff --git a/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.mm b/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
similarity index 98%
rename from Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.mm
rename to Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
index a0ad14f..cac425e 100644
--- a/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.mm
+++ b/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
@@ -29,7 +29,7 @@
  */
 
 #include "config.h"
-#include "core/platform/mac/ScrollbarThemeMacOverlayAPI.h"
+#include "core/platform/ScrollbarThemeMacOverlayAPI.h"
 
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromium.cpp b/Source/core/platform/ScrollbarThemeNonMacCommon.cpp
similarity index 77%
rename from Source/core/platform/chromium/ScrollbarThemeChromium.cpp
rename to Source/core/platform/ScrollbarThemeNonMacCommon.cpp
index d44a778..72208ba 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromium.cpp
+++ b/Source/core/platform/ScrollbarThemeNonMacCommon.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "core/platform/ScrollbarThemeNonMacCommon.h"
 
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/platform/ScrollableArea.h"
@@ -33,21 +33,16 @@
 #include "core/platform/ScrollbarTheme.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 
-// -----------------------------------------------------------------------------
-// This file contains scrollbar theme code that is cross platform. Additional
-// members of ScrollbarThemeChromium can be found in the platform specific files
-// -----------------------------------------------------------------------------
-
 namespace WebCore {
 
-bool ScrollbarThemeChromium::hasThumb(ScrollbarThemeClient* scrollbar)
+bool ScrollbarThemeNonMacCommon::hasThumb(ScrollbarThemeClient* scrollbar)
 {
     // This method is just called as a paint-time optimization to see if
-    // painting the thumb can be skipped.  We don't have to be exact here.
+    // painting the thumb can be skipped. We don't have to be exact here.
     return thumbLength(scrollbar) > 0;
 }
 
-IntRect ScrollbarThemeChromium::backButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool)
+IntRect ScrollbarThemeNonMacCommon::backButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool)
 {
     // Windows and Linux just have single arrows.
     if (part == BackButtonEndPart)
@@ -57,7 +52,7 @@
     return IntRect(scrollbar->x(), scrollbar->y(), size.width(), size.height());
 }
 
-IntRect ScrollbarThemeChromium::forwardButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool)
+IntRect ScrollbarThemeNonMacCommon::forwardButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool)
 {
     // Windows and Linux just have single arrows.
     if (part == ForwardButtonStartPart)
@@ -75,7 +70,7 @@
     return IntRect(x, y, size.width(), size.height());
 }
 
-IntRect ScrollbarThemeChromium::trackRect(ScrollbarThemeClient* scrollbar, bool)
+IntRect ScrollbarThemeNonMacCommon::trackRect(ScrollbarThemeClient* scrollbar, bool)
 {
     IntSize bs = buttonSize(scrollbar);
     int thickness = scrollbarThickness(scrollbar->controlSize());
@@ -91,20 +86,20 @@
     return IntRect(scrollbar->x(), scrollbar->y() + bs.height(), thickness, scrollbar->height() - 2 * bs.height());
 }
 
-void ScrollbarThemeChromium::paintTrackBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
+void ScrollbarThemeNonMacCommon::paintTrackBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
-    // Just assume a forward track part.  We only paint the track as a single piece when there is no thumb.
+    // Just assume a forward track part. We only paint the track as a single piece when there is no thumb.
     if (!hasThumb(scrollbar))
         paintTrackPiece(context, scrollbar, rect, ForwardTrackPart);
 }
 
-void ScrollbarThemeChromium::paintTickmarks(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
+void ScrollbarThemeNonMacCommon::paintTickmarks(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
     if (scrollbar->orientation() != VerticalScrollbar)
         return;
 
     if (rect.height() <= 0 || rect.width() <= 0)
-        return;  // nothing to draw on.
+        return;
 
     // Get the tickmarks for the frameview.
     Vector<IntRect> tickmarks;
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromium.h b/Source/core/platform/ScrollbarThemeNonMacCommon.h
similarity index 91%
rename from Source/core/platform/chromium/ScrollbarThemeChromium.h
rename to Source/core/platform/ScrollbarThemeNonMacCommon.h
index 9866a17..3fc7647 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromium.h
+++ b/Source/core/platform/ScrollbarThemeNonMacCommon.h
@@ -28,8 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromium_h
-#define ScrollbarThemeChromium_h
+#ifndef ScrollbarThemeNonMacCommon_h
+#define ScrollbarThemeNonMacCommon_h
 
 #include "core/platform/ScrollbarTheme.h"
 
@@ -37,9 +37,7 @@
 
 class PlatformMouseEvent;
 
-// This class contains the scrollbar code which is shared between Chromium
-// Windows and Linux.
-class ScrollbarThemeChromium : public ScrollbarTheme {
+class ScrollbarThemeNonMacCommon : public ScrollbarTheme {
 protected:
     virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return true; }
     virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp b/Source/core/platform/ScrollbarThemeOverlay.cpp
similarity index 67%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp
rename to Source/core/platform/ScrollbarThemeOverlay.cpp
index c10c89b..d6c4631 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp
+++ b/Source/core/platform/ScrollbarThemeOverlay.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "config.h"
-#include "core/platform/chromium/ScrollbarThemeChromiumOverlay.h"
+#include "core/platform/ScrollbarThemeOverlay.h"
 
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/platform/Scrollbar.h"
@@ -37,20 +37,24 @@
 
 namespace WebCore {
 
-static const int scrollbarWidth = 3;
-static const int scrollbarMargin = 4;
-
-int ScrollbarThemeChromiumOverlay::scrollbarThickness(ScrollbarControlSize controlSize)
+ScrollbarThemeOverlay::ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin)
+    : ScrollbarTheme()
+    , m_thumbThickness(thumbThickness)
+    , m_scrollbarMargin(scrollbarMargin)
 {
-    return scrollbarWidth + scrollbarMargin;
 }
 
-bool ScrollbarThemeChromiumOverlay::usesOverlayScrollbars() const
+int ScrollbarThemeOverlay::scrollbarThickness(ScrollbarControlSize controlSize)
+{
+    return m_thumbThickness + m_scrollbarMargin;
+}
+
+bool ScrollbarThemeOverlay::usesOverlayScrollbars() const
 {
     return true;
 }
 
-int ScrollbarThemeChromiumOverlay::thumbPosition(ScrollbarThemeClient* scrollbar)
+int ScrollbarThemeOverlay::thumbPosition(ScrollbarThemeClient* scrollbar)
 {
     if (!scrollbar->totalSize())
         return 0;
@@ -60,7 +64,7 @@
     return round(proportion * trackLen);
 }
 
-int ScrollbarThemeChromiumOverlay::thumbLength(ScrollbarThemeClient* scrollbar)
+int ScrollbarThemeOverlay::thumbLength(ScrollbarThemeClient* scrollbar)
 {
     int trackLen = trackLength(scrollbar);
 
@@ -73,38 +77,38 @@
     return length;
 }
 
-bool ScrollbarThemeChromiumOverlay::hasThumb(ScrollbarThemeClient* scrollbar)
+bool ScrollbarThemeOverlay::hasThumb(ScrollbarThemeClient* scrollbar)
 {
     return true;
 }
 
-IntRect ScrollbarThemeChromiumOverlay::backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
+IntRect ScrollbarThemeOverlay::backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
 {
     return IntRect();
 }
 
-IntRect ScrollbarThemeChromiumOverlay::forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
+IntRect ScrollbarThemeOverlay::forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
 {
     return IntRect();
 }
 
-IntRect ScrollbarThemeChromiumOverlay::trackRect(ScrollbarThemeClient* scrollbar, bool)
+IntRect ScrollbarThemeOverlay::trackRect(ScrollbarThemeClient* scrollbar, bool)
 {
     IntRect rect = scrollbar->frameRect();
     if (scrollbar->orientation() == HorizontalScrollbar)
-        rect.inflateX(-scrollbarMargin);
+        rect.inflateX(-m_scrollbarMargin);
     else
-        rect.inflateY(-scrollbarMargin);
+        rect.inflateY(-m_scrollbarMargin);
     return rect;
 }
 
-void ScrollbarThemeChromiumOverlay::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
+void ScrollbarThemeOverlay::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
     IntRect thumbRect = rect;
     if (scrollbar->orientation() == HorizontalScrollbar)
-        thumbRect.setHeight(thumbRect.height() - scrollbarMargin);
+        thumbRect.setHeight(thumbRect.height() - m_scrollbarMargin);
     else
-        thumbRect.setWidth(thumbRect.width() - scrollbarMargin);
+        thumbRect.setWidth(thumbRect.width() - m_scrollbarMargin);
     context->fillRect(thumbRect, Color(128, 128, 128, 128));
 }
 
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.h b/Source/core/platform/ScrollbarThemeOverlay.h
similarity index 88%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.h
rename to Source/core/platform/ScrollbarThemeOverlay.h
index 291ef8c..62e4f01 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.h
+++ b/Source/core/platform/ScrollbarThemeOverlay.h
@@ -23,8 +23,8 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumOverlay_h
-#define ScrollbarThemeChromiumOverlay_h
+#ifndef ScrollbarThemeOverlay_h
+#define ScrollbarThemeOverlay_h
 
 #include "core/platform/ScrollbarTheme.h"
 
@@ -32,8 +32,11 @@
 
 // This scrollbar theme is used to get overlay scrollbar for platforms other
 // than Mac. Mac's overlay scrollbars are in ScrollbarThemeMac*.
-class ScrollbarThemeChromiumOverlay : public ScrollbarTheme {
+class ScrollbarThemeOverlay : public ScrollbarTheme {
 public:
+    ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin);
+    virtual ~ScrollbarThemeOverlay() { }
+
     virtual int scrollbarThickness(ScrollbarControlSize) OVERRIDE;
     virtual bool usesOverlayScrollbars() const OVERRIDE;
 
@@ -48,6 +51,10 @@
     virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
 
     virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
+
+private:
+    int m_thumbThickness;
+    int m_scrollbarMargin;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumWin.cpp b/Source/core/platform/ScrollbarThemeWin.cpp
similarity index 85%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumWin.cpp
rename to Source/core/platform/ScrollbarThemeWin.cpp
index a41c6b1..d8f51e4 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumWin.cpp
+++ b/Source/core/platform/ScrollbarThemeWin.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/platform/chromium/ScrollbarThemeChromiumWin.h"
+#include "core/platform/ScrollbarThemeWin.h"
 
 #include <windows.h>
 #include <vsstyle.h>
@@ -38,28 +38,27 @@
 #include "public/platform/Platform.h"
 #include "public/platform/WebRect.h"
 #include "public/platform/win/WebThemeEngine.h"
-
 namespace WebCore {
 
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
-    static ScrollbarThemeChromiumWin theme;
+    static ScrollbarThemeWin theme;
     return &theme;
 }
 
 // The scrollbar size in DumpRenderTree on the Mac - so we can match their
-// layout results.  Entries are for regular, small, and mini scrollbars.
+// layout results. Entries are for regular, small, and mini scrollbars.
 // Metrics obtained using [NSScroller scrollerWidthForControlSize:]
 static const int kMacScrollbarSize[3] = { 15, 11, 15 };
 
 // Constants used to figure the drag rect outside which we should snap the
-// scrollbar thumb back to its origin.  These calculations are based on
+// scrollbar thumb back to its origin. These calculations are based on
 // observing the behavior of the MSVC8 main window scrollbar + some
 // guessing/extrapolation.
 static const int kOffEndMultiplier = 3;
 static const int kOffSideMultiplier = 8;
 
-int ScrollbarThemeChromiumWin::scrollbarThickness(ScrollbarControlSize controlSize)
+int ScrollbarThemeWin::scrollbarThickness(ScrollbarControlSize controlSize)
 {
     static int thickness;
     if (!thickness) {
@@ -70,12 +69,12 @@
     return thickness;
 }
 
-bool ScrollbarThemeChromiumWin::invalidateOnMouseEnterExit()
+bool ScrollbarThemeWin::invalidateOnMouseEnterExit()
 {
     return windowsVersion() >= WindowsVista;
 }
 
-bool ScrollbarThemeChromiumWin::shouldSnapBackToDragOrigin(ScrollbarThemeClient* scrollbar, const PlatformMouseEvent& evt)
+bool ScrollbarThemeWin::shouldSnapBackToDragOrigin(ScrollbarThemeClient* scrollbar, const PlatformMouseEvent& evt)
 {
     // Find the rect within which we shouldn't snap, by expanding the track rect
     // in both dimensions.
@@ -93,7 +92,7 @@
     return !rect.contains(mousePosition);
 }
 
-void ScrollbarThemeChromiumWin::paintTrackPiece(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart partType)
+void ScrollbarThemeWin::paintTrackPiece(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart partType)
 {
     bool horz = scrollbar->orientation() == HorizontalScrollbar;
 
@@ -110,7 +109,7 @@
     WebKit::Platform::current()->themeEngine()->paintScrollbarTrack(canvas, partId, getThemeState(scrollbar, partType), getClassicThemeState(scrollbar, partType), WebKit::WebRect(rect), WebKit::WebRect(alignRect));
 }
 
-void ScrollbarThemeChromiumWin::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
+void ScrollbarThemeWin::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
 {
     bool horz = scrollbar->orientation() == HorizontalScrollbar;
 
@@ -125,7 +124,7 @@
     WebKit::Platform::current()->themeEngine()->paintScrollbarArrow(canvas, getThemeArrowState(scrollbar, part), partId | getClassicThemeState(scrollbar, part), WebKit::WebRect(rect));
 }
 
-void ScrollbarThemeChromiumWin::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
+void ScrollbarThemeWin::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
     bool horz = scrollbar->orientation() == HorizontalScrollbar;
 
@@ -137,10 +136,10 @@
     WebKit::Platform::current()->themeEngine()->paintScrollbarThumb(canvas, horz ? SBP_GRIPPERHORZ : SBP_GRIPPERVERT, getThemeState(scrollbar, ThumbPart), getClassicThemeState(scrollbar, ThumbPart), WebKit::WebRect(rect));
 }
 
-int ScrollbarThemeChromiumWin::getThemeState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
+int ScrollbarThemeWin::getThemeState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
 {
     // When dragging the thumb, draw thumb pressed and other segments normal
-    // regardless of where the cursor actually is.  See also four places in
+    // regardless of where the cursor actually is. See also four places in
     // getThemeArrowState().
     if (scrollbar->pressedPart() == ThumbPart) {
         if (part == ThumbPart)
@@ -156,7 +155,7 @@
     return (scrollbar->pressedPart() == part) ? SCRBS_PRESSED : SCRBS_NORMAL;
 }
 
-int ScrollbarThemeChromiumWin::getThemeArrowState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
+int ScrollbarThemeWin::getThemeArrowState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
 {
     // We could take advantage of knowing the values in the state enum to write
     // some simpler code, but treating the state enum as a black box seems
@@ -206,7 +205,7 @@
     return (scrollbar->pressedPart() == part) ? ABS_DOWNPRESSED : ABS_DOWNNORMAL;
 }
 
-int ScrollbarThemeChromiumWin::getClassicThemeState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
+int ScrollbarThemeWin::getClassicThemeState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
 {
     // When dragging the thumb, draw the buttons normal even when hovered.
     if (scrollbar->pressedPart() == ThumbPart)
@@ -220,24 +219,24 @@
     return (scrollbar->pressedPart() == part) ? (DFCS_PUSHED | DFCS_FLAT) : 0;
 }
 
-bool ScrollbarThemeChromiumWin::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
+bool ScrollbarThemeWin::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
 {
     return evt.shiftKey() && evt.button() == LeftButton;
 }
 
-IntSize ScrollbarThemeChromiumWin::buttonSize(ScrollbarThemeClient* scrollbar)
+IntSize ScrollbarThemeWin::buttonSize(ScrollbarThemeClient* scrollbar)
 {
     // Our desired rect is essentially thickness by thickness.
 
     // Our actual rect will shrink to half the available space when we have < 2
-    // times thickness pixels left.  This allows the scrollbar to scale down
+    // times thickness pixels left. This allows the scrollbar to scale down
     // and function even at tiny sizes.
 
     int thickness = scrollbarThickness(scrollbar->controlSize());
 
     // In layout test mode, we force the button "girth" (i.e., the length of
     // the button along the axis of the scrollbar) to be a fixed size.
-    // FIXME: This is retarded!  scrollbarThickness is already fixed in layout
+    // FIXME: This is retarded! scrollbarThickness is already fixed in layout
     // test mode so that should be enough to result in repeatable results, but
     // preserving this hack avoids having to rebaseline pixel tests.
     const int kLayoutTestModeGirth = 17;
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumWin.h b/Source/core/platform/ScrollbarThemeWin.h
similarity index 92%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumWin.h
rename to Source/core/platform/ScrollbarThemeWin.h
index ba8deaf..5b5ee6e 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumWin.h
+++ b/Source/core/platform/ScrollbarThemeWin.h
@@ -28,14 +28,14 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumWin_h
-#define ScrollbarThemeChromiumWin_h
+#ifndef ScrollbarThemeWin_h
+#define ScrollbarThemeWin_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "core/platform/ScrollbarThemeNonMacCommon.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumWin : public ScrollbarThemeChromium {
+class ScrollbarThemeWin : public ScrollbarThemeNonMacCommon {
 public:
     virtual int scrollbarThickness(ScrollbarControlSize) OVERRIDE;
     virtual bool invalidateOnMouseEnterExit() OVERRIDE;
diff --git a/Source/core/platform/Widget.h b/Source/core/platform/Widget.h
index 6a871a3..0454440 100644
--- a/Source/core/platform/Widget.h
+++ b/Source/core/platform/Widget.h
@@ -130,9 +130,6 @@
     // A means to access the AX cache when this object can get a pointer to it.
     virtual AXObjectCache* axObjectCache() const { return 0; }
 
-    // Notifies this widget that it will no longer be receiving events.
-    virtual void eventListenersRemoved() { }
-
 private:
     ScrollView* m_parent;
     IntRect m_frame;
diff --git a/Source/core/platform/animation/AnimationUtilities.h b/Source/core/platform/animation/AnimationUtilities.h
index 4cdc829..4c86e77 100644
--- a/Source/core/platform/animation/AnimationUtilities.h
+++ b/Source/core/platform/animation/AnimationUtilities.h
@@ -39,7 +39,7 @@
 
 inline unsigned blend(unsigned from, unsigned to, double progress)
 {
-    return lround(to > from ? from + (to - from) * progress : from - (from - to) * progress);
+    return clampTo<unsigned>(round(to > from ? from + (to - from) * progress : from - (from - to) * progress));
 }
 
 inline double blend(double from, double to, double progress)
diff --git a/Source/core/platform/animation/CSSAnimationData.h b/Source/core/platform/animation/CSSAnimationData.h
index f8c441c..a8ab459 100644
--- a/Source/core/platform/animation/CSSAnimationData.h
+++ b/Source/core/platform/animation/CSSAnimationData.h
@@ -148,7 +148,7 @@
 
 private:
     CSSAnimationData();
-    CSSAnimationData(const CSSAnimationData& o);
+    explicit CSSAnimationData(const CSSAnimationData&);
 
     AtomicString m_name;
     CSSPropertyID m_property;
diff --git a/Source/core/platform/animation/CSSAnimationDataList.h b/Source/core/platform/animation/CSSAnimationDataList.h
index bd7d942..48d8556 100644
--- a/Source/core/platform/animation/CSSAnimationDataList.h
+++ b/Source/core/platform/animation/CSSAnimationDataList.h
@@ -35,7 +35,7 @@
     WTF_MAKE_FAST_ALLOCATED;
 public:
     CSSAnimationDataList() { }
-    CSSAnimationDataList(const CSSAnimationDataList&);
+    explicit CSSAnimationDataList(const CSSAnimationDataList&);
 
     void fillUnsetProperties();
     bool operator==(const CSSAnimationDataList& o) const;
diff --git a/Source/core/platform/audio/FFTFrame.h b/Source/core/platform/audio/FFTFrame.h
index 65ae060..8e473f8 100644
--- a/Source/core/platform/audio/FFTFrame.h
+++ b/Source/core/platform/audio/FFTFrame.h
@@ -44,7 +44,6 @@
 #if !USE_ACCELERATE_FFT
 
 #if USE(WEBAUDIO_OPENMAX_DL_FFT)
-#include "dl/sp/api/armSP.h"
 #include "dl/sp/api/omxSP.h"
 #elif USE(WEBAUDIO_FFMPEG)
 struct RDFTContext;
diff --git a/Source/core/platform/chromium/ChromiumDataObject.cpp b/Source/core/platform/chromium/ChromiumDataObject.cpp
index 2c7fa16..a9a536d 100644
--- a/Source/core/platform/chromium/ChromiumDataObject.cpp
+++ b/Source/core/platform/chromium/ChromiumDataObject.cpp
@@ -90,18 +90,24 @@
     m_itemList.clear();
 }
 
-void ChromiumDataObject::add(const String& data, const String& type, ExceptionState& es)
+PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(const String& data, const String& type, ExceptionState& es)
 {
-    if (!internalAddStringItem(ChromiumDataObjectItem::createFromString(type, data)))
+    RefPtr<ChromiumDataObjectItem> item = ChromiumDataObjectItem::createFromString(type, data);
+    if (!internalAddStringItem(item)) {
         es.throwDOMException(NotSupportedError);
+        return 0;
+    }
+    return item;
 }
 
-void ChromiumDataObject::add(PassRefPtr<File> file, ScriptExecutionContext* context)
+PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(PassRefPtr<File> file, ScriptExecutionContext* context)
 {
     if (!file)
-        return;
+        return 0;
 
-    m_itemList.append(ChromiumDataObjectItem::createFromFile(file));
+    RefPtr<ChromiumDataObjectItem> item = ChromiumDataObjectItem::createFromFile(file);
+    m_itemList.append(item);
+    return item;
 }
 
 void ChromiumDataObject::clearData(const String& type)
diff --git a/Source/core/platform/chromium/ChromiumDataObject.h b/Source/core/platform/chromium/ChromiumDataObject.h
index 0406317..dfb9a75 100644
--- a/Source/core/platform/chromium/ChromiumDataObject.h
+++ b/Source/core/platform/chromium/ChromiumDataObject.h
@@ -62,8 +62,8 @@
     // FIXME: Implement V8DataTransferItemList::indexedPropertyDeleter to get this called.
     void deleteItem(unsigned long index);
     void clearAll();
-    void add(const String& data, const String& type, ExceptionState&);
-    void add(PassRefPtr<File>, ScriptExecutionContext*);
+    PassRefPtr<ChromiumDataObjectItem> add(const String& data, const String& type, ExceptionState&);
+    PassRefPtr<ChromiumDataObjectItem> add(PassRefPtr<File>, ScriptExecutionContext*);
 
     // WebCore helpers.
     void clearData(const String& type);
diff --git a/Source/core/platform/chromium/ClipboardChromium.cpp b/Source/core/platform/chromium/ClipboardChromium.cpp
index 50e69e5..48b258c 100644
--- a/Source/core/platform/chromium/ClipboardChromium.cpp
+++ b/Source/core/platform/chromium/ClipboardChromium.cpp
@@ -35,9 +35,9 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/StringCallback.h"
 #include "core/editing/markup.h"
+#include "core/fetch/ImageResource.h"
 #include "core/fileapi/File.h"
 #include "core/fileapi/FileList.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/platform/DragData.h"
 #include "core/platform/MIMETypeRegistry.h"
@@ -64,8 +64,8 @@
     virtual PassRefPtr<DataTransferItem> item(unsigned long index) OVERRIDE;
     virtual void deleteItem(unsigned long index, ExceptionState&) OVERRIDE;
     virtual void clear() OVERRIDE;
-    virtual void add(const String& data, const String& type, ExceptionState&) OVERRIDE;
-    virtual void add(PassRefPtr<File>) OVERRIDE;
+    virtual PassRefPtr<DataTransferItem> add(const String& data, const String& type, ExceptionState&) OVERRIDE;
+    virtual PassRefPtr<DataTransferItem> add(PassRefPtr<File>) OVERRIDE;
 
 private:
     DataTransferItemListPolicyWrapper(PassRefPtr<ClipboardChromium>, PassRefPtr<ChromiumDataObject>);
@@ -119,18 +119,24 @@
     m_dataObject->clearAll();
 }
 
-void DataTransferItemListPolicyWrapper::add(const String& data, const String& type, ExceptionState& es)
+PassRefPtr<DataTransferItem> DataTransferItemListPolicyWrapper::add(const String& data, const String& type, ExceptionState& es)
 {
     if (!m_clipboard->canWriteData())
-        return;
-    m_dataObject->add(data, type, es);
+        return 0;
+    RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(data, type, es);
+    if (!item)
+        return 0;
+    return DataTransferItemPolicyWrapper::create(m_clipboard, item);
 }
 
-void DataTransferItemListPolicyWrapper::add(PassRefPtr<File> file)
+PassRefPtr<DataTransferItem> DataTransferItemListPolicyWrapper::add(PassRefPtr<File> file)
 {
     if (!m_clipboard->canWriteData())
-        return;
-    m_dataObject->add(file, m_clipboard->frame()->document()->scriptExecutionContext());
+        return 0;
+    RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(file, m_clipboard->frame()->document()->scriptExecutionContext());
+    if (!item)
+        return 0;
+    return DataTransferItemPolicyWrapper::create(m_clipboard, item);
 }
 
 DataTransferItemListPolicyWrapper::DataTransferItemListPolicyWrapper(
diff --git a/Source/core/platform/chromium/ClipboardChromium.h b/Source/core/platform/chromium/ClipboardChromium.h
index 980a22d..4cc1416 100644
--- a/Source/core/platform/chromium/ClipboardChromium.h
+++ b/Source/core/platform/chromium/ClipboardChromium.h
@@ -32,7 +32,7 @@
 
 #include "core/dom/Clipboard.h"
 #include "core/dom/DataTransferItem.h"
-#include "core/loader/cache/ImageResourceClient.h"
+#include "core/fetch/ImageResourceClient.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/chromium/support/WebCrypto.cpp b/Source/core/platform/chromium/support/WebCrypto.cpp
index 9f63634..cd4e179 100644
--- a/Source/core/platform/chromium/support/WebCrypto.cpp
+++ b/Source/core/platform/chromium/support/WebCrypto.cpp
@@ -29,92 +29,56 @@
  */
 
 #include "config.h"
+#include "public/platform/WebArrayBuffer.h"
 #include "public/platform/WebCrypto.h"
+#include <string.h>
 
 namespace WebKit {
 
-// FIXME: Assert that these methods are called from the right thread.
-
-void WebCryptoOperationResult::initializationFailed()
-{
-    m_impl->initializationFailed();
-    reset();
-}
-
-void WebCryptoOperationResult::initializationSucceeded(WebCryptoOperation* op)
-{
-    m_impl->initializationSucceeded(op);
-    reset();
-}
-
-void WebCryptoOperationResult::completeWithError()
+void WebCryptoResult::completeWithError()
 {
     m_impl->completeWithError();
     reset();
 }
 
-void WebCryptoOperationResult::completeWithArrayBuffer(const WebArrayBuffer& buffer)
+void WebCryptoResult::completeWithBuffer(const WebArrayBuffer& buffer)
 {
-    m_impl->completeWithArrayBuffer(buffer);
+    RELEASE_ASSERT(!buffer.isNull());
+    m_impl->completeWithBuffer(buffer);
     reset();
 }
 
-void WebCryptoOperationResult::completeWithBoolean(bool b)
+void WebCryptoResult::completeWithBuffer(const void* bytes, size_t bytesSize)
+{
+    WebArrayBuffer buffer = WebKit::WebArrayBuffer::create(bytesSize, 1);
+    RELEASE_ASSERT(!buffer.isNull());
+    memcpy(buffer.data(), bytes, bytesSize);
+    completeWithBuffer(buffer);
+}
+
+void WebCryptoResult::completeWithBoolean(bool b)
 {
     m_impl->completeWithBoolean(b);
     reset();
 }
 
-void WebCryptoOperationResult::reset()
-{
-    m_impl.reset();
-}
-
-void WebCryptoOperationResult::assign(const WebCryptoOperationResult& o)
-{
-    m_impl = o.m_impl;
-}
-
-void WebCryptoOperationResult::assign(WebCryptoOperationResultPrivate* impl)
-{
-    m_impl = impl;
-}
-
-void WebCryptoKeyOperationResult::initializationFailed()
-{
-    m_impl->initializationFailed();
-    reset();
-}
-
-void WebCryptoKeyOperationResult::initializationSucceeded(WebCryptoKeyOperation* op)
-{
-    m_impl->initializationSucceeded(op);
-    reset();
-}
-
-void WebCryptoKeyOperationResult::completeWithError()
-{
-    m_impl->completeWithError();
-    reset();
-}
-
-void WebCryptoKeyOperationResult::completeWithKey(const WebCryptoKey& key)
+void WebCryptoResult::completeWithKey(const WebCryptoKey& key)
 {
     m_impl->completeWithKey(key);
     reset();
 }
 
-void WebCryptoKeyOperationResult::reset()
+void WebCryptoResult::reset()
 {
     m_impl.reset();
 }
 
-void WebCryptoKeyOperationResult::assign(const WebCryptoKeyOperationResult& o)
+void WebCryptoResult::assign(const WebCryptoResult& o)
 {
     m_impl = o.m_impl;
 }
 
-void WebCryptoKeyOperationResult::assign(WebCryptoKeyOperationResultPrivate* impl)
+void WebCryptoResult::assign(WebCryptoResultPrivate* impl)
 {
     m_impl = impl;
 }
diff --git a/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp b/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
index 891cb10..fe8ff81 100644
--- a/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
+++ b/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
@@ -99,6 +99,13 @@
     return 0;
 }
 
+WebCryptoHmacKeyParams* WebCryptoAlgorithm::hmacKeyParams() const
+{
+    if (paramsType() == WebCryptoAlgorithmParamsTypeHmacKeyParams)
+        return static_cast<WebCryptoHmacKeyParams*>(m_private->params.get());
+    return 0;
+}
+
 WebCryptoRsaSsaParams* WebCryptoAlgorithm::rsaSsaParams() const
 {
     if (paramsType() == WebCryptoAlgorithmParamsTypeRsaSsaParams)
diff --git a/Source/core/platform/graphics/ANGLEWebKitBridge.cpp b/Source/core/platform/graphics/ANGLEWebKitBridge.cpp
index ac7820e..4b5021d 100644
--- a/Source/core/platform/graphics/ANGLEWebKitBridge.cpp
+++ b/Source/core/platform/graphics/ANGLEWebKitBridge.cpp
@@ -30,12 +30,7 @@
 
 namespace WebCore {
 
-// Temporary typedef to support an incompatible change in the ANGLE API.
-#if !defined(ANGLE_SH_VERSION) || ANGLE_SH_VERSION < 108
-typedef int ANGLEGetInfoType;
-#else
 typedef size_t ANGLEGetInfoType;
-#endif
 
 inline static ANGLEGetInfoType getValidationResultValue(const ShHandle compiler, ShShaderInfo shaderInfo)
 {
@@ -80,11 +75,19 @@
         switch (symbolType) {
         case SH_ACTIVE_ATTRIBUTES:
             symbol.symbolType = SHADER_SYMBOL_TYPE_ATTRIBUTE;
-            ShGetActiveAttrib(compiler, i, &nameLength, &symbol.size, &symbol.dataType, nameBuffer.data(), mappedNameBuffer.data());
+#if ANGLE_SH_VERSION >= 112
+            ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, &symbol.staticUse, nameBuffer.data(), mappedNameBuffer.data());
+#else
+            ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, nameBuffer.data(), mappedNameBuffer.data());
+#endif
             break;
         case SH_ACTIVE_UNIFORMS:
             symbol.symbolType = SHADER_SYMBOL_TYPE_UNIFORM;
-            ShGetActiveUniform(compiler, i, &nameLength, &symbol.size, &symbol.dataType, nameBuffer.data(), mappedNameBuffer.data());
+#if ANGLE_SH_VERSION >= 112
+            ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, &symbol.staticUse, nameBuffer.data(), mappedNameBuffer.data());
+#else
+            ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, nameBuffer.data(), mappedNameBuffer.data());
+#endif
             break;
         default:
             ASSERT_NOT_REACHED();
@@ -187,7 +190,11 @@
 
     const char* const shaderSourceStrings[] = { shaderSource };
 
+#if ANGLE_SH_VERSION >= 111
+    bool validateSuccess = ShCompile(compiler, shaderSourceStrings, 1, SH_OBJECT_CODE | SH_VARIABLES | extraCompileOptions);
+#else
     bool validateSuccess = ShCompile(compiler, shaderSourceStrings, 1, SH_OBJECT_CODE | SH_ATTRIBUTES_UNIFORMS | extraCompileOptions);
+#endif
     if (!validateSuccess) {
         int logSize = getValidationResultValue(compiler, SH_INFO_LOG_LENGTH);
         if (logSize > 1) {
diff --git a/Source/core/platform/graphics/ANGLEWebKitBridge.h b/Source/core/platform/graphics/ANGLEWebKitBridge.h
index 143a15b..d41c830 100644
--- a/Source/core/platform/graphics/ANGLEWebKitBridge.h
+++ b/Source/core/platform/graphics/ANGLEWebKitBridge.h
@@ -50,6 +50,10 @@
     ShDataType dataType;
     int size;
     bool isArray;
+    ShPrecisionType precision;
+#if ANGLE_SH_VERSION >= 112
+    int staticUse;
+#endif
 
     bool isSampler() const
     {
diff --git a/Source/core/platform/graphics/Font.cpp b/Source/core/platform/graphics/Font.cpp
index 481b6eb..740bd6b 100644
--- a/Source/core/platform/graphics/Font.cpp
+++ b/Source/core/platform/graphics/Font.cpp
@@ -694,4 +694,11 @@
     return true;
 }
 
+void Font::willUseFontData() const
+{
+    const FontFamily& family = fontDescription().family();
+    if (m_fontFallbackList && m_fontFallbackList->fontSelector() && !family.familyIsEmpty())
+        m_fontFallbackList->fontSelector()->willUseFontData(fontDescription(), family.family());
+}
+
 }
diff --git a/Source/core/platform/graphics/Font.h b/Source/core/platform/graphics/Font.h
index bd7a19d..3c57abc 100644
--- a/Source/core/platform/graphics/Font.h
+++ b/Source/core/platform/graphics/Font.h
@@ -235,6 +235,8 @@
     bool needsTranscoding() const { return m_needsTranscoding; }
     FontFallbackList* fontList() const { return m_fontFallbackList.get(); }
 
+    void willUseFontData() const;
+
 private:
     bool loadingCustomFonts() const
     {
diff --git a/Source/core/platform/graphics/FontCache.cpp b/Source/core/platform/graphics/FontCache.cpp
index aafd75f..49a1c41 100644
--- a/Source/core/platform/graphics/FontCache.cpp
+++ b/Source/core/platform/graphics/FontCache.cpp
@@ -340,6 +340,11 @@
     return result.get()->value.first;
 }
 
+bool FontCache::isPlatformFontAvailable(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName)
+{
+    return getFontResourcePlatformData(fontDescription, family, checkingAlternateName);
+}
+
 SimpleFontData* FontCache::getNonRetainedLastResortFallbackFont(const FontDescription& fontDescription)
 {
     return getLastResortFallbackFont(fontDescription, DoNotRetain).leakRef();
diff --git a/Source/core/platform/graphics/FontCache.h b/Source/core/platform/graphics/FontCache.h
index b268374..905f1cb 100644
--- a/Source/core/platform/graphics/FontCache.h
+++ b/Source/core/platform/graphics/FontCache.h
@@ -35,6 +35,7 @@
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
+#include "wtf/text/CString.h"
 #include "wtf/text/WTFString.h"
 #include "wtf/unicode/Unicode.h"
 
@@ -44,6 +45,8 @@
 #include <mlang.h>
 #endif
 
+class SkTypeface;
+
 namespace WebCore {
 
 class Font;
@@ -78,6 +81,7 @@
     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);
 
     void addClient(FontSelector*);
     void removeClient(FontSelector*);
@@ -126,6 +130,9 @@
     PassRefPtr<SimpleFontData> getSimilarFontPlatformData(const Font&);
     FontPlatformData* createFontPlatformData(const FontDescription&, const AtomicString& family);
 
+    // Implemented on skia platforms.
+    SkTypeface* createTypeface(const FontDescription&, const AtomicString& family, CString& name);
+
     PassRefPtr<SimpleFontData> getFontResourceData(const FontPlatformData*, ShouldRetain = Retain);
     const FontPlatformData* getFallbackFontData(const FontDescription&);
 
diff --git a/Source/core/platform/graphics/FontPlatformData.h b/Source/core/platform/graphics/FontPlatformData.h
index 606c917..fee50e4 100644
--- a/Source/core/platform/graphics/FontPlatformData.h
+++ b/Source/core/platform/graphics/FontPlatformData.h
@@ -107,6 +107,7 @@
     bool allowsLigatures() const;
 #endif
 
+    String fontFamilyName() const;
     bool isFixedPitch() const;
     float size() const { return m_size; }
     void setSize(float size) { m_size = size; }
diff --git a/Source/core/platform/graphics/FontSelector.h b/Source/core/platform/graphics/FontSelector.h
index 69dc632..1225ffc 100644
--- a/Source/core/platform/graphics/FontSelector.h
+++ b/Source/core/platform/graphics/FontSelector.h
@@ -40,6 +40,7 @@
 public:
     virtual ~FontSelector() { }
     virtual PassRefPtr<FontData> getFontData(const FontDescription&, const AtomicString& familyName) = 0;
+    virtual void willUseFontData(const FontDescription&, const AtomicString& familyName) = 0;
 
     virtual void fontCacheInvalidated() { }
 
diff --git a/Source/core/platform/graphics/GraphicsContextStateSaver.h b/Source/core/platform/graphics/GraphicsContextStateSaver.h
index 68f80b4..c4b0be5 100644
--- a/Source/core/platform/graphics/GraphicsContextStateSaver.h
+++ b/Source/core/platform/graphics/GraphicsContextStateSaver.h
@@ -65,6 +65,7 @@
     }
 
     GraphicsContext* context() const { return &m_context; }
+    bool saved() const { return m_saveAndRestore; }
 
 private:
     GraphicsContext& m_context;
diff --git a/Source/core/platform/graphics/GraphicsLayer.cpp b/Source/core/platform/graphics/GraphicsLayer.cpp
index cce5cba..60d7c82 100644
--- a/Source/core/platform/graphics/GraphicsLayer.cpp
+++ b/Source/core/platform/graphics/GraphicsLayer.cpp
@@ -137,6 +137,7 @@
     m_opaqueRectTrackingContentLayerDelegate = adoptPtr(new OpaqueRectTrackingContentLayerDelegate(this));
     m_layer = adoptPtr(Platform::current()->compositorSupport()->createContentLayer(m_opaqueRectTrackingContentLayerDelegate.get()));
     m_layer->layer()->setDrawsContent(m_drawsContent && m_contentsVisible);
+    m_layer->layer()->setWebLayerClient(this);
     m_layer->setAutomaticallyComputeRasterScale(true);
 }
 
@@ -512,21 +513,6 @@
     return firstIndex;
 }
 
-void GraphicsLayer::updateNames()
-{
-    String debugName = "Layer for " + m_nameBase;
-    m_layer->layer()->setDebugName(debugName);
-
-    if (WebLayer* contentsLayer = contentsLayerIfRegistered()) {
-        String debugName = "ContentsLayer for " + m_nameBase;
-        contentsLayer->setDebugName(debugName);
-    }
-    if (m_linkHighlight) {
-        String debugName = "LinkHighlight for " + m_nameBase;
-        m_linkHighlight->layer()->setDebugName(debugName);
-    }
-}
-
 void GraphicsLayer::updateChildList()
 {
     WebLayer* childHost = m_layer->layer();
@@ -632,6 +618,7 @@
     m_contentsLayerId = m_contentsLayer->id();
 
     if (m_contentsLayer) {
+        m_contentsLayer->setWebLayerClient(this);
         m_contentsLayer->setAnchorPoint(FloatPoint(0, 0));
         m_contentsLayer->setUseParentBackfaceVisibility(true);
 
@@ -643,7 +630,6 @@
         // shadow content that must display in front of the video.
         m_layer->layer()->insertChild(m_contentsLayer, 0);
     }
-    updateNames();
 }
 
 void GraphicsLayer::clearContentsLayerIfUnregistered()
@@ -705,7 +691,7 @@
 
     if (flags & LayerTreeIncludesDebugInfo) {
         ts << " " << static_cast<void*>(const_cast<GraphicsLayer*>(this));
-        ts << " \"" << m_name << "\"";
+        ts << " \"" << m_client->debugName(this) << "\"";
     }
 
     ts << "\n";
@@ -885,11 +871,22 @@
     return ts.release();
 }
 
-void GraphicsLayer::setName(const String& name)
+WebKit::WebString GraphicsLayer::debugName(WebKit::WebLayer* webLayer)
 {
-    m_nameBase = name;
-    m_name = String::format("GraphicsLayer(%p) ", this) + name;
-    updateNames();
+    String name;
+    if (!m_client)
+        return name;
+
+    if (webLayer == m_contentsLayer) {
+        name = "ContentsLayer for " + m_client->debugName(this);
+    } else if (m_linkHighlight && webLayer == m_linkHighlight->layer()) {
+        name = "LinkHighlight for " + m_client->debugName(this);
+    } else if (webLayer == m_layer->layer()) {
+        name = m_client->debugName(this);
+    } else {
+        ASSERT_NOT_REACHED();
+    }
+    return name;
 }
 
 void GraphicsLayer::setCompositingReasons(WebKit::WebCompositingReasons reasons)
@@ -1266,6 +1263,8 @@
 void GraphicsLayer::setLinkHighlight(LinkHighlightClient* linkHighlight)
 {
     m_linkHighlight = linkHighlight;
+    if (m_linkHighlight)
+        m_linkHighlight->layer()->setWebLayerClient(this);
     updateChildList();
 }
 
diff --git a/Source/core/platform/graphics/GraphicsLayer.h b/Source/core/platform/graphics/GraphicsLayer.h
index e4bb578..8196d29 100644
--- a/Source/core/platform/graphics/GraphicsLayer.h
+++ b/Source/core/platform/graphics/GraphicsLayer.h
@@ -46,6 +46,7 @@
 #include "public/platform/WebCompositingReasons.h"
 #include "public/platform/WebContentLayer.h"
 #include "public/platform/WebImageLayer.h"
+#include "public/platform/WebLayerClient.h"
 #include "public/platform/WebLayerScrollClient.h"
 #include "public/platform/WebSolidColorLayer.h"
 
@@ -71,7 +72,7 @@
 class AnimationValue {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit AnimationValue(float keyTime, PassRefPtr<TimingFunction> timingFunction = 0)
+    explicit AnimationValue(double keyTime, PassRefPtr<TimingFunction> timingFunction = 0)
         : m_keyTime(keyTime)
         , m_timingFunction(timingFunction)
     {
@@ -79,12 +80,12 @@
 
     virtual ~AnimationValue() { }
 
-    float keyTime() const { return m_keyTime; }
+    double keyTime() const { return m_keyTime; }
     const TimingFunction* timingFunction() const { return m_timingFunction.get(); }
     virtual PassOwnPtr<AnimationValue> clone() const = 0;
 
 private:
-    float m_keyTime;
+    double m_keyTime;
     RefPtr<TimingFunction> m_timingFunction;
 };
 
@@ -92,7 +93,7 @@
 // FIXME: Should be moved to its own header file.
 class FloatAnimationValue : public AnimationValue {
 public:
-    FloatAnimationValue(float keyTime, float value, PassRefPtr<TimingFunction> timingFunction = 0)
+    FloatAnimationValue(double keyTime, float value, PassRefPtr<TimingFunction> timingFunction = 0)
         : AnimationValue(keyTime, timingFunction)
         , m_value(value)
     {
@@ -109,7 +110,7 @@
 // FIXME: Should be moved to its own header file.
 class TransformAnimationValue : public AnimationValue {
 public:
-    explicit TransformAnimationValue(float keyTime, const TransformOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
+    explicit TransformAnimationValue(double keyTime, const TransformOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
         : AnimationValue(keyTime, timingFunction)
     {
         if (value)
@@ -127,7 +128,7 @@
 // FIXME: Should be moved to its own header file.
 class FilterAnimationValue : public AnimationValue {
 public:
-    explicit FilterAnimationValue(float keyTime, const FilterOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
+    explicit FilterAnimationValue(double keyTime, const FilterOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
         : AnimationValue(keyTime, timingFunction)
     {
         if (value)
@@ -198,7 +199,7 @@
 // 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 {
+class GraphicsLayer : public GraphicsContextPainter, public WebKit::WebAnimationDelegate, public WebKit::WebLayerScrollClient, public WebKit::WebLayerClient {
     WTF_MAKE_NONCOPYABLE(GraphicsLayer); WTF_MAKE_FAST_ALLOCATED;
 public:
     enum ContentsLayerPurpose {
@@ -214,9 +215,8 @@
 
     GraphicsLayerClient* client() const { return m_client; }
 
-    // Layer name. Only used to identify layers in debug output
-    const String& name() const { return m_name; }
-    void setName(const String&);
+    // WebKit::WebLayerClient implementation.
+    virtual WebKit::WebString debugName(WebKit::WebLayer*) OVERRIDE;
 
     void setCompositingReasons(WebKit::WebCompositingReasons);
 
@@ -466,7 +466,6 @@
     void dumpAdditionalProperties(TextStream&, int /*indent*/, LayerTreeFlags) const { }
 
     // Helper functions used by settors to keep layer's the state consistent.
-    void updateNames();
     void updateChildList();
     void updateLayerIsDrawable();
     void updateContentsRect();
@@ -477,7 +476,6 @@
     WebKit::WebLayer* contentsLayerIfRegistered();
 
     GraphicsLayerClient* m_client;
-    String m_name;
 
     // Offset from the owning renderer
     IntSize m_offsetFromRenderer;
@@ -522,8 +520,6 @@
 
     int m_repaintCount;
 
-    String m_nameBase;
-
     Color m_contentsSolidColor;
 
     OwnPtr<WebKit::WebContentLayer> m_layer;
diff --git a/Source/core/platform/graphics/GraphicsLayerClient.h b/Source/core/platform/graphics/GraphicsLayerClient.h
index ecc9888..1728b43 100644
--- a/Source/core/platform/graphics/GraphicsLayerClient.h
+++ b/Source/core/platform/graphics/GraphicsLayerClient.h
@@ -26,6 +26,8 @@
 #ifndef GraphicsLayerClient_h
 #define GraphicsLayerClient_h
 
+#include "wtf/text/WTFString.h"
+
 namespace WebCore {
 
 class FloatPoint;
@@ -78,6 +80,8 @@
 
     virtual bool isTrackingRepaints() const { return false; }
 
+    virtual String debugName(const GraphicsLayer*) = 0;
+
 #ifndef NDEBUG
     // RenderLayerBacking overrides this to verify that it is not
     // currently painting contents. An ASSERT fails, if it is.
diff --git a/Source/core/platform/graphics/LayoutRect.cpp b/Source/core/platform/graphics/LayoutRect.cpp
index 05c7280..a3c0b00 100644
--- a/Source/core/platform/graphics/LayoutRect.cpp
+++ b/Source/core/platform/graphics/LayoutRect.cpp
@@ -115,6 +115,12 @@
     m_size.scale(s);
 }
 
+void LayoutRect::scale(float xAxisScale, float yAxisScale)
+{
+    m_location.scale(xAxisScale, yAxisScale);
+    m_size.scale(xAxisScale, yAxisScale);
+}
+
 LayoutRect unionRect(const Vector<LayoutRect>& rects)
 {
     LayoutRect result;
diff --git a/Source/core/platform/graphics/LayoutRect.h b/Source/core/platform/graphics/LayoutRect.h
index 2133977..dc46a9b 100644
--- a/Source/core/platform/graphics/LayoutRect.h
+++ b/Source/core/platform/graphics/LayoutRect.h
@@ -159,6 +159,7 @@
     }
     void inflate(LayoutUnit d) { inflateX(d); inflateY(d); }
     void scale(float s);
+    void scale(float xAxisScale, float yAxisScale);
 
     LayoutRect transposedRect() const { return LayoutRect(m_location.transposedPoint(), m_size.transposedSize()); }
 
diff --git a/Source/core/platform/graphics/LayoutSize.h b/Source/core/platform/graphics/LayoutSize.h
index 3bce732..3844e6b 100644
--- a/Source/core/platform/graphics/LayoutSize.h
+++ b/Source/core/platform/graphics/LayoutSize.h
@@ -39,6 +39,11 @@
 
 class LayoutPoint;
 
+enum AspectRatioFit {
+    AspectRatioFitShrink,
+    AspectRatioFitGrow
+};
+
 class LayoutSize {
 public:
     LayoutSize() : m_width(0), m_height(0) { }
@@ -112,6 +117,15 @@
         return LayoutSize(m_height, m_width);
     }
 
+    LayoutSize fitToAspectRatio(const LayoutSize& aspectRatio, AspectRatioFit fit) const
+    {
+        float heightScale = height().toFloat() / aspectRatio.height().toFloat();
+        float widthScale = width().toFloat() / aspectRatio.width().toFloat();
+        if ((widthScale > heightScale) != (fit == AspectRatioFitGrow))
+            return LayoutSize(height() * aspectRatio.width() / aspectRatio.height(), height());
+        return LayoutSize(width(), width() * aspectRatio.height() / aspectRatio.width());
+    }
+
 private:
     LayoutUnit m_width, m_height;
 };
diff --git a/Source/core/platform/graphics/MediaPlayer.h b/Source/core/platform/graphics/MediaPlayer.h
index 268cd97..9d36d1a 100644
--- a/Source/core/platform/graphics/MediaPlayer.h
+++ b/Source/core/platform/graphics/MediaPlayer.h
@@ -66,6 +66,8 @@
     // the play/pause status changed
     virtual void mediaPlayerPlaybackStateChanged() = 0;
 
+    virtual void mediaPlayerRequestSeek(double) = 0;
+
 // Presentation-related methods
     // a new frame of video is available
     virtual void mediaPlayerRepaint() = 0;
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
index 91a37d3..79b46e3 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
@@ -53,7 +53,7 @@
 {
     const float ts = m_size >= 0 ? m_size : 12;
     paint->setTextSize(SkFloatToScalar(m_size));
-    paint->setTypeface(m_typeface);
+    paint->setTypeface(typeface());
 }
 #endif
 
@@ -154,6 +154,7 @@
     , m_size(size)
     , m_orientation(Horizontal)
     , m_scriptCache(0)
+    , m_typeface(0)
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(false)
 {
@@ -181,6 +182,25 @@
 {
 }
 
+FontPlatformData::FontPlatformData(SkTypeface* tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation)
+    : m_font(0)
+    , m_size(textSize)
+    , m_orientation(orientation)
+    , m_scriptCache(0)
+    , m_typeface(tf)
+    , m_isHashTableDeletedValue(false)
+{
+    // FIXME: This can be removed together with m_font once the last few
+    // uses of hfont() has been eliminated.
+    LOGFONT logFont;
+    SkLOGFONTFromTypeface(tf, &logFont);
+    logFont.lfHeight = -textSize;
+    HFONT hFont = CreateFontIndirect(&logFont);
+    if (hFont)
+        m_font = RefCountedHFONT::create(hFont);
+    m_paintTextFlags = computePaintTextFlags(logFont);
+}
+
 FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data)
 {
     if (this != &data) {
@@ -204,6 +224,18 @@
     m_scriptCache = 0;
 }
 
+String FontPlatformData::fontFamilyName() const
+{
+    HWndDC dc(0);
+    HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont()));
+    WCHAR name[LF_FACESIZE];
+    unsigned resultLength = GetTextFace(dc, LF_FACESIZE, name);
+    if (resultLength > 0)
+        resultLength--; // ignore the null terminator
+    SelectObject(dc, oldFont);
+    return String(name, resultLength);
+}
+
 bool FontPlatformData::isFixedPitch() const
 {
 #if ENABLE(GDI_FONTS_ON_WINDOWS)
@@ -230,7 +262,7 @@
 
     return treatAsFixedPitch;
 #else
-    return typeface()->isFixedPitch();
+    return typeface() && typeface()->isFixedPitch();
 #endif
 }
 
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
index 6cb370d..e2a5c05 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
+++ b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
@@ -34,6 +34,7 @@
 
 #include "config.h"
 
+#include "../ports/SkTypeface_win.h"
 #include "SkPaint.h"
 #include "SkTypeface.h"
 #include "core/platform/SharedBuffer.h"
@@ -73,6 +74,7 @@
     FontPlatformData(float size, bool bold, bool oblique);
     FontPlatformData(const FontPlatformData&);
     FontPlatformData(const FontPlatformData&, float textSize);
+    FontPlatformData(SkTypeface*, const char* name, float textSize, bool fakeBold, bool fakeItalic, FontOrientation = Horizontal);
 
 #if !ENABLE(GDI_FONTS_ON_WINDOWS)
     void setupPaint(SkPaint*) const;
@@ -90,6 +92,8 @@
     SkTypeface* typeface() const { return m_typeface.get(); }
     int paintTextFlags() const { return m_paintTextFlags; }
 
+    String fontFamilyName() const;
+
     FontOrientation orientation() const { return m_orientation; }
     void setOrientation(FontOrientation orientation) { m_orientation = orientation; }
 
diff --git a/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp b/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp
index 5c32e12..c1265af 100644
--- a/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp
+++ b/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp
@@ -101,10 +101,6 @@
     cachedImage = tryToResumeDecodeAndScale(scaledSize, index);
     if (cachedImage)
         return cachedImage;
-
-    cachedImage = tryToDecodeAndScale(scaledSize, index);
-    if (cachedImage)
-        return cachedImage;
     return 0;
 }
 
@@ -147,20 +143,29 @@
 {
     TRACE_EVENT1("webkit", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));
 
-    ImageDecoder* cachedDecoder = 0;
+    ImageDecoder* decoder = 0;
+    const bool resumeDecoding = ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &decoder);
+    ASSERT(!resumeDecoding || decoder);
 
-    if (!ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &cachedDecoder))
+    OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &decoder);
+
+    if (!decoder)
         return 0;
-    ASSERT(cachedDecoder);
 
-    // Always generate a new image and insert it into cache.
-    OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &cachedDecoder);
+    // If we are not resuming decoding that means the decoder is freshly
+    // created and we have ownership. If we are resuming decoding then
+    // the decoder is owned by ImageDecodingStore.
+    OwnPtr<ImageDecoder> decoderContainer;
+    if (!resumeDecoding)
+        decoderContainer = adoptPtr(decoder);
 
     if (!fullSizeImage) {
         // If decode has failed and resulted an empty image we can save work
         // in the future by returning early.
-        m_decodeFailedAndEmpty = !m_isMultiFrame && cachedDecoder->failed();
-        ImageDecodingStore::instance()->unlockDecoder(this, cachedDecoder);
+        m_decodeFailedAndEmpty = !m_isMultiFrame && decoder->failed();
+
+        if (resumeDecoding)
+            ImageDecodingStore::instance()->unlockDecoder(this, decoder);
         return 0;
     }
 
@@ -169,42 +174,16 @@
     // If the image generated is complete then there is no need to keep
     // the decoder. The exception is multi-frame decoder which can generate
     // multiple complete frames.
-    if (cachedImage->isComplete() && !m_isMultiFrame)
-        ImageDecodingStore::instance()->removeDecoder(this, cachedDecoder);
-    else
-        ImageDecodingStore::instance()->unlockDecoder(this, cachedDecoder);
+    const bool removeDecoder = cachedImage->isComplete() && !m_isMultiFrame;
 
-    if (m_fullSize == scaledSize)
-        return cachedImage;
-    return tryToScale(cachedImage, scaledSize, index);
-}
-
-const ScaledImageFragment* ImageFrameGenerator::tryToDecodeAndScale(const SkISize& scaledSize, size_t index)
-{
-    TRACE_EVENT1("webkit", "ImageFrameGenerator::tryToDecodeAndScale", "index", static_cast<int>(index));
-
-    ImageDecoder* decoder = 0;
-    OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &decoder);
-
-    if (!decoder)
-        return 0;
-
-    OwnPtr<ImageDecoder> decoderContainer = adoptPtr(decoder);
-
-    if (!fullSizeImage) {
-        // If decode has failed and resulted an empty image we can save work
-        // in the future by returning early.
-        m_decodeFailedAndEmpty = !m_isMultiFrame && decoderContainer->failed();
-        return 0;
-    }
-
-    const ScaledImageFragment* cachedImage = ImageDecodingStore::instance()->insertAndLockCache(this, fullSizeImage.release());
-
-    // If image is complete then decoder is not needed in the future.
-    // Otherwise save the decoder for later use. The exception is
-    // multi-frame decoder which can generate multiple complete frames.
-    if (!cachedImage->isComplete() || m_isMultiFrame)
+    if (resumeDecoding) {
+        if (removeDecoder)
+            ImageDecodingStore::instance()->removeDecoder(this, decoder);
+        else
+            ImageDecodingStore::instance()->unlockDecoder(this, decoder);
+    } else if (!removeDecoder) {
         ImageDecodingStore::instance()->insertDecoder(this, decoderContainer.release(), DiscardablePixelRef::isDiscardable(cachedImage->bitmap().pixelRef()));
+    }
 
     if (m_fullSize == scaledSize)
         return cachedImage;
diff --git a/Source/core/platform/graphics/chromium/ImageFrameGenerator.h b/Source/core/platform/graphics/chromium/ImageFrameGenerator.h
index 6d0f35c..b3252e0 100644
--- a/Source/core/platform/graphics/chromium/ImageFrameGenerator.h
+++ b/Source/core/platform/graphics/chromium/ImageFrameGenerator.h
@@ -82,7 +82,6 @@
     const ScaledImageFragment* tryToLockCompleteCache(const SkISize& scaledSize, size_t index);
     const ScaledImageFragment* tryToScale(const ScaledImageFragment* fullSizeImage, const SkISize& scaledSize, size_t index);
     const ScaledImageFragment* tryToResumeDecodeAndScale(const SkISize& scaledSize, size_t index);
-    const ScaledImageFragment* tryToDecodeAndScale(const SkISize& scaledSize, size_t index);
 
     // Use the given decoder to decode. If a decoder is not given then try to create one.
     PassOwnPtr<ScaledImageFragment> decode(size_t index, ImageDecoder**);
diff --git a/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp b/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
index 4e04d87..e3f938e 100644
--- a/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
+++ b/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
@@ -92,7 +92,9 @@
 
     virtual ImageFrame::FrameStatus frameStatus()
     {
-        return m_frameStatus;
+        ImageFrame::FrameStatus currentStatus = m_frameStatus;
+        m_frameStatus = m_nextFrameStatus;
+        return currentStatus;
     }
 
     virtual size_t frameCount() { return 1; }
@@ -114,13 +116,15 @@
         m_generator->setData(m_data, false);
     }
 
-    void setFrameStatus(ImageFrame::FrameStatus status)  { m_frameStatus = status; }
+    void setFrameStatus(ImageFrame::FrameStatus status)  { m_frameStatus = m_nextFrameStatus = status; }
+    void setNextFrameStatus(ImageFrame::FrameStatus status)  { m_nextFrameStatus = status; }
 
     RefPtr<SharedBuffer> m_data;
     RefPtr<ImageFrameGenerator> m_generator;
     int m_decodersDestroyed;
     int m_frameBufferRequestCount;
     ImageFrame::FrameStatus m_frameStatus;
+    ImageFrame::FrameStatus m_nextFrameStatus;
 };
 
 PassOwnPtr<ImageDecoder> MockImageDecoderFactory::create()
@@ -392,7 +396,7 @@
     ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), tempDecoder);
 }
 
-TEST_F(ImageFrameGeneratorTest, resumeDecodeEmptyFrame)
+TEST_F(ImageFrameGeneratorTest, resumeDecodeEmptyFrameTurnsComplete)
 {
     m_generator = ImageFrameGenerator::create(fullSize(), m_data, false, true);
     m_generator->setImageDecoderFactoryForTesting(MockImageDecoderFactory::create(this));
@@ -403,6 +407,7 @@
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
 
     setFrameStatus(ImageFrame::FrameEmpty);
+    setNextFrameStatus(ImageFrame::FrameComplete);
     EXPECT_FALSE(m_generator->decodeAndScale(fullSize(), 1));
 }
 
diff --git a/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm b/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
index aa7a5e7..ab3caf3 100644
--- a/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
+++ b/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
@@ -234,6 +234,11 @@
     return descriptor;
 }
 
+String FontPlatformData::fontFamilyName() const
+{
+    return String(CTFontCopyDisplayName(ctFont()));
+}
+
 CTFontRef FontPlatformData::ctFont() const
 {
     if (m_CTFont)
diff --git a/Source/core/platform/graphics/filters/FilterOperation.h b/Source/core/platform/graphics/filters/FilterOperation.h
index 3473418..4e4a31a 100644
--- a/Source/core/platform/graphics/filters/FilterOperation.h
+++ b/Source/core/platform/graphics/filters/FilterOperation.h
@@ -26,7 +26,7 @@
 #ifndef FilterOperation_h
 #define FilterOperation_h
 
-#include "core/loader/cache/DocumentResourceReference.h"
+#include "core/fetch/DocumentResourceReference.h"
 #include "core/platform/Length.h"
 #include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/filters/Filter.h"
diff --git a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
index 1857d7d..83145c1 100644
--- a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
+++ b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
@@ -211,6 +211,15 @@
     return m_typeface->uniqueID();
 }
 
+String FontPlatformData::fontFamilyName() const
+{
+    SkTypeface::LocalizedStrings* fontFamilyIterator = this->typeface()->createFamilyNameIterator();
+    SkTypeface::LocalizedString localizedString;
+    while (fontFamilyIterator->next(&localizedString) && !localizedString.fString.size()) { }
+    fontFamilyIterator->unref();
+    return String(localizedString.fString.c_str());
+}
+
 bool FontPlatformData::operator==(const FontPlatformData& a) const
 {
     // If either of the typeface pointers are null then we test for pointer
diff --git a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
index 9d9ea6a..7f94d60 100644
--- a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
+++ b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
@@ -70,6 +70,8 @@
     FontPlatformData(const FontPlatformData& src, float textSize);
     ~FontPlatformData();
 
+    String fontFamilyName() const;
+
     // -------------------------------------------------------------------------
     // Return true iff this font is monospaced (i.e. every glyph has an equal x
     // advance)
diff --git a/Source/core/platform/graphics/skia/FontCacheSkia.cpp b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
index 14fafc3..cba5deb 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkia.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
@@ -46,6 +46,7 @@
 {
 }
 
+#if !OS(WINDOWS)
 PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 c)
 {
     icu::Locale locale = icu::Locale::getDefault();
@@ -83,6 +84,8 @@
     return getFontResourceData(&platformData, DoNotRetain);
 }
 
+#endif // !OS(WINDOWNS)
+
 PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
 {
     return 0;
@@ -107,11 +110,9 @@
     notImplemented();
 }
 
-FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription,
-                                                    const AtomicString& family)
+SkTypeface* FontCache::createTypeface(const FontDescription& fontDescription, const AtomicString& family, CString& name)
 {
-    const char* name = 0;
-    CString s;
+    name = "";
 
     // If we're creating a fallback font (e.g. "-webkit-monospace"), convert the name into
     // the fallback name (like "monospace") that fontconfig understands.
@@ -134,12 +135,9 @@
                 break;
             }
         }
-        if (!name)
-            name = "";
     } else {
         // convert the name to utf8
-        s = family.string().utf8();
-        name = s.data();
+        name = family.string().utf8();
     }
 
     int style = SkTypeface::kNormal;
@@ -148,19 +146,26 @@
     if (fontDescription.italic())
         style |= SkTypeface::kItalic;
 
-    SkTypeface* tf = SkTypeface::CreateFromName(name, static_cast<SkTypeface::Style>(style));
+    return SkTypeface::CreateFromName(name.data(), static_cast<SkTypeface::Style>(style));
+}
+
+#if !OS(WINDOWS)
+FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
+{
+    CString name;
+    SkTypeface* tf = createTypeface(fontDescription, family, name);
     if (!tf)
         return 0;
 
-    FontPlatformData* result =
-        new FontPlatformData(tf,
-                             name,
-                             fontDescription.computedSize(),
-                             (style & SkTypeface::kBold) && !tf->isBold(),
-                             (style & SkTypeface::kItalic) && !tf->isItalic(),
-                             fontDescription.orientation());
+    FontPlatformData* result = new FontPlatformData(tf,
+        name.data(),
+        fontDescription.computedSize(),
+        fontDescription.weight() >= FontWeightBold && !tf->isBold(),
+        fontDescription.italic() && !tf->isItalic(),
+        fontDescription.orientation());
     tf->unref();
     return result;
 }
+#endif // !OS(WINDOWNS)
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
new file mode 100644
index 0000000..1d504f8
--- /dev/null
+++ b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Computer, Inc.
+ * Copyright (c) 2006, 2007, 2008, 2009, 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/FontCache.h"
+
+#include "core/platform/NotImplemented.h"
+#include "core/platform/graphics/Font.h"
+#include "core/platform/graphics/SimpleFontData.h"
+#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
+
+namespace WebCore {
+
+static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character)
+{
+    char characters[2] = {character, 0};
+    return fontData->typeface()->charsToGlyphs(characters, SkTypeface::kUTF32_Encoding, 0, 1) == 1;
+}
+
+// Given the desired base font, this will create a SimpleFontData for a specific
+// font that can be used to render the given range of characters.
+PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC)
+{
+    // FIXME: We should fix getFallbackFamily to take a UChar32
+    // and remove this split-to-UChar16 code.
+    UChar codeUnits[2];
+    int codeUnitsLength;
+    if (inputC <= 0xFFFF) {
+        codeUnits[0] = inputC;
+        codeUnitsLength = 1;
+    } else {
+        codeUnits[0] = U16_LEAD(inputC);
+        codeUnits[1] = U16_TRAIL(inputC);
+        codeUnitsLength = 2;
+    }
+
+    // FIXME: Consider passing fontDescription.dominantScript()
+    // to GetFallbackFamily here.
+    FontDescription fontDescription = font.fontDescription();
+    UChar32 c;
+    UScriptCode script;
+    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);
+
+    // Last resort font list : PanUnicode. CJK fonts have a pretty
+    // large repertoire. Eventually, we need to scan all the fonts
+    // on the system to have a Firefox-like coverage.
+    // Make sure that all of them are lowercased.
+    const static wchar_t* const cjkFonts[] = {
+        L"arial unicode ms",
+        L"ms pgothic",
+        L"simsun",
+        L"gulim",
+        L"pmingliu",
+        L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
+        L"ar pl shanheisun uni",
+        L"ar pl zenkai uni",
+        L"han nom a", // Complete CJK Ext. A coverage.
+        L"code2000" // Complete CJK Ext. A coverage.
+        // CJK Ext. B fonts are not listed here because it's of no use
+        // with our current non-BMP character handling because we use
+        // Uniscribe for it and that code path does not go through here.
+    };
+
+    const static wchar_t* const commonFonts[] = {
+        L"tahoma",
+        L"arial unicode ms",
+        L"lucida sans unicode",
+        L"microsoft sans serif",
+        L"palatino linotype",
+        // Six fonts below (and code2000 at the end) are not from MS, but
+        // once installed, cover a very wide range of characters.
+        L"dejavu serif",
+        L"dejavu sasns",
+        L"freeserif",
+        L"freesans",
+        L"gentium",
+        L"gentiumalt",
+        L"ms pgothic",
+        L"simsun",
+        L"gulim",
+        L"pmingliu",
+        L"code2000"
+    };
+
+    const wchar_t* const* panUniFonts = 0;
+    int numFonts = 0;
+    if (script == USCRIPT_HAN) {
+        panUniFonts = cjkFonts;
+        numFonts = WTF_ARRAY_LENGTH(cjkFonts);
+    } else {
+        panUniFonts = commonFonts;
+        numFonts = WTF_ARRAY_LENGTH(commonFonts);
+    }
+    // Font returned from GetFallbackFamily may not cover |characters|
+    // because it's based on script to font mapping. This problem is
+    // critical enough for non-Latin scripts (especially Han) to
+    // warrant an additional (real coverage) check with fontCotainsCharacter.
+    int i;
+    for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
+        family = panUniFonts[i];
+        data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
+    }
+    // When i-th font (0-base) in |panUniFonts| contains a character and
+    // we get out of the loop, |i| will be |i + 1|. That is, if only the
+    // last font in the array covers the character, |i| will be numFonts.
+    // So, we have to use '<=" rather than '<' to see if we found a font
+    // covering the character.
+    if (i <= numFonts)
+        return getFontResourceData(data, DoNotRetain);
+
+    return 0;
+}
+
+static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
+{
+    SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
+    bool matchesRequestedFamily = false;
+    SkTypeface::LocalizedString actualFamily;
+
+    while (actualFamilies->next(&actualFamily)) {
+        if (equalIgnoringCase(family, actualFamily.fString.c_str())) {
+            matchesRequestedFamily = true;
+            break;
+        }
+    }
+    actualFamilies->unref();
+
+    return matchesRequestedFamily;
+}
+
+FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
+{
+    CString name;
+    SkTypeface* tf = createTypeface(fontDescription, family, name);
+    if (!tf)
+        return 0;
+
+    // Windows will always give us a valid pointer here, even if the face name
+    // is non-existent. We have to double-check and see if the family name was
+    // really used.
+    // FIXME: Do we need to use predefined fonts "guaranteed" to exist
+    // when we're running in layout-test mode?
+    if (!typefacesMatchesFamily(tf, family)) {
+        tf->unref();
+        return 0;
+    }
+
+    FontPlatformData* result = new FontPlatformData(tf,
+        name.data(),
+        fontDescription.computedSize(),
+        fontDescription.weight() >= FontWeightBold && !tf->isBold(),
+        fontDescription.italic() && !tf->isItalic(),
+        fontDescription.orientation());
+    tf->unref();
+    return result;
+}
+
+}
diff --git a/Source/core/platform/graphics/transforms/TransformOperations.cpp b/Source/core/platform/graphics/transforms/TransformOperations.cpp
index bcca502..3ca3d7f 100644
--- a/Source/core/platform/graphics/transforms/TransformOperations.cpp
+++ b/Source/core/platform/graphics/transforms/TransformOperations.cpp
@@ -108,4 +108,12 @@
     return blendByUsingMatrixInterpolation(from, progress);
 }
 
+TransformOperations TransformOperations::add(const TransformOperations& addend) const
+{
+    TransformOperations result;
+    result.m_operations = operations();
+    result.m_operations.append(addend.operations());
+    return result;
+}
+
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/TransformOperations.h b/Source/core/platform/graphics/transforms/TransformOperations.h
index f40f77f..2f65012 100644
--- a/Source/core/platform/graphics/transforms/TransformOperations.h
+++ b/Source/core/platform/graphics/transforms/TransformOperations.h
@@ -75,6 +75,7 @@
     TransformOperations blendByMatchingOperations(const TransformOperations& from, const double& progress) const;
     TransformOperations blendByUsingMatrixInterpolation(const TransformOperations& from, double progress) const;
     TransformOperations blend(const TransformOperations& from, double progress) const;
+    TransformOperations add(const TransformOperations& addend) const;
 
 private:
     Vector<RefPtr<TransformOperation> > m_operations;
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
index c356d9b..12c15e1 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
@@ -55,7 +55,6 @@
     , m_frameBackgroundHasAlpha(false)
 #if USE(QCMSLIB)
     , m_haveReadProfile(false)
-    , m_hasProfile(false)
     , m_transform(0)
 #endif
     , m_demux(0)
@@ -164,15 +163,8 @@
 {
     if (failed())
         return;
-
     ImageDecoder::setData(data, allDataReceived);
-
-    if (m_demuxState != WEBP_DEMUX_DONE)
-        m_haveAlreadyParsedThisData = false;
-#if USE(QCMSLIB)
-    else if (m_hasProfile && !m_haveReadProfile)
-        m_haveAlreadyParsedThisData = false;
-#endif
+    m_haveAlreadyParsedThisData = false;
 }
 
 int WEBPImageDecoder::repetitionCount() const
@@ -220,9 +212,6 @@
     bool hasAnimation = (m_formatFlags & ANIMATION_FLAG);
     if (!ImageDecoder::isSizeAvailable()) {
         m_formatFlags = WebPDemuxGetI(m_demux, WEBP_FF_FORMAT_FLAGS);
-#if USE(QCMSLIB)
-        m_hasProfile = (m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile();
-#endif
         hasAnimation = (m_formatFlags & ANIMATION_FLAG);
         if (hasAnimation && !RuntimeEnabledFeatures::animatedWebPEnabled())
             return setFailed();
@@ -405,7 +394,7 @@
     const int top = frameRect.y();
 
 #if USE(QCMSLIB)
-    if (m_hasProfile) {
+    if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile()) {
         if (!m_haveReadProfile) {
             readColorProfile();
             m_haveReadProfile = true;
@@ -517,7 +506,7 @@
         if (!m_premultiplyAlpha)
             mode = outputMode(false);
 #if USE(QCMSLIB)
-        if (m_hasProfile)
+        if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile())
             mode = MODE_RGBA; // Decode to RGBA for input to libqcms.
 #endif
         WebPInitDecBuffer(&m_decoderBuffer);
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
index 9118f97..8d6f4b8 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
@@ -65,7 +65,6 @@
     void readColorProfile();
 
     bool m_haveReadProfile;
-    bool m_hasProfile;
     qcms_transform* m_transform;
 #endif
 
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
index 002ae08..0b18f68 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
@@ -138,6 +138,28 @@
     }
 }
 
+void testDecodeAfterReallocatingData(const char* webpFile)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+    RefPtr<SharedBuffer> data = readFile(webpFile);
+    ASSERT_TRUE(data.get());
+
+    // Parse from 'data'.
+    decoder->setData(data.get(), true);
+    size_t frameCount = decoder->frameCount();
+
+    // ... and then decode frames from 'reallocatedData'.
+    RefPtr<SharedBuffer> reallocatedData = data.get()->copy();
+    ASSERT_TRUE(reallocatedData.get());
+    data.clear();
+    decoder->setData(reallocatedData.get(), true);
+
+    for (size_t i = 0; i < frameCount; ++i) {
+        const ImageFrame* const frame = decoder->frameBufferAtIndex(i);
+        EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
+    }
+}
+
 } // namespace
 
 class AnimatedWebPTests : public ::testing::Test {
@@ -432,4 +454,10 @@
     EXPECT_EQ(baselineHashes[0], hashSkBitmap(firstFrame->getSkBitmap()));
 }
 
+TEST_F(AnimatedWebPTests, decodeAfterReallocatingData)
+{
+    testDecodeAfterReallocatingData("/LayoutTests/fast/images/resources/webp-animated.webp");
+    testDecodeAfterReallocatingData("/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp");
+}
+
 #endif
diff --git a/Source/core/platform/mac/ScrollAnimatorMac.mm b/Source/core/platform/mac/ScrollAnimatorMac.mm
index a92ab24..9f4dda5 100644
--- a/Source/core/platform/mac/ScrollAnimatorMac.mm
+++ b/Source/core/platform/mac/ScrollAnimatorMac.mm
@@ -32,12 +32,12 @@
 #include "core/platform/ScrollView.h"
 #include "core/platform/ScrollableArea.h"
 #include "core/platform/ScrollbarTheme.h"
+#include "core/platform/ScrollbarThemeMacCommon.h"
+#include "core/platform/ScrollbarThemeMacOverlayAPI.h"
 #include "core/platform/graphics/FloatPoint.h"
 #include "core/platform/mac/BlockExceptions.h"
 #include "core/platform/mac/EmptyProtocolDefinitions.h"
 #include "core/platform/mac/NSScrollerImpDetails.h"
-#include "core/platform/mac/ScrollbarThemeMac.h"
-#include "core/platform/mac/ScrollbarThemeMacOverlayAPI.h"
 #include "wtf/MainThread.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/UnusedParam.h"
diff --git a/Source/core/platform/mock/GeolocationClientMock.h b/Source/core/platform/mock/GeolocationClientMock.h
index cfe9941..b3eec87 100644
--- a/Source/core/platform/mock/GeolocationClientMock.h
+++ b/Source/core/platform/mock/GeolocationClientMock.h
@@ -60,13 +60,13 @@
     int numberOfPendingPermissionRequests() const;
 
     // GeolocationClient
-    virtual void geolocationDestroyed();
-    virtual void startUpdating();
-    virtual void stopUpdating();
-    virtual void setEnableHighAccuracy(bool);
-    virtual GeolocationPosition* lastPosition();
-    virtual void requestPermission(Geolocation*);
-    virtual void cancelPermissionRequest(Geolocation*);
+    virtual void geolocationDestroyed() OVERRIDE;
+    virtual void startUpdating() OVERRIDE;
+    virtual void stopUpdating() OVERRIDE;
+    virtual void setEnableHighAccuracy(bool) OVERRIDE;
+    virtual GeolocationPosition* lastPosition() OVERRIDE;
+    virtual void requestPermission(Geolocation*) OVERRIDE;
+    virtual void cancelPermissionRequest(Geolocation*) OVERRIDE;
 
 private:
     void asyncUpdateController();
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/platform/mock/MIDIClientMock.cpp
similarity index 63%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/platform/mock/MIDIClientMock.cpp
index 133dab0..b5c603c 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/platform/mock/MIDIClientMock.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,26 +28,39 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#include "config.h"
+#include "core/platform/mock/MIDIClientMock.h"
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "modules/webmidi/MIDIAccess.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
-public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
+MIDIClientMock::MIDIClientMock()
+    : m_allowed(false)
+{
+}
 
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
-};
+MIDIClientMock::~MIDIClientMock()
+{
+}
 
-} // namespace WebCore
+void MIDIClientMock::setSysExPermission(bool allowed)
+{
+    m_allowed = allowed;
+}
 
-#endif
+void MIDIClientMock::resetMock()
+{
+    m_allowed = false;
+}
+
+void MIDIClientMock::requestSysExPermission(PassRefPtr<MIDIAccess> access)
+{
+    access->setSysExEnabled(m_allowed);
+}
+
+void MIDIClientMock::cancelSysExPermissionRequest(MIDIAccess*)
+{
+}
+
+} // WebCore
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/platform/mock/MIDIClientMock.h
similarity index 64%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/platform/mock/MIDIClientMock.h
index 133dab0..7276c85 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/platform/mock/MIDIClientMock.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,26 +28,29 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#ifndef MIDIClientMock_h
+#define MIDIClientMock_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "modules/webmidi/MIDIClient.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
+class MIDIClientMock : public MIDIClient {
 public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
+    MIDIClientMock();
+    virtual ~MIDIClientMock();
 
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+    void setSysExPermission(bool);
+    void resetMock();
+
+    // MIDIClient
+    virtual void requestSysExPermission(PassRefPtr<MIDIAccess>) OVERRIDE;
+    virtual void cancelSysExPermissionRequest(MIDIAccess*) OVERRIDE;
+
+private:
+    bool m_allowed;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // MIDIClient_h
diff --git a/Source/core/rendering/CompositingReasons.h b/Source/core/rendering/CompositingReasons.h
index 5940c09..792f3ed 100644
--- a/Source/core/rendering/CompositingReasons.h
+++ b/Source/core/rendering/CompositingReasons.h
@@ -56,7 +56,10 @@
 
 // FIXME: the following compositing reasons need to be re-organized to fit with categories
 // used in all the other reasons above.
-const uint64_t CompositingReasonLayerForVideoOverlay                   = UINT64_C(1) << 32;
+const uint64_t CompositingReasonOverflowScrollingParent                = UINT64_C(1) << 32;
+const uint64_t CompositingReasonOutOfFlowClipping                      = UINT64_C(1) << 33;
+
+const uint64_t CompositingReasonLayerForVideoOverlay                   = UINT64_C(1) << 34;
 
 // Note: if you add more reasons here, you will need to update WebCompositingReasons as well.
 typedef uint64_t CompositingReasons;
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index ea8f36e..f578722 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -29,8 +29,8 @@
 #include "core/rendering/FilterEffectRenderer.h"
 
 #include "core/dom/Document.h"
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/DocumentResourceReference.h"
+#include "core/fetch/DocumentResource.h"
+#include "core/fetch/DocumentResourceReference.h"
 #include "core/page/Page.h"
 #include "core/platform/FloatConversion.h"
 #include "core/platform/graphics/ColorSpace.h"
diff --git a/Source/core/rendering/FloatingObjects.cpp b/Source/core/rendering/FloatingObjects.cpp
new file mode 100644
index 0000000..7312d7c
--- /dev/null
+++ b/Source/core/rendering/FloatingObjects.cpp
@@ -0,0 +1,319 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2007 David Smith (catfish.man@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple 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/rendering/FloatingObjects.h"
+
+#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBox.h"
+#include "core/rendering/RenderView.h"
+
+using namespace std;
+using namespace WTF;
+
+namespace WebCore {
+
+struct SameSizeAsFloatingObject {
+    void* pointers[2];
+    LayoutRect rect;
+    int paginationStrut;
+    uint32_t bitfields : 8;
+};
+
+COMPILE_ASSERT(sizeof(FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
+
+template <FloatingObject::Type FloatTypeValue>
+class ComputeFloatOffsetAdapter {
+public:
+    typedef FloatingObjectInterval IntervalType;
+
+    ComputeFloatOffsetAdapter(const RenderBlock* renderer, int lineTop, int lineBottom, LayoutUnit& offset)
+        : m_renderer(renderer)
+        , m_lineTop(lineTop)
+        , m_lineBottom(lineBottom)
+        , m_offset(offset)
+        , m_outermostFloat(0)
+    {
+    }
+
+    int lowValue() const { return m_lineTop; }
+    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;
+
+private:
+    bool updateOffsetIfNeeded(const FloatingObject*);
+
+    const RenderBlock* m_renderer;
+    int m_lineTop;
+    int m_lineBottom;
+    LayoutUnit& m_offset;
+    const FloatingObject* m_outermostFloat;
+};
+
+
+FloatingObjects::~FloatingObjects()
+{
+    // FIXME: m_set should use OwnPtr instead.
+    deleteAllValues(m_set);
+}
+void FloatingObjects::clearLineBoxTreePointers()
+{
+    // Clear references to originating lines, since the lines are being deleted
+    FloatingObjectSetIterator end = m_set.end();
+    for (FloatingObjectSetIterator it = m_set.begin(); it != end; ++it) {
+        ASSERT(!((*it)->originatingLine()) || (*it)->originatingLine()->renderer() == m_renderer);
+        (*it)->setOriginatingLine(0);
+    }
+}
+
+template<>
+inline bool ComputeFloatOffsetAdapter<FloatingObject::FloatLeft>::updateOffsetIfNeeded(const FloatingObject* floatingObject)
+{
+    LayoutUnit logicalRight = floatingObject->logicalRight(m_renderer->isHorizontalWritingMode());
+    if (logicalRight > m_offset) {
+        m_offset = logicalRight;
+        return true;
+    }
+    return false;
+}
+
+FloatingObjects::FloatingObjects(const RenderBlock* renderer, bool horizontalWritingMode)
+    : m_placedFloatsTree(UninitializedTree)
+    , m_leftObjectsCount(0)
+    , m_rightObjectsCount(0)
+    , m_horizontalWritingMode(horizontalWritingMode)
+    , m_renderer(renderer)
+{
+}
+
+void FloatingObjects::clear()
+{
+    // FIXME: This should call deleteAllValues, except clearFloats
+    // like to play fast and loose with ownership of these pointers.
+    // If we move to OwnPtr that will fix this ownership oddness.
+    m_set.clear();
+    m_placedFloatsTree.clear();
+    m_leftObjectsCount = 0;
+    m_rightObjectsCount = 0;
+}
+
+inline void FloatingObjects::increaseObjectsCount(FloatingObject::Type type)
+{
+    if (type == FloatingObject::FloatLeft)
+        m_leftObjectsCount++;
+    else
+        m_rightObjectsCount++;
+}
+
+inline void FloatingObjects::decreaseObjectsCount(FloatingObject::Type type)
+{
+    if (type == FloatingObject::FloatLeft)
+        m_leftObjectsCount--;
+    else
+        m_rightObjectsCount--;
+}
+
+inline FloatingObjectInterval FloatingObjects::intervalForFloatingObject(FloatingObject* floatingObject)
+{
+    if (m_horizontalWritingMode)
+        return FloatingObjectInterval(floatingObject->frameRect().pixelSnappedY(), floatingObject->frameRect().pixelSnappedMaxY(), floatingObject);
+    return FloatingObjectInterval(floatingObject->frameRect().pixelSnappedX(), floatingObject->frameRect().pixelSnappedMaxX(), floatingObject);
+}
+
+void FloatingObjects::addPlacedObject(FloatingObject* floatingObject)
+{
+    ASSERT(!floatingObject->isInPlacedTree());
+
+    floatingObject->setIsPlaced(true);
+    if (m_placedFloatsTree.isInitialized())
+        m_placedFloatsTree.add(intervalForFloatingObject(floatingObject));
+
+#ifndef NDEBUG
+    floatingObject->setIsInPlacedTree(true);
+#endif
+}
+
+void FloatingObjects::removePlacedObject(FloatingObject* floatingObject)
+{
+    ASSERT(floatingObject->isPlaced() && floatingObject->isInPlacedTree());
+
+    if (m_placedFloatsTree.isInitialized()) {
+        bool removed = m_placedFloatsTree.remove(intervalForFloatingObject(floatingObject));
+        ASSERT_UNUSED(removed, removed);
+    }
+
+    floatingObject->setIsPlaced(false);
+#ifndef NDEBUG
+    floatingObject->setIsInPlacedTree(false);
+#endif
+}
+
+void FloatingObjects::add(FloatingObject* floatingObject)
+{
+    increaseObjectsCount(floatingObject->type());
+    m_set.add(floatingObject);
+    if (floatingObject->isPlaced())
+        addPlacedObject(floatingObject);
+}
+
+void FloatingObjects::remove(FloatingObject* floatingObject)
+{
+    decreaseObjectsCount(floatingObject->type());
+    m_set.remove(floatingObject);
+    ASSERT(floatingObject->isPlaced() || !floatingObject->isInPlacedTree());
+    if (floatingObject->isPlaced())
+        removePlacedObject(floatingObject);
+}
+
+void FloatingObjects::computePlacedFloatsTree()
+{
+    ASSERT(!m_placedFloatsTree.isInitialized());
+    if (m_set.isEmpty())
+        return;
+    m_placedFloatsTree.initIfNeeded(m_renderer->view()->intervalArena());
+    FloatingObjectSetIterator it = m_set.begin();
+    FloatingObjectSetIterator end = m_set.end();
+    for (; it != end; ++it) {
+        FloatingObject* floatingObject = *it;
+        if (floatingObject->isPlaced())
+            m_placedFloatsTree.add(intervalForFloatingObject(floatingObject));
+    }
+}
+
+LayoutUnit FloatingObjects::logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode, LayoutUnit *heightRemaining)
+{
+    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->computeSegmentsForContainingBlockLine(logicalTop, outermostFloat->logicalTop(m_horizontalWritingMode), logicalHeight);
+            offset += shapeOutside->rightSegmentMarginBoxDelta();
+        }
+    }
+
+    return offset;
+}
+
+LayoutUnit FloatingObjects::logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode, LayoutUnit *heightRemaining)
+{
+    LayoutUnit offset = fixedOffset;
+    ComputeFloatOffsetAdapter<FloatingObject::FloatRight> 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->computeSegmentsForContainingBlockLine(logicalTop, outermostFloat->logicalTop(m_horizontalWritingMode), logicalHeight);
+            offset += shapeOutside->leftSegmentMarginBoxDelta();
+        }
+    }
+
+    return min(fixedOffset, offset);
+}
+
+inline static bool rangesIntersect(int floatTop, int floatBottom, int objectTop, int objectBottom)
+{
+    if (objectTop >= floatBottom || objectBottom < floatTop)
+        return false;
+
+    // The top of the object overlaps the float
+    if (objectTop >= floatTop)
+        return true;
+
+    // The object encloses the float
+    if (objectTop < floatTop && objectBottom > floatBottom)
+        return true;
+
+    // The bottom of the object overlaps the float
+    if (objectBottom > objectTop && objectBottom > floatTop && objectBottom <= floatBottom)
+        return true;
+
+    return false;
+}
+
+template<>
+inline bool ComputeFloatOffsetAdapter<FloatingObject::FloatRight>::updateOffsetIfNeeded(const FloatingObject* floatingObject)
+{
+    LayoutUnit logicalLeft = floatingObject->logicalLeft(m_renderer->isHorizontalWritingMode());
+    if (logicalLeft < m_offset) {
+        m_offset = logicalLeft;
+        return true;
+    }
+    return false;
+}
+
+template <FloatingObject::Type FloatTypeValue>
+inline void ComputeFloatOffsetAdapter<FloatTypeValue>::collectIfNeeded(const IntervalType& interval)
+{
+    const FloatingObject* floatingObject = interval.data();
+    if (floatingObject->type() != FloatTypeValue || !rangesIntersect(interval.low(), interval.high(), m_lineTop, m_lineBottom))
+        return;
+
+    // Make sure the float hasn't changed since it was added to the placed floats tree.
+    ASSERT(floatingObject->isPlaced());
+    ASSERT(interval.low() == floatingObject->pixelSnappedLogicalTop(m_renderer->isHorizontalWritingMode()));
+    ASSERT(interval.high() == floatingObject->pixelSnappedLogicalBottom(m_renderer->isHorizontalWritingMode()));
+
+    bool floatIsNewExtreme = updateOffsetIfNeeded(floatingObject);
+    if (floatIsNewExtreme)
+        m_outermostFloat = floatingObject;
+}
+
+template <FloatingObject::Type FloatTypeValue>
+LayoutUnit ComputeFloatOffsetAdapter<FloatTypeValue>::getHeightRemaining() const
+{
+    return m_outermostFloat ? m_outermostFloat->logicalBottom(m_renderer->isHorizontalWritingMode()) - m_lineTop : LayoutUnit(1);
+}
+
+#ifndef NDEBUG
+// These helpers are only used by the PODIntervalTree for debugging purposes.
+String ValueToString<int>::string(const int value)
+{
+    return String::number(value);
+}
+
+String ValueToString<FloatingObject*>::string(const FloatingObject* floatingObject)
+{
+    return String::format("%p (%dx%d %dx%d)", floatingObject, floatingObject->frameRect().pixelSnappedX(), floatingObject->frameRect().pixelSnappedY(), floatingObject->frameRect().pixelSnappedMaxX(), floatingObject->frameRect().pixelSnappedMaxY());
+}
+#endif
+
+
+} // namespace WebCore
diff --git a/Source/core/rendering/FloatingObjects.h b/Source/core/rendering/FloatingObjects.h
new file mode 100644
index 0000000..ba8c4e9
--- /dev/null
+++ b/Source/core/rendering/FloatingObjects.h
@@ -0,0 +1,255 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2007 David Smith (catfish.man@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple 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.
+ */
+
+#ifndef FloatingObjects_h
+#define FloatingObjects_h
+
+#include "core/platform/PODFreeListArena.h"
+#include "core/platform/PODIntervalTree.h"
+#include "core/rendering/RootInlineBox.h"
+#include "wtf/ListHashSet.h"
+
+namespace WebCore {
+
+class RenderBlock;
+class RenderBox;
+
+enum ShapeOutsideFloatOffsetMode { ShapeOutsideFloatShapeOffset, ShapeOutsideFloatMarginBoxOffset };
+
+class FloatingObject {
+    WTF_MAKE_NONCOPYABLE(FloatingObject); WTF_MAKE_FAST_ALLOCATED;
+public:
+#ifndef NDEBUG
+    // Used by the PODIntervalTree for debugging the FloatingObject.
+    template <class> friend struct ValueToString;
+#endif
+
+    // Note that Type uses bits so you can use FloatLeftRight as a mask to query for both left and right.
+    enum Type { FloatLeft = 1, FloatRight = 2, FloatLeftRight = 3 };
+
+    FloatingObject(EFloat type)
+        : m_renderer(0)
+        , m_originatingLine(0)
+        , m_paginationStrut(0)
+        , m_shouldPaint(true)
+        , m_isDescendant(false)
+        , m_isPlaced(false)
+#ifndef NDEBUG
+        , m_isInPlacedTree(false)
+#endif
+    {
+        ASSERT(type != NoFloat);
+        if (type == LeftFloat)
+            m_type = FloatLeft;
+        else if (type == RightFloat)
+            m_type = FloatRight;
+    }
+
+    FloatingObject(Type type, const LayoutRect& frameRect)
+        : m_renderer(0)
+        , m_originatingLine(0)
+        , m_frameRect(frameRect)
+        , m_paginationStrut(0)
+        , m_type(type)
+        , m_shouldPaint(true)
+        , m_isDescendant(false)
+        , m_isPlaced(true)
+#ifndef NDEBUG
+        , m_isInPlacedTree(false)
+#endif
+    {
+    }
+
+    FloatingObject* clone() const
+    {
+        FloatingObject* cloneObject = new FloatingObject(type(), m_frameRect);
+        cloneObject->m_renderer = m_renderer;
+        cloneObject->m_originatingLine = m_originatingLine;
+        cloneObject->m_paginationStrut = m_paginationStrut;
+        cloneObject->m_shouldPaint = m_shouldPaint;
+        cloneObject->m_isDescendant = m_isDescendant;
+        cloneObject->m_isPlaced = m_isPlaced;
+        return cloneObject;
+    }
+
+    Type type() const { return static_cast<Type>(m_type); }
+    RenderBox* renderer() const { return m_renderer; }
+
+    bool isPlaced() const { return m_isPlaced; }
+    void setIsPlaced(bool placed = true) { m_isPlaced = placed; }
+
+    LayoutUnit x() const { ASSERT(isPlaced()); return m_frameRect.x(); }
+    LayoutUnit maxX() const { ASSERT(isPlaced()); return m_frameRect.maxX(); }
+    LayoutUnit y() const { ASSERT(isPlaced()); return m_frameRect.y(); }
+    LayoutUnit maxY() const { ASSERT(isPlaced()); return m_frameRect.maxY(); }
+    LayoutUnit width() const { return m_frameRect.width(); }
+    LayoutUnit height() const { return m_frameRect.height(); }
+
+    void setX(LayoutUnit x) { ASSERT(!isInPlacedTree()); m_frameRect.setX(x); }
+    void setY(LayoutUnit y) { ASSERT(!isInPlacedTree()); m_frameRect.setY(y); }
+    void setWidth(LayoutUnit width) { ASSERT(!isInPlacedTree()); m_frameRect.setWidth(width); }
+    void setHeight(LayoutUnit height) { ASSERT(!isInPlacedTree()); m_frameRect.setHeight(height); }
+
+    const LayoutRect& frameRect() const { ASSERT(isPlaced()); return m_frameRect; }
+    void setFrameRect(const LayoutRect& frameRect) { ASSERT(!isInPlacedTree()); m_frameRect = frameRect; }
+
+    int paginationStrut() const { return m_paginationStrut; }
+    void setPaginationStrut(int strut) { m_paginationStrut = strut; }
+
+#ifndef NDEBUG
+    bool isInPlacedTree() const { return m_isInPlacedTree; }
+    void setIsInPlacedTree(bool value) { m_isInPlacedTree = value; }
+#endif
+
+    bool shouldPaint() const { return m_shouldPaint; }
+    void setShouldPaint(bool shouldPaint) { m_shouldPaint = shouldPaint; }
+    bool isDescendant() const { return m_isDescendant; }
+    void setIsDescendant(bool isDescendant) { m_isDescendant = isDescendant; }
+
+    // FIXME: Callers of these methods are dangerous and should be whitelisted explicitly or removed.
+    void setRenderer(RenderBox* renderer) { m_renderer = renderer; }
+    RootInlineBox* originatingLine() const { return m_originatingLine; }
+    void setOriginatingLine(RootInlineBox* line) { m_originatingLine = line; }
+
+    LayoutUnit logicalTop(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? y() : x(); }
+    LayoutUnit logicalBottom(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? maxY() : maxX(); }
+    LayoutUnit logicalLeft(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? x() : y(); }
+    LayoutUnit logicalRight(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? maxX() : maxY(); }
+    LayoutUnit logicalWidth(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? width() : height(); }
+
+    int pixelSnappedLogicalTop(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedY() : frameRect().pixelSnappedX(); }
+    int pixelSnappedLogicalBottom(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedMaxY() : frameRect().pixelSnappedMaxX(); }
+    int pixelSnappedLogicalLeft(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedX() : frameRect().pixelSnappedY(); }
+    int pixelSnappedLogicalRight(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedMaxX() : frameRect().pixelSnappedMaxY(); }
+
+    void setLogicalTop(LayoutUnit logicalTop, bool isHorizontalWritingMode)
+    {
+        if (isHorizontalWritingMode)
+            setY(logicalTop);
+        else
+            setX(logicalTop);
+    }
+    void setLogicalLeft(LayoutUnit logicalLeft, bool isHorizontalWritingMode)
+    {
+        if (isHorizontalWritingMode)
+            setX(logicalLeft);
+        else
+            setY(logicalLeft);
+    }
+    void setLogicalHeight(LayoutUnit logicalHeight, bool isHorizontalWritingMode)
+    {
+        if (isHorizontalWritingMode)
+            setHeight(logicalHeight);
+        else
+            setWidth(logicalHeight);
+    }
+    void setLogicalWidth(LayoutUnit logicalWidth, bool isHorizontalWritingMode)
+    {
+        if (isHorizontalWritingMode)
+            setWidth(logicalWidth);
+        else
+            setHeight(logicalWidth);
+    }
+
+private:
+    RenderBox* m_renderer;
+    RootInlineBox* m_originatingLine;
+    LayoutRect m_frameRect;
+    int m_paginationStrut; // FIXME: Is this class size-sensitive? Does this need 32-bits?
+
+    unsigned m_type : 2; // Type (left or right aligned)
+    unsigned m_shouldPaint : 1;
+    unsigned m_isDescendant : 1;
+    unsigned m_isPlaced : 1;
+#ifndef NDEBUG
+    unsigned m_isInPlacedTree : 1;
+#endif
+};
+
+struct FloatingObjectHashFunctions {
+    static unsigned hash(FloatingObject* key) { return DefaultHash<RenderBox*>::Hash::hash(key->renderer()); }
+    static bool equal(FloatingObject* a, FloatingObject* b) { return a->renderer() == b->renderer(); }
+    static const bool safeToCompareToEmptyOrDeleted = true;
+};
+struct FloatingObjectHashTranslator {
+    static unsigned hash(RenderBox* key) { return DefaultHash<RenderBox*>::Hash::hash(key); }
+    static bool equal(FloatingObject* a, RenderBox* b) { return a->renderer() == b; }
+};
+typedef ListHashSet<FloatingObject*, 4, FloatingObjectHashFunctions> FloatingObjectSet;
+typedef FloatingObjectSet::const_iterator FloatingObjectSetIterator;
+typedef PODInterval<int, FloatingObject*> FloatingObjectInterval;
+typedef PODIntervalTree<int, FloatingObject*> FloatingObjectTree;
+typedef PODFreeListArena<PODRedBlackTree<FloatingObjectInterval>::Node> IntervalArena;
+
+class FloatingObjects {
+    WTF_MAKE_NONCOPYABLE(FloatingObjects); WTF_MAKE_FAST_ALLOCATED;
+public:
+    FloatingObjects(const RenderBlock*, bool horizontalWritingMode);
+    ~FloatingObjects();
+
+    void clear();
+    void add(FloatingObject*);
+    void remove(FloatingObject*);
+    void addPlacedObject(FloatingObject*);
+    void removePlacedObject(FloatingObject*);
+    void setHorizontalWritingMode(bool b = true) { m_horizontalWritingMode = b; }
+
+    bool hasLeftObjects() const { return m_leftObjectsCount > 0; }
+    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);
+private:
+    void computePlacedFloatsTree();
+    const FloatingObjectTree& placedFloatsTree()
+    {
+        if (!m_placedFloatsTree.isInitialized())
+            computePlacedFloatsTree();
+        return m_placedFloatsTree;
+    }
+    void increaseObjectsCount(FloatingObject::Type);
+    void decreaseObjectsCount(FloatingObject::Type);
+    FloatingObjectInterval intervalForFloatingObject(FloatingObject*);
+
+    FloatingObjectSet m_set;
+    FloatingObjectTree m_placedFloatsTree;
+    unsigned m_leftObjectsCount;
+    unsigned m_rightObjectsCount;
+    bool m_horizontalWritingMode;
+    const RenderBlock* m_renderer;
+};
+
+#ifndef NDEBUG
+// These structures are used by PODIntervalTree for debugging purposes.
+template <> struct ValueToString<int> {
+    static String string(const int value);
+};
+template<> struct ValueToString<FloatingObject*> {
+    static String string(const FloatingObject*);
+};
+#endif
+
+} // namespace WebCore
+
+#endif // FloatingObjects_h
diff --git a/Source/core/rendering/HitTestLocation.cpp b/Source/core/rendering/HitTestLocation.cpp
index 96c55ae..d09665d 100644
--- a/Source/core/rendering/HitTestLocation.cpp
+++ b/Source/core/rendering/HitTestLocation.cpp
@@ -27,6 +27,7 @@
 #include "XLinkNames.h"
 #include "core/dom/DocumentMarkerController.h"
 #include "core/editing/FrameSelection.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
@@ -34,7 +35,6 @@
 #include "core/html/HTMLPlugInImageElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/platform/Scrollbar.h"
diff --git a/Source/core/rendering/HitTestResult.cpp b/Source/core/rendering/HitTestResult.cpp
index 393d2cb..d312652 100644
--- a/Source/core/rendering/HitTestResult.cpp
+++ b/Source/core/rendering/HitTestResult.cpp
@@ -29,6 +29,7 @@
 #include "core/dom/NodeRenderingTraversal.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLAreaElement.h"
 #include "core/html/HTMLImageElement.h"
@@ -37,7 +38,6 @@
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/platform/Scrollbar.h"
@@ -317,7 +317,7 @@
         return 0;
 
     if (isHTMLVideoElement(m_innerNonSharedNode.get()) || m_innerNonSharedNode->hasTagName(HTMLNames::audioTag))
-        return static_cast<HTMLMediaElement*>(m_innerNonSharedNode.get());
+        return toHTMLMediaElement(m_innerNonSharedNode.get());
     return 0;
 }
 
diff --git a/Source/core/rendering/InlineFlowBox.cpp b/Source/core/rendering/InlineFlowBox.cpp
index e9890ff..dc50595 100644
--- a/Source/core/rendering/InlineFlowBox.cpp
+++ b/Source/core/rendering/InlineFlowBox.cpp
@@ -1105,8 +1105,9 @@
                     // Add ourselves to the containing block of the entire continuation so that it can
                     // paint us atomically.
                     cb->addContinuationWithOutline(toRenderInline(renderer()->node()->renderer()));
-                } else if (!inlineFlow->isInlineElementContinuation())
-                    paintInfo.outlineObjects->add(inlineFlow);
+                } else if (!inlineFlow->isInlineElementContinuation()) {
+                    paintInfo.outlineObjects()->add(inlineFlow);
+                }
             }
         } else if (paintInfo.phase == PaintPhaseMask) {
             paintMask(paintInfo, paintOffset);
diff --git a/Source/core/rendering/InlineIterator.h b/Source/core/rendering/InlineIterator.h
index eae2dca..d88205a 100644
--- a/Source/core/rendering/InlineIterator.h
+++ b/Source/core/rendering/InlineIterator.h
@@ -417,12 +417,17 @@
 static inline RenderObject* containingIsolate(RenderObject* object, RenderObject* root)
 {
     ASSERT(object);
+    RenderObject* containingIsolateObj = 0;
     while (object && object != root) {
+        if (containingIsolateObj && !isIsolatedInline(object))
+            break;
+
         if (isIsolatedInline(object))
-            return object;
+            containingIsolateObj = object;
+
         object = object->parent();
     }
-    return 0;
+    return containingIsolateObj;
 }
 
 static inline unsigned numberOfIsolateAncestors(const InlineIterator& iter)
diff --git a/Source/core/rendering/InlineTextBox.cpp b/Source/core/rendering/InlineTextBox.cpp
index 2bfe7de..7287d00 100644
--- a/Source/core/rendering/InlineTextBox.cpp
+++ b/Source/core/rendering/InlineTextBox.cpp
@@ -1534,6 +1534,11 @@
     return run;
 }
 
+TextRun InlineTextBox::constructTextRunForInspector(RenderStyle* style, const Font& font) const
+{
+    return InlineTextBox::constructTextRun(style, font);
+}
+
 #ifndef NDEBUG
 
 const char* InlineTextBox::boxName() const
diff --git a/Source/core/rendering/InlineTextBox.h b/Source/core/rendering/InlineTextBox.h
index ed4d663..3d6fdee 100644
--- a/Source/core/rendering/InlineTextBox.h
+++ b/Source/core/rendering/InlineTextBox.h
@@ -107,6 +107,7 @@
     TextRun constructTextRun(RenderStyle*, const Font&, StringView, int maximumLength, StringBuilder* charactersWithHyphen = 0) const;
 
 public:
+    TextRun constructTextRunForInspector(RenderStyle*, const Font&) const;
     virtual FloatRect calculateBoundaries() const { return FloatRect(x(), y(), width(), height()); }
 
     virtual LayoutRect localSelectionRect(int startPos, int endPos);
diff --git a/Source/core/rendering/PaintInfo.h b/Source/core/rendering/PaintInfo.h
index 5ff00c5..3f7aa80 100644
--- a/Source/core/rendering/PaintInfo.h
+++ b/Source/core/rendering/PaintInfo.h
@@ -59,9 +59,9 @@
         , paintBehavior(newPaintBehavior)
         , paintingRoot(newPaintingRoot)
         , renderRegion(region)
-        , outlineObjects(newOutlineObjects)
         , overlapTestRequests(overlapTestRequests)
-        , paintContainer(newPaintContainer)
+        , m_paintContainer(newPaintContainer)
+        , m_outlineObjects(newOutlineObjects)
     {
     }
 
@@ -101,6 +101,10 @@
     }
 
     static IntRect infiniteRect() { return IntRect(LayoutRect::infiniteRect()); }
+    const RenderLayerModelObject* paintContainer() const { return m_paintContainer; }
+
+    ListHashSet<RenderInline*>* outlineObjects() { return m_outlineObjects; }
+    void setOutlineObjects(ListHashSet<RenderInline*>* objects) { m_outlineObjects = objects; }
 
     // FIXME: Introduce setters/getters at some point. Requires a lot of changes throughout rendering/.
     GraphicsContext* context;
@@ -109,9 +113,12 @@
     PaintBehavior paintBehavior;
     RenderObject* paintingRoot; // used to draw just one element and its visual kids
     RenderRegion* renderRegion;
-    ListHashSet<RenderInline*>* outlineObjects; // used to list outlines that should be painted by a block with inline children
     OverlapTestRequestMap* overlapTestRequests;
-    const RenderLayerModelObject* paintContainer; // the layer object that originates the current painting
+
+private:
+
+    const RenderLayerModelObject* m_paintContainer; // the layer object that originates the current painting
+    ListHashSet<RenderInline*>* m_outlineObjects; // used to list outlines that should be painted by a block with inline children
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index d40b5f2..d682aba 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -36,7 +36,6 @@
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/PODFreeListArena.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/transforms/TransformState.h"
@@ -82,13 +81,6 @@
 
 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
 
-struct SameSizeAsFloatingObject {
-    void* pointers[2];
-    LayoutRect rect;
-    int paginationStrut;
-    uint32_t bitfields : 8;
-};
-
 COMPILE_ASSERT(sizeof(RenderBlock::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
 
 struct SameSizeAsMarginInfo {
@@ -200,7 +192,6 @@
     , m_hasBorderOrPaddingLogicalWidthChanged(false)
 {
     setChildrenInline(true);
-    COMPILE_ASSERT(sizeof(RenderBlock::FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
     COMPILE_ASSERT(sizeof(RenderBlock::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
 }
 
@@ -224,12 +215,8 @@
 
 RenderBlock::~RenderBlock()
 {
-    if (m_floatingObjects)
-        deleteAllValues(m_floatingObjects->set());
-
     if (hasColumns())
         gColumnInfoMap->take(this);
-
     if (gPercentHeightDescendantsMap)
         removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
     if (gPositionedDescendantsMap)
@@ -970,15 +957,8 @@
 
 void RenderBlock::deleteLineBoxTree()
 {
-    if (containsFloats()) {
-        // Clear references to originating lines, since the lines are being deleted
-        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator end = floatingObjectSet.end();
-        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-            ASSERT(!((*it)->m_originatingLine) || (*it)->m_originatingLine->renderer() == this);
-            (*it)->m_originatingLine = 0;
-        }
-    }
+    if (containsFloats())
+        m_floatingObjects->clearLineBoxTreePointers();
     m_lineBoxes.deleteLineBoxTree();
 
     if (AXObjectCache* cache = document()->existingAXObjectCache())
@@ -1415,6 +1395,21 @@
     invalidateBackgroundObscurationStatus();
 }
 
+void RenderBlock::imageChanged(WrappedImagePtr image, const IntRect*)
+{
+    RenderBox::imageChanged(image);
+
+    if (!parent())
+        return;
+
+    ShapeValue* shapeValue = style()->shapeInside();
+    if (shapeValue && shapeValue->image() && shapeValue->image()->data() == image) {
+        ShapeInsideInfo* shapeInsideInfo = ensureShapeInsideInfo();
+        shapeInsideInfo->dirtyShapeSize();
+        markShapeInsideDescendantsForLayout();
+    }
+}
+
 void RenderBlock::updateShapeInsideInfoAfterStyleChange(const ShapeValue* shapeInside, const ShapeValue* oldShapeInside)
 {
     // FIXME: A future optimization would do a deep comparison for equality.
@@ -1590,6 +1585,8 @@
         setPaginationStrut(0);
     }
 
+    SubtreeLayoutScope layoutScope(this);
+
     LayoutUnit repaintLogicalTop = 0;
     LayoutUnit repaintLogicalBottom = 0;
     LayoutUnit maxFloatLogicalBottom = 0;
@@ -1598,7 +1595,7 @@
     if (childrenInline())
         layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
     else
-        layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
+        layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom, layoutScope);
 
     // Expand our intrinsic height to encompass floats.
     LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
@@ -1783,7 +1780,7 @@
     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
         FloatingObject* r = *it;
         if (r->isDescendant())
-            addOverflowFromChild(r->m_renderer, IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
+            addOverflowFromChild(r->renderer(), IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
     }
 }
 
@@ -2455,7 +2452,7 @@
         child->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
 }
 
-void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
+void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope& layoutScope)
 {
     if (gPercentHeightDescendantsMap) {
         if (TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this)) {
@@ -2465,7 +2462,7 @@
                 while (box != this) {
                     if (box->normalChildNeedsLayout())
                         break;
-                    box->setChildNeedsLayout(MarkOnlyThis);
+                    layoutScope.setChildNeedsLayout(box);
                     box = box->containingBlock();
                     ASSERT(box);
                     if (!box)
@@ -2490,7 +2487,7 @@
     // Fieldsets need to find their legend and position it inside the border of the object.
     // The legend then gets skipped during normal layout.  The same is true for ruby text.
     // It doesn't get included in the normal layout process but is instead skipped.
-    RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
+    RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren, layoutScope);
 
     LayoutUnit previousFloatLogicalBottom = 0;
     maxFloatLogicalBottom = 0;
@@ -2575,8 +2572,9 @@
             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
     }
 
+    SubtreeLayoutScope layoutScope(child);
     if (!child->needsLayout())
-        child->markForPaginationRelayoutIfNeeded();
+        child->markForPaginationRelayoutIfNeeded(layoutScope);
 
     bool childHadLayout = child->everHadLayout();
     bool childNeededLayout = child->needsLayout();
@@ -2604,19 +2602,20 @@
     // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
     // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
     if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
+        SubtreeLayoutScope layoutScope(child);
         if (child->shrinkToAvoidFloats()) {
             // The child's width depends on the line width.
             // When the child shifts to clear an item, its width can
             // change (because it has more available line width).
             // So go ahead and mark the item as dirty.
-            child->setChildNeedsLayout(MarkOnlyThis);
+            layoutScope.setChildNeedsLayout(child);
         }
 
         if (childRenderBlock) {
             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
                 childRenderBlock->markAllDescendantsWithFloatsForLayout();
             if (!child->needsLayout())
-                child->markForPaginationRelayoutIfNeeded();
+                child->markForPaginationRelayoutIfNeeded(layoutScope);
         }
 
         // Our guess was wrong. Make the child lay itself out again.
@@ -2713,6 +2712,11 @@
     if (needsSimplifiedNormalFlowLayout())
         simplifiedNormalFlowLayout();
 
+    // Make sure a forced break is applied after the content if we are a flow thread in a simplified layout.
+    // This ensures the size information is correctly computed for the last auto-height region receiving content.
+    if (isRenderFlowThread())
+        toRenderFlowThread(this)->applyBreakAfterContent(clientLogicalBottom());
+
     // Lay out our positioned objects if our positioned child bit is set.
     // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
     // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the
@@ -2742,7 +2746,7 @@
     return true;
 }
 
-void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child)
+void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope& layoutScope)
 {
     if (child->style()->position() != FixedPosition)
         return;
@@ -2763,12 +2767,12 @@
         LayoutUnit oldLeft = box->logicalLeft();
         box->updateLogicalWidth();
         if (box->logicalLeft() != oldLeft)
-            child->setChildNeedsLayout(MarkOnlyThis);
+            layoutScope.setChildNeedsLayout(child);
     } else if (hasStaticBlockPosition) {
         LayoutUnit oldTop = box->logicalTop();
         box->updateLogicalHeight();
         if (box->logicalTop() != oldTop)
-            child->setChildNeedsLayout(MarkOnlyThis);
+            layoutScope.setChildNeedsLayout(child);
     }
 }
 
@@ -2786,10 +2790,11 @@
     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
         r = *it;
 
+        SubtreeLayoutScope layoutScope(r);
         // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
         // if this is a fixed position element, mark it for layout if it has an abspos ancestor and needs to move with that ancestor, i.e.
         // it has static position.
-        markFixedPositionObjectForLayoutIfNeeded(r);
+        markFixedPositionObjectForLayoutIfNeeded(r, layoutScope);
         if (fixedPositionObjectsOnly) {
             r->layoutIfNeeded();
             continue;
@@ -2800,14 +2805,14 @@
         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
         // positioned explicitly) this should not incur a performance penalty.
         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
-            r->setChildNeedsLayout(MarkOnlyThis);
+            layoutScope.setChildNeedsLayout(r);
 
         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
             r->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
 
         if (!r->needsLayout())
-            r->markForPaginationRelayoutIfNeeded();
+            r->markForPaginationRelayoutIfNeeded(layoutScope);
 
         // We don't have to do a full layout.  We just have to update our position. Try that first. If we have shrink-to-fit width
         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
@@ -2850,14 +2855,14 @@
     }
 }
 
-void RenderBlock::markForPaginationRelayoutIfNeeded()
+void RenderBlock::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutScope)
 {
     ASSERT(!needsLayout());
     if (needsLayout())
         return;
 
     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()) || shouldBreakAtLineToAvoidWidow())
-        setChildNeedsLayout(MarkOnlyThis);
+        layoutScope.setChildNeedsLayout(this);
 }
 
 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
@@ -2877,9 +2882,11 @@
         // Only repaint the object if it is overhanging, is not in its own layer, and
         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
         // condition is replaced with being a descendant of us.
-        if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->shouldPaint()) && !r->m_renderer->hasSelfPaintingLayer()) {
-            r->m_renderer->repaint();
-            r->m_renderer->repaintOverhangingFloats(false);
+        if (r->logicalBottom(isHorizontalWritingMode()) > logicalHeight()
+            && !r->renderer()->hasSelfPaintingLayer()
+            && (r->shouldPaint() || (paintAllDescendants && r->renderer()->isDescendantOf(this)))) {
+            r->renderer()->repaint();
+            r->renderer()->repaintOverhangingFloats(false);
         }
     }
 }
@@ -3240,20 +3247,21 @@
     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
         FloatingObject* r = *it;
         // Only paint the object if our m_shouldPaint flag is set.
-        if (r->shouldPaint() && !r->m_renderer->hasSelfPaintingLayer()) {
+        if (r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()) {
             PaintInfo currentPaintInfo(paintInfo);
             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
-            LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->m_renderer->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->m_renderer->y()));
-            r->m_renderer->paint(currentPaintInfo, childPoint);
+            // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
+            LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->renderer()->y()));
+            r->renderer()->paint(currentPaintInfo, childPoint);
             if (!preservePhase) {
                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
-                r->m_renderer->paint(currentPaintInfo, childPoint);
+                r->renderer()->paint(currentPaintInfo, childPoint);
                 currentPaintInfo.phase = PaintPhaseFloat;
-                r->m_renderer->paint(currentPaintInfo, childPoint);
+                r->renderer()->paint(currentPaintInfo, childPoint);
                 currentPaintInfo.phase = PaintPhaseForeground;
-                r->m_renderer->paint(currentPaintInfo, childPoint);
+                r->renderer()->paint(currentPaintInfo, childPoint);
                 currentPaintInfo.phase = PaintPhaseOutline;
-                r->m_renderer->paint(currentPaintInfo, childPoint);
+                r->renderer()->paint(currentPaintInfo, childPoint);
             }
         }
     }
@@ -3467,7 +3475,7 @@
                 FloatingObject* r = *it;
                 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
                                     offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
-                                    r->m_renderer->width(), r->m_renderer->height());
+                                    r->renderer()->width(), r->renderer()->height());
                 rootBlock->flipForWritingMode(floatBox);
                 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
                 paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
@@ -3873,7 +3881,7 @@
     m_floatingObjects->clear();
 }
 
-RenderBlock::FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o)
+FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o)
 {
     ASSERT(o->isFloating());
 
@@ -3906,14 +3914,14 @@
         o->computeAndSetBlockDirectionMargins(this);
     }
 
-    setLogicalWidthForFloat(newObj, logicalWidthForChild(o) + marginStartForChild(o) + marginEndForChild(o));
+    newObj->setLogicalWidth(logicalWidthForChild(o) + marginStartForChild(o) + marginEndForChild(o), isHorizontalWritingMode());
 
     if (ShapeOutsideInfo* shapeOutside = o->shapeOutsideInfo())
         shapeOutside->setShapeSize(logicalWidthForChild(o), logicalHeightForChild(o));
 
     newObj->setShouldPaint(!o->hasSelfPaintingLayer()); // If a layer exists, the float will paint itself. Otherwise someone else will.
     newObj->setIsDescendant(true);
-    newObj->m_renderer = o;
+    newObj->setRenderer(o);
 
     m_floatingObjects->add(newObj);
 
@@ -3928,8 +3936,8 @@
         if (it != floatingObjectSet.end()) {
             FloatingObject* r = *it;
             if (childrenInline()) {
-                LayoutUnit logicalTop = logicalTopForFloat(r);
-                LayoutUnit logicalBottom = logicalBottomForFloat(r);
+                LayoutUnit logicalTop = r->logicalTop(isHorizontalWritingMode());
+                LayoutUnit logicalBottom = r->logicalBottom(isHorizontalWritingMode());
 
                 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
                 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max())
@@ -3940,19 +3948,19 @@
                     // accomplished by pretending they have a height of 1.
                     logicalBottom = max(logicalBottom, logicalTop + 1);
                 }
-                if (r->m_originatingLine) {
+                if (r->originatingLine()) {
                     if (!selfNeedsLayout()) {
-                        ASSERT(r->m_originatingLine->renderer() == this);
-                        r->m_originatingLine->markDirty();
+                        ASSERT(r->originatingLine()->renderer() == this);
+                        r->originatingLine()->markDirty();
                     }
 #if !ASSERT_DISABLED
-                    r->m_originatingLine = 0;
+                    r->setOriginatingLine(0);
 #endif
                 }
                 markLinesDirtyInBlockRange(0, logicalBottom);
             }
             m_floatingObjects->remove(r);
-            ASSERT(!r->m_originatingLine);
+            ASSERT(!r->originatingLine());
             delete r;
         }
     }
@@ -3965,9 +3973,9 @@
 
     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
     FloatingObject* curr = floatingObjectSet.last();
-    while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
+    while (curr != lastFloat && (!curr->isPlaced() || curr->logicalTop(isHorizontalWritingMode()) >= logicalOffset)) {
         m_floatingObjects->remove(curr);
-        ASSERT(!curr->m_originatingLine);
+        ASSERT(!curr->originatingLine());
         delete curr;
         if (floatingObjectSet.isEmpty())
             break;
@@ -3982,8 +3990,9 @@
     LayoutUnit logicalRightOffset; // Constant part of right offset.
     // FIXME Bug 102948: This only works for shape outside directly set on this block.
     ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
-    // FIXME Bug 102846: Take into account the height of the content. The offset should be
-    // equal to the maximum segment length.
+    // FIXME: We should place the float based on its width/height.
+    if (shapeInsideInfo)
+        shapeInsideInfo->computeSegmentsForLine(logicalTopOffset, childBox->logicalHeight());
     if (shapeInsideInfo && shapeInsideInfo->hasSegments() && shapeInsideInfo->segments().size() == 1) {
         // FIXME Bug 102949: Add support for shapes with multipe segments.
 
@@ -3993,7 +4002,7 @@
     } else
         logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset);
 
-    LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
+    LayoutUnit floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset); // The width we look for.
 
     LayoutUnit floatLogicalLeft;
 
@@ -4010,7 +4019,7 @@
                 // Have to re-evaluate all of our offsets, since they may have changed.
                 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
                 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
-                floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
+                floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset);
             }
         }
         floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
@@ -4025,10 +4034,10 @@
                 // Have to re-evaluate all of our offsets, since they may have changed.
                 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
                 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
-                floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
+                floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset);
             }
         }
-        floatLogicalLeft -= logicalWidthForFloat(floatingObject); // Use the original width of the float here, since the local variable
+        floatLogicalLeft -= floatingObject->logicalWidth(isHorizontalWritingMode()); // Use the original width of the float here, since the local variable
                                                                   // |floatLogicalWidth| was capped to the available line width.
                                                                   // See fast/block/float/clamped-right-float.html.
     }
@@ -4069,7 +4078,7 @@
 
     // The float cannot start above the top position of the last positioned float.
     if (lastPlacedFloatingObject)
-        logicalTop = max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
+        logicalTop = max(lastPlacedFloatingObject->logicalTop(isHorizontalWritingMode()), logicalTop);
 
     FloatingObjectSetIterator end = floatingObjectSet.end();
     // Now walk through the set of unpositioned floats and place them.
@@ -4092,15 +4101,16 @@
 
         LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
 
-        setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
+        floatingObject->setLogicalLeft(floatLogicalLocation.x(), isHorizontalWritingMode());
 
         setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
         setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
 
+        SubtreeLayoutScope layoutScope(childBox);
         LayoutState* layoutState = view()->layoutState();
         bool isPaginated = layoutState->isPaginated();
         if (isPaginated && !childBox->needsLayout())
-            childBox->markForPaginationRelayoutIfNeeded();
+            childBox->markForPaginationRelayoutIfNeeded(layoutScope);
 
         childBox->layoutIfNeeded();
 
@@ -4119,10 +4129,10 @@
             }
 
             if (newLogicalTop != floatLogicalLocation.y()) {
-                floatingObject->m_paginationStrut = newLogicalTop - floatLogicalLocation.y();
+                floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
 
                 floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
-                setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
+                floatingObject->setLogicalLeft(floatLogicalLocation.x(), isHorizontalWritingMode());
 
                 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
                 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
@@ -4133,9 +4143,9 @@
             }
         }
 
-        setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
+        floatingObject->setLogicalTop(floatLogicalLocation.y(), isHorizontalWritingMode());
 
-        setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
+        floatingObject->setLogicalHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox), isHorizontalWritingMode());
 
         m_floatingObjects->addPlacedObject(floatingObject);
 
@@ -4226,64 +4236,6 @@
     }
 }
 
-static bool rangesIntersect(int floatTop, int floatBottom, int objectTop, int objectBottom)
-{
-    if (objectTop >= floatBottom || objectBottom < floatTop)
-        return false;
-
-    // The top of the object overlaps the float
-    if (objectTop >= floatTop)
-        return true;
-
-    // The object encloses the float
-    if (objectTop < floatTop && objectBottom > floatBottom)
-        return true;
-
-    // The bottom of the object overlaps the float
-    if (objectBottom > objectTop && objectBottom > floatTop && objectBottom <= floatBottom)
-        return true;
-
-    return false;
-}
-
-template<>
-bool RenderBlock::FloatIntervalSearchAdapter<RenderBlock::FloatingObject::FloatLeft>::updateOffsetIfNeeded(const FloatingObject* floatingObject) const
-{
-    if (m_renderer->logicalRightForFloat(floatingObject) > m_offset) {
-        m_offset = m_renderer->logicalRightForFloat(floatingObject);
-        return true;
-    }
-    return false;
-}
-
-template<>
-bool RenderBlock::FloatIntervalSearchAdapter<RenderBlock::FloatingObject::FloatRight>::updateOffsetIfNeeded(const FloatingObject* floatingObject) const
-{
-    if (m_renderer->logicalLeftForFloat(floatingObject) < m_offset) {
-        m_offset = m_renderer->logicalLeftForFloat(floatingObject);
-        return true;
-    }
-    return false;
-}
-
-template <RenderBlock::FloatingObject::Type FloatTypeValue>
-inline void RenderBlock::FloatIntervalSearchAdapter<FloatTypeValue>::collectIfNeeded(const IntervalType& interval) const
-{
-    const FloatingObject* floatingObject = interval.data();
-    if (floatingObject->type() != FloatTypeValue || !rangesIntersect(interval.low(), interval.high(), m_lowValue, m_highValue))
-        return;
-
-    // All the objects returned from the tree should be already placed.
-    ASSERT(floatingObject->isPlaced());
-    ASSERT(rangesIntersect(m_renderer->pixelSnappedLogicalTopForFloat(floatingObject), m_renderer->pixelSnappedLogicalBottomForFloat(floatingObject), m_lowValue, m_highValue));
-
-    bool floatIsNewExtreme = updateOffsetIfNeeded(floatingObject);
-    if (floatIsNewExtreme && m_heightRemaining)
-        *m_heightRemaining = m_renderer->logicalBottomForFloat(floatingObject) - m_lowValue;
-
-    m_last = floatingObject;
-}
-
 LayoutUnit RenderBlock::textIndentOffset() const
 {
     LayoutUnit cw = 0;
@@ -4316,24 +4268,10 @@
 
 LayoutUnit RenderBlock::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
 {
-    LayoutUnit left = fixedOffset;
-    if (m_floatingObjects && m_floatingObjects->hasLeftObjects()) {
-        if (heightRemaining)
-            *heightRemaining = 1;
+    if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
+        return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
 
-        FloatIntervalSearchAdapter<FloatingObject::FloatLeft> adapter(this, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), left, heightRemaining);
-        m_floatingObjects->placedFloatsTree().allOverlapsWithAdapter(adapter);
-
-        const FloatingObject* lastFloat = adapter.lastFloat();
-        if (offsetMode == ShapeOutsideFloatShapeOffset && lastFloat) {
-            if (ShapeOutsideInfo* shapeOutside = lastFloat->renderer()->shapeOutsideInfo()) {
-                shapeOutside->computeSegmentsForContainingBlockLine(logicalTop, logicalTopForFloat(lastFloat), logicalHeight);
-                left += shapeOutside->rightSegmentMarginBoxDelta();
-            }
-        }
-    }
-
-    return left;
+    return fixedOffset;
 }
 
 LayoutUnit RenderBlock::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
@@ -4376,26 +4314,10 @@
 
 LayoutUnit RenderBlock::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
 {
-    LayoutUnit right = fixedOffset;
-    if (m_floatingObjects && m_floatingObjects->hasRightObjects()) {
-        if (heightRemaining)
-            *heightRemaining = 1;
+    if (m_floatingObjects && m_floatingObjects->hasRightObjects())
+        return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
 
-        LayoutUnit rightFloatOffset = fixedOffset;
-        FloatIntervalSearchAdapter<FloatingObject::FloatRight> adapter(this, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), rightFloatOffset, heightRemaining);
-        m_floatingObjects->placedFloatsTree().allOverlapsWithAdapter(adapter);
-
-        const FloatingObject* lastFloat = adapter.lastFloat();
-        if (offsetMode == ShapeOutsideFloatShapeOffset && lastFloat) {
-            if (ShapeOutsideInfo* shapeOutside = lastFloat->renderer()->shapeOutsideInfo()) {
-                shapeOutside->computeSegmentsForContainingBlockLine(logicalTop, logicalTopForFloat(lastFloat), logicalHeight);
-                rightFloatOffset += shapeOutside->leftSegmentMarginBoxDelta();
-            }
-        }
-
-        right = min(right, rightFloatOffset);
-    }
-    return right;
+    return fixedOffset;
 }
 
 LayoutUnit RenderBlock::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
@@ -4446,7 +4368,7 @@
     FloatingObjectSetIterator end = floatingObjectSet.end();
     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
         FloatingObject* r = *it;
-        LayoutUnit floatBottom = logicalBottomForFloat(r);
+        LayoutUnit floatBottom = r->logicalBottom(isHorizontalWritingMode());
         if (floatBottom > logicalHeight)
             bottom = min(floatBottom, bottom);
     }
@@ -4464,7 +4386,7 @@
     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
         FloatingObject* r = *it;
         if (r->isPlaced() && r->type() & floatType)
-            lowestFloatBottom = max(lowestFloatBottom, logicalBottomForFloat(r));
+            lowestFloatBottom = max(lowestFloatBottom, r->logicalBottom(isHorizontalWritingMode()));
     }
     return lowestFloatBottom;
 }
@@ -4499,7 +4421,7 @@
         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
             FloatingObject* floatingObject = *it;
             if (!floatingObject->isDescendant())
-                oldIntrudingFloatSet.add(floatingObject->m_renderer);
+                oldIntrudingFloatSet.add(floatingObject->renderer());
         }
     }
 
@@ -4523,7 +4445,7 @@
             FloatingObjectSetIterator end = floatingObjectSet.end();
             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
                 FloatingObject* f = *it;
-                floatMap.add(f->m_renderer, f);
+                floatMap.add(f->renderer(), f);
             }
         } else {
             deleteAllValues(floatingObjectSet);
@@ -4575,11 +4497,11 @@
             FloatingObjectSetIterator end = floatingObjectSet.end();
             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
                 FloatingObject* f = *it;
-                FloatingObject* oldFloatingObject = floatMap.get(f->m_renderer);
-                LayoutUnit logicalBottom = logicalBottomForFloat(f);
+                FloatingObject* oldFloatingObject = floatMap.get(f->renderer());
+                LayoutUnit logicalBottom = f->logicalBottom(isHorizontalWritingMode());
                 if (oldFloatingObject) {
-                    LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject);
-                    if (logicalWidthForFloat(f) != logicalWidthForFloat(oldFloatingObject) || logicalLeftForFloat(f) != logicalLeftForFloat(oldFloatingObject)) {
+                    LayoutUnit oldLogicalBottom = oldFloatingObject->logicalBottom(isHorizontalWritingMode());
+                    if (f->logicalWidth(isHorizontalWritingMode()) != oldFloatingObject->logicalWidth(isHorizontalWritingMode()) || f->logicalLeft(isHorizontalWritingMode()) != oldFloatingObject->logicalLeft(isHorizontalWritingMode())) {
                         changeLogicalTop = 0;
                         changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
                     } else {
@@ -4587,18 +4509,18 @@
                             changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
                             changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
                         }
-                        LayoutUnit logicalTop = logicalTopForFloat(f);
-                        LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject);
+                        LayoutUnit logicalTop = f->logicalTop(isHorizontalWritingMode());
+                        LayoutUnit oldLogicalTop = oldFloatingObject->logicalTop(isHorizontalWritingMode());
                         if (logicalTop != oldLogicalTop) {
                             changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
                             changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
                         }
                     }
 
-                    floatMap.remove(f->m_renderer);
-                    if (oldFloatingObject->m_originatingLine && !selfNeedsLayout()) {
-                        ASSERT(oldFloatingObject->m_originatingLine->renderer() == this);
-                        oldFloatingObject->m_originatingLine->markDirty();
+                    floatMap.remove(f->renderer());
+                    if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
+                        ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
+                        oldFloatingObject->originatingLine()->markDirty();
                     }
                     delete oldFloatingObject;
                 } else {
@@ -4613,7 +4535,7 @@
             FloatingObject* floatingObject = (*it).value;
             if (!floatingObject->isDescendant()) {
                 changeLogicalTop = 0;
-                changeLogicalBottom = max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
+                changeLogicalBottom = max(changeLogicalBottom, floatingObject->logicalBottom(isHorizontalWritingMode()));
             }
         }
         deleteAllValues(floatMap);
@@ -4628,7 +4550,7 @@
             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
             FloatingObjectSetIterator end = floatingObjectSet.end();
             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
-                oldIntrudingFloatSet.remove((*it)->m_renderer);
+                oldIntrudingFloatSet.remove((*it)->renderer());
             if (!oldIntrudingFloatSet.isEmpty())
                 markAllDescendantsWithFloatsForLayout();
         }
@@ -4650,22 +4572,22 @@
     FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
     for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
         FloatingObject* r = *childIt;
-        LayoutUnit logicalBottomForFloat = min(this->logicalBottomForFloat(r), LayoutUnit::max() - childLogicalTop);
+        LayoutUnit logicalBottomForFloat = min(r->logicalBottom(isHorizontalWritingMode()), LayoutUnit::max() - childLogicalTop);
         LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
         lowestFloatLogicalBottom = max(lowestFloatLogicalBottom, logicalBottom);
 
         if (logicalBottom > logicalHeight()) {
             // If the object is not in the list, we add it now.
-            if (!containsFloat(r->m_renderer)) {
+            if (!containsFloat(r->renderer())) {
                 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
                 FloatingObject* floatingObj = new FloatingObject(r->type(), LayoutRect(r->frameRect().location() - offset, r->frameRect().size()));
-                floatingObj->m_renderer = r->m_renderer;
+                floatingObj->setRenderer(r->renderer());
 
                 // The nearest enclosing layer always paints the float (so that zindex and stacking
                 // behaves properly).  We always want to propagate the desire to paint the float as
                 // far out as we can, to the outermost block that overlaps the float, stopping only
                 // if we hit a self-painting layer boundary.
-                if (r->m_renderer->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer())
+                if (r->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer())
                     r->setShouldPaint(false);
                 else
                     floatingObj->setShouldPaint(false);
@@ -4678,8 +4600,8 @@
                 m_floatingObjects->add(floatingObj);
             }
         } else {
-            if (makeChildPaintOtherFloats && !r->shouldPaint() && !r->m_renderer->hasSelfPaintingLayer()
-                && r->m_renderer->isDescendantOf(child) && r->m_renderer->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
+            if (makeChildPaintOtherFloats && !r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()
+                && r->renderer()->isDescendantOf(child) && r->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
                 // The float is not overhanging from this block, so if it is a descendant of the child, the child should
                 // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
                 // layer.
@@ -4691,7 +4613,7 @@
             // Since the float doesn't overhang, it didn't get put into our list.  We need to go ahead and add its overflow in to the
             // child now.
             if (r->isDescendant())
-                child->addOverflowFromChild(r->m_renderer, LayoutSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
+                child->addOverflowFromChild(r->renderer(), LayoutSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
         }
     }
     return lowestFloatLogicalBottom;
@@ -4707,7 +4629,7 @@
     if (it == floatingObjectSet.end())
         return false;
 
-    return logicalBottomForFloat(*it) > logicalHeight();
+    return (*it)->logicalBottom(isHorizontalWritingMode()) > logicalHeight();
 }
 
 void RenderBlock::addIntrudingFloats(RenderBlock* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
@@ -4724,7 +4646,7 @@
     FloatingObjectSetIterator prevEnd = prevSet.end();
     for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
         FloatingObject* r = *prevIt;
-        if (logicalBottomForFloat(r) > logicalTopOffset) {
+        if (r->logicalBottom(isHorizontalWritingMode()) > logicalTopOffset) {
             if (!m_floatingObjects || !m_floatingObjects->set().contains(r)) {
                 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, logicalTopOffset) : LayoutSize(logicalTopOffset, logicalLeftOffset);
                 FloatingObject* floatingObj = new FloatingObject(r->type(), LayoutRect(r->frameRect().location() - offset, r->frameRect().size()));
@@ -4742,7 +4664,7 @@
                 }
 
                 floatingObj->setShouldPaint(false); // We are not in the direct inheritance chain for this float. We will never paint it.
-                floatingObj->m_renderer = r->m_renderer;
+                floatingObj->setRenderer(r->renderer());
 
                 // We create the floating object list lazily.
                 if (!m_floatingObjects)
@@ -4996,11 +4918,11 @@
     for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
         --it;
         FloatingObject* floatingObject = *it;
-        if (floatingObject->shouldPaint() && !floatingObject->m_renderer->hasSelfPaintingLayer()) {
-            LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->m_renderer->x();
-            LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->m_renderer->y();
+        if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
+            LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
+            LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
             LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
-            if (floatingObject->m_renderer->hitTest(request, result, locationInContainer, childPoint)) {
+            if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
                 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
                 return true;
             }
@@ -6411,10 +6333,8 @@
         // (the content inside them moves).  This matches WinIE as well, which just bottom-aligns them.
         // We also give up on finding a baseline if we have a vertical scrollbar, or if we are scrolled
         // vertically (e.g., an overflow:hidden block that has had scrollTop moved).
-        // inline-block with overflow should use the bottom of margin box as well.
         bool ignoreBaseline = (layer() && (isMarquee() || (direction == HorizontalLine ? (layer()->verticalScrollbar() || layer()->scrollYOffset())
-            : (layer()->horizontalScrollbar() || layer()->scrollXOffset())))) || (isWritingModeRoot() && !isRubyRun())
-            || (style()->isDisplayInlineType() && style()->overflowY() != OVISIBLE);
+            : (layer()->horizontalScrollbar() || layer()->scrollXOffset())))) || (isWritingModeRoot() && !isRubyRun());
 
         int baselinePos = ignoreBaseline ? -1 : inlineBlockBaseline(direction);
 
@@ -6468,6 +6388,11 @@
 
 int RenderBlock::inlineBlockBaseline(LineDirectionMode direction) const
 {
+    if (style()->overflowY() != OVISIBLE) {
+        // We are not calling RenderBox::baselinePosition here because the caller should add the margin-top/margin-right, not us.
+        return direction == HorizontalLine ? height() + m_marginBox.bottom() : width() + m_marginBox.left();
+    }
+
     return lastLineBoxBaseline(direction);
 }
 
@@ -6891,8 +6816,8 @@
                 FloatingObject* r = *it;
                 // Only examine the object if our m_shouldPaint flag is set.
                 if (r->shouldPaint()) {
-                    LayoutUnit floatLeft = xPositionForFloatIncludingMargin(r) - r->m_renderer->x();
-                    LayoutUnit floatRight = floatLeft + r->m_renderer->width();
+                    LayoutUnit floatLeft = xPositionForFloatIncludingMargin(r) - r->renderer()->x();
+                    LayoutUnit floatRight = floatLeft + r->renderer()->width();
                     left = min(left, floatLeft);
                     right = max(right, floatRight);
                 }
@@ -7576,11 +7501,13 @@
             child->setChildNeedsLayout(MarkOnlyThis);
         }
 
+        SubtreeLayoutScope layoutScope(child);
+
         if (childRenderBlock) {
             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
                 childRenderBlock->markAllDescendantsWithFloatsForLayout();
             if (!child->needsLayout())
-                child->markForPaginationRelayoutIfNeeded();
+                child->markForPaginationRelayoutIfNeeded(layoutScope);
         }
 
         // Our guess was wrong. Make the child lay itself out again.
@@ -7660,7 +7587,7 @@
         // FIXME: Sanity check that the renderer in the layout state is ours, since otherwise the computation will be off.
         // Right now this assert gets hit inside computeLogicalHeight for percentage margins, since they're computed using
         // widths which can vary in each region. Until we patch that, we can't have this assert.
-        // ASSERT(layoutState->m_renderer == this);
+        // ASSERT(layoutState->renderer() == this);
 
         LayoutSize offsetDelta = layoutState->m_layoutOffset - layoutState->m_pageOffset;
         return isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width();
@@ -7916,111 +7843,11 @@
     return "RenderBlock";
 }
 
-inline RenderBlock::FloatingObjects::FloatingObjects(const RenderBlock* renderer, bool horizontalWritingMode)
-    : m_placedFloatsTree(UninitializedTree)
-    , m_leftObjectsCount(0)
-    , m_rightObjectsCount(0)
-    , m_horizontalWritingMode(horizontalWritingMode)
-    , m_renderer(renderer)
-{
-}
-
 void RenderBlock::createFloatingObjects()
 {
     m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
 }
 
-inline void RenderBlock::FloatingObjects::clear()
-{
-    m_set.clear();
-    m_placedFloatsTree.clear();
-    m_leftObjectsCount = 0;
-    m_rightObjectsCount = 0;
-}
-
-inline void RenderBlock::FloatingObjects::increaseObjectsCount(FloatingObject::Type type)
-{
-    if (type == FloatingObject::FloatLeft)
-        m_leftObjectsCount++;
-    else
-        m_rightObjectsCount++;
-}
-
-inline void RenderBlock::FloatingObjects::decreaseObjectsCount(FloatingObject::Type type)
-{
-    if (type == FloatingObject::FloatLeft)
-        m_leftObjectsCount--;
-    else
-        m_rightObjectsCount--;
-}
-
-inline RenderBlock::FloatingObjectInterval RenderBlock::FloatingObjects::intervalForFloatingObject(FloatingObject* floatingObject)
-{
-    if (m_horizontalWritingMode)
-        return RenderBlock::FloatingObjectInterval(floatingObject->frameRect().pixelSnappedY(), floatingObject->frameRect().pixelSnappedMaxY(), floatingObject);
-    return RenderBlock::FloatingObjectInterval(floatingObject->frameRect().pixelSnappedX(), floatingObject->frameRect().pixelSnappedMaxX(), floatingObject);
-}
-
-void RenderBlock::FloatingObjects::addPlacedObject(FloatingObject* floatingObject)
-{
-    ASSERT(!floatingObject->isInPlacedTree());
-
-    floatingObject->setIsPlaced(true);
-    if (m_placedFloatsTree.isInitialized())
-        m_placedFloatsTree.add(intervalForFloatingObject(floatingObject));
-
-#ifndef NDEBUG
-    floatingObject->setIsInPlacedTree(true);
-#endif
-}
-
-void RenderBlock::FloatingObjects::removePlacedObject(FloatingObject* floatingObject)
-{
-    ASSERT(floatingObject->isPlaced() && floatingObject->isInPlacedTree());
-
-    if (m_placedFloatsTree.isInitialized()) {
-        bool removed = m_placedFloatsTree.remove(intervalForFloatingObject(floatingObject));
-        ASSERT_UNUSED(removed, removed);
-    }
-
-    floatingObject->setIsPlaced(false);
-#ifndef NDEBUG
-    floatingObject->setIsInPlacedTree(false);
-#endif
-}
-
-inline void RenderBlock::FloatingObjects::add(FloatingObject* floatingObject)
-{
-    increaseObjectsCount(floatingObject->type());
-    m_set.add(floatingObject);
-    if (floatingObject->isPlaced())
-        addPlacedObject(floatingObject);
-}
-
-inline void RenderBlock::FloatingObjects::remove(FloatingObject* floatingObject)
-{
-    decreaseObjectsCount(floatingObject->type());
-    m_set.remove(floatingObject);
-    ASSERT(floatingObject->isPlaced() || !floatingObject->isInPlacedTree());
-    if (floatingObject->isPlaced())
-        removePlacedObject(floatingObject);
-}
-
-void RenderBlock::FloatingObjects::computePlacedFloatsTree()
-{
-    ASSERT(!m_placedFloatsTree.isInitialized());
-    if (m_set.isEmpty())
-        return;
-    m_placedFloatsTree.initIfNeeded(m_renderer->view()->intervalArena());
-    FloatingObjectSetIterator it = m_set.begin();
-    FloatingObjectSetIterator end = m_set.end();
-    for (; it != end; ++it) {
-        FloatingObject* floatingObject = *it;
-        if (floatingObject->isPlaced())
-            m_placedFloatsTree.add(intervalForFloatingObject(floatingObject));
-    }
-}
-
 template <typename CharacterType>
 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
 {
@@ -8155,18 +7982,6 @@
         root->showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj, 1);
 }
 
-// These helpers are only used by the PODIntervalTree for debugging purposes.
-String ValueToString<int>::string(const int value)
-{
-    return String::number(value);
-}
-
-String ValueToString<RenderBlock::FloatingObject*>::string(const RenderBlock::FloatingObject* floatingObject)
-{
-    return String::format("%p (%dx%d %dx%d)", floatingObject, floatingObject->frameRect().pixelSnappedX(), floatingObject->frameRect().pixelSnappedY(), floatingObject->frameRect().pixelSnappedMaxX(), floatingObject->frameRect().pixelSnappedMaxY());
-}
-
-
 #endif
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index 06300e8..24cc747 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -23,10 +23,10 @@
 #ifndef RenderBlock_h
 #define RenderBlock_h
 
-#include "core/platform/PODIntervalTree.h"
 #include "core/platform/graphics/TextRun.h"
 #include "core/platform/text/TextBreakIterator.h"
 #include "core/rendering/ColumnInfo.h"
+#include "core/rendering/FloatingObjects.h"
 #include "core/rendering/GapRects.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderLineBoxList.h"
@@ -78,11 +78,6 @@
 class RenderBlock : public RenderBox {
 public:
     friend class LineLayoutState;
-#ifndef NDEBUG
-    // Used by the PODIntervalTree for debugging the FloatingObject.
-    template <class> friend struct ValueToString;
-#endif
-
     explicit RenderBlock(ContainerNode*);
     virtual ~RenderBlock();
 
@@ -154,7 +149,9 @@
     void markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove = 0, bool inLayout = true);
     void markSiblingsWithFloatsForLayout(RenderBox* floatToRemove = 0);
     void markPositionedObjectsForLayout();
-    virtual void markForPaginationRelayoutIfNeeded() OVERRIDE FINAL;
+    // FIXME: Do we really need this to be virtual? It's just so we can call this on
+    // RenderBoxes without needed to check whether they're RenderBlocks first.
+    virtual void markForPaginationRelayoutIfNeeded(SubtreeLayoutScope&) OVERRIDE FINAL;
 
     bool containsFloats() const { return m_floatingObjects && !m_floatingObjects->set().isEmpty(); }
     bool containsFloat(RenderBox*) const;
@@ -455,6 +452,7 @@
     }
     ShapeInsideInfo* layoutShapeInsideInfo() const;
     bool allowsShapeInsideInfoSharing() const { return !isInline() && !isFloating(); }
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
 protected:
     virtual void willBeDestroyed();
@@ -494,7 +492,7 @@
     virtual void layout();
 
     void layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly = false);
-    void markFixedPositionObjectForLayoutIfNeeded(RenderObject* child);
+    void markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope&);
 
     virtual void paint(PaintInfo&, const LayoutPoint&);
     virtual void paintObject(PaintInfo&, const LayoutPoint&);
@@ -583,8 +581,6 @@
     virtual void checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight);
 
 private:
-    enum ShapeOutsideFloatOffsetMode { ShapeOutsideFloatShapeOffset, ShapeOutsideFloatMarginBoxOffset };
-
     LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
     LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
     LayoutUnit adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
@@ -624,7 +620,7 @@
 
     virtual void repaintOverhangingFloats(bool paintAllDescendants) OVERRIDE FINAL;
 
-    void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom);
+    void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
     void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
     BidiRun* handleTrailingSpaces(BidiRunList<BidiRun>&, BidiContext*);
 
@@ -634,7 +630,7 @@
     virtual RootInlineBox* createRootInlineBox(); // Subclassed by 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*/) { return 0; }
+    virtual RenderObject* layoutSpecialExcludedChild(bool /*relayoutChildren*/, SubtreeLayoutScope&) { return 0; }
 
     void createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderObject* currentChild);
     void updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderObject* firstLetterContainer);
@@ -654,145 +650,8 @@
         bool everHadLayout;
     };
 
-    struct FloatingObject {
-        WTF_MAKE_NONCOPYABLE(FloatingObject); WTF_MAKE_FAST_ALLOCATED;
-    public:
-        // Note that Type uses bits so you can use FloatLeftRight as a mask to query for both left and right.
-        enum Type { FloatLeft = 1, FloatRight = 2, FloatLeftRight = 3 };
-
-        FloatingObject(EFloat type)
-            : m_renderer(0)
-            , m_originatingLine(0)
-            , m_paginationStrut(0)
-            , m_shouldPaint(true)
-            , m_isDescendant(false)
-            , m_isPlaced(false)
-#ifndef NDEBUG
-            , m_isInPlacedTree(false)
-#endif
-        {
-            ASSERT(type != NoFloat);
-            if (type == LeftFloat)
-                m_type = FloatLeft;
-            else if (type == RightFloat)
-                m_type = FloatRight;
-        }
-
-        FloatingObject(Type type, const LayoutRect& frameRect)
-            : m_renderer(0)
-            , m_originatingLine(0)
-            , m_frameRect(frameRect)
-            , m_paginationStrut(0)
-            , m_type(type)
-            , m_shouldPaint(true)
-            , m_isDescendant(false)
-            , m_isPlaced(true)
-#ifndef NDEBUG
-            , m_isInPlacedTree(false)
-#endif
-        {
-        }
-
-        FloatingObject* clone() const
-        {
-            FloatingObject* cloneObject = new FloatingObject(type(), m_frameRect);
-            cloneObject->m_renderer = m_renderer;
-            cloneObject->m_originatingLine = m_originatingLine;
-            cloneObject->m_paginationStrut = m_paginationStrut;
-            cloneObject->m_shouldPaint = m_shouldPaint;
-            cloneObject->m_isDescendant = m_isDescendant;
-            cloneObject->m_isPlaced = m_isPlaced;
-            return cloneObject;
-        }
-
-        Type type() const { return static_cast<Type>(m_type); }
-        RenderBox* renderer() const { return m_renderer; }
-
-        bool isPlaced() const { return m_isPlaced; }
-        void setIsPlaced(bool placed = true) { m_isPlaced = placed; }
-
-        inline LayoutUnit x() const { ASSERT(isPlaced()); return m_frameRect.x(); }
-        inline LayoutUnit maxX() const { ASSERT(isPlaced()); return m_frameRect.maxX(); }
-        inline LayoutUnit y() const { ASSERT(isPlaced()); return m_frameRect.y(); }
-        inline LayoutUnit maxY() const { ASSERT(isPlaced()); return m_frameRect.maxY(); }
-        inline LayoutUnit width() const { return m_frameRect.width(); }
-        inline LayoutUnit height() const { return m_frameRect.height(); }
-
-        void setX(LayoutUnit x) { ASSERT(!isInPlacedTree()); m_frameRect.setX(x); }
-        void setY(LayoutUnit y) { ASSERT(!isInPlacedTree()); m_frameRect.setY(y); }
-        void setWidth(LayoutUnit width) { ASSERT(!isInPlacedTree()); m_frameRect.setWidth(width); }
-        void setHeight(LayoutUnit height) { ASSERT(!isInPlacedTree()); m_frameRect.setHeight(height); }
-
-        const LayoutRect& frameRect() const { ASSERT(isPlaced()); return m_frameRect; }
-        void setFrameRect(const LayoutRect& frameRect) { ASSERT(!isInPlacedTree()); m_frameRect = frameRect; }
-
-#ifndef NDEBUG
-        bool isInPlacedTree() const { return m_isInPlacedTree; }
-        void setIsInPlacedTree(bool value) { m_isInPlacedTree = value; }
-#endif
-
-        bool shouldPaint() const { return m_shouldPaint; }
-        void setShouldPaint(bool shouldPaint) { m_shouldPaint = shouldPaint; }
-        bool isDescendant() const { return m_isDescendant; }
-        void setIsDescendant(bool isDescendant) { m_isDescendant = isDescendant; }
-
-        RenderBox* m_renderer;
-        RootInlineBox* m_originatingLine;
-        LayoutRect m_frameRect;
-        int m_paginationStrut;
-
-    private:
-        unsigned m_type : 2; // Type (left or right aligned)
-        unsigned m_shouldPaint : 1;
-        unsigned m_isDescendant : 1;
-        unsigned m_isPlaced : 1;
-#ifndef NDEBUG
-        unsigned m_isInPlacedTree : 1;
-#endif
-    };
-
     LayoutPoint flipFloatForWritingModeForChild(const FloatingObject*, const LayoutPoint&) const;
 
-    LayoutUnit logicalTopForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->y() : child->x(); }
-    LayoutUnit logicalBottomForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->maxY() : child->maxX(); }
-    LayoutUnit logicalLeftForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->x() : child->y(); }
-    LayoutUnit logicalRightForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->maxX() : child->maxY(); }
-    LayoutUnit logicalWidthForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->width() : child->height(); }
-
-    int pixelSnappedLogicalTopForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->frameRect().pixelSnappedY() : child->frameRect().pixelSnappedX(); }
-    int pixelSnappedLogicalBottomForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->frameRect().pixelSnappedMaxY() : child->frameRect().pixelSnappedMaxX(); }
-    int pixelSnappedLogicalLeftForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->frameRect().pixelSnappedX() : child->frameRect().pixelSnappedY(); }
-    int pixelSnappedLogicalRightForFloat(const FloatingObject* child) const { return isHorizontalWritingMode() ? child->frameRect().pixelSnappedMaxX() : child->frameRect().pixelSnappedMaxY(); }
-
-    void setLogicalTopForFloat(FloatingObject* child, LayoutUnit logicalTop)
-    {
-        if (isHorizontalWritingMode())
-            child->setY(logicalTop);
-        else
-            child->setX(logicalTop);
-    }
-    void setLogicalLeftForFloat(FloatingObject* child, LayoutUnit logicalLeft)
-    {
-        if (isHorizontalWritingMode())
-            child->setX(logicalLeft);
-        else
-            child->setY(logicalLeft);
-    }
-    void setLogicalHeightForFloat(FloatingObject* child, LayoutUnit logicalHeight)
-    {
-        if (isHorizontalWritingMode())
-            child->setHeight(logicalHeight);
-        else
-            child->setWidth(logicalHeight);
-    }
-    void setLogicalWidthForFloat(FloatingObject* child, LayoutUnit logicalWidth)
-    {
-        if (isHorizontalWritingMode())
-            child->setWidth(logicalWidth);
-        else
-            child->setHeight(logicalWidth);
-    }
-
     LayoutUnit xPositionForFloatIncludingMargin(const FloatingObject* child) const
     {
         if (isHorizontalWritingMode())
@@ -1148,108 +1007,11 @@
     RenderRegion* clampToStartAndEndRegions(RenderRegion*) const;
 
 protected:
-    struct FloatingObjectHashFunctions {
-        static unsigned hash(FloatingObject* key) { return DefaultHash<RenderBox*>::Hash::hash(key->m_renderer); }
-        static bool equal(FloatingObject* a, FloatingObject* b) { return a->m_renderer == b->m_renderer; }
-        static const bool safeToCompareToEmptyOrDeleted = true;
-    };
-    struct FloatingObjectHashTranslator {
-        static unsigned hash(RenderBox* key) { return DefaultHash<RenderBox*>::Hash::hash(key); }
-        static bool equal(FloatingObject* a, RenderBox* b) { return a->m_renderer == b; }
-    };
-    typedef ListHashSet<FloatingObject*, 4, FloatingObjectHashFunctions> FloatingObjectSet;
-    typedef FloatingObjectSet::const_iterator FloatingObjectSetIterator;
-    typedef PODInterval<int, FloatingObject*> FloatingObjectInterval;
-    typedef PODIntervalTree<int, FloatingObject*> FloatingObjectTree;
-    typedef PODFreeListArena<PODRedBlackTree<FloatingObjectInterval>::Node> IntervalArena;
-
-    template <FloatingObject::Type FloatTypeValue>
-    class FloatIntervalSearchAdapter {
-    public:
-        typedef FloatingObjectInterval IntervalType;
-
-        FloatIntervalSearchAdapter(const RenderBlock* renderer, int lowValue, int highValue, LayoutUnit& offset, LayoutUnit* heightRemaining)
-            : m_renderer(renderer)
-            , m_lowValue(lowValue)
-            , m_highValue(highValue)
-            , m_offset(offset)
-            , m_heightRemaining(heightRemaining)
-            , m_last(0)
-        {
-        }
-
-        inline int lowValue() const { return m_lowValue; }
-        inline int highValue() const { return m_highValue; }
-        void collectIfNeeded(const IntervalType&) const;
-
-        // 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.
-        // We save the last float encountered so that the offset can be
-        // computed correctly by the code using this adapter.
-        const FloatingObject* lastFloat() const { return m_last; }
-
-    private:
-        bool updateOffsetIfNeeded(const FloatingObject*) const;
-
-        const RenderBlock* m_renderer;
-        int m_lowValue;
-        int m_highValue;
-        LayoutUnit& m_offset;
-        LayoutUnit* m_heightRemaining;
-        // This member variable is mutable because the collectIfNeeded method
-        // is declared as const, even though it doesn't actually respect that
-        // contract. It modifies other member variables via loopholes in the
-        // const behavior. Instead of using loopholes, I decided it was better
-        // to make the fact that this is modified in a const method explicit.
-        mutable const FloatingObject* m_last;
-    };
 
     void createFloatingObjects();
 
 public:
 
-    class FloatingObjects {
-        WTF_MAKE_NONCOPYABLE(FloatingObjects); WTF_MAKE_FAST_ALLOCATED;
-    public:
-        void clear();
-        void add(FloatingObject*);
-        void remove(FloatingObject*);
-        void addPlacedObject(FloatingObject*);
-        void removePlacedObject(FloatingObject*);
-        void setHorizontalWritingMode(bool b = true) { m_horizontalWritingMode = b; }
-
-        bool hasLeftObjects() const { return m_leftObjectsCount > 0; }
-        bool hasRightObjects() const { return m_rightObjectsCount > 0; }
-        const FloatingObjectSet& set() const { return m_set; }
-        const FloatingObjectTree& placedFloatsTree()
-        {
-            computePlacedFloatsTreeIfNeeded();
-            return m_placedFloatsTree;
-        }
-    private:
-        FloatingObjects(const RenderBlock*, bool horizontalWritingMode);
-        void computePlacedFloatsTree();
-        inline void computePlacedFloatsTreeIfNeeded()
-        {
-            if (!m_placedFloatsTree.isInitialized())
-                computePlacedFloatsTree();
-        }
-        void increaseObjectsCount(FloatingObject::Type);
-        void decreaseObjectsCount(FloatingObject::Type);
-        FloatingObjectInterval intervalForFloatingObject(FloatingObject*);
-
-        FloatingObjectSet m_set;
-        FloatingObjectTree m_placedFloatsTree;
-        unsigned m_leftObjectsCount;
-        unsigned m_rightObjectsCount;
-        bool m_horizontalWritingMode;
-        const RenderBlock* m_renderer;
-
-        friend void RenderBlock::createFloatingObjects();
-    };
-
     // Allocated only when some of these fields have non-default values
     struct RenderBlockRareData {
         WTF_MAKE_NONCOPYABLE(RenderBlockRareData); WTF_MAKE_FAST_ALLOCATED;
@@ -1336,16 +1098,6 @@
 // This will catch anyone doing an unnecessary cast.
 void toRenderBlock(const RenderBlock*);
 
-#ifndef NDEBUG
-// These structures are used by PODIntervalTree for debugging purposes.
-template <> struct ValueToString<int> {
-    static String string(const int value);
-};
-template<> struct ValueToString<RenderBlock::FloatingObject*> {
-    static String string(const RenderBlock::FloatingObject*);
-};
-#endif
-
 } // namespace WebCore
 
 #endif // RenderBlock_h
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index f16fcb6..b418021 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -112,7 +112,7 @@
     float availableWidth() const { return m_availableWidth; }
 
     void updateAvailableWidth(LayoutUnit minimumHeight = 0);
-    void shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject*);
+    void shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject*);
     void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; }
     void commit()
     {
@@ -158,10 +158,10 @@
     computeAvailableWidthFromLeftAndRight();
 }
 
-inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject* newFloat)
+inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject* newFloat)
 {
     LayoutUnit height = m_block->logicalHeight();
-    if (height < m_block->logicalTopForFloat(newFloat) || height >= m_block->logicalBottomForFloat(newFloat))
+    if (height < newFloat->logicalTop(m_block->isHorizontalWritingMode()) || height >= newFloat->logicalBottom(m_block->isHorizontalWritingMode()))
         return;
 
     // When floats with shape outside are stacked, the floats are positioned based on the margin box of the float,
@@ -170,16 +170,16 @@
     // based on the margin box. In order to do this, we need to walk back through the floating object list to find
     // the first previous float that is on the same side as our newFloat.
     ShapeOutsideInfo* previousShapeOutsideInfo = 0;
-    const RenderBlock::FloatingObjectSet& floatingObjectSet = m_block->m_floatingObjects->set();
-    RenderBlock::FloatingObjectSetIterator it = floatingObjectSet.end();
-    RenderBlock::FloatingObjectSetIterator begin = floatingObjectSet.begin();
+    const FloatingObjectSet& floatingObjectSet = m_block->m_floatingObjects->set();
+    FloatingObjectSetIterator it = floatingObjectSet.end();
+    FloatingObjectSetIterator begin = floatingObjectSet.begin();
     while (it != begin) {
         --it;
-        RenderBlock::FloatingObject* previousFloat = *it;
+        FloatingObject* previousFloat = *it;
         if (previousFloat != newFloat && previousFloat->type() == newFloat->type()) {
             previousShapeOutsideInfo = previousFloat->renderer()->shapeOutsideInfo();
             if (previousShapeOutsideInfo) {
-                previousShapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block->logicalHeight(), m_block->logicalTopForFloat(previousFloat), logicalHeightForLine(m_block, m_isFirstLine));
+                previousShapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block->logicalHeight(), previousFloat->logicalTop(m_block->isHorizontalWritingMode()), logicalHeightForLine(m_block, m_isFirstLine));
             }
             break;
         }
@@ -187,10 +187,10 @@
 
     ShapeOutsideInfo* shapeOutsideInfo = newFloat->renderer()->shapeOutsideInfo();
     if (shapeOutsideInfo)
-        shapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block->logicalHeight(), m_block->logicalTopForFloat(newFloat), logicalHeightForLine(m_block, m_isFirstLine));
+        shapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block->logicalHeight(), newFloat->logicalTop(m_block->isHorizontalWritingMode()), logicalHeightForLine(m_block, m_isFirstLine));
 
-    if (newFloat->type() == RenderBlock::FloatingObject::FloatLeft) {
-        float newLeft = m_block->logicalRightForFloat(newFloat);
+    if (newFloat->type() == FloatingObject::FloatLeft) {
+        float newLeft = newFloat->logicalRight(m_block->isHorizontalWritingMode());
         if (previousShapeOutsideInfo)
             newLeft -= previousShapeOutsideInfo->rightSegmentMarginBoxDelta();
         if (shapeOutsideInfo)
@@ -200,7 +200,7 @@
             newLeft += floorToInt(m_block->textIndentOffset());
         m_left = max<float>(m_left, newLeft);
     } else {
-        float newRight = m_block->logicalLeftForFloat(newFloat);
+        float newRight = newFloat->logicalLeft(m_block->isHorizontalWritingMode());
         if (previousShapeOutsideInfo)
             newRight -= previousShapeOutsideInfo->leftSegmentMarginBoxDelta();
         if (shapeOutsideInfo)
@@ -344,9 +344,61 @@
     return extraWidth;
 }
 
-static void determineDirectionality(TextDirection& dir, InlineIterator iter)
+static RenderObject* firstRenderObjectForDirectionalityDetermination(RenderObject* root, RenderObject* current = 0)
 {
+    RenderObject* next = current;
+    while (current) {
+        if (isIsolated(current->style()->unicodeBidi())
+            && (current->isRenderInline() || current->isRenderBlock())) {
+            if (current != root)
+                current = 0;
+            else
+                current = next;
+            break;
+        }
+        current = current->parent();
+    }
+
+    if (!current)
+        current = root->firstChild();
+
+    while (current) {
+        next = 0;
+        if (isIteratorTarget(current) && !(current->isText() && toRenderText(current)->isAllCollapsibleWhitespace()))
+            break;
+
+        if (!isIteratorTarget(current) && !isIsolated(current->style()->unicodeBidi()))
+            next = current->firstChild();
+
+        if (!next) {
+            while (current && current != root) {
+                next = current->nextSibling();
+                if (next)
+                    break;
+                current = current->parent();
+            }
+        }
+
+        if (!next)
+            break;
+
+        current = next;
+    }
+
+    return current;
+}
+
+static void determinePlaintextDirectionality(TextDirection& dir, RenderObject* root, RenderObject* current = 0, unsigned pos = 0)
+{
+    InlineIterator iter(root, firstRenderObjectForDirectionalityDetermination(root, current), pos);
+    InlineBidiResolver observer;
+    observer.setPositionIgnoringNestedIsolates(iter);
+    observer.setStatus(BidiStatus(root->style()->direction(), isOverride(root->style()->unicodeBidi())));
     while (!iter.atEnd()) {
+        if (observer.inIsolate()) {
+            iter.increment(&observer);
+            continue;
+        }
         if (iter.atParagraphSeparator())
             return;
         if (UChar current = iter.current()) {
@@ -360,7 +412,7 @@
                 return;
             }
         }
-        iter.increment();
+        iter.increment(&observer);
     }
 }
 
@@ -1226,8 +1278,8 @@
 
 void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
 {
-    ASSERT(!floatingObject->m_originatingLine);
-    floatingObject->m_originatingLine = lastRootBox();
+    ASSERT(!floatingObject->originatingLine());
+    floatingObject->setOriginatingLine(lastRootBox());
     lastRootBox()->appendFloat(floatingObject->renderer());
 }
 
@@ -1276,9 +1328,9 @@
 
         InlineBidiResolver isolatedResolver;
         EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
-        TextDirection direction;
+        TextDirection direction = isolatedInline->style()->direction();
         if (unicodeBidi == Plaintext)
-            determineDirectionality(direction, InlineIterator(isolatedInline, isolatedRun->object(), 0));
+            determinePlaintextDirectionality(direction, isolatedInline, startObj);
         else {
             ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride);
             direction = isolatedInline->style()->direction();
@@ -1309,6 +1361,7 @@
         if (!isolatedResolver.isolatedRuns().isEmpty()) {
             topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns());
             isolatedResolver.isolatedRuns().clear();
+            currentRoot = isolatedInline;
         }
     }
 }
@@ -1443,8 +1496,8 @@
     RootInlineBox* endLine() const { return m_endLine; }
     void setEndLine(RootInlineBox* line) { m_endLine = line; }
 
-    RenderBlock::FloatingObject* lastFloat() const { return m_lastFloat; }
-    void setLastFloat(RenderBlock::FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
+    FloatingObject* lastFloat() const { return m_lastFloat; }
+    void setLastFloat(FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
 
     Vector<RenderBlock::FloatWithRect>& floats() { return m_floats; }
 
@@ -1459,7 +1512,7 @@
 
 private:
     Vector<RenderBlock::FloatWithRect> m_floats;
-    RenderBlock::FloatingObject* m_lastFloat;
+    FloatingObject* m_lastFloat;
     RootInlineBox* m_endLine;
     LineInfo m_lineInfo;
     unsigned m_floatIndex;
@@ -1804,7 +1857,7 @@
 
             if (isNewUBAParagraph && styleToUse->unicodeBidi() == Plaintext && !resolver.context()->parent()) {
                 TextDirection direction = styleToUse->direction();
-                determineDirectionality(direction, resolver.position());
+                determinePlaintextDirectionality(direction, resolver.position().root(), resolver.position().object(), resolver.position().offset());
                 resolver.setStatus(BidiStatus(direction, isOverride(styleToUse->unicodeBidi())));
             }
             // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
@@ -1881,7 +1934,7 @@
             for (; it != end; ++it) {
                 FloatingObject* f = *it;
                 appendFloatingObjectToLastLine(f);
-                ASSERT(f->m_renderer == layoutState.floats()[layoutState.floatIndex()].object);
+                ASSERT(f->renderer() == layoutState.floats()[layoutState.floatIndex()].object);
                 // If a float's geometry has changed, give up on syncing with clean lines.
                 if (layoutState.floats()[layoutState.floatIndex()].rect != f->frameRect())
                     checkForEndLineMatch = false;
@@ -1975,8 +2028,8 @@
                     Vector<RenderBox*>::iterator end = cleanLineFloats->end();
                     for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
                         FloatingObject* floatingObject = insertFloatingObject(*f);
-                        ASSERT(!floatingObject->m_originatingLine);
-                        floatingObject->m_originatingLine = line;
+                        ASSERT(!floatingObject->originatingLine());
+                        floatingObject->setOriginatingLine(line);
                         setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f) + delta);
                         positionNewFloats();
                     }
@@ -2266,8 +2319,8 @@
                 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
                 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
                     FloatingObject* floatingObject = insertFloatingObject(*f);
-                    ASSERT(!floatingObject->m_originatingLine);
-                    floatingObject->m_originatingLine = line;
+                    ASSERT(!floatingObject->originatingLine());
+                    floatingObject->setOriginatingLine(line);
                     setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f));
                     positionNewFloats();
                     ASSERT(layoutState.floats()[numCleanFloats].object == *f);
@@ -2291,7 +2344,7 @@
     } else {
         TextDirection direction = style()->direction();
         if (style()->unicodeBidi() == Plaintext)
-            determineDirectionality(direction, InlineIterator(this, bidiFirstSkippingEmptyInlines(this), 0));
+            determinePlaintextDirectionality(direction, this);
         resolver.setStatus(BidiStatus(direction, isOverride(style()->unicodeBidi())));
         InlineIterator iter = InlineIterator(this, bidiFirstSkippingEmptyInlines(this, &resolver), 0);
         resolver.setPosition(iter, numberOfIsolateAncestors(iter));
@@ -2374,7 +2427,7 @@
     FloatingObjectSetIterator end = floatingObjectSet.end();
     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
         FloatingObject* f = *it;
-        if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
+        if (f->logicalBottom(isHorizontalWritingMode()) >= logicalTop && f->logicalBottom(isHorizontalWritingMode()) < logicalBottom)
             return false;
     }
 
@@ -2832,7 +2885,7 @@
             // 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 (floatsFitOnLine && width.fitsOnLine(m_block->logicalWidthForFloat(f))) {
+            if (floatsFitOnLine && width.fitsOnLine(f->logicalWidth(m_block->isHorizontalWritingMode()))) {
                 m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, lineInfo, width);
                 if (lBreak.m_obj == current.m_obj) {
                     ASSERT(!lBreak.m_pos);
@@ -3401,14 +3454,14 @@
     // We only connect floats to lines for pagination purposes if the floats occur at the start of
     // the line and the previous line had a hard break (so this line is either the first in the block
     // or follows a <br>).
-    if (!newFloat->m_paginationStrut || !lineInfo.previousLineBrokeCleanly() || !lineInfo.isEmpty())
+    if (!newFloat->paginationStrut() || !lineInfo.previousLineBrokeCleanly() || !lineInfo.isEmpty())
         return true;
 
     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
     ASSERT(floatingObjectSet.last() == newFloat);
 
-    LayoutUnit floatLogicalTop = logicalTopForFloat(newFloat);
-    int paginationStrut = newFloat->m_paginationStrut;
+    LayoutUnit floatLogicalTop = newFloat->logicalTop(isHorizontalWritingMode());
+    int paginationStrut = newFloat->paginationStrut();
 
     if (floatLogicalTop - paginationStrut != logicalHeight() + lineInfo.floatPaginationStrut())
         return true;
@@ -3421,18 +3474,19 @@
         FloatingObject* f = *it;
         if (f == lastFloatFromPreviousLine)
             break;
-        if (logicalTopForFloat(f) == logicalHeight() + lineInfo.floatPaginationStrut()) {
-            f->m_paginationStrut += paginationStrut;
-            RenderBox* o = f->m_renderer;
+        if (f->logicalTop(isHorizontalWritingMode()) == logicalHeight() + lineInfo.floatPaginationStrut()) {
+            f->setPaginationStrut(paginationStrut + f->paginationStrut());
+            RenderBox* o = f->renderer();
             setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
             if (o->isRenderBlock())
-                toRenderBlock(o)->setChildNeedsLayout(MarkOnlyThis);
-            o->layoutIfNeeded();
+                o->forceChildLayout();
+            else
+                o->layoutIfNeeded();
             // Save the old logical top before calling removePlacedObject which will set
             // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
-            LayoutUnit oldLogicalTop = logicalTopForFloat(f);
+            LayoutUnit oldLogicalTop = f->logicalTop(isHorizontalWritingMode());
             m_floatingObjects->removePlacedObject(f);
-            setLogicalTopForFloat(f, oldLogicalTop + paginationStrut);
+            f->setLogicalTop(oldLogicalTop + paginationStrut, isHorizontalWritingMode());
             m_floatingObjects->addPlacedObject(f);
         }
     }
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index bb53fd5..91cca45 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -708,10 +708,15 @@
     return 0;
 }
 
-bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
+bool RenderBox::scrollImpl(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
 {
     RenderLayer* l = layer();
-    if (l && l->scroll(direction, granularity, multiplier)) {
+    return l && l->scroll(direction, granularity, multiplier);
+}
+
+bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
+{
+    if (scrollImpl(direction, granularity, multiplier)) {
         if (stopNode)
             *stopNode = node();
         return true;
@@ -728,18 +733,11 @@
 
 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
 {
-    bool scrolled = false;
-
-    RenderLayer* l = layer();
-    if (l) {
-        if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), granularity, multiplier))
-            scrolled = true;
-
-        if (scrolled) {
-            if (stopNode)
-                *stopNode = node();
-            return true;
-        }
+    if (scrollImpl(logicalToPhysical(direction, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()),
+        granularity, multiplier)) {
+        if (stopNode)
+            *stopNode = node();
+        return true;
     }
 
     if (stopNode && *stopNode && *stopNode == node())
@@ -808,6 +806,8 @@
     IntSize offset;
     IntPoint point = frameView->windowToContents(windowPoint);
     IntRect box(absoluteBoundingBoxRect());
+    if (isRenderView())
+        box.moveBy(frameView->windowToContents(IntPoint()));
 
     if (point.x() < box.x() + autoscrollBeltSize)
         point.move(-autoscrollBeltSize, 0);
@@ -1539,6 +1539,11 @@
         if (contentsVisualOverflow.isEmpty())
             return false;
 
+        // FIXME: Get rid of this slop from here and elsewhere.
+        // Instead, properly include the outline in visual overflow.
+        if (RenderView* view = this->view())
+            contentsVisualOverflow.inflate(view->maximalOutlineSize());
+
         LayoutRect conservativeClipRect = clipRect;
         if (hasBorderRadius)
             conservativeClipRect.intersect(clipRoundedRect.radiusCenterRect());
@@ -2738,6 +2743,17 @@
             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
             availableHeight = max<LayoutUnit>(0, contentBoxHeight);
         }
+    } else if (cbstyle->logicalHeight().isViewportPercentage()) {
+        LayoutUnit heightWithScrollbar = valueForLength(cbstyle->logicalHeight(), 0, view());
+        if (heightWithScrollbar != -1) {
+            LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
+            // We need to adjust for min/max height because this method does not
+            // handle the min/max of the current block, its caller does. So the
+            // return value from the recursive call will not have been adjusted
+            // yet.
+            LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
+            availableHeight = max<LayoutUnit>(0, contentBoxHeight);
+        }
     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
         // Don't allow this to affect the block' height() member variable, since this
         // can get called while the block is still laying out its kids.
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index 4246b71..bda7815 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -464,10 +464,14 @@
     bool hasAutoVerticalScrollbar() const { return hasOverflowClip() && (style()->overflowY() == OAUTO || style()->overflowY() == OOVERLAY); }
     bool hasAutoHorizontalScrollbar() const { return hasOverflowClip() && (style()->overflowX() == OAUTO || style()->overflowX() == OOVERLAY); }
     bool scrollsOverflow() const { return scrollsOverflowX() || scrollsOverflowY(); }
-    bool scrollsOverflowX() const { return hasOverflowClip() && (style()->overflowX() == OSCROLL || hasAutoHorizontalScrollbar()); }
-    bool scrollsOverflowY() const { return hasOverflowClip() && (style()->overflowY() == OSCROLL || hasAutoVerticalScrollbar()); }
+    virtual bool scrollsOverflowX() const { return hasOverflowClip() && (style()->overflowX() == OSCROLL || hasAutoHorizontalScrollbar()); }
+    virtual bool scrollsOverflowY() const { return hasOverflowClip() && (style()->overflowY() == OSCROLL || hasAutoVerticalScrollbar()); }
     bool usesCompositedScrolling() const;
 
+    // Elements such as the <input> field override this to specify that they are scrollable
+    // outside the context of the CSS overflow style
+    virtual bool isIntristicallyScrollable(ScrollbarOrientation orientation) const { return false; }
+
     bool hasUnsplittableScrollingOverflow() const;
     bool isUnsplittableForPagination() const;
 
@@ -512,7 +516,7 @@
     bool shrinkToAvoidFloats() const;
     virtual bool avoidsFloats() const;
 
-    virtual void markForPaginationRelayoutIfNeeded() { }
+    virtual void markForPaginationRelayoutIfNeeded(SubtreeLayoutScope&) { }
 
     bool isWritingModeRoot() const { return !parent() || parent()->style()->writingMode() != style()->writingMode(); }
 
@@ -670,6 +674,10 @@
 
     virtual LayoutRect frameRectForStickyPositioning() const OVERRIDE FINAL { return frameRect(); }
 
+    // This method performs the actual scroll. Override if scrolling without a RenderLayer. The scroll() and logicalScroll()
+    // are responsible for scroll propagation/bubbling and call this method to do the actual scrolling
+    virtual bool scrollImpl(ScrollDirection, ScrollGranularity, float);
+
 private:
     // The width/height of the contents + borders + padding.  The x/y location is relative to our container (which is not always our parent).
     LayoutRect m_frameRect;
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index d2be443..f6a8072 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -1061,16 +1061,42 @@
     int availableHeight = positioningAreaSize.height() - geometry.tileSize().height();
 
     LayoutUnit computedXPosition = minimumValueForLength(fillLayer->xPosition(), availableWidth, renderView, true);
-    if (backgroundRepeatX == RepeatFill)
+    if (backgroundRepeatX == RoundFill && positioningAreaSize.width() > 0 && fillTileSize.width() > 0) {
+        int nrTiles = ceil((double)positioningAreaSize.width() /
+            fillTileSize.width());
+
+        if (fillLayer->size().size.height().isAuto() && backgroundRepeatY != RoundFill) {
+            fillTileSize.setHeight(fillTileSize.height() * positioningAreaSize.width() / (nrTiles * fillTileSize.width()));
+        }
+
+        fillTileSize.setWidth(positioningAreaSize.width() / nrTiles);
+        geometry.setTileSize(fillTileSize);
         geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0);
-    else {
+    }
+
+    LayoutUnit computedYPosition = minimumValueForLength(fillLayer->yPosition(), availableHeight, renderView, true);
+    if (backgroundRepeatY == RoundFill && positioningAreaSize.height() > 0 && fillTileSize.height() > 0) {
+        int nrTiles = ceil((double)positioningAreaSize.height() /
+            fillTileSize.height());
+
+        if (fillLayer->size().size.width().isAuto() && backgroundRepeatX != RoundFill) {
+            fillTileSize.setWidth(fillTileSize.width() * positioningAreaSize.height() / (nrTiles * fillTileSize.height()));
+        }
+
+        fillTileSize.setHeight(positioningAreaSize.height() / nrTiles);
+        geometry.setTileSize(fillTileSize);
+        geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0);
+    }
+
+    if (backgroundRepeatX == RepeatFill) {
+        geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0);
+    } else if (backgroundRepeatX == NoRepeatFill) {
         int xOffset = fillLayer->backgroundXOrigin() == RightEdge ? availableWidth - computedXPosition : computedXPosition;
         geometry.setNoRepeatX(left + xOffset);
     }
-    LayoutUnit computedYPosition = minimumValueForLength(fillLayer->yPosition(), availableHeight, renderView, true);
-    if (backgroundRepeatY == RepeatFill)
+    if (backgroundRepeatY == RepeatFill) {
         geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0);
-    else {
+    } else if (backgroundRepeatY == NoRepeatFill) {
         int yOffset = fillLayer->backgroundYOrigin() == BottomEdge ? availableHeight - computedYPosition : computedYPosition;
         geometry.setNoRepeatY(top + yOffset);
     }
@@ -2423,8 +2449,9 @@
 
     bool hasBorderRadius = s->hasBorderRadius();
     bool isHorizontal = s->isHorizontalWritingMode();
-
     bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
+
+    GraphicsContextStateSaver stateSaver(*context, false);
     for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
         if (shadow->style() != shadowStyle)
             continue;
@@ -2448,26 +2475,50 @@
             shadowRect.inflate(shadowBlur + shadowSpread);
             shadowRect.move(shadowOffset);
 
+            // Save the state and clip, if not already done.
+            // The clip does not depend on any shadow-specific properties.
+            if (!stateSaver.saved()) {
+                stateSaver.save();
+                if (hasBorderRadius) {
+                    RoundedRect rectToClipOut = border;
+
+                    // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
+                    // when painting the shadow. On the other hand, it introduces subpixel gaps along the
+                    // corners. Those are avoided by insetting the clipping path by one pixel.
+                    if (hasOpaqueBackground)
+                        rectToClipOut.inflateWithRadii(-1);
+
+                    if (!rectToClipOut.isEmpty()) {
+                        context->clipOutRoundedRect(rectToClipOut);
+                    }
+                } else {
+                    IntRect rectToClipOut = border.rect();
+
+                    // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
+                    // when painting the shadow. On the other hand, it introduces subpixel gaps along the
+                    // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
+                    // by one pixel.
+                    if (hasOpaqueBackground) {
+                        // FIXME: The function to decide on the policy based on the transform should be a named function.
+                        // FIXME: It's not clear if this check is right. What about integral scale factors?
+                        AffineTransform transform = context->getCTM();
+                        if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
+                            rectToClipOut.inflate(-1);
+                    }
+
+                    if (!rectToClipOut.isEmpty()) {
+                        context->clipOut(rectToClipOut);
+                    }
+                }
+            }
+
             // Draw only the shadow.
             DrawLooper drawLooper;
             drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
             context->setDrawLooper(drawLooper);
 
-            context->save();
             if (hasBorderRadius) {
-                RoundedRect rectToClipOut = border;
-
-                // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
-                // when painting the shadow. On the other hand, it introduces subpixel gaps along the
-                // corners. Those are avoided by insetting the clipping path by one pixel.
-                if (hasOpaqueBackground)
-                    rectToClipOut.inflateWithRadii(-1);
-
-                if (!rectToClipOut.isEmpty()) {
-                    context->clipOutRoundedRect(rectToClipOut);
-                }
-
                 RoundedRect influenceRect(shadowRect, border.radii());
                 influenceRect.expandRadii(2 * shadowBlur + shadowSpread);
                 if (allCornersClippedOut(influenceRect, info.rect))
@@ -2479,27 +2530,8 @@
                     context->fillRoundedRect(fillRect, Color::black);
                 }
             } else {
-                IntRect rectToClipOut = border.rect();
-
-                // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
-                // when painting the shadow. On the other hand, it introduces subpixel gaps along the
-                // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
-                // by one pixel.
-                if (hasOpaqueBackground) {
-                    // FIXME: The function to decide on the policy based on the transform should be a named function.
-                    // FIXME: It's not clear if this check is right. What about integral scale factors?
-                    AffineTransform transform = context->getCTM();
-                    if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
-                        rectToClipOut.inflate(-1);
-                }
-
-                if (!rectToClipOut.isEmpty()) {
-                    context->clipOut(rectToClipOut);
-                }
                 context->fillRect(fillRect.rect(), Color::black);
             }
-            context->restore();
-            context->clearDrawLooper();
         } else {
             GraphicsContext::Edges clippedEdges = GraphicsContext::NoEdge;
             if (!includeLogicalLeftEdge) {
diff --git a/Source/core/rendering/RenderCounter.cpp b/Source/core/rendering/RenderCounter.cpp
index 5da28ef..a6055c2 100644
--- a/Source/core/rendering/RenderCounter.cpp
+++ b/Source/core/rendering/RenderCounter.cpp
@@ -25,7 +25,7 @@
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLOListElement.h"
 #include "core/rendering/CounterNode.h"
 #include "core/rendering/RenderListItem.h"
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index bdf05c9..f3bd1d9 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -391,18 +391,18 @@
         // our box's intrinsic height.
         LayoutUnit maxAscent = 0, maxDescent = 0;
         for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
-            // make sure we relayout children if we need it.
-            if (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent())))
-                child->setChildNeedsLayout(MarkOnlyThis);
-
             if (child->isOutOfFlowPositioned())
                 continue;
 
+            SubtreeLayoutScope layoutScope(child);
+            if (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent())))
+                layoutScope.setChildNeedsLayout(child);
+
             // Compute the child's vertical margins.
             child->computeAndSetBlockDirectionMargins(this);
 
             if (!child->needsLayout())
-                child->markForPaginationRelayoutIfNeeded();
+                child->markForPaginationRelayoutIfNeeded(layoutScope);
 
             // Now do the layout.
             child->layoutIfNeeded();
@@ -462,6 +462,7 @@
                 continue;
             }
 
+            SubtreeLayoutScope layoutScope(child);
 
             // We need to see if this child's height has changed, since we make block elements
             // fill the height of a containing box by default.
@@ -469,10 +470,10 @@
             LayoutUnit oldChildHeight = child->height();
             child->updateLogicalHeight();
             if (oldChildHeight != child->height())
-                child->setChildNeedsLayout(MarkOnlyThis);
+                layoutScope.setChildNeedsLayout(child);
 
             if (!child->needsLayout())
-                child->markForPaginationRelayoutIfNeeded();
+                child->markForPaginationRelayoutIfNeeded(layoutScope);
 
             child->layoutIfNeeded();
 
@@ -680,10 +681,6 @@
         LayoutUnit minHeight = height() + toAdd;
 
         for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
-            // Make sure we relayout children if we need it.
-            if (!haveLineClamp && (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent()))))
-                child->setChildNeedsLayout(MarkOnlyThis);
-
             if (child->isOutOfFlowPositioned()) {
                 child->containingBlock()->insertPositionedObject(child);
                 RenderLayer* childLayer = child->layer();
@@ -696,6 +693,10 @@
                 continue;
             }
 
+            SubtreeLayoutScope layoutScope(child);
+            if (!haveLineClamp && (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent()))))
+                layoutScope.setChildNeedsLayout(child);
+
             if (child->style()->visibility() == COLLAPSE) {
                 // visibility: collapsed children do not participate in our positioning.
                 // But we need to lay them down.
@@ -710,7 +711,7 @@
             setHeight(height() + child->marginTop());
 
             if (!child->needsLayout())
-                child->markForPaginationRelayoutIfNeeded();
+                child->markForPaginationRelayoutIfNeeded(layoutScope);
 
             // Now do a layout.
             child->layoutIfNeeded();
diff --git a/Source/core/rendering/RenderFieldset.cpp b/Source/core/rendering/RenderFieldset.cpp
index 7587425..ba01593 100644
--- a/Source/core/rendering/RenderFieldset.cpp
+++ b/Source/core/rendering/RenderFieldset.cpp
@@ -60,7 +60,7 @@
     }
 }
 
-RenderObject* RenderFieldset::layoutSpecialExcludedChild(bool relayoutChildren)
+RenderObject* RenderFieldset::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&)
 {
     RenderBox* legend = findLegend();
     if (legend) {
diff --git a/Source/core/rendering/RenderFieldset.h b/Source/core/rendering/RenderFieldset.h
index 151d535..0bfd538 100644
--- a/Source/core/rendering/RenderFieldset.h
+++ b/Source/core/rendering/RenderFieldset.h
@@ -39,7 +39,7 @@
     virtual const char* renderName() const { return "RenderFieldSet"; }
     virtual bool isFieldset() const { return true; }
 
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren);
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
 
     virtual void computePreferredLogicalWidths();
     virtual bool avoidsFloats() const { return true; }
diff --git a/Source/core/rendering/RenderFlexibleBox.cpp b/Source/core/rendering/RenderFlexibleBox.cpp
index 54139ab..0dbf969 100644
--- a/Source/core/rendering/RenderFlexibleBox.cpp
+++ b/Source/core/rendering/RenderFlexibleBox.cpp
@@ -901,18 +901,19 @@
         LayoutUnit childMainAxisExtent = preferredMainAxisContentExtentForChild(child, hasInfiniteLineLength);
         LayoutUnit childMainAxisMarginBorderPadding = mainAxisBorderAndPaddingExtentForChild(child)
             + (isHorizontalFlow() ? child->marginWidth() : child->marginHeight());
-        LayoutUnit childMainAxisMarginBoxExtent = childMainAxisExtent + childMainAxisMarginBorderPadding;
+        LayoutUnit childFlexBaseSize = childMainAxisExtent + childMainAxisMarginBorderPadding;
 
-        if (isMultiline() && sumFlexBaseSize + childMainAxisMarginBoxExtent > lineBreakLength && lineHasInFlowItem)
+        LayoutUnit childMinMaxAppliedMainAxisExtent = adjustChildSizeForMinAndMax(child, childMainAxisExtent);
+        LayoutUnit childHypotheticalMainSize = childMinMaxAppliedMainAxisExtent + childMainAxisMarginBorderPadding;
+
+        if (isMultiline() && sumHypotheticalMainSize + childHypotheticalMainSize > lineBreakLength && lineHasInFlowItem)
             break;
         orderedChildren.append(child);
         lineHasInFlowItem  = true;
-        sumFlexBaseSize += childMainAxisMarginBoxExtent;
+        sumFlexBaseSize += childFlexBaseSize;
         totalFlexGrow += child->style()->flexGrow();
         totalWeightedFlexShrink += child->style()->flexShrink() * childMainAxisExtent;
-
-        LayoutUnit childMinMaxAppliedMainAxisExtent = adjustChildSizeForMinAndMax(child, childMainAxisExtent);
-        sumHypotheticalMainSize += childMinMaxAppliedMainAxisExtent + childMainAxisMarginBorderPadding;
+        sumHypotheticalMainSize += childHypotheticalMainSize;
     }
     return true;
 }
diff --git a/Source/core/rendering/RenderGeometryMap.cpp b/Source/core/rendering/RenderGeometryMap.cpp
index 1a23c42..842fbd3 100644
--- a/Source/core/rendering/RenderGeometryMap.cpp
+++ b/Source/core/rendering/RenderGeometryMap.cpp
@@ -26,6 +26,8 @@
 #include "config.h"
 #include "core/rendering/RenderGeometryMap.h"
 
+#include "core/page/Frame.h"
+#include "core/page/Page.h"
 #include "core/platform/graphics/transforms/TransformState.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
@@ -63,7 +65,7 @@
     for (int i = m_mapping.size() - 1; i >= 0; --i) {
         const RenderGeometryMapStep& currentStep = m_mapping[i];
 
-        // If container is the RenderView (step 0) we want to apply its scroll offset.
+        // If container is the root RenderView (step 0) we want to apply its fixed position offset.
         if (i > 0 && currentStep.m_renderer == container) {
 #if !ASSERT_DISABLED
             foundContainer = true;
@@ -79,14 +81,12 @@
         else if (currentStep.m_isFixedPosition)
             inFixed = true;
 
+        ASSERT(!i == isTopmostRenderView(currentStep.m_renderer));
+
         if (!i) {
-            // A null container indicates mapping through the RenderView, so including its transform (the page scale).
+            // A null container indicates mapping through the root RenderView, so including its transform (the page scale).
             if (!container && currentStep.m_transform)
                 transformState.applyTransform(*currentStep.m_transform.get());
-
-            // The root gets special treatment for fixed position
-            if (inFixed)
-                transformState.move(currentStep.m_offset.width(), currentStep.m_offset.height());
         } else {
             TransformState::TransformAccumulation accumulate = currentStep.m_accumulatingTransform ? TransformState::AccumulateTransform : TransformState::FlattenTransform;
             if (currentStep.m_transform)
@@ -94,6 +94,11 @@
             else
                 transformState.move(currentStep.m_offset.width(), currentStep.m_offset.height(), accumulate);
         }
+
+        if (inFixed && !currentStep.m_offsetForFixedPosition.isZero()) {
+            ASSERT(currentStep.m_renderer->isRenderView());
+            transformState.move(currentStep.m_offsetForFixedPosition);
+        }
     }
 
     ASSERT(foundContainer);
@@ -122,6 +127,20 @@
     return result;
 }
 
+#ifndef NDEBUG
+// Handy function to call from gdb while debugging mismatched point/rect errors.
+void RenderGeometryMap::dumpSteps()
+{
+    fprintf(stderr, "RenderGeometryMap::dumpSteps accumulatedOffset=%d,%d\n", m_accumulatedOffset.width().toInt(), m_accumulatedOffset.height().toInt());
+    for (int i = m_mapping.size() - 1; i >= 0; --i) {
+        fprintf(stderr, " [%d] %s: offset=%d,%d", i, m_mapping[i].m_renderer->debugName().ascii().data(), m_mapping[i].m_offset.width().toInt(), m_mapping[i].m_offset.height().toInt());
+        if (m_mapping[i].m_hasTransform)
+            fprintf(stderr, " hasTransform");
+        fprintf(stderr, "\n");
+    }
+}
+#endif
+
 FloatQuad RenderGeometryMap::mapToContainer(const FloatRect& rect, const RenderLayerModelObject* container) const
 {
     FloatRect result;
@@ -155,7 +174,7 @@
         renderer = renderer->pushMappingToContainer(ancestorRenderer, *this);
     } while (renderer && renderer != ancestorRenderer);
 
-    ASSERT(m_mapping.isEmpty() || m_mapping[0].m_renderer->isRenderView());
+    ASSERT(m_mapping.isEmpty() || isTopmostRenderView(m_mapping[0].m_renderer));
 }
 
 static bool canMapBetweenRenderers(const RenderObject* renderer, const RenderObject* ancestor)
@@ -179,9 +198,12 @@
 {
     const RenderObject* renderer = layer->renderer();
 
+    bool crossDocument = ancestorLayer && layer->renderer()->frame() != ancestorLayer->renderer()->frame();
+    ASSERT(!crossDocument || m_mapCoordinatesFlags & TraverseDocumentBoundaries);
+
     // We have to visit all the renderers to detect flipped blocks. This might defeat the gains
     // from mapping via layers.
-    bool canConvertInLayerTree = ancestorLayer ? canMapBetweenRenderers(layer->renderer(), ancestorLayer->renderer()) : false;
+    bool canConvertInLayerTree = (ancestorLayer && !crossDocument) ? canMapBetweenRenderers(layer->renderer(), ancestorLayer->renderer()) : false;
 
 //    fprintf(stderr, "RenderGeometryMap::pushMappingsToAncestor from layer %p to layer %p, canConvertInLayerTree=%d\n", layer, ancestorLayer, canConvertInLayerTree);
 
@@ -203,27 +225,34 @@
     pushMappingsToAncestor(renderer, ancestorRenderer);
 }
 
-void RenderGeometryMap::push(const RenderObject* renderer, const LayoutSize& offsetFromContainer, bool accumulatingTransform, bool isNonUniform, bool isFixedPosition, bool hasTransform)
+void RenderGeometryMap::push(const RenderObject* renderer, const LayoutSize& offsetFromContainer, bool accumulatingTransform, bool isNonUniform, bool isFixedPosition, bool hasTransform, LayoutSize offsetForFixedPosition)
 {
 //    fprintf(stderr, "RenderGeometryMap::push %p %d,%d isNonUniform=%d\n", renderer, offsetFromContainer.width().toInt(), offsetFromContainer.height().toInt(), isNonUniform);
 
     ASSERT(m_insertionPosition != notFound);
+    ASSERT(!renderer->isRenderView() || !m_insertionPosition || m_mapCoordinatesFlags & TraverseDocumentBoundaries);
+    ASSERT(offsetForFixedPosition.isZero() || renderer->isRenderView());
 
     m_mapping.insert(m_insertionPosition, RenderGeometryMapStep(renderer, accumulatingTransform, isNonUniform, isFixedPosition, hasTransform));
 
     RenderGeometryMapStep& step = m_mapping[m_insertionPosition];
     step.m_offset = offsetFromContainer;
+    step.m_offsetForFixedPosition = offsetForFixedPosition;
 
     stepInserted(step);
 }
 
-void RenderGeometryMap::push(const RenderObject* renderer, const TransformationMatrix& t, bool accumulatingTransform, bool isNonUniform, bool isFixedPosition, bool hasTransform)
+void RenderGeometryMap::push(const RenderObject* renderer, const TransformationMatrix& t, bool accumulatingTransform, bool isNonUniform, bool isFixedPosition, bool hasTransform, LayoutSize offsetForFixedPosition)
 {
     ASSERT(m_insertionPosition != notFound);
+    ASSERT(!renderer->isRenderView() || !m_insertionPosition || m_mapCoordinatesFlags & TraverseDocumentBoundaries);
+    ASSERT(offsetForFixedPosition.isZero() || renderer->isRenderView());
 
     m_mapping.insert(m_insertionPosition, RenderGeometryMapStep(renderer, accumulatingTransform, isNonUniform, isFixedPosition, hasTransform));
 
     RenderGeometryMapStep& step = m_mapping[m_insertionPosition];
+    step.m_offsetForFixedPosition = offsetForFixedPosition;
+
     if (!t.isIntegerTranslation())
         step.m_transform = adoptPtr(new TransformationMatrix(t));
     else
@@ -232,21 +261,6 @@
     stepInserted(step);
 }
 
-void RenderGeometryMap::pushView(const RenderView* view, const LayoutSize& scrollOffset, const TransformationMatrix* t)
-{
-    ASSERT(m_insertionPosition != notFound);
-    ASSERT(!m_insertionPosition); // The view should always be the first step.
-
-    m_mapping.insert(m_insertionPosition, RenderGeometryMapStep(view, false, false, false, t));
-
-    RenderGeometryMapStep& step = m_mapping[m_insertionPosition];
-    step.m_offset = scrollOffset;
-    if (t)
-        step.m_transform = adoptPtr(new TransformationMatrix(*t));
-
-    stepInserted(step);
-}
-
 void RenderGeometryMap::popMappingsToAncestor(const RenderLayerModelObject* ancestorRenderer)
 {
     ASSERT(m_mapping.size());
@@ -265,9 +279,7 @@
 
 void RenderGeometryMap::stepInserted(const RenderGeometryMapStep& step)
 {
-    // RenderView's offset, is only applied when we have fixed-positions.
-    if (!step.m_renderer->isRenderView())
-        m_accumulatedOffset += step.m_offset;
+    m_accumulatedOffset += step.m_offset;
 
     if (step.m_isNonUniform)
         ++m_nonUniformStepsCount;
@@ -281,9 +293,7 @@
 
 void RenderGeometryMap::stepRemoved(const RenderGeometryMapStep& step)
 {
-    // RenderView's offset, is only applied when we have fixed-positions.
-    if (!step.m_renderer->isRenderView())
-        m_accumulatedOffset -= step.m_offset;
+    m_accumulatedOffset -= step.m_offset;
 
     if (step.m_isNonUniform) {
         ASSERT(m_nonUniformStepsCount);
@@ -301,4 +311,20 @@
     }
 }
 
+#if !ASSERT_DISABLED
+bool RenderGeometryMap::isTopmostRenderView(const RenderObject* renderer) const
+{
+    if (!renderer->isRenderView())
+        return false;
+
+    // If we're not working with multiple RenderViews, then any view is considered
+    // "topmost" (to preserve original behavior).
+    if (!(m_mapCoordinatesFlags & TraverseDocumentBoundaries))
+        return true;
+
+    Frame* thisFrame = renderer->frame();
+    return thisFrame == thisFrame->page()->mainFrame();
+}
+#endif
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderGeometryMap.h b/Source/core/rendering/RenderGeometryMap.h
index 318cd16..9892c8a 100644
--- a/Source/core/rendering/RenderGeometryMap.h
+++ b/Source/core/rendering/RenderGeometryMap.h
@@ -46,6 +46,7 @@
     RenderGeometryMapStep(const RenderGeometryMapStep& o)
         : m_renderer(o.m_renderer)
         , m_offset(o.m_offset)
+        , m_offsetForFixedPosition(o.m_offsetForFixedPosition)
         , m_accumulatingTransform(o.m_accumulatingTransform)
         , m_isNonUniform(o.m_isNonUniform)
         , m_isFixedPosition(o.m_isFixedPosition)
@@ -64,6 +65,7 @@
     const RenderObject* m_renderer;
     LayoutSize m_offset;
     OwnPtr<TransformationMatrix> m_transform; // Includes offset if non-null.
+    LayoutSize m_offsetForFixedPosition;
     bool m_accumulatingTransform;
     bool m_isNonUniform; // Mapping depends on the input point, e.g. because of CSS columns.
     bool m_isFixedPosition;
@@ -105,11 +107,8 @@
 
     // Push geometry info between this renderer and some ancestor. The ancestor must be its container() or some
     // stacking context between the renderer and its container.
-    void push(const RenderObject*, const LayoutSize&, bool accumulatingTransform = false, bool isNonUniform = false, bool isFixedPosition = false, bool hasTransform = false);
-    void push(const RenderObject*, const TransformationMatrix&, bool accumulatingTransform = false, bool isNonUniform = false, bool isFixedPosition = false, bool hasTransform = false);
-
-    // RenderView gets special treatment, because it applies the scroll offset only for elements inside in fixed position.
-    void pushView(const RenderView*, const LayoutSize& scrollOffset, const TransformationMatrix* = 0);
+    void push(const RenderObject*, const LayoutSize&, bool accumulatingTransform = false, bool isNonUniform = false, bool isFixedPosition = false, bool hasTransform = false, LayoutSize offsetForFixedPosition = LayoutSize());
+    void push(const RenderObject*, const TransformationMatrix&, bool accumulatingTransform = false, bool isNonUniform = false, bool isFixedPosition = false, bool hasTransform = false, LayoutSize offsetForFixedPosition = LayoutSize());
 
 private:
     void mapToContainer(TransformState&, const RenderLayerModelObject* container = 0) const;
@@ -121,6 +120,14 @@
     bool hasTransformStep() const { return m_transformedStepsCount; }
     bool hasFixedPositionStep() const { return m_fixedStepsCount; }
 
+#ifndef NDEBUG
+    void dumpSteps();
+#endif
+
+#if !ASSERT_DISABLED
+    bool isTopmostRenderView(const RenderObject* renderer) const;
+#endif
+
     typedef Vector<RenderGeometryMapStep, 32> RenderGeometryMapSteps;
 
     size_t m_insertionPosition;
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index 9d0d589..195c2f3 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -93,7 +93,7 @@
 public:
     // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
     // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
-    GridIterator(const Vector<Vector<Vector<RenderBox*, 1> > >& grid, TrackSizingDirection direction, size_t fixedTrackIndex)
+    GridIterator(const GridRepresentation& grid, TrackSizingDirection direction, size_t fixedTrackIndex)
         : m_grid(grid)
         , m_direction(direction)
         , m_rowIndex((direction == ForColumns) ? 0 : fixedTrackIndex)
@@ -106,13 +106,12 @@
 
     RenderBox* nextGridItem()
     {
-        if (!m_grid.size())
-            return 0;
+        ASSERT(!m_grid.isEmpty());
 
         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
-            const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
+            const GridCell& children = m_grid[m_rowIndex][m_columnIndex];
             if (m_childIndex < children.size())
                 return children[m_childIndex++];
 
@@ -123,13 +122,12 @@
 
     PassOwnPtr<GridCoordinate> nextEmptyGridArea()
     {
-        if (m_grid.isEmpty())
-            return nullptr;
+        ASSERT(!m_grid.isEmpty());
 
         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
-            const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
+            const GridCell& children = m_grid[m_rowIndex][m_columnIndex];
             if (children.isEmpty()) {
                 OwnPtr<GridCoordinate> result = adoptPtr(new GridCoordinate(GridSpan(m_rowIndex, m_rowIndex), GridSpan(m_columnIndex, m_columnIndex)));
                 // Advance the iterator to avoid an infinite loop where we would return the same grid area over and over.
@@ -141,7 +139,7 @@
     }
 
 private:
-    const Vector<Vector<Vector<RenderBox*, 1> > >& m_grid;
+    const GridRepresentation& m_grid;
     TrackSizingDirection m_direction;
     size_t m_rowIndex;
     size_t m_columnIndex;
@@ -168,6 +166,11 @@
     if (gridIsDirty())
         return;
 
+    if (!newChild->isBox()) {
+        dirtyGrid();
+        return;
+    }
+
     RenderBox* newChildBox = toRenderBox(newChild);
     OwnPtr<GridSpan> rowPositions = resolveGridPositionsFromStyle(newChildBox, ForRows);
     OwnPtr<GridSpan> columnPositions = resolveGridPositionsFromStyle(newChildBox, ForColumns);
@@ -356,6 +359,7 @@
 {
     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
     Vector<GridTrack>& tracks = (direction == ForColumns) ? columnTracks : rowTracks;
+    Vector<size_t> contentSizedTracks;
     for (size_t i = 0; i < tracks.size(); ++i) {
         GridTrack& track = tracks[i];
         const GridTrackSize& trackSize = gridTrackSize(direction, i);
@@ -366,10 +370,18 @@
         track.m_maxBreadth = computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.m_usedBreadth);
 
         track.m_maxBreadth = std::max(track.m_maxBreadth, track.m_usedBreadth);
+
+        if (trackSize.isContentSized())
+            contentSizedTracks.append(i);
     }
 
-    // FIXME: We shouldn't call resolveContentBasedTrackSizingFunctions if we have no min-content / max-content tracks.
-    resolveContentBasedTrackSizingFunctions(direction, columnTracks, rowTracks, availableLogicalSpace);
+    if (!contentSizedTracks.isEmpty())
+        resolveContentBasedTrackSizingFunctions(direction, columnTracks, rowTracks, contentSizedTracks, availableLogicalSpace);
+
+    for (size_t i = 0; i < tracks.size(); ++i) {
+        ASSERT(tracks[i].m_maxBreadth != infinity);
+        availableLogicalSpace -= tracks[i].m_usedBreadth;
+    }
 
     if (availableLogicalSpace <= 0)
         return;
@@ -509,18 +521,15 @@
 
 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox* child, Vector<GridTrack>& columnTracks)
 {
-    // FIXME: We shouldn't force a layout every time this function is called but
-    // 1) Return computeLogicalHeight's value if it's available. Unfortunately computeLogicalHeight
-    // doesn't return if the logical height is available so would need to be changed.
-    // 2) Relayout if the column track's used breadth changed OR the logical height is unavailable.
-    if (!child->needsLayout())
-        child->setNeedsLayout(MarkOnlyThis);
+    SubtreeLayoutScope layoutScope(child);
+    if (child->style()->logicalHeight().isPercent())
+        layoutScope.setNeedsLayout(child);
 
     child->setOverrideContainingBlockContentLogicalWidth(gridAreaBreadthForChild(child, ForColumns, columnTracks));
     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
     child->setOverrideContainingBlockContentLogicalHeight(-1);
-    child->layout();
+    child->layoutIfNeeded();
     return child->logicalHeight();
 }
 
@@ -556,26 +565,24 @@
     return logicalContentHeightForChild(child, columnTracks);
 }
 
-void RenderGrid::resolveContentBasedTrackSizingFunctions(TrackSizingDirection direction, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, LayoutUnit& availableLogicalSpace)
+void RenderGrid::resolveContentBasedTrackSizingFunctions(TrackSizingDirection direction, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, Vector<size_t> contentSizedTracks, LayoutUnit& availableLogicalSpace)
 {
     // FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track (crbug.com/235258).
 
-    Vector<GridTrack>& tracks = (direction == ForColumns) ? columnTracks : rowTracks;
-
     // FIXME: Per step 2 of the specification, we should order the grid items by increasing span.
-    for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
-        resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, child, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
-        resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, child, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
-        resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, child, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
-        resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, child, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
-    }
 
-    for (size_t i = 0; i < tracks.size(); ++i) {
-        GridTrack& track = tracks[i];
+    for (size_t i = 0; i < contentSizedTracks.size(); ++i) {
+        GridIterator iterator(m_grid, direction, contentSizedTracks[i]);
+        while (RenderBox* gridItem = iterator.nextGridItem()) {
+            resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
+            resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
+            resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
+            resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
+        }
+
+        GridTrack& track = (direction == ForColumns) ? columnTracks[i] : rowTracks[i];
         if (track.m_maxBreadth == infinity)
             track.m_maxBreadth = track.m_usedBreadth;
-
-        availableLogicalSpace -= track.m_usedBreadth;
     }
 }
 
@@ -595,6 +602,9 @@
         tracks.append(&track);
     }
 
+    if (tracks.isEmpty())
+        return;
+
     LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItem, direction, columnTracks);
     for (size_t trackIndexForSpace = initialTrackIndex; trackIndexForSpace <= finalTrackIndex; ++trackIndexForSpace) {
         GridTrack& track = (direction == ForColumns) ? columnTracks[trackIndexForSpace] : rowTracks[trackIndexForSpace];
@@ -671,7 +681,11 @@
 
 void RenderGrid::insertItemIntoGrid(RenderBox* child, const GridCoordinate& coordinate)
 {
-    m_grid[coordinate.rows.initialPositionIndex][coordinate.columns.initialPositionIndex].append(child);
+    for (size_t row = coordinate.rows.initialPositionIndex; row <= coordinate.rows.finalPositionIndex; ++row) {
+        for (size_t column = coordinate.columns.initialPositionIndex; column <= coordinate.columns.finalPositionIndex; ++column)
+            m_grid[row][column].append(child);
+    }
+
     m_gridItemCoordinate.set(child, coordinate);
 }
 
@@ -854,8 +868,10 @@
         // in minContentForChild / maxContentForChild which means that we will always relayout the child.
         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, rowTracks);
+
+        SubtreeLayoutScope layoutScope(child);
         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight)
-            child->setNeedsLayout(MarkOnlyThis);
+            layoutScope.setNeedsLayout(child);
 
         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
diff --git a/Source/core/rendering/RenderGrid.h b/Source/core/rendering/RenderGrid.h
index 0966ec3..5fea205 100644
--- a/Source/core/rendering/RenderGrid.h
+++ b/Source/core/rendering/RenderGrid.h
@@ -77,7 +77,7 @@
     LayoutUnit computeUsedBreadthOfMinLength(TrackSizingDirection, const GridLength&) const;
     LayoutUnit computeUsedBreadthOfMaxLength(TrackSizingDirection, const GridLength&, LayoutUnit usedBreadth) const;
     LayoutUnit computeUsedBreadthOfSpecifiedLength(TrackSizingDirection, const Length&) const;
-    void resolveContentBasedTrackSizingFunctions(TrackSizingDirection, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, LayoutUnit& availableLogicalSpace);
+    void resolveContentBasedTrackSizingFunctions(TrackSizingDirection, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, Vector<size_t>, LayoutUnit& availableLogicalSpace);
 
     void growGrid(TrackSizingDirection);
     void insertItemIntoGrid(RenderBox*, size_t rowTrack, size_t columnTrack);
@@ -142,7 +142,9 @@
         return m_grid.size();
     }
 
-    Vector<Vector<Vector<RenderBox*, 1> > > m_grid;
+    typedef Vector<RenderBox*, 1> GridCell;
+    typedef Vector<Vector<GridCell> > GridRepresentation;
+    GridRepresentation m_grid;
     bool m_gridIsDirty;
     HashMap<const RenderBox*, GridCoordinate> m_gridItemCoordinate;
     OrderIterator m_orderIterator;
diff --git a/Source/core/rendering/RenderHTMLCanvas.cpp b/Source/core/rendering/RenderHTMLCanvas.cpp
index e1c5924..737cadf 100644
--- a/Source/core/rendering/RenderHTMLCanvas.cpp
+++ b/Source/core/rendering/RenderHTMLCanvas.cpp
@@ -55,18 +55,32 @@
 
 void RenderHTMLCanvas::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
-    LayoutRect rect = contentBoxRect();
-    rect.moveBy(paintOffset);
+    GraphicsContext* context = paintInfo.context;
+
+    LayoutRect contentRect = contentBoxRect();
+    contentRect.moveBy(paintOffset);
+    LayoutRect paintRect = replacedContentRect();
+    paintRect.moveBy(paintOffset);
+
+    bool clip = !contentRect.contains(paintRect);
+    if (clip) {
+        // Not allowed to overflow the content box.
+        paintInfo.context->save();
+        paintInfo.context->clip(pixelSnappedIntRect(contentRect));
+    }
 
     if (Frame* frame = this->frame()) {
         if (Page* page = frame->page()) {
             if (paintInfo.phase == PaintPhaseForeground)
-                page->addRelevantRepaintedObject(this, rect);
+                page->addRelevantRepaintedObject(this, intersection(paintRect, contentRect));
         }
     }
 
     bool useLowQualityScale = style()->imageRendering() == ImageRenderingOptimizeContrast;
-    toHTMLCanvasElement(node())->paint(paintInfo.context, rect, useLowQualityScale);
+    toHTMLCanvasElement(node())->paint(context, paintRect, useLowQualityScale);
+
+    if (clip)
+        context->restore();
 }
 
 void RenderHTMLCanvas::canvasSizeChanged()
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index ce48656..91773c8 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -30,11 +30,11 @@
 
 #include "HTMLNames.h"
 #include "core/editing/FrameSelection.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLAreaElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLMapElement.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/Font.h"
@@ -99,7 +99,7 @@
     IntSize imageSize;
     if (newImage->willPaintBrokenImage()) {
         float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
-        pair<Image*, float> brokenImageAndImageScaleFactor = newImage->brokenImage(deviceScaleFactor);
+        pair<Image*, float> brokenImageAndImageScaleFactor = ImageResource::brokenImage(deviceScaleFactor);
         imageSize = brokenImageAndImageScaleFactor.first->size();
         imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
     } else
@@ -196,9 +196,18 @@
     return true;
 }
 
+void RenderImage::updateInnerContentRect()
+{
+    // Propagate container size to image resource.
+    LayoutRect paintRect = replacedContentRect();
+    IntSize containerSize(paintRect.width(), paintRect.height());
+    if (!containerSize.isEmpty())
+        m_imageResource->setContainerSizeForRenderer(containerSize);
+}
+
 void RenderImage::imageDimensionsChanged(bool imageSizeChanged, const IntRect* rect)
 {
-    bool intrinsicSizeChanged = updateIntrinsicSizeIfNeeded(m_imageResource->imageSize(style()->effectiveZoom()), imageSizeChanged);
+    bool intrinsicSizeChanged = updateIntrinsicSizeIfNeeded(m_imageResource->intrinsicSize(style()->effectiveZoom()), imageSizeChanged);
 
     // In the case of generated image content using :before/:after/content, we might not be
     // in the render tree yet. In that case, we just need to update our intrinsic size.
@@ -236,6 +245,17 @@
             if (!selfNeedsLayout())
                 setNeedsLayout();
         }
+
+        if (everHadLayout() && !selfNeedsLayout()) {
+            // The inner content rectangle is calculated during layout, but may need an update now
+            // (unless the box has already been scheduled for layout). In order to calculate it, we
+            // may need values from the containing block, though, so make sure that we're not too
+            // early. It may be that layout hasn't even taken place once yet.
+
+            // FIXME: we should not have to trigger another call to setContainerSizeForRenderer()
+            // from here, since it's already being done during layout (crbug.com/275755).
+            updateInnerContentRect();
+        }
     }
 
     if (shouldRepaint) {
@@ -316,7 +336,7 @@
             if (m_imageResource->errorOccurred() && !image->isNull() && usableWidth >= image->width() && usableHeight >= image->height()) {
                 float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
                 // Call brokenImage() explicitly to ensure we get the broken image icon at the appropriate resolution.
-                pair<Image*, float> brokenImageAndImageScaleFactor = m_imageResource->cachedImage()->brokenImage(deviceScaleFactor);
+                pair<Image*, float> brokenImageAndImageScaleFactor = ImageResource::brokenImage(deviceScaleFactor);
                 image = brokenImageAndImageScaleFactor.first;
                 IntSize imageSize = image->size();
                 imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
@@ -363,19 +383,30 @@
             return;
         }
 
-        LayoutSize contentSize(cWidth, cHeight);
-        LayoutPoint contentLocation = paintOffset;
-        contentLocation.move(leftBorder + leftPad, topBorder + topPad);
-        paintIntoRect(context, LayoutRect(contentLocation, contentSize));
+        LayoutRect contentRect = contentBoxRect();
+        contentRect.moveBy(paintOffset);
+        LayoutRect paintRect = replacedContentRect();
+        paintRect.moveBy(paintOffset);
+        bool clip = !contentRect.contains(paintRect);
+        if (clip) {
+            context->save();
+            context->clip(contentRect);
+        }
+
+        paintIntoRect(context, paintRect);
 
         if (cachedImage() && page && paintInfo.phase == PaintPhaseForeground) {
             // For now, count images as unpainted if they are still progressively loading. We may want
             // to refine this in the future to account for the portion of the image that has painted.
+            LayoutRect visibleRect = intersection(paintRect, contentRect);
             if (cachedImage()->isLoading())
-                page->addRelevantUnpaintedObject(this, LayoutRect(contentLocation, contentSize));
+                page->addRelevantUnpaintedObject(this, visibleRect);
             else
-                page->addRelevantRepaintedObject(this, LayoutRect(contentLocation, contentSize));
+                page->addRelevantRepaintedObject(this, visibleRect);
         }
+
+        if (clip)
+            context->restore();
     }
 }
 
@@ -485,6 +516,10 @@
     // Background shows in padding area.
     if ((backgroundClip == BorderFillBox || backgroundClip == PaddingFillBox) && style()->hasPadding())
         return false;
+    // Object-fit may leave parts of the content box empty.
+    ObjectFit objectFit = style()->objectFit();
+    if (objectFit != ObjectFitFill && objectFit != ObjectFitCover)
+        return false;
     // Check for image with alpha.
     return m_imageResource->cachedImage() && m_imageResource->cachedImage()->currentFrameKnownToBeOpaque(this);
 }
@@ -546,11 +581,7 @@
 {
     StackStats::LayoutCheckPoint layoutCheckPoint;
     RenderReplaced::layout();
-
-    // Propagate container size to image resource.
-    IntSize containerSize(contentWidth(), contentHeight());
-    if (!containerSize.isEmpty())
-        m_imageResource->setContainerSizeForRenderer(containerSize);
+    updateInnerContentRect();
 }
 
 void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
diff --git a/Source/core/rendering/RenderImage.h b/Source/core/rendering/RenderImage.h
index 6c4aeed..1204ea5 100644
--- a/Source/core/rendering/RenderImage.h
+++ b/Source/core/rendering/RenderImage.h
@@ -101,6 +101,8 @@
     IntSize imageSizeForError(ImageResource*) const;
     void imageDimensionsChanged(bool imageSizeChanged, const IntRect* = 0);
     bool updateIntrinsicSizeIfNeeded(const LayoutSize&, bool imageSizeChanged);
+    // Update the size of the image to be rendered. Object-fit may cause this to be different from the CSS box's content rect.
+    void updateInnerContentRect();
 
     void paintAreaElementFocusRing(PaintInfo&);
 
diff --git a/Source/core/rendering/RenderImageResource.cpp b/Source/core/rendering/RenderImageResource.cpp
index 4a38fdd..6130187 100644
--- a/Source/core/rendering/RenderImageResource.cpp
+++ b/Source/core/rendering/RenderImageResource.cpp
@@ -28,7 +28,7 @@
 #include "config.h"
 #include "core/rendering/RenderImageResource.h"
 
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/platform/graphics/Image.h"
 #include "core/rendering/RenderObject.h"
 
diff --git a/Source/core/rendering/RenderImageResource.h b/Source/core/rendering/RenderImageResource.h
index d222111..d5d8fca 100644
--- a/Source/core/rendering/RenderImageResource.h
+++ b/Source/core/rendering/RenderImageResource.h
@@ -26,8 +26,8 @@
 #ifndef RenderImageResource_h
 #define RenderImageResource_h
 
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/LayoutSize.h"
 #include "core/rendering/style/StyleImage.h"
@@ -64,6 +64,7 @@
     virtual bool imageHasRelativeHeight() const { return m_cachedImage ? m_cachedImage->imageHasRelativeHeight() : false; }
 
     virtual LayoutSize imageSize(float multiplier) const { return m_cachedImage ? m_cachedImage->imageSizeForRenderer(m_renderer, multiplier) : LayoutSize(); }
+    virtual LayoutSize intrinsicSize(float multiplier) const { return m_cachedImage ? m_cachedImage->imageSizeForRenderer(m_renderer, multiplier, ImageResource::IntrinsicSize) : LayoutSize(); }
 
     virtual WrappedImagePtr imagePtr() const { return m_cachedImage.get(); }
 
diff --git a/Source/core/rendering/RenderImageResourceStyleImage.cpp b/Source/core/rendering/RenderImageResourceStyleImage.cpp
index ec90235..9c3b03e 100644
--- a/Source/core/rendering/RenderImageResourceStyleImage.cpp
+++ b/Source/core/rendering/RenderImageResourceStyleImage.cpp
@@ -28,7 +28,7 @@
 #include "config.h"
 #include "core/rendering/RenderImageResourceStyleImage.h"
 
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/style/StyleFetchedImage.h"
 
diff --git a/Source/core/rendering/RenderImageResourceStyleImage.h b/Source/core/rendering/RenderImageResourceStyleImage.h
index f77854d..6844e2a 100644
--- a/Source/core/rendering/RenderImageResourceStyleImage.h
+++ b/Source/core/rendering/RenderImageResourceStyleImage.h
@@ -55,6 +55,7 @@
     virtual bool imageHasRelativeHeight() const { return m_styleImage->imageHasRelativeHeight(); }
 
     virtual LayoutSize imageSize(float multiplier) const OVERRIDE { return m_styleImage->imageSize(m_renderer, multiplier); }
+    virtual LayoutSize intrinsicSize(float multiplier) const OVERRIDE { return m_styleImage->imageSize(m_renderer, multiplier); }
 
     virtual WrappedImagePtr imagePtr() const { return m_styleImage->data(); }
 
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 9f6939f..f53f7f3 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -132,6 +132,7 @@
     , m_hasOutOfFlowPositionedDescendant(false)
     , m_hasOutOfFlowPositionedDescendantDirty(true)
     , m_hasUnclippedDescendant(false)
+    , m_isUnclippedDescendant(false)
     , m_needsCompositedScrolling(false)
     , m_canBePromotedToStackingContainer(false)
     , m_canBePromotedToStackingContainerDirty(true)
@@ -167,6 +168,10 @@
     , m_resizer(0)
     , m_enclosingPaginationLayer(0)
     , m_forceNeedsCompositedScrolling(DoNotForceCompositedScrolling)
+    // FIXME: We could lazily allocate our ScrollableArea based on style properties
+    // ('overflow', ...) but for now, we are always allocating it as it's safer.
+    , m_scrollableArea(adoptPtr(new RenderLayerScrollableArea(this)))
+
 {
     m_isNormalFlowOnly = shouldBeNormalFlowOnly();
     m_isSelfPaintingLayer = shouldBeSelfPaintingLayer();
@@ -175,23 +180,11 @@
     // there is no need to dirty / recompute these lists.
     m_zOrderListsDirty = isStackingContainer();
 
-    ScrollableArea::setConstrainsScrollingToContentEdge(false);
-
     if (!renderer->firstChild() && renderer->style()) {
         m_visibleContentStatusDirty = false;
         m_hasVisibleContent = renderer->style()->visibility() == VISIBLE;
     }
 
-    Node* node = renderer->node();
-    if (node && node->isElementNode()) {
-        // We save and restore only the scrollOffset as the other scroll values are recalculated.
-        Element* element = toElement(node);
-        m_scrollOffset = element->savedLayerScrollOffset();
-        if (!m_scrollOffset.isZero())
-            scrollAnimator()->setCurrentPosition(FloatPoint(m_scrollOffset.width(), m_scrollOffset.height()));
-        element->setSavedLayerScrollOffset(IntSize());
-    }
-
     updateResizerAreaSet();
 }
 
@@ -203,10 +196,8 @@
     }
 
     if (Frame* frame = renderer()->frame()) {
-        if (FrameView* frameView = frame->view()) {
-            frameView->removeScrollableArea(this);
+        if (FrameView* frameView = frame->view())
             frameView->removeResizerArea(this);
-        }
     }
 
     if (!m_renderer->documentBeingDestroyed()) {
@@ -223,7 +214,7 @@
 
     if (renderer()->frame() && renderer()->frame()->page()) {
         if (ScrollingCoordinator* scrollingCoordinator = renderer()->frame()->page()->scrollingCoordinator())
-            scrollingCoordinator->willDestroyScrollableArea(this);
+            scrollingCoordinator->willDestroyRenderLayer(this);
     }
 
     if (m_reflection)
@@ -242,7 +233,6 @@
         m_resizer->destroy();
 }
 
-#ifndef NDEBUG
 String RenderLayer::debugName() const
 {
     String name = renderer()->debugName();
@@ -250,7 +240,6 @@
         return name;
     return name + " (reflection)";
 }
-#endif
 
 RenderLayerCompositor* RenderLayer::compositor() const
 {
@@ -498,6 +487,9 @@
 // overflow scroll is ready (crbug.com/254111).
 bool RenderLayer::compositorDrivenAcceleratedScrollingEnabled() const
 {
+    if (!acceleratedCompositingForOverflowScrollEnabled())
+        return false;
+
     const Settings* settings = renderer()->document()->settings();
     return settings && settings->isCompositorDrivenAcceleratedScrollingEnabled();
 }
@@ -508,13 +500,13 @@
 // preserved between the two sets of lists.
 void RenderLayer::updateCanBeStackingContainer()
 {
-    TRACE_EVENT0("blink_rendering", "RenderLayer::updateCanBeStackingContainer");
+    TRACE_EVENT0("blink_rendering,comp-scroll", "RenderLayer::updateCanBeStackingContainer");
 
     if (isStackingContext() || !m_canBePromotedToStackingContainerDirty || !acceleratedCompositingForOverflowScrollEnabled())
         return;
 
     FrameView* frameView = renderer()->view()->frameView();
-    if (!frameView || !frameView->containsScrollableArea(this))
+    if (!frameView || !frameView->containsScrollableArea(scrollableArea()))
         return;
 
     RenderLayer* ancestorStackingContext = this->ancestorStackingContext();
@@ -1032,8 +1024,19 @@
         return;
 
     const RenderObject* containingBlock = renderer()->containingBlock();
-    for (RenderLayer* ancestor = parent(); ancestor && ancestor->renderer() != containingBlock; ancestor = ancestor->parent())
+    setIsUnclippedDescendant(false);
+    for (RenderLayer* ancestor = parent(); ancestor && ancestor->renderer() != containingBlock; ancestor = ancestor->parent()) {
+        // TODO(vollick): This isn't quite right. Whenever ancestor is composited and clips
+        // overflow, we're technically unclipped. However, this will currently cause a huge
+        // number of layers to report that they are unclipped. Eventually, when we've formally
+        // separated the clipping, transform, opacity, and stacking trees here and in the
+        // compositor, we will be able to relax this restriction without it being prohibitively
+        // expensive (currently, we have to do a lot of work in the compositor to honor a
+        // clip child/parent relationship).
+        if (ancestor->needsCompositedScrolling())
+            setIsUnclippedDescendant(true);
         ancestor->setHasUnclippedDescendant(true);
+    }
 }
 
 static bool subtreeContainsOutOfFlowPositionedLayer(const RenderLayer* subtreeRoot)
@@ -1322,6 +1325,9 @@
     RenderBox* box = renderBox();
     ASSERT(box);
 
+    if (box->isIntristicallyScrollable(orientation))
+        return true;
+
     EOverflow overflowStyle = (orientation == HorizontalScrollbar) ?
         renderer()->style()->overflowX() : renderer()->style()->overflowY();
     return (overflowStyle == OSCROLL || overflowStyle == OAUTO || overflowStyle == OOVERLAY);
@@ -1391,6 +1397,23 @@
     return 0;
 }
 
+RenderLayer* RenderLayer::ancestorScrollingLayer() const
+{
+    if (!acceleratedCompositingForOverflowScrollEnabled())
+        return 0;
+
+    RenderObject* containingBlock = renderer()->containingBlock();
+    if (!containingBlock)
+        return 0;
+
+    for (RenderLayer* ancestorLayer = containingBlock->enclosingLayer(); ancestorLayer; ancestorLayer = ancestorLayer->parent()) {
+        if (ancestorLayer->needsCompositedScrolling())
+            return ancestorLayer;
+    }
+
+    return 0;
+}
+
 RenderLayer* RenderLayer::enclosingFilterLayer(bool includeSelf) const
 {
     const RenderLayer* curr = includeSelf ? this : parent();
@@ -1950,11 +1973,26 @@
 
 bool RenderLayer::usesCompositedScrolling() const
 {
+    RenderBox* box = renderBox();
+
+    // Scroll form controls on the main thread so they exhibit correct touch scroll event bubbling
+    if (box && (box->isIntristicallyScrollable(VerticalScrollbar) || box->isIntristicallyScrollable(HorizontalScrollbar)))
+        return false;
+
     return isComposited() && backing()->scrollingLayer();
 }
 
 bool RenderLayer::needsCompositedScrolling() const
 {
+    if (!compositorDrivenAcceleratedScrollingEnabled())
+        return needsToBeStackingContainer();
+    if (FrameView* frameView = renderer()->view()->frameView())
+        return frameView->containsScrollableArea(scrollableArea());
+    return false;
+}
+
+bool RenderLayer::needsToBeStackingContainer() const
+{
     switch (m_forceNeedsCompositedScrolling) {
     case DoNotForceCompositedScrolling:
         return m_needsCompositedScrolling;
@@ -1970,10 +2008,12 @@
 
 void RenderLayer::updateNeedsCompositedScrolling()
 {
+    TRACE_EVENT0("comp-scroll", "RenderLayer::updateNeedsCompositedScrolling");
+
     updateCanBeStackingContainer();
     updateDescendantDependentFlags();
 
-    ASSERT(renderer()->view()->frameView() && renderer()->view()->frameView()->containsScrollableArea(this));
+    ASSERT(renderer()->view()->frameView() && renderer()->view()->frameView()->containsScrollableArea(scrollableArea()));
     bool needsCompositedScrolling = acceleratedCompositingForOverflowScrollEnabled()
         && canBeStackingContainer()
         && !hasUnclippedDescendant();
@@ -2121,7 +2161,7 @@
 {
     IntSize newScrollOffset = clamp == ScrollOffsetClamped ? clampScrollOffset(scrollOffset) : scrollOffset;
     if (newScrollOffset != adjustedScrollOffset())
-        scrollToOffsetWithoutAnimation(-scrollOrigin() + newScrollOffset);
+        m_scrollableArea->scrollToOffsetWithoutAnimation(-scrollOrigin() + newScrollOffset);
 }
 
 void RenderLayer::setScrollOffset(const IntPoint& newScrollOffset)
@@ -2157,10 +2197,7 @@
         if (view) {
             // Update regions, scrolling may change the clip of a particular region.
             view->frameView()->updateAnnotatedRegions();
-
             view->updateWidgetPositions();
-
-            view->markLazyBlocksForLayout();
         }
 
         updateCompositingLayersAfterScroll();
@@ -2255,7 +2292,7 @@
                 HTMLFrameElementBase* frameElementBase = 0;
 
                 if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
-                    frameElementBase = static_cast<HTMLFrameElementBase*>(ownerElement);
+                    frameElementBase = toHTMLFrameElementBase(ownerElement);
 
                 if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
                     LayoutRect viewRect = frameView->visibleContentRect();
@@ -2508,11 +2545,11 @@
     return -scrollOrigin() + enclosingIntRect(m_overflowRect).size() - enclosingIntRect(box->clientBoxRect()).size();
 }
 
-IntRect RenderLayer::visibleContentRect(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
+IntRect RenderLayer::visibleContentRect(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion) const
 {
     int verticalScrollbarWidth = 0;
     int horizontalScrollbarHeight = 0;
-    if (scrollbarInclusion == IncludeScrollbars) {
+    if (scrollbarInclusion == ScrollableArea::IncludeScrollbars) {
         verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0;
         horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar()) ? horizontalScrollbar()->height() : 0;
     }
@@ -2815,13 +2852,13 @@
     RenderObject* actualRenderer = rendererForScrollbar(renderer());
     bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
     if (hasCustomScrollbarStyle)
-        widget = RenderScrollbar::createCustomScrollbar(this, orientation, actualRenderer->node());
+        widget = RenderScrollbar::createCustomScrollbar(scrollableArea(), orientation, actualRenderer->node());
     else {
-        widget = Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar);
+        widget = Scrollbar::createNativeScrollbar(scrollableArea(), orientation, RegularScrollbar);
         if (orientation == HorizontalScrollbar)
-            didAddHorizontalScrollbar(widget.get());
+            scrollableArea()->didAddHorizontalScrollbar(widget.get());
         else
-            didAddVerticalScrollbar(widget.get());
+            scrollableArea()->didAddVerticalScrollbar(widget.get());
     }
     renderer()->document()->view()->addChild(widget.get());
     return widget.release();
@@ -2835,9 +2872,9 @@
 
     if (!scrollbar->isCustomScrollbar()) {
         if (orientation == HorizontalScrollbar)
-            willRemoveHorizontalScrollbar(scrollbar.get());
+            scrollableArea()->willRemoveHorizontalScrollbar(scrollbar.get());
         else
-            willRemoveVerticalScrollbar(scrollbar.get());
+            scrollableArea()->willRemoveVerticalScrollbar(scrollbar.get());
     }
 
     scrollbar->removeFromParent();
@@ -2890,7 +2927,7 @@
 ScrollableArea* RenderLayer::enclosingScrollableArea() const
 {
     if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
-        return scrollableLayer;
+        return scrollableLayer->scrollableArea();
 
     // FIXME: We should return the frame view here (or possibly an ancestor frame view,
     // if the frame view isn't scrollable.
@@ -2989,7 +3026,7 @@
 
     int scrollableLeftOverflow = m_overflowRect.x() - box->borderLeft();
     int scrollableTopOverflow = m_overflowRect.y() - box->borderTop();
-    setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
+    m_scrollableArea->setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
 }
 
 bool RenderLayer::hasScrollableHorizontalOverflow() const
@@ -3056,7 +3093,8 @@
             if (!m_inOverflowRelayout) {
                 // Our proprietary overflow: overlay value doesn't trigger a layout.
                 m_inOverflowRelayout = true;
-                renderer()->setNeedsLayout(MarkOnlyThis);
+                SubtreeLayoutScope layoutScope(renderer());
+                layoutScope.setNeedsLayout(renderer());
                 if (renderer()->isRenderBlock()) {
                     RenderBlock* block = toRenderBlock(renderer());
                     block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
@@ -3103,7 +3141,7 @@
     updateScrollbarsAfterLayout();
 
     if (originalScrollOffset != adjustedScrollOffset())
-        scrollToOffsetWithoutAnimation(-scrollOrigin() + adjustedScrollOffset());
+        scrollableArea()->scrollToOffsetWithoutAnimation(-scrollOrigin() + adjustedScrollOffset());
 
     // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
     if (renderer()->view() && compositor()->updateLayerCompositingState(this))
@@ -3347,7 +3385,10 @@
 
 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
 {
-    return ScrollableArea::scroll(direction, granularity, multiplier);
+    if (ScrollableArea* scrollableArea = this->scrollableArea())
+        return scrollableArea->scroll(direction, granularity, multiplier);
+
+    return false;
 }
 
 void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, RenderRegion* region, PaintLayerFlags paintFlags)
@@ -5944,6 +5985,14 @@
     } else {
         dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
         compositor()->removeOutOfFlowPositionedLayer(this);
+
+        // We need to reset the isUnclippedDescendant bit here because normally
+        // the "unclipped-ness" property is only updated in
+        // RenderLayerCompositor::updateCompositingRequirementsState(). However,
+        // it is only updated for layers which are known to be out of flow.
+        // Since this is no longer out of flow, we have to explicitly ensure
+        // that it doesn't think it is unclipped.
+        setIsUnclippedDescendant(false);
     }
 }
 
@@ -6093,10 +6142,10 @@
         isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
 
     if (hasOverflow && isVisibleToHitTest) {
-        if (frameView->addScrollableArea(this))
+        if (frameView->addScrollableArea(scrollableArea()))
             compositor()->setNeedsUpdateCompositingRequirementsState();
     } else {
-        if (frameView->removeScrollableArea(this))
+        if (frameView->removeScrollableArea(scrollableArea()))
             setNeedsCompositedScrolling(false);
     }
 }
@@ -6289,7 +6338,7 @@
     RenderLayerFilterInfo* filterInfo = ensureFilterInfo();
     if (!filterInfo->renderer()) {
         RefPtr<FilterEffectRenderer> filterRenderer = FilterEffectRenderer::create();
-        RenderingMode renderingMode = renderer()->frame()->page()->settings()->acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
+        RenderingMode renderingMode = renderer()->frame()->page()->settings().acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
         filterRenderer->setRenderingMode(renderingMode);
         filterInfo->setRenderer(filterRenderer.release());
 
@@ -6337,6 +6386,21 @@
         child->addLayerHitTestRects(rects);
 }
 
+const IntPoint& RenderLayer::scrollOrigin() const
+{
+    if (!m_scrollableArea) {
+        static IntPoint emptyPoint = IntPoint::zero();
+        return emptyPoint;
+    }
+
+    return m_scrollableArea->scrollOrigin();
+}
+
+bool RenderLayer::hasOverlayScrollbars() const
+{
+    return m_scrollableArea && m_scrollableArea->hasOverlayScrollbars();
+}
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index 5a7c14f..4d5389f 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -44,10 +44,10 @@
 #ifndef RenderLayer_h
 #define RenderLayer_h
 
-#include "core/platform/ScrollableArea.h"
 #include "core/rendering/CompositingReasons.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBox.h"
+#include "core/rendering/RenderLayerScrollableArea.h"
 
 #include "wtf/OwnPtr.h"
 
@@ -310,16 +310,16 @@
 
 typedef Vector<LayerFragment, 1> LayerFragments;
 
-class RenderLayer : public ScrollableArea {
+class RenderLayer {
 public:
     friend class RenderReplica;
+    // FIXME: Needed until we move all the necessary bits to the new class.
+    friend class RenderLayerScrollableArea;
 
     RenderLayer(RenderLayerModelObject*);
     ~RenderLayer();
 
-#ifndef NDEBUG
     String debugName() const;
-#endif
 
     RenderLayerModelObject* renderer() const { return m_renderer; }
     RenderBox* renderBox() const { return m_renderer && m_renderer->isBox() ? toRenderBox(m_renderer) : 0; }
@@ -375,13 +375,8 @@
 
     LayoutRect rect() const { return LayoutRect(location(), size()); }
 
-    enum ResizerHitTestType {
-        ResizerForPointer,
-        ResizerForTouch
-    };
-
     // See comments on isPointInResizeControl.
-    virtual IntRect resizerCornerRect(const IntRect& bounds, ResizerHitTestType) const;
+    IntRect resizerCornerRect(const IntRect& bounds, ResizerHitTestType) const;
 
     int scrollWidth() const;
     int scrollHeight() const;
@@ -410,11 +405,6 @@
     bool hasHorizontalScrollbar() const { return horizontalScrollbar(); }
     bool hasVerticalScrollbar() const { return verticalScrollbar(); }
 
-    // ScrollableArea overrides
-    virtual Scrollbar* horizontalScrollbar() const { return m_hBar.get(); }
-    virtual Scrollbar* verticalScrollbar() const { return m_vBar.get(); }
-    virtual ScrollableArea* enclosingScrollableArea() const;
-
     int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
     int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
 
@@ -488,7 +478,7 @@
     // stacking containers, but the converse is not true. Layers that use
     // composited scrolling are stacking containers, but they may not
     // necessarily be stacking contexts.
-    bool isStackingContainer() const { return isStackingContext() || needsCompositedScrolling(); }
+    bool isStackingContainer() const { return isStackingContext() || needsToBeStackingContainer(); }
 
     RenderLayer* ancestorStackingContainer() const;
     RenderLayer* ancestorStackingContext() const;
@@ -550,6 +540,7 @@
     bool hasUnclippedDescendant() const { return m_hasUnclippedDescendant; }
     void setHasUnclippedDescendant(bool hasDescendant) { m_hasUnclippedDescendant = hasDescendant; }
     void updateHasUnclippedDescendant();
+    bool isUnclippedDescendant() const { return m_isUnclippedDescendant; }
 
     // Gets the nearest enclosing positioned ancestor layer (also includes
     // the <html> layer and the root layer).
@@ -567,6 +558,9 @@
     // Ancestor compositing layer, excluding this.
     RenderLayer* ancestorCompositingLayer() const { return enclosingCompositingLayer(false); }
 
+    // Ancestor scrolling layer at or above our containing block.
+    RenderLayer* ancestorScrollingLayer() const;
+
     RenderLayer* enclosingFilterLayer(bool includeSelf = true) const;
     RenderLayer* enclosingFilterRepaintLayer() const;
     void setFilterBackendNeedsRepaintingInRect(const LayoutRect&);
@@ -715,7 +709,7 @@
     bool preserves3D() const { return renderer()->style()->transformStyle3D() == TransformStyle3DPreserve3D; }
     bool has3DTransform() const { return m_transform && !m_transform->isAffine(); }
 
-    virtual void filterNeedsRepaint();
+    void filterNeedsRepaint();
     bool hasFilter() const { return renderer()->hasFilter(); }
 
     bool hasBlendMode() const;
@@ -729,12 +723,8 @@
     RenderLayerBacking* backing() const { return m_backing.get(); }
     RenderLayerBacking* ensureBacking();
     void clearBacking(bool layerBeingDestroyed = false);
-    virtual GraphicsLayer* layerForScrolling() const;
-    virtual GraphicsLayer* layerForHorizontalScrollbar() const;
-    virtual GraphicsLayer* layerForVerticalScrollbar() const;
-    virtual GraphicsLayer* layerForScrollCorner() const;
-    virtual bool usesCompositedScrolling() const OVERRIDE;
     bool needsCompositedScrolling() const;
+    bool needsToBeStackingContainer() const;
     bool needsCompositingLayersRebuiltForClip(const RenderStyle* oldStyle, const RenderStyle* newStyle) const;
     bool needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const;
     bool needsCompositingLayersRebuiltForFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle, bool didPaintWithFilters) const;
@@ -813,6 +803,8 @@
 
     void addLayerHitTestRects(LayerHitTestRects&) const;
 
+    ScrollableArea* scrollableArea() const { return m_scrollableArea.get(); }
+
 private:
     enum CollectLayersBehavior {
         ForceLayerToStackingContainer,
@@ -833,6 +825,8 @@
     // See the comment for collectLayers for information about the layerToForceAsStackingContainer parameter.
     void rebuildZOrderLists(OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0, CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
     void clearZOrderLists();
+    void setIsUnclippedDescendant(bool isUnclippedDescendant) { m_isUnclippedDescendant = isUnclippedDescendant; }
+
 
     void updateNormalFlowList();
 
@@ -877,7 +871,6 @@
 
     void updateOutOfFlowPositioned(const RenderStyle* oldStyle);
 
-    virtual void updateNeedsCompositedScrolling() OVERRIDE;
     void setNeedsCompositedScrolling(bool);
     void didUpdateNeedsCompositedScrolling();
 
@@ -1001,32 +994,53 @@
 
     bool shouldBeSelfPaintingLayer() const;
 
-    // ScrollableArea interface
-    virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&);
-    virtual void invalidateScrollCornerRect(const IntRect&);
-    virtual bool isActive() const;
-    virtual bool isScrollCornerVisible() const;
-    virtual IntRect scrollCornerRect() const;
-    virtual IntRect convertFromScrollbarToContainingView(const Scrollbar*, const IntRect&) const;
-    virtual IntRect convertFromContainingViewToScrollbar(const Scrollbar*, const IntRect&) const;
-    virtual IntPoint convertFromScrollbarToContainingView(const Scrollbar*, const IntPoint&) const;
-    virtual IntPoint convertFromContainingViewToScrollbar(const Scrollbar*, const IntPoint&) const;
-    virtual int scrollSize(ScrollbarOrientation) const;
-    virtual void setScrollOffset(const IntPoint&);
-    virtual IntPoint scrollPosition() const;
-    virtual IntPoint minimumScrollPosition() const;
-    virtual IntPoint maximumScrollPosition() const;
-    virtual IntRect visibleContentRect(VisibleContentRectIncludesScrollbars) const;
-    virtual int visibleHeight() const;
-    virtual int visibleWidth() const;
-    virtual IntSize contentsSize() const;
-    virtual IntSize overhangAmount() const;
-    virtual IntPoint lastKnownMousePosition() const;
-    virtual bool shouldSuspendScrollAnimations() const;
-    virtual bool scrollbarsCanBeActive() const;
-    virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
-    virtual bool userInputScrollable(ScrollbarOrientation) const OVERRIDE;
-    virtual int pageStep(ScrollbarOrientation) const OVERRIDE;
+    // Start of ScrollableArea interface
+    // To be moved to RenderLayerScrollableArea
+    ScrollableArea* enclosingScrollableArea() const;
+
+    void updateNeedsCompositedScrolling();
+
+public:
+    GraphicsLayer* layerForScrolling() const;
+    GraphicsLayer* layerForHorizontalScrollbar() const;
+    GraphicsLayer* layerForVerticalScrollbar() const;
+    GraphicsLayer* layerForScrollCorner() const;
+    Scrollbar* horizontalScrollbar() const { return m_hBar.get(); }
+    Scrollbar* verticalScrollbar() const { return m_vBar.get(); }
+    bool usesCompositedScrolling() const;
+
+    bool hasOverlayScrollbars() const;
+
+private:
+    void invalidateScrollbarRect(Scrollbar*, const IntRect&);
+    void invalidateScrollCornerRect(const IntRect&);
+    bool isActive() const;
+    bool isScrollCornerVisible() const;
+    IntRect scrollCornerRect() const;
+    IntRect convertFromScrollbarToContainingView(const Scrollbar*, const IntRect&) const;
+    IntRect convertFromContainingViewToScrollbar(const Scrollbar*, const IntRect&) const;
+    IntPoint convertFromScrollbarToContainingView(const Scrollbar*, const IntPoint&) const;
+    IntPoint convertFromContainingViewToScrollbar(const Scrollbar*, const IntPoint&) const;
+    int scrollSize(ScrollbarOrientation) const;
+    void setScrollOffset(const IntPoint&);
+    IntPoint scrollPosition() const;
+    IntPoint minimumScrollPosition() const;
+    IntPoint maximumScrollPosition() const;
+    IntRect visibleContentRect(ScrollableArea::VisibleContentRectIncludesScrollbars) const;
+    int visibleHeight() const;
+    int visibleWidth() const;
+    IntSize contentsSize() const;
+    IntSize overhangAmount() const;
+    IntPoint lastKnownMousePosition() const;
+    bool shouldSuspendScrollAnimations() const;
+    bool scrollbarsCanBeActive() const;
+    IntRect scrollableAreaBoundingBox() const;
+    bool userInputScrollable(ScrollbarOrientation) const;
+    int pageStep(ScrollbarOrientation) const;
+    // End of ScrollableArea interface
+
+    // FIXME: This should be removed once we have transitioned to RenderLayerScrollableArea.
+    const IntPoint& scrollOrigin() const;
 
     // Rectangle encompassing the scroll corner and resizer rect.
     IntRect scrollCornerAndResizerRect() const;
@@ -1035,6 +1049,7 @@
 
     IntSize scrollbarOffset(const Scrollbar*) const;
 
+    bool requiresScrollableArea() const { return renderer()->style()->overflowX() != OVISIBLE || canResize() || usesCompositedScrolling(); }
     void updateResizerAreaSet();
     void updateScrollableAreaSet(bool hasOverflow);
 
@@ -1104,8 +1119,6 @@
     bool overflowControlsIntersectRect(const IntRect& localRect) const;
 
 protected:
-    // The bitfields are up here so they will fall into the padding from ScrollableArea on 64-bit.
-
     // Keeps track of whether the layer is currently resizing, so events can cause resizing to start and stop.
     unsigned m_inResizeMode : 1;
 
@@ -1130,6 +1143,8 @@
     // composited scrolling (which causes clipping of all descendants).
     unsigned m_hasUnclippedDescendant : 1;
 
+    unsigned m_isUnclippedDescendant : 1;
+
     unsigned m_needsCompositedScrolling : 1;
 
     // If this is true, then no non-descendant appears between any of our
@@ -1261,6 +1276,7 @@
     IntRect m_blockSelectionGapsBounds;
 
     OwnPtr<RenderLayerBacking> m_backing;
+    OwnPtr<RenderLayerScrollableArea> m_scrollableArea;
 };
 
 inline void RenderLayer::clearZOrderLists()
diff --git a/Source/core/rendering/RenderLayerBacking.cpp b/Source/core/rendering/RenderLayerBacking.cpp
index c8991f2..991d529 100644
--- a/Source/core/rendering/RenderLayerBacking.cpp
+++ b/Source/core/rendering/RenderLayerBacking.cpp
@@ -30,11 +30,11 @@
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLMediaElement.h"
 #include "core/html/canvas/CanvasRenderingContext.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/page/Chrome.h"
 #include "core/page/FrameView.h"
 #include "core/page/Settings.h"
@@ -180,20 +180,14 @@
     destroyGraphicsLayers();
 }
 
-PassOwnPtr<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(const String& name, CompositingReasons reasons)
+PassOwnPtr<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(CompositingReasons reasons)
 {
     GraphicsLayerFactory* graphicsLayerFactory = 0;
     if (Page* page = renderer()->frame()->page())
-        graphicsLayerFactory = page->chrome().client()->graphicsLayerFactory();
+        graphicsLayerFactory = page->chrome().client().graphicsLayerFactory();
 
     OwnPtr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(graphicsLayerFactory, this);
 
-#ifndef NDEBUG
-    graphicsLayer->setName(name);
-#else
-    UNUSED_PARAM(name);
-#endif
-
     graphicsLayer->setCompositingReasons(reasons);
 
     return graphicsLayer.release();
@@ -201,12 +195,7 @@
 
 void RenderLayerBacking::createPrimaryGraphicsLayer()
 {
-    String layerName;
-#ifndef NDEBUG
-    layerName = m_owningLayer->debugName();
-#endif
-
-    m_graphicsLayer = createGraphicsLayer(layerName, m_owningLayer->compositingReasons());
+    m_graphicsLayer = createGraphicsLayer(m_owningLayer->compositingReasons());
 
 #if !OS(ANDROID)
     if (m_isMainFrameRenderViewLayer)
@@ -461,7 +450,7 @@
         PluginView* pluginView = toPluginView(toRenderWidget(renderer)->widget());
         m_graphicsLayer->setContentsToMedia(pluginView->platformLayer());
     } else if (renderer->isVideo()) {
-        HTMLMediaElement* mediaElement = toMediaElement(renderer->node());
+        HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer->node());
         m_graphicsLayer->setContentsToMedia(mediaElement->platformLayer());
     } else if (isAcceleratedCanvas(renderer)) {
         HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
@@ -855,7 +844,7 @@
 
     if (needsAncestorClip) {
         if (!m_ancestorClippingLayer) {
-            m_ancestorClippingLayer = createGraphicsLayer("Ancestor clipping Layer", CompositingReasonLayerForClip);
+            m_ancestorClippingLayer = createGraphicsLayer(CompositingReasonLayerForClip);
             m_ancestorClippingLayer->setMasksToBounds(true);
             layersChanged = true;
         }
@@ -869,7 +858,7 @@
         // We don't need a child containment layer if we're the main frame render view
         // layer. It's redundant as the frame clip above us will handle this clipping.
         if (!m_childContainmentLayer && !m_isMainFrameRenderViewLayer) {
-            m_childContainmentLayer = createGraphicsLayer("Child clipping Layer", CompositingReasonLayerForClip);
+            m_childContainmentLayer = createGraphicsLayer(CompositingReasonLayerForClip);
             m_childContainmentLayer->setMasksToBounds(true);
             layersChanged = true;
         }
@@ -892,7 +881,7 @@
     bool horizontalScrollbarLayerChanged = false;
     if (needsHorizontalScrollbarLayer) {
         if (!m_layerForHorizontalScrollbar) {
-            m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar", CompositingReasonLayerForScrollbar);
+            m_layerForHorizontalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
             horizontalScrollbarLayerChanged = true;
         }
     } else if (m_layerForHorizontalScrollbar) {
@@ -903,7 +892,7 @@
     bool verticalScrollbarLayerChanged = false;
     if (needsVerticalScrollbarLayer) {
         if (!m_layerForVerticalScrollbar) {
-            m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar", CompositingReasonLayerForScrollbar);
+            m_layerForVerticalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
             verticalScrollbarLayerChanged = true;
         }
     } else if (m_layerForVerticalScrollbar) {
@@ -914,7 +903,7 @@
     bool scrollCornerLayerChanged = false;
     if (needsScrollCornerLayer) {
         if (!m_layerForScrollCorner) {
-            m_layerForScrollCorner = createGraphicsLayer("scroll corner", CompositingReasonLayerForScrollbar);
+            m_layerForScrollCorner = createGraphicsLayer(CompositingReasonLayerForScrollbar);
             scrollCornerLayerChanged = true;
         }
     } else if (m_layerForScrollCorner) {
@@ -924,9 +913,9 @@
 
     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
         if (horizontalScrollbarLayerChanged)
-            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer, HorizontalScrollbar);
+            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer->scrollableArea(), HorizontalScrollbar);
         if (verticalScrollbarLayerChanged)
-            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer, VerticalScrollbar);
+            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer->scrollableArea(), VerticalScrollbar);
     }
 
     return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
@@ -987,11 +976,7 @@
     bool layerChanged = false;
     if (needsForegroundLayer) {
         if (!m_foregroundLayer) {
-            String layerName;
-#ifndef NDEBUG
-            layerName = m_owningLayer->debugName() + " (foreground)";
-#endif
-            m_foregroundLayer = createGraphicsLayer(layerName, CompositingReasonLayerForForeground);
+            m_foregroundLayer = createGraphicsLayer(CompositingReasonLayerForForeground);
             m_foregroundLayer->setDrawsContent(true);
             m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
             layerChanged = true;
@@ -1013,11 +998,7 @@
     bool layerChanged = false;
     if (needsBackgroundLayer) {
         if (!m_backgroundLayer) {
-            String layerName;
-#ifndef NDEBUG
-            layerName = m_owningLayer->debugName() + " (background)";
-#endif
-            m_backgroundLayer = createGraphicsLayer(layerName, CompositingReasonLayerForBackground);
+            m_backgroundLayer = createGraphicsLayer(CompositingReasonLayerForBackground);
             m_backgroundLayer->setDrawsContent(true);
             m_backgroundLayer->setAnchorPoint(FloatPoint3D());
             m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintBackground);
@@ -1049,7 +1030,7 @@
     bool layerChanged = false;
     if (needsMaskLayer) {
         if (!m_maskLayer) {
-            m_maskLayer = createGraphicsLayer("Mask", CompositingReasonLayerForMask);
+            m_maskLayer = createGraphicsLayer(CompositingReasonLayerForMask);
             m_maskLayer->setDrawsContent(true);
             m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
             layerChanged = true;
@@ -1073,12 +1054,12 @@
     if (needsScrollingLayers) {
         if (!m_scrollingLayer) {
             // Outer layer which corresponds with the scroll view.
-            m_scrollingLayer = createGraphicsLayer("Scrolling container", CompositingReasonLayerForClip);
+            m_scrollingLayer = createGraphicsLayer(CompositingReasonLayerForClip);
             m_scrollingLayer->setDrawsContent(false);
             m_scrollingLayer->setMasksToBounds(true);
 
             // Inner layer which renders the content that scrolls.
-            m_scrollingContentsLayer = createGraphicsLayer("Scrolled Contents", CompositingReasonLayerForScrollingContainer);
+            m_scrollingContentsLayer = createGraphicsLayer(CompositingReasonLayerForScrollingContainer);
             m_scrollingContentsLayer->setDrawsContent(true);
             GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll;
             if (!m_foregroundLayer)
@@ -1088,14 +1069,14 @@
 
             layerChanged = true;
             if (scrollingCoordinator)
-                scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer);
+                scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer->scrollableArea());
         }
     } else if (m_scrollingLayer) {
         m_scrollingLayer = nullptr;
         m_scrollingContentsLayer = nullptr;
         layerChanged = true;
         if (scrollingCoordinator)
-            scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer);
+            scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer->scrollableArea());
     }
 
     if (layerChanged) {
@@ -1708,7 +1689,7 @@
     for (size_t i = 0; i < numKeyframes; ++i) {
         const KeyframeValue& currentKeyframe = keyframes[i];
         const RenderStyle* keyframeStyle = currentKeyframe.style();
-        float key = currentKeyframe.key();
+        double key = currentKeyframe.key();
 
         if (!keyframeStyle)
             continue;
@@ -1922,4 +1903,36 @@
     return backingMemory;
 }
 
+String RenderLayerBacking::debugName(const GraphicsLayer* graphicsLayer)
+{
+    String name;
+    if (graphicsLayer == m_graphicsLayer.get()) {
+        name = m_owningLayer->debugName();
+    } else if (graphicsLayer == m_ancestorClippingLayer.get()) {
+        name = "Ancestor Clipping Layer";
+    } else if (graphicsLayer == m_foregroundLayer.get()) {
+        name = m_owningLayer->debugName() + " (foreground) Layer";
+    } else if (graphicsLayer == m_backgroundLayer.get()) {
+        name = m_owningLayer->debugName() + " (background) Layer";
+    } else if (graphicsLayer == m_childContainmentLayer.get()) {
+        name = "Child Containment Layer";
+    } else if (graphicsLayer == m_maskLayer.get()) {
+        name = "Mask Layer";
+    } else if (graphicsLayer == m_layerForHorizontalScrollbar.get()) {
+        name = "Horizontal Scrollbar Layer";
+    } else if (graphicsLayer == m_layerForVerticalScrollbar.get()) {
+        name = "Vertical Scrollbar Layer";
+    } else if (graphicsLayer == m_layerForScrollCorner.get()) {
+        name = "Scroll Corner Layer";
+    } else if (graphicsLayer == m_scrollingLayer.get()) {
+        name = "Scrolling Layer";
+    } else if (graphicsLayer == m_scrollingContentsLayer.get()) {
+        name = "Scrolling Contents Layer";
+    } else {
+        ASSERT_NOT_REACHED();
+    }
+
+    return name;
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerBacking.h b/Source/core/rendering/RenderLayerBacking.h
index 7a62c3c..5a18edd 100644
--- a/Source/core/rendering/RenderLayerBacking.h
+++ b/Source/core/rendering/RenderLayerBacking.h
@@ -177,11 +177,13 @@
 
     void setBlendMode(BlendMode);
 
+    virtual String debugName(const GraphicsLayer*) OVERRIDE;
+
 private:
     void createPrimaryGraphicsLayer();
     void destroyGraphicsLayers();
 
-    PassOwnPtr<GraphicsLayer> createGraphicsLayer(const String& name, CompositingReasons);
+    PassOwnPtr<GraphicsLayer> createGraphicsLayer(CompositingReasons);
 
     RenderLayerModelObject* renderer() const { return m_owningLayer->renderer(); }
     RenderLayerCompositor* compositor() const { return m_owningLayer->compositor(); }
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index c8ea29d..ddab6e9 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -270,8 +270,7 @@
         // on a chrome that doesn't allow accelerated compositing.
         if (hasAcceleratedCompositing) {
             if (Page* page = this->page()) {
-                ChromeClient* chromeClient = page->chrome().client();
-                m_compositingTriggers = chromeClient->allowedCompositingTriggers();
+                m_compositingTriggers = page->chrome().client().allowedCompositingTriggers();
                 hasAcceleratedCompositing = m_compositingTriggers;
             }
         }
@@ -315,7 +314,7 @@
     IntRect visibleRect = m_containerLayer ? IntRect(IntPoint(), frameView->contentsSize()) : frameView->visibleContentRect();
     if (rootLayer->visibleRectChangeRequiresFlush(visibleRect)) {
         if (Page* page = this->page())
-            page->chrome().client()->scheduleCompositingLayerFlush();
+            page->chrome().client().scheduleCompositingLayerFlush();
     }
 }
 
@@ -326,25 +325,29 @@
 
 void RenderLayerCompositor::updateCompositingRequirementsState()
 {
-    TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::updateCompositingRequirementsState");
-
     if (!m_needsUpdateCompositingRequirementsState)
         return;
 
+    TRACE_EVENT0("blink_rendering,comp-scroll", "RenderLayerCompositor::updateCompositingRequirementsState");
+
     m_needsUpdateCompositingRequirementsState = false;
 
     if (!rootRenderLayer() || !rootRenderLayer()->acceleratedCompositingForOverflowScrollEnabled())
         return;
 
+    const bool compositorDrivenAcceleratedScrollingEnabled = rootRenderLayer()->compositorDrivenAcceleratedScrollingEnabled();
+
     const FrameView::ScrollableAreaSet* scrollableAreas = m_renderView->frameView()->scrollableAreas();
-    if (!scrollableAreas)
+    if (!compositorDrivenAcceleratedScrollingEnabled && !scrollableAreas)
         return;
 
     for (HashSet<RenderLayer*>::iterator it = m_outOfFlowPositionedLayers.begin(); it != m_outOfFlowPositionedLayers.end(); ++it)
         (*it)->updateHasUnclippedDescendant();
 
-    for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
-        (*it)->updateNeedsCompositedScrolling();
+    if (!compositorDrivenAcceleratedScrollingEnabled) {
+        for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
+            (*it)->updateNeedsCompositedScrolling();
+    }
 }
 
 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
@@ -1213,7 +1216,7 @@
 bool RenderLayerCompositor::scrollingLayerDidChange(RenderLayer* layer)
 {
     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
-        return scrollingCoordinator->scrollableAreaScrollLayerDidChange(layer);
+        return scrollingCoordinator->scrollableAreaScrollLayerDidChange(layer->scrollableArea());
     return false;
 }
 
@@ -1249,7 +1252,7 @@
     if (!renderer->node()->isFrameOwnerElement())
         return 0;
 
-    HTMLFrameOwnerElement* element = toFrameOwnerElement(renderer->node());
+    HTMLFrameOwnerElement* element = toHTMLFrameOwnerElement(renderer->node());
     if (Document* contentDocument = element->contentDocument()) {
         if (RenderView* view = contentDocument->renderView())
             return view->compositor();
@@ -1551,6 +1554,8 @@
         || requiresCompositingForBlending(renderer)
         || requiresCompositingForPosition(renderer, layer)
         || requiresCompositingForOverflowScrolling(layer)
+        || requiresCompositingForOverflowScrollingParent(layer)
+        || requiresCompositingForOutOfFlowClipping(layer)
         || renderer->isTransparent()
         || renderer->hasMask()
         || renderer->hasReflection()
@@ -1608,6 +1613,12 @@
     if (requiresCompositingForBlending(renderer))
         directReasons |= CompositingReasonBlending;
 
+    if (requiresCompositingForOverflowScrollingParent(layer))
+        directReasons |= CompositingReasonOverflowScrollingParent;
+
+    if (requiresCompositingForOutOfFlowClipping(layer))
+        directReasons |= CompositingReasonOutOfFlowClipping;
+
     return directReasons;
 }
 
@@ -1929,6 +1940,43 @@
     return renderer->hasBlendMode();
 }
 
+bool RenderLayerCompositor::requiresCompositingForOverflowScrollingParent(const RenderLayer* layer) const
+{
+    if (!layer->compositorDrivenAcceleratedScrollingEnabled())
+        return false;
+
+    // A layer scrolls with its containing block. So to find the overflow scrolling layer
+    // that we scroll with respect to, we must ascend the layer tree until we reach the
+    // first overflow scrolling div at or above our containing block. I will refer to this
+    // layer as our 'scrolling ancestor'.
+    //
+    // Now, if we reside in a normal flow list, then we will naturally scroll with our scrolling
+    // ancestor, and we need not be composited. If, on the other hand, we reside in a z-order
+    // list, and on our walk upwards to our scrolling ancestor we find no layer that is a stacking
+    // context, then we know that in the stacking tree, we will not be in the subtree rooted at
+    // our scrolling ancestor, and we will therefore not scroll with it. In this case, we must
+    // be a composited layer since the compositor will need to take special measures to ensure
+    // that we scroll with our scrolling ancestor and it cannot do this if we do not promote.
+    RenderLayer* scrollParent = layer->ancestorScrollingLayer();
+
+    if (!scrollParent || scrollParent->isStackingContext())
+        return false;
+
+    // If we hit a stacking context on our way up to the ancestor scrolling layer, it will already
+    // be composited due to an overflow scrolling parent, so we don't need to.
+    for (RenderLayer* ancestor = layer->parent(); ancestor && ancestor != scrollParent; ancestor = ancestor->parent()) {
+        if (ancestor->isStackingContext())
+            return false;
+    }
+
+    return true;
+}
+
+bool RenderLayerCompositor::requiresCompositingForOutOfFlowClipping(const RenderLayer* layer) const
+{
+    return layer->compositorDrivenAcceleratedScrollingEnabled() && layer->isUnclippedDescendant();
+}
+
 bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* renderer, const RenderLayer* layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
 {
     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
@@ -1983,7 +2031,7 @@
 
     RenderLayer* ancestor = layer->parent();
     while (ancestor && !hasScrollableAncestor) {
-        if (frameView->containsScrollableArea(ancestor))
+        if (frameView->containsScrollableArea(ancestor->scrollableArea()))
             hasScrollableAncestor = true;
         if (ancestor->renderer() == m_renderView)
             break;
@@ -2203,9 +2251,6 @@
     if (requiresOverhangAreasLayer()) {
         if (!m_layerForOverhangAreas) {
             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-            m_layerForOverhangAreas->setName("overhang areas");
-#endif
             m_layerForOverhangAreas->setDrawsContent(false);
             m_layerForOverhangAreas->setSize(m_renderView->frameView()->frameRect().size());
 
@@ -2222,9 +2267,6 @@
     if (requiresHorizontalScrollbarLayer()) {
         if (!m_layerForHorizontalScrollbar) {
             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-            m_layerForHorizontalScrollbar->setName("horizontal scrollbar");
-#endif
             m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
 
             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
@@ -2241,9 +2283,6 @@
     if (requiresVerticalScrollbarLayer()) {
         if (!m_layerForVerticalScrollbar) {
             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-            m_layerForVerticalScrollbar->setName("vertical scrollbar");
-#endif
             m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
 
             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
@@ -2260,9 +2299,6 @@
     if (requiresScrollCornerLayer()) {
         if (!m_layerForScrollCorner) {
             m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-            m_layerForScrollCorner->setName("scroll corner");
-#endif
             m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
         }
     } else if (m_layerForScrollCorner) {
@@ -2281,9 +2317,6 @@
 
     if (!m_rootContentLayer) {
         m_rootContentLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-        m_rootContentLayer->setName("content root");
-#endif
         IntRect overflowRect = m_renderView->pixelSnappedLayoutOverflowRect();
         m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
         m_rootContentLayer->setPosition(FloatPoint());
@@ -2298,22 +2331,13 @@
 
         // Create a layer to host the clipping layer and the overflow controls layers.
         m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-        m_overflowControlsHostLayer->setName("overflow controls host");
-#endif
 
         // Create a clipping layer if this is an iframe
         m_containerLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-        m_containerLayer->setName("frame clipping");
-#endif
         if (!isMainFrame())
             m_containerLayer->setMasksToBounds(true);
 
         m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
-#ifndef NDEBUG
-        m_scrollLayer->setName("frame scrolling");
-#endif
         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
             scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(m_scrollLayer.get(), true);
 
@@ -2393,8 +2417,7 @@
             Page* page = frame ? frame->page() : 0;
             if (!page)
                 return;
-
-            page->chrome().client()->attachRootGraphicsLayer(frame, rootGraphicsLayer());
+            page->chrome().client().attachRootGraphicsLayer(frame, rootGraphicsLayer());
             break;
         }
         case RootLayerAttachedViaEnclosingFrame: {
@@ -2431,8 +2454,7 @@
         Page* page = frame ? frame->page() : 0;
         if (!page)
             return;
-
-        page->chrome().client()->attachRootGraphicsLayer(frame, 0);
+        page->chrome().client().attachRootGraphicsLayer(frame, 0);
     }
     break;
     case RootLayerUnattached:
@@ -2626,8 +2648,7 @@
 GraphicsLayerFactory* RenderLayerCompositor::graphicsLayerFactory() const
 {
     if (Page* page = this->page())
-        return page->chrome().client()->graphicsLayerFactory();
-
+        return page->chrome().client().graphicsLayerFactory();
     return 0;
 }
 
@@ -2639,4 +2660,32 @@
     return 0;
 }
 
+String RenderLayerCompositor::debugName(const GraphicsLayer* graphicsLayer)
+{
+    String name;
+    if (graphicsLayer == m_rootContentLayer.get()) {
+        name = "Content Root Layer";
+#if ENABLE(RUBBER_BANDING)
+    } else if (graphicsLayer == m_layerForOverhangAreas.get()) {
+        name = "Overhang Areas Layer";
+#endif
+    } else if (graphicsLayer == m_overflowControlsHostLayer.get()) {
+        name = "Overflow Controls Host Layer";
+    } else if (graphicsLayer == m_layerForHorizontalScrollbar.get()) {
+        name = "Horizontal Scrollbar Layer";
+    } else if (graphicsLayer == m_layerForVerticalScrollbar.get()) {
+        name = "Vertical Scrollbar Layer";
+    } else if (graphicsLayer == m_layerForScrollCorner.get()) {
+        name = "Scroll Corner Layer";
+    } else if (graphicsLayer == m_containerLayer.get()) {
+        name = "Frame Clipping Layer";
+    } else if (graphicsLayer == m_scrollLayer.get()) {
+        name = "Frame Scrolling Layer";
+    } else {
+        ASSERT_NOT_REACHED();
+    }
+
+    return name;
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerCompositor.h b/Source/core/rendering/RenderLayerCompositor.h
index ac4edae..27fc5ec 100644
--- a/Source/core/rendering/RenderLayerCompositor.h
+++ b/Source/core/rendering/RenderLayerCompositor.h
@@ -205,6 +205,8 @@
     // Returns all reasons (direct, indirectly due to subtree, and indirectly due to overlap) that a layer should be composited.
     CompositingReasons reasonsForCompositing(const RenderLayer*) const;
 
+    virtual String debugName(const GraphicsLayer*) OVERRIDE;
+
 private:
     class OverlapMap;
 
@@ -283,6 +285,8 @@
     bool requiresCompositingForBackfaceVisibilityHidden(RenderObject*) const;
     bool requiresCompositingForFilters(RenderObject*) const;
     bool requiresCompositingForBlending(RenderObject* renderer) const;
+    bool requiresCompositingForOverflowScrollingParent(const RenderLayer*) const;
+    bool requiresCompositingForOutOfFlowClipping(const RenderLayer*) const;
     bool requiresCompositingForScrollableFrame() const;
     bool requiresCompositingForPosition(RenderObject*, const RenderLayer*, RenderLayer::ViewportConstrainedNotCompositedReason* = 0) const;
     bool requiresCompositingForOverflowScrolling(const RenderLayer*) const;
diff --git a/Source/core/rendering/RenderLayerFilterInfo.cpp b/Source/core/rendering/RenderLayerFilterInfo.cpp
index abad09d..8a6b4e3 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.cpp
+++ b/Source/core/rendering/RenderLayerFilterInfo.cpp
@@ -31,8 +31,8 @@
 
 #include "core/rendering/RenderLayerFilterInfo.h"
 
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/DocumentResourceReference.h"
+#include "core/fetch/DocumentResource.h"
+#include "core/fetch/DocumentResourceReference.h"
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 #include "core/rendering/FilterEffectRenderer.h"
diff --git a/Source/core/rendering/RenderLayerFilterInfo.h b/Source/core/rendering/RenderLayerFilterInfo.h
index ad29a02..4e44b3f 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.h
+++ b/Source/core/rendering/RenderLayerFilterInfo.h
@@ -31,7 +31,7 @@
 #define RenderLayerFilterInfo_h
 
 #include "core/dom/Element.h"
-#include "core/loader/cache/DocumentResource.h"
+#include "core/fetch/DocumentResource.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/graphics/filters/FilterOperation.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgramClient.h"
diff --git a/Source/core/rendering/RenderLayerModelObject.cpp b/Source/core/rendering/RenderLayerModelObject.cpp
index e0f8f77..6e91511 100644
--- a/Source/core/rendering/RenderLayerModelObject.cpp
+++ b/Source/core/rendering/RenderLayerModelObject.cpp
@@ -73,6 +73,11 @@
     return m_layer && m_layer->isSelfPaintingLayer();
 }
 
+ScrollableArea* RenderLayerModelObject::scrollableArea() const
+{
+    return m_layer ? m_layer->scrollableArea() : 0;
+}
+
 void RenderLayerModelObject::willBeDestroyed()
 {
     if (isPositioned()) {
diff --git a/Source/core/rendering/RenderLayerModelObject.h b/Source/core/rendering/RenderLayerModelObject.h
index 42f1183..959853b 100644
--- a/Source/core/rendering/RenderLayerModelObject.h
+++ b/Source/core/rendering/RenderLayerModelObject.h
@@ -28,6 +28,7 @@
 namespace WebCore {
 
 class RenderLayer;
+class ScrollableArea;
 
 class RenderLayerModelObject : public RenderObject {
 public:
@@ -39,6 +40,7 @@
 
     bool hasSelfPaintingLayer() const;
     RenderLayer* layer() const { return m_layer; }
+    ScrollableArea* scrollableArea() const;
 
     virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
diff --git a/Source/core/rendering/RenderLayerScrollableArea.cpp b/Source/core/rendering/RenderLayerScrollableArea.cpp
new file mode 100644
index 0000000..5d72399
--- /dev/null
+++ b/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -0,0 +1,256 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ *   Robert O'Callahan <roc+@cs.cmu.edu>
+ *   David Baron <dbaron@fas.harvard.edu>
+ *   Christian Biesinger <cbiesinger@web.de>
+ *   Randall Jesup <rjesup@wgate.com>
+ *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ *   Josh Soref <timeless@mac.com>
+ *   Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above.  If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderLayer.h"
+
+#include "core/page/Frame.h"
+#include "core/page/FrameView.h"
+#include "core/page/Page.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+#include "core/platform/ScrollAnimator.h"
+
+namespace WebCore {
+
+RenderLayerScrollableArea::RenderLayerScrollableArea(RenderLayer* layer)
+    : m_layer(layer)
+{
+    ScrollableArea::setConstrainsScrollingToContentEdge(false);
+
+    Node* node = m_layer->renderer()->node();
+    if (node && node->isElementNode()) {
+        // We save and restore only the scrollOffset as the other scroll values are recalculated.
+        Element* element = toElement(node);
+        m_layer->m_scrollOffset = element->savedLayerScrollOffset();
+        if (!m_layer->m_scrollOffset.isZero())
+            scrollAnimator()->setCurrentPosition(FloatPoint(m_layer->m_scrollOffset.width(), m_layer->m_scrollOffset.height()));
+        element->setSavedLayerScrollOffset(IntSize());
+    }
+
+}
+
+RenderLayerScrollableArea::~RenderLayerScrollableArea()
+{
+    if (Frame* frame = m_layer->renderer()->frame()) {
+        if (FrameView* frameView = frame->view()) {
+            frameView->removeScrollableArea(this);
+        }
+    }
+
+    if (m_layer->renderer()->frame() && m_layer->renderer()->frame()->page()) {
+        if (ScrollingCoordinator* scrollingCoordinator = m_layer->renderer()->frame()->page()->scrollingCoordinator())
+            scrollingCoordinator->willDestroyScrollableArea(this);
+    }
+}
+
+Scrollbar* RenderLayerScrollableArea::horizontalScrollbar() const
+{
+    return m_layer->horizontalScrollbar();
+}
+
+Scrollbar* RenderLayerScrollableArea::verticalScrollbar() const
+{
+    return m_layer->verticalScrollbar();
+}
+
+ScrollableArea* RenderLayerScrollableArea::enclosingScrollableArea() const
+{
+    return m_layer->enclosingScrollableArea();
+}
+
+void RenderLayerScrollableArea::updateNeedsCompositedScrolling()
+{
+    m_layer->updateNeedsCompositedScrolling();
+}
+
+GraphicsLayer* RenderLayerScrollableArea::layerForScrolling() const
+{
+    return m_layer->layerForScrolling();
+}
+
+GraphicsLayer* RenderLayerScrollableArea::layerForHorizontalScrollbar() const
+{
+    return m_layer->layerForHorizontalScrollbar();
+}
+
+GraphicsLayer* RenderLayerScrollableArea::layerForVerticalScrollbar() const
+{
+    return m_layer->layerForVerticalScrollbar();
+}
+
+GraphicsLayer* RenderLayerScrollableArea::layerForScrollCorner() const
+{
+    return m_layer->layerForScrollCorner();
+}
+
+bool RenderLayerScrollableArea::usesCompositedScrolling() const
+{
+    return m_layer->usesCompositedScrolling();
+}
+
+void RenderLayerScrollableArea::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
+{
+    m_layer->invalidateScrollbarRect(scrollbar, rect);
+}
+
+void RenderLayerScrollableArea::invalidateScrollCornerRect(const IntRect& rect)
+{
+    m_layer->invalidateScrollCornerRect(rect);
+}
+
+bool RenderLayerScrollableArea::isActive() const
+{
+    return m_layer->isActive();
+}
+
+bool RenderLayerScrollableArea::isScrollCornerVisible() const
+{
+    return m_layer->isScrollCornerVisible();
+}
+
+IntRect RenderLayerScrollableArea::scrollCornerRect() const
+{
+    return m_layer->scrollCornerRect();
+}
+
+IntRect RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& rect) const
+{
+    return m_layer->convertFromScrollbarToContainingView(scrollbar, rect);
+}
+
+IntRect RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& rect) const
+{
+    return m_layer->convertFromContainingViewToScrollbar(scrollbar, rect);
+}
+
+IntPoint RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& point) const
+{
+    return m_layer->convertFromScrollbarToContainingView(scrollbar, point);
+}
+
+IntPoint RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& point) const
+{
+    return m_layer->convertFromContainingViewToScrollbar(scrollbar, point);
+}
+
+int RenderLayerScrollableArea::scrollSize(ScrollbarOrientation orientation) const
+{
+    return m_layer->scrollSize(orientation);
+}
+
+void RenderLayerScrollableArea::setScrollOffset(const IntPoint& offset)
+{
+    m_layer->setScrollOffset(offset);
+}
+
+IntPoint RenderLayerScrollableArea::scrollPosition() const
+{
+    return m_layer->scrollPosition();
+}
+
+IntPoint RenderLayerScrollableArea::minimumScrollPosition() const
+{
+    return m_layer->minimumScrollPosition();
+}
+
+IntPoint RenderLayerScrollableArea::maximumScrollPosition() const
+{
+    return m_layer->maximumScrollPosition();
+}
+
+IntRect RenderLayerScrollableArea::visibleContentRect(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
+{
+    return m_layer->visibleContentRect(scrollbarInclusion);
+}
+
+int RenderLayerScrollableArea::visibleHeight() const
+{
+    return m_layer->visibleHeight();
+}
+
+int RenderLayerScrollableArea::visibleWidth() const
+{
+    return m_layer->visibleWidth();
+}
+
+IntSize RenderLayerScrollableArea::contentsSize() const
+{
+    return m_layer->contentsSize();
+}
+
+IntSize RenderLayerScrollableArea::overhangAmount() const
+{
+    return m_layer->overhangAmount();
+}
+
+IntPoint RenderLayerScrollableArea::lastKnownMousePosition() const
+{
+    return m_layer->lastKnownMousePosition();
+}
+
+bool RenderLayerScrollableArea::shouldSuspendScrollAnimations() const
+{
+    return m_layer->shouldSuspendScrollAnimations();
+}
+
+bool RenderLayerScrollableArea::scrollbarsCanBeActive() const
+{
+    return m_layer->scrollbarsCanBeActive();
+}
+
+IntRect RenderLayerScrollableArea::scrollableAreaBoundingBox() const
+{
+    return m_layer->scrollableAreaBoundingBox();
+}
+
+bool RenderLayerScrollableArea::userInputScrollable(ScrollbarOrientation orientation) const
+{
+    return m_layer->userInputScrollable(orientation);
+}
+
+int RenderLayerScrollableArea::pageStep(ScrollbarOrientation orientation) const
+{
+    return m_layer->pageStep(orientation);
+}
+
+} // Namespace WebCore
diff --git a/Source/core/rendering/RenderLayerScrollableArea.h b/Source/core/rendering/RenderLayerScrollableArea.h
new file mode 100644
index 0000000..79b5326
--- /dev/null
+++ b/Source/core/rendering/RenderLayerScrollableArea.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ *   Robert O'Callahan <roc+@cs.cmu.edu>
+ *   David Baron <dbaron@fas.harvard.edu>
+ *   Christian Biesinger <cbiesinger@web.de>
+ *   Randall Jesup <rjesup@wgate.com>
+ *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ *   Josh Soref <timeless@mac.com>
+ *   Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above.  If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#ifndef RenderLayerScrollableArea_h
+#define RenderLayerScrollableArea_h
+
+#include "core/platform/ScrollableArea.h"
+
+namespace WebCore {
+
+enum ResizerHitTestType {
+    ResizerForPointer,
+    ResizerForTouch
+};
+
+class RenderLayer;
+
+class RenderLayerScrollableArea FINAL : public ScrollableArea {
+    // FIXME: Remove once the bits from RenderLayer have been moved here.
+    friend class RenderLayer;
+public:
+    RenderLayerScrollableArea(RenderLayer*);
+    virtual ~RenderLayerScrollableArea();
+
+    virtual Scrollbar* horizontalScrollbar() const OVERRIDE;
+    virtual Scrollbar* verticalScrollbar() const OVERRIDE;
+    virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
+
+    virtual void updateNeedsCompositedScrolling() OVERRIDE;
+
+    virtual GraphicsLayer* layerForScrolling() const OVERRIDE;
+    virtual GraphicsLayer* layerForHorizontalScrollbar() const OVERRIDE;
+    virtual GraphicsLayer* layerForVerticalScrollbar() const OVERRIDE;
+    virtual GraphicsLayer* layerForScrollCorner() const OVERRIDE;
+    virtual bool usesCompositedScrolling() const OVERRIDE;
+    virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE;
+    virtual void invalidateScrollCornerRect(const IntRect&) OVERRIDE;
+    virtual bool isActive() const OVERRIDE;
+    virtual bool isScrollCornerVisible() const OVERRIDE;
+    virtual IntRect scrollCornerRect() const OVERRIDE;
+    virtual IntRect convertFromScrollbarToContainingView(const Scrollbar*, const IntRect&) const OVERRIDE;
+    virtual IntRect convertFromContainingViewToScrollbar(const Scrollbar*, const IntRect&) const OVERRIDE;
+    virtual IntPoint convertFromScrollbarToContainingView(const Scrollbar*, const IntPoint&) const OVERRIDE;
+    virtual IntPoint convertFromContainingViewToScrollbar(const Scrollbar*, const IntPoint&) const OVERRIDE;
+    virtual int scrollSize(ScrollbarOrientation) const OVERRIDE;
+    virtual void setScrollOffset(const IntPoint&) OVERRIDE;
+    virtual IntPoint scrollPosition() const OVERRIDE;
+    virtual IntPoint minimumScrollPosition() const OVERRIDE;
+    virtual IntPoint maximumScrollPosition() const OVERRIDE;
+    virtual IntRect visibleContentRect(VisibleContentRectIncludesScrollbars) const OVERRIDE;
+    virtual int visibleHeight() const OVERRIDE;
+    virtual int visibleWidth() const OVERRIDE;
+    virtual IntSize contentsSize() const OVERRIDE;
+    virtual IntSize overhangAmount() const OVERRIDE;
+    virtual IntPoint lastKnownMousePosition() const OVERRIDE;
+    virtual bool shouldSuspendScrollAnimations() const OVERRIDE;
+    virtual bool scrollbarsCanBeActive() const OVERRIDE;
+    virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
+    virtual bool userInputScrollable(ScrollbarOrientation) const OVERRIDE;
+    virtual int pageStep(ScrollbarOrientation) const OVERRIDE;
+
+private:
+    RenderLayer* m_layer;
+};
+
+} // Namespace WebCore
+
+#endif // RenderLayerScrollableArea_h
diff --git a/Source/core/rendering/RenderLazyBlock.cpp b/Source/core/rendering/RenderLazyBlock.cpp
deleted file mode 100644
index a43ab54..0000000
--- a/Source/core/rendering/RenderLazyBlock.cpp
+++ /dev/null
@@ -1,251 +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/rendering/RenderLazyBlock.h"
-
-#include "core/rendering/LayoutRepainter.h"
-#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderView.h"
-
-namespace WebCore {
-
-RenderLazyBlock::RenderLazyBlock(Element* element)
-    : RenderBlock(element)
-    , m_next(0)
-    , m_previous(0)
-    , m_firstVisibleChildBox(0)
-    , m_lastVisibleChildBox(0)
-    , m_attached(false)
-    , m_isNestedLayout(false)
-{
-    setChildrenInline(false); // All of our children must be block-level.
-}
-
-RenderLazyBlock::~RenderLazyBlock()
-{
-    ASSERT(!m_attached);
-}
-
-void RenderLazyBlock::willBeDestroyed()
-{
-    detachLazyBlock();
-    RenderBlock::willBeDestroyed();
-}
-
-void RenderLazyBlock::willBeRemovedFromTree()
-{
-    RenderBlock::willBeRemovedFromTree();
-    detachLazyBlock();
-}
-
-bool RenderLazyBlock::isNested() const
-{
-    for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
-        if (ancestor->isRenderLazyBlock())
-            return true;
-    }
-    return false;
-}
-
-// FIXME: This method and detachLazyBlock are essentially identical to
-// RenderQuote::attachQuote and detachQuote. We should just have a
-// RenderTreeOrderedList that does this stuff internally.
-void RenderLazyBlock::attachLazyBlock()
-{
-    ASSERT(view());
-    ASSERT(!m_attached);
-    ASSERT(!m_next && !m_previous);
-    ASSERT(isRooted());
-
-    if (!view()->firstLazyBlock()) {
-        view()->setFirstLazyBlock(this);
-        m_attached = true;
-        return;
-    }
-
-    for (RenderObject* predecessor = previousInPreOrder(); predecessor; predecessor = predecessor->previousInPreOrder()) {
-        if (!predecessor->isRenderLazyBlock() || !toRenderLazyBlock(predecessor)->isAttached())
-            continue;
-        m_previous = toRenderLazyBlock(predecessor);
-        m_next = m_previous->m_next;
-        m_previous->m_next = this;
-        if (m_next)
-            m_next->m_previous = this;
-        break;
-    }
-
-    if (!m_previous) {
-        m_next = view()->firstLazyBlock();
-        view()->setFirstLazyBlock(this);
-        if (m_next)
-            m_next->m_previous = this;
-    }
-    m_attached = true;
-
-    ASSERT(!m_next || m_next->m_attached);
-    ASSERT(!m_next || m_next->m_previous == this);
-    ASSERT(!m_previous || m_previous->m_attached);
-    ASSERT(!m_previous || m_previous->m_next == this);
-}
-
-void RenderLazyBlock::detachLazyBlock()
-{
-    ASSERT(!m_next || m_next->m_attached);
-    ASSERT(!m_previous || m_previous->m_attached);
-    if (!m_attached)
-        return;
-    if (m_previous)
-        m_previous->m_next = m_next;
-    else if (view())
-        view()->setFirstLazyBlock(m_next);
-    if (m_next)
-        m_next->m_previous = m_previous;
-    m_attached = false;
-    m_next = 0;
-    m_previous = 0;
-}
-
-void RenderLazyBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
-{
-    for (RenderBox* child = m_firstVisibleChildBox; child && child != m_lastVisibleChildBox; child = child->nextSiblingBox())
-        paintChild(child, paintInfo, paintOffset);
-}
-
-void RenderLazyBlock::layoutChildren(bool relayoutChildren)
-{
-    LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
-    LayoutUnit height = borderBefore() + paddingBefore();
-    LayoutRect intersectRect = m_intersectRect;
-
-    // FIXME: If we already have m_firstVisibleChildBox we should start there
-    // and stop when we have enough to fill the viewport. This catches the most
-    // common cases of scrolling upward or downward.
-
-    m_firstVisibleChildBox = 0;
-    m_lastVisibleChildBox = 0;
-
-    // FIXME: This should approximate the height so we don't actually need to walk
-    // every child and can optimistically layout children until we fill the
-    // the expandedViewportRect.
-
-    setLogicalHeight(height);
-    int childCount = 0;
-    LayoutUnit heightOfChildren = 0;
-    for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
-        ++childCount;
-        updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
-
-        if (relayoutChildren)
-            child->setNeedsLayout(MarkOnlyThis);
-
-        if (child->style()->logicalHeight().isSpecified()) {
-            LogicalExtentComputedValues computedValues;
-            child->computeLogicalHeight(-1, height, computedValues);
-            child->setLogicalHeight(computedValues.m_extent);
-            heightOfChildren += computedValues.m_extent;
-        } else {
-            // FIXME: Enable guessing about height so we don't need to do layout
-            // on every non fixed height child.
-            setLogicalHeight(height);
-            setLogicalTopForChild(child, height);
-            if (heightOfChildren && child->needsLayout())
-                child->setLogicalHeight(heightOfChildren / childCount);
-            else
-                child->layoutIfNeeded();
-            heightOfChildren += child->logicalHeight();
-        }
-
-        intersectRect.setHeight(child->logicalHeight());
-
-        if (m_expandedViewportRect.intersects(enclosingIntRect(intersectRect))) {
-            if (!m_firstVisibleChildBox)
-                m_firstVisibleChildBox = child;
-            m_lastVisibleChildBox = child->nextSiblingBox();
-            setLogicalHeight(height);
-            setLogicalTopForChild(child, height);
-            child->layoutIfNeeded();
-            // FIXME: Track how far off our estimated height is from the actual height,
-            // and adjust the scrollbars accordingly.
-        }
-
-        intersectRect.setY(intersectRect.y() + child->logicalHeight());
-        height += child->logicalHeight();
-    }
-
-    setLogicalHeight(height + afterEdge);
-
-    updateLogicalHeight();
-}
-
-void RenderLazyBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
-{
-    ASSERT(needsLayout());
-
-    if (!m_attached)
-        attachLazyBlock();
-
-    // FIXME: We should adjust the style to disallow columns too.
-    ASSERT(!hasColumns());
-
-    LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
-    LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
-
-    // FIXME: The compositor can instead give us a list of rects it thinks
-    // are important.
-    IntRect expandedViewportRect = view()->frameView()->visibleContentRect(ScrollableArea::IncludeScrollbars);
-    expandedViewportRect.move(-4000, -4000);
-    expandedViewportRect.expand(8000, 8000);
-
-    // FIXME: We probably want a RenderGeometryMap instead since we need to handle
-    // rotation of the RenderLazyBlock and other transforms.
-    Vector<FloatQuad> quads;
-    enclosingBoxModelObject()->absoluteQuads(quads);
-    LayoutRect intersectRect = quads[0].enclosingBoundingBox();
-    if (hasOverflowClip())
-        intersectRect.move(-scrolledContentOffset());
-
-    // Avoid doing work inside the nested layout if we know everything is correct already.
-    if (!m_isNestedLayout || m_intersectRect != intersectRect || m_expandedViewportRect != expandedViewportRect) {
-        m_intersectRect = intersectRect;
-        m_expandedViewportRect = expandedViewportRect;
-        layoutChildren(relayoutChildren || updateLogicalWidthAndColumnWidth());
-    }
-
-    statePusher.pop();
-    updateLayerTransform();
-    updateScrollInfoAfterLayout();
-    repainter.repaintAfterLayout();
-
-    m_isNestedLayout = false;
-    clearNeedsLayout();
-}
-
-} // namespace WebCore
diff --git a/Source/core/rendering/RenderLazyBlock.h b/Source/core/rendering/RenderLazyBlock.h
deleted file mode 100644
index 5f13f90..0000000
--- a/Source/core/rendering/RenderLazyBlock.h
+++ /dev/null
@@ -1,95 +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 RenderLazyBlock_h
-#define RenderLazyBlock_h
-
-#include "core/rendering/RenderBlock.h"
-
-namespace WebCore {
-
-class RenderLazyBlock FINAL : public RenderBlock {
-public:
-    RenderLazyBlock(Element*);
-    virtual ~RenderLazyBlock();
-
-    bool isAttached() const { return m_attached; }
-    bool isNested() const;
-
-    void markForNestedLayout()
-    {
-        setNeedsLayout();
-        m_isNestedLayout = true;
-    }
-
-    RenderLazyBlock* next() const { return m_next; }
-    RenderLazyBlock* previous() const { return m_previous; }
-
-    RenderBox* firstVisibleChildBox() const { return m_firstVisibleChildBox; }
-    RenderBox* lastVisibleChildBox() const { return m_lastVisibleChildBox; }
-
-private:
-    virtual void paintChildren(PaintInfo&, const LayoutPoint&) OVERRIDE;
-
-    virtual bool isRenderLazyBlock() const OVERRIDE { return true; }
-    virtual void willBeDestroyed() OVERRIDE;
-    virtual void willBeRemovedFromTree() OVERRIDE;
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight) OVERRIDE;
-
-    void layoutChildren(bool relayoutChildren);
-
-    void attachLazyBlock();
-    void detachLazyBlock();
-
-    RenderLazyBlock* m_next;
-    RenderLazyBlock* m_previous;
-    RenderBox* m_firstVisibleChildBox;
-    RenderBox* m_lastVisibleChildBox;
-    bool m_attached;
-    bool m_isNestedLayout;
-    LayoutRect m_intersectRect;
-    IntRect m_expandedViewportRect;
-};
-
-inline RenderLazyBlock* toRenderLazyBlock(RenderObject* object)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderLazyBlock());
-    return static_cast<RenderLazyBlock*>(object);
-}
-
-inline const RenderLazyBlock* toRenderLazyBlock(const RenderObject* object)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderLazyBlock());
-    return static_cast<const RenderLazyBlock*>(object);
-}
-
-} // namespace WebCore
-
-#endif // RenderLazyBlock_h
diff --git a/Source/core/rendering/RenderLineBoxList.cpp b/Source/core/rendering/RenderLineBoxList.cpp
index 6613173..5030827 100644
--- a/Source/core/rendering/RenderLineBoxList.cpp
+++ b/Source/core/rendering/RenderLineBoxList.cpp
@@ -214,7 +214,7 @@
 
     PaintInfo info(paintInfo);
     ListHashSet<RenderInline*> outlineObjects;
-    info.outlineObjects = &outlineObjects;
+    info.setOutlineObjects(&outlineObjects);
 
     // See if our root lines intersect with the dirty rect.  If so, then we paint
     // them.  Note that boxes can easily overlap, so we can't make any assumptions
@@ -227,12 +227,12 @@
     }
 
     if (info.phase == PaintPhaseOutline || info.phase == PaintPhaseSelfOutline || info.phase == PaintPhaseChildOutlines) {
-        ListHashSet<RenderInline*>::iterator end = info.outlineObjects->end();
-        for (ListHashSet<RenderInline*>::iterator it = info.outlineObjects->begin(); it != end; ++it) {
+        ListHashSet<RenderInline*>::iterator end = info.outlineObjects()->end();
+        for (ListHashSet<RenderInline*>::iterator it = info.outlineObjects()->begin(); it != end; ++it) {
             RenderInline* flow = *it;
             flow->paintOutline(info, paintOffset);
         }
-        info.outlineObjects->clear();
+        info.outlineObjects()->clear();
     }
 }
 
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index 4759684..b944498 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -82,7 +82,7 @@
 RenderListBox::RenderListBox(Element* element)
     : RenderBlock(element)
     , m_optionsChanged(true)
-    , m_scrollToRevealSelectionAfterLayout(false)
+    , m_scrollToRevealSelectionAfterLayout(true)
     , m_inAutoscroll(false)
     , m_optionsWidth(0)
     , m_indexOffset(0)
@@ -605,16 +605,11 @@
     return index >= m_indexOffset && index < m_indexOffset + numVisibleItems();
 }
 
-bool RenderListBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node**)
+bool RenderListBox::scrollImpl(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
 {
     return ScrollableArea::scroll(direction, granularity, multiplier);
 }
 
-bool RenderListBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node**)
-{
-    return ScrollableArea::scroll(logicalToPhysical(direction, style()->isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), granularity, multiplier);
-}
-
 void RenderListBox::valueChanged(unsigned listIndex)
 {
     HTMLSelectElement* element = selectElement();
diff --git a/Source/core/rendering/RenderListBox.h b/Source/core/rendering/RenderListBox.h
index f039edb..11d461d 100644
--- a/Source/core/rendering/RenderListBox.h
+++ b/Source/core/rendering/RenderListBox.h
@@ -72,8 +72,7 @@
 
     virtual bool isPointInOverflowControl(HitTestResult&, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset);
 
-    virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1, Node** stopNode = 0);
-    virtual bool logicalScroll(ScrollLogicalDirection, ScrollGranularity, float multiplier = 1, Node** stopNode = 0);
+    virtual bool scrollImpl(ScrollDirection, ScrollGranularity, float) OVERRIDE;
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
diff --git a/Source/core/rendering/RenderListItem.cpp b/Source/core/rendering/RenderListItem.cpp
index 918224a..8913dae 100644
--- a/Source/core/rendering/RenderListItem.cpp
+++ b/Source/core/rendering/RenderListItem.cpp
@@ -25,7 +25,7 @@
 #include "core/rendering/RenderListItem.h"
 
 #include "HTMLNames.h"
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLOListElement.h"
 #include "core/rendering/RenderListMarker.h"
 #include "core/rendering/RenderView.h"
diff --git a/Source/core/rendering/RenderListMarker.cpp b/Source/core/rendering/RenderListMarker.cpp
index d63728e..c2dea3b 100644
--- a/Source/core/rendering/RenderListMarker.cpp
+++ b/Source/core/rendering/RenderListMarker.cpp
@@ -26,7 +26,7 @@
 #include "core/rendering/RenderListMarker.h"
 
 #include "core/dom/Document.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/RenderLayer.h"
diff --git a/Source/core/rendering/RenderMedia.cpp b/Source/core/rendering/RenderMedia.cpp
index 662cbeb..caa1fb6 100644
--- a/Source/core/rendering/RenderMedia.cpp
+++ b/Source/core/rendering/RenderMedia.cpp
@@ -52,7 +52,7 @@
 
 HTMLMediaElement* RenderMedia::mediaElement() const
 {
-    return toMediaElement(node());
+    return toHTMLMediaElement(node());
 }
 
 void RenderMedia::layout()
diff --git a/Source/core/rendering/RenderMenuList.cpp b/Source/core/rendering/RenderMenuList.cpp
index e0856e7..d881830 100644
--- a/Source/core/rendering/RenderMenuList.cpp
+++ b/Source/core/rendering/RenderMenuList.cpp
@@ -384,10 +384,12 @@
     if (listIndex < 0 || listIndex >= static_cast<int>(select->listItems().size()))
         return;
 
-    ASSERT(select->listItems()[listIndex]);
-
-    if (AccessibilityMenuList* menuList = static_cast<AccessibilityMenuList*>(document()->axObjectCache()->get(this)))
-        menuList->didUpdateActiveOption(optionIndex);
+    HTMLElement* listItem = select->listItems()[listIndex];
+    ASSERT(listItem);
+    if (listItem->attached()) {
+        if (AccessibilityMenuList* menuList = static_cast<AccessibilityMenuList*>(document()->axObjectCache()->get(this)))
+            menuList->didUpdateActiveOption(optionIndex);
+    }
 }
 
 String RenderMenuList::itemText(unsigned listIndex) const
diff --git a/Source/core/rendering/RenderMultiColumnBlock.cpp b/Source/core/rendering/RenderMultiColumnBlock.cpp
index 5ab8cb6..ebcf426 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.cpp
+++ b/Source/core/rendering/RenderMultiColumnBlock.cpp
@@ -146,7 +146,7 @@
     m_flowThread->addChild(newChild, beforeChild);
 }
 
-RenderObject* RenderMultiColumnBlock::layoutSpecialExcludedChild(bool relayoutChildren)
+RenderObject* RenderMultiColumnBlock::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
 {
     if (!m_flowThread)
         return 0;
@@ -170,7 +170,7 @@
         m_flowThread->invalidateRegions();
 
     if (relayoutChildren)
-        m_flowThread->setChildNeedsLayout(MarkOnlyThis);
+        layoutScope.setChildNeedsLayout(m_flowThread);
 
     setLogicalTopForChild(m_flowThread, borderBefore() + paddingBefore());
     m_flowThread->layoutIfNeeded();
diff --git a/Source/core/rendering/RenderMultiColumnBlock.h b/Source/core/rendering/RenderMultiColumnBlock.h
index 6b441c2..881bd8a 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.h
+++ b/Source/core/rendering/RenderMultiColumnBlock.h
@@ -51,7 +51,7 @@
 
     virtual const char* renderName() const;
 
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren) OVERRIDE;
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&) OVERRIDE;
 
     virtual void styleDidChange(StyleDifference, const RenderStyle*) OVERRIDE;
 
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index 58bbf32..d2546bc 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -63,7 +63,6 @@
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderLazyBlock.h"
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderMarquee.h"
 #include "core/rendering/RenderMultiColumnBlock.h"
@@ -83,6 +82,7 @@
 #include "core/rendering/svg/SVGRenderSupport.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/UnusedParam.h"
+#include "wtf/text/StringBuilder.h"
 #include <algorithm>
 #include <stdio.h>
 
@@ -213,8 +213,6 @@
     case GRID:
     case INLINE_GRID:
         return new RenderGrid(element);
-    case LAZY_BLOCK:
-        return new RenderLazyBlock(element);
     }
 
     return 0;
@@ -255,7 +253,6 @@
     return document()->page()->theme();
 }
 
-#ifndef NDEBUG
 String RenderObject::debugName() const
 {
     StringBuilder name;
@@ -268,7 +265,6 @@
 
     return name.toString();
 }
-#endif
 
 bool RenderObject::isDescendantOf(const RenderObject* obj) const
 {
@@ -673,10 +669,11 @@
     return true;
 }
 
-void RenderObject::markContainingBlocksForLayout(bool scheduleRelayout, RenderObject* newRoot)
+void RenderObject::markContainingBlocksForLayout(bool scheduleRelayout, RenderObject* newRoot, SubtreeLayoutScope* layouter)
 {
     ASSERT(!scheduleRelayout || !newRoot);
     ASSERT(!isSetNeedsLayoutForbidden());
+    ASSERT(!layouter || this != layouter->root());
 
     RenderObject* object = container();
     RenderObject* last = this;
@@ -722,6 +719,12 @@
             ASSERT(!object->isSetNeedsLayoutForbidden());
         }
 
+        if (layouter) {
+            layouter->addRendererToLayout(object);
+            if (object == layouter->root())
+                return;
+        }
+
         if (object == newRoot)
             return;
 
@@ -1121,7 +1124,7 @@
 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
 {
     Vector<IntRect> focusRingRects;
-    addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
+    addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer());
     if (style->outlineStyleIsAuto())
         paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), resolveColor(style, CSSPropertyOutlineColor));
     else
@@ -1654,15 +1657,15 @@
 
 #endif // NDEBUG
 
-static bool shouldUseSelectionColor(const RenderStyle& style)
+bool RenderObject::isSelectable() const
 {
-    return style.userSelect() != SELECT_NONE || style.userModify() != READ_ONLY;
+    return !isInert() && !(style()->userSelect() == SELECT_NONE && style()->userModify() == READ_ONLY);
 }
 
 Color RenderObject::selectionBackgroundColor() const
 {
     Color backgroundColor= Color::transparent;
-    if (shouldUseSelectionColor(*style())) {
+    if (isSelectable()) {
         RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
         if (pseudoStyle) {
             StyleColor styleColor = resolveCurrentColor(pseudoStyle.get(), CSSPropertyBackgroundColor);
@@ -1682,8 +1685,7 @@
 {
     // If the element is unselectable, or we are only painting the selection,
     // don't override the foreground color with the selection foreground color.
-    if (!shouldUseSelectionColor(*style())
-        || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
+    if (!isSelectable() || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
         return Color::transparent;
 
     Color color;
@@ -1864,10 +1866,13 @@
     updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style ? m_style->borderImage().image() : 0);
     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
 
+    updateShapeImage(oldStyle ? oldStyle->shapeInside() : 0, m_style ? m_style->shapeInside() : 0);
+
     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
-    if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
-        toRenderView(document()->renderer())->setMaximalOutlineSize(m_style->outlineSize());
+    // FIXME: Do this more cleanly. http://crbug.com/273904
+    if (m_style->outlineWidth() > 0 && m_style->outlineSize() > view()->maximalOutlineSize())
+        view()->setMaximalOutlineSize(m_style->outlineSize());
 
     bool doesNotNeedLayout = !m_parent || isText();
 
@@ -2105,6 +2110,12 @@
     }
 }
 
+void RenderObject::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
+{
+    if (oldShapeValue || newShapeValue)
+        updateImage(oldShapeValue ? oldShapeValue->image() : 0, newShapeValue ? newShapeValue->image() : 0);
+}
+
 LayoutRect RenderObject::viewRect() const
 {
     return view()->viewRect();
@@ -2656,6 +2667,14 @@
     // WARNING: |this| is deleted here.
 }
 
+void RenderObject::removeShapeImageClient(ShapeValue* shapeValue)
+{
+    if (!shapeValue)
+        return;
+    if (StyleImage* shapeImage = shapeValue->image())
+        shapeImage->removeClient(this);
+}
+
 void RenderObject::destroy()
 {
     willBeDestroyed();
@@ -2681,6 +2700,8 @@
 
         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
             maskBoxImage->removeClient(this);
+
+        removeShapeImageClient(m_style->shapeInside());
     }
 
     delete this;
@@ -2785,22 +2806,18 @@
     clearNeedsLayout();
 }
 
-// FIXME: Do we need this method at all? If setNeedsLayout early returns in all the right places,
-// then MarkOnlyThis is not needed for performance or correctness.
 void RenderObject::forceLayout()
 {
-    // This is the only way it's safe to use MarkOnlyThis (i.e. if we're immediately going to call layout).
-    // FIXME: Add asserts that we only ever do the MarkOnlyThis behavior from here.
-    setNeedsLayout(MarkOnlyThis);
+    setSelfNeedsLayout(true);
     layout();
 }
 
-// FIXME: Does this do anything different than forceLayout given that we're passing MarkOnlyThis.
-// I don't think it does and we should change all callers to use forceLayout.
+// FIXME: Does this do anything different than forceLayout given that we don't walk
+// the containing block chain. If not, we should change all callers to use forceLayout.
 void RenderObject::forceChildLayout()
 {
-    setChildNeedsLayout(MarkOnlyThis);
-    forceLayout();
+    setNormalChildNeedsLayout(true);
+    layout();
 }
 
 enum StyleCacheState {
@@ -3066,10 +3083,7 @@
     const RenderObject* renderer = this;
     while (!renderer->node())
         renderer = renderer->parent();
-    const Node* parentNode = renderer->node();
-    while (parentNode && !parentNode->isElementNode())
-        parentNode = parentNode->parentNode();
-    return parentNode && toElement(parentNode)->isInert();
+    return renderer->node()->isInert();
 }
 
 void RenderObject::imageChanged(ImageResource* image, const IntRect* rect)
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index 4d34112..9429d07 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -29,13 +29,14 @@
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Element.h"
 #include "core/dom/Position.h"
-#include "core/loader/cache/ImageResourceClient.h"
+#include "core/fetch/ImageResourceClient.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/graphics/transforms/TransformationMatrix.h"
 #include "core/rendering/PaintPhase.h"
 #include "core/rendering/RenderObjectChildList.h"
 #include "core/rendering/ScrollBehavior.h"
+#include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/style/StyleInheritedData.h"
 #include "wtf/HashSet.h"
@@ -149,9 +150,7 @@
 
     virtual const char* renderName() const = 0;
 
-#ifndef NDEBUG
     String debugName() const;
-#endif
 
     RenderObject* parent() const { return m_parent; }
     bool isDescendantOf(const RenderObject*) const;
@@ -332,7 +331,6 @@
     virtual bool isProgress() const { return false; }
     virtual bool isRenderBlock() const { return false; }
     virtual bool isRenderSVGBlock() const { return false; };
-    virtual bool isRenderLazyBlock() const { return false; }
     virtual bool isRenderButton() const { return false; }
     virtual bool isRenderIFrame() const { return false; }
     virtual bool isRenderImage() const { return false; }
@@ -548,15 +546,15 @@
 
     bool needsLayout() const
     {
-        return m_bitfields.needsLayout() || m_bitfields.normalChildNeedsLayout() || m_bitfields.posChildNeedsLayout()
+        return m_bitfields.selfNeedsLayout() || m_bitfields.normalChildNeedsLayout() || m_bitfields.posChildNeedsLayout()
             || m_bitfields.needsSimplifiedNormalFlowLayout() || m_bitfields.needsPositionedMovementLayout();
     }
 
-    bool selfNeedsLayout() const { return m_bitfields.needsLayout(); }
+    bool selfNeedsLayout() const { return m_bitfields.selfNeedsLayout(); }
     bool needsPositionedMovementLayout() const { return m_bitfields.needsPositionedMovementLayout(); }
     bool needsPositionedMovementLayoutOnly() const
     {
-        return m_bitfields.needsPositionedMovementLayout() && !m_bitfields.needsLayout() && !m_bitfields.normalChildNeedsLayout()
+        return m_bitfields.needsPositionedMovementLayout() && !m_bitfields.selfNeedsLayout() && !m_bitfields.normalChildNeedsLayout()
             && !m_bitfields.posChildNeedsLayout() && !m_bitfields.needsSimplifiedNormalFlowLayout();
     }
 
@@ -621,10 +619,10 @@
 
     Element* offsetParent() const;
 
-    void markContainingBlocksForLayout(bool scheduleRelayout = true, RenderObject* newRoot = 0);
-    void setNeedsLayout(MarkingBehavior = MarkContainingBlockChain);
+    void markContainingBlocksForLayout(bool scheduleRelayout = true, RenderObject* newRoot = 0, SubtreeLayoutScope* = 0);
+    void setNeedsLayout(MarkingBehavior = MarkContainingBlockChain, SubtreeLayoutScope* = 0);
     void clearNeedsLayout();
-    void setChildNeedsLayout(MarkingBehavior = MarkContainingBlockChain);
+    void setChildNeedsLayout(MarkingBehavior = MarkContainingBlockChain, SubtreeLayoutScope* = 0);
     void setNeedsPositionedMovementLayout();
     void setNeedsSimplifiedNormalFlowLayout();
     void setPreferredLogicalWidthsDirty(bool, MarkingBehavior = MarkContainingBlockChain);
@@ -663,6 +661,7 @@
 
     void updateFillImages(const FillLayer*, const FillLayer*);
     void updateImage(StyleImage*, StyleImage*);
+    void updateShapeImage(const ShapeValue*, const ShapeValue*);
 
     virtual void paint(PaintInfo&, const LayoutPoint&);
 
@@ -902,6 +901,7 @@
     virtual bool canBeSelectionLeaf() const { return false; }
     bool hasSelectedChildren() const { return selectionState() != SelectionNone; }
 
+    bool isSelectable() const;
     // Obtains the selection colors that should be used when painting a selection.
     Color selectionBackgroundColor() const;
     Color selectionForegroundColor() const;
@@ -1070,6 +1070,8 @@
         return styleColor;
     }
 
+    void removeShapeImageClient(ShapeValue*);
+
 #ifndef NDEBUG
     void checkBlockPositionedObjectsNeedLayout();
 #endif
@@ -1106,7 +1108,7 @@
 
     public:
         RenderObjectBitfields(Node* node)
-            : m_needsLayout(false)
+            : m_selfNeedsLayout(false)
             , m_needsPositionedMovementLayout(false)
             , m_normalChildNeedsLayout(false)
             , m_posChildNeedsLayout(false)
@@ -1136,7 +1138,7 @@
         }
 
         // 31 bits have been used here. There is one bit available.
-        ADD_BOOLEAN_BITFIELD(needsLayout, NeedsLayout);
+        ADD_BOOLEAN_BITFIELD(selfNeedsLayout, SelfNeedsLayout);
         ADD_BOOLEAN_BITFIELD(needsPositionedMovementLayout, NeedsPositionedMovementLayout);
         ADD_BOOLEAN_BITFIELD(normalChildNeedsLayout, NormalChildNeedsLayout);
         ADD_BOOLEAN_BITFIELD(posChildNeedsLayout, PosChildNeedsLayout);
@@ -1197,7 +1199,7 @@
 
     RenderObjectBitfields m_bitfields;
 
-    // FIXME: These private methods are silly. We should just call m_bitfields.setXXX(b) directly.
+    void setSelfNeedsLayout(bool b) { m_bitfields.setSelfNeedsLayout(b); }
     void setNeedsPositionedMovementLayout(bool b) { m_bitfields.setNeedsPositionedMovementLayout(b); }
     void setNormalChildNeedsLayout(bool b) { m_bitfields.setNormalChildNeedsLayout(b); }
     void setPosChildNeedsLayout(bool b) { m_bitfields.setPosChildNeedsLayout(b); }
@@ -1240,14 +1242,14 @@
     return isBeforeContent() || isAfterContent();
 }
 
-inline void RenderObject::setNeedsLayout(MarkingBehavior markParents)
+inline void RenderObject::setNeedsLayout(MarkingBehavior markParents, SubtreeLayoutScope* layouter)
 {
     ASSERT(!isSetNeedsLayoutForbidden());
-    bool alreadyNeededLayout = m_bitfields.needsLayout();
-    m_bitfields.setNeedsLayout(true);
+    bool alreadyNeededLayout = m_bitfields.selfNeedsLayout();
+    setSelfNeedsLayout(true);
     if (!alreadyNeededLayout) {
-        if (markParents == MarkContainingBlockChain)
-            markContainingBlocksForLayout();
+        if (markParents == MarkContainingBlockChain && (!layouter || layouter->root() != this))
+            markContainingBlocksForLayout(true, 0, layouter);
         if (hasLayer())
             setLayerNeedsFullRepaint();
     }
@@ -1255,7 +1257,7 @@
 
 inline void RenderObject::clearNeedsLayout()
 {
-    m_bitfields.setNeedsLayout(false);
+    setSelfNeedsLayout(false);
     setEverHadLayout(true);
     setPosChildNeedsLayout(false);
     setNeedsSimplifiedNormalFlowLayout(false);
@@ -1267,13 +1269,14 @@
 #endif
 }
 
-inline void RenderObject::setChildNeedsLayout(MarkingBehavior markParents)
+inline void RenderObject::setChildNeedsLayout(MarkingBehavior markParents, SubtreeLayoutScope* layouter)
 {
     ASSERT(!isSetNeedsLayoutForbidden());
     bool alreadyNeededLayout = normalChildNeedsLayout();
     setNormalChildNeedsLayout(true);
-    if (!alreadyNeededLayout && markParents == MarkContainingBlockChain)
-        markContainingBlocksForLayout();
+    // FIXME: Replace MarkOnlyThis with the SubtreeLayoutScope code path and remove the MarkingBehavior argument entirely.
+    if (!alreadyNeededLayout && markParents == MarkContainingBlockChain && (!layouter || layouter->root() != this))
+        markContainingBlocksForLayout(true, 0, layouter);
 }
 
 inline void RenderObject::setNeedsPositionedMovementLayout()
diff --git a/Source/core/rendering/RenderOverflow.h b/Source/core/rendering/RenderOverflow.h
index 1c5417f..49ad02a 100644
--- a/Source/core/rendering/RenderOverflow.h
+++ b/Source/core/rendering/RenderOverflow.h
@@ -91,10 +91,13 @@
 {
     LayoutUnit maxX = std::max(rect.maxX(), m_layoutOverflow.maxX());
     LayoutUnit maxY = std::max(rect.maxY(), m_layoutOverflow.maxY());
-    m_layoutOverflow.setX(std::min(rect.x(), m_layoutOverflow.x()));
-    m_layoutOverflow.setY(std::min(rect.y(), m_layoutOverflow.y()));
-    m_layoutOverflow.setWidth(maxX - m_layoutOverflow.x());
-    m_layoutOverflow.setHeight(maxY - m_layoutOverflow.y());
+    LayoutUnit minX = std::min(rect.x(), m_layoutOverflow.x());
+    LayoutUnit minY = std::min(rect.y(), m_layoutOverflow.y());
+    // In case the width/height is larger than LayoutUnit can represent, fix the right/bottom edge and shift the top/left ones
+    m_layoutOverflow.setWidth(maxX - minX);
+    m_layoutOverflow.setHeight(maxY - minY);
+    m_layoutOverflow.setX(maxX - m_layoutOverflow.width());
+    m_layoutOverflow.setY(maxY - m_layoutOverflow.height());
 }
 
 inline void RenderOverflow::addVisualOverflow(const LayoutRect& rect)
diff --git a/Source/core/rendering/RenderPart.cpp b/Source/core/rendering/RenderPart.cpp
index 4395bcc..fa73e5e 100644
--- a/Source/core/rendering/RenderPart.cpp
+++ b/Source/core/rendering/RenderPart.cpp
@@ -85,7 +85,7 @@
     if (!node() || !node()->isFrameOwnerElement())
         return false;
 
-    HTMLFrameOwnerElement* element = toFrameOwnerElement(node());
+    HTMLFrameOwnerElement* element = toHTMLFrameOwnerElement(node());
     if (Document* contentDocument = element->contentDocument()) {
         if (RenderView* view = contentDocument->renderView())
             return view->usesCompositing();
diff --git a/Source/core/rendering/RenderReplaced.cpp b/Source/core/rendering/RenderReplaced.cpp
index 8b229f4..6d569f0 100644
--- a/Source/core/rendering/RenderReplaced.cpp
+++ b/Source/core/rendering/RenderReplaced.cpp
@@ -311,6 +311,42 @@
     }
 }
 
+LayoutRect RenderReplaced::replacedContentRect(const LayoutSize* overriddenIntrinsicSize) const
+{
+    LayoutRect contentRect = contentBoxRect();
+    ObjectFit objectFit = style()->objectFit();
+    if (objectFit == ObjectFitFill)
+        return contentRect;
+
+    LayoutSize intrinsicSize = overriddenIntrinsicSize ? *overriddenIntrinsicSize : this->intrinsicSize();
+    if (!intrinsicSize.width() || !intrinsicSize.height())
+        return contentRect;
+
+    LayoutRect finalRect = contentRect;
+    switch (objectFit) {
+    case ObjectFitContain:
+    case ObjectFitScaleDown:
+    case ObjectFitCover:
+        finalRect.setSize(finalRect.size().fitToAspectRatio(intrinsicSize, objectFit == ObjectFitCover ? AspectRatioFitGrow : AspectRatioFitShrink));
+        if (objectFit != ObjectFitScaleDown || finalRect.width() <= intrinsicSize.width())
+            break;
+        // fall through
+    case ObjectFitNone:
+        finalRect.setSize(intrinsicSize);
+        break;
+    case ObjectFitFill:
+        ASSERT_NOT_REACHED();
+    }
+
+    // FIXME: This is where object-position should be taken into account, but since it's not
+    // implemented yet, assume the initial value of "50% 50%".
+    LayoutUnit xOffset = (contentRect.width() - finalRect.width()) / 2;
+    LayoutUnit yOffset = (contentRect.height() - finalRect.height()) / 2;
+    finalRect.move(xOffset, yOffset);
+
+    return finalRect;
+}
+
 void RenderReplaced::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
 {
     // If there's an embeddedContentBox() of a remote, referenced document available, this code-path should never be used.
diff --git a/Source/core/rendering/RenderReplaced.h b/Source/core/rendering/RenderReplaced.h
index 9b04219..e5db970 100644
--- a/Source/core/rendering/RenderReplaced.h
+++ b/Source/core/rendering/RenderReplaced.h
@@ -46,6 +46,7 @@
     virtual void layout();
 
     virtual LayoutSize intrinsicSize() const OVERRIDE FINAL { return m_intrinsicSize; }
+    LayoutRect replacedContentRect(const LayoutSize* overriddenIntrinsicSize = 0) const;
     virtual void computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const;
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE FINAL;
diff --git a/Source/core/rendering/RenderRubyRun.cpp b/Source/core/rendering/RenderRubyRun.cpp
index a0d3c10..46b5656 100644
--- a/Source/core/rendering/RenderRubyRun.cpp
+++ b/Source/core/rendering/RenderRubyRun.cpp
@@ -214,7 +214,7 @@
     return rr;
 }
 
-RenderObject* RenderRubyRun::layoutSpecialExcludedChild(bool relayoutChildren)
+RenderObject* RenderRubyRun::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
 {
     StackStats::LayoutCheckPoint layoutCheckPoint;
     // Don't bother positioning the RenderRubyRun yet.
@@ -222,7 +222,7 @@
     if (!rt)
         return 0;
     if (relayoutChildren)
-        rt->setChildNeedsLayout(MarkOnlyThis);
+        layoutScope.setChildNeedsLayout(rt);
     rt->layoutIfNeeded();
     return rt;
 }
diff --git a/Source/core/rendering/RenderRubyRun.h b/Source/core/rendering/RenderRubyRun.h
index 2c8bdae..37a1ee3 100644
--- a/Source/core/rendering/RenderRubyRun.h
+++ b/Source/core/rendering/RenderRubyRun.h
@@ -52,7 +52,7 @@
     RenderRubyBase* rubyBase() const;
     RenderRubyBase* rubyBaseSafe(); // creates the base if it doesn't already exist
 
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren);
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
     virtual void layout();
 
     virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
diff --git a/Source/core/rendering/RenderSearchField.cpp b/Source/core/rendering/RenderSearchField.cpp
index 4e4244c..f7ca739 100644
--- a/Source/core/rendering/RenderSearchField.cpp
+++ b/Source/core/rendering/RenderSearchField.cpp
@@ -24,6 +24,7 @@
 #include "config.h"
 #include "core/rendering/RenderSearchField.h"
 
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/shadow/ShadowElementNames.h"
 
@@ -47,12 +48,12 @@
 
 inline Element* RenderSearchField::searchDecorationElement() const
 {
-    return inputElement()->uaShadowElementById(ShadowElementNames::searchDecoration());
+    return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::searchDecoration());
 }
 
 inline Element* RenderSearchField::cancelButtonElement() const
 {
-    return inputElement()->uaShadowElementById(ShadowElementNames::clearButton());
+    return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton());
 }
 
 LayoutUnit RenderSearchField::computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const
@@ -73,35 +74,6 @@
     return lineHeight + nonContentHeight;
 }
 
-void RenderSearchField::updateFromElement()
-{
-    RenderTextControlSingleLine::updateFromElement();
-
-    if (cancelButtonElement())
-        updateCancelButtonVisibility();
-}
-
-void RenderSearchField::updateCancelButtonVisibility() const
-{
-    RenderObject* cancelButtonRenderer = cancelButtonElement()->renderer();
-    if (!cancelButtonRenderer)
-        return;
-
-    const RenderStyle* curStyle = cancelButtonRenderer->style();
-    EVisibility buttonVisibility = visibilityForCancelButton();
-    if (curStyle->visibility() == buttonVisibility)
-        return;
-
-    RefPtr<RenderStyle> cancelButtonStyle = RenderStyle::clone(curStyle);
-    cancelButtonStyle->setVisibility(buttonVisibility);
-    cancelButtonRenderer->setStyle(cancelButtonStyle);
-}
-
-EVisibility RenderSearchField::visibilityForCancelButton() const
-{
-    return (style()->visibility() == HIDDEN || inputElement()->value().isEmpty()) ? HIDDEN : VISIBLE;
-}
-
 LayoutUnit RenderSearchField::computeLogicalHeightLimit() const
 {
     return logicalHeight();
diff --git a/Source/core/rendering/RenderSearchField.h b/Source/core/rendering/RenderSearchField.h
index d8617ae..006169b 100644
--- a/Source/core/rendering/RenderSearchField.h
+++ b/Source/core/rendering/RenderSearchField.h
@@ -33,17 +33,12 @@
 public:
     RenderSearchField(HTMLInputElement*);
     virtual ~RenderSearchField();
-
-    void updateCancelButtonVisibility() const;
-
     void stopSearchEventTimer();
 
 private:
     virtual void centerContainerIfNeeded(RenderBox*) const OVERRIDE;
     virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const OVERRIDE;
     virtual LayoutUnit computeLogicalHeightLimit() const OVERRIDE;
-    virtual void updateFromElement() OVERRIDE;
-    EVisibility visibilityForCancelButton() const;
 
     Element* searchDecorationElement() const;
     Element* cancelButtonElement() const;
diff --git a/Source/core/rendering/RenderSlider.cpp b/Source/core/rendering/RenderSlider.cpp
index bb0be19..c220f6b 100644
--- a/Source/core/rendering/RenderSlider.cpp
+++ b/Source/core/rendering/RenderSlider.cpp
@@ -21,7 +21,9 @@
 #include "config.h"
 #include "core/rendering/RenderSlider.h"
 
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/SliderThumbElement.h"
 #include "wtf/MathExtras.h"
 
@@ -88,12 +90,17 @@
     setPreferredLogicalWidthsDirty(false);
 }
 
+inline SliderThumbElement* RenderSlider::sliderThumbElement() const
+{
+    return toSliderThumbElement(toElement(node())->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb()));
+}
+
 void RenderSlider::layout()
 {
     StackStats::LayoutCheckPoint layoutCheckPoint;
     // FIXME: Find a way to cascade appearance.
     // http://webkit.org/b/62535
-    RenderBox* thumbBox = sliderThumbElementOf(node())->renderBox();
+    RenderBox* thumbBox = sliderThumbElement()->renderBox();
     if (thumbBox && thumbBox->isSliderThumb())
         static_cast<RenderSliderThumb*>(thumbBox)->updateAppearance(style());
 
@@ -102,7 +109,7 @@
 
 bool RenderSlider::inDragMode() const
 {
-    return sliderThumbElementOf(node())->active();
+    return sliderThumbElement()->active();
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderSlider.h b/Source/core/rendering/RenderSlider.h
index 68dfbd0..d6b457e 100644
--- a/Source/core/rendering/RenderSlider.h
+++ b/Source/core/rendering/RenderSlider.h
@@ -48,6 +48,8 @@
     virtual void computePreferredLogicalWidths() OVERRIDE;
     virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
     virtual void layout();
+
+    SliderThumbElement* sliderThumbElement() const;
 };
 
 inline RenderSlider* toRenderSlider(RenderObject* object)
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index 12ea553..7ea9fa2 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -40,6 +40,7 @@
 #include "core/rendering/RenderTableCol.h"
 #include "core/rendering/RenderTableSection.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/style/CollapsedBorderValue.h"
 #include "core/rendering/style/StyleInheritedData.h"
 
@@ -422,9 +423,11 @@
     LayoutUnit oldLogicalWidth = logicalWidth();
     updateLogicalWidth();
 
+    SubtreeLayoutScope layouter(this);
+
     if (logicalWidth() != oldLogicalWidth) {
         for (unsigned i = 0; i < m_captions.size(); i++)
-            m_captions[i]->setNeedsLayout(MarkOnlyThis);
+            layouter.setNeedsLayout(m_captions[i]);
     }
     // FIXME: The optimisation below doesn't work since the internal table
     // layout could have changed.  we need to add a flag to the table
@@ -444,7 +447,7 @@
         if (child->isTableSection()) {
             RenderTableSection* section = toRenderTableSection(child);
             if (m_columnLogicalWidthChanged)
-                section->setChildNeedsLayout(MarkOnlyThis);
+                layouter.setChildNeedsLayout(section);
             section->layoutIfNeeded();
             totalSectionLogicalHeight += section->calcRowLogicalHeight();
             if (collapsing)
diff --git a/Source/core/rendering/RenderTableCell.cpp b/Source/core/rendering/RenderTableCell.cpp
index b67203d..25ae144 100644
--- a/Source/core/rendering/RenderTableCell.cpp
+++ b/Source/core/rendering/RenderTableCell.cpp
@@ -34,6 +34,7 @@
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTableCol.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/style/CollapsedBorderValue.h"
 
 using namespace std;
@@ -162,7 +163,7 @@
     }
 }
 
-void RenderTableCell::computeIntrinsicPadding(int rowHeight)
+void RenderTableCell::computeIntrinsicPadding(int rowHeight, SubtreeLayoutScope& layouter)
 {
     int oldIntrinsicPaddingBefore = intrinsicPaddingBefore();
     int oldIntrinsicPaddingAfter = intrinsicPaddingAfter();
@@ -200,20 +201,19 @@
     // FIXME: Changing an intrinsic padding shouldn't trigger a relayout as it only shifts the cell inside the row but
     // doesn't change the logical height.
     if (intrinsicPaddingBefore != oldIntrinsicPaddingBefore || intrinsicPaddingAfter != oldIntrinsicPaddingAfter)
-        setNeedsLayout(MarkOnlyThis);
+        layouter.setNeedsLayout(this);
 }
 
 void RenderTableCell::updateLogicalWidth()
 {
 }
 
-void RenderTableCell::setCellLogicalWidth(int tableLayoutLogicalWidth)
+void RenderTableCell::setCellLogicalWidth(int tableLayoutLogicalWidth, SubtreeLayoutScope& layouter)
 {
     if (tableLayoutLogicalWidth == logicalWidth())
         return;
 
-    setNeedsLayout(MarkOnlyThis);
-    row()->setChildNeedsLayout(MarkOnlyThis);
+    layouter.setNeedsLayout(this);
 
     if (!table()->selfNeedsLayout() && checkForRepaintDuringLayout())
         repaint();
@@ -224,6 +224,8 @@
 
 void RenderTableCell::layout()
 {
+    ASSERT(needsLayout());
+
     StackStats::LayoutCheckPoint layoutCheckPoint;
     updateFirstLetter();
 
@@ -237,7 +239,8 @@
     if (isBaselineAligned() && section()->rowBaseline(rowIndex()) && cellBaselinePosition() > section()->rowBaseline(rowIndex())) {
         int newIntrinsicPaddingBefore = max<LayoutUnit>(0, intrinsicPaddingBefore() - max<LayoutUnit>(0, cellBaselinePosition() - oldCellBaseline));
         setIntrinsicPaddingBefore(newIntrinsicPaddingBefore);
-        setNeedsLayout(MarkOnlyThis);
+        SubtreeLayoutScope layouter(this);
+        layouter.setNeedsLayout(this);
         layoutBlock(cellWidthChanged());
     }
 
diff --git a/Source/core/rendering/RenderTableCell.h b/Source/core/rendering/RenderTableCell.h
index 14dac60..9a0da52 100644
--- a/Source/core/rendering/RenderTableCell.h
+++ b/Source/core/rendering/RenderTableCell.h
@@ -35,6 +35,8 @@
 
 enum IncludeBorderColorOrNot { DoNotIncludeBorderColor, IncludeBorderColor };
 
+class SubtreeLayoutScope;
+
 class RenderTableCell FINAL : public RenderBlock {
 public:
     explicit RenderTableCell(Element*);
@@ -103,7 +105,7 @@
     }
 
 
-    void setCellLogicalWidth(int constrainedLogicalWidth);
+    void setCellLogicalWidth(int constrainedLogicalWidth, SubtreeLayoutScope&);
 
     virtual int borderLeft() const;
     virtual int borderRight() const;
@@ -131,7 +133,7 @@
         return va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP || va == SUPER || va == SUB || va == LENGTH;
     }
 
-    void computeIntrinsicPadding(int rowHeight);
+    void computeIntrinsicPadding(int rowHeight, SubtreeLayoutScope&);
     void clearIntrinsicPadding() { setIntrinsicPadding(0, 0); }
 
     int intrinsicPaddingBefore() const { return m_intrinsicPaddingBefore; }
diff --git a/Source/core/rendering/RenderTableCol.cpp b/Source/core/rendering/RenderTableCol.cpp
index ce0dd03..4831a49 100644
--- a/Source/core/rendering/RenderTableCol.cpp
+++ b/Source/core/rendering/RenderTableCol.cpp
@@ -28,7 +28,6 @@
 
 #include "HTMLNames.h"
 #include "core/html/HTMLTableColElement.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderTable.h"
 #include "core/rendering/RenderTableCell.h"
 
diff --git a/Source/core/rendering/RenderTableRow.cpp b/Source/core/rendering/RenderTableRow.cpp
index 3fae922..dc1d16c 100644
--- a/Source/core/rendering/RenderTableRow.cpp
+++ b/Source/core/rendering/RenderTableRow.cpp
@@ -27,11 +27,12 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTableCell.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/style/StyleInheritedData.h"
 
 namespace WebCore {
@@ -84,7 +85,7 @@
             for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
                 if (!childBox->isTableCell())
                     continue;
-                childBox->setChildNeedsLayout(MarkOnlyThis);
+                childBox->setChildNeedsLayout();
             }
         }
     }
@@ -165,9 +166,10 @@
 
     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
         if (child->isTableCell()) {
+            SubtreeLayoutScope layouter(child);
             RenderTableCell* cell = toRenderTableCell(child);
             if (!cell->needsLayout() && paginated && view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(cell, cell->logicalTop()) != cell->pageLogicalOffset())
-                cell->setChildNeedsLayout(MarkOnlyThis);
+                layouter.setChildNeedsLayout(cell);
 
             if (child->needsLayout()) {
                 cell->computeAndSetBlockDirectionMargins(table());
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index 80938cc..d55550b 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -35,6 +35,7 @@
 #include "core/rendering/RenderTableCol.h"
 #include "core/rendering/RenderTableRow.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/SubtreeLayoutScope.h"
 #include "wtf/HashSet.h"
 #include "wtf/Vector.h"
 
@@ -612,6 +613,7 @@
 
     const Vector<int>& columnPos = table()->columnPositions();
 
+    SubtreeLayoutScope layouter(this);
     for (unsigned r = 0; r < m_grid.size(); ++r) {
         Row& row = m_grid[r].row;
         unsigned cols = row.size();
@@ -631,7 +633,7 @@
                 endCol++;
             }
             int tableLayoutLogicalWidth = columnPos[endCol] - columnPos[startColumn] - table()->hBorderSpacing();
-            cell->setCellLogicalWidth(tableLayoutLogicalWidth);
+            cell->setCellLogicalWidth(tableLayoutLogicalWidth, layouter);
         }
 
         if (RenderTableRow* rowRenderer = m_grid[r].rowRenderer)
@@ -736,6 +738,11 @@
     return extraLogicalHeight - remainingExtraLogicalHeight;
 }
 
+static bool shouldFlexCellChild(RenderObject* cellDescendant)
+{
+    return cellDescendant->isReplaced() || (cellDescendant->isBox() && toRenderBox(cellDescendant)->scrollsOverflow());
+}
+
 void RenderTableSection::layoutRows()
 {
 #ifndef NDEBUG
@@ -795,33 +802,24 @@
             bool flexAllChildren = cell->style()->logicalHeight().isFixed()
                 || (!table()->style()->logicalHeight().isAuto() && rHeight != cell->logicalHeight());
 
-            for (RenderObject* o = cell->firstChild(); o; o = o->nextSibling()) {
-                if (!o->isText() && o->style()->logicalHeight().isPercent() && (flexAllChildren || o->isReplaced() || (o->isBox() && toRenderBox(o)->scrollsOverflow()))) {
-                    // Tables with no sections do not flex.
-                    if (!o->isTable() || toRenderTable(o)->hasSections()) {
-                        o->setNeedsLayout(MarkOnlyThis);
-                        cellChildrenFlex = true;
-                    }
+            for (RenderObject* child = cell->firstChild(); child; child = child->nextSibling()) {
+                if (!child->isText() && child->style()->logicalHeight().isPercent()
+                    && (flexAllChildren || shouldFlexCellChild(child))
+                    && (!child->isTable() || toRenderTable(child)->hasSections())) {
+                    cellChildrenFlex = true;
+                    break;
                 }
             }
 
-            if (TrackedRendererListHashSet* percentHeightDescendants = cell->percentHeightDescendants()) {
-                TrackedRendererListHashSet::iterator end = percentHeightDescendants->end();
-                for (TrackedRendererListHashSet::iterator it = percentHeightDescendants->begin(); it != end; ++it) {
-                    RenderBox* box = *it;
-                    if (!box->isReplaced() && !box->scrollsOverflow() && !flexAllChildren)
-                        continue;
-
-                    while (box != cell) {
-                        if (box->normalChildNeedsLayout())
+            if (!cellChildrenFlex) {
+                if (TrackedRendererListHashSet* percentHeightDescendants = cell->percentHeightDescendants()) {
+                    TrackedRendererListHashSet::iterator end = percentHeightDescendants->end();
+                    for (TrackedRendererListHashSet::iterator it = percentHeightDescendants->begin(); it != end; ++it) {
+                        if (flexAllChildren || shouldFlexCellChild(*it)) {
+                            cellChildrenFlex = true;
                             break;
-                        box->setChildNeedsLayout(MarkOnlyThis);
-                        box = box->containingBlock();
-                        ASSERT(box);
-                        if (!box)
-                            break;
+                        }
                     }
-                    cellChildrenFlex = true;
                 }
             }
 
@@ -840,14 +838,15 @@
                 }
             }
 
-            cell->computeIntrinsicPadding(rHeight);
+            SubtreeLayoutScope layouter(cell);
+            cell->computeIntrinsicPadding(rHeight, layouter);
 
             LayoutRect oldCellRect = cell->frameRect();
 
             setLogicalPositionForCell(cell, c);
 
             if (!cell->needsLayout() && view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(cell, cell->logicalTop()) != cell->pageLogicalOffset())
-                cell->setChildNeedsLayout(MarkOnlyThis);
+                layouter.setChildNeedsLayout(cell);
 
             cell->layoutIfNeeded();
 
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index 56135c0..9572f74 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -215,6 +215,9 @@
     ETextSecurity oldSecurity = oldStyle ? oldStyle->textSecurity() : TSNONE;
     if (needsResetText || oldTransform != newStyle->textTransform() || oldSecurity != newStyle->textSecurity())
         transformText();
+
+    if (!text().containsOnlyWhitespace())
+        newStyle->font().willUseFontData();
 }
 
 void RenderText::removeAndDestroyTextBoxes()
diff --git a/Source/core/rendering/RenderTextControl.cpp b/Source/core/rendering/RenderTextControl.cpp
index aaac50e..a14e099 100644
--- a/Source/core/rendering/RenderTextControl.cpp
+++ b/Source/core/rendering/RenderTextControl.cpp
@@ -273,18 +273,14 @@
         rects.append(pixelSnappedIntRect(additionalOffset, size()));
 }
 
-RenderObject* RenderTextControl::layoutSpecialExcludedChild(bool relayoutChildren)
+RenderObject* RenderTextControl::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
 {
     HTMLElement* placeholder = toHTMLTextFormControlElement(node())->placeholderElement();
     RenderObject* placeholderRenderer = placeholder ? placeholder->renderer() : 0;
     if (!placeholderRenderer)
         return 0;
-    if (relayoutChildren) {
-        // The markParents arguments should be false because this function is
-        // called from layout() of the parent and the placeholder layout doesn't
-        // affect the parent layout.
-        placeholderRenderer->setChildNeedsLayout(MarkOnlyThis);
-    }
+    if (relayoutChildren)
+        layoutScope.setChildNeedsLayout(placeholderRenderer);
     return placeholderRenderer;
 }
 
diff --git a/Source/core/rendering/RenderTextControl.h b/Source/core/rendering/RenderTextControl.h
index e5fd2b7..d446fab 100644
--- a/Source/core/rendering/RenderTextControl.h
+++ b/Source/core/rendering/RenderTextControl.h
@@ -62,7 +62,7 @@
 
     virtual void updateFromElement();
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren);
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
 
 private:
     virtual const char* renderName() const { return "RenderTextControl"; }
@@ -112,7 +112,7 @@
         return RenderBlock::baselinePosition(baseline, firstLine, direction, position);
     }
     virtual int firstLineBoxBaseline() const OVERRIDE { return RenderBlock::firstLineBoxBaseline(); }
-    virtual int inlineBlockBaseline(LineDirectionMode direction) const OVERRIDE { return RenderBlock::inlineBlockBaseline(direction); }
+    virtual int inlineBlockBaseline(LineDirectionMode direction) const OVERRIDE { return lastLineBoxBaseline(direction); }
 
 };
 
diff --git a/Source/core/rendering/RenderTextControlMultiLine.cpp b/Source/core/rendering/RenderTextControlMultiLine.cpp
index 22e9722..6faf2ac 100644
--- a/Source/core/rendering/RenderTextControlMultiLine.cpp
+++ b/Source/core/rendering/RenderTextControlMultiLine.cpp
@@ -92,9 +92,9 @@
     return style();
 }
 
-RenderObject* RenderTextControlMultiLine::layoutSpecialExcludedChild(bool relayoutChildren)
+RenderObject* RenderTextControlMultiLine::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
 {
-    RenderObject* placeholderRenderer = RenderTextControl::layoutSpecialExcludedChild(relayoutChildren);
+    RenderObject* placeholderRenderer = RenderTextControl::layoutSpecialExcludedChild(relayoutChildren, layoutScope);
     if (!placeholderRenderer)
         return 0;
     if (!placeholderRenderer->isBox())
diff --git a/Source/core/rendering/RenderTextControlMultiLine.h b/Source/core/rendering/RenderTextControlMultiLine.h
index 5755f23..6ca0167 100644
--- a/Source/core/rendering/RenderTextControlMultiLine.h
+++ b/Source/core/rendering/RenderTextControlMultiLine.h
@@ -45,7 +45,7 @@
 
     virtual RenderStyle* textBaseStyle() const;
     virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const;
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren);
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
 };
 
 inline RenderTextControlMultiLine* toRenderTextControlMultiLine(RenderObject* object)
diff --git a/Source/core/rendering/RenderTextControlSingleLine.cpp b/Source/core/rendering/RenderTextControlSingleLine.cpp
index 08b9501..d788a82 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -25,7 +25,9 @@
 #include "core/rendering/RenderTextControlSingleLine.h"
 
 #include "CSSValueKeywords.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/page/Frame.h"
 #include "core/platform/PlatformKeyboardEvent.h"
 #include "core/platform/graphics/SimpleFontData.h"
@@ -53,7 +55,7 @@
 
 inline HTMLElement* RenderTextControlSingleLine::innerSpinButtonElement() const
 {
-    return inputElement()->innerSpinButtonElement();
+    return toHTMLElement(inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
 }
 
 RenderStyle* RenderTextControlSingleLine::textBaseStyle() const
@@ -86,18 +88,10 @@
     return containerElement() ? contentLogicalHeight() : logicalHeight();
 }
 
-// 'end' must be an ancestor of 'start.'
-static void setNeedsLayoutInRange(RenderObject* start, RenderObject* end)
-{
-    ASSERT(start);
-    ASSERT(start != end);
-    for (RenderObject* renderer = start; renderer != end; renderer = renderer->parent())
-        renderer->setNeedsLayout(MarkOnlyThis);
-}
-
 void RenderTextControlSingleLine::layout()
 {
     StackStats::LayoutCheckPoint layoutCheckPoint;
+    SubtreeLayoutScope layoutScope(this);
 
     // FIXME: We should remove the height-related hacks in layout() and
     // styleDidChange(). We need them because
@@ -116,11 +110,11 @@
     // To ensure consistency between layouts, we need to reset any conditionally overriden height.
     if (innerTextRenderer && !innerTextRenderer->style()->logicalHeight().isAuto()) {
         innerTextRenderer->style()->setLogicalHeight(Length(Auto));
-        setNeedsLayoutInRange(innerTextRenderer, this);
+        layoutScope.setNeedsLayout(innerTextRenderer);
     }
     if (innerBlockRenderer && !innerBlockRenderer->style()->logicalHeight().isAuto()) {
         innerBlockRenderer->style()->setLogicalHeight(Length(Auto));
-        setNeedsLayoutInRange(innerBlockRenderer, this);
+        layoutScope.setNeedsLayout(innerBlockRenderer);
     }
 
     RenderBlock::layoutBlock(false);
@@ -133,15 +127,15 @@
     LayoutUnit logicalHeightLimit = computeLogicalHeightLimit();
     if (innerTextRenderer && innerTextRenderer->logicalHeight() > logicalHeightLimit) {
         if (desiredLogicalHeight != innerTextRenderer->logicalHeight())
-            setNeedsLayout(MarkOnlyThis);
+            layoutScope.setNeedsLayout(this);
 
         m_desiredInnerTextLogicalHeight = desiredLogicalHeight;
 
         innerTextRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
-        innerTextRenderer->setNeedsLayout(MarkOnlyThis);
+        layoutScope.setNeedsLayout(innerTextRenderer);
         if (innerBlockRenderer) {
             innerBlockRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
-            innerBlockRenderer->setNeedsLayout(MarkOnlyThis);
+            layoutScope.setNeedsLayout(innerBlockRenderer);
         }
     }
     // The container might be taller because of decoration elements.
@@ -150,10 +144,10 @@
         LayoutUnit containerLogicalHeight = containerRenderer->logicalHeight();
         if (containerLogicalHeight > logicalHeightLimit) {
             containerRenderer->style()->setLogicalHeight(Length(logicalHeightLimit, Fixed));
-            setNeedsLayout(MarkOnlyThis);
+            layoutScope.setNeedsLayout(this);
         } else if (containerRenderer->logicalHeight() < contentLogicalHeight()) {
             containerRenderer->style()->setLogicalHeight(Length(contentLogicalHeight(), Fixed));
-            setNeedsLayout(MarkOnlyThis);
+            layoutScope.setNeedsLayout(this);
         } else
             containerRenderer->style()->setLogicalHeight(Length(containerLogicalHeight, Fixed));
     }
@@ -252,7 +246,7 @@
     }
     RenderObject* innerTextRenderer = innerTextElement()->renderer();
     if (innerTextRenderer && diff == StyleDifferenceLayout)
-        innerTextRenderer->setNeedsLayout(MarkContainingBlockChain);
+        innerTextRenderer->setNeedsLayout();
     if (HTMLElement* placeholder = inputElement()->placeholderElement())
         placeholder->setInlineStyleProperty(CSSPropertyTextOverflow, textShouldBeTruncated() ? CSSValueEllipsis : CSSValueClip);
     setHasOverflowClip(false);
@@ -377,24 +371,6 @@
     return textBlockStyle.release();
 }
 
-PassRefPtr<RenderStyle> RenderTextControlSingleLine::createInnerBlockStyle(const RenderStyle* startStyle) const
-{
-    RefPtr<RenderStyle> innerBlockStyle = RenderStyle::create();
-    innerBlockStyle->inheritFrom(startStyle);
-
-    innerBlockStyle->setFlexGrow(1);
-    // min-width: 0; is needed for correct shrinking.
-    // FIXME: Remove this line when https://bugs.webkit.org/show_bug.cgi?id=111790 is fixed.
-    innerBlockStyle->setMinWidth(Length(0, Fixed));
-    innerBlockStyle->setDisplay(BLOCK);
-    innerBlockStyle->setDirection(LTR);
-
-    // We don't want the shadow dom to be editable, so we set this block to read-only in case the input itself is editable.
-    innerBlockStyle->setUserModify(READ_ONLY);
-
-    return innerBlockStyle.release();
-}
-
 bool RenderTextControlSingleLine::textShouldBeTruncated() const
 {
     return document()->focusedElement() != node() && style()->textOverflow() == TextOverflowEllipsis;
@@ -450,25 +426,6 @@
         innerTextElement()->setScrollTop(newTop);
 }
 
-bool RenderTextControlSingleLine::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
-{
-    RenderBox* renderer = innerTextElement()->renderBox();
-    if (!renderer)
-        return false;
-    RenderLayer* layer = renderer->layer();
-    if (layer && layer->scroll(direction, granularity, multiplier))
-        return true;
-    return RenderBlock::scroll(direction, granularity, multiplier, stopNode);
-}
-
-bool RenderTextControlSingleLine::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
-{
-    RenderLayer* layer = innerTextElement()->renderBox()->layer();
-    if (layer && layer->scroll(logicalToPhysical(direction, style()->isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), granularity, multiplier))
-        return true;
-    return RenderBlock::logicalScroll(direction, granularity, multiplier, stopNode);
-}
-
 HTMLInputElement* RenderTextControlSingleLine::inputElement() const
 {
     return toHTMLInputElement(node());
diff --git a/Source/core/rendering/RenderTextControlSingleLine.h b/Source/core/rendering/RenderTextControlSingleLine.h
index 91970d6..7f36979 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.h
+++ b/Source/core/rendering/RenderTextControlSingleLine.h
@@ -34,9 +34,8 @@
 public:
     RenderTextControlSingleLine(HTMLInputElement*);
     virtual ~RenderTextControlSingleLine();
-    // FIXME: Move create*Style() to their classes.
+    // FIXME: Move createInnerTextStyle() to TextControlInnerTextElement.
     virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const;
-    PassRefPtr<RenderStyle> createInnerBlockStyle(const RenderStyle* startStyle) const;
 
     void capsLockStateMayHaveChanged();
 
@@ -67,8 +66,6 @@
     virtual int scrollHeight() const;
     virtual void setScrollLeft(int);
     virtual void setScrollTop(int);
-    virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1, Node** stopNode = 0);
-    virtual bool logicalScroll(ScrollLogicalDirection, ScrollGranularity, float multiplier = 1, Node** stopNode = 0);
 
     int textBlockWidth() const;
     virtual float getAvgCharWidth(AtomicString family);
@@ -111,9 +108,16 @@
 class RenderTextControlInnerBlock : public RenderBlock {
 public:
     RenderTextControlInnerBlock(Element* element) : RenderBlock(element) { }
+    virtual int inlineBlockBaseline(LineDirectionMode direction) const OVERRIDE { return lastLineBoxBaseline(direction); }
 
 private:
-    virtual bool hasLineIfEmpty() const { return true; }
+    virtual bool isIntristicallyScrollable(ScrollbarOrientation orientation) const OVERRIDE
+    {
+        return orientation == HorizontalScrollbar;
+    }
+    virtual bool scrollsOverflowX() const OVERRIDE { return hasOverflowClip(); }
+    virtual bool scrollsOverflowY() const OVERRIDE { return false; }
+    virtual bool hasLineIfEmpty() const OVERRIDE { return true; }
 };
 
 }
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index 0e4903c..c73b983 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -37,6 +37,7 @@
 #include "core/html/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/MediaControlElements.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/SpinButtonElement.h"
 #include "core/html/shadow/TextControlInnerElements.h"
 #include "core/page/FocusController.h"
@@ -1001,7 +1002,7 @@
     bool isHorizontal = part ==  SliderHorizontalPart;
 
     IntSize thumbSize;
-    RenderObject* thumbRenderer = input->sliderThumbElement()->renderer();
+    RenderObject* thumbRenderer = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb())->renderer();
     if (thumbRenderer) {
         RenderStyle* thumbStyle = thumbRenderer->style();
         int thumbWidth = thumbStyle->width().intValue();
@@ -1016,7 +1017,7 @@
     int tickRegionSideMargin = 0;
     int tickRegionWidth = 0;
     IntRect trackBounds;
-    RenderObject* trackRenderer = input->sliderTrackElement()->renderer();
+    RenderObject* trackRenderer = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack())->renderer();
     // We can ignoring transforms because transform is handled by the graphics context.
     if (trackRenderer)
         trackBounds = trackRenderer->absoluteBoundingBoxRectIgnoringTransforms();
diff --git a/Source/core/rendering/RenderTreeAsText.cpp b/Source/core/rendering/RenderTreeAsText.cpp
index fc0982c..e22b2c9 100644
--- a/Source/core/rendering/RenderTreeAsText.cpp
+++ b/Source/core/rendering/RenderTreeAsText.cpp
@@ -786,6 +786,9 @@
 
 String externalRepresentation(Frame* frame, RenderAsTextBehavior behavior)
 {
+    if (!(behavior & RenderAsTextDontUpdateLayout))
+        frame->document()->updateLayout();
+
     RenderObject* renderer = frame->contentRenderer();
     if (!renderer || !renderer->isBox())
         return String();
@@ -793,22 +796,21 @@
     PrintContext printContext(frame);
     if (behavior & RenderAsTextPrintingMode)
         printContext.begin(toRenderBox(renderer)->width());
-    if (!(behavior & RenderAsTextDontUpdateLayout))
-        frame->document()->updateLayout();
 
     return externalRepresentation(toRenderBox(renderer), behavior);
 }
 
 String externalRepresentation(Element* element, RenderAsTextBehavior behavior)
 {
-    RenderObject* renderer = element->renderer();
-    if (!renderer || !renderer->isBox())
-        return String();
     // Doesn't support printing mode.
     ASSERT(!(behavior & RenderAsTextPrintingMode));
     if (!(behavior & RenderAsTextDontUpdateLayout) && element->document())
         element->document()->updateLayout();
 
+    RenderObject* renderer = element->renderer();
+    if (!renderer || !renderer->isBox())
+        return String();
+
     return externalRepresentation(toRenderBox(renderer), behavior | RenderAsTextShowAllLayers);
 }
 
diff --git a/Source/core/rendering/RenderVideo.cpp b/Source/core/rendering/RenderVideo.cpp
index 62e8ac2..a854d9f 100644
--- a/Source/core/rendering/RenderVideo.cpp
+++ b/Source/core/rendering/RenderVideo.cpp
@@ -140,35 +140,11 @@
 
 IntRect RenderVideo::videoBox() const
 {
-    if (m_cachedImageSize.isEmpty() && videoElement()->shouldDisplayPosterImage())
-        return IntRect();
-
-    LayoutSize elementSize;
+    const LayoutSize* overriddenIntrinsicSize = 0;
     if (videoElement()->shouldDisplayPosterImage())
-        elementSize = m_cachedImageSize;
-    else
-        elementSize = intrinsicSize();
+        overriddenIntrinsicSize = &m_cachedImageSize;
 
-    IntRect contentRect = pixelSnappedIntRect(contentBoxRect());
-    if (elementSize.isEmpty() || contentRect.isEmpty())
-        return IntRect();
-
-    LayoutRect renderBox = contentRect;
-    LayoutUnit ratio = renderBox.width() * elementSize.height() - renderBox.height() * elementSize.width();
-    if (ratio > 0) {
-        LayoutUnit newWidth = renderBox.height() * elementSize.width() / elementSize.height();
-        // Just fill the whole area if the difference is one pixel or less (in both sides)
-        if (renderBox.width() - newWidth > 2)
-            renderBox.setWidth(newWidth);
-        renderBox.move((contentRect.width() - renderBox.width()) / 2, 0);
-    } else if (ratio < 0) {
-        LayoutUnit newHeight = renderBox.width() * elementSize.height() / elementSize.width();
-        if (renderBox.height() - newHeight > 2)
-            renderBox.setHeight(newHeight);
-        renderBox.move(0, (contentRect.height() - renderBox.height()) / 2);
-    }
-
-    return pixelSnappedIntRect(renderBox);
+    return pixelSnappedIntRect(replacedContentRect(overriddenIntrinsicSize));
 }
 
 bool RenderVideo::shouldDisplayVideo() const
@@ -202,12 +178,24 @@
     if (page && paintInfo.phase == PaintPhaseForeground)
         page->addRelevantRepaintedObject(this, rect);
 
+    LayoutRect contentRect = contentBoxRect();
+    contentRect.moveBy(paintOffset);
+    GraphicsContext* context = paintInfo.context;
+    bool clip = !contentRect.contains(rect);
+    if (clip) {
+        context->save();
+        context->clip(contentRect);
+    }
+
     if (displayingPoster)
-        paintIntoRect(paintInfo.context, rect);
+        paintIntoRect(context, rect);
     else if (document()->view() && document()->view()->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
-        mediaPlayer->paintCurrentFrameInContext(paintInfo.context, pixelSnappedIntRect(rect));
+        mediaPlayer->paintCurrentFrameInContext(context, pixelSnappedIntRect(rect));
     else
-        mediaPlayer->paint(paintInfo.context, pixelSnappedIntRect(rect));
+        mediaPlayer->paint(context, pixelSnappedIntRect(rect));
+
+    if (clip)
+        context->restore();
 }
 
 void RenderVideo::layout()
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index b71d4fe..5defa30 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -39,7 +39,6 @@
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderLazyBlock.h"
 #include "core/rendering/RenderSelectionInfo.h"
 #include "core/rendering/RenderWidget.h"
 
@@ -57,7 +56,6 @@
     , m_pageLogicalHeightChanged(false)
     , m_layoutState(0)
     , m_layoutStateDisableCount(0)
-    , m_firstLazyBlock(0)
     , m_renderQuoteHead(0)
     , m_renderCounterCount(0)
 {
@@ -116,12 +114,6 @@
     return child->isBox();
 }
 
-void RenderView::markLazyBlocksForLayout()
-{
-    for (RenderLazyBlock* block = m_firstLazyBlock; block; block = block->next())
-        block->setNeedsLayout();
-}
-
 void RenderView::layoutContent(const LayoutState& state)
 {
     UNUSED_PARAM(state);
@@ -257,10 +249,12 @@
     if (shouldUsePrintingLayout())
         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = logicalWidth();
 
+    SubtreeLayoutScope layoutScope(this);
+
     // Use calcWidth/Height to get the new width/height, since this will take the full page zoom factor into account.
     bool relayoutChildren = !shouldUsePrintingLayout() && (!m_frameView || width() != viewWidth() || height() != viewHeight());
     if (relayoutChildren) {
-        setChildNeedsLayout(MarkOnlyThis);
+        layoutScope.setChildNeedsLayout(this);
         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
             if ((child->isBox() && toRenderBox(child)->hasRelativeLogicalHeight())
                     || child->style()->logicalHeight().isPercent()
@@ -270,7 +264,7 @@
                     || child->style()->logicalMinHeight().isViewportPercentage()
                     || child->style()->logicalMaxHeight().isViewportPercentage()
                     || child->isSVGRoot())
-                child->setChildNeedsLayout(MarkOnlyThis);
+                layoutScope.setChildNeedsLayout(child);
         }
     }
 
@@ -332,23 +326,34 @@
 
 const RenderObject* RenderView::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
 {
-    // If a container was specified, and was not 0 or the RenderView,
-    // then we should have found it by now.
-    ASSERT_ARG(ancestorToStopAt, !ancestorToStopAt || ancestorToStopAt == this);
-
-    LayoutSize scrollOffset;
+    LayoutSize offsetForFixedPosition;
+    LayoutSize offset;
+    RenderObject* container = 0;
 
     if (m_frameView)
-        scrollOffset = m_frameView->scrollOffsetForFixedPosition();
+        offsetForFixedPosition = m_frameView->scrollOffsetForFixedPosition();
 
-    if (!ancestorToStopAt && shouldUseTransformFromContainer(0)) {
+    if (geometryMap.mapCoordinatesFlags() & TraverseDocumentBoundaries) {
+        if (RenderPart* parentDocRenderer = frame()->ownerRenderer()) {
+            offset = -m_frameView->scrollOffset();
+            offset += toLayoutSize(parentDocRenderer->contentBoxRect().location());
+            container = parentDocRenderer;
+        }
+    }
+
+    // If a container was specified, and was not 0 or the RenderView, then we
+    // should have found it by now unless we're traversing to a parent document.
+    ASSERT_ARG(ancestorToStopAt, !ancestorToStopAt || ancestorToStopAt == this || container);
+
+    if ((!ancestorToStopAt || container) && shouldUseTransformFromContainer(container)) {
         TransformationMatrix t;
-        getTransformFromContainer(0, LayoutSize(), t);
-        geometryMap.pushView(this, scrollOffset, &t);
-    } else
-        geometryMap.pushView(this, scrollOffset);
+        getTransformFromContainer(container, LayoutSize(), t);
+        geometryMap.push(this, t, false, false, false, true, offsetForFixedPosition);
+    } else {
+        geometryMap.push(this, offset, false, false, false, false, offsetForFixedPosition);
+    }
 
-    return 0;
+    return container;
 }
 
 void RenderView::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
@@ -1098,7 +1103,7 @@
     return m_flowThreadController.get();
 }
 
-RenderBlock::IntervalArena* RenderView::intervalArena()
+IntervalArena* RenderView::intervalArena()
 {
     if (!m_intervalArena)
         m_intervalArena = IntervalArena::create();
diff --git a/Source/core/rendering/RenderView.h b/Source/core/rendering/RenderView.h
index 80061e0..21ba4f4 100644
--- a/Source/core/rendering/RenderView.h
+++ b/Source/core/rendering/RenderView.h
@@ -33,7 +33,6 @@
 class CustomFilterGlobalContext;
 class FlowThreadController;
 class RenderLayerCompositor;
-class RenderLazyBlock;
 class RenderQuote;
 class RenderWidget;
 
@@ -185,10 +184,6 @@
     void setRenderQuoteHead(RenderQuote* head) { m_renderQuoteHead = head; }
     RenderQuote* renderQuoteHead() const { return m_renderQuoteHead; }
 
-    void setFirstLazyBlock(RenderLazyBlock* block) { m_firstLazyBlock = block; }
-    RenderLazyBlock* firstLazyBlock() const { return m_firstLazyBlock; }
-    void markLazyBlocksForLayout();
-
     // FIXME: This is a work around because the current implementation of counters
     // requires walking the entire tree repeatedly and most pages don't actually use either
     // feature so we shouldn't take the performance hit when not needed. Long term we should
@@ -283,7 +278,6 @@
     OwnPtr<FlowThreadController> m_flowThreadController;
     RefPtr<IntervalArena> m_intervalArena;
 
-    RenderLazyBlock* m_firstLazyBlock;
     RenderQuote* m_renderQuoteHead;
     unsigned m_renderCounterCount;
 };
diff --git a/Source/core/rendering/SubtreeLayoutScope.cpp b/Source/core/rendering/SubtreeLayoutScope.cpp
new file mode 100644
index 0000000..c3bfefe
--- /dev/null
+++ b/Source/core/rendering/SubtreeLayoutScope.cpp
@@ -0,0 +1,79 @@
+/*
+ * 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/SubtreeLayoutScope.h"
+
+#include "core/page/FrameView.h"
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+SubtreeLayoutScope::SubtreeLayoutScope(RenderObject* root)
+    : m_root(root)
+{
+    RELEASE_ASSERT(m_root->document()->view()->isInLayout());
+}
+
+SubtreeLayoutScope::~SubtreeLayoutScope()
+{
+    RELEASE_ASSERT(!m_root->needsLayout());
+
+#ifndef NDEBUG
+    for (HashSet<RenderObject*>::iterator it = m_renderersToLayout.begin(); it != m_renderersToLayout.end(); ++it) {
+        RenderObject* renderer = *it;
+        // FIXME: Thie patter is really common. Move it into an assertRendererLaidOut function.
+        if (renderer->needsLayout())
+            showRenderTree(renderer);
+        ASSERT(!renderer->needsLayout());
+    }
+#endif
+}
+
+void SubtreeLayoutScope::setNeedsLayout(RenderObject* descendant)
+{
+    ASSERT(descendant->isDescendantOf(m_root));
+    descendant->setNeedsLayout(MarkContainingBlockChain, this);
+}
+
+void SubtreeLayoutScope::setChildNeedsLayout(RenderObject* descendant)
+{
+    ASSERT(descendant->isDescendantOf(m_root));
+    descendant->setChildNeedsLayout(MarkContainingBlockChain, this);
+}
+
+void SubtreeLayoutScope::addRendererToLayout(RenderObject* renderer)
+{
+#ifndef NDEBUG
+    m_renderersToLayout.add(renderer);
+#endif
+}
+
+}
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/rendering/SubtreeLayoutScope.h
similarity index 61%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/rendering/SubtreeLayoutScope.h
index 133dab0..c073b7f 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/rendering/SubtreeLayoutScope.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,26 +28,43 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#ifndef SubtreeLayoutScope_h
+#define SubtreeLayoutScope_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "wtf/HashSet.h"
+
+// This is the way to mark a subtree as needing layout during layout,
+// e.g. for the purposes of doing a multipass layout.
+//
+// It should only be used during layout. Outside of layout, you should
+// just call renderer->setNeedsLayout() directly.
+//
+// It ensures that you don't accidentally mark part of the tree as
+// needing layout and not actually lay it out.
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
-public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
+class RenderObject;
 
-protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+class SubtreeLayoutScope {
+public:
+    SubtreeLayoutScope(RenderObject* root);
+    ~SubtreeLayoutScope();
+
+    void setNeedsLayout(RenderObject* descendant);
+    void setChildNeedsLayout(RenderObject* descendant);
+
+    RenderObject* root() { return m_root; }
+    void addRendererToLayout(RenderObject* renderer);
+
+private:
+    RenderObject* m_root;
+
+#ifndef NDEBUG
+    HashSet<RenderObject*> m_renderersToLayout;
+#endif
 };
 
-} // namespace WebCore
+}
 
 #endif
diff --git a/Source/core/rendering/shapes/RasterShape.cpp b/Source/core/rendering/shapes/RasterShape.cpp
new file mode 100644
index 0000000..a1d0963
--- /dev/null
+++ b/Source/core/rendering/shapes/RasterShape.cpp
@@ -0,0 +1,211 @@
+/*
+ * 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 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/rendering/shapes/RasterShape.h"
+
+#include "core/rendering/shapes/ShapeInterval.h"
+#include "wtf/MathExtras.h"
+
+namespace WebCore {
+
+IntRect RasterShapeIntervals::bounds() const
+{
+    if (!m_bounds)
+        m_bounds = adoptPtr(new IntRect(m_region.bounds()));
+    return *m_bounds;
+}
+
+void RasterShapeIntervals::addInterval(int y, int x1, int x2)
+{
+    m_region.unite(Region(IntRect(x1, y, x2 - x1, 1)));
+    m_bounds.clear();
+}
+
+bool RasterShapeIntervals::firstIncludedIntervalY(int minY, const IntSize& minSize, LayoutUnit& result) const
+{
+    for (int y = minY; y <= bounds().height() - minSize.height(); y++) {
+        Region lineRegion(IntRect(bounds().x(), y, bounds().width(), minSize.height()));
+        lineRegion.intersect(m_region);
+        if (lineRegion.isEmpty())
+            continue;
+
+        const Vector<IntRect>& lineRects = lineRegion.rects();
+        ASSERT(lineRects.size() > 0);
+
+        for (unsigned i = 0; i < lineRects.size(); i++) {
+            IntRect rect = lineRects[i];
+            if (rect.width() >= minSize.width() && lineRegion.contains(Region(IntRect(IntPoint(rect.x(), y), minSize)))) {
+                result = y;
+                return true;
+            }
+        }
+    }
+    return false;
+}
+
+static inline IntRect alignedRect(IntRect r, int y1, int y2)
+{
+    return IntRect(r.x(), y1, r.width(), y2 - y1);
+}
+
+void RasterShapeIntervals::getIncludedIntervals(int y1, int y2, SegmentList& result) const
+{
+    ASSERT(y2 >= y1);
+
+    IntRect lineRect(bounds().x(), y1, bounds().width(), y2 - y1);
+    Region lineRegion(lineRect);
+    lineRegion.intersect(m_region);
+    if (lineRegion.isEmpty())
+        return;
+
+    const Vector<IntRect>& lineRects = lineRegion.rects();
+    ASSERT(lineRects.size() > 0);
+
+    Region segmentsRegion(lineRect);
+    Region intervalsRegion;
+
+    // The loop below uses Regions to compute the intersection of the horizontal
+    // shape intervals that fall within the line's box.
+    int currentLineY = lineRects[0].y();
+    int currentLineMaxY = lineRects[0].maxY();
+    for (unsigned i = 0; i < lineRects.size(); ++i) {
+        int lineY = lineRects[i].y();
+        ASSERT(lineY >= currentLineY);
+        if (lineY > currentLineMaxY) // We've encountered a vertical gap in lineRects, there are no included intervals.
+            return;
+        if (lineY > currentLineY) {
+            currentLineY = lineY;
+            currentLineMaxY = lineRects[i].maxY();
+            segmentsRegion.intersect(intervalsRegion);
+            intervalsRegion = Region();
+        } else {
+            currentLineMaxY = std::max<int>(currentLineMaxY, lineRects[i].maxY());
+        }
+        intervalsRegion.unite(Region(alignedRect(lineRects[i], y1, y2)));
+    }
+    if (!intervalsRegion.isEmpty())
+        segmentsRegion.intersect(intervalsRegion);
+
+    const Vector<IntRect>& segmentRects = segmentsRegion.rects();
+    for (unsigned i = 0; i < segmentRects.size(); ++i)
+        result.append(LineSegment(segmentRects[i].x(), segmentRects[i].maxX()));
+}
+
+void RasterShapeIntervals::getExcludedIntervals(int y1, int y2, SegmentList& result) const
+{
+    ASSERT(y2 >= y1);
+
+    IntRect lineRect(bounds().x(), y1, bounds().width(), y2 - y1);
+    Region lineRegion(lineRect);
+    lineRegion.intersect(m_region);
+    if (lineRegion.isEmpty())
+        return;
+
+    const Vector<IntRect>& lineRects = lineRegion.rects();
+    ASSERT(lineRects.size() > 0);
+
+    Region segmentsRegion;
+    for (unsigned i = 0; i < lineRects.size(); i++)
+        segmentsRegion.unite(Region(alignedRect(lineRects[i], y1, y2)));
+
+    const Vector<IntRect>& segmentRects = segmentsRegion.rects();
+    for (unsigned i = 0; i < segmentRects.size(); i++)
+        result.append(LineSegment(segmentRects[i].x(), segmentRects[i].maxX() + 1));
+}
+
+const RasterShapeIntervals& RasterShape::marginIntervals() const
+{
+    ASSERT(shapeMargin() >= 0);
+    if (!shapeMargin())
+        return *m_intervals;
+
+    // FIXME: add support for non-zero margin, see https://code.google.com/p/chromium/issues/detail?id=252737.
+    return *m_intervals;
+}
+
+const RasterShapeIntervals& RasterShape::paddingIntervals() const
+{
+    ASSERT(shapePadding() >= 0);
+    if (!shapePadding())
+        return *m_intervals;
+
+    // FIXME: add support for non-zero padding, see https://code.google.com/p/chromium/issues/detail?id=252737.
+    return *m_intervals;
+}
+
+void RasterShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+{
+    const RasterShapeIntervals& intervals = marginIntervals();
+    if (intervals.isEmpty())
+        return;
+
+    float y1 = logicalTop;
+    float y2 = logicalTop + logicalHeight;
+
+    if (y2 < intervals.bounds().y() || y1 >= intervals.bounds().maxY())
+        return;
+
+    intervals.getExcludedIntervals(y1, y2, result);
+}
+
+void RasterShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+{
+    const RasterShapeIntervals& intervals = paddingIntervals();
+    if (intervals.isEmpty())
+        return;
+
+    float y1 = logicalTop;
+    float y2 = logicalTop + logicalHeight;
+
+    if (y1 < intervals.bounds().y() || y2 > intervals.bounds().maxY())
+        return;
+
+    intervals.getIncludedIntervals(y1, y2, result);
+}
+
+bool RasterShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
+{
+    float minIntervalTop = minLogicalIntervalTop;
+    float minIntervalHeight = minLogicalIntervalSize.height();
+    float minIntervalWidth = minLogicalIntervalSize.width();
+
+    const RasterShapeIntervals& intervals = paddingIntervals();
+    if (intervals.isEmpty() || minIntervalWidth > intervals.bounds().width())
+        return false;
+
+    float minY = std::max<float>(intervals.bounds().y(), minIntervalTop);
+    float maxY = minY + minIntervalHeight;
+    if (maxY > intervals.bounds().maxY())
+        return false;
+
+    return intervals.firstIncludedIntervalY(minY, flooredIntSize(minLogicalIntervalSize), result);
+}
+
+} // namespace WebCore
diff --git a/Source/core/rendering/shapes/RasterShape.h b/Source/core/rendering/shapes/RasterShape.h
new file mode 100644
index 0000000..1ad6666
--- /dev/null
+++ b/Source/core/rendering/shapes/RasterShape.h
@@ -0,0 +1,82 @@
+/*
+ * 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 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 RasterShape_h
+#define RasterShape_h
+
+#include "core/platform/graphics/FloatRect.h"
+#include "core/platform/graphics/Region.h"
+#include "core/rendering/shapes/Shape.h"
+#include "wtf/Assertions.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class RasterShapeIntervals {
+public:
+    RasterShapeIntervals() { }
+
+    IntRect bounds() const;
+    bool isEmpty() const  { return m_region.isEmpty(); }
+    void addInterval(int y, int x1, int x2);
+    void getIncludedIntervals(int y1, int y2, SegmentList&) const;
+    void getExcludedIntervals(int y1, int y2, SegmentList&) const;
+    bool firstIncludedIntervalY(int minY, const IntSize& minIntervalSize, LayoutUnit&) const;
+
+private:
+    Region m_region;
+    mutable OwnPtr<IntRect> m_bounds; // Cached value of m_region.bounds().
+};
+
+class RasterShape : public Shape {
+    WTF_MAKE_NONCOPYABLE(RasterShape);
+public:
+    RasterShape(PassOwnPtr<RasterShapeIntervals> intervals)
+        : Shape()
+        , m_intervals(intervals)
+    {
+    }
+
+    virtual LayoutRect shapeMarginLogicalBoundingBox() const OVERRIDE { return static_cast<LayoutRect>(marginIntervals().bounds()); }
+    virtual LayoutRect shapePaddingLogicalBoundingBox() const OVERRIDE { return static_cast<LayoutRect>(paddingIntervals().bounds()); }
+    virtual bool isEmpty() const OVERRIDE { return m_intervals->isEmpty(); }
+    virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
+    virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
+    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
+
+private:
+    const RasterShapeIntervals& marginIntervals() const;
+    const RasterShapeIntervals& paddingIntervals() const;
+
+    OwnPtr<RasterShapeIntervals> m_intervals;
+};
+
+} // namespace WebCore
+
+#endif // RasterShape_h
diff --git a/Source/core/rendering/shapes/Shape.cpp b/Source/core/rendering/shapes/Shape.cpp
index 60d003b..b325c07 100644
--- a/Source/core/rendering/shapes/Shape.cpp
+++ b/Source/core/rendering/shapes/Shape.cpp
@@ -31,9 +31,12 @@
 #include "core/rendering/shapes/Shape.h"
 
 #include "core/css/LengthFunctions.h"
+#include "core/fetch/ImageResource.h"
 #include "core/platform/graphics/FloatSize.h"
+#include "core/platform/graphics/ImageBuffer.h"
 #include "core/platform/graphics/WindRule.h"
 #include "core/rendering/shapes/PolygonShape.h"
+#include "core/rendering/shapes/RasterShape.h"
 #include "core/rendering/shapes/RectangleShape.h"
 #include "wtf/MathExtras.h"
 #include "wtf/OwnPtr.h"
@@ -198,4 +201,45 @@
     return shape.release();
 }
 
+PassOwnPtr<Shape> Shape::createShape(const StyleImage* styleImage, float threshold, const LayoutSize&, WritingMode writingMode, Length margin, Length padding)
+{
+    ASSERT(styleImage && styleImage->isImageResource() && styleImage->cachedImage() && styleImage->cachedImage()->image());
+
+    OwnPtr<RasterShapeIntervals> intervals = adoptPtr(new RasterShapeIntervals());
+
+    Image* image = styleImage->cachedImage()->image();
+    const IntSize& imageSize = image->size();
+    OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(imageSize);
+    if (imageBuffer) {
+        GraphicsContext* graphicsContext = imageBuffer->context();
+        graphicsContext->drawImage(image, IntPoint());
+
+        RefPtr<Uint8ClampedArray> pixelArray = imageBuffer->getUnmultipliedImageData(IntRect(IntPoint(), imageSize));
+        unsigned pixelArrayLength = pixelArray->length();
+        unsigned pixelArrayOffset = 3; // Each pixel is four bytes: RGBA.
+        uint8_t alphaPixelThreshold = threshold * 255;
+
+        ASSERT(static_cast<unsigned>(imageSize.width() * imageSize.height() * 4) == pixelArrayLength);
+
+        for (int y = 0; y < imageSize.height(); ++y) {
+            int startX = -1;
+            for (int x = 0; x < imageSize.width() && pixelArrayOffset < pixelArrayLength; ++x, pixelArrayOffset += 4) {
+                uint8_t alpha = pixelArray->item(pixelArrayOffset);
+                if ((startX == -1) && alpha > alphaPixelThreshold) {
+                    startX = x;
+                } else if (startX != -1 && (alpha <= alphaPixelThreshold || x == imageSize.width() - 1)) {
+                    intervals->addInterval(y, startX, x);
+                    startX = -1;
+                }
+            }
+        }
+    }
+
+    OwnPtr<RasterShape> rasterShape = adoptPtr(new RasterShape(intervals.release()));
+    rasterShape->m_writingMode = writingMode;
+    rasterShape->m_margin = floatValueForLength(margin, 0);
+    rasterShape->m_padding = floatValueForLength(padding, 0);
+    return rasterShape.release();
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/shapes/Shape.h b/Source/core/rendering/shapes/Shape.h
index 6e257c9..b1ea954 100644
--- a/Source/core/rendering/shapes/Shape.h
+++ b/Source/core/rendering/shapes/Shape.h
@@ -33,6 +33,7 @@
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/text/WritingMode.h"
 #include "core/rendering/style/BasicShapes.h"
+#include "core/rendering/style/StyleImage.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
 
@@ -60,6 +61,7 @@
 class Shape {
 public:
     static PassOwnPtr<Shape> createShape(const BasicShape*, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
+    static PassOwnPtr<Shape> createShape(const StyleImage*, float threshold, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
 
     virtual ~Shape() { }
 
diff --git a/Source/core/rendering/shapes/ShapeInfo.cpp b/Source/core/rendering/shapes/ShapeInfo.cpp
index 78341a3..54f97ab 100644
--- a/Source/core/rendering/shapes/ShapeInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInfo.cpp
@@ -41,12 +41,26 @@
     if (Shape* shape = m_shape.get())
         return shape;
 
-    ShapeValue* shapeValue = (m_renderer->style()->*shapeGetter)();
-    BasicShape* shape = (shapeValue && shapeValue->type() == ShapeValue::Shape) ? shapeValue->shape() : 0;
+    const LayoutSize logicalBoxSize(m_shapeLogicalWidth, m_shapeLogicalHeight);
+    WritingMode writingMode = m_renderer->style()->writingMode();
+    Length margin = m_renderer->style()->shapeMargin();
+    Length padding = m_renderer->style()->shapePadding();
+    const ShapeValue* shapeValue = (m_renderer->style()->*shapeGetter)();
+    ASSERT(shapeValue);
 
-    ASSERT(shape);
+    switch (shapeValue->type()) {
+    case ShapeValue::Shape:
+        ASSERT(shapeValue->shape());
+        m_shape = Shape::createShape(shapeValue->shape(), logicalBoxSize, writingMode, margin, padding);
+        break;
+    case ShapeValue::Image:
+        ASSERT(shapeValue->image());
+        m_shape = Shape::createShape(shapeValue->image(), 0, logicalBoxSize, writingMode, margin, padding);
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+    }
 
-    m_shape = Shape::createShape(shape, LayoutSize(m_shapeLogicalWidth, m_shapeLogicalHeight), m_renderer->style()->writingMode(), m_renderer->style()->shapeMargin(), m_renderer->style()->shapePadding());
     ASSERT(m_shape);
     return m_shape.get();
 }
diff --git a/Source/core/rendering/shapes/ShapeInsideInfo.cpp b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
index 01dff49..8c63f6c 100644
--- a/Source/core/rendering/shapes/ShapeInsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
@@ -44,11 +44,19 @@
 bool ShapeInsideInfo::isEnabledFor(const RenderBlock* renderer)
 {
     ShapeValue* shapeValue = renderer->style()->resolvedShapeInside();
-    if (!shapeValue || shapeValue->type() != ShapeValue::Shape)
+    if (!shapeValue)
         return false;
 
-    BasicShape* shape = shapeValue->shape();
-    return shape && shape->type() != BasicShape::BasicShapeInsetRectangleType;
+    switch (shapeValue->type()) {
+    case ShapeValue::Shape:
+        return shapeValue->shape() && shapeValue->shape()->type() != BasicShape::BasicShapeInsetRectangleType;
+    case ShapeValue::Image:
+        return shapeValue->isImageValid();
+    case ShapeValue::Outside:
+        return false;
+    }
+
+    return false;
 }
 
 bool ShapeInsideInfo::adjustLogicalLineTop(float minSegmentWidth)
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
index 76f52dd..5888fe8 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
@@ -35,8 +35,20 @@
 namespace WebCore {
 bool ShapeOutsideInfo::isEnabledFor(const RenderBox* box)
 {
-    ShapeValue* value = box->style()->shapeOutside();
-    return box->isFloatingWithShapeOutside() && value->type() == ShapeValue::Shape && value->shape();
+    ShapeValue* shapeValue = box->style()->shapeOutside();
+    if (!box->isFloatingWithShapeOutside() || !shapeValue)
+        return false;
+
+    switch (shapeValue->type()) {
+    case ShapeValue::Shape:
+        return shapeValue->shape();
+    case ShapeValue::Image:
+        return shapeValue->isImageValid();
+    case ShapeValue::Outside:
+        return false;
+    }
+
+    return false;
 }
 
 bool ShapeOutsideInfo::computeSegmentsForContainingBlockLine(LayoutUnit lineTop, LayoutUnit floatTop, LayoutUnit lineHeight)
diff --git a/Source/core/rendering/style/GridLength.h b/Source/core/rendering/style/GridLength.h
index 6ba26b9..277b355 100644
--- a/Source/core/rendering/style/GridLength.h
+++ b/Source/core/rendering/style/GridLength.h
@@ -69,9 +69,11 @@
 
     bool operator==(const GridLength& o) const
     {
-        return m_length == o.m_length;
+        return m_length == o.m_length && m_flex == o.m_flex && m_type == o.m_type;
     }
 
+    bool isContentSized() const { return m_type == LengthType && (m_length.isAuto() || m_length.isMinContent() || m_length.isMaxContent()); }
+
 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.
diff --git a/Source/core/rendering/style/GridTrackSize.h b/Source/core/rendering/style/GridTrackSize.h
index 55f0ca3..a75820e 100644
--- a/Source/core/rendering/style/GridTrackSize.h
+++ b/Source/core/rendering/style/GridTrackSize.h
@@ -94,6 +94,8 @@
 
     GridTrackSizeType type() const { return m_type; }
 
+    bool isContentSized() const { return m_minTrackBreadth.isContentSized() || m_maxTrackBreadth.isContentSized(); }
+
     bool operator==(const GridTrackSize& other) const
     {
         return m_type == other.m_type && m_minTrackBreadth == other.m_minTrackBreadth && m_maxTrackBreadth == other.m_maxTrackBreadth;
diff --git a/Source/core/rendering/style/KeyframeList.cpp b/Source/core/rendering/style/KeyframeList.cpp
index 9d20a1c..093d796 100644
--- a/Source/core/rendering/style/KeyframeList.cpp
+++ b/Source/core/rendering/style/KeyframeList.cpp
@@ -36,7 +36,7 @@
         CSSPropertyID property = propertySet->propertyAt(i).id();
         // Timing-function within keyframes is special, because it is not animated; it just
         // describes the timing function between this keyframe and the next.
-        if (property != CSSPropertyWebkitAnimationTimingFunction)
+        if (property != CSSPropertyWebkitAnimationTimingFunction && property != CSSPropertyAnimationTimingFunction)
             addProperty(property);
     }
 }
diff --git a/Source/core/rendering/style/KeyframeList.h b/Source/core/rendering/style/KeyframeList.h
index 5a5cf92..4d5e207 100644
--- a/Source/core/rendering/style/KeyframeList.h
+++ b/Source/core/rendering/style/KeyframeList.h
@@ -40,7 +40,7 @@
 
 class KeyframeValue {
 public:
-    KeyframeValue(float key, PassRefPtr<RenderStyle> style)
+    KeyframeValue(double key, PassRefPtr<RenderStyle> style)
         : m_key(key)
         , m_style(style)
     {
@@ -51,14 +51,14 @@
     bool containsProperty(CSSPropertyID prop) const { return m_properties.contains(prop); }
     const HashSet<CSSPropertyID>& properties() const { return m_properties; }
 
-    float key() const { return m_key; }
-    void setKey(float key) { m_key = key; }
+    double key() const { return m_key; }
+    void setKey(double key) { m_key = key; }
 
     const RenderStyle* style() const { return m_style.get(); }
     void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
 
 private:
-    float m_key;
+    double m_key;
     HashSet<CSSPropertyID> m_properties; // The properties specified in this keyframe.
     RefPtr<RenderStyle> m_style;
 };
diff --git a/Source/core/rendering/style/RenderStyle.cpp b/Source/core/rendering/style/RenderStyle.cpp
index 220362e..e875a43 100644
--- a/Source/core/rendering/style/RenderStyle.cpp
+++ b/Source/core/rendering/style/RenderStyle.cpp
@@ -613,6 +613,7 @@
         || rareInheritedData->userSelect != other->rareInheritedData->userSelect
         || rareNonInheritedData->userDrag != other->rareNonInheritedData->userDrag
         || rareNonInheritedData->m_borderFit != other->rareNonInheritedData->m_borderFit
+        || rareNonInheritedData->m_objectFit != other->rareNonInheritedData->m_objectFit
         || rareInheritedData->m_imageRendering != other->rareInheritedData->m_imageRendering)
         return StyleDifferenceRepaint;
 
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index 7d97ea9..9fb6b65 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -737,6 +737,8 @@
     const Vector<GridTrackSize>& gridDefinitionRows() const { return rareNonInheritedData->m_grid->m_gridDefinitionRows; }
     const NamedGridLinesMap& namedGridColumnLines() const { return rareNonInheritedData->m_grid->m_namedGridColumnLines; }
     const NamedGridLinesMap& namedGridRowLines() const { return rareNonInheritedData->m_grid->m_namedGridRowLines; }
+    const OrderedNamedGridLines& orderedNamedGridColumnLines() const { return rareNonInheritedData->m_grid->m_orderedNamedGridColumnLines; }
+    const OrderedNamedGridLines& orderedNamedGridRowLines() const { return rareNonInheritedData->m_grid->m_orderedNamedGridRowLines; }
     const NamedGridAreaMap& namedGridArea() const { return rareNonInheritedData->m_grid->m_namedGridArea; }
     size_t namedGridAreaRowCount() const { return rareNonInheritedData->m_grid->m_namedGridAreaRowCount; }
     size_t namedGridAreaColumnCount() const { return rareNonInheritedData->m_grid->m_namedGridAreaColumnCount; }
@@ -818,6 +820,8 @@
 
     TextOrientation textOrientation() const { return static_cast<TextOrientation>(rareInheritedData->m_textOrientation); }
 
+    ObjectFit objectFit() const { return static_cast<ObjectFit>(rareNonInheritedData->m_objectFit); }
+
     // Return true if any transform related property (currently transform, transformStyle3D or perspective)
     // indicates that we are transforming
     bool hasTransformRelatedProperty() const { return hasTransform() || preserves3D() || hasPerspective(); }
@@ -1186,6 +1190,8 @@
     void setGridDefinitionRows(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridDefinitionRows, lengths); }
     void setNamedGridColumnLines(const NamedGridLinesMap& namedGridColumnLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridColumnLines, namedGridColumnLines); }
     void setNamedGridRowLines(const NamedGridLinesMap& namedGridRowLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridRowLines, namedGridRowLines); }
+    void setOrderedNamedGridColumnLines(const OrderedNamedGridLines& orderedNamedGridColumnLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_orderedNamedGridColumnLines, orderedNamedGridColumnLines); }
+    void setOrderedNamedGridRowLines(const OrderedNamedGridLines& orderedNamedGridRowLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_orderedNamedGridRowLines, orderedNamedGridRowLines); }
     void setNamedGridArea(const NamedGridAreaMap& namedGridArea) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridArea, namedGridArea); }
     void setNamedGridAreaRowCount(size_t rowCount) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridAreaRowCount, rowCount); }
     void setNamedGridAreaColumnCount(size_t columnCount) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridAreaColumnCount, columnCount); }
@@ -1251,6 +1257,8 @@
     void setTextEmphasisPosition(TextEmphasisPosition position) { SET_VAR(rareInheritedData, textEmphasisPosition, position); }
     bool setTextOrientation(TextOrientation);
 
+    void setObjectFit(ObjectFit f) { SET_VAR(rareNonInheritedData, m_objectFit, f); }
+
     void setRubyPosition(RubyPosition position) { SET_VAR(rareInheritedData, m_rubyPosition, position); }
 
     void setFilter(const FilterOperations& ops) { SET_VAR(rareNonInheritedData.access()->m_filter, m_operations, ops); }
@@ -1456,6 +1464,7 @@
     static WritingMode initialWritingMode() { return TopToBottomWritingMode; }
     static TextCombine initialTextCombine() { return TextCombineNone; }
     static TextOrientation initialTextOrientation() { return TextOrientationVerticalRight; }
+    static ObjectFit initialObjectFit() { return ObjectFitFill; }
     static EDisplay initialDisplay() { return INLINE; }
     static EEmptyCell initialEmptyCells() { return SHOW; }
     static EFloat initialFloating() { return NoFloat; }
@@ -1592,6 +1601,9 @@
     static NamedGridLinesMap initialNamedGridColumnLines() { return NamedGridLinesMap(); }
     static NamedGridLinesMap initialNamedGridRowLines() { return NamedGridLinesMap(); }
 
+    static OrderedNamedGridLines initialOrderedNamedGridColumnLines() { return OrderedNamedGridLines(); }
+    static OrderedNamedGridLines initialOrderedNamedGridRowLines() { return OrderedNamedGridLines(); }
+
     static NamedGridAreaMap initialNamedGridArea() { return NamedGridAreaMap(); }
     static size_t initialNamedGridAreaCount() { return 0; }
 
diff --git a/Source/core/rendering/style/RenderStyleConstants.h b/Source/core/rendering/style/RenderStyleConstants.h
index 178b93a..0048886 100644
--- a/Source/core/rendering/style/RenderStyleConstants.h
+++ b/Source/core/rendering/style/RenderStyleConstants.h
@@ -205,6 +205,9 @@
     SELECT_NONE, SELECT_TEXT, SELECT_ALL
 };
 
+// CSS3 Image Values
+enum ObjectFit { ObjectFitFill, ObjectFitContain, ObjectFitCover, ObjectFitNone, ObjectFitScaleDown };
+
 // Word Break Values. Matches WinIE, rather than CSS3
 
 enum EWordBreak {
@@ -431,7 +434,6 @@
     TABLE_CAPTION, BOX, INLINE_BOX,
     FLEX, INLINE_FLEX,
     GRID, INLINE_GRID,
-    LAZY_BLOCK,
     NONE
 };
 
diff --git a/Source/core/rendering/style/SVGRenderStyle.cpp b/Source/core/rendering/style/SVGRenderStyle.cpp
index 4ec5581..7d7498a 100644
--- a/Source/core/rendering/style/SVGRenderStyle.cpp
+++ b/Source/core/rendering/style/SVGRenderStyle.cpp
@@ -169,7 +169,10 @@
             || stroke->paintUri != other->stroke->paintUri
             || stroke->miterLimit != other->stroke->miterLimit
             || stroke->dashArray != other->stroke->dashArray
-            || stroke->dashOffset != other->stroke->dashOffset)
+            || stroke->dashOffset != other->stroke->dashOffset
+            || stroke->visitedLinkPaintColor != other->stroke->visitedLinkPaintColor
+            || stroke->visitedLinkPaintUri != other->stroke->visitedLinkPaintUri
+            || stroke->visitedLinkPaintType != other->stroke->visitedLinkPaintType)
             return StyleDifferenceLayout;
 
         // Only the stroke-opacity case remains, where we only need a repaint.
@@ -218,4 +221,11 @@
     return StyleDifferenceEqual;
 }
 
+EPaintOrderType SVGRenderStyle::paintOrderType(unsigned index) const
+{
+    ASSERT(index < ((1 << kPaintOrderBitwidth)-1));
+    unsigned pt = (paintOrder() >> (kPaintOrderBitwidth*index)) & ((1u << kPaintOrderBitwidth) - 1);
+    return (EPaintOrderType)pt;
+}
+
 }
diff --git a/Source/core/rendering/style/SVGRenderStyle.h b/Source/core/rendering/style/SVGRenderStyle.h
index 96fa991..658af07 100644
--- a/Source/core/rendering/style/SVGRenderStyle.h
+++ b/Source/core/rendering/style/SVGRenderStyle.h
@@ -93,6 +93,7 @@
     static String initialMarkerMidResource() { return String(); }
     static String initialMarkerEndResource() { return String(); }
     static EMaskType initialMaskType() { return MT_LUMINANCE; }
+    static EPaintOrder initialPaintOrder() { return PO_NORMAL; }
 
     static SVGLength initialBaselineShiftValue()
     {
@@ -141,6 +142,7 @@
     void setGlyphOrientationHorizontal(EGlyphOrientation val) { svg_inherited_flags._glyphOrientationHorizontal = val; }
     void setGlyphOrientationVertical(EGlyphOrientation val) { svg_inherited_flags._glyphOrientationVertical = val; }
     void setMaskType(EMaskType val) { svg_noninherited_flags.f.maskType = val; }
+    void setPaintOrder(EPaintOrder val) { svg_inherited_flags._paintOrder = (int)val; }
 
     void setFillOpacity(float obj)
     {
@@ -342,6 +344,8 @@
     String markerMidResource() const { return inheritedResources->markerMid; }
     String markerEndResource() const { return inheritedResources->markerEnd; }
     EMaskType maskType() const { return (EMaskType) svg_noninherited_flags.f.maskType; }
+    EPaintOrder paintOrder() const { return (EPaintOrder) svg_inherited_flags._paintOrder; }
+    EPaintOrderType paintOrderType(unsigned index) const;
 
     const SVGPaint::SVGPaintType& visitedLinkFillPaintType() const { return fill->visitedLinkPaintType; }
     const Color& visitedLinkFillPaintColor() const { return fill->visitedLinkPaintColor; }
@@ -376,7 +380,8 @@
                 && (_colorInterpolationFilters == other._colorInterpolationFilters)
                 && (_writingMode == other._writingMode)
                 && (_glyphOrientationHorizontal == other._glyphOrientationHorizontal)
-                && (_glyphOrientationVertical == other._glyphOrientationVertical);
+                && (_glyphOrientationVertical == other._glyphOrientationVertical)
+                && (_paintOrder == other._paintOrder);
         }
 
         bool operator!=(const InheritedFlags& other) const
@@ -396,6 +401,7 @@
         unsigned _writingMode : 3; // SVGWritingMode
         unsigned _glyphOrientationHorizontal : 3; // EGlyphOrientation
         unsigned _glyphOrientationVertical : 3; // EGlyphOrientation
+        unsigned _paintOrder : 6; // EPaintOrder
     } svg_inherited_flags;
 
     // don't inherit
@@ -450,6 +456,7 @@
         svg_inherited_flags._writingMode = initialWritingMode();
         svg_inherited_flags._glyphOrientationHorizontal = initialGlyphOrientationHorizontal();
         svg_inherited_flags._glyphOrientationVertical = initialGlyphOrientationVertical();
+        svg_inherited_flags._paintOrder = initialPaintOrder();
 
         svg_noninherited_flags._niflags = 0;
         svg_noninherited_flags.f._alignmentBaseline = initialAlignmentBaseline();
diff --git a/Source/core/rendering/style/SVGRenderStyleDefs.h b/Source/core/rendering/style/SVGRenderStyleDefs.h
index 3cc75ab..9b32f78 100644
--- a/Source/core/rendering/style/SVGRenderStyleDefs.h
+++ b/Source/core/rendering/style/SVGRenderStyleDefs.h
@@ -92,6 +92,17 @@
         MT_ALPHA
     };
 
+    enum EPaintOrderType {
+        PT_NONE    = 0,
+        PT_FILL    = 1,
+        PT_STROKE  = 2,
+        PT_MARKERS = 3
+    };
+
+    const int kPaintOrderBitwidth = 2;
+    typedef unsigned EPaintOrder;
+    const unsigned PO_NORMAL = PT_FILL | PT_STROKE << 2 | PT_MARKERS << 4;
+
     class CSSValue;
     class CSSValueList;
     class SVGPaint;
diff --git a/Source/core/rendering/style/ShapeValue.h b/Source/core/rendering/style/ShapeValue.h
index b72d251..bb71dab 100644
--- a/Source/core/rendering/style/ShapeValue.h
+++ b/Source/core/rendering/style/ShapeValue.h
@@ -30,6 +30,7 @@
 #ifndef ShapeValue_h
 #define ShapeValue_h
 
+#include "core/fetch/ImageResource.h"
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/StyleImage.h"
 #include "wtf/PassRefPtr.h"
@@ -62,9 +63,12 @@
 
     ShapeValueType type() const { return m_type; }
     BasicShape* shape() const { return m_shape.get(); }
+
     StyleImage* image() const { return m_image.get(); }
+    bool isImageValid() const { return image() && image()->cachedImage() && image()->cachedImage()->hasImage(); }
     void setImage(PassRefPtr<StyleImage> image)
     {
+        ASSERT(type() == Image);
         if (m_image != image)
             m_image = image;
     }
diff --git a/Source/core/rendering/style/StyleCustomFilterProgram.h b/Source/core/rendering/style/StyleCustomFilterProgram.h
index 1678217..18be011 100644
--- a/Source/core/rendering/style/StyleCustomFilterProgram.h
+++ b/Source/core/rendering/style/StyleCustomFilterProgram.h
@@ -30,9 +30,9 @@
 #ifndef StyleCustomFilterProgram_h
 #define StyleCustomFilterProgram_h
 
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
-#include "core/loader/cache/ShaderResource.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ShaderResource.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 #include "core/rendering/style/StyleShader.h"
 #include "weborigin/KURL.h"
diff --git a/Source/core/rendering/style/StyleFetchedImage.cpp b/Source/core/rendering/style/StyleFetchedImage.cpp
index e094475..31dc65a 100644
--- a/Source/core/rendering/style/StyleFetchedImage.cpp
+++ b/Source/core/rendering/style/StyleFetchedImage.cpp
@@ -24,7 +24,7 @@
 #include "config.h"
 #include "core/rendering/style/StyleFetchedImage.h"
 
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebCore {
diff --git a/Source/core/rendering/style/StyleFetchedImage.h b/Source/core/rendering/style/StyleFetchedImage.h
index b9effd9..9ea82f5 100644
--- a/Source/core/rendering/style/StyleFetchedImage.h
+++ b/Source/core/rendering/style/StyleFetchedImage.h
@@ -24,8 +24,8 @@
 #ifndef StyleFetchedImage_h
 #define StyleFetchedImage_h
 
-#include "core/loader/cache/ImageResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ImageResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/rendering/style/StyleImage.h"
 
 namespace WebCore {
diff --git a/Source/core/rendering/style/StyleFetchedImageSet.cpp b/Source/core/rendering/style/StyleFetchedImageSet.cpp
index b9e9d52..04a8d9d 100644
--- a/Source/core/rendering/style/StyleFetchedImageSet.cpp
+++ b/Source/core/rendering/style/StyleFetchedImageSet.cpp
@@ -27,7 +27,7 @@
 #include "core/rendering/style/StyleFetchedImageSet.h"
 
 #include "core/css/CSSImageSetValue.h"
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebCore {
diff --git a/Source/core/rendering/style/StyleFetchedImageSet.h b/Source/core/rendering/style/StyleFetchedImageSet.h
index 3e431e2..178ec3c 100644
--- a/Source/core/rendering/style/StyleFetchedImageSet.h
+++ b/Source/core/rendering/style/StyleFetchedImageSet.h
@@ -26,8 +26,8 @@
 #ifndef StyleFetchedImageSet_h
 #define StyleFetchedImageSet_h
 
-#include "core/loader/cache/ImageResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ImageResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/graphics/LayoutSize.h"
 #include "core/rendering/style/StyleImage.h"
 
diff --git a/Source/core/rendering/style/StyleFetchedShader.cpp b/Source/core/rendering/style/StyleFetchedShader.cpp
index 2b6c6c2..13a8b98 100644
--- a/Source/core/rendering/style/StyleFetchedShader.cpp
+++ b/Source/core/rendering/style/StyleFetchedShader.cpp
@@ -32,7 +32,7 @@
 #include "core/rendering/style/StyleFetchedShader.h"
 
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/loader/cache/ShaderResource.h"
+#include "core/fetch/ShaderResource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/rendering/style/StyleFetchedShader.h b/Source/core/rendering/style/StyleFetchedShader.h
index 88e5411..104a90c 100644
--- a/Source/core/rendering/style/StyleFetchedShader.h
+++ b/Source/core/rendering/style/StyleFetchedShader.h
@@ -30,7 +30,7 @@
 #ifndef StyleFetchedShader_h
 #define StyleFetchedShader_h
 
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/rendering/style/StyleShader.h"
 
 namespace WebCore {
diff --git a/Source/core/rendering/style/StyleGridData.cpp b/Source/core/rendering/style/StyleGridData.cpp
index 8ecde3c..a3f8a34 100644
--- a/Source/core/rendering/style/StyleGridData.cpp
+++ b/Source/core/rendering/style/StyleGridData.cpp
@@ -35,6 +35,8 @@
     , m_gridDefinitionRows(RenderStyle::initialGridDefinitionRows())
     , m_namedGridColumnLines(RenderStyle::initialNamedGridColumnLines())
     , m_namedGridRowLines(RenderStyle::initialNamedGridRowLines())
+    , m_orderedNamedGridColumnLines(RenderStyle::initialOrderedNamedGridColumnLines())
+    , m_orderedNamedGridRowLines(RenderStyle::initialOrderedNamedGridRowLines())
     , m_gridAutoFlow(RenderStyle::initialGridAutoFlow())
     , m_gridAutoRows(RenderStyle::initialGridAutoRows())
     , m_gridAutoColumns(RenderStyle::initialGridAutoColumns())
@@ -50,6 +52,8 @@
     , m_gridDefinitionRows(o.m_gridDefinitionRows)
     , m_namedGridColumnLines(o.m_namedGridColumnLines)
     , m_namedGridRowLines(o.m_namedGridRowLines)
+    , m_orderedNamedGridColumnLines(o.m_orderedNamedGridColumnLines)
+    , m_orderedNamedGridRowLines(o.m_orderedNamedGridRowLines)
     , m_gridAutoFlow(o.m_gridAutoFlow)
     , m_gridAutoRows(o.m_gridAutoRows)
     , m_gridAutoColumns(o.m_gridAutoColumns)
diff --git a/Source/core/rendering/style/StyleGridData.h b/Source/core/rendering/style/StyleGridData.h
index 21d9b01..c7f5e54 100644
--- a/Source/core/rendering/style/StyleGridData.h
+++ b/Source/core/rendering/style/StyleGridData.h
@@ -37,6 +37,7 @@
 namespace WebCore {
 
 typedef HashMap<String, Vector<size_t> > NamedGridLinesMap;
+typedef HashMap<size_t, Vector<String>, WTF::IntHash<size_t>, WTF::UnsignedWithZeroKeyHashTraits<size_t> > OrderedNamedGridLines;
 
 class StyleGridData : public RefCounted<StyleGridData> {
 public:
@@ -45,7 +46,7 @@
 
     bool operator==(const StyleGridData& o) const
     {
-        return m_gridDefinitionColumns == o.m_gridDefinitionColumns && m_gridDefinitionRows == o.m_gridDefinitionRows && m_gridAutoFlow == o.m_gridAutoFlow && m_gridAutoRows == o.m_gridAutoRows && m_gridAutoColumns == o.m_gridAutoColumns && m_namedGridColumnLines == o.m_namedGridColumnLines && m_namedGridRowLines == o.m_namedGridRowLines && m_namedGridArea == o.m_namedGridArea && m_namedGridArea == o.m_namedGridArea && m_namedGridAreaRowCount == o.m_namedGridAreaRowCount && m_namedGridAreaColumnCount == o.m_namedGridAreaColumnCount;
+        return m_gridDefinitionColumns == o.m_gridDefinitionColumns && m_gridDefinitionRows == o.m_gridDefinitionRows && m_gridAutoFlow == o.m_gridAutoFlow && m_gridAutoRows == o.m_gridAutoRows && m_gridAutoColumns == o.m_gridAutoColumns && m_namedGridColumnLines == o.m_namedGridColumnLines && m_namedGridRowLines == o.m_namedGridRowLines && m_orderedNamedGridColumnLines == o.m_orderedNamedGridColumnLines && m_orderedNamedGridRowLines == o.m_orderedNamedGridRowLines && m_namedGridArea == o.m_namedGridArea && m_namedGridArea == o.m_namedGridArea && m_namedGridAreaRowCount == o.m_namedGridAreaRowCount && m_namedGridAreaColumnCount == o.m_namedGridAreaColumnCount;
     }
 
     bool operator!=(const StyleGridData& o) const
@@ -59,6 +60,11 @@
     NamedGridLinesMap m_namedGridColumnLines;
     NamedGridLinesMap m_namedGridRowLines;
 
+    // In order to reconstruct the original named grid line order, we can't rely on NamedGridLinesMap
+    // as it loses the position if multiple grid lines are set on a single track.
+    OrderedNamedGridLines m_orderedNamedGridColumnLines;
+    OrderedNamedGridLines m_orderedNamedGridRowLines;
+
     GridAutoFlow m_gridAutoFlow;
 
     GridTrackSize m_gridAutoRows;
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.cpp b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
index c93cdd4..3539ba1 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
@@ -75,6 +75,7 @@
     , m_hasAspectRatio(false)
     , m_effectiveBlendMode(RenderStyle::initialBlendMode())
     , m_touchAction(RenderStyle::initialTouchAction())
+    , m_objectFit(RenderStyle::initialObjectFit())
 {
     m_maskBoxImage.setMaskDefaults();
 }
@@ -147,6 +148,7 @@
     , m_hasAspectRatio(o.m_hasAspectRatio)
     , m_effectiveBlendMode(o.m_effectiveBlendMode)
     , m_touchAction(o.m_touchAction)
+    , m_objectFit(o.m_objectFit)
 {
 }
 
@@ -221,7 +223,8 @@
         && !m_runningAcceleratedAnimation && !o.m_runningAcceleratedAnimation
         && m_effectiveBlendMode == o.m_effectiveBlendMode
         && m_hasAspectRatio == o.m_hasAspectRatio
-        && m_touchAction == o.m_touchAction;
+        && m_touchAction == o.m_touchAction
+        && m_objectFit == o.m_objectFit;
 }
 
 bool StyleRareNonInheritedData::contentDataEquivalent(const StyleRareNonInheritedData& o) const
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.h b/Source/core/rendering/style/StyleRareNonInheritedData.h
index a48395e..340357a 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.h
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.h
@@ -179,6 +179,8 @@
 
     unsigned m_touchAction : 1; // TouchAction
 
+    unsigned m_objectFit : 3; // ObjectFit
+
 private:
     StyleRareNonInheritedData();
     StyleRareNonInheritedData(const StyleRareNonInheritedData&);
diff --git a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
index ab598e3..b2a9feb 100644
--- a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
+++ b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
@@ -33,8 +33,8 @@
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/dom/Element.h"
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/DocumentResourceReference.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"
diff --git a/Source/core/rendering/svg/RenderSVGEllipse.cpp b/Source/core/rendering/svg/RenderSVGEllipse.cpp
index 3c559f6..7542fa6 100644
--- a/Source/core/rendering/svg/RenderSVGEllipse.cpp
+++ b/Source/core/rendering/svg/RenderSVGEllipse.cpp
@@ -77,8 +77,7 @@
 {
     ASSERT(node());
     if (node()->hasTagName(SVGNames::circleTag)) {
-
-        SVGCircleElement* circle = static_cast<SVGCircleElement*>(node());
+        SVGCircleElement* circle = toSVGCircleElement(node());
 
         SVGLengthContext lengthContext(circle);
         float radius = circle->rCurrentValue().value(lengthContext);
@@ -87,8 +86,7 @@
         return;
     }
 
-    ASSERT(node()->hasTagName(SVGNames::ellipseTag));
-    SVGEllipseElement* ellipse = static_cast<SVGEllipseElement*>(node());
+    SVGEllipseElement* ellipse = toSVGEllipseElement(node());
 
     SVGLengthContext lengthContext(ellipse);
     m_radii = FloatSize(ellipse->rxCurrentValue().value(lengthContext), ellipse->ryCurrentValue().value(lengthContext));
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index 92a96dd..9da09f9 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -127,7 +127,7 @@
         }
     }
     // Only one visible shape/path was found. Directly continue clipping and transform the content to userspace if necessary.
-    if (static_cast<SVGClipPathElement*>(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+    if (toSVGClipPathElement(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         AffineTransform transform;
         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
         transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
@@ -152,7 +152,7 @@
         m_clipper.set(object, new ClipperData);
 
     bool shouldCreateClipData = false;
-    AffineTransform animatedLocalTransform = static_cast<SVGClipPathElement*>(node())->animatedLocalTransform();
+    AffineTransform animatedLocalTransform = toSVGClipPathElement(node())->animatedLocalTransform();
     ClipperData* clipperData = m_clipper.get(object);
     if (!clipperData->clipMaskImage) {
         if (pathOnlyClipping(context, animatedLocalTransform, objectBoundingBox))
@@ -208,8 +208,7 @@
     ASSERT(maskContext);
 
     AffineTransform maskContentTransformation;
-    SVGClipPathElement* clipPath = static_cast<SVGClipPathElement*>(node());
-    if (clipPath->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+    if (toSVGClipPathElement(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         maskContentTransformation.translate(objectBoundingBox.x(), objectBoundingBox.y());
         maskContentTransformation.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
         maskContext->concatCTM(maskContentTransformation);
@@ -277,7 +276,7 @@
              continue;
         m_clipBoundaries.unite(renderer->localToParentTransform().mapRect(renderer->repaintRectInLocalCoordinates()));
     }
-    m_clipBoundaries = static_cast<SVGClipPathElement*>(node())->animatedLocalTransform().mapRect(m_clipBoundaries);
+    m_clipBoundaries = toSVGClipPathElement(node())->animatedLocalTransform().mapRect(m_clipBoundaries);
 }
 
 bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundingBox, const FloatPoint& nodeAtPoint)
@@ -286,7 +285,7 @@
     if (!SVGRenderSupport::pointInClippingArea(this, point))
         return false;
 
-    SVGClipPathElement* clipPathElement = static_cast<SVGClipPathElement*>(node());
+    SVGClipPathElement* clipPathElement = toSVGClipPathElement(node());
     if (clipPathElement->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         AffineTransform transform;
         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
@@ -320,7 +319,7 @@
     if (m_clipBoundaries.isEmpty())
         calculateClipContentRepaintRect();
 
-    if (static_cast<SVGClipPathElement*>(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+    if (toSVGClipPathElement(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         FloatRect objectBoundingBox = object->objectBoundingBox();
         AffineTransform transform;
         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.h b/Source/core/rendering/svg/RenderSVGResourceClipper.h
index 32e4971..69ee986 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.h
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.h
@@ -52,7 +52,7 @@
 
     bool hitTestClipContent(const FloatRect&, const FloatPoint&);
 
-    SVGUnitTypes::SVGUnitType clipPathUnits() const { return static_cast<SVGClipPathElement*>(node())->clipPathUnitsCurrentValue(); }
+    SVGUnitTypes::SVGUnitType clipPathUnits() const { return toSVGClipPathElement(node())->clipPathUnitsCurrentValue(); }
 
     static RenderSVGResourceType s_resourceType;
 private:
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index 4b83d6f..aef216a 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -215,7 +215,7 @@
     effectiveTransform.multiply(filterData->shearFreeAbsoluteTransform);
 
     OwnPtr<ImageBuffer> sourceGraphic;
-    RenderingMode renderingMode = object->document()->page()->settings()->acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
+    RenderingMode renderingMode = object->document()->page()->settings().acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
     if (!SVGRenderingContext::createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, renderingMode)) {
         ASSERT(!m_filter.contains(object));
         filterData->savedContext = context;
diff --git a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
index a23c163..51e6782 100644
--- a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
@@ -62,7 +62,7 @@
     // 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
     // GradientData object! Leaving out the line below will cause svg/dynamic-updates/SVG*GradientElement-svgdom* to crash.
-    SVGGradientElement* gradientElement = static_cast<SVGGradientElement*>(node());
+    SVGGradientElement* gradientElement = toSVGGradientElement(node());
     if (!gradientElement)
         return false;
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
index d6f5472..4a0b52f 100644
--- a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
@@ -41,7 +41,7 @@
 bool RenderSVGResourceLinearGradient::collectGradientAttributes(SVGGradientElement* gradientElement)
 {
     m_attributes = LinearGradientAttributes();
-    return static_cast<SVGLinearGradientElement*>(gradientElement)->collectGradientAttributes(m_attributes);
+    return toSVGLinearGradientElement(gradientElement)->collectGradientAttributes(m_attributes);
 }
 
 FloatPoint RenderSVGResourceLinearGradient::startPoint(const LinearGradientAttributes& attributes) const
diff --git a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
index c280f47..e10f289 100644
--- a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
@@ -42,7 +42,7 @@
 bool RenderSVGResourceRadialGradient::collectGradientAttributes(SVGGradientElement* gradientElement)
 {
     m_attributes = RadialGradientAttributes();
-    return static_cast<SVGRadialGradientElement*>(gradientElement)->collectGradientAttributes(m_attributes);
+    return toSVGRadialGradientElement(gradientElement)->collectGradientAttributes(m_attributes);
 }
 
 FloatPoint RenderSVGResourceRadialGradient::centerPoint(const RadialGradientAttributes& attributes) const
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index 3e63935..c6cb3c6 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -40,6 +40,7 @@
 #include "core/rendering/svg/SVGResourcesCache.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGSVGElement.h"
+#include "core/svg/graphics/SVGImage.h"
 
 using namespace std;
 
@@ -110,22 +111,7 @@
 
 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
 {
-    if (!node())
-        return false;
-
-    Frame* frame = node()->document()->frame();
-    if (!frame)
-        return false;
-
-    // Test whether we're embedded through an img.
-    if (!frame->page())
-        return false;
-
-    ChromeClient* chromeClient = frame->page()->chrome().client();
-    if (!chromeClient || !chromeClient->isSVGImageChromeClient())
-        return false;
-
-    return true;
+    return SVGImage::isInSVGImage(toSVGSVGElement(node()));
 }
 
 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index 522f7ab..5156aa5 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -243,26 +243,6 @@
     }
 }
 
-void RenderSVGShape::fillAndStrokeShape(GraphicsContext* context)
-{
-    RenderStyle* style = this->style();
-
-    fillShape(style, context);
-
-    if (!style->svgStyle()->hasVisibleStroke())
-        return;
-
-    GraphicsContextStateSaver stateSaver(*context, false);
-
-    if (hasNonScalingStroke()) {
-        AffineTransform nonScalingTransform = nonScalingStrokeTransform();
-        if (!setupNonScalingStrokeContext(nonScalingTransform, stateSaver))
-            return;
-    }
-
-    strokeShape(style, context);
-}
-
 void RenderSVGShape::paint(PaintInfo& paintInfo, const LayoutPoint&)
 {
     ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
@@ -287,9 +267,34 @@
                 if (svgStyle->shapeRendering() == SR_CRISPEDGES)
                     childPaintInfo.context->setShouldAntialias(false);
 
-                fillAndStrokeShape(childPaintInfo.context);
-                if (!m_markerPositions.isEmpty())
-                    drawMarkers(childPaintInfo);
+                for (int i = 0; i < 3; i++) {
+                    switch (svgStyle->paintOrderType(i)) {
+                    case PT_FILL:
+                        fillShape(this->style(), childPaintInfo.context);
+                        break;
+                    case PT_STROKE:
+                        if (svgStyle->hasVisibleStroke()) {
+                            GraphicsContextStateSaver stateSaver(*childPaintInfo.context, false);
+                            AffineTransform nonScalingTransform;
+
+                            if (hasNonScalingStroke()) {
+                                AffineTransform nonScalingTransform = nonScalingStrokeTransform();
+                                if (!setupNonScalingStrokeContext(nonScalingTransform, stateSaver))
+                                    return;
+                            }
+
+                            strokeShape(this->style(), childPaintInfo.context);
+                        }
+                        break;
+                    case PT_MARKERS:
+                        if (!m_markerPositions.isEmpty())
+                            drawMarkers(childPaintInfo);
+                        break;
+                    default:
+                        ASSERT_NOT_REACHED();
+                        break;
+                    }
+                }
             }
         }
 
diff --git a/Source/core/rendering/svg/RenderSVGShape.h b/Source/core/rendering/svg/RenderSVGShape.h
index 8ace237..49295b4 100644
--- a/Source/core/rendering/svg/RenderSVGShape.h
+++ b/Source/core/rendering/svg/RenderSVGShape.h
@@ -109,7 +109,6 @@
 
     void fillShape(RenderStyle*, GraphicsContext*);
     void strokeShape(RenderStyle*, GraphicsContext*);
-    void fillAndStrokeShape(GraphicsContext*);
     void drawMarkers(PaintInfo&);
 
 private:
diff --git a/Source/core/rendering/svg/RenderSVGTextPath.cpp b/Source/core/rendering/svg/RenderSVGTextPath.cpp
index a1fbae3..f2068b8 100644
--- a/Source/core/rendering/svg/RenderSVGTextPath.cpp
+++ b/Source/core/rendering/svg/RenderSVGTextPath.cpp
@@ -35,7 +35,7 @@
 
 Path RenderSVGTextPath::layoutPath() const
 {
-    SVGTextPathElement* textPathElement = static_cast<SVGTextPathElement*>(node());
+    SVGTextPathElement* textPathElement = toSVGTextPathElement(node());
     Element* targetElement = SVGURIReference::targetElementFromIRIString(textPathElement->hrefCurrentValue(), textPathElement->document());
     if (!targetElement || !targetElement->hasTagName(SVGNames::pathTag))
         return Path();
@@ -56,17 +56,17 @@
 
 float RenderSVGTextPath::startOffset() const
 {
-    return static_cast<SVGTextPathElement*>(node())->startOffsetCurrentValue().valueAsPercentage();
+    return toSVGTextPathElement(node())->startOffsetCurrentValue().valueAsPercentage();
 }
 
 bool RenderSVGTextPath::exactAlignment() const
 {
-    return static_cast<SVGTextPathElement*>(node())->spacingCurrentValue() == SVGTextPathSpacingExact;
+    return toSVGTextPathElement(node())->spacingCurrentValue() == SVGTextPathSpacingExact;
 }
 
 bool RenderSVGTextPath::stretchMethod() const
 {
-    return static_cast<SVGTextPathElement*>(node())->methodCurrentValue() == SVGTextPathMethodStretch;
+    return toSVGTextPathElement(node())->methodCurrentValue() == SVGTextPathMethodStretch;
 }
 
 }
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.cpp b/Source/core/rendering/svg/SVGInlineTextBox.cpp
index 8731b0c..0a08afb 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineTextBox.cpp
@@ -326,16 +326,29 @@
         if (decorations & TextDecorationOverline)
             paintDecoration(paintInfo.context, TextDecorationOverline, fragment);
 
-        // Fill text
-        if (hasFill) {
-            m_paintingResourceMode = ApplyToFillMode | ApplyToTextMode;
-            paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
-        }
-
-        // Stroke text
-        if (hasVisibleStroke) {
-            m_paintingResourceMode = ApplyToStrokeMode | ApplyToTextMode;
-            paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
+        for (int i = 0; i < 3; i++) {
+            switch (svgStyle->paintOrderType(i)) {
+            case PT_FILL:
+                // Fill text
+                if (hasFill) {
+                    m_paintingResourceMode = ApplyToFillMode | ApplyToTextMode;
+                    paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
+                }
+                break;
+            case PT_STROKE:
+                // Stroke text
+                if (hasVisibleStroke) {
+                    m_paintingResourceMode = ApplyToStrokeMode | ApplyToTextMode;
+                    paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
+                }
+                break;
+            case PT_MARKERS:
+                // Markers don't apply to text
+                break;
+            default:
+                ASSERT_NOT_REACHED();
+                break;
+            }
         }
 
         // Spec: Line-through should be drawn after the text is filled and stroked; thus, the line-through is rendered on top of the text.
diff --git a/Source/core/rendering/svg/SVGPathData.cpp b/Source/core/rendering/svg/SVGPathData.cpp
index 707f548..23fc965 100644
--- a/Source/core/rendering/svg/SVGPathData.cpp
+++ b/Source/core/rendering/svg/SVGPathData.cpp
@@ -36,8 +36,7 @@
 
 static void updatePathFromCircleElement(SVGElement* element, Path& path)
 {
-    ASSERT(element->hasTagName(SVGNames::circleTag));
-    SVGCircleElement* circle = static_cast<SVGCircleElement*>(element);
+    SVGCircleElement* circle = toSVGCircleElement(element);
 
     SVGLengthContext lengthContext(element);
     float r = circle->rCurrentValue().value(lengthContext);
@@ -47,8 +46,7 @@
 
 static void updatePathFromEllipseElement(SVGElement* element, Path& path)
 {
-    ASSERT(element->hasTagName(SVGNames::ellipseTag));
-    SVGEllipseElement* ellipse = static_cast<SVGEllipseElement*>(element);
+    SVGEllipseElement* ellipse = toSVGEllipseElement(element);
 
     SVGLengthContext lengthContext(element);
     float rx = ellipse->rxCurrentValue().value(lengthContext);
@@ -62,8 +60,7 @@
 
 static void updatePathFromLineElement(SVGElement* element, Path& path)
 {
-    ASSERT(element->hasTagName(SVGNames::lineTag));
-    SVGLineElement* line = static_cast<SVGLineElement*>(element);
+    SVGLineElement* line = toSVGLineElement(element);
 
     SVGLengthContext lengthContext(element);
     path.moveTo(FloatPoint(line->x1CurrentValue().value(lengthContext), line->y1CurrentValue().value(lengthContext)));
diff --git a/Source/core/rendering/svg/SVGRenderSupport.cpp b/Source/core/rendering/svg/SVGRenderSupport.cpp
index 09fdae4..1e48649 100644
--- a/Source/core/rendering/svg/SVGRenderSupport.cpp
+++ b/Source/core/rendering/svg/SVGRenderSupport.cpp
@@ -29,6 +29,7 @@
 #include "core/platform/graphics/transforms/TransformState.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderLayer.h"
+#include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
 #include "core/rendering/svg/RenderSVGResourceClipper.h"
 #include "core/rendering/svg/RenderSVGResourceFilter.h"
@@ -240,8 +241,9 @@
             }
         }
 
+        SubtreeLayoutScope layoutScope(child);
         if (needsLayout)
-            child->setNeedsLayout(MarkOnlyThis);
+            layoutScope.setNeedsLayout(child);
 
         if (child->needsLayout()) {
             child->layout();
@@ -253,8 +255,6 @@
                 child->repaint();
         } else if (layoutSizeChanged)
             notlayoutedObjects.add(child);
-
-        ASSERT(!child->needsLayout());
     }
 
     if (!layoutSizeChanged) {
diff --git a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index f6b6dde..b4ebbd0 100644
--- a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -337,30 +337,28 @@
         writeNameValuePair(ts, "width", element->widthCurrentValue().value(lengthContext));
         writeNameValuePair(ts, "height", element->heightCurrentValue().value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::lineTag)) {
-        SVGLineElement* element = static_cast<SVGLineElement*>(svgElement);
+        SVGLineElement* element = toSVGLineElement(svgElement);
         writeNameValuePair(ts, "x1", element->x1CurrentValue().value(lengthContext));
         writeNameValuePair(ts, "y1", element->y1CurrentValue().value(lengthContext));
         writeNameValuePair(ts, "x2", element->x2CurrentValue().value(lengthContext));
         writeNameValuePair(ts, "y2", element->y2CurrentValue().value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::ellipseTag)) {
-        SVGEllipseElement* element = static_cast<SVGEllipseElement*>(svgElement);
+        SVGEllipseElement* element = toSVGEllipseElement(svgElement);
         writeNameValuePair(ts, "cx", element->cxCurrentValue().value(lengthContext));
         writeNameValuePair(ts, "cy", element->cyCurrentValue().value(lengthContext));
         writeNameValuePair(ts, "rx", element->rxCurrentValue().value(lengthContext));
         writeNameValuePair(ts, "ry", element->ryCurrentValue().value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::circleTag)) {
-        SVGCircleElement* element = static_cast<SVGCircleElement*>(svgElement);
+        SVGCircleElement* element = toSVGCircleElement(svgElement);
         writeNameValuePair(ts, "cx", element->cxCurrentValue().value(lengthContext));
         writeNameValuePair(ts, "cy", element->cyCurrentValue().value(lengthContext));
         writeNameValuePair(ts, "r", element->rCurrentValue().value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::polygonTag) || svgElement->hasTagName(SVGNames::polylineTag)) {
-        SVGPolyElement* element = static_cast<SVGPolyElement*>(svgElement);
-        writeNameAndQuotedValue(ts, "points", element->pointList().valueAsString());
+        writeNameAndQuotedValue(ts, "points", toSVGPolyElement(svgElement)->pointList().valueAsString());
     } else if (svgElement->hasTagName(SVGNames::pathTag)) {
-        SVGPathElement* element = toSVGPathElement(svgElement);
         String pathString;
         // FIXME: We should switch to UnalteredParsing here - this will affect the path dumping output of dozens of tests.
-        buildStringFromByteStream(element->pathByteStream(), pathString, NormalizedParsing);
+        buildStringFromByteStream(toSVGPathElement(svgElement)->pathByteStream(), pathString, NormalizedParsing);
         writeNameAndQuotedValue(ts, "data", pathString);
     } else
         ASSERT_NOT_REACHED();
@@ -541,10 +539,8 @@
 
         // Dump final results that are used for rendering. No use in asking SVGGradientElement for its gradientUnits(), as it may
         // link to other gradients using xlink:href, we need to build the full inheritance chain, aka. collectGradientProperties()
-        SVGLinearGradientElement* linearGradientElement = static_cast<SVGLinearGradientElement*>(gradient->node());
-
         LinearGradientAttributes attributes;
-        linearGradientElement->collectGradientAttributes(attributes);
+        toSVGLinearGradientElement(gradient->node())->collectGradientAttributes(attributes);
         writeCommonGradientProperties(ts, attributes.spreadMethod(), attributes.gradientTransform(), attributes.gradientUnits());
 
         ts << " [start=" << gradient->startPoint(attributes) << "] [end=" << gradient->endPoint(attributes) << "]\n";
@@ -553,10 +549,8 @@
 
         // Dump final results that are used for rendering. No use in asking SVGGradientElement for its gradientUnits(), as it may
         // link to other gradients using xlink:href, we need to build the full inheritance chain, aka. collectGradientProperties()
-        SVGRadialGradientElement* radialGradientElement = static_cast<SVGRadialGradientElement*>(gradient->node());
-
         RadialGradientAttributes attributes;
-        radialGradientElement->collectGradientAttributes(attributes);
+        toSVGRadialGradientElement(gradient->node())->collectGradientAttributes(attributes);
         writeCommonGradientProperties(ts, attributes.spreadMethod(), attributes.gradientTransform(), attributes.gradientUnits());
 
         FloatPoint focalPoint = gradient->focalPoint(attributes);
@@ -625,7 +619,7 @@
 {
     writeStandardPrefix(ts, stop, indent);
 
-    SVGStopElement* stopElement = static_cast<SVGStopElement*>(stop.node());
+    SVGStopElement* stopElement = toSVGStopElement(stop.node());
     ASSERT(stopElement);
 
     RenderStyle* style = stop.style();
diff --git a/Source/core/scripts/make_css_property_names.py b/Source/core/scripts/make_css_property_names.py
index f775462..ab137e9 100755
--- a/Source/core/scripts/make_css_property_names.py
+++ b/Source/core/scripts/make_css_property_names.py
@@ -16,9 +16,10 @@
 #ifndef %(class_name)s_h
 #define %(class_name)s_h
 
-#include <string.h>
+#include "core/css/CSSParserMode.h"
 #include "wtf/HashFunctions.h"
 #include "wtf/HashTraits.h"
+#include <string.h>
 
 namespace WTF {
 class AtomicString;
@@ -42,6 +43,7 @@
 const WTF::AtomicString& getPropertyNameAtomicString(CSSPropertyID);
 WTF::String getPropertyNameString(CSSPropertyID);
 WTF::String getJSPropertyName(CSSPropertyID);
+bool isInternalProperty(CSSPropertyID id);
 
 inline CSSPropertyID convertToCSSPropertyID(int value)
 {
@@ -163,6 +165,16 @@
     return String(result);
 }
 
+bool isInternalProperty(CSSPropertyID id)
+{
+    switch (id) {
+        %(internal_properties)s
+            return true;
+        default:
+            return false;
+    }
+}
+
 } // namespace WebCore
 """
 
@@ -172,6 +184,7 @@
     defaults = {
         'alias_for': None,
         'condition': None,
+        'is_internal': False,
     }
 
     def __init__(self, file_paths, enabled_conditions):
@@ -196,6 +209,8 @@
         for offset, property in enumerate(self._properties):
             property['enum_name'] = self._enum_name_from_property_name(property['name'])
             property['enum_value'] = self._first_property_id + offset
+            if property['name'].startswith('-internal-'):
+                property['is_internal'] = True
 
     def _enum_name_from_property_name(self, property_name):
         return "CSSProperty" + re.sub(r'(^[^-])|-(.)', lambda match: (match.group(1) or match.group(2)).upper(), property_name)
@@ -214,6 +229,9 @@
             'max_name_length': reduce(max, map(len, map(lambda property: property['name'], self._properties))),
         }
 
+    def _case_properties(self, property):
+        return "case %(enum_name)s:" % property
+
     def generate_implementation(self):
         property_offsets = []
         current_offset = 0
@@ -227,6 +245,7 @@
             'property_name_strings': '\n'.join(map(lambda property: '    "%(name)s\\0"' % property, self._properties)),
             'property_name_offsets': '\n'.join(map(lambda offset: '    %d,' % offset, property_offsets)),
             'property_to_enum_map': '\n'.join(map(lambda property: '%(name)s, %(enum_name)s' % property, self._properties + self._aliases)),
+            'internal_properties': '\n'.join(map(self._case_properties, filter(lambda property: property['is_internal'], self._properties))),
         }
         # FIXME: If we could depend on Python 2.7, we would use subprocess.check_output
         gperf_args = ['gperf', '--key-positions=*', '-P', '-D', '-n', '-s', '2']
diff --git a/Source/core/scripts/make_names.pl b/Source/core/scripts/make_names.pl
index 5fa77e2..a3d003a 100755
--- a/Source/core/scripts/make_names.pl
+++ b/Source/core/scripts/make_names.pl
@@ -859,8 +859,8 @@
     if (!document)
         return 0;
 
-    if (CustomElement::isCustomTagName(qName.localName()) && document->registrationContext()) {
-        RefPtr<Element> element = document->registrationContext()->createCustomTagElement(document, qName);
+    if (CustomElement::isValidName(qName.localName()) && document->registrationContext()) {
+        RefPtr<Element> element = document->registrationContext()->createCustomTagElement(document, qName, createdByParser ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
         ASSERT_WITH_SECURITY_IMPLICATION(element->is$parameters{namespace}Element());
         return static_pointer_cast<$parameters{namespace}Element>(element.release());
     }
diff --git a/Source/core/scripts/make_runtime_features.py b/Source/core/scripts/make_runtime_features.py
index 1454f09..6ec681b 100755
--- a/Source/core/scripts/make_runtime_features.py
+++ b/Source/core/scripts/make_runtime_features.py
@@ -47,6 +47,7 @@
         'depends_on' : [],
         'custom': False,
         'status': None,
+        'writeable': False,
     }
 
     def __init__(self, in_file_path, enabled_conditions):
@@ -72,6 +73,7 @@
         lowered = lowered.replace("cSS", "css")
         lowered = lowered.replace("iME", "ime")
         lowered = lowered.replace("hTML", "html")
+        lowered = lowered.replace("sVG", "svg")
         lowered = lowered.replace("wOFF", "woff")
         return lowered
 
diff --git a/Source/core/scripts/make_token_matcher.py b/Source/core/scripts/make_token_matcher.py
index 3631ed9..10fae62 100755
--- a/Source/core/scripts/make_token_matcher.py
+++ b/Source/core/scripts/make_token_matcher.py
@@ -219,8 +219,8 @@
 
 def process_file(input_name, output_name):
     """Transforms input file into legal C++ source code."""
-    with io.open(input_name) as input_file:
-        with io.open(output_name, 'w') as output_file:
+    with io.open(input_name, 'r', -1, 'utf-8') as input_file:
+        with io.open(output_name, 'w', -1, 'utf-8') as output_file:
             processor = MainLineProcessor(output_file)
             input_lines = input_file.readlines()
             for line in input_lines:
diff --git a/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl b/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
index fe77d0c..f33a3b3 100644
--- a/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
+++ b/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
@@ -27,6 +27,9 @@
 {% for feature in features if not feature.custom %}
 {%- call wrap_with_condition(feature.condition) %}
     bool {{feature.first_lowered_name}}Enabled() { return RuntimeEnabledFeatures::{{feature.first_lowered_name}}Enabled(); }
+    {% if feature.writeable %}
+    void set{{feature.name}}Enabled(bool isEnabled) { RuntimeEnabledFeatures::set{{feature.name}}Enabled(isEnabled); }
+    {% endif %}
 {%- endcall %}
 {% endfor %}
 
diff --git a/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl b/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
index c73ce7a..f0161f9 100644
--- a/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
+++ b/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
@@ -9,7 +9,10 @@
     it's possible that some can be and should be conditionally readonly.
 #}
     {% if feature.condition -%} [Conditional={{feature.condition}}] {% endif -%}
+    {% if feature.writeable %}
+    attribute boolean {{feature.first_lowered_name}}Enabled;
+    {% else %}
     readonly attribute boolean {{feature.first_lowered_name}}Enabled;
+    {% endif %}
 {%- endfor %}
 };
-
diff --git a/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl b/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl
index 2bf0382..5ef9feb 100644
--- a/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl
+++ b/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl
@@ -70,8 +70,9 @@
 {%- set camel_case_name = property.camel_case_name %}
 const StylePropertyShorthand& {{ camel_case_name }}Shorthand();
 {%- endfor %}
-const StylePropertyShorthand& borderShorthandForParsing();
-const StylePropertyShorthand& webkitAnimationShorthandForParsing();
+
+// Returns an empty list if the property is not a shorthand, otherwise the list of longhands for parsing.
+const StylePropertyShorthand& parsingShorthandForProperty(CSSPropertyID);
 
 // Returns an empty list if the property is not a shorthand.
 const StylePropertyShorthand& shorthandForProperty(CSSPropertyID);
diff --git a/Source/core/storage/Storage.cpp b/Source/core/storage/Storage.cpp
index bbeb0a3..c46e9bb 100644
--- a/Source/core/storage/Storage.cpp
+++ b/Source/core/storage/Storage.cpp
@@ -28,8 +28,8 @@
 
 #include "bindings/v8/ExceptionState.h"
 #include "wtf/PassOwnPtr.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/storage/Storage.h b/Source/core/storage/Storage.h
index 4ffefd5..825dad3 100644
--- a/Source/core/storage/Storage.h
+++ b/Source/core/storage/Storage.h
@@ -29,9 +29,9 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/page/DOMWindowProperty.h"
 #include "core/storage/StorageArea.h"
-#include <wtf/Forward.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/storage/StorageArea.h b/Source/core/storage/StorageArea.h
index 00533e5..00114d5 100644
--- a/Source/core/storage/StorageArea.h
+++ b/Source/core/storage/StorageArea.h
@@ -26,8 +26,8 @@
 #ifndef StorageArea_h
 #define StorageArea_h
 
-#include <wtf/Forward.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/storage/StorageEvent.h b/Source/core/storage/StorageEvent.h
index c59471e..a4e8ffc 100644
--- a/Source/core/storage/StorageEvent.h
+++ b/Source/core/storage/StorageEvent.h
@@ -27,7 +27,7 @@
 #define StorageEvent_h
 
 #include "core/dom/Event.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/svg/SVGAElement.cpp b/Source/core/svg/SVGAElement.cpp
index 23b39ce..c1d88fb 100644
--- a/Source/core/svg/SVGAElement.cpp
+++ b/Source/core/svg/SVGAElement.cpp
@@ -217,16 +217,14 @@
     return false;
 }
 
-bool SVGAElement::isKeyboardFocusable(KeyboardEvent*) const
+bool SVGAElement::isKeyboardFocusable() const
 {
     if (!isFocusable())
         return false;
 
-    Page* page = document()->page();
-    if (!page)
-        return false;
-
-    return page->chrome().client()->tabsToLinks();
+    if (Page* page = document()->page())
+        return page->chrome().client().tabsToLinks();
+    return false;
 }
 
 bool SVGAElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
diff --git a/Source/core/svg/SVGAElement.h b/Source/core/svg/SVGAElement.h
index bd8b805..8fa4b67 100644
--- a/Source/core/svg/SVGAElement.h
+++ b/Source/core/svg/SVGAElement.h
@@ -52,8 +52,8 @@
     virtual void defaultEventHandler(Event*);
 
     virtual bool supportsFocus() const OVERRIDE;
-    virtual bool isMouseFocusable() const;
-    virtual bool isKeyboardFocusable(KeyboardEvent*) const;
+    virtual bool isMouseFocusable() const OVERRIDE;
+    virtual bool isKeyboardFocusable() const OVERRIDE;
     virtual bool rendererIsFocusable() const OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const;
 
diff --git a/Source/core/svg/SVGAnimateElement.cpp b/Source/core/svg/SVGAnimateElement.cpp
index 0f404eb..e3af159 100644
--- a/Source/core/svg/SVGAnimateElement.cpp
+++ b/Source/core/svg/SVGAnimateElement.cpp
@@ -111,12 +111,7 @@
     ASSERT(m_fromType->type() == m_animatedPropertyType);
     ASSERT(m_toType);
 
-    ASSERT(resultElement->hasTagName(SVGNames::animateTag)
-        || resultElement->hasTagName(SVGNames::animateColorTag)
-        || resultElement->hasTagName(SVGNames::animateTransformTag)
-        || resultElement->hasTagName(SVGNames::setTag));
-
-    SVGAnimateElement* resultAnimationElement = static_cast<SVGAnimateElement*>(resultElement);
+    SVGAnimateElement* resultAnimationElement = toSVGAnimateElement(resultElement);
     ASSERT(resultAnimationElement->m_animatedType);
     ASSERT(resultAnimationElement->m_animatedPropertyType == m_animatedPropertyType);
 
diff --git a/Source/core/svg/SVGAnimateElement.h b/Source/core/svg/SVGAnimateElement.h
index d987374..f53a5bb 100644
--- a/Source/core/svg/SVGAnimateElement.h
+++ b/Source/core/svg/SVGAnimateElement.h
@@ -23,6 +23,7 @@
 #ifndef SVGAnimateElement_h
 #define SVGAnimateElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimationElement.h"
 #include "wtf/OwnPtr.h"
 
@@ -73,6 +74,16 @@
     OwnPtr<SVGAnimatedTypeAnimator> m_animator;
 };
 
+inline SVGAnimateElement* toSVGAnimateElement(Element* element)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!element
+        || element->hasTagName(SVGNames::animateTag)
+        || element->hasTagName(SVGNames::animateColorTag)
+        || element->hasTagName(SVGNames::animateTransformTag)
+        || element->hasTagName(SVGNames::setTag));
+    return static_cast<SVGAnimateElement*>(element);
+}
+
 } // namespace WebCore
 
 #endif // SVGAnimateElement_h
diff --git a/Source/core/svg/SVGAnimationElement.cpp b/Source/core/svg/SVGAnimationElement.cpp
index 6e7f664..9351da4 100644
--- a/Source/core/svg/SVGAnimationElement.cpp
+++ b/Source/core/svg/SVGAnimationElement.cpp
@@ -507,8 +507,7 @@
 
     CalcMode calcMode = this->calcMode();
     if (hasTagName(SVGNames::animateTag) || hasTagName(SVGNames::animateColorTag)) {
-        SVGAnimateElement* animateElement = static_cast<SVGAnimateElement*>(this);
-        AnimatedPropertyType attributeType = animateElement->determineAnimatedPropertyType(targetElement());
+        AnimatedPropertyType attributeType = toSVGAnimateElement(this)->determineAnimatedPropertyType(targetElement());
         // Fall back to discrete animations for Strings.
         if (attributeType == AnimatedBoolean
             || attributeType == AnimatedEnumeration
@@ -571,10 +570,11 @@
     AnimationMode animationMode = this->animationMode();
     CalcMode calcMode = this->calcMode();
     if (calcMode == CalcModeSpline) {
-        unsigned splinesCount = m_keySplines.size() + 1;
-        if ((fastHasAttribute(SVGNames::keyPointsAttr) && m_keyPoints.size() != splinesCount)
-            || (animationMode == ValuesAnimation && m_values.size() != splinesCount)
-            || (fastHasAttribute(SVGNames::keyTimesAttr) && m_keyTimes.size() != splinesCount))
+        unsigned splinesCount = m_keySplines.size();
+        if (!splinesCount
+            || (fastHasAttribute(SVGNames::keyPointsAttr) && m_keyPoints.size() - 1 != splinesCount)
+            || (animationMode == ValuesAnimation && m_values.size() - 1 != splinesCount)
+            || (fastHasAttribute(SVGNames::keyTimesAttr) && m_keyTimes.size() - 1 != splinesCount))
             return;
     }
 
diff --git a/Source/core/svg/SVGAnimationElement.h b/Source/core/svg/SVGAnimationElement.h
index 9108719..a2d9ac4 100644
--- a/Source/core/svg/SVGAnimationElement.h
+++ b/Source/core/svg/SVGAnimationElement.h
@@ -237,6 +237,9 @@
 
     AttributeType m_attributeType;
     Vector<String> m_values;
+    // FIXME: We should probably use doubles for this, but there's no point
+    // making such a change unless all SVG logic for sampling animations is
+    // changed to use doubles.
     Vector<float> m_keyTimes;
     Vector<float> m_keyPoints;
     Vector<UnitBezier> m_keySplines;
diff --git a/Source/core/svg/SVGCircleElement.h b/Source/core/svg/SVGCircleElement.h
index 25b5d88..99dc642 100644
--- a/Source/core/svg/SVGCircleElement.h
+++ b/Source/core/svg/SVGCircleElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGCircleElement_h
 #define SVGCircleElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
@@ -55,6 +56,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGCircleElement* toSVGCircleElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::circleTag));
+    return static_cast<SVGCircleElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // SVGCircleElement_h
diff --git a/Source/core/svg/SVGClipPathElement.h b/Source/core/svg/SVGClipPathElement.h
index c5bbb88..5667aa7 100644
--- a/Source/core/svg/SVGClipPathElement.h
+++ b/Source/core/svg/SVGClipPathElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGClipPathElement_h
 #define SVGClipPathElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
@@ -55,6 +56,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGClipPathElement* toSVGClipPathElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::clipPathTag));
+    return static_cast<SVGClipPathElement*>(node);
+}
+
 }
 
 #endif
diff --git a/Source/core/svg/SVGDocument.cpp b/Source/core/svg/SVGDocument.cpp
index 0823df0..ddab3c4 100644
--- a/Source/core/svg/SVGDocument.cpp
+++ b/Source/core/svg/SVGDocument.cpp
@@ -94,11 +94,6 @@
     }
 }
 
-PassRefPtr<Document> SVGDocument::cloneDocumentWithoutChildren()
-{
-    return create();
-}
-
 bool SVGDocument::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
 {
     if (childContext.node()->hasTagName(SVGNames::svgTag))
diff --git a/Source/core/svg/SVGDocument.h b/Source/core/svg/SVGDocument.h
index 163188b..273db02 100644
--- a/Source/core/svg/SVGDocument.h
+++ b/Source/core/svg/SVGDocument.h
@@ -47,8 +47,6 @@
     void startPan(const FloatPoint& start);
     void updatePan(const FloatPoint& pos) const;
 
-    virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
-
 private:
     SVGDocument(const DocumentInit&);
 
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index 9fa1de0..9ca209f 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -34,9 +34,9 @@
 #include "core/css/CSSParser.h"
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/Event.h"
 #include "core/dom/NodeRenderingContext.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/svg/RenderSVGResourceContainer.h"
@@ -408,6 +408,7 @@
         mapAttributeToCSSProperty(propertyNameToIdMap, mask_typeAttr);
         mapAttributeToCSSProperty(propertyNameToIdMap, opacityAttr);
         mapAttributeToCSSProperty(propertyNameToIdMap, overflowAttr);
+        mapAttributeToCSSProperty(propertyNameToIdMap, paint_orderAttr);
         mapAttributeToCSSProperty(propertyNameToIdMap, pointer_eventsAttr);
         mapAttributeToCSSProperty(propertyNameToIdMap, shape_renderingAttr);
         mapAttributeToCSSProperty(propertyNameToIdMap, stop_colorAttr);
@@ -671,6 +672,7 @@
     s_cssPropertyMap.set(mask_typeAttr, AnimatedString);
     s_cssPropertyMap.set(opacityAttr, AnimatedNumber);
     s_cssPropertyMap.set(overflowAttr, AnimatedString);
+    s_cssPropertyMap.set(paint_orderAttr, AnimatedString);
     s_cssPropertyMap.set(pointer_eventsAttr, AnimatedString);
     s_cssPropertyMap.set(shape_renderingAttr, AnimatedString);
     s_cssPropertyMap.set(stop_colorAttr, AnimatedColor);
diff --git a/Source/core/svg/SVGElementInstance.cpp b/Source/core/svg/SVGElementInstance.cpp
index a25bf7f..26e57cc 100644
--- a/Source/core/svg/SVGElementInstance.cpp
+++ b/Source/core/svg/SVGElementInstance.cpp
@@ -59,6 +59,7 @@
 DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(SVGElementInstance, correspondingElement(), mouseover);
 DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(SVGElementInstance, correspondingElement(), mouseup);
 DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(SVGElementInstance, correspondingElement(), mousewheel);
+DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(SVGElementInstance, correspondingElement(), wheel);
 DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(SVGElementInstance, correspondingElement(), beforecut);
 DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(SVGElementInstance, correspondingElement(), cut);
 DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(SVGElementInstance, correspondingElement(), beforecopy);
diff --git a/Source/core/svg/SVGElementInstance.h b/Source/core/svg/SVGElementInstance.h
index 88e39a3..ba364f3 100644
--- a/Source/core/svg/SVGElementInstance.h
+++ b/Source/core/svg/SVGElementInstance.h
@@ -120,6 +120,7 @@
     DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), mouseover);
     DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), mouseup);
     DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), mousewheel);
+    DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), wheel);
     DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), beforecut);
     DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), cut);
     DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), beforecopy);
diff --git a/Source/core/svg/SVGElementInstance.idl b/Source/core/svg/SVGElementInstance.idl
index 4344913..8f6a1d8 100644
--- a/Source/core/svg/SVGElementInstance.idl
+++ b/Source/core/svg/SVGElementInstance.idl
@@ -56,7 +56,7 @@
     [NotEnumerable] attribute EventHandler onmouseout;
     [NotEnumerable] attribute EventHandler onmouseover;
     [NotEnumerable] attribute EventHandler onmouseup;
-    [NotEnumerable] attribute EventHandler onmousewheel;
+    [NotEnumerable] attribute EventHandler onmousewheel; // Deprecated in favor of onwheel.
     [NotEnumerable] attribute EventHandler onbeforecut;
     [NotEnumerable] attribute EventHandler oncut;
     [NotEnumerable] attribute EventHandler onbeforecopy;
@@ -78,4 +78,5 @@
     [NotEnumerable] attribute EventHandler onselectstart;
     [NotEnumerable] attribute EventHandler onsubmit;
     [NotEnumerable] attribute EventHandler onunload;
+    [NotEnumerable] attribute EventHandler onwheel;
 };
diff --git a/Source/core/svg/SVGEllipseElement.h b/Source/core/svg/SVGEllipseElement.h
index c341e14..8d98e10 100644
--- a/Source/core/svg/SVGEllipseElement.h
+++ b/Source/core/svg/SVGEllipseElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGEllipseElement_h
 #define SVGEllipseElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
@@ -56,6 +57,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGEllipseElement* toSVGEllipseElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::ellipseTag));
+    return static_cast<SVGEllipseElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFEImageElement.cpp b/Source/core/svg/SVGFEImageElement.cpp
index b67789c..cbf76e8 100644
--- a/Source/core/svg/SVGFEImageElement.cpp
+++ b/Source/core/svg/SVGFEImageElement.cpp
@@ -26,9 +26,9 @@
 #include "SVGNames.h"
 #include "XLinkNames.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/platform/graphics/Image.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/svg/SVGElementInstance.h"
@@ -193,7 +193,8 @@
     if (!parent->hasTagName(SVGNames::filterTag) || !parent->renderer())
         return;
 
-    RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer());
+    if (RenderObject* renderer = this->renderer())
+        RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
 }
 
 PassRefPtr<FilterEffect> SVGFEImageElement::build(SVGFilterBuilder*, Filter* filter)
diff --git a/Source/core/svg/SVGFEImageElement.h b/Source/core/svg/SVGFEImageElement.h
index 64f326d..799a8ff 100644
--- a/Source/core/svg/SVGFEImageElement.h
+++ b/Source/core/svg/SVGFEImageElement.h
@@ -21,8 +21,8 @@
 #ifndef SVGFEImageElement_h
 #define SVGFEImageElement_h
 
-#include "core/loader/cache/ImageResource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
diff --git a/Source/core/svg/SVGFontElement.cpp b/Source/core/svg/SVGFontElement.cpp
index 08d15de..e076129 100644
--- a/Source/core/svg/SVGFontElement.cpp
+++ b/Source/core/svg/SVGFontElement.cpp
@@ -73,7 +73,7 @@
 {
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         if (child->hasTagName(SVGNames::missing_glyphTag))
-            return static_cast<SVGMissingGlyphElement*>(child);
+            return toSVGMissingGlyphElement(child);
     }
 
     return 0;
@@ -141,8 +141,9 @@
         } else if (child->hasTagName(SVGNames::vkernTag)) {
             SVGVKernElement* vkern = static_cast<SVGVKernElement*>(child);
             vkern->buildVerticalKerningPair(m_verticalKerningPairs);
-        } else if (child->hasTagName(SVGNames::missing_glyphTag) && !firstMissingGlyphElement)
-            firstMissingGlyphElement = static_cast<SVGMissingGlyphElement*>(child);
+        } else if (child->hasTagName(SVGNames::missing_glyphTag) && !firstMissingGlyphElement) {
+            firstMissingGlyphElement = toSVGMissingGlyphElement(child);
+        }
     }
 
     // Register each character of each ligature, if needed.
diff --git a/Source/core/svg/SVGFontFaceElement.cpp b/Source/core/svg/SVGFontFaceElement.cpp
index eca1641..9c77958 100644
--- a/Source/core/svg/SVGFontFaceElement.cpp
+++ b/Source/core/svg/SVGFontFaceElement.cpp
@@ -316,7 +316,7 @@
         }
     }
 
-    document()->styleResolverChanged(DeferRecalcStyle);
+    document()->styleResolverChanged(RecalcStyleDeferred);
 }
 
 Node::InsertionNotificationRequest SVGFontFaceElement::insertedInto(ContainerNode* rootParent)
@@ -341,7 +341,7 @@
         document()->accessSVGExtensions()->unregisterSVGFontFaceElement(this);
         m_fontFaceRule->mutableProperties()->clear();
 
-        document()->styleResolverChanged(DeferRecalcStyle);
+        document()->styleResolverChanged(RecalcStyleDeferred);
     } else
         ASSERT(!m_fontElement);
 }
diff --git a/Source/core/svg/SVGFontFaceUriElement.cpp b/Source/core/svg/SVGFontFaceUriElement.cpp
index 569ca30..d040e43 100644
--- a/Source/core/svg/SVGFontFaceUriElement.cpp
+++ b/Source/core/svg/SVGFontFaceUriElement.cpp
@@ -27,9 +27,9 @@
 #include "XLinkNames.h"
 #include "core/css/CSSFontFaceSrcValue.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/FontResource.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/svg/SVGFontFaceElement.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/SVGFontFaceUriElement.h b/Source/core/svg/SVGFontFaceUriElement.h
index 99d1046..6101a5c 100644
--- a/Source/core/svg/SVGFontFaceUriElement.h
+++ b/Source/core/svg/SVGFontFaceUriElement.h
@@ -21,8 +21,8 @@
 #define SVGFontFaceUriElement_h
 
 #if ENABLE(SVG_FONTS)
-#include "core/loader/cache/FontResource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/svg/SVGElement.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/SVGImageLoader.cpp b/Source/core/svg/SVGImageLoader.cpp
index 75dd0d4..85c0fbb 100644
--- a/Source/core/svg/SVGImageLoader.cpp
+++ b/Source/core/svg/SVGImageLoader.cpp
@@ -24,8 +24,8 @@
 
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
+#include "core/fetch/ImageResource.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/ImageResource.h"
 #include "core/svg/SVGImageElement.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/SVGLineElement.h b/Source/core/svg/SVGLineElement.h
index f90960a..c1e8a51 100644
--- a/Source/core/svg/SVGLineElement.h
+++ b/Source/core/svg/SVGLineElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGLineElement_h
 #define SVGLineElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
@@ -56,6 +57,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGLineElement* toSVGLineElement(Element* element)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->hasTagName(SVGNames::lineTag));
+    return static_cast<SVGLineElement*>(element);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGLinearGradientElement.cpp b/Source/core/svg/SVGLinearGradientElement.cpp
index 583fcf4..5d5a807 100644
--- a/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/Source/core/svg/SVGLinearGradientElement.cpp
@@ -148,7 +148,7 @@
         }
 
         if (isLinear) {
-            SVGLinearGradientElement* linear = static_cast<SVGLinearGradientElement*>(current);
+            SVGLinearGradientElement* linear = toSVGLinearGradientElement(current);
 
             if (!attributes.hasX1() && current->hasAttribute(SVGNames::x1Attr))
                 attributes.setX1(linear->x1CurrentValue());
diff --git a/Source/core/svg/SVGLinearGradientElement.h b/Source/core/svg/SVGLinearGradientElement.h
index 21bd87c..c80d6ff 100644
--- a/Source/core/svg/SVGLinearGradientElement.h
+++ b/Source/core/svg/SVGLinearGradientElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGLinearGradientElement_h
 #define SVGLinearGradientElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGGradientElement.h"
 
@@ -53,6 +54,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGLinearGradientElement* toSVGLinearGradientElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::linearGradientTag));
+    return static_cast<SVGLinearGradientElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGMissingGlyphElement.h b/Source/core/svg/SVGMissingGlyphElement.h
index 9dfaf3f..9437431 100644
--- a/Source/core/svg/SVGMissingGlyphElement.h
+++ b/Source/core/svg/SVGMissingGlyphElement.h
@@ -21,6 +21,7 @@
 #define SVGMissingGlyphElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGElement.h"
 
 namespace WebCore {
@@ -35,6 +36,12 @@
     virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
 };
 
+inline SVGMissingGlyphElement* toSVGMissingGlyphElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::missing_glyphTag));
+    return static_cast<SVGMissingGlyphElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SVG_FONTS)
diff --git a/Source/core/svg/SVGRadialGradientElement.cpp b/Source/core/svg/SVGRadialGradientElement.cpp
index 6ba70e5..4929cc2 100644
--- a/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/Source/core/svg/SVGRadialGradientElement.cpp
@@ -159,7 +159,7 @@
         }
 
         if (isRadial) {
-            SVGRadialGradientElement* radial = static_cast<SVGRadialGradientElement*>(current);
+            SVGRadialGradientElement* radial = toSVGRadialGradientElement(current);
 
             if (!attributes.hasCx() && current->hasAttribute(SVGNames::cxAttr))
                 attributes.setCx(radial->cxCurrentValue());
diff --git a/Source/core/svg/SVGRadialGradientElement.h b/Source/core/svg/SVGRadialGradientElement.h
index f70de31..20be564 100644
--- a/Source/core/svg/SVGRadialGradientElement.h
+++ b/Source/core/svg/SVGRadialGradientElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGRadialGradientElement_h
 #define SVGRadialGradientElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGGradientElement.h"
 
@@ -55,6 +56,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGRadialGradientElement* toSVGRadialGradientElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::radialGradientTag));
+    return static_cast<SVGRadialGradientElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index d695883..708e209 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -28,6 +28,7 @@
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/css/CSSHelper.h"
 #include "core/dom/Document.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/EventListener.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/NodeTraversal.h"
@@ -718,7 +719,7 @@
         if (SVGViewElement* viewElement = anchorNode->hasTagName(SVGNames::viewTag) ? static_cast<SVGViewElement*>(anchorNode) : 0) {
             SVGElement* element = SVGLocatable::nearestViewportElement(viewElement);
             if (element->hasTagName(SVGNames::svgTag)) {
-                SVGSVGElement* svg = static_cast<SVGSVGElement*>(element);
+                SVGSVGElement* svg = toSVGSVGElement(element);
                 svg->inheritViewAttributes(viewElement);
 
                 if (RenderObject* renderer = svg->renderer())
diff --git a/Source/core/svg/SVGStopElement.h b/Source/core/svg/SVGStopElement.h
index a19d928..828c7f7 100644
--- a/Source/core/svg/SVGStopElement.h
+++ b/Source/core/svg/SVGStopElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGStopElement_h
 #define SVGStopElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGElement.h"
 
@@ -49,10 +50,10 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
-inline SVGStopElement* toSVGStopElement(SVGElement* element)
+inline SVGStopElement* toSVGStopElement(Node* node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isGradientStop());
-    return static_cast<SVGStopElement*>(element);
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isGradientStop());
+    return static_cast<SVGStopElement*>(node);
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTextContentElement.cpp b/Source/core/svg/SVGTextContentElement.cpp
index 532b74b..48c806a 100644
--- a/Source/core/svg/SVGTextContentElement.cpp
+++ b/Source/core/svg/SVGTextContentElement.cpp
@@ -123,6 +123,9 @@
         return 0.0f;
     }
 
+    if (nchars > numberOfChars - charnum)
+        nchars = numberOfChars - charnum;
+
     return SVGTextQuery(renderer()).subStringLength(charnum, nchars);
 }
 
diff --git a/Source/core/svg/SVGTextContentElement.idl b/Source/core/svg/SVGTextContentElement.idl
index 4d69375..f4ce37d 100644
--- a/Source/core/svg/SVGTextContentElement.idl
+++ b/Source/core/svg/SVGTextContentElement.idl
@@ -34,15 +34,13 @@
 
     long getNumberOfChars();
     float getComputedTextLength();
-    [RaisesException] float getSubStringLength([Default=Undefined,IsIndex] optional unsigned long offset,
-                             [Default=Undefined,IsIndex] optional unsigned long length);
-    [RaisesException] SVGPoint getStartPositionOfChar([Default=Undefined,IsIndex] optional unsigned long offset);
-    [RaisesException] SVGPoint getEndPositionOfChar([Default=Undefined,IsIndex] optional unsigned long offset);
-    [RaisesException] SVGRect getExtentOfChar([Default=Undefined,IsIndex] optional unsigned long offset);
-    [RaisesException] float getRotationOfChar([Default=Undefined,IsIndex] optional unsigned long offset);
-    long getCharNumAtPosition([Default=Undefined] optional SVGPoint point);
-    [RaisesException] void selectSubString([Default=Undefined,IsIndex] optional unsigned long offset,
-                         [Default=Undefined,IsIndex] optional unsigned long length);
+    [RaisesException] float getSubStringLength(unsigned long offset, unsigned long length);
+    [RaisesException] SVGPoint getStartPositionOfChar(unsigned long offset);
+    [RaisesException] SVGPoint getEndPositionOfChar(unsigned long offset);
+    [RaisesException] SVGRect getExtentOfChar(unsigned long offset);
+    [RaisesException] float getRotationOfChar(unsigned long offset);
+    long getCharNumAtPosition(SVGPoint point);
+    [RaisesException] void selectSubString(unsigned long offset, unsigned long length);
 };
 
 // FIXME: SVGTextContentElement is not supposed to implement SVGExternalResourcesRequired.
diff --git a/Source/core/svg/SVGTextPathElement.h b/Source/core/svg/SVGTextPathElement.h
index ab6bcb9..0ad3f96 100644
--- a/Source/core/svg/SVGTextPathElement.h
+++ b/Source/core/svg/SVGTextPathElement.h
@@ -20,8 +20,8 @@
 #ifndef SVGTextPathElement_h
 #define SVGTextPathElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGTextContentElement.h"
-
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
@@ -140,6 +140,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGTextPathElement* toSVGTextPathElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::textPathTag));
+    return static_cast<SVGTextPathElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index 9ea0250..06b3c7a 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -30,13 +30,13 @@
 #include "XLinkNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/Event.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/loader/cache/DocumentResource.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/DocumentResource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/rendering/svg/RenderSVGTransformableContainer.h"
 #include "core/svg/SVGElementInstance.h"
diff --git a/Source/core/svg/SVGUseElement.h b/Source/core/svg/SVGUseElement.h
index 1540588..3216a51 100644
--- a/Source/core/svg/SVGUseElement.h
+++ b/Source/core/svg/SVGUseElement.h
@@ -22,7 +22,7 @@
 #define SVGUseElement_h
 
 #include "SVGNames.h"
-#include "core/loader/cache/DocumentResource.h"
+#include "core/fetch/DocumentResource.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
diff --git a/Source/core/svg/animation/SMILTimeContainer.cpp b/Source/core/svg/animation/SMILTimeContainer.cpp
index a91c96f..5b6ccc9 100644
--- a/Source/core/svg/animation/SMILTimeContainer.cpp
+++ b/Source/core/svg/animation/SMILTimeContainer.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/svg/animation/SMILTimeContainer.h"
 
-#include "core/dom/NodeTraversal.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/animation/SVGSMILElement.h"
 #include "wtf/CurrentTime.h"
diff --git a/Source/core/svg/graphics/SVGImage.cpp b/Source/core/svg/graphics/SVGImage.cpp
index bbcfe3c..395f2db 100644
--- a/Source/core/svg/graphics/SVGImage.cpp
+++ b/Source/core/svg/graphics/SVGImage.cpp
@@ -29,7 +29,10 @@
 
 #include "core/svg/graphics/SVGImage.h"
 
+#include "core/dom/NodeTraversal.h"
+#include "core/dom/shadow/ComposedShadowTreeWalker.h"
 #include "core/loader/DocumentLoader.h"
+#include "core/page/Chrome.h"
 #include "core/page/FrameView.h"
 #include "core/page/Settings.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
@@ -39,6 +42,7 @@
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/svg/SVGDocument.h"
+#include "core/svg/SVGImageElement.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/graphics/SVGImageChromeClient.h"
 #include "wtf/PassRefPtr.h"
@@ -62,6 +66,48 @@
     ASSERT(!m_chromeClient || !m_chromeClient->image());
 }
 
+bool SVGImage::isInSVGImage(const Element* element)
+{
+    ASSERT(element);
+
+    Page* page = element->document()->page();
+    if (!page)
+        return false;
+
+    return page->chrome().client().isSVGImageChromeClient();
+}
+
+bool SVGImage::hasSingleSecurityOrigin() const
+{
+    if (!m_page)
+        return true;
+
+    Frame* frame = m_page->mainFrame();
+    SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
+    if (!rootElement)
+        return true;
+
+    // Don't allow foreignObject elements or images that are not known to be
+    // single-origin since these can leak cross-origin information.
+    ComposedShadowTreeWalker walker(rootElement);
+    while (Node* node = walker.get()) {
+        if (node->hasTagName(SVGNames::foreignObjectTag))
+            return false;
+        // FIXME(crbug.com/249037): Images should be allowed but the
+        // implementation is difficult because images can have animations which
+        // cause them to dynamically change their single-origin state.
+        if (node->hasTagName(SVGNames::imageTag))
+            return false;
+        if (node->hasTagName(SVGNames::feImageTag))
+            return false;
+        walker.next();
+    }
+
+    // Because SVG image rendering disallows external resources and links, these
+    // images effectively are restricted to a single security origin.
+    return true;
+}
+
 void SVGImage::setContainerSize(const IntSize& size)
 {
     if (!m_page || !usesContainerSize())
@@ -338,10 +384,10 @@
         // SVGImage objects, but we're safe now, because SVGImage can only be
         // loaded by a top-level document.
         m_page = adoptPtr(new Page(pageClients));
-        m_page->settings()->setMediaEnabled(false);
-        m_page->settings()->setScriptEnabled(false);
-        m_page->settings()->setPluginsEnabled(false);
-        m_page->settings()->setAcceleratedCompositingEnabled(false);
+        m_page->settings().setMediaEnabled(false);
+        m_page->settings().setScriptEnabled(false);
+        m_page->settings().setPluginsEnabled(false);
+        m_page->settings().setAcceleratedCompositingEnabled(false);
 
         RefPtr<Frame> frame = Frame::create(m_page.get(), 0, dummyFrameLoaderClient);
         frame->setView(FrameView::create(frame.get()));
diff --git a/Source/core/svg/graphics/SVGImage.h b/Source/core/svg/graphics/SVGImage.h
index 186f2b7..65a1a05 100644
--- a/Source/core/svg/graphics/SVGImage.h
+++ b/Source/core/svg/graphics/SVGImage.h
@@ -31,6 +31,7 @@
 
 namespace WebCore {
 
+class Element;
 class FrameView;
 class ImageBuffer;
 class Page;
@@ -45,12 +46,16 @@
         return adoptRef(new SVGImage(observer));
     }
 
+    static bool isInSVGImage(const Element*);
+
     RenderBox* embeddedContentBox() const;
     FrameView* frameView() const;
 
     virtual bool isSVGImage() const OVERRIDE { return true; }
     virtual IntSize size() const OVERRIDE { return m_intrinsicSize; }
 
+    virtual bool hasSingleSecurityOrigin() const OVERRIDE;
+
     virtual bool hasRelativeWidth() const OVERRIDE;
     virtual bool hasRelativeHeight() const OVERRIDE;
 
diff --git a/Source/core/svg/graphics/SVGImageCache.cpp b/Source/core/svg/graphics/SVGImageCache.cpp
index 6b5e5a2..81153b3 100644
--- a/Source/core/svg/graphics/SVGImageCache.cpp
+++ b/Source/core/svg/graphics/SVGImageCache.cpp
@@ -21,7 +21,7 @@
 #include "config.h"
 #include "core/svg/graphics/SVGImageCache.h"
 
-#include "core/loader/cache/ImageResource.h"
+#include "core/fetch/ImageResource.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/GraphicsContext.h"
diff --git a/Source/core/svg/svgattrs.in b/Source/core/svg/svgattrs.in
index c73cf5c..bee8ecc 100644
--- a/Source/core/svg/svgattrs.in
+++ b/Source/core/svg/svgattrs.in
@@ -144,6 +144,7 @@
 overflow
 overline-position
 overline-thickness
+paint-order
 panose-1
 path
 pathLength
diff --git a/Source/core/testing/InspectorFrontendClientLocal.cpp b/Source/core/testing/InspectorFrontendClientLocal.cpp
index a68a070..3d57d26 100644
--- a/Source/core/testing/InspectorFrontendClientLocal.cpp
+++ b/Source/core/testing/InspectorFrontendClientLocal.cpp
@@ -39,16 +39,16 @@
 #include "core/platform/Timer.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebThread.h"
-#include <wtf/Deque.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Deque.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 class InspectorBackendMessageQueue : public RefCounted<InspectorBackendMessageQueue> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit InspectorBackendMessageQueue(InspectorController* inspectorController)
-        : m_inspectorController(inspectorController)
+    explicit InspectorBackendMessageQueue(InspectorController& inspectorController)
+        : m_inspectorController(&inspectorController)
     {
     }
 
@@ -96,11 +96,10 @@
     Deque<String> m_messages;
 };
 
-InspectorFrontendClientLocal::InspectorFrontendClientLocal(InspectorController* inspectorController, Page* frontendPage)
-    : m_inspectorController(inspectorController)
-    , m_frontendPage(frontendPage)
+InspectorFrontendClientLocal::InspectorFrontendClientLocal(InspectorController& inspectorController, Page* frontendPage)
+    : m_frontendPage(frontendPage)
 {
-    m_frontendPage->settings()->setAllowFileAccessFromFileURLs(true);
+    m_frontendPage->settings().setAllowFileAccessFromFileURLs(true);
     m_messageQueue = adoptRef(new InspectorBackendMessageQueue(inspectorController));
 }
 
@@ -110,7 +109,6 @@
     if (m_frontendHost)
         m_frontendHost->disconnectClient();
     m_frontendPage = 0;
-    m_inspectorController = 0;
 }
 
 void InspectorFrontendClientLocal::windowObjectCleared()
diff --git a/Source/core/testing/InspectorFrontendClientLocal.h b/Source/core/testing/InspectorFrontendClientLocal.h
index ef35eba..f18fb0e 100644
--- a/Source/core/testing/InspectorFrontendClientLocal.h
+++ b/Source/core/testing/InspectorFrontendClientLocal.h
@@ -32,9 +32,9 @@
 #define InspectorFrontendClientLocal_h
 
 #include "core/inspector/InspectorFrontendClient.h"
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -47,7 +47,7 @@
 class InspectorFrontendClientLocal : public InspectorFrontendClient {
     WTF_MAKE_NONCOPYABLE(InspectorFrontendClientLocal); WTF_MAKE_FAST_ALLOCATED;
 public:
-    InspectorFrontendClientLocal(InspectorController*, Page*);
+    InspectorFrontendClientLocal(InspectorController&, Page*);
     virtual ~InspectorFrontendClientLocal();
 
     virtual void windowObjectCleared();
@@ -80,7 +80,6 @@
     virtual bool isUnderTest() { return true; }
 
 private:
-    InspectorController* m_inspectorController;
     Page* m_frontendPage;
     // TODO(yurys): this ref shouldn't be needed.
     RefPtr<InspectorFrontendHost> m_frontendHost;
diff --git a/Source/core/testing/InternalSettings.cpp b/Source/core/testing/InternalSettings.cpp
index 29e34ec..745e2fa 100644
--- a/Source/core/testing/InternalSettings.cpp
+++ b/Source/core/testing/InternalSettings.cpp
@@ -58,6 +58,7 @@
 
 InternalSettings::Backup::Backup(Settings* settings)
     : m_originalCSSExclusionsEnabled(RuntimeEnabledFeatures::cssExclusionsEnabled())
+    , m_originalCSSShapesEnabled(RuntimeEnabledFeatures::cssShapesEnabled())
     , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
     , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())
     , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())
@@ -66,7 +67,6 @@
     , m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())
     , m_originalTextAutosizingFontScaleFactor(settings->textAutosizingFontScaleFactor())
     , m_originalMediaTypeOverride(settings->mediaTypeOverride())
-    , m_originalLazyLayoutEnabled(RuntimeEnabledFeatures::lazyLayoutEnabled())
     , m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())
     , m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
     , m_imagesEnabled(settings->areImagesEnabled())
@@ -80,6 +80,7 @@
 void InternalSettings::Backup::restoreTo(Settings* settings)
 {
     RuntimeEnabledFeatures::setCSSExclusionsEnabled(m_originalCSSExclusionsEnabled);
+    RuntimeEnabledFeatures::setCSSShapesEnabled(m_originalCSSShapesEnabled);
     RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);
     settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);
     RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);
@@ -88,7 +89,6 @@
     settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);
     settings->setTextAutosizingFontScaleFactor(m_originalTextAutosizingFontScaleFactor);
     settings->setMediaTypeOverride(m_originalMediaTypeOverride);
-    RuntimeEnabledFeatures::setLazyLayoutEnabled(m_originalLazyLayoutEnabled);
     settings->setMockScrollbarsEnabled(m_originalMockScrollbarsEnabled);
     RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(m_langAttributeAwareFormControlUIEnabled);
     settings->setImagesEnabled(m_imagesEnabled);
@@ -134,7 +134,7 @@
 InternalSettings::InternalSettings(Page* page)
     : InternalSettingsGenerated(page)
     , m_page(page)
-    , m_backup(page->settings())
+    , m_backup(&page->settings())
 {
 }
 
@@ -152,7 +152,7 @@
 {
     if (!page())
         return 0;
-    return page()->settings();
+    return &page()->settings();
 }
 
 void InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& es)
@@ -182,6 +182,12 @@
     settings()->setTouchEventEmulationEnabled(enabled);
 }
 
+void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& es)
+{
+    InternalSettingsGuardForSettings();
+    settings()->setViewportEnabled(enabled);
+}
+
 // 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)
@@ -284,11 +290,6 @@
         es.throwDOMException(SyntaxError);
 }
 
-void InternalSettings::setLazyLayoutEnabled(bool enabled)
-{
-    RuntimeEnabledFeatures::setLazyLayoutEnabled(enabled);
-}
-
 void InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)
 {
     RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(enabled);
diff --git a/Source/core/testing/InternalSettings.h b/Source/core/testing/InternalSettings.h
index 186385d..290566a 100644
--- a/Source/core/testing/InternalSettings.h
+++ b/Source/core/testing/InternalSettings.h
@@ -50,6 +50,7 @@
         void restoreTo(Settings*);
 
         bool m_originalCSSExclusionsEnabled;
+        bool m_originalCSSShapesEnabled;
         bool m_originalAuthorShadowDOMForAnyElementEnabled;
         bool m_originalExperimentalWebSocketEnabled;
         bool m_originalStyleScoped;
@@ -58,7 +59,6 @@
         IntSize m_originalTextAutosizingWindowSizeOverride;
         float m_originalTextAutosizingFontScaleFactor;
         String m_originalMediaTypeOverride;
-        bool m_originalLazyLayoutEnabled;
         bool m_originalMockScrollbarsEnabled;
         bool m_originalUsesOverlayScrollbars;
         bool m_langAttributeAwareFormControlUIEnabled;
@@ -97,6 +97,7 @@
     void setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState&);
     void setTouchEventEmulationEnabled(bool, ExceptionState&);
     void setUsesOverlayScrollbars(bool, ExceptionState&);
+    void setViewportEnabled(bool, ExceptionState&);
 
     // FIXME: This is a temporary flag and should be removed once accelerated
     // overflow scroll is ready (crbug.com/254111).
@@ -109,7 +110,6 @@
     void setCSSExclusionsEnabled(bool);
     void setExperimentalWebSocketEnabled(bool);
     void setLangAttributeAwareFormControlUIEnabled(bool);
-    void setLazyLayoutEnabled(bool);
     void setStyleScopedEnabled(bool);
 
 private:
diff --git a/Source/core/testing/InternalSettings.idl b/Source/core/testing/InternalSettings.idl
index 9d98511..f1d7594 100644
--- a/Source/core/testing/InternalSettings.idl
+++ b/Source/core/testing/InternalSettings.idl
@@ -44,6 +44,7 @@
 
     [RaisesException] void setImagesEnabled(boolean enabled);
     [RaisesException] void setDefaultVideoPosterURL(DOMString poster);
+    [RaisesException] void setViewportEnabled(boolean enabled);
 
     // FIXME: This is a temporary flag and should be removed once accelerated
     // overflow scroll is ready (crbug.com/254111).
@@ -56,6 +57,5 @@
     void setCSSExclusionsEnabled(boolean enabled);
     void setExperimentalWebSocketEnabled(boolean enabled);
     void setLangAttributeAwareFormControlUIEnabled(boolean enabled);
-    void setLazyLayoutEnabled(boolean enabled);
     void setStyleScopedEnabled(boolean enabled);
 };
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index dba52a6..e3f3c82 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -41,6 +41,7 @@
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/SerializedScriptValue.h"
 #include "bindings/v8/V8ThrowException.h"
+#include "core/animation/DocumentTimeline.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
@@ -60,13 +61,15 @@
 #include "core/dom/TreeScope.h"
 #include "core/dom/ViewportArguments.h"
 #include "core/dom/shadow/ComposedShadowTreeWalker.h"
-#include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ScopeContentDistribution.h"
 #include "core/dom/shadow/SelectRuleFeatureSet.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
-#include "core/editing/SpellChecker.h"
+#include "core/editing/SpellCheckRequester.h"
 #include "core/editing/TextIterator.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/history/BackForwardController.h"
 #include "core/history/HistoryItem.h"
 #include "core/html/FormController.h"
@@ -84,8 +87,6 @@
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/DOMPoint.h"
@@ -109,7 +110,9 @@
 #include "core/platform/graphics/filters/FilterOperations.h"
 #include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
 #include "core/platform/mock/PlatformSpeechSynthesizerMock.h"
+#include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
+#include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderMenuList.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderTreeAsText.h"
@@ -118,6 +121,7 @@
 #include "core/workers/WorkerThread.h"
 #include "modules/speech/DOMWindowSpeechSynthesis.h"
 #include "modules/speech/SpeechSynthesis.h"
+#include "public/platform/WebLayer.h"
 #include "weborigin/SchemeRegistry.h"
 #include "wtf/dtoa.h"
 #include "wtf/text/StringBuffer.h"
@@ -165,12 +169,12 @@
     return true;
 }
 
-static SpellChecker* spellchecker(Document* document)
+static SpellCheckRequester* spellCheckRequester(Document* document)
 {
     if (!document || !document->frame() || !document->frame()->editor())
         return 0;
 
-    return document->frame()->editor()->spellChecker();
+    return &document->frame()->editor()->spellCheckRequester();
 }
 
 const char* Internals::internalsId = "internals";
@@ -182,9 +186,6 @@
 
 Internals::~Internals()
 {
-    if (m_scrollingCoordinator) {
-        m_scrollingCoordinator->removeTouchEventTargetRectsObserver(this);
-    }
 }
 
 void Internals::resetToConsistentState(Page* page)
@@ -199,7 +200,7 @@
     WebCore::Settings::setUsesOverlayScrollbars(false);
     delete s_pagePopupDriver;
     s_pagePopupDriver = 0;
-    page->chrome().client()->resetPagePopupDriver();
+    page->chrome().client().resetPagePopupDriver();
     if (!page->mainFrame()->editor()->isContinuousSpellCheckingEnabled())
         page->mainFrame()->editor()->toggleContinuousSpellChecking();
     if (page->mainFrame()->editor()->isOverwriteModeEnabled())
@@ -209,12 +210,8 @@
 Internals::Internals(Document* document)
     : ContextLifecycleObserver(document)
     , m_runtimeFlags(InternalRuntimeFlags::create())
-    , m_scrollingCoordinator(document->page()->scrollingCoordinator())
-    , m_touchEventTargetRectUpdateCount(0)
+    , m_scrollingCoordinator(document->page() ? document->page()->scrollingCoordinator() : 0)
 {
-    if (m_scrollingCoordinator) {
-        m_scrollingCoordinator->addTouchEventTargetRectsObserver(this);
-    }
 }
 
 Document* Internals::contextDocument() const
@@ -344,7 +341,7 @@
         return 0;
     }
 
-    return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForId(idValue);
+    return host->shadow()->ensureSelectFeatureSet().hasSelectorForId(idValue);
 }
 
 bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionState& es)
@@ -354,7 +351,7 @@
         return 0;
     }
 
-    return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForClass(className);
+    return host->shadow()->ensureSelectFeatureSet().hasSelectorForClass(className);
 }
 
 bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionState& es)
@@ -364,7 +361,7 @@
         return 0;
     }
 
-    return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForAttribute(attributeName);
+    return host->shadow()->ensureSelectFeatureSet().hasSelectorForAttribute(attributeName);
 }
 
 bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState& es)
@@ -374,7 +371,7 @@
         return 0;
     }
 
-    const SelectRuleFeatureSet& featureSet = host->shadow()->distributor().ensureSelectFeatureSet(host->shadow());
+    const SelectRuleFeatureSet& featureSet = host->shadow()->ensureSelectFeatureSet();
     if (pseudoClass == "checked")
         return featureSet.hasSelectorForChecked();
     if (pseudoClass == "enabled")
@@ -414,10 +411,10 @@
 unsigned Internals::numberOfActiveAnimations() const
 {
     Frame* contextFrame = frame();
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
-        if (AnimationController* controller = contextFrame->animation())
-            return controller->numberOfActiveAnimations(contextFrame->document());
-    }
+    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+        return frame()->document()->timeline()->numberOfActiveAnimationsForTesting();
+    if (AnimationController* controller = contextFrame->animation())
+        return controller->numberOfActiveAnimations(contextFrame->document());
     return 0;
 }
 
@@ -460,7 +457,9 @@
         return;
     }
 
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+        frame()->document()->timeline()->pauseAnimationsForTesting(pauseTime);
+    else
         frame()->animation()->pauseAnimationsForTesting(pauseTime);
 }
 
@@ -775,12 +774,12 @@
         return;
     Page* page = document->page();
     if (!enabled) {
-        page->chrome().client()->resetPagePopupDriver();
+        page->chrome().client().resetPagePopupDriver();
         return;
     }
     if (!s_pagePopupDriver)
         s_pagePopupDriver = MockPagePopupDriver::create(page->mainFrame()).leakPtr();
-    page->chrome().client()->setPagePopupDriver(s_pagePopupDriver);
+    page->chrome().client().setPagePopupDriver(s_pagePopupDriver);
 }
 
 PassRefPtr<PagePopupController> Internals::pagePopupController()
@@ -826,13 +825,13 @@
 
 PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionState& es)
 {
-    if (!document || !document->page() || !document->page()->inspectorController()) {
+    if (!document || !document->page()) {
         es.throwDOMException(InvalidAccessError);
         return ClientRectList::create();
     }
 
     Highlight highlight;
-    document->page()->inspectorController()->getHighlight(&highlight);
+    document->page()->inspectorController().getHighlight(&highlight);
     return ClientRectList::create(highlight.quads);
 }
 
@@ -852,6 +851,26 @@
     return node->document()->markers()->markersFor(node, markerTypes).size();
 }
 
+unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& es)
+{
+    if (!node) {
+        es.throwDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    // Only TextMatch markers can be active.
+    DocumentMarker::MarkerType markerType = DocumentMarker::TextMatch;
+    Vector<DocumentMarker*> markers = node->document()->markers()->markersFor(node, markerType);
+
+    unsigned activeMarkerCount = 0;
+    for (Vector<DocumentMarker*>::iterator iter = markers.begin(); iter != markers.end(); ++iter) {
+        if ((*iter)->activeMatch())
+            activeMarkerCount++;
+    }
+
+    return activeMarkerCount;
+}
+
 DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionState& es)
 {
     if (!node) {
@@ -893,6 +912,16 @@
     range->ownerDocument()->markers()->addTextMatchMarker(range, isActive);
 }
 
+void Internals::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active, ExceptionState& es)
+{
+    if (!node) {
+        es.throwDOMException(InvalidAccessError);
+        return;
+    }
+
+    node->document()->markers()->setMarkersActive(node, startOffset, endOffset, active);
+}
+
 void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionState& es)
 {
     if (!document || !document->view()) {
@@ -940,7 +969,7 @@
     page->setPagination(pagination);
 }
 
-String Internals::configurationForViewport(Document* document, float, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionState& es)
+String Internals::viewportAsText(Document* document, float, int availableWidth, int availableHeight, ExceptionState& es)
 {
     if (!document || !document->page()) {
         es.throwDOMException(InvalidAccessError);
@@ -954,7 +983,7 @@
     document->styleResolver()->viewportStyleResolver()->resolve();
 
     ViewportArguments arguments = page->viewportArguments();
-    PageScaleConstraints constraints = arguments.resolve(initialViewportSize, FloatSize(deviceWidth, deviceHeight), 980 /* defaultLayoutWidthForNonMobilePages */);
+    PageScaleConstraints constraints = arguments.resolve(initialViewportSize, 980 /* defaultLayoutWidthForNonMobilePages */);
 
     constraints.fitToContentsWidth(constraints.layoutSize.width(), availableWidth);
 
@@ -1092,6 +1121,9 @@
         return 0;
     }
 
+    // TextIterator depends on Layout information, make sure layout it up to date.
+    scope->document()->updateLayoutIgnorePendingStylesheets();
+
     return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
 }
 
@@ -1102,6 +1134,9 @@
         return 0;
     }
 
+    // TextIterator depends on Layout information, make sure layout it up to date.
+    scope->document()->updateLayoutIgnorePendingStylesheets();
+
     size_t location = 0;
     size_t unusedLength = 0;
     TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength);
@@ -1115,6 +1150,9 @@
         return 0;
     }
 
+    // TextIterator depends on Layout information, make sure layout it up to date.
+    scope->document()->updateLayoutIgnorePendingStylesheets();
+
     size_t unusedLocation = 0;
     size_t length = 0;
     TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length);
@@ -1235,26 +1273,26 @@
 
 int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionState& es)
 {
-    SpellChecker* checker = spellchecker(document);
+    SpellCheckRequester* requester = spellCheckRequester(document);
 
-    if (!checker) {
+    if (!requester) {
         es.throwDOMException(InvalidAccessError);
         return -1;
     }
 
-    return checker->lastRequestSequence();
+    return requester->lastRequestSequence();
 }
 
 int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionState& es)
 {
-    SpellChecker* checker = spellchecker(document);
+    SpellCheckRequester* requester = spellCheckRequester(document);
 
-    if (!checker) {
+    if (!requester) {
         es.throwDOMException(InvalidAccessError);
         return -1;
     }
 
-    return checker->lastProcessedSequence();
+    return requester->lastProcessedSequence();
 }
 
 Vector<String> Internals::userPreferredLanguages() const
@@ -1294,7 +1332,105 @@
     return count;
 }
 
-LayerRectList* Internals::touchEventTargetLayerRects(Document* document, ExceptionState& es)
+static RenderLayer* findRenderLayerForGraphicsLayer(RenderLayer* searchRoot, GraphicsLayer* graphicsLayer, String* layerType)
+{
+    if (searchRoot->backing() && graphicsLayer == searchRoot->backing()->graphicsLayer())
+        return searchRoot;
+
+    if (graphicsLayer == searchRoot->layerForScrolling()) {
+        *layerType = "scrolling";
+        return searchRoot;
+    }
+
+    if (graphicsLayer == searchRoot->layerForHorizontalScrollbar()) {
+        *layerType = "horizontalScrollbar";
+        return searchRoot;
+    }
+
+    if (graphicsLayer == searchRoot->layerForVerticalScrollbar()) {
+        *layerType = "verticalScrollbar";
+        return searchRoot;
+    }
+
+    if (graphicsLayer == searchRoot->layerForScrollCorner()) {
+        *layerType = "scrollCorner";
+        return searchRoot;
+    }
+
+    for (RenderLayer* child = searchRoot->firstChild(); child; child = child->nextSibling()) {
+        RenderLayer* foundLayer = findRenderLayerForGraphicsLayer(child, graphicsLayer, layerType);
+        if (foundLayer)
+            return foundLayer;
+    }
+
+    return 0;
+}
+
+// Given a vector of rects, merge those that are adjacent, leaving empty rects
+// in the place of no longer used slots. This is intended to simplify the list
+// 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)
+{
+    for (size_t i = 0; i < rects.size(); ++i) {
+        if (rects[i].isEmpty())
+            continue;
+        bool updated;
+        do {
+            updated = false;
+            for (size_t j = i+1; j < rects.size(); ++j) {
+                if (rects[j].isEmpty())
+                    continue;
+                // Try to merge rects[j] into rects[i] along the 4 possible edges.
+                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();
+                        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();
+                        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();
+                        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();
+                        updated = true;
+                    }
+                }
+            }
+        } while (updated);
+    }
+}
+
+static void accumulateLayerRectList(RenderLayerCompositor* compositor, GraphicsLayer* graphicsLayer, LayerRectList* rects)
+{
+    WebKit::WebVector<WebKit::WebRect> layerRects = graphicsLayer->platformLayer()->touchEventHandlerRegion();
+    if (!layerRects.isEmpty()) {
+        mergeRects(layerRects);
+        String layerType;
+        RenderLayer* renderLayer = findRenderLayerForGraphicsLayer(compositor->rootRenderLayer(), graphicsLayer, &layerType);
+        Node* node = renderLayer ? renderLayer->renderer()->node() : 0;
+        for (size_t i = 0; i < layerRects.size(); ++i) {
+            if (!layerRects[i].isEmpty())
+                rects->append(node, layerType, ClientRect::create(layerRects[i]));
+        }
+    }
+
+    size_t numChildren = graphicsLayer->children().size();
+    for (size_t i = 0; i < numChildren; ++i)
+        accumulateLayerRectList(compositor, graphicsLayer->children()[i], rects);
+}
+
+PassRefPtr<LayerRectList> Internals::touchEventTargetLayerRects(Document* document, ExceptionState& es)
 {
     if (!document || !document->view() || !document->page() || document != contextDocument()) {
         es.throwDOMException(InvalidAccessError);
@@ -1304,38 +1440,18 @@
     // Do any pending layouts (which may call touchEventTargetRectsChange) to ensure this
     // really takes any previous changes into account.
     document->updateLayout();
-    return m_currentTouchEventRects.get();
-}
 
-unsigned Internals::touchEventTargetLayerRectsUpdateCount(Document* document, ExceptionState& es)
-{
-    if (!document || !document->view() || !document->page() || document != contextDocument()) {
-        es.throwDOMException(InvalidAccessError);
-        return 0;
-    }
-
-    // Do any pending layouts to ensure this really takes any previous changes into account.
-    document->updateLayout();
-
-    return m_touchEventTargetRectUpdateCount;
-}
-
-void Internals::touchEventTargetRectsChanged(const LayerHitTestRects& rects)
-{
-    // When profiling content_shell, it can be handy to exclude this time (since it's only
-    // present for testing / debugging).
-    TRACE_EVENT0("input", "Internals::touchEventTargetRectsChanged");
-
-    m_touchEventTargetRectUpdateCount++;
-
-    // Since it's not safe to hang onto the pointers in a LayerHitTestRects, we immediately
-    // copy into a LayerRectList.
-    m_currentTouchEventRects = LayerRectList::create();
-    for (LayerHitTestRects::const_iterator iter = rects.begin(); iter != rects.end(); ++iter) {
-        for (size_t i = 0; i < iter->value.size(); ++i) {
-            m_currentTouchEventRects->append(iter->key->renderer()->node(), ClientRect::create(enclosingIntRect(iter->value[i])));
+    if (RenderView* view = document->renderView()) {
+        if (RenderLayerCompositor* compositor = view->compositor()) {
+            if (GraphicsLayer* rootLayer = compositor->rootGraphicsLayer()) {
+                RefPtr<LayerRectList> rects = LayerRectList::create();
+                accumulateLayerRectList(compositor, rootLayer, rects.get());
+                return rects;
+            }
         }
     }
+
+    return 0;
 }
 
 PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
@@ -1390,14 +1506,12 @@
 
 void Internals::emitInspectorDidBeginFrame()
 {
-    InspectorController* inspectorController = contextDocument()->frame()->page()->inspectorController();
-    inspectorController->didBeginFrame();
+    contextDocument()->page()->inspectorController().didBeginFrame();
 }
 
 void Internals::emitInspectorDidCancelFrame()
 {
-    InspectorController* inspectorController = contextDocument()->frame()->page()->inspectorController();
-    inspectorController->didCancelFrame();
+    contextDocument()->page()->inspectorController().didCancelFrame();
 }
 
 bool Internals::hasSpellingMarker(Document* document, int from, int length, ExceptionState&)
@@ -1474,11 +1588,11 @@
 
     OwnPtr<InspectorFrontendClientLocal> frontendClient = adoptPtr(new InspectorFrontendClientLocal(page->inspectorController(), frontendPage));
 
-    frontendPage->inspectorController()->setInspectorFrontendClient(frontendClient.release());
+    frontendPage->inspectorController().setInspectorFrontendClient(frontendClient.release());
 
     m_frontendChannel = adoptPtr(new InspectorFrontendChannelDummy(frontendPage));
 
-    page->inspectorController()->connectFrontend(m_frontendChannel.get());
+    page->inspectorController().connectFrontend(m_frontendChannel.get());
 
     return m_frontendWindow;
 }
@@ -1489,7 +1603,7 @@
     ASSERT(page);
     ASSERT(m_frontendWindow);
 
-    page->inspectorController()->disconnectFrontend();
+    page->inspectorController().disconnectFrontend();
 
     m_frontendChannel.release();
 
@@ -1510,11 +1624,11 @@
 void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionState& es)
 {
     Page* page = contextDocument()->frame()->page();
-    if (!page || !page->inspectorController()) {
+    if (!page) {
         es.throwDOMException(InvalidAccessError);
         return;
     }
-    page->inspectorController()->setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize);
+    page->inspectorController().setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize);
 }
 
 bool Internals::hasGrammarMarker(Document* document, int from, int length, ExceptionState&)
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index bde21e2..02ed1a3 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -33,10 +33,10 @@
 #include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/NodeList.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include <wtf/ArrayBuffer.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/ArrayBuffer.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -67,8 +67,7 @@
 class TypeConversions;
 
 class Internals : public RefCounted<Internals>
-    , public ContextLifecycleObserver
-    , public ScrollingCoordinator::TouchEventTargetRectsObserver {
+    , public ContextLifecycleObserver {
 public:
     static PassRefPtr<Internals> create(Document*);
     virtual ~Internals();
@@ -144,14 +143,16 @@
     PassRefPtr<ClientRectList> inspectorHighlightRects(Document*, ExceptionState&);
 
     unsigned markerCountForNode(Node*, const String&, ExceptionState&);
+    unsigned activeMarkerCountForNode(Node*, ExceptionState&);
     PassRefPtr<Range> markerRangeForNode(Node*, const String& markerType, unsigned index, ExceptionState&);
     String markerDescriptionForNode(Node*, const String& markerType, unsigned index, ExceptionState&);
     void addTextMatchMarker(const Range*, bool isActive);
+    void setMarkersActive(Node*, unsigned startOffset, unsigned endOffset, bool, ExceptionState&);
 
     void setScrollViewPosition(Document*, long x, long y, ExceptionState&);
     void setPagination(Document* document, const String& mode, int gap, ExceptionState& ec) { setPagination(document, mode, gap, 0, ec); }
     void setPagination(Document*, const String& mode, int gap, int pageLength, ExceptionState&);
-    String configurationForViewport(Document*, float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionState&);
+    String viewportAsText(Document*, float devicePixelRatio, int availableWidth, int availableHeight, ExceptionState&);
 
     bool wasLastChangeUserEdit(Element* textField, ExceptionState&);
     bool elementShouldAutoComplete(Element* inputElement, ExceptionState&);
@@ -182,9 +183,7 @@
 
     unsigned wheelEventHandlerCount(Document*, ExceptionState&);
     unsigned touchEventHandlerCount(Document*, ExceptionState&);
-    LayerRectList* touchEventTargetLayerRects(Document*, ExceptionState&);
-    unsigned touchEventTargetLayerRectsUpdateCount(Document*, ExceptionState&);
-    virtual void touchEventTargetRectsChanged(const LayerHitTestRects&);
+    PassRefPtr<LayerRectList> touchEventTargetLayerRects(Document*, ExceptionState&);
 
     // This is used to test rect based hit testing like what's done on touch screens.
     PassRefPtr<NodeList> nodesFromRect(Document*, int x, int y, unsigned topPadding, unsigned rightPadding,
@@ -307,8 +306,6 @@
     OwnPtr<InspectorFrontendChannelDummy> m_frontendChannel;
     RefPtr<InternalRuntimeFlags> m_runtimeFlags;
     RefPtr<ScrollingCoordinator> m_scrollingCoordinator;
-    int m_touchEventTargetRectUpdateCount;
-    RefPtr<LayerRectList> m_currentTouchEventRects;
     RefPtr<InternalProfilers> m_profilers;
 };
 
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index d521c04..3ebeb51 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -96,20 +96,20 @@
     [RaisesException] ClientRectList inspectorHighlightRects(Document document);
 
     [RaisesException] unsigned long markerCountForNode(Node node, DOMString markerType);
+    [RaisesException] unsigned long activeMarkerCountForNode(Node node);
     [RaisesException] Range markerRangeForNode(Node node, DOMString markerType, unsigned long index);
     [RaisesException] DOMString markerDescriptionForNode(Node node, DOMString markerType, unsigned long index);
     void addTextMatchMarker(Range range, boolean isActive);
+    [RaisesException] void setMarkersActive(Node node, unsigned long startOffset, unsigned long endOffset, boolean active);
 
     [RaisesException] void setScrollViewPosition(Document document, long x, long y);
 
     [RaisesException] void setPagination(Document document, DOMString mode, long gap, optional long pageLength);
 
-    [RaisesException] DOMString configurationForViewport(Document document,
-                                       float devicePixelRatio,
-                                       long deviceWidth,
-                                       long deviceHeight,
-                                       long availableWidth,
-                                       long availableHeight);
+    [RaisesException] DOMString viewportAsText(Document document,
+                                               float devicePixelRatio,
+                                               long availableWidth,
+                                               long availableHeight);
 
     [RaisesException] boolean wasLastChangeUserEdit(Element textField);
     [RaisesException] boolean elementShouldAutoComplete(Element inputElement);
@@ -142,7 +142,7 @@
     [RaisesException] unsigned long wheelEventHandlerCount(Document document);
     [RaisesException] unsigned long touchEventHandlerCount(Document document);
     [RaisesException] LayerRectList touchEventTargetLayerRects(Document document);
-    [RaisesException] unsigned long touchEventTargetLayerRectsUpdateCount(Document document);
+
 
     [RaisesException] NodeList nodesFromRect(Document document, long x, long y,
         unsigned long topPadding, unsigned long rightPadding, unsigned long bottomPadding, unsigned long leftPadding,
diff --git a/Source/core/testing/LayerRect.h b/Source/core/testing/LayerRect.h
index f945681..4827fee 100644
--- a/Source/core/testing/LayerRect.h
+++ b/Source/core/testing/LayerRect.h
@@ -36,6 +36,7 @@
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -43,22 +44,25 @@
 
 class LayerRect : public RefCounted<LayerRect> {
 public:
-    static PassRefPtr<LayerRect> create(PassRefPtr<Node> node, PassRefPtr<ClientRect> rect)
+    static PassRefPtr<LayerRect> create(PassRefPtr<Node> node, const String& layerType, PassRefPtr<ClientRect> rect)
     {
-        return adoptRef(new LayerRect(node, rect));
+        return adoptRef(new LayerRect(node, layerType, rect));
     }
 
     Node* layerRootNode() const { return m_layerRootNode.get(); }
+    String layerType() const { return m_layerType; }
     ClientRect* layerRelativeRect() const { return m_rect.get(); }
 
 private:
-    LayerRect(PassRefPtr<Node> node, PassRefPtr<ClientRect> rect)
+    LayerRect(PassRefPtr<Node> node, const String& layerName, PassRefPtr<ClientRect> rect)
         : m_layerRootNode(node)
+        , m_layerType(layerName)
         , m_rect(rect)
     {
     }
 
     RefPtr<Node> m_layerRootNode;
+    String m_layerType;
     RefPtr<ClientRect> m_rect;
 };
 
diff --git a/Source/core/testing/LayerRect.idl b/Source/core/testing/LayerRect.idl
index 50994ab..8a4d8e1 100644
--- a/Source/core/testing/LayerRect.idl
+++ b/Source/core/testing/LayerRect.idl
@@ -31,5 +31,6 @@
 [
 ] interface LayerRect {
     readonly attribute Node layerRootNode;
+    readonly attribute DOMString layerType;
     readonly attribute ClientRect layerRelativeRect;
 };
diff --git a/Source/core/testing/LayerRectList.cpp b/Source/core/testing/LayerRectList.cpp
index 578b407..4e8b991 100644
--- a/Source/core/testing/LayerRectList.cpp
+++ b/Source/core/testing/LayerRectList.cpp
@@ -58,9 +58,9 @@
     return m_list[index].get();
 }
 
-void LayerRectList::append(PassRefPtr<Node> layerRootNode, PassRefPtr<ClientRect> layerRelativeRect)
+void LayerRectList::append(PassRefPtr<Node> layerRootNode, const String& layerType, PassRefPtr<ClientRect> layerRelativeRect)
 {
-    m_list.append(LayerRect::create(layerRootNode, layerRelativeRect));
+    m_list.append(LayerRect::create(layerRootNode, layerType, layerRelativeRect));
 }
 
 } // namespace WebCore
diff --git a/Source/core/testing/LayerRectList.h b/Source/core/testing/LayerRectList.h
index d46d1dc..ec1582b 100644
--- a/Source/core/testing/LayerRectList.h
+++ b/Source/core/testing/LayerRectList.h
@@ -35,6 +35,7 @@
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -50,7 +51,7 @@
 
     unsigned length() const;
     LayerRect* item(unsigned index);
-    void append(PassRefPtr<Node> layerRootNode, PassRefPtr<ClientRect> layerRelativeRect);
+    void append(PassRefPtr<Node> layerRootNode, const String& layerName, PassRefPtr<ClientRect> layerRelativeRect);
 
 private:
     LayerRectList();
diff --git a/Source/core/testing/MallocStatistics.h b/Source/core/testing/MallocStatistics.h
index 3f07bbd..bc4da85 100644
--- a/Source/core/testing/MallocStatistics.h
+++ b/Source/core/testing/MallocStatistics.h
@@ -26,9 +26,9 @@
 #ifndef MallocStatistics_h
 #define MallocStatistics_h
 
-#include <wtf/FastMalloc.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/FastMalloc.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/testing/MockPagePopupDriver.cpp b/Source/core/testing/MockPagePopupDriver.cpp
index 767c2da..966897b 100644
--- a/Source/core/testing/MockPagePopupDriver.cpp
+++ b/Source/core/testing/MockPagePopupDriver.cpp
@@ -68,7 +68,7 @@
     m_iframe->setInlineStyleProperty(CSSPropertyLeft, originBoundsInRootView.x(), CSSPrimitiveValue::CSS_PX, true);
     m_iframe->setInlineStyleProperty(CSSPropertyTop, originBoundsInRootView.maxY(), CSSPrimitiveValue::CSS_PX, true);
     if (document->body())
-        document->body()->appendChild(m_iframe.get(), ASSERT_NO_EXCEPTION, AttachLazily);
+        document->body()->appendChild(m_iframe.get());
     Frame* contentFrame = m_iframe->contentFrame();
     DocumentWriter* writer = contentFrame->loader()->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
     const char scriptToSetUpPagePopupController[] = "<script>window.pagePopupController = parent.internals.pagePopupController;</script>";
diff --git a/Source/core/testing/MockPagePopupDriver.h b/Source/core/testing/MockPagePopupDriver.h
index 154815b..e1f90aa 100644
--- a/Source/core/testing/MockPagePopupDriver.h
+++ b/Source/core/testing/MockPagePopupDriver.h
@@ -28,7 +28,7 @@
 
 #include "core/page/PagePopupClient.h"
 #include "core/page/PagePopupDriver.h"
-#include <wtf/RefPtr.h>
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/testing/TypeConversions.h b/Source/core/testing/TypeConversions.h
index b8cde7b..10f675f 100644
--- a/Source/core/testing/TypeConversions.h
+++ b/Source/core/testing/TypeConversions.h
@@ -26,9 +26,9 @@
 #ifndef TypeConversions_h
 #define TypeConversions_h
 
-#include <wtf/FastMalloc.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/FastMalloc.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_derived.target.darwin-arm.mk
index d45c92a..f5167f5 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_derived.target.darwin-arm.mk
@@ -202,6 +202,7 @@
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
+	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
@@ -218,6 +219,7 @@
 	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptInstance.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
+	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
@@ -414,7 +416,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -581,7 +582,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_derived.target.darwin-mips.mk
index 214a295..26a31af 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_derived.target.darwin-mips.mk
@@ -202,6 +202,7 @@
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
+	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
@@ -218,6 +219,7 @@
 	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptInstance.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
+	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
@@ -414,7 +416,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -581,7 +582,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_derived.target.darwin-x86.mk
index b398af2..d4b5bc4 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_derived.target.darwin-x86.mk
@@ -202,6 +202,7 @@
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
+	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
@@ -218,6 +219,7 @@
 	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptInstance.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
+	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
@@ -416,7 +418,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -586,7 +587,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
index d45c92a..f5167f5 100644
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ b/Source/core/webcore_derived.target.linux-arm.mk
@@ -202,6 +202,7 @@
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
+	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
@@ -218,6 +219,7 @@
 	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptInstance.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
+	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
@@ -414,7 +416,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -581,7 +582,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
index 214a295..26a31af 100644
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ b/Source/core/webcore_derived.target.linux-mips.mk
@@ -202,6 +202,7 @@
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
+	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
@@ -218,6 +219,7 @@
 	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptInstance.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
+	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
@@ -414,7 +416,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -581,7 +582,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
index b398af2..d4b5bc4 100644
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ b/Source/core/webcore_derived.target.linux-x86.mk
@@ -202,6 +202,7 @@
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
+	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
 	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
@@ -218,6 +219,7 @@
 	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptInstance.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
+	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
@@ -416,7 +418,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -586,7 +587,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index 9fc0709..440660b 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -52,6 +52,8 @@
 	third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
@@ -148,6 +150,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
@@ -178,7 +181,8 @@
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp \
-	third_party/WebKit/Source/core/dom/shadow/ContentDistributor.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ScopeContentDistribution.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp \
 	third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp \
 	third_party/WebKit/Source/core/dom/shadow/SelectRuleFeatureSet.cpp \
@@ -254,7 +258,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -412,7 +415,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index afccbd2..f8bad83 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -52,6 +52,8 @@
 	third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
@@ -148,6 +150,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
@@ -178,7 +181,8 @@
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp \
-	third_party/WebKit/Source/core/dom/shadow/ContentDistributor.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ScopeContentDistribution.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp \
 	third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp \
 	third_party/WebKit/Source/core/dom/shadow/SelectRuleFeatureSet.cpp \
@@ -254,7 +258,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -412,7 +415,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 332d6c5..3912de7 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -52,6 +52,8 @@
 	third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
@@ -148,6 +150,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
@@ -178,7 +181,8 @@
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp \
-	third_party/WebKit/Source/core/dom/shadow/ContentDistributor.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ScopeContentDistribution.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp \
 	third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp \
 	third_party/WebKit/Source/core/dom/shadow/SelectRuleFeatureSet.cpp \
@@ -256,7 +260,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -417,7 +420,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index 9fc0709..440660b 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -52,6 +52,8 @@
 	third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
@@ -148,6 +150,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
@@ -178,7 +181,8 @@
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp \
-	third_party/WebKit/Source/core/dom/shadow/ContentDistributor.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ScopeContentDistribution.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp \
 	third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp \
 	third_party/WebKit/Source/core/dom/shadow/SelectRuleFeatureSet.cpp \
@@ -254,7 +258,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -412,7 +415,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index afccbd2..f8bad83 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -52,6 +52,8 @@
 	third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
@@ -148,6 +150,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
@@ -178,7 +181,8 @@
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp \
-	third_party/WebKit/Source/core/dom/shadow/ContentDistributor.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ScopeContentDistribution.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp \
 	third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp \
 	third_party/WebKit/Source/core/dom/shadow/SelectRuleFeatureSet.cpp \
@@ -254,7 +258,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -412,7 +415,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 332d6c5..3912de7 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -52,6 +52,8 @@
 	third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
@@ -148,6 +150,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
@@ -178,7 +181,8 @@
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp \
-	third_party/WebKit/Source/core/dom/shadow/ContentDistributor.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
+	third_party/WebKit/Source/core/dom/shadow/ScopeContentDistribution.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp \
 	third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp \
 	third_party/WebKit/Source/core/dom/shadow/SelectRuleFeatureSet.cpp \
@@ -256,7 +260,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -417,7 +420,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index 3fc4459..3d57f44 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -358,7 +358,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -516,7 +515,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index cb8f08f..3a234d6 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -358,7 +358,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -516,7 +515,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index b0cb85b..01dbc6c 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -360,7 +360,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -521,7 +520,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index 3fc4459..3d57f44 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -358,7 +358,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -516,7 +515,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index cb8f08f..3a234d6 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -358,7 +358,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -516,7 +515,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index b0cb85b..01dbc6c 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -360,7 +360,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -521,7 +520,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
index 20d5608..ccc3b35 100644
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ b/Source/core/webcore_platform.target.darwin-arm.mk
@@ -51,6 +51,7 @@
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
 	third_party/WebKit/Source/core/platform/Partitions.cpp \
+	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
@@ -63,6 +64,9 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -128,16 +132,12 @@
 	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/PasteboardChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -292,6 +292,7 @@
 	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
+	third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
@@ -405,7 +406,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -564,7 +564,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
index a176710..a1c43b5 100644
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ b/Source/core/webcore_platform.target.darwin-mips.mk
@@ -51,6 +51,7 @@
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
 	third_party/WebKit/Source/core/platform/Partitions.cpp \
+	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
@@ -63,6 +64,9 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -128,16 +132,12 @@
 	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/PasteboardChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -292,6 +292,7 @@
 	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
+	third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
@@ -405,7 +406,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -564,7 +564,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
index cd3fffc..0b8cec3 100644
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ b/Source/core/webcore_platform.target.darwin-x86.mk
@@ -51,6 +51,7 @@
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
 	third_party/WebKit/Source/core/platform/Partitions.cpp \
+	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
@@ -63,6 +64,9 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -128,16 +132,12 @@
 	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/PasteboardChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -292,6 +292,7 @@
 	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
+	third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
@@ -407,7 +408,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -569,7 +569,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
index 20d5608..ccc3b35 100644
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ b/Source/core/webcore_platform.target.linux-arm.mk
@@ -51,6 +51,7 @@
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
 	third_party/WebKit/Source/core/platform/Partitions.cpp \
+	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
@@ -63,6 +64,9 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -128,16 +132,12 @@
 	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/PasteboardChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -292,6 +292,7 @@
 	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
+	third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
@@ -405,7 +406,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -564,7 +564,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
index a176710..a1c43b5 100644
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ b/Source/core/webcore_platform.target.linux-mips.mk
@@ -51,6 +51,7 @@
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
 	third_party/WebKit/Source/core/platform/Partitions.cpp \
+	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
@@ -63,6 +64,9 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -128,16 +132,12 @@
 	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/PasteboardChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -292,6 +292,7 @@
 	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
+	third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
@@ -405,7 +406,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -564,7 +564,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
index cd3fffc..0b8cec3 100644
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ b/Source/core/webcore_platform.target.linux-x86.mk
@@ -51,6 +51,7 @@
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
 	third_party/WebKit/Source/core/platform/Partitions.cpp \
+	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
@@ -63,6 +64,9 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp \
+	third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -128,16 +132,12 @@
 	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/PasteboardChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -292,6 +292,7 @@
 	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
+	third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
@@ -407,7 +408,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -569,7 +569,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-arm.mk b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
index 8dac89c..1aa861f 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
@@ -106,7 +106,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -264,7 +263,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-mips.mk b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
index deeb00b..d5c67d6 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
@@ -106,7 +106,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -264,7 +263,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-x86.mk b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
index 3f7b461..91dcd7b 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
@@ -108,7 +108,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -269,7 +268,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-arm.mk b/Source/core/webcore_platform_geometry.target.linux-arm.mk
index 8dac89c..1aa861f 100644
--- a/Source/core/webcore_platform_geometry.target.linux-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-arm.mk
@@ -106,7 +106,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -264,7 +263,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-mips.mk b/Source/core/webcore_platform_geometry.target.linux-mips.mk
index deeb00b..d5c67d6 100644
--- a/Source/core/webcore_platform_geometry.target.linux-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-mips.mk
@@ -106,7 +106,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -264,7 +263,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-x86.mk b/Source/core/webcore_platform_geometry.target.linux-x86.mk
index 3f7b461..91dcd7b 100644
--- a/Source/core/webcore_platform_geometry.target.linux-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-x86.mk
@@ -108,7 +108,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -269,7 +268,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index 5e59107..f873cf1 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/AccessibilityTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
@@ -221,7 +222,7 @@
 	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
+	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
 	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
@@ -239,6 +240,22 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FontResource.cpp \
+	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/RawResource.cpp \
+	third_party/WebKit/Source/core/fetch/Resource.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
+	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
+	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
@@ -339,8 +356,6 @@
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
@@ -348,25 +363,11 @@
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
-	third_party/WebKit/Source/core/loader/appcache/DOMApplicationCache.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/loader/cache/CSSStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -382,6 +383,8 @@
 	third_party/WebKit/Source/core/page/DOMTimer.cpp \
 	third_party/WebKit/Source/core/page/DOMWindow.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowProperty.cpp \
@@ -396,12 +399,12 @@
 	third_party/WebKit/Source/core/page/FrameView.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/page/ImageBitmapFactories.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
 	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
+	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
@@ -575,7 +578,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -734,7 +736,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index 5188e64..2a5980b 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/AccessibilityTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
@@ -221,7 +222,7 @@
 	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
+	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
 	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
@@ -239,6 +240,22 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FontResource.cpp \
+	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/RawResource.cpp \
+	third_party/WebKit/Source/core/fetch/Resource.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
+	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
+	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
@@ -339,8 +356,6 @@
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
@@ -348,25 +363,11 @@
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
-	third_party/WebKit/Source/core/loader/appcache/DOMApplicationCache.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/loader/cache/CSSStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -382,6 +383,8 @@
 	third_party/WebKit/Source/core/page/DOMTimer.cpp \
 	third_party/WebKit/Source/core/page/DOMWindow.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowProperty.cpp \
@@ -396,12 +399,12 @@
 	third_party/WebKit/Source/core/page/FrameView.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/page/ImageBitmapFactories.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
 	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
+	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
@@ -575,7 +578,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -734,7 +736,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index 1081dcc..8de370e 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/AccessibilityTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
@@ -221,7 +222,7 @@
 	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
+	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
 	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
@@ -239,6 +240,22 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FontResource.cpp \
+	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/RawResource.cpp \
+	third_party/WebKit/Source/core/fetch/Resource.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
+	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
+	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
@@ -339,8 +356,6 @@
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
@@ -348,25 +363,11 @@
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
-	third_party/WebKit/Source/core/loader/appcache/DOMApplicationCache.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/loader/cache/CSSStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -382,6 +383,8 @@
 	third_party/WebKit/Source/core/page/DOMTimer.cpp \
 	third_party/WebKit/Source/core/page/DOMWindow.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowProperty.cpp \
@@ -396,12 +399,12 @@
 	third_party/WebKit/Source/core/page/FrameView.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/page/ImageBitmapFactories.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
 	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
+	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
@@ -577,7 +580,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -739,7 +741,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index 5e59107..f873cf1 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/AccessibilityTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
@@ -221,7 +222,7 @@
 	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
+	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
 	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
@@ -239,6 +240,22 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FontResource.cpp \
+	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/RawResource.cpp \
+	third_party/WebKit/Source/core/fetch/Resource.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
+	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
+	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
@@ -339,8 +356,6 @@
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
@@ -348,25 +363,11 @@
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
-	third_party/WebKit/Source/core/loader/appcache/DOMApplicationCache.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/loader/cache/CSSStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -382,6 +383,8 @@
 	third_party/WebKit/Source/core/page/DOMTimer.cpp \
 	third_party/WebKit/Source/core/page/DOMWindow.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowProperty.cpp \
@@ -396,12 +399,12 @@
 	third_party/WebKit/Source/core/page/FrameView.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/page/ImageBitmapFactories.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
 	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
+	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
@@ -575,7 +578,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -734,7 +736,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index 5188e64..2a5980b 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/AccessibilityTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
@@ -221,7 +222,7 @@
 	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
+	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
 	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
@@ -239,6 +240,22 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FontResource.cpp \
+	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/RawResource.cpp \
+	third_party/WebKit/Source/core/fetch/Resource.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
+	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
+	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
@@ -339,8 +356,6 @@
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
@@ -348,25 +363,11 @@
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
-	third_party/WebKit/Source/core/loader/appcache/DOMApplicationCache.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/loader/cache/CSSStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -382,6 +383,8 @@
 	third_party/WebKit/Source/core/page/DOMTimer.cpp \
 	third_party/WebKit/Source/core/page/DOMWindow.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowProperty.cpp \
@@ -396,12 +399,12 @@
 	third_party/WebKit/Source/core/page/FrameView.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/page/ImageBitmapFactories.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
 	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
+	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
@@ -575,7 +578,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -734,7 +736,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index 1081dcc..8de370e 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/AccessibilityTableHeaderContainer.cpp \
 	third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
@@ -221,7 +222,7 @@
 	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
+	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
 	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
@@ -239,6 +240,22 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FontResource.cpp \
+	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/RawResource.cpp \
+	third_party/WebKit/Source/core/fetch/Resource.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
+	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
+	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
@@ -339,8 +356,6 @@
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
-	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
@@ -348,25 +363,11 @@
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
-	third_party/WebKit/Source/core/loader/appcache/DOMApplicationCache.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/loader/cache/CSSStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
@@ -382,6 +383,8 @@
 	third_party/WebKit/Source/core/page/DOMTimer.cpp \
 	third_party/WebKit/Source/core/page/DOMWindow.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowProperty.cpp \
@@ -396,12 +399,12 @@
 	third_party/WebKit/Source/core/page/FrameView.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/page/ImageBitmapFactories.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
 	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
+	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
@@ -577,7 +580,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -739,7 +741,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index ee8fc29..e87a726 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -30,6 +30,7 @@
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
+	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
@@ -76,8 +77,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLazyBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -136,8 +137,10 @@
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.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 \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
@@ -245,7 +248,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -403,7 +405,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index 8c1050e..27336d3 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -30,6 +30,7 @@
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
+	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
@@ -76,8 +77,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLazyBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -136,8 +137,10 @@
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.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 \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
@@ -245,7 +248,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -403,7 +405,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 0bf4672..2afffaf 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -30,6 +30,7 @@
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
+	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
@@ -76,8 +77,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLazyBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -136,8 +137,10 @@
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.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 \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
@@ -248,7 +251,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -410,7 +412,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index ee8fc29..e87a726 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -30,6 +30,7 @@
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
+	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
@@ -76,8 +77,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLazyBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -136,8 +137,10 @@
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.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 \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
@@ -245,7 +248,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -403,7 +405,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index 8c1050e..27336d3 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -30,6 +30,7 @@
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
+	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
@@ -76,8 +77,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLazyBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -136,8 +137,10 @@
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.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 \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
@@ -245,7 +248,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -403,7 +405,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 0bf4672..2afffaf 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -30,6 +30,7 @@
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
+	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
@@ -76,8 +77,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLazyBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -136,8 +137,10 @@
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.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 \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
@@ -248,7 +251,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -410,7 +412,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 1abe037..31bd1e0 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -315,7 +315,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -473,7 +472,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index 05c3429..9e8e28e 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -315,7 +315,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -473,7 +472,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 79ff516..0b57271 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -317,7 +317,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -478,7 +477,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 1abe037..31bd1e0 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -315,7 +315,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -473,7 +472,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index 05c3429..9e8e28e 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -315,7 +315,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -473,7 +472,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 79ff516..0b57271 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -317,7 +317,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
@@ -478,7 +477,6 @@
 	'-DENABLE_MEDIA_CAPTURE=1' \
 	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_PRINTING=0' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
diff --git a/Source/core/workers/AbstractWorker.cpp b/Source/core/workers/AbstractWorker.cpp
index e4b9c7f..0d3907d 100644
--- a/Source/core/workers/AbstractWorker.cpp
+++ b/Source/core/workers/AbstractWorker.cpp
@@ -57,24 +57,25 @@
 KURL AbstractWorker::resolveURL(const String& url, ExceptionState& es)
 {
     if (url.isEmpty()) {
-        es.throwDOMException(SyntaxError);
+        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 = scriptExecutionContext()->completeURL(url);
     if (!scriptURL.isValid()) {
-        es.throwDOMException(SyntaxError);
+        es.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 (!scriptExecutionContext()->securityOrigin()->canRequest(scriptURL)) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError("Failed to create a worker: script at '" + scriptURL.elidedString() + "' cannot be accessed from origin '" + scriptExecutionContext()->securityOrigin()->toString() + "'.");
         return KURL();
     }
 
     if (scriptExecutionContext()->contentSecurityPolicy() && !scriptExecutionContext()->contentSecurityPolicy()->allowScriptFromSource(scriptURL)) {
-        es.throwDOMException(SecurityError);
+        es.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 5805534..de94684 100644
--- a/Source/core/workers/AbstractWorker.h
+++ b/Source/core/workers/AbstractWorker.h
@@ -36,10 +36,10 @@
 #include "core/dom/EventListener.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/EventTarget.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicStringHash.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/DefaultSharedWorkerRepository.h b/Source/core/workers/DefaultSharedWorkerRepository.h
index 1237988..6cf1ee1 100644
--- a/Source/core/workers/DefaultSharedWorkerRepository.h
+++ b/Source/core/workers/DefaultSharedWorkerRepository.h
@@ -32,14 +32,14 @@
 #define DefaultSharedWorkerRepository_h
 
 #include "core/page/ContentSecurityPolicy.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/StringHash.h>
-#include <wtf/Threading.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Threading.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/SharedWorker.cpp b/Source/core/workers/SharedWorker.cpp
index 55019ec..484cbe8 100644
--- a/Source/core/workers/SharedWorker.cpp
+++ b/Source/core/workers/SharedWorker.cpp
@@ -65,18 +65,18 @@
 
     worker->suspendIfNeeded();
 
-    KURL scriptURL = worker->resolveURL(url, es);
-    if (scriptURL.isEmpty())
-        return 0;
-
     // We don't currently support nested workers, so workers can only be created from documents.
     ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
     Document* document = toDocument(context);
     if (!document->securityOrigin()->canAccessSharedWorkers()) {
-        es.throwDOMException(SecurityError);
+        es.throwSecurityError("Failed to create 'SharedWorker': access to shared workers is denied to origin '" + document->securityOrigin()->toString() + "'.");
         return 0;
     }
 
+    KURL scriptURL = worker->resolveURL(url, es);
+    if (scriptURL.isEmpty())
+        return 0;
+
     SharedWorkerRepository::connect(worker.get(), remotePort.release(), scriptURL, name, es);
 
     return worker.release();
diff --git a/Source/core/workers/SharedWorkerGlobalScope.cpp b/Source/core/workers/SharedWorkerGlobalScope.cpp
index fe229eb..43254a1 100644
--- a/Source/core/workers/SharedWorkerGlobalScope.cpp
+++ b/Source/core/workers/SharedWorkerGlobalScope.cpp
@@ -45,7 +45,8 @@
 
 PassRefPtr<MessageEvent> createConnectEvent(PassRefPtr<MessagePort> port)
 {
-    RefPtr<MessageEvent> event = MessageEvent::create(adoptPtr(new MessagePortArray(1, port)));
+    RefPtr<MessagePort> sourcePort = port;
+    RefPtr<MessageEvent> event = MessageEvent::create(adoptPtr(new MessagePortArray(1, sourcePort)), "", "", sourcePort);
     event->initEvent(eventNames().connectEvent, false, false);
     return event.release();
 }
@@ -82,7 +83,7 @@
 void SharedWorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
 {
     WorkerGlobalScope::logExceptionToConsole(errorMessage, sourceURL, lineNumber, columnNumber, callStack);
-    addMessageToWorkerConsole(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
+    addMessageToWorkerConsole(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
 }
 
 } // namespace WebCore
diff --git a/Source/core/workers/SharedWorkerRepository.h b/Source/core/workers/SharedWorkerRepository.h
index 6a3927a..26d15cb 100644
--- a/Source/core/workers/SharedWorkerRepository.h
+++ b/Source/core/workers/SharedWorkerRepository.h
@@ -31,9 +31,9 @@
 #ifndef SharedWorkerRepository_h
 #define SharedWorkerRepository_h
 
-#include <wtf/Forward.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/Worker.cpp b/Source/core/workers/Worker.cpp
index c94d08c..52d8523 100644
--- a/Source/core/workers/Worker.cpp
+++ b/Source/core/workers/Worker.cpp
@@ -33,9 +33,9 @@
 #include "core/dom/EventListener.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/MessageEvent.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
diff --git a/Source/core/workers/Worker.h b/Source/core/workers/Worker.h
index 3f0eb1a..023578a 100644
--- a/Source/core/workers/Worker.h
+++ b/Source/core/workers/Worker.h
@@ -34,10 +34,10 @@
 #include "core/dom/MessagePort.h"
 #include "core/workers/AbstractWorker.h"
 #include "core/workers/WorkerScriptLoaderClient.h"
-#include <wtf/Forward.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicStringHash.h>
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerEventQueue.h b/Source/core/workers/WorkerEventQueue.h
index 5eb8567..fda0b93 100644
--- a/Source/core/workers/WorkerEventQueue.h
+++ b/Source/core/workers/WorkerEventQueue.h
@@ -28,10 +28,10 @@
 #define WorkerEventQueue_h
 
 #include "core/dom/EventQueue.h"
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerGlobalScope.cpp b/Source/core/workers/WorkerGlobalScope.cpp
index f80e1ff..61f57e8 100644
--- a/Source/core/workers/WorkerGlobalScope.cpp
+++ b/Source/core/workers/WorkerGlobalScope.cpp
@@ -194,7 +194,7 @@
     for (Vector<String>::const_iterator it = urls.begin(); it != urlsEnd; ++it) {
         const KURL& url = scriptExecutionContext()->completeURL(*it);
         if (!url.isValid()) {
-            es.throwDOMException(SyntaxError);
+            es.throwDOMException(SyntaxError, "Failed to execute 'importScripts': the URL '" + *it + "' is invalid.");
             return;
         }
         completedURLs.append(url);
@@ -208,7 +208,7 @@
 
         // If the fetching attempt failed, throw a NetworkError exception and abort all these steps.
         if (scriptLoader->failed()) {
-            es.throwDOMException(NetworkError);
+            es.throwDOMException(NetworkError, "Failed to execute 'importScripts': the script at '" + it->elidedString() + "' failed to load.");
             return;
         }
 
@@ -233,34 +233,23 @@
     thread()->workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, columnNumber, sourceURL);
 }
 
-void WorkerGlobalScope::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
-{
-    if (!isContextThread()) {
-        postTask(AddConsoleMessageTask::create(source, level, message));
-        return;
-    }
-    thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, 0, String());
-
-    addMessageToWorkerConsole(source, level, message, String(), 0, 0, 0, requestIdentifier);
-}
-
-void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
+void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
 {
     if (!isContextThread()) {
         postTask(AddConsoleMessageTask::create(source, level, message));
         return;
     }
     thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, lineNumber, sourceURL);
-    addMessageToWorkerConsole(source, level, message, sourceURL, lineNumber, callStack, state, requestIdentifier);
+    addMessageToWorkerConsole(source, level, message, sourceURL, lineNumber, 0, state);
 }
 
-void WorkerGlobalScope::addMessageToWorkerConsole(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
+void WorkerGlobalScope::addMessageToWorkerConsole(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state)
 {
     ASSERT(isContextThread());
     if (callStack)
-        InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, callStack, requestIdentifier);
+        InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, callStack);
     else
-        InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, sourceURL, lineNumber, 0, state, requestIdentifier);
+        InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, sourceURL, lineNumber, 0, state);
 }
 
 bool WorkerGlobalScope::isContextThread() const
diff --git a/Source/core/workers/WorkerGlobalScope.h b/Source/core/workers/WorkerGlobalScope.h
index 3a9d05d..d732489 100644
--- a/Source/core/workers/WorkerGlobalScope.h
+++ b/Source/core/workers/WorkerGlobalScope.h
@@ -136,7 +136,7 @@
         void applyContentSecurityPolicyFromString(const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
 
         virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) OVERRIDE;
-        void addMessageToWorkerConsole(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState* = 0, unsigned long requestIdentifier = 0);
+        void addMessageToWorkerConsole(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
 
     private:
         virtual void refScriptExecutionContext() OVERRIDE { ref(); }
@@ -150,8 +150,7 @@
         virtual const KURL& virtualURL() const OVERRIDE;
         virtual KURL virtualCompleteURL(const String&) const;
 
-        virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState* = 0, unsigned long requestIdentifier = 0) OVERRIDE;
-        virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0) OVERRIDE;
+        virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* = 0) OVERRIDE;
 
         virtual EventTarget* errorEventTarget() OVERRIDE;
 
diff --git a/Source/core/workers/WorkerGlobalScope.idl b/Source/core/workers/WorkerGlobalScope.idl
index 87c3594..bfc432a 100644
--- a/Source/core/workers/WorkerGlobalScope.idl
+++ b/Source/core/workers/WorkerGlobalScope.idl
@@ -37,12 +37,13 @@
     attribute EventHandler onerror;
 
     // WorkerUtils
-    [Custom] void importScripts(/*[Variadic] in DOMString urls */);
+    [RaisesException] void importScripts(DOMString... urls);
     [Replaceable] readonly attribute WorkerNavigator navigator;
 
     // Additional constructors
     attribute URLConstructor webkitURL; // FIXME: deprecate this.
 };
 
+WorkerGlobalScope implements ImageBitmapFactories;
 WorkerGlobalScope implements WindowBase64;
 WorkerGlobalScope implements WindowTimers;
diff --git a/Source/core/workers/WorkerLoaderProxy.h b/Source/core/workers/WorkerLoaderProxy.h
index 3342d90..f3eed8d 100644
--- a/Source/core/workers/WorkerLoaderProxy.h
+++ b/Source/core/workers/WorkerLoaderProxy.h
@@ -32,8 +32,8 @@
 #define WorkerLoaderProxy_h
 
 #include "core/dom/ScriptExecutionContext.h"
-#include <wtf/Forward.h>
-#include <wtf/PassOwnPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebKit {
 class WebWorkerBase;
diff --git a/Source/core/workers/WorkerLocation.cpp b/Source/core/workers/WorkerLocation.cpp
index 87b5090..c93e8d1 100644
--- a/Source/core/workers/WorkerLocation.cpp
+++ b/Source/core/workers/WorkerLocation.cpp
@@ -25,10 +25,9 @@
  */
 
 #include "config.h"
-
 #include "core/workers/WorkerLocation.h"
 
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerMessagingProxy.cpp b/Source/core/workers/WorkerMessagingProxy.cpp
index eb15b16..9794ea6 100644
--- a/Source/core/workers/WorkerMessagingProxy.cpp
+++ b/Source/core/workers/WorkerMessagingProxy.cpp
@@ -49,7 +49,7 @@
 #include "core/workers/Worker.h"
 #include "core/workers/WorkerClients.h"
 #include "core/workers/WorkerThreadStartupData.h"
-#include <wtf/MainThread.h>
+#include "wtf/MainThread.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerMessagingProxy.h b/Source/core/workers/WorkerMessagingProxy.h
index 9b2113b..26566bf 100644
--- a/Source/core/workers/WorkerMessagingProxy.h
+++ b/Source/core/workers/WorkerMessagingProxy.h
@@ -31,12 +31,12 @@
 #include "core/workers/WorkerGlobalScopeProxy.h"
 #include "core/workers/WorkerLoaderProxy.h"
 #include "core/workers/WorkerObjectProxy.h"
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerObjectProxy.h b/Source/core/workers/WorkerObjectProxy.h
index d4da869..d0061f7 100644
--- a/Source/core/workers/WorkerObjectProxy.h
+++ b/Source/core/workers/WorkerObjectProxy.h
@@ -33,7 +33,7 @@
 
 #include "core/dom/MessagePort.h"
 #include "core/workers/WorkerReportingProxy.h"
-#include <wtf/PassOwnPtr.h>
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerReportingProxy.h b/Source/core/workers/WorkerReportingProxy.h
index a42df14..daa8f50 100644
--- a/Source/core/workers/WorkerReportingProxy.h
+++ b/Source/core/workers/WorkerReportingProxy.h
@@ -32,7 +32,7 @@
 #define WorkerReportingProxy_h
 
 #include "core/page/ConsoleTypes.h"
-#include <wtf/Forward.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerRunLoop.cpp b/Source/core/workers/WorkerRunLoop.cpp
index a0744cc..5dedc0e 100644
--- a/Source/core/workers/WorkerRunLoop.cpp
+++ b/Source/core/workers/WorkerRunLoop.cpp
@@ -32,12 +32,13 @@
 #include "core/workers/WorkerRunLoop.h"
 
 #include "core/dom/ScriptExecutionContext.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/platform/SharedTimer.h"
 #include "core/platform/ThreadGlobalData.h"
 #include "core/platform/ThreadTimers.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerThread.h"
-#include <wtf/CurrentTime.h>
+#include "wtf/CurrentTime.h"
 
 namespace WebCore {
 
@@ -106,12 +107,14 @@
 class RunLoopSetup {
     WTF_MAKE_NONCOPYABLE(RunLoopSetup);
 public:
-    RunLoopSetup(WorkerRunLoop& runLoop)
+    RunLoopSetup(WorkerRunLoop& runLoop, WorkerGlobalScope* context)
         : m_runLoop(runLoop)
+        , m_context(context)
     {
         if (!m_runLoop.m_nestedCount)
             threadGlobalData().threadTimers().setSharedTimer(m_runLoop.m_sharedTimer.get());
         m_runLoop.m_nestedCount++;
+        InspectorInstrumentation::willEnterNestedRunLoop(m_context);
     }
 
     ~RunLoopSetup()
@@ -119,14 +122,16 @@
         m_runLoop.m_nestedCount--;
         if (!m_runLoop.m_nestedCount)
             threadGlobalData().threadTimers().setSharedTimer(0);
+        InspectorInstrumentation::didLeaveNestedRunLoop(m_context);
     }
 private:
     WorkerRunLoop& m_runLoop;
+    WorkerGlobalScope* m_context;
 };
 
 void WorkerRunLoop::run(WorkerGlobalScope* context)
 {
-    RunLoopSetup setup(*this);
+    RunLoopSetup setup(*this, context);
     ModePredicate modePredicate(defaultMode());
     MessageQueueWaitResult result;
     do {
@@ -137,7 +142,7 @@
 
 MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerGlobalScope* context, const String& mode, WaitMode waitMode)
 {
-    RunLoopSetup setup(*this);
+    RunLoopSetup setup(*this, context);
     ModePredicate modePredicate(mode);
     MessageQueueWaitResult result = runInMode(context, modePredicate, waitMode);
     return result;
@@ -185,7 +190,9 @@
         break;
 
     case MessageQueueMessageReceived:
+        InspectorInstrumentation::willProcessTask(context);
         task->performTask(*this, context);
+        InspectorInstrumentation::didProcessTask(context);
         break;
 
     case MessageQueueTimeout:
diff --git a/Source/core/workers/WorkerRunLoop.h b/Source/core/workers/WorkerRunLoop.h
index 28a7bc5..8ee3e8e 100644
--- a/Source/core/workers/WorkerRunLoop.h
+++ b/Source/core/workers/WorkerRunLoop.h
@@ -32,9 +32,9 @@
 #define WorkerRunLoop_h
 
 #include "core/dom/ScriptExecutionContext.h"
-#include <wtf/MessageQueue.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
+#include "wtf/MessageQueue.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/workers/WorkerScriptLoader.cpp b/Source/core/workers/WorkerScriptLoader.cpp
index 9c10f8b..7f6290e 100644
--- a/Source/core/workers/WorkerScriptLoader.cpp
+++ b/Source/core/workers/WorkerScriptLoader.cpp
@@ -26,7 +26,6 @@
  */
 
 #include "config.h"
-
 #include "core/workers/WorkerScriptLoader.h"
 
 #include "core/dom/ScriptExecutionContext.h"
@@ -36,9 +35,9 @@
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerScriptLoaderClient.h"
 
-#include <wtf/OwnPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/OwnPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/UnusedParam.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/DOMParser.cpp b/Source/core/xml/DOMParser.cpp
index 561b34d..b923b46 100644
--- a/Source/core/xml/DOMParser.cpp
+++ b/Source/core/xml/DOMParser.cpp
@@ -21,7 +21,7 @@
 
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/NativeXPathNSResolver.cpp b/Source/core/xml/NativeXPathNSResolver.cpp
index e398afd..8ae8c04 100644
--- a/Source/core/xml/NativeXPathNSResolver.cpp
+++ b/Source/core/xml/NativeXPathNSResolver.cpp
@@ -28,7 +28,7 @@
 
 #include "XMLNames.h"
 #include "core/dom/Node.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/NativeXPathNSResolver.h b/Source/core/xml/NativeXPathNSResolver.h
index 00e04fd..17a1238 100644
--- a/Source/core/xml/NativeXPathNSResolver.h
+++ b/Source/core/xml/NativeXPathNSResolver.h
@@ -27,7 +27,7 @@
 #define NativeXPathNSResolver_h
 
 #include "core/xml/XPathNSResolver.h"
-#include <wtf/RefPtr.h>
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XMLErrors.cpp b/Source/core/xml/XMLErrors.cpp
index 2c1bd85..acef59f 100644
--- a/Source/core/xml/XMLErrors.cpp
+++ b/Source/core/xml/XMLErrors.cpp
@@ -34,7 +34,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/Text.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XMLErrors.h b/Source/core/xml/XMLErrors.h
index d45a259..7adfd1e 100644
--- a/Source/core/xml/XMLErrors.h
+++ b/Source/core/xml/XMLErrors.h
@@ -29,8 +29,8 @@
 #ifndef XMLErrors_h
 #define XMLErrors_h
 
-#include <wtf/text/StringBuilder.h>
-#include <wtf/text/TextPosition.h>
+#include "wtf/text/StringBuilder.h"
+#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index e65a4a7..d5852ee 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -24,6 +24,7 @@
 #include "core/xml/XMLHttpRequest.h"
 
 #include "FetchInitiatorTypeNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ContextFeatures.h"
 #include "core/dom/DOMImplementation.h"
@@ -215,7 +216,7 @@
 ScriptString XMLHttpRequest::responseText(ExceptionState& es)
 {
     if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeText) {
-        es.throwDOMException(InvalidStateError);
+        es.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))
@@ -223,10 +224,21 @@
     return m_responseText;
 }
 
+ScriptString XMLHttpRequest::responseJSONSource(ExceptionState& es)
+{
+    if (m_responseTypeCode != ResponseTypeJSON) {
+        es.throwDOMException(InvalidStateError);
+        return ScriptString();
+    }
+    if (m_error || m_state != DONE)
+        return ScriptString();
+    return m_responseText;
+}
+
 Document* XMLHttpRequest::responseXML(ExceptionState& es)
 {
     if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeDocument) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("responseXML", "XMLHttpRequest", "the value is only accessible if the object's 'responseType' is '' or 'document' (was '" + responseType() + "')."));
         return 0;
     }
 
@@ -260,12 +272,10 @@
     return m_responseDocument.get();
 }
 
-Blob* XMLHttpRequest::responseBlob(ExceptionState& es)
+Blob* XMLHttpRequest::responseBlob()
 {
-    if (m_responseTypeCode != ResponseTypeBlob) {
-        es.throwDOMException(InvalidStateError);
-        return 0;
-    }
+    ASSERT(m_responseTypeCode == ResponseTypeBlob);
+
     // We always return null before DONE.
     if (m_error || m_state != DONE)
         return 0;
@@ -295,12 +305,9 @@
     return m_responseBlob.get();
 }
 
-ArrayBuffer* XMLHttpRequest::responseArrayBuffer(ExceptionState& es)
+ArrayBuffer* XMLHttpRequest::responseArrayBuffer()
 {
-    if (m_responseTypeCode != ResponseTypeArrayBuffer) {
-        es.throwDOMException(InvalidStateError);
-        return 0;
-    }
+    ASSERT(m_responseTypeCode == ResponseTypeArrayBuffer);
 
     if (m_error || m_state != DONE)
         return 0;
@@ -318,8 +325,7 @@
     // 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 (scriptExecutionContext()->isDocument() && !m_async) {
-        logConsoleError(scriptExecutionContext(), "XMLHttpRequest.timeout cannot be set for synchronous HTTP(S) requests made from the window context.");
-        es.throwDOMException(InvalidAccessError);
+        es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("timeout", "XMLHttpRequest", "timeouts cannot be set for synchronous requests made from a document."));
         return;
     }
     m_timeoutMilliseconds = timeout;
@@ -328,7 +334,7 @@
 void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& es)
 {
     if (m_state >= LOADING) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type cannot be set if the object's state is LOADING or DONE."));
         return;
     }
 
@@ -337,8 +343,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 && scriptExecutionContext()->isDocument() && m_url.protocolIsInHTTPFamily()) {
-        logConsoleError(scriptExecutionContext(), "XMLHttpRequest.responseType cannot be changed for synchronous HTTP(S) requests made from the window context.");
-        es.throwDOMException(InvalidAccessError);
+        es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type can only be changed for asynchronous HTTP requests made from a document."));
         return;
     }
 
@@ -346,6 +351,8 @@
         m_responseTypeCode = ResponseTypeDefault;
     else if (responseType == "text")
         m_responseTypeCode = ResponseTypeText;
+    else if (responseType == "json")
+        m_responseTypeCode = ResponseTypeJSON;
     else if (responseType == "document")
         m_responseTypeCode = ResponseTypeDocument;
     else if (responseType == "blob")
@@ -363,6 +370,8 @@
         return "";
     case ResponseTypeText:
         return "text";
+    case ResponseTypeJSON:
+        return "json";
     case ResponseTypeDocument:
         return "document";
     case ResponseTypeBlob:
@@ -410,7 +419,7 @@
 void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& es)
 {
     if (m_state > OPENED || m_loader) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("withCredentials", "XMLHttpRequest", "the value may only be set if the object's state is UNSENT or OPENED."));
         return;
     }
 
@@ -463,24 +472,24 @@
     ASSERT(m_state == UNSENT);
 
     if (!isValidHTTPToken(method)) {
-        es.throwDOMException(SyntaxError);
+        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' is not a valid HTTP method."));
         return;
     }
 
     if (!isAllowedHTTPMethod(method)) {
-        es.throwDOMException(SecurityError, "'XMLHttpRequest.open' does not support the '" + method + "' method.");
+        es.throwSecurityError(ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' HTTP method is unsupported."));
         return;
     }
 
     if (!ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) && !scriptExecutionContext()->contentSecurityPolicy()->allowConnectToSource(url)) {
-        es.throwDOMException(SecurityError, "Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy.");
+        // 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.");
         return;
     }
 
     if (!async && scriptExecutionContext()->isDocument()) {
         if (document()->settings() && !document()->settings()->syncXHRInDocumentsEnabled()) {
-            logConsoleError(scriptExecutionContext(), "Synchronous XMLHttpRequests are disabled for this page.");
-            es.throwDOMException(InvalidAccessError);
+            es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests are disabled for this page."));
             return;
         }
 
@@ -489,15 +498,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) {
-            logConsoleError(scriptExecutionContext(), "Synchronous HTTP(S) requests made from the window context cannot have XMLHttpRequest.responseType set.");
-            es.throwDOMException(InvalidAccessError);
+            es.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) {
-            logConsoleError(scriptExecutionContext(), "Synchronous XMLHttpRequests must not have a timeout value set.");
-            es.throwDOMException(InvalidAccessError);
+            es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests must not set a timeout."));
             return;
         }
     }
@@ -541,7 +548,7 @@
         return false;
 
     if (m_state != OPENED || m_loader) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "the object's state must be OPENED."));
         return false;
     }
 
@@ -696,7 +703,7 @@
 {
     // Only GET request is supported for blob URL.
     if (m_url.protocolIs("blob") && m_method != "GET") {
-        es.throwDOMException(NetworkError);
+        es.throwDOMException(NetworkError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "'GET' is the only method allowed for 'blob:' URLs."));
         return;
     }
 
@@ -756,11 +763,15 @@
         // This is true while running onunload handlers.
         // FIXME: Maybe we need to be able to send XMLHttpRequests from onunload, <http://bugs.webkit.org/show_bug.cgi?id=10904>.
         // FIXME: Maybe create() can return null for other reasons too?
+        ASSERT(!m_loader);
         m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options);
         if (m_loader) {
             // Neither this object nor the JavaScript wrapper should be deleted while
             // a request is in progress because we need to keep the listeners alive,
             // and they are referenced by the JavaScript wrapper.
+
+            // m_loader was null, so there should be no pending activity at this point.
+            ASSERT(!hasPendingActivity());
             setPendingActivity(this);
         }
     } else {
@@ -806,26 +817,25 @@
     }
 }
 
-void XMLHttpRequest::internalAbort()
+void XMLHttpRequest::internalAbort(DropProtection async)
 {
-    bool hadLoader = m_loader;
-
     m_error = true;
 
     // FIXME: when we add the support for multi-part XHR, we will have to think be careful with this initialization.
     m_receivedLength = 0;
-
-    if (hadLoader) {
-        m_loader->cancel();
-        m_loader = 0;
-    }
-
     m_decoder = 0;
 
     InspectorInstrumentation::didFailXHRLoading(scriptExecutionContext(), this);
 
-    if (hadLoader)
-        dropProtectionSoon();
+    if (m_loader) {
+        m_loader->cancel();
+        m_loader = 0;
+
+        if (async == DropProtectionAsync)
+            dropProtectionSoon();
+        else
+            dropProtection();
+    }
 }
 
 void XMLHttpRequest::clearResponse()
@@ -903,12 +913,17 @@
 void XMLHttpRequest::setRequestHeader(const AtomicString& name, const String& value, ExceptionState& es)
 {
     if (m_state != OPENED || m_loader) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "the object's state must be OPENED."));
         return;
     }
 
-    if (!isValidHTTPToken(name) || !isValidHTTPHeaderValue(value)) {
-        es.throwDOMException(SyntaxError);
+    if (!isValidHTTPToken(name)) {
+        es.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."));
         return;
     }
 
@@ -936,7 +951,7 @@
 String XMLHttpRequest::getAllResponseHeaders(ExceptionState& es) const
 {
     if (m_state < HEADERS_RECEIVED) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("getAllResponseHeaders", "XMLHttpRequest", "the object's state must not be UNSENT or OPENED."));
         return "";
     }
 
@@ -972,7 +987,7 @@
 String XMLHttpRequest::getResponseHeader(const AtomicString& name, ExceptionState& es) const
 {
     if (m_state < HEADERS_RECEIVED) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("getResponseHeader", "XMLHttpRequest", "the object's state must not be UNSENT or OPENED."));
         return String();
     }
 
@@ -1022,7 +1037,7 @@
     if (m_state == OPENED) {
         // Firefox only raises an exception in this state; we match it.
         // Note the case of local file requests, where we have no HTTP response code! Firefox never raises an exception for those, but we match HTTP case for consistency.
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("status", "XMLHttpRequest", "the object's state must not be OPENED."));
     }
 
     return 0;
@@ -1035,7 +1050,7 @@
 
     if (m_state == OPENED) {
         // See comments in status() above.
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("statusText", "XMLHttpRequest", "the object's state must not be OPENED."));
     }
 
     return String();
@@ -1085,15 +1100,17 @@
 
     InspectorInstrumentation::didFinishXHRLoading(scriptExecutionContext(), this, identifier, m_responseText, m_url, m_lastSendURL, m_lastSendLineNumber);
 
-    bool hadLoader = m_loader;
-    m_loader = 0;
+    // Prevent dropProtection releasing the last reference, and retain |this| until the end of this method.
+    RefPtr<XMLHttpRequest> protect(this);
+
+    if (m_loader) {
+        m_loader = 0;
+        dropProtection();
+    }
 
     changeState(DONE);
     m_responseEncoding = String();
     m_decoder = 0;
-
-    if (hadLoader)
-        dropProtection();
 }
 
 void XMLHttpRequest::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
@@ -1133,10 +1150,12 @@
     if (m_state < HEADERS_RECEIVED)
         changeState(HEADERS_RECEIVED);
 
-    bool useDecoder = m_responseTypeCode == ResponseTypeDefault || m_responseTypeCode == ResponseTypeText || m_responseTypeCode == ResponseTypeDocument;
+    bool useDecoder = m_responseTypeCode == ResponseTypeDefault || m_responseTypeCode == ResponseTypeText || m_responseTypeCode == ResponseTypeJSON || m_responseTypeCode == ResponseTypeDocument;
 
     if (useDecoder && !m_decoder) {
-        if (!m_responseEncoding.isEmpty())
+        if (m_responseTypeCode == ResponseTypeJSON)
+            m_decoder = TextResourceDecoder::create("application/json", "UTF-8");
+        else if (!m_responseEncoding.isEmpty())
             m_decoder = TextResourceDecoder::create("text/plain", m_responseEncoding);
         // allow TextResourceDecoder to look inside the m_response if it's XML or HTML
         else if (responseIsXML()) {
@@ -1227,7 +1246,7 @@
 
 void XMLHttpRequest::stop()
 {
-    internalAbort();
+    internalAbort(DropProtectionAsync);
 }
 
 void XMLHttpRequest::contextDestroyed()
@@ -1246,14 +1265,4 @@
     return ActiveDOMObject::scriptExecutionContext();
 }
 
-EventTargetData* XMLHttpRequest::eventTargetData()
-{
-    return &m_eventTargetData;
-}
-
-EventTargetData* XMLHttpRequest::ensureEventTargetData()
-{
-    return &m_eventTargetData;
-}
-
 } // namespace WebCore
diff --git a/Source/core/xml/XMLHttpRequest.h b/Source/core/xml/XMLHttpRequest.h
index fde3a84..3e15efb 100644
--- a/Source/core/xml/XMLHttpRequest.h
+++ b/Source/core/xml/XMLHttpRequest.h
@@ -27,10 +27,10 @@
 #include "core/dom/ActiveDOMObject.h"
 #include "core/dom/EventListener.h"
 #include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
 #include "core/loader/ThreadableLoaderClient.h"
 #include "core/platform/network/FormData.h"
 #include "core/platform/network/ResourceResponse.h"
+#include "core/xml/XMLHttpRequestEventTarget.h"
 #include "core/xml/XMLHttpRequestProgressEventThrottle.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/OwnPtr.h"
@@ -51,7 +51,7 @@
 
 typedef int ExceptionCode;
 
-class XMLHttpRequest : public ScriptWrappable, public RefCounted<XMLHttpRequest>, public EventTarget, private ThreadableLoaderClient, public ActiveDOMObject {
+class XMLHttpRequest : public ScriptWrappable, public RefCounted<XMLHttpRequest>, public XMLHttpRequestEventTarget, private ThreadableLoaderClient, public ActiveDOMObject {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassRefPtr<XMLHttpRequest> create(ScriptExecutionContext*, PassRefPtr<SecurityOrigin> = 0);
@@ -69,11 +69,17 @@
     enum ResponseTypeCode {
         ResponseTypeDefault,
         ResponseTypeText,
+        ResponseTypeJSON,
         ResponseTypeDocument,
         ResponseTypeBlob,
         ResponseTypeArrayBuffer
     };
 
+    enum DropProtection {
+        DropProtectionSync,
+        DropProtectionAsync,
+    };
+
     virtual void contextDestroyed();
     virtual void didTimeout();
     virtual bool canSuspend() const;
@@ -81,8 +87,8 @@
     virtual void resume();
     virtual void stop();
 
-    virtual const AtomicString& interfaceName() const;
-    virtual ScriptExecutionContext* scriptExecutionContext() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
+    virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
 
     const KURL& url() const { return m_url; }
     String statusText(ExceptionState&) const;
@@ -107,8 +113,9 @@
     String getAllResponseHeaders(ExceptionState&) const;
     String getResponseHeader(const AtomicString& name, ExceptionState&) const;
     ScriptString responseText(ExceptionState&);
+    ScriptString responseJSONSource(ExceptionState&);
     Document* responseXML(ExceptionState&);
-    Blob* responseBlob(ExceptionState&);
+    Blob* responseBlob();
     unsigned long timeout() const { return m_timeoutMilliseconds; }
     void setTimeout(unsigned long timeout, ExceptionState&);
 
@@ -124,7 +131,7 @@
     ResponseTypeCode responseTypeCode() const { return m_responseTypeCode; }
 
     // response attribute has custom getter.
-    ArrayBuffer* responseArrayBuffer(ExceptionState&);
+    ArrayBuffer* responseArrayBuffer();
 
     void setLastSendLineNumber(unsigned lineNumber) { m_lastSendLineNumber = lineNumber; }
     void setLastSendURL(const String& url) { m_lastSendURL = url; }
@@ -132,13 +139,6 @@
     XMLHttpRequestUpload* upload();
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(timeout);
 
     using RefCounted<XMLHttpRequest>::ref;
     using RefCounted<XMLHttpRequest>::deref;
@@ -146,10 +146,8 @@
 private:
     XMLHttpRequest(ScriptExecutionContext*, PassRefPtr<SecurityOrigin>);
 
-    virtual void refEventTarget() { ref(); }
-    virtual void derefEventTarget() { deref(); }
-    virtual EventTargetData* eventTargetData();
-    virtual EventTargetData* ensureEventTargetData();
+    virtual void refEventTarget() OVERRIDE { ref(); }
+    virtual void derefEventTarget() OVERRIDE { deref(); }
 
     Document* document() const;
     SecurityOrigin* securityOrigin() const;
@@ -176,7 +174,7 @@
     void callReadyStateChangeListener();
     void dropProtectionSoon();
     void dropProtection(Timer<XMLHttpRequest>* = 0);
-    void internalAbort();
+    void internalAbort(DropProtection = DropProtectionSync);
     void clearResponse();
     void clearResponseBuffers();
     void clearRequest();
@@ -229,8 +227,6 @@
     String m_lastSendURL;
     ExceptionCode m_exceptionCode;
 
-    EventTargetData m_eventTargetData;
-
     XMLHttpRequestProgressEventThrottle m_progressEventThrottle;
 
     // An enum corresponding to the allowed string values for the responseType attribute.
diff --git a/Source/core/xml/XMLHttpRequest.idl b/Source/core/xml/XMLHttpRequest.idl
index 2c4f120..ecee6f5 100644
--- a/Source/core/xml/XMLHttpRequest.idl
+++ b/Source/core/xml/XMLHttpRequest.idl
@@ -31,8 +31,7 @@
     "arraybuffer",
     "blob",
     "document",
-//    FIXME: enable once support for json responseText is completed. (bug #73648)
-//    "json",
+    "json",
     "text"
 };
 
@@ -42,17 +41,7 @@
     Constructor,
     ConstructorCallWith=ScriptExecutionContext,
     CustomConstructor(optional XMLHttpRequestOptions options)
-] interface XMLHttpRequest : EventTarget {
-    // From XMLHttpRequestEventTarget
-    // event handler attributes
-    attribute EventHandler onabort;
-    attribute EventHandler onerror;
-    attribute EventHandler onload;
-    attribute EventHandler onloadend;
-    attribute EventHandler onloadstart;
-    attribute EventHandler onprogress;
-    attribute EventHandler ontimeout;
-
+] interface XMLHttpRequest : XMLHttpRequestEventTarget {
     // event handler attributes
     attribute EventHandler onreadystatechange;
 
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h b/Source/core/xml/XMLHttpRequestEventTarget.h
similarity index 65%
copy from Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
copy to Source/core/xml/XMLHttpRequestEventTarget.h
index 133dab0..be91c5d 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.h
+++ b/Source/core/xml/XMLHttpRequestEventTarget.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 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,26 +28,31 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumDefault_h
-#define ScrollbarThemeChromiumDefault_h
+#ifndef XMLHttpRequestEventTarget_h
+#define XMLHttpRequestEventTarget_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "core/dom/EventTarget.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumDefault : public ScrollbarThemeChromium {
+class XMLHttpRequestEventTarget : public EventTarget {
 public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(timeout);
 
 protected:
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual IntSize buttonSize(ScrollbarThemeClient*);
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+    virtual EventTargetData* eventTargetData() OVERRIDE { return &m_eventTargetData; }
+    virtual EventTargetData* ensureEventTargetData() OVERRIDE { return &m_eventTargetData; }
+
+private:
+    EventTargetData m_eventTargetData;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // XMLHttpRequestEventTarget_h
diff --git a/Source/core/loader/cache/CachePolicy.h b/Source/core/xml/XMLHttpRequestEventTarget.idl
similarity index 72%
copy from Source/core/loader/cache/CachePolicy.h
copy to Source/core/xml/XMLHttpRequestEventTarget.idl
index a44c32d..7ec93d9 100644
--- a/Source/core/loader/cache/CachePolicy.h
+++ b/Source/core/xml/XMLHttpRequestEventTarget.idl
@@ -1,5 +1,6 @@
 /*
- * Copyright (C) 2003, 2006 Apple Computer, Inc.  All rights reserved.
+ * Copyright (C) 2008, 2010 Apple 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
@@ -23,19 +24,14 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CachePolicy_h
-#define CachePolicy_h
-
-namespace WebCore {
-
-    enum CachePolicy {
-        CachePolicyCache,
-        CachePolicyVerify,
-        CachePolicyRevalidate,
-        CachePolicyReload,
-        CachePolicyHistoryBuffer
-    };
-
-}
-
-#endif
+[
+    NoInterfaceObject
+] interface XMLHttpRequestEventTarget : EventTarget {
+    attribute EventHandler onabort;
+    attribute EventHandler onerror;
+    attribute EventHandler onload;
+    attribute EventHandler onloadend;
+    attribute EventHandler onloadstart;
+    attribute EventHandler onprogress;
+    attribute EventHandler ontimeout;
+};
diff --git a/Source/core/xml/XMLHttpRequestUpload.cpp b/Source/core/xml/XMLHttpRequestUpload.cpp
index 770e495..3e9f5cf 100644
--- a/Source/core/xml/XMLHttpRequestUpload.cpp
+++ b/Source/core/xml/XMLHttpRequestUpload.cpp
@@ -30,8 +30,8 @@
 #include "core/dom/EventNames.h"
 #include "core/xml/XMLHttpRequest.h"
 #include "core/xml/XMLHttpRequestProgressEvent.h"
-#include <wtf/Assertions.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/Assertions.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -51,16 +51,6 @@
     return m_xmlHttpRequest->scriptExecutionContext();
 }
 
-EventTargetData* XMLHttpRequestUpload::eventTargetData()
-{
-    return &m_eventTargetData;
-}
-
-EventTargetData* XMLHttpRequestUpload::ensureEventTargetData()
-{
-    return &m_eventTargetData;
-}
-
 void XMLHttpRequestUpload::dispatchEventAndLoadEnd(PassRefPtr<Event> event)
 {
     ASSERT(event->type() == eventNames().loadEvent || event->type() == eventNames().abortEvent || event->type() == eventNames().errorEvent || event->type() == eventNames().timeoutEvent);
diff --git a/Source/core/xml/XMLHttpRequestUpload.h b/Source/core/xml/XMLHttpRequestUpload.h
index 3b83aa1..408e379 100644
--- a/Source/core/xml/XMLHttpRequestUpload.h
+++ b/Source/core/xml/XMLHttpRequestUpload.h
@@ -29,8 +29,8 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/EventListener.h"
 #include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
 #include "core/xml/XMLHttpRequest.h"
+#include "core/xml/XMLHttpRequestEventTarget.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/PassOwnPtr.h"
@@ -44,7 +44,7 @@
 class ScriptExecutionContext;
 class XMLHttpRequest;
 
-class XMLHttpRequestUpload : public ScriptWrappable, public EventTarget {
+class XMLHttpRequestUpload : public ScriptWrappable, public XMLHttpRequestEventTarget {
 public:
     static PassOwnPtr<XMLHttpRequestUpload> create(XMLHttpRequest* xmlHttpRequest)
     {
@@ -55,25 +55,16 @@
     void deref() { m_xmlHttpRequest->deref(); }
     XMLHttpRequest* xmlHttpRequest() const { return m_xmlHttpRequest; }
 
-    virtual const AtomicString& interfaceName() const;
-    ScriptExecutionContext* scriptExecutionContext() const;
-
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
+    virtual const AtomicString& interfaceName() const OVERRIDE;
+    virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
 
     void dispatchEventAndLoadEnd(PassRefPtr<Event>);
 
 private:
     explicit XMLHttpRequestUpload(XMLHttpRequest*);
 
-    virtual void refEventTarget() { ref(); }
-    virtual void derefEventTarget() { deref(); }
-    virtual EventTargetData* eventTargetData();
-    virtual EventTargetData* ensureEventTargetData();
+    virtual void refEventTarget() OVERRIDE { ref(); }
+    virtual void derefEventTarget() OVERRIDE { deref(); }
 
     XMLHttpRequest* m_xmlHttpRequest;
     EventTargetData m_eventTargetData;
diff --git a/Source/core/xml/XMLHttpRequestUpload.idl b/Source/core/xml/XMLHttpRequestUpload.idl
index eec9988..ae66d38 100644
--- a/Source/core/xml/XMLHttpRequestUpload.idl
+++ b/Source/core/xml/XMLHttpRequestUpload.idl
@@ -26,14 +26,6 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface XMLHttpRequestUpload : EventTarget {
-    // From XMLHttpRequestEventTarget
-    // event handler attributes
-    attribute EventHandler onabort;
-    attribute EventHandler onerror;
-    attribute EventHandler onload;
-    attribute EventHandler onloadend;
-    attribute EventHandler onloadstart;
-    attribute EventHandler onprogress;
+interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {
 };
 
diff --git a/Source/core/xml/XMLSerializer.cpp b/Source/core/xml/XMLSerializer.cpp
index ad32db4..3b05636 100644
--- a/Source/core/xml/XMLSerializer.cpp
+++ b/Source/core/xml/XMLSerializer.cpp
@@ -24,7 +24,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/editing/markup.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XMLTreeViewer.cpp b/Source/core/xml/XMLTreeViewer.cpp
index 28978a6..04bfa13 100644
--- a/Source/core/xml/XMLTreeViewer.cpp
+++ b/Source/core/xml/XMLTreeViewer.cpp
@@ -58,7 +58,7 @@
 
     String cssString(reinterpret_cast<const char*>(XMLViewer_css), sizeof(XMLViewer_css));
     RefPtr<Text> text = m_document->createTextNode(cssString);
-    m_document->getElementById("xml-viewer-style")->appendChild(text, IGNORE_EXCEPTION, AttachLazily);
+    m_document->getElementById("xml-viewer-style")->appendChild(text, IGNORE_EXCEPTION);
 }
 
 } // namespace WebCore
diff --git a/Source/core/xml/XPathExpression.cpp b/Source/core/xml/XPathExpression.cpp
index 0e587e3..0850a92 100644
--- a/Source/core/xml/XPathExpression.cpp
+++ b/Source/core/xml/XPathExpression.cpp
@@ -34,7 +34,7 @@
 #include "core/xml/XPathParser.h"
 #include "core/xml/XPathResult.h"
 #include "core/xml/XPathUtil.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XPathExpressionNode.cpp b/Source/core/xml/XPathExpressionNode.cpp
index a534976..524a48d 100644
--- a/Source/core/xml/XPathExpressionNode.cpp
+++ b/Source/core/xml/XPathExpressionNode.cpp
@@ -28,7 +28,7 @@
 #include "core/xml/XPathExpressionNode.h"
 
 #include "core/dom/Node.h"
-#include <wtf/StdLibExtras.h>
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 namespace XPath {
diff --git a/Source/core/xml/XPathExpressionNode.h b/Source/core/xml/XPathExpressionNode.h
index 64a930d..7101a56 100644
--- a/Source/core/xml/XPathExpressionNode.h
+++ b/Source/core/xml/XPathExpressionNode.h
@@ -29,9 +29,9 @@
 
 #include "core/dom/Node.h"
 #include "core/xml/XPathValue.h"
-#include <wtf/HashMap.h>
-#include <wtf/text/StringHash.h>
-#include <wtf/Vector.h>
+#include "wtf/HashMap.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XPathFunctions.cpp b/Source/core/xml/XPathFunctions.cpp
index 0e9f977..0af3a8b 100644
--- a/Source/core/xml/XPathFunctions.cpp
+++ b/Source/core/xml/XPathFunctions.cpp
@@ -34,8 +34,8 @@
 #include "core/dom/TreeScope.h"
 #include "core/xml/XPathUtil.h"
 #include "core/xml/XPathValue.h"
-#include <wtf/MathExtras.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MathExtras.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 namespace XPath {
diff --git a/Source/core/xml/XPathGrammar.y b/Source/core/xml/XPathGrammar.y
index e2a8c23..a4f5b69 100644
--- a/Source/core/xml/XPathGrammar.y
+++ b/Source/core/xml/XPathGrammar.y
@@ -36,7 +36,7 @@
 #include "core/xml/XPathPredicate.h"
 #include "core/xml/XPathStep.h"
 #include "core/xml/XPathVariableReference.h"
-#include <wtf/FastMalloc.h>
+#include "wtf/FastMalloc.h"
 
 #define YYMALLOC fastMalloc
 #define YYFREE fastFree
diff --git a/Source/core/xml/XPathNodeSet.h b/Source/core/xml/XPathNodeSet.h
index 488fe87..c90e395 100644
--- a/Source/core/xml/XPathNodeSet.h
+++ b/Source/core/xml/XPathNodeSet.h
@@ -26,8 +26,8 @@
 #ifndef XPathNodeSet_h
 #define XPathNodeSet_h
 
-#include <wtf/Forward.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/Vector.h"
 
 #include "core/dom/Node.h"
 
diff --git a/Source/core/xml/XPathParser.cpp b/Source/core/xml/XPathParser.cpp
index 4f2c8b2..3fe9b35 100644
--- a/Source/core/xml/XPathParser.cpp
+++ b/Source/core/xml/XPathParser.cpp
@@ -34,8 +34,8 @@
 #include "core/xml/XPathNSResolver.h"
 #include "core/xml/XPathPath.h"
 #include "core/xml/XPathStep.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/StdLibExtras.h"
+#include "wtf/text/StringHash.h"
 
 using namespace WebCore;
 using namespace WTF;
diff --git a/Source/core/xml/XPathPredicate.cpp b/Source/core/xml/XPathPredicate.cpp
index 3a77f7d..963e115 100644
--- a/Source/core/xml/XPathPredicate.cpp
+++ b/Source/core/xml/XPathPredicate.cpp
@@ -32,7 +32,7 @@
 #include "core/xml/XPathFunctions.h"
 #include "core/xml/XPathUtil.h"
 #include "core/xml/XPathValue.h"
-#include <wtf/MathExtras.h>
+#include "wtf/MathExtras.h"
 
 namespace WebCore {
 namespace XPath {
diff --git a/Source/core/xml/XPathUtil.cpp b/Source/core/xml/XPathUtil.cpp
index 9ee19c8b..5967efa 100644
--- a/Source/core/xml/XPathUtil.cpp
+++ b/Source/core/xml/XPathUtil.cpp
@@ -29,7 +29,7 @@
 
 #include "core/dom/ContainerNode.h"
 #include "core/dom/NodeTraversal.h"
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 namespace XPath {
diff --git a/Source/core/xml/XPathUtil.h b/Source/core/xml/XPathUtil.h
index 62b6599..9db3314 100644
--- a/Source/core/xml/XPathUtil.h
+++ b/Source/core/xml/XPathUtil.h
@@ -27,8 +27,8 @@
 #ifndef XPathUtil_h
 #define XPathUtil_h
 
-#include <wtf/Forward.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XPathValue.cpp b/Source/core/xml/XPathValue.cpp
index 2bd56c0..301356c 100644
--- a/Source/core/xml/XPathValue.cpp
+++ b/Source/core/xml/XPathValue.cpp
@@ -30,8 +30,8 @@
 #include <limits>
 #include "core/xml/XPathExpressionNode.h"
 #include "core/xml/XPathUtil.h"
-#include <wtf/MathExtras.h>
-#include <wtf/StdLibExtras.h>
+#include "wtf/MathExtras.h"
+#include "wtf/StdLibExtras.h"
 
 using std::numeric_limits;
 
diff --git a/Source/core/xml/XPathValue.h b/Source/core/xml/XPathValue.h
index a693e71..c21a8dc 100644
--- a/Source/core/xml/XPathValue.h
+++ b/Source/core/xml/XPathValue.h
@@ -28,7 +28,7 @@
 #define XPathValue_h
 
 #include "core/xml/XPathNodeSet.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XSLImportRule.cpp b/Source/core/xml/XSLImportRule.cpp
index 242303c..b6917af 100644
--- a/Source/core/xml/XSLImportRule.cpp
+++ b/Source/core/xml/XSLImportRule.cpp
@@ -24,9 +24,9 @@
 
 #include "FetchInitiatorTypeNames.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/FetchRequest.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/XSLStyleSheetResource.h"
+#include "core/fetch/FetchRequest.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/XSLStyleSheetResource.h"
 #include "core/xml/XSLStyleSheet.h"
 
 namespace WebCore {
diff --git a/Source/core/xml/XSLImportRule.h b/Source/core/xml/XSLImportRule.h
index 63355d1..e78fc08 100644
--- a/Source/core/xml/XSLImportRule.h
+++ b/Source/core/xml/XSLImportRule.h
@@ -23,10 +23,10 @@
 #ifndef XSLImportRule_h
 #define XSLImportRule_h
 
-#include "core/loader/cache/ResourcePtr.h"
-#include "core/loader/cache/StyleSheetResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResourceClient.h"
 #include "core/xml/XSLStyleSheet.h"
-#include <wtf/PassOwnPtr.h>
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XSLStyleSheet.h b/Source/core/xml/XSLStyleSheet.h
index f7b47c5..6b21a11 100644
--- a/Source/core/xml/XSLStyleSheet.h
+++ b/Source/core/xml/XSLStyleSheet.h
@@ -27,7 +27,7 @@
 #include <libxslt/transform.h>
 #include "core/css/StyleSheet.h"
 #include "core/dom/ProcessingInstruction.h"
-#include <wtf/PassRefPtr.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
@@ -111,6 +111,7 @@
 
     xmlDocPtr m_stylesheetDoc;
     bool m_stylesheetDocTaken;
+    bool m_compilationFailed;
 
     XSLStyleSheet* m_parentStyleSheet;
 };
diff --git a/Source/core/xml/XSLStyleSheetLibxslt.cpp b/Source/core/xml/XSLStyleSheetLibxslt.cpp
index 35ea279..15e8a66 100644
--- a/Source/core/xml/XSLStyleSheetLibxslt.cpp
+++ b/Source/core/xml/XSLStyleSheetLibxslt.cpp
@@ -47,6 +47,7 @@
     , m_processed(false) // Child sheets get marked as processed when the libxslt engine has finally seen them.
     , m_stylesheetDoc(0)
     , m_stylesheetDocTaken(false)
+    , m_compilationFailed(false)
     , m_parentStyleSheet(parentRule ? parentRule->parentStyleSheet() : 0)
 {
 }
@@ -60,6 +61,7 @@
     , m_processed(true) // The root sheet starts off processed.
     , m_stylesheetDoc(0)
     , m_stylesheetDocTaken(false)
+    , m_compilationFailed(false)
     , m_parentStyleSheet(0)
 {
 }
@@ -129,7 +131,7 @@
     PageConsole* console = 0;
     Frame* frame = ownerDocument()->frame();
     if (frame && frame->page())
-        console = frame->page()->console();
+        console = &frame->page()->console();
 
     XMLDocumentParserScope scope(fetcher(), XSLTProcessor::genericErrorFunc, XSLTProcessor::parseErrorFunc, console);
     XMLParserInput input(source);
@@ -226,12 +228,19 @@
     if (m_embedded)
         return xsltLoadStylesheetPI(document());
 
+    // Certain libxslt versions are corrupting the xmlDoc on compilation failures -
+    // hence attempting to recompile after a failure is unsafe.
+    if (m_compilationFailed)
+        return 0;
+
     // xsltParseStylesheetDoc makes the document part of the stylesheet
     // so we have to release our pointer to it.
     ASSERT(!m_stylesheetDocTaken);
     xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc);
     if (result)
         m_stylesheetDocTaken = true;
+    else
+        m_compilationFailed = true;
     return result;
 }
 
diff --git a/Source/core/xml/XSLTProcessor.cpp b/Source/core/xml/XSLTProcessor.cpp
index 043fd8d..d1807cd 100644
--- a/Source/core/xml/XSLTProcessor.cpp
+++ b/Source/core/xml/XSLTProcessor.cpp
@@ -21,7 +21,6 @@
  */
 
 #include "config.h"
-
 #include "core/xml/XSLTProcessor.h"
 
 #include "core/dom/DOMImplementation.h"
@@ -33,9 +32,8 @@
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "weborigin/SecurityOrigin.h"
-
-#include <wtf/Assertions.h>
-#include <wtf/Vector.h>
+#include "wtf/Assertions.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/xml/XSLTProcessorLibxslt.cpp b/Source/core/xml/XSLTProcessorLibxslt.cpp
index 6e3866c..74fcf53 100644
--- a/Source/core/xml/XSLTProcessorLibxslt.cpp
+++ b/Source/core/xml/XSLTProcessorLibxslt.cpp
@@ -21,22 +21,12 @@
  */
 
 #include "config.h"
-
 #include "core/xml/XSLTProcessor.h"
 
-#include <libxslt/imports.h>
-#include <libxslt/security.h>
-#include <libxslt/variables.h>
-#include <libxslt/xsltutils.h>
-#include <wtf/Assertions.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/StringBuffer.h>
-#include <wtf/unicode/UTF8.h>
-#include <wtf/Vector.h>
 #include "core/dom/Document.h"
 #include "core/dom/TransformSource.h"
 #include "core/editing/markup.h"
-#include "core/loader/cache/ResourceFetcher.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
@@ -48,6 +38,15 @@
 #include "core/xml/XSLTUnicodeSort.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "weborigin/SecurityOrigin.h"
+#include "wtf/Assertions.h"
+#include "wtf/Vector.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/StringBuffer.h"
+#include "wtf/unicode/UTF8.h"
+#include <libxslt/imports.h>
+#include <libxslt/security.h>
+#include <libxslt/variables.h>
+#include <libxslt/xsltutils.h>
 
 namespace WebCore {
 
@@ -116,7 +115,7 @@
         PageConsole* console = 0;
         Frame* frame = globalProcessor->xslStylesheet()->ownerDocument()->frame();
         if (frame && frame->page())
-            console = frame->page()->console();
+            console = &frame->page()->console();
         xmlSetStructuredErrorFunc(console, XSLTProcessor::parseErrorFunc);
         xmlSetGenericErrorFunc(console, XSLTProcessor::genericErrorFunc);
 
diff --git a/Source/core/xml/XSLTUnicodeSort.cpp b/Source/core/xml/XSLTUnicodeSort.cpp
index 316b5c4..83342cb 100644
--- a/Source/core/xml/XSLTUnicodeSort.cpp
+++ b/Source/core/xml/XSLTUnicodeSort.cpp
@@ -29,10 +29,10 @@
 #include "config.h"
 #include "core/xml/XSLTUnicodeSort.h"
 
+#include "wtf/text/WTFString.h"
+#include "wtf/unicode/Collator.h"
 #include <libxslt/templates.h>
 #include <libxslt/xsltutils.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/unicode/Collator.h>
 
 namespace WebCore {
 
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index 197868f..7f2b90f 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -26,15 +26,6 @@
 #include "config.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 
-#include <libxml/parser.h>
-#include <libxml/parserInternals.h>
-#include <libxslt/xslt.h>
-#include <wtf/StringExtras.h>
-#include <wtf/text/CString.h>
-#include <wtf/Threading.h>
-#include <wtf/unicode/UTF8.h>
-#include <wtf/UnusedParam.h>
-#include <wtf/Vector.h>
 #include "HTMLNames.h"
 #include "XMLNSNames.h"
 #include "bindings/v8/ExceptionState.h"
@@ -49,14 +40,14 @@
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/ScriptLoader.h"
 #include "core/dom/TransformSource.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ScriptResource.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/parser/HTMLEntityParser.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ImageLoader.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/ResourceFetcher.h"
-#include "core/loader/cache/ScriptResource.h"
 #include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
 #include "core/platform/network/ResourceError.h"
@@ -67,7 +58,16 @@
 #include "core/xml/parser/XMLDocumentParserScope.h"
 #include "core/xml/parser/XMLParserInput.h"
 #include "weborigin/SecurityOrigin.h"
+#include "wtf/StringExtras.h"
 #include "wtf/TemporaryChange.h"
+#include "wtf/Threading.h"
+#include "wtf/UnusedParam.h"
+#include "wtf/Vector.h"
+#include "wtf/text/CString.h"
+#include "wtf/unicode/UTF8.h"
+#include <libxml/parser.h>
+#include <libxml/parserInternals.h>
+#include <libxslt/xslt.h>
 
 using namespace std;
 
diff --git a/Source/core/xml/parser/XMLDocumentParser.h b/Source/core/xml/parser/XMLDocumentParser.h
index 7233482..64b1898 100644
--- a/Source/core/xml/parser/XMLDocumentParser.h
+++ b/Source/core/xml/parser/XMLDocumentParser.h
@@ -27,15 +27,15 @@
 
 #include "core/dom/ParserContentPolicy.h"
 #include "core/dom/ScriptableDocumentParser.h"
-#include "core/loader/cache/ResourceClient.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
 #include "core/platform/text/SegmentedString.h"
 #include "core/xml/XMLErrors.h"
+#include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/StringHash.h"
 #include <libxml/tree.h>
-#include <wtf/HashMap.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/StringHash.h>
 
 namespace WebCore {
 
diff --git a/Source/core/xml/parser/XMLDocumentParserScope.h b/Source/core/xml/parser/XMLDocumentParserScope.h
index 510c583..613d165 100644
--- a/Source/core/xml/parser/XMLDocumentParserScope.h
+++ b/Source/core/xml/parser/XMLDocumentParserScope.h
@@ -26,8 +26,7 @@
 #ifndef XMLDocumentParserScope_h
 #define XMLDocumentParserScope_h
 
-#include <wtf/Noncopyable.h>
-
+#include "wtf/Noncopyable.h"
 #include <libxml/xmlerror.h>
 
 namespace WebCore {