Merge from Chromium at DEPS revision r213057

This commit was generated by merge_to_master.py.

Change-Id: If0dbdee1edae80ae428c081eb0ecd6ce3518559f
diff --git a/Source/core/dom/ChildNode.idl b/Source/core/dom/ChildNode.idl
index c5fdbba..80ba9f1 100644
--- a/Source/core/dom/ChildNode.idl
+++ b/Source/core/dom/ChildNode.idl
@@ -20,8 +20,10 @@
  * Boston, MA 02110-1301, USA.
  */
 
-[NoInterfaceObject]
-interface ChildNode {
+[
+    NoInterfaceObject,
+    LegacyImplementedInBaseClass
+] interface ChildNode {
     [PerWorldBindings] readonly attribute Element previousElementSibling;
     [PerWorldBindings] readonly attribute Element nextElementSibling;
     [RaisesException, DeliverCustomElementCallbacks] void remove();
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index d58f224..0738935 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -466,7 +466,7 @@
 
     RefPtr<Node> child = oldChild;
 
-    document()->removeFocusedNodeOfSubtree(child.get());
+    document()->removeFocusedElementOfSubtree(child.get());
 
     if (FullscreenController* fullscreen = FullscreenController::fromIfExists(document()))
         fullscreen->removeFullScreenElementOfSubtree(child.get());
@@ -562,11 +562,11 @@
     // and remove... e.g. stop loading frames, fire unload events.
     willRemoveChildren(protect.get());
 
-    // Exclude this node when looking for removed focusedNode since only
+    // Exclude this node when looking for removed focusedElement since only
     // children will be removed.
     // This must be later than willRemvoeChildren, which might change focus
     // state of a child.
-    document()->removeFocusedNodeOfSubtree(this, true);
+    document()->removeFocusedElementOfSubtree(this, true);
 
     NodeVector removedChildren;
     {
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.cpp b/Source/core/dom/CustomElementCallbackDispatcher.cpp
index 10db728..7904e73 100644
--- a/Source/core/dom/CustomElementCallbackDispatcher.cpp
+++ b/Source/core/dom/CustomElementCallbackDispatcher.cpp
@@ -47,49 +47,6 @@
     return instance;
 }
 
-void CustomElementCallbackDispatcher::enqueueAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
-{
-    if (!callbacks->hasAttributeChangedCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = scheduleInCurrentElementQueue(element);
-    queue->append(CustomElementCallbackInvocation::createAttributeChangedInvocation(callbacks, name, oldValue, newValue));
-}
-
-void CustomElementCallbackDispatcher::enqueueCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
-    if (!callbacks->hasCreatedCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = createCallbackQueue(element);
-    queue->setOwner(currentElementQueue());
-
-    // The created callback is unique in being prepended to the front
-    // of the element queue
-    m_flattenedProcessingStack.insert(inCallbackDeliveryScope() ? s_elementQueueStart : /* skip null sentinel */ 1, queue);
-    ++s_elementQueueEnd;
-
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
-}
-
-void CustomElementCallbackDispatcher::enqueueEnteredDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
-    if (!callbacks->hasEnteredDocumentCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = scheduleInCurrentElementQueue(element);
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::EnteredDocument));
-}
-
-void CustomElementCallbackDispatcher::enqueueLeftDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
-    if (!callbacks->hasLeftDocumentCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = scheduleInCurrentElementQueue(element);
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::LeftDocument));
-}
-
 // Dispatches callbacks at microtask checkpoint.
 bool CustomElementCallbackDispatcher::dispatch()
 {
@@ -168,7 +125,7 @@
 // its owner is set to the element queue on the top of the processing
 // stack. Because callback queues are processed exhaustively, this
 // effectively moves the callback queue to the top of the stack.
-CustomElementCallbackQueue* CustomElementCallbackDispatcher::scheduleInCurrentElementQueue(PassRefPtr<Element> element)
+CustomElementCallbackQueue* CustomElementCallbackDispatcher::ensureInCurrentElementQueue(PassRefPtr<Element> element)
 {
     CustomElementCallbackQueue* queue = ensureCallbackQueue(element);
     bool isInCurrentQueue = queue->owner() == currentElementQueue();
@@ -180,4 +137,17 @@
     return queue;
 }
 
+CustomElementCallbackQueue* CustomElementCallbackDispatcher::createAtFrontOfCurrentElementQueue(PassRefPtr<Element> element)
+{
+    CustomElementCallbackQueue* queue = createCallbackQueue(element);
+    queue->setOwner(currentElementQueue());
+
+    // The created callback is unique in being prepended to the front
+    // of the element queue
+    m_flattenedProcessingStack.insert(inCallbackDeliveryScope() ? s_elementQueueStart : /* skip null sentinel */ 1, queue);
+    ++s_elementQueueEnd;
+
+    return queue;
+}
+
 } // namespace WebCore
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.h b/Source/core/dom/CustomElementCallbackDispatcher.h
index 9b6f10d..4c44910 100644
--- a/Source/core/dom/CustomElementCallbackDispatcher.h
+++ b/Source/core/dom/CustomElementCallbackDispatcher.h
@@ -32,7 +32,6 @@
 #define CustomElementCallbackDispatcher_h
 
 #include "core/dom/CustomElementCallbackQueue.h"
-#include "core/dom/CustomElementLifecycleCallbacks.h"
 #include "core/dom/Element.h"
 #include "wtf/HashMap.h"
 #include "wtf/OwnPtr.h"
@@ -66,16 +65,17 @@
         size_t m_savedElementQueueStart;
     };
 
-    void enqueueAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
-    void enqueueCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-    void enqueueEnteredDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-    void enqueueLeftDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-
     // Returns true if more work may have to be performed at the
     // checkpoint by this or other workers (for example, this work
     // invoked author scripts)
     bool dispatch();
 
+protected:
+    friend class CustomElementCallbackScheduler;
+
+    CustomElementCallbackQueue* createAtFrontOfCurrentElementQueue(PassRefPtr<Element>);
+    CustomElementCallbackQueue* ensureInCurrentElementQueue(PassRefPtr<Element>);
+
 private:
     CustomElementCallbackDispatcher()
     {
@@ -107,7 +107,6 @@
 
     CustomElementCallbackQueue* createCallbackQueue(PassRefPtr<Element>);
     CustomElementCallbackQueue* ensureCallbackQueue(PassRefPtr<Element>);
-    CustomElementCallbackQueue* scheduleInCurrentElementQueue(PassRefPtr<Element>);
 
     // The processing stack, flattened. Element queues lower in the
     // stack appear toward the head of the vector. The first element
diff --git a/Source/core/dom/CustomElementCallbackInvocation.cpp b/Source/core/dom/CustomElementCallbackInvocation.cpp
index 2d81c89..38ea76d 100644
--- a/Source/core/dom/CustomElementCallbackInvocation.cpp
+++ b/Source/core/dom/CustomElementCallbackInvocation.cpp
@@ -31,7 +31,8 @@
 #include "config.h"
 #include "core/dom/CustomElementCallbackInvocation.h"
 
-#include "core/dom/CustomElementCallbackDispatcher.h"
+#include "core/dom/CustomElementCallbackScheduler.h"
+#include "core/dom/Element.h"
 
 namespace WebCore {
 
@@ -49,7 +50,7 @@
 void CreatedInvocation::dispatch(Element* element)
 {
     if (element->inDocument())
-        CustomElementCallbackDispatcher::instance().enqueueEnteredDocumentCallback(callbacks(), element);
+        CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(callbacks(), element);
     callbacks()->created(element);
 }
 
diff --git a/Source/core/dom/CustomElementCallbackScheduler.cpp b/Source/core/dom/CustomElementCallbackScheduler.cpp
new file mode 100644
index 0000000..4a95d2b
--- /dev/null
+++ b/Source/core/dom/CustomElementCallbackScheduler.cpp
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer
+ *    in the documentation and/or other materials provided with the
+ *    distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ *    may be used to endorse or promote products derived from this
+ *    software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/CustomElementCallbackScheduler.h"
+
+#include "core/dom/CustomElementCallbackDispatcher.h"
+#include "core/dom/CustomElementCallbackQueue.h"
+#include "core/dom/CustomElementLifecycleCallbacks.h"
+#include "core/dom/Element.h"
+
+namespace WebCore {
+
+void CustomElementCallbackScheduler::scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
+{
+    if (!callbacks->hasAttributeChangedCallback())
+        return;
+
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().ensureInCurrentElementQueue(element);
+    queue->append(CustomElementCallbackInvocation::createAttributeChangedInvocation(callbacks, name, oldValue, newValue));
+}
+
+void CustomElementCallbackScheduler::scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+    if (!callbacks->hasCreatedCallback())
+        return;
+
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().createAtFrontOfCurrentElementQueue(element);
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
+}
+
+void CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+    if (!callbacks->hasEnteredDocumentCallback())
+        return;
+
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().ensureInCurrentElementQueue(element);
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::EnteredDocument));
+}
+
+void CustomElementCallbackScheduler::scheduleLeftDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+    if (!callbacks->hasLeftDocumentCallback())
+        return;
+
+    CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().ensureInCurrentElementQueue(element);
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::LeftDocument));
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/CustomElementCallbackScheduler.h b/Source/core/dom/CustomElementCallbackScheduler.h
new file mode 100644
index 0000000..3f5194e
--- /dev/null
+++ b/Source/core/dom/CustomElementCallbackScheduler.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer
+ *    in the documentation and/or other materials provided with the
+ *    distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ *    may be used to endorse or promote products derived from this
+ *    software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementCallbackScheduler_h
+#define CustomElementCallbackScheduler_h
+
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class CustomElementLifecycleCallbacks;
+class Element;
+
+class CustomElementCallbackScheduler {
+public:
+    static void scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
+    static void scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+    static void scheduleEnteredDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+    static void scheduleLeftDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+
+private:
+    CustomElementCallbackScheduler();
+};
+
+}
+
+#endif // CustomElementCallbackScheduler_h
diff --git a/Source/core/dom/CustomElementRegistrationContext.cpp b/Source/core/dom/CustomElementRegistrationContext.cpp
index 57b43b6..4ed6abf 100644
--- a/Source/core/dom/CustomElementRegistrationContext.cpp
+++ b/Source/core/dom/CustomElementRegistrationContext.cpp
@@ -34,7 +34,7 @@
 #include "HTMLNames.h"
 #include "MathMLNames.h"
 #include "SVGNames.h"
-#include "core/dom/CustomElementCallbackDispatcher.h"
+#include "core/dom/CustomElementCallbackScheduler.h"
 #include "core/dom/CustomElementDefinition.h"
 #include "core/dom/CustomElementRegistry.h"
 #include "core/dom/CustomElementUpgradeCandidateMap.h"
@@ -145,7 +145,6 @@
         return Element::create(tagName, document);
     }
 
-    element->setIsCustomElement();
     resolve(element.get());
     return element.release();
 }
@@ -157,8 +156,6 @@
 
 void ActiveRegistrationContext::resolve(Element* element)
 {
-    ASSERT(element->isCustomElement());
-    ASSERT(!element->isUpgradedCustomElement());
     const CustomElementDescriptor& descriptor = describe(element);
     CustomElementDefinition* definition = m_registry.find(descriptor);
     if (definition)
@@ -169,16 +166,19 @@
 
 void ActiveRegistrationContext::didResolveElement(CustomElementDefinition* definition, Element* element)
 {
-    CustomElementCallbackDispatcher::instance().enqueueCreatedCallback(definition->callbacks(), element);
+    element->setCustomElementState(Element::Defined);
+    CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
 }
 
 void ActiveRegistrationContext::didCreateUnresolvedElement(const CustomElementDescriptor& descriptor, Element* element)
 {
+    element->setCustomElementState(Element::UpgradeCandidate);
     m_candidates.add(descriptor, element);
 }
 
 CustomElementDefinition* ActiveRegistrationContext::definitionFor(Element* element) const
 {
+    ASSERT(element->customElementState() == Element::Defined || element->customElementState() == Element::Upgraded);
     ASSERT(element->document()->registrationContext() == this);
     const CustomElementDescriptor& descriptor = describe(element);
     return m_registry.find(descriptor);
@@ -186,29 +186,29 @@
 
 void ActiveRegistrationContext::customElementAttributeDidChange(Element* element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
 {
-    ASSERT(element->isUpgradedCustomElement());
+    ASSERT(element->customElementState() == Element::Upgraded);
     CustomElementDefinition* definition = definitionFor(element);
-    CustomElementCallbackDispatcher::instance().enqueueAttributeChangedCallback(definition->callbacks(), element, name, oldValue, newValue);
+    CustomElementCallbackScheduler::scheduleAttributeChangedCallback(definition->callbacks(), element, name, oldValue, newValue);
 }
 
 void ActiveRegistrationContext::customElementDidEnterDocument(Element* element)
 {
-    ASSERT(element->isUpgradedCustomElement());
+    ASSERT(element->customElementState() == Element::Upgraded);
     CustomElementDefinition* definition = definitionFor(element);
-    CustomElementCallbackDispatcher::instance().enqueueEnteredDocumentCallback(definition->callbacks(), element);
+    CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(definition->callbacks(), element);
 }
 
 void ActiveRegistrationContext::customElementDidLeaveDocument(Element* element)
 {
-    ASSERT(element->isUpgradedCustomElement());
+    ASSERT(element->customElementState() == Element::Upgraded);
     CustomElementDefinition* definition = definitionFor(element);
-    CustomElementCallbackDispatcher::instance().enqueueLeftDocumentCallback(definition->callbacks(), element);
+    CustomElementCallbackScheduler::scheduleLeftDocumentCallback(definition->callbacks(), element);
 }
 
 void ActiveRegistrationContext::customElementIsBeingDestroyed(Element* element)
 {
-    CustomElementRegistrationContext::customElementIsBeingDestroyed(element);
     m_candidates.remove(element);
+    CustomElementRegistrationContext::customElementIsBeingDestroyed(element);
 }
 
 PassRefPtr<CustomElementRegistrationContext> CustomElementRegistrationContext::create()
@@ -246,8 +246,6 @@
 
 CustomElementDescriptor CustomElementRegistrationContext::describe(Element* element)
 {
-    ASSERT(element->isCustomElement());
-
     // If an element has a custom tag name it takes precedence over
     // the "is" attribute (if any).
     const AtomicString& type = isCustomTagName(element->localName())
@@ -275,7 +273,6 @@
 
     TypeExtensionMap::AddResult result = typeExtensionMap()->add(element, type);
     ASSERT(result.isNewEntry); // Type extensions should only be set once
-    element->setIsCustomElement();
     element->document()->registrationContext()->didGiveTypeExtension(element);
 }
 
diff --git a/Source/core/dom/CustomElementUpgradeCandidateMap.cpp b/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
index 0c3049a..e3bcd0d 100644
--- a/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
+++ b/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
@@ -45,13 +45,14 @@
 
 void CustomElementUpgradeCandidateMap::remove(Element* element)
 {
-    UpgradeCandidateMap::iterator it = m_upgradeCandidates.find(element);
-    if (it == m_upgradeCandidates.end())
+    UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
+    if (candidate == m_upgradeCandidates.end())
         return;
 
-    const CustomElementDescriptor& descriptor = it->value;
-    m_unresolvedDefinitions.get(descriptor).remove(element);
-    m_upgradeCandidates.remove(it);
+    UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
+    ASSERT(elements != m_unresolvedDefinitions.end());
+    elements->value.remove(element);
+    m_upgradeCandidates.remove(candidate);
 }
 
 ListHashSet<Element*> CustomElementUpgradeCandidateMap::takeUpgradeCandidatesFor(const CustomElementDescriptor& descriptor)
diff --git a/Source/core/dom/CustomEvent.cpp b/Source/core/dom/CustomEvent.cpp
index bad25d2..c79ecac 100644
--- a/Source/core/dom/CustomEvent.cpp
+++ b/Source/core/dom/CustomEvent.cpp
@@ -26,6 +26,7 @@
 #include "config.h"
 #include "core/dom/CustomEvent.h"
 
+#include "bindings/v8/SerializedScriptValue.h"
 #include "core/dom/EventNames.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/CustomEvent.h b/Source/core/dom/CustomEvent.h
index 22466bf..fc7bb11 100644
--- a/Source/core/dom/CustomEvent.h
+++ b/Source/core/dom/CustomEvent.h
@@ -26,12 +26,12 @@
 #ifndef CustomEvent_h
 #define CustomEvent_h
 
-#include "bindings/v8/ScriptValue.h"
-#include "bindings/v8/SerializedScriptValue.h"
 #include "core/dom/Event.h"
 
 namespace WebCore {
 
+class SerializedScriptValue;
+
 typedef EventInit CustomEventInit;
 
 class CustomEvent : public Event {
@@ -54,6 +54,12 @@
 
     SerializedScriptValue* serializedScriptValue() { return m_serializedScriptValue.get(); }
 
+    void setSerializedDetail(PassRefPtr<SerializedScriptValue> detail)
+    {
+        ASSERT(!m_serializedScriptValue);
+        m_serializedScriptValue = detail;
+    }
+
 private:
     CustomEvent();
     CustomEvent(const AtomicString& type, const CustomEventInit& initializer);
diff --git a/Source/core/dom/DOMException.cpp b/Source/core/dom/DOMException.cpp
index 1a4126c..5883eba 100644
--- a/Source/core/dom/DOMException.cpp
+++ b/Source/core/dom/DOMException.cpp
@@ -86,7 +86,7 @@
     return tableIndex < tableSize ? &coreExceptions[tableIndex] : 0;
 }
 
-DOMException::DOMException(unsigned short code, const char* name, const char * message)
+DOMException::DOMException(unsigned short code, const String& name, const String& message)
 {
     ASSERT(name);
     m_code = code;
@@ -95,11 +95,13 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<DOMException> DOMException::create(ExceptionCode ec, const char* message)
+PassRefPtr<DOMException> DOMException::create(ExceptionCode ec, const String& message)
 {
     const CoreException* entry = getErrorEntry(ec);
     ASSERT(entry);
-    return adoptRef(new DOMException(entry->code, entry->name ? entry->name : "Error", message ? message : entry->message));
+    return adoptRef(new DOMException(entry->code,
+        ASCIILiteral(entry->name ? entry->name : "Error"),
+        message.isNull() ? String(ASCIILiteral(entry->message)) : message));
 }
 
 String DOMException::toString() const
@@ -112,9 +114,9 @@
     const CoreException* entry = getErrorEntry(ec);
     ASSERT(entry);
     if (!entry)
-        return "UnknownError";
+        return ASCIILiteral("UnknownError");
 
-    return entry->name;
+    return ASCIILiteral(entry->name);
 }
 
 String DOMException::getErrorMessage(ExceptionCode ec)
@@ -122,9 +124,9 @@
     const CoreException* entry = getErrorEntry(ec);
     ASSERT(entry);
     if (!entry)
-        return "Unknown error.";
+        return ASCIILiteral("Unknown error.");
 
-    return entry->message;
+    return ASCIILiteral(entry->message);
 }
 
 unsigned short DOMException::getLegacyErrorCode(ExceptionCode ec)
diff --git a/Source/core/dom/DOMException.h b/Source/core/dom/DOMException.h
index fb1163f..ca96483 100644
--- a/Source/core/dom/DOMException.h
+++ b/Source/core/dom/DOMException.h
@@ -40,7 +40,7 @@
 
 class DOMException : public RefCounted<DOMException>, public ScriptWrappable {
 public:
-    static PassRefPtr<DOMException> create(ExceptionCode, const char* message = 0);
+    static PassRefPtr<DOMException> create(ExceptionCode, const String& message = String());
 
     unsigned short code() const { return m_code; }
     String name() const { return m_name; }
@@ -53,7 +53,7 @@
     static unsigned short getLegacyErrorCode(ExceptionCode);
 
 private:
-    DOMException(unsigned short m_code, const char* name, const char* message);
+    DOMException(unsigned short m_code, const String& name, const String& message);
 
     unsigned short m_code;
     String m_name;
diff --git a/Source/core/dom/DeviceOrientationController.cpp b/Source/core/dom/DeviceOrientationController.cpp
index 460e1fb..9071098 100644
--- a/Source/core/dom/DeviceOrientationController.cpp
+++ b/Source/core/dom/DeviceOrientationController.cpp
@@ -28,8 +28,8 @@
 #include "core/dom/DeviceOrientationController.h"
 
 #include "core/dom/DeviceOrientationClient.h"
-#include "core/dom/DeviceOrientationEvent.h"
 #include "core/inspector/InspectorInstrumentation.h"
+#include "modules/device_orientation/DeviceOrientationEvent.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DeviceOrientationData.cpp b/Source/core/dom/DeviceOrientationData.cpp
deleted file mode 100644
index 781a466..0000000
--- a/Source/core/dom/DeviceOrientationData.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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/DeviceOrientationData.h"
-
-namespace WebCore {
-
-PassRefPtr<DeviceOrientationData> DeviceOrientationData::create()
-{
-    return adoptRef(new DeviceOrientationData);
-}
-
-PassRefPtr<DeviceOrientationData> DeviceOrientationData::create(bool canProvideAlpha, double alpha, bool canProvideBeta, double beta, bool canProvideGamma, double gamma, bool canProvideAbsolute, bool absolute)
-{
-    return adoptRef(new DeviceOrientationData(canProvideAlpha, alpha, canProvideBeta, beta, canProvideGamma, gamma, canProvideAbsolute, absolute));
-}
-
-
-DeviceOrientationData::DeviceOrientationData()
-    : m_canProvideAlpha(false)
-    , m_canProvideBeta(false)
-    , m_canProvideGamma(false)
-    , m_canProvideAbsolute(false)
-    , m_alpha(0)
-    , m_beta(0)
-    , m_gamma(0)
-    , m_absolute(false)
-{
-}
-
-DeviceOrientationData::DeviceOrientationData(bool canProvideAlpha, double alpha, bool canProvideBeta, double beta, bool canProvideGamma, double gamma, bool canProvideAbsolute, bool absolute)
-    : m_canProvideAlpha(canProvideAlpha)
-    , m_canProvideBeta(canProvideBeta)
-    , m_canProvideGamma(canProvideGamma)
-    , m_canProvideAbsolute(canProvideAbsolute)
-    , m_alpha(alpha)
-    , m_beta(beta)
-    , m_gamma(gamma)
-    , m_absolute(absolute)
-{
-}
-
-double DeviceOrientationData::alpha() const
-{
-    return m_alpha;
-}
-
-double DeviceOrientationData::beta() const
-{
-    return m_beta;
-}
-
-double DeviceOrientationData::gamma() const
-{
-    return m_gamma;
-}
-
-bool DeviceOrientationData::absolute() const
-{
-    return m_absolute;
-}
-
-bool DeviceOrientationData::canProvideAlpha() const
-{
-    return m_canProvideAlpha;
-}
-
-bool DeviceOrientationData::canProvideBeta() const
-{
-    return m_canProvideBeta;
-}
-
-bool DeviceOrientationData::canProvideGamma() const
-{
-    return m_canProvideGamma;
-}
-
-bool DeviceOrientationData::canProvideAbsolute() const
-{
-    return m_canProvideAbsolute;
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/DeviceOrientationData.h b/Source/core/dom/DeviceOrientationData.h
deleted file mode 100644
index 2c37a13..0000000
--- a/Source/core/dom/DeviceOrientationData.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 DeviceOrientationData_h
-#define DeviceOrientationData_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class DeviceOrientationData : public RefCounted<DeviceOrientationData> {
-public:
-    static PassRefPtr<DeviceOrientationData> create();
-    static PassRefPtr<DeviceOrientationData> create(bool canProvideAlpha, double alpha, bool canProvideBeta, double beta, bool canProvideGamma, double gamma, bool canProvideAbsolute = false, bool absolute = false);
-
-    double alpha() const;
-    double beta() const;
-    double gamma() const;
-    bool absolute() const;
-    bool canProvideAlpha() const;
-    bool canProvideBeta() const;
-    bool canProvideGamma() const;
-    bool canProvideAbsolute() const;
-
-private:
-    DeviceOrientationData();
-    DeviceOrientationData(bool canProvideAlpha, double alpha, bool canProvideBeta, double beta, bool canProvideGamma, double gamma, bool canProvideAbsolute, bool absolute);
-
-    bool m_canProvideAlpha;
-    bool m_canProvideBeta;
-    bool m_canProvideGamma;
-    bool m_canProvideAbsolute;
-    double m_alpha;
-    double m_beta;
-    double m_gamma;
-    bool m_absolute;
-};
-
-} // namespace WebCore
-
-#endif // DeviceOrientationData_h
diff --git a/Source/core/dom/DeviceOrientationEvent.cpp b/Source/core/dom/DeviceOrientationEvent.cpp
deleted file mode 100644
index 5875edc..0000000
--- a/Source/core/dom/DeviceOrientationEvent.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- *
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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/DeviceOrientationEvent.h"
-
-#include "core/dom/DeviceOrientationData.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-DeviceOrientationEvent::~DeviceOrientationEvent()
-{
-}
-
-DeviceOrientationEvent::DeviceOrientationEvent()
-    : m_orientation(DeviceOrientationData::create())
-{
-    ScriptWrappable::init(this);
-}
-
-DeviceOrientationEvent::DeviceOrientationEvent(const AtomicString& eventType, DeviceOrientationData* orientation)
-    : Event(eventType, false, false) // Can't bubble, not cancelable
-    , m_orientation(orientation)
-{
-    ScriptWrappable::init(this);
-}
-
-void DeviceOrientationEvent::initDeviceOrientationEvent(const AtomicString& type, bool bubbles, bool cancelable, DeviceOrientationData* orientation)
-{
-    if (dispatched())
-        return;
-
-    initEvent(type, bubbles, cancelable);
-    m_orientation = orientation;
-}
-
-double DeviceOrientationEvent::alpha(bool& isNull) const
-{
-    if (m_orientation->canProvideAlpha())
-        return m_orientation->alpha();
-
-    isNull = true;
-    return 0;
-}
-
-double DeviceOrientationEvent::beta(bool& isNull) const
-{
-    if (m_orientation->canProvideBeta())
-        return m_orientation->beta();
-
-    isNull = true;
-    return 0;
-}
-
-double DeviceOrientationEvent::gamma(bool& isNull) const
-{
-    if (m_orientation->canProvideGamma())
-        return m_orientation->gamma();
-
-    isNull = true;
-    return 0;
-}
-
-bool DeviceOrientationEvent::absolute(bool& isNull) const
-{
-    if (m_orientation->canProvideAbsolute())
-        return m_orientation->absolute();
-
-    isNull = true;
-    return 0;
-}
-
-const AtomicString& DeviceOrientationEvent::interfaceName() const
-{
-    return eventNames().interfaceForDeviceOrientationEvent;
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/DeviceOrientationEvent.h b/Source/core/dom/DeviceOrientationEvent.h
deleted file mode 100644
index dc55e67..0000000
--- a/Source/core/dom/DeviceOrientationEvent.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- *
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 DeviceOrientationEvent_h
-#define DeviceOrientationEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-class DeviceOrientationData;
-
-class DeviceOrientationEvent : public Event {
-public:
-    ~DeviceOrientationEvent();
-    static PassRefPtr<DeviceOrientationEvent> create()
-    {
-        return adoptRef(new DeviceOrientationEvent);
-    }
-    static PassRefPtr<DeviceOrientationEvent> create(const AtomicString& eventType, DeviceOrientationData* orientation)
-    {
-        return adoptRef(new DeviceOrientationEvent(eventType, orientation));
-    }
-
-    void initDeviceOrientationEvent(const AtomicString& type, bool bubbles, bool cancelable, DeviceOrientationData*);
-
-    DeviceOrientationData* orientation() const { return m_orientation.get(); }
-
-    double alpha(bool& isNull) const;
-    double beta(bool& isNull) const;
-    double gamma(bool& isNull) const;
-    bool absolute(bool& isNull) const;
-
-    virtual const AtomicString& interfaceName() const;
-
-private:
-    DeviceOrientationEvent();
-    DeviceOrientationEvent(const AtomicString& eventType, DeviceOrientationData*);
-
-    RefPtr<DeviceOrientationData> m_orientation;
-};
-
-} // namespace WebCore
-
-#endif // DeviceOrientationEvent_h
diff --git a/Source/core/dom/DeviceOrientationEvent.idl b/Source/core/dom/DeviceOrientationEvent.idl
deleted file mode 100644
index 286f2bb..0000000
--- a/Source/core/dom/DeviceOrientationEvent.idl
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- *
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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.
- */
-
-interface DeviceOrientationEvent : Event {
-    readonly attribute double? alpha;
-    readonly attribute double? beta;
-    readonly attribute double? gamma;
-    readonly attribute boolean? absolute;
-    [Custom] void initDeviceOrientationEvent([Default=Undefined] optional DOMString type, 
-                                             [Default=Undefined] optional boolean bubbles, 
-                                             [Default=Undefined] optional boolean cancelable, 
-                                             [Default=Undefined] optional double alpha, 
-                                             [Default=Undefined] optional double beta, 
-                                             [Default=Undefined] optional double gamma,
-                                             [Default=Undefined] optional boolean absolute);
-};
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 2f47ff4..d4b4fc7 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -275,23 +275,23 @@
     return url.isEmpty() || url.isBlankURL();
 }
 
-static Widget* widgetForNode(Node* focusedNode)
+static Widget* widgetForElement(Element* focusedElement)
 {
-    if (!focusedNode)
+    if (!focusedElement)
         return 0;
-    RenderObject* renderer = focusedNode->renderer();
+    RenderObject* renderer = focusedElement->renderer();
     if (!renderer || !renderer->isWidget())
         return 0;
     return toRenderWidget(renderer)->widget();
 }
 
-static bool acceptsEditingFocus(Node* node)
+static bool acceptsEditingFocus(Element* element)
 {
-    ASSERT(node);
-    ASSERT(node->rendererIsEditable());
+    ASSERT(element);
+    ASSERT(element->rendererIsEditable());
 
-    Node* root = node->rootEditableElement();
-    Frame* frame = node->document()->frame();
+    Element* root = element->rootEditableElement();
+    Frame* frame = element->document()->frame();
     if (!frame || !root)
         return false;
 
@@ -331,34 +331,35 @@
     String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
 
     // FIXME: should we print to the console of the document performing the navigation instead?
-    frame->document()->domWindow()->printErrorMessage(message);
+    frame->domWindow()->printErrorMessage(message);
 }
 
 uint64_t Document::s_globalTreeVersion = 0;
 
 // This class should be passed only to Document::postTask.
-class CheckFocusedNodeTask FINAL : public ScriptExecutionContext::Task {
+class CheckFocusedElementTask FINAL : public ScriptExecutionContext::Task {
 public:
-    static PassOwnPtr<CheckFocusedNodeTask> create()
+    static PassOwnPtr<CheckFocusedElementTask> create()
     {
-        return adoptPtr(new CheckFocusedNodeTask());
+        return adoptPtr(new CheckFocusedElementTask());
     }
-    virtual ~CheckFocusedNodeTask() { }
+    virtual ~CheckFocusedElementTask() { }
 
 private:
-    CheckFocusedNodeTask() { }
+    CheckFocusedElementTask() { }
     virtual void performTask(ScriptExecutionContext* context) OVERRIDE
     {
         ASSERT(context->isDocument());
         Document* document = toDocument(context);
-        document->didRunCheckFocusedNodeTask();
-        if (!document->focusedNode())
+        document->didRunCheckFocusedElementTask();
+        Element* element = document->focusedElement();
+        if (!element)
             return;
         if (document->childNeedsStyleRecalc())
             return;
-        if (document->focusedNode()->renderer() && document->focusedNode()->renderer()->needsLayout())
+        if (element->renderer() && element->renderer()->needsLayout())
             return;
-        if (!document->focusedNode()->isFocusable())
+        if (!element->isFocusable())
             document->setFocusedElement(0);
     }
 };
@@ -384,7 +385,7 @@
     , m_ignoreAutofocus(false)
     , m_compatibilityMode(NoQuirksMode)
     , m_compatibilityModeLocked(false)
-    , m_didPostCheckFocusedNodeTask(false)
+    , m_didPostCheckFocusedElementTask(false)
     , m_domTreeVersion(++s_globalTreeVersion)
     , m_listenerTypes(0)
     , m_mutationObserverTypes(0)
@@ -583,7 +584,7 @@
     // We must make sure not to be retaining any of our children through
     // these extra pointers or we will create a reference cycle.
     m_docType = 0;
-    m_focusedNode = 0;
+    m_focusedElement = 0;
     m_hoverNode = 0;
     m_activeElement = 0;
     m_titleElement = 0;
@@ -1103,8 +1104,11 @@
 
 String Document::encoding() const
 {
+    // TextEncoding::domName() returns a char*, no need to allocate a new
+    // String for it each time.
+    // FIXME: We should fix TextEncoding to speak AtomicString anyway.
     if (TextResourceDecoder* d = decoder())
-        return d->encoding().domName();
+        return AtomicString(d->encoding().domName());
     return String();
 }
 
@@ -1655,7 +1659,7 @@
 
         // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
         if (m_styleResolver)
-            m_styleSheetCollection->resetCSSFeatureFlags();
+            m_styleSheetCollection->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
 
         if (frameView) {
             frameView->resumeScheduledEvents();
@@ -1669,6 +1673,9 @@
         implicitClose();
     }
 
+    STYLE_STATS_PRINT();
+    STYLE_STATS_CLEAR();
+
     InspectorInstrumentation::didRecalculateStyle(cookie);
 
     // As a result of the style recalculation, the currently hovered element might have been
@@ -1725,9 +1732,9 @@
         frameView->layout();
 
     // FIXME: Using a Task doesn't look a good idea.
-    if (m_focusedNode && !m_didPostCheckFocusedNodeTask) {
-        postTask(CheckFocusedNodeTask::create());
-        m_didPostCheckFocusedNodeTask = true;
+    if (m_focusedElement && !m_didPostCheckFocusedElementTask) {
+        postTask(CheckFocusedElementTask::create());
+        m_didPostCheckFocusedElementTask = true;
     }
 }
 
@@ -1837,7 +1844,7 @@
     if (Settings* docSettings = settings())
         matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
     m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
-    m_styleSheetCollection->combineCSSFeatureFlags();
+    m_styleSheetCollection->combineCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
 }
 
 void Document::clearStyleResolver()
@@ -1902,7 +1909,7 @@
     setRenderer(0);
 
     m_hoverNode = 0;
-    m_focusedNode = 0;
+    m_focusedElement = 0;
     m_activeElement = 0;
 
     ContainerNode::detach(context);
@@ -2090,7 +2097,7 @@
     cancelParsing();
 
     removeChildren();
-    ASSERT(!m_focusedNode);
+    ASSERT(!m_focusedElement);
 
     setCompatibilityMode(NoQuirksMode);
 
@@ -2276,7 +2283,7 @@
         // The AX cache may have been cleared at this point, but we need to make sure it contains an
         // AX object to send the notification to. getOrCreate will make sure that an valid AX object
         // exists in the cache (we ignore the return value because we don't need it here). This is
-        // only safe to call when a layout is not in progress, so it can not be used in postNotification.    
+        // only safe to call when a layout is not in progress, so it can not be used in postNotification.
         if (AXObjectCache* cache = axObjectCache()) {
             cache->getOrCreate(renderObject);
             if (this == topDocument()) {
@@ -2393,7 +2400,7 @@
     return domWindow();
 }
 
-void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
+void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
 {
     addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
 }
@@ -2666,12 +2673,20 @@
             refreshUrl = m_url.string();
         else
             refreshUrl = completeURL(refreshUrl).string();
-        if (!protocolIsJavaScript(refreshUrl)) {
-            frame->navigationScheduler()->scheduleRedirect(delay, refreshUrl);
-        } else {
+
+        if (protocolIsJavaScript(refreshUrl)) {
             String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
             addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+            return;
         }
+
+        if (isSandboxed(SandboxAutomaticFeatures)) {
+            String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
+            addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+            return;
+        }
+
+        frame->navigationScheduler()->scheduleRedirect(delay, refreshUrl);
     }
 }
 
@@ -3040,9 +3055,9 @@
     m_activeElement = newActiveElement;
 }
 
-void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
+void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
 {
-    if (!m_focusedNode)
+    if (!m_focusedElement)
         return;
 
     Element* focusedElement = node->treeScope()->adjustedFocusedElement();
@@ -3106,64 +3121,59 @@
     setAnnotatedRegionsDirty(false);
 }
 
-bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedNode, FocusDirection direction)
+bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
 {
-    RefPtr<Node> newFocusedNode = prpNewFocusedNode;
+    RefPtr<Element> newFocusedElement = prpNewFocusedElement;
 
     // Make sure newFocusedNode is actually in this document
-    if (newFocusedNode && (newFocusedNode->document() != this))
+    if (newFocusedElement && (newFocusedElement->document() != this))
         return true;
 
-    if (m_focusedNode == newFocusedNode)
+    if (m_focusedElement == newFocusedElement)
         return true;
 
     bool focusChangeBlocked = false;
-    RefPtr<Node> oldFocusedNode = m_focusedNode;
-    m_focusedNode = 0;
+    RefPtr<Element> oldFocusedElement = m_focusedElement;
+    m_focusedElement = 0;
 
     // Remove focus from the existing focus node (if any)
-    if (oldFocusedNode) {
-        ASSERT(!oldFocusedNode->inDetach());
+    if (oldFocusedElement) {
+        ASSERT(!oldFocusedElement->inDetach());
 
-        if (oldFocusedNode->active())
-            oldFocusedNode->setActive(false);
+        if (oldFocusedElement->active())
+            oldFocusedElement->setActive(false);
 
-        oldFocusedNode->setFocus(false);
+        oldFocusedElement->setFocus(false);
 
         // Dispatch a change event for text fields or textareas that have been edited
-        if (oldFocusedNode->isElementNode()) {
-            Element* element = toElement(oldFocusedNode.get());
-            if (element->wasChangedSinceLastFormControlChangeEvent())
-                element->dispatchFormControlChangeEvent();
-        }
+        if (oldFocusedElement->wasChangedSinceLastFormControlChangeEvent())
+            oldFocusedElement->dispatchFormControlChangeEvent();
 
         // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
-        oldFocusedNode->dispatchBlurEvent(newFocusedNode);
+        oldFocusedElement->dispatchBlurEvent(newFocusedElement);
 
-        if (m_focusedNode) {
+        if (m_focusedElement) {
             // handler shifted focus
             focusChangeBlocked = true;
-            newFocusedNode = 0;
+            newFocusedElement = 0;
         }
 
-        oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
+        oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement); // DOM level 3 name for the bubbling blur event.
         // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
         // on it, probably when <rdar://problem/8503958> is resolved.
-        oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
+        oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement); // DOM level 2 name for compatibility.
 
-        if (m_focusedNode) {
+        if (m_focusedElement) {
             // handler shifted focus
             focusChangeBlocked = true;
-            newFocusedNode = 0;
+            newFocusedElement = 0;
         }
-        if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
-            return true;
 
-        if (oldFocusedNode->isRootEditableElement())
+        if (oldFocusedElement->isRootEditableElement())
             frame()->editor()->didEndEditing();
 
         if (view()) {
-            Widget* oldWidget = widgetForNode(oldFocusedNode.get());
+            Widget* oldWidget = widgetForElement(oldFocusedElement.get());
             if (oldWidget)
                 oldWidget->setFocus(false);
             else
@@ -3171,57 +3181,57 @@
         }
     }
 
-    if (newFocusedNode && newFocusedNode->isFocusable()) {
-        if (newFocusedNode->isRootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
+    if (newFocusedElement && newFocusedElement->isFocusable()) {
+        if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
             // delegate blocks focus change
             focusChangeBlocked = true;
-            goto SetFocusedNodeDone;
+            goto SetFocusedElementDone;
         }
         // Set focus on the new node
-        m_focusedNode = newFocusedNode;
+        m_focusedElement = newFocusedElement;
 
         // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
-        m_focusedNode->dispatchFocusEvent(oldFocusedNode, direction);
+        m_focusedElement->dispatchFocusEvent(oldFocusedElement, direction);
 
-        if (m_focusedNode != newFocusedNode) {
+        if (m_focusedElement != newFocusedElement) {
             // handler shifted focus
             focusChangeBlocked = true;
-            goto SetFocusedNodeDone;
+            goto SetFocusedElementDone;
         }
 
-        m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
+        m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement); // DOM level 3 bubbling focus event.
 
-        if (m_focusedNode != newFocusedNode) {
+        if (m_focusedElement != newFocusedElement) {
             // handler shifted focus
             focusChangeBlocked = true;
-            goto SetFocusedNodeDone;
+            goto SetFocusedElementDone;
         }
 
         // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
         // on it, probably when <rdar://problem/8503958> is m.
-        m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
+        m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement); // DOM level 2 for compatibility.
 
-        if (m_focusedNode != newFocusedNode) {
+        if (m_focusedElement != newFocusedElement) {
             // handler shifted focus
             focusChangeBlocked = true;
-            goto SetFocusedNodeDone;
+            goto SetFocusedElementDone;
         }
-        m_focusedNode->setFocus(true);
+        m_focusedElement->setFocus(true);
 
-        if (m_focusedNode->isRootEditableElement())
+        if (m_focusedElement->isRootEditableElement())
             frame()->editor()->didBeginEditing();
 
         // eww, I suck. set the qt focus correctly
         // ### find a better place in the code for this
         if (view()) {
-            Widget* focusWidget = widgetForNode(m_focusedNode.get());
+            Widget* focusWidget = widgetForElement(m_focusedElement.get());
             if (focusWidget) {
                 // Make sure a widget has the right size before giving it focus.
                 // Otherwise, we are testing edge cases of the Widget code.
                 // Specifically, in WebCore this does not work well for text fields.
                 updateLayout();
                 // Re-get the widget in case updating the layout changed things.
-                focusWidget = widgetForNode(m_focusedNode.get());
+                focusWidget = widgetForElement(m_focusedElement.get());
             }
             if (focusWidget)
                 focusWidget->setFocus(true);
@@ -3230,16 +3240,16 @@
         }
     }
 
-    if (!focusChangeBlocked && m_focusedNode) {
+    if (!focusChangeBlocked && m_focusedElement) {
         // Create the AXObject cache in a focus change because Chromium relies on it.
         if (AXObjectCache* cache = axObjectCache())
-            cache->handleFocusedUIElementChanged(oldFocusedNode.get(), newFocusedNode.get());
+            cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
     }
 
     if (!focusChangeBlocked)
-        page()->chrome().focusedNodeChanged(m_focusedNode.get());
+        page()->chrome().focusedNodeChanged(m_focusedElement.get());
 
-SetFocusedNodeDone:
+SetFocusedElementDone:
     updateStyleIfNeeded();
     if (Frame* frame = this->frame())
         frame->selection()->didChangeFocus();
@@ -3632,6 +3642,11 @@
     return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
 }
 
+const KURL& Document::firstPartyForCookies() const
+{
+    return topDocument()->url();
+}
+
 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
 {
     if (!isValidNameStart(characters[0]))
@@ -4317,15 +4332,10 @@
 
 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
 {
-    Node* node = focusedNode();
-    if (!node)
+    Element* element = focusedElement();
+    if (!element)
         return;
-    if (!node->isElementNode())
-        return;
-
     updateLayout();
-
-    Element* element = toElement(node);
     if (element->isFocusable())
         element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
 }
@@ -4791,7 +4801,7 @@
 {
     if (!doc)
         return 0;
-    Node* node = doc->focusedNode();
+    Node* node = doc->focusedElement();
     if (!node && doc->isPluginDocument()) {
         PluginDocument* pluginDocument = toPluginDocument(doc);
         node =  pluginDocument->pluginNode();
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 1cbb69b..cfd2f8f 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -629,10 +629,10 @@
     void setSelectedStylesheetSet(const String&);
 
     bool setFocusedElement(PassRefPtr<Element>, FocusDirection = FocusDirectionNone);
-    Node* focusedNode() const { return m_focusedNode.get(); }
+    Element* focusedElement() const { return m_focusedElement.get(); }
     UserActionElementSet& userActionElements()  { return m_userActionElements; }
     const UserActionElementSet& userActionElements() const { return m_userActionElements; }
-    void didRunCheckFocusedNodeTask() { m_didPostCheckFocusedNodeTask = false; }
+    void didRunCheckFocusedElementTask() { m_didPostCheckFocusedElementTask = false; }
 
     // The m_ignoreAutofocus flag specifies whether or not the document has been changed by the user enough 
     // for WebCore to ignore the autofocus attribute on any form controls
@@ -645,7 +645,7 @@
     void setActiveElement(PassRefPtr<Element>);
     Element* activeElement() const { return m_activeElement.get(); }
 
-    void removeFocusedNodeOfSubtree(Node*, bool amongChildrenOnly = false);
+    void removeFocusedElementOfSubtree(Node*, bool amongChildrenOnly = false);
     void hoveredNodeDetached(Node*);
     void activeChainNodeDetached(Node*);
 
@@ -780,18 +780,7 @@
     const KURL& cookieURL() const { return m_cookieURL; }
     void setCookieURL(const KURL& url) { m_cookieURL = url; }
 
-    // The firstPartyForCookies is used to compute whether this document
-    // appears in a "third-party" context for the purpose of third-party
-    // cookie blocking.  The document is in a third-party context if the
-    // cookieURL and the firstPartyForCookies are from different hosts.
-    //
-    // Note: Some ports (including possibly Apple's) only consider the
-    //       document in a third-party context if the cookieURL and the
-    //       firstPartyForCookies have a different registry-controlled
-    //       domain.
-    //
-    const KURL& firstPartyForCookies() const { return m_firstPartyForCookies; }
-    void setFirstPartyForCookies(const KURL& url) { m_firstPartyForCookies = url; }
+    const KURL& firstPartyForCookies() const;
     
     // The following implements the rule from HTML 4 for what valid names are.
     // To get this right for all the XML cases, we probably have to improve this or move it
@@ -958,7 +947,7 @@
     void serviceScriptedAnimations(double monotonicAnimationStartTime);
 
     virtual EventTarget* errorEventTarget();
-    virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack>);
+    virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>);
 
     void initDNSPrefetch();
 
@@ -1157,7 +1146,6 @@
     KURL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
     KURL m_baseElementURL; // The URL set by the <base> element.
     KURL m_cookieURL; // The URL to use for cookie access.
-    KURL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
 
     // Document.documentURI:
     // Although URL-like, Document.documentURI can actually be set to any
@@ -1181,8 +1169,8 @@
     CompatibilityMode m_compatibilityMode;
     bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
 
-    bool m_didPostCheckFocusedNodeTask;
-    RefPtr<Node> m_focusedNode;
+    bool m_didPostCheckFocusedElementTask;
+    RefPtr<Element> m_focusedElement;
     RefPtr<Node> m_hoverNode;
     RefPtr<Element> m_activeElement;
     RefPtr<Element> m_documentElement;
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index effc829..3e1af34 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -174,32 +174,32 @@
     [NotEnumerable] attribute EventListener onabort;
     [NotEnumerable] attribute EventListener onblur;
     [NotEnumerable] attribute EventListener onchange;
-    [NotEnumerable] attribute EventListener onclick;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onclick;
     [NotEnumerable] attribute EventListener oncontextmenu;
-    [NotEnumerable] attribute EventListener ondblclick;
-    [NotEnumerable] attribute EventListener ondrag;
-    [NotEnumerable] attribute EventListener ondragend;
-    [NotEnumerable] attribute EventListener ondragenter;
-    [NotEnumerable] attribute EventListener ondragleave;
-    [NotEnumerable] attribute EventListener ondragover;
-    [NotEnumerable] attribute EventListener ondragstart;
-    [NotEnumerable] attribute EventListener ondrop;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondblclick;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrag;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragend;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragstart;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrop;
     [NotEnumerable] attribute EventListener onerror;
     [NotEnumerable] attribute EventListener onfocus;
-    [NotEnumerable] attribute EventListener oninput;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener oninput;
     [NotEnumerable] attribute EventListener oninvalid;
-    [NotEnumerable] attribute EventListener onkeydown;
-    [NotEnumerable] attribute EventListener onkeypress;
-    [NotEnumerable] attribute EventListener onkeyup;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeydown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeypress;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeyup;
     [NotEnumerable] attribute EventListener onload;
-    [NotEnumerable] attribute EventListener onmousedown;
-    [NotEnumerable] attribute EventListener onmouseenter;
-    [NotEnumerable] attribute EventListener onmouseleave;
-    [NotEnumerable] attribute EventListener onmousemove;
-    [NotEnumerable] attribute EventListener onmouseout;
-    [NotEnumerable] attribute EventListener onmouseover;
-    [NotEnumerable] attribute EventListener onmouseup;
-    [NotEnumerable] attribute EventListener onmousewheel;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousedown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousemove;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseout;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseup;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousewheel;
     [NotEnumerable] attribute EventListener onreadystatechange;
     [NotEnumerable] attribute EventListener onscroll;
     [NotEnumerable] attribute EventListener onselect;
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index 34b0816..e2088d8 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -90,36 +90,34 @@
     return m_collectionForDocument.activeAuthorStyleSheets();
 }
 
-void DocumentStyleSheetCollection::combineCSSFeatureFlags()
+void DocumentStyleSheetCollection::combineCSSFeatureFlags(const RuleFeatureSet& features)
 {
     // Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
-    StyleResolver* styleResolver = m_document->styleResolver();
-    m_usesSiblingRules = m_usesSiblingRules || styleResolver->usesSiblingRules();
-    m_usesFirstLineRules = m_usesFirstLineRules || styleResolver->usesFirstLineRules();
-    m_usesBeforeAfterRules = m_usesBeforeAfterRules || styleResolver->usesBeforeAfterRules();
+    m_usesSiblingRules = m_usesSiblingRules || features.usesSiblingRules();
+    m_usesFirstLineRules = m_usesFirstLineRules || features.usesFirstLineRules();
+    m_usesBeforeAfterRules = m_usesBeforeAfterRules || features.usesBeforeAfterRules();
 }
 
-void DocumentStyleSheetCollection::resetCSSFeatureFlags()
+void DocumentStyleSheetCollection::resetCSSFeatureFlags(const RuleFeatureSet& features)
 {
-    StyleResolver* styleResolver = m_document->styleResolver();
-    m_usesSiblingRules = styleResolver->usesSiblingRules();
-    m_usesFirstLineRules = styleResolver->usesFirstLineRules();
-    m_usesBeforeAfterRules = styleResolver->usesBeforeAfterRules();
+    m_usesSiblingRules = features.usesSiblingRules();
+    m_usesFirstLineRules = features.usesFirstLineRules();
+    m_usesBeforeAfterRules = features.usesBeforeAfterRules();
 }
 
 CSSStyleSheet* DocumentStyleSheetCollection::pageUserSheet()
 {
     if (m_pageUserSheet)
         return m_pageUserSheet.get();
-    
+
     Page* owningPage = m_document->page();
     if (!owningPage)
         return 0;
-    
+
     String userSheetText = owningPage->userStyleSheet();
     if (userSheetText.isEmpty())
         return 0;
-    
+
     // Parse the sheet and cache it.
     m_pageUserSheet = CSSStyleSheet::createInline(m_document, m_document->settings()->userStyleSheetLocation());
     m_pageUserSheet->contents()->setIsUserStyleSheet(true);
@@ -268,7 +266,7 @@
     m_needsUpdateActiveStylesheetsOnStyleRecalc = false;
 
     if (styleResolverUpdateType != StyleSheetCollection::Reconstruct)
-        resetCSSFeatureFlags();
+        resetCSSFeatureFlags(m_document->styleResolver()->ruleFeatureSet());
 
     InspectorInstrumentation::activeStyleSheetsUpdated(m_document, m_collectionForDocument.styleSheetsForStyleSheetList());
     m_usesRemUnits = styleSheetsUseRemUnits(m_collectionForDocument.activeAuthorStyleSheets());
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index c0e0327..0e220e2 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -41,6 +41,7 @@
 
 class CSSStyleSheet;
 class Node;
+class RuleFeatureSet;
 class StyleSheet;
 class StyleSheetContents;
 class StyleSheetList;
@@ -100,8 +101,8 @@
     bool usesRemUnits() const { return m_usesRemUnits; }
     void setUsesRemUnit(bool b) { m_usesRemUnits = b; }
 
-    void combineCSSFeatureFlags();
-    void resetCSSFeatureFlags();
+    void combineCSSFeatureFlags(const RuleFeatureSet&);
+    void resetCSSFeatureFlags(const RuleFeatureSet&);
 
 private:
     DocumentStyleSheetCollection(Document*);
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index 5aa5f57..7affb64 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -29,6 +29,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "XMLNames.h"
 #include "core/accessibility/AXObjectCache.h"
@@ -883,12 +884,12 @@
     return value;
 }
 
-static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, StyleResolver* styleResolver)
+static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
 {
     ASSERT(newId != oldId);
-    if (!oldId.isEmpty() && styleResolver->hasSelectorForId(oldId))
+    if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
         return true;
-    if (!newId.isEmpty() && styleResolver->hasSelectorForId(newId))
+    if (!newId.isEmpty() && features.hasSelectorForId(newId))
         return true;
     return false;
 }
@@ -920,7 +921,7 @@
         AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
         if (newId != oldId) {
             elementData()->setIdForStyleResolution(newId);
-            shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver);
+            shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
         }
     } else if (name == classAttr) {
         classAttributeChanged(newValue);
@@ -1028,10 +1029,10 @@
         const SpaceSplitString oldClasses = elementData()->classNames();
         elementData()->setClass(newClassString, shouldFoldCase);
         const SpaceSplitString& newClasses = elementData()->classNames();
-        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver);
+        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
     } else {
         const SpaceSplitString& oldClasses = elementData()->classNames();
-        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver);
+        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
         elementData()->clearClass();
     }
 
@@ -1363,7 +1364,7 @@
     if (hasRareData()) {
         ElementRareData* data = elementRareData();
         if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
-            if (isFocusable() && document()->focusedNode() == this)
+            if (isFocusable() && document()->focusedElement() == this)
                 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
             data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
         }
@@ -2024,7 +2025,7 @@
         return;
 
     Document* doc = document();
-    if (doc->focusedNode() == this)
+    if (doc->focusedElement() == this)
         return;
 
     // If the stylesheets have already been loaded we can reliably check isFocusable.
@@ -2407,7 +2408,7 @@
 {
     if (hasRareData())
         elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
-    if (document()->focusedNode() == this)
+    if (document()->focusedElement() == this)
         document()->cancelFocusAppearanceUpdate();
 }
 
@@ -2799,6 +2800,11 @@
         scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
 }
 
+static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
+{
+    return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
+}
+
 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
 {
     if (isIdAttributeName(name))
@@ -2812,7 +2818,7 @@
     }
 
     if (oldValue != newValue) {
-        if (attached() && document()->styleResolver() && document()->styleResolver()->hasSelectorForAttribute(name.localName()))
+        if (attached() && hasSelectorForAttribute(document(), name.localName()))
            setNeedsStyleRecalc();
 
         if (isUpgradedCustomElement())
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index 8575c9f..35f6e17 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -481,6 +481,7 @@
     void setIsInCanvasSubtree(bool);
     bool isInCanvasSubtree() const;
 
+    bool isUpgradedCustomElement() { return customElementState() == Upgraded; }
     bool isUnresolvedCustomElement() { return isCustomElement() && !isUpgradedCustomElement(); }
 
     void setIsInsideRegion(bool);
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 2dd8467..db0aef0 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -126,32 +126,32 @@
     [NotEnumerable, PerWorldBindings] attribute EventListener onabort;
     [NotEnumerable, PerWorldBindings] attribute EventListener onblur;
     [NotEnumerable, PerWorldBindings] attribute EventListener onchange;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onclick;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onclick;
     [NotEnumerable, PerWorldBindings] attribute EventListener oncontextmenu;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondblclick;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondrag;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondragend;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondragenter;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondragleave;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondragover;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondragstart;
-    [NotEnumerable, PerWorldBindings] attribute EventListener ondrop;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondblclick;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrag;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragend;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragstart;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrop;
     [NotEnumerable, PerWorldBindings] attribute EventListener onerror;
     [NotEnumerable, PerWorldBindings] attribute EventListener onfocus;
-    [NotEnumerable, PerWorldBindings] attribute EventListener oninput;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener oninput;
     [NotEnumerable, PerWorldBindings] attribute EventListener oninvalid;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onkeydown;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onkeypress;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onkeyup;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeydown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeypress;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeyup;
     [NotEnumerable, PerWorldBindings] attribute EventListener onload;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmousedown;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmouseenter;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmouseleave;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmousemove;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmouseout;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmouseover;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmouseup;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onmousewheel;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousedown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousemove;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseout;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseup;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousewheel;
     [NotEnumerable, PerWorldBindings] attribute EventListener onscroll;
     [NotEnumerable, PerWorldBindings] attribute EventListener onselect;
     [NotEnumerable, PerWorldBindings] attribute EventListener onsubmit;
diff --git a/Source/core/dom/ErrorEvent.cpp b/Source/core/dom/ErrorEvent.cpp
index f9f4638..db11e53 100644
--- a/Source/core/dom/ErrorEvent.cpp
+++ b/Source/core/dom/ErrorEvent.cpp
@@ -52,15 +52,17 @@
     , m_message(initializer.message)
     , m_fileName(initializer.filename)
     , m_lineNumber(initializer.lineno)
+    , m_columnNumber(initializer.column)
 {
     ScriptWrappable::init(this);
 }
 
-ErrorEvent::ErrorEvent(const String& message, const String& fileName, unsigned lineNumber)
+ErrorEvent::ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber)
     : Event(eventNames().errorEvent, false, true)
     , m_message(message)
     , m_fileName(fileName)
     , m_lineNumber(lineNumber)
+    , m_columnNumber(columnNumber)
 {
     ScriptWrappable::init(this);
 }
diff --git a/Source/core/dom/ErrorEvent.h b/Source/core/dom/ErrorEvent.h
index 0c2a453..1e57e25 100644
--- a/Source/core/dom/ErrorEvent.h
+++ b/Source/core/dom/ErrorEvent.h
@@ -42,6 +42,7 @@
     String message;
     String filename;
     unsigned lineno;
+    unsigned column;
 };
 
 class ErrorEvent : public Event {
@@ -50,9 +51,9 @@
     {
         return adoptRef(new ErrorEvent);
     }
-    static PassRefPtr<ErrorEvent> create(const String& message, const String& fileName, unsigned lineNumber)
+    static PassRefPtr<ErrorEvent> create(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber)
     {
-        return adoptRef(new ErrorEvent(message, fileName, lineNumber));
+        return adoptRef(new ErrorEvent(message, fileName, lineNumber, columnNumber));
     }
     static PassRefPtr<ErrorEvent> create(const AtomicString& type, const ErrorEventInit& initializer)
     {
@@ -63,17 +64,19 @@
     const String& message() const { return m_message; }
     const String& filename() const { return m_fileName; }
     unsigned lineno() const { return m_lineNumber; }
+    unsigned column() const { return m_columnNumber; }
 
     virtual const AtomicString& interfaceName() const;
 
 private:
     ErrorEvent();
-    ErrorEvent(const String& message, const String& fileName, unsigned lineNumber);
+    ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber);
     ErrorEvent(const AtomicString&, const ErrorEventInit&);
 
     String m_message;
     String m_fileName;
     unsigned m_lineNumber;
+    unsigned m_columnNumber;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/ErrorEvent.idl b/Source/core/dom/ErrorEvent.idl
index 612a970..21195e9 100644
--- a/Source/core/dom/ErrorEvent.idl
+++ b/Source/core/dom/ErrorEvent.idl
@@ -34,5 +34,9 @@
     [InitializedByEventConstructor] readonly attribute DOMString message;
     [InitializedByEventConstructor] readonly attribute DOMString filename;
     [InitializedByEventConstructor] readonly attribute unsigned long lineno;
+
+    // FIXME: Part of the specification but not exposed yet.
+    // No other browser seems to support it (except IE10 as 'colno').
+    // [InitializedByEventConstructor] readonly attribute unsigned long column;
 };
 
diff --git a/Source/core/dom/EventRetargeter.h b/Source/core/dom/EventRetargeter.h
index f274e70..f2e66ca 100644
--- a/Source/core/dom/EventRetargeter.h
+++ b/Source/core/dom/EventRetargeter.h
@@ -85,7 +85,7 @@
     // At this time, SVG nodes are not supported in non-<use> shadow trees.
     if (!shadowHostElement || !shadowHostElement->hasTagName(SVGNames::useTag))
         return referenceNode;
-    SVGUseElement* useElement = static_cast<SVGUseElement*>(shadowHostElement);
+    SVGUseElement* useElement = toSVGUseElement(shadowHostElement);
     if (SVGElementInstance* instance = useElement->instanceForShadowTreeElement(referenceNode))
         return instance;
 
diff --git a/Source/core/dom/MessageEvent.h b/Source/core/dom/MessageEvent.h
index 80965bf..d68bac8 100644
--- a/Source/core/dom/MessageEvent.h
+++ b/Source/core/dom/MessageEvent.h
@@ -98,11 +98,17 @@
         DataTypeArrayBuffer
     };
     DataType dataType() const { return m_dataType; }
-    SerializedScriptValue* dataAsSerializedScriptValue() const { ASSERT(m_dataType == DataTypeSerializedScriptValue); return m_dataAsSerializedScriptValue.get(); }
+    SerializedScriptValue* dataAsSerializedScriptValue() const { ASSERT(m_dataType == DataTypeScriptValue || m_dataType == DataTypeSerializedScriptValue); return m_dataAsSerializedScriptValue.get(); }
     String dataAsString() const { ASSERT(m_dataType == DataTypeString); return m_dataAsString; }
     Blob* dataAsBlob() const { ASSERT(m_dataType == DataTypeBlob); return m_dataAsBlob.get(); }
     ArrayBuffer* dataAsArrayBuffer() const { ASSERT(m_dataType == DataTypeArrayBuffer); return m_dataAsArrayBuffer.get(); }
 
+    void setSerializedData(PassRefPtr<SerializedScriptValue> data)
+    {
+        ASSERT(!m_dataAsSerializedScriptValue);
+        m_dataAsSerializedScriptValue = data;
+    }
+
 private:
     MessageEvent();
     MessageEvent(const AtomicString&, const MessageEventInit&);
diff --git a/Source/core/dom/MessagePort.cpp b/Source/core/dom/MessagePort.cpp
index c83921e..07b4eb1 100644
--- a/Source/core/dom/MessagePort.cpp
+++ b/Source/core/dom/MessagePort.cpp
@@ -27,6 +27,7 @@
 #include "config.h"
 #include "core/dom/MessagePort.h"
 
+#include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
@@ -55,7 +56,7 @@
         m_scriptExecutionContext->destroyedMessagePort(this);
 }
 
-void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
+void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& es)
 {
     if (!isEntangled())
         return;
@@ -67,12 +68,12 @@
         for (unsigned int i = 0; i < ports->size(); ++i) {
             MessagePort* dataPort = (*ports)[i].get();
             if (dataPort == this || m_entangledChannel->isConnectedTo(dataPort)) {
-                ec = InvalidStateError;
+                es.throwDOMException(InvalidStateError);
                 return;
             }
         }
-        channels = MessagePort::disentanglePorts(ports, ec);
-        if (ec)
+        channels = MessagePort::disentanglePorts(ports, es);
+        if (es.hadException())
             return;
     }
     m_entangledChannel->postMessageToRemote(message, channels.release());
@@ -188,7 +189,7 @@
     return m_entangledChannel ? m_entangledChannel->locallyEntangledPort(m_scriptExecutionContext) : 0;
 }
 
-PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionCode& ec)
+PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionState& es)
 {
     if (!ports || !ports->size())
         return nullptr;
@@ -200,7 +201,7 @@
     for (unsigned int i = 0; i < ports->size(); ++i) {
         MessagePort* port = (*ports)[i].get();
         if (!port || port->isNeutered() || portSet.contains(port)) {
-            ec = DataCloneError;
+            es.throwDOMException(DataCloneError);
             return nullptr;
         }
         portSet.add(port);
diff --git a/Source/core/dom/MessagePort.h b/Source/core/dom/MessagePort.h
index 5124eb2..f5f63c4 100644
--- a/Source/core/dom/MessagePort.h
+++ b/Source/core/dom/MessagePort.h
@@ -41,6 +41,7 @@
 namespace WebCore {
 
 class Event;
+class ExceptionState;
 class Frame;
 class MessagePort;
 class ScriptExecutionContext;
@@ -53,7 +54,7 @@
     static PassRefPtr<MessagePort> create(ScriptExecutionContext& scriptExecutionContext) { return adoptRef(new MessagePort(scriptExecutionContext)); }
     virtual ~MessagePort();
 
-    void postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray*, ExceptionCode&);
+    void postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray*, ExceptionState&);
 
     void start();
     void close();
@@ -62,7 +63,7 @@
     PassOwnPtr<MessagePortChannel> disentangle();
 
     // Returns 0 if there is an exception, or if the passed-in array is 0/empty.
-    static PassOwnPtr<MessagePortChannelArray> disentanglePorts(const MessagePortArray*, ExceptionCode&);
+    static PassOwnPtr<MessagePortChannelArray> disentanglePorts(const MessagePortArray*, ExceptionState&);
 
     // Returns 0 if the passed array is 0/empty.
     static PassOwnPtr<MessagePortArray> entanglePorts(ScriptExecutionContext&, PassOwnPtr<MessagePortChannelArray>);
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 8860aee..8f63f06 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -2681,17 +2681,34 @@
     return document()->userActionElements().isFocused(this);
 }
 
-void Node::setIsCustomElement()
+void Node::setCustomElementState(CustomElementState newState)
 {
-    ASSERT(isHTMLElement() || isSVGElement());
-    setFlag(IsCustomElement);
-}
+    CustomElementState oldState = customElementState();
 
-void Node::setIsUpgradedCustomElement()
-{
-    ASSERT(isCustomElement());
-    setFlag(IsUpgradedCustomElement);
-    setNeedsStyleRecalc(); // :unresolved has changed
+    switch (newState) {
+    case NotCustomElement:
+        ASSERT_NOT_REACHED(); // Everything starts in this state
+        return;
+
+    case UpgradeCandidate:
+        ASSERT(NotCustomElement == oldState);
+        break;
+
+    case Defined:
+        ASSERT(UpgradeCandidate == oldState || NotCustomElement == oldState);
+        break;
+
+    case Upgraded:
+        ASSERT(Defined == oldState);
+        break;
+    }
+
+    ASSERT(isHTMLElement() || isSVGElement());
+    setFlag(newState & 1, CustomElementIsUpgradeCandidateOrUpgraded);
+    setFlag(newState & 2, CustomElementHasDefinitionOrIsUpgraded);
+
+    if (oldState == NotCustomElement || newState == Upgraded)
+        setNeedsStyleRecalc(); // :unresolved has changed
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 8567496..f71a14a 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -244,10 +244,15 @@
     bool isAfterPseudoElement() const { return pseudoId() == AFTER; }
     PseudoId pseudoId() const { return (isElementNode() && hasCustomStyleCallbacks()) ? customPseudoId() : NOPSEUDO; }
 
-    bool isCustomElement() const { return getFlag(IsCustomElement); }
-    void setIsCustomElement();
-    bool isUpgradedCustomElement() const { return getFlag(IsUpgradedCustomElement); }
-    void setIsUpgradedCustomElement();
+    enum CustomElementState {
+        NotCustomElement,
+        UpgradeCandidate,
+        Defined,
+        Upgraded
+    };
+    bool isCustomElement() const { return customElementState() != NotCustomElement; }
+    CustomElementState customElementState() const { return CustomElementState((getFlag(CustomElementHasDefinitionOrIsUpgraded) ? 2 : 0) | (getFlag(CustomElementIsUpgradeCandidateOrUpgraded) ? 1 : 0)); }
+    void setCustomElementState(CustomElementState newState);
 
     virtual bool isMediaControlElement() const { return false; }
     virtual bool isMediaControls() const { return false; }
@@ -744,11 +749,11 @@
         V8CollectableDuringMinorGCFlag = 1 << 23,
         IsInsertionPointFlag = 1 << 24,
         IsInShadowTreeFlag = 1 << 25,
-        IsCustomElement = 1 << 26,
 
-        NotifyRendererWithIdenticalStyles = 1 << 27,
+        NotifyRendererWithIdenticalStyles = 1 << 26,
 
-        IsUpgradedCustomElement = 1 << 28,
+        CustomElementIsUpgradeCandidateOrUpgraded = 1 << 27,
+        CustomElementHasDefinitionOrIsUpgraded = 1 << 28,
 
         DefaultNodeFlags = IsParsingChildrenFinishedFlag
     };
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index 8ea7f81..f403465 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -26,6 +26,7 @@
 #include "config.h"
 #include "core/dom/NodeRenderingContext.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ContainerNode.h"
diff --git a/Source/core/dom/ParentNode.idl b/Source/core/dom/ParentNode.idl
index 10b418e..358271b 100644
--- a/Source/core/dom/ParentNode.idl
+++ b/Source/core/dom/ParentNode.idl
@@ -1,5 +1,6 @@
 [
-    NoInterfaceObject
+    NoInterfaceObject,
+    LegacyImplementedInBaseClass
 ] interface ParentNode {
     [PerWorldBindings] readonly attribute HTMLCollection children;
     [PerWorldBindings] readonly attribute Element firstElementChild;
diff --git a/Source/core/dom/PopStateEvent.cpp b/Source/core/dom/PopStateEvent.cpp
index 78456c8..6bd19f3 100644
--- a/Source/core/dom/PopStateEvent.cpp
+++ b/Source/core/dom/PopStateEvent.cpp
@@ -43,7 +43,6 @@
 
 PopStateEvent::PopStateEvent(const AtomicString& type, const PopStateEventInit& initializer)
     : Event(type, initializer)
-    , m_serializedState(0)
     , m_history(0)
 {
     ScriptWrappable::init(this);
diff --git a/Source/core/dom/PopStateEvent.h b/Source/core/dom/PopStateEvent.h
index cbe4627..46f6dd8 100644
--- a/Source/core/dom/PopStateEvent.h
+++ b/Source/core/dom/PopStateEvent.h
@@ -31,11 +31,11 @@
 
 namespace WebCore {
 
-typedef EventInit PopStateEventInit;
-
 class History;
 class SerializedScriptValue;
 
+typedef EventInit PopStateEventInit;
+
 class PopStateEvent : public Event {
 public:
     virtual ~PopStateEvent();
@@ -44,6 +44,11 @@
     static PassRefPtr<PopStateEvent> create(const AtomicString&, const PopStateEventInit&);
 
     SerializedScriptValue* serializedState() const { return m_serializedState.get(); }
+    void setSerializedState(PassRefPtr<SerializedScriptValue> state)
+    {
+        ASSERT(!m_serializedState);
+        m_serializedState = state;
+    }
     History* history() const { return m_history.get(); }
 
     virtual const AtomicString& interfaceName() const;
diff --git a/Source/core/dom/ScriptExecutionContext.cpp b/Source/core/dom/ScriptExecutionContext.cpp
index b292094..6c0b210 100644
--- a/Source/core/dom/ScriptExecutionContext.cpp
+++ b/Source/core/dom/ScriptExecutionContext.cpp
@@ -60,15 +60,17 @@
 class ScriptExecutionContext::PendingException {
     WTF_MAKE_NONCOPYABLE(PendingException);
 public:
-    PendingException(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
+    PendingException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
         : m_errorMessage(errorMessage)
         , m_lineNumber(lineNumber)
+        , m_columnNumber(columnNumber)
         , m_sourceURL(sourceURL)
         , m_callStack(callStack)
     {
     }
     String m_errorMessage;
     int m_lineNumber;
+    int m_columnNumber;
     String m_sourceURL;
     RefPtr<ScriptCallStack> m_callStack;
 };
@@ -193,7 +195,7 @@
     }
 }
 
-bool ScriptExecutionContext::sanitizeScriptError(String& errorMessage, int& lineNumber, String& sourceURL, CachedScript* cachedScript)
+bool ScriptExecutionContext::sanitizeScriptError(String& errorMessage, int& lineNumber, int& columnNumber, String& sourceURL, CachedScript* cachedScript)
 {
     KURL targetURL = completeURL(sourceURL);
     if (securityOrigin()->canRequest(targetURL) || (cachedScript && cachedScript->passesAccessControlCheck(securityOrigin())))
@@ -201,28 +203,29 @@
     errorMessage = "Script error.";
     sourceURL = String();
     lineNumber = 0;
+    columnNumber = 0;
     return true;
 }
 
-void ScriptExecutionContext::reportException(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack, CachedScript* cachedScript)
+void ScriptExecutionContext::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack, CachedScript* cachedScript)
 {
     if (m_inDispatchErrorEvent) {
         if (!m_pendingExceptions)
             m_pendingExceptions = adoptPtr(new Vector<OwnPtr<PendingException> >());
-        m_pendingExceptions->append(adoptPtr(new PendingException(errorMessage, lineNumber, sourceURL, callStack)));
+        m_pendingExceptions->append(adoptPtr(new PendingException(errorMessage, lineNumber, columnNumber, sourceURL, callStack)));
         return;
     }
 
     // First report the original exception and only then all the nested ones.
-    if (!dispatchErrorEvent(errorMessage, lineNumber, sourceURL, cachedScript))
-        logExceptionToConsole(errorMessage, sourceURL, lineNumber, callStack);
+    if (!dispatchErrorEvent(errorMessage, lineNumber, columnNumber, sourceURL, cachedScript))
+        logExceptionToConsole(errorMessage, sourceURL, lineNumber, columnNumber, callStack);
 
     if (!m_pendingExceptions)
         return;
 
     for (size_t i = 0; i < m_pendingExceptions->size(); i++) {
         PendingException* e = m_pendingExceptions->at(i).get();
-        logExceptionToConsole(e->m_errorMessage, e->m_sourceURL, e->m_lineNumber, e->m_callStack);
+        logExceptionToConsole(e->m_errorMessage, e->m_sourceURL, e->m_lineNumber, e->m_columnNumber, e->m_callStack);
     }
     m_pendingExceptions.clear();
 }
@@ -232,7 +235,7 @@
     addMessage(source, level, message, sourceURL, lineNumber, 0, state, requestIdentifier);
 }
 
-bool ScriptExecutionContext::dispatchErrorEvent(const String& errorMessage, int lineNumber, const String& sourceURL, CachedScript* cachedScript)
+bool ScriptExecutionContext::dispatchErrorEvent(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, CachedScript* cachedScript)
 {
     EventTarget* target = errorEventTarget();
     if (!target)
@@ -240,12 +243,13 @@
 
     String message = errorMessage;
     int line = lineNumber;
+    int column = columnNumber;
     String sourceName = sourceURL;
-    sanitizeScriptError(message, line, sourceName, cachedScript);
+    sanitizeScriptError(message, line, column, sourceName, cachedScript);
 
     ASSERT(!m_inDispatchErrorEvent);
     m_inDispatchErrorEvent = true;
-    RefPtr<ErrorEvent> errorEvent = ErrorEvent::create(message, sourceName, line);
+    RefPtr<ErrorEvent> errorEvent = ErrorEvent::create(message, sourceName, line, column);
     target->dispatchEvent(errorEvent);
     m_inDispatchErrorEvent = false;
     return errorEvent->defaultPrevented();
@@ -259,7 +263,7 @@
     return m_circularSequentialID;
 }
 
-int ScriptExecutionContext::installNewTimeout(PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot)
+int ScriptExecutionContext::installNewTimeout(DOMTimer::Type timerType, PassOwnPtr<ScheduledAction> action, int timeout)
 {
     int timeoutID;
     while (true) {
@@ -267,20 +271,25 @@
         if (!m_timeouts.contains(timeoutID))
             break;
     }
-    TimeoutMap::AddResult result = m_timeouts.add(timeoutID, DOMTimer::create(this, action, timeout, singleShot, timeoutID));
+    TimeoutMap::AddResult result = m_timeouts.add(timeoutID, DOMTimer::create(this, timerType, action, timeout, timeoutID));
     ASSERT(result.isNewEntry);
     DOMTimer* timer = result.iterator->value.get();
 
     timer->suspendIfNeeded();
 
-    return timer->timeoutID();
+    return timeoutID;
 }
 
-void ScriptExecutionContext::removeTimeoutByID(int timeoutID)
+bool ScriptExecutionContext::removeTimeoutByIDIfTypeMatches(DOMTimer::Type timerType, int timeoutID)
 {
     if (timeoutID <= 0)
-        return;
-    m_timeouts.remove(timeoutID);
+        return false;
+    TimeoutMap::iterator iter = m_timeouts.find(timeoutID);
+    if (iter != m_timeouts.end() && iter->value->type() == timerType) {
+        m_timeouts.remove(iter);
+        return true;
+    }
+    return false;
 }
 
 PublicURLManager& ScriptExecutionContext::publicURLManager()
diff --git a/Source/core/dom/ScriptExecutionContext.h b/Source/core/dom/ScriptExecutionContext.h
index d438f53..48be118 100644
--- a/Source/core/dom/ScriptExecutionContext.h
+++ b/Source/core/dom/ScriptExecutionContext.h
@@ -69,8 +69,8 @@
 
     virtual void disableEval(const String& errorMessage) = 0;
 
-    bool sanitizeScriptError(String& errorMessage, int& lineNumber, String& sourceURL, CachedScript* = 0);
-    void reportException(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack>, CachedScript* = 0);
+    bool sanitizeScriptError(String& errorMessage, int& lineNumber, int& columnNumber, String& sourceURL, CachedScript* = 0);
+    void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, PassRefPtr<ScriptCallStack>, CachedScript* = 0);
 
     void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* = 0, unsigned long requestIdentifier = 0);
     virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0) = 0;
@@ -158,8 +158,8 @@
 
     virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState* = 0, unsigned long requestIdentifier = 0) = 0;
     virtual EventTarget* errorEventTarget() = 0;
-    virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack>) = 0;
-    bool dispatchErrorEvent(const String& errorMessage, int lineNumber, const String& sourceURL, CachedScript*);
+    virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) = 0;
+    bool dispatchErrorEvent(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, CachedScript*);
 
     void closeMessagePorts();
 
@@ -168,8 +168,8 @@
     virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
 
     // Implementation details for DOMTimer. No other classes should call these functions.
-    int installNewTimeout(PassOwnPtr<ScheduledAction>, int timeout, bool singleShot);
-    void removeTimeoutByID(int timeoutID); // This makes underlying DOMTimer instance destructed.
+    int installNewTimeout(DOMTimer::Type, PassOwnPtr<ScheduledAction>, int timeout);
+    bool removeTimeoutByIDIfTypeMatches(DOMTimer::Type, int timeoutID); // This makes underlying DOMTimer instance destructed. Returns true if removed.
 
     HashSet<MessagePort*> m_messagePorts;
 
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index df9209c..a5f47dd 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -339,7 +339,7 @@
         adopter.execute();
 }
 
-static Node* focusedFrameOwnerElement(Frame* focusedFrame, Frame* currentFrame)
+static Element* focusedFrameOwnerElement(Frame* focusedFrame, Frame* currentFrame)
 {
     for (; focusedFrame; focusedFrame = focusedFrame->tree()->parent()) {
         if (focusedFrame->tree()->parent() == currentFrame)
@@ -351,20 +351,26 @@
 Element* TreeScope::adjustedFocusedElement()
 {
     Document* document = rootNode()->document();
-    Node* node = document->focusedNode();
-    if (!node && document->page())
-        node = focusedFrameOwnerElement(document->page()->focusController()->focusedFrame(), document->frame());
-    if (!node)
+    Element* element = document->focusedElement();
+    if (!element && document->page())
+        element = focusedFrameOwnerElement(document->page()->focusController()->focusedFrame(), document->frame());
+    if (!element)
         return 0;
     Vector<Node*> targetStack;
-    for (EventPathWalker walker(node); walker.node(); walker.moveToParent()) {
+    for (EventPathWalker walker(element); walker.node(); walker.moveToParent()) {
         Node* node = walker.node();
         if (targetStack.isEmpty())
             targetStack.append(node);
         else if (walker.isVisitingInsertionPointInReprojection())
             targetStack.append(targetStack.last());
-        if (node == rootNode())
+        if (node == rootNode()) {
+            // targetStack.last() is one of the followings:
+            // - InsertionPoint
+            // - shadow host
+            // - Document::focusedElement()
+            // So, it's safe to do toElement().
             return toElement(targetStack.last());
+        }
         if (node->isShadowRoot()) {
             ASSERT(!targetStack.isEmpty());
             targetStack.removeLast();
diff --git a/Source/core/dom/UserTypingGestureIndicator.cpp b/Source/core/dom/UserTypingGestureIndicator.cpp
index 1200868..e05967e 100644
--- a/Source/core/dom/UserTypingGestureIndicator.cpp
+++ b/Source/core/dom/UserTypingGestureIndicator.cpp
@@ -27,9 +27,8 @@
 #include "core/dom/UserTypingGestureIndicator.h"
 
 #include "core/dom/Document.h"
-#include "core/dom/Node.h"
+#include "core/dom/Element.h"
 #include "core/page/Frame.h"
-#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
@@ -39,29 +38,29 @@
     return s_processingUserTypingGesture;
 }
 
-static RefPtr<Node>& focusedNode()
+static RefPtr<Element>& focusedElement()
 {
-    DEFINE_STATIC_LOCAL(RefPtr<Node>, node, ());
-    return node;
+    DEFINE_STATIC_LOCAL(RefPtr<Element>, element, ());
+    return element;
 }
 
-Node* UserTypingGestureIndicator::focusedElementAtGestureStart()
+Element* UserTypingGestureIndicator::focusedElementAtGestureStart()
 {
-    return focusedNode().get();
+    return focusedElement().get();
 }
 
 UserTypingGestureIndicator::UserTypingGestureIndicator(Frame* frame)
     : m_previousProcessingUserTypingGesture(s_processingUserTypingGesture)
-    , m_previousFocusedNode(focusedNode())
+    , m_previousFocusedElement(focusedElement())
 {
     s_processingUserTypingGesture = true;
-    focusedNode() = frame->document() ? frame->document()->focusedNode() : 0;
+    focusedElement() = frame->document() ? frame->document()->focusedElement() : 0;
 }
 
 UserTypingGestureIndicator::~UserTypingGestureIndicator()
 {
     s_processingUserTypingGesture = m_previousProcessingUserTypingGesture;
-    focusedNode() = m_previousFocusedNode;
+    focusedElement() = m_previousFocusedElement;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/UserTypingGestureIndicator.h b/Source/core/dom/UserTypingGestureIndicator.h
index 149c430..02a9794 100644
--- a/Source/core/dom/UserTypingGestureIndicator.h
+++ b/Source/core/dom/UserTypingGestureIndicator.h
@@ -32,20 +32,20 @@
 namespace WebCore {
 
 class Frame;
-class Node;
+class Element;
 
 class UserTypingGestureIndicator {
     WTF_MAKE_NONCOPYABLE(UserTypingGestureIndicator);
 public:
     static bool processingUserTypingGesture();
-    static Node* focusedElementAtGestureStart();
+    static Element* focusedElementAtGestureStart();
 
     explicit UserTypingGestureIndicator(Frame*);
     ~UserTypingGestureIndicator();
 
 private:
     bool m_previousProcessingUserTypingGesture;
-    RefPtr<Node> m_previousFocusedNode;
+    RefPtr<Element> m_previousFocusedElement;
 };    
 
 } // namespace WebCore
diff --git a/Source/core/dom/ViewportArguments.cpp b/Source/core/dom/ViewportArguments.cpp
index d6a56f9..92ae2cf 100644
--- a/Source/core/dom/ViewportArguments.cpp
+++ b/Source/core/dom/ViewportArguments.cpp
@@ -6,7 +6,7 @@
  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
  * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ * Copyright (C) 2012-2013 Intel Corporation. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -37,8 +37,6 @@
 
 static const float& compareIgnoringAuto(const float& value1, const float& value2, const float& (*compare) (const float&, const float&))
 {
-    ASSERT(value1 != ViewportArguments::ValueAuto || value2 != ViewportArguments::ValueAuto);
-
     if (value1 == ViewportArguments::ValueAuto)
         return value2;
 
@@ -78,29 +76,12 @@
     float resultHeight = height;
     float resultMinHeight = minHeight;
     float resultMaxHeight = maxHeight;
+
     float resultZoom = zoom;
     float resultMinZoom = minZoom;
     float resultMaxZoom = maxZoom;
     float resultUserZoom = userZoom;
 
-    switch (int(resultWidth)) {
-    case ViewportArguments::ValueDeviceWidth:
-        resultWidth = deviceSize.width();
-        break;
-    case ViewportArguments::ValueDeviceHeight:
-        resultWidth = deviceSize.height();
-        break;
-    }
-
-    switch (int(resultHeight)) {
-    case ViewportArguments::ValueDeviceWidth:
-        resultHeight = deviceSize.width();
-        break;
-    case ViewportArguments::ValueDeviceHeight:
-        resultHeight = deviceSize.height();
-        break;
-    }
-
     if (type == ViewportArguments::CSSDeviceAdaptation) {
 
         // device-width/device-height not supported for @viewport.
@@ -113,35 +94,97 @@
         ASSERT(resultMaxHeight != ViewportArguments::ValueDeviceWidth);
         ASSERT(resultMaxHeight != ViewportArguments::ValueDeviceHeight);
 
-        if (resultMinWidth != ViewportArguments::ValueAuto || resultMaxWidth != ViewportArguments::ValueAuto)
-            resultWidth = compareIgnoringAuto(resultMinWidth, compareIgnoringAuto(resultMaxWidth, initialViewportSize.width(), min), max);
-
-        if (resultMinHeight != ViewportArguments::ValueAuto || resultMaxHeight != ViewportArguments::ValueAuto)
-            resultHeight = compareIgnoringAuto(resultMinHeight, compareIgnoringAuto(resultMaxHeight, initialViewportSize.height(), min), max);
-
+        // 1. Resolve min-zoom and max-zoom values.
         if (resultMinZoom != ViewportArguments::ValueAuto && resultMaxZoom != ViewportArguments::ValueAuto)
             resultMaxZoom = max(resultMinZoom, resultMaxZoom);
 
+        // 2. Constrain zoom value to the [min-zoom, max-zoom] range.
         if (resultZoom != ViewportArguments::ValueAuto)
             resultZoom = compareIgnoringAuto(resultMinZoom, compareIgnoringAuto(resultMaxZoom, resultZoom, min), max);
 
-        if (resultWidth == ViewportArguments::ValueAuto && (resultHeight == ViewportArguments::ValueAuto || !initialViewportSize.height()))
-            resultWidth = initialViewportSize.width();
+        float extendZoom = compareIgnoringAuto(resultZoom, resultMaxZoom, min);
 
-        if (resultWidth == ViewportArguments::ValueAuto) {
-            ASSERT(initialViewportSize.height()); // If height is 0, resultWidth should be resolved above.
-            resultWidth = resultHeight * initialViewportSize.width() / initialViewportSize.height();
+        if (extendZoom == ViewportArguments::ValueAuto) {
+            if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
+                resultMaxWidth = ViewportArguments::ValueAuto;
+
+            if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
+                resultMaxHeight = ViewportArguments::ValueAuto;
+
+            if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
+                resultMinWidth = resultMaxWidth;
+
+            if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
+                resultMinHeight = resultMaxHeight;
+        } else {
+            float extendWidth = initialViewportSize.width() / extendZoom;
+            float extendHeight = initialViewportSize.height() / extendZoom;
+
+            if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
+                resultMaxWidth = extendWidth;
+
+            if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
+                resultMaxHeight = extendHeight;
+
+            if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
+                resultMinWidth = compareIgnoringAuto(extendWidth, resultMaxWidth, max);
+
+            if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
+                resultMinHeight = compareIgnoringAuto(extendHeight, resultMaxHeight, max);
         }
 
+        // 4. Resolve initial width from min/max descriptors.
+        if (resultMinWidth != ViewportArguments::ValueAuto || resultMaxWidth != ViewportArguments::ValueAuto)
+            resultWidth = compareIgnoringAuto(resultMinWidth, compareIgnoringAuto(resultMaxWidth, initialViewportSize.width(), min), max);
+
+        // 5. Resolve initial height from min/max descriptors.
+        if (resultMinHeight != ViewportArguments::ValueAuto || resultMaxHeight != ViewportArguments::ValueAuto)
+            resultHeight = compareIgnoringAuto(resultMinHeight, compareIgnoringAuto(resultMaxHeight, initialViewportSize.height(), min), max);
+
+        // 6-7. Resolve width value.
+        if (resultWidth == ViewportArguments::ValueAuto) {
+            if (resultHeight == ViewportArguments::ValueAuto || !initialViewportSize .height())
+                resultWidth = initialViewportSize.width();
+            else
+                resultWidth = resultHeight * (initialViewportSize.width() / initialViewportSize.height());
+        }
+
+        // 8. Resolve height value.
         if (resultHeight == ViewportArguments::ValueAuto) {
             if (!initialViewportSize.width())
                 resultHeight = initialViewportSize.height();
             else
                 resultHeight = resultWidth * initialViewportSize.height() / initialViewportSize.width();
         }
+
+        PageScaleConstraints result;
+        result.minimumScale = resultMinZoom;
+        result.maximumScale = resultMaxZoom;
+        result.initialScale = resultZoom;
+        result.layoutSize.setWidth(resultWidth);
+        result.layoutSize.setHeight(resultHeight);
+        return result;
     }
 
-    if (type != ViewportArguments::CSSDeviceAdaptation && type != ViewportArguments::Implicit) {
+    switch (static_cast<int>(resultWidth)) {
+    case ViewportArguments::ValueDeviceWidth:
+        resultWidth = deviceSize.width();
+        break;
+    case ViewportArguments::ValueDeviceHeight:
+        resultWidth = deviceSize.height();
+        break;
+    }
+
+    switch (static_cast<int>(resultHeight)) {
+    case ViewportArguments::ValueDeviceWidth:
+        resultHeight = deviceSize.width();
+        break;
+    case ViewportArguments::ValueDeviceHeight:
+        resultHeight = deviceSize.height();
+        break;
+    }
+
+    if (type != ViewportArguments::Implicit) {
         // Clamp values to a valid range, but not for @viewport since is
         // not mandated by the specification.
         resultWidth = clampLengthValue(resultWidth);
diff --git a/Source/core/dom/ViewportArguments.h b/Source/core/dom/ViewportArguments.h
index 925604a..5afacfe 100644
--- a/Source/core/dom/ViewportArguments.h
+++ b/Source/core/dom/ViewportArguments.h
@@ -6,7 +6,7 @@
  * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
  * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ * Copyright (C) 2012-2013 Intel Corporation. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -65,7 +65,8 @@
         ValueDeviceDPI = -6,
         ValueLowDPI = -7,
         ValueMediumDPI = -8,
-        ValueHighDPI = -9
+        ValueHighDPI = -9,
+        ValueExtendToZoom = -10
     };
 
     ViewportArguments(Type type = Implicit)
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 4518e29..b767737 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -56,7 +56,7 @@
 
     while (RefPtr<ShadowRoot> oldRoot = m_shadowRoots.head()) {
         InspectorInstrumentation::willPopShadowRoot(shadowHost, oldRoot.get());
-        shadowHost->document()->removeFocusedNodeOfSubtree(oldRoot.get());
+        shadowHost->document()->removeFocusedElementOfSubtree(oldRoot.get());
 
         if (oldRoot->attached())
             oldRoot->detach();