Merge from Chromium at DEPS revision r210036

This commit was generated by merge_to_master.py.

Change-Id: Ib2112ed87a48d7a6d9c0563ba71850716d1475ef
diff --git a/Source/core/dom/ActiveDOMObject.cpp b/Source/core/dom/ActiveDOMObject.cpp
index a3270fc..c2008aa 100644
--- a/Source/core/dom/ActiveDOMObject.cpp
+++ b/Source/core/dom/ActiveDOMObject.cpp
@@ -33,7 +33,7 @@
 namespace WebCore {
 
 ActiveDOMObject::ActiveDOMObject(ScriptExecutionContext* scriptExecutionContext)
-    : ContextDestructionObserver(scriptExecutionContext)
+    : ContextLifecycleObserver(scriptExecutionContext, ActiveDOMObjectType)
     , m_pendingActivityCount(0)
 #if !ASSERT_DISABLED
     , m_suspendIfNeededCalled(false)
@@ -43,26 +43,22 @@
         return;
 
     ASSERT(m_scriptExecutionContext->isContextThread());
-    m_scriptExecutionContext->didCreateActiveDOMObject(this);
 }
 
 ActiveDOMObject::~ActiveDOMObject()
 {
+    // ActiveDOMObject may be inherited by a sub-class whose life-cycle
+    // exceeds that of the associated ScriptExecutionContext. In those cases,
+    // m_scriptExecutionContext would/should have been nullified by
+    // ContextLifecycleObserver::contextDestroyed() (which we implement /
+    // inherit). Hence, we should ensure that this is not 0 before use it
+    // here.
     if (!m_scriptExecutionContext)
         return;
 
     ASSERT(m_suspendIfNeededCalled);
-
-    // ActiveDOMObject may be inherited by a sub-class whose life-cycle
-    // exceeds that of the associated ScriptExecutionContext. In those cases,
-    // m_scriptExecutionContext would/should have been nullified by
-    // ContextDestructionObserver::contextDestroyed() (which we implement /
-    // inherit). Hence, we should ensure that this is not 0 before use it
-    // here.
-    if (m_scriptExecutionContext) {
-        ASSERT(m_scriptExecutionContext->isContextThread());
-        m_scriptExecutionContext->willDestroyActiveDOMObject(this);
-    }
+    ASSERT(m_scriptExecutionContext->isContextThread());
+    observeContext(0, ActiveDOMObjectType);
 }
 
 void ActiveDOMObject::suspendIfNeeded()
diff --git a/Source/core/dom/ActiveDOMObject.h b/Source/core/dom/ActiveDOMObject.h
index d37017e..bfb47db 100644
--- a/Source/core/dom/ActiveDOMObject.h
+++ b/Source/core/dom/ActiveDOMObject.h
@@ -27,13 +27,13 @@
 #ifndef ActiveDOMObject_h
 #define ActiveDOMObject_h
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include <wtf/Assertions.h>
 #include <wtf/Forward.h>
 
 namespace WebCore {
 
-class ActiveDOMObject : public ContextDestructionObserver {
+class ActiveDOMObject : public ContextLifecycleObserver {
 public:
     ActiveDOMObject(ScriptExecutionContext*);
 
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index 7aaf56c..2d56cb2 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -24,13 +24,12 @@
 #include "core/dom/Attr.h"
 
 #include "XMLNSNames.h"
-#include "core/css/StylePropertySet.h"
+#include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ScopedEventQueue.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/Text.h"
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Attr.h b/Source/core/dom/Attr.h
index 9bff433..5f6004e 100644
--- a/Source/core/dom/Attr.h
+++ b/Source/core/dom/Attr.h
@@ -57,8 +57,6 @@
 
     bool isId() const;
 
-    CSSStyleDeclaration* style();
-
     void setSpecified(bool specified) { m_specified = specified; }
 
     void attachToElement(Element*);
@@ -100,6 +98,18 @@
     bool m_specified : 1;
 };
 
+inline Attr* toAttr(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isAttributeNode());
+    return static_cast<Attr*>(node);
+}
+
+inline const Attr* toAttr(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isAttributeNode());
+    return static_cast<const Attr*>(node);
+}
+
 } // namespace WebCore
 
 #endif // Attr_h
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index 9fda297..e57d138 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -28,14 +28,11 @@
 #include "core/dom/MutationEvent.h"
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/editing/FrameSelection.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/platform/text/TextBreakIterator.h"
-#include "core/rendering/RenderText.h"
-#include "core/rendering/style/StyleInheritedData.h"
 
 using namespace std;
 
diff --git a/Source/core/dom/CharacterData.idl b/Source/core/dom/CharacterData.idl
index 9d8ee85..2e3262c 100644
--- a/Source/core/dom/CharacterData.idl
+++ b/Source/core/dom/CharacterData.idl
@@ -36,10 +36,7 @@
      [RaisesException] void replaceData([IsIndex,Default=Undefined] optional unsigned long offset, 
                                     [IsIndex,Default=Undefined] optional unsigned long length,
                                     [Default=Undefined] optional DOMString data);
-
-    // ChildNode interface API
-    readonly attribute Element previousElementSibling;
-    readonly attribute Element nextElementSibling;
-    [RaisesException] void remove();
 };
 
+CharacterData implements ChildNode;
+
diff --git a/Source/core/dom/ChildListMutationScope.h b/Source/core/dom/ChildListMutationScope.h
index b5060e1..78c63c3 100644
--- a/Source/core/dom/ChildListMutationScope.h
+++ b/Source/core/dom/ChildListMutationScope.h
@@ -34,10 +34,9 @@
 #include "core/dom/Document.h"
 #include "core/dom/MutationObserver.h"
 #include "core/dom/Node.h"
-#include <wtf/HashMap.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/RegisteredEventListener.cpp b/Source/core/dom/ChildNode.idl
similarity index 65%
rename from Source/core/dom/RegisteredEventListener.cpp
rename to Source/core/dom/ChildNode.idl
index 6153b5c..b37f05f 100644
--- a/Source/core/dom/RegisteredEventListener.cpp
+++ b/Source/core/dom/ChildNode.idl
@@ -1,8 +1,8 @@
 /*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * 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 Apple Inc. All rights reserved.
+ * Copyright (C) 2006, 2007, 2009 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
@@ -20,11 +20,10 @@
  * Boston, MA 02110-1301, USA.
  */
 
-#include "config.h"
-#include "core/dom/RegisteredEventListener.h"
+[NoInterfaceObject]
+interface ChildNode {
+    [PerWorldBindings] readonly attribute Element previousElementSibling;
+    [PerWorldBindings] readonly attribute Element nextElementSibling;
+    [RaisesException] void remove();
+};
 
-#include "core/dom/EventListener.h"
-
-namespace WebCore {
-
-} // namespace WebCore
diff --git a/Source/core/dom/Clipboard.h b/Source/core/dom/Clipboard.h
index ef51bf3..1593a5c 100644
--- a/Source/core/dom/Clipboard.h
+++ b/Source/core/dom/Clipboard.h
@@ -31,13 +31,17 @@
 #include "core/page/DragActions.h"
 #include "core/platform/DragImage.h"
 #include "core/platform/graphics/IntPoint.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
+class CachedImage;
 class DataTransferItemList;
 class DragData;
+class DragImage;
 class FileList;
 class Frame;
