Merge from Chromium at DEPS revision r200144

This commit was generated by merge_to_master.py.

Change-Id: I52995489013675af682cee321f417f624396b584
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index 4751272..3aa4dab 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -85,6 +85,7 @@
         // This does everything appendChild() would do in this situation (assuming m_ignoreChildrenChanged was set),
         // but much more efficiently.
         textNode->setParentOrShadowHostNode(this);
+        treeScope()->adoptIfNeeded(textNode.get());
         setFirstChild(textNode.get());
         setLastChild(textNode.get());
     }
diff --git a/Source/core/dom/CharacterData.idl b/Source/core/dom/CharacterData.idl
index 4b45308..6491b8e 100644
--- a/Source/core/dom/CharacterData.idl
+++ b/Source/core/dom/CharacterData.idl
@@ -37,7 +37,9 @@
                                     [IsIndex,Default=Undefined] optional unsigned long length,
                                     [Default=Undefined] optional DOMString data);
 
-    // DOM 4
+    // ChildNode interface API
+    readonly attribute Element previousElementSibling;
+    readonly attribute Element nextElementSibling;
     [RaisesException] void remove();
 };
 
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index 4256a59..7c3ff41 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -30,10 +30,11 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/MutationEvent.h"
+#include "core/dom/NodeRareData.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/TemplateContentDocumentFragment.h"
-#include "core/html/shadow/InsertionPoint.h"
+#include "core/html/HTMLCollection.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/cache/MemoryCache.h"
 #include "core/page/Chrome.h"
@@ -825,6 +826,35 @@
     }
 }
 
