shadowAncestorNode() should be renamed to deprecatedShadowAncestorNode()
[WebKit-https.git] / Source / WebCore / page / EventHandler.cpp
index d785834..04f2ac2 100644 (file)
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
  * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2012 Digia Plc. and/or its subsidiary(-ies)
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "EventHandler.h"
 
 #include "AXObjectCache.h"
+#include "AncestorChainWalker.h"
+#include "AutoscrollController.h"
 #include "CachedImage.h"
 #include "Chrome.h"
 #include "ChromeClient.h"
-#include "ComposedShadowTreeWalker.h"
 #include "Cursor.h"
 #include "CursorList.h"
 #include "Document.h"
@@ -39,6 +41,7 @@
 #include "DragController.h"
 #include "DragState.h"
 #include "Editor.h"
+#include "EditorClient.h"
 #include "EventNames.h"
 #include "FloatPoint.h"
 #include "FloatRect.h"
@@ -79,7 +82,6 @@
 #include "StyleCachedImage.h"
 #include "TextEvent.h"
 #include "TextIterator.h"
-#include "UserGestureIndicator.h"
 #include "UserTypingGestureIndicator.h"
 #include "WheelEvent.h"
 #include "WindowsKeyboardCodes.h"
 #include "TouchList.h"
 #endif
 
+#if ENABLE(CSS_IMAGE_SET)
+#include "StyleCachedImageSet.h"
+#endif
+
 namespace WebCore {
 
 using namespace HTMLNames;
@@ -131,15 +137,20 @@ const int CompositionEventKeyCode = 229;
 using namespace SVGNames;
 #endif
 
-// When the autoscroll or the panScroll is triggered when do the scroll every 0.05s to make it smooth
-const double autoscrollInterval = 0.05;
-
 // The amount of time to wait before sending a fake mouse event, triggered
 // during a scroll. The short interval is used if the content responds to the mouse events quickly enough,
 // otherwise the long interval is used.
 const double fakeMouseMoveShortInterval = 0.1;
 const double fakeMouseMoveLongInterval = 0.250;
 
+const int maximumCursorSize = 128;
+#if ENABLE(MOUSE_CURSOR_SCALE)
+// It's pretty unlikely that a scale of less than one would ever be used. But all we really
+// need to ensure here is that the scale isn't so small that integer overflow can occur when
+// dividing cursor sizes (limited above) by the scale.
+const double minimumCursorScale = 0.001;
+#endif
+
 enum NoCursorChangeType { NoCursorChange };
 
 class OptionalCursor {
@@ -148,7 +159,7 @@ public:
     OptionalCursor(const Cursor& cursor) : m_isCursorChange(true), m_cursor(cursor) { }
 
     bool isCursorChange() const { return m_isCursorChange; }
-    const Cursor& cursor() const { return m_cursor; }
+    const Cursor& cursor() const { ASSERT(m_isCursorChange); return m_cursor; }
 
 private:
     bool m_isCursorChange;
@@ -264,6 +275,20 @@ static inline bool scrollNode(float delta, ScrollGranularity granularity, Scroll
     return enclosingBox->scroll(delta < 0 ? negativeDirection : positiveDirection, granularity, absDelta, stopNode);
 }
 
+#if ENABLE(GESTURE_EVENTS)
+static inline bool shouldGesturesTriggerActive()
+{
+    // If the platform we're on supports GestureTapDown and GestureTapCancel then we'll
+    // rely on them to set the active state. Unfortunately there's no generic way to
+    // know in advance what event types are supported.
+#if PLATFORM(CHROMIUM) && !OS(ANDROID)
+    return true;
+#else
+    return false;
+#endif
+}
+#endif
+
 #if !PLATFORM(MAC)
 
 inline bool EventHandler::eventLoopHandleMouseUp(const MouseEventWithHitTestResults&)
@@ -291,13 +316,8 @@ EventHandler::EventHandler(Frame* frame)
 #endif
     , m_mouseDownWasSingleClickInSelection(false)
     , m_selectionInitiationState(HaveNotStartedSelection)
-    , m_panScrollInProgress(false)
-    , m_panScrollButtonPressed(false)
-    , m_springLoadedPanScrollInProgress(false)
     , m_hoverTimer(this, &EventHandler::hoverTimerFired)
-    , m_autoscrollTimer(this, &EventHandler::autoscrollTimerFired)
-    , m_autoscrollRenderer(0)
-    , m_autoscrollInProgress(false)
+    , m_autoscrollController(adoptPtr(new AutoscrollController))
     , m_mouseDownMayStartAutoscroll(false)
     , m_mouseDownWasInSubframe(false)
     , m_fakeMouseMoveEventTimer(this, &EventHandler::fakeMouseMoveEventTimerFired)
@@ -307,8 +327,8 @@ EventHandler::EventHandler(Frame* frame)
     , m_resizeLayer(0)
     , m_eventHandlerWillResetCapturingMouseEventsNode(0)
     , m_clickCount(0)
+    , m_mousePositionIsUnknown(true)
     , m_mouseDownTimestamp(0)
-    , m_useLatchedWheelEventNode(false)
     , m_widgetIsLatched(false)
 #if PLATFORM(MAC)
     , m_mouseDownView(nil)
@@ -316,10 +336,17 @@ EventHandler::EventHandler(Frame* frame)
     , m_activationEventNumber(-1)
 #endif
 #if ENABLE(TOUCH_EVENTS)
+    , m_originatingTouchPointTargetKey(0)
     , m_touchPressed(false)
 #endif
+#if ENABLE(GESTURE_EVENTS)
+    , m_scrollGestureHandlingNode(0)
+    , m_lastHitTestResultOverWidget(false)
+#endif
     , m_maxMouseMovedDuration(0)
     , m_baseEventType(PlatformEvent::NoType)
+    , m_didStartDrag(false)
+    , m_didLongPressInvokeContextMenu(false)
 {
 }
 
@@ -356,8 +383,10 @@ void EventHandler::clear()
     m_dragTarget = 0;
     m_shouldOnlyFireDragOverEvent = false;
 #endif
-    m_currentMousePosition = IntPoint();
-    m_currentMouseGlobalPosition = IntPoint();
+    m_mousePositionIsUnknown = true;
+    m_lastKnownMousePosition = IntPoint();
+    m_lastKnownMouseGlobalPosition = IntPoint();
+    m_lastMouseDownUserGestureToken.clear();
     m_mousePressNode = 0;
     m_mousePressed = false;
     m_capturesDragging = false;
@@ -366,11 +395,18 @@ void EventHandler::clear()
     m_previousWheelScrolledNode = 0;
 #if ENABLE(TOUCH_EVENTS)
     m_originatingTouchPointTargets.clear();
+    m_originatingTouchPointDocument.clear();
+    m_originatingTouchPointTargetKey = 0;
 #endif
-    m_maxMouseMovedDuration = 0;
 #if ENABLE(GESTURE_EVENTS)
-    m_baseEventType = PlatformEvent::NoType;
+    m_scrollGestureHandlingNode = 0;
+    m_lastHitTestResultOverWidget = false;
+    m_scrollbarHandlingScrollGesture = 0;
 #endif
+    m_maxMouseMovedDuration = 0;
+    m_baseEventType = PlatformEvent::NoType;
+    m_didStartDrag = false;
+    m_didLongPressInvokeContextMenu = false;
 }
 
 void EventHandler::nodeWillBeRemoved(Node* nodeToBeRemoved)
@@ -402,43 +438,58 @@ bool EventHandler::updateSelectionForMouseDownDispatchingSelectStart(Node* targe
     if (!dispatchSelectStart(targetNode))
         return false;
 
-    if (newSelection.isRange())
+    VisibleSelection selection(newSelection);
+#if ENABLE(USERSELECT_ALL)
+    if (Node* rootUserSelectAll = Position::rootUserSelectAllForNode(targetNode)) {
+        selection.setBase(positionBeforeNode(rootUserSelectAll).upstream(CanCrossEditingBoundary));
+        selection.setExtent(positionAfterNode(rootUserSelectAll).downstream(CanCrossEditingBoundary));
+    }
+#endif
+    if (selection.isRange())
         m_selectionInitiationState = ExtendedSelection;
     else {
         granularity = CharacterGranularity;
         m_selectionInitiationState = PlacedCaret;
     }
 
-    m_frame->selection()->setNonDirectionalSelectionIfNeeded(newSelection, granularity);
+    m_frame->selection()->setNonDirectionalSelectionIfNeeded(selection, granularity);
 
     return true;
 }
 
-void EventHandler::selectClosestWordFromMouseEvent(const MouseEventWithHitTestResults& result)
+void EventHandler::selectClosestWordFromHitTestResult(const HitTestResult& result, AppendTrailingWhitespace appendTrailingWhitespace)
 {
-    Node* innerNode = targetNode(result);
+    Node* innerNode = result.targetNode();
     VisibleSelection newSelection;
 
-    if (innerNode && innerNode->renderer() && m_mouseDownMayStartSelect) {
+    if (innerNode && innerNode->renderer()) {
         VisiblePosition pos(innerNode->renderer()->positionForPoint(result.localPoint()));
         if (pos.isNotNull()) {
             newSelection = VisibleSelection(pos);
             newSelection.expandUsingGranularity(WordGranularity);
         }
 
-        if (newSelection.isRange() && result.event().clickCount() == 2 && m_frame->editor()->isSelectTrailingWhitespaceEnabled()) 
+        if (appendTrailingWhitespace == ShouldAppendTrailingWhitespace && newSelection.isRange())
             newSelection.appendTrailingWhitespace();
 
         updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, WordGranularity);
     }
 }
 
+void EventHandler::selectClosestWordFromMouseEvent(const MouseEventWithHitTestResults& result)
+{
+    if (m_mouseDownMayStartSelect) {
+        selectClosestWordFromHitTestResult(result.hitTestResult(),
+            (result.event().clickCount() == 2 && m_frame->editor()->isSelectTrailingWhitespaceEnabled()) ? ShouldAppendTrailingWhitespace : DontAppendTrailingWhitespace);
+    }
+}
+
 void EventHandler::selectClosestWordOrLinkFromMouseEvent(const MouseEventWithHitTestResults& result)
 {
     if (!result.hitTestResult().isLiveLink())
         return selectClosestWordFromMouseEvent(result);
 
-    Node* innerNode = targetNode(result);
+    Node* innerNode = result.targetNode();
 
     if (innerNode && innerNode->renderer() && m_mouseDownMayStartSelect) {
         VisibleSelection newSelection;
@@ -474,7 +525,7 @@ bool EventHandler::handleMousePressEventTripleClick(const MouseEventWithHitTestR
     if (event.event().button() != LeftButton)
         return false;
     
-    Node* innerNode = targetNode(event);
+    Node* innerNode = event.targetNode();
     if (!(innerNode && innerNode->renderer() && m_mouseDownMayStartSelect))
         return false;
 
@@ -496,7 +547,8 @@ static int textDistance(const Position& start, const Position& end)
 
 bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
 {
-    Node* innerNode = targetNode(event);
+    m_frame->document()->updateLayoutIgnorePendingStylesheets();
+    Node* innerNode = event.targetNode();
     if (!(innerNode && innerNode->renderer() && m_mouseDownMayStartSelect))
         return false;
 
@@ -544,7 +596,13 @@ bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestR
     } else
         newSelection = VisibleSelection(visiblePos);
     
-    return updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, granularity);
+    bool handled = updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, granularity);
+
+    if (event.event().button() == MiddleButton) {
+        // Ignore handled, since we want to paste to where the caret was placed anyway.
+        handled = handlePasteGlobalSelection(event.event()) || handled;
+    }
+    return handled;
 }
 
 static inline bool canMouseDownStartSelect(Node* node)
@@ -577,8 +635,8 @@ bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& eve
     bool singleClick = event.event().clickCount() <= 1;
 
     // If we got the event back, that must mean it wasn't prevented,
-    // so it's allowed to start a drag or selection.
-    m_mouseDownMayStartSelect = canMouseDownStartSelect(targetNode(event));
+    // so it's allowed to start a drag or selection if it wasn't in a scrollbar.
+    m_mouseDownMayStartSelect = canMouseDownStartSelect(event.targetNode()) && !event.scrollbar();
     
 #if ENABLE(DRAG_SUPPORT)
     // Careful that the drag starting logic stays in sync with eventMayStartDrag()
@@ -608,7 +666,7 @@ bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& eve
     if (singleClick)
         focusDocumentView();
 
-    Node* innerNode = targetNode(event);
+    Node* innerNode = event.targetNode();
 
     m_mousePressNode = innerNode;
 #if ENABLE(DRAG_SUPPORT)
@@ -632,40 +690,16 @@ bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& eve
     return swallowEvent;
 }
 