+class Range;
 
 // State available during IE's events for drag and drop and copy/paste
 class Clipboard : public RefCounted<Clipboard>, public ScriptWrappable {
@@ -76,7 +80,7 @@
     Node* dragImageElement() const { return m_dragImageElement.get(); }
     virtual void setDragImageElement(Node*, const IntPoint&) = 0;
 
-    virtual DragImageRef createDragImage(IntPoint& dragLocation) const = 0;
+    virtual PassOwnPtr<DragImage> createDragImage(IntPoint& dragLocation) const = 0;
     virtual void declareAndWriteDragImage(Element*, const KURL&, const String& title, Frame*) = 0;
     virtual void writeURL(const KURL&, const String&, Frame*) = 0;
     virtual void writeRange(Range*, Frame*) = 0;
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index 33bf98d..1f9b351 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -33,13 +33,11 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLCollection.h"
-#include "core/page/Page.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderWidget.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
 
 using namespace std;
 
@@ -558,9 +556,6 @@
     // The container node can be removed from event handlers.
     RefPtr<ContainerNode> protect(this);
 
-    // exclude this node when looking for removed focusedNode since only children will be removed
-    document()->removeFocusedNodeOfSubtree(this, true);
-
     if (FullscreenController* fullscreen = FullscreenController::fromIfExists(document()))
         fullscreen->removeFullScreenElementOfSubtree(this, true);
 
@@ -568,6 +563,12 @@
     // and remove... e.g. stop loading frames, fire unload events.
     willRemoveChildren(protect.get());
 
+    // Exclude this node when looking for removed focusedNode since only
+    // children will be removed.
+    // This must be later than willRemvoeChildren, which might change focus
+    // state of a child.
+    document()->removeFocusedNodeOfSubtree(this, true);
+
     NodeVector removedChildren;
     {
         WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
@@ -713,13 +714,13 @@
 
 void ContainerNode::attach(const AttachContext& context)
 {
-    attachChildren();
+    attachChildren(context);
     Node::attach(context);
 }
 
 void ContainerNode::detach(const AttachContext& context)
 {
-    detachChildren();
+    detachChildren(context);
     clearChildNeedsStyleRecalc();
     Node::detach(context);
 }
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index e25b308..28dea40 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -127,11 +127,6 @@
     // node that is of the type CDATA_SECTION_NODE, TEXT_NODE or COMMENT_NODE has changed its value.
     virtual void childrenChanged(bool createdByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    void attachChildren();
-    void attachChildrenLazily();
-    void detachChildren();
-    void detachChildrenIfNeeded();
-
     void disconnectDescendantFrames();
 
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const { return true; }
@@ -158,6 +153,9 @@
     void removeBetween(Node* previousChild, Node* nextChild, Node* oldChild);
     void insertBeforeCommon(Node* nextChild, Node* oldChild);
 
+    void attachChildren(const AttachContext& = AttachContext());
+    void detachChildren(const AttachContext& = AttachContext());
+
     static void dispatchPostAttachCallbacks();
 
     void suspendPostAttachCallbacks();
@@ -196,34 +194,25 @@
 {
 }
 
-inline void ContainerNode::attachChildren()
+inline void ContainerNode::attachChildren(const AttachContext& context)
 {
+    AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
+
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         ASSERT(!child->attached() || childAttachedAllowedWhenAttachingChildren(this));
         if (!child->attached())
-            child->attach();
+            child->attach(childrenContext);
     }
 }
 
-inline void ContainerNode::attachChildrenLazily()
+inline void ContainerNode::detachChildren(const AttachContext& context)
 {
-    for (Node* child = firstChild(); child; child = child->nextSibling())
-        if (!child->attached())
-            child->lazyAttach();
-}
+    AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
 
-inline void ContainerNode::detachChildrenIfNeeded()
-{
-    for (Node* child = firstChild(); child; child = child->nextSibling()) {
-        if (child->attached())
-            child->detach();
-    }
-}
-
-inline void ContainerNode::detachChildren()
-{
     for (Node* child = firstChild(); child; child = child->nextSibling())
-        child->detach();
+        child->detach(childrenContext);
 }
 
 inline unsigned Node::childNodeCount() const
diff --git a/Source/core/dom/ContainerNodeAlgorithms.h b/Source/core/dom/ContainerNodeAlgorithms.h
index 5e09a6b..f02eb7f 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.h
+++ b/Source/core/dom/ContainerNodeAlgorithms.h
@@ -26,8 +26,7 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Frame.h"
-#include <wtf/Assertions.h>
+#include "wtf/Assertions.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ContextLifecycleNotifier.cpp b/Source/core/dom/ContextLifecycleNotifier.cpp
new file mode 100644
index 0000000..1c1b72f
--- /dev/null
+++ b/Source/core/dom/ContextLifecycleNotifier.cpp
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/ContextLifecycleNotifier.h"
+
+#include "core/dom/WebCoreMemoryInstrumentation.h"
+#include "wtf/TemporaryChange.h"
+
+namespace WebCore {
+
+ContextLifecycleNotifier::ContextLifecycleNotifier(ScriptExecutionContext* context)
+    : m_context(context)
+    , m_iterating(IteratingNone)
+    , m_inDestructor(false)
+{
+}
+
+ContextLifecycleNotifier::~ContextLifecycleNotifier()
+{
+    m_inDestructor = true;
+    for (ContextObserverSet::iterator iter = m_contextObservers.begin(); iter != m_contextObservers.end(); iter = m_contextObservers.begin()) {
+        ContextLifecycleObserver* observer = *iter;
+        m_contextObservers.remove(observer);
+        ASSERT(observer->scriptExecutionContext() == m_context);
+        observer->contextDestroyed();
+    }
+}
+
+void ContextLifecycleNotifier::addObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    RELEASE_ASSERT(!m_inDestructor);
+    RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
+    m_contextObservers.add(observer);
+    if (as == ContextLifecycleObserver::ActiveDOMObjectType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
+        m_activeDOMObjects.add(static_cast<ActiveDOMObject*>(observer));
+    }
+}
+
+void ContextLifecycleNotifier::removeObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    RELEASE_ASSERT(!m_inDestructor);
+    RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
+    m_contextObservers.remove(observer);
+    if (as == ContextLifecycleObserver::ActiveDOMObjectType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
+        m_activeDOMObjects.remove(static_cast<ActiveDOMObject*>(observer));
+    }
+}
+
+void ContextLifecycleNotifier::notifyResumingActiveDOMObjects()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        (*iter)->resume();
+    }
+}
+
+void ContextLifecycleNotifier::notifySuspendingActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        (*iter)->suspend(why);
+    }
+}
+
+void ContextLifecycleNotifier::notifyStoppingActiveDOMObjects()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        (*iter)->stop();
+    }
+}
+
+bool ContextLifecycleNotifier::canSuspendActiveDOMObjects()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::const_iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        if (!(*iter)->canSuspend())
+            return false;
+    }
+
+    return true;
+}
+
+bool ContextLifecycleNotifier::hasPendingActivity() const
+{
+    ActiveDOMObjectSet::const_iterator activeObjectsEnd = activeDOMObjects().end();
+    for (ActiveDOMObjectSet::const_iterator iter = activeDOMObjects().begin(); iter != activeObjectsEnd; ++iter) {
+        if ((*iter)->hasPendingActivity())
+            return true;
+    }
+
+    return false;
+}
+
+void ContextLifecycleNotifier::reportMemoryUsage(WTF::MemoryObjectInfo* memoryObjectInfo) const
+{
+    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter)
+        info.addMember(*iter, "activeDOMObject", WTF::RetainingPointer);
+}
+
+} // namespace WebCore
+
diff --git a/Source/core/dom/ContextLifecycleNotifier.h b/Source/core/dom/ContextLifecycleNotifier.h
new file mode 100644
index 0000000..4929ade
--- /dev/null
+++ b/Source/core/dom/ContextLifecycleNotifier.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+#ifndef ContextLifecycleNotifier_h
+#define ContextLifecycleNotifier_h
+
+#include "core/dom/ActiveDOMObject.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WTF {
+class MemoryObjectInfo;
+}
+
+namespace WebCore {
+
+class ActiveDOMObject;
+class ContextLifecycleObserver;
+class ScriptExecutionContext;
+
+class ContextLifecycleNotifier {
+public:
+    static PassOwnPtr<ContextLifecycleNotifier> create(ScriptExecutionContext*);
+
+    virtual ~ContextLifecycleNotifier();
+
+    typedef HashSet<ContextLifecycleObserver*> ContextObserverSet;
+    typedef HashSet<ActiveDOMObject*> ActiveDOMObjectSet;
+
+    const ActiveDOMObjectSet& activeDOMObjects() const { return m_activeDOMObjects; }
+
+    virtual void addObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
+    virtual void removeObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
+
+    void notifyResumingActiveDOMObjects();
+    void notifySuspendingActiveDOMObjects(ActiveDOMObject::ReasonForSuspension);
+    void notifyStoppingActiveDOMObjects();
+
+    bool contains(ActiveDOMObject* object) const { return m_activeDOMObjects.contains(object); }
+    bool canSuspendActiveDOMObjects();
+    bool hasPendingActivity() const;
+
+    void reportMemoryUsage(WTF::MemoryObjectInfo*) const;
+
+protected:
+    explicit ContextLifecycleNotifier(ScriptExecutionContext*);
+
+    enum IterationType {
+        IteratingNone,
+        IteratingOverActiveDOMObjects,
+        IteratingOverContextObservers,
+        IteratingOverDocumentObservers
+    };
+
+    IterationType m_iterating;
+
+private:
+    ScriptExecutionContext* m_context;
+    ContextObserverSet m_contextObservers;
+    ActiveDOMObjectSet m_activeDOMObjects;
+    bool m_inDestructor;
+};
+
+inline PassOwnPtr<ContextLifecycleNotifier> ContextLifecycleNotifier::create(ScriptExecutionContext* context)
+{
+    return adoptPtr(new ContextLifecycleNotifier(context));
+}
+
+} // namespace WebCore
+
+#endif // ContextLifecycleNotifier_h
+
diff --git a/Source/core/dom/ContextDestructionObserver.cpp b/Source/core/dom/ContextLifecycleObserver.cpp
similarity index 74%
rename from Source/core/dom/ContextDestructionObserver.cpp
rename to Source/core/dom/ContextLifecycleObserver.cpp
index 6750d80..656f54e 100644
--- a/Source/core/dom/ContextDestructionObserver.cpp
+++ b/Source/core/dom/ContextLifecycleObserver.cpp
@@ -20,44 +20,45 @@
  * 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/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 
 #include "core/dom/ScriptExecutionContext.h"
 
 namespace WebCore {
 
-ContextDestructionObserver::ContextDestructionObserver(ScriptExecutionContext* scriptExecutionContext)
+ContextLifecycleObserver::ContextLifecycleObserver(ScriptExecutionContext* scriptExecutionContext, Type type)
     : m_scriptExecutionContext(0)
 {
-    observeContext(scriptExecutionContext);
+    observeContext(scriptExecutionContext, type);
 }
 
-ContextDestructionObserver::~ContextDestructionObserver()
+ContextLifecycleObserver::~ContextLifecycleObserver()
 {
-    observeContext(0);
+    if (m_scriptExecutionContext)
+        observeContext(0, GenericType);
 }
 
-void ContextDestructionObserver::observeContext(ScriptExecutionContext* scriptExecutionContext)
+void ContextLifecycleObserver::observeContext(ScriptExecutionContext* scriptExecutionContext, Type as)
 {
     if (m_scriptExecutionContext) {
         ASSERT(m_scriptExecutionContext->isContextThread());
-        m_scriptExecutionContext->willDestroyDestructionObserver(this);
+        m_scriptExecutionContext->wasUnobservedBy(this, as);
     }
 
     m_scriptExecutionContext = scriptExecutionContext;
 
     if (m_scriptExecutionContext) {
         ASSERT(m_scriptExecutionContext->isContextThread());
-        m_scriptExecutionContext->didCreateDestructionObserver(this);
+        m_scriptExecutionContext->wasObservedBy(this, as);
     }
 }
 
-void ContextDestructionObserver::contextDestroyed()
+void ContextLifecycleObserver::contextDestroyed()
 {
     m_scriptExecutionContext = 0;
 }
diff --git a/Source/core/dom/ContextDestructionObserver.h b/Source/core/dom/ContextLifecycleObserver.h
similarity index 78%
rename from Source/core/dom/ContextDestructionObserver.h
rename to Source/core/dom/ContextLifecycleObserver.h
index ca956ab..574455e 100644
--- a/Source/core/dom/ContextDestructionObserver.h
+++ b/Source/core/dom/ContextLifecycleObserver.h
@@ -20,31 +20,37 @@
  * 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.
  *
  */
 
-#ifndef ContextDestructionObserver_h
-#define ContextDestructionObserver_h
+#ifndef ContextLifecycleObserver_h
+#define ContextLifecycleObserver_h
 
 namespace WebCore {
 
 class ScriptExecutionContext;
 
-class ContextDestructionObserver {
+class ContextLifecycleObserver {
 public:
-    explicit ContextDestructionObserver(ScriptExecutionContext*);
+    enum Type {
+        ActiveDOMObjectType,
+        DocumentLifecycleObserverType,
+        GenericType
+    };
+
+    explicit ContextLifecycleObserver(ScriptExecutionContext*, Type = GenericType);
     virtual void contextDestroyed();
 
     ScriptExecutionContext* scriptExecutionContext() const { return m_scriptExecutionContext; }
 
 protected:
-    virtual ~ContextDestructionObserver();
-    void observeContext(ScriptExecutionContext*);
+    virtual ~ContextLifecycleObserver();
+    void observeContext(ScriptExecutionContext*, Type);
 
     ScriptExecutionContext* m_scriptExecutionContext;
 };
 
 } // namespace WebCore
 
-#endif // ContextDestructionObserver_h
+#endif // ContextLifecycleObserver_h
diff --git a/Source/core/dom/CustomElementCallback.h b/Source/core/dom/CustomElementCallback.h
new file mode 100644
index 0000000..d71e35a
--- /dev/null
+++ b/Source/core/dom/CustomElementCallback.h
@@ -0,0 +1,61 @@
+/*
+ * 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 CustomElementCallback_h
+#define CustomElementCallback_h
+
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class Element;
+
+class CustomElementCallback : public RefCounted<CustomElementCallback> {
+public:
+    virtual ~CustomElementCallback() { }
+
+    bool hasReady() const { return m_which == Ready; }
+    virtual void ready(Element*) = 0;
+
+protected:
+    enum CallbackType {
+        None,
+        Ready
+    };
+
+    CustomElementCallback(CallbackType which) : m_which(which) { }
+
+private:
+    CallbackType m_which;
+};
+
+}
+
+#endif // CustomElementCallback_h
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.cpp b/Source/core/dom/CustomElementCallbackDispatcher.cpp
new file mode 100644
index 0000000..667c6c2
--- /dev/null
+++ b/Source/core/dom/CustomElementCallbackDispatcher.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 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 "CustomElementCallbackDispatcher.h"
+
+#include "CustomElementCallback.h"
+
+namespace WebCore {
+
+CustomElementCallbackDispatcher& CustomElementCallbackDispatcher::instance()
+{
+    DEFINE_STATIC_LOCAL(CustomElementCallbackDispatcher, instance, ());
+    return instance;
+}
+
+CustomElementCallbackDispatcher::ReadyInvocation::ReadyInvocation(PassRefPtr<CustomElementCallback> callback, PassRefPtr<Element> element)
+    : m_callback(callback)
+    , m_element(element)
+{
+}
+
+bool CustomElementCallbackDispatcher::dispatch()
+{
+    if (m_invocations.isEmpty())
+        return false;
+
+    do  {
+        Vector<ReadyInvocation> invocations;
+        m_invocations.swap(invocations);
+
+        for (Vector<ReadyInvocation>::iterator it = invocations.begin(); it != invocations.end(); ++it)
+            it->invoke();
+    } while (!m_invocations.isEmpty());
+
+    return true;
+}
+
+void CustomElementCallbackDispatcher::enqueueReadyCallback(CustomElementCallback* callback, Element* element)
+{
+    if (!callback->hasReady())
+        return;
+
+    m_invocations.append(ReadyInvocation(callback, element));
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.h b/Source/core/dom/CustomElementCallbackDispatcher.h
new file mode 100644
index 0000000..46a4f76
--- /dev/null
+++ b/Source/core/dom/CustomElementCallbackDispatcher.h
@@ -0,0 +1,86 @@
+/*
+ * 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 CustomElementCallbackDispatcher_h
+#define CustomElementCallbackDispatcher_h
+
+#include "core/dom/CustomElementCallback.h"
+#include "core/dom/Element.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class CustomElementCallbackDispatcher {
+    WTF_MAKE_NONCOPYABLE(CustomElementCallbackDispatcher);
+public:
+    static CustomElementCallbackDispatcher& instance();
+
+    class CallbackDeliveryScope {
+    public:
+        CallbackDeliveryScope() { }
+        ~CallbackDeliveryScope()
+        {
+            CustomElementCallbackDispatcher& dispatcher = CustomElementCallbackDispatcher::instance();
+            if (dispatcher.hasQueuedCallbacks())
+                dispatcher.dispatch();
+        }
+    };
+
+    void enqueueReadyCallback(CustomElementCallback*, Element*);
+
+    // Returns true if more work may have to be performed at the
+    // checkpoint by this or other workers (for example, this work
+    // invoked author scripts)
+    bool dispatch();
+
+private:
+    explicit CustomElementCallbackDispatcher() { }
+
+    bool hasQueuedCallbacks() { return !m_invocations.isEmpty(); }
+
+    class ReadyInvocation {
+    public:
+        ReadyInvocation(PassRefPtr<CustomElementCallback>, PassRefPtr<Element>);
+        virtual ~ReadyInvocation() { }
+        void invoke() { m_callback->ready(m_element.get()); }
+
+    private:
+        RefPtr<CustomElementCallback> m_callback;
+        RefPtr<Element> m_element;
+    };
+
+    Vector<ReadyInvocation> m_invocations;
+};
+
+}
+
+#endif // CustomElementCallbackDispatcher_h
diff --git a/Source/core/dom/CustomElementDefinition.cpp b/Source/core/dom/CustomElementDefinition.cpp
index 70666dc..827383b 100644
--- a/Source/core/dom/CustomElementDefinition.cpp
+++ b/Source/core/dom/CustomElementDefinition.cpp
@@ -32,20 +32,17 @@
 
 #include "core/dom/CustomElementDefinition.h"
 
-#include "SVGNames.h"
-#include "bindings/v8/CustomElementHelpers.h"
-#include <wtf/Assertions.h>
-
 namespace WebCore {
 
-PassRefPtr<CustomElementDefinition> CustomElementDefinition::create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI)
+PassRefPtr<CustomElementDefinition> CustomElementDefinition::create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback> callback)
 {
-    return adoptRef(new CustomElementDefinition(type, name, namespaceURI));
+    return adoptRef(new CustomElementDefinition(type, name, namespaceURI, callback));
 }
 
-CustomElementDefinition::CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI)
+CustomElementDefinition::CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback> callback)
     : m_type(type)
     , m_tag(QualifiedName(nullAtom, name, namespaceURI))
+    , m_callback(callback)
 {
 }
 
diff --git a/Source/core/dom/CustomElementDefinition.h b/Source/core/dom/CustomElementDefinition.h
index ac5fe2d..a3a7134 100644
--- a/Source/core/dom/CustomElementDefinition.h
+++ b/Source/core/dom/CustomElementDefinition.h
@@ -31,7 +31,7 @@
 #ifndef CustomElementDefinition_h
 #define CustomElementDefinition_h
 
-#include "bindings/v8/ScriptValue.h"
+#include "core/dom/CustomElementCallback.h"
 #include "core/dom/QualifiedName.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
@@ -39,11 +39,9 @@
 
 namespace WebCore {
 
-class ScriptState;
-
 class CustomElementDefinition : public RefCounted<CustomElementDefinition> {
 public:
-    static PassRefPtr<CustomElementDefinition> create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI);
+    static PassRefPtr<CustomElementDefinition> create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback>);
 
     virtual ~CustomElementDefinition() {}
 
@@ -72,11 +70,14 @@
     CustomElementKind kind() const { return isTypeExtension() ? TypeExtension : CustomTag; }
     bool isTypeExtension() const { return type() != name(); }
 
+    CustomElementCallback* callback() const { return m_callback.get(); }
+
 private:
-    CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI);
+    CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback>);
 
     AtomicString m_type;
     QualifiedName m_tag;
+    RefPtr<CustomElementCallback> m_callback;
 };
 
 }
diff --git a/Source/core/dom/CustomElementRegistry.cpp b/Source/core/dom/CustomElementRegistry.cpp
index 3bad3ba..3eeb0df 100644
--- a/Source/core/dom/CustomElementRegistry.cpp
+++ b/Source/core/dom/CustomElementRegistry.cpp
@@ -29,14 +29,12 @@
  */
 
 #include "config.h"
-
 #include "core/dom/CustomElementRegistry.h"
 
 #include "HTMLNames.h"
 #include "SVGNames.h"
-#include "bindings/v8/CustomElementHelpers.h"
-#include "bindings/v8/Dictionary.h"
-#include "bindings/v8/ScriptValue.h"
+#include "bindings/v8/CustomElementConstructorBuilder.h"
+#include "core/dom/CustomElementCallbackDispatcher.h"
 #include "core/dom/CustomElementDefinition.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
@@ -45,15 +43,6 @@
 
 namespace WebCore {
 
-CustomElementInvocation::CustomElementInvocation(PassRefPtr<Element> element)
-    : m_element(element)
-{
-}
-
-CustomElementInvocation::~CustomElementInvocation()
-{
-}
-
 void setTypeExtension(Element* element, const AtomicString& typeExtension)
 {
     ASSERT(element);
@@ -62,15 +51,10 @@
 }
 
 CustomElementRegistry::CustomElementRegistry(Document* document)
-    : ContextDestructionObserver(document)
+    : ContextLifecycleObserver(document)
 {
 }
 
-CustomElementRegistry::~CustomElementRegistry()
-{
-    deactivate();
-}
-
 static inline bool nameIncludesHyphen(const AtomicString& name)
 {
     size_t hyphenPosition = name.find('-');
@@ -99,79 +83,66 @@
     return Document::isValidName(name.string());
 }
 
-ScriptValue CustomElementRegistry::registerElement(ScriptState* state, const AtomicString& userSuppliedName, const Dictionary& options, ExceptionCode& ec)
+void CustomElementRegistry::registerElement(CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, ExceptionCode& ec)
 {
     RefPtr<CustomElementRegistry> protect(this);
 
-    if (!CustomElementHelpers::isFeatureAllowed(state))
-        return ScriptValue();
+    if (!constructorBuilder->isFeatureAllowed())
+        return;
 
-    AtomicString name = userSuppliedName.lower();
-    if (!isValidName(name)) {
+    AtomicString type = userSuppliedName.lower();
+    if (!isValidName(type)) {
         ec = INVALID_CHARACTER_ERR;
-        return ScriptValue();
+        return;
     }
 
-    ScriptValue prototypeValue;
-    if (!options.get("prototype", prototypeValue)) {
-        // FIXME: Implement the default value handling.
-        // Currently default value of the "prototype" parameter, which
-        // is HTMLSpanElement.prototype, has an ambiguity about its
-        // behavior. The spec should be fixed before WebKit implements
-        // it. https://www.w3.org/Bugs/Public/show_bug.cgi?id=20801
+    if (!constructorBuilder->validateOptions()) {
         ec = INVALID_STATE_ERR;
-        return ScriptValue();
+        return;
     }
 
-    AtomicString namespaceURI;
-    if (!CustomElementHelpers::isValidPrototypeParameter(prototypeValue, state, namespaceURI)) {
-        ec = INVALID_STATE_ERR;
-        return ScriptValue();
-    }
-
-    if (namespaceURI.isNull()) {
+    QualifiedName tagName = nullQName();
+    if (!constructorBuilder->findTagName(type, tagName)) {
         ec = NAMESPACE_ERR;
-        return ScriptValue();
+        return;
     }
+    ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
 
-    AtomicString type = name;
     if (m_definitions.contains(type)) {
         ec = INVALID_STATE_ERR;
-        return ScriptValue();
+        return;
     }
 
-    const QualifiedName* prototypeTagName = CustomElementHelpers::findLocalName(prototypeValue);
-    if (prototypeTagName)
-        name = prototypeTagName->localName();
+    RefPtr<CustomElementCallback> lifecycleCallbacks = constructorBuilder->createCallback(document());
 
-    // A script execution could happen in isValidPrototypeParameter(), which kills the document.
+    // Consulting the constructor builder could execute script and
+    // kill the document.
     if (!document()) {
         ec = INVALID_STATE_ERR;
-        return ScriptValue();
+        return;
     }
 
-    ASSERT(name == type || QualifiedName(nullAtom, name, namespaceURI) == *CustomElementHelpers::findLocalName(prototypeValue));
-    ASSERT(namespaceURI == HTMLNames::xhtmlNamespaceURI || namespaceURI == SVGNames::svgNamespaceURI);
+    RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(type, tagName.localName(), tagName.namespaceURI(), lifecycleCallbacks);
 
-    RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(type, name, namespaceURI);
-    ScriptValue constructor = CustomElementHelpers::createConstructor(state, prototypeValue, document(), definition->namespaceURI(), definition->name(), definition->isTypeExtension() ? definition->type() : nullAtom);
-    if (constructor.hasNoValue()) {
-        ec = INVALID_STATE_ERR;
-        return ScriptValue();
+    if (!constructorBuilder->createConstructor(document(), definition.get())) {
+        ec = NOT_SUPPORTED_ERR;
+        return;
     }
-    ASSERT(constructor.isFunction());
 
     m_definitions.add(definition->type(), definition);
 
     // Upgrade elements that were waiting for this definition.
     CustomElementUpgradeCandidateMap::ElementSet upgradeCandidates = m_candidates.takeUpgradeCandidatesFor(definition.get());
-    CustomElementHelpers::didRegisterDefinition(definition.get(), document(), upgradeCandidates, prototypeValue);
-    for (CustomElementUpgradeCandidateMap::ElementSet::iterator it = upgradeCandidates.begin(); it != upgradeCandidates.end(); ++it) {
-        (*it)->setNeedsStyleRecalc(); // :unresolved has changed
-        activate(CustomElementInvocation(*it));
+    if (!constructorBuilder->didRegisterDefinition(definition.get(), upgradeCandidates)) {
+        ec = NOT_SUPPORTED_ERR;
+        return;
     }
 
-    return constructor;
+    for (CustomElementUpgradeCandidateMap::ElementSet::iterator it = upgradeCandidates.begin(); it != upgradeCandidates.end(); ++it) {
+        (*it)->setNeedsStyleRecalc(); // :unresolved has changed
+
+        CustomElementCallbackDispatcher::instance().enqueueReadyCallback(lifecycleCallbacks.get(), *it);
+    }
 }
 
 bool CustomElementRegistry::isUnresolved(Element* element) const
@@ -238,7 +209,7 @@
         // custom tag element will be unresolved in perpetuity.
         didCreateUnresolvedElement(CustomElementDefinition::CustomTag, tagName.localName(), element.get());
     } else {
-        didCreateCustomTagElement(element.get());
+        didCreateCustomTagElement(definition.get(), element.get());
     }
 
     return element.release();
@@ -255,13 +226,13 @@
         // extension element will be unresolved in perpetuity.
         didCreateUnresolvedElement(CustomElementDefinition::TypeExtension, type, element);
     } else {
-        activate(CustomElementInvocation(element));
+        CustomElementCallbackDispatcher::instance().enqueueReadyCallback(definition->callback(), element);
     }
 }
 
-void CustomElementRegistry::didCreateCustomTagElement(Element* element)
+void CustomElementRegistry::didCreateCustomTagElement(CustomElementDefinition* definition, Element* element)
 {
-    activate(CustomElementInvocation(element));
+    CustomElementCallbackDispatcher::instance().enqueueReadyCallback(definition->callback(), element);
 }
 
 void CustomElementRegistry::didCreateUnresolvedElement(CustomElementDefinition::CustomElementKind kind, const AtomicString& type, Element* element)
@@ -275,49 +246,9 @@
     m_candidates.remove(element);
 }
 
-void CustomElementRegistry::activate(const CustomElementInvocation& invocation)
-{
-    bool wasInactive = m_invocations.isEmpty();
-    m_invocations.append(invocation);
-    if (wasInactive)
-        activeCustomElementRegistries().add(this);
-}
-
-void CustomElementRegistry::deactivate()
-{
-    ASSERT(m_invocations.isEmpty());
-    if (activeCustomElementRegistries().contains(this))
-        activeCustomElementRegistries().remove(this);
-}
-
 inline Document* CustomElementRegistry::document() const
 {
     return toDocument(m_scriptExecutionContext);
 }
 
-void CustomElementRegistry::deliverLifecycleCallbacks()
-{
-    ASSERT(!m_invocations.isEmpty());
-
-    if (!m_invocations.isEmpty()) {
-        Vector<CustomElementInvocation> invocations;
-        m_invocations.swap(invocations);
-        CustomElementHelpers::invokeReadyCallbacksIfNeeded(m_scriptExecutionContext, invocations);
-    }
-
-    ASSERT(m_invocations.isEmpty());
-    deactivate();
-}
-
-void CustomElementRegistry::deliverAllLifecycleCallbacks()
-{
-    while (!activeCustomElementRegistries().isEmpty()) {
-        Vector<RefPtr<CustomElementRegistry> > registries;
-        copyToVector(activeCustomElementRegistries(), registries);
-        activeCustomElementRegistries().clear();
-        for (size_t i = 0; i < registries.size(); ++i)
-            registries[i]->deliverLifecycleCallbacks();
-    }
-}
-
 }
diff --git a/Source/core/dom/CustomElementRegistry.h b/Source/core/dom/CustomElementRegistry.h
index 532f623..525618a 100644
--- a/Source/core/dom/CustomElementRegistry.h
+++ b/Source/core/dom/CustomElementRegistry.h
@@ -31,58 +31,35 @@
 #ifndef CustomElementRegistry_h
 #define CustomElementRegistry_h
 
-#include "bindings/v8/ScriptValue.h"
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/CustomElementUpgradeCandidateMap.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/QualifiedName.h"
-#include "wtf/HashSet.h"
-#include "wtf/ListHashSet.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
+class CustomElementConstructorBuilder;
 class CustomElementDefinition;
-class Dictionary;
 class Document;
 class Element;
-class ScriptState;
-
-class CustomElementInvocation {
-public:
-    explicit CustomElementInvocation(PassRefPtr<Element>);
-    ~CustomElementInvocation();
-
-    Element* element() const { return m_element.get(); }
-
-private:
-    RefPtr<Element> m_element;
-};
 
 void setTypeExtension(Element*, const AtomicString& typeExtension);
 
-class CustomElementRegistry : public RefCounted<CustomElementRegistry>, public ContextDestructionObserver {
+class CustomElementRegistry : public RefCounted<CustomElementRegistry>, public ContextLifecycleObserver {
     WTF_MAKE_NONCOPYABLE(CustomElementRegistry); WTF_MAKE_FAST_ALLOCATED;
 public:
-    class CallbackDeliveryScope {
-    public:
-        CallbackDeliveryScope() { }
-        ~CallbackDeliveryScope() { CustomElementRegistry::deliverAllLifecycleCallbacksIfNeeded(); }
-    };
-
     explicit CustomElementRegistry(Document*);
-    ~CustomElementRegistry();
+    virtual ~CustomElementRegistry() { }
 
-    ScriptValue registerElement(ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionCode&);
+    void registerElement(CustomElementConstructorBuilder*, const AtomicString& name, ExceptionCode&);
 
     bool isUnresolved(Element*) const;
     PassRefPtr<CustomElementDefinition> findFor(Element*) const;
-    PassRefPtr<CustomElementDefinition> findAndCheckNamespace(const AtomicString& type, const AtomicString& namespaceURI) const;
 
     PassRefPtr<Element> createCustomTagElement(const QualifiedName& localName);
 
@@ -93,43 +70,19 @@
 
     static bool isCustomTagName(const AtomicString& name) { return isValidName(name); }
 
-    static void deliverAllLifecycleCallbacks();
-    static void deliverAllLifecycleCallbacksIfNeeded();
-
 private:
     typedef HashMap<AtomicString, RefPtr<CustomElementDefinition> > DefinitionMap;
-    typedef ListHashSet<CustomElementRegistry*> InstanceSet;
-
     static bool isValidName(const AtomicString&);
 
-    static InstanceSet& activeCustomElementRegistries();
-    void activate(const CustomElementInvocation&);
-    void deactivate();
-    void deliverLifecycleCallbacks();
+    PassRefPtr<CustomElementDefinition> findAndCheckNamespace(const AtomicString& type, const AtomicString& namespaceURI) const;
 
-    void didCreateCustomTagElement(Element*);
+    void didCreateCustomTagElement(CustomElementDefinition*, Element*);
     void didCreateUnresolvedElement(CustomElementDefinition::CustomElementKind, const AtomicString& type, Element*);
 
     DefinitionMap m_definitions;
     CustomElementUpgradeCandidateMap m_candidates;
-
-    Vector<CustomElementInvocation> m_invocations;
 };
 
-inline void CustomElementRegistry::deliverAllLifecycleCallbacksIfNeeded()
-{
-    if (!activeCustomElementRegistries().isEmpty())
-        deliverAllLifecycleCallbacks();
-    ASSERT(activeCustomElementRegistries().isEmpty());
-}
-
-inline CustomElementRegistry::InstanceSet& CustomElementRegistry::activeCustomElementRegistries()
-{
-    DEFINE_STATIC_LOCAL(InstanceSet, activeInstances, ());
-    return activeInstances;
-}
-
-
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/dom/DOMCoreException.cpp b/Source/core/dom/DOMCoreException.cpp
deleted file mode 100644
index 10488d5..0000000
--- a/Source/core/dom/DOMCoreException.cpp
+++ /dev/null
@@ -1,83 +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:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/DOMCoreException.h"
-
-#include "DOMException.h"
-
-namespace WebCore {
-
-static struct CoreException {
-    const char* const name;
-    const char* const description;
-} coreExceptions[] = {
-    { "IndexSizeError", "Index or size was negative, or greater than the allowed value." },
-    { 0, 0 }, // DOMStringSizeError
-    { "HierarchyRequestError", "A Node was inserted somewhere it doesn't belong." },
-    { "WrongDocumentError", "A Node was used in a different document than the one that created it (that doesn't support it)." },
-    { "InvalidCharacterError", "An invalid or illegal character was specified, such as in an XML name." },
-    { 0, 0 }, // NoDataAllowedError
-    { "NoModificationAllowedError", "An attempt was made to modify an object where modifications are not allowed." },
-    { "NotFoundError", "An attempt was made to reference a Node in a context where it does not exist." },
-    { "NotSupportedError", "The implementation did not support the requested type of object or operation." },
-    { "InUseAttributeError", "An attempt was made to add an attribute that is already in use elsewhere." },
-    { "InvalidStateError", "An attempt was made to use an object that is not, or is no longer, usable." },
-    { "SyntaxError", "An invalid or illegal string was specified." },
-    { "InvalidModificationError", "An attempt was made to modify the type of the underlying object." },
-    { "NamespaceError", "An attempt was made to create or change an object in a way which is incorrect with regard to namespaces." },
-    { "InvalidAccessError", "A parameter or an operation was not supported by the underlying object." },
-    { 0, 0 }, // ValidationError
-    { "TypeMismatchError", "The type of an object was incompatible with the expected type of the parameter associated to the object." },
-    { "SecurityError", "An attempt was made to break through the security policy of the user agent." },
-    // FIXME: Couldn't find a description in the HTML/DOM specifications for NETWORK_ERR, ABORT_ERR, URL_MISMATCH_ERR, and QUOTA_EXCEEDED_ERR
-    { "NetworkError", "A network error occurred." },
-    { "AbortError", "The user aborted a request." },
-    { "URLMismatchError", "A worker global scope represented an absolute URL that is not equal to the resulting absolute URL." },
-    { "QuotaExceededError", "An attempt was made to add something to storage that exceeded the quota." },
-    { "TimeoutError", "A timeout occurred." },
-    { "InvalidNodeTypeError", "The supplied node is invalid or has an invalid ancestor for this operation." },
-    { "DataCloneError", "An object could not be cloned." }
-};
-
-bool DOMCoreException::initializeDescription(ExceptionCode ec, ExceptionCodeDescription* description)
-{
-    description->typeName = "DOM";
-    description->code = ec;
-    description->type = DOMCoreExceptionType;
-
-    size_t tableSize = WTF_ARRAY_LENGTH(coreExceptions);
-    size_t tableIndex = ec - INDEX_SIZE_ERR;
-
-    description->name = tableIndex < tableSize ? coreExceptions[tableIndex].name : 0;
-    description->description = tableIndex < tableSize ? coreExceptions[tableIndex].description : 0;
-
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/DOMCoreException.h b/Source/core/dom/DOMCoreException.h
deleted file mode 100644
index 1a98c6e..0000000
--- a/Source/core/dom/DOMCoreException.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMCoreException_h
-#define DOMCoreException_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ExceptionBase.h"
-
-namespace WebCore {
-
-class DOMCoreException : public ExceptionBase, public ScriptWrappable {
-public:
-    static PassRefPtr<DOMCoreException> create(const ExceptionCodeDescription& description)
-    {
-        return adoptRef(new DOMCoreException(description));
-    }
-
-    static bool initializeDescription(ExceptionCode, ExceptionCodeDescription*);
-
-private:
-    explicit DOMCoreException(const ExceptionCodeDescription& description)
-        : ExceptionBase(description)
-    {
-        ScriptWrappable::init(this);
-    }
-};
-
-} // namespace WebCore
-
-#endif // DOMCoreException_h
diff --git a/Source/core/dom/DOMError.h b/Source/core/dom/DOMError.h
index b74b7f0..74d4d17 100644
--- a/Source/core/dom/DOMError.h
+++ b/Source/core/dom/DOMError.h
@@ -27,6 +27,8 @@
 #define DOMError_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/DOMException.h"
+#include "core/dom/ExceptionCode.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
@@ -44,6 +46,16 @@
         return adoptRef(new DOMError(name, message));
     }
 
+    static PassRefPtr<DOMError> create(ExceptionCode ec)
+    {
+        return adoptRef(new DOMError(DOMException::getErrorName(ec), DOMException::getErrorMessage(ec)));
+    }
+
+    static PassRefPtr<DOMError> create(ExceptionCode ec, const String& message)
+    {
+        return adoptRef(new DOMError(DOMException::getErrorName(ec), message));
+    }
+
     const String& name() const { return m_name; }
     const String& message() const { return m_message; }
 
diff --git a/Source/core/dom/DOMException.cpp b/Source/core/dom/DOMException.cpp
new file mode 100644
index 0000000..ff41cd3
--- /dev/null
+++ b/Source/core/dom/DOMException.cpp
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1.  Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ * 2.  Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ *     its contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DOMException.h"
+
+#include "ExceptionCode.h"
+
+namespace WebCore {
+
+static struct CoreException {
+    const char* const name;
+    const char* const message;
+    const int code;
+} coreExceptions[] = {
+    { "IndexSizeError", "Index or size was negative, or greater than the allowed value.", 1 },
+    { "HierarchyRequestError", "A Node was inserted somewhere it doesn't belong.", 3 },
+    { "WrongDocumentError", "A Node was used in a different document than the one that created it (that doesn't support it).", 4 },
+    { "InvalidCharacterError", "An invalid or illegal character was specified, such as in an XML name.", 5 },
+    { "NoModificationAllowedError", "An attempt was made to modify an object where modifications are not allowed.", 7 },
+    { "NotFoundError", "An attempt was made to reference a Node in a context where it does not exist.", 8 },
+    { "NotSupportedError", "The implementation did not support the requested type of object or operation.", 9 },
+    { "InUseAttributeError", "An attempt was made to add an attribute that is already in use elsewhere.", 10 },
+    { "InvalidStateError", "An attempt was made to use an object that is not, or is no longer, usable.", 11 },
+    { "SyntaxError", "An invalid or illegal string was specified.", 12 },
+    { "InvalidModificationError", "An attempt was made to modify the type of the underlying object.", 13 },
+    { "NamespaceError", "An attempt was made to create or change an object in a way which is incorrect with regard to namespaces.", 14 },
+    { "InvalidAccessError", "A parameter or an operation was not supported by the underlying object.", 15 },
+    { "TypeMismatchError", "The type of an object was incompatible with the expected type of the parameter associated to the object.", 17 },
+    { "SecurityError", "An attempt was made to break through the security policy of the user agent.", 18 },
+    { "NetworkError", "A network error occurred.", 19 },
+    { "AbortError", "The user aborted a request.", 20 },
+    { "URLMismatchError", "A worker global scope represented an absolute URL that is not equal to the resulting absolute URL.", 21 },
+    { "QuotaExceededError", "An attempt was made to add something to storage that exceeded the quota.", 22 },
+    { "TimeoutError", "A timeout occurred.", 23 },
+    { "InvalidNodeTypeError", "The supplied node is invalid or has an invalid ancestor for this operation.", 24 },
+    { "DataCloneError", "An object could not be cloned.", 25 },
+
+    // These are IDB-specific errors.
+    // FIXME: NotFoundError is duplicated to have a more specific error message.
+    // https://code.google.com/p/chromium/issues/detail?id=252233
+    { "NotFoundError", "An operation failed because the requested database object could not be found.", 8 },
+
+    // More IDB-specific errors.
+    { "UnknownError", "An unknown error occurred within Indexed Database.", 0 },
+    { "ConstraintError", "A mutation operation in the transaction failed because a constraint was not satisfied.", 0 },
+    { "DataError", "The data provided does not meet requirements.", 0 },
+    { "TransactionInactiveError", "A request was placed against a transaction which is either currently not active, or which is finished.", 0 },
+    { "ReadOnlyError", "A write operation was attempted in a read-only transaction.", 0 },
+    { "VersionError", "An attempt was made to open a database using a lower version than the existing version.", 0 },
+
+    // File system
+    { "NotFoundError", "A requested file or directory could not be found at the time an operation was processed.", 8 },
+    { "SecurityError", "It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.", 18 },
+    { "AbortError", "An ongoing operation was aborted, typically with a call to abort().", 20 },
+    { "NotReadableError", "The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", 0 },
+    { "EncodingError", "A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs.", 0 },
+    { "NoModificationAllowedError", "An attempt was made to write to a file or directory which could not be modified due to the state of the underlying filesystem.", 7 },
+    { "InvalidStateError", "An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk.", 11 },
+    { "SyntaxError", "An invalid or unsupported argument was given, like an invalid line ending specifier.", 12 },
+    { "InvalidModificationError", "The modification request was illegal.", 13 },
+    { "QuotaExceededError", "The operation failed because it would cause the application to exceed its storage quota.", 22 },
+    { "TypeMismatchError", "The path supplied exists, but was not an entry of requested type.", 17 },
+    { "PathExistsError", "An attempt was made to create a file or directory where an element already exists.", 0 },
+
+    // SQL
+    { "UnknownError", "The operation failed for reasons unrelated to the database.", 0 },
+    { "DatabaseError", "The operation failed for some reason related to the database.", 0 },
+    { "VersionError", "The actual database version did not match the expected version.", 0 },
+    { "TooLargeError", "Data returned from the database is too large.", 0 },
+    { "QuotaExceededError", "Quota was exceeded.", 22 },
+    { "SyntaxError", "Invalid or unauthorized statement; or the number of arguments did not match the number of ? placeholders.", 12 },
+    { "ConstraintError", "A constraint was violated.", 0 },
+    { "TimeoutError", "A transaction lock could not be acquired in a reasonable time.", 23 },
+};
+
+static const CoreException* getErrorEntry(ExceptionCode ec)
+{
+    size_t tableSize = WTF_ARRAY_LENGTH(coreExceptions);
+    size_t tableIndex = ec - INDEX_SIZE_ERR;
+
+    return tableIndex < tableSize ? &coreExceptions[tableIndex] : 0;
+}
+
+DOMException::DOMException(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+    if (!entry) {
+        m_code = 0;
+        m_name = "UnknownError";
+        m_message = "Unknown Error";
+    } else {
+        m_code = entry->code;
+        if (entry->name)
+            m_name = entry->name;
+        else
+            m_name = "Error";
+        m_message = entry->message;
+    }
+
+    ScriptWrappable::init(this);
+}
+
+PassRefPtr<DOMException> DOMException::create(ExceptionCode ec)
+{
+    return adoptRef(new DOMException(ec));
+}
+
+String DOMException::toString() const
+{
+    return name() + ": " + message();
+}
+
+String DOMException::getErrorName(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+    if (!entry)
+        return "UnknownError";
+
+    return entry->name;
+}
+
+String DOMException::getErrorMessage(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+    if (!entry)
+        return "Unknown error.";
+
+    return entry->message;
+}
+
+unsigned short DOMException::getLegacyErrorCode(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+
+    return (entry && entry->code) ? entry->code : 0;
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/ExceptionBase.h b/Source/core/dom/DOMException.h
similarity index 72%
rename from Source/core/dom/ExceptionBase.h
rename to Source/core/dom/DOMException.h
index d500f1e..88fbebb 100644
--- a/Source/core/dom/ExceptionBase.h
+++ b/Source/core/dom/DOMException.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -26,35 +26,39 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ExceptionBase_h
-#define ExceptionBase_h
+#ifndef DOMException_h
+#define DOMException_h
 
-#include "core/dom/ExceptionCode.h"
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "bindings/v8/ScriptWrappable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-struct ExceptionCodeDescription;
+typedef int ExceptionCode;
 
-class ExceptionBase : public RefCounted<ExceptionBase> {
+class DOMException : public RefCounted<DOMException>, public ScriptWrappable {
 public:
+    static PassRefPtr<DOMException> create(ExceptionCode);
+
     unsigned short code() const { return m_code; }
     String name() const { return m_name; }
-    String message() const { return description(); }
-    String description() const { return m_description; }
+    String message() const { return m_message; }
 
     String toString() const;
 
-protected:
-    explicit ExceptionBase(const ExceptionCodeDescription&);
+    static String getErrorName(ExceptionCode);
+    static String getErrorMessage(ExceptionCode);
+    static unsigned short getLegacyErrorCode(ExceptionCode);
 
 private:
+    explicit DOMException(ExceptionCode);
+
     unsigned short m_code;
     String m_name;
-    String m_description;
+    String m_message;
 };
 
 } // namespace WebCore
 
-#endif // ExceptionBase_h
+#endif // DOMException_h
diff --git a/Source/core/dom/DOMException.idl b/Source/core/dom/DOMException.idl
index d4e9520..68d04bf 100644
--- a/Source/core/dom/DOMException.idl
+++ b/Source/core/dom/DOMException.idl
@@ -27,8 +27,7 @@
  */
 
 [
-    DoNotCheckConstants,
-    ImplementedAs=DOMCoreException
+    DoNotCheckConstants
 ] exception DOMException {
 
     readonly attribute unsigned short   code;
diff --git a/Source/core/dom/DOMExceptions.in b/Source/core/dom/DOMExceptions.in
deleted file mode 100644
index 433d0ba..0000000
--- a/Source/core/dom/DOMExceptions.in
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace=DOMException
-
-core/dom/DOMException implementedAs=DOMCoreException
-core/fileapi/FileException
-core/svg/SVGException
-core/xml/XPathException
-modules/webdatabase/SQLException
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 87ed5dc..d9e8989 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -26,7 +26,6 @@
 #include "core/dom/DOMImplementation.h"
 
 #include "HTMLNames.h"
-#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/MediaList.h"
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index fe2c31d..14dcdf7 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -25,10 +25,8 @@
 #define DOMImplementation_h
 
 #include "core/dom/Document.h"
-#include "core/platform/graphics/MediaPlayer.h"
-#include <wtf/Forward.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DatasetDOMStringMap.cpp b/Source/core/dom/DatasetDOMStringMap.cpp
index c16bdf5..d1db9f1 100644
--- a/Source/core/dom/DatasetDOMStringMap.cpp
+++ b/Source/core/dom/DatasetDOMStringMap.cpp
@@ -39,10 +39,9 @@
     if (!name.startsWith("data-"))
         return false;
 
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 5; i < length; ++i) {
-        if (isASCIIUpper(characters[i]))
+        if (isASCIIUpper(name[i]))
             return false;
     }
 
@@ -53,15 +52,14 @@
 {
     StringBuilder stringBuilder;
 
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 5; i < length; ++i) {
-        UChar character = characters[i];
+        UChar character = name[i];
         if (character != '-')
             stringBuilder.append(character);
         else {
-            if ((i + 1 < length) && isASCIILower(characters[i + 1])) {
-                stringBuilder.append(toASCIIUpper(characters[i + 1]));
+            if ((i + 1 < length) && isASCIILower(name[i + 1])) {
+                stringBuilder.append(toASCIIUpper(name[i + 1]));
                 ++i;
             } else
                 stringBuilder.append(character);
@@ -76,8 +74,6 @@
     if (!attributeName.startsWith("data-"))
         return false;
 
-    const UChar* property = propertyName.characters();
-    const UChar* attribute = attributeName.characters();
     unsigned propertyLength = propertyName.length();
     unsigned attributeLength = attributeName.length();
    
@@ -85,10 +81,10 @@
     unsigned p = 0;
     bool wordBoundary = false;
     while (a < attributeLength && p < propertyLength) {
-        if (attribute[a] == '-' && a + 1 < attributeLength && attribute[a + 1] != '-')
+        if (attributeName[a] == '-' && a + 1 < attributeLength && attributeName[a + 1] != '-')
             wordBoundary = true;
         else {
-            if ((wordBoundary ? toASCIIUpper(attribute[a]) : attribute[a]) != property[p])
+            if ((wordBoundary ? toASCIIUpper(attributeName[a]) : attributeName[a]) != propertyName[p])
                 return false;
             p++;
             wordBoundary = false;
@@ -101,10 +97,9 @@
 
 static bool isValidPropertyName(const String& name)
 {
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 0; i < length; ++i) {
-        if (characters[i] == '-' && (i + 1 < length) && isASCIILower(characters[i + 1]))
+        if (name[i] == '-' && (i + 1 < length) && isASCIILower(name[i + 1]))
             return false;
     }
     return true;
@@ -115,10 +110,9 @@
     StringBuilder builder;
     builder.append("data-");
 
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 0; i < length; ++i) {
-        UChar character = characters[i];
+        UChar character = name[i];
         if (isASCIIUpper(character)) {
             builder.append('-');
             builder.append(toASCIILower(character));
diff --git a/Source/core/dom/DecodedDataDocumentParser.cpp b/Source/core/dom/DecodedDataDocumentParser.cpp
index da89429..2f76a28 100644
--- a/Source/core/dom/DecodedDataDocumentParser.cpp
+++ b/Source/core/dom/DecodedDataDocumentParser.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/dom/DecodedDataDocumentParser.h"
 
-#include "core/loader/DocumentWriter.h"
+#include "core/dom/Document.h"
 #include "core/loader/TextResourceDecoder.h"
 
 namespace WebCore {
@@ -36,27 +36,36 @@
 {
 }
 
-void DecodedDataDocumentParser::appendBytes(DocumentWriter* writer, const char* data, size_t length)
+size_t DecodedDataDocumentParser::appendBytes(const char* data, size_t length)
 {
     if (!length)
-        return;
+        return 0;
 
-    String decoded = writer->createDecoderIfNeeded()->decode(data, length);
+    String decoded = document()->decoder()->decode(data, length);
     if (decoded.isEmpty())
-        return;
+        return 0;
 
-    writer->reportDataReceived();
+    size_t consumedChars = decoded.length();
     append(decoded.releaseImpl());
+
+    return consumedChars;
 }
 
-void DecodedDataDocumentParser::flush(DocumentWriter* writer)
+size_t DecodedDataDocumentParser::flush()
 {
-    String remainingData = writer->createDecoderIfNeeded()->flush();
+    // null decoder indicates there is no data received.
+    // We have nothing to do in that case.
+    TextResourceDecoder* decoder = document()->decoder();
+    if (!decoder)
+        return 0;
+    String remainingData = decoder->flush();
     if (remainingData.isEmpty())
-        return;
+        return 0;
 
-    writer->reportDataReceived();
+    size_t consumedChars = remainingData.length();
     append(remainingData.releaseImpl());
+
+    return consumedChars;
 }
 
 };
diff --git a/Source/core/dom/DecodedDataDocumentParser.h b/Source/core/dom/DecodedDataDocumentParser.h
index 4e61a93..ea13ff6 100644
--- a/Source/core/dom/DecodedDataDocumentParser.h
+++ b/Source/core/dom/DecodedDataDocumentParser.h
@@ -44,8 +44,9 @@
     virtual void append(PassRefPtr<StringImpl>) = 0;
 
     // appendBytes and flush are used by DocumentWriter (the loader).
-    virtual void appendBytes(DocumentWriter*, const char* bytes, size_t length);
-    virtual void flush(DocumentWriter*);
+    virtual size_t appendBytes(const char* bytes, size_t length) OVERRIDE;
+    virtual size_t flush() OVERRIDE;
+    virtual bool needsDecoder() const OVERRIDE { return true; }
 };
 
 }
diff --git a/Source/core/dom/DeviceOrientationController.cpp b/Source/core/dom/DeviceOrientationController.cpp
index bc9df50..460e1fb 100644
--- a/Source/core/dom/DeviceOrientationController.cpp
+++ b/Source/core/dom/DeviceOrientationController.cpp
@@ -28,7 +28,6 @@
 #include "core/dom/DeviceOrientationController.h"
 
 #include "core/dom/DeviceOrientationClient.h"
-#include "core/dom/DeviceOrientationData.h"
 #include "core/dom/DeviceOrientationEvent.h"
 #include "core/inspector/InspectorInstrumentation.h"
 
diff --git a/Source/core/dom/DeviceOrientationController.h b/Source/core/dom/DeviceOrientationController.h
index 922a54d..3173d39 100644
--- a/Source/core/dom/DeviceOrientationController.h
+++ b/Source/core/dom/DeviceOrientationController.h
@@ -28,7 +28,6 @@
 #define DeviceOrientationController_h
 
 #include "core/page/DeviceController.h"
-#include <wtf/HashCountedSet.h>
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 6f0e65b..b296bc1 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -28,7 +28,6 @@
 #include "config.h"
 #include "core/dom/Document.h"
 
-#include "CSSValueKeywords.h"
 #include "HTMLElementFactory.h"
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
@@ -36,23 +35,20 @@
 #include "SVGNames.h"
 #include "XMLNSNames.h"
 #include "XMLNames.h"
+#include "bindings/v8/CustomElementConstructorBuilder.h"
 #include "bindings/v8/Dictionary.h"
 #include "bindings/v8/ScriptController.h"
-#include "bindings/v8/ScriptEventListener.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/animation/DocumentTimeline.h"
-#include "core/css/CSSParser.h"
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/FontLoader.h"
-#include "core/css/MediaQueryList.h"
 #include "core/css/MediaQueryMatcher.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/StyleSheetList.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
-#include "core/dom/Attribute.h"
 #include "core/dom/CDATASection.h"
 #include "core/dom/Comment.h"
 #include "core/dom/ContextFeatures.h"
@@ -74,7 +70,6 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/HashChangeEvent.h"
-#include "core/dom/NameNodeList.h"
 #include "core/dom/NamedFlowCollection.h"
 #include "core/dom/NodeFilter.h"
 #include "core/dom/NodeIterator.h"
@@ -86,10 +81,8 @@
 #include "core/dom/PopStateEvent.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/QualifiedName.h"
-#include "core/dom/RegisteredEventListener.h"
 #include "core/dom/RequestAnimationFrameCallback.h"
 #include "core/dom/ScopedEventQueue.h"
-#include "core/dom/ScriptElement.h"
 #include "core/dom/ScriptRunner.h"
 #include "core/dom/ScriptedAnimationController.h"
 #include "core/dom/SelectorQuery.h"
@@ -103,11 +96,9 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
-#include "core/editing/htmlediting.h"
 #include "core/html/FormController.h"
 #include "core/html/HTMLAllCollection.h"
 #include "core/html/HTMLAnchorElement.h"
-#include "core/html/HTMLBodyElement.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDocument.h"
@@ -116,7 +107,6 @@
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLImportsController.h"
 #include "core/html/HTMLLinkElement.h"
-#include "core/html/HTMLMapElement.h"
 #include "core/html/HTMLNameCollection.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/HTMLStyleElement.h"
@@ -131,21 +121,16 @@
 #include "core/loader/CookieJar.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
 #include "core/loader/ImageLoader.h"
 #include "core/loader/Prerenderer.h"
-#include "core/loader/ResourceLoader.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/DOMSecurityPolicy.h"
-#include "core/page/DOMSelection.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/EventHandler.h"
-#include "core/page/FocusController.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/page/FrameView.h"
@@ -153,48 +138,36 @@
 #include "core/page/MouseEventWithHitTestResults.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
-#include "core/page/PageGroup.h"
 #include "core/page/PointerLockController.h"
 #include "core/page/Settings.h"
-#include "core/page/UserContentURLPattern.h"
 #include "core/page/ValidationMessageClient.h"
 #include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/DateComponents.h"
 #include "core/platform/HistogramSupport.h"
 #include "core/platform/Language.h"
-#include "core/platform/Logging.h"
-#include "core/platform/PlatformKeyboardEvent.h"
 #include "core/platform/Timer.h"
 #include "core/platform/chromium/TraceEvent.h"
 #include "core/platform/network/HTTPParsers.h"
 #include "core/platform/text/PlatformLocale.h"
 #include "core/platform/text/SegmentedString.h"
-#include "core/rendering/FlowThreadController.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderArena.h"
-#include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-#include "core/rendering/RenderTextControl.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "core/rendering/TextAutosizer.h"
 #include "core/svg/SVGDocumentExtensions.h"
-#include "core/svg/SVGSVGElement.h"
 #include "core/svg/SVGStyleElement.h"
 #include "core/workers/SharedWorkerRepository.h"
-#include "core/xml/XMLHttpRequest.h"
 #include "core/xml/XPathEvaluator.h"
 #include "core/xml/XPathExpression.h"
 #include "core/xml/XPathNSResolver.h"
 #include "core/xml/XPathResult.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParser.h"
-#include "modules/geolocation/GeolocationController.h"
 #include "weborigin/SchemeRegistry.h"
 #include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/HashFunctions.h"
 #include "wtf/MainThread.h"
@@ -435,7 +408,6 @@
     , m_closeAfterStyleRecalc(false)
     , m_gotoAnchorNeededAfterStylesheetsLoad(false)
     , m_pendingStyleRecalcShouldForce(false)
-    , m_frameElementsShouldIgnoreScrolling(false)
     , m_containsValidityStyleRules(false)
     , m_updateFocusAppearanceRestoresSelection(false)
     , m_ignoreDestructiveWriteCount(0)
@@ -643,8 +615,7 @@
         m_scriptedAnimationController->clearDocumentPointer();
     m_scriptedAnimationController.clear();
 
-    if (m_lifecycleNotifier)
-        m_lifecycleNotifier->notifyDocumentWasDisposed();
+    lifecycleNotifier()->notifyDocumentWasDisposed();
 }
 
 Element* Document::getElementById(const AtomicString& id) const
@@ -842,7 +813,9 @@
         return ScriptValue();
     }
 
-    return ensureCustomElementRegistry()->registerElement(state, name, options, ec);
+    CustomElementConstructorBuilder constructorBuilder(state, &options);
+    ensureCustomElementRegistry()->registerElement(&constructorBuilder, name, ec);
+    return constructorBuilder.bindingsReturnValue();
 }
 
 CustomElementRegistry* Document::ensureCustomElementRegistry()
@@ -854,11 +827,10 @@
     return m_registry.get();
 }
 
-HTMLImportsController* Document::ensureImports()
+void Document::setImports(PassRefPtr<HTMLImportsController> imports)
 {
-    if (!m_imports)
-        m_imports = HTMLImportsController::create(this);
-    return m_imports.get();
+    ASSERT(!m_imports);
+    m_imports = imports;
 }
 
 void Document::didLoadAllImports()
@@ -962,7 +934,7 @@
         return newElement.release();
     }
     case ATTRIBUTE_NODE:
-        return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
+        return Attr::create(this, QualifiedName(nullAtom, toAttr(importedNode)->name(), nullAtom), toAttr(importedNode)->value());
     case DOCUMENT_FRAGMENT_NODE: {
         if (importedNode->isShadowRoot()) {
             // ShadowRoot nodes should not be explicitly importable.
@@ -1016,7 +988,7 @@
         ec = NOT_SUPPORTED_ERR;
         return 0;
     case ATTRIBUTE_NODE: {
-        Attr* attr = static_cast<Attr*>(source.get());
+        Attr* attr = toAttr(source.get());
         if (attr->ownerElement())
             attr->ownerElement()->removeAttributeNode(attr, ec);
         attr->setSpecified(true);
@@ -1680,6 +1652,7 @@
         return; // Guard against re-entrancy. -dwh
 
     TRACE_EVENT0("webkit", "Document::recalcStyle");
+    TraceEvent::SamplingState0Scope("Blink\0Blink-RecalcStyle");
 
     // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
     // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
@@ -1689,7 +1662,7 @@
     // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
 
     if (m_styleSheetCollection->needsUpdateActiveStylesheetsOnStyleRecalc())
-        m_styleSheetCollection->updateActiveStyleSheets(DocumentStyleSheetCollection::FullUpdate);
+        m_styleSheetCollection->updateActiveStyleSheets(FullStyleUpdate);
 
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
 
@@ -1760,6 +1733,12 @@
     }
 
     InspectorInstrumentation::didRecalculateStyle(cookie);
+
+    // As a result of the style recalculation, the currently hovered element might have been
+    // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
+    // to check if any other elements ended up under the mouse pointer due to re-layout.
+    if (hoverNode() && !hoverNode()->renderer() && frame())
+        frame()->eventHandler()->dispatchFakeMouseMoveEventSoon();
 }
 
 void Document::updateStyleIfNeeded()
@@ -1774,6 +1753,18 @@
     recalcStyle(NoChange);
 }
 
+void Document::updateStyleForNodeIfNeeded(Node* node)
+{
+    if (!hasPendingForcedStyleRecalc() && !childNeedsStyleRecalc() && !needsStyleRecalc())
+        return;
+
+    bool needsStyleRecalc = hasPendingForcedStyleRecalc();
+    for (Node* n = node; n && !needsStyleRecalc; n = n->parentNode())
+        needsStyleRecalc = n->needsStyleRecalc();
+    if (needsStyleRecalc)
+        updateStyleIfNeeded();
+}
+
 void Document::updateLayout()
 {
     ASSERT(isMainThread());
@@ -2002,8 +1993,7 @@
     if (m_mediaQueryMatcher)
         m_mediaQueryMatcher->documentDestroyed();
 
-    if (m_lifecycleNotifier)
-        m_lifecycleNotifier->notifyDocumentWasDetached();
+    lifecycleNotifier()->notifyDocumentWasDetached();
 }
 
 void Document::prepareForDestruction()
@@ -2162,11 +2152,12 @@
     explicitClose();
 }
 
-void Document::implicitOpen()
+PassRefPtr<DocumentParser> Document::implicitOpen()
 {
     cancelParsing();
 
     removeChildren();
+    ASSERT(!m_focusedNode);
 
     setCompatibilityMode(NoQuirksMode);
 
@@ -2179,6 +2170,8 @@
     m_parser = createParser();
     setParsing(true);
     setReadyState(Loading);
+
+    return m_parser;
 }
 
 HTMLElement* Document::body() const
@@ -2295,12 +2288,14 @@
     if (f)
         f->animation()->resumeAnimationsForDocument(this);
 
-    ImageLoader::dispatchPendingBeforeLoadEvents();
-    ImageLoader::dispatchPendingLoadEvents();
-    ImageLoader::dispatchPendingErrorEvents();
+    if (f && f->script()->canExecuteScripts(NotAboutToExecuteScript)) {
+        ImageLoader::dispatchPendingBeforeLoadEvents();
+        ImageLoader::dispatchPendingLoadEvents();
+        ImageLoader::dispatchPendingErrorEvents();
 
-    HTMLLinkElement::dispatchPendingLoadEvents();
-    HTMLStyleElement::dispatchPendingLoadEvents();
+        HTMLLinkElement::dispatchPendingLoadEvents();
+        HTMLStyleElement::dispatchPendingLoadEvents();
+    }
 
     // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
     // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
@@ -2688,7 +2683,7 @@
 {
     m_needsNotifyRemoveAllPendingStylesheet = false;
 
-    styleResolverChanged(RecalcStyleIfNeeded);
+    styleResolverChanged(RecalcStyleImmediately, AnalyzedStyleUpdate);
     executeScriptsWaitingForResourcesIfNeeded();
 
     if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
@@ -3052,7 +3047,7 @@
         m_mediaQueryMatcher->styleResolverChanged();
 }
 
-void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
+void Document::styleResolverChanged(StyleResolverUpdateType updateType, StyleResolverUpdateMode updateMode)
 {
     // Don't bother updating, since we haven't loaded all our style info yet
     // and haven't calculated the style selector for the first time.
@@ -3067,12 +3062,9 @@
         printf("Beginning update of style selector at time %d.\n", elapsedTime());
 #endif
 
-    DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded)
-        ? DocumentStyleSheetCollection::OptimizedUpdate
-        : DocumentStyleSheetCollection::FullUpdate;
-    bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection->updateActiveStyleSheets(styleSheetUpdate);
+    bool needsRecalc = m_styleSheetCollection->updateActiveStyleSheets(updateMode);
 
-    if (updateFlag == DeferRecalcStyle) {
+    if (updateType >= DeferRecalcStyle) {
         scheduleForcedStyleRecalc();
         return;
     }
@@ -3083,7 +3075,7 @@
             renderView()->repaintViewAndCompositedLayers();
     }
 
-    if (!stylesheetChangeRequiresStyleRecalc)
+    if (!needsRecalc)
         return;
 
     // This recalcStyle initiates a new recalc cycle. We need to bracket it to
@@ -3138,11 +3130,6 @@
     m_activeElement = newActiveElement;
 }
 
-void Document::focusedNodeRemoved()
-{
-    setFocusedNode(0);
-}
-
 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
 {
     if (!m_focusedNode)
@@ -3159,7 +3146,7 @@
         nodeInSubtree = (focusedNode == node) || focusedNode->isDescendantOf(node);
 
     if (nodeInSubtree)
-        document()->focusedNodeRemoved();
+        setFocusedNode(0);
 }
 
 void Document::hoveredNodeDetached(Node* node)
@@ -3344,6 +3331,8 @@
 
 SetFocusedNodeDone:
     updateStyleIfNeeded();
+    if (Frame* frame = this->frame())
+        frame->selection()->didChangeFocus();
     return !focusChangeBlocked;
 }
 
@@ -3826,7 +3815,7 @@
     bool sawColon = false;
     int colonPos = 0;
 
-    const UChar* s = qualifiedName.characters();
+    const UChar* s = qualifiedName.bloatedCharacters();
     for (unsigned i = 0; i < length;) {
         UChar32 c;
         U16_NEXT(s, i, length, c)
@@ -4134,6 +4123,12 @@
     return ensureCachedCollection(DocAnchors);
 }
 
+PassRefPtr<HTMLCollection> Document::allForBinding()
+{
+    UseCounter::count(this, UseCounter::DocumentAll);
+    return all();
+}
+
 PassRefPtr<HTMLCollection> Document::all()
 {
     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
@@ -4479,8 +4474,10 @@
 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
 {
     RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).iterator->value;
-    if (!element)
+    if (!element) {
         element = HTMLCanvasElement::create(this);
+        element->setAccelerationDisabled(true);
+    }
     return element.get();
 }
 
@@ -4528,7 +4525,7 @@
     }
 
     if (Page* page = this->page())
-        page->console()->addMessage(source, level, message, sourceURL, lineNumber, callStack, state, requestIdentifier);
+        page->console()->addMessage(source, level, message, sourceURL, lineNumber, 0, callStack, state, requestIdentifier);
 }
 
 const SecurityOrigin* Document::topOrigin() const
@@ -5050,11 +5047,14 @@
 
     if (oldHoverObj != newHoverObj) {
         // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
-        // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element
+        // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
         // must be updated, to ensure it's normal style is re-applied.
         if (oldHoverNode && !oldHoverObj) {
-            if (!mustBeInActiveChain || oldHoverNode->inActiveChain())
-                nodesToRemoveFromChain.append(oldHoverNode);
+            for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
+                if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
+                    nodesToRemoveFromChain.append(node);
+            }
+
         }
 
         // The old hover path only needs to be cleared up to (and not including) the common ancestor;
@@ -5226,11 +5226,14 @@
     m_associatedFormControls.clear();
 }
 