+PassRefPtr<HTMLCollection> ContainerNode::children()
+{
+    return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, NodeChildren);
+}
+
+Element* ContainerNode::firstElementChild() const
+{
+    return ElementTraversal::firstWithin(this);
+}
+
+Element* ContainerNode::lastElementChild() const
+{
+    Node* n = lastChild();
+    while (n && !n->isElementNode())
+        n = n->previousSibling();
+    return toElement(n);
+}
+
+unsigned ContainerNode::childElementCount() const
+{
+    unsigned count = 0;
+    Node* n = firstChild();
+    while (n) {
+        count += n->isElementNode();
+        n = n->nextSibling();
+    }
+    return count;
+}
+
 unsigned ContainerNode::childNodeCount() const
 {
     unsigned count = 0;
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index e96dc0f..b29abf7 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -33,7 +33,8 @@
 namespace WebCore {
 
 class FloatPoint;
-    
+class HTMLCollection;
+
 typedef void (*NodeCallback)(Node*, unsigned);
 
 namespace Private { 
@@ -86,6 +87,12 @@
     Node* lastChild() const { return m_lastChild; }
     bool hasChildNodes() const { return m_firstChild; }
 
+    // ParentNode interface API
+    PassRefPtr<HTMLCollection> children();
+    Element* firstElementChild() const;
+    Element* lastElementChild() const;
+    unsigned childElementCount() const;
+
     unsigned childNodeCount() const;
     Node* childNode(unsigned index) const;
 
diff --git a/Source/core/dom/ContainerNodeAlgorithms.cpp b/Source/core/dom/ContainerNodeAlgorithms.cpp
index 5a3a513..59d65ed 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.cpp
+++ b/Source/core/dom/ContainerNodeAlgorithms.cpp
@@ -27,7 +27,7 @@
 #include "core/dom/ContainerNodeAlgorithms.h"
 
 #include "core/dom/Element.h"
-#include "core/dom/ElementShadow.h"
+#include "core/dom/shadow/ElementShadow.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/ContextFeatures.h b/Source/core/dom/ContextFeatures.h
index 3f56c11..b46b85e 100644
--- a/Source/core/dom/ContextFeatures.h
+++ b/Source/core/dom/ContextFeatures.h
@@ -28,7 +28,6 @@
 #define ContextFeatures_h
 
 #include "core/platform/RefCountedSupplement.h"
-#include <wtf/PassOwnPtr.h>
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 7118c1c..07c6c66 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -51,7 +51,7 @@
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/MediaPlayer.h"
 #include "core/plugins/PluginData.h"
-#include "origin/SecurityOrigin.h"
+#include "weborigin/SecurityOrigin.h"
 
 #if ENABLE(SVG)
 #include "SVGNames.h"
@@ -302,7 +302,7 @@
     return doc.release();
 }
 
-PassRefPtr<CSSStyleSheet> DOMImplementation::createCSSStyleSheet(const String&, const String& media, ExceptionCode&)
+PassRefPtr<CSSStyleSheet> DOMImplementation::createCSSStyleSheet(const String&, const String& media)
 {
     // FIXME: Title should be set.
     // FIXME: Media could have wrong syntax, in which case we should generate an exception.
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index 918e766..fe2c31d 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -58,7 +58,7 @@
     DOMImplementation* getInterface(const String& feature);
 
     // From the DOMImplementationCSS interface
-    static PassRefPtr<CSSStyleSheet> createCSSStyleSheet(const String& title, const String& media, ExceptionCode&);
+    static PassRefPtr<CSSStyleSheet> createCSSStyleSheet(const String& title, const String& media);
 
     // From the HTMLDOMImplementation interface
     PassRefPtr<HTMLDocument> createHTMLDocument(const String& title);
diff --git a/Source/core/dom/DOMImplementation.idl b/Source/core/dom/DOMImplementation.idl
index 960e2df..d7ef3be 100644
--- a/Source/core/dom/DOMImplementation.idl
+++ b/Source/core/dom/DOMImplementation.idl
@@ -39,8 +39,8 @@
 
     // DOMImplementationCSS interface from DOM Level 2 CSS
 
-     [RaisesException] CSSStyleSheet createCSSStyleSheet([Default=Undefined] optional DOMString title,
-                                                     [Default=Undefined] optional DOMString media);
+     CSSStyleSheet createCSSStyleSheet([Default=Undefined] optional DOMString title,
+                                       [Default=Undefined] optional DOMString media);
 
     // HTMLDOMImplementation interface from DOM Level 2 HTML
 
diff --git a/Source/core/dom/DOMNamedFlowCollection.cpp b/Source/core/dom/DOMNamedFlowCollection.cpp
index b882120..47107a1 100644
--- a/Source/core/dom/DOMNamedFlowCollection.cpp
+++ b/Source/core/dom/DOMNamedFlowCollection.cpp
@@ -38,6 +38,7 @@
 DOMNamedFlowCollection::DOMNamedFlowCollection(const Vector<NamedFlow*>& namedFlows)
 {
     ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
+    ScriptWrappable::init(this);
     for (Vector<NamedFlow*>::const_iterator it = namedFlows.begin(); it != namedFlows.end(); ++it)
         m_namedFlows.add(*it);
 }
diff --git a/Source/core/dom/DOMNamedFlowCollection.h b/Source/core/dom/DOMNamedFlowCollection.h
index 739fad3..0a87b2b 100644
--- a/Source/core/dom/DOMNamedFlowCollection.h
+++ b/Source/core/dom/DOMNamedFlowCollection.h
@@ -29,6 +29,7 @@
 #ifndef DOMNamedFlowCollection_h
 #define DOMNamedFlowCollection_h
 
+#include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/NamedFlowCollection.h"
 #include <wtf/ListHashSet.h>
 #include <wtf/PassRefPtr.h>
@@ -40,7 +41,7 @@
 class Document;
 class NamedFlow;
 
-class DOMNamedFlowCollection : public RefCounted<DOMNamedFlowCollection> {
+class DOMNamedFlowCollection : public ScriptWrappable, public RefCounted<DOMNamedFlowCollection> {
 public:
     static PassRefPtr<DOMNamedFlowCollection> create(const Vector<NamedFlow*>& namedFlows)
     {
diff --git a/Source/core/dom/DOMStringList.h b/Source/core/dom/DOMStringList.h
index d365799..f4dddd3 100644
--- a/Source/core/dom/DOMStringList.h
+++ b/Source/core/dom/DOMStringList.h
@@ -26,6 +26,7 @@
 #ifndef DOMStringList_h
 #define DOMStringList_h
 
+#include "bindings/v8/ScriptWrappable.h"
 #include <wtf/PassRefPtr.h>
 #include <wtf/RefCounted.h>
 #include <wtf/Vector.h>
@@ -35,7 +36,7 @@
 
 // FIXME: Some consumers of this class may benefit from lazily fetching items rather
 //        than creating the list statically as is currently the only option.
-class DOMStringList : public RefCounted<DOMStringList> {
+class DOMStringList : public ScriptWrappable, public RefCounted<DOMStringList> {
 public:
     static PassRefPtr<DOMStringList> create()
     {
@@ -55,7 +56,10 @@
     operator const Vector<String>&() const { return m_strings; }
 
 private:
-    DOMStringList() { }
+    DOMStringList()
+    {
+        ScriptWrappable::init(this);
+    }
 
     Vector<String> m_strings;
 };
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 6cf7bcc..84cf458 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -74,7 +74,6 @@
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
-#include "core/dom/ElementShadow.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventFactory.h"
 #include "core/dom/EventListener.h"
@@ -100,13 +99,14 @@
 #include "core/dom/ScriptRunner.h"
 #include "core/dom/ScriptedAnimationController.h"
 #include "core/dom/SelectorQuery.h"
-#include "core/dom/ShadowRoot.h"
 #include "core/dom/TouchList.h"
 #include "core/dom/TransformSource.h"
 #include "core/dom/TreeWalker.h"
 #include "core/dom/UserActionElementSet.h"
 #include "core/dom/VisitedLinkState.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/htmlediting.h"
@@ -193,9 +193,9 @@
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "modules/geolocation/GeolocationController.h"
-#include "origin/SchemeRegistry.h"
-#include "origin/SecurityOrigin.h"
-#include "origin/SecurityPolicy.h"
+#include "weborigin/SchemeRegistry.h"
+#include "weborigin/SecurityOrigin.h"
+#include "weborigin/SecurityPolicy.h"
 
 #if ENABLE(SVG)
 #include "SVGElementFactory.h"
@@ -2048,9 +2048,6 @@
     if (ScriptableDocumentParser* parser = scriptableDocumentParser())
         parser->setWasCreatedByScript(true);
 
-    if (DOMWindow* domWindow = this->domWindow())
-        domWindow->removeAllEventListeners();
-
     if (m_frame)
         m_frame->loader()->didExplicitOpen();
 }
@@ -4206,18 +4203,6 @@
     return m_iconURLs;
 }
 
-void Document::addIconURL(const String& url, const String&, const String&, IconType iconType)
-{
-    if (url.isEmpty())
-        return;
-
-    Frame* f = frame();
-    if (!f)
-        return;
-
-    f->loader()->didChangeIcons(iconType);
-}
-
 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
 {
     if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 14d4b4b..2da5a7e 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -45,7 +45,7 @@
 #include "core/page/FocusDirection.h"
 #include "core/page/PageVisibilityState.h"
 #include "core/platform/PlatformScreen.h"
-#include "origin/ReferrerPolicy.h"
+#include "weborigin/ReferrerPolicy.h"
 #include "core/platform/Timer.h"
 #include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/IntRect.h"
@@ -893,7 +893,6 @@
 
     const Vector<IconURL>& shortcutIconURLs();
     const Vector<IconURL>& iconURLs(int iconTypesMask);
-    void addIconURL(const String& url, const String& mimeType, const String& size, IconType);
 
     void setUseSecureKeyboardEntryWhenActive(bool);
     bool useSecureKeyboardEntryWhenActive() const;
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index 7f756cf..02f2bb5 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -150,7 +150,7 @@
                                            [Default=Undefined] optional long y);
 
     // Mozilla extensions
-    DOMSelection       getSelection();
+    Selection          getSelection();
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString characterSet;
 
     // WebKit extensions
@@ -286,7 +286,12 @@
     readonly attribute boolean webkitHidden;
 
     // Security Policy API: http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#script-interfaces
-    [EnabledAtRuntime=experimentalContentSecurityPolicyFeatures] readonly attribute DOMSecurityPolicy securityPolicy;
+    [EnabledAtRuntime=experimentalContentSecurityPolicyFeatures] readonly attribute SecurityPolicy securityPolicy;
 
+    // ParentNode interface API
+    readonly attribute HTMLCollection children;
+    readonly attribute Element firstElementChild;
+    readonly attribute Element lastElementChild;
+    readonly attribute unsigned long childElementCount;
 };
 
diff --git a/Source/core/dom/DocumentFragment.idl b/Source/core/dom/DocumentFragment.idl
index 0837e78..01ca5de 100644
--- a/Source/core/dom/DocumentFragment.idl
+++ b/Source/core/dom/DocumentFragment.idl
@@ -25,5 +25,11 @@
     // NodeSelector - Selector API
     [RaisesException] Element querySelector(DOMString selectors);
     [RaisesException] NodeList querySelectorAll(DOMString selectors);
+
+    // ParentNode interface API
+    readonly attribute HTMLCollection children;
+    readonly attribute Element firstElementChild;
+    readonly attribute Element lastElementChild;
+    readonly attribute unsigned long childElementCount;
 };
 
diff --git a/Source/core/dom/DocumentMarker.h b/Source/core/dom/DocumentMarker.h
index ce63fa6..e8e6d9f 100644
--- a/Source/core/dom/DocumentMarker.h
+++ b/Source/core/dom/DocumentMarker.h
@@ -41,31 +41,7 @@
     enum MarkerType {
         Spelling = 1 << 0,
         Grammar = 1 << 1,
-        TextMatch = 1 << 2,
-        // Text has been modified by spell correction, reversion of spell correction or other type of substitution. 
-        // On some platforms, this prevents the text from being autocorrected again. On post Snow Leopard Mac OS X, 
-        // if a Replacement marker contains non-empty description, a reversion UI will be shown.
-        Replacement = 1 << 3,
-        // Renderer needs to add underline indicating that the text has been modified by spell
-        // correction. Text with Replacement marker doesn't necessarily has CorrectionIndicator
-        // marker. For instance, after some text has been corrected, it will have both Replacement
-        // and CorrectionIndicator. However, if user further modifies such text, we would remove
-        // CorrectionIndicator marker, but retain Replacement marker.
-        CorrectionIndicator = 1 << 4,
-        // Correction suggestion has been offered, but got rejected by user.
-        RejectedCorrection = 1 << 5,
-        // Text has been modified by autocorrection. The description of this marker is the original text before autocorrection.
-        Autocorrected = 1 << 6,
-        // On some platforms, this prevents the text from being spellchecked again.
-        SpellCheckingExemption = 1 << 7,
-        // This marker indicates user has deleted an autocorrection starting at the end of the
-        // range that bears this marker. In some platforms, if the user later inserts the same original
-        // word again at this position, it will not be autocorrected again. The description of this
-        // marker is the original word before autocorrection was applied.
-        DeletedAutocorrection = 1 << 8,
-        // This marker indicates that the range of text spanned by the marker is entered by voice dictation,
-        // and it has alternative text.
-        DictationAlternatives = 1 << 9
+        TextMatch = 1 << 2
     };
 
     class MarkerTypes {
@@ -87,7 +63,7 @@
     class AllMarkers : public MarkerTypes {
     public:
         AllMarkers()
-            : MarkerTypes(Spelling | Grammar | TextMatch | Replacement | CorrectionIndicator | RejectedCorrection | Autocorrected | SpellCheckingExemption | DeletedAutocorrection | DictationAlternatives)
+            : MarkerTypes(Spelling | Grammar | TextMatch)
         {
         }
     };
diff --git a/Source/core/dom/DocumentMarkerController.cpp b/Source/core/dom/DocumentMarkerController.cpp
index 90d3a15..0928c3d 100644
--- a/Source/core/dom/DocumentMarkerController.cpp
+++ b/Source/core/dom/DocumentMarkerController.cpp
@@ -50,13 +50,14 @@
 {
 }
 
+DocumentMarkerController::~DocumentMarkerController()
+{
+}
+
 void DocumentMarkerController::detach()
 {
-    m_possiblyExistingMarkerTypes = 0;
-    if (m_markers.isEmpty())
-        return;
-    deleteAllValues(m_markers);
     m_markers.clear();
+    m_possiblyExistingMarkerTypes = 0;
 }
 
 void DocumentMarkerController::addMarker(Range* range, DocumentMarker::MarkerType type, const String& description, uint32_t hash)
@@ -143,12 +144,11 @@
 
     m_possiblyExistingMarkerTypes.add(newMarker.type());
 
-    MarkerList* list = m_markers.get(node);
+    OwnPtr<MarkerList>& list = m_markers.add(node, nullptr).iterator->value;
 
     if (!list) {
-        list = new MarkerList;
+        list = adoptPtr(new MarkerList);
         list->append(RenderedDocumentMarker(newMarker));
-        m_markers.set(node, list);
     } else {
         RenderedDocumentMarker toInsert(newMarker);
         size_t numMarkers = list->size();
@@ -295,11 +295,9 @@
 
     if (list->isEmpty()) {
         m_markers.remove(node);
-        delete list;
+        if (m_markers.isEmpty())
+            m_possiblyExistingMarkerTypes = 0;
     }
-    
-    if (m_markers.isEmpty())
-        m_possiblyExistingMarkerTypes = 0;
 
     // repaint the affected node
     if (docDirty && node->renderer())
@@ -316,7 +314,7 @@
     MarkerMap::iterator end = m_markers.end();
     for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
         // inner loop; process each marker in this node
-        MarkerList* list = nodeIterator->value;
+        MarkerList* list = nodeIterator->value.get();
         unsigned markerCount = list->size();
         for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
             RenderedDocumentMarker& marker = list->at(markerIndex);
@@ -414,7 +412,7 @@
     MarkerMap::iterator end = m_markers.end();
     for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
         // inner loop; process each marker in this node
-        MarkerList* list = nodeIterator->value;
+        MarkerList* list = nodeIterator->value.get();
         unsigned markerCount = list->size();
         for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
             const RenderedDocumentMarker& marker = list->at(markerIndex);
@@ -441,7 +439,7 @@
     
     MarkerMap::iterator iterator = m_markers.find(node);
     if (iterator != m_markers.end())
-        removeMarkersFromList(node, iterator->value, markerTypes);
+        removeMarkersFromList(iterator, markerTypes);
 }
 
 void DocumentMarkerController::removeMarkers(DocumentMarker::MarkerTypes markerTypes)
@@ -450,25 +448,30 @@
         return;
     ASSERT(!m_markers.isEmpty());
 
-    // outer loop: process each markered node in the document
-    MarkerMap markerMapCopy = m_markers;
-    MarkerMap::iterator end = markerMapCopy.end();
-    for (MarkerMap::iterator i = markerMapCopy.begin(); i != end; ++i)
-        removeMarkersFromList(i->key.get(), i->value, markerTypes);
+    Vector<RefPtr<Node> > nodesWithMarkers;
+    copyKeysToVector(m_markers, nodesWithMarkers);
+    unsigned size = nodesWithMarkers.size();
+    for (unsigned i = 0; i < size; ++i) {
+        MarkerMap::iterator iterator = m_markers.find(nodesWithMarkers[i]);
+        if (iterator != m_markers.end())
+            removeMarkersFromList(iterator, markerTypes);
+    }
+
     m_possiblyExistingMarkerTypes.remove(markerTypes);
 }
 
-// This function may release node and vectorPair.
-void DocumentMarkerController::removeMarkersFromList(Node* node, MarkerList* list, DocumentMarker::MarkerTypes markerTypes)
+void DocumentMarkerController::removeMarkersFromList(MarkerMap::iterator iterator, DocumentMarker::MarkerTypes markerTypes)
 {
+    bool needsRepainting = false;
+    bool listCanBeRemoved;
+
     if (markerTypes == DocumentMarker::AllMarkers()) {
-        delete list;
-        m_markers.remove(node);
-        if (RenderObject* renderer = node->renderer())
-            renderer->repaint();
+        needsRepainting = true;
+        listCanBeRemoved = true;
     } else {
-        bool needsRepaint = false;
-        for (size_t i = 0; i != list->size();) {
+        MarkerList* list = iterator->value.get();
+
+        for (size_t i = 0; i != list->size(); ) {
             DocumentMarker marker = list->at(i);
 
             // skip nodes that are not of the specified type
@@ -479,26 +482,23 @@
 
             // pitch the old marker
             list->remove(i);
-            needsRepaint = true;
+            needsRepainting = true;
             // i now is the index of the next marker
         }
 
-        // Redraw the node if it changed. Do this before the node is removed from m_markers, since
-        // m_markers might contain the last reference to the node.
-        if (needsRepaint) {
-            RenderObject* renderer = node->renderer();
-            if (renderer)
-                renderer->repaint();
-        }
-
-        // delete the node's list if it is now empty
-        if (list->isEmpty()) {
-            m_markers.remove(node);
-            delete list;
-        }
+        listCanBeRemoved = list->isEmpty();
     }
-    if (m_markers.isEmpty())
-        m_possiblyExistingMarkerTypes = 0;
+
+    if (needsRepainting) {
+        if (RenderObject* renderer = iterator->key->renderer())
+            renderer->repaint();
+    }
+
+    if (listCanBeRemoved) {
+        m_markers.remove(iterator);
+        if (m_markers.isEmpty())
+            m_possiblyExistingMarkerTypes = 0;
+    }
 }
 
 void DocumentMarkerController::repaintMarkers(DocumentMarker::MarkerTypes markerTypes)
@@ -513,7 +513,7 @@
         Node* node = i->key.get();
 
         // inner loop: process each marker in the current node
-        MarkerList* list = i->value;
+        MarkerList* list = i->value.get();
         bool nodeNeedsRepaint = false;
         for (size_t i = 0; i != list->size(); ++i) {
             DocumentMarker marker = list->at(i);
@@ -541,7 +541,7 @@
     for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
 
         // inner loop: process each rect in the current node
-        MarkerList* list = i->value;
+        MarkerList* list = i->value.get();
         for (size_t listIndex = 0; listIndex < list->size(); ++listIndex)
             list->at(listIndex).invalidate(r);
     }
@@ -649,41 +649,6 @@
     return false;
 }
 
-void DocumentMarkerController::clearDescriptionOnMarkersIntersectingRange(Range* range, DocumentMarker::MarkerTypes markerTypes)
-{
-    if (!possiblyHasMarkers(markerTypes))
-        return;
-    ASSERT(!m_markers.isEmpty());
-
-    Node* startContainer = range->startContainer();
-    Node* endContainer = range->endContainer();
-
-    Node* pastLastNode = range->pastLastNode();
-    for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(node)) {
-        unsigned startOffset = node == startContainer ? range->startOffset() : 0;
-        unsigned endOffset = node == endContainer ? static_cast<unsigned>(range->endOffset()) : std::numeric_limits<unsigned>::max();
-        MarkerList* list = m_markers.get(node);
-        if (!list)
-            continue;
-
-        for (size_t i = 0; i < list->size(); ++i) {
-            DocumentMarker& marker = list->at(i);
-
-            // markers are returned in order, so stop if we are now past the specified range
-            if (marker.startOffset() >= endOffset)
-                break;
-
-            // skip marker that is wrong type or before target
-            if (marker.endOffset() <= startOffset || !markerTypes.contains(marker.type())) {
-                i++;
-                continue;
-            }
-
-            marker.clearDetails();
-        }
-    }
-}
-
 #ifndef NDEBUG
 void DocumentMarkerController::showMarkers() const
 {
@@ -692,7 +657,7 @@
     for (MarkerMap::const_iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
         Node* node = nodeIterator->key.get();
         fprintf(stderr, "%p", node);
-        MarkerList* list = nodeIterator->value;
+        MarkerList* list = nodeIterator->value.get();
         for (unsigned markerIndex = 0; markerIndex < list->size(); ++markerIndex) {
             const DocumentMarker& marker = list->at(markerIndex);
             fprintf(stderr, " %d:[%d:%d](%d)", marker.type(), marker.startOffset(), marker.endOffset(), marker.activeMatch());
@@ -705,7 +670,6 @@
 
 } // namespace WebCore
 
-
 #ifndef NDEBUG
 void showDocumentMarkers(const WebCore::DocumentMarkerController* controller)
 {
diff --git a/Source/core/dom/DocumentMarkerController.h b/Source/core/dom/DocumentMarkerController.h
index 095c295..b73bcd1 100644
--- a/Source/core/dom/DocumentMarkerController.h
+++ b/Source/core/dom/DocumentMarkerController.h
@@ -45,7 +45,7 @@
 public:
 
     DocumentMarkerController();
-    ~DocumentMarkerController() { detach(); }
+    ~DocumentMarkerController();
 
     void detach();
     void addMarker(Range*, DocumentMarker::MarkerType);
@@ -79,7 +79,6 @@
     Vector<DocumentMarker> markersForNode(Node*);
     Vector<DocumentMarker*> markers();
     Vector<IntRect> renderedRectsForMarkers(DocumentMarker::MarkerType);
-    void clearDescriptionOnMarkersIntersectingRange(Range*, DocumentMarker::MarkerTypes);
 
 #ifndef NDEBUG
     void showMarkers() const;
@@ -89,9 +88,9 @@
     void addMarker(Node*, const DocumentMarker&);
 
     typedef Vector<RenderedDocumentMarker> MarkerList;
-    typedef HashMap<RefPtr<Node>, MarkerList*> MarkerMap;
+    typedef HashMap<RefPtr<Node>, OwnPtr<MarkerList> > MarkerMap;
     bool possiblyHasMarkers(DocumentMarker::MarkerTypes);
-    void removeMarkersFromList(Node*, MarkerList*, DocumentMarker::MarkerTypes);
+    void removeMarkersFromList(MarkerMap::iterator, DocumentMarker::MarkerTypes);
 
     MarkerMap m_markers;
     // Provide a quick way to determine whether a particular marker type is absent without going through the map.
diff --git a/Source/core/dom/DocumentType.idl b/Source/core/dom/DocumentType.idl
index 5cd61a9..352da12 100644
--- a/Source/core/dom/DocumentType.idl
+++ b/Source/core/dom/DocumentType.idl
@@ -31,7 +31,9 @@
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString systemId;
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString internalSubset;        
 
-    // DOM 4
+    // ChildNode interface API
+    readonly attribute Element previousElementSibling;
+    readonly attribute Element nextElementSibling;
     [RaisesException] void remove();
 };
 
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index cd5ec55..e8645e2 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -53,9 +53,10 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/PseudoElement.h"
 #include "core/dom/SelectorQuery.h"
-#include "core/dom/ShadowRoot.h"
 #include "core/dom/Text.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/htmlediting.h"
@@ -71,7 +72,6 @@
 #include "core/html/HTMLTableRowsCollection.h"
 #include "core/html/VoidCallback.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/html/shadow/InsertionPoint.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/FocusController.h"
 #include "core/page/Frame.h"
@@ -289,18 +289,27 @@
 PassRefPtr<Attr> Element::detachAttribute(size_t index)
 {
     ASSERT(elementData());
+    const Attribute* attribute = elementData()->attributeItem(index);
+    RefPtr<Attr> attrNode = attrIfExists(attribute->name());
+    if (attrNode)
+        detachAttrNodeAtIndex(attrNode.get(), index);
+    else {
+        attrNode = Attr::create(document(), attribute->name(), attribute->value());
+        removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
+    }
+    return attrNode.release();
+}
+
+void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
+{
+    ASSERT(attr);
+    ASSERT(elementData());
 
     const Attribute* attribute = elementData()->attributeItem(index);
     ASSERT(attribute);
-
-    RefPtr<Attr> attrNode = attrIfExists(attribute->name());
-    if (attrNode)
-        detachAttrNodeFromElementWithValue(attrNode.get(), attribute->value());
-    else
-        attrNode = Attr::create(document(), attribute->name(), attribute->value());
-
+    ASSERT(attribute->name() == attr->qualifiedName());
+    detachAttrNodeFromElementWithValue(attr, attribute->value());
     removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
-    return attrNode.release();
 }
 
 void Element::removeAttribute(const QualifiedName& name)
@@ -1443,12 +1452,10 @@
             change = Force;
         }
 
-        if (change != Force) {
-            if (styleChangeType() >= FullStyleChange)
-                change = Force;
-            else
-                change = localChange;
-        }
+        if (styleChangeType() == FullStyleChange)
+            change = Force;
+        else if (change != Force)
+            change = localChange;
     }
     StyleResolverParentPusher parentPusher(this);
 
@@ -1800,13 +1807,15 @@
 
     synchronizeAttribute(attr->qualifiedName());
 
-    size_t index = elementData()->getAttributeItemIndex(attr->qualifiedName());
+    size_t index = elementData()->getAttrIndex(attr);
     if (index == notFound) {
         ec = NOT_FOUND_ERR;
         return 0;
     }
 
-    return detachAttribute(index);
+    RefPtr<Attr> guard(attr);
+    detachAttrNodeAtIndex(attr, index);
+    return guard.release();
 }
 
 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
@@ -2336,31 +2345,6 @@
     return 0;
 }
 
-// ElementTraversal API
-Element* Element::firstElementChild() const
-{
-    return ElementTraversal::firstWithin(this);
-}
-
-Element* Element::lastElementChild() const
-{
-    Node* n = lastChild();
-    while (n && !n->isElementNode())
-        n = n->previousSibling();
-    return toElement(n);
-}
-
-unsigned Element::childElementCount() const
-{
-    unsigned count = 0;
-    Node* n = firstChild();
-    while (n) {
-        count += n->isElementNode();
-        n = n->nextSibling();
-    }
-    return count;
-}
-
 bool Element::matchesReadOnlyPseudoClass() const
 {
     return false;
@@ -3113,6 +3097,16 @@
         info.addMember(*attributeItem(i), "*attributeItem");
 }
 
+size_t ElementData::getAttrIndex(Attr* attr) const
+{
+    // This relies on the fact that Attr's QualifiedName == the Attribute's name.
+    for (unsigned i = 0; i < length(); ++i) {
+        if (attributeItem(i)->name() == attr->qualifiedName())
+            return i;
+    }
+    return notFound;
+}
+
 size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
 {
     // Continue to checking case-insensitively and/or full namespaced names if necessary:
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index 8b2580b..f5870e2 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -80,6 +80,7 @@
     const Attribute* getAttributeItem(const QualifiedName&) const;
     size_t getAttributeItemIndex(const QualifiedName&) const;
     size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
+    size_t getAttrIndex(Attr*) const;
 
     bool hasID() const { return !m_idForStyleResolution.isNull(); }
     bool hasClass() const { return !m_classNames.isNull(); }
@@ -503,13 +504,6 @@
     bool childNeedsShadowWalker() const;
     void didShadowTreeAwareChildrenChange();
 
-    // ElementTraversal API
-    Element* firstElementChild() const;
-    Element* lastElementChild() const;
-    Element* previousElementSibling() const;
-    Element* nextElementSibling() const;
-    unsigned childElementCount() const;
-
     virtual bool matchesReadOnlyPseudoClass() const;
     virtual bool matchesReadWritePseudoClass() const;
     bool webkitMatchesSelector(const String& selectors, ExceptionCode&);
@@ -555,6 +549,7 @@
     virtual bool isDisabledFormControl() const;
 
     bool isInert() const;
+    virtual bool shouldBeReparentedUnderRenderView(const RenderStyle*) const { return isInTopLayer(); }
 
 #if ENABLE(SVG)
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
@@ -723,6 +718,7 @@
 
     void detachAllAttrNodesFromElement();
     void detachAttrNodeFromElementWithValue(Attr*, const AtomicString& value);
+    void detachAttrNodeAtIndex(Attr*, size_t index);
 
     void createRendererIfNeeded();
 
@@ -777,7 +773,7 @@
     return parent && parent->isElementNode() ? toElement(parent) : 0;
 }
 
-inline Element* Element::previousElementSibling() const
+inline Element* Node::previousElementSibling() const
 {
     Node* n = previousSibling();
     while (n && !n->isElementNode())
@@ -785,7 +781,7 @@
     return static_cast<Element*>(n);
 }
 
-inline Element* Element::nextElementSibling() const
+inline Element* Node::nextElementSibling() const
 {
     Node* n = nextSibling();
     while (n && !n->isElementNode())
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 76136bc..52be687 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -101,11 +101,10 @@
     // WebKit extension, pending specification.
     [RaisesException] boolean webkitMatchesSelector([Default=Undefined] optional DOMString selectors);
 
-    // ElementTraversal API
+    // ParentNode interface API
+    [PerWorldBindings] readonly attribute HTMLCollection children;
     [PerWorldBindings] readonly attribute Element firstElementChild;
     [PerWorldBindings] readonly attribute Element lastElementChild;
-    [PerWorldBindings] readonly attribute Element previousElementSibling;
-    [PerWorldBindings] readonly attribute Element nextElementSibling;
     [PerWorldBindings] readonly attribute unsigned long childElementCount;
 
     // ShadowAware API
@@ -114,7 +113,9 @@
     [ImplementedAs=shadowRoot, PerWorldBindings] readonly attribute ShadowRoot webkitShadowRoot;
     [ImplementedAs=insertionParentForBinding, PerWorldBindings] readonly attribute Node webkitInsertionParent;
 
-    // DOM 4
+    // ChildNode interface API
+    [PerWorldBindings] readonly attribute Element previousElementSibling;
+    [PerWorldBindings] readonly attribute Element nextElementSibling;
     [RaisesException] void remove();
 
     // CSSOM View Module API
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index fe35129..3c512cb 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -24,10 +24,10 @@
 
 #include "core/animation/Animation.h"
 #include "core/dom/DatasetDOMStringMap.h"
-#include "core/dom/ElementShadow.h"
 #include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRareData.h"
 #include "core/dom/PseudoElement.h"
+#include "core/dom/shadow/ElementShadow.h"
 #include "core/html/ClassList.h"
 #include "core/html/ime/InputMethodContext.h"
 #include "core/rendering/style/StyleInheritedData.h"
diff --git a/Source/core/dom/Event.cpp b/Source/core/dom/Event.cpp
index de51a3f..4fc4330 100644
--- a/Source/core/dom/Event.cpp
+++ b/Source/core/dom/Event.cpp
@@ -206,16 +206,15 @@
 {
     if (!m_currentTarget || !m_currentTarget->toNode())
         return StaticNodeList::createEmpty();
-    TreeScope* currentScope = m_currentTarget->toNode()->treeScope();
-    Vector<RefPtr<Node> > nodes;
+    Node* node = m_currentTarget->toNode();
     size_t eventPathSize = m_eventPath.size();
     for (size_t i = 0; i < eventPathSize; ++i) {
-        Node* node = m_eventPath[i]->node();
-        ASSERT(node);
-        if (node->treeScope()->isInclusiveAncestorOf(currentScope))
-            nodes.append(node);
+        if (node == m_eventPath[i]->node()) {
+            ASSERT(m_eventPath[i]->eventPath());
+            return m_eventPath[i]->eventPath();
+        }
     }
-    return StaticNodeList::adopt(nodes);
+    return StaticNodeList::createEmpty();
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/EventContext.cpp b/Source/core/dom/EventContext.cpp
index 7b8dd56..30a44c5 100644
--- a/Source/core/dom/EventContext.cpp
+++ b/Source/core/dom/EventContext.cpp
@@ -32,6 +32,7 @@
 #include "core/dom/FocusEvent.h"
 #include "core/dom/MouseEvent.h"
 #include "core/dom/Node.h"
+#include "core/dom/StaticNodeList.h"
 #include "core/dom/TouchEvent.h"
 #include "core/dom/TouchList.h"
 #include "core/page/DOMWindow.h"
@@ -51,6 +52,11 @@
 {
 }
 
+void EventContext::adoptEventPath(Vector<RefPtr<Node> >& nodes)
+{
+    m_eventPath = StaticNodeList::adopt(nodes);
+}
+
 void EventContext::handleLocalEvents(Event* event) const
 {
     event->setTarget(m_target.get());
diff --git a/Source/core/dom/EventContext.h b/Source/core/dom/EventContext.h
index 5017e5c..5e4f136 100644
--- a/Source/core/dom/EventContext.h
+++ b/Source/core/dom/EventContext.h
@@ -29,6 +29,7 @@
 
 #include "core/dom/EventTarget.h"
 #include "core/dom/Node.h"
+#include "core/dom/StaticNodeList.h"
 #include "core/dom/TreeScope.h"
 #include <wtf/RefPtr.h>
 
@@ -45,6 +46,10 @@
 
     Node* node() const { return m_node.get(); }
     EventTarget* target() const { return m_target.get(); }
+    PassRefPtr<NodeList> eventPath() { return m_eventPath; }
+    void adoptEventPath(Vector<RefPtr<Node> >&);
+    void setEventPath(PassRefPtr<NodeList> nodeList) { m_eventPath = nodeList; }
+
     bool currentTargetSameAsTarget() const { return m_currentTarget.get() == m_target.get(); }
     virtual void handleLocalEvents(Event*) const;
     virtual bool isMouseOrFocusEventContext() const;
@@ -57,6 +62,7 @@
     RefPtr<Node> m_node;
     RefPtr<EventTarget> m_currentTarget;
     RefPtr<EventTarget> m_target;
+    RefPtr<NodeList> m_eventPath;
 };
 
 typedef Vector<OwnPtr<EventContext>, 32> EventPath;
diff --git a/Source/core/dom/EventDispatcher.cpp b/Source/core/dom/EventDispatcher.cpp
index 9465946..ccec89c 100644
--- a/Source/core/dom/EventDispatcher.cpp
+++ b/Source/core/dom/EventDispatcher.cpp
@@ -27,17 +27,17 @@
 #include "core/dom/EventDispatcher.h"
 
 #include "core/dom/ContainerNode.h"
-#include "core/dom/ElementShadow.h"
 #include "core/dom/EventContext.h"
 #include "core/dom/EventDispatchMediator.h"
 #include "core/dom/EventPathWalker.h"
 #include "core/dom/EventRetargeter.h"
 #include "core/dom/MouseEvent.h"
 #include "core/dom/ScopedEventQueue.h"
-#include "core/dom/ShadowRoot.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/html/HTMLMediaElement.h"
-#include "core/html/shadow/InsertionPoint.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/FrameView.h"
 #include <wtf/RefPtr.h>
diff --git a/Source/core/dom/EventPathWalker.cpp b/Source/core/dom/EventPathWalker.cpp
index 2adac7b..b29af07 100644
--- a/Source/core/dom/EventPathWalker.cpp
+++ b/Source/core/dom/EventPathWalker.cpp
@@ -27,9 +27,9 @@
 #include "config.h"
 #include "core/dom/EventPathWalker.h"
 
-#include "core/dom/ShadowRoot.h"
-#include "core/html/shadow/ContentDistributor.h"
-#include "core/html/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ContentDistributor.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/EventRetargeter.cpp b/Source/core/dom/EventRetargeter.cpp
index 297fa6c..502a570 100644
--- a/Source/core/dom/EventRetargeter.cpp
+++ b/Source/core/dom/EventRetargeter.cpp
@@ -20,16 +20,17 @@
 #include "config.h"
 #include "core/dom/EventRetargeter.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/EventContext.h"
 #include "core/dom/EventPathWalker.h"
 #include "core/dom/FocusEvent.h"
 #include "core/dom/MouseEvent.h"
-#include "core/dom/ShadowRoot.h"
 #include "core/dom/Touch.h"
 #include "core/dom/TouchEvent.h"
 #include "core/dom/TouchList.h"
 #include "core/dom/TreeScope.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include <wtf/PassRefPtr.h>
 #include <wtf/RefPtr.h>
 #include <wtf/Vector.h>
@@ -103,6 +104,28 @@
             targetStack.removeLast();
         }
     }
+
+    // Calculates eventPath for each node for Event.path() API.
+    if (!RuntimeEnabledFeatures::experimentalShadowDOMEnabled())
+        return;
+    TreeScope* lastScope = 0;
+    size_t eventPathSize = eventPath.size();
+    for (size_t i = 0; i < eventPathSize; ++i) {
+        TreeScope* currentScope = eventPath[i]->node()->treeScope();
+        if (currentScope == lastScope) {
+            // Fast path.
+            eventPath[i]->setEventPath(eventPath[i - 1]->eventPath());
+            continue;
+        }
+        lastScope = currentScope;
+        Vector<RefPtr<Node> > nodes;
+        for (size_t j = 0; j < eventPathSize; ++j) {
+            Node* node = eventPath[j]->node();
+            if (node->treeScope()->isInclusiveAncestorOf(currentScope))
+                nodes.append(node);
+        }
+        eventPath[i]->adoptEventPath(nodes);
+    }
 }
 
 void EventRetargeter::adjustForMouseEvent(Node* node, MouseEvent& mouseEvent)