-// There are two kinds of renderer that can autoscroll.
-static bool canAutoscroll(RenderObject* renderer)
-{
-    if (!renderer->isBox())
-        return false;
-
-    // Check for a box that can be scrolled in its own right.
-    if (toRenderBox(renderer)->canBeScrolledAndHasScrollableArea())
-        return true;
-
-    // Check for a box that represents the top level of a web page.
-    // This can be scrolled by calling Chrome::scrollRectIntoView.
-    // This only has an effect on the Mac platform in applications
-    // that put web views into scrolling containers, such as Mac OS X Mail.
-    // The code for this is in RenderLayer::scrollRectToVisible.
-    if (renderer->node() != renderer->document())
-        return false;
-    Frame* frame = renderer->frame();
-    if (!frame)
-        return false;
-    Page* page = frame->page();
-    return page && page->mainFrame() == frame;
-}
-
 #if ENABLE(DRAG_SUPPORT)
 bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& event)
 {
-    if (handleDrag(event))
+    if (handleDrag(event, ShouldCheckDragHysteresis))
         return true;
 
     if (!m_mousePressed)
         return false;
 
-    Node* targetNode = EventHandler::targetNode(event);
+    Node* targetNode = event.targetNode();
     if (event.event().button() != LeftButton || !targetNode)
         return false;
 
@@ -682,20 +716,8 @@ bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& e
 
     m_mouseDownMayStartDrag = false;
 
-    if (m_mouseDownMayStartAutoscroll && !m_panScrollInProgress) {            
-        // Find a renderer that can autoscroll.
-        while (renderer && !canAutoscroll(renderer)) {
-            if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document()->ownerElement())
-                renderer = renderer->document()->ownerElement()->renderer();
-            else
-                renderer = renderer->parent();
-        }
-        
-        if (renderer) {
-            m_autoscrollInProgress = true;
-            handleAutoscroll(renderer);
-        }
-        
+    if (m_mouseDownMayStartAutoscroll && !panScrollInProgress()) {
+        m_autoscrollController->startAutoscrollForSelection(renderer);
         m_mouseDownMayStartAutoscroll = false;
     }
 
@@ -735,7 +757,7 @@ bool EventHandler::eventMayStartDrag(const PlatformMouseEvent& event) const
     HitTestResult result(view->windowToContents(event.position()));
     m_frame->contentRenderer()->hitTest(request, result);
     DragState state;
-    return result.innerNode() && page->dragController()->draggableNode(m_frame, result.innerNode(), roundedIntPoint(result.point()), state);
+    return result.innerNode() && page->dragController()->draggableNode(m_frame, result.innerNode(), result.roundedPointInInnerNodeFrame(), state);
 }
 
 void EventHandler::updateSelectionForMouseDrag()
@@ -750,7 +772,7 @@ void EventHandler::updateSelectionForMouseDrag()
     HitTestRequest request(HitTestRequest::ReadOnly |
                            HitTestRequest::Active |
                            HitTestRequest::Move);
-    HitTestResult result(view->windowToContents(m_currentMousePosition));
+    HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
     renderer->hitTest(request, result);
     updateSelectionForMouseDrag(result);
 }
@@ -780,7 +802,7 @@ void EventHandler::updateSelectionForMouseDrag(const HitTestResult& hitTestResul
     if (!m_mouseDownMayStartSelect)
         return;
 
-    Node* target = targetNode(hitTestResult);
+    Node* target = hitTestResult.targetNode();
     if (!target)
         return;
 
@@ -813,7 +835,28 @@ void EventHandler::updateSelectionForMouseDrag(const HitTestResult& hitTestResul
         newSelection = VisibleSelection(targetPosition);
     }
 
+#if ENABLE(USERSELECT_ALL)
+    Node* rootUserSelectAllForMousePressNode = Position::rootUserSelectAllForNode(m_mousePressNode.get());
+    if (rootUserSelectAllForMousePressNode && rootUserSelectAllForMousePressNode == Position::rootUserSelectAllForNode(target)) {
+        newSelection.setBase(positionBeforeNode(rootUserSelectAllForMousePressNode).upstream(CanCrossEditingBoundary));
+        newSelection.setExtent(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
+    } else {
+        // Reset base for user select all when base is inside user-select-all area and extent < base.
+        if (rootUserSelectAllForMousePressNode && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint()), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos)) < 0)
+            newSelection.setBase(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
+        
+        Node* rootUserSelectAllForTarget = Position::rootUserSelectAllForNode(target);
+        if (rootUserSelectAllForTarget && m_mousePressNode->renderer() && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint()), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos)) < 0)
+            newSelection.setExtent(positionBeforeNode(rootUserSelectAllForTarget).upstream(CanCrossEditingBoundary));
+        else if (rootUserSelectAllForTarget && m_mousePressNode->renderer())
+            newSelection.setExtent(positionAfterNode(rootUserSelectAllForTarget).downstream(CanCrossEditingBoundary));
+        else
+            newSelection.setExtent(targetPosition);
+    }
+#else
     newSelection.setExtent(targetPosition);
+#endif
+
     if (m_frame->selection()->granularity() != CharacterGranularity)
         newSelection.expandUsingGranularity(m_frame->selection()->granularity());
 
@@ -842,7 +885,7 @@ bool EventHandler::handleMouseUp(const MouseEventWithHitTestResults& event)
 
 bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& event)
 {
-    if (m_autoscrollInProgress)
+    if (autoscrollInProgress())
         stopAutoscrollTimer();
 
     if (handleMouseUp(event))
@@ -850,7 +893,6 @@ bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& e
 
     // Used to prevent mouseMoveEvent from initiating a drag before
     // the mouse is pressed again.
-    m_frame->selection()->setCaretBlinkingSuspended(false);
     m_mousePressed = false;
     m_capturesDragging = false;
 #if ENABLE(DRAG_SUPPORT)
@@ -873,7 +915,7 @@ bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& e
             && m_frame->selection()->isRange()
             && event.event().button() != RightButton) {
         VisibleSelection newSelection;
-        Node* node = targetNode(event);
+        Node* node = event.targetNode();
         bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
         if (node && (caretBrowsing || node->rendererIsEditable()) && node->renderer()) {
             VisiblePosition pos = node->renderer()->positionForPoint(event.localPoint());
@@ -889,135 +931,54 @@ bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& e
 
     m_frame->selection()->selectFrameElementInParentIfFullySelected();
 
+    if (event.event().button() == MiddleButton) {
+        // Ignore handled, since we want to paste to where the caret was placed anyway.
+        handled = handlePasteGlobalSelection(event.event()) || handled;
+    }
+
     return handled;
 }
 
-void EventHandler::handleAutoscroll(RenderObject* renderer)
-{
-    // We don't want to trigger the autoscroll or the panScroll if it's already active
-    if (m_autoscrollTimer.isActive())
-        return;     
-
-    setAutoscrollRenderer(renderer);
-
 #if ENABLE(PAN_SCROLLING)
-    if (m_panScrollInProgress) {
-        m_panScrollStartPos = currentMousePosition();
-        if (FrameView* view = m_frame->view())
-            view->addPanScrollIcon(m_panScrollStartPos);
-        // If we're not in the top frame we notify it that we doing a panScroll.
-        if (Page* page = m_frame->page()) {
-            Frame* mainFrame = page->mainFrame();
-            if (m_frame != mainFrame)
-                mainFrame->eventHandler()->m_panScrollInProgress = true;
-        }
-    }
-#endif
-
-    startAutoscrollTimer();
-}
 
-void EventHandler::autoscrollTimerFired(Timer<EventHandler>*)
+void EventHandler::didPanScrollStart()
 {
-    RenderObject* r = autoscrollRenderer();
-    if (!r || !r->isBox()) {
-        stopAutoscrollTimer();
-        return;
-    }
-
-    if (m_autoscrollInProgress) {
-        if (!m_mousePressed) {
-            stopAutoscrollTimer();
-            return;
-        }
-        toRenderBox(r)->autoscroll();
-    } else {
-        // we verify that the main frame hasn't received the order to stop the panScroll
-        if (Page* page = m_frame->page()) {
-            if (!page->mainFrame()->eventHandler()->m_panScrollInProgress) {
-                stopAutoscrollTimer();
-                return;
-            }
-        }
-#if ENABLE(PAN_SCROLLING)
-        updatePanScrollState();
-        toRenderBox(r)->panScroll(m_panScrollStartPos);
-#endif
-    }
+    m_autoscrollController->didPanScrollStart();
 }
 
-#if ENABLE(PAN_SCROLLING)
-
-void EventHandler::startPanScrolling(RenderObject* renderer)
+void EventHandler::didPanScrollStop()
 {
-    m_panScrollInProgress = true;
-    m_panScrollButtonPressed = true;
-    handleAutoscroll(renderer);
-    invalidateClick();
+    m_autoscrollController->didPanScrollStop();
 }
 
-void EventHandler::updatePanScrollState()
+void EventHandler::startPanScrolling(RenderObject* renderer)
 {
-    FrameView* view = m_frame->view();
-    if (!view)
+    if (!renderer->isBox())
         return;
-
-    // At the original click location we draw a 4 arrowed icon. Over this icon there won't be any scroll
-    // So we don't want to change the cursor over this area
-    bool east = m_panScrollStartPos.x() < (m_currentMousePosition.x() - ScrollView::noPanScrollRadius);
-    bool west = m_panScrollStartPos.x() > (m_currentMousePosition.x() + ScrollView::noPanScrollRadius);
-    bool north = m_panScrollStartPos.y() > (m_currentMousePosition.y() + ScrollView::noPanScrollRadius);
-    bool south = m_panScrollStartPos.y() < (m_currentMousePosition.y() - ScrollView::noPanScrollRadius);
-         
-    if ((east || west || north || south) && m_panScrollButtonPressed)
-        m_springLoadedPanScrollInProgress = true;
-
-    if (north) {
-        if (east)
-            view->setCursor(northEastPanningCursor());
-        else if (west)
-            view->setCursor(northWestPanningCursor());
-        else
-            view->setCursor(northPanningCursor());
-    } else if (south) {
-        if (east)
-            view->setCursor(southEastPanningCursor());
-        else if (west)
-            view->setCursor(southWestPanningCursor());
-        else
-            view->setCursor(southPanningCursor());
-    } else if (east)
-        view->setCursor(eastPanningCursor());
-    else if (west)
-        view->setCursor(westPanningCursor());
-    else
-        view->setCursor(middlePanningCursor());
+    m_autoscrollController->startPanScrolling(toRenderBox(renderer), lastKnownMousePosition());
+    invalidateClick();
 }
 
 #endif // ENABLE(PAN_SCROLLING)
 
 RenderObject* EventHandler::autoscrollRenderer() const
 {
-    return m_autoscrollRenderer;
+    return m_autoscrollController->autoscrollRenderer();
 }
 
 void EventHandler::updateAutoscrollRenderer()
 {
-    if (!m_autoscrollRenderer)
-        return;
-
-    HitTestResult hitTest = hitTestResultAtPoint(m_panScrollStartPos, true);
-
-    if (Node* nodeAtPoint = hitTest.innerNode())
-        m_autoscrollRenderer = nodeAtPoint->renderer();
+    m_autoscrollController->updateAutoscrollRenderer();
+}
 
-    while (m_autoscrollRenderer && !canAutoscroll(m_autoscrollRenderer))
-        m_autoscrollRenderer = m_autoscrollRenderer->parent();
+bool EventHandler::autoscrollInProgress() const
+{
+    return m_autoscrollController->autoscrollInProgress();
 }
 
-void EventHandler::setAutoscrollRenderer(RenderObject* renderer)
+bool EventHandler::panScrollInProgress() const
 {
-    m_autoscrollRenderer = renderer;
+    return m_autoscrollController->panScrollInProgress();
 }
 
 #if ENABLE(DRAG_SUPPORT)
@@ -1037,17 +998,33 @@ DragSourceAction EventHandler::updateDragSourceActionsAllowed() const
     return page->dragController()->delegateDragSourceAction(view->contentsToRootView(m_mouseDownPos));
 }
 #endif // ENABLE(DRAG_SUPPORT)
-    
+
 HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, bool allowShadowContent, bool ignoreClipping, HitTestScrollbars testScrollbars, HitTestRequest::HitTestRequestType hitType, const LayoutSize& padding)
 {
-    enum ShadowContentFilterPolicy shadowContentFilterPolicy = allowShadowContent ? AllowShadowContent : DoNotAllowShadowContent;
-    HitTestResult result(point, padding.height(), padding.width(), padding.height(), padding.width(), shadowContentFilterPolicy);
+    // 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) {
+            FrameView* frameView = m_frame->view();
+            FrameView* mainView = mainFrame->view();
+            if (frameView && mainView) {
+                IntPoint mainFramePoint = mainView->rootViewToContents(frameView->contentsToRootView(roundedIntPoint(point)));
+                return mainFrame->eventHandler()->hitTestResultAtPoint(mainFramePoint, allowShadowContent, ignoreClipping, testScrollbars, hitType, padding);
+            }
+        }
+    }
+
+    HitTestResult result(point, padding.height(), padding.width(), padding.height(), padding.width());
 
     if (!m_frame->contentRenderer())
         return result;
     if (ignoreClipping)
         hitType |= HitTestRequest::IgnoreClipping;
-    m_frame->contentRenderer()->hitTest(HitTestRequest(hitType), result);
+    if (allowShadowContent)
+        hitType |= HitTestRequest::AllowShadowContent;
+    HitTestRequest request(hitType);
+    m_frame->contentRenderer()->hitTest(request, result);
 
     while (true) {
         Node* n = result.innerNode();
@@ -1063,8 +1040,9 @@ HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, bool
         FrameView* view = static_cast<FrameView*>(widget);
         LayoutPoint widgetPoint(result.localPoint().x() + view->scrollX() - renderWidget->borderLeft() - renderWidget->paddingLeft(), 
             result.localPoint().y() + view->scrollY() - renderWidget->borderTop() - renderWidget->paddingTop());
-        HitTestResult widgetHitTestResult(widgetPoint, padding.height(), padding.width(), padding.height(), padding.width(), shadowContentFilterPolicy);
-        frame->contentRenderer()->hitTest(HitTestRequest(hitType), widgetHitTestResult);
+        HitTestResult widgetHitTestResult(widgetPoint, padding.height(), padding.width(), padding.height(), padding.width());
+        widgetHitTestResult.setPointInMainFrame(result.pointInMainFrame());
+        frame->contentRenderer()->hitTest(request, widgetHitTestResult);
         result = widgetHitTestResult;
 
         if (testScrollbars == ShouldHitTestScrollbars) {
@@ -1073,21 +1051,6 @@ HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, bool
                 result.setScrollbar(eventScrollbar);
         }
     }
-    
-    // If our HitTestResult is not visible, then we started hit testing too far down the frame chain. 
-    // Another hit test at the main frame level should get us the correct visible result.
-    Frame* resultFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : 0;
-    if (Page* page = m_frame->page()) {
-        Frame* mainFrame = page->mainFrame();
-        if (m_frame != mainFrame && resultFrame && resultFrame != mainFrame) {
-            FrameView* resultView = resultFrame->view();
-            FrameView* mainView = mainFrame->view();
-            if (resultView && mainView) {
-                IntPoint mainFramePoint = mainView->rootViewToContents(resultView->contentsToRootView(roundedIntPoint(result.point())));
-                result = mainFrame->eventHandler()->hitTestResultAtPoint(mainFramePoint, allowShadowContent, ignoreClipping, testScrollbars, hitType, padding);
-            }
-        }
-    }
 
     if (!allowShadowContent)
         result.setToNonShadowAncestor();
@@ -1095,50 +1058,9 @@ HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, bool
     return result;
 }
 
-
-void EventHandler::startAutoscrollTimer()
-{
-    m_autoscrollTimer.startRepeating(autoscrollInterval);
-}
-
 void EventHandler::stopAutoscrollTimer(bool rendererIsBeingDestroyed)
 {
-    if (m_autoscrollInProgress) {
-        if (m_mouseDownWasInSubframe) {
-            if (Frame* subframe = subframeForTargetNode(m_mousePressNode.get()))
-                subframe->eventHandler()->stopAutoscrollTimer(rendererIsBeingDestroyed);
-            return;
-        }
-    }
-
-    if (autoscrollRenderer()) {
-        if (!rendererIsBeingDestroyed && (m_autoscrollInProgress || m_panScrollInProgress))
-            toRenderBox(autoscrollRenderer())->stopAutoscroll();
-#if ENABLE(PAN_SCROLLING)
-        if (m_panScrollInProgress) {
-            if (FrameView* view = m_frame->view()) {
-                view->removePanScrollIcon();
-                view->setCursor(pointerCursor());
-            }
-        }
-#endif
-
-        setAutoscrollRenderer(0);
-    }
-
-    m_autoscrollTimer.stop();
-
-    m_panScrollInProgress = false;
-    m_springLoadedPanScrollInProgress = false;
-
-    // If we're not in the top frame we notify it that we are not doing a panScroll any more.
-    if (Page* page = m_frame->page()) {
-        Frame* mainFrame = page->mainFrame();
-        if (m_frame != mainFrame)
-            mainFrame->eventHandler()->m_panScrollInProgress = false;
-    }
-
-    m_autoscrollInProgress = false;
+    m_autoscrollController->stopAutoscrollTimer(rendererIsBeingDestroyed);
 }
 
 Node* EventHandler::mousePressNode() const
@@ -1239,16 +1161,16 @@ bool EventHandler::logicalScrollRecursively(ScrollLogicalDirection direction, Sc
     return frame->eventHandler()->logicalScrollRecursively(direction, granularity, m_frame->ownerElement());
 }
 
-IntPoint EventHandler::currentMousePosition() const
+IntPoint EventHandler::lastKnownMousePosition() const
 {
-    return m_currentMousePosition;
+    return m_lastKnownMousePosition;
 }
 
 Frame* EventHandler::subframeForHitTestResult(const MouseEventWithHitTestResults& hitTestResult)
 {
     if (!hitTestResult.isOverWidget())
         return 0;
-    return subframeForTargetNode(targetNode(hitTestResult));
+    return subframeForTargetNode(hitTestResult.targetNode());
 }
 
 Frame* EventHandler::subframeForTargetNode(Node* node)
@@ -1278,6 +1200,41 @@ static bool nodeIsNotBeingEdited(Node* node, Frame* frame)
     return frame->selection()->rootEditableElement() != node->rootEditableElement();
 }
 
+bool EventHandler::useHandCursor(Node* node, bool isOverLink, bool shiftKey)
+{
+    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));
+}
+
 OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& event, Scrollbar* scrollbar)
 {
     if (m_resizeLayer && m_resizeLayer->inResizeMode())
@@ -1286,10 +1243,12 @@ OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& ev
     Page* page = m_frame->page();
     if (!page)
         return NoCursorChange;
-    if (page->mainFrame()->eventHandler()->m_panScrollInProgress)
+#if ENABLE(PAN_SCROLLING)
+    if (page->mainFrame()->eventHandler()->panScrollInProgress())
         return NoCursorChange;
+#endif
 
-    Node* node = targetNode(event);
+    Node* node = event.targetNode();
     RenderObject* renderer = node ? node->renderer() : 0;
     RenderStyle* style = renderer ? renderer->style() : 0;
     bool horizontalText = !style || style->isHorizontalWritingMode();
@@ -1319,53 +1278,45 @@ OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& ev
     if (style && style->cursors()) {
         const CursorList* cursors = style->cursors();
         for (unsigned i = 0; i < cursors->size(); ++i) {
-            CachedImage* cimage = 0;
-            StyleImage* image = (*cursors)[i].image();
-            if (image && image->isCachedImage())
-                cimage = static_cast<StyleCachedImage*>(image)->cachedImage();
-            if (!cimage)
+            StyleImage* styleImage = (*cursors)[i].image();
+            if (!styleImage)
+                continue;
+            CachedImage* cachedImage = styleImage->cachedImage();
+            if (!cachedImage)
                 continue;
+            float scale = styleImage->imageScaleFactor();
+            // Get hotspot and convert from logical pixels to physical pixels.
             IntPoint hotSpot = (*cursors)[i].hotSpot();
-            // Limit the size of cursors so that they cannot be used to cover UI elements in chrome.
-            IntSize size = cimage->imageForRenderer(renderer)->size();
-            if (size.width() > 128 || size.height() > 128)
+            hotSpot.scale(scale, scale);
+            IntSize size = cachedImage->imageForRenderer(renderer)->size();
+            if (cachedImage->errorOccurred())
+                continue;
+            // Limit the size of cursors (in UI pixels) so that they cannot be
+            // used to cover UI elements in chrome.
+            size.scale(1 / scale);
+            if (size.width() > maximumCursorSize || size.height() > maximumCursorSize)
+                continue;
+
+            Image* image = cachedImage->imageForRenderer(renderer);
+#if ENABLE(MOUSE_CURSOR_SCALE)
+            // Ensure no overflow possible in calculations above.
+            if (scale < minimumCursorScale)
                 continue;
-            if (!cimage->errorOccurred())
-                return Cursor(cimage->imageForRenderer(renderer), hotSpot);
+            return Cursor(image, hotSpot, scale);
+#else
+            ASSERT(scale == 1);
+            return Cursor(image, hotSpot);
+#endif // ENABLE(MOUSE_CURSOR_SCALE)
         }
     }
 
     switch (style ? style->cursor() : CURSOR_AUTO) {
     case CURSOR_AUTO: {
         bool editable = (node && 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) || event.event().shiftKey();
-                break;
-            
-            case EditableLinkOnlyLiveWithShiftKey:
-                editableLinkEnabled = event.event().shiftKey();
-                break;
-            }
-        }
-
-        if ((event.isOverLink() || isSubmitImage(node)) && (!editable || editableLinkEnabled))
+        if (useHandCursor(node, event.isOverLink(), event.event().shiftKey()))
             return handCursor();
+
         bool inResizer = false;
         if (renderer) {
             if (RenderLayer* layer = renderer->enclosingLayer()) {
@@ -1450,7 +1401,7 @@ OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& ev
     }
     return pointerCursor();
 }
-    
+
 static LayoutPoint documentPointForWindowPoint(Frame* frame, const IntPoint& windowPoint)
 {
     FrameView* view = frame->view();
@@ -1459,27 +1410,6 @@ static LayoutPoint documentPointForWindowPoint(Frame* frame, const IntPoint& win
     return view ? view->windowToContents(windowPoint) : windowPoint;
 }
 
-Node* EventHandler::targetNode(const MouseEventWithHitTestResults& event)
-{
-    return targetNode(event.hitTestResult());
-}
-
-Node* EventHandler::targetNode(const HitTestResult& hitTestResult)
-{
-    Node* node = hitTestResult.innerNode();
-    if (!node)
-        return 0;
-    if (node->inDocument())
-        return node;
-
-    Element* element = node->parentElement();
-    if (element && element->inDocument())
-        return element;
-
-    return node;
-
-}
-
 bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 {
     RefPtr<FrameView> protector(m_frame->view());
@@ -1496,6 +1426,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 #endif
 
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
+    m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
 
     // FIXME (bug 68185): this call should be made at another abstraction layer
     m_frame->loader()->resetMultipleFormSubmissionProtection();
@@ -1503,8 +1434,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
     cancelFakeMouseMoveEvent();
     m_mousePressed = true;
     m_capturesDragging = true;
-    m_currentMousePosition = mouseEvent.position();
-    m_currentMouseGlobalPosition = mouseEvent.globalPosition();
+    setLastKnownMousePosition(mouseEvent);
     m_mouseDownTimestamp = mouseEvent.timestamp();
 #if ENABLE(DRAG_SUPPORT)
     m_mouseDownMayStartDrag = false;
@@ -1525,20 +1455,20 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
     LayoutPoint documentPoint = documentPointForWindowPoint(m_frame, mouseEvent.position());
     MouseEventWithHitTestResults mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
 
-    if (!targetNode(mev)) {
+    if (!mev.targetNode()) {
         invalidateClick();
         return false;
     }
 
-    m_mousePressNode = targetNode(mev);
+    m_mousePressNode = mev.targetNode();
 
-    Frame* subframe = subframeForHitTestResult(mev);
-    if (subframe && passMousePressEventToSubframe(mev, subframe)) {
+    RefPtr<Frame> 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.
         m_capturesDragging = subframe->eventHandler()->capturesDragging();
         if (m_mousePressed && m_capturesDragging) {
-            m_capturingMouseEventsNode = targetNode(mev);
+            m_capturingMouseEventsNode = mev.targetNode();
             m_eventHandlerWillResetCapturingMouseEventsNode = true;
         }
         invalidateClick();
@@ -1547,10 +1477,9 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 
 #if ENABLE(PAN_SCROLLING)
     // We store whether pan scrolling is in progress before calling stopAutoscrollTimer()
-    // because it will set m_panScrollInProgress to false on return.
-    bool isPanScrollInProgress = m_frame->page() && m_frame->page()->mainFrame()->eventHandler()->m_panScrollInProgress;
-    if (isPanScrollInProgress || m_autoscrollInProgress)
-        stopAutoscrollTimer();
+    // because it will set m_autoscrollType to NoAutoscroll on return.
+    bool isPanScrollInProgress = m_frame->page() && m_frame->page()->mainFrame()->eventHandler()->panScrollInProgress();
+    stopAutoscrollTimer();
     if (isPanScrollInProgress) {
         // We invalidate the click when exiting pan scrolling so that we don't inadvertently navigate
         // away from the current page (e.g. the click was on a hyperlink). See <rdar://problem/6095023>.
@@ -1560,7 +1489,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 #endif
 
     m_clickCount = mouseEvent.clickCount();
-    m_clickNode = targetNode(mev);
+    m_clickNode = mev.targetNode();
 
     if (FrameView* view = m_frame->view()) {
         RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
@@ -1576,7 +1505,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
 
     m_frame->selection()->setCaretBlinkingSuspended(true);
 
-    bool swallowEvent = dispatchMouseEvent(eventNames().mousedownEvent, targetNode(mev), true, m_clickCount, mouseEvent, true);
+    bool swallowEvent = !dispatchMouseEvent(eventNames().mousedownEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
     m_capturesDragging = !swallowEvent || mev.scrollbar();
 
     // If the hit testing originally determined the event was in a scrollbar, refetch the MouseEventWithHitTestResults
@@ -1602,7 +1531,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
         // If a mouse event handler changes the input element type to one that has a widget associated,
         // we'd like to EventHandler::handleMousePressEvent to pass the event to the widget and thus the
         // event target node can't still be the shadow node.
-        if (targetNode(mev)->isShadowRoot() && toShadowRoot(targetNode(mev))->host()->hasTagName(inputTag)) {
+        if (mev.targetNode()->isShadowRoot() && toShadowRoot(mev.targetNode())->host()->hasTagName(inputTag)) {
             HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
             mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
         }
@@ -1620,7 +1549,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
             swallowEvent = handleMousePressEvent(mev);
     }
 
-    return swallowEvent;
+    return !swallowEvent;
 }
 
 // This method only exists for platforms that don't know how to deliver 
@@ -1628,12 +1557,13 @@ bool EventHandler::handleMouseDoubleClickEvent(const PlatformMouseEvent& mouseEv
 {
     RefPtr<FrameView> protector(m_frame->view());
 
+    m_frame->selection()->setCaretBlinkingSuspended(false);
+
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
 
     // We get this instead of a second mouse-up 
     m_mousePressed = false;
-    m_currentMousePosition = mouseEvent.position();
-    m_currentMouseGlobalPosition = mouseEvent.globalPosition();
+    setLastKnownMousePosition(mouseEvent);
 
     HitTestRequest request(HitTestRequest::Active);
     MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
@@ -1644,9 +1574,9 @@ bool EventHandler::handleMouseDoubleClickEvent(const PlatformMouseEvent& mouseEv
         return true;
 
     m_clickCount = mouseEvent.clickCount();
-    bool swallowMouseUpEvent = dispatchMouseEvent(eventNames().mouseupEvent, targetNode(mev), true, m_clickCount, mouseEvent, false);
+    bool swallowMouseUpEvent = !dispatchMouseEvent(eventNames().mouseupEvent, mev.targetNode(), true, m_clickCount, mouseEvent, false);
 
-    bool swallowClickEvent = mouseEvent.button() != RightButton && targetNode(mev) == m_clickNode && dispatchMouseEvent(eventNames().clickEvent, targetNode(mev), true, m_clickCount, mouseEvent, true);
+    bool swallowClickEvent = mouseEvent.button() != RightButton && mev.targetNode() == m_clickNode && !dispatchMouseEvent(eventNames().clickEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
 
     if (m_lastScrollbarUnderMouse)
         swallowMouseUpEvent = m_lastScrollbarUnderMouse->mouseUp(mouseEvent);
@@ -1676,8 +1606,8 @@ static RenderLayer* layerForNode(Node* node)
 
 bool EventHandler::mouseMoved(const PlatformMouseEvent& event)
 {
-    MaximumDurationTracker maxDurationTracker(&m_maxMouseMovedDuration);
     RefPtr<FrameView> protector(m_frame->view());
+    MaximumDurationTracker maxDurationTracker(&m_maxMouseMovedDuration);
 
 
 #if ENABLE(TOUCH_EVENTS)
@@ -1727,8 +1657,8 @@ bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& mouseEvent, Hi
         return false;
 
     RefPtr<FrameView> protector(m_frame->view());
-    m_currentMousePosition = mouseEvent.position();
-    m_currentMouseGlobalPosition = mouseEvent.globalPosition();
+    
+    setLastKnownMousePosition(mouseEvent);
 
     if (m_hoverTimer.isActive())
         m_hoverTimer.stop();
@@ -1737,13 +1667,13 @@ bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& mouseEvent, Hi
 
 #if ENABLE(SVG)
     if (m_svgPan) {
-        static_cast<SVGDocument*>(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_currentMousePosition));
+        static_cast<SVGDocument*>(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_lastKnownMousePosition));
         return true;
     }
 #endif
 
     if (m_frameSetBeingResized)
-        return dispatchMouseEvent(eventNames().mousemoveEvent, m_frameSetBeingResized.get(), false, 0, mouseEvent, false);
+        return !dispatchMouseEvent(eventNames().mousemoveEvent, m_frameSetBeingResized.get(), false, 0, mouseEvent, false);
 
     // Send events right to a scrollbar if the mouse is pressed.
     if (m_lastScrollbarUnderMouse && m_mousePressed)
@@ -1795,7 +1725,7 @@ bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& mouseEvent, Hi
 
     if (newSubframe) {
         // Update over/out state before passing the event to the subframe.
-        updateMouseEventTargetNode(targetNode(mev), mouseEvent, true);
+        updateMouseEventTargetNode(mev.targetNode(), mouseEvent, true);
         
         // Event dispatch in updateMouseEventTargetNode may have caused the subframe of the target
         // node to be detached from its FrameView, in which case the event should not be passed.
@@ -1806,8 +1736,10 @@ bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& mouseEvent, Hi
             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, scrollbar);
-            if (optionalCursor.isCursorChange())
-                view->setCursor(optionalCursor.cursor());
+            if (optionalCursor.isCursorChange()) {
+                m_currentMouseCursor = optionalCursor.cursor();
+                view->setCursor(m_currentMouseCursor);
+            }
         }
     }
     
@@ -1816,7 +1748,7 @@ bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& mouseEvent, Hi
     if (swallowEvent)
         return true;
     
-    swallowEvent = dispatchMouseEvent(eventNames().mousemoveEvent, targetNode(mev), false, 0, mouseEvent, true);
+    swallowEvent = !dispatchMouseEvent(eventNames().mousemoveEvent, mev.targetNode(), false, 0, mouseEvent, true);
 #if ENABLE(DRAG_SUPPORT)
     if (!swallowEvent)
         swallowEvent = handleMouseDraggedEvent(mev);
@@ -1835,35 +1767,38 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
 {
     RefPtr<FrameView> protector(m_frame->view());
 
+    m_frame->selection()->setCaretBlinkingSuspended(false);
+
 #if ENABLE(TOUCH_EVENTS)
     bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(mouseEvent);
     if (defaultPrevented)
         return true;
 #endif
 
-    UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
+    OwnPtr<UserGestureIndicator> gestureIndicator;
+
+    if (m_lastMouseDownUserGestureToken)
+        gestureIndicator = adoptPtr(new UserGestureIndicator(m_lastMouseDownUserGestureToken.release()));
+    else
+        gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingUserGesture));
 
 #if ENABLE(PAN_SCROLLING)
-    if (mouseEvent.button() == MiddleButton)
-        m_panScrollButtonPressed = false;
-    if (m_springLoadedPanScrollInProgress)
-        stopAutoscrollTimer();
+    m_autoscrollController->handleMouseReleaseEvent(mouseEvent);
 #endif
 
     m_mousePressed = false;
-    m_currentMousePosition = mouseEvent.position();
-    m_currentMouseGlobalPosition = mouseEvent.globalPosition();
+    setLastKnownMousePosition(mouseEvent);
 
 #if ENABLE(SVG)
     if (m_svgPan) {
         m_svgPan = false;
-        static_cast<SVGDocument*>(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_currentMousePosition));
+        static_cast<SVGDocument*>(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_lastKnownMousePosition));
         return true;
     }
 #endif
 
     if (m_frameSetBeingResized)
-        return dispatchMouseEvent(eventNames().mouseupEvent, m_frameSetBeingResized.get(), true, m_clickCount, mouseEvent, false);
+        return !dispatchMouseEvent(eventNames().mouseupEvent, m_frameSetBeingResized.get(), true, m_clickCount, mouseEvent, false);
 
     if (m_lastScrollbarUnderMouse) {
         invalidateClick();
@@ -1878,9 +1813,20 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
     if (subframe && passMouseReleaseEventToSubframe(mev, subframe))
         return true;
 
-    bool swallowMouseUpEvent = dispatchMouseEvent(eventNames().mouseupEvent, targetNode(mev), true, m_clickCount, mouseEvent, false);
+    bool swallowMouseUpEvent = !dispatchMouseEvent(eventNames().mouseupEvent, mev.targetNode(), true, m_clickCount, mouseEvent, false);
 
-    bool swallowClickEvent = m_clickCount > 0 && mouseEvent.button() != RightButton && targetNode(mev) == m_clickNode && dispatchMouseEvent(eventNames().clickEvent, targetNode(mev), true, m_clickCount, mouseEvent, true);
+    Node* clickTarget = mev.targetNode();
+    if (clickTarget)
+        clickTarget = clickTarget->deprecatedShadowAncestorNode();
+    Node* adjustedClickNode = m_clickNode ? m_clickNode->deprecatedShadowAncestorNode() : 0;
+
+    bool contextMenuEvent = mouseEvent.button() == RightButton;
+#if PLATFORM(CHROMIUM) && OS(DARWIN)
+    // FIXME: The Mac port achieves the same behavior by checking whether the context menu is currently open in WebPage::mouseEvent(). Consider merging the implementations.
+    if (mouseEvent.button() == LeftButton && mouseEvent.modifiers() & PlatformEvent::CtrlKey)
+        contextMenuEvent = true;
+#endif
+    bool swallowClickEvent = m_clickCount > 0 && !contextMenuEvent && clickTarget == adjustedClickNode && !dispatchMouseEvent(eventNames().clickEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
 
     if (m_resizeLayer) {
         m_resizeLayer->setInResizeMode(false);
@@ -1896,6 +1842,41 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
     return swallowMouseUpEvent || swallowClickEvent || swallowMouseReleaseEvent;
 }
 
+bool EventHandler::handlePasteGlobalSelection(const PlatformMouseEvent& mouseEvent)
+{
+    // If the event was a middle click, attempt to copy global selection in after
+    // the newly set caret position.
+    //
+    // This code is called from either the mouse up or mouse down handling. There
+    // is some debate about when the global selection is pasted:
+    //   xterm: pastes on up.
+    //   GTK: pastes on down.
+    //   Qt: pastes on up.
+    //   Firefox: pastes on up.
+    //   Chromium: pastes on up.
+    //
+    // There is something of a webcompat angle to this well, as highlighted by
+    // crbug.com/14608. Pages can clear text boxes 'onclick' and, if we paste on
+    // down then the text is pasted just before the onclick handler runs and
+    // clears the text box. So it's important this happens after the event
+    // handlers have been fired.
+#if PLATFORM(GTK)
+    if (mouseEvent.type() != PlatformEvent::MousePressed)
+        return false;
+#else
+    if (mouseEvent.type() != PlatformEvent::MouseReleased)
+        return false;
+#endif
+
+    Frame* focusFrame = m_frame->page()->focusController()->focusedOrMainFrame();
+    // Do not paste here if the focus was moved somewhere else.
+    if (m_frame == focusFrame && m_frame->editor()->client()->supportsGlobalSelection())
+        return m_frame->editor()->command(ASCIILiteral("PasteGlobalSelection")).execute();
+
+    return false;
+}
+
+
 #if ENABLE(DRAG_SUPPORT)
 bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Node* dragTarget, const PlatformMouseEvent& event, Clipboard* clipboard)
 {
@@ -1980,10 +1961,12 @@ bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard*
     MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
 
     // Drag events should never go to text nodes (following IE, and proper mouseover/out dispatch)
-    RefPtr<Node> newTarget = targetNode(mev);
+    RefPtr<Node> newTarget = mev.targetNode();
     if (newTarget && newTarget->isTextNode())
         newTarget = newTarget->parentNode();
 
+    m_autoscrollController->updateDragAndDrop(newTarget.get(), event.position(), event.timestamp());
+
     if (m_dragTarget != newTarget) {
         // FIXME: this ordering was explicitly chosen to match WinIE. However,
         // it is sometimes incorrect when dragging within subframes, as seen with
@@ -2067,6 +2050,7 @@ bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, Clipboard
 
 void EventHandler::clearDragState()
 {
+    stopAutoscrollTimer();
     m_dragTarget = 0;
     m_capturingMouseEventsNode = 0;
     m_shouldOnlyFireDragOverEvent = false;
@@ -2096,7 +2080,7 @@ static inline SVGElementInstance* instanceAssociatedWithShadowTreeElement(Node*
     if (!referenceNode || !referenceNode->isSVGElement())
         return 0;
 
-    ShadowRoot* shadowRoot = referenceNode->shadowRoot();
+    ShadowRoot* shadowRoot = referenceNode->containingShadowRoot();
     if (!shadowRoot)
         return 0;
 
@@ -2118,8 +2102,8 @@ 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()) {
-            ComposedShadowTreeParentWalker walker(result);
-            walker.parentIncludingInsertionPointAndShadowRoot();
+            AncestorChainWalker walker(result);
+            walker.parent();
             result = walker.get();
         }
     }
@@ -2230,14 +2214,14 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
     bool swallowEvent = false;
 
     if (m_nodeUnderMouse)
-        swallowEvent = m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventType, clickCount);
+        swallowEvent = !(m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventType, clickCount));
 
     if (!swallowEvent && eventType == eventNames().mousedownEvent) {
 
         // 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 false;
+                return true;
         }
 
         // The layout needs to be up to date to determine if an element is focusable.
@@ -2260,13 +2244,17 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
                 if (m_frame->selection()->isRange()
                     && m_frame->selection()->toNormalizedRange()->compareNode(n, ec) == Range::NODE_INSIDE
                     && n->isDescendantOf(m_frame->document()->focusedNode()))
-                    return false;
+                    return true;
                     
                 break;
             }
             node = node->parentOrHostNode();
         }
 
+        // Only change the focus when clicking scrollbars if it can transfered to a mouse focusable node.
+        if ((!node || !node->isMouseFocusable()) && isInsideScrollbar(mouseEvent.position()))
+            return false;
+
         // 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 (Page* page = m_frame->page()) {
@@ -2280,11 +2268,23 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
         }
     }
 
-    return swallowEvent;
+    return !swallowEvent;
+}
+
+bool EventHandler::isInsideScrollbar(const IntPoint& windowPoint) const
+{
+    if (RenderView* renderView = m_frame->contentRenderer()) {
+        HitTestRequest request(HitTestRequest::ReadOnly);
+        HitTestResult result(windowPoint);
+        renderView->hitTest(request, result);
+        return result.scrollbar();
+    }
+
+    return false;
 }
 
 #if !PLATFORM(GTK) && !(PLATFORM(CHROMIUM) && (OS(UNIX) && !OS(DARWIN)))
-bool EventHandler::shouldTurnVerticalTicksIntoHorizontal(const HitTestResult&) const
+bool EventHandler::shouldTurnVerticalTicksIntoHorizontal(const HitTestResult&, const PlatformWheelEvent&) const
 {
     return false;
 }
@@ -2313,11 +2313,9 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
     HitTestResult result(vPoint);
     doc->renderView()->hitTest(request, result);
 
-#if PLATFORM(MAC)
-    m_useLatchedWheelEventNode = e.momentumPhase() == PlatformWheelEventPhaseBegan || e.momentumPhase() == PlatformWheelEventPhaseChanged;
-#endif
+    bool useLatchedWheelEventNode = e.useLatchedEventNode();
 
-    if (m_useLatchedWheelEventNode) {
+    if (useLatchedWheelEventNode) {
         if (!m_latchedWheelEventNode) {
             m_latchedWheelEventNode = result.innerNode();
             m_widgetIsLatched = result.isOverWidget();
@@ -2339,7 +2337,7 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
     // Instead, the handlers should know convert vertical scrolls
     // appropriately.
     PlatformWheelEvent event = e;
-    if (m_baseEventType == PlatformEvent::NoType && shouldTurnVerticalTicksIntoHorizontal(result))
+    if (m_baseEventType == PlatformEvent::NoType && shouldTurnVerticalTicksIntoHorizontal(result, e))
         event = event.copyTurningVerticalTicksIntoHorizontalTicks();
 
     if (node) {
@@ -2371,7 +2369,7 @@ void EventHandler::defaultWheelEventHandler(Node* startNode, WheelEvent* wheelEv
         return;
     
     Node* stopNode = m_previousWheelScrolledNode.get();
-    ScrollGranularity granularity = m_baseEventType == PlatformEvent::GestureScrollEnd ? ScrollByPixelVelocity : wheelGranularityToScrollGranularity(wheelEvent->granularity());
+    ScrollGranularity granularity = wheelGranularityToScrollGranularity(wheelEvent->granularity());
     
     // Break up into two scrolls if we need to.  Diagonal movement on 
     // a MacBook pro is an example of a 2-dimensional mouse wheel event (where both deltaX and deltaY can be set).
@@ -2381,7 +2379,7 @@ void EventHandler::defaultWheelEventHandler(Node* startNode, WheelEvent* wheelEv
     if (scrollNode(wheelEvent->rawDeltaY(), granularity, ScrollUp, ScrollDown, startNode, &stopNode))
         wheelEvent->setDefaultHandled();
     
-    if (!m_useLatchedWheelEventNode)
+    if (!m_latchedWheelEventNode)
         m_previousWheelScrolledNode = stopNode;
 }
 
@@ -2407,26 +2405,92 @@ bool EventHandler::handleGestureTapDown()
 
 bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
 {
+    // We don't use DoubleTap at the moment, it's mostly redundant with tap since tap now contains
+    // a tap count. FIXME: We should probably remove GestureDoubleTap (http://wkb.ug/93045).
+    if (gestureEvent.type() == PlatformEvent::GestureDoubleTap)
+        return false;
+
+    Node* eventTarget = 0;
+    Scrollbar* scrollbar = 0;
+    if (gestureEvent.type() == PlatformEvent::GestureScrollEnd || gestureEvent.type() == PlatformEvent::GestureScrollUpdate) {
+        scrollbar = m_scrollbarHandlingScrollGesture.get();
+        eventTarget = m_scrollGestureHandlingNode.get();
+    }
+
+    IntPoint adjustedPoint = gestureEvent.position();
+    HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
+    if (gestureEvent.type() == PlatformEvent::GestureTapDown) {
+#if ENABLE(TOUCH_ADJUSTMENT)
+        adjustGesturePosition(gestureEvent, adjustedPoint);
+#endif
+        hitType |= HitTestRequest::Active;
+    } else if (gestureEvent.type() == PlatformEvent::GestureTap || gestureEvent.type() == PlatformEvent::GestureTapDownCancel)
+        hitType |= HitTestRequest::Release;
+    else
+        hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
+
+    if (!shouldGesturesTriggerActive())
+        hitType |= HitTestRequest::ReadOnly;
+
+    if ((!scrollbar && !eventTarget) || !(hitType & HitTestRequest::ReadOnly)) {
+        IntPoint hitTestPoint = m_frame->view()->windowToContents(adjustedPoint);
+        HitTestResult result = hitTestResultAtPoint(hitTestPoint, false, false, ShouldHitTestScrollbars, hitType);
+        eventTarget = result.targetNode();
+        if (!scrollbar) {
+            FrameView* view = m_frame->view();
+            scrollbar = view ? view->scrollbarAtPoint(gestureEvent.position()) : 0;
+        }
+        if (!scrollbar)
+            scrollbar = result.scrollbar();
+    }
+
+    if (scrollbar) {
+        bool eventSwallowed = scrollbar->gestureEvent(gestureEvent);
+        if (gestureEvent.type() == PlatformEvent::GestureScrollBegin && eventSwallowed)
+            m_scrollbarHandlingScrollGesture = scrollbar;
+        else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd || !eventSwallowed)
+            m_scrollbarHandlingScrollGesture = 0;
+
+        if (eventSwallowed)
+            return true;
+    }
+
+    if (eventTarget) {
+        bool 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 handleGestureScrollCore(gestureEvent, ScrollByPixelWheelEvent, false);
-    case PlatformEvent::GestureScrollEnd:
-        return handleGestureScrollCore(gestureEvent, ScrollByPixelVelocityWheelEvent, true);
+        return handleGestureScrollBegin(gestureEvent);
     case PlatformEvent::GestureScrollUpdate:
         return handleGestureScrollUpdate(gestureEvent);
     case PlatformEvent::GestureTap:
         return handleGestureTap(gestureEvent);
     case PlatformEvent::GestureTapDown:
         return handleGestureTapDown();
-    case PlatformEvent::GestureDoubleTap:
     case PlatformEvent::GestureLongPress:
+        return handleGestureLongPress(gestureEvent);
+    case PlatformEvent::GestureLongTap:
+        return handleGestureLongTap(gestureEvent);
+    case PlatformEvent::GestureTwoFingerTap:
+        return handleGestureTwoFingerTap(gestureEvent);
+    case PlatformEvent::GestureScrollEnd:
+    case PlatformEvent::GestureDoubleTap:
     case PlatformEvent::GesturePinchBegin:
     case PlatformEvent::GesturePinchEnd:
     case PlatformEvent::GesturePinchUpdate:
+    case PlatformEvent::GestureTapDownCancel:
         break;
     default:
         ASSERT_NOT_REACHED();
@@ -2437,57 +2501,241 @@ bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
 
 bool EventHandler::handleGestureTap(const PlatformGestureEvent& gestureEvent)
 {
-    // FIXME: Refactor this code to not hit test multiple times.
+    // 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.
     IntPoint adjustedPoint = gestureEvent.position();
 #if ENABLE(TOUCH_ADJUSTMENT)
-    if (!gestureEvent.area().isEmpty()) {
-        Node* targetNode = 0;
-        // For now we use the adjusted position to ensure the later redundant hit-tests hits the right node.
-        bestClickableNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode);
-        if (!targetNode)
-            return false;
-    }
+    adjustGesturePosition(gestureEvent, adjustedPoint);
 #endif
 
-    bool defaultPrevented = false;
-    PlatformMouseEvent fakeMouseMove(adjustedPoint, gestureEvent.globalPosition(), NoButton, PlatformEvent::MouseMoved, /* clickCount */ 1, gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
-    PlatformMouseEvent fakeMouseDown(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, /* clickCount */ 1, gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
-    PlatformMouseEvent fakeMouseUp(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MouseReleased, /* clickCount */ 1, gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
+    PlatformMouseEvent fakeMouseMove(adjustedPoint, gestureEvent.globalPosition(),
+        NoButton, PlatformEvent::MouseMoved, /* clickCount */ 0,
+        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
     mouseMoved(fakeMouseMove);
+
+    int tapCount = 1;
+    // FIXME: deletaX is overloaded to mean different things for different gestures.
+    // http://wkb.ug/93123
+    if (gestureEvent.deltaX() > 0)
+        tapCount = static_cast<int>(gestureEvent.deltaX());
+
+    bool defaultPrevented = false;
+    PlatformMouseEvent fakeMouseDown(adjustedPoint, gestureEvent.globalPosition(),
+        LeftButton, PlatformEvent::MousePressed, tapCount,
+        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
     defaultPrevented |= handleMousePressEvent(fakeMouseDown);
+
+    PlatformMouseEvent fakeMouseUp(adjustedPoint, gestureEvent.globalPosition(),
+        LeftButton, PlatformEvent::MouseReleased, tapCount,
+        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
     defaultPrevented |= handleMouseReleaseEvent(fakeMouseUp);
+
     return defaultPrevented;
 }
 
-bool EventHandler::handleGestureScrollUpdate(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEvent)
 {
-    return handleGestureScrollCore(gestureEvent, ScrollByPixelWheelEvent, true);
+#if ENABLE(DRAG_SUPPORT)
+    if (m_frame->settings() && m_frame->settings()->touchDragDropEnabled()) {
+        IntPoint adjustedPoint = gestureEvent.position();
+#if ENABLE(TOUCH_ADJUSTMENT)
+        adjustGesturePosition(gestureEvent, adjustedPoint);
+#endif
+        PlatformMouseEvent mouseDownEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 0, false, false, false, false, WTF::currentTime());
+        handleMousePressEvent(mouseDownEvent);
+        PlatformMouseEvent mouseDragEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WTF::currentTime());
+        HitTestRequest request(HitTestRequest::ReadOnly);
+        MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseDragEvent);
+        m_didStartDrag = false;
+        RefPtr<Frame> subframe = subframeForHitTestResult(mev);
+        if (subframe && !m_mouseDownMayStartDrag) {
+            if (subframe->eventHandler()->handleGestureLongPress(gestureEvent))
+                return true;
+        }
+        handleDrag(mev, DontCheckDragHysteresis);
+        if (m_didStartDrag)
+            return true;
+    }
+#endif
+    return handleGestureForTextSelectionOrContextMenu(gestureEvent);
 }
 
-bool EventHandler::handleGestureScrollCore(const PlatformGestureEvent& gestureEvent, PlatformWheelEventGranularity granularity, bool latchedWheel)
+bool EventHandler::handleGestureLongTap(const PlatformGestureEvent& gestureEvent)
 {
-    TemporaryChange<bool> latched(m_useLatchedWheelEventNode, latchedWheel);
-    const float tickDivisor = (float)WheelEvent::tickMultiplier;
-    IntPoint point(gestureEvent.position().x(), gestureEvent.position().y());
-    IntPoint globalPoint(gestureEvent.globalPosition().x(), gestureEvent.globalPosition().y());
-    PlatformWheelEvent syntheticWheelEvent(point, globalPoint,
-        gestureEvent.deltaX(), gestureEvent.deltaY(), gestureEvent.deltaX() / tickDivisor, gestureEvent.deltaY() / tickDivisor,
-        granularity,
-        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey());
-    return handleWheelEvent(syntheticWheelEvent);
+#if ENABLE(CONTEXT_MENUS) && !OS(ANDROID)
+    if (!m_didLongPressInvokeContextMenu)
+        return sendContextMenuEventForGesture(gestureEvent);
+#endif
+    return false;
 }
+
+bool EventHandler::handleGestureForTextSelectionOrContextMenu(const PlatformGestureEvent& gestureEvent)
+{
+#if OS(ANDROID)
+    IntPoint hitTestPoint = m_frame->view()->windowToContents(gestureEvent.position());
+    HitTestResult result = hitTestResultAtPoint(hitTestPoint, true);
+    Node* innerNode = result.targetNode();
+    if (!result.isLiveLink() && innerNode && (innerNode->isContentEditable() || innerNode->isTextNode())) {
+        selectClosestWordFromHitTestResult(result, DontAppendTrailingWhitespace);
+        if (m_frame->selection()->isRange())
+            return true;
+    }
+#endif
+#if ENABLE(CONTEXT_MENUS)
+    m_didLongPressInvokeContextMenu = (gestureEvent.type() == PlatformEvent::GestureLongPress);
+    return sendContextMenuEventForGesture(gestureEvent);
+#else
+    return false;
 #endif
+}
+
+bool EventHandler::handleGestureTwoFingerTap(const PlatformGestureEvent& gestureEvent)
+{
+    return handleGestureForTextSelectionOrContextMenu(gestureEvent);
+}
+
+bool EventHandler::passGestureEventToWidget(const PlatformGestureEvent& gestureEvent, Widget* widget)
+{
+    if (!widget)
+        return false;
+
+    if (!widget->isFrameView())
+        return false;
+
+    return static_cast<FrameView*>(widget)->frame()->eventHandler()->handleGestureEvent(gestureEvent);
+}
+
+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;
+}
+
+static const Node* closestScrollableNodeInDocumentIfPossibleOrSelfIfNotScrollable(const Node* node)
+{
+    for (const Node* scrollableNode = node; scrollableNode; scrollableNode = scrollableNode->parentNode()) {
+        if (scrollableNode->isDocumentNode())
+            break;
+        RenderObject* renderer = scrollableNode->renderer();
+        if (renderer && renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea())
+            return scrollableNode;
+    }
+    return node;
+}
+
+bool EventHandler::handleGestureScrollBegin(const PlatformGestureEvent& gestureEvent)
+{
+    Document* document = m_frame->document();
+    RenderObject* documentRenderer = document->renderer();
+    if (!documentRenderer)
+        return false;
+
+    FrameView* view = m_frame->view();
+    if (!view)
+        return false;
+
+    LayoutPoint viewPoint = view->windowToContents(gestureEvent.position());
+    HitTestRequest request(HitTestRequest::ReadOnly);
+    HitTestResult result(viewPoint);
+    document->renderView()->hitTest(request, result);
+
+    m_lastHitTestResultOverWidget = result.isOverWidget(); 
+    m_scrollGestureHandlingNode = result.innerNode();
+
+    Node* node = m_scrollGestureHandlingNode.get();
+    if (node)
+        passGestureEventToWidgetIfPossible(gestureEvent, node->renderer());
+    
+    return node && node->renderer();
+}
+
+bool EventHandler::handleGestureScrollUpdate(const PlatformGestureEvent& gestureEvent)
+{
+    // Ignore this event if we don't already have a targeted node with a valid renderer.
+    const Node* node = m_scrollGestureHandlingNode.get();
+    if (!node)
+        return false;
+
+    RenderObject* latchedRenderer = node->renderer();
+    if (!latchedRenderer)
+        return false;
+
+    IntSize delta(-gestureEvent.deltaX(), -gestureEvent.deltaY());
+    if (delta.isZero())
+        return false;
+
+    RefPtr<FrameView> protector(m_frame->view());
+
+    // Try to send the event to the correct view.
+    if (passGestureEventToWidgetIfPossible(gestureEvent, latchedRenderer))
+        return true;
+
+    // Otherwise if this is the correct view for the event, find the closest scrollable
+    // ancestor of the targeted node and scroll the layer that contains this node's renderer.
+    node = closestScrollableNodeInDocumentIfPossibleOrSelfIfNotScrollable(node);
+    if (!node)
+        return false;
+
+    latchedRenderer = node->renderer();
+    if (!latchedRenderer)
+        return false;
+
+    const float scaleFactor = m_frame->pageZoomFactor() * m_frame->frameScaleFactor();
+    delta.scale(1 / scaleFactor, 1 / scaleFactor);
+
+    bool result = latchedRenderer->enclosingLayer()->scrollByRecursively(delta, RenderLayer::ScrollOffsetClamped);
+
+    if (result)
+        setFrameWasScrolledByUser();
+
+    return result;
+}
+
+bool EventHandler::isScrollbarHandlingGestures() const
+{
+    return m_scrollbarHandlingScrollGesture.get();
+}
+#endif // ENABLE(GESTURE_EVENTS)
 
 #if ENABLE(TOUCH_ADJUSTMENT)
+bool EventHandler::shouldApplyTouchAdjustment(const PlatformGestureEvent& event) const
+{
+    if (m_frame->settings() && !m_frame->settings()->touchAdjustmentEnabled())
+        return false;
+    return !event.area().isEmpty();
+}
+
+
 bool EventHandler::bestClickableNodeForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntPoint& targetPoint, Node*& targetNode)
 {
     HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
     IntPoint hitTestPoint = m_frame->view()->windowToContents(touchCenter);
-    HitTestResult result = hitTestResultAtPoint(hitTestPoint, /*allowShadowContent*/ false, /*ignoreClipping*/ false, DontHitTestScrollbars, hitType, touchRadius);
+    HitTestResult result = hitTestResultAtPoint(hitTestPoint, /*allowShadowContent*/ true, /*ignoreClipping*/ false, DontHitTestScrollbars, hitType, touchRadius);
+
+    IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
+    RefPtr<StaticHashSetNodeList> nodeList = StaticHashSetNodeList::adopt(result.rectBasedTestResult());
+
+    // 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. 
+    bool success = findBestClickableCandidate(targetNode, targetPoint, touchCenter, touchRect, *nodeList.get());
+    if (success && targetNode)
+        targetNode = targetNode->deprecatedShadowAncestorNode();
+    return success;
+}
+
+bool EventHandler::bestContextMenuNodeForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntPoint& targetPoint, Node*& targetNode)
+{
+    HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
+    IntPoint hitTestPoint = m_frame->view()->windowToContents(touchCenter);
+    HitTestResult result = hitTestResultAtPoint(hitTestPoint, /*allowShadowContent*/ true, /*ignoreClipping*/ false, DontHitTestScrollbars, hitType, touchRadius);
 
     IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
     RefPtr<StaticHashSetNodeList> nodeList = StaticHashSetNodeList::adopt(result.rectBasedTestResult());
-    return findBestClickableCandidate(targetNode, targetPoint, touchCenter, touchRect, *nodeList.get());
+    return findBestContextMenuCandidate(targetNode, targetPoint, touchCenter, touchRect, *nodeList.get());
 }
 
 bool EventHandler::bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode)
@@ -2500,6 +2748,29 @@ bool EventHandler::bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, co
     RefPtr<StaticHashSetNodeList> nodeList = StaticHashSetNodeList::adopt(result.rectBasedTestResult());
     return findBestZoomableArea(targetNode, targetArea, touchCenter, touchRect, *nodeList.get());
 }
+
+bool EventHandler::adjustGesturePosition(const PlatformGestureEvent& gestureEvent, IntPoint& adjustedPoint)
+{
+    if (!shouldApplyTouchAdjustment(gestureEvent))
+        return false;
+
+    Node* targetNode = 0;
+    switch (gestureEvent.type()) {
+    case PlatformEvent::GestureTap:
+    case PlatformEvent::GestureTapDown:
+        bestClickableNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode);
+        break;
+    case PlatformEvent::GestureLongPress:
+    case PlatformEvent::GestureLongTap:
+    case PlatformEvent::GestureTwoFingerTap:
+        bestContextMenuNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode);
+        break;
+    default:
+        // FIXME: Implement handling for other types as needed.
+        ASSERT_NOT_REACHED();
+    }
+    return targetNode;
+}
 #endif
 
 #if ENABLE(CONTEXT_MENUS)
@@ -2510,6 +2781,8 @@ bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
     if (!v)
         return false;
     
+    // 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);
@@ -2517,15 +2790,16 @@ bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
 
     if (m_frame->editor()->behavior().shouldSelectOnContextualMenuClick()
         && !m_frame->selection()->contains(viewportPos)
+        && !mev.scrollbar()
         // FIXME: In the editable case, word selection sometimes selects content that isn't underneath the mouse.
         // If the selection is non-editable, we do word selection to make it easier to use the contextual menu items
         // available for text selections.  But only if we're above text.
-        && (m_frame->selection()->isContentEditable() || (targetNode(mev) && targetNode(mev)->isTextNode()))) {
+        && (m_frame->selection()->isContentEditable() || (mev.targetNode() && mev.targetNode()->isTextNode()))) {
         m_mouseDownMayStartSelect = true; // context menu events are always allowed to perform a selection
         selectClosestWordOrLinkFromMouseEvent(mev);
     }
 
-    swallowEvent = dispatchMouseEvent(eventNames().contextmenuEvent, targetNode(mev), true, 0, event, false);
+    swallowEvent = !dispatchMouseEvent(eventNames().contextmenuEvent, mev.targetNode(), true, 0, event, false);
     
     return swallowEvent;
 }
@@ -2540,6 +2814,9 @@ bool EventHandler::sendContextMenuEventForKey()
     if (!doc)
         return false;
 
+    // Clear mouse press state to avoid initiating a drag while context menu is up.
+    m_mousePressed = false;
+
     static const int kContextMenuMargin = 1;
 
 #if OS(WINDOWS) && !OS(WINCE)
@@ -2586,7 +2863,7 @@ bool EventHandler::sendContextMenuEventForKey()
     HitTestResult result(position);
     result.setInnerNode(targetNode);
     HitTestRequest request(HitTestRequest::Active);
-    doc->renderView()->layer()->updateHoverActiveState(request, result);
+    doc->updateHoverActiveState(request, result);
     doc->updateStyleIfNeeded();
    
     // The contextmenu event is a mouse event even when invoked using the keyboard.
@@ -2600,7 +2877,7 @@ bool EventHandler::sendContextMenuEventForKey()
 
     PlatformMouseEvent mouseEvent(position, globalPosition, RightButton, eventType, 1, false, false, false, false, WTF::currentTime());
 
-    return dispatchMouseEvent(eventNames().contextmenuEvent, targetNode, true, 0, mouseEvent, false);
+    return !dispatchMouseEvent(eventNames().contextmenuEvent, targetNode, true, 0, mouseEvent, false);
 }
 
 #if ENABLE(GESTURE_EVENTS)
@@ -2611,8 +2888,18 @@ bool EventHandler::sendContextMenuEventForGesture(const PlatformGestureEvent& ev
 #else
     PlatformEvent::Type eventType = PlatformEvent::MousePressed;
 #endif
-    PlatformMouseEvent mouseEvent(event.position(), event.globalPosition(), RightButton, eventType, 1, false, false, false, false, WTF::currentTime());
+
+    IntPoint adjustedPoint = event.position();
+#if ENABLE(TOUCH_ADJUSTMENT)
+    adjustGesturePosition(event, adjustedPoint);
+#endif
+    PlatformMouseEvent mouseEvent(adjustedPoint, 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.
+    handleMousePressEvent(mouseEvent);
     return sendContextMenuEvent(mouseEvent);
+    // We do not need to send a corresponding mouse release because in case of
+    // right-click, the context menu takes capture and consumes all events.
 }
 #endif // ENABLE(GESTURE_EVENTS)
 #endif // ENABLE(CONTEXT_MENUS)
@@ -2628,6 +2915,9 @@ void EventHandler::dispatchFakeMouseMoveEventSoon()
     if (m_mousePressed)
         return;
 
+    if (m_mousePositionIsUnknown)
+        return;
+
     Settings* settings = m_frame->settings();
     if (settings && !settings->deviceSupportsMouse())
         return;
@@ -2652,7 +2942,7 @@ void EventHandler::dispatchFakeMouseMoveEventSoonInQuad(const FloatQuad& quad)
     if (!view)
         return;
 
-    if (!quad.containsPoint(view->windowToContents(m_currentMousePosition)))
+    if (!quad.containsPoint(view->windowToContents(m_lastKnownMousePosition)))
         return;
 
     dispatchFakeMouseMoveEventSoon();
@@ -2676,12 +2966,15 @@ void EventHandler::fakeMouseMoveEventTimerFired(Timer<EventHandler>* timer)
     if (!view)
         return;
 
+    if (!m_frame->page() || !m_frame->page()->isOnscreen() || !m_frame->page()->focusController()->isActive())
+        return;
+
     bool shiftKey;
     bool ctrlKey;
     bool altKey;
     bool metaKey;
     PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
-    PlatformMouseEvent fakeMouseMoveEvent(m_currentMousePosition, m_currentMouseGlobalPosition, NoButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey, metaKey, currentTime());
+    PlatformMouseEvent fakeMouseMoveEvent(m_lastKnownMousePosition, m_lastKnownMouseGlobalPosition, NoButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey, metaKey, currentTime());
     mouseMoved(fakeMouseMoveEvent);
 }
 
@@ -2706,7 +2999,7 @@ void EventHandler::hoverTimerFired(Timer<EventHandler>*)
     if (RenderView* renderer = m_frame->contentRenderer()) {
         if (FrameView* view = m_frame->view()) {
             HitTestRequest request(HitTestRequest::Move);
-            HitTestResult result(view->windowToContents(m_currentMousePosition));
+            HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
             renderer->hitTest(request, result);
             m_frame->document()->updateStyleIfNeeded();
         }
@@ -2773,7 +3066,7 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
 
 #if ENABLE(PAN_SCROLLING)
     if (Page* page = m_frame->page()) {
-        if (page->mainFrame()->eventHandler()->m_panScrollInProgress) {
+        if (page->mainFrame()->eventHandler()->panScrollInProgress()) {
             // If a key is pressed while the panScroll is in progress then we want to stop
             if (initialKeyEvent.type() == PlatformEvent::KeyDown || initialKeyEvent.type() == PlatformEvent::RawKeyDown) 
                 stopAutoscrollTimer();
@@ -2879,10 +3172,10 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
 
 static FocusDirection focusDirectionForKey(const AtomicString& keyIdentifier)
 {
-    DEFINE_STATIC_LOCAL(AtomicString, Down, ("Down"));
-    DEFINE_STATIC_LOCAL(AtomicString, Up, ("Up"));
-    DEFINE_STATIC_LOCAL(AtomicString, Left, ("Left"));
-    DEFINE_STATIC_LOCAL(AtomicString, Right, ("Right"));
+    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;
 
@@ -3046,7 +3339,7 @@ static bool ExactlyOneBitSet(DragSourceAction n)
     return n && !(n & (n - 1));
 }
 
-bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event)
+bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDragHysteresis checkDragHysteresis)
 {
     if (event.event().button() != LeftButton || event.event().type() != PlatformEvent::MouseMoved) {
         // If we allowed the other side of the bridge to handle a drag
@@ -3125,7 +3418,7 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event)
         view->setCursor(pointerCursor());
     }
 
-    if (!dragHysteresisExceeded(event.event().position())) 
+    if (checkDragHysteresis == ShouldCheckDragHysteresis && !dragHysteresisExceeded(event.event().position()))
         return true;
     
     // Once we're past the hysteresis point, we don't want to treat this gesture as a click
@@ -3145,7 +3438,7 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event)
                 // FIXME: This doesn't work correctly with transforms.
                 FloatPoint absPos = renderer->localToAbsolute();
                 IntSize delta = m_mouseDownPos - roundedIntPoint(absPos);
-                dragState().m_dragClipboard->setDragImageElement(dragState().m_dragSrc.get(), toPoint(delta));
+                dragState().m_dragClipboard->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.
@@ -3176,11 +3469,11 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event)
     if (m_mouseDownMayStartDrag) {
         Page* page = m_frame->page();
         DragController* dragController = page ? page->dragController() : 0;
-        bool startedDrag = dragController && dragController->startDrag(m_frame, dragState(), srcOp, event.event(), m_mouseDownPos);
+        m_didStartDrag = dragController && dragController->startDrag(m_frame, dragState(), srcOp, event.event(), m_mouseDownPos);
         // In WebKit2 we could reenter this code and start another drag.
         // On OS X this causes problems with the ownership of the pasteboard
         // and the promised types.
-        if (startedDrag) {
+        if (m_didStartDrag) {
             m_mouseDownMayStartDrag = false;
             return true;
         }
@@ -3223,7 +3516,7 @@ bool EventHandler::handleTextInputEvent(const String& text, Event* underlyingEve
     if (FrameView* view = m_frame->view())
         view->resetDeferredRepaintDelay();
 
-    RefPtr<TextEvent> event = TextEvent::create(m_frame->domWindow(), text, inputType);
+    RefPtr<TextEvent> event = TextEvent::create(m_frame->document()->domWindow(), text, inputType);
     event->setUnderlyingEvent(underlyingEvent);
 
     ExceptionCode ec;
@@ -3449,6 +3742,22 @@ static const AtomicString& eventNameForTouchPointState(PlatformTouchPoint::State
     }
 }
 
+HitTestResult EventHandler::hitTestResultInFrame(Frame* frame, const LayoutPoint& point, HitTestRequest::HitTestRequestType hitType)
+{
+    HitTestResult result(point);
+
+    if (!frame || !frame->contentRenderer())
+        return result;
+    if (frame->view()) {
+        IntRect rect = frame->view()->visibleContentRect();
+        if (!rect.contains(roundedIntPoint(point)))
+            return result;
+    }
+    frame->contentRenderer()->hitTest(HitTestRequest(hitType), result);
+    result.setToNonShadowAncestor();
+    return result;
+}
+
 bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
 {
     // First build up the lists to use for the 'touches', 'targetTouches' and 'changedTouches' attributes
@@ -3476,7 +3785,18 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
 
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
 
-    for (unsigned i = 0; i < points.size(); ++i) {
+    unsigned i;
+    bool freshTouchEvents = true;
+    bool allTouchReleased = true;
+    for (i = 0; i < points.size(); ++i) {
+        const PlatformTouchPoint& point = points[i];
+        if (point.state() != PlatformTouchPoint::TouchPressed)
+            freshTouchEvents = false;
+        if (point.state() != PlatformTouchPoint::TouchReleased && point.state() != PlatformTouchPoint::TouchCancelled)
+            allTouchReleased = false;
+    }
+
+    for (i = 0; i < points.size(); ++i) {
         const PlatformTouchPoint& point = points[i];
         PlatformTouchPoint::State pointState = point.state();
         LayoutPoint pagePoint = documentPointForWindowPoint(m_frame, point.pos());
@@ -3506,11 +3826,26 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
             break;
         }
 
+#if ENABLE(GESTURE_EVENTS)
+        if (shouldGesturesTriggerActive())
+            hitType |= HitTestRequest::ReadOnly;
+#endif
+
         // 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) {
-            HitTestResult result = hitTestResultAtPoint(pagePoint, /*allowShadowContent*/ false, false, DontHitTestScrollbars, hitType);
+            HitTestResult result;
+            if (freshTouchEvents) {
+                result = hitTestResultAtPoint(pagePoint, /*allowShadowContent*/ false, false, DontHitTestScrollbars, 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);
+                if (!result.innerNode())
+                    continue;
+            } else
+                continue;
             Node* node = result.innerNode();
             ASSERT(node);
 
@@ -3518,17 +3853,30 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
             if (node->isTextNode())
                 node = node->parentNode();
 
+            if (InspectorInstrumentation::handleTouchEvent(m_frame->page(), node))
+                return true;
+
             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;
+            }
             if (!doc)
                 continue;
-            if (!doc->hasListenerType(Document::TOUCH_LISTENER))
+            if (!doc->hasTouchEventHandlers())
                 continue;
-
             m_originatingTouchPointTargets.set(touchPointTargetKey, node);
             touchTarget = node;
         } else if (pointState == PlatformTouchPoint::TouchReleased || pointState == PlatformTouchPoint::TouchCancelled) {
             // We only perform a hittest on release or cancel to unset :active or :hover state.
-            hitTestResultAtPoint(pagePoint, /*allowShadowContent*/ false, false, DontHitTestScrollbars, hitType);
+            if (touchPointTargetKey == m_originatingTouchPointTargetKey) {
+                hitTestResultAtPoint(pagePoint, /*allowShadowContent*/ false, false, DontHitTestScrollbars, hitType);
+                m_originatingTouchPointTargetKey = 0;
+            } else if (m_originatingTouchPointDocument.get() && m_originatingTouchPointDocument->frame()) {
+                LayoutPoint pagePointInOriginatingDocument = documentPointForWindowPoint(m_originatingTouchPointDocument->frame(), point.pos());
+                hitTestResultInFrame(m_originatingTouchPointDocument->frame(), pagePointInOriginatingDocument, hitType);
+            }
             // 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);
@@ -3541,7 +3889,7 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
         Document* doc = touchTarget->toNode()->document();
         if (!doc)
             continue;
-        if (!doc->hasListenerType(Document::TOUCH_LISTENER))
+        if (!doc->hasTouchEventHandlers())
             continue;
         Frame* targetFrame = doc->frame();
         if (!targetFrame)
@@ -3571,7 +3919,7 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
         // released or cancelled it will only appear in the changedTouches list.
         if (pointState != PlatformTouchPoint::TouchReleased && pointState != PlatformTouchPoint::TouchCancelled) {
             touches->append(touch);
-            targetTouchesIterator->second->append(touch);
+            targetTouchesIterator->value->append(touch);
         }
 
         // Now build up the correct list for changedTouches.
@@ -3589,6 +3937,8 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
         }
     }
     m_touchPressed = touches->length() > 0;
+    if (allTouchReleased)
+        m_originatingTouchPointDocument.clear();
 
     // Now iterate the changedTouches list and m_targets within it, sending events to the targets as required.
     bool swallowedEvent = false;
@@ -3631,6 +3981,12 @@ bool EventHandler::dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent
         return false;
 
     if (eventType == PlatformEvent::MouseMoved && !m_touchPressed)
+        return true;
+
+    HitTestRequest request(HitTestRequest::Active);
+    MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
+
+    if (mev.scrollbar() || subframeForHitTestResult(mev))
         return false;
 
     SyntheticSingleTouchEvent touchEvent(event);
@@ -3639,4 +3995,11 @@ bool EventHandler::dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent
 
 #endif
 
+void EventHandler::setLastKnownMousePosition(const PlatformMouseEvent& event)
+{
+    m_mousePositionIsUnknown = false;
+    m_lastKnownMousePosition = event.position();
+    m_lastKnownMouseGlobalPosition = event.globalPosition();
 }
+
+} // namespace WebCore