-void Document::addLifecycleObserver(DocumentLifecycleObserver* observer)
+PassOwnPtr<ContextLifecycleNotifier> Document::createLifecycleNotifier()
 {
-    if (!m_lifecycleNotifier)
-        m_lifecycleNotifier = DocumentLifecycleNotifier::create();
-    m_lifecycleNotifier->addObserver(observer);
+    return DocumentLifecycleNotifier::create(this);
+}
+
+DocumentLifecycleNotifier* Document::lifecycleNotifier()
+{
+    return static_cast<DocumentLifecycleNotifier*>(ScriptExecutionContext::lifecycleNotifier());
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 8c28505..e77c623 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -41,23 +41,19 @@
 #include "core/dom/UserActionElementSet.h"
 #include "core/dom/ViewportArguments.h"
 #include "core/html/CollectionType.h"
-#include "core/inspector/InspectorCounters.h"
 #include "core/page/FocusDirection.h"
 #include "core/page/PageVisibilityState.h"
-#include "core/platform/PlatformScreen.h"
 #include "weborigin/ReferrerPolicy.h"
 #include "core/platform/Timer.h"
 #include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/IntRect.h"
 #include "core/platform/text/StringWithDirection.h"
 #include "core/rendering/HitTestRequest.h"
-#include <wtf/Deque.h>
-#include <wtf/FixedArray.h>
-#include <wtf/HashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/WeakPtr.h>
+#include "wtf/Deque.h"
+#include "wtf/HashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
@@ -174,7 +170,16 @@
     PageshowEventPersisted = 1
 };
 
-enum StyleResolverUpdateFlag { RecalcStyleImmediately, DeferRecalcStyle, RecalcStyleIfNeeded };
+// FIXME: We should rename DeferRecalcStyle to RecalcStyleDeferred to be consitent.
+
+enum StyleResolverUpdateType { RecalcStyleImmediately, DeferRecalcStyle };
+
+enum StyleResolverUpdateMode {
+    // Discards the StyleResolver and rebuilds it.
+    FullStyleUpdate,
+    // Attempts to use StyleInvalidationAnalysis to avoid discarding the entire StyleResolver.
+    AnalyzedStyleUpdate
+};
 
 enum NodeListInvalidationType {
     DoNotInvalidateOnAttributeChanges = 0,
@@ -395,6 +400,7 @@
     PassRefPtr<HTMLCollection> forms();
     PassRefPtr<HTMLCollection> anchors();
     PassRefPtr<HTMLCollection> scripts();
+    PassRefPtr<HTMLCollection> allForBinding();
     PassRefPtr<HTMLCollection> all();
 
     PassRefPtr<HTMLCollection> windowNamedItems(const AtomicString& name);
@@ -440,16 +446,8 @@
     bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
     void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
 
-    /**
-     * Called when one or more stylesheets in the document may have been added, removed or changed.
-     *
-     * Creates a new style resolver and assign it to this document. This is done by iterating through all nodes in
-     * document (or those before <BODY> in a HTML document), searching for stylesheets. Stylesheets can be contained in
-     * <LINK>, <STYLE> or <BODY> elements, as well as processing instructions (XML documents only). A list is
-     * constructed from these which is used to create the a new style selector which collates all of the stylesheets
-     * found and is used to calculate the derived styles for all rendering objects.
-     */
-    void styleResolverChanged(StyleResolverUpdateFlag);
+    // Called when one or more stylesheets in the document may have been added, removed, or changed.
+    void styleResolverChanged(StyleResolverUpdateType, StyleResolverUpdateMode = FullStyleUpdate);
 
     void didAccessStyleResolver();
 
@@ -484,6 +482,7 @@
     void recalcStyle(StyleChange = NoChange);
     bool childNeedsAndNotInStyleRecalc();
     void updateStyleIfNeeded();
+    void updateStyleForNodeIfNeeded(Node*);
     void updateLayout();
     void updateLayoutIgnorePendingStylesheets();
     PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
@@ -533,7 +532,7 @@
     DocumentLoader* loader() const;
 
     void open(Document* ownerDocument = 0);
-    void implicitOpen();
+    PassRefPtr<DocumentParser> implicitOpen();
 
     // close() is the DOM API document.close()
     void close();
@@ -656,7 +655,6 @@
     void setActiveElement(PassRefPtr<Element>);
     Element* activeElement() const { return m_activeElement.get(); }
 
-    void focusedNodeRemoved();
     void removeFocusedNodeOfSubtree(Node*, bool amongChildrenOnly = false);
     void hoveredNodeDetached(Node*);
     void activeChainNodeDetached(Node*);
@@ -928,10 +926,6 @@
         displayBufferModifiedByEncodingInternal(buffer, len);
     }
 
-    // Quirk for the benefit of Apple's Dictionary application.
-    void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
-    bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
-
     void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
     bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
     bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
@@ -1027,7 +1021,7 @@
     CustomElementRegistry* registry() const { return m_registry.get(); }
     CustomElementRegistry* ensureCustomElementRegistry();
 
-    HTMLImportsController* ensureImports();
+    void setImports(PassRefPtr<HTMLImportsController>);
     HTMLImportsController* imports() const { return m_imports.get(); }
     bool haveImportsLoaded() const;
     void didLoadAllImports();
@@ -1076,8 +1070,7 @@
     virtual const SecurityOrigin* topOrigin() const OVERRIDE;
 
     PassRefPtr<FontLoader> fontloader();
-
-    void addLifecycleObserver(DocumentLifecycleObserver*);
+    DocumentLifecycleNotifier* lifecycleNotifier();
 
 protected:
     Document(Frame*, const KURL&, DocumentClassFlags = DefaultDocumentClass);
@@ -1108,6 +1101,7 @@
 
     virtual void refScriptExecutionContext() { ref(); }
     virtual void derefScriptExecutionContext() { deref(); }
+    virtual PassOwnPtr<ContextLifecycleNotifier> createLifecycleNotifier() OVERRIDE;
 
     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.
@@ -1252,7 +1246,6 @@
     bool m_gotoAnchorNeededAfterStylesheetsLoad;
     bool m_isDNSPrefetchEnabled;
     bool m_haveExplicitlyDisabledDNSPrefetch;
-    bool m_frameElementsShouldIgnoreScrolling;
     bool m_containsValidityStyleRules;
     bool m_updateFocusAppearanceRestoresSelection;
 
@@ -1371,7 +1364,7 @@
     OwnPtr<TextAutosizer> m_textAutosizer;
 
     RefPtr<CustomElementRegistry> m_registry;
-    OwnPtr<HTMLImportsController> m_imports;
+    RefPtr<HTMLImportsController> m_imports;
 
     bool m_scheduledTasksAreSuspended;
     
@@ -1400,8 +1393,6 @@
 
     Timer<Document> m_didAssociateFormControlsTimer;
     HashSet<RefPtr<Element> > m_associatedFormControls;
-
-    OwnPtr<DocumentLifecycleNotifier> m_lifecycleNotifier;
 };
 
 inline void Document::notifyRemovePendingSheetIfNeeded()
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index 6d7fb1b..7afd390 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -285,3 +285,5 @@
     readonly attribute HTMLScriptElement currentScript;
 };
 
+Document implements ParentNode;
+
diff --git a/Source/core/dom/DocumentEventQueue.cpp b/Source/core/dom/DocumentEventQueue.cpp
index af1c3c7..b32cb00 100644
--- a/Source/core/dom/DocumentEventQueue.cpp
+++ b/Source/core/dom/DocumentEventQueue.cpp
@@ -33,8 +33,8 @@
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/SuspendableTimer.h"
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationListHashSet.h>
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationListHashSet.h"
 
 namespace WebCore {
     
diff --git a/Source/core/dom/DocumentEventQueue.h b/Source/core/dom/DocumentEventQueue.h
index 233192a..d877833 100644
--- a/Source/core/dom/DocumentEventQueue.h
+++ b/Source/core/dom/DocumentEventQueue.h
@@ -28,12 +28,11 @@
 #define DocumentEventQueue_h
 
 #include "core/dom/EventQueue.h"
-#include <wtf/Forward.h>
-#include <wtf/HashSet.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DocumentFragment.h b/Source/core/dom/DocumentFragment.h
index 5d713fe..08ede54 100644
--- a/Source/core/dom/DocumentFragment.h
+++ b/Source/core/dom/DocumentFragment.h
@@ -25,7 +25,7 @@
 #define DocumentFragment_h
 
 #include "core/dom/ContainerNode.h"
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DocumentFragment.idl b/Source/core/dom/DocumentFragment.idl
index 6cd787a..076c949 100644
--- a/Source/core/dom/DocumentFragment.idl
+++ b/Source/core/dom/DocumentFragment.idl
@@ -26,3 +26,5 @@
     [RaisesException] NodeList querySelectorAll(DOMString selectors);
 };
 
+DocumentFragment implements ParentNode;
+
diff --git a/Source/core/dom/DocumentFullscreen.cpp b/Source/core/dom/DocumentFullscreen.cpp
index 472682c..17bc1ee 100644
--- a/Source/core/dom/DocumentFullscreen.cpp
+++ b/Source/core/dom/DocumentFullscreen.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 #include "core/dom/DocumentFullscreen.h"
 
-#include "core/dom/Document.h"
 #include "core/dom/FullscreenController.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/DocumentLifecycleObserver.cpp b/Source/core/dom/DocumentLifecycleObserver.cpp
index 2a231ac..2af13c0 100644
--- a/Source/core/dom/DocumentLifecycleObserver.cpp
+++ b/Source/core/dom/DocumentLifecycleObserver.cpp
@@ -32,21 +32,38 @@
 namespace WebCore {
 
 DocumentLifecycleObserver::DocumentLifecycleObserver(Document* document)
-    : ContextDestructionObserver(document)
+    : ContextLifecycleObserver(document, DocumentLifecycleObserverType)
 {
-    document->addLifecycleObserver(this);
 }
 
-PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create()
+DocumentLifecycleObserver::~DocumentLifecycleObserver()
 {
-    return adoptPtr(new DocumentLifecycleNotifier());
+    observeContext(0, DocumentLifecycleObserverType);
 }
 
-void DocumentLifecycleNotifier::addObserver(DocumentLifecycleObserver* observer)
+DocumentLifecycleNotifier::DocumentLifecycleNotifier(ScriptExecutionContext* context)
+    : ContextLifecycleNotifier(context)
 {
-    ASSERT(!m_iterating);
-    ASSERT(!m_observers.contains(observer));
-    m_observers.append(observer);
+}
+
+void DocumentLifecycleNotifier::addObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    if (as == ContextLifecycleObserver::DocumentLifecycleObserverType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
+        m_documentObservers.add(static_cast<DocumentLifecycleObserver*>(observer));
+    }
+
+    ContextLifecycleNotifier::addObserver(observer, as);
+}
+
+void DocumentLifecycleNotifier::removeObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    if (as == ContextLifecycleObserver::DocumentLifecycleObserverType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
+        m_documentObservers.remove(static_cast<DocumentLifecycleObserver*>(observer));
+    }
+
+    ContextLifecycleNotifier::removeObserver(observer, as);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentLifecycleObserver.h b/Source/core/dom/DocumentLifecycleObserver.h
index d6d0263..47a449f 100644
--- a/Source/core/dom/DocumentLifecycleObserver.h
+++ b/Source/core/dom/DocumentLifecycleObserver.h
@@ -26,61 +26,58 @@
 #ifndef DocumentLifecycleObserver_h
 #define DocumentLifecycleObserver_h
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleNotifier.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "wtf/Assertions.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
+#include "wtf/TemporaryChange.h"
 
 namespace WebCore {
 
 class Document;
 
-class DocumentLifecycleObserver : public ContextDestructionObserver {
+class DocumentLifecycleObserver : public ContextLifecycleObserver {
 public:
     explicit DocumentLifecycleObserver(Document*);
-    virtual ~DocumentLifecycleObserver() { }
+    virtual ~DocumentLifecycleObserver();
     virtual void documentWasDetached() { }
     virtual void documentWasDisposed() { }
 };
 
-class DocumentLifecycleNotifier {
+class DocumentLifecycleNotifier  : public ContextLifecycleNotifier {
 public:
-    static PassOwnPtr<DocumentLifecycleNotifier> create();
+    static PassOwnPtr<DocumentLifecycleNotifier> create(ScriptExecutionContext*);
 
     void notifyDocumentWasDetached();
     void notifyDocumentWasDisposed();
 
-    void addObserver(DocumentLifecycleObserver*);
+    virtual void addObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as) OVERRIDE;
+    virtual void removeObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as) OVERRIDE;
 
 private:
-#if ASSERT_DISABLED
-    DocumentLifecycleNotifier() { }
-    void startIteration() { }
-    void endIteration() { }
-#else
-    DocumentLifecycleNotifier() : m_iterating(false) { }
-    void startIteration() { m_iterating = true; }
-    void endIteration() { m_iterating = false; }
-    bool m_iterating;
-#endif
+    explicit DocumentLifecycleNotifier(ScriptExecutionContext*);
 
-    Vector<DocumentLifecycleObserver*> m_observers; // Use Vector instead of HashSet for faster iteration
+    typedef HashSet<DocumentLifecycleObserver*> DocumentObserverSet;
+    DocumentObserverSet m_documentObservers;
 };
 
+inline PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create(ScriptExecutionContext* context)
+{
+    return adoptPtr(new DocumentLifecycleNotifier(context));
+}
+
 inline void DocumentLifecycleNotifier::notifyDocumentWasDetached()
 {
-    startIteration();
-    for (size_t i = 0; i < m_observers.size(); ++i)
-        m_observers[i]->documentWasDetached();
-    endIteration();
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
+    for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
+        (*i)->documentWasDetached();
 }
 
 inline void DocumentLifecycleNotifier::notifyDocumentWasDisposed()
 {
-    startIteration();
-    for (size_t i = 0; i < m_observers.size(); ++i)
-        m_observers[i]->documentWasDisposed();
-    endIteration();
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
+    for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
+        (*i)->documentWasDisposed();
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentOrderedList.cpp b/Source/core/dom/DocumentOrderedList.cpp
new file mode 100644
index 0000000..62802cc
--- /dev/null
+++ b/Source/core/dom/DocumentOrderedList.cpp
@@ -0,0 +1,73 @@
+/*
+ * 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, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
+ * 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/DocumentOrderedList.h"
+
+#include "core/dom/Node.h"
+
+namespace WebCore {
+
+void DocumentOrderedList::add(Node* node)
+{
+    if (m_nodes.isEmpty()) {
+        m_nodes.add(node);
+        return;
+    }
+
+    // Determine an appropriate insertion point.
+    iterator begin = m_nodes.begin();
+    iterator end = m_nodes.end();
+    iterator it = end;
+    Node* followingNode = 0;
+    do {
+        --it;
+        Node* n = *it;
+        unsigned short position = n->compareDocumentPositionInternal(node, Node::TreatShadowTreesAsComposed);
+        if (position & Node::DOCUMENT_POSITION_FOLLOWING) {
+            m_nodes.insertBefore(followingNode, node);
+            return;
+        }
+        followingNode = n;
+    } while (it != begin);
+
+    m_nodes.insertBefore(followingNode, node);
+}
+
+void DocumentOrderedList::parserAdd(Node* node)
+{
+    ASSERT(m_nodes.isEmpty() || m_nodes.last()->compareDocumentPositionInternal(node, Node::TreatShadowTreesAsComposed) & Node::DOCUMENT_POSITION_FOLLOWING);
+    m_nodes.add(node);
+}
+
+void DocumentOrderedList::remove(Node* node)
+{
+    m_nodes.remove(node);
+}
+
+}
+
diff --git a/Source/core/dom/DocumentOrderedList.h b/Source/core/dom/DocumentOrderedList.h
new file mode 100644
index 0000000..8dde172
--- /dev/null
+++ b/Source/core/dom/DocumentOrderedList.h
@@ -0,0 +1,60 @@
+/*
+ * 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 DocumentOrderedList_h
+#define DocumentOrderedList_h
+
+#include "wtf/FastAllocBase.h"
+#include "wtf/ListHashSet.h"
+
+namespace WebCore {
+
+class Node;
+
+class DocumentOrderedList {
+    WTF_MAKE_NONCOPYABLE(DocumentOrderedList); WTF_MAKE_FAST_ALLOCATED;
+public:
+    DocumentOrderedList() { }
+
+    void add(Node*);
+    void parserAdd(Node*);
+    void remove(Node*);
+    bool isEmpty() const { return m_nodes.isEmpty(); }
+    void clear() { m_nodes.clear(); }
+
+    typedef ListHashSet<Node*, 32>::iterator iterator;
+
+    iterator begin() { return m_nodes.begin(); }
+    iterator end() { return m_nodes.end(); }
+
+private:
+    ListHashSet<Node*, 32> m_nodes;
+};
+
+}
+
+#endif
diff --git a/Source/core/dom/DocumentParser.h b/Source/core/dom/DocumentParser.h
index f65d369..98a473b 100644
--- a/Source/core/dom/DocumentParser.h
+++ b/Source/core/dom/DocumentParser.h
@@ -47,8 +47,9 @@
     virtual void insert(const SegmentedString&) = 0;
 
     // appendBytes and flush are used by DocumentWriter (the loader).
-    virtual void appendBytes(DocumentWriter*, const char* bytes, size_t length) = 0;
-    virtual void flush(DocumentWriter*) = 0;
+    virtual size_t appendBytes(const char* bytes, size_t length) = 0;
+    virtual size_t flush() = 0;
+    virtual bool needsDecoder() const { return false; }
 
     virtual void pinToMainThread() { }
 
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index ab2b188..35b41b4 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -226,33 +226,17 @@
 {
     if (!node->inDocument())
         return;
-    
+
     // Until the <body> exists, we have no choice but to compare document positions,
     // since styles outside of the body and head continue to be shunted into the head
     // (and thus can shift to end up before dynamically added DOM content that is also
     // outside the body).
-    if ((createdByParser && m_document->body()) || m_styleSheetCandidateNodes.isEmpty()) {
-        m_styleSheetCandidateNodes.add(node);
+    if (createdByParser && m_document->body()) {
+        m_styleSheetCandidateNodes.parserAdd(node);
         return;
     }
 
-    // Determine an appropriate insertion point.
-    StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
-    StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
-    StyleSheetCandidateListHashSet::iterator it = end;
-    Node* followingNode = 0;
-    do {
-        --it;
-        Node* n = *it;
-        unsigned short position = n->compareDocumentPositionInternal(node, Node::TreatShadowTreesAsComposed);
-        if (position & Node::DOCUMENT_POSITION_FOLLOWING) {
-            m_styleSheetCandidateNodes.insertBefore(followingNode, node);
-            return;
-        }
-        followingNode = n;
-    } while (it != begin);
-    
-    m_styleSheetCandidateNodes.insertBefore(followingNode, node);
+    m_styleSheetCandidateNodes.add(node);
 }
 
 void DocumentStyleSheetCollection::removeStyleSheetCandidateNode(Node* node)
@@ -260,21 +244,21 @@
     m_styleSheetCandidateNodes.remove(node);
 }
 
-void DocumentStyleSheetCollection::collectActiveStyleSheets(Vector<RefPtr<StyleSheet> >& sheets)
+void DocumentStyleSheetCollection::collectStyleSheets(Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
 {
     if (m_document->settings() && !m_document->settings()->authorAndUserStylesEnabled())
         return;
 
-    StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
-    StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
-    for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
+    DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
+    DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
+    for (DocumentOrderedList::iterator it = begin; it != end; ++it) {
         Node* n = *it;
         StyleSheet* sheet = 0;
+        CSSStyleSheet* activeSheet = 0;
         if (n->nodeType() == Node::PROCESSING_INSTRUCTION_NODE) {
             // Processing instruction (XML documents only).
             // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
             ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
-            sheet = pi->sheet();
             // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
             if (pi->isXSL() && !m_document->transformSourceDocument()) {
                 // Don't apply XSL transforms until loading is finished.
@@ -282,6 +266,9 @@
                     m_document->applyXSLTransform(pi);
                 return;
             }
+            sheet = pi->sheet();
+            if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
+                activeSheet = static_cast<CSSStyleSheet*>(sheet);
         } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))) || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))) {
             Element* e = toElement(n);
             AtomicString title = e->getAttribute(titleAttr);
@@ -289,10 +276,8 @@
             if (e->hasLocalName(linkTag)) {
                 // <LINK> element
                 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
-                if (linkElement->isDisabled())
-                    continue;
                 enabledViaScript = linkElement->isEnabledViaScript();
-                if (linkElement->styleSheetIsLoading()) {
+                if (!linkElement->isDisabled() && linkElement->styleSheetIsLoading()) {
                     // it is loading but we should still decide which style sheet set to use
                     if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSetName.isEmpty()) {
                         const AtomicString& rel = e->getAttribute(relAttr);
@@ -301,25 +286,26 @@
                             m_selectedStylesheetSetName = title;
                         }
                     }
+
                     continue;
                 }
-                if (!linkElement->sheet())
+                sheet = linkElement->sheet();
+                if (!sheet)
                     title = nullAtom;
-            }
-            // Get the current preferred styleset. This is the
-            // set of sheets that will be enabled.
-            if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
+            } else if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag)) {
                 sheet = static_cast<SVGStyleElement*>(n)->sheet();
-            else if (e->hasLocalName(linkTag))
-                sheet = static_cast<HTMLLinkElement*>(n)->sheet();
-            else
-                // <STYLE> element
+            } else {
                 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
+            }
+
+            if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
+                activeSheet = static_cast<CSSStyleSheet*>(sheet);
+
             // Check to see if this sheet belongs to a styleset
             // (thus making it PREFERRED or ALTERNATE rather than
             // PERSISTENT).
             AtomicString rel = e->getAttribute(relAttr);
-            if (!enabledViaScript && !title.isEmpty()) {
+            if (!enabledViaScript && sheet && !title.isEmpty()) {
                 // Yes, we have a title.
                 if (m_preferredStylesheetSetName.isEmpty()) {
                     // No preferred set has been established. If
@@ -330,22 +316,24 @@
                         m_preferredStylesheetSetName = m_selectedStylesheetSetName = title;
                 }
                 if (title != m_preferredStylesheetSetName)
-                    sheet = 0;
+                    activeSheet = 0;
             }
 
             if (rel.contains("alternate") && title.isEmpty())
-                sheet = 0;
+                activeSheet = 0;
         }
         if (sheet)
-            sheets.append(sheet);
+            styleSheets.append(sheet);
+        if (activeSheet)
+            activeSheets.append(activeSheet);
     }
 }
 
-void DocumentStyleSheetCollection::analyzeStyleSheetChange(UpdateFlag updateFlag, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
+void DocumentStyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
 {
     styleResolverUpdateType = Reconstruct;
     requiresFullStyleRecalc = true;
-    
+
     // 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();
@@ -359,7 +347,7 @@
     }
     m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
 
-    if (updateFlag != OptimizedUpdate)
+    if (updateMode != AnalyzedStyleUpdate)
         return;
     if (!m_document->styleResolverIfExists())
         return;
@@ -409,17 +397,6 @@
     return false;
 }
 
-static void filterEnabledCSSStyleSheets(Vector<RefPtr<CSSStyleSheet> >& result, const Vector<RefPtr<StyleSheet> >& sheets)
-{
-    for (unsigned i = 0; i < sheets.size(); ++i) {
-        if (!sheets[i]->isCSSStyleSheet())
-            continue;
-        if (sheets[i]->disabled())
-            continue;
-        result.append(static_cast<CSSStyleSheet*>(sheets[i].get()));
-    }
-}
-
 static void collectActiveCSSStyleSheetsFromSeamlessParents(Vector<RefPtr<CSSStyleSheet> >& sheets, Document* document)
 {
     HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
@@ -428,7 +405,7 @@
     sheets.append(seamlessParentIFrame->document()->styleSheetCollection()->activeAuthorStyleSheets());
 }
 
-bool DocumentStyleSheetCollection::updateActiveStyleSheets(UpdateFlag updateFlag)
+bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
 {
     if (m_document->inStyleRecalc()) {
         // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
@@ -442,18 +419,16 @@
     if (!m_document->renderer() || !m_document->attached())
         return false;
 
-    Vector<RefPtr<StyleSheet> > activeStyleSheets;
-    collectActiveStyleSheets(activeStyleSheets);
-
+    Vector<RefPtr<StyleSheet> > styleSheets;
     Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
     activeCSSStyleSheets.append(injectedAuthorStyleSheets());
     activeCSSStyleSheets.append(documentAuthorStyleSheets());
     collectActiveCSSStyleSheetsFromSeamlessParents(activeCSSStyleSheets, m_document);
-    filterEnabledCSSStyleSheets(activeCSSStyleSheets, activeStyleSheets);
+    collectStyleSheets(styleSheets, activeCSSStyleSheets);
 
     StyleResolverUpdateType styleResolverUpdateType;
     bool requiresFullStyleRecalc;
-    analyzeStyleSheetChange(updateFlag, activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
+    analyzeStyleSheetChange(updateMode, activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
 
     if (styleResolverUpdateType == Reconstruct)
         m_document->clearStyleResolver();
@@ -469,8 +444,8 @@
         resetCSSFeatureFlags();
     }
     m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
-    InspectorInstrumentation::activeStyleSheetsUpdated(m_document, activeStyleSheets);
-    m_styleSheetsForStyleSheetList.swap(activeStyleSheets);
+    InspectorInstrumentation::activeStyleSheetsUpdated(m_document, styleSheets);
+    m_styleSheetsForStyleSheetList.swap(styleSheets);
 
     m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets);
     m_needsUpdateActiveStylesheetsOnStyleRecalc = false;
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index 51997fa..1a67e28 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -28,16 +28,17 @@
 #ifndef DocumentStyleSheetCollection_h
 #define DocumentStyleSheetCollection_h
 
-#include <wtf/FastAllocBase.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
-#include <wtf/text/WTFString.h>
+#include "core/dom/Document.h"
+#include "core/dom/DocumentOrderedList.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 class CSSStyleSheet;
-class Document;
 class Node;
 class StyleSheet;
 class StyleSheetContents;
@@ -73,8 +74,7 @@
 
     bool needsUpdateActiveStylesheetsOnStyleRecalc() const { return m_needsUpdateActiveStylesheetsOnStyleRecalc; }
 
-    enum UpdateFlag { FullUpdate, OptimizedUpdate };
-    bool updateActiveStyleSheets(UpdateFlag);
+    bool updateActiveStyleSheets(StyleResolverUpdateMode);
 
     String preferredStylesheetSetName() const { return m_preferredStylesheetSetName; }
     String selectedStylesheetSetName() const { return m_selectedStylesheetSetName; }
@@ -108,13 +108,13 @@
 private:
     DocumentStyleSheetCollection(Document*);
 
-    void collectActiveStyleSheets(Vector<RefPtr<StyleSheet> >&);
+    void collectStyleSheets(Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
     enum StyleResolverUpdateType {
         Reconstruct,
         Reset,
         Additive
     };
-    void analyzeStyleSheetChange(UpdateFlag, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
+    void analyzeStyleSheetChange(StyleResolverUpdateMode, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
 
     Document* m_document;
 
@@ -139,8 +139,7 @@
     bool m_hadActiveLoadingStylesheet;
     bool m_needsUpdateActiveStylesheetsOnStyleRecalc;
 
-    typedef ListHashSet<Node*, 32> StyleSheetCandidateListHashSet;
-    StyleSheetCandidateListHashSet m_styleSheetCandidateNodes;
+    DocumentOrderedList m_styleSheetCandidateNodes;
 
     String m_preferredStylesheetSetName;
     String m_selectedStylesheetSetName;
diff --git a/Source/core/dom/DocumentType.idl b/Source/core/dom/DocumentType.idl
index 352da12..8f192f3 100644
--- a/Source/core/dom/DocumentType.idl
+++ b/Source/core/dom/DocumentType.idl
@@ -29,11 +29,7 @@
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString publicId;
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString systemId;
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString internalSubset;        
-
-    // ChildNode interface API
-    readonly attribute Element previousElementSibling;
-    readonly attribute Element nextElementSibling;
-    [RaisesException] void remove();
+    [TreatReturnedNullStringAs=Null] readonly attribute DOMString internalSubset;
 };
 
+DocumentType implements ChildNode;
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index bf2c5fc..ab2f94d 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -26,13 +26,20 @@
 #include "config.h"
 #include "core/dom/Element.h"
 
+#include "CSSPropertyNames.h"
+#include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "SVGNames.h"
 #include "XMLNames.h"
 #include "core/accessibility/AXObjectCache.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSStyleSheet.h"
+#include "core/css/CSSValuePool.h"
+#include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
+#include "core/dom/Attribute.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/ClientRectList.h"
 #include "core/dom/CustomElementRegistry.h"
@@ -48,6 +55,7 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/PseudoElement.h"
+#include "core/dom/ScriptableDocumentParser.h"
 #include "core/dom/SelectorQuery.h"
 #include "core/dom/Text.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
@@ -66,6 +74,7 @@
 #include "core/html/HTMLOptionsCollection.h"
 #include "core/html/HTMLTableRowsCollection.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/page/ContentSecurityPolicy.h"
 #include "core/page/FocusController.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
@@ -78,8 +87,10 @@
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGElement.h"
 #include "wtf/BitVector.h"
+#include "wtf/HashFunctions.h"
 #include "wtf/MemoryInstrumentationVector.h"
 #include "wtf/text/CString.h"
+#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
@@ -90,7 +101,7 @@
 {
     return e && e->document()->isHTMLDocument() && e->isHTMLElement();
 }
-    
+
 class StyleResolverParentPusher {
 public:
     StyleResolverParentPusher(Element* parent)
@@ -187,6 +198,9 @@
     }
 #endif
 
+    if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
+        cssomWrapper->clearParentElement();
+
     if (hasRareData()) {
         ElementRareData* data = elementRareData();
         data->setPseudoElement(BEFORE, 0);
@@ -406,7 +420,7 @@
         return;
     if (elementData()->m_styleAttributeIsDirty) {
         ASSERT(isStyledElement());
-        static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
+        synchronizeStyleAttributeInternal();
     }
     if (elementData()->m_animatedSVGAttributesAreDirty) {
         ASSERT(isSVGElement());
@@ -420,7 +434,7 @@
         return;
     if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
         ASSERT(isStyledElement());
-        static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
+        synchronizeStyleAttributeInternal();
         return;
     }
     if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
@@ -437,7 +451,7 @@
         return;
     if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
         ASSERT(isStyledElement());
-        static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
+        synchronizeStyleAttributeInternal();
         return;
     }
     if (elementData()->m_animatedSVGAttributesAreDirty) {
@@ -457,7 +471,7 @@
     return nullAtom;
 }
 
-void Element::scrollIntoView(bool alignToTop) 
+void Element::scrollIntoView(bool alignToTop)
 {
     document()->updateLayoutIgnorePendingStylesheets();
 
@@ -564,6 +578,13 @@
 
 int Element::offsetWidth()
 {
+    document()->updateStyleForNodeIfNeeded(this);
+
+    if (RenderBox* renderer = renderBox()) {
+        if (!renderer->requiresLayoutToDetermineWidth())
+            return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
+    }
+
     document()->updateLayoutIgnorePendingStylesheets();
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
@@ -626,7 +647,7 @@
                 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
         }
     }
-    
+
     if (RenderBox* renderer = renderBox())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
     return 0;
@@ -638,7 +659,7 @@
 
     // When in strict mode, clientHeight for the document element should return the height of the containing frame.
     // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
-    bool inQuirksMode = document()->inQuirksMode();     
+    bool inQuirksMode = document()->inQuirksMode();
 
     if ((!inQuirksMode && document()->documentElement() == this) ||
         (inQuirksMode && isHTMLElement() && document()->body() == this)) {
@@ -647,7 +668,7 @@
                 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
         }
     }
-    
+
     if (RenderBox* renderer = renderBox())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
     return 0;
@@ -775,7 +796,7 @@
     document()->adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
     return ClientRect::create(result);
 }
-    
+
 IntRect Element::screenRect() const
 {
     if (!renderer())
@@ -874,7 +895,7 @@
     return false;
 }
 
-void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason)
+void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
 {
     if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
         if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
@@ -889,6 +910,13 @@
     bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
     bool shouldInvalidateStyle = false;
 
+    if (isStyledElement() && name == styleAttr) {
+        styleAttributeChanged(newValue, reason);
+    } else if (isStyledElement() && isPresentationAttribute(name)) {
+        elementData()->m_presentationAttributeStyleIsDirty = true;
+        setNeedsStyleRecalc(InlineStyleChange);
+    }
+
     if (isIdAttributeName(name)) {
         AtomicString oldId = elementData()->idForStyleResolution();
         AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
@@ -896,12 +924,13 @@
             elementData()->setIdForStyleResolution(newId);
             shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver);
         }
-    } else if (name == classAttr)
+    } else if (name == classAttr) {
         classAttributeChanged(newValue);
-    else if (name == HTMLNames::nameAttr)
+    } else if (name == HTMLNames::nameAttr) {
         setHasName(!newValue.isNull());
-    else if (name == HTMLNames::pseudoAttr)
+    } else if (name == HTMLNames::pseudoAttr) {
         shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
+    }
 
     invalidateNodeListCachesInAncestors(&name, this);
 
@@ -1168,7 +1197,7 @@
     return context.style()->display() != NONE;
 }
 
-RenderObject* Element::createRenderer(RenderArena*, RenderStyle* style)
+RenderObject* Element::createRenderer(RenderStyle* style)
 {
     return RenderObject::createObject(this, style);
 }
@@ -1207,7 +1236,9 @@
 bool Element::isInert() const
 {
     const Element* dialog = document()->activeModalDialog();
-    return dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this);
+    if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
+        return true;
+    return document()->ownerElement() && document()->ownerElement()->isInert();
 }
 
 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
@@ -1312,7 +1343,7 @@
     // When a shadow root exists, it does the work of attaching the children.
     if (ElementShadow* shadow = this->shadow()) {
         parentPusher.push();
-        shadow->attach();
+        shadow->attach(context);
     } else if (firstChild())
         parentPusher.push();
 
@@ -1320,7 +1351,7 @@
 
     createPseudoElementIfNeeded(AFTER);
 
-    if (hasRareData()) {   
+    if (hasRareData()) {
         ElementRareData* data = elementRareData();
         if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
             if (isFocusable() && document()->focusedNode() == this)
@@ -1328,6 +1359,12 @@
             data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
         }
     }
+
+    // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
+    // not in a Document::recalcStyle. Since we're hopefully going to always
+    // lazyAttach in the future that problem should go away.
+    if (document()->inStyleRecalc())
+        InspectorInstrumentation::didRecalculateStyleForElement(this);
 }
 
 void Element::unregisterNamedFlowContentNode()
@@ -1348,12 +1385,10 @@
         data->setIsInCanvasSubtree(false);
         data->resetComputedStyle();
         data->resetDynamicRestyleObservations();
+        data->setIsInsideRegion(false);
     }
-
-    if (ElementShadow* shadow = this->shadow()) {
-        detachChildrenIfNeeded();
-        shadow->detach();
-    }
+    if (ElementShadow* shadow = this->shadow())
+        shadow->detach(context);
     ContainerNode::detach(context);
 }
 
@@ -1455,8 +1490,10 @@
             return;
         }
 
+        InspectorInstrumentation::didRecalculateStyleForElement(this);
+
         if (RenderObject* renderer = this->renderer()) {
-            if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || styleChangeType() == SyntheticStyleChange)
+            if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || needsLayerUpdate())
                 renderer->setAnimatableStyle(newStyle.get());
             else if (needsStyleRecalc()) {
                 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
@@ -1500,8 +1537,8 @@
         if (n->isTextNode()) {
             toText(n)->recalcTextStyle(change);
             continue;
-        } 
-        if (!n->isElementNode()) 
+        }
+        if (!n->isElementNode())
             continue;
         Element* element = toElement(n);
         bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == FullStyleChange;
@@ -1520,10 +1557,9 @@
 
     clearNeedsStyleRecalc();
     clearChildNeedsStyleRecalc();
-    
+
     if (hasCustomStyleCallbacks())
         didRecalcStyle(change);
-    InspectorInstrumentation::didRecalculateStyleForElement(this);
 }
 
 ElementShadow* Element::shadow() const
@@ -1627,7 +1663,7 @@
 {
     // :empty selector.
     checkForEmptyStyleChange(e, style);
-    
+
     if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
         return;
 
@@ -1638,18 +1674,18 @@
         // Find our new first child.
         Node* newFirstChild = 0;
         for (newFirstChild = e->firstChild(); newFirstChild && !newFirstChild->isElementNode(); newFirstChild = newFirstChild->nextSibling()) {};
-        
+
         // Find the first element node following |afterChange|
         Node* firstElementAfterInsertion = 0;
         for (firstElementAfterInsertion = afterChange;
              firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
              firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
-        
+
         // This is the insert/append case.
         if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertion && firstElementAfterInsertion->attached() &&
             firstElementAfterInsertion->renderStyle() && firstElementAfterInsertion->renderStyle()->firstChildState())
             firstElementAfterInsertion->setNeedsStyleRecalc();
-            
+
         // We also have to handle node removal.
         if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChild->renderStyle() || !newFirstChild->renderStyle()->firstChildState()))
             newFirstChild->setNeedsStyleRecalc();
@@ -1661,17 +1697,17 @@
         // Find our new last child.
         Node* newLastChild = 0;
         for (newLastChild = e->lastChild(); newLastChild && !newLastChild->isElementNode(); newLastChild = newLastChild->previousSibling()) {};
-        
+
         // Find the last element node going backwards from |beforeChange|
         Node* lastElementBeforeInsertion = 0;
         for (lastElementBeforeInsertion = beforeChange;
              lastElementBeforeInsertion && !lastElementBeforeInsertion->isElementNode();
              lastElementBeforeInsertion = lastElementBeforeInsertion->previousSibling()) {};
-        
+
         if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertion && lastElementBeforeInsertion->attached() &&
             lastElementBeforeInsertion->renderStyle() && lastElementBeforeInsertion->renderStyle()->lastChildState())
             lastElementBeforeInsertion->setNeedsStyleRecalc();
-            
+
         // We also have to handle node removal.  The parser callback case is similar to node removal as well in that we need to change the last child
         // to match now.
         if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChild->renderStyle() || !newLastChild->renderStyle()->lastChildState()))
@@ -1803,6 +1839,7 @@
     setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
 
     attrNode->attachToElement(this);
+    treeScope()->adoptIfNeeded(attrNode);
     ensureAttrNodeListForElement(this)->append(attrNode);
 
     return oldAttrNode.release();
@@ -1906,7 +1943,7 @@
     size_t index = elementData()->getAttributeItemIndex(localName, false);
     if (index == notFound) {
         if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
-            static_cast<StyledElement*>(this)->removeAllInlineStyleProperties();
+            removeAllInlineStyleProperties();
         return;
     }
 
@@ -1958,11 +1995,6 @@
     return elementData()->getAttributeItem(qName);
 }
 
-CSSStyleDeclaration *Element::style()
-{
-    return 0;
-}
-
 void Element::focus(bool restorePreviousSelection, FocusDirection direction)
 {
     if (!inDocument())
@@ -1974,7 +2006,7 @@
 
     // If the stylesheets have already been loaded we can reliably check isFocusable.
     // If not, we continue and set the focused node on the focus controller below so
-    // that it can be updated soon after attach. 
+    // that it can be updated soon after attach.
     if (doc->haveStylesheetsLoaded()) {
         doc->updateLayoutIgnorePendingStylesheets();
         if (!isFocusable())
@@ -2001,7 +2033,7 @@
         ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
         return;
     }
-        
+
     cancelFocusAppearanceUpdate();
     updateFocusAppearance(restorePreviousSelection);
 }
@@ -2012,14 +2044,14 @@
         Frame* frame = document()->frame();
         if (!frame)
             return;
-        
+
         // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
         if (this == frame->selection()->rootEditableElement())
             return;
 
         // FIXME: We should restore the previous selection if there is one.
         VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
-        
+
         if (frame->selection()->shouldChangeSelection(newSelection)) {
             frame->selection()->setSelection(newSelection);
             frame->selection()->revealSelection();
@@ -2061,6 +2093,46 @@
     return innerText();
 }
 
+String Element::textFromChildren()
+{
+    Text* firstTextNode = 0;
+    bool foundMultipleTextNodes = false;
+    unsigned totalLength = 0;
+
+    for (Node* child = firstChild(); child; child = child->nextSibling()) {
+        if (!child->isTextNode())
+            continue;
+        Text* text = toText(child);
+        if (!firstTextNode)
+            firstTextNode = text;
+        else
+            foundMultipleTextNodes = true;
+        unsigned length = text->data().length();
+        if (length > std::numeric_limits<unsigned>::max() - totalLength)
+            return emptyString();
+        totalLength += length;
+    }
+
+    if (!firstTextNode)
+        return emptyString();
+
+    if (firstTextNode && !foundMultipleTextNodes) {
+        firstTextNode->atomize();
+        return firstTextNode->data();
+    }
+
+    StringBuilder content;
+    content.reserveCapacity(totalLength);
+    for (Node* child = firstTextNode; child; child = child->nextSibling()) {
+        if (!child->isTextNode())
+            continue;
+        content.append(toText(child)->data());
+    }
+
+    ASSERT(content.length() == totalLength);
+    return content.toString();
+}
+
 String Element::title() const
 {
     return String();
@@ -2260,6 +2332,29 @@
     return isCustomElement() && document()->registry()->isUnresolved(this);
 }
 
+void Element::setIsInsideRegion(bool value)
+{
+    if (value == isInsideRegion())
+        return;
+
+    ensureElementRareData()->setIsInsideRegion(value);
+}
+
+bool Element::isInsideRegion() const
+{
+    return hasRareData() ? elementRareData()->isInsideRegion() : false;
+}
+
+void Element::setRegionOversetState(RegionOversetState state)
+{
+    ensureElementRareData()->setRegionOversetState(state);
+}
+
+RegionOversetState Element::regionOversetState() const
+{
+    return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
+}
+
 AtomicString Element::computeInheritedLanguage() const
 {
     const Node* n = this;
@@ -2548,6 +2643,22 @@
     return 0;
 }
 
+bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
+{
+    ASSERT(styleToUse);
+
+    if (FullscreenController::isActiveFullScreenElement(this))
+        return false;
+
+    if (isInShadowTree())
+        return false;
+
+    if (styleToUse->flowThread().isEmpty())
+        return false;
+
+    return !isRegisteredWithNamedFlow();
+}
+
 const AtomicString& Element::webkitRegionOverset() const
 {
     document()->updateLayoutIgnorePendingStylesheets();
@@ -2556,20 +2667,20 @@
     if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
         return undefinedState;
 
-    switch (renderRegion()->regionState()) {
-    case RenderRegion::RegionFit: {
+    switch (renderRegion()->regionOversetState()) {
+    case RegionFit: {
         DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
         return fitState;
     }
-    case RenderRegion::RegionEmpty: {
+    case RegionEmpty: {
         DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
         return emptyState;
     }
-    case RenderRegion::RegionOverset: {
+    case RegionOverset: {
         DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
         return overflowState;
     }
-    case RenderRegion::RegionUndefined:
+    case RegionUndefined:
         return undefinedState;
     }
 
@@ -2752,17 +2863,17 @@
     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
 }
 
-static void needsSyntheticStyleChangeCallback(Node* node)
+static void scheduleLayerUpdateCallback(Node* node)
 {
-    node->setNeedsStyleRecalc(SyntheticStyleChange);
+    node->setNeedsLayerUpdate();
 }
 
-void Element::scheduleSyntheticStyleChange()
+void Element::scheduleLayerUpdate()
 {
     if (postAttachCallbacksAreSuspended())
-        queuePostAttachCallback(needsSyntheticStyleChangeCallback, this);
+        queuePostAttachCallback(scheduleLayerUpdateCallback, this);
     else
-        setNeedsStyleRecalc(SyntheticStyleChange);
+        setNeedsLayerUpdate();
 }
 
 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
@@ -2934,6 +3045,345 @@
     ensureElementRareData()->setHasPendingResources(false);
 }
 
+struct PresentationAttributeCacheKey {
+    PresentationAttributeCacheKey() : tagName(0) { }
+    AtomicStringImpl* tagName;
+    // Only the values need refcounting.
+    Vector<pair<AtomicStringImpl*, AtomicString>, 3> attributesAndValues;
+};
+
+struct PresentationAttributeCacheEntry {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    PresentationAttributeCacheKey key;
+    RefPtr<StylePropertySet> value;
+};
+
+typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
+
+static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
+{
+    if (a.tagName != b.tagName)
+        return true;
+    return a.attributesAndValues != b.attributesAndValues;
+}
+
+static PresentationAttributeCache& presentationAttributeCache()
+{
+    DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
+    return cache;
+}
+
+class PresentationAttributeCacheCleaner {
+    WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
+public:
+    PresentationAttributeCacheCleaner()
+        : m_hitCount(0)
+        , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
+    {
+    }
+
+    void didHitPresentationAttributeCache()
+    {
+        if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
+            return;
+
+        m_hitCount++;
+
+        if (!m_cleanTimer.isActive())
+            m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
+    }
+
+private:
+    static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
+    static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
+    static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
+
+    void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
+    {
+        ASSERT_UNUSED(timer, timer == &m_cleanTimer);
+        unsigned hitCount = m_hitCount;
+        m_hitCount = 0;
+        if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
+            return;
+        presentationAttributeCache().clear();
+    }
+
+    unsigned m_hitCount;
+    Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
+};
+
+static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
+{
+    DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
+    return cleaner;
+}
+
+void Element::synchronizeStyleAttributeInternal() const
+{
+    ASSERT(isStyledElement());
+    ASSERT(elementData());
+    ASSERT(elementData()->m_styleAttributeIsDirty);
+    elementData()->m_styleAttributeIsDirty = false;
+    if (const StylePropertySet* inlineStyle = this->inlineStyle())
+        const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
+}
+
+CSSStyleDeclaration* Element::style()
+{
+    if (!isStyledElement())
+        return 0;
+    return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
+}
+
+MutableStylePropertySet* Element::ensureMutableInlineStyle()
+{
+    ASSERT(isStyledElement());
+    RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
+    if (!inlineStyle)
+        inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
+    else if (!inlineStyle->isMutable())
+        inlineStyle = inlineStyle->mutableCopy();
+    ASSERT(inlineStyle->isMutable());
+    return static_cast<MutableStylePropertySet*>(inlineStyle.get());
+}
+
+PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
+{
+    if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
+        return 0;
+    PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
+    ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
+    return cssomWrapper;
+}
+
+inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
+{
+    ASSERT(isStyledElement());
+    RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
+
+    // Avoid redundant work if we're using shared attribute data with already parsed inline style.
+    if (inlineStyle && !elementData()->isUnique())
+        return;
+
+    // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
+    // This makes wrapperless property sets immutable and so cacheable.
+    if (inlineStyle && !inlineStyle->isMutable())
+        inlineStyle.clear();
+
+    if (!inlineStyle) {
+        inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
+    } else {
+        ASSERT(inlineStyle->isMutable());
+        static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
+    }
+}
+
+void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
+{
+    ASSERT(isStyledElement());
+    WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
+    if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
+        startLineNumber = document()->scriptableDocumentParser()->lineNumber();
+
+    if (newStyleString.isNull()) {
+        if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
+            cssomWrapper->clearParentElement();
+        ensureUniqueElementData()->m_inlineStyle.clear();
+    } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
+        setInlineStyleFromString(newStyleString);
+    }
+
+    elementData()->m_styleAttributeIsDirty = false;
+
+    setNeedsStyleRecalc(InlineStyleChange);
+    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
+}
+
+void Element::inlineStyleChanged()
+{
+    ASSERT(isStyledElement());
+    setNeedsStyleRecalc(InlineStyleChange);
+    ASSERT(elementData());
+    elementData()->m_styleAttributeIsDirty = true;
+    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
+{
+    ASSERT(isStyledElement());
+    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
+    inlineStyleChanged();
+    return true;
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
+{
+    ASSERT(isStyledElement());
+    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
+    inlineStyleChanged();
+    return true;
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
+{
+    ASSERT(isStyledElement());
+    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
+    inlineStyleChanged();
+    return true;
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
+{
+    ASSERT(isStyledElement());
+    bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
+    if (changes)
+        inlineStyleChanged();
+    return changes;
+}
+
+bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
+{
+    ASSERT(isStyledElement());
+    if (!inlineStyle())
+        return false;
+    bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
+    if (changes)
+        inlineStyleChanged();
+    return changes;
+}
+
+void Element::removeAllInlineStyleProperties()
+{
+    ASSERT(isStyledElement());
+    if (!inlineStyle() || inlineStyle()->isEmpty())
+        return;
+    ensureMutableInlineStyle()->clear();
+    inlineStyleChanged();
+}
+
+void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
+{
+    ASSERT(isStyledElement());
+    if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
+        inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
+}
+
+static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
+{
+    // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
+    return p1.first < p2.first;
+}
+
+void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
+{
+    ASSERT(isStyledElement());
+    // FIXME: Enable for SVG.
+    if (namespaceURI() != xhtmlNamespaceURI)
+        return;
+    // Interpretation of the size attributes on <input> depends on the type attribute.
+    if (hasTagName(inputTag))
+        return;
+    unsigned size = attributeCount();
+    for (unsigned i = 0; i < size; ++i) {
+        const Attribute* attribute = attributeItem(i);
+        if (!isPresentationAttribute(attribute->name()))
+            continue;
+        if (!attribute->namespaceURI().isNull())
+            return;
+        // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
+        if (attribute->name() == backgroundAttr)
+            return;
+        result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
+    }
+    if (result.attributesAndValues.isEmpty())
+        return;
+    // Attribute order doesn't matter. Sort for easy equality comparison.
+    std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
+    // The cache key is non-null when the tagName is set.
+    result.tagName = localName().impl();
+}
+
+static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
+{
+    if (!key.tagName)
+        return 0;
+    ASSERT(key.attributesAndValues.size());
+    unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
+    return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
+}
+
+void Element::rebuildPresentationAttributeStyle()
+{
+    ASSERT(isStyledElement());
+    PresentationAttributeCacheKey cacheKey;
+    makePresentationAttributeCacheKey(cacheKey);
+
+    unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
+
+    PresentationAttributeCache::iterator cacheIterator;
+    if (cacheHash) {
+        cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
+        if (cacheIterator->value && cacheIterator->value->key != cacheKey)
+            cacheHash = 0;
+    } else {
+        cacheIterator = presentationAttributeCache().end();
+    }
+
+    RefPtr<StylePropertySet> style;
+    if (cacheHash && cacheIterator->value) {
+        style = cacheIterator->value->value;
+        presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
+    } else {
+        style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
+        unsigned size = attributeCount();
+        for (unsigned i = 0; i < size; ++i) {
+            const Attribute* attribute = attributeItem(i);
+            collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
+        }
+    }
+
+    // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
+    UniqueElementData* elementData = ensureUniqueElementData();
+
+    elementData->m_presentationAttributeStyleIsDirty = false;
+    elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
+
+    if (!cacheHash || cacheIterator->value)
+        return;
+
+    OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
+    newEntry->key = cacheKey;
+    newEntry->value = style.release();
+
+    static const int presentationAttributeCacheMaximumSize = 4096;
+    if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
+        // Start building from scratch if the cache ever gets big.
+        presentationAttributeCache().clear();
+        presentationAttributeCache().set(cacheHash, newEntry.release());
+    } else {
+        cacheIterator->value = newEntry.release();
+    }
+}
+
+void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
+{
+    ASSERT(isStyledElement());
+    style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
+}
+
+void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
+{
+    ASSERT(isStyledElement());
+    style->setProperty(propertyID, cssValuePool().createValue(value, unit));
+}
+
+void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
+{
+    ASSERT(isStyledElement());
+    style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
+}
+
 void ElementData::deref()
 {
     if (!derefBase())
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index fed0c42..2aa1745 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -25,19 +25,21 @@
 #ifndef Element_h
 #define Element_h
 
+#include "CSSPropertyNames.h"
 #include "HTMLNames.h"
+#include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
-#include "core/dom/FragmentScriptingPermission.h"
 #include "core/dom/SpaceSplitString.h"
 #include "core/html/CollectionType.h"
 #include "core/platform/ScrollTypes.h"
+#include "core/rendering/RegionOversetState.h"
 
 namespace WebCore {
 
 class Animation;
-
 class Attr;
+class Attribute;
 class ClientRect;
 class ClientRectList;
 class DOMStringMap;
@@ -48,6 +50,8 @@
 class InputMethodContext;
 class IntSize;
 class Locale;
+class MutableStylePropertySet;
+class PropertySetCSSStyleDeclaration;
 class PseudoElement;
 class RenderRegion;
 class ShadowRoot;
@@ -55,6 +59,8 @@
 class StylePropertySet;
 class UniqueElementData;
 
+struct PresentationAttributeCacheKey;
+
 class ElementData : public RefCounted<ElementData> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -108,7 +114,6 @@
 
 private:
     friend class Element;
-    friend class StyledElement;
     friend class ShareableElementData;
     friend class UniqueElementData;
     friend class SVGElement;
@@ -345,7 +350,7 @@
 
     const Vector<RefPtr<Attr> >& attrNodeList();
 
-    virtual CSSStyleDeclaration* style();
+    CSSStyleDeclaration* style();
 
     const QualifiedName& tagQName() const { return m_tagName; }
     String tagName() const { return nodeName(); }
@@ -366,13 +371,30 @@
     PassRefPtr<Element> cloneElementWithChildren();
     PassRefPtr<Element> cloneElementWithoutChildren();
 
-    void scheduleSyntheticStyleChange();
+    void scheduleLayerUpdate();
 
     void normalizeAttributes();
     String nodeNamePreservingCase() const;
 
     void setBooleanAttribute(const QualifiedName& name, bool);
 
+    virtual const StylePropertySet* additionalPresentationAttributeStyle() { return 0; }
+    void invalidateStyleAttribute();
+
+    const StylePropertySet* inlineStyle() const { return elementData() ? elementData()->m_inlineStyle.get() : 0; }
+
+    bool setInlineStyleProperty(CSSPropertyID, CSSValueID identifier, bool important = false);
+    bool setInlineStyleProperty(CSSPropertyID, CSSPropertyID identifier, bool important = false);
+    bool setInlineStyleProperty(CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes, bool important = false);
+    bool setInlineStyleProperty(CSSPropertyID, const String& value, bool important = false);
+    bool removeInlineStyleProperty(CSSPropertyID);
+    void removeAllInlineStyleProperties();
+
+    void synchronizeStyleAttributeInternal() const;
+
+    const StylePropertySet* presentationAttributeStyle();
+    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) { }
+
     // For exposing to DOM only.
     NamedNodeMap* attributes() const;
 
@@ -408,7 +430,7 @@
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
     void recalcStyle(StyleChange = NoChange);
     void didAffectSelector(AffectedSelectorMask);
@@ -459,6 +481,12 @@
 
     bool isUnresolvedCustomElement();
 
+    void setIsInsideRegion(bool);
+    bool isInsideRegion() const;
+
+    void setRegionOversetState(RegionOversetState);
+    RegionOversetState regionOversetState() const;
+
     AtomicString computeInheritedLanguage() const;
     Locale& locale() const;
 
@@ -480,6 +508,8 @@
     String innerText();
     String outerText();
  
+    String textFromChildren();
+
     virtual String title() const;
 
     const AtomicString& pseudo() const;
@@ -578,6 +608,7 @@
     PassRefPtr<RenderStyle> originalStyleForRenderer();
 
     RenderRegion* renderRegion() const;
+    virtual bool shouldMoveToFlowThread(RenderStyle*) const;
     const AtomicString& webkitRegionOverset() const;
     Vector<RefPtr<Range> > webkitGetRegionFlowRanges() const;
 
@@ -605,6 +636,14 @@
         ScriptWrappable::init(this);
     }
 
+    virtual bool isPresentationAttribute(const QualifiedName&) const { return false; }
+
+    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, CSSValueID identifier);
+    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes);
+    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
+
+    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+
     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;
@@ -632,6 +671,16 @@
     void classAttributeChanged(const AtomicString& newClassString);
 
 private:
+    void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
+
+    void inlineStyleChanged();
+    PropertySetCSSStyleDeclaration* inlineStyleCSSOMWrapper();
+    void setInlineStyleFromString(const AtomicString&);
+    MutableStylePropertySet* ensureMutableInlineStyle();
+
+    void makePresentationAttributeCacheKey(PresentationAttributeCacheKey&) const;
+    void rebuildPresentationAttributeStyle();
+
     void updatePseudoElement(PseudoId, StyleChange);
     void createPseudoElementIfNeeded(PseudoId);
 
@@ -771,7 +820,7 @@
     Node* n = previousSibling();
     while (n && !n->isElementNode())
         n = n->previousSibling();
-    return static_cast<Element*>(n);
+    return toElement(n);
 }
 
 inline Element* Node::nextElementSibling() const
@@ -779,7 +828,7 @@
     Node* n = nextSibling();
     while (n && !n->isElementNode())
         n = n->nextSibling();
-    return static_cast<Element*>(n);
+    return toElement(n);
 }
 
 inline bool Element::fastHasAttribute(const QualifiedName& name) const
@@ -914,6 +963,21 @@
         clearFlag(IsInShadowTreeFlag);
 }
 
+inline void Element::invalidateStyleAttribute()
+{
+    ASSERT(elementData());
+    elementData()->m_styleAttributeIsDirty = true;
+}
+
+inline const StylePropertySet* Element::presentationAttributeStyle()
+{
+    if (!elementData())
+        return 0;
+    if (elementData()->m_presentationAttributeStyleIsDirty)
+        rebuildPresentationAttributeStyle();
+    return elementData()->presentationAttributeStyle();
+}
+
 inline bool isShadowHost(const Node* node)
 {
     return node && node->isElementNode() && toElement(node)->shadow();
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 55f592f..543a8a1 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -105,11 +105,6 @@
     [ImplementedAs=createShadowRoot, RaisesException] ShadowRoot webkitCreateShadowRoot();
     [ImplementedAs=shadowRoot, PerWorldBindings] readonly attribute ShadowRoot webkitShadowRoot;
 
-    // ChildNode interface API
-    [PerWorldBindings] readonly attribute Element previousElementSibling;
-    [PerWorldBindings] readonly attribute Element nextElementSibling;
-    [RaisesException] void remove();
-
     // CSSOM View Module API
     ClientRectList getClientRects();
     ClientRect getBoundingClientRect();
@@ -199,3 +194,7 @@
     [NotEnumerable, PerWorldBindings] attribute EventListener onwebkitfullscreenchange;
     [NotEnumerable, PerWorldBindings] attribute EventListener onwebkitfullscreenerror;
 };
+
+Element implements ParentNode;
+Element implements ChildNode;
+
diff --git a/Source/core/dom/ElementRareData.cpp b/Source/core/dom/ElementRareData.cpp
index 24e14a9..dd404bf 100644
--- a/Source/core/dom/ElementRareData.cpp
+++ b/Source/core/dom/ElementRareData.cpp
@@ -32,6 +32,7 @@
 #include "core/dom/ElementRareData.h"
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
+#include "core/rendering/RegionOversetState.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
@@ -39,6 +40,7 @@
 struct SameSizeAsElementRareData : NodeRareData {
     short indices[2];
     unsigned bitfields;
+    RegionOversetState regionOversetState;
     LayoutSize sizeForResizing;
     IntSize scrollOffset;
     void* pointers[9];
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index 89bee36..440df8e 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -22,7 +22,6 @@
 #ifndef ElementRareData_h
 #define ElementRareData_h
 
-#include "core/animation/Animation.h"
 #include "core/dom/DatasetDOMStringMap.h"
 #include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRareData.h"
@@ -31,7 +30,7 @@
 #include "core/html/ClassList.h"
 #include "core/html/ime/InputMethodContext.h"
 #include "core/rendering/style/StyleInheritedData.h"
-#include <wtf/OwnPtr.h>
+#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
@@ -64,6 +63,12 @@
     bool isInCanvasSubtree() const { return m_isInCanvasSubtree; }
     void setIsInCanvasSubtree(bool value) { m_isInCanvasSubtree = value; }
 
+    bool isInsideRegion() const { return m_isInsideRegion; }
+    void setIsInsideRegion(bool value) { m_isInsideRegion = value; }
+
+    RegionOversetState regionOversetState() const { return m_regionOversetState; }
+    void setRegionOversetState(RegionOversetState state) { m_regionOversetState = state; }
+
     bool containsFullScreenElement() { return m_containsFullScreenElement; }
     void setContainsFullScreenElement(bool value) { m_containsFullScreenElement = value; }
 
@@ -164,6 +169,9 @@
     unsigned m_childrenAffectedByForwardPositionalRules : 1;
     unsigned m_childrenAffectedByBackwardPositionalRules : 1;
 
+    unsigned m_isInsideRegion : 1;
+    RegionOversetState m_regionOversetState;
+
     LayoutSize m_minimumSizeForResizing;
     IntSize m_savedLayerScrollOffset;
     RefPtr<RenderStyle> m_computedStyle;
@@ -207,6 +215,8 @@
     , m_childrenAffectedByDirectAdjacentRules(false)
     , m_childrenAffectedByForwardPositionalRules(false)
     , m_childrenAffectedByBackwardPositionalRules(false)
+    , m_isInsideRegion(false)
+    , m_regionOversetState(RegionUndefined)
     , m_minimumSizeForResizing(defaultMinimumSizeForResizing())
 {
 }
diff --git a/Source/core/dom/Event.cpp b/Source/core/dom/Event.cpp
index c713e0d..770e175 100644
--- a/Source/core/dom/Event.cpp
+++ b/Source/core/dom/Event.cpp
@@ -172,11 +172,6 @@
     info.addMember(m_underlyingEvent, "underlyingEvent");
 }
 
-PassRefPtr<Event> Event::cloneFor(HTMLIFrameElement*) const
-{
-    return Event::create(type(), bubbles(), cancelable());
-}
-
 void Event::setTarget(PassRefPtr<EventTarget> target)
 {
     if (m_target == target)
diff --git a/Source/core/dom/Event.h b/Source/core/dom/Event.h
index f736261..60a60fa 100644
--- a/Source/core/dom/Event.h
+++ b/Source/core/dom/Event.h
@@ -27,11 +27,8 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/DOMTimeStamp.h"
 #include "core/dom/EventContext.h"
-#include "core/dom/EventNames.h"
-#include <wtf/HashMap.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/RefCounted.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -169,8 +166,6 @@
 
     virtual void reportMemoryUsage(MemoryObjectInfo*) const;
 
-    virtual PassRefPtr<Event> cloneFor(HTMLIFrameElement*) const;
-
 protected:
     Event();
     Event(const AtomicString& type, bool canBubble, bool cancelable);
diff --git a/Source/core/dom/EventAliases.in b/Source/core/dom/EventAliases.in
new file mode 100644
index 0000000..07c2e49
--- /dev/null
+++ b/Source/core/dom/EventAliases.in
@@ -0,0 +1,13 @@
+# Aliases
+Events ImplementedAs=Event
+HTMLEvents ImplementedAs=Event
+KeyboardEvents ImplementedAs=KeyboardEvent
+MouseEvents ImplementedAs=MouseEvent
+MutationEvents ImplementedAs=MutationEvent
+OrientationEvent ImplementedAs=Event, Conditional=ORIENTATION_EVENTS
+SVGEvents ImplementedAs=Event
+SVGZoomEvents ImplementedAs=SVGZoomEvent
+UIEvents ImplementedAs=UIEvent
+WebKitTransitionEvent ImplementedAs=TransitionEvent
+
+core/dom/TouchEvent EnabledAtRuntime=touchEnabled
diff --git a/Source/core/dom/EventDispatcher.cpp b/Source/core/dom/EventDispatcher.cpp
index c84ede2..bf9f40b 100644
--- a/Source/core/dom/EventDispatcher.cpp
+++ b/Source/core/dom/EventDispatcher.cpp
@@ -35,8 +35,7 @@
 #include "core/dom/WindowEventContext.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/FrameView.h"
-#include <wtf/RefPtr.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
@@ -200,6 +199,7 @@
     // implementation detail and not part of the DOM.
     if (!m_event->defaultPrevented() && !m_event->defaultHandled()) {
         // Non-bubbling events call only one default event handler, the one for the target.
+        m_node->willCallDefaultEventHandler(*m_event);
         m_node->defaultEventHandler(m_event.get());
         ASSERT(!m_event->defaultPrevented());
         if (m_event->defaultHandled())
@@ -209,6 +209,7 @@
         if (m_event->bubbles()) {
             size_t size = m_event->eventPath().size();
             for (size_t i = 1; i < size; ++i) {
+                m_event->eventPath()[i]->node()->willCallDefaultEventHandler(*m_event);
                 m_event->eventPath()[i]->node()->defaultEventHandler(m_event.get());
                 ASSERT(!m_event->defaultPrevented());
                 if (m_event->defaultHandled())
diff --git a/Source/core/dom/EventDispatcher.h b/Source/core/dom/EventDispatcher.h
index b4a439e..5587132 100644
--- a/Source/core/dom/EventDispatcher.h
+++ b/Source/core/dom/EventDispatcher.h
@@ -28,10 +28,8 @@
 
 #include "core/dom/EventContext.h"
 #include "core/dom/SimulatedClickOptions.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/EventListenerMap.cpp b/Source/core/dom/EventListenerMap.cpp
index 7753865..1bc8690 100644
--- a/Source/core/dom/EventListenerMap.cpp
+++ b/Source/core/dom/EventListenerMap.cpp
@@ -34,12 +34,11 @@
 #include "core/dom/EventListenerMap.h"
 
 #include "core/dom/EventTarget.h"
-#include <wtf/MainThread.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/Vector.h>
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
 
 #ifndef NDEBUG
-#include <wtf/Threading.h>
+#include "wtf/Threading.h"
 #endif
 
 using namespace WTF;
diff --git a/Source/core/dom/EventNames.h b/Source/core/dom/EventNames.h
index 9438b10..69796a9 100644
--- a/Source/core/dom/EventNames.h
+++ b/Source/core/dom/EventNames.h
@@ -252,6 +252,8 @@
     \
     macro(webkitregionlayoutupdate) \
     \
+    macro(webkitregionoversetchange) \
+    \
     macro(webkitnetworkinfochange) \
     \
     macro(webkitresourcetimingbufferfull) \
diff --git a/Source/core/dom/EventNames.in b/Source/core/dom/EventNames.in
deleted file mode 100644
index 25a9ac3..0000000
--- a/Source/core/dom/EventNames.in
+++ /dev/null
@@ -1,64 +0,0 @@
-namespace="Event"
-
-core/css/CSSFontFaceLoadEvent
-core/dom/AutocompleteErrorEvent
-core/dom/BeforeLoadEvent
-core/dom/CompositionEvent
-core/dom/CustomEvent
-core/dom/DeviceOrientationEvent
-core/dom/ErrorEvent
-core/dom/Event
-core/dom/FocusEvent
-core/dom/HashChangeEvent
-core/dom/KeyboardEvent
-core/dom/MessageEvent
-core/dom/MouseEvent
-core/dom/MutationEvent
-core/dom/OverflowEvent
-core/dom/PageTransitionEvent
-core/dom/PopStateEvent
-core/dom/ProgressEvent
-core/dom/ResourceProgressEvent
-core/dom/SecurityPolicyViolationEvent
-core/dom/TextEvent
-core/dom/TouchEvent runtimeConditional=touchEnabled
-core/dom/TransitionEvent
-core/dom/UIEvent
-core/dom/WebKitAnimationEvent implementedAs=AnimationEvent
-core/dom/WebKitTransitionEvent implementedAs=TransitionEvent
-core/dom/WheelEvent
-core/html/MediaKeyEvent
-core/html/canvas/WebGLContextEvent
-core/html/track/TrackEvent
-core/page/SpeechInputEvent conditional=INPUT_SPEECH
-core/storage/StorageEvent
-core/svg/SVGEvents implementedAs=Event
-core/svg/SVGZoomEvent
-core/xml/XMLHttpRequestProgressEvent
-modules/device_orientation/DeviceMotionEvent
-modules/encryptedmedia/MediaKeyMessageEvent conditional=ENCRYPTED_MEDIA_V2
-modules/encryptedmedia/MediaKeyNeededEvent conditional=ENCRYPTED_MEDIA_V2
-modules/indexeddb/IDBVersionChangeEvent
-modules/mediastream/MediaStreamEvent
-modules/mediastream/MediaStreamTrackEvent
-modules/mediastream/RTCDTMFToneChangeEvent
-modules/mediastream/RTCDataChannelEvent
-modules/mediastream/RTCIceCandidateEvent
-modules/speech/SpeechRecognitionError
-modules/speech/SpeechRecognitionEvent
-modules/speech/SpeechSynthesisEvent
-modules/webaudio/AudioProcessingEvent conditional=WEB_AUDIO
-modules/webaudio/OfflineAudioCompletionEvent conditional=WEB_AUDIO
-modules/webmidi/MIDIConnectionEvent
-modules/webmidi/MIDIMessageEvent
-modules/websockets/CloseEvent
-
-# Aliases
-Events implementedAs=Event
-HTMLEvents implementedAs=Event
-KeyboardEvents implementedAs=KeyboardEvent
-MouseEvents implementedAs=MouseEvent
-MutationEvents implementedAs=MutationEvent
-OrientationEvent implementedAs=Event, conditional=ORIENTATION_EVENTS
-SVGZoomEvents implementedAs=SVGZoomEvent
-UIEvents implementedAs=UIEvent
diff --git a/Source/core/dom/EventRetargeter.h b/Source/core/dom/EventRetargeter.h
index 76cfd9e..f274e70 100644
--- a/Source/core/dom/EventRetargeter.h
+++ b/Source/core/dom/EventRetargeter.h
@@ -27,7 +27,6 @@
 #include "core/svg/SVGElementInstance.h"
 #include "core/svg/SVGUseElement.h"
 #include "wtf/HashMap.h"
-#include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/EventTarget.cpp b/Source/core/dom/EventTarget.cpp
index c06d6dd..15fb804 100644
--- a/Source/core/dom/EventTarget.cpp
+++ b/Source/core/dom/EventTarget.cpp
@@ -37,9 +37,8 @@
 #include "core/dom/Event.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include <wtf/MainThread.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/Vector.h>
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
 
 using namespace WTF;
 
diff --git a/Source/core/dom/EventTarget.h b/Source/core/dom/EventTarget.h
index 58837f0..2d8a0a9 100644
--- a/Source/core/dom/EventTarget.h
+++ b/Source/core/dom/EventTarget.h
@@ -34,14 +34,12 @@
 
 #include "core/dom/EventListenerMap.h"
 #include "core/dom/EventNames.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/text/AtomicStringHash.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
     class AudioContext;
-    class DedicatedWorkerContext;
+    class DedicatedWorkerGlobalScope;
     class DOMApplicationCache;
     class DOMWindow;
     class Event;
@@ -65,7 +63,7 @@
     class ScriptExecutionContext;
     class ScriptProcessorNode;
     class SharedWorker;
-    class SharedWorkerContext;
+    class SharedWorkerGlobalScope;
     class TextTrack;
     class TextTrackCue;
     class WebSocket;
diff --git a/Source/core/dom/EventTargetFactory.in b/Source/core/dom/EventTargetFactory.in
index 5ebf267..1929c1e 100644
--- a/Source/core/dom/EventTargetFactory.in
+++ b/Source/core/dom/EventTargetFactory.in
@@ -3,7 +3,7 @@
 core/css/FontLoader
 core/dom/MessagePort
 core/dom/Node
-core/dom/WebKitNamedFlow implementedAs=NamedFlow
+core/dom/WebKitNamedFlow ImplementedAs=NamedFlow
 core/fileapi/FileReader
 core/html/MediaController
 core/html/track/TextTrack
@@ -12,15 +12,15 @@
 core/loader/appcache/DOMApplicationCache
 core/page/EventSource
 core/page/Performance
-core/page/Window implementedAs=DOMWindow
+core/page/Window ImplementedAs=DOMWindow
 core/svg/SVGElementInstance
-core/workers/DedicatedWorkerContext
+core/workers/DedicatedWorkerGlobalScope
 core/workers/SharedWorker
-core/workers/SharedWorkerContext
+core/workers/SharedWorkerGlobalScope
 core/workers/Worker
 core/xml/XMLHttpRequest
 core/xml/XMLHttpRequestUpload
-modules/encryptedmedia/MediaKeySession conditional=ENCRYPTED_MEDIA_V2
+modules/encryptedmedia/MediaKeySession Conditional=ENCRYPTED_MEDIA_V2
 modules/filesystem/FileWriter
 modules/indexeddb/IDBDatabase
 modules/indexeddb/IDBOpenDBRequest
@@ -36,11 +36,11 @@
 modules/mediastream/RTCDTMFSender
 modules/mediastream/RTCDataChannel
 modules/mediastream/RTCPeerConnection
-modules/notifications/Notification conditional=NOTIFICATIONS
+modules/notifications/Notification Conditional=NOTIFICATIONS
 modules/speech/SpeechRecognition
 modules/speech/SpeechSynthesisUtterance
-modules/webaudio/AudioContext conditional=WEB_AUDIO
-modules/webaudio/AudioNode conditional=WEB_AUDIO
+modules/webaudio/AudioContext Conditional=WEB_AUDIO
+modules/webaudio/AudioNode Conditional=WEB_AUDIO
 modules/webmidi/MIDIAccess
 modules/webmidi/MIDIInput
 modules/webmidi/MIDIPort
diff --git a/Source/core/dom/ExceptionBase.cpp b/Source/core/dom/ExceptionBase.cpp
deleted file mode 100644
index 9276fd7..0000000
--- a/Source/core/dom/ExceptionBase.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/ExceptionBase.h"
-#include "core/dom/ExceptionCode.h"
-
-#include <wtf/text/WTFString.h>
-
-namespace WebCore {
-
-ExceptionBase::ExceptionBase(const ExceptionCodeDescription& description)
-    : m_code(description.code)
-    , m_description(description.description)
-{
-    if (description.name)
-        m_name = description.name;
-    else
-        m_name = description.typeName;
-}
-
-String ExceptionBase::toString() const
-{
-    return m_name + ": " + message();
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/ExceptionCode.h b/Source/core/dom/ExceptionCode.h
index 84b520e..cf6dc69 100644
--- a/Source/core/dom/ExceptionCode.h
+++ b/Source/core/dom/ExceptionCode.h
@@ -19,9 +19,6 @@
 #ifndef ExceptionCode_h
 #define ExceptionCode_h
 
-// FIXME: Move this header into the files that actually need it.
-#include "DOMException.h"
-
 namespace WebCore {
 
     // The DOM standards use unsigned short for exception codes.
@@ -34,40 +31,76 @@
     // Some of these are considered historical since they have been
     // changed or removed from the specifications.
     enum {
+        // FIXME: Rename these to use CamelCase matching the exception name.
         INDEX_SIZE_ERR = 1,
-        HIERARCHY_REQUEST_ERR = 3,
-        WRONG_DOCUMENT_ERR = 4,
-        INVALID_CHARACTER_ERR = 5,
-        NO_MODIFICATION_ALLOWED_ERR = 7,
-        NOT_FOUND_ERR = 8,
-        NOT_SUPPORTED_ERR = 9,
-        INUSE_ATTRIBUTE_ERR = 10, // Historical. Only used in setAttributeNode etc which have been removed from the DOM specs.
+        HIERARCHY_REQUEST_ERR,
+        WRONG_DOCUMENT_ERR,
+        INVALID_CHARACTER_ERR,
+        NO_MODIFICATION_ALLOWED_ERR,
+        NOT_FOUND_ERR,
+        NOT_SUPPORTED_ERR,
+        INUSE_ATTRIBUTE_ERR, // Historical. Only used in setAttributeNode etc which have been removed from the DOM specs.
 
         // Introduced in DOM Level 2:
-        INVALID_STATE_ERR = 11,
-        SYNTAX_ERR = 12,
-        INVALID_MODIFICATION_ERR = 13,
-        NAMESPACE_ERR = 14,
-        INVALID_ACCESS_ERR = 15,
+        INVALID_STATE_ERR,
+        SYNTAX_ERR,
+        INVALID_MODIFICATION_ERR,
+        NAMESPACE_ERR,
+        INVALID_ACCESS_ERR,
 
         // Introduced in DOM Level 3:
-        TYPE_MISMATCH_ERR = 17, // Historical; use TypeError instead
+        TYPE_MISMATCH_ERR, // Historical; use TypeError instead
 
         // XMLHttpRequest extension:
-        SECURITY_ERR = 18,
+        SECURITY_ERR,
 
         // Others introduced in HTML5:
-        NETWORK_ERR = 19,
-        ABORT_ERR = 20,
-        URL_MISMATCH_ERR = 21,
-        QUOTA_EXCEEDED_ERR = 22,
-        TIMEOUT_ERR = 23,
-        INVALID_NODE_TYPE_ERR = 24,
-        DATA_CLONE_ERR = 25,
+        NETWORK_ERR,
+        ABORT_ERR,
+        URL_MISMATCH_ERR,
+        QUOTA_EXCEEDED_ERR,
+        TIMEOUT_ERR,
+        INVALID_NODE_TYPE_ERR,
+        DATA_CLONE_ERR,
+
+        // These are IDB-specific.
+        IDBNotFoundError,
+        UnknownError,
+        ConstraintError,
+        DataError,
+        TransactionInactiveError,
+        ReadOnlyError,
+        VersionError,
+
+        // File system
+        // FIXME: Consolidate these once https://crbug.com/252233 is fixed.
+        FSNotFoundError,
+        FSSecurityError,
+        FSAbortError,
+        FSNotReadableError,
+        FSEncodingError,
+        FSNoModificationAllowedError,
+        FSInvalidStateError,
+        FSSyntaxError,
+        FSInvalidModificationError,
+        FSQuotaExceededError,
+        FSTypeMismatchError,
+        FSPathExistsError,
+
+        // SQL
+        // FIXME: Consolidate these once https://crbug.com/252233 is fixed.
+        SQLUnknownError,
+        SQLDatabaseError,
+        SQLVersionError,
+        SQLTooLargeError,
+        SQLQuotaExceededError,
+        SQLSyntaxError,
+        SQLConstraintError,
+        SQLTimeoutError,
 
         // WebIDL exception types, handled by the binding layer.
         // FIXME: Add GeneralError, EvalError, etc. when implemented in the bindings.
-        TypeError = 105,
+        TypeError,
     };
 
 } // namespace WebCore
diff --git a/Source/core/dom/FullscreenController.cpp b/Source/core/dom/FullscreenController.cpp
index b01d12b..ed63fee 100644
--- a/Source/core/dom/FullscreenController.cpp
+++ b/Source/core/dom/FullscreenController.cpp
@@ -98,17 +98,9 @@
     return false;
 }
 
-bool FullscreenController::isAnimatingFullScreen(Document* document)
-{
-    if (FullscreenController* found = fromIfExists(document))
-        return found->isAnimatingFullScreen();
-    return false;
-}
-
 FullscreenController::FullscreenController(Document* document)
     : DocumentLifecycleObserver(document)
     , m_areKeysEnabledInFullScreen(false)
-    , m_isAnimatingFullScreen(false)
     , m_fullScreenRenderer(0)
     , m_fullScreenChangeDelayTimer(this, &FullscreenController::fullScreenChangeDelayTimerFired)
 {
@@ -539,18 +531,6 @@
         fullScreenElementRemoved();
 }
 
-void FullscreenController::setAnimatingFullScreen(bool flag)
-{
-    if (m_isAnimatingFullScreen == flag)
-        return;
-    m_isAnimatingFullScreen = flag;
-
-    if (m_fullScreenElement && m_fullScreenElement->isDescendantOf(document())) {
-        m_fullScreenElement->setNeedsStyleRecalc();
-        document()->scheduleForcedStyleRecalc();
-    }
-}
-
 void FullscreenController::clearFullscreenElementStack()
 {
     m_fullScreenElementStack.clear();
diff --git a/Source/core/dom/FullscreenController.h b/Source/core/dom/FullscreenController.h
index b32a96b..9fbfe3d 100644
--- a/Source/core/dom/FullscreenController.h
+++ b/Source/core/dom/FullscreenController.h
@@ -57,7 +57,6 @@
     static Element* fullscreenElementFrom(Document*);
     static Element* currentFullScreenElementFrom(Document*);
     static bool isFullScreen(Document*);
-    static bool isAnimatingFullScreen(Document*);
     static bool isActiveFullScreenElement(const Element*);
 
     enum FullScreenCheckType {
@@ -85,8 +84,6 @@
     bool fullScreenIsAllowedForElement(Element*) const;
     void fullScreenElementRemoved();
     void removeFullScreenElementOfSubtree(Node*, bool amongChildrenOnly = false);
-    bool isAnimatingFullScreen() const { return m_isAnimatingFullScreen; }
-    void setAnimatingFullScreen(bool);
 
     // W3C API
     static bool webkitFullscreenEnabled(Document*);
@@ -109,7 +106,6 @@
     void fullScreenChangeDelayTimerFired(Timer<FullscreenController>*);
 
     bool m_areKeysEnabledInFullScreen;
-    bool m_isAnimatingFullScreen;
     RefPtr<Element> m_fullScreenElement;
     Vector<RefPtr<Element> > m_fullScreenElementStack;
     RenderFullScreen* m_fullScreenRenderer;
diff --git a/Source/core/dom/GestureEvent.h b/Source/core/dom/GestureEvent.h
index f0809b8..a0d6f2e 100644
--- a/Source/core/dom/GestureEvent.h
+++ b/Source/core/dom/GestureEvent.h
@@ -27,11 +27,7 @@
 #define GestureEvent_h
 
 #include "core/dom/EventDispatcher.h"
-#include "core/dom/EventNames.h"
 #include "core/dom/MouseRelatedEvent.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/PlatformEvent.h"
 #include "core/platform/PlatformGestureEvent.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/KeyboardEvent.cpp b/Source/core/dom/KeyboardEvent.cpp
index 25e42d4..5354fc0 100644
--- a/Source/core/dom/KeyboardEvent.cpp
+++ b/Source/core/dom/KeyboardEvent.cpp
@@ -212,9 +212,10 @@
 
 KeyboardEvent* findKeyboardEvent(Event* event)
 {
-    for (Event* e = event; e; e = e->underlyingEvent())
+    for (Event* e = event; e; e = e->underlyingEvent()) {
         if (e->isKeyboardEvent())
-            return static_cast<KeyboardEvent*>(e);
+            return toKeyboardEvent(e);
+    }
     return 0;
 }
 
diff --git a/Source/core/dom/KeyboardEvent.h b/Source/core/dom/KeyboardEvent.h
index 1900174..acb0d32 100644
--- a/Source/core/dom/KeyboardEvent.h
+++ b/Source/core/dom/KeyboardEvent.h
@@ -26,7 +26,6 @@
 
 #include "core/dom/EventDispatchMediator.h"
 #include "core/dom/UIEventWithKeyState.h"
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
@@ -123,6 +122,12 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
+inline KeyboardEvent* toKeyboardEvent(Event* event)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isKeyboardEvent());
+    return static_cast<KeyboardEvent*>(event);
+}
+
 } // namespace WebCore
 
 #endif // KeyboardEvent_h
diff --git a/Source/core/dom/MessageChannel.idl b/Source/core/dom/MessageChannel.idl
index ca0e39f..c380c44 100644
--- a/Source/core/dom/MessageChannel.idl
+++ b/Source/core/dom/MessageChannel.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     Constructor,
     ConstructorCallWith=ScriptExecutionContext,
     CustomConstructor
diff --git a/Source/core/dom/MessageEvent.idl b/Source/core/dom/MessageEvent.idl
index 540b17d..7b5fec3 100644
--- a/Source/core/dom/MessageEvent.idl
+++ b/Source/core/dom/MessageEvent.idl
@@ -26,7 +26,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=Event
 ] interface MessageEvent : Event {
     [InitializedByEventConstructor] readonly attribute DOMString origin;
diff --git a/Source/core/dom/MessagePort.cpp b/Source/core/dom/MessagePort.cpp
index dec07cf..37181e2 100644
--- a/Source/core/dom/MessagePort.cpp
+++ b/Source/core/dom/MessagePort.cpp
@@ -27,15 +27,13 @@
 #include "config.h"
 #include "core/dom/MessagePort.h"
 
-#include <wtf/text/AtomicString.h>
 #include "core/dom/Document.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/MessageEvent.h"
 #include "core/page/DOMWindow.h"
-#include "core/platform/Timer.h"
-#include "core/workers/WorkerContext.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/workers/WorkerGlobalScope.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -164,7 +162,7 @@
     while (m_entangledChannel && m_entangledChannel->tryGetMessageFromRemote(message, channels)) {
 
         // close() in Worker onmessage handler should prevent next message from dispatching.
-        if (m_scriptExecutionContext->isWorkerContext() && static_cast<WorkerContext*>(m_scriptExecutionContext)->isClosing())
+        if (m_scriptExecutionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_scriptExecutionContext)->isClosing())
             return;
 
         OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_scriptExecutionContext, channels.release());
diff --git a/Source/core/dom/MessagePortChannel.h b/Source/core/dom/MessagePortChannel.h
index c11c363..5c78a31 100644
--- a/Source/core/dom/MessagePortChannel.h
+++ b/Source/core/dom/MessagePortChannel.h
@@ -32,13 +32,9 @@
 #define MessagePortChannel_h
 
 #include "bindings/v8/SerializedScriptValue.h"
-#include <wtf/Forward.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Microtask.cpp b/Source/core/dom/Microtask.cpp
new file mode 100644
index 0000000..cb0b12b
--- /dev/null
+++ b/Source/core/dom/Microtask.cpp
@@ -0,0 +1,56 @@
+/*
+ * 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/Microtask.h"
+
+#include "core/dom/CustomElementCallbackDispatcher.h"
+#include "core/dom/MutationObserver.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+void Microtask::performCheckpoint()
+{
+    static bool performingCheckpoint = false;
+    if (performingCheckpoint)
+        return;
+    performingCheckpoint = true;
+
+    bool anyWorkDone;
+    do {
+        MutationObserver::deliverAllMutations();
+        anyWorkDone = CustomElementCallbackDispatcher::instance().dispatch();
+    } while (anyWorkDone);
+
+    performingCheckpoint = false;
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/Microtask.h b/Source/core/dom/Microtask.h
new file mode 100644
index 0000000..27f72cb
--- /dev/null
+++ b/Source/core/dom/Microtask.h
@@ -0,0 +1,46 @@
+/*
+ * 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 Microtask_h
+#define Microtask_h
+
+namespace WebCore {
+
+class Microtask {
+public:
+    static void performCheckpoint();
+
+private:
+    explicit Microtask();
+};
+
+}
+
+#endif // Microtask_h
diff --git a/Source/core/dom/MouseEvent.cpp b/Source/core/dom/MouseEvent.cpp
index c1a8f6c..c0a6cbe 100644
--- a/Source/core/dom/MouseEvent.cpp
+++ b/Source/core/dom/MouseEvent.cpp
@@ -204,36 +204,6 @@
     return target() ? target()->toNode() : 0;
 }
 
-// FIXME: Fix positioning. e.g. We need to consider border/padding.
-// https://bugs.webkit.org/show_bug.cgi?id=93696
-inline static int adjustedClientX(int innerClientX, HTMLIFrameElement* iframe, FrameView* frameView)
-{
-    return iframe->offsetLeft() - frameView->scrollX() + innerClientX;
-}
-
-inline static int adjustedClientY(int innerClientY, HTMLIFrameElement* iframe, FrameView* frameView)
-{
-    return iframe->offsetTop() - frameView->scrollY() + innerClientY;
-}
-
-PassRefPtr<Event> MouseEvent::cloneFor(HTMLIFrameElement* iframe) const
-{
-    ASSERT(iframe);
-    RefPtr<MouseEvent> clonedMouseEvent = MouseEvent::create();
-    Frame* frame = iframe->document()->frame();
-    FrameView* frameView = frame ? frame->view() : 0;
-    clonedMouseEvent->initMouseEvent(type(), bubbles(), cancelable(),
-            iframe->document()->defaultView(),
-            detail(), screenX(), screenY(),
-            frameView ? adjustedClientX(clientX(), iframe, frameView) : 0,
-            frameView ? adjustedClientY(clientY(), iframe, frameView) : 0,
-            ctrlKey(), altKey(), shiftKey(), metaKey(),
-            button(),
-            // Nullifies relatedTarget.
-            0);
-    return clonedMouseEvent.release();
-}
-
 PassRefPtr<SimulatedMouseEvent> SimulatedMouseEvent::create(const AtomicString& eventType, PassRefPtr<AbstractView> view, PassRefPtr<Event> underlyingEvent)
 {
     return adoptRef(new SimulatedMouseEvent(eventType, view, underlyingEvent));
@@ -257,7 +227,7 @@
     setUnderlyingEvent(underlyingEvent);
 
     if (this->underlyingEvent() && this->underlyingEvent()->isMouseEvent()) {
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(this->underlyingEvent());
+        MouseEvent* mouseEvent = toMouseEvent(this->underlyingEvent());
         m_screenLocation = mouseEvent->screenLocation();
         initCoordinates(mouseEvent->clientLocation());
     }
@@ -275,7 +245,7 @@
 
 MouseEvent* MouseEventDispatchMediator::event() const
 {
-    return static_cast<MouseEvent*>(EventDispatchMediator::event());
+    return toMouseEvent(EventDispatchMediator::event());
 }
 
 bool MouseEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
diff --git a/Source/core/dom/MouseEvent.h b/Source/core/dom/MouseEvent.h
index d91daff..5ef39b0 100644
--- a/Source/core/dom/MouseEvent.h
+++ b/Source/core/dom/MouseEvent.h
@@ -98,8 +98,6 @@
     virtual bool isDragEvent() const;
     virtual int which() const;
 
-    virtual PassRefPtr<Event> cloneFor(HTMLIFrameElement*) const OVERRIDE;
-
 protected:
     MouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
         int detail, int screenX, int screenY, int pageX, int pageY,
@@ -143,7 +141,7 @@
 
 inline MouseEvent* toMouseEvent(Event* event)
 {
-    ASSERT(event && event->isMouseEvent());
+    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isMouseEvent());
     return static_cast<MouseEvent*>(event);
 }
 
diff --git a/Source/core/dom/MutationObserver.h b/Source/core/dom/MutationObserver.h
index 643a4e9..eb0da18 100644
--- a/Source/core/dom/MutationObserver.h
+++ b/Source/core/dom/MutationObserver.h
@@ -32,13 +32,10 @@
 #define MutationObserver_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/MutationRecord.cpp b/Source/core/dom/MutationRecord.cpp
index cc3b05a..5d86f3e 100644
--- a/Source/core/dom/MutationRecord.cpp
+++ b/Source/core/dom/MutationRecord.cpp
@@ -36,8 +36,7 @@
 #include "core/dom/NodeList.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/StaticNodeList.h"
-#include <wtf/Assertions.h>
-#include <wtf/StdLibExtras.h>
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/MutationRecord.h b/Source/core/dom/MutationRecord.h
index c5001c2..2c9812e 100644
--- a/Source/core/dom/MutationRecord.h
+++ b/Source/core/dom/MutationRecord.h
@@ -34,7 +34,6 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/NamedFlow.cpp b/Source/core/dom/NamedFlow.cpp
index 6f6d936..00519a1 100644
--- a/Source/core/dom/NamedFlow.cpp
+++ b/Source/core/dom/NamedFlow.cpp
@@ -33,7 +33,6 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/NamedFlowCollection.h"
-#include "core/dom/ScriptExecutionContext.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/dom/UIEvent.h"
 #include "core/rendering/RenderNamedFlowThread.h"
@@ -104,7 +103,7 @@
     RenderRegionList::const_iterator iter = regionList.begin();
     for (int index = 0; iter != regionList.end(); ++index, ++iter) {
         const RenderRegion* renderRegion = *iter;
-        if (renderRegion->regionState() == RenderRegion::RegionEmpty)
+        if (renderRegion->regionOversetState() == RegionEmpty)
             return index;
     }
     return -1;
@@ -218,6 +217,19 @@
     dispatchEvent(event);
 }
 
+void NamedFlow::dispatchRegionOversetChangeEvent()
+{
+    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+
+    // If the flow is in the "NULL" state the event should not be dispatched any more.
+    if (flowState() == FlowStateNull)
+        return;
+
+    RefPtr<Event> event = UIEvent::create(eventNames().webkitregionoversetchangeEvent, false, false, m_flowManager->document()->defaultView(), 0);
+
+    dispatchEvent(event);
+}
+
 const AtomicString& NamedFlow::interfaceName() const
 {
     return eventNames().interfaceForNamedFlow;
diff --git a/Source/core/dom/NamedFlow.h b/Source/core/dom/NamedFlow.h
index 060a3ff..13306cc 100644
--- a/Source/core/dom/NamedFlow.h
+++ b/Source/core/dom/NamedFlow.h
@@ -32,7 +32,6 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/EventTarget.h"
-#include "wtf/ListHashSet.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 #include "wtf/text/AtomicString.h"
@@ -79,6 +78,7 @@
     FlowState flowState() const { return m_parentFlowThread ? FlowStateCreated : FlowStateNull; }
 
     void dispatchRegionLayoutUpdateEvent();
+    void dispatchRegionOversetChangeEvent();
 
 private:
     NamedFlow(PassRefPtr<NamedFlowCollection>, const AtomicString&);
diff --git a/Source/core/dom/NamedFlowCollection.cpp b/Source/core/dom/NamedFlowCollection.cpp
index ea88831..8672d6d 100644
--- a/Source/core/dom/NamedFlowCollection.cpp
+++ b/Source/core/dom/NamedFlowCollection.cpp
@@ -42,7 +42,7 @@
 namespace WebCore {
 
 NamedFlowCollection::NamedFlowCollection(Document* document)
-    : ContextDestructionObserver(document)
+    : ContextLifecycleObserver(document)
 {
     ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
 }
@@ -104,7 +104,7 @@
 
 Document* NamedFlowCollection::document() const
 {
-    ScriptExecutionContext* context = ContextDestructionObserver::scriptExecutionContext();
+    ScriptExecutionContext* context = ContextLifecycleObserver::scriptExecutionContext();
     return toDocument(context);
 }
 
diff --git a/Source/core/dom/NamedFlowCollection.h b/Source/core/dom/NamedFlowCollection.h
index ef163b8..47107e0 100644
--- a/Source/core/dom/NamedFlowCollection.h
+++ b/Source/core/dom/NamedFlowCollection.h
@@ -30,7 +30,7 @@
 #ifndef NamedFlowCollection_h
 #define NamedFlowCollection_h
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/NamedFlow.h"
 #include <wtf/Forward.h>
 #include <wtf/ListHashSet.h>
@@ -43,7 +43,7 @@
 class Document;
 class DOMNamedFlowCollection;
 
-class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public ContextDestructionObserver {
+class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public ContextLifecycleObserver {
 public:
     static PassRefPtr<NamedFlowCollection> create(Document* doc) { return adoptRef(new NamedFlowCollection(doc)); }
 
diff --git a/Source/core/dom/NamedNodeMap.cpp b/Source/core/dom/NamedNodeMap.cpp
index 5e054e7..05f194f 100644
--- a/Source/core/dom/NamedNodeMap.cpp
+++ b/Source/core/dom/NamedNodeMap.cpp
@@ -92,7 +92,7 @@
         return 0;
     }
 
-    return m_element->setAttributeNode(static_cast<Attr*>(node), ec);
+    return m_element->setAttributeNode(toAttr(node), ec);
 }
 
 PassRefPtr<Node> NamedNodeMap::setNamedItemNS(Node* node, ExceptionCode& ec)
diff --git a/Source/core/dom/NamedNodesCollection.cpp b/Source/core/dom/NamedNodesCollection.cpp
index 51fac3c..9112f03 100644
--- a/Source/core/dom/NamedNodesCollection.cpp
+++ b/Source/core/dom/NamedNodesCollection.cpp
@@ -31,7 +31,6 @@
 #include "core/dom/NamedNodesCollection.h"
 
 #include "core/dom/Element.h"
-#include "core/dom/NamedNodeMap.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 730d4eb..3f107e9 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -28,19 +28,12 @@
 #include "HTMLNames.h"
 #include "XMLNames.h"
 #include "core/accessibility/AXObjectCache.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSRule.h"
-#include "core/css/CSSSelector.h"
-#include "core/css/CSSSelectorList.h"
-#include "core/css/CSSStyleRule.h"
-#include "core/css/CSSStyleSheet.h"
 #include "core/dom/Attr.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/BeforeLoadEvent.h"
 #include "core/dom/ChildListMutationScope.h"
 #include "core/dom/ChildNodeList.h"
 #include "core/dom/ClassNodeList.h"
-#include "core/dom/ContainerNodeAlgorithms.h"
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
@@ -48,7 +41,6 @@
 #include "core/dom/Element.h"
 #include "core/dom/ElementRareData.h"
 #include "core/dom/Event.h"
-#include "core/dom/EventContext.h"
 #include "core/dom/EventDispatchMediator.h"
 #include "core/dom/EventDispatcher.h"
 #include "core/dom/EventListener.h"
@@ -62,16 +54,11 @@
 #include "core/dom/MouseEvent.h"
 #include "core/dom/MutationEvent.h"
 #include "core/dom/NameNodeList.h"
-#include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRareData.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/ProcessingInstruction.h"
-#include "core/dom/ProgressEvent.h"
-#include "core/dom/RegisteredEventListener.h"
-#include "core/dom/ScopedEventQueue.h"
 #include "core/dom/SelectorQuery.h"
-#include "core/dom/StaticNodeList.h"
 #include "core/dom/TagNodeList.h"
 #include "core/dom/TemplateContentDocumentFragment.h"
 #include "core/dom/Text.h"
@@ -79,40 +66,25 @@
 #include "core/dom/TouchEvent.h"
 #include "core/dom/TreeScopeAdopter.h"
 #include "core/dom/UIEvent.h"
-#include "core/dom/UIEventWithKeyState.h"
 #include "core/dom/UserActionElementSet.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/dom/WheelEvent.h"
-#include "core/dom/WindowEventContext.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/htmlediting.h"
-#include "core/html/DOMSettableTokenList.h"
-#include "core/html/HTMLElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLStyleElement.h"
-#include "core/html/LabelsNodeList.h"
 #include "core/html/RadioNodeList.h"
 #include "core/inspector/InspectorCounters.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
 #include "core/page/ContextMenuController.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
-#include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/Logging.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/platform/Partitions.h"
+#include "core/rendering/FlowThreadController.h"
 #include "core/rendering/RenderBox.h"
-#include "core/rendering/RenderTextControl.h"
-#include "core/rendering/RenderView.h"
-#include "core/storage/StorageEvent.h"
 #include "wtf/HashSet.h"
-#include "wtf/PartitionAlloc.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/UnusedParam.h"
@@ -120,10 +92,6 @@
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
 
-#ifndef NDEBUG
-#include "core/rendering/RenderLayer.h"
-#endif
-
 using namespace std;
 
 namespace WebCore {
@@ -131,11 +99,9 @@
 using namespace HTMLNames;
 
 #if ENABLE(PARTITION_ALLOC)
-static PartitionRoot root;
-
 void* Node::operator new(size_t size)
 {
-    return partitionAlloc(&root, size);
+    return partitionAlloc(Partitions::getObjectModelPartition(), size);
 }
 
 void Node::operator delete(void* ptr)
@@ -144,20 +110,6 @@
 }
 #endif // ENABLE(PARTITION_ALLOC)
 
-void Node::init()
-{
-#if ENABLE(PARTITION_ALLOC)
-    partitionAllocInit(&root);
-#endif
-}
-
-void Node::shutdown()
-{
-#if ENABLE(PARTITION_ALLOC)
-    partitionAllocShutdown(&root);
-#endif
-}
-
 bool Node::isSupported(const String& feature, const String& version)
 {
     return DOMImplementation::hasFeature(feature, version);
@@ -875,6 +827,12 @@
     if (!attached()) // changed compared to what?
         return;
 
+    // FIXME: Switch all callers to use setNeedsLayerUpdate and get rid of SyntheticStyleChange.
+    if (changeType == SyntheticStyleChange) {
+        setNeedsLayerUpdate();
+        return;
+    }
+
     StyleChangeType existingChangeType = styleChangeType();
     if (changeType > existingChangeType)
         setStyleChange(changeType);
@@ -883,6 +841,12 @@
         markAncestorsWithChildNeedsStyleRecalc();
 }
 
+void Node::setNeedsLayerUpdate()
+{
+    setFlag(NeedsLayerUpdate);
+    setNeedsStyleRecalc(InlineStyleChange);
+}
+
 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
 {
     // It's safe to synchronously attach here because we're in the middle of style recalc
@@ -912,7 +876,8 @@
 {
     if (!inDocument() || !supportsFocus())
         return false;
-
+    if (isElementNode() && toElement(this)->isInert())
+        return false;
     return rendererIsFocusable();
 }
 
@@ -931,6 +896,12 @@
     return this;
 }
 
+bool Node::shouldHaveFocusAppearance() const
+{
+    ASSERT(focused());
+    return true;
+}
+
 unsigned Node::nodeIndex() const
 {
     Node *_tempNode = previousSibling();
@@ -1035,8 +1006,10 @@
     // Return true if other is an ancestor of this, otherwise false
     if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
         return false;
-    if (other->isDocumentNode())
-        return document() == other && !isDocumentNode() && inDocument() && !isInShadowTree();
+    if (other->treeScope() != treeScope())
+        return false;
+    if (other->isTreeScope())
+        return !isTreeScope();
     for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
         if (n == other)
             return true;
@@ -1233,6 +1206,11 @@
     return parentOrShadowHostNode() ? parentOrShadowHostNode()->canStartSelection() : true;
 }
 
+bool Node::isRegisteredWithNamedFlow() const
+{
+    return document()->renderView()->flowThreadController()->isContentNodeRegisteredWithAnyNamedFlow(this);
+}
+
 Element* Node::shadowHost() const
 {
     if (ShadowRoot* root = containingShadowRoot())
@@ -1515,7 +1493,7 @@
         case DOCUMENT_FRAGMENT_NODE:
             return false;
         case ATTRIBUTE_NODE: {
-            const Attr* attr = static_cast<const Attr*>(this);
+            const Attr* attr = toAttr(this);
             if (attr->ownerElement())
                 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
             return false;
@@ -1537,7 +1515,7 @@
     
     switch (nodeType()) {
         case ELEMENT_NODE:
-            return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
+            return lookupNamespacePrefix(namespaceURI, toElement(this));
         case DOCUMENT_NODE:
             if (Element* de = toDocument(this)->documentElement())
                 return de->lookupPrefix(namespaceURI);
@@ -1570,7 +1548,7 @@
     
     switch (nodeType()) {
         case ELEMENT_NODE: {
-            const Element *elem = static_cast<const Element *>(this);
+            const Element *elem = toElement(this);
             
             if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
                 return elem->namespaceURI();
@@ -1753,8 +1731,8 @@
     if (otherNode == this)
         return DOCUMENT_POSITION_EQUIVALENT;
     
-    const Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<const Attr*>(this) : 0;
-    const Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<const Attr*>(otherNode) : 0;
+    const Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? toAttr(this) : 0;
+    const Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? toAttr(otherNode) : 0;
     
     const Node* start1 = attr1 ? attr1->ownerElement() : this;
     const Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
@@ -1910,11 +1888,10 @@
 
     if (hasClass()) {
         name.appendLiteral(" class=\'");
-        const StyledElement* styledElement = static_cast<const StyledElement*>(this);
-        for (size_t i = 0; i < styledElement->classNames().size(); ++i) {
+        for (size_t i = 0; i < toElement(this)->classNames().size(); ++i) {
             if (i > 0)
                 name.append(' ');
-            name.append(styledElement->classNames()[i]);
+            name.append(toElement(this)->classNames()[i]);
         }
         name.append('\'');
     }
@@ -2511,9 +2488,10 @@
         return;
     const AtomicString& eventType = event->type();
     if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
-        if (event->isKeyboardEvent())
+        if (event->isKeyboardEvent()) {
             if (Frame* frame = document()->frame())
-                frame->eventHandler()->defaultKeyboardEventHandler(static_cast<KeyboardEvent*>(event));
+                frame->eventHandler()->defaultKeyboardEventHandler(toKeyboardEvent(event));
+        }
     } else if (eventType == eventNames().clickEvent) {
         int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
         if (dispatchDOMActivateEvent(detail, event))
@@ -2528,7 +2506,7 @@
                 frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
 #if ENABLE(PAN_SCROLLING)
     } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+        MouseEvent* mouseEvent = toMouseEvent(event);
         if (mouseEvent->button() == MiddleButton) {
             if (enclosingLinkEventParentOrSelf())
                 return;
@@ -2560,6 +2538,10 @@
     }
 }
 
+void Node::willCallDefaultEventHandler(const Event&)
+{
+}
+
 bool Node::willRespondToMouseMoveEvents()
 {
     if (isDisabledFormControl(this))
@@ -2701,7 +2683,7 @@
 {
     size_t count = 0;
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
-        if (child->hasTagName(HTMLNames::styleTag) && static_cast<HTMLStyleElement*>(child)->isRegisteredAsScoped())
+        if (child->hasTagName(HTMLNames::styleTag) && toHTMLStyleElement(child)->isRegisteredAsScoped())
             count++;
     }
 
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 87c486b..6df001f 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -75,7 +75,6 @@
 class QualifiedName;
 class RadioNodeList;
 class RegisteredEventListener;
-class RenderArena;
 class RenderBox;
 class RenderBoxModelObject;
 class RenderObject;
@@ -88,14 +87,13 @@
 
 const int nodeStyleChangeShift = 15;
 
-// SyntheticStyleChange means that we need to go through the entire style change logic even though
-// no style property has actually changed. It is used to restructure the tree when, for instance,
-// RenderLayers are created or destroyed due to animation changes.
 enum StyleChangeType {
     NoStyleChange = 0,
     InlineStyleChange = 1 << nodeStyleChangeShift,
-    SyntheticStyleChange = 2 << nodeStyleChangeShift,
-    FullStyleChange = 3 << nodeStyleChangeShift,
+    FullStyleChange = 2 << nodeStyleChangeShift,
+
+    // FIXME: SyntheticStyleChange is deprecated, instead you should use setNeedsLayerUpdate().
+    SyntheticStyleChange = 3 << nodeStyleChangeShift,
 };
 
 class NodeRareDataBase {
@@ -156,8 +154,6 @@
         DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
     };
 
-    static void init();
-    static void shutdown();
 #if ENABLE(PARTITION_ALLOC)
     // All Nodes are placed in their own heap partition for security.
     // See http://crbug.com/246860 for detail.
@@ -273,6 +269,8 @@
     bool inNamedFlow() const { return getFlag(InNamedFlowFlag); }
     bool hasCustomStyleCallbacks() const { return getFlag(HasCustomStyleCallbacksFlag); }
 
+    bool isRegisteredWithNamedFlow() const;
+
     bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
     void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
 
@@ -376,7 +374,14 @@
     void clearChildNeedsStyleRecalc() { clearFlag(ChildNeedsStyleRecalcFlag); }
 
     void setNeedsStyleRecalc(StyleChangeType changeType = FullStyleChange);
-    void clearNeedsStyleRecalc() { m_nodeFlags &= ~StyleChangeMask; }
+    void clearNeedsStyleRecalc()
+    {
+        m_nodeFlags &= ~StyleChangeMask;
+        clearFlag(NeedsLayerUpdate);
+    }
+
+    void setNeedsLayerUpdate();
+    bool needsLayerUpdate() const { return getFlag(NeedsLayerUpdate); }
 
     void setIsLink(bool f) { setFlag(f, IsLinkFlag); }
     void setIsLink() { setFlag(IsLinkFlag); }
@@ -417,6 +422,8 @@
     virtual bool isKeyboardFocusable(KeyboardEvent*) const;
     virtual bool isMouseFocusable() const;
     virtual Node* focusDelegate();
+    // This is called only when the node is focused.
+    virtual bool shouldHaveFocusAppearance() const;
 
     enum UserSelectAllTreatment {
         UserSelectAllDoesNotAffectEditability,
@@ -670,6 +677,7 @@
 
     // Perform the default action for an event.
     virtual void defaultEventHandler(Event*);
+    virtual void willCallDefaultEventHandler(const Event&);
 
     using TreeShared<Node>::ref;
     using TreeShared<Node>::deref;
@@ -735,10 +743,12 @@
         IsInShadowTreeFlag = 1 << 26,
         IsCustomElement = 1 << 27,
 
+        NeedsLayerUpdate = 1 << 28,
+
         DefaultNodeFlags = IsParsingChildrenFinishedFlag
     };
 
-    // 4 bits remaining
+    // 3 bits remaining
 
     bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
     void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); } 
@@ -914,8 +924,11 @@
 
 inline void Node::lazyReattach(ShouldSetAttached shouldSetAttached)
 {
+    AttachContext context;
+    context.performingReattach = true;
+
     if (attached())
-        detach();
+        detach(context);
     lazyAttach(shouldSetAttached);
 }
 
diff --git a/Source/core/dom/NodeRareData.cpp b/Source/core/dom/NodeRareData.cpp
index 2aec8fa..e11eb42 100644
--- a/Source/core/dom/NodeRareData.cpp
+++ b/Source/core/dom/NodeRareData.cpp
@@ -32,9 +32,7 @@
 #include "core/dom/NodeRareData.h"
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MemoryInstrumentationHashMap.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/NodeRareData.h b/Source/core/dom/NodeRareData.h
index f20b19a..7da5008 100644
--- a/Source/core/dom/NodeRareData.h
+++ b/Source/core/dom/NodeRareData.h
@@ -22,21 +22,17 @@
 #ifndef NodeRareData_h
 #define NodeRareData_h
 
-#include "HTMLNames.h"
 #include "core/dom/ChildNodeList.h"
 #include "core/dom/LiveNodeList.h"
-#include "core/dom/MutationObserver.h"
 #include "core/dom/MutationObserverRegistration.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/TagNodeList.h"
-#include "core/html/DOMSettableTokenList.h"
-#include "core/html/track/TextTrack.h"
 #include "core/page/Page.h"
-#include <wtf/HashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/HashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index 856fc6f..8ea7f81 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -26,19 +26,12 @@
 #include "config.h"
 #include "core/dom/NodeRenderingContext.h"
 
-#include "HTMLNames.h"
 #include "SVGNames.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/FullscreenController.h"
 #include "core/dom/Node.h"
-#include "core/dom/PseudoElement.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/HTMLInputElement.h"
-#include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/RenderFullScreen.h"
@@ -46,12 +39,9 @@
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderView.h"
-#include "core/rendering/style/StyleInheritedData.h"
 
 namespace WebCore {
 
-using namespace HTMLNames;
-
 NodeRenderingContext::NodeRenderingContext(Node* node)
     : m_node(node)
     , m_parentFlowRenderer(0)
@@ -184,6 +174,7 @@
 {
     if (!m_renderingParent)
         return false;
+
     RenderObject* parentRenderer = this->parentRenderer();
     if (!parentRenderer)
         return false;
@@ -194,37 +185,41 @@
     return true;
 }
 
+// Check the specific case of elements that are children of regions but are flowed into a flow thread themselves.
+bool NodeRenderingContext::elementInsideRegionNeedsRenderer()
+{
+    Element* element = toElement(m_node);
+    bool elementInsideRegionNeedsRenderer = false;
+    RenderObject* parentRenderer = this->parentRenderer();
+    if ((parentRenderer && !parentRenderer->canHaveChildren() && parentRenderer->isRenderRegion())
+        || (!parentRenderer && element->parentElement() && element->parentElement()->isInsideRegion())) {
+
+        if (!m_style)
+            m_style = element->styleForRenderer();
+
+        elementInsideRegionNeedsRenderer = element->shouldMoveToFlowThread(m_style.get());
+
+        // Children of this element will only be allowed to be flowed into other flow-threads if display is NOT none.
+        if (element->rendererIsNeeded(*this))
+            element->setIsInsideRegion(true);
+    }
+
+    return elementInsideRegionNeedsRenderer;
+}
+
 void NodeRenderingContext::moveToFlowThreadIfNeeded()
 {
-    ASSERT(m_node->isElementNode());
-    ASSERT(m_style);
     if (!RuntimeEnabledFeatures::cssRegionsEnabled())
         return;
 
-    if (m_style->flowThread().isEmpty())
+    Element* element = toElement(m_node);
+
+    if (!element->shouldMoveToFlowThread(m_style.get()))
         return;
 
-    // As per http://dev.w3.org/csswg/css3-regions/#flow-into, pseudo-elements such as ::first-line, ::first-letter, ::before or ::after
-    // cannot be directly collected into a named flow.
-    if (m_node->isPseudoElement())
-        return;
-
-    // FIXME: Do not collect elements if they are in shadow tree.
-    if (m_node->isInShadowTree())
-        return;
-
-    if (m_node->isElementNode() && FullscreenController::isActiveFullScreenElement(toElement(m_node)))
-        return;
-
-    // Allow only svg root elements to be directly collected by a render flow thread.
-    if (m_node->isSVGElement()
-        && (!(m_node->hasTagName(SVGNames::svgTag) && m_node->parentNode() && !m_node->parentNode()->isSVGElement())))
-        return;
-
-    m_flowThread = m_style->flowThread();
     ASSERT(m_node->document()->renderView());
     FlowThreadController* flowThreadController = m_node->document()->renderView()->flowThreadController();
-    m_parentFlowRenderer = flowThreadController->ensureRenderFlowThreadWithName(m_flowThread);
+    m_parentFlowRenderer = flowThreadController->ensureRenderFlowThreadWithName(m_style->flowThread());
     flowThreadController->registerNamedFlowContentNode(m_node, m_parentFlowRenderer);
 }
 
@@ -244,9 +239,13 @@
 
     Element* element = toElement(m_node);
 
-    if (!shouldCreateRenderer())
+    element->setIsInsideRegion(false);
+
+    if (!shouldCreateRenderer() && !elementInsideRegionNeedsRenderer())
         return;
-    m_style = element->styleForRenderer();
+
+    if (!m_style)
+        m_style = element->styleForRenderer();
     ASSERT(m_style);
 
     moveToFlowThreadIfNeeded();
@@ -258,7 +257,7 @@
     RenderObject* nextRenderer = this->nextRenderer();
 
     Document* document = element->document();
-    RenderObject* newRenderer = element->createRenderer(document->renderArena(), m_style.get());
+    RenderObject* newRenderer = element->createRenderer(m_style.get());
     if (!newRenderer)
         return;
 
@@ -304,7 +303,7 @@
 
     if (!textNode->textRendererIsNeeded(*this))
         return;
-    RenderText* newRenderer = textNode->createTextRenderer(document->renderArena(), m_style.get());
+    RenderText* newRenderer = textNode->createTextRenderer(m_style.get());
     if (!newRenderer)
         return;
     if (!parentRenderer->isChildAllowed(newRenderer, m_style.get())) {
diff --git a/Source/core/dom/NodeRenderingContext.h b/Source/core/dom/NodeRenderingContext.h
index c0e0c9d..3bacbf4 100644
--- a/Source/core/dom/NodeRenderingContext.h
+++ b/Source/core/dom/NodeRenderingContext.h
@@ -28,9 +28,8 @@
 
 #include "core/dom/NodeRenderingTraversal.h"
 
-#include <wtf/Noncopyable.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -69,6 +68,7 @@
 private:
     bool shouldCreateRenderer() const;
     void moveToFlowThreadIfNeeded();
+    bool elementInsideRegionNeedsRenderer();
 
     Node* m_node;
     ContainerNode* m_renderingParent;
diff --git a/Source/core/dom/NodeRenderingTraversal.cpp b/Source/core/dom/NodeRenderingTraversal.cpp
index a04d763..482b8ad 100644
--- a/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/Source/core/dom/NodeRenderingTraversal.cpp
@@ -49,9 +49,8 @@
 
 ContainerNode* parent(const Node* node, ParentDetails* details)
 {
-    if (ShadowRoot* root = node->containingShadowRoot())
-        root->host()->ensureDistribution();
-
+    // FIXME(morrita): We should ensure shadow tree distribution to be valid here through ContentDistributor::ensureDistribution().
+    // Currently we rely on the caller side since doing it here is expensive.
     ComposedShadowTreeWalker walker(node, ComposedShadowTreeWalker::CrossUpperBoundary, ComposedShadowTreeWalker::CanStartFromShadowBoundary);
     ContainerNode* found = toContainerNode(walker.traverseParent(walker.get(), details));
     return details->outOfComposition() ? 0 : found;
diff --git a/Source/core/dom/ParentNode.idl b/Source/core/dom/ParentNode.idl
index fef5c3b..10b418e 100644
--- a/Source/core/dom/ParentNode.idl
+++ b/Source/core/dom/ParentNode.idl
@@ -7,6 +7,3 @@
     [PerWorldBindings] readonly attribute unsigned long childElementCount;
 };
 
-Document implements ParentNode;
-DocumentFragment implements ParentNode;
-Element implements ParentNode;
diff --git a/Source/core/dom/FragmentScriptingPermission.h b/Source/core/dom/ParserContentPolicy.h
similarity index 96%
rename from Source/core/dom/FragmentScriptingPermission.h
rename to Source/core/dom/ParserContentPolicy.h
index 21b3552..5d3ecd4 100644
--- a/Source/core/dom/FragmentScriptingPermission.h
+++ b/Source/core/dom/ParserContentPolicy.h
@@ -23,8 +23,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-// FIXME: Move this file to ParserContentPolicy.h.
-
 #ifndef ParserContentPolicy_h
 #define ParserContentPolicy_h
 
@@ -37,7 +35,7 @@
     AllowScriptingContentAndDoNotMarkAlreadyStarted,
 };
 
-static inline bool scriptingContentIsAllowed(ParserContentPolicy parserContentPolicy) 
+static inline bool scriptingContentIsAllowed(ParserContentPolicy parserContentPolicy)
 {
     return parserContentPolicy == AllowScriptingContent || parserContentPolicy == AllowScriptingContentAndDoNotMarkAlreadyStarted;
 }
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index 21f5080..627bfa1 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -35,15 +35,14 @@
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
-#include "RuntimeEnabledFeatures.h"
 #include "core/platform/Logging.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderText.h"
-#include <wtf/text/CString.h>
-#include <wtf/unicode/CharacterNames.h>
+#include "wtf/text/CString.h"
+#include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
 
@@ -843,7 +842,7 @@
 
 bool Position::nodeIsUserSelectNone(Node* node)
 {
-    return node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_NONE;
+    return node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_NONE && node->renderer()->style()->userModify() == READ_ONLY;
 }
 
 ContainerNode* Position::findParent(const Node* node)
diff --git a/Source/core/dom/Promise.h b/Source/core/dom/Promise.h
new file mode 100644
index 0000000..2c842aa
--- /dev/null
+++ b/Source/core/dom/Promise.h
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+// FIXME: This file should be deleted.
+#ifndef Promise_h
+#define Promise_h
+
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+// An empty class. This is here because a generated file use it.
+class Promise : public RefCounted<Promise> {
+};
+
+} // namespace WebCore
+
+
+#endif // Promise_h
diff --git a/Source/core/dom/Promise.idl b/Source/core/dom/Promise.idl
new file mode 100644
index 0000000..893b8ee
--- /dev/null
+++ b/Source/core/dom/Promise.idl
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+[
+   CustomConstructor(any init),
+   EnabledAtRuntime=promise
+] interface Promise {
+};
diff --git a/Source/core/dom/PromiseResolver.h b/Source/core/dom/PromiseResolver.h
new file mode 100644
index 0000000..664018a
--- /dev/null
+++ b/Source/core/dom/PromiseResolver.h
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+// FIXME: This file should be deleted.
+#ifndef PromiseResolver_h
+#define PromiseResolver_h
+
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+// An empty class. This is here because a generated file use it.
+class PromiseResolver : public RefCounted<PromiseResolver> {
+};
+
+} // namespace WebCore
+
+
+#endif // PromiseResolver_h
diff --git a/Source/core/dom/PromiseResolver.idl b/Source/core/dom/PromiseResolver.idl
new file mode 100644
index 0000000..f2c80b4
--- /dev/null
+++ b/Source/core/dom/PromiseResolver.idl
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+[
+   EnabledAtRuntime=promise
+] interface PromiseResolver {
+   [Custom] void fulfill(optional any value);
+   [Custom] void resolve(optional any value);
+   [Custom] void reject(optional any value);
+};
diff --git a/Source/core/dom/PseudoElement.h b/Source/core/dom/PseudoElement.h
index a5d7018..0575704 100644
--- a/Source/core/dom/PseudoElement.h
+++ b/Source/core/dom/PseudoElement.h
@@ -28,9 +28,8 @@
 #define PseudoElement_h
 
 #include "core/dom/Element.h"
-#include "core/dom/Event.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/Forward.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
@@ -46,6 +45,10 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
 
+    // As per http://dev.w3.org/csswg/css3-regions/#flow-into, pseudo-elements such as ::first-line, ::first-letter, ::before or ::after
+    // cannot be directly collected into a named flow.
+    virtual bool shouldMoveToFlowThread(RenderStyle*) const OVERRIDE { return false; }
+
     virtual bool canStartSelection() const OVERRIDE { return false; }
     virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
diff --git a/Source/core/dom/QualifiedName.cpp b/Source/core/dom/QualifiedName.cpp
index c7f59fb..6edcf87 100644
--- a/Source/core/dom/QualifiedName.cpp
+++ b/Source/core/dom/QualifiedName.cpp
@@ -72,7 +72,7 @@
     if (!gNameCache)
         gNameCache = new QNameSet;
     QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() };
-    QNameSet::AddResult addResult = gNameCache->add<QualifiedNameComponents, QNameComponentsTranslator>(components);
+    QNameSet::AddResult addResult = gNameCache->add<QNameComponentsTranslator>(components);
     m_impl = *addResult.iterator;
     if (!addResult.isNewEntry)
         m_impl->ref();
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index 7817efd..15a10d0 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -693,9 +693,13 @@
         return fragment;
     }
 
+    // Since mutation observers can modify the range during the process, the boundary points need to be saved.
+    RangeBoundaryPoint originalStart(m_start);
+    RangeBoundaryPoint originalEnd(m_end);
+
     // what is the highest node that partially selects the start / end of the range?
-    RefPtr<Node> partialStart = highestAncestorUnderCommonRoot(m_start.container(), commonRoot.get());
-    RefPtr<Node> partialEnd = highestAncestorUnderCommonRoot(m_end.container(), commonRoot.get());
+    RefPtr<Node> partialStart = highestAncestorUnderCommonRoot(originalStart.container(), commonRoot.get());
+    RefPtr<Node> partialEnd = highestAncestorUnderCommonRoot(originalEnd.container(), commonRoot.get());
 
     // Start and end containers are different.
     // There are three possibilities here:
@@ -718,22 +722,22 @@
     // after any DOM mutation event, at various stages below. See webkit bug 60350.
 
     RefPtr<Node> leftContents;
-    if (m_start.container() != commonRoot && commonRoot->contains(m_start.container())) {
-        leftContents = processContentsBetweenOffsets(action, 0, m_start.container(), m_start.offset(), lengthOfContentsInNode(m_start.container()), ec);
-        leftContents = processAncestorsAndTheirSiblings(action, m_start.container(), ProcessContentsForward, leftContents, commonRoot.get(), ec);
+    if (originalStart.container() != commonRoot && commonRoot->contains(originalStart.container())) {
+        leftContents = processContentsBetweenOffsets(action, 0, originalStart.container(), originalStart.offset(), lengthOfContentsInNode(originalStart.container()), ec);
+        leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), ec);
     }
 
     RefPtr<Node> rightContents;
-    if (m_end.container() != commonRoot && commonRoot->contains(m_end.container())) {
-        rightContents = processContentsBetweenOffsets(action, 0, m_end.container(), 0, m_end.offset(), ec);
-        rightContents = processAncestorsAndTheirSiblings(action, m_end.container(), ProcessContentsBackward, rightContents, commonRoot.get(), ec);
+    if (m_end.container() != commonRoot && commonRoot->contains(originalEnd.container())) {
+        rightContents = processContentsBetweenOffsets(action, 0, originalEnd.container(), 0, originalEnd.offset(), ec);
+        rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), ec);
     }
 
     // delete all children of commonRoot between the start and end container
-    RefPtr<Node> processStart = childOfCommonRootBeforeOffset(m_start.container(), m_start.offset(), commonRoot.get());
-    if (processStart && m_start.container() != commonRoot) // processStart contains nodes before m_start.
+    RefPtr<Node> processStart = childOfCommonRootBeforeOffset(originalStart.container(), originalStart.offset(), commonRoot.get());
+    if (processStart && originalStart.container() != commonRoot) // processStart contains nodes before m_start.
         processStart = processStart->nextSibling();
-    RefPtr<Node> processEnd = childOfCommonRootBeforeOffset(m_end.container(), m_end.offset(), commonRoot.get());
+    RefPtr<Node> processEnd = childOfCommonRootBeforeOffset(originalEnd.container(), originalEnd.offset(), commonRoot.get());
 
     // Collapse the range, making sure that the result is not within a node that was partially selected.
     if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) {
@@ -746,6 +750,9 @@
         m_end = m_start;
     }
 
+    originalStart.clear();
+    originalEnd.clear();
+
     // Now add leftContents, stuff in between, and rightContents to the fragment
     // (or just delete the stuff in between)
 
@@ -1062,7 +1069,7 @@
             int length = data.length();
             int start = (n == m_start.container()) ? min(max(0, m_start.offset()), length) : 0;
             int end = (n == m_end.container()) ? min(max(start, m_end.offset()), length) : length;
-            builder.append(data.characters() + start, end - start);
+            builder.append(data, start, end - start);
         }
     }
 
diff --git a/Source/core/dom/Range.h b/Source/core/dom/Range.h
index 0df40c2..dea17c6 100644
--- a/Source/core/dom/Range.h
+++ b/Source/core/dom/Range.h
@@ -27,13 +27,12 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
-#include "core/dom/FragmentScriptingPermission.h"
 #include "core/dom/RangeBoundaryPoint.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/IntRect.h"
-#include <wtf/Forward.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/RangeBoundaryPoint.h b/Source/core/dom/RangeBoundaryPoint.h
index e868452..77c025d 100644
--- a/Source/core/dom/RangeBoundaryPoint.h
+++ b/Source/core/dom/RangeBoundaryPoint.h
@@ -35,6 +35,8 @@
 public:
     explicit RangeBoundaryPoint(PassRefPtr<Node> container);
 
+    explicit RangeBoundaryPoint(const RangeBoundaryPoint&);
+
     const Position toPosition() const;
 
     Node* container() const;
@@ -56,7 +58,7 @@
 
 private:
     static const int invalidOffset = -1;
-    
+
     RefPtr<Node> m_containerNode;
     mutable int m_offsetInContainer;
     RefPtr<Node> m_childBeforeBoundary;
@@ -70,6 +72,13 @@
     ASSERT(m_containerNode);
 }
 
+inline RangeBoundaryPoint::RangeBoundaryPoint(const RangeBoundaryPoint& other)
+    : m_containerNode(other.container())
+    , m_offsetInContainer(other.offset())
+    , m_childBeforeBoundary(other.childBefore())
+{
+}
+
 inline Node* RangeBoundaryPoint::container() const
 {
     return m_containerNode.get();
diff --git a/Source/core/dom/RawDataDocumentParser.h b/Source/core/dom/RawDataDocumentParser.h
index 47d9952..b56a694 100644
--- a/Source/core/dom/RawDataDocumentParser.h
+++ b/Source/core/dom/RawDataDocumentParser.h
@@ -26,6 +26,7 @@
 #ifndef RawDataDocumentParser_h
 #define RawDataDocumentParser_h
 
+#include "core/dom/Document.h"
 #include "core/dom/DocumentParser.h"
 
 namespace WebCore {
@@ -44,10 +45,11 @@
     }
 
 private:
-    virtual void flush(DocumentWriter* writer)
+    virtual size_t flush() OVERRIDE
     {
         // Make sure appendBytes is called at least once.
-        appendBytes(writer, 0, 0);
+        appendBytes(0, 0);
+        return 0;
     }
 
     virtual void insert(const SegmentedString&)
diff --git a/Source/core/dom/ScriptElement.cpp b/Source/core/dom/ScriptElement.cpp
index d80a9c8..94018c1 100644
--- a/Source/core/dom/ScriptElement.cpp
+++ b/Source/core/dom/ScriptElement.cpp
@@ -36,7 +36,6 @@
 #include "core/dom/Text.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/CrossOriginAccessControl.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/loader/cache/CachedResourceRequest.h"
 #include "core/loader/cache/CachedScript.h"
@@ -65,7 +64,6 @@
     , m_willExecuteWhenDocumentFinishedParsing(false)
     , m_forceAsync(!parserInserted)
     , m_willExecuteInOrder(false)
-    , m_requestUsesAccessControl(false)
 {
     ASSERT(m_element);
     if (parserInserted && m_element->document()->scriptableDocumentParser() && !m_element->document()->isInDocumentWrite())
@@ -253,9 +251,8 @@
 
         String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
         if (!crossOriginMode.isNull()) {
-            m_requestUsesAccessControl = true;
             StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-            updateRequestForAccessControl(request.mutableResourceRequest(), m_element->document()->securityOrigin(), allowCredentials);
+            request.setPotentiallyCrossOriginEnabled(m_element->document()->securityOrigin(), allowCredentials);
         }
         request.setCharset(scriptCharset());
 
@@ -358,14 +355,8 @@
     ASSERT_UNUSED(resource, resource == m_cachedScript);
     if (!m_cachedScript)
         return;
-
-    String error;
-    if (m_requestUsesAccessControl
-        && !m_element->document()->securityOrigin()->canRequest(m_cachedScript->response().url())
-        && !m_cachedScript->passesAccessControlCheck(m_element->document()->securityOrigin(), error)) {
-
+    if (!m_element->document()->cachedResourceLoader()->canAccess(m_cachedScript.get())) {
         dispatchErrorEvent();
-        m_element->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Script from origin '" + SecurityOrigin::create(m_cachedScript->response().url())->toString() + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + error);
         return;
     }
 
@@ -400,31 +391,7 @@
 
 String ScriptElement::scriptContent() const
 {
-    StringBuilder content;
-    Text* firstTextNode = 0;
-    bool foundMultipleTextNodes = false;
-
-    for (Node* n = m_element->firstChild(); n; n = n->nextSibling()) {
-        if (!n->isTextNode())
-            continue;
-
-        Text* t = toText(n);
-        if (foundMultipleTextNodes)
-            content.append(t->data());
-        else if (firstTextNode) {
-            content.append(firstTextNode->data());
-            content.append(t->data());
-            foundMultipleTextNodes = true;
-        } else
-            firstTextNode = t;
-    }
-
-    if (firstTextNode && !foundMultipleTextNodes) {
-        firstTextNode->atomize();
-        return firstTextNode->data();
-    }
-
-    return content.toString();
+    return m_element->textFromChildren();
 }
 
 ScriptElement* toScriptElementIfPossible(Element* element)
diff --git a/Source/core/dom/ScriptElement.h b/Source/core/dom/ScriptElement.h
index 7f9869e..32a011d 100644
--- a/Source/core/dom/ScriptElement.h
+++ b/Source/core/dom/ScriptElement.h
@@ -103,7 +103,6 @@
     bool m_willExecuteWhenDocumentFinishedParsing : 1;
     bool m_forceAsync : 1;
     bool m_willExecuteInOrder : 1;
-    bool m_requestUsesAccessControl : 1;
     String m_characterEncoding;
     String m_fallbackCharacterEncoding;
 };
diff --git a/Source/core/dom/ScriptExecutionContext.cpp b/Source/core/dom/ScriptExecutionContext.cpp
index 2f621cd..f8d343e 100644
--- a/Source/core/dom/ScriptExecutionContext.cpp
+++ b/Source/core/dom/ScriptExecutionContext.cpp
@@ -28,6 +28,7 @@
 #include "config.h"
 #include "core/dom/ScriptExecutionContext.h"
 
+#include "core/dom/ContextLifecycleNotifier.h"
 #include "core/dom/ErrorEvent.h"
 #include "core/dom/EventTarget.h"
 #include "core/dom/MessagePort.h"
@@ -36,16 +37,17 @@
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/cache/CachedScript.h"
 #include "core/page/DOMTimer.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerThread.h"
 #include "modules/webdatabase/DatabaseContext.h"
-#include <wtf/MainThread.h>
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MainThread.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WTF {
 
-template<> struct SequenceMemoryInstrumentationTraits<WebCore::ContextDestructionObserver*> {
+template<> struct SequenceMemoryInstrumentationTraits<WebCore::ContextLifecycleObserver*> {
     template <typename I> static void reportMemoryUsage(I, I, MemoryClassInfo&) { }
 };
 
@@ -87,9 +89,7 @@
 }
 
 ScriptExecutionContext::ScriptExecutionContext()
-    : m_iteratingActiveDOMObjects(false)
-    , m_inDestructor(false)
-    , m_circularSequentialID(0)
+    : m_circularSequentialID(0)
     , m_inDispatchErrorEvent(false)
     , m_activeDOMObjectsAreSuspended(false)
     , m_reasonForSuspendingActiveDOMObjects(static_cast<ActiveDOMObject::ReasonForSuspension>(-1))
@@ -99,14 +99,6 @@
 
 ScriptExecutionContext::~ScriptExecutionContext()
 {
-    m_inDestructor = true;
-    for (HashSet<ContextDestructionObserver*>::iterator iter = m_destructionObservers.begin(); iter != m_destructionObservers.end(); iter = m_destructionObservers.begin()) {
-        ContextDestructionObserver* observer = *iter;
-        m_destructionObservers.remove(observer);
-        ASSERT(observer->scriptExecutionContext() == this);
-        observer->contextDestroyed();
-    }
-
     HashSet<MessagePort*>::iterator messagePortsEnd = m_messagePorts.end();
     for (HashSet<MessagePort*>::iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
         ASSERT((*iter)->scriptExecutionContext() == this);
@@ -141,7 +133,7 @@
 {
     ASSERT(port);
     ASSERT((isDocument() && isMainThread())
-        || (isWorkerContext() && static_cast<WorkerContext*>(this)->thread()->isCurrentThread()));
+        || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
 
     m_messagePorts.add(port);
 }
@@ -150,39 +142,33 @@
 {
     ASSERT(port);
     ASSERT((isDocument() && isMainThread())
-        || (isWorkerContext() && static_cast<WorkerContext*>(this)->thread()->isCurrentThread()));
+        || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
 
     m_messagePorts.remove(port);
 }
 
 bool ScriptExecutionContext::canSuspendActiveDOMObjects()
 {
-    // No protection against m_activeDOMObjects changing during iteration: canSuspend() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        if (!(*iter)->canSuspend()) {
-            m_iteratingActiveDOMObjects = false;
-            return false;
-        }
+    return lifecycleNotifier()->canSuspendActiveDOMObjects();
+}
+
+bool ScriptExecutionContext::hasPendingActivity()
+{
+    if (lifecycleNotifier()->hasPendingActivity())
+        return true;
+
+    HashSet<MessagePort*>::const_iterator messagePortsEnd = m_messagePorts.end();
+    for (HashSet<MessagePort*>::const_iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
+        if ((*iter)->hasPendingActivity())
+            return true;
     }
-    m_iteratingActiveDOMObjects = false;
-    return true;
+
+    return false;
 }
 
 void ScriptExecutionContext::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
 {
-    // No protection against m_activeDOMObjects changing during iteration: suspend() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        (*iter)->suspend(why);
-    }
-    m_iteratingActiveDOMObjects = false;
+    lifecycleNotifier()->notifySuspendingActiveDOMObjects(why);
     m_activeDOMObjectsAreSuspended = true;
     m_reasonForSuspendingActiveDOMObjects = why;
 }
@@ -190,70 +176,33 @@
 void ScriptExecutionContext::resumeActiveDOMObjects()
 {
     m_activeDOMObjectsAreSuspended = false;
-    // No protection against m_activeDOMObjects changing during iteration: resume() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        (*iter)->resume();
-    }
-    m_iteratingActiveDOMObjects = false;
+    lifecycleNotifier()->notifyResumingActiveDOMObjects();
 }
 
 void ScriptExecutionContext::stopActiveDOMObjects()
 {
     m_activeDOMObjectsAreStopped = true;
-    // No protection against m_activeDOMObjects changing during iteration: stop() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        (*iter)->stop();
-    }
-    m_iteratingActiveDOMObjects = false;
-
+    lifecycleNotifier()->notifyStoppingActiveDOMObjects();
     // Also close MessagePorts. If they were ActiveDOMObjects (they could be) then they could be stopped instead.
     closeMessagePorts();
 }
 
 void ScriptExecutionContext::suspendActiveDOMObjectIfNeeded(ActiveDOMObject* object)
 {
-    ASSERT(m_activeDOMObjects.contains(object));
+    ASSERT(lifecycleNotifier()->contains(object));
     // Ensure all ActiveDOMObjects are suspended also newly created ones.
     if (m_activeDOMObjectsAreSuspended)
         object->suspend(m_reasonForSuspendingActiveDOMObjects);
 }
 
-void ScriptExecutionContext::didCreateActiveDOMObject(ActiveDOMObject* object)
+void ScriptExecutionContext::wasObservedBy(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
 {
-    ASSERT(object);
-    ASSERT(!m_inDestructor);
-    if (m_iteratingActiveDOMObjects)
-        CRASH();
-    m_activeDOMObjects.add(object);
+    lifecycleNotifier()->addObserver(observer, as);
 }
 
-void ScriptExecutionContext::willDestroyActiveDOMObject(ActiveDOMObject* object)
+void ScriptExecutionContext::wasUnobservedBy(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
 {
-    ASSERT(object);
-    if (m_iteratingActiveDOMObjects)
-        CRASH();
-    m_activeDOMObjects.remove(object);
-}
-
-void ScriptExecutionContext::didCreateDestructionObserver(ContextDestructionObserver* observer)
-{
-    ASSERT(observer);
-    ASSERT(!m_inDestructor);
-    m_destructionObservers.add(observer);
-}
-
-void ScriptExecutionContext::willDestroyDestructionObserver(ContextDestructionObserver* observer)
-{
-    ASSERT(observer);
-    m_destructionObservers.remove(observer);
+    lifecycleNotifier()->removeObserver(observer, as);
 }
 
 void ScriptExecutionContext::closeMessagePorts() {
@@ -350,19 +299,27 @@
     return DOMTimer::visiblePageAlignmentInterval();
 }
 
+ContextLifecycleNotifier* ScriptExecutionContext::lifecycleNotifier()
+{
+    if (!m_lifecycleNotifier)
+        m_lifecycleNotifier = const_cast<ScriptExecutionContext*>(this)->createLifecycleNotifier();
+    return m_lifecycleNotifier.get();
+}
+
+PassOwnPtr<ContextLifecycleNotifier> ScriptExecutionContext::createLifecycleNotifier()
+{
+    return ContextLifecycleNotifier::create(this);
+}
+
 void ScriptExecutionContext::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
     SecurityContext::reportMemoryUsage(memoryObjectInfo);
     info.addMember(m_messagePorts, "messagePorts");
-    info.addMember(m_destructionObservers, "destructionObservers");
-    info.addMember(m_activeDOMObjects, "activeDOMObjects");
+    info.addMember(m_lifecycleNotifier, "lifecycleObserver");
     info.addMember(m_timeouts, "timeouts");
     info.addMember(m_pendingExceptions, "pendingExceptions");
     info.addMember(m_publicURLManager, "publicURLManager");
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter)
-        info.addMember(*iter, "activeDOMObject", WTF::RetainingPointer);
 }
 
 ScriptExecutionContext::Task::~Task()
@@ -371,7 +328,6 @@
 
 void ScriptExecutionContext::setDatabaseContext(DatabaseContext* databaseContext)
 {
-    ASSERT(!m_databaseContext);
     m_databaseContext = databaseContext;
 }
 
diff --git a/Source/core/dom/ScriptExecutionContext.h b/Source/core/dom/ScriptExecutionContext.h
index af5e831..ea1759a 100644
--- a/Source/core/dom/ScriptExecutionContext.h
+++ b/Source/core/dom/ScriptExecutionContext.h
@@ -38,6 +38,7 @@
 namespace WebCore {
 
 class CachedScript;
+class ContextLifecycleNotifier;
 class DatabaseContext;
 class DOMTimer;
 class EventListener;
@@ -54,7 +55,7 @@
     virtual ~ScriptExecutionContext();
 
     virtual bool isDocument() const { return false; }
-    virtual bool isWorkerContext() const { return false; }
+    virtual bool isWorkerGlobalScope() const { return false; }
 
     virtual bool isContextThread() const { return true; }
     virtual bool isJSExecutionForbidden() const = 0;
@@ -78,6 +79,8 @@
 
     // Active objects are not garbage collected even if inaccessible, e.g. because their activity may result in callbacks being invoked.
     bool canSuspendActiveDOMObjects();
+    bool hasPendingActivity();
+
     // Active objects can be asked to suspend even if canSuspendActiveDOMObjects() returns 'false' -
     // step-by-step JS debugging is one example.
     virtual void suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension);
@@ -87,18 +90,12 @@
     bool activeDOMObjectsAreSuspended() const { return m_activeDOMObjectsAreSuspended; }
     bool activeDOMObjectsAreStopped() const { return m_activeDOMObjectsAreStopped; }
 
-    // Called from the constructor and destructors of ActiveDOMObject.
-    void didCreateActiveDOMObject(ActiveDOMObject*);
-    void willDestroyActiveDOMObject(ActiveDOMObject*);
-
     // Called after the construction of an ActiveDOMObject to synchronize suspend state.
     void suspendActiveDOMObjectIfNeeded(ActiveDOMObject*);
 
-    typedef HashSet<ActiveDOMObject*> ActiveDOMObjectsSet;
-    const ActiveDOMObjectsSet& activeDOMObjects() const { return m_activeDOMObjects; }
-
-    void didCreateDestructionObserver(ContextDestructionObserver*);
-    void willDestroyDestructionObserver(ContextDestructionObserver*);
+    // Called from the constructor and destructors of ContextLifecycleObserver
+    void wasObservedBy(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
+    void wasUnobservedBy(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
 
     // MessagePort is conceptually a kind of ActiveDOMObject, but it needs to be tracked separately for message dispatch.
     void processMessagePortMessagesSoon();
@@ -159,6 +156,8 @@
         String m_message;
     };
 
+    ContextLifecycleNotifier* lifecycleNotifier();
+
 private:
     virtual const KURL& virtualURL() const = 0;
     virtual KURL virtualCompleteURL(const String&) const = 0;
@@ -172,12 +171,10 @@
 
     virtual void refScriptExecutionContext() = 0;
     virtual void derefScriptExecutionContext() = 0;
+    virtual PassOwnPtr<ContextLifecycleNotifier> createLifecycleNotifier();
 
+    OwnPtr<ContextLifecycleNotifier> m_lifecycleNotifier;
     HashSet<MessagePort*> m_messagePorts;
-    HashSet<ContextDestructionObserver*> m_destructionObservers;
-    ActiveDOMObjectsSet m_activeDOMObjects;
-    bool m_iteratingActiveDOMObjects;
-    bool m_inDestructor;
 
     int m_circularSequentialID;
     typedef HashMap<int, DOMTimer*> TimeoutMap;
diff --git a/Source/core/dom/ScriptRunner.h b/Source/core/dom/ScriptRunner.h
index c52bd89..1790764 100644
--- a/Source/core/dom/ScriptRunner.h
+++ b/Source/core/dom/ScriptRunner.h
@@ -28,11 +28,10 @@
 
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/Timer.h"
-#include <wtf/HashMap.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/HashMap.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ScriptableDocumentParser.h b/Source/core/dom/ScriptableDocumentParser.h
index 9a8581d..f8a95ad 100644
--- a/Source/core/dom/ScriptableDocumentParser.h
+++ b/Source/core/dom/ScriptableDocumentParser.h
@@ -27,7 +27,7 @@
 #define ScriptableDocumentParser_h
 
 #include "core/dom/DecodedDataDocumentParser.h"
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 #include <wtf/text/TextPosition.h>
 
 namespace WebCore {
diff --git a/Source/core/dom/ScriptedAnimationController.h b/Source/core/dom/ScriptedAnimationController.h
index 9737c89..4379b2a 100644
--- a/Source/core/dom/ScriptedAnimationController.h
+++ b/Source/core/dom/ScriptedAnimationController.h
@@ -26,10 +26,9 @@
 #ifndef ScriptedAnimationController_h
 #define ScriptedAnimationController_h
 
-#include "core/dom/DOMTimeStamp.h"
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/SecurityContext.cpp b/Source/core/dom/SecurityContext.cpp
index cfaeacd2..80fcaba 100644
--- a/Source/core/dom/SecurityContext.cpp
+++ b/Source/core/dom/SecurityContext.cpp
@@ -90,18 +90,17 @@
     // http://www.w3.org/TR/html5/the-iframe-element.html#attr-iframe-sandbox
     // Parse the unordered set of unique space-separated tokens.
     SandboxFlags flags = SandboxAll;
-    const UChar* characters = policy.characters();
     unsigned length = policy.length();
     unsigned start = 0;
     unsigned numberOfTokenErrors = 0;
     StringBuilder tokenErrors;
     while (true) {
-        while (start < length && isHTMLSpace(characters[start]))
+        while (start < length && isHTMLSpace(policy[start]))
             ++start;
         if (start >= length)
             break;
         unsigned end = start + 1;
-        while (end < length && !isHTMLSpace(characters[end]))
+        while (end < length && !isHTMLSpace(policy[end]))
             ++end;
 
         // Turn off the corresponding sandbox flag if it's set as "allowed".
diff --git a/Source/core/dom/SpaceSplitString.cpp b/Source/core/dom/SpaceSplitString.cpp
index 4af9a1c..29222d4 100644
--- a/Source/core/dom/SpaceSplitString.cpp
+++ b/Source/core/dom/SpaceSplitString.cpp
@@ -22,10 +22,9 @@
 #include "core/dom/SpaceSplitString.h"
 
 #include "core/html/parser/HTMLParserIdioms.h"
-#include <wtf/ASCIICType.h>
-#include <wtf/HashMap.h>
-#include <wtf/text/AtomicStringHash.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/ASCIICType.h"
+#include "wtf/HashMap.h"
+#include "wtf/text/AtomicStringHash.h"
 
 using namespace WTF;
 
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 7093671..83f797b 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -34,13 +34,6 @@
 
 namespace WebCore {
 
-static bool isValidStyleChild(Node* node)
-{
-    ASSERT(node);
-    Node::NodeType nodeType = node->nodeType();
-    return nodeType == Node::TEXT_NODE || nodeType == Node::CDATA_SECTION_NODE;
-}
-
 static bool isCSS(Element* element, const AtomicString& type)
 {
     return type.isEmpty() || (element->isHTMLElement() ? equalIgnoringCase(type, "text/css") : (type == "text/css"));
@@ -111,33 +104,11 @@
     m_createdByParser = false;
 }
 
-void StyleElement::process(Element* e)
+void StyleElement::process(Element* element)
 {
-    if (!e || !e->inDocument())
+    if (!element || !element->inDocument())
         return;
-
-    unsigned resultLength = 0;
-    for (Node* c = e->firstChild(); c; c = c->nextSibling()) {
-        if (isValidStyleChild(c)) {
-            unsigned length = c->nodeValue().length();
-            if (length > std::numeric_limits<unsigned>::max() - resultLength) {
-                createSheet(e, "");
-                return;
-            }
-            resultLength += length;
-        }
-    }
-    StringBuilder sheetText;
-    sheetText.reserveCapacity(resultLength);
-
-    for (Node* c = e->firstChild(); c; c = c->nextSibling()) {
-        if (isValidStyleChild(c)) {
-            sheetText.append(c->nodeValue());
-        }
-    }
-    ASSERT(sheetText.length() == resultLength);
-
-    createSheet(e, sheetText.toString());
+    createSheet(element, element->textFromChildren());
 }
 
 void StyleElement::clearSheet()
diff --git a/Source/core/dom/StyledElement.cpp b/Source/core/dom/StyledElement.cpp
deleted file mode 100644
index f6ecb91..0000000
--- a/Source/core/dom/StyledElement.cpp
+++ /dev/null
@@ -1,391 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- *           (C) 2001 Peter Kelly (pmk@post.com)
- *           (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/StyledElement.h"
-
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
-#include "HTMLNames.h"
-#include "core/css/CSSImageValue.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValuePool.h"
-#include "core/css/PropertySetCSSStyleDeclaration.h"
-#include "core/css/StylePropertySet.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Attribute.h"
-#include "core/dom/Document.h"
-#include "core/dom/ScriptableDocumentParser.h"
-#include "core/html/ClassList.h"
-#include "core/html/DOMTokenList.h"
-#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/platform/graphics/Color.h"
-#include <wtf/HashFunctions.h>
-#include <wtf/text/TextPosition.h>
-
-using namespace std;
-
-namespace WebCore {
-
-COMPILE_ASSERT(sizeof(StyledElement) == sizeof(Element), styledelement_should_remain_same_size_as_element);
-
-using namespace HTMLNames;
-
-struct PresentationAttributeCacheKey {
-    PresentationAttributeCacheKey() : tagName(0) { }
-    AtomicStringImpl* tagName;
-    // Only the values need refcounting.
-    Vector<pair<AtomicStringImpl*, AtomicString>, 3> attributesAndValues;
-};
-
-struct PresentationAttributeCacheEntry {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    PresentationAttributeCacheKey key;
-    RefPtr<StylePropertySet> value;
-};
-
-typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
-    
-static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
-{
-    if (a.tagName != b.tagName)
-        return true;
-    return a.attributesAndValues != b.attributesAndValues;
-}
-
-static PresentationAttributeCache& presentationAttributeCache()
-{
-    DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
-    return cache;
-}
-
-class PresentationAttributeCacheCleaner {
-    WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
-public:
-    PresentationAttributeCacheCleaner()
-        : m_hitCount(0)
-        , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
-    {
-    }
-
-    void didHitPresentationAttributeCache()
-    {
-        if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
-            return;
-
-        m_hitCount++;
-
-        if (!m_cleanTimer.isActive())
-            m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
-     }
-
-private:
-    static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
-    static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
-    static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
-
-    void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
-    {
-        ASSERT_UNUSED(timer, timer == &m_cleanTimer);
-        unsigned hitCount = m_hitCount;
-        m_hitCount = 0;
-        if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
-            return;
-        presentationAttributeCache().clear();
-    }
-
-    unsigned m_hitCount;
-    Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
-};
-
-static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
-{
-    DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
-    return cleaner;
-}
-
-void StyledElement::synchronizeStyleAttributeInternal() const
-{
-    ASSERT(elementData());
-    ASSERT(elementData()->m_styleAttributeIsDirty);
-    elementData()->m_styleAttributeIsDirty = false;
-    if (const StylePropertySet* inlineStyle = this->inlineStyle())
-        const_cast<StyledElement*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
-}
-
-StyledElement::~StyledElement()
-{
-    if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
-        cssomWrapper->clearParentElement();
-}
-
-CSSStyleDeclaration* StyledElement::style()
-{
-    return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
-}
-
-MutableStylePropertySet* StyledElement::ensureMutableInlineStyle()
-{
-    RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
-    if (!inlineStyle)
-        inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
-    else if (!inlineStyle->isMutable())
-        inlineStyle = inlineStyle->mutableCopy();
-    ASSERT(inlineStyle->isMutable());
-    return static_cast<MutableStylePropertySet*>(inlineStyle.get());
-}
-
-void StyledElement::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
-{
-    if (name == styleAttr)
-        styleAttributeChanged(newValue, reason);
-    else if (isPresentationAttribute(name)) {
-        elementData()->m_presentationAttributeStyleIsDirty = true;
-        setNeedsStyleRecalc(InlineStyleChange);
-    }
-
-    Element::attributeChanged(name, newValue, reason);
-}
-
-PropertySetCSSStyleDeclaration* StyledElement::inlineStyleCSSOMWrapper()
-{
-    if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
-        return 0;
-    PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
-    ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
-    return cssomWrapper;
-}
-
-inline void StyledElement::setInlineStyleFromString(const AtomicString& newStyleString)
-{
-    RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
-
-    // Avoid redundant work if we're using shared attribute data with already parsed inline style.
-    if (inlineStyle && !elementData()->isUnique())
-        return;
-
-    // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
-    // This makes wrapperless property sets immutable and so cacheable.
-    if (inlineStyle && !inlineStyle->isMutable())
-        inlineStyle.clear();
-
-    if (!inlineStyle)
-        inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
-    else {
-        ASSERT(inlineStyle->isMutable());
-        static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
-    }
-}
-
-void StyledElement::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
-{
-    WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
-    if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
-        startLineNumber = document()->scriptableDocumentParser()->lineNumber();
-
-    if (newStyleString.isNull()) {
-        if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
-            cssomWrapper->clearParentElement();
-        ensureUniqueElementData()->m_inlineStyle.clear();
-    } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber))
-        setInlineStyleFromString(newStyleString);
-
-    elementData()->m_styleAttributeIsDirty = false;
-
-    setNeedsStyleRecalc(InlineStyleChange);
-    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
-}
-
-void StyledElement::inlineStyleChanged()
-{
-    setNeedsStyleRecalc(InlineStyleChange);
-    ASSERT(elementData());
-    elementData()->m_styleAttributeIsDirty = true;
-    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
-}
-    
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
-{
-    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
-    inlineStyleChanged();
-    return true;
-}
-
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
-{
-    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
-    inlineStyleChanged();
-    return true;
-}
-
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
-{
-    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
-    inlineStyleChanged();
-    return true;
-}
-
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
-{
-    bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
-    if (changes)
-        inlineStyleChanged();
-    return changes;
-}
-
-bool StyledElement::removeInlineStyleProperty(CSSPropertyID propertyID)
-{
-    if (!inlineStyle())
-        return false;
-    bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
-    if (changes)
-        inlineStyleChanged();
-    return changes;
-}
-
-void StyledElement::removeAllInlineStyleProperties()
-{
-    if (!inlineStyle() || inlineStyle()->isEmpty())
-        return;
-    ensureMutableInlineStyle()->clear();
-    inlineStyleChanged();
-}
-
-void StyledElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
-        inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
-}
-
-static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
-{
-    // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same. 
-    return p1.first < p2.first;
-}
-
-void StyledElement::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
-{    
-    // FIXME: Enable for SVG.
-    if (namespaceURI() != xhtmlNamespaceURI)
-        return;
-    // Interpretation of the size attributes on <input> depends on the type attribute.
-    if (hasTagName(inputTag))
-        return;
-    unsigned size = attributeCount();
-    for (unsigned i = 0; i < size; ++i) {
-        const Attribute* attribute = attributeItem(i);
-        if (!isPresentationAttribute(attribute->name()))
-            continue;
-        if (!attribute->namespaceURI().isNull())
-            return;
-        // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
-        if (attribute->name() == backgroundAttr)
-            return;
-        result.attributesAndValues.append(make_pair(attribute->localName().impl(), attribute->value()));
-    }
-    if (result.attributesAndValues.isEmpty())
-        return;
-    // Attribute order doesn't matter. Sort for easy equality comparison.
-    std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
-    // The cache key is non-null when the tagName is set.
-    result.tagName = localName().impl();
-}
-
-static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
-{
-    if (!key.tagName)
-        return 0;
-    ASSERT(key.attributesAndValues.size());
-    unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
-    return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
-}
-
-void StyledElement::rebuildPresentationAttributeStyle()
-{
-    PresentationAttributeCacheKey cacheKey;
-    makePresentationAttributeCacheKey(cacheKey);
-
-    unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
-
-    PresentationAttributeCache::iterator cacheIterator;
-    if (cacheHash) {
-        cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
-        if (cacheIterator->value && cacheIterator->value->key != cacheKey)
-            cacheHash = 0;
-    } else
-        cacheIterator = presentationAttributeCache().end();
-
-    RefPtr<StylePropertySet> style;
-    if (cacheHash && cacheIterator->value) {
-        style = cacheIterator->value->value;
-        presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
-    } else {
-        style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
-        unsigned size = attributeCount();
-        for (unsigned i = 0; i < size; ++i) {
-            const Attribute* attribute = attributeItem(i);
-            collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
-        }
-    }
-
-    // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
-    UniqueElementData* elementData = ensureUniqueElementData();
-
-    elementData->m_presentationAttributeStyleIsDirty = false;
-    elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
-
-    if (!cacheHash || cacheIterator->value)
-        return;
-
-    OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
-    newEntry->key = cacheKey;
-    newEntry->value = style.release();
-
-    static const int presentationAttributeCacheMaximumSize = 4096;
-    if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
-        // Start building from scratch if the cache ever gets big.
-        presentationAttributeCache().clear();
-        presentationAttributeCache().set(cacheHash, newEntry.release());
-    } else
-        cacheIterator->value = newEntry.release();
-}
-
-void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
-{
-    style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
-}
-
-void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
-{
-    style->setProperty(propertyID, cssValuePool().createValue(value, unit));
-}
-    
-void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
-{
-    style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
-}
-
-}
diff --git a/Source/core/dom/StyledElement.h b/Source/core/dom/StyledElement.h
deleted file mode 100644
index a93efe2..0000000
--- a/Source/core/dom/StyledElement.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- *           (C) 2001 Peter Kelly (pmk@post.com)
- *           (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef StyledElement_h
-#define StyledElement_h
-
-#include "CSSPropertyNames.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/dom/Element.h"
-
-namespace WebCore {
-
-class Attribute;
-class MutableStylePropertySet;
-class PropertySetCSSStyleDeclaration;
-class StylePropertySet;
-
-struct PresentationAttributeCacheKey;
-
-class StyledElement : public Element {
-public:
-    virtual ~StyledElement();
-
-    virtual const StylePropertySet* additionalPresentationAttributeStyle() { return 0; }
-    void invalidateStyleAttribute();
-
-    const StylePropertySet* inlineStyle() const { return elementData() ? elementData()->m_inlineStyle.get() : 0; }
-    
-    bool setInlineStyleProperty(CSSPropertyID, CSSValueID identifier, bool important = false);
-    bool setInlineStyleProperty(CSSPropertyID, CSSPropertyID identifier, bool important = false);
-    bool setInlineStyleProperty(CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes, bool important = false);
-    bool setInlineStyleProperty(CSSPropertyID, const String& value, bool important = false);
-    bool removeInlineStyleProperty(CSSPropertyID);
-    void removeAllInlineStyleProperties();
-
-    void synchronizeStyleAttributeInternal() const;
-    
-    virtual CSSStyleDeclaration* style() OVERRIDE;
-
-    const StylePropertySet* presentationAttributeStyle();
-    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) { }
-
-protected:
-    StyledElement(const QualifiedName& name, Document* document, ConstructionType type)
-        : Element(name, document, type)
-    {
-    }
-
-    virtual void attributeChanged(const QualifiedName&, const AtomicString&, AttributeModificationReason = ModifiedDirectly) OVERRIDE;
-
-    virtual bool isPresentationAttribute(const QualifiedName&) const { return false; }
-
-    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, CSSValueID identifier);
-    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes);
-    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
-private:
-    void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
-
-    void inlineStyleChanged();
-    PropertySetCSSStyleDeclaration* inlineStyleCSSOMWrapper();
-    void setInlineStyleFromString(const AtomicString&);
-    MutableStylePropertySet* ensureMutableInlineStyle();
-
-    void makePresentationAttributeCacheKey(PresentationAttributeCacheKey&) const;
-    void rebuildPresentationAttributeStyle();
-};
-
-inline void StyledElement::invalidateStyleAttribute()
-{
-    ASSERT(elementData());
-    elementData()->m_styleAttributeIsDirty = true;
-}
-
-inline const StylePropertySet* StyledElement::presentationAttributeStyle()
-{
-    if (!elementData())
-        return 0;
-    if (elementData()->m_presentationAttributeStyleIsDirty)
-        rebuildPresentationAttributeStyle();
-    return elementData()->presentationAttributeStyle();
-}
-
-} //namespace
-
-#endif
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index f5d58a3..c36409b 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -211,7 +211,8 @@
         return true;
 
     RenderObject* parent = context.parentRenderer();
-    if (parent->isTable() || parent->isTableRow() || parent->isTableSection() || parent->isRenderTableCol() || parent->isFrameSet())
+    if (parent->isTable() || parent->isTableRow() || parent->isTableSection() || parent->isRenderTableCol() || parent->isFrameSet()
+        || parent->isFlexibleBox() || parent->isRenderGrid())
         return false;
     
     if (context.style()->preserveNewline()) // pre/pre-wrap/pre-line always make renderers.
@@ -259,15 +260,15 @@
     NodeRenderingContext(this).createRendererForTextIfNeeded();
 }
 
-RenderText* Text::createTextRenderer(RenderArena* arena, RenderStyle* style)
+RenderText* Text::createTextRenderer(RenderStyle* style)
 {
     if (isSVGText(this) || isSVGShadowText(this))
-        return new (arena) RenderSVGInlineText(this, dataImpl());
+        return new (document()->renderArena()) RenderSVGInlineText(this, dataImpl());
 
     if (style->hasTextCombine())
-        return new (arena) RenderCombineText(this, dataImpl());
+        return new (document()->renderArena()) RenderCombineText(this, dataImpl());
 
-    return new (arena) RenderText(this, dataImpl());
+    return new (document()->renderArena()) RenderText(this, dataImpl());
 }
 
 void Text::attach(const AttachContext& context)
@@ -280,18 +281,13 @@
 {
     RenderText* renderer = toRenderText(this->renderer());
 
-    if (!renderer) {
+    if (renderer) {
+        if (change != NoChange || needsStyleRecalc())
+            renderer->setStyle(document()->styleResolver()->styleForText(this));
         if (needsStyleRecalc())
-            reattach();
-        clearNeedsStyleRecalc();
-        return;
-    }
-
-    if (needsStyleRecalc()) {
-        renderer->setStyle(document()->styleResolver()->styleForText(this));
-        renderer->setText(dataImpl());
-    } else if (change != NoChange) {
-        renderer->setStyle(document()->styleResolver()->styleForText(this));
+            renderer->setText(dataImpl());
+    } else if (needsStyleRecalc()) {
+        reattach();
     }
 
     clearNeedsStyleRecalc();
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index 3f33246..e4b3b1c 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -49,7 +49,7 @@
     void recalcTextStyle(StyleChange);
     void createTextRendererIfNeeded();
     bool textRendererIsNeeded(const NodeRenderingContext&);
-    RenderText* createTextRenderer(RenderArena*, RenderStyle*);
+    virtual RenderText* createTextRenderer(RenderStyle*);
     void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 76e0aa2..2c447dc 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -47,9 +47,8 @@
 #include "core/page/Page.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderView.h"
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/CString.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/UserActionElementSet.h b/Source/core/dom/UserActionElementSet.h
index fa4d53f..9883262 100644
--- a/Source/core/dom/UserActionElementSet.h
+++ b/Source/core/dom/UserActionElementSet.h
@@ -27,11 +27,9 @@
 #ifndef UserActionElementSet_h
 #define UserActionElementSet_h
 
-#include <wtf/HashMap.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/HashMap.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ViewportArguments.cpp b/Source/core/dom/ViewportArguments.cpp
index 331ac12..e0b346d 100644
--- a/Source/core/dom/ViewportArguments.cpp
+++ b/Source/core/dom/ViewportArguments.cpp
@@ -29,8 +29,7 @@
 #include "core/dom/ViewportArguments.h"
 
 #include "core/dom/Document.h"
-#include "core/platform/graphics/IntSize.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 using namespace std;
 
diff --git a/Source/core/dom/VisitedLinkState.h b/Source/core/dom/VisitedLinkState.h
index dc5338c..552e222 100644
--- a/Source/core/dom/VisitedLinkState.h
+++ b/Source/core/dom/VisitedLinkState.h
@@ -34,7 +34,6 @@
 #include "core/platform/LinkHash.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "wtf/HashSet.h"
-#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/WheelEvent.cpp b/Source/core/dom/WheelEvent.cpp
index a0a1ec6..2f430c3 100644
--- a/Source/core/dom/WheelEvent.cpp
+++ b/Source/core/dom/WheelEvent.cpp
@@ -27,8 +27,6 @@
 #include "core/dom/EventNames.h"
 #include "core/platform/PlatformWheelEvent.h"
 
-#include <wtf/MathExtras.h>
-
 namespace WebCore {
 
 WheelEventInit::WheelEventInit()
diff --git a/Source/core/dom/shadow/ContentDistributor.cpp b/Source/core/dom/shadow/ContentDistributor.cpp
index b9033b1..b3daf77 100644
--- a/Source/core/dom/shadow/ContentDistributor.cpp
+++ b/Source/core/dom/shadow/ContentDistributor.cpp
@@ -436,7 +436,7 @@
 {
     for (NodeInsertionPointMap::iterator i = m_nodeToInsertionPoint.begin(); i != m_nodeToInsertionPoint.end(); ++i) {
         if (i->value == insertionPoint)
-            const_cast<Node*>(i->key)->setNeedsStyleRecalc(SyntheticStyleChange);
+            const_cast<Node*>(i->key)->setNeedsStyleRecalc(InlineStyleChange);
     }
 }
 
diff --git a/Source/core/dom/shadow/ContentDistributor.h b/Source/core/dom/shadow/ContentDistributor.h
index c90049b..442dc41 100644
--- a/Source/core/dom/shadow/ContentDistributor.h
+++ b/Source/core/dom/shadow/ContentDistributor.h
@@ -34,7 +34,6 @@
 #include "core/dom/shadow/SelectRuleFeatureSet.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
-#include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/shadow/ContentSelectorQuery.h b/Source/core/dom/shadow/ContentSelectorQuery.h
index fd7cd82..b37008a 100644
--- a/Source/core/dom/shadow/ContentSelectorQuery.h
+++ b/Source/core/dom/shadow/ContentSelectorQuery.h
@@ -32,8 +32,6 @@
 #define ContentSelectorQuery_h
 
 #include "core/css/CSSSelectorList.h"
-#include "core/css/SelectorChecker.h"
-#include "core/dom/SelectorQuery.h"
 #include "wtf/Forward.h"
 #include "wtf/Vector.h"
 
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 807aeab..2e988ee 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -72,21 +72,27 @@
     m_distributor.invalidateDistribution(shadowHost);
 }
 
-void ElementShadow::attach()
+void ElementShadow::attach(const Node::AttachContext& context)
 {
     ContentDistributor::ensureDistribution(host());
 
+    Node::AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
+
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         if (!root->attached())
-            root->attach();
+            root->attach(childrenContext);
     }
 }
 
-void ElementShadow::detach()
+void ElementShadow::detach(const Node::AttachContext& context)
 {
+    Node::AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
+
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         if (root->attached())
-            root->detach();
+            root->detach(childrenContext);
     }
 }
 
diff --git a/Source/core/dom/shadow/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
index fc7c7b9..a3ce07e 100644
--- a/Source/core/dom/shadow/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -27,13 +27,11 @@
 #ifndef ElementShadow_h
 #define ElementShadow_h
 
-#include "core/dom/ExceptionCode.h"
 #include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "wtf/DoublyLinkedList.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -58,8 +56,8 @@
 
     ShadowRoot* addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType);
 
-    void attach();
-    void detach();
+    void attach(const Node::AttachContext&);
+    void detach(const Node::AttachContext&);
 
     bool childNeedsStyleRecalc() const;
     bool needsStyleRecalc() const;
diff --git a/Source/core/dom/shadow/InsertionPoint.h b/Source/core/dom/shadow/InsertionPoint.h
index 9348f23..44cd1f9 100644
--- a/Source/core/dom/shadow/InsertionPoint.h
+++ b/Source/core/dom/shadow/InsertionPoint.h
@@ -31,11 +31,9 @@
 #ifndef InsertionPoint_h
 #define InsertionPoint_h
 
-#include "HTMLNames.h"
 #include "core/css/CSSSelectorList.h"
 #include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLElement.h"
 #include "wtf/Forward.h"
 
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index b3f02e9..52165d6 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -27,7 +27,6 @@
 #include "config.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
-#include "RuntimeEnabledFeatures.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ContentDistributor.h"