diff --git a/Source/core/dom/EventRetargeter.h b/Source/core/dom/EventRetargeter.h
index d88e674..3e89f0f 100644
--- a/Source/core/dom/EventRetargeter.h
+++ b/Source/core/dom/EventRetargeter.h
@@ -22,7 +22,7 @@
 
 #include "core/dom/ContainerNode.h"
 #include "core/dom/EventContext.h"
-#include "core/dom/ShadowRoot.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include <wtf/HashMap.h>
 #include <wtf/PassRefPtr.h>
 #include <wtf/RefPtr.h>
diff --git a/Source/core/dom/EventTarget.h b/Source/core/dom/EventTarget.h
index 7bf80c9..2039839 100644
--- a/Source/core/dom/EventTarget.h
+++ b/Source/core/dom/EventTarget.h
@@ -55,7 +55,6 @@
     class MIDIInput;
     class MIDIPort;
     class MediaController;
-    class MediaSource;
     class MediaStream;
     class MessagePort;
     class NamedFlow;
@@ -66,9 +65,10 @@
     class ScriptProcessorNode;
     class SharedWorker;
     class SharedWorkerContext;
-    class SourceBufferList;
     class TextTrack;
     class TextTrackCue;
+    class WebKitMediaSource;
+    class WebKitSourceBufferList;
     class WebSocket;
     class Worker;
     class XMLHttpRequest;
diff --git a/Source/core/dom/EventTargetFactory.in b/Source/core/dom/EventTargetFactory.in
index c62e1da..dc3235b 100644
--- a/Source/core/dom/EventTargetFactory.in
+++ b/Source/core/dom/EventTargetFactory.in
@@ -26,8 +26,8 @@
 modules/indexeddb/IDBOpenDBRequest
 modules/indexeddb/IDBRequest
 modules/indexeddb/IDBTransaction
-modules/mediasource/MediaSource
-modules/mediasource/SourceBufferList
+modules/mediasource/WebKitMediaSource
+modules/mediasource/WebKitSourceBufferList
 modules/mediastream/MediaStream
 modules/mediastream/MediaStreamTrack
 modules/mediastream/RTCDataChannel
diff --git a/Source/core/dom/MessagePort.cpp b/Source/core/dom/MessagePort.cpp
index 0068061..d505c66 100644
--- a/Source/core/dom/MessagePort.cpp
+++ b/Source/core/dom/MessagePort.cpp
@@ -36,7 +36,7 @@
 #include "core/page/DOMWindow.h"
 #include "core/platform/Timer.h"
 #include "core/workers/WorkerContext.h"
-#include "origin/SecurityOrigin.h"
+#include "weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 79136ad..3223aa7 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -48,7 +48,6 @@
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
 #include "core/dom/ElementRareData.h"
-#include "core/dom/ElementShadow.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventContext.h"
 #include "core/dom/EventDispatchMediator.h"
@@ -74,7 +73,6 @@
 #include "core/dom/RegisteredEventListener.h"
 #include "core/dom/ScopedEventQueue.h"
 #include "core/dom/SelectorQuery.h"
-#include "core/dom/ShadowRoot.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/dom/TagNodeList.h"
 #include "core/dom/TemplateContentDocumentFragment.h"
@@ -88,6 +86,9 @@
 #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"
@@ -95,7 +96,6 @@
 #include "core/html/HTMLStyleElement.h"
 #include "core/html/LabelsNodeList.h"
 #include "core/html/RadioNodeList.h"
-#include "core/html/shadow/InsertionPoint.h"
 #include "core/inspector/InspectorCounters.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
@@ -1284,7 +1284,10 @@
 
 Node* Node::insertionParentForBinding() const
 {
-    return resolveReprojection(this);
+    Node* node = resolveReprojection(this);
+    while (node && node->containingShadowRoot() && node->containingShadowRoot()->type() == ShadowRoot::UserAgentShadowRoot)
+        node = resolveReprojection(node);
+    return node;
 }
 
 bool Node::needsShadowTreeWalkerSlow() const
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index b919d19..b571f9c 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -90,11 +90,11 @@
 // 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, 
-    FullStyleChange = 2 << nodeStyleChangeShift, 
-    SyntheticStyleChange = 3 << nodeStyleChangeShift
+enum StyleChangeType {
+    NoStyleChange = 0,
+    InlineStyleChange = 1 << nodeStyleChangeShift,
+    SyntheticStyleChange = 2 << nodeStyleChangeShift,
+    FullStyleChange = 3 << nodeStyleChangeShift,
 };
 
 class NodeRareDataBase {
@@ -186,6 +186,11 @@
     bool hasAttributes() const;
     NamedNodeMap* attributes() const;
 
+    // ChildNode interface API
+    Element* previousElementSibling() const;
+    Element* nextElementSibling() const;
+    void remove(ExceptionCode&);
+
     Node* pseudoAwareNextSibling() const;
     Node* pseudoAwarePreviousSibling() const;
     Node* pseudoAwareFirstChild() const;
@@ -203,7 +208,6 @@
     bool removeChild(Node* child, ExceptionCode&);
     bool appendChild(PassRefPtr<Node> newChild, ExceptionCode&, AttachBehavior = AttachNow);
 
-    void remove(ExceptionCode&);
     bool hasChildNodes() const { return firstChild(); }
     virtual PassRefPtr<Node> cloneNode(bool deep) = 0;
     const AtomicString& localName() const { return virtualLocalName(); }
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index acdfbbd..1533f0a 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -29,13 +29,13 @@
 #include "HTMLNames.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ContainerNode.h"
-#include "core/dom/ElementShadow.h"
 #include "core/dom/Node.h"
 #include "core/dom/PseudoElement.h"
-#include "core/dom/ShadowRoot.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/ContentDistributor.h"
 #include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 #include "core/rendering/FlowThreadController.h"
@@ -79,7 +79,7 @@
         return false;
     if (renderer->style() && !renderer->style()->flowThread().isEmpty())
         return true;
-    if (toElement(renderer->node())->isInTopLayer())
+    if (toElement(renderer->node())->shouldBeReparentedUnderRenderView(renderer->style()))
         return true;
     return false;
 }
@@ -90,7 +90,16 @@
         return renderer->nextSibling();
 
     Element* element = m_node->isElementNode() ? toElement(m_node) : 0;
-    if (element && element->isInTopLayer()) {
+    if (element && element->shouldBeReparentedUnderRenderView(m_style.get())) {
+        // FIXME: Reparented renderers not in the top layer should probably be
+        // ordered in DOM tree order. We don't have a good way to do that yet,
+        // since NodeRenderingTraversal isn't aware of reparenting. It's safe to
+        // just append for now; it doesn't disrupt the top layer rendering as
+        // the layer collection in RenderLayer only requires that top layer
+        // renderers are orderered correctly relative to each other.
+        if (!element->isInTopLayer())
+            return 0;
+
         const Vector<RefPtr<Element> >& topLayerElements = element->document()->topLayerElements();
         size_t position = topLayerElements.find(element);
         ASSERT(position != notFound);
@@ -123,10 +132,10 @@
     if (RenderObject* renderer = m_node->renderer())
         return renderer->previousSibling();
 
-    // FIXME: This doesn't work correctly for things in the top layer that are
+    // FIXME: This doesn't work correctly for reparented elements that are
     // display: none. We'd need to duplicate the logic in nextRenderer, but since
     // nothing needs that yet just assert.
-    ASSERT(!m_node->isElementNode() || !toElement(m_node)->isInTopLayer());
+    ASSERT(!m_node->isElementNode() || !toElement(m_node)->shouldBeReparentedUnderRenderView(m_style.get()));
 
     if (m_parentFlowRenderer)
         return m_parentFlowRenderer->previousRendererForNode(m_node);
@@ -147,8 +156,8 @@
     if (RenderObject* renderer = m_node->renderer())
         return renderer->parent();
 
-    if (m_node->isElementNode() && toElement(m_node)->isInTopLayer()) {
-        // The parent renderer of top layer elements is the RenderView, but only
+    if (m_node->isElementNode() && toElement(m_node)->shouldBeReparentedUnderRenderView(m_style.get())) {
+        // The parent renderer of reparented elements is the RenderView, but only
         // if the normal parent would have had a renderer.
         // FIXME: This behavior isn't quite right as the spec for top layer
         // only talks about display: none ancestors so putting a <dialog> inside
diff --git a/Source/core/dom/NodeRenderingTraversal.cpp b/Source/core/dom/NodeRenderingTraversal.cpp
index 97a4878..1b23181 100644
--- a/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/Source/core/dom/NodeRenderingTraversal.cpp
@@ -27,8 +27,8 @@
 #include "config.h"
 #include "core/dom/NodeRenderingTraversal.h"
 
-#include "core/dom/ComposedShadowTreeWalker.h"
 #include "core/dom/PseudoElement.h"
+#include "core/dom/shadow/ComposedShadowTreeWalker.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/NodeRenderingTraversal.h b/Source/core/dom/NodeRenderingTraversal.h
index 3d7fa11..6fb020d 100644
--- a/Source/core/dom/NodeRenderingTraversal.h
+++ b/Source/core/dom/NodeRenderingTraversal.h
@@ -93,8 +93,11 @@
 inline Node* nextSibling(const Node* node)
 {
     if (!node->needsShadowTreeWalker()) {
-        ASSERT(nextSiblingSlow(node) == node->nextSibling());
-        return node->nextSibling();
+        Node* next = node->nextSibling();
+        if (!next || !next->isInsertionPoint()) {
+            ASSERT(nextSiblingSlow(node) == next);
+            return next;
+        }
     }
 
     return nextSiblingSlow(node);
@@ -103,8 +106,11 @@
 inline Node* previousSibling(const Node* node)
 {
     if (!node->needsShadowTreeWalker()) {
-        ASSERT(previousSiblingSlow(node) == node->previousSibling());
-        return node->previousSibling();
+        Node* prev = node->previousSibling();
+        if (!prev || !prev->isInsertionPoint()) {
+            ASSERT(previousSiblingSlow(node) == prev);
+            return prev;
+        }
     }
 
     return previousSiblingSlow(node);
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index 49d9d93..d65ca0f 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -69,7 +69,7 @@
         document()->styleSheetCollection()->removeStyleSheetCandidateNode(this);
 }
 
-void ProcessingInstruction::setData(const String& data, ExceptionCode&)
+void ProcessingInstruction::setData(const String& data)
 {
     int oldLength = m_data.length();
     m_data = data;
@@ -94,8 +94,7 @@
 
 void ProcessingInstruction::setNodeValue(const String& nodeValue, ExceptionCode& ec)
 {
-    // NO_MODIFICATION_ALLOWED_ERR: taken care of by setData()
-    setData(nodeValue, ec);
+    setData(nodeValue);
 }
 
 PassRefPtr<Node> ProcessingInstruction::cloneNode(bool /*deep*/)
diff --git a/Source/core/dom/ProcessingInstruction.h b/Source/core/dom/ProcessingInstruction.h
index a63c1b7..b24b4ef 100644
--- a/Source/core/dom/ProcessingInstruction.h
+++ b/Source/core/dom/ProcessingInstruction.h
@@ -38,7 +38,7 @@
 
     const String& target() const { return m_target; }
     const String& data() const { return m_data; }
-    void setData(const String&, ExceptionCode&);
+    void setData(const String&);
 
     void setCreatedByParser(bool createdByParser) { m_createdByParser = createdByParser; }
 
diff --git a/Source/core/dom/ProcessingInstruction.idl b/Source/core/dom/ProcessingInstruction.idl
index 03530e2..1767ee5 100644
--- a/Source/core/dom/ProcessingInstruction.idl
+++ b/Source/core/dom/ProcessingInstruction.idl
@@ -23,7 +23,7 @@
     // DOM Level 1
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString target;
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString data;
+             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString] attribute DOMString data;
 
     // interface LinkStyle from DOM Level 2 Style Sheets
     readonly attribute StyleSheet sheet;
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index 125cab1..311660d 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -804,7 +804,7 @@
         ASSERT(endOffset <= static_cast<ProcessingInstruction*>(container)->data().length());
         if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
             RefPtr<ProcessingInstruction> c = static_pointer_cast<ProcessingInstruction>(container->cloneNode(true));
-            c->setData(c->data().substring(startOffset, endOffset - startOffset), ec);
+            c->setData(c->data().substring(startOffset, endOffset - startOffset));
             if (fragment) {
                 result = fragment;
                 result->appendChild(c.release(), ec);
@@ -815,7 +815,7 @@
             ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(container);
             String data(pi->data());
             data.remove(startOffset, endOffset - startOffset);
-            pi->setData(data, ec);
+            pi->setData(data);
         }
         break;
     case Node::ELEMENT_NODE:
@@ -1807,7 +1807,11 @@
     unsigned boundaryOffset = boundary.offset();
     if (boundaryOffset <= oldNode->length())
         return;
-    boundary.set(oldNode->nextSibling(), boundaryOffset - oldNode->length(), 0);
+    Node* next = oldNode->nextSibling();
+    if (!next || !next->isTextNode())
+        boundary.set(oldNode, oldNode->length(), 0);
+    else
+        boundary.set(next, std::min(boundaryOffset - oldNode->length(), toText(next)->length()), 0);
 }
 
 void Range::textNodeSplit(Text* oldNode)
@@ -1816,8 +1820,6 @@
     ASSERT(oldNode->document() == m_ownerDocument);
     ASSERT(oldNode->parentNode());
     ASSERT(oldNode->isTextNode());
-    ASSERT(oldNode->nextSibling());
-    ASSERT(oldNode->nextSibling()->isTextNode());
     boundaryTextNodesSplit(m_start, oldNode);
     boundaryTextNodesSplit(m_end, oldNode);
 }
diff --git a/Source/core/dom/ScriptElement.cpp b/Source/core/dom/ScriptElement.cpp
index a70eedb..6b58738 100644
--- a/Source/core/dom/ScriptElement.cpp
+++ b/Source/core/dom/ScriptElement.cpp
@@ -52,7 +52,7 @@
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/platform/MIMETypeRegistry.h"
-#include "origin/SecurityOrigin.h"
+#include "weborigin/SecurityOrigin.h"
 
 #if ENABLE(SVG)
 #include "SVGNames.h"
diff --git a/Source/core/dom/SecurityContext.cpp b/Source/core/dom/SecurityContext.cpp
index 2c3d18f..cfaeacd2 100644
--- a/Source/core/dom/SecurityContext.cpp
+++ b/Source/core/dom/SecurityContext.cpp
@@ -31,7 +31,7 @@
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/page/ContentSecurityPolicy.h"
-#include "origin/SecurityOrigin.h"
+#include "weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index 71721f2..21cb569 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -25,7 +25,7 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/NodeRenderingContext.h"
-#include "core/dom/ShadowRoot.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/rendering/RenderCombineText.h"
 #include "core/rendering/RenderText.h"
 
@@ -148,7 +148,7 @@
     return result.toString();
 }
 
-PassRefPtr<Text> Text::replaceWholeText(const String& newText, ExceptionCode&)
+PassRefPtr<Text> Text::replaceWholeText(const String& newText)
 {
     // Remove all adjacent text nodes, and replace the contents of this one.
 
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index d70c2c4..10fc820 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -44,7 +44,7 @@
     // DOM Level 3: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1312295772
 
     String wholeText() const;
-    PassRefPtr<Text> replaceWholeText(const String&, ExceptionCode&);
+    PassRefPtr<Text> replaceWholeText(const String&);
     
     void recalcTextStyle(StyleChange);
     void createTextRendererIfNeeded();
diff --git a/Source/core/dom/Text.idl b/Source/core/dom/Text.idl
index 10c9af9..a86f063 100644
--- a/Source/core/dom/Text.idl
+++ b/Source/core/dom/Text.idl
@@ -29,7 +29,7 @@
 
     // Introduced in DOM Level 3:
     readonly attribute DOMString       wholeText;
-    [RaisesException] Text               replaceWholeText([Default=Undefined] optional DOMString content);
+    Text                               replaceWholeText([Default=Undefined] optional DOMString content);
     // ShadowAware API
     [ImplementedAs=insertionParentForBinding, PerWorldBindings] readonly attribute Node webkitInsertionParent;
 
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 851371f..3087be8 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -34,13 +34,13 @@
 #include "core/dom/EventPathWalker.h"
 #include "core/dom/IdTargetObserverRegistry.h"
 #include "core/dom/NodeTraversal.h"
-#include "core/dom/ShadowRoot.h"
 #include "core/dom/TreeScopeAdopter.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLMapElement.h"
-#include "core/html/shadow/InsertionPoint.h"
 #include "core/page/DOMSelection.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/FocusController.h"
diff --git a/Source/core/dom/TreeScopeAdopter.cpp b/Source/core/dom/TreeScopeAdopter.cpp
index bd0911f..cd36f11 100644
--- a/Source/core/dom/TreeScopeAdopter.cpp
+++ b/Source/core/dom/TreeScopeAdopter.cpp
@@ -28,10 +28,10 @@
 #include "core/dom/Attr.h"
 #include "core/dom/Document.h"
 #include "core/dom/ElementRareData.h"
-#include "core/dom/ElementShadow.h"
 #include "core/dom/NodeRareData.h"
 #include "core/dom/NodeTraversal.h"
-#include "core/dom/ShadowRoot.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/ComposedShadowTreeWalker.cpp b/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
similarity index 97%
rename from Source/core/dom/ComposedShadowTreeWalker.cpp
rename to Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
index 7b9ff2a..1c4f81f 100644
--- a/Source/core/dom/ComposedShadowTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
@@ -26,15 +26,15 @@
  */
 
 #include "config.h"
-#include "core/dom/ComposedShadowTreeWalker.h"
+#include "core/dom/shadow/ComposedShadowTreeWalker.h"
 
 #include "core/dom/Element.h"
-#include "core/dom/ElementShadow.h"
 #include "core/dom/PseudoElement.h"
-#include "core/html/shadow/ContentDistributor.h"
+#include "core/dom/shadow/ContentDistributor.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/InsertionPoint.h"
 #include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
-#include "core/html/shadow/InsertionPoint.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ComposedShadowTreeWalker.h b/Source/core/dom/shadow/ComposedShadowTreeWalker.h
similarity index 98%
rename from Source/core/dom/ComposedShadowTreeWalker.h
rename to Source/core/dom/shadow/ComposedShadowTreeWalker.h
index 1fd2aaa..d93d378 100644
--- a/Source/core/dom/ComposedShadowTreeWalker.h
+++ b/Source/core/dom/shadow/ComposedShadowTreeWalker.h
@@ -28,8 +28,8 @@
 #define ComposedShadowTreeWalker_h
 
 #include "core/dom/NodeRenderingTraversal.h"
-#include "core/dom/ShadowRoot.h"
-#include "core/html/shadow/InsertionPoint.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/shadow/ContentDistributor.cpp b/Source/core/dom/shadow/ContentDistributor.cpp
new file mode 100644
index 0000000..70f6d5b
--- /dev/null
+++ b/Source/core/dom/shadow/ContentDistributor.cpp
@@ -0,0 +1,439 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/shadow/ContentDistributor.h"
+
+#include "core/dom/NodeTraversal.h"
+#include "core/dom/shadow/ContentSelectorQuery.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/shadow/HTMLContentElement.h"
+#include "core/html/shadow/HTMLShadowElement.h"
+
+
+namespace WebCore {
+
+void ContentDistribution::swap(ContentDistribution& other)
+{
+    m_nodes.swap(other.m_nodes);
+    m_indices.swap(other.m_indices);
+}
+
+void ContentDistribution::append(PassRefPtr<Node> node)
+{
+    size_t size = m_nodes.size();
+    m_indices.set(node.get(), size);
+    m_nodes.append(node);
+}
+
+size_t ContentDistribution::find(const Node* node) const
+{
+    HashMap<const Node*, size_t>::const_iterator it = m_indices.find(node);
+    if (it == m_indices.end())
+        return notFound;
+
+    return it.get()->value;
+}
+
+Node* ContentDistribution::nextTo(const Node* node) const
+{
+    size_t index = find(node);
+    if (index == notFound || index + 1 == size())
+        return 0;
+    return at(index + 1).get();
+}
+
+Node* ContentDistribution::previousTo(const Node* node) const
+{
+    size_t index = find(node);
+    if (index == notFound || !index)
+        return 0;
+    return at(index - 1).get();
+}
+
+
+ScopeContentDistribution::ScopeContentDistribution()
+    : m_insertionPointAssignedTo(0)
+    , m_numberOfShadowElementChildren(0)
+    , m_numberOfContentElementChildren(0)
+    , m_numberOfElementShadowChildren(0)
+    , m_insertionPointListIsValid(false)
+{
+}
+
+void ScopeContentDistribution::invalidateInsertionPointList()
+{
+    m_insertionPointListIsValid = false;
+    m_insertionPointList.clear();
+}
+
+const Vector<RefPtr<InsertionPoint> >& ScopeContentDistribution::ensureInsertionPointList(ShadowRoot* shadowRoot)
+{
+    if (m_insertionPointListIsValid)
+        return m_insertionPointList;
+
+    m_insertionPointListIsValid = true;
+    ASSERT(m_insertionPointList.isEmpty());
+
+    if (!hasInsertionPoint(shadowRoot))
+        return m_insertionPointList;
+
+    for (Element* element = ElementTraversal::firstWithin(shadowRoot); element; element = ElementTraversal::next(element, shadowRoot)) {
+        if (element->isInsertionPoint())
+            m_insertionPointList.append(toInsertionPoint(element));
+    }
+
+    return m_insertionPointList;
+}
+
+void ScopeContentDistribution::registerInsertionPoint(InsertionPoint* point)
+{
+    switch (point->insertionPointType()) {
+    case InsertionPoint::ShadowInsertionPoint:
+        ++m_numberOfShadowElementChildren;
+        break;
+    case InsertionPoint::ContentInsertionPoint:
+        ++m_numberOfContentElementChildren;
+        break;
+    }
+
+    invalidateInsertionPointList();
+}
+
+void ScopeContentDistribution::unregisterInsertionPoint(InsertionPoint* point)
+{
+    switch (point->insertionPointType()) {
+    case InsertionPoint::ShadowInsertionPoint:
+        ASSERT(m_numberOfShadowElementChildren > 0);
+        --m_numberOfShadowElementChildren;
+        break;
+    case InsertionPoint::ContentInsertionPoint:
+        ASSERT(m_numberOfContentElementChildren > 0);
+        --m_numberOfContentElementChildren;
+        break;
+    }
+
+    invalidateInsertionPointList();
+}
+
+bool ScopeContentDistribution::hasShadowElement(const ShadowRoot* holder)
+{
+    if (!holder->scopeDistribution())
+        return false;
+
+    return holder->scopeDistribution()->hasShadowElementChildren();
+}
+
+bool ScopeContentDistribution::hasContentElement(const ShadowRoot* holder)
+{
+    if (!holder->scopeDistribution())
+        return false;
+
+    return holder->scopeDistribution()->hasContentElementChildren();
+}
+
+unsigned ScopeContentDistribution::countElementShadow(const ShadowRoot* holder)
+{
+    if (!holder->scopeDistribution())
+        return 0;
+
+    return holder->scopeDistribution()->numberOfElementShadowChildren();
+}
+
+bool ScopeContentDistribution::hasInsertionPoint(const ShadowRoot* holder)
+{
+    return hasShadowElement(holder) || hasContentElement(holder);
+}
+
+InsertionPoint* ScopeContentDistribution::assignedTo(const ShadowRoot* holder)
+{
+    if (!holder->scopeDistribution())
+        return 0;
+
+    return holder->scopeDistribution()->insertionPointAssignedTo();
+}
+
+ContentDistributor::ContentDistributor()
+    : m_needsSelectFeatureSet(false)
+    , m_validity(Undetermined)
+{
+}
+
+ContentDistributor::~ContentDistributor()
+{
+}
+
+InsertionPoint* ContentDistributor::findInsertionPointFor(const Node* key) const
+{
+    return m_nodeToInsertionPoint.get(key);
+}
+
+void ContentDistributor::populate(Node* node, ContentDistribution& pool)
+{
+    if (!isActiveInsertionPoint(node)) {
+        pool.append(node);
+        return;
+    }
+
+    InsertionPoint* insertionPoint = toInsertionPoint(node);
+    if (insertionPoint->hasDistribution()) {
+        for (size_t i = 0; i < insertionPoint->size(); ++i)
+            populate(insertionPoint->at(i), pool);
+    } else {
+        for (Node* fallbackNode = insertionPoint->firstChild(); fallbackNode; fallbackNode = fallbackNode->nextSibling())
+            pool.append(fallbackNode);
+    }
+}
+
+void ContentDistributor::distribute(Element* host)
+{
+    ASSERT(needsDistribution());
+    ASSERT(m_nodeToInsertionPoint.isEmpty());
+    ASSERT(!host->containingShadowRoot() || host->containingShadowRoot()->owner()->distributor().isValid());
+
+    m_validity = Valid;
+
+    ContentDistribution pool;
+    for (Node* node = host->firstChild(); node; node = node->nextSibling())
+        populate(node, pool);
+
+    Vector<bool> distributed(pool.size());
+    distributed.fill(false);
+
+    Vector<HTMLShadowElement*, 8> activeShadowInsertionPoints;
+    for (ShadowRoot* root = host->youngestShadowRoot(); root; root = root->olderShadowRoot()) {
+        HTMLShadowElement* firstActiveShadowInsertionPoint = 0;
+
+        if (ScopeContentDistribution* scope = root->scopeDistribution()) {
+            const Vector<RefPtr<InsertionPoint> >& insertionPoints = scope->ensureInsertionPointList(root);
+            for (size_t i = 0; i < insertionPoints.size(); ++i) {
+                InsertionPoint* point = insertionPoints[i].get();
+                if (!point->isActive())
+                    continue;
+
+                if (isHTMLShadowElement(point)) {
+                    if (!firstActiveShadowInsertionPoint)
+                        firstActiveShadowInsertionPoint = toHTMLShadowElement(point);
+                } else {
+                    distributeSelectionsTo(point, pool, distributed);
+                    if (ElementShadow* shadow = point->parentNode()->isElementNode() ? toElement(point->parentNode())->shadow() : 0)
+                        shadow->invalidateDistribution();
+                }
+            }
+        }
+
+        if (firstActiveShadowInsertionPoint)
+            activeShadowInsertionPoints.append(firstActiveShadowInsertionPoint);
+    }
+
+    for (size_t i = activeShadowInsertionPoints.size(); i > 0; --i) {
+        HTMLShadowElement* shadowElement = activeShadowInsertionPoints[i - 1];
+        ShadowRoot* root = shadowElement->containingShadowRoot();
+        ASSERT(root);
+        if (root->olderShadowRoot()) {
+            distributeNodeChildrenTo(shadowElement, root->olderShadowRoot());
+            root->olderShadowRoot()->ensureScopeDistribution()->setInsertionPointAssignedTo(shadowElement);
+        } else {
+            distributeSelectionsTo(shadowElement, pool, distributed);
+            if (ElementShadow* shadow = shadowElement->parentNode()->isElementNode() ? toElement(shadowElement->parentNode())->shadow() : 0)
+                shadow->invalidateDistribution();
+        }
+    }
+}
+
+bool ContentDistributor::invalidate(Element* host)
+{
+    ASSERT(needsInvalidation());
+    bool needsReattach = (m_validity == Undetermined) || !m_nodeToInsertionPoint.isEmpty();
+
+    for (ShadowRoot* root = host->youngestShadowRoot(); root; root = root->olderShadowRoot()) {
+        if (ScopeContentDistribution* scope = root->scopeDistribution()) {
+            scope->setInsertionPointAssignedTo(0);
+            const Vector<RefPtr<InsertionPoint> >& insertionPoints = scope->ensureInsertionPointList(root);
+            for (size_t i = 0; i < insertionPoints.size(); ++i) {
+                needsReattach = needsReattach || true;
+                insertionPoints[i]->clearDistribution();
+
+                // After insertionPoint's distribution is invalidated, its reprojection should also be invalidated.
+                if (!insertionPoints[i]->isActive())
+                    continue;
+
+                if (Element* parent = insertionPoints[i]->parentElement()) {
+                    if (ElementShadow* shadow = parent->shadow())
+                        shadow->invalidateDistribution();
+                }
+            }
+        }
+    }
+
+    m_validity = Invalidating;
+    m_nodeToInsertionPoint.clear();
+    return needsReattach;
+}
+
+void ContentDistributor::distributeSelectionsTo(InsertionPoint* insertionPoint, const ContentDistribution& pool, Vector<bool>& distributed)
+{
+    ContentDistribution distribution;
+    ContentSelectorQuery query(insertionPoint);
+
+    for (size_t i = 0; i < pool.size(); ++i) {
+        if (distributed[i])
+            continue;
+
+        if (!query.matches(pool.nodes(), i))
+            continue;
+
+        Node* child = pool.at(i).get();
+        distribution.append(child);
+        m_nodeToInsertionPoint.add(child, insertionPoint);
+        distributed[i] = true;
+    }
+
+    insertionPoint->setDistribution(distribution);
+}
+
+void ContentDistributor::distributeNodeChildrenTo(InsertionPoint* insertionPoint, ContainerNode* containerNode)
+{
+    ContentDistribution distribution;
+    for (Node* node = containerNode->firstChild(); node; node = node->nextSibling()) {
+        if (isActiveInsertionPoint(node)) {
+            InsertionPoint* innerInsertionPoint = toInsertionPoint(node);
+            if (innerInsertionPoint->hasDistribution()) {
+                for (size_t i = 0; i < innerInsertionPoint->size(); ++i) {
+                    distribution.append(innerInsertionPoint->at(i));
+                    if (!m_nodeToInsertionPoint.contains(innerInsertionPoint->at(i)))
+                        m_nodeToInsertionPoint.add(innerInsertionPoint->at(i), insertionPoint);
+                }
+            } else {
+                for (Node* child = innerInsertionPoint->firstChild(); child; child = child->nextSibling()) {
+                    distribution.append(child);
+                    m_nodeToInsertionPoint.add(child, insertionPoint);
+                }
+            }
+        } else {
+            distribution.append(node);
+            if (!m_nodeToInsertionPoint.contains(node))
+                m_nodeToInsertionPoint.add(node, insertionPoint);
+        }
+    }
+
+    insertionPoint->setDistribution(distribution);
+}
+
+void ContentDistributor::ensureDistribution(ShadowRoot* shadowRoot)
+{
+    ASSERT(shadowRoot);
+
+    Vector<ElementShadow*, 8> elementShadows;
+    for (Element* current = shadowRoot->host(); current; current = current->shadowHost()) {
+        ElementShadow* elementShadow = current->shadow();
+        if (!elementShadow->distributor().needsDistribution())
+            break;
+
+        elementShadows.append(elementShadow);
+    }
+
+    for (size_t i = elementShadows.size(); i > 0; --i)
+        elementShadows[i - 1]->distributor().distribute(elementShadows[i - 1]->host());
+}
+
+
+void ContentDistributor::invalidateDistribution(Element* host)
+{
+    bool didNeedInvalidation = needsInvalidation();
+    bool needsReattach = didNeedInvalidation ? invalidate(host) : false;
+
+    if (needsReattach && host->attached()) {
+        for (Node* n = host->firstChild(); n; n = n->nextSibling())
+            n->lazyReattach();
+        host->setNeedsStyleRecalc();
+    }
+
+    if (didNeedInvalidation) {
+        ASSERT(m_validity == Invalidating);
+        m_validity = Invalidated;
+    }
+}
+
+const SelectRuleFeatureSet& ContentDistributor::ensureSelectFeatureSet(ElementShadow* shadow)
+{
+    if (!m_needsSelectFeatureSet)
+        return m_selectFeatures;
+
+    m_selectFeatures.clear();
+    for (ShadowRoot* root = shadow->oldestShadowRoot(); root; root = root->youngerShadowRoot())
+        collectSelectFeatureSetFrom(root);
+    m_needsSelectFeatureSet = false;
+    return m_selectFeatures;
+}
+
+void ContentDistributor::collectSelectFeatureSetFrom(ShadowRoot* root)
+{
+    if (ScopeContentDistribution::hasElementShadow(root)) {
+        for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(element)) {
+            if (ElementShadow* elementShadow = element->shadow())
+                m_selectFeatures.add(elementShadow->distributor().ensureSelectFeatureSet(elementShadow));
+        }
+    }
+
+    if (ScopeContentDistribution::hasContentElement(root)) {
+        for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(element)) {
+            if (!isHTMLContentElement(element))
+                continue;
+            const CSSSelectorList& list = toHTMLContentElement(element)->selectorList();
+            for (const CSSSelector* selector = list.first(); selector; selector = CSSSelectorList::next(selector)) {
+                for (const CSSSelector* component = selector; component; component = component->tagHistory())
+                    m_selectFeatures.collectFeaturesFromSelector(component);
+            }
+        }
+    }
+}
+
+void ContentDistributor::didAffectSelector(Element* host, AffectedSelectorMask mask)
+{
+    if (ensureSelectFeatureSet(host->shadow()).hasSelectorFor(mask))
+        invalidateDistribution(host);
+}
+
+void ContentDistributor::willAffectSelector(Element* host)
+{
+    for (ElementShadow* shadow = host->shadow(); shadow; shadow = shadow->containingShadow()) {
+        if (shadow->distributor().needsSelectFeatureSet())
+            break;
+        shadow->distributor().setNeedsSelectFeatureSet();
+    }
+
+    invalidateDistribution(host);
+}
+
+void ContentDistributor::didShadowBoundaryChange(Element* host)
+{
+    setValidity(Undetermined);
+    invalidateDistribution(host);
+}
+
+}
diff --git a/Source/core/dom/shadow/ContentDistributor.h b/Source/core/dom/shadow/ContentDistributor.h
new file mode 100644
index 0000000..91a480c
--- /dev/null
+++ b/Source/core/dom/shadow/ContentDistributor.h
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ContentDistributor_h
+#define ContentDistributor_h
+
+#include "core/dom/shadow/SelectRuleFeatureSet.h"
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class ContainerNode;
+class Element;
+class InsertionPoint;
+class Node;
+class ShadowRoot;
+
+class ContentDistribution {
+public:
+    PassRefPtr<Node> first() const { return m_nodes.first(); }
+    PassRefPtr<Node> last() const { return m_nodes.last(); }
+    PassRefPtr<Node> at(size_t index) const { return m_nodes.at(index); }
+
+    size_t size() const { return m_nodes.size(); }
+    bool isEmpty() const { return m_nodes.isEmpty(); }
+
+    void append(PassRefPtr<Node>);
+    void clear() { m_nodes.clear(); m_indices.clear(); }
+
+    bool contains(const Node* node) const { return m_indices.contains(node); }
+    size_t find(const Node*) const;
+    Node* nextTo(const Node*) const;
+    Node* previousTo(const Node*) const;
+
+    void swap(ContentDistribution& other);
+
+    const Vector<RefPtr<Node> >& nodes() const { return m_nodes; }
+
+private:
+    Vector<RefPtr<Node> > m_nodes;
+    HashMap<const Node*, size_t> m_indices;
+};
+
+class ScopeContentDistribution {
+public:
+    ScopeContentDistribution();
+
+    InsertionPoint* insertionPointAssignedTo() const { return m_insertionPointAssignedTo; }
+    void setInsertionPointAssignedTo(InsertionPoint* insertionPoint) { m_insertionPointAssignedTo = insertionPoint; }
+
+    void registerInsertionPoint(InsertionPoint*);
+    void unregisterInsertionPoint(InsertionPoint*);
+    bool hasShadowElementChildren() const { return m_numberOfShadowElementChildren > 0; }
+    bool hasContentElementChildren() const { return m_numberOfContentElementChildren > 0; }
+
+    void registerElementShadow() { ++m_numberOfElementShadowChildren; }
+    void unregisterElementShadow() { ASSERT(m_numberOfElementShadowChildren > 0); --m_numberOfElementShadowChildren; }
+    unsigned numberOfElementShadowChildren() const { return m_numberOfElementShadowChildren; }
+    bool hasElementShadowChildren() const { return m_numberOfElementShadowChildren > 0; }
+
+    void invalidateInsertionPointList();
+    const Vector<RefPtr<InsertionPoint> >& ensureInsertionPointList(ShadowRoot*);
+
+    bool isUsedForRendering() const;
+
+    static bool hasShadowElement(const ShadowRoot*);
+    static bool hasContentElement(const ShadowRoot*);
+    static bool hasInsertionPoint(const ShadowRoot*);
+    static bool hasElementShadow(const ShadowRoot* holder) { return countElementShadow(holder); }
+    static unsigned countElementShadow(const ShadowRoot*);
+    static InsertionPoint* assignedTo(const ShadowRoot*);
+
+private:
+    InsertionPoint* m_insertionPointAssignedTo;
+    unsigned m_numberOfShadowElementChildren;
+    unsigned m_numberOfContentElementChildren;
+    unsigned m_numberOfElementShadowChildren;
+    bool m_insertionPointListIsValid;
+    Vector<RefPtr<InsertionPoint> > m_insertionPointList;
+};
+
+class ContentDistributor {
+    WTF_MAKE_NONCOPYABLE(ContentDistributor);
+public:
+    enum Validity {
+        Valid = 0,
+        Invalidated = 1,
+        Invalidating = 2,
+        Undetermined = 3
+    };
+
+    ContentDistributor();
+    ~ContentDistributor();
+
+    InsertionPoint* findInsertionPointFor(const Node* key) const;
+    const SelectRuleFeatureSet& ensureSelectFeatureSet(ElementShadow*);
+
+    void distributeSelectionsTo(InsertionPoint*, const ContentDistribution& pool, Vector<bool>& distributed);
+    void distributeNodeChildrenTo(InsertionPoint*, ContainerNode*);
+
+    void invalidateDistribution(Element* host);
+    void didShadowBoundaryChange(Element* host);
+    void didAffectSelector(Element* host, AffectedSelectorMask);
+    void willAffectSelector(Element* host);
+
+    static void ensureDistribution(ShadowRoot*);
+
+private:
+    void distribute(Element* host);
+    bool invalidate(Element* host);
+    void populate(Node*, ContentDistribution&);
+
+    void collectSelectFeatureSetFrom(ShadowRoot*);
+    bool needsSelectFeatureSet() const { return m_needsSelectFeatureSet; }
+    void setNeedsSelectFeatureSet() { m_needsSelectFeatureSet = true; }
+
+    void setValidity(Validity validity) { m_validity = validity; }
+    bool isValid() const { return m_validity == Valid; }
+    bool needsDistribution() const;
+    bool needsInvalidation() const { return m_validity != Invalidated; }
+
+    HashMap<const Node*, RefPtr<InsertionPoint> > m_nodeToInsertionPoint;
+    SelectRuleFeatureSet m_selectFeatures;
+    unsigned m_needsSelectFeatureSet : 1;
+    unsigned m_validity : 2;
+};
+
+inline bool ContentDistributor::needsDistribution() const
+{
+    // During the invalidation, re-distribution should be supressed.
+    return m_validity != Valid && m_validity != Invalidating;
+}
+
+}
+
+#endif
diff --git a/Source/core/dom/shadow/ContentSelectorQuery.cpp b/Source/core/dom/shadow/ContentSelectorQuery.cpp
new file mode 100644
index 0000000..17c5aae
--- /dev/null
+++ b/Source/core/dom/shadow/ContentSelectorQuery.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/shadow/ContentSelectorQuery.h"
+
+#include "core/css/CSSSelectorList.h"
+#include "core/css/SelectorChecker.h"
+#include "core/css/SiblingTraversalStrategies.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
+
+namespace WebCore {
+
+bool ContentSelectorDataList::checkContentSelector(const CSSSelector* selector, const Vector<RefPtr<Node> >& siblings, int nth)
+{
+    Element* element = toElement(siblings[nth].get());
+    SelectorChecker selectorChecker(element->document(), SelectorChecker::CollectingRules);
+    SelectorChecker::SelectorCheckingContext context(selector, element, SelectorChecker::VisitedMatchEnabled);
+    ShadowDOMSiblingTraversalStrategy strategy(siblings, nth);
+    PseudoId ignoreDynamicPseudo = NOPSEUDO;
+    return selectorChecker.match(context, ignoreDynamicPseudo, strategy) == SelectorChecker::SelectorMatches;
+}
+
+void ContentSelectorDataList::initialize(const CSSSelectorList& selectors)
+{
+    for (const CSSSelector* selector = selectors.first(); selector; selector = CSSSelectorList::next(selector))
+        m_selectors.append(selector);
+}
+
+bool ContentSelectorDataList::matches(const Vector<RefPtr<Node> >& siblings, int nth) const
+{
+    unsigned selectorCount = m_selectors.size();
+    for (unsigned i = 0; i < selectorCount; ++i) {
+        if (checkContentSelector(m_selectors[i], siblings, nth))
+            return true;
+    }
+    return false;
+}
+
+ContentSelectorQuery::ContentSelectorQuery(InsertionPoint* insertionPoint)
+    : m_insertionPoint(insertionPoint)
+{
+    m_selectors.initialize(insertionPoint->selectorList());
+}
+
+bool ContentSelectorQuery::matches(const Vector<RefPtr<Node> >& siblings, int nth) const
+{
+    Node* node = siblings[nth].get();
+    ASSERT(node);
+
+    switch (m_insertionPoint->matchTypeFor(node)) {
+    case InsertionPoint::AlwaysMatches:
+        return true;
+    case InsertionPoint::NeverMatches:
+        return false;
+    case InsertionPoint::HasToMatchSelector:
+        return node->isElementNode() && m_selectors.matches(siblings, nth);
+    default:
+        ASSERT_NOT_REACHED();
+        return false;
+    }
+}
+
+}
diff --git a/Source/core/dom/shadow/ContentSelectorQuery.h b/Source/core/dom/shadow/ContentSelectorQuery.h
new file mode 100644
index 0000000..fd7cd82
--- /dev/null
+++ b/Source/core/dom/shadow/ContentSelectorQuery.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ContentSelectorQuery_h
+#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"
+
+namespace WebCore {
+
+class Document;
+class Node;
+class InsertionPoint;
+
+class ContentSelectorDataList {
+public:
+    void initialize(const CSSSelectorList&);
+    bool matches(const Vector<RefPtr<Node> >& siblings, int nthNode) const;
+
+private:
+    static bool checkContentSelector(const CSSSelector*, const Vector<RefPtr<Node> >& siblings, int nthNode);
+
+    Vector<const CSSSelector*> m_selectors;
+};
+
+class ContentSelectorQuery {
+    WTF_MAKE_NONCOPYABLE(ContentSelectorQuery);
+public:
+    explicit ContentSelectorQuery(InsertionPoint*);
+
+    bool matches(const Vector<RefPtr<Node> >& siblings, int nthNode) const;
+
+private:
+    InsertionPoint* m_insertionPoint;
+    ContentSelectorDataList m_selectors;
+};
+
+}
+
+#endif
diff --git a/Source/core/dom/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
similarity index 98%
rename from Source/core/dom/ElementShadow.cpp
rename to Source/core/dom/shadow/ElementShadow.cpp
index 9fe6b93..f40edc3 100644
--- a/Source/core/dom/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/dom/ElementShadow.h"
+#include "core/dom/shadow/ElementShadow.h"
 
 #include "core/dom/ContainerNodeAlgorithms.h"
 #include "core/inspector/InspectorInstrumentation.h"
diff --git a/Source/core/dom/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
similarity index 92%
rename from Source/core/dom/ElementShadow.h
rename to Source/core/dom/shadow/ElementShadow.h
index 3276f65..914471b 100644
--- a/Source/core/dom/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -28,18 +28,18 @@
 #define ElementShadow_h
 
 #include "core/dom/ExceptionCode.h"
-#include "core/dom/ShadowRoot.h"
-#include "core/html/shadow/ContentDistributor.h"
-#include <wtf/DoublyLinkedList.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/Vector.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 {
 
 class ElementShadow {
-   WTF_MAKE_NONCOPYABLE(ElementShadow); WTF_MAKE_FAST_ALLOCATED;
+    WTF_MAKE_NONCOPYABLE(ElementShadow); WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassOwnPtr<ElementShadow> create()
     {
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
new file mode 100644
index 0000000..8e905c7
--- /dev/null
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -0,0 +1,256 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/shadow/InsertionPoint.h"
+
+#include "HTMLNames.h"
+#include "core/dom/QualifiedName.h"
+#include "core/dom/StaticNodeList.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+InsertionPoint::InsertionPoint(const QualifiedName& tagName, Document* document)
+    : HTMLElement(tagName, document, CreateInsertionPoint)
+    , m_registeredWithShadowRoot(false)
+{
+}
+
+InsertionPoint::~InsertionPoint()
+{
+}
+
+void InsertionPoint::attach()
+{
+    if (ShadowRoot* shadowRoot = containingShadowRoot())
+        ContentDistributor::ensureDistribution(shadowRoot);
+    for (size_t i = 0; i < m_distribution.size(); ++i) {
+        if (!m_distribution.at(i)->attached())
+            m_distribution.at(i)->attach();
+    }
+
+    HTMLElement::attach();
+}
+
+void InsertionPoint::detach()
+{
+    if (ShadowRoot* shadowRoot = containingShadowRoot())
+        ContentDistributor::ensureDistribution(shadowRoot);
+
+    for (size_t i = 0; i < m_distribution.size(); ++i)
+        m_distribution.at(i)->detach();
+
+    HTMLElement::detach();
+}
+
+bool InsertionPoint::shouldUseFallbackElements() const
+{
+    return isActive() && !hasDistribution();
+}
+
+bool InsertionPoint::isShadowBoundary() const
+{
+    return treeScope()->rootNode()->isShadowRoot() && isActive();
+}
+
+bool InsertionPoint::isActive() const
+{
+    if (!containingShadowRoot())
+        return false;
+    const Node* node = parentNode();
+    while (node) {
+        if (node->isInsertionPoint())
+            return false;
+
+        node = node->parentNode();
+    }
+    return true;
+}
+
+PassRefPtr<NodeList> InsertionPoint::getDistributedNodes() const
+{
+    if (ShadowRoot* shadowRoot = containingShadowRoot())
+        ContentDistributor::ensureDistribution(shadowRoot);
+
+    Vector<RefPtr<Node> > nodes;
+
+    for (size_t i = 0; i < m_distribution.size(); ++i)
+        nodes.append(m_distribution.at(i));
+
+    return StaticNodeList::adopt(nodes);
+}
+
+bool InsertionPoint::rendererIsNeeded(const NodeRenderingContext& context)
+{
+    return !isShadowBoundary() && HTMLElement::rendererIsNeeded(context);
+}
+
+void InsertionPoint::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
+{
+    HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+    if (ShadowRoot* root = containingShadowRoot())
+        if (ElementShadow* rootOwner = root->owner())
+            rootOwner->invalidateDistribution();
+}
+
+Node::InsertionNotificationRequest InsertionPoint::insertedInto(ContainerNode* insertionPoint)
+{
+    HTMLElement::insertedInto(insertionPoint);
+
+    if (ShadowRoot* root = containingShadowRoot()) {
+        if (ElementShadow* rootOwner = root->owner()) {
+            rootOwner->distributor().didShadowBoundaryChange(root->host());
+            if (isActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope()->rootNode() == root) {
+                m_registeredWithShadowRoot = true;
+                root->ensureScopeDistribution()->registerInsertionPoint(this);
+                if (canAffectSelector())
+                    rootOwner->willAffectSelector();
+            }
+        }
+    }
+
+    return InsertionDone;
+}
+
+void InsertionPoint::removedFrom(ContainerNode* insertionPoint)
+{
+    ShadowRoot* root = containingShadowRoot();
+    if (!root)
+        root = insertionPoint->containingShadowRoot();
+
+    // host can be null when removedFrom() is called from ElementShadow destructor.
+    ElementShadow* rootOwner = root ? root->owner() : 0;
+    if (rootOwner)
+        rootOwner->invalidateDistribution();
+
+    // Since this insertion point is no longer visible from the shadow subtree, it need to clean itself up.
+    clearDistribution();
+
+    if (m_registeredWithShadowRoot && insertionPoint->treeScope()->rootNode() == root) {
+        ASSERT(root);
+        m_registeredWithShadowRoot = false;
+        root->ensureScopeDistribution()->unregisterInsertionPoint(this);
+        if (rootOwner && canAffectSelector())
+            rootOwner->willAffectSelector();
+    }
+
+    HTMLElement::removedFrom(insertionPoint);
+}
+
+void InsertionPoint::parseAttribute(const QualifiedName& name, const AtomicString& value)
+{
+    if (name == reset_style_inheritanceAttr) {
+        if (!inDocument() || !attached() || !isActive())
+            return;
+        containingShadowRoot()->host()->setNeedsStyleRecalc();
+    } else
+        HTMLElement::parseAttribute(name, value);
+}
+
+bool InsertionPoint::resetStyleInheritance() const
+{
+    return fastHasAttribute(reset_style_inheritanceAttr);
+}
+
+void InsertionPoint::setResetStyleInheritance(bool value)
+{
+    setBooleanAttribute(reset_style_inheritanceAttr, value);
+}
+
+bool InsertionPoint::contains(const Node* node) const
+{
+    return m_distribution.contains(const_cast<Node*>(node)) || (node->isShadowRoot() && ScopeContentDistribution::assignedTo(toShadowRoot(node)) == this);
+}
+
+const CSSSelectorList& InsertionPoint::emptySelectorList()
+{
+    DEFINE_STATIC_LOCAL(CSSSelectorList, selectorList, (CSSSelectorList()));
+    return selectorList;
+}
+
+InsertionPoint* resolveReprojection(const Node* projectedNode)
+{
+    InsertionPoint* insertionPoint = 0;
+    const Node* current = projectedNode;
+
+    while (current) {
+        if (ElementShadow* shadow = shadowOfParentForDistribution(current)) {
+            if (ShadowRoot* root = current->containingShadowRoot())
+                ContentDistributor::ensureDistribution(root);
+            if (InsertionPoint* insertedTo = shadow->distributor().findInsertionPointFor(projectedNode)) {
+                current = insertedTo;
+                insertionPoint = insertedTo;
+                continue;
+            }
+        }
+
+        if (Node* parent = parentNodeForDistribution(current)) {
+            if (InsertionPoint* insertedTo = parent->isShadowRoot() ? ScopeContentDistribution::assignedTo(toShadowRoot(parent)) : 0) {
+                current = insertedTo;
+                insertionPoint = insertedTo;
+                continue;
+            }
+        }
+
+        break;
+    }
+
+    return insertionPoint;
+}
+
+void collectInsertionPointsWhereNodeIsDistributed(const Node* node, Vector<InsertionPoint*, 8>& results)
+{
+    const Node* current = node;
+    while (true) {
+        if (ElementShadow* shadow = shadowOfParentForDistribution(current)) {
+            if (ShadowRoot* root = current->containingShadowRoot())
+                ContentDistributor::ensureDistribution(root);
+            if (InsertionPoint* insertedTo = shadow->distributor().findInsertionPointFor(node)) {
+                current = insertedTo;
+                results.append(insertedTo);
+                continue;
+            }
+        }
+        if (Node* parent = parentNodeForDistribution(current)) {
+            if (InsertionPoint* insertedTo = parent->isShadowRoot() ? ScopeContentDistribution::assignedTo(toShadowRoot(parent)) : 0) {
+                current = insertedTo;
+                results.append(insertedTo);
+                continue;
+            }
+        }
+        return;
+    }
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/shadow/InsertionPoint.h b/Source/core/dom/shadow/InsertionPoint.h
new file mode 100644
index 0000000..cbc5afb
--- /dev/null
+++ b/Source/core/dom/shadow/InsertionPoint.h
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef 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"
+
+namespace WebCore {
+
+class InsertionPoint : public HTMLElement {
+public:
+    enum Type {
+        ShadowInsertionPoint,
+        ContentInsertionPoint
+    };
+
+    enum MatchType {
+        AlwaysMatches,
+        NeverMatches,
+        HasToMatchSelector
+    };
+
+    virtual ~InsertionPoint();
+
+    bool hasDistribution() const { return !m_distribution.isEmpty(); }
+    void setDistribution(ContentDistribution& distribution) { m_distribution.swap(distribution); }
+    void clearDistribution() { m_distribution.clear(); }
+    bool isShadowBoundary() const;
+    bool isActive() const;
+
+    PassRefPtr<NodeList> getDistributedNodes() const;
+
+    virtual MatchType matchTypeFor(Node*) { return AlwaysMatches; }
+    virtual const CSSSelectorList& selectorList() { return emptySelectorList(); }
+    virtual Type insertionPointType() const = 0;
+    virtual bool canAffectSelector() const { return false; }
+
+    bool resetStyleInheritance() const;
+    void setResetStyleInheritance(bool);
+
+    virtual void attach();
+    virtual void detach();
+
+    bool shouldUseFallbackElements() const;
+
+    size_t indexOf(Node* node) const { return m_distribution.find(node); }
+    bool contains(const Node*) const;
+    size_t size() const { return m_distribution.size(); }
+    Node* at(size_t index)  const { return m_distribution.at(index).get(); }
+    Node* first() const { return m_distribution.isEmpty() ? 0 : m_distribution.first().get(); }
+    Node* last() const { return m_distribution.isEmpty() ? 0 : m_distribution.last().get(); }
+    Node* nextTo(const Node* node) const { return m_distribution.nextTo(node); }
+    Node* previousTo(const Node* node) const { return m_distribution.previousTo(node); }
+
+    static const CSSSelectorList& emptySelectorList();
+
+protected:
+    InsertionPoint(const QualifiedName&, Document*);
+    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
+    virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
+    virtual void removedFrom(ContainerNode*) OVERRIDE;
+    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
+    virtual bool isInsertionPointNode() const OVERRIDE { return true; }
+
+private:
+
+    ContentDistribution m_distribution;
+    bool m_registeredWithShadowRoot;
+};
+
+inline InsertionPoint* toInsertionPoint(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isInsertionPoint());
+    return static_cast<InsertionPoint*>(node);
+}
+
+inline const InsertionPoint* toInsertionPoint(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isInsertionPoint());
+    return static_cast<const InsertionPoint*>(node);
+}
+
+inline bool isActiveInsertionPoint(const Node* node)
+{
+    return node->isInsertionPoint() && toInsertionPoint(node)->isActive();
+}
+
+inline bool isLowerEncapsulationBoundary(Node* node)
+{
+    if (!node || !node->isInsertionPoint())
+        return false;
+    return toInsertionPoint(node)->isShadowBoundary();
+}
+
+inline Node* parentNodeForDistribution(const Node* node)
+{
+    ASSERT(node);
+
+    if (Node* parent = node->parentNode()) {
+        if (parent->isInsertionPoint() && toInsertionPoint(parent)->shouldUseFallbackElements())
+            return parent->parentNode();
+        return parent;
+    }
+
+    return 0;
+}
+
+inline Element* parentElementForDistribution(const Node* node)
+{
+    if (Node* parent = parentNodeForDistribution(node)) {
+        if (parent->isElementNode())
+            return toElement(parent);
+    }
+
+    return 0;
+}
+
+inline ElementShadow* shadowOfParentForDistribution(const Node* node)
+{
+    ASSERT(node);
+    if (Element* parent = parentElementForDistribution(node))
+        return parent->shadow();
+
+    return 0;
+}
+
+InsertionPoint* resolveReprojection(const Node*);
+
+void collectInsertionPointsWhereNodeIsDistributed(const Node*, Vector<InsertionPoint*, 8>& results);
+
+} // namespace WebCore
+
+#endif // InsertionPoint_h
diff --git a/Source/core/dom/shadow/SelectRuleFeatureSet.cpp b/Source/core/dom/shadow/SelectRuleFeatureSet.cpp
new file mode 100644
index 0000000..4f6f526
--- /dev/null
+++ b/Source/core/dom/shadow/SelectRuleFeatureSet.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/shadow/SelectRuleFeatureSet.h"
+
+#include "core/css/CSSSelector.h"
+
+namespace WebCore {
+
+SelectRuleFeatureSet::SelectRuleFeatureSet()
+    : m_featureFlags(0)
+{
+}
+
+void SelectRuleFeatureSet::add(const SelectRuleFeatureSet& featureSet)
+{
+    m_cssRuleFeatureSet.add(featureSet.m_cssRuleFeatureSet);
+    m_featureFlags |= featureSet.m_featureFlags;
+}
+
+void SelectRuleFeatureSet::clear()
+{
+    m_cssRuleFeatureSet.clear();
+    m_featureFlags = 0;
+}
+
+void SelectRuleFeatureSet::collectFeaturesFromSelector(const CSSSelector* selector)
+{
+    m_cssRuleFeatureSet.collectFeaturesFromSelector(selector);
+
+    switch (selector->pseudoType()) {
+    case CSSSelector::PseudoChecked:
+        setSelectRuleFeature(AffectedSelectorChecked);
+        break;
+    case CSSSelector::PseudoEnabled:
+        setSelectRuleFeature(AffectedSelectorEnabled);
+        break;
+    case CSSSelector::PseudoDisabled:
+        setSelectRuleFeature(AffectedSelectorDisabled);
+        break;
+    case CSSSelector::PseudoIndeterminate:
+        setSelectRuleFeature(AffectedSelectorIndeterminate);
+        break;
+    case CSSSelector::PseudoLink:
+        setSelectRuleFeature(AffectedSelectorLink);
+        break;
+    case CSSSelector::PseudoTarget:
+        setSelectRuleFeature(AffectedSelectorTarget);
+        break;
+    case CSSSelector::PseudoVisited:
+        setSelectRuleFeature(AffectedSelectorVisited);
+        break;
+    default:
+        break;
+    }
+}
+
+}
+
diff --git a/Source/core/dom/shadow/SelectRuleFeatureSet.h b/Source/core/dom/shadow/SelectRuleFeatureSet.h
new file mode 100644
index 0000000..7292b12
--- /dev/null
+++ b/Source/core/dom/shadow/SelectRuleFeatureSet.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SelectRuleFeatureSet_h
+#define SelectRuleFeatureSet_h
+
+#include "core/css/RuleFeature.h"
+#include "core/dom/Element.h"
+
+namespace WebCore {
+
+class SelectRuleFeatureSet {
+public:
+    SelectRuleFeatureSet();
+
+    void add(const SelectRuleFeatureSet&);
+    void clear();
+    void collectFeaturesFromSelector(const CSSSelector*);
+
+    bool hasSelectorForId(const AtomicString&) const;
+    bool hasSelectorForClass(const AtomicString&) const;
+    bool hasSelectorForAttribute(const AtomicString&) const;
+
+    bool hasSelectorForChecked() const { return hasSelectorFor(AffectedSelectorChecked); }
+    bool hasSelectorForEnabled() const { return hasSelectorFor(AffectedSelectorEnabled); }
+    bool hasSelectorForDisabled() const { return hasSelectorFor(AffectedSelectorDisabled); }
+    bool hasSelectorForIndeterminate() const { return hasSelectorFor(AffectedSelectorIndeterminate); }
+    bool hasSelectorForLink() const { return hasSelectorFor(AffectedSelectorLink); }
+    bool hasSelectorForTarget() const { return hasSelectorFor(AffectedSelectorTarget); }
+    bool hasSelectorForVisited() const { return hasSelectorFor(AffectedSelectorVisited); }
+
+    bool hasSelectorFor(AffectedSelectorMask features) const { return m_featureFlags & features; }
+
+private:
+    void setSelectRuleFeature(AffectedSelectorType feature) { m_featureFlags |= feature; }
+
+    RuleFeatureSet m_cssRuleFeatureSet;
+    int m_featureFlags;
+};
+
+inline bool SelectRuleFeatureSet::hasSelectorForId(const AtomicString& idValue) const
+{
+    ASSERT(!idValue.isEmpty());
+    return m_cssRuleFeatureSet.idsInRules.contains(idValue.impl());
+}
+
+inline bool SelectRuleFeatureSet::hasSelectorForClass(const AtomicString& classValue) const
+{
+    ASSERT(!classValue.isEmpty());
+    return m_cssRuleFeatureSet.classesInRules.contains(classValue.impl());
+}
+
+inline bool SelectRuleFeatureSet::hasSelectorForAttribute(const AtomicString& attributeName) const
+{
+    ASSERT(!attributeName.isEmpty());
+    return m_cssRuleFeatureSet.attrsInRules.contains(attributeName.impl());
+}
+
+}
+
+#endif
diff --git a/Source/core/dom/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
similarity index 97%
rename from Source/core/dom/ShadowRoot.cpp
rename to Source/core/dom/shadow/ShadowRoot.cpp
index 47d3eb0..7c0aad9 100644
--- a/Source/core/dom/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -25,15 +25,15 @@
  */
 
 #include "config.h"
-#include "core/dom/ShadowRoot.h"
+#include "core/dom/shadow/ShadowRoot.h"
 
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/ElementShadow.h"
-#include "core/dom/Text.h"
-#include "core/editing/markup.h"
-#include "core/html/shadow/ContentDistributor.h"
-#include "core/html/shadow/InsertionPoint.h"
 #include "RuntimeEnabledFeatures.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/Text.h"
+#include "core/dom/shadow/ContentDistributor.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/editing/markup.h"
 #include "core/platform/HistogramSupport.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
similarity index 99%
rename from Source/core/dom/ShadowRoot.h
rename to Source/core/dom/shadow/ShadowRoot.h
index ce1ce4c..5188c4e 100644
--- a/Source/core/dom/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -33,7 +33,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/TreeScope.h"
-#include <wtf/DoublyLinkedList.h>
+#include "wtf/DoublyLinkedList.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ShadowRoot.idl b/Source/core/dom/shadow/ShadowRoot.idl
similarity index 98%
rename from Source/core/dom/ShadowRoot.idl
rename to Source/core/dom/shadow/ShadowRoot.idl
index 9fe8551..34190bc 100644
--- a/Source/core/dom/ShadowRoot.idl
+++ b/Source/core/dom/shadow/ShadowRoot.idl
@@ -34,7 +34,7 @@
     [TreatNullAs=NullString, DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
 
     [RaisesException] Node cloneNode([Default=Undefined] optional boolean deep);
-    DOMSelection getSelection();
+    Selection getSelection();
     Element getElementById([Default=Undefined] optional DOMString elementId);
     NodeList getElementsByClassName([Default=Undefined] optional DOMString className);
     NodeList getElementsByTagName([Default=Undefined] optional DOMString tagName);