Upstream version 10.38.208.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / page / EventHandler.cpp
old mode 100755 (executable)
new mode 100644 (file)
index c6c5a70..f0166a1
 #include "config.h"
 #include "core/page/EventHandler.h"
 
-#include "HTMLNames.h"
-#include "RuntimeEnabledFeatures.h"
-#include "SVGNames.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/Clipboard.h"
-#include "core/dom/DataObject.h"
+#include "bindings/core/v8/ExceptionStatePlaceholder.h"
+#include "core/HTMLNames.h"
+#include "core/SVGNames.h"
+#include "core/clipboard/DataObject.h"
+#include "core/clipboard/DataTransfer.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/events/MouseEvent.h"
 #include "core/events/TextEvent.h"
-#include "core/events/ThreadLocalEventNames.h"
 #include "core/events/TouchEvent.h"
 #include "core/events/WheelEvent.h"
 #include "core/fetch/ImageResource.h"
+#include "core/frame/EventHandlerRegistry.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/LocalFrame.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLDialogElement.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLFrameSetElement.h"
 #include "core/html/HTMLInputElement.h"
+#include "core/inspector/InspectorController.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/AutoscrollController.h"
 #include "core/page/DragController.h"
 #include "core/page/DragState.h"
 #include "core/page/EditorClient.h"
+#include "core/page/EventWithHitTestResults.h"
 #include "core/page/FocusController.h"
-#include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
-#include "core/frame/FrameView.h"
-#include "core/inspector/InspectorController.h"
-#include "core/page/MouseEventWithHitTestResults.h"
 #include "core/page/Page.h"
-#include "core/frame/Settings.h"
 #include "core/page/SpatialNavigation.h"
 #include "core/page/TouchAdjustment.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
-#include "core/rendering/style/CursorList.h"
 #include "core/rendering/style/RenderStyle.h"
-#include "core/svg/SVGDocument.h"
-#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGUseElement.h"
+#include "core/svg/SVGDocumentExtensions.h"
 #include "platform/PlatformGestureEvent.h"
 #include "platform/PlatformKeyboardEvent.h"
 #include "platform/PlatformTouchEvent.h"
 #include "platform/PlatformWheelEvent.h"
+#include "platform/RuntimeEnabledFeatures.h"
+#include "platform/TraceEvent.h"
 #include "platform/WindowsKeyboardCodes.h"
 #include "platform/geometry/FloatPoint.h"
 #include "platform/graphics/Image.h"
+#include "platform/heap/Handle.h"
 #include "platform/scroll/ScrollAnimator.h"
 #include "platform/scroll/Scrollbar.h"
 #include "wtf/Assertions.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/TemporaryChange.h"
 
-namespace WebCore {
+namespace blink {
 
 using namespace HTMLNames;
-using namespace SVGNames;
 
 // The link drag hysteresis is much larger than the others because there
 // needs to be enough space to cancel the link press without starting a link drag,
@@ -134,8 +131,8 @@ static const int maximumCursorSize = 128;
 static const double minimumCursorScale = 0.001;
 
 // The minimum amount of time an element stays active after a ShowPress
-// This is roughly 2 frames, which should be long enough to be noticeable.
-static const double minimumActiveInterval = 0.032;
+// This is roughly 9 frames, which should be long enough to be noticeable.
+static const double minimumActiveInterval = 0.15;
 
 #if OS(MACOSX)
 static const double TextDragDelay = 0.15;
@@ -176,71 +173,6 @@ private:
     double m_start;
 };
 
-class SyntheticTouchPoint : public PlatformTouchPoint {
-public:
-
-    // The default values are based on http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
-    explicit SyntheticTouchPoint(const PlatformMouseEvent& event)
-    {
-        const static int idDefaultValue = 0;
-        const static int radiusYDefaultValue = 1;
-        const static int radiusXDefaultValue = 1;
-        const static float rotationAngleDefaultValue = 0.0f;
-        const static float forceDefaultValue = 1.0f;
-
-        m_id = idDefaultValue; // There is only one active TouchPoint.
-        m_screenPos = event.globalPosition();
-        m_pos = event.position();
-        m_radiusY = radiusYDefaultValue;
-        m_radiusX = radiusXDefaultValue;
-        m_rotationAngle = rotationAngleDefaultValue;
-        m_force = forceDefaultValue;
-
-        PlatformEvent::Type type = event.type();
-        ASSERT(type == PlatformEvent::MouseMoved || type == PlatformEvent::MousePressed || type == PlatformEvent::MouseReleased);
-
-        switch (type) {
-        case PlatformEvent::MouseMoved:
-            m_state = TouchMoved;
-            break;
-        case PlatformEvent::MousePressed:
-            m_state = TouchPressed;
-            break;
-        case PlatformEvent::MouseReleased:
-            m_state = TouchReleased;
-            break;
-        default:
-            ASSERT_NOT_REACHED();
-            break;
-        }
-    }
-};
-
-class SyntheticSingleTouchEvent : public PlatformTouchEvent {
-public:
-    explicit SyntheticSingleTouchEvent(const PlatformMouseEvent& event)
-    {
-        switch (event.type()) {
-        case PlatformEvent::MouseMoved:
-            m_type = TouchMove;
-            break;
-        case PlatformEvent::MousePressed:
-            m_type = TouchStart;
-            break;
-        case PlatformEvent::MouseReleased:
-            m_type = TouchEnd;
-            break;
-        default:
-            ASSERT_NOT_REACHED();
-            m_type = NoType;
-            break;
-        }
-        m_timestamp = event.timestamp();
-        m_modifiers = event.modifiers();
-        m_touchPoints.append(SyntheticTouchPoint(event));
-    }
-};
-
 static inline ScrollGranularity wheelGranularityToScrollGranularity(unsigned deltaMode)
 {
     switch (deltaMode) {
@@ -264,10 +196,10 @@ static inline bool shouldRefetchEventTarget(const MouseEventWithHitTestResults&
     Node* targetNode = mev.targetNode();
     if (!targetNode || !targetNode->parentNode())
         return true;
-    return targetNode->isShadowRoot() && toShadowRoot(targetNode)->host()->hasTagName(inputTag);
+    return targetNode->isShadowRoot() && isHTMLInputElement(*toShadowRoot(targetNode)->host());
 }
 
-EventHandler::EventHandler(Frame* frame)
+EventHandler::EventHandler(LocalFrame* frame)
     : m_frame(frame)
     , m_mousePressed(false)
     , m_capturesDragging(false)
@@ -288,15 +220,12 @@ EventHandler::EventHandler(Frame* frame)
     , m_mousePositionIsUnknown(true)
     , m_mouseDownTimestamp(0)
     , m_widgetIsLatched(false)
-    , m_originatingTouchPointTargetKey(0)
     , m_touchPressed(false)
-    , m_scrollGestureHandlingNode(0)
-    , m_lastHitTestResultOverWidget(false)
+    , m_scrollGestureHandlingNode(nullptr)
+    , m_lastGestureScrollOverWidget(false)
     , m_maxMouseMovedDuration(0)
-    , m_baseEventType(PlatformEvent::NoType)
     , m_didStartDrag(false)
     , m_longTapShouldInvokeContextMenu(false)
-    , m_syntheticPageScaleFactor(0)
     , m_activeIntervalTimer(this, &EventHandler::activeIntervalTimerFired)
     , m_lastShowPressTimestamp(0)
 {
@@ -307,10 +236,30 @@ EventHandler::~EventHandler()
     ASSERT(!m_fakeMouseMoveEventTimer.isActive());
 }
 
+void EventHandler::trace(Visitor* visitor)
+{
+#if ENABLE(OILPAN)
+    visitor->trace(m_mousePressNode);
+    visitor->trace(m_capturingMouseEventsNode);
+    visitor->trace(m_nodeUnderMouse);
+    visitor->trace(m_lastNodeUnderMouse);
+    visitor->trace(m_clickNode);
+    visitor->trace(m_dragTarget);
+    visitor->trace(m_frameSetBeingResized);
+    visitor->trace(m_latchedWheelEventNode);
+    visitor->trace(m_previousWheelScrolledNode);
+    visitor->trace(m_targetForTouchID);
+    visitor->trace(m_touchSequenceDocument);
+    visitor->trace(m_scrollGestureHandlingNode);
+    visitor->trace(m_previousGestureScrolledNode);
+    visitor->trace(m_lastDeferredTapElement);
+#endif
+}
+
 DragState& EventHandler::dragState()
 {
-    DEFINE_STATIC_LOCAL(DragState, state, ());
-    return state;
+    DEFINE_STATIC_LOCAL(OwnPtrWillBePersistent<DragState>, state, (adoptPtrWillBeNoop(new DragState())));
+    return *state;
 }
 
 void EventHandler::clear()
@@ -320,42 +269,39 @@ void EventHandler::clear()
     m_fakeMouseMoveEventTimer.stop();
     m_activeIntervalTimer.stop();
     m_resizeScrollableArea = 0;
-    m_nodeUnderMouse = 0;
-    m_lastNodeUnderMouse = 0;
-    m_instanceUnderMouse = 0;
-    m_lastInstanceUnderMouse = 0;
-    m_lastMouseMoveEventSubframe = 0;
-    m_lastScrollbarUnderMouse = 0;
+    m_nodeUnderMouse = nullptr;
+    m_lastNodeUnderMouse = nullptr;
+    m_lastMouseMoveEventSubframe = nullptr;
+    m_lastScrollbarUnderMouse = nullptr;
     m_clickCount = 0;
-    m_clickNode = 0;
-    m_frameSetBeingResized = 0;
-    m_dragTarget = 0;
+    m_clickNode = nullptr;
+    m_frameSetBeingResized = nullptr;
+    m_dragTarget = nullptr;
     m_shouldOnlyFireDragOverEvent = false;
     m_mousePositionIsUnknown = true;
     m_lastKnownMousePosition = IntPoint();
     m_lastKnownMouseGlobalPosition = IntPoint();
     m_lastMouseDownUserGestureToken.clear();
-    m_mousePressNode = 0;
+    m_mousePressNode = nullptr;
     m_mousePressed = false;
     m_capturesDragging = false;
-    m_capturingMouseEventsNode = 0;
-    m_latchedWheelEventNode = 0;
-    m_previousWheelScrolledNode = 0;
-    m_originatingTouchPointTargets.clear();
-    m_originatingTouchPointDocument.clear();
-    m_originatingTouchPointTargetKey = 0;
-    m_scrollGestureHandlingNode = 0;
-    m_lastHitTestResultOverWidget = false;
-    m_previousGestureScrolledNode = 0;
-    m_scrollbarHandlingScrollGesture = 0;
+    m_capturingMouseEventsNode = nullptr;
+    m_latchedWheelEventNode = nullptr;
+    m_previousWheelScrolledNode = nullptr;
+    m_targetForTouchID.clear();
+    m_touchSequenceDocument.clear();
+    m_touchSequenceUserGestureToken.clear();
+    m_scrollGestureHandlingNode = nullptr;
+    m_lastGestureScrollOverWidget = false;
+    m_previousGestureScrolledNode = nullptr;
+    m_scrollbarHandlingScrollGesture = nullptr;
     m_maxMouseMovedDuration = 0;
-    m_baseEventType = PlatformEvent::NoType;
     m_didStartDrag = false;
     m_touchPressed = false;
     m_mouseDownMayStartSelect = false;
     m_mouseDownMayStartDrag = false;
     m_lastShowPressTimestamp = 0;
-    m_lastDeferredTapElement = 0;
+    m_lastDeferredTapElement = nullptr;
 }
 
 void EventHandler::nodeWillBeRemoved(Node& nodeToBeRemoved)
@@ -367,7 +313,7 @@ void EventHandler::nodeWillBeRemoved(Node& nodeToBeRemoved)
     } else {
         // We don't dispatch click events if the mousedown node is removed
         // before a mouseup event. It is compatible with IE and Firefox.
-        m_clickNode = 0;
+        m_clickNode = nullptr;
     }
 }
 
@@ -447,7 +393,7 @@ void EventHandler::selectClosestMisspellingFromHitTestResult(const HitTestResult
         Position start = pos.deepEquivalent();
         Position end = pos.deepEquivalent();
         if (pos.isNotNull()) {
-            Vector<DocumentMarker*> markers = innerNode->document().markers()->markersInRange(makeRange(pos, pos).get(), DocumentMarker::MisspellingMarkers());
+            DocumentMarkerVector markers = innerNode->document().markers().markersInRange(makeRange(pos, pos).get(), DocumentMarker::MisspellingMarkers());
             if (markers.size() == 1) {
                 start.moveToOffset(markers[0]->startOffset());
                 end.moveToOffset(markers[0]->endOffset());
@@ -498,6 +444,8 @@ void EventHandler::selectClosestWordOrLinkFromMouseEvent(const MouseEventWithHit
 
 bool EventHandler::handleMousePressEventDoubleClick(const MouseEventWithHitTestResults& event)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMousePressEventDoubleClick");
+
     if (event.event().button() != LeftButton)
         return false;
 
@@ -516,6 +464,8 @@ bool EventHandler::handleMousePressEventDoubleClick(const MouseEventWithHitTestR
 
 bool EventHandler::handleMousePressEventTripleClick(const MouseEventWithHitTestResults& event)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMousePressEventTripleClick");
+
     if (event.event().button() != LeftButton)
         return false;
 
@@ -535,12 +485,14 @@ bool EventHandler::handleMousePressEventTripleClick(const MouseEventWithHitTestR
 
 static int textDistance(const Position& start, const Position& end)
 {
-    RefPtr<Range> range = Range::create(*start.document(), start, end);
+    RefPtrWillBeRawPtr<Range> range = Range::create(*start.document(), start, end);
     return TextIterator::rangeLength(range.get(), true);
 }
 
 bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMousePressEventSingleClick");
+
     m_frame->document()->updateLayoutIgnorePendingStylesheets();
     Node* innerNode = event.targetNode();
     if (!(innerNode && innerNode->renderer() && m_mouseDownMayStartSelect))
@@ -568,7 +520,7 @@ bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestR
     TextGranularity granularity = CharacterGranularity;
 
     if (extendSelection && newSelection.isCaretOrRange()) {
-        VisibleSelection selectionInUserSelectAll = expandSelectionToRespectUserSelectAll(innerNode, VisibleSelection(pos));
+        VisibleSelection selectionInUserSelectAll(expandSelectionToRespectUserSelectAll(innerNode, VisibleSelection(VisiblePosition(pos))));
         if (selectionInUserSelectAll.isRange()) {
             if (comparePositions(selectionInUserSelectAll.start(), newSelection.start()) < 0)
                 pos = selectionInUserSelectAll.start();
@@ -577,16 +529,18 @@ bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestR
         }
 
         if (!m_frame->editor().behavior().shouldConsiderSelectionAsDirectional()) {
-            // See <rdar://problem/3668157> REGRESSION (Mail): shift-click deselects when selection
-            // was created right-to-left
-            Position start = newSelection.start();
-            Position end = newSelection.end();
-            int distanceToStart = textDistance(start, pos);
-            int distanceToEnd = textDistance(pos, end);
-            if (distanceToStart <= distanceToEnd)
-                newSelection = VisibleSelection(end, pos);
-            else
-                newSelection = VisibleSelection(start, pos);
+            if (pos.isNotNull()) {
+                // See <rdar://problem/3668157> REGRESSION (Mail): shift-click deselects when selection
+                // was created right-to-left
+                Position start = newSelection.start();
+                Position end = newSelection.end();
+                int distanceToStart = textDistance(start, pos);
+                int distanceToEnd = textDistance(pos, end);
+                if (distanceToStart <= distanceToEnd)
+                    newSelection = VisibleSelection(end, pos);
+                else
+                    newSelection = VisibleSelection(start, pos);
+            }
         } else
             newSelection.setExtent(pos);
 
@@ -594,11 +548,13 @@ bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestR
             granularity = m_frame->selection().granularity();
             newSelection.expandUsingGranularity(m_frame->selection().granularity());
         }
-    } else
-        newSelection = expandSelectionToRespectUserSelectAll(innerNode, visiblePos);
+    } else {
+        newSelection = expandSelectionToRespectUserSelectAll(innerNode, VisibleSelection(visiblePos));
+    }
 
-    bool handled = updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, granularity);
-    return handled;
+    // Updating the selection is considered side-effect of the event and so it doesn't impact the handled state.
+    updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, granularity);
+    return false;
 }
 
 static inline bool canMouseDownStartSelect(Node* node)
@@ -614,8 +570,10 @@ static inline bool canMouseDownStartSelect(Node* node)
 
 bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& event)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMousePressEvent");
+
     // Reset drag state.
-    dragState().m_dragSrc = 0;
+    dragState().m_dragSrc = nullptr;
 
     cancelFakeMouseMoveEvent();
 
@@ -641,11 +599,10 @@ bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& eve
     if (event.isOverWidget() && passWidgetMouseDownEventToWidget(event))
         return true;
 
-    if (m_frame->document()->isSVGDocument()
-        && toSVGDocument(m_frame->document())->zoomAndPanEnabled()) {
+    if (m_frame->document()->isSVGDocument() && m_frame->document()->accessSVGExtensions().zoomAndPanEnabled()) {
         if (event.event().shiftKey() && singleClick) {
             m_svgPan = true;
-            toSVGDocument(m_frame->document())->startPan(m_frame->view()->windowToContents(event.event().position()));
+            m_frame->document()->accessSVGExtensions().startPan(m_frame->view()->windowToContents(event.event().position()));
             return true;
         }
     }
@@ -679,6 +636,8 @@ bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& eve
 
 bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& event)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMouseDraggedEvent");
+
     if (!m_mousePressed)
         return false;
 
@@ -691,7 +650,7 @@ bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& e
 
     RenderObject* renderer = targetNode->renderer();
     if (!renderer) {
-        Node* parent = EventPath::parent(targetNode);
+        Node* parent = NodeRenderingTraversal::parent(targetNode);
         if (!parent)
             return false;
 
@@ -710,7 +669,7 @@ bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& e
     }
 
     if (m_selectionInitiationState != ExtendedSelection) {
-        HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+        HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
         HitTestResult result(m_mouseDownPos);
         m_frame->document()->renderView()->hitTest(request, result);
 
@@ -729,7 +688,7 @@ void EventHandler::updateSelectionForMouseDrag()
     if (!renderer)
         return;
 
-    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::Move | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::Move);
     HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
     renderer->hitTest(request, result);
     updateSelectionForMouseDrag(result);
@@ -827,7 +786,7 @@ bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& e
         VisibleSelection newSelection;
         Node* node = event.targetNode();
         bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
-        if (node && node->renderer() && (caretBrowsing || node->rendererIsEditable())) {
+        if (node && node->renderer() && (caretBrowsing || node->hasEditableStyle())) {
             VisiblePosition pos = VisiblePosition(node->renderer()->positionForPoint(event.localPoint()));
             newSelection = VisibleSelection(pos);
         }
@@ -878,11 +837,13 @@ bool EventHandler::panScrollInProgress() const
 
 HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, HitTestRequest::HitTestRequestType hitType, const LayoutSize& padding)
 {
+    TRACE_EVENT0("blink", "EventHandler::hitTestResultAtPoint");
+
     // We always send hitTestResultAtPoint to the main frame if we have one,
     // otherwise we might hit areas that are obscured by higher frames.
-    if (Page* page = m_frame->page()) {
-        Frame* mainFrame = page->mainFrame();
-        if (m_frame != mainFrame) {
+    if (m_frame->page()) {
+        LocalFrame* mainFrame = m_frame->localFrameRoot();
+        if (mainFrame && m_frame != mainFrame) {
             FrameView* frameView = m_frame->view();
             FrameView* mainView = mainFrame->view();
             if (frameView && mainView) {
@@ -909,9 +870,6 @@ HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, HitTe
     if (!request.readOnly())
         m_frame->document()->updateHoverActiveState(request, result.innerElement());
 
-    if (request.disallowsShadowContent())
-        result.setToNodesInDocumentTreeScope();
-
     return result;
 }
 
@@ -959,17 +917,7 @@ bool EventHandler::scroll(ScrollDirection direction, ScrollGranularity granulari
             return true;
         }
 
-        // FIXME: This should probably move to a virtual method on RenderBox, something like
-        // RenderBox::scrollAncestor, and specialized for RenderFlowThread
         curBox = curBox->containingBlock();
-        if (curBox && curBox->isRenderNamedFlowThread()) {
-            RenderBox* flowedBox = curBox;
-
-            if (RenderBox* startBox = node->renderBox())
-                flowedBox = startBox;
-
-            curBox = toRenderFlowThread(curBox)->regionFromAbsolutePointAndBox(absolutePoint, flowedBox);
-        }
     }
 
     return false;
@@ -982,14 +930,15 @@ bool EventHandler::bubblingScroll(ScrollDirection direction, ScrollGranularity g
     m_frame->document()->updateLayoutIgnorePendingStylesheets();
     if (scroll(direction, granularity, startingNode))
         return true;
-    Frame* frame = m_frame;
+    LocalFrame* frame = m_frame;
     FrameView* view = frame->view();
     if (view && view->scroll(direction, granularity))
         return true;
-    frame = frame->tree().parent();
-    if (!frame)
+    Frame* parentFrame = frame->tree().parent();
+    if (!parentFrame || !parentFrame->isLocalFrame())
         return false;
-    return frame->eventHandler().bubblingScroll(direction, granularity, m_frame->ownerElement());
+    // FIXME: Broken for OOPI.
+    return toLocalFrame(parentFrame)->eventHandler().bubblingScroll(direction, granularity, m_frame->deprecatedLocalOwner());
 }
 
 IntPoint EventHandler::lastKnownMousePosition() const
@@ -997,7 +946,7 @@ IntPoint EventHandler::lastKnownMousePosition() const
     return m_lastKnownMousePosition;
 }
 
-static Frame* subframeForTargetNode(Node* node)
+static LocalFrame* subframeForTargetNode(Node* node)
 {
     if (!node)
         return 0;
@@ -1006,6 +955,10 @@ static Frame* subframeForTargetNode(Node* node)
     if (!renderer || !renderer->isWidget())
         return 0;
 
+    // FIXME: This explicit check is needed only until RemoteFrames have RemoteFrameViews.
+    if (isHTMLFrameElementBase(node) && toHTMLFrameElementBase(node)->contentFrame() && toHTMLFrameElementBase(node)->contentFrame()->isRemoteFrameTemporary())
+        return 0;
+
     Widget* widget = toRenderWidget(renderer)->widget();
     if (!widget || !widget->isFrameView())
         return 0;
@@ -1013,7 +966,7 @@ static Frame* subframeForTargetNode(Node* node)
     return &toFrameView(widget)->frame();
 }
 
-static Frame* subframeForHitTestResult(const MouseEventWithHitTestResults& hitTestResult)
+static LocalFrame* subframeForHitTestResult(const MouseEventWithHitTestResults& hitTestResult)
 {
     if (!hitTestResult.isOverWidget())
         return 0;
@@ -1022,48 +975,15 @@ static Frame* subframeForHitTestResult(const MouseEventWithHitTestResults& hitTe
 
 static bool isSubmitImage(Node* node)
 {
-    return node && node->hasTagName(inputTag) && toHTMLInputElement(node)->isImageButton();
-}
-
-// Returns true if the node's editable block is not current focused for editing
-static bool nodeIsNotBeingEdited(Node* node, Frame* frame)
-{
-    return frame->selection().rootEditableElement() != node->rootEditableElement();
+    return isHTMLInputElement(node) && toHTMLInputElement(node)->isImageButton();
 }
 
-bool EventHandler::useHandCursor(Node* node, bool isOverLink, bool shiftKey)
+bool EventHandler::useHandCursor(Node* node, bool isOverLink)
 {
     if (!node)
         return false;
 
-    bool editable = node->rendererIsEditable();
-    bool editableLinkEnabled = false;
-
-    // If the link is editable, then we need to check the settings to see whether or not the link should be followed
-    if (editable) {
-        ASSERT(m_frame->settings());
-        switch (m_frame->settings()->editableLinkBehavior()) {
-        default:
-        case EditableLinkDefaultBehavior:
-        case EditableLinkAlwaysLive:
-            editableLinkEnabled = true;
-            break;
-
-        case EditableLinkNeverLive:
-            editableLinkEnabled = false;
-            break;
-
-        case EditableLinkLiveWhenNotFocused:
-            editableLinkEnabled = nodeIsNotBeingEdited(node, m_frame) || shiftKey;
-            break;
-
-        case EditableLinkOnlyLiveWithShiftKey:
-            editableLinkEnabled = shiftKey;
-            break;
-        }
-    }
-
-    return ((isOverLink || isSubmitImage(node)) && (!editable || editableLinkEnabled));
+    return ((isOverLink || isSubmitImage(node)) && !node->hasEditableStyle());
 }
 
 void EventHandler::cursorUpdateTimerFired(Timer<EventHandler>*)
@@ -1087,26 +1007,20 @@ void EventHandler::updateCursor()
     if (!renderView)
         return;
 
-    bool shiftKey;
-    bool ctrlKey;
-    bool altKey;
-    bool metaKey;
-    PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
-
     m_frame->document()->updateLayout();
 
     HitTestRequest request(HitTestRequest::ReadOnly);
     HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
     renderView->hitTest(request, result);
 
-    OptionalCursor optionalCursor = selectCursor(result, shiftKey);
+    OptionalCursor optionalCursor = selectCursor(result);
     if (optionalCursor.isCursorChange()) {
         m_currentMouseCursor = optionalCursor.cursor();
         view->setCursor(m_currentMouseCursor);
     }
 }
 
-OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shiftKey)
+OptionalCursor EventHandler::selectCursor(const HitTestResult& result)
 {
     if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode())
         return NoCursorChange;
@@ -1119,9 +1033,9 @@ OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shif
         return NoCursorChange;
 #endif
 
-    Node* node = result.targetNode();
+    Node* node = result.innerPossiblyPseudoNode();
     if (!node)
-        return selectAutoCursor(result, node, iBeamCursor(), shiftKey);
+        return selectAutoCursor(result, node, iBeamCursor());
 
     RenderObject* renderer = node->renderer();
     RenderStyle* style = renderer ? renderer->style() : 0;
@@ -1172,7 +1086,7 @@ OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shif
     case CURSOR_AUTO: {
         bool horizontalText = !style || style->isHorizontalWritingMode();
         const Cursor& iBeam = horizontalText ? iBeamCursor() : verticalTextCursor();
-        return selectAutoCursor(result, node, iBeam, shiftKey);
+        return selectAutoCursor(result, node, iBeam);
     }
     case CURSOR_CROSS:
         return crossCursor();
@@ -1236,9 +1150,9 @@ OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shif
         return notAllowedCursor();
     case CURSOR_DEFAULT:
         return pointerCursor();
-    case CURSOR_WEBKIT_ZOOM_IN:
+    case CURSOR_ZOOM_IN:
         return zoomInCursor();
-    case CURSOR_WEBKIT_ZOOM_OUT:
+    case CURSOR_ZOOM_OUT:
         return zoomOutCursor();
     case CURSOR_WEBKIT_GRAB:
         return grabCursor();
@@ -1248,20 +1162,18 @@ OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shif
     return pointerCursor();
 }
 
-OptionalCursor EventHandler::selectAutoCursor(const HitTestResult& result, Node* node, const Cursor& iBeam, bool shiftKey)
+OptionalCursor EventHandler::selectAutoCursor(const HitTestResult& result, Node* node, const Cursor& iBeam)
 {
-    bool editable = (node && node->rendererIsEditable());
+    bool editable = (node && node->hasEditableStyle());
 
-    if (useHandCursor(node, result.isOverLink(), shiftKey))
+    if (useHandCursor(node, result.isOverLink()))
         return handCursor();
 
     bool inResizer = false;
     RenderObject* renderer = node ? node->renderer() : 0;
-    if (renderer) {
-        if (RenderLayer* layer = renderer->enclosingLayer()) {
-            if (m_frame->view())
-                inResizer = layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(result.roundedPointInMainFrame(), ResizerForPointer);
-        }
+    if (renderer && m_frame->view()) {
+        RenderLayer* layer = renderer->enclosingLayer();
+        inResizer = layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(result.roundedPointInMainFrame(), ResizerForPointer);
     }
 
     // During selection, use an I-beam no matter what we're over.
@@ -1278,7 +1190,7 @@ OptionalCursor EventHandler::selectAutoCursor(const HitTestResult& result, Node*
     return pointerCursor();
 }
 
-static LayoutPoint documentPointForWindowPoint(Frame* frame, const IntPoint& windowPoint)
+static LayoutPoint documentPointForWindowPoint(LocalFrame* frame, const IntPoint& windowPoint)
 {
     FrameView* view = frame->view();
     // FIXME: Is it really OK to use the wrong coordinates here when view is 0?
@@ -1288,18 +1200,16 @@ static LayoutPoint documentPointForWindowPoint(Frame* frame, const IntPoint& win
 
 bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 {
-    RefPtr<FrameView> protector(m_frame->view());
+    TRACE_EVENT0("blink", "EventHandler::handleMousePressEvent");
 
-    bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(mouseEvent);
-    if (defaultPrevented)
-        return true;
+    RefPtr<FrameView> protector(m_frame->view());
 
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
-    m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
+    m_frame->localFrameRoot()->eventHandler().m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
 
     cancelFakeMouseMoveEvent();
     if (m_eventHandlerWillResetCapturingMouseEventsNode)
-        m_capturingMouseEventsNode = 0;
+        m_capturingMouseEventsNode = nullptr;
     m_mousePressed = true;
     m_capturesDragging = true;
     setLastKnownMousePosition(mouseEvent);
@@ -1315,10 +1225,10 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
     }
     m_mouseDownWasInSubframe = false;
 
-    HitTestRequest::HitTestRequestType hitType = HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
-    if (mouseEvent.fromTouch())
-        hitType |= HitTestRequest::ReadOnly;
-    HitTestRequest request(hitType);
+    // Mouse events simulated from touch should not hit-test again.
+    ASSERT(!mouseEvent.fromTouch());
+
+    HitTestRequest request(HitTestRequest::Active);
     // Save the document point we generate in case the window coordinate is invalidated by what happens
     // when we dispatch the event.
     LayoutPoint documentPoint = documentPointForWindowPoint(m_frame, mouseEvent.position());
@@ -1331,7 +1241,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 
     m_mousePressNode = mev.targetNode();
 
-    RefPtr<Frame> subframe = subframeForHitTestResult(mev);
+    RefPtr<LocalFrame> subframe = subframeForHitTestResult(mev);
     if (subframe && passMousePressEventToSubframe(mev, subframe.get())) {
         // Start capturing future events for this frame.  We only do this if we didn't clear
         // the m_mousePressed flag, which may happen if an AppKit widget entered a modal event loop.
@@ -1358,7 +1268,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 #endif
 
     m_clickCount = mouseEvent.clickCount();
-    m_clickNode = mev.targetNode()->isTextNode() ?  mev.targetNode()->parentOrShadowHostNode() : mev.targetNode();
+    m_clickNode = mev.targetNode()->isTextNode() ?  NodeRenderingTraversal::parent(mev.targetNode()) : mev.targetNode();
 
     if (FrameView* view = m_frame->view()) {
         RenderLayer* layer = mev.targetNode()->renderer() ? mev.targetNode()->renderer()->enclosingLayer() : 0;
@@ -1374,41 +1284,30 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 
     m_frame->selection().setCaretBlinkingSuspended(true);
 
-    bool swallowEvent = !dispatchMouseEvent(EventTypeNames::mousedown, mev.targetNode(), true, m_clickCount, mouseEvent, true);
+    bool swallowEvent = !dispatchMouseEvent(EventTypeNames::mousedown, mev.targetNode(), m_clickCount, mouseEvent, true);
+    swallowEvent = swallowEvent || handleMouseFocus(mouseEvent);
     m_capturesDragging = !swallowEvent || mev.scrollbar();
 
     // If the hit testing originally determined the event was in a scrollbar, refetch the MouseEventWithHitTestResults
     // in case the scrollbar widget was destroyed when the mouse event was handled.
     if (mev.scrollbar()) {
         const bool wasLastScrollBar = mev.scrollbar() == m_lastScrollbarUnderMouse.get();
-        HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+        HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
         mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
         if (wasLastScrollBar && mev.scrollbar() != m_lastScrollbarUnderMouse.get())
-            m_lastScrollbarUnderMouse = 0;
+            m_lastScrollbarUnderMouse = nullptr;
     }
 
     if (swallowEvent) {
         // scrollbars should get events anyway, even disabled controls might be scrollable
-        Scrollbar* scrollbar = mev.scrollbar();
-
-        updateLastScrollbarUnderMouse(scrollbar, true);
-
-        if (scrollbar)
-            passMousePressEventToScrollbar(mev, scrollbar);
+        passMousePressEventToScrollbar(mev);
     } else {
         if (shouldRefetchEventTarget(mev)) {
-            HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+            HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
             mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
         }
 
-        FrameView* view = m_frame->view();
-        Scrollbar* scrollbar = view ? view->scrollbarAtPoint(mouseEvent.position()) : 0;
-        if (!scrollbar)
-            scrollbar = mev.scrollbar();
-
-        updateLastScrollbarUnderMouse(scrollbar, true);
-
-        if (scrollbar && passMousePressEventToScrollbar(mev, scrollbar))
+        if (passMousePressEventToScrollbar(mev))
             swallowEvent = true;
         else
             swallowEvent = handleMousePressEvent(mev);
@@ -1435,13 +1334,9 @@ static RenderLayer* layerForNode(Node* node)
 
 ScrollableArea* EventHandler::associatedScrollableArea(const RenderLayer* layer) const
 {
-    ScrollableArea* layerScrollableArea = layer->scrollableArea();
-    if (!layerScrollableArea)
-        return 0;
-
-    if (FrameView* frameView = m_frame->view()) {
-        if (frameView->containsScrollableArea(layerScrollableArea))
-            return layerScrollableArea;
+    if (RenderLayerScrollableArea* scrollableArea = layer->scrollableArea()) {
+        if (scrollableArea->scrollsOverflow())
+            return scrollableArea;
     }
 
     return 0;
@@ -1449,6 +1344,8 @@ ScrollableArea* EventHandler::associatedScrollableArea(const RenderLayer* layer)
 
 bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& event)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMouseMoveEvent");
+
     RefPtr<FrameView> protector(m_frame->view());
     MaximumDurationTracker maxDurationTracker(&m_maxMouseMovedDuration);
 
@@ -1476,27 +1373,17 @@ bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& event)
 
 void EventHandler::handleMouseLeaveEvent(const PlatformMouseEvent& event)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMouseLeaveEvent");
+
     RefPtr<FrameView> protector(m_frame->view());
     handleMouseMoveOrLeaveEvent(event);
 }
 
-static Cursor& syntheticTouchCursor()
-{
-    DEFINE_STATIC_LOCAL(Cursor, c, (Image::loadPlatformResource("syntheticTouchCursor").get(), IntPoint(10, 10)));
-    return c;
-}
-
 bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEvent, HitTestResult* hoveredNode, bool onlyUpdateScrollbars)
 {
     ASSERT(m_frame);
     ASSERT(m_frame->view());
 
-    bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(mouseEvent);
-    if (defaultPrevented) {
-        m_frame->view()->setCursor(syntheticTouchCursor());
-        return true;
-    }
-
     setLastKnownMousePosition(mouseEvent);
 
     if (m_hoverTimer.isActive())
@@ -1507,12 +1394,12 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
     cancelFakeMouseMoveEvent();
 
     if (m_svgPan) {
-        toSVGDocument(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_lastKnownMousePosition));
+        m_frame->document()->accessSVGExtensions().updatePan(m_frame->view()->windowToContents(m_lastKnownMousePosition));
         return true;
     }
 
     if (m_frameSetBeingResized)
-        return !dispatchMouseEvent(EventTypeNames::mousemove, m_frameSetBeingResized.get(), false, 0, mouseEvent, false);
+        return !dispatchMouseEvent(EventTypeNames::mousemove, m_frameSetBeingResized.get(), 0, mouseEvent, false);
 
     // Send events right to a scrollbar if the mouse is pressed.
     if (m_lastScrollbarUnderMouse && m_mousePressed) {
@@ -1520,10 +1407,10 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
         return true;
     }
 
-    HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
-    if (mouseEvent.fromTouch())
-        hitType |= HitTestRequest::ReadOnly;
+    // Mouse events simulated from touch should not hit-test again.
+    ASSERT(!mouseEvent.fromTouch());
 
+    HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move;
     if (m_mousePressed)
         hitType |= HitTestRequest::Active;
     else if (onlyUpdateScrollbars) {
@@ -1559,7 +1446,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
     }
 
     bool swallowEvent = false;
-    RefPtr<Frame> newSubframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
+    RefPtr<LocalFrame> newSubframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
 
     // We want mouseouts to happen first, from the inside out.  First send a move event to the last subframe so that it will fire mouseouts.
     if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree().isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
@@ -1577,7 +1464,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
         if (scrollbar && !m_mousePressed)
             scrollbar->mouseMoved(mouseEvent); // Handle hover effects on platforms that support visual feedback on scrollbar hovering.
         if (FrameView* view = m_frame->view()) {
-            OptionalCursor optionalCursor = selectCursor(mev.hitTestResult(), mouseEvent.shiftKey());
+            OptionalCursor optionalCursor = selectCursor(mev.hitTestResult());
             if (optionalCursor.isCursorChange()) {
                 m_currentMouseCursor = optionalCursor.cursor();
                 view->setCursor(m_currentMouseCursor);
@@ -1590,7 +1477,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
     if (swallowEvent)
         return true;
 
-    swallowEvent = !dispatchMouseEvent(EventTypeNames::mousemove, mev.targetNode(), false, 0, mouseEvent, true);
+    swallowEvent = !dispatchMouseEvent(EventTypeNames::mousemove, mev.targetNode(), 0, mouseEvent, true);
     if (!swallowEvent)
         swallowEvent = handleMouseDraggedEvent(mev);
 
@@ -1600,7 +1487,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
 void EventHandler::invalidateClick()
 {
     m_clickCount = 0;
-    m_clickNode = 0;
+    m_clickNode = nullptr;
 }
 
 static Node* parentForClickEvent(const Node& node)
@@ -1609,23 +1496,21 @@ static Node* parentForClickEvent(const Node& node)
     // controls.
     if (node.isHTMLElement() && toHTMLElement(node).isInteractiveContent())
         return 0;
-    return node.parentOrShadowHostNode();
+    return NodeRenderingTraversal::parent(&node);
 }
 
 bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
 {
+    TRACE_EVENT0("blink", "EventHandler::handleMouseReleaseEvent");
+
     RefPtr<FrameView> protector(m_frame->view());
 
     m_frame->selection().setCaretBlinkingSuspended(false);
 
-    bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(mouseEvent);
-    if (defaultPrevented)
-        return true;
-
     OwnPtr<UserGestureIndicator> gestureIndicator;
 
-    if (m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken)
-        gestureIndicator = adoptPtr(new UserGestureIndicator(m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken.release()));
+    if (m_frame->localFrameRoot()->eventHandler().m_lastMouseDownUserGestureToken)
+        gestureIndicator = adoptPtr(new UserGestureIndicator(m_frame->localFrameRoot()->eventHandler().m_lastMouseDownUserGestureToken.release()));
     else
         gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingUserGesture));
 
@@ -1639,33 +1524,33 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
 
     if (m_svgPan) {
         m_svgPan = false;
-        toSVGDocument(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_lastKnownMousePosition));
+        m_frame->document()->accessSVGExtensions().updatePan(m_frame->view()->windowToContents(m_lastKnownMousePosition));
         return true;
     }
 
     if (m_frameSetBeingResized)
-        return !dispatchMouseEvent(EventTypeNames::mouseup, m_frameSetBeingResized.get(), true, m_clickCount, mouseEvent, false);
+        return !dispatchMouseEvent(EventTypeNames::mouseup, m_frameSetBeingResized.get(), m_clickCount, mouseEvent, false);
 
     if (m_lastScrollbarUnderMouse) {
         invalidateClick();
         m_lastScrollbarUnderMouse->mouseUp(mouseEvent);
-        bool cancelable = true;
         bool setUnder = false;
-        return !dispatchMouseEvent(EventTypeNames::mouseup, m_lastNodeUnderMouse.get(), cancelable, m_clickCount, mouseEvent, setUnder);
+        return !dispatchMouseEvent(EventTypeNames::mouseup, m_lastNodeUnderMouse.get(), m_clickCount, mouseEvent, setUnder);
     }
 
-    HitTestRequest::HitTestRequestType hitType = HitTestRequest::Release | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
-    if (mouseEvent.fromTouch())
-        hitType |= HitTestRequest::ReadOnly;
+    // Mouse events simulated from touch should not hit-test again.
+    ASSERT(!mouseEvent.fromTouch());
+
+    HitTestRequest::HitTestRequestType hitType = HitTestRequest::Release;
     HitTestRequest request(hitType);
     MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
-    Frame* subframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
+    LocalFrame* subframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
     if (m_eventHandlerWillResetCapturingMouseEventsNode)
-        m_capturingMouseEventsNode = 0;
+        m_capturingMouseEventsNode = nullptr;
     if (subframe && passMouseReleaseEventToSubframe(mev, subframe))
         return true;
 
-    bool swallowMouseUpEvent = !dispatchMouseEvent(EventTypeNames::mouseup, mev.targetNode(), true, m_clickCount, mouseEvent, false);
+    bool swallowMouseUpEvent = !dispatchMouseEvent(EventTypeNames::mouseup, mev.targetNode(), m_clickCount, mouseEvent, false);
 
     bool contextMenuEvent = mouseEvent.button() == RightButton;
 #if OS(MACOSX)
@@ -1677,7 +1562,7 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
     bool swallowClickEvent = false;
     if (m_clickCount > 0 && !contextMenuEvent && mev.targetNode() && m_clickNode) {
         if (Node* clickTargetNode = mev.targetNode()->commonAncestor(*m_clickNode, parentForClickEvent))
-            swallowClickEvent = !dispatchMouseEvent(EventTypeNames::click, clickTargetNode, true, m_clickCount, mouseEvent, true);
+            swallowClickEvent = !dispatchMouseEvent(EventTypeNames::click, clickTargetNode, m_clickCount, mouseEvent, true);
     }
 
     if (m_resizeScrollableArea) {
@@ -1726,7 +1611,7 @@ bool EventHandler::handlePasteGlobalSelection(const PlatformMouseEvent& mouseEve
 }
 
 
-bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Node* dragTarget, const PlatformMouseEvent& event, Clipboard* clipboard)
+bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Node* dragTarget, const PlatformMouseEvent& event, DataTransfer* dataTransfer)
 {
     FrameView* view = m_frame->view();
 
@@ -1734,30 +1619,31 @@ bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Node* dragTa
     if (!view)
         return false;
 
-    RefPtr<MouseEvent> me = MouseEvent::create(eventType,
+    RefPtrWillBeRawPtr<MouseEvent> me = MouseEvent::create(eventType,
         true, true, m_frame->document()->domWindow(),
         0, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
         event.movementDelta().x(), event.movementDelta().y(),
         event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(),
-        0, 0, clipboard);
+        0, nullptr, dataTransfer);
 
     dragTarget->dispatchEvent(me.get(), IGNORE_EXCEPTION);
     return me->defaultPrevented();
 }
 
-static bool targetIsFrame(Node* target, Frame*& frame)
+static bool targetIsFrame(Node* target, LocalFrame*& frame)
 {
-    if (!target)
+    if (!isHTMLFrameElementBase(target))
         return false;
 
-    if (!target->hasTagName(frameTag) && !target->hasTagName(iframeTag))
+    // Cross-process drag and drop is not yet supported.
+    if (toHTMLFrameElementBase(target)->contentFrame() && !toHTMLFrameElementBase(target)->contentFrame()->isLocalFrame())
         return false;
 
-    frame = toHTMLFrameElementBase(target)->contentFrame();
+    frame = toLocalFrame(toHTMLFrameElementBase(target)->contentFrame());
     return true;
 }
 
-static bool findDropZone(Node* target, Clipboard* clipboard)
+static bool findDropZone(Node* target, DataTransfer* dataTransfer)
 {
     Element* element = target->isElementNode() ? toElement(target) : target->parentElement();
     for (; element; element = element->parentElement()) {
@@ -1767,6 +1653,8 @@ static bool findDropZone(Node* target, Clipboard* clipboard)
         if (dropZoneStr.isEmpty())
             continue;
 
+        UseCounter::count(element->document(), UseCounter::PrefixedHTMLElementDropzone);
+
         dropZoneStr = dropZoneStr.lower();
 
         SpaceSplitString keywords(dropZoneStr, false);
@@ -1774,39 +1662,40 @@ static bool findDropZone(Node* target, Clipboard* clipboard)
             continue;
 
         DragOperation dragOperation = DragOperationNone;
-        for (unsigned int i = 0; i < keywords.size(); i++) {
+        for (unsigned i = 0; i < keywords.size(); i++) {
             DragOperation op = convertDropZoneOperationToDragOperation(keywords[i]);
             if (op != DragOperationNone) {
                 if (dragOperation == DragOperationNone)
                     dragOperation = op;
-            } else
-                matched = matched || clipboard->hasDropZoneType(keywords[i].string());
+            } else {
+                matched = matched || dataTransfer->hasDropZoneType(keywords[i].string());
+            }
 
             if (matched && dragOperation != DragOperationNone)
                 break;
         }
         if (matched) {
-            clipboard->setDropEffect(convertDragOperationToDropZoneOperation(dragOperation));
+            dataTransfer->setDropEffect(convertDragOperationToDropZoneOperation(dragOperation));
             return true;
         }
     }
     return false;
 }
 
-bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
+bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, DataTransfer* dataTransfer)
 {
     bool accept = false;
 
     if (!m_frame->view())
         return false;
 
-    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+    HitTestRequest request(HitTestRequest::ReadOnly);
     MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
 
     // Drag events should never go to text nodes (following IE, and proper mouseover/out dispatch)
-    RefPtr<Node> newTarget = mev.targetNode();
+    RefPtrWillBeRawPtr<Node> newTarget = mev.targetNode();
     if (newTarget && newTarget->isTextNode())
-        newTarget = EventPath::parent(newTarget.get());
+        newTarget = NodeRenderingTraversal::parent(newTarget.get());
 
     if (AutoscrollController* controller = autoscrollController())
         controller->updateDragAndDrop(newTarget.get(), event.position(), event.timestamp());
@@ -1817,26 +1706,27 @@ bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard*
         // LayoutTests/fast/events/drag-in-frames.html.
         //
         // Moreover, this ordering conforms to section 7.9.4 of the HTML 5 spec. <http://dev.w3.org/html5/spec/Overview.html#drag-and-drop-processing-model>.
-        Frame* targetFrame;
+        LocalFrame* targetFrame;
         if (targetIsFrame(newTarget.get(), targetFrame)) {
             if (targetFrame)
-                accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
+                accept = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
         } else if (newTarget) {
             // As per section 7.9.4 of the HTML 5 spec., we must always fire a drag event before firing a dragenter, dragleave, or dragover event.
             if (dragState().m_dragSrc) {
                 // for now we don't care if event handler cancels default behavior, since there is none
                 dispatchDragSrcEvent(EventTypeNames::drag, event);
             }
-            accept = dispatchDragEvent(EventTypeNames::dragenter, newTarget.get(), event, clipboard);
+            accept = dispatchDragEvent(EventTypeNames::dragenter, newTarget.get(), event, dataTransfer);
             if (!accept)
-                accept = findDropZone(newTarget.get(), clipboard);
+                accept = findDropZone(newTarget.get(), dataTransfer);
         }
 
         if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
             if (targetFrame)
-                accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
-        } else if (m_dragTarget)
-            dispatchDragEvent(EventTypeNames::dragleave, m_dragTarget.get(), event, clipboard);
+                accept = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
+        } else if (m_dragTarget) {
+            dispatchDragEvent(EventTypeNames::dragleave, m_dragTarget.get(), event, dataTransfer);
+        }
 
         if (newTarget) {
             // We do not explicitly call dispatchDragEvent here because it could ultimately result in the appearance that
@@ -1844,19 +1734,19 @@ bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard*
             m_shouldOnlyFireDragOverEvent = true;
         }
     } else {
-        Frame* targetFrame;
+        LocalFrame* targetFrame;
         if (targetIsFrame(newTarget.get(), targetFrame)) {
             if (targetFrame)
-                accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
+                accept = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
         } else if (newTarget) {
             // Note, when dealing with sub-frames, we may need to fire only a dragover event as a drag event may have been fired earlier.
             if (!m_shouldOnlyFireDragOverEvent && dragState().m_dragSrc) {
                 // for now we don't care if event handler cancels default behavior, since there is none
                 dispatchDragSrcEvent(EventTypeNames::drag, event);
             }
-            accept = dispatchDragEvent(EventTypeNames::dragover, newTarget.get(), event, clipboard);
+            accept = dispatchDragEvent(EventTypeNames::dragover, newTarget.get(), event, dataTransfer);
             if (!accept)
-                accept = findDropZone(newTarget.get(), clipboard);
+                accept = findDropZone(newTarget.get(), dataTransfer);
             m_shouldOnlyFireDragOverEvent = false;
         }
     }
@@ -1865,29 +1755,30 @@ bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard*
     return accept;
 }
 
-void EventHandler::cancelDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
+void EventHandler::cancelDragAndDrop(const PlatformMouseEvent& event, DataTransfer* dataTransfer)
 {
-    Frame* targetFrame;
+    LocalFrame* targetFrame;
     if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
         if (targetFrame)
-            targetFrame->eventHandler().cancelDragAndDrop(event, clipboard);
+            targetFrame->eventHandler().cancelDragAndDrop(event, dataTransfer);
     } else if (m_dragTarget.get()) {
         if (dragState().m_dragSrc)
             dispatchDragSrcEvent(EventTypeNames::drag, event);
-        dispatchDragEvent(EventTypeNames::dragleave, m_dragTarget.get(), event, clipboard);
+        dispatchDragEvent(EventTypeNames::dragleave, m_dragTarget.get(), event, dataTransfer);
     }
     clearDragState();
 }
 
-bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
+bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, DataTransfer* dataTransfer)
 {
-    Frame* targetFrame;
+    LocalFrame* targetFrame;
     bool preventedDefault = false;
     if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
         if (targetFrame)
-            preventedDefault = targetFrame->eventHandler().performDragAndDrop(event, clipboard);
-    } else if (m_dragTarget.get())
-        preventedDefault = dispatchDragEvent(EventTypeNames::drop, m_dragTarget.get(), event, clipboard);
+            preventedDefault = targetFrame->eventHandler().performDragAndDrop(event, dataTransfer);
+    } else if (m_dragTarget.get()) {
+        preventedDefault = dispatchDragEvent(EventTypeNames::drop, m_dragTarget.get(), event, dataTransfer);
+    }
     clearDragState();
     return preventedDefault;
 }
@@ -1895,12 +1786,12 @@ bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, Clipboard
 void EventHandler::clearDragState()
 {
     stopAutoscroll();
-    m_dragTarget = 0;
-    m_capturingMouseEventsNode = 0;
+    m_dragTarget = nullptr;
+    m_capturingMouseEventsNode = nullptr;
     m_shouldOnlyFireDragOverEvent = false;
 }
 
-void EventHandler::setCapturingMouseEventsNode(PassRefPtr<Node> n)
+void EventHandler::setCapturingMouseEventsNode(PassRefPtrWillBeRawPtr<Node> n)
 {
     m_capturingMouseEventsNode = n;
     m_eventHandlerWillResetCapturingMouseEventsNode = false;
@@ -1914,22 +1805,6 @@ MouseEventWithHitTestResults EventHandler::prepareMouseEvent(const HitTestReques
     return m_frame->document()->prepareMouseEvent(request, documentPointForWindowPoint(m_frame, mev.position()), mev);
 }
 
-static inline SVGElementInstance* instanceAssociatedWithShadowTreeElement(Node* referenceNode)
-{
-    if (!referenceNode || !referenceNode->isSVGElement())
-        return 0;
-
-    ShadowRoot* shadowRoot = referenceNode->containingShadowRoot();
-    if (!shadowRoot)
-        return 0;
-
-    Element* shadowTreeParentElement = shadowRoot->host();
-    if (!shadowTreeParentElement || !shadowTreeParentElement->hasTagName(useTag))
-        return 0;
-
-    return toSVGUseElement(shadowTreeParentElement)->instanceForShadowTreeElement(referenceNode);
-}
-
 void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMouseEvent& mouseEvent, bool fireMouseOverOut)
 {
     Node* result = targetNode;
@@ -1940,41 +1815,9 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
     else {
         // If the target node is a text node, dispatch on the parent node - rdar://4196646
         if (result && result->isTextNode())
-            result = EventPath::parent(result);
+            result = NodeRenderingTraversal::parent(result);
     }
     m_nodeUnderMouse = result;
-    m_instanceUnderMouse = instanceAssociatedWithShadowTreeElement(result);
-
-    // <use> shadow tree elements may have been recloned, update node under mouse in any case
-    if (m_lastInstanceUnderMouse) {
-        SVGElement* lastCorrespondingElement = m_lastInstanceUnderMouse->correspondingElement();
-        SVGElement* lastCorrespondingUseElement = m_lastInstanceUnderMouse->correspondingUseElement();
-
-        if (lastCorrespondingElement && lastCorrespondingUseElement) {
-            HashSet<SVGElementInstance*> instances = lastCorrespondingElement->instancesForElement();
-
-            // Locate the recloned shadow tree element for our corresponding instance
-            HashSet<SVGElementInstance*>::iterator end = instances.end();
-            for (HashSet<SVGElementInstance*>::iterator it = instances.begin(); it != end; ++it) {
-                SVGElementInstance* instance = (*it);
-                ASSERT(instance->correspondingElement() == lastCorrespondingElement);
-
-                if (instance == m_lastInstanceUnderMouse)
-                    continue;
-
-                if (instance->correspondingUseElement() != lastCorrespondingUseElement)
-                    continue;
-
-                SVGElement* shadowTreeElement = instance->shadowTreeElement();
-                if (!shadowTreeElement->inDocument() || m_lastNodeUnderMouse == shadowTreeElement)
-                    continue;
-
-                m_lastNodeUnderMouse = shadowTreeElement;
-                m_lastInstanceUnderMouse = instance;
-                break;
-            }
-        }
-    }
 
     // Fire mouseout/mouseover if the mouse has shifted to a different node.
     if (fireMouseOverOut) {
@@ -1984,7 +1827,7 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
 
         if (m_lastNodeUnderMouse && (!m_nodeUnderMouse || m_nodeUnderMouse->document() != m_frame->document())) {
             // The mouse has moved between frames.
-            if (Frame* frame = m_lastNodeUnderMouse->document().frame()) {
+            if (LocalFrame* frame = m_lastNodeUnderMouse->document().frame()) {
                 if (FrameView* frameView = frame->view())
                     frameView->mouseExitedContentArea();
             }
@@ -1996,7 +1839,7 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
 
         if (m_nodeUnderMouse && (!m_lastNodeUnderMouse || m_lastNodeUnderMouse->document() != m_frame->document())) {
             // The mouse has moved between frames.
-            if (Frame* frame = m_nodeUnderMouse->document().frame()) {
+            if (LocalFrame* frame = m_nodeUnderMouse->document().frame()) {
                 if (FrameView* frameView = frame->view())
                     frameView->mouseEnteredContentArea();
             }
@@ -2007,9 +1850,8 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
         }
 
         if (m_lastNodeUnderMouse && m_lastNodeUnderMouse->document() != m_frame->document()) {
-            m_lastNodeUnderMouse = 0;
-            m_lastScrollbarUnderMouse = 0;
-            m_lastInstanceUnderMouse = 0;
+            m_lastNodeUnderMouse = nullptr;
+            m_lastScrollbarUnderMouse = nullptr;
         }
 
         if (m_lastNodeUnderMouse != m_nodeUnderMouse) {
@@ -2021,26 +1863,23 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
                 m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, EventTypeNames::mouseover, 0, m_lastNodeUnderMouse.get());
         }
         m_lastNodeUnderMouse = m_nodeUnderMouse;
-        m_lastInstanceUnderMouse = instanceAssociatedWithShadowTreeElement(m_nodeUnderMouse.get());
     }
 }
 
-bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targetNode, bool /*cancelable*/, int clickCount, const PlatformMouseEvent& mouseEvent, bool setUnder)
+// The return value means 'continue default handling.'
+bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targetNode, int clickCount, const PlatformMouseEvent& mouseEvent, bool setUnder)
 {
     updateMouseEventTargetNode(targetNode, mouseEvent, setUnder);
+    return !m_nodeUnderMouse || m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventType, clickCount);
+}
 
-    bool swallowEvent = false;
-
-    if (m_nodeUnderMouse)
-        swallowEvent = !(m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventType, clickCount));
-
-    if (swallowEvent || eventType != EventTypeNames::mousedown)
-        return !swallowEvent;
-
+// The return value means 'swallow event' (was handled), as for other handle* functions.
+bool EventHandler::handleMouseFocus(const PlatformMouseEvent& mouseEvent)
+{
     // If clicking on a frame scrollbar, do not mess up with content focus.
     if (FrameView* view = m_frame->view()) {
         if (view->scrollbarAtPoint(mouseEvent.position()))
-            return true;
+            return false;
     }
 
     // The layout needs to be up to date to determine if an element is focusable.
@@ -2051,7 +1890,7 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
         element = m_nodeUnderMouse->isElementNode() ? toElement(m_nodeUnderMouse) : m_nodeUnderMouse->parentOrShadowHostElement();
     for (; element; element = element->parentOrShadowHostElement()) {
         if (element->isFocusable() && element->focused())
-            return !swallowEvent;
+            return false;
         if (element->isMouseFocusable())
             break;
     }
@@ -2066,37 +1905,37 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
         && m_frame->selection().isRange()
         && m_frame->selection().toNormalizedRange()->compareNode(element, IGNORE_EXCEPTION) == Range::NODE_INSIDE
         && element->isDescendantOf(m_frame->document()->focusedElement()))
-        return true;
+        return false;
 
     // Only change the focus when clicking scrollbars if it can transfered to a
     // mouse focusable node.
     if (!element && isInsideScrollbar(mouseEvent.position()))
-        return false;
+        return true;
 
     if (Page* page = m_frame->page()) {
         // If focus shift is blocked, we eat the event. Note we should never
         // clear swallowEvent if the page already set it (e.g., by canceling
         // default behavior).
         if (element) {
-            if (!page->focusController().setFocusedElement(element, m_frame, FocusDirectionMouse))
-                swallowEvent = true;
+            if (!page->focusController().setFocusedElement(element, m_frame, FocusTypeMouse))
+                return true;
         } else {
             // We call setFocusedElement even with !element in order to blur
             // current focus element when a link is clicked; this is expected by
             // some sites that rely on onChange handlers running from form
             // fields before the button click is processed.
             if (!page->focusController().setFocusedElement(0, m_frame))
-                swallowEvent = true;
+                return true;
         }
     }
 
-    return !swallowEvent;
+    return false;
 }
 
 bool EventHandler::isInsideScrollbar(const IntPoint& windowPoint) const
 {
     if (RenderView* renderView = m_frame->contentRenderer()) {
-        HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+        HitTestRequest request(HitTestRequest::ReadOnly);
         HitTestResult result(windowPoint);
         renderView->hitTest(request, result);
         return result.scrollbar();
@@ -2105,19 +1944,7 @@ bool EventHandler::isInsideScrollbar(const IntPoint& windowPoint) const
     return false;
 }
 
-bool EventHandler::shouldTurnVerticalTicksIntoHorizontal(const HitTestResult& result, const PlatformWheelEvent& event) const
-{
-#if OS(ANDROID) || OS(MACOSX) || OS(WIN)
-    return false;
-#else
-    // GTK+ must scroll horizontally if the mouse pointer is on top of the
-    // horizontal scrollbar while scrolling with the wheel.
-    // This code comes from gtk/EventHandlerGtk.cpp.
-    return !event.hasPreciseScrollingDeltas() && result.scrollbar() && result.scrollbar()->orientation() == HorizontalScrollbar;
-#endif
-}
-
-bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
+bool EventHandler::handleWheelEvent(const PlatformWheelEvent& event)
 {
 #define RETURN_WHEEL_EVENT_HANDLED() \
     { \
@@ -2127,7 +1954,7 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
 
     Document* doc = m_frame->document();
 
-    if (!doc->renderer())
+    if (!doc->renderView())
         return false;
 
     RefPtr<FrameView> protector(m_frame->view());
@@ -2136,22 +1963,19 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
     if (!view)
         return false;
 
-    if (handleWheelEventAsEmulatedGesture(e))
-        return true;
-
-    LayoutPoint vPoint = view->windowToContents(e.position());
+    LayoutPoint vPoint = view->windowToContents(event.position());
 
-    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+    HitTestRequest request(HitTestRequest::ReadOnly);
     HitTestResult result(vPoint);
     doc->renderView()->hitTest(request, result);
 
     Node* node = result.innerNode();
     // Wheel events should not dispatch to text nodes.
     if (node && node->isTextNode())
-        node = EventPath::parent(node);
+        node = NodeRenderingTraversal::parent(node);
 
     bool isOverWidget;
-    if (e.useLatchedEventNode()) {
+    if (event.useLatchedEventNode()) {
         if (!m_latchedWheelEventNode) {
             m_latchedWheelEventNode = node;
             m_widgetIsLatched = result.isOverWidget();
@@ -2161,27 +1985,20 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
         isOverWidget = m_widgetIsLatched;
     } else {
         if (m_latchedWheelEventNode)
-            m_latchedWheelEventNode = 0;
+            m_latchedWheelEventNode = nullptr;
         if (m_previousWheelScrolledNode)
-            m_previousWheelScrolledNode = 0;
+            m_previousWheelScrolledNode = nullptr;
 
         isOverWidget = result.isOverWidget();
     }
 
-    // FIXME: It should not be necessary to do this mutation here.
-    // Instead, the handlers should know convert vertical scrolls
-    // appropriately.
-    PlatformWheelEvent event = e;
-    if (m_baseEventType == PlatformEvent::NoType && shouldTurnVerticalTicksIntoHorizontal(result, e))
-        event = event.copyTurningVerticalTicksIntoHorizontalTicks();
-
     if (node) {
         // Figure out which view to send the event to.
         RenderObject* target = node->renderer();
 
         if (isOverWidget && target && target->isWidget()) {
             Widget* widget = toRenderWidget(target)->widget();
-            if (widget && passWheelEventToWidget(e, widget))
+            if (widget && passWheelEventToWidget(event, widget))
                 RETURN_WHEEL_EVENT_HANDLED();
         }
 
@@ -2189,7 +2006,6 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
             RETURN_WHEEL_EVENT_HANDLED();
     }
 
-
     // We do another check on the frame view because the event handler can run JS which results in the frame getting destroyed.
     view = m_frame->view();
     if (!view || !view->wheelEvent(event))
@@ -2205,6 +2021,10 @@ void EventHandler::defaultWheelEventHandler(Node* startNode, WheelEvent* wheelEv
     if (!startNode || !wheelEvent)
         return;
 
+    // Ctrl + scrollwheel is reserved for triggering zoom in/out actions in Chromium.
+    if (wheelEvent->ctrlKey())
+        return;
+
     Node* stopNode = m_previousWheelScrolledNode.get();
     ScrollGranularity granularity = wheelGranularityToScrollGranularity(wheelEvent->deltaMode());
 
@@ -2234,7 +2054,7 @@ bool EventHandler::handleGestureShowPress()
         return false;
     for (FrameView::ScrollableAreaSet::const_iterator it = areas->begin(); it != areas->end(); ++it) {
         ScrollableArea* sa = *it;
-        ScrollAnimator* animator = sa->scrollAnimator();
+        ScrollAnimator* animator = sa->existingScrollAnimator();
         if (animator)
             animator->cancelAnimations();
     }
@@ -2243,122 +2063,127 @@ bool EventHandler::handleGestureShowPress()
 
 bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
 {
-    IntPoint adjustedPoint = gestureEvent.position();
-    RefPtr<Frame> subframe = 0;
-    switch (gestureEvent.type()) {
-    case PlatformEvent::GestureScrollBegin:
-    case PlatformEvent::GestureScrollUpdate:
-    case PlatformEvent::GestureScrollUpdateWithoutPropagation:
-    case PlatformEvent::GestureScrollEnd:
-    case PlatformEvent::GestureFlingStart:
-        // Handle directly in main frame
-        break;
+    TRACE_EVENT0("input", "EventHandler::handleGestureEvent");
+
+    // Propagation to inner frames is handled below this function.
+    ASSERT(m_frame == m_frame->localFrameRoot());
+
+    // Scrolling-related gesture events invoke EventHandler recursively for each frame down
+    // the chain, doing a single-frame hit-test per frame. This matches handleWheelEvent.
+    // Perhaps we could simplify things by rewriting scroll handling to work inner frame
+    // out, and then unify with other gesture events.
+    if (gestureEvent.isScrollEvent())
+        return handleGestureScrollEvent(gestureEvent);
+
+    // Non-scrolling related gesture events instead do a single cross-frame hit-test and
+    // jump directly to the inner most frame. This matches handleMousePressEvent etc.
+
+    // Hit test across all frames and do touch adjustment as necessary for the event type.
+    GestureEventWithHitTestResults targetedEvent = targetGestureEvent(gestureEvent);
 
+    // Route to the correct frame.
+    if (LocalFrame* innerFrame = targetedEvent.hitTestResult().innerNodeFrame())
+        return innerFrame->eventHandler().handleGestureEventInFrame(targetedEvent);
+
+    // No hit test result, handle in root instance. Perhaps we should just return false instead?
+    return handleGestureEventInFrame(targetedEvent);
+}
+
+bool EventHandler::handleGestureEventInFrame(const GestureEventWithHitTestResults& targetedEvent)
+{
+    ASSERT(!targetedEvent.event().isScrollEvent());
+
+    RefPtrWillBeRawPtr<Node> eventTarget = targetedEvent.hitTestResult().targetNode();
+    RefPtr<Scrollbar> scrollbar = targetedEvent.hitTestResult().scrollbar();
+    const PlatformGestureEvent& gestureEvent = targetedEvent.event();
+
+    if (scrollbar) {
+        bool eventSwallowed = scrollbar->gestureEvent(gestureEvent);
+        if (gestureEvent.type() == PlatformEvent::GestureTapDown && eventSwallowed)
+            m_scrollbarHandlingScrollGesture = scrollbar;
+        if (eventSwallowed)
+            return true;
+    }
+
+    if (eventTarget && eventTarget->dispatchGestureEvent(gestureEvent))
+        return true;
+
+    switch (gestureEvent.type()) {
     case PlatformEvent::GestureTap:
-    case PlatformEvent::GestureTapUnconfirmed:
-    case PlatformEvent::GestureTapDown:
+        return handleGestureTap(targetedEvent);
     case PlatformEvent::GestureShowPress:
-    case PlatformEvent::GestureTapDownCancel:
-    case PlatformEvent::GestureTwoFingerTap:
+        return handleGestureShowPress();
     case PlatformEvent::GestureLongPress:
+        return handleGestureLongPress(targetedEvent);
     case PlatformEvent::GestureLongTap:
+        return handleGestureLongTap(targetedEvent);
+    case PlatformEvent::GestureTwoFingerTap:
+        return sendContextMenuEventForGesture(targetedEvent);
+    case PlatformEvent::GestureTapDown:
     case PlatformEvent::GesturePinchBegin:
     case PlatformEvent::GesturePinchEnd:
     case PlatformEvent::GesturePinchUpdate:
-        adjustGesturePosition(gestureEvent, adjustedPoint);
-        subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
-        if (subframe)
-            return subframe->eventHandler().handleGestureEvent(gestureEvent);
+    case PlatformEvent::GestureTapDownCancel:
+    case PlatformEvent::GestureTapUnconfirmed:
         break;
-
     default:
         ASSERT_NOT_REACHED();
     }
 
-    Node* eventTarget = 0;
-    Scrollbar* scrollbar = 0;
-    if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
-        || gestureEvent.type() == PlatformEvent::GestureScrollUpdate
-        || gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation
-        || gestureEvent.type() == PlatformEvent::GestureFlingStart) {
+    return false;
+}
+
+bool EventHandler::handleGestureScrollEvent(const PlatformGestureEvent& gestureEvent)
+{
+    RefPtrWillBeRawPtr<Node> eventTarget = nullptr;
+    RefPtr<Scrollbar> scrollbar;
+    if (gestureEvent.type() != PlatformEvent::GestureScrollBegin) {
         scrollbar = m_scrollbarHandlingScrollGesture.get();
         eventTarget = m_scrollGestureHandlingNode.get();
     }
 
-    HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
-    double activeInterval = 0;
-    bool shouldKeepActiveForMinInterval = false;
-    if (gestureEvent.type() == PlatformEvent::GestureShowPress
-        || gestureEvent.type() == PlatformEvent::GestureTapUnconfirmed) {
-        hitType |= HitTestRequest::Active;
-    } else if (gestureEvent.type() == PlatformEvent::GestureTapDownCancel) {
-        hitType |= HitTestRequest::Release;
-        // A TapDownCancel received when no element is active shouldn't really be changing hover state.
-        if (!m_frame->document()->activeHoverElement())
-            hitType |= HitTestRequest::ReadOnly;
-    } else if (gestureEvent.type() == PlatformEvent::GestureTap) {
-        hitType |= HitTestRequest::Release;
-        // If the Tap is received very shortly after ShowPress, we want to delay clearing
-        // of the active state so that it's visible to the user for at least one frame.
-        activeInterval = WTF::currentTime() - m_lastShowPressTimestamp;
-        shouldKeepActiveForMinInterval = m_lastShowPressTimestamp && activeInterval < minimumActiveInterval;
-        if (shouldKeepActiveForMinInterval)
-            hitType |= HitTestRequest::ReadOnly;
-    }
-    else
-        hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
+    if (!eventTarget) {
+        Document* document = m_frame->document();
+        if (!document->renderView())
+            return false;
 
-    if ((!scrollbar && !eventTarget) || !(hitType & HitTestRequest::ReadOnly)) {
-        IntPoint hitTestPoint = m_frame->view()->windowToContents(adjustedPoint);
-        HitTestResult result = hitTestResultAtPoint(hitTestPoint, hitType | HitTestRequest::AllowFrameScrollbars);
+        FrameView* view = m_frame->view();
+        LayoutPoint viewPoint = view->windowToContents(gestureEvent.position());
+        HitTestRequest request(HitTestRequest::ReadOnly);
+        HitTestResult result(viewPoint);
+        document->renderView()->hitTest(request, result);
 
-        if (shouldKeepActiveForMinInterval) {
-            m_lastDeferredTapElement = result.innerElement();
-            m_activeIntervalTimer.startOneShot(minimumActiveInterval - activeInterval);
-        }
+        eventTarget = result.innerNode();
+
+        m_lastGestureScrollOverWidget = result.isOverWidget();
+        m_scrollGestureHandlingNode = eventTarget;
+        m_previousGestureScrolledNode = nullptr;
 
-        eventTarget = result.targetNode();
-        if (!scrollbar) {
-            FrameView* view = m_frame->view();
-            scrollbar = view ? view->scrollbarAtPoint(gestureEvent.position()) : 0;
-        }
+        if (!scrollbar)
+            scrollbar = view->scrollbarAtPoint(gestureEvent.position());
         if (!scrollbar)
             scrollbar = result.scrollbar();
     }
 
     if (scrollbar) {
         bool eventSwallowed = scrollbar->gestureEvent(gestureEvent);
-        if (gestureEvent.type() == PlatformEvent::GestureTapDown && eventSwallowed) {
-            m_scrollbarHandlingScrollGesture = scrollbar;
-        } else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
+        if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
             || gestureEvent.type() == PlatformEvent::GestureFlingStart
             || !eventSwallowed) {
-            m_scrollbarHandlingScrollGesture = 0;
+            m_scrollbarHandlingScrollGesture = nullptr;
         }
-
         if (eventSwallowed)
             return true;
     }
 
     if (eventTarget) {
-        bool eventSwallowed = false;
-        if (handleScrollGestureOnResizer(eventTarget, gestureEvent))
-            eventSwallowed = true;
-        else
+        bool eventSwallowed = handleScrollGestureOnResizer(eventTarget.get(), gestureEvent);
+        if (!eventSwallowed)
             eventSwallowed = eventTarget->dispatchGestureEvent(gestureEvent);
-        if (gestureEvent.type() == PlatformEvent::GestureScrollBegin || gestureEvent.type() == PlatformEvent::GestureScrollEnd) {
-            if (eventSwallowed)
-                m_scrollGestureHandlingNode = eventTarget;
-        }
-
         if (eventSwallowed)
             return true;
     }
 
-    // FIXME: A more general scroll system (https://bugs.webkit.org/show_bug.cgi?id=80596) will
-    // eliminate the need for this.
-    TemporaryChange<PlatformEvent::Type> baseEventType(m_baseEventType, gestureEvent.type());
-
     switch (gestureEvent.type()) {
     case PlatformEvent::GestureScrollBegin:
         return handleGestureScrollBegin(gestureEvent);
@@ -2367,34 +2192,23 @@ bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
         return handleGestureScrollUpdate(gestureEvent);
     case PlatformEvent::GestureScrollEnd:
         return handleGestureScrollEnd(gestureEvent);
-    case PlatformEvent::GestureTap:
-        return handleGestureTap(gestureEvent, adjustedPoint);
-    case PlatformEvent::GestureShowPress:
-        return handleGestureShowPress();
-    case PlatformEvent::GestureLongPress:
-        return handleGestureLongPress(gestureEvent, adjustedPoint);
-    case PlatformEvent::GestureLongTap:
-        return handleGestureLongTap(gestureEvent, adjustedPoint);
-    case PlatformEvent::GestureTwoFingerTap:
-        return handleGestureTwoFingerTap(gestureEvent, adjustedPoint);
-    case PlatformEvent::GestureTapDown:
+    case PlatformEvent::GestureFlingStart:
     case PlatformEvent::GesturePinchBegin:
     case PlatformEvent::GesturePinchEnd:
     case PlatformEvent::GesturePinchUpdate:
-    case PlatformEvent::GestureTapDownCancel:
-    case PlatformEvent::GestureTapUnconfirmed:
-    case PlatformEvent::GestureFlingStart:
-        break;
+        return false;
     default:
         ASSERT_NOT_REACHED();
+        return false;
     }
-
-    return false;
 }
 
-bool EventHandler::handleGestureTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
+bool EventHandler::handleGestureTap(const GestureEventWithHitTestResults& targetedEvent)
 {
-    // FIXME: Refactor this code to not hit test multiple times. We use the adjusted position to ensure that the correct node is targeted by the later redundant hit tests.
+    RefPtr<FrameView> protector(m_frame->view());
+    const PlatformGestureEvent& gestureEvent = targetedEvent.event();
+
+    UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
 
     unsigned modifierFlags = 0;
     if (gestureEvent.altKey())
@@ -2407,27 +2221,69 @@ bool EventHandler::handleGestureTap(const PlatformGestureEvent& gestureEvent, co
         modifierFlags |= PlatformEvent::ShiftKey;
     PlatformEvent::Modifiers modifiers = static_cast<PlatformEvent::Modifiers>(modifierFlags);
 
+    HitTestResult currentHitTest = targetedEvent.hitTestResult();
+
+    // We use the adjusted position so the application isn't surprised to see a event with
+    // co-ordinates outside the target's bounds.
+    IntPoint adjustedPoint = m_frame->view()->windowToContents(gestureEvent.position());
+
     PlatformMouseEvent fakeMouseMove(adjustedPoint, gestureEvent.globalPosition(),
         NoButton, PlatformEvent::MouseMoved, /* clickCount */ 0,
         modifiers, PlatformMouseEvent::FromTouch, gestureEvent.timestamp());
-    handleMouseMoveEvent(fakeMouseMove);
+    dispatchMouseEvent(EventTypeNames::mousemove, currentHitTest.innerNode(), 0, fakeMouseMove, true);
+
+    // Do a new hit-test in case the mousemove event changed the DOM.
+    // Note that if the original hit test wasn't over an element (eg. was over a scrollbar) we
+    // don't want to re-hit-test because it may be in the wrong frame (and there's no way the page
+    // could have seen the event anyway).
+    // FIXME: Use a hit-test cache to avoid unnecessary hit tests. http://crbug.com/398920
+    if (currentHitTest.innerNode())
+        currentHitTest = hitTestResultInFrame(m_frame, adjustedPoint, HitTestRequest::ReadOnly);
+    m_clickNode = currentHitTest.innerNode();
+    if (m_clickNode && m_clickNode->isTextNode())
+        m_clickNode = NodeRenderingTraversal::parent(m_clickNode.get());
 
-    bool defaultPrevented = false;
     PlatformMouseEvent fakeMouseDown(adjustedPoint, gestureEvent.globalPosition(),
         LeftButton, PlatformEvent::MousePressed, gestureEvent.tapCount(),
         modifiers, PlatformMouseEvent::FromTouch,  gestureEvent.timestamp());
-    defaultPrevented |= handleMousePressEvent(fakeMouseDown);
-
+    bool swallowMouseDownEvent = !dispatchMouseEvent(EventTypeNames::mousedown, currentHitTest.innerNode(), gestureEvent.tapCount(), fakeMouseDown, true);
+    if (!swallowMouseDownEvent)
+        swallowMouseDownEvent = handleMouseFocus(fakeMouseDown);
+    if (!swallowMouseDownEvent)
+        swallowMouseDownEvent = handleMousePressEvent(MouseEventWithHitTestResults(fakeMouseDown, currentHitTest));
+
+    // FIXME: Use a hit-test cache to avoid unnecessary hit tests. http://crbug.com/398920
+    if (currentHitTest.innerNode())
+        currentHitTest = hitTestResultInFrame(m_frame, adjustedPoint, HitTestRequest::ReadOnly);
     PlatformMouseEvent fakeMouseUp(adjustedPoint, gestureEvent.globalPosition(),
         LeftButton, PlatformEvent::MouseReleased, gestureEvent.tapCount(),
         modifiers, PlatformMouseEvent::FromTouch,  gestureEvent.timestamp());
-    defaultPrevented |= handleMouseReleaseEvent(fakeMouseUp);
+    bool swallowMouseUpEvent = !dispatchMouseEvent(EventTypeNames::mouseup, currentHitTest.innerNode(), gestureEvent.tapCount(), fakeMouseUp, false);
 
-    return defaultPrevented;
+    bool swallowClickEvent = false;
+    if (m_clickNode) {
+        if (currentHitTest.innerNode()) {
+            Node* clickTargetNode = currentHitTest.innerNode()->commonAncestor(*m_clickNode, parentForClickEvent);
+            swallowClickEvent = !dispatchMouseEvent(EventTypeNames::click, clickTargetNode, gestureEvent.tapCount(), fakeMouseUp, true);
+        }
+        m_clickNode = nullptr;
+    }
+
+    if (!swallowMouseUpEvent)
+        swallowMouseUpEvent = handleMouseReleaseEvent(MouseEventWithHitTestResults(fakeMouseUp, currentHitTest));
+
+    return swallowMouseDownEvent | swallowMouseUpEvent | swallowClickEvent;
 }
 
-bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
+bool EventHandler::handleGestureLongPress(const GestureEventWithHitTestResults& targetedEvent)
 {
+    const PlatformGestureEvent& gestureEvent = targetedEvent.event();
+    IntPoint adjustedPoint = gestureEvent.position();
+
+    // FIXME: Ideally we should try to remove the extra mouse-specific hit-tests here (re-using the
+    // supplied HitTestResult), but that will require some overhaul of the touch drag-and-drop code
+    // and LongPress is such a special scenario that it's unlikely to matter much in practice.
+
     m_longTapShouldInvokeContextMenu = false;
     if (m_frame->settings() && m_frame->settings()->touchDragDropEnabled() && m_frame->view()) {
         PlatformMouseEvent mouseDownEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1,
@@ -2436,11 +2292,11 @@ bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEve
 
         PlatformMouseEvent mouseDragEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MouseMoved, 1,
             gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), WTF::currentTime());
-        HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+        HitTestRequest request(HitTestRequest::ReadOnly);
         MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseDragEvent);
         m_didStartDrag = false;
         m_mouseDownMayStartDrag = true;
-        dragState().m_dragSrc = 0;
+        dragState().m_dragSrc = nullptr;
         m_mouseDownPos = m_frame->view()->windowToContents(mouseDragEvent.position());
         RefPtr<FrameView> protector(m_frame->view());
         handleDrag(mev, DontCheckDragHysteresis);
@@ -2466,15 +2322,15 @@ bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEve
             }
         }
     }
-    return sendContextMenuEventForGesture(gestureEvent);
+    return sendContextMenuEventForGesture(targetedEvent);
 }
 
-bool EventHandler::handleGestureLongTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
+bool EventHandler::handleGestureLongTap(const GestureEventWithHitTestResults& targetedEvent)
 {
 #if !OS(ANDROID)
     if (m_longTapShouldInvokeContextMenu) {
         m_longTapShouldInvokeContextMenu = false;
-        return sendContextMenuEventForGesture(gestureEvent);
+        return sendContextMenuEventForGesture(targetedEvent);
     }
 #endif
     return false;
@@ -2507,39 +2363,30 @@ bool EventHandler::handleScrollGestureOnResizer(Node* eventTarget, const Platfor
     return false;
 }
 
-bool EventHandler::handleGestureTwoFingerTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
+bool EventHandler::passScrollGestureEventToWidget(const PlatformGestureEvent& gestureEvent, RenderObject* renderer)
 {
-    return sendContextMenuEventForGesture(gestureEvent);
-}
+    ASSERT(gestureEvent.isScrollEvent());
 
-bool EventHandler::passGestureEventToWidget(const PlatformGestureEvent& gestureEvent, Widget* widget)
-{
-    if (!widget)
+    if (!m_lastGestureScrollOverWidget)
         return false;
 
-    if (!widget->isFrameView())
+    if (!renderer || !renderer->isWidget())
         return false;
 
-    return toFrameView(widget)->frame().eventHandler().handleGestureEvent(gestureEvent);
-}
+    Widget* widget = toRenderWidget(renderer)->widget();
 
-bool EventHandler::passGestureEventToWidgetIfPossible(const PlatformGestureEvent& gestureEvent, RenderObject* renderer)
-{
-    if (m_lastHitTestResultOverWidget && renderer && renderer->isWidget()) {
-        Widget* widget = toRenderWidget(renderer)->widget();
-        return widget && passGestureEventToWidget(gestureEvent, widget);
-    }
-    return false;
+    if (!widget || !widget->isFrameView())
+        return false;
+
+    return toFrameView(widget)->frame().eventHandler().handleGestureScrollEvent(gestureEvent);
 }
 
 bool EventHandler::handleGestureScrollEnd(const PlatformGestureEvent& gestureEvent) {
-    RefPtr<Node> node = m_scrollGestureHandlingNode;
+    RefPtrWillBeRawPtr<Node> node = m_scrollGestureHandlingNode;
     clearGestureScrollNodes();
 
-    if (node) {
-        ASSERT(node->refCount() > 0);
-        passGestureEventToWidgetIfPossible(gestureEvent, node->renderer());
-    }
+    if (node)
+        passScrollGestureEventToWidget(gestureEvent, node->renderer());
 
     return false;
 }
@@ -2554,15 +2401,6 @@ bool EventHandler::handleGestureScrollBegin(const PlatformGestureEvent& gestureE
     if (!view)
         return false;
 
-    LayoutPoint viewPoint = view->windowToContents(gestureEvent.position());
-    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
-    HitTestResult result(viewPoint);
-    document->renderView()->hitTest(request, result);
-
-    m_lastHitTestResultOverWidget = result.isOverWidget();
-    m_scrollGestureHandlingNode = result.innerNode();
-    m_previousGestureScrolledNode = 0;
-
     // If there's no renderer on the node, send the event to the nearest ancestor with a renderer.
     // Needed for <option> and <optgroup> elements so we can touch scroll <select>s
     while (m_scrollGestureHandlingNode && !m_scrollGestureHandlingNode->renderer())
@@ -2571,7 +2409,7 @@ bool EventHandler::handleGestureScrollBegin(const PlatformGestureEvent& gestureE
     if (!m_scrollGestureHandlingNode)
         return false;
 
-    passGestureEventToWidgetIfPossible(gestureEvent, m_scrollGestureHandlingNode->renderer());
+    passScrollGestureEventToWidget(gestureEvent, m_scrollGestureHandlingNode->renderer());
 
     return true;
 }
@@ -2600,7 +2438,7 @@ bool EventHandler::handleGestureScrollUpdate(const PlatformGestureEvent& gesture
     bool scrollShouldNotPropagate = gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation;
 
     // Try to send the event to the correct view.
-    if (passGestureEventToWidgetIfPossible(gestureEvent, renderer)) {
+    if (passScrollGestureEventToWidget(gestureEvent, renderer)) {
         if(scrollShouldNotPropagate)
               m_previousGestureScrolledNode = m_scrollGestureHandlingNode;
 
@@ -2650,19 +2488,10 @@ bool EventHandler::sendScrollEventToView(const PlatformGestureEvent& gestureEven
     return scrolledFrame;
 }
 
-Frame* EventHandler::getSubFrameForGestureEvent(const IntPoint& touchAdjustedPoint, const PlatformGestureEvent& gestureEvent)
-{
-    PlatformMouseEvent mouseDown(touchAdjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1,
-        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
-    HitTestRequest request(HitTestRequest::ReadOnly);
-    MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseDown);
-    return subframeForHitTestResult(mev);
-}
-
 void EventHandler::clearGestureScrollNodes()
 {
-    m_scrollGestureHandlingNode = 0;
-    m_previousGestureScrolledNode = 0;
+    m_scrollGestureHandlingNode = nullptr;
+    m_previousGestureScrolledNode = nullptr;
 }
 
 bool EventHandler::isScrollbarHandlingGestures() const
@@ -2677,11 +2506,12 @@ bool EventHandler::shouldApplyTouchAdjustment(const PlatformGestureEvent& event)
     return !event.area().isEmpty();
 }
 
-
-bool EventHandler::bestClickableNodeForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntPoint& targetPoint, Node*& targetNode)
+bool EventHandler::bestClickableNodeForHitTestResult(const HitTestResult& result, IntPoint& targetPoint, Node*& targetNode)
 {
-    IntPoint hitTestPoint = m_frame->view()->windowToContents(touchCenter);
-    HitTestResult result = hitTestResultAtPoint(hitTestPoint, HitTestRequest::ReadOnly | HitTestRequest::Active, touchRadius);
+    // FIXME: Unify this with the other best* functions which are very similar.
+
+    TRACE_EVENT0("input", "EventHandler::bestClickableNodeForHitTestResult");
+    ASSERT(result.isRectBasedTest());
 
     // If the touch is over a scrollbar, don't adjust the touch point since touch adjustment only takes into account
     // DOM nodes so a touch over a scrollbar will be adjusted towards nearby nodes. This leads to things like textarea
@@ -2689,74 +2519,174 @@ bool EventHandler::bestClickableNodeForTouchPoint(const IntPoint& touchCenter, c
     if (result.scrollbar())
         return false;
 
-    IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
-    Vector<RefPtr<Node>, 11> nodes;
+    IntPoint touchCenter = m_frame->view()->contentsToWindow(result.roundedPointInMainFrame());
+    IntRect touchRect = m_frame->view()->contentsToWindow(result.hitTestLocation().boundingBox());
+
+    WillBeHeapVector<RefPtrWillBeMember<Node>, 11> nodes;
     copyToVector(result.rectBasedTestResult(), nodes);
 
-    // FIXME: Should be able to handle targetNode being a shadow DOM node to avoid performing uncessary hit tests
-    // in the case where further processing on the node is required. Returning the shadow ancestor prevents a
-    // regression in touchadjustment/html-label.html. Some refinement is required to testing/internals to
-    // handle targetNode being a shadow DOM node.
+    // FIXME: the explicit Vector conversion copies into a temporary and is wasteful.
+    return findBestClickableCandidate(targetNode, targetPoint, touchCenter, touchRect, WillBeHeapVector<RefPtrWillBeMember<Node> > (nodes));
+}
+
+bool EventHandler::bestContextMenuNodeForHitTestResult(const HitTestResult& result, IntPoint& targetPoint, Node*& targetNode)
+{
+    ASSERT(result.isRectBasedTest());
+    IntPoint touchCenter = m_frame->view()->contentsToWindow(result.roundedPointInMainFrame());
+    IntRect touchRect = m_frame->view()->contentsToWindow(result.hitTestLocation().boundingBox());
+    WillBeHeapVector<RefPtrWillBeMember<Node>, 11> nodes;
+    copyToVector(result.rectBasedTestResult(), nodes);
 
-    // FIXME: the explicit Vector conversion copies into a temporary and is
-    // wasteful.
-    bool success = findBestClickableCandidate(targetNode, targetPoint, touchCenter, touchRect, Vector<RefPtr<Node> > (nodes));
-    if (success && targetNode)
-        targetNode = targetNode->deprecatedShadowAncestorNode();
-    return success;
+    // FIXME: the explicit Vector conversion copies into a temporary and is wasteful.
+    return findBestContextMenuCandidate(targetNode, targetPoint, touchCenter, touchRect, WillBeHeapVector<RefPtrWillBeMember<Node> >(nodes));
 }
 
-bool EventHandler::bestContextMenuNodeForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntPoint& targetPoint, Node*& targetNode)
+bool EventHandler::bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode)
 {
     IntPoint hitTestPoint = m_frame->view()->windowToContents(touchCenter);
     HitTestResult result = hitTestResultAtPoint(hitTestPoint, HitTestRequest::ReadOnly | HitTestRequest::Active, touchRadius);
 
     IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
-    Vector<RefPtr<Node>, 11> nodes;
+    WillBeHeapVector<RefPtrWillBeMember<Node>, 11> nodes;
     copyToVector(result.rectBasedTestResult(), nodes);
 
-    // FIXME: the explicit Vector conversion copies into a temporary and is
-    // wasteful.
-    return findBestContextMenuCandidate(targetNode, targetPoint, touchCenter, touchRect, Vector<RefPtr<Node> >(nodes));
+    // FIXME: the explicit Vector conversion copies into a temporary and is wasteful.
+    return findBestZoomableArea(targetNode, targetArea, touchCenter, touchRect, WillBeHeapVector<RefPtrWillBeMember<Node> >(nodes));
 }
 
-bool EventHandler::bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode)
+GestureEventWithHitTestResults EventHandler::targetGestureEvent(const PlatformGestureEvent& gestureEvent, bool readOnly)
 {
-    IntPoint hitTestPoint = m_frame->view()->windowToContents(touchCenter);
-    HitTestResult result = hitTestResultAtPoint(hitTestPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, touchRadius);
+    ASSERT(m_frame == m_frame->localFrameRoot());
+    // Scrolling events get hit tested per frame (like wheel events do).
+    ASSERT(!gestureEvent.isScrollEvent());
 
-    IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
-    Vector<RefPtr<Node>, 11> nodes;
-    copyToVector(result.rectBasedTestResult(), nodes);
+    HitTestRequest::HitTestRequestType hitType = getHitTypeForGestureType(gestureEvent.type());
+    double activeInterval = 0;
+    bool shouldKeepActiveForMinInterval = false;
+    if (readOnly) {
+        hitType |= HitTestRequest::ReadOnly;
+    } else if (gestureEvent.type() == PlatformEvent::GestureTap) {
+        // If the Tap is received very shortly after ShowPress, we want to
+        // delay clearing of the active state so that it's visible to the user
+        // for at least a couple of frames.
+        activeInterval = WTF::currentTime() - m_lastShowPressTimestamp;
+        shouldKeepActiveForMinInterval = m_lastShowPressTimestamp && activeInterval < minimumActiveInterval;
+        if (shouldKeepActiveForMinInterval)
+            hitType |= HitTestRequest::ReadOnly;
+    }
+
+    // Perform the rect-based hit-test. Note that we don't yet apply hover/active state here
+    // because we need to resolve touch adjustment first so that we apply hover/active it to
+    // the final adjusted node.
+    IntPoint hitTestPoint = m_frame->view()->windowToContents(gestureEvent.position());
+    IntSize touchRadius = gestureEvent.area();
+    touchRadius.scale(1.f / 2);
+    // FIXME: We should not do a rect-based hit-test if touch adjustment is disabled.
+    HitTestResult hitTestResult = hitTestResultAtPoint(hitTestPoint, hitType | HitTestRequest::ReadOnly, touchRadius);
 
-    // FIXME: the explicit Vector conversion copies into a temporary and is
-    // wasteful.
-    return findBestZoomableArea(targetNode, targetArea, touchCenter, touchRect, Vector<RefPtr<Node> >(nodes));
+    // Hit-test the main frame scrollbars (in addition to the child-frame and RenderLayer
+    // scroll bars checked by the hit-test code.
+    if (!hitTestResult.scrollbar()) {
+        if (FrameView* view = m_frame->view()) {
+            hitTestResult.setScrollbar(view->scrollbarAtPoint(gestureEvent.position()));
+        }
+    }
+
+    // Adjust the location of the gesture to the most likely nearby node, as appropriate for the
+    // type of event.
+    PlatformGestureEvent adjustedEvent = gestureEvent;
+    applyTouchAdjustment(&adjustedEvent, &hitTestResult);
+
+    // Do a new hit-test at the (adjusted) gesture co-ordinates. This is necessary because
+    // rect-based hit testing and touch adjustment sometimes return a different node than
+    // what a point-based hit test would return for the same point.
+    // FIXME: Fix touch adjustment to avoid the need for a redundant hit test. http://crbug.com/398914
+    if (shouldApplyTouchAdjustment(gestureEvent)) {
+        LocalFrame* hitFrame = hitTestResult.innerNodeFrame();
+        if (!hitFrame)
+            hitFrame = m_frame;
+        hitTestResult = hitTestResultInFrame(hitFrame, hitFrame->view()->windowToContents(adjustedEvent.position()), hitType | HitTestRequest::ReadOnly);
+        // FIXME: HitTest entry points should really check for main frame scrollbars themselves.
+        if (!hitTestResult.scrollbar()) {
+            if (FrameView* view = m_frame->view()) {
+                hitTestResult.setScrollbar(view->scrollbarAtPoint(gestureEvent.position()));
+            }
+        }
+    }
+
+    // Now apply hover/active state to the final target.
+    // FIXME: This is supposed to send mouseenter/mouseleave events, but doesn't because we
+    // aren't passing a PlatformMouseEvent.
+    HitTestRequest request(hitType | HitTestRequest::AllowChildFrameContent);
+    if (!request.readOnly())
+        m_frame->document()->updateHoverActiveState(request, hitTestResult.innerElement());
+
+    if (shouldKeepActiveForMinInterval) {
+        m_lastDeferredTapElement = hitTestResult.innerElement();
+        m_activeIntervalTimer.startOneShot(minimumActiveInterval - activeInterval, FROM_HERE);
+    }
+
+    return GestureEventWithHitTestResults(adjustedEvent, hitTestResult);
 }
 
-bool EventHandler::adjustGesturePosition(const PlatformGestureEvent& gestureEvent, IntPoint& adjustedPoint)
+HitTestRequest::HitTestRequestType EventHandler::getHitTypeForGestureType(PlatformEvent::Type type)
 {
-    if (!shouldApplyTouchAdjustment(gestureEvent))
-        return false;
+    HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent | HitTestRequest::AllowFrameScrollbars;
+    switch (type) {
+    case PlatformEvent::GestureShowPress:
+    case PlatformEvent::GestureTapUnconfirmed:
+        return hitType | HitTestRequest::Active;
+    case PlatformEvent::GestureTapDownCancel:
+        // A TapDownCancel received when no element is active shouldn't really be changing hover state.
+        if (!m_frame->document()->activeHoverElement())
+            hitType |= HitTestRequest::ReadOnly;
+        return hitType | HitTestRequest::Release;
+    case PlatformEvent::GestureTap:
+        return hitType | HitTestRequest::Release;
+    case PlatformEvent::GestureTapDown:
+    case PlatformEvent::GestureLongPress:
+    case PlatformEvent::GestureLongTap:
+    case PlatformEvent::GestureTwoFingerTap:
+        // FIXME: Shouldn't LongTap and TwoFingerTap clear the Active state?
+        return hitType | HitTestRequest::Active | HitTestRequest::ReadOnly;
+    default:
+        ASSERT_NOT_REACHED();
+        return hitType | HitTestRequest::Active | HitTestRequest::ReadOnly;
+    }
+}
 
-    Node* targetNode = 0;
-    switch (gestureEvent.type()) {
+void EventHandler::applyTouchAdjustment(PlatformGestureEvent* gestureEvent, HitTestResult* hitTestResult)
+{
+    if (!shouldApplyTouchAdjustment(*gestureEvent))
+        return;
+
+    Node* adjustedNode = 0;
+    IntPoint adjustedPoint = gestureEvent->position();
+    IntSize radius = gestureEvent->area();
+    radius.scale(1.f / 2);
+    bool adjusted = false;
+    switch (gestureEvent->type()) {
     case PlatformEvent::GestureTap:
     case PlatformEvent::GestureTapUnconfirmed:
     case PlatformEvent::GestureTapDown:
     case PlatformEvent::GestureShowPress:
-        bestClickableNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode);
+        adjusted = bestClickableNodeForHitTestResult(*hitTestResult, adjustedPoint, adjustedNode);
         break;
     case PlatformEvent::GestureLongPress:
     case PlatformEvent::GestureLongTap:
     case PlatformEvent::GestureTwoFingerTap:
-        bestContextMenuNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode);
+        adjusted = bestContextMenuNodeForHitTestResult(*hitTestResult, adjustedPoint, adjustedNode);
         break;
     default:
-        // FIXME: Implement handling for other types as needed.
         ASSERT_NOT_REACHED();
     }
-    return targetNode;
+
+    // Update the hit-test result to be a point-based result instead of a rect-based result.
+    // FIXME: We should do this even when no candidate matches the node filter. crbug.com/398914
+    if (adjusted) {
+        hitTestResult->resolveRectBasedTest(adjustedNode, m_frame->view()->windowToContents(adjustedPoint));
+        gestureEvent->applyTouchAdjustment(adjustedPoint);
+    }
 }
 
 bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
@@ -2768,9 +2698,8 @@ bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
 
     // Clear mouse press state to avoid initiating a drag while context menu is up.
     m_mousePressed = false;
-    bool swallowEvent;
     LayoutPoint viewportPos = v->windowToContents(event.position());
-    HitTestRequest request(HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+    HitTestRequest request(HitTestRequest::Active);
     MouseEventWithHitTestResults mev = doc->prepareMouseEvent(request, viewportPos, event);
 
     if (!m_frame->selection().contains(viewportPos)
@@ -2787,9 +2716,7 @@ bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
             selectClosestWordOrLinkFromMouseEvent(mev);
     }
 
-    swallowEvent = !dispatchMouseEvent(EventTypeNames::contextmenu, mev.targetNode(), true, 0, event, false);
-
-    return swallowEvent;
+    return !dispatchMouseEvent(EventTypeNames::contextmenu, mev.targetNode(), 0, event, false);
 }
 
 bool EventHandler::sendContextMenuEventForKey()
@@ -2817,9 +2744,10 @@ bool EventHandler::sendContextMenuEventForKey()
     Element* focusedElement = doc->focusedElement();
     FrameSelection& selection = m_frame->selection();
     Position start = selection.selection().start();
+    bool shouldTranslateToRootView = true;
 
     if (start.deprecatedNode() && (selection.rootEditableElement() || selection.isRange())) {
-        RefPtr<Range> selectionRange = selection.toNormalizedRange();
+        RefPtrWillBeRawPtr<Range> selectionRange = selection.toNormalizedRange();
         IntRect firstRect = m_frame->editor().firstRectForRange(selectionRange.get());
 
         int x = rightAligned ? firstRect.maxX() : firstRect.x();
@@ -2827,20 +2755,18 @@ bool EventHandler::sendContextMenuEventForKey()
         int y = firstRect.maxY() ? firstRect.maxY() - 1 : 0;
         location = IntPoint(x, y);
     } else if (focusedElement) {
-        RenderBoxModelObject* box = focusedElement->renderBoxModelObject();
-        if (!box)
-            return false;
-        IntRect clippedRect = box->pixelSnappedAbsoluteClippedOverflowRect();
-        location = IntPoint(clippedRect.x(), clippedRect.maxY() - 1);
+        IntRect clippedRect = focusedElement->boundsInRootViewSpace();
+        location = IntPoint(clippedRect.center());
     } else {
         location = IntPoint(
             rightAligned ? view->contentsWidth() - kContextMenuMargin : kContextMenuMargin,
             kContextMenuMargin);
+        shouldTranslateToRootView = false;
     }
 
     m_frame->view()->setCursor(pointerCursor());
 
-    IntPoint position = view->contentsToRootView(location);
+    IntPoint position = shouldTranslateToRootView ? view->contentsToRootView(location) : location;
     IntPoint globalPosition = view->hostWindow()->rootViewToScreen(IntRect(position, IntSize())).location();
 
     Node* targetNode = doc->focusedElement();
@@ -2850,7 +2776,7 @@ bool EventHandler::sendContextMenuEventForKey()
     // Use the focused node as the target for hover and active.
     HitTestResult result(position);
     result.setInnerNode(targetNode);
-    doc->updateHoverActiveState(HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, result.innerElement());
+    doc->updateHoverActiveState(HitTestRequest::Active, result.innerElement());
 
     // The contextmenu event is a mouse event even when invoked using the keyboard.
     // This is required for web compatibility.
@@ -2863,10 +2789,11 @@ bool EventHandler::sendContextMenuEventForKey()
 
     PlatformMouseEvent mouseEvent(position, globalPosition, RightButton, eventType, 1, false, false, false, false, WTF::currentTime());
 
-    return !dispatchMouseEvent(EventTypeNames::contextmenu, targetNode, true, 0, mouseEvent, false);
+    handleMousePressEvent(mouseEvent);
+    return sendContextMenuEvent(mouseEvent);
 }
 
-bool EventHandler::sendContextMenuEventForGesture(const PlatformGestureEvent& event)
+bool EventHandler::sendContextMenuEventForGesture(const GestureEventWithHitTestResults& targetedEvent)
 {
 #if OS(WIN)
     PlatformEvent::Type eventType = PlatformEvent::MouseReleased;
@@ -2874,11 +2801,10 @@ bool EventHandler::sendContextMenuEventForGesture(const PlatformGestureEvent& ev
     PlatformEvent::Type eventType = PlatformEvent::MousePressed;
 #endif
 
-    IntPoint adjustedPoint = event.position();
-    adjustGesturePosition(event, adjustedPoint);
-    PlatformMouseEvent mouseEvent(adjustedPoint, event.globalPosition(), RightButton, eventType, 1, false, false, false, false, WTF::currentTime());
+    PlatformMouseEvent mouseEvent(targetedEvent.event().position(), targetedEvent.event().globalPosition(), RightButton, eventType, 1, false, false, false, false, WTF::currentTime());
     // To simulate right-click behavior, we send a right mouse down and then
     // context menu event.
+    // FIXME: Send HitTestResults to avoid redundant hit tests.
     handleMousePressEvent(mouseEvent);
     return sendContextMenuEvent(mouseEvent);
     // We do not need to send a corresponding mouse release because in case of
@@ -2888,13 +2814,13 @@ bool EventHandler::sendContextMenuEventForGesture(const PlatformGestureEvent& ev
 void EventHandler::scheduleHoverStateUpdate()
 {
     if (!m_hoverTimer.isActive())
-        m_hoverTimer.startOneShot(0);
+        m_hoverTimer.startOneShot(0, FROM_HERE);
 }
 
 void EventHandler::scheduleCursorUpdate()
 {
     if (!m_cursorUpdateTimer.isActive())
-        m_cursorUpdateTimer.startOneShot(cursorUpdateInterval);
+        m_cursorUpdateTimer.startOneShot(cursorUpdateInterval, FROM_HERE);
 }
 
 void EventHandler::dispatchFakeMouseMoveEventSoon()
@@ -2916,10 +2842,10 @@ void EventHandler::dispatchFakeMouseMoveEventSoon()
     if (m_maxMouseMovedDuration > fakeMouseMoveShortInterval) {
         if (m_fakeMouseMoveEventTimer.isActive())
             m_fakeMouseMoveEventTimer.stop();
-        m_fakeMouseMoveEventTimer.startOneShot(fakeMouseMoveLongInterval);
+        m_fakeMouseMoveEventTimer.startOneShot(fakeMouseMoveLongInterval, FROM_HERE);
     } else {
         if (!m_fakeMouseMoveEventTimer.isActive())
-            m_fakeMouseMoveEventTimer.startOneShot(fakeMouseMoveShortInterval);
+            m_fakeMouseMoveEventTimer.startOneShot(fakeMouseMoveShortInterval, FROM_HERE);
     }
 }
 
@@ -2994,7 +2920,7 @@ void EventHandler::hoverTimerFired(Timer<EventHandler>*)
 
     if (RenderView* renderer = m_frame->contentRenderer()) {
         if (FrameView* view = m_frame->view()) {
-            HitTestRequest request(HitTestRequest::Move | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+            HitTestRequest request(HitTestRequest::Move);
             HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
             renderer->hitTest(request, result);
             m_frame->document()->updateHoverActiveState(request, result.innerElement());
@@ -3014,7 +2940,7 @@ void EventHandler::activeIntervalTimerFired(Timer<EventHandler>*)
         HitTestRequest request(HitTestRequest::TouchEvent | HitTestRequest::Release);
         m_frame->document()->updateHoverActiveState(request, m_lastDeferredTapElement.get());
     }
-    m_lastDeferredTapElement = 0;
+    m_lastDeferredTapElement = nullptr;
 }
 
 void EventHandler::notifyElementActivated()
@@ -3022,7 +2948,7 @@ void EventHandler::notifyElementActivated()
     // Since another element has been set to active, stop current timer and clear reference.
     if (m_activeIntervalTimer.isActive())
         m_activeIntervalTimer.stop();
-    m_lastDeferredTapElement = 0;
+    m_lastDeferredTapElement = nullptr;
 }
 
 bool EventHandler::handleAccessKey(const PlatformKeyboardEvent& evt)
@@ -3065,9 +2991,12 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
 {
     RefPtr<FrameView> protector(m_frame->view());
 
-    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(m_frame->document())) {
-        if (fullscreen->webkitIsFullScreen() && !isKeyEventAllowedInFullScreen(fullscreen, initialKeyEvent))
+    ASSERT(m_frame->document());
+    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(*m_frame->document())) {
+        if (fullscreen->webkitIsFullScreen() && !isKeyEventAllowedInFullScreen(fullscreen, initialKeyEvent)) {
+            UseCounter::count(*m_frame->document(), UseCounter::KeyEventNotAllowedInFullScreen);
             return false;
+        }
     }
 
     if (initialKeyEvent.windowsVirtualKeyCode() == VK_CAPITAL)
@@ -3086,7 +3015,7 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
 
     // Check for cases where we are too early for events -- possible unmatched key up
     // from pressing return in the location bar.
-    RefPtr<Node> node = eventTargetNodeForDocument(m_frame->document());
+    RefPtrWillBeRawPtr<Node> node = eventTargetNodeForDocument(m_frame->document());
     if (!node)
         return false;
 
@@ -3108,7 +3037,7 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
     PlatformKeyboardEvent keyDownEvent = initialKeyEvent;
     if (keyDownEvent.type() != PlatformEvent::RawKeyDown)
         keyDownEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
-    RefPtr<KeyboardEvent> keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->domWindow());
+    RefPtrWillBeRawPtr<KeyboardEvent> keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->domWindow());
     if (matchedAnAccessKey)
         keydown->setDefaultPrevented(true);
     keydown->setTarget(node);
@@ -3137,7 +3066,7 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
     keyPressEvent.disambiguateKeyDownEvent(PlatformEvent::Char);
     if (keyPressEvent.text().isEmpty())
         return keydownResult;
-    RefPtr<KeyboardEvent> keypress = KeyboardEvent::create(keyPressEvent, m_frame->document()->domWindow());
+    RefPtrWillBeRawPtr<KeyboardEvent> keypress = KeyboardEvent::create(keyPressEvent, m_frame->document()->domWindow());
     keypress->setTarget(node);
     if (keydownResult)
         keypress->setDefaultPrevented(true);
@@ -3146,23 +3075,23 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
     return keydownResult || keypress->defaultPrevented() || keypress->defaultHandled();
 }
 
-static FocusDirection focusDirectionForKey(const AtomicString& keyIdentifier)
+static FocusType focusDirectionForKey(const AtomicString& keyIdentifier)
 {
     DEFINE_STATIC_LOCAL(AtomicString, Down, ("Down", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, Up, ("Up", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, Left, ("Left", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, Right, ("Right", AtomicString::ConstructFromLiteral));
 
-    FocusDirection retVal = FocusDirectionNone;
+    FocusType retVal = FocusTypeNone;
 
     if (keyIdentifier == Down)
-        retVal = FocusDirectionDown;
+        retVal = FocusTypeDown;
     else if (keyIdentifier == Up)
-        retVal = FocusDirectionUp;
+        retVal = FocusTypeUp;
     else if (keyIdentifier == Left)
-        retVal = FocusDirectionLeft;
+        retVal = FocusTypeLeft;
     else if (keyIdentifier == Right)
-        retVal = FocusDirectionRight;
+        retVal = FocusTypeRight;
 
     return retVal;
 }
@@ -3170,6 +3099,11 @@ static FocusDirection focusDirectionForKey(const AtomicString& keyIdentifier)
 void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
 {
     if (event->type() == EventTypeNames::keydown) {
+        // Clear caret blinking suspended state to make sure that caret blinks
+        // when we type again after long pressing on an empty input field.
+        if (m_frame && m_frame->selection().isCaretBlinkingSuspended())
+            m_frame->selection().setCaretBlinkingSuspended(false);
+
         m_frame->editor().handleKeyboardEvent(event);
         if (event->defaultHandled())
             return;
@@ -3180,9 +3114,9 @@ void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
         else if (event->keyIdentifier() == "U+001B")
             defaultEscapeEventHandler(event);
         else {
-            FocusDirection direction = focusDirectionForKey(AtomicString(event->keyIdentifier()));
-            if (direction != FocusDirectionNone)
-                defaultArrowEventHandler(direction, event);
+            FocusType type = focusDirectionForKey(AtomicString(event->keyIdentifier()));
+            if (type != FocusTypeNone)
+                defaultArrowEventHandler(type, event);
         }
     }
     if (event->type() == EventTypeNames::keypress) {
@@ -3194,18 +3128,17 @@ void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
     }
 }
 
-bool EventHandler::dragHysteresisExceeded(const IntPoint& floatDragViewportLocation) const
+bool EventHandler::dragHysteresisExceeded(const FloatPoint& floatDragViewportLocation) const
 {
-    FloatPoint dragViewportLocation(floatDragViewportLocation.x(), floatDragViewportLocation.y());
-    return dragHysteresisExceeded(dragViewportLocation);
+    return dragHysteresisExceeded(flooredIntPoint(floatDragViewportLocation));
 }
 
-bool EventHandler::dragHysteresisExceeded(const FloatPoint& dragViewportLocation) const
+bool EventHandler::dragHysteresisExceeded(const IntPoint& dragViewportLocation) const
 {
     FrameView* view = m_frame->view();
     if (!view)
         return false;
-    IntPoint dragLocation = view->windowToContents(flooredIntPoint(dragViewportLocation));
+    IntPoint dragLocation = view->windowToContents(dragViewportLocation);
     IntSize delta = dragLocation - m_mouseDownPos;
 
     int threshold = GeneralDragHysteresis;
@@ -3228,25 +3161,27 @@ bool EventHandler::dragHysteresisExceeded(const FloatPoint& dragViewportLocation
     return abs(delta.width()) >= threshold || abs(delta.height()) >= threshold;
 }
 
-void EventHandler::freeClipboard()
+void EventHandler::clearDragDataTransfer()
 {
-    if (dragState().m_dragClipboard)
-        dragState().m_dragClipboard->setAccessPolicy(ClipboardNumb);
+    if (dragState().m_dragDataTransfer) {
+        dragState().m_dragDataTransfer->clearDragImage();
+        dragState().m_dragDataTransfer->setAccessPolicy(DataTransferNumb);
+    }
 }
 
 void EventHandler::dragSourceEndedAt(const PlatformMouseEvent& event, DragOperation operation)
 {
     // Send a hit test request so that RenderLayer gets a chance to update the :hover and :active pseudoclasses.
-    HitTestRequest request(HitTestRequest::Release | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+    HitTestRequest request(HitTestRequest::Release);
     prepareMouseEvent(request, event);
 
     if (dragState().m_dragSrc) {
-        dragState().m_dragClipboard->setDestinationOperation(operation);
+        dragState().m_dragDataTransfer->setDestinationOperation(operation);
         // for now we don't care if event handler cancels default behavior, since there is none
         dispatchDragSrcEvent(EventTypeNames::dragend, event);
     }
-    freeClipboard();
-    dragState().m_dragSrc = 0;
+    clearDragDataTransfer();
+    dragState().m_dragSrc = nullptr;
     // In case the drag was ended due to an escape key press we need to ensure
     // that consecutive mousemove events don't reinitiate the drag and drop.
     m_mouseDownMayStartDrag = false;
@@ -3262,7 +3197,7 @@ void EventHandler::updateDragStateAfterEditDragIfNeeded(Element* rootEditableEle
 // returns if we should continue "default processing", i.e., whether eventhandler canceled
 bool EventHandler::dispatchDragSrcEvent(const AtomicString& eventType, const PlatformMouseEvent& event)
 {
-    return !dispatchDragEvent(eventType, dragState().m_dragSrc.get(), event, dragState().m_dragClipboard.get());
+    return !dispatchDragEvent(eventType, dragState().m_dragSrc.get(), event, dragState().m_dragDataTransfer.get());
 }
 
 bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDragHysteresis checkDragHysteresis)
@@ -3295,7 +3230,7 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDr
                 : DragController::ImmediateSelectionDragResolution;
             dragState().m_dragSrc = m_frame->page()->dragController().draggableNode(m_frame, node, m_mouseDownPos, selectionDragPolicy, dragState().m_dragType);
         } else {
-            dragState().m_dragSrc = 0;
+            dragState().m_dragSrc = nullptr;
         }
 
         if (!dragState().m_dragSrc)
@@ -3317,8 +3252,8 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDr
 
     if (!tryStartDrag(event)) {
         // Something failed to start the drag, clean up.
-        freeClipboard();
-        dragState().m_dragSrc = 0;
+        clearDragDataTransfer();
+        dragState().m_dragSrc = nullptr;
     }
 
     m_mouseDownMayStartDrag = false;
@@ -3328,18 +3263,19 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDr
 
 bool EventHandler::tryStartDrag(const MouseEventWithHitTestResults& event)
 {
-    freeClipboard(); // would only happen if we missed a dragEnd.  Do it anyway, just
-                     // to make sure it gets numbified
-    dragState().m_dragClipboard = createDraggingClipboard();
+    // The DataTransfer would only be non-empty if we missed a dragEnd.
+    // Clear it anyway, just to make sure it gets numbified.
+    clearDragDataTransfer();
+
+    dragState().m_dragDataTransfer = createDraggingDataTransfer();
 
     // Check to see if this a DOM based drag, if it is get the DOM specified drag
     // image and offset
     if (dragState().m_dragType == DragSourceActionDHTML) {
         if (RenderObject* renderer = dragState().m_dragSrc->renderer()) {
-            // FIXME: This doesn't work correctly with transforms.
-            FloatPoint absPos = renderer->localToAbsolute();
+            FloatPoint absPos = renderer->localToAbsolute(FloatPoint(), UseTransforms);
             IntSize delta = m_mouseDownPos - roundedIntPoint(absPos);
-            dragState().m_dragClipboard->setDragImageElement(dragState().m_dragSrc.get(), IntPoint(delta));
+            dragState().m_dragDataTransfer->setDragImageElement(dragState().m_dragSrc.get(), IntPoint(delta));
         } else {
             // The renderer has disappeared, this can happen if the onStartDrag handler has hidden
             // the element in some way. In this case we just kill the drag.
@@ -3348,14 +3284,14 @@ bool EventHandler::tryStartDrag(const MouseEventWithHitTestResults& event)
     }
 
     DragController& dragController = m_frame->page()->dragController();
-    if (!dragController.populateDragClipboard(m_frame, dragState(), m_mouseDownPos))
+    if (!dragController.populateDragDataTransfer(m_frame, dragState(), m_mouseDownPos))
         return false;
     m_mouseDownMayStartDrag = dispatchDragSrcEvent(EventTypeNames::dragstart, m_mouseDown)
         && !m_frame->selection().isInPasswordField();
 
     // Invalidate clipboard here against anymore pasteboard writing for security. The drag
     // image can still be changed as we drag, but not the pasteboard data.
-    dragState().m_dragClipboard->setAccessPolicy(ClipboardImageWritable);
+    dragState().m_dragDataTransfer->setAccessPolicy(DataTransferImageWritable);
 
     if (m_mouseDownMayStartDrag) {
         // Dispatching the event could cause Page to go away. Make sure it's still valid before trying to use DragController.
@@ -3389,7 +3325,7 @@ bool EventHandler::handleTextInputEvent(const String& text, Event* underlyingEve
     if (!target)
         return false;
 
-    RefPtr<TextEvent> event = TextEvent::create(m_frame->domWindow(), text, inputType);
+    RefPtrWillBeRawPtr<TextEvent> event = TextEvent::create(m_frame->domWindow(), text, inputType);
     event->setUnderlyingEvent(underlyingEvent);
 
     target->dispatchEvent(event, IGNORE_EXCEPTION);
@@ -3406,7 +3342,7 @@ void EventHandler::defaultSpaceEventHandler(KeyboardEvent* event)
 {
     ASSERT(event->type() == EventTypeNames::keypress);
 
-    if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
+    if (event->ctrlKey() || event->metaKey() || event->altKey())
         return;
 
     ScrollDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward;
@@ -3427,25 +3363,25 @@ void EventHandler::defaultBackspaceEventHandler(KeyboardEvent* event)
 {
     ASSERT(event->type() == EventTypeNames::keydown);
 
-    if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
+    if (event->ctrlKey() || event->metaKey() || event->altKey())
         return;
 
     if (!m_frame->editor().behavior().shouldNavigateBackOnBackspace())
         return;
 
     Page* page = m_frame->page();
-    if (!page)
+    if (!page || !page->mainFrame()->isLocalFrame())
         return;
-    bool handledEvent = page->mainFrame()->loader().client()->navigateBackForward(event->shiftKey() ? 1 : -1);
+    bool handledEvent = page->deprecatedLocalMainFrame()->loader().client()->navigateBackForward(event->shiftKey() ? 1 : -1);
     if (handledEvent)
         event->setDefaultHandled();
 }
 
-void EventHandler::defaultArrowEventHandler(FocusDirection focusDirection, KeyboardEvent* event)
+void EventHandler::defaultArrowEventHandler(FocusType focusType, KeyboardEvent* event)
 {
     ASSERT(event->type() == EventTypeNames::keydown);
 
-    if (event->ctrlKey() || event->metaKey() || event->altGraphKey() || event->shiftKey())
+    if (event->ctrlKey() || event->metaKey() || event->shiftKey())
         return;
 
     Page* page = m_frame->page();
@@ -3460,7 +3396,7 @@ void EventHandler::defaultArrowEventHandler(FocusDirection focusDirection, Keybo
     if (m_frame->document()->inDesignMode())
         return;
 
-    if (page->focusController().advanceFocus(focusDirection))
+    if (page->focusController().advanceFocus(focusType))
         event->setDefaultHandled();
 }
 
@@ -3469,7 +3405,7 @@ void EventHandler::defaultTabEventHandler(KeyboardEvent* event)
     ASSERT(event->type() == EventTypeNames::keydown);
 
     // We should only advance focus on tabs if no special modifier keys are held down.
-    if (event->ctrlKey() || event->metaKey() || event->altGraphKey())
+    if (event->ctrlKey() || event->metaKey())
         return;
 
     Page* page = m_frame->page();
@@ -3478,13 +3414,13 @@ void EventHandler::defaultTabEventHandler(KeyboardEvent* event)
     if (!page->tabKeyCyclesThroughElements())
         return;
 
-    FocusDirection focusDirection = event->shiftKey() ? FocusDirectionBackward : FocusDirectionForward;
+    FocusType focusType = event->shiftKey() ? FocusTypeBackward : FocusTypeForward;
 
     // Tabs can be used in design mode editing.
     if (m_frame->document()->inDesignMode())
         return;
 
-    if (page->focusController().advanceFocus(focusDirection))
+    if (page->focusController().advanceFocus(focusType))
         event->setDefaultHandled();
 }
 
@@ -3510,8 +3446,18 @@ void EventHandler::setFrameWasScrolledByUser()
         view->setWasScrolledByUser(true);
 }
 
-bool EventHandler::passMousePressEventToScrollbar(MouseEventWithHitTestResults& mev, Scrollbar* scrollbar)
+bool EventHandler::passMousePressEventToScrollbar(MouseEventWithHitTestResults& mev)
 {
+    // First try to use the frame scrollbar.
+    FrameView* view = m_frame->view();
+    Scrollbar* scrollbar = view ? view->scrollbarAtPoint(mev.event().position()) : 0;
+
+    // Then try the scrollbar in the hit test.
+    if (!scrollbar)
+        scrollbar = mev.scrollbar();
+
+    updateLastScrollbarUnderMouse(scrollbar, true);
+
     if (!scrollbar || !scrollbar->enabled())
         return false;
     setFrameWasScrolledByUser();
@@ -3555,7 +3501,7 @@ static const AtomicString& eventNameForTouchPointState(PlatformTouchPoint::State
     }
 }
 
-HitTestResult EventHandler::hitTestResultInFrame(Frame* frame, const LayoutPoint& point, HitTestRequest::HitTestRequestType hitType)
+HitTestResult EventHandler::hitTestResultInFrame(LocalFrame* frame, const LayoutPoint& point, HitTestRequest::HitTestRequestType hitType)
 {
     HitTestResult result(point);
 
@@ -3572,31 +3518,10 @@ HitTestResult EventHandler::hitTestResultInFrame(Frame* frame, const LayoutPoint
 
 bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
 {
-    // First build up the lists to use for the 'touches', 'targetTouches' and 'changedTouches' attributes
-    // in the JS event. See http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
-    // for an overview of how these lists fit together.
-
-    // Holds the complete set of touches on the screen and will be used as the 'touches' list in the JS event.
-    RefPtr<TouchList> touches = TouchList::create();
-
-    // A different view on the 'touches' list above, filtered and grouped by event target. Used for the
-    // 'targetTouches' list in the JS event.
-    typedef HashMap<EventTarget*, RefPtr<TouchList> > TargetTouchesMap;
-    TargetTouchesMap touchesByTarget;
-
-    // Array of touches per state, used to assemble the 'changedTouches' list in the JS event.
-    typedef HashSet<RefPtr<EventTarget> > EventTargetSet;
-    struct {
-        // The touches corresponding to the particular change state this struct instance represents.
-        RefPtr<TouchList> m_touches;
-        // Set of targets involved in m_touches.
-        EventTargetSet m_targets;
-    } changedTouches[PlatformTouchPoint::TouchStateEnd];
+    TRACE_EVENT0("blink", "EventHandler::handleTouchEvent");
 
     const Vector<PlatformTouchPoint>& points = event.touchPoints();
 
-    UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
-
     unsigned i;
     bool freshTouchEvents = true;
     bool allTouchReleased = true;
@@ -3607,50 +3532,48 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
         if (point.state() != PlatformTouchPoint::TouchReleased && point.state() != PlatformTouchPoint::TouchCancelled)
             allTouchReleased = false;
     }
+    if (freshTouchEvents) {
+        // Ideally we'd ASSERT !m_touchSequenceDocument here since we should
+        // have cleared the active document when we saw the last release. But we
+        // have some tests that violate this, ClusterFuzz could trigger it, and
+        // there may be cases where the browser doesn't reliably release all
+        // touches. http://crbug.com/345372 tracks this.
+        m_touchSequenceDocument.clear();
+        m_touchSequenceUserGestureToken.clear();
+    }
+
+    OwnPtr<UserGestureIndicator> gestureIndicator;
+
+    if (m_touchSequenceUserGestureToken)
+        gestureIndicator = adoptPtr(new UserGestureIndicator(m_touchSequenceUserGestureToken.release()));
+    else
+        gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingUserGesture));
+
+    m_touchSequenceUserGestureToken = gestureIndicator->currentToken();
+
+    ASSERT(m_frame->view());
+    if (m_touchSequenceDocument && (!m_touchSequenceDocument->frame() || !m_touchSequenceDocument->frame()->view())) {
+        // If the active touch document has no frame or view, it's probably being destroyed
+        // so we can't dispatch events.
+        return false;
+    }
 
+    // First do hit tests for any new touch points.
     for (i = 0; i < points.size(); ++i) {
         const PlatformTouchPoint& point = points[i];
-        PlatformTouchPoint::State pointState = point.state();
-        LayoutPoint pagePoint = documentPointForWindowPoint(m_frame, point.pos());
-
-        // Gesture events trigger the active state, not touch events,
-        // so touch event hit tests can always be read only.
-        HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent | HitTestRequest::ReadOnly;
-        // The HitTestRequest types used for mouse events map quite adequately
-        // to touch events. Note that in addition to meaning that the hit test
-        // should affect the active state of the current node if necessary,
-        // HitTestRequest::Active signifies that the hit test is taking place
-        // with the mouse (or finger in this case) being pressed.
-        switch (pointState) {
-        case PlatformTouchPoint::TouchPressed:
-            hitType |= HitTestRequest::Active;
-            break;
-        case PlatformTouchPoint::TouchMoved:
-            hitType |= HitTestRequest::Active | HitTestRequest::Move;
-            break;
-        case PlatformTouchPoint::TouchReleased:
-        case PlatformTouchPoint::TouchCancelled:
-            hitType |= HitTestRequest::Release;
-            break;
-        case PlatformTouchPoint::TouchStationary:
-            hitType |= HitTestRequest::Active;
-            break;
-        default:
-            ASSERT_NOT_REACHED();
-            break;
-        }
 
-        // Increment the platform touch id by 1 to avoid storing a key of 0 in the hashmap.
-        unsigned touchPointTargetKey = point.id() + 1;
-        RefPtr<EventTarget> touchTarget;
-        if (pointState == PlatformTouchPoint::TouchPressed) {
+        // Touch events implicitly capture to the touched node, and don't change
+        // active/hover states themselves (Gesture events do). So we only need
+        // to hit-test on touchstart, and it can be read-only.
+        if (point.state() == PlatformTouchPoint::TouchPressed) {
+            HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent | HitTestRequest::ReadOnly | HitTestRequest::Active;
+            LayoutPoint pagePoint = roundedLayoutPoint(m_frame->view()->windowToContents(point.pos()));
             HitTestResult result;
-            if (freshTouchEvents) {
+            if (!m_touchSequenceDocument) {
                 result = hitTestResultAtPoint(pagePoint, hitType);
-                m_originatingTouchPointTargetKey = touchPointTargetKey;
-            } else if (m_originatingTouchPointDocument.get() && m_originatingTouchPointDocument->frame()) {
-                LayoutPoint pagePointInOriginatingDocument = documentPointForWindowPoint(m_originatingTouchPointDocument->frame(), point.pos());
-                result = hitTestResultInFrame(m_originatingTouchPointDocument->frame(), pagePointInOriginatingDocument, hitType);
+            } else if (m_touchSequenceDocument->frame()) {
+                LayoutPoint framePoint = roundedLayoutPoint(m_touchSequenceDocument->frame()->view()->windowToContents(point.pos()));
+                result = hitTestResultInFrame(m_touchSequenceDocument->frame(), framePoint, hitType);
             } else
                 continue;
 
@@ -3660,66 +3583,136 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
 
             // Touch events should not go to text nodes
             if (node->isTextNode())
-                node = EventPath::parent(node);
-
-            Document& doc = node->document();
-            // Record the originating touch document even if it does not have a touch listener.
-            if (freshTouchEvents) {
-                m_originatingTouchPointDocument = &doc;
-                freshTouchEvents = false;
+                node = NodeRenderingTraversal::parent(node);
+
+            if (!m_touchSequenceDocument) {
+                // Keep track of which document should receive all touch events
+                // in the active sequence. This must be a single document to
+                // ensure we don't leak Nodes between documents.
+                m_touchSequenceDocument = &(result.innerNode()->document());
+                ASSERT(m_touchSequenceDocument->frame()->view());
             }
-            if (!doc.hasTouchEventHandlers())
-                continue;
-            m_originatingTouchPointTargets.set(touchPointTargetKey, node);
-            touchTarget = node;
 
-            // FIXME(rbyers): Should really be doing a second hit test that ignores inline elements - crbug.com/319479.
+            // Ideally we'd ASSERT(!m_targetForTouchID.contains(point.id())
+            // since we shouldn't get a touchstart for a touch that's already
+            // down. However EventSender allows this to be violated and there's
+            // some tests that take advantage of it. There may also be edge
+            // cases in the browser where this happens.
+            // See http://crbug.com/345372.
+            m_targetForTouchID.set(point.id(), node);
+
             TouchAction effectiveTouchAction = computeEffectiveTouchAction(*node);
             if (effectiveTouchAction != TouchActionAuto)
                 m_frame->page()->chrome().client().setTouchAction(effectiveTouchAction);
+        }
+    }
 
-        } else if (pointState == PlatformTouchPoint::TouchReleased || pointState == PlatformTouchPoint::TouchCancelled) {
-            // The target should be the original target for this touch, so get it from the hashmap. As it's a release or cancel
-            // we also remove it from the map.
-            touchTarget = m_originatingTouchPointTargets.take(touchPointTargetKey);
-        } else
-            // No hittest is performed on move or stationary, since the target is not allowed to change anyway.
-            touchTarget = m_originatingTouchPointTargets.get(touchPointTargetKey);
+    m_touchPressed = !allTouchReleased;
 
-        if (!touchTarget.get())
-            continue;
-        Document& doc = touchTarget->toNode()->document();
-        if (!doc.hasTouchEventHandlers())
-            continue;
-        Frame* targetFrame = doc.frame();
-        if (!targetFrame)
-            continue;
+    // If there's no document receiving touch events, or no handlers on the
+    // document set to receive the events, then we can skip all the rest of
+    // this work.
+    if (!m_touchSequenceDocument || !m_touchSequenceDocument->frameHost() || !m_touchSequenceDocument->frameHost()->eventHandlerRegistry().hasEventHandlers(EventHandlerRegistry::TouchEvent) || !m_touchSequenceDocument->frame()) {
+        if (allTouchReleased) {
+            m_touchSequenceDocument.clear();
+            m_touchSequenceUserGestureToken.clear();
+        }
+        return false;
+    }
+
+    // Build up the lists to use for the 'touches', 'targetTouches' and
+    // 'changedTouches' attributes in the JS event. See
+    // http://www.w3.org/TR/touch-events/#touchevent-interface for how these
+    // lists fit together.
+
+    // Holds the complete set of touches on the screen.
+    RefPtrWillBeRawPtr<TouchList> touches = TouchList::create();
 
-        if (m_frame != targetFrame) {
-            // pagePoint should always be relative to the target elements containing frame.
-            pagePoint = documentPointForWindowPoint(targetFrame, point.pos());
+    // A different view on the 'touches' list above, filtered and grouped by
+    // event target. Used for the 'targetTouches' list in the JS event.
+    typedef WillBeHeapHashMap<EventTarget*, RefPtrWillBeMember<TouchList> > TargetTouchesHeapMap;
+    TargetTouchesHeapMap touchesByTarget;
+
+    // Array of touches per state, used to assemble the 'changedTouches' list.
+    typedef WillBeHeapHashSet<RefPtrWillBeMember<EventTarget> > EventTargetSet;
+    struct {
+        // The touches corresponding to the particular change state this struct
+        // instance represents.
+        RefPtrWillBeMember<TouchList> m_touches;
+        // Set of targets involved in m_touches.
+        EventTargetSet m_targets;
+    } changedTouches[PlatformTouchPoint::TouchStateEnd];
+
+    for (i = 0; i < points.size(); ++i) {
+        const PlatformTouchPoint& point = points[i];
+        PlatformTouchPoint::State pointState = point.state();
+        RefPtrWillBeRawPtr<EventTarget> touchTarget = nullptr;
+
+        if (pointState == PlatformTouchPoint::TouchReleased || pointState == PlatformTouchPoint::TouchCancelled) {
+            // The target should be the original target for this touch, so get
+            // it from the hashmap. As it's a release or cancel we also remove
+            // it from the map.
+            touchTarget = m_targetForTouchID.take(point.id());
+        } else {
+            // No hittest is performed on move or stationary, since the target
+            // is not allowed to change anyway.
+            touchTarget = m_targetForTouchID.get(point.id());
         }
 
-        float scaleFactor = targetFrame->pageZoomFactor();
+        LocalFrame* targetFrame = 0;
+        bool knownTarget = false;
+        if (touchTarget) {
+            Document& doc = touchTarget->toNode()->document();
+            // If the target node has moved to a new document while it was being touched,
+            // we can't send events to the new document because that could leak nodes
+            // from one document to another. See http://crbug.com/394339.
+            if (&doc == m_touchSequenceDocument.get()) {
+                targetFrame = doc.frame();
+                knownTarget = true;
+            }
+        }
+        if (!knownTarget) {
+            // If we don't have a target registered for the point it means we've
+            // missed our opportunity to do a hit test for it (due to some
+            // optimization that prevented blink from ever seeing the
+            // touchstart), or that the touch started outside the active touch
+            // sequence document. We should still include the touch in the
+            // Touches list reported to the application (eg. so it can
+            // differentiate between a one and two finger gesture), but we won't
+            // actually dispatch any events for it. Set the target to the
+            // Document so that there's some valid node here. Perhaps this
+            // should really be LocalDOMWindow, but in all other cases the target of
+            // a Touch is a Node so using the window could be a breaking change.
+            // Since we know there was no handler invoked, the specific target
+            // should be completely irrelevant to the application.
+            touchTarget = m_touchSequenceDocument;
+            targetFrame = m_touchSequenceDocument->frame();
+        }
+        ASSERT(targetFrame);
 
-        int adjustedPageX = lroundf(pagePoint.x() / scaleFactor);
-        int adjustedPageY = lroundf(pagePoint.y() / scaleFactor);
-        int adjustedRadiusX = lroundf(point.radiusX() / scaleFactor);
-        int adjustedRadiusY = lroundf(point.radiusY() / scaleFactor);
+        // pagePoint should always be relative to the target elements
+        // containing frame.
+        FloatPoint pagePoint = targetFrame->view()->windowToContents(point.pos());
 
-        RefPtr<Touch> touch = Touch::create(targetFrame, touchTarget.get(), point.id(),
-                                            point.screenPos().x(), point.screenPos().y(),
-                                            adjustedPageX, adjustedPageY,
-                                            adjustedRadiusX, adjustedRadiusY,
-                                            point.rotationAngle(), point.force());
+        float scaleFactor = 1.0f / targetFrame->pageZoomFactor();
 
-        // Ensure this target's touch list exists, even if it ends up empty, so it can always be passed to TouchEvent::Create below.
-        TargetTouchesMap::iterator targetTouchesIterator = touchesByTarget.find(touchTarget.get());
-        if (targetTouchesIterator == touchesByTarget.end())
-            targetTouchesIterator = touchesByTarget.set(touchTarget.get(), TouchList::create()).iterator;
+        FloatPoint adjustedPagePoint = pagePoint.scaledBy(scaleFactor);
+        FloatSize adjustedRadius = point.radius().scaledBy(scaleFactor);
 
-        // touches and targetTouches should only contain information about touches still on the screen, so if this point is
-        // released or cancelled it will only appear in the changedTouches list.
+        RefPtrWillBeRawPtr<Touch> touch = Touch::create(
+            targetFrame, touchTarget.get(), point.id(), point.screenPos(), adjustedPagePoint, adjustedRadius, point.rotationAngle(), point.force());
+
+        // Ensure this target's touch list exists, even if it ends up empty, so
+        // it can always be passed to TouchEvent::Create below.
+        TargetTouchesHeapMap::iterator targetTouchesIterator = touchesByTarget.find(touchTarget.get());
+        if (targetTouchesIterator == touchesByTarget.end()) {
+            touchesByTarget.set(touchTarget.get(), TouchList::create());
+            targetTouchesIterator = touchesByTarget.find(touchTarget.get());
+        }
+
+        // touches and targetTouches should only contain information about
+        // touches still on the screen, so if this point is released or
+        // cancelled it will only appear in the changedTouches list.
         if (pointState != PlatformTouchPoint::TouchReleased && pointState != PlatformTouchPoint::TouchCancelled) {
             touches->append(touch);
             targetTouchesIterator->value->append(touch);
@@ -3728,10 +3721,10 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
         // Now build up the correct list for changedTouches.
         // Note that  any touches that are in the TouchStationary state (e.g. if
         // the user had several points touched but did not move them all) should
-        // never be in the changedTouches list so we do not handle them explicitly here.
-        // See https://bugs.webkit.org/show_bug.cgi?id=37609 for further discussion
-        // about the TouchStationary state.
-        if (pointState != PlatformTouchPoint::TouchStationary) {
+        // never be in the changedTouches list so we do not handle them
+        // explicitly here. See https://bugs.webkit.org/show_bug.cgi?id=37609
+        // for further discussion about the TouchStationary state.
+        if (pointState != PlatformTouchPoint::TouchStationary && knownTarget) {
             ASSERT(pointState < PlatformTouchPoint::TouchStateEnd);
             if (!changedTouches[pointState].m_touches)
                 changedTouches[pointState].m_touches = TouchList::create();
@@ -3739,32 +3732,26 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
             changedTouches[pointState].m_targets.add(touchTarget);
         }
     }
-    m_touchPressed = touches->length() > 0;
-    if (allTouchReleased)
-        m_originatingTouchPointDocument.clear();
+    if (allTouchReleased) {
+        m_touchSequenceDocument.clear();
+        m_touchSequenceUserGestureToken.clear();
+    }
 
-    // Now iterate the changedTouches list and m_targets within it, sending events to the targets as required.
+    // Now iterate the changedTouches list and m_targets within it, sending
+    // events to the targets as required.
     bool swallowedEvent = false;
-    RefPtr<TouchList> emptyList = TouchList::create();
     for (unsigned state = 0; state != PlatformTouchPoint::TouchStateEnd; ++state) {
         if (!changedTouches[state].m_touches)
             continue;
 
-        // When sending a touch cancel event, use empty touches and targetTouches lists.
-        bool isTouchCancelEvent = (state == PlatformTouchPoint::TouchCancelled);
-        RefPtr<TouchList>& effectiveTouches(isTouchCancelEvent ? emptyList : touches);
         const AtomicString& stateName(eventNameForTouchPointState(static_cast<PlatformTouchPoint::State>(state)));
         const EventTargetSet& targetsForState = changedTouches[state].m_targets;
-
         for (EventTargetSet::const_iterator it = targetsForState.begin(); it != targetsForState.end(); ++it) {
             EventTarget* touchEventTarget = it->get();
-            RefPtr<TouchList> targetTouches(isTouchCancelEvent ? emptyList : touchesByTarget.get(touchEventTarget));
-            ASSERT(targetTouches);
-
-            RefPtr<TouchEvent> touchEvent =
-                TouchEvent::create(effectiveTouches.get(), targetTouches.get(), changedTouches[state].m_touches.get(),
-                    stateName, touchEventTarget->toNode()->document().domWindow(),
-                    0, 0, 0, 0, event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey());
+            RefPtrWillBeRawPtr<TouchEvent> touchEvent = TouchEvent::create(
+                touches.get(), touchesByTarget.get(touchEventTarget), changedTouches[state].m_touches.get(),
+                stateName, touchEventTarget->toNode()->document().domWindow(),
+                event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), event.cancelable());
             touchEventTarget->toNode()->dispatchTouchEvent(touchEvent.get());
             swallowedEvent = swallowedEvent || touchEvent->defaultPrevented() || touchEvent->defaultHandled();
         }
@@ -3773,125 +3760,6 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
     return swallowedEvent;
 }
 
-bool EventHandler::dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent& event)
-{
-    if (!m_frame || !m_frame->settings() || !m_frame->settings()->touchEventEmulationEnabled())
-        return false;
-
-    PlatformEvent::Type eventType = event.type();
-    if (eventType != PlatformEvent::MouseMoved && eventType != PlatformEvent::MousePressed && eventType != PlatformEvent::MouseReleased)
-        return false;
-
-    HitTestRequest request(HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
-    MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
-    if (mev.scrollbar() || subframeForHitTestResult(mev))
-        return false;
-
-    // The order is important. This check should follow the subframe test: http://webkit.org/b/111292.
-    if (eventType == PlatformEvent::MouseMoved && event.button() == NoButton)
-        return true;
-
-    SyntheticSingleTouchEvent touchEvent(event);
-    if (handleTouchEvent(touchEvent))
-        return true;
-
-    return handleMouseEventAsEmulatedGesture(event);
-}
-
-bool EventHandler::handleMouseEventAsEmulatedGesture(const PlatformMouseEvent& event)
-{
-    PlatformEvent::Type eventType = event.type();
-    if (event.button() != LeftButton || !m_frame->isMainFrame())
-        return false;
-
-    // Simulate pinch / scroll gesture.
-    const IntPoint& position = event.position();
-    bool swallowEvent = false;
-
-    FrameView* view = m_frame->view();
-    if (event.shiftKey()) {
-        // Shift pressed - consider it gesture.
-        swallowEvent = true;
-        Page* page = m_frame->page();
-        float pageScaleFactor = page->pageScaleFactor();
-        switch (eventType) {
-        case PlatformEvent::MousePressed:
-            m_lastSyntheticPinchAnchorCss = adoptPtr(new IntPoint(view->scrollPosition() + position));
-            m_lastSyntheticPinchAnchorDip = adoptPtr(new IntPoint(position));
-            m_lastSyntheticPinchAnchorDip->scale(pageScaleFactor, pageScaleFactor);
-            m_syntheticPageScaleFactor = pageScaleFactor;
-            break;
-        case PlatformEvent::MouseMoved:
-            {
-                if (!m_lastSyntheticPinchAnchorCss)
-                    break;
-
-                float dy = m_lastSyntheticPinchAnchorDip->y() - position.y() * pageScaleFactor;
-                float magnifyDelta = exp(dy * 0.002f);
-                float newPageScaleFactor = m_syntheticPageScaleFactor * magnifyDelta;
-
-                IntPoint anchorCss(*m_lastSyntheticPinchAnchorDip.get());
-                anchorCss.scale(1.f / newPageScaleFactor, 1.f / newPageScaleFactor);
-                page->inspectorController().requestPageScaleFactor(newPageScaleFactor, *m_lastSyntheticPinchAnchorCss.get() - toIntSize(anchorCss));
-                break;
-            }
-        case PlatformEvent::MouseReleased:
-            m_lastSyntheticPinchAnchorCss.clear();
-            m_lastSyntheticPinchAnchorDip.clear();
-        default:
-            break;
-        }
-    } else {
-        switch (eventType) {
-        case PlatformEvent::MouseMoved:
-            {
-                // Always consume move events.
-                swallowEvent = true;
-                int dx = m_lastSyntheticPanLocation ? position.x() - m_lastSyntheticPanLocation->x() : 0;
-                int dy = m_lastSyntheticPanLocation ? position.y() - m_lastSyntheticPanLocation->y() : 0;
-                if (dx || dy)
-                    view->scrollBy(IntSize(-dx, -dy));
-                // Mouse dragged - consider it gesture.
-                m_lastSyntheticPanLocation = adoptPtr(new IntPoint(position));
-                break;
-            }
-        case PlatformEvent::MouseReleased:
-            // There was a drag -> gesture.
-            swallowEvent = !!m_lastSyntheticPanLocation;
-            m_lastSyntheticPanLocation.clear();
-        default:
-            break;
-        }
-    }
-
-    return swallowEvent;
-}
-
-bool EventHandler::handleWheelEventAsEmulatedGesture(const PlatformWheelEvent& event)
-{
-    if (!m_frame || !m_frame->settings() || !m_frame->settings()->touchEventEmulationEnabled())
-        return false;
-
-    // Only convert vertical wheel w/ shift into pinch for touch-enabled device convenience.
-    if (!event.shiftKey() || !event.deltaY())
-        return false;
-
-    Page* page = m_frame->page();
-    FrameView* view = m_frame->view();
-    float pageScaleFactor = page->pageScaleFactor();
-    IntPoint anchorBeforeCss(view->scrollPosition() + event.position());
-    IntPoint anchorBeforeDip(event.position());
-    anchorBeforeDip.scale(pageScaleFactor, pageScaleFactor);
-
-    float magnifyDelta = exp(event.deltaY() * 0.002f);
-    float newPageScaleFactor = pageScaleFactor * magnifyDelta;
-
-    IntPoint anchorAfterCss(anchorBeforeDip);
-    anchorAfterCss.scale(1.f / newPageScaleFactor, 1.f / newPageScaleFactor);
-    page->inspectorController().requestPageScaleFactor(newPageScaleFactor, anchorBeforeCss - toIntSize(anchorAfterCss));
-    return true;
-}
-
 TouchAction EventHandler::intersectTouchAction(TouchAction action1, TouchAction action2)
 {
     if (action1 == TouchActionNone || action2 == TouchActionNone)
@@ -3907,21 +3775,13 @@ TouchAction EventHandler::intersectTouchAction(TouchAction action1, TouchAction
 
 TouchAction EventHandler::computeEffectiveTouchAction(const Node& node)
 {
-    // Optimization to minimize risk of this new feature (behavior should be identical
-    // since there's no way to get non-default touch-action values).
-    if (!RuntimeEnabledFeatures::cssTouchActionEnabled())
-        return TouchActionAuto;
-
-    // Start by permitting all actions, then walk the block level elements from
-    // the target node up to the nearest scrollable ancestor and exclude any
-    // prohibited actions. For now this is trivial, but when we add more types
-    // of actions it'll get a little more complex.
+    // Start by permitting all actions, then walk the elements supporting
+    // touch-action from the target node up to the nearest scrollable ancestor
+    // and exclude any prohibited actions.
     TouchAction effectiveTouchAction = TouchActionAuto;
     for (const Node* curNode = &node; curNode; curNode = NodeRenderingTraversal::parent(curNode)) {
-        // The spec says only block and SVG elements get touch-action.
-        // FIXME(rbyers): Add correct support for SVG, crbug.com/247396.
         if (RenderObject* renderer = curNode->renderer()) {
-            if (renderer->isRenderBlockFlow()) {
+            if (renderer->supportsTouchAction()) {
                 TouchAction action = renderer->style()->touchAction();
                 effectiveTouchAction = intersectTouchAction(action, effectiveTouchAction);
                 if (effectiveTouchAction == TouchActionNone)
@@ -3943,7 +3803,7 @@ void EventHandler::setLastKnownMousePosition(const PlatformMouseEvent& event)
     m_lastKnownMouseGlobalPosition = event.globalPosition();
 }
 
-bool EventHandler::passMousePressEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
+bool EventHandler::passMousePressEventToSubframe(MouseEventWithHitTestResults& mev, LocalFrame* subframe)
 {
     // If we're clicking into a frame that is selected, the frame will appear
     // greyed out even though we're clicking on the selection.  This looks
@@ -3961,7 +3821,7 @@ bool EventHandler::passMousePressEventToSubframe(MouseEventWithHitTestResults& m
     return true;
 }
 
-bool EventHandler::passMouseMoveEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe, HitTestResult* hoveredNode)
+bool EventHandler::passMouseMoveEventToSubframe(MouseEventWithHitTestResults& mev, LocalFrame* subframe, HitTestResult* hoveredNode)
 {
     if (m_mouseDownMayStartDrag && !m_mouseDownWasInSubframe)
         return false;
@@ -3969,7 +3829,7 @@ bool EventHandler::passMouseMoveEventToSubframe(MouseEventWithHitTestResults& me
     return true;
 }
 
-bool EventHandler::passMouseReleaseEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
+bool EventHandler::passMouseReleaseEventToSubframe(MouseEventWithHitTestResults& mev, LocalFrame* subframe)
 {
     subframe->eventHandler().handleMouseReleaseEvent(mev.event());
     return true;
@@ -3998,9 +3858,9 @@ bool EventHandler::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestR
     return false;
 }
 
-PassRefPtr<Clipboard> EventHandler::createDraggingClipboard() const
+PassRefPtrWillBeRawPtr<DataTransfer> EventHandler::createDraggingDataTransfer() const
 {
-    return Clipboard::create(Clipboard::DragAndDrop, ClipboardWritable, DataObject::create());
+    return DataTransfer::create(DataTransfer::DragAndDrop, DataTransferWritable, DataObject::create());
 }
 
 void EventHandler::focusDocumentView()
@@ -4008,7 +3868,7 @@ void EventHandler::focusDocumentView()
     Page* page = m_frame->page();
     if (!page)
         return;
-    page->focusController().setFocusedFrame(m_frame);
+    page->focusController().focusDocumentView(m_frame);
 }
 
 unsigned EventHandler::accessKeyModifiers()
@@ -4020,4 +3880,4 @@ unsigned EventHandler::accessKeyModifiers()
 #endif
 }
 
-} // namespace WebCore
+} // namespace blink