7a511dd4eb90a9332b47bf3e302748a96cae1e93
[WebKit-https.git] / Source / WebCore / page / EventHandler.cpp
1 /*
2  * Copyright (C) 2006-2015 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
4  * Copyright (C) 2012 Digia Plc. and/or its subsidiary(-ies)
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
26  */
27
28 #include "config.h"
29 #include "EventHandler.h"
30
31 #include "AXObjectCache.h"
32 #include "AutoscrollController.h"
33 #include "BackForwardController.h"
34 #include "CachedImage.h"
35 #include "Chrome.h"
36 #include "ChromeClient.h"
37 #include "Cursor.h"
38 #include "CursorList.h"
39 #include "Document.h"
40 #include "DocumentEventQueue.h"
41 #include "DragController.h"
42 #include "DragState.h"
43 #include "Editor.h"
44 #include "EditorClient.h"
45 #include "EventNames.h"
46 #include "ExceptionCodePlaceholder.h"
47 #include "FileList.h"
48 #include "FloatPoint.h"
49 #include "FloatRect.h"
50 #include "FocusController.h"
51 #include "FrameLoader.h"
52 #include "FrameSelection.h"
53 #include "FrameTree.h"
54 #include "FrameView.h"
55 #include "htmlediting.h"
56 #include "HTMLFrameElementBase.h"
57 #include "HTMLFrameSetElement.h"
58 #include "HTMLInputElement.h"
59 #include "HTMLNames.h"
60 #include "HitTestRequest.h"
61 #include "HitTestResult.h"
62 #include "Image.h"
63 #include "InspectorInstrumentation.h"
64 #include "KeyboardEvent.h"
65 #include "MainFrame.h"
66 #include "MouseEvent.h"
67 #include "MouseEventWithHitTestResults.h"
68 #include "Page.h"
69 #include "PageOverlayController.h"
70 #include "PlatformEvent.h"
71 #include "PlatformKeyboardEvent.h"
72 #include "PlatformWheelEvent.h"
73 #include "PluginDocument.h"
74 #include "RenderFrameSet.h"
75 #include "RenderLayer.h"
76 #include "RenderListBox.h"
77 #include "RenderNamedFlowThread.h"
78 #include "RenderTextControlSingleLine.h"
79 #include "RenderView.h"
80 #include "RenderWidget.h"
81 #include "RuntimeApplicationChecks.h"
82 #include "SVGDocument.h"
83 #include "SVGNames.h"
84 #include "ScrollLatchingState.h"
85 #include "Scrollbar.h"
86 #include "Settings.h"
87 #include "ShadowRoot.h"
88 #include "SpatialNavigation.h"
89 #include "StyleCachedImage.h"
90 #include "TextEvent.h"
91 #include "TextIterator.h"
92 #include "UserGestureIndicator.h"
93 #include "UserTypingGestureIndicator.h"
94 #include "VisibleUnits.h"
95 #include "WheelEvent.h"
96 #include "WindowsKeyboardCodes.h"
97 #include <wtf/Assertions.h>
98 #include <wtf/CurrentTime.h>
99 #include <wtf/StdLibExtras.h>
100 #include <wtf/TemporaryChange.h>
101 #include <wtf/WeakPtr.h>
102
103 #if ENABLE(CSS_IMAGE_SET)
104 #include "StyleCachedImageSet.h"
105 #endif
106
107 #if ENABLE(IOS_TOUCH_EVENTS)
108 #include "PlatformTouchEventIOS.h"
109 #endif
110
111 #if ENABLE(TOUCH_EVENTS)
112 #include "TouchEvent.h"
113 #include "TouchList.h"
114 #endif
115
116 #if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
117 #include "PlatformTouchEvent.h"
118 #endif
119
120 namespace WebCore {
121
122 using namespace HTMLNames;
123
124 #if ENABLE(DRAG_SUPPORT)
125 // The link drag hysteresis is much larger than the others because there
126 // needs to be enough space to cancel the link press without starting a link drag,
127 // and because dragging links is rare.
128 const int LinkDragHysteresis = 40;
129 const int ImageDragHysteresis = 5;
130 const int TextDragHysteresis = 3;
131 const int GeneralDragHysteresis = 3;
132 #endif // ENABLE(DRAG_SUPPORT)
133
134 const std::chrono::milliseconds longMousePressRecognitionDelay = std::chrono::milliseconds(500);
135 const int maximumLongMousePressDragDistance = 5; // in points.
136
137 #if ENABLE(IOS_GESTURE_EVENTS)
138 const float GestureUnknown = 0;
139 #endif
140
141 #if ENABLE(IOS_TOUCH_EVENTS)
142 // FIXME: Share this constant with EventHandler and SliderThumbElement.
143 const unsigned InvalidTouchIdentifier = 0;
144 #endif
145
146 // Match key code of composition keydown event on windows.
147 // IE sends VK_PROCESSKEY which has value 229;
148 const int CompositionEventKeyCode = 229;
149
150 using namespace SVGNames;
151
152 #if !ENABLE(IOS_TOUCH_EVENTS)
153 // The amount of time to wait before sending a fake mouse event, triggered
154 // during a scroll. The short interval is used if the content responds to the mouse events
155 // in fakeMouseMoveDurationThreshold or less, otherwise the long interval is used.
156 const double fakeMouseMoveDurationThreshold = 0.01;
157 const double fakeMouseMoveShortInterval = 0.1;
158 const double fakeMouseMoveLongInterval = 0.25;
159 #endif
160
161 #if ENABLE(CURSOR_SUPPORT)
162 // The amount of time to wait for a cursor update on style and layout changes
163 // Set to 50Hz, no need to be faster than common screen refresh rate
164 const double cursorUpdateInterval = 0.02;
165
166 const int maximumCursorSize = 128;
167 #endif
168
169 #if ENABLE(MOUSE_CURSOR_SCALE)
170 // It's pretty unlikely that a scale of less than one would ever be used. But all we really
171 // need to ensure here is that the scale isn't so small that integer overflow can occur when
172 // dividing cursor sizes (limited above) by the scale.
173 const double minimumCursorScale = 0.001;
174 #endif
175
176 enum NoCursorChangeType { NoCursorChange };
177
178 class OptionalCursor {
179 public:
180     OptionalCursor(NoCursorChangeType) : m_isCursorChange(false) { }
181     OptionalCursor(const Cursor& cursor) : m_isCursorChange(true), m_cursor(cursor) { }
182
183     bool isCursorChange() const { return m_isCursorChange; }
184     const Cursor& cursor() const { ASSERT(m_isCursorChange); return m_cursor; }
185
186 private:
187     bool m_isCursorChange;
188     Cursor m_cursor;
189 };
190
191 class MaximumDurationTracker {
192 public:
193     explicit MaximumDurationTracker(double *maxDuration)
194         : m_maxDuration(maxDuration)
195         , m_start(monotonicallyIncreasingTime())
196     {
197     }
198
199     ~MaximumDurationTracker()
200     {
201         *m_maxDuration = std::max(*m_maxDuration, monotonicallyIncreasingTime() - m_start);
202     }
203
204 private:
205     double* m_maxDuration;
206     double m_start;
207 };
208
209 #if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
210 class SyntheticTouchPoint : public PlatformTouchPoint {
211 public:
212
213     // The default values are based on http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
214     explicit SyntheticTouchPoint(const PlatformMouseEvent& event)
215     {
216         const static int idDefaultValue = 0;
217         const static int radiusYDefaultValue = 1;
218         const static int radiusXDefaultValue = 1;
219         const static float rotationAngleDefaultValue = 0.0f;
220         const static float forceDefaultValue = 1.0f;
221
222         m_id = idDefaultValue; // There is only one active TouchPoint.
223         m_screenPos = event.globalPosition();
224         m_pos = event.position();
225         m_radiusY = radiusYDefaultValue;
226         m_radiusX = radiusXDefaultValue;
227         m_rotationAngle = rotationAngleDefaultValue;
228         m_force = forceDefaultValue;
229
230         PlatformEvent::Type type = event.type();
231         ASSERT(type == PlatformEvent::MouseMoved || type == PlatformEvent::MousePressed || type == PlatformEvent::MouseReleased);
232
233         switch (type) {
234         case PlatformEvent::MouseMoved:
235             m_state = TouchMoved;
236             break;
237         case PlatformEvent::MousePressed:
238             m_state = TouchPressed;
239             break;
240         case PlatformEvent::MouseReleased:
241             m_state = TouchReleased;
242             break;
243         default:
244             ASSERT_NOT_REACHED();
245             break;
246         }
247     }
248 };
249
250 class SyntheticSingleTouchEvent : public PlatformTouchEvent {
251 public:
252     explicit SyntheticSingleTouchEvent(const PlatformMouseEvent& event)
253     {
254         switch (event.type()) {
255         case PlatformEvent::MouseMoved:
256             m_type = TouchMove;
257             break;
258         case PlatformEvent::MousePressed:
259             m_type = TouchStart;
260             break;
261         case PlatformEvent::MouseReleased:
262             m_type = TouchEnd;
263             break;
264         default:
265             ASSERT_NOT_REACHED();
266             m_type = NoType;
267             break;
268         }
269         m_timestamp = event.timestamp();
270         m_modifiers = event.modifiers();
271         m_touchPoints.append(SyntheticTouchPoint(event));
272     }
273 };
274 #endif // ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
275
276 static inline ScrollGranularity wheelGranularityToScrollGranularity(unsigned deltaMode)
277 {
278     switch (deltaMode) {
279     case WheelEvent::DOM_DELTA_PAGE:
280         return ScrollByPage;
281     case WheelEvent::DOM_DELTA_LINE:
282         return ScrollByLine;
283     case WheelEvent::DOM_DELTA_PIXEL:
284         return ScrollByPixel;
285     default:
286         return ScrollByPixel;
287     }
288 }
289
290 static inline bool didScrollInScrollableAreaForSingleAxis(ScrollableArea* scrollableArea, WheelEvent* wheelEvent, ScrollEventAxis axis)
291 {
292     float delta = axis == ScrollEventAxis::Vertical ? wheelEvent->deltaY() : wheelEvent->deltaX();
293     ScrollDirection negativeDirection = axis == ScrollEventAxis::Vertical ? ScrollUp : ScrollLeft;
294     ScrollDirection positiveDirection = axis == ScrollEventAxis::Vertical ? ScrollDown : ScrollRight;
295     return scrollableArea->scroll(delta < 0 ? negativeDirection : positiveDirection, wheelGranularityToScrollGranularity(wheelEvent->deltaMode()), delta > 0 ? delta : -delta);
296 }
297
298 static inline bool handleWheelEventInAppropriateEnclosingBoxForSingleAxis(Node* startNode, WheelEvent* wheelEvent, Element** stopElement, ScrollEventAxis axis)
299 {
300     bool shouldHandleEvent = (axis == ScrollEventAxis::Vertical && wheelEvent->deltaY()) || (axis == ScrollEventAxis::Horizontal && wheelEvent->deltaX());
301 #if PLATFORM(MAC)
302     shouldHandleEvent |= wheelEvent->phase() == PlatformWheelEventPhaseEnded;
303 #if ENABLE(CSS_SCROLL_SNAP)
304     shouldHandleEvent |= wheelEvent->momentumPhase() == PlatformWheelEventPhaseEnded;
305 #endif
306 #endif
307     if (!startNode->renderer() || !shouldHandleEvent)
308         return false;
309
310     RenderBox& initialEnclosingBox = startNode->renderer()->enclosingBox();
311     if (initialEnclosingBox.isListBox())
312         return didScrollInScrollableAreaForSingleAxis(static_cast<RenderListBox*>(&initialEnclosingBox), wheelEvent, axis);
313
314     RenderBox* currentEnclosingBox = &initialEnclosingBox;
315     while (currentEnclosingBox) {
316         if (RenderLayer* boxLayer = currentEnclosingBox->layer()) {
317             const PlatformWheelEvent* platformEvent = wheelEvent->wheelEvent();
318             bool scrollingWasHandled;
319             if (platformEvent != nullptr)
320                 scrollingWasHandled = boxLayer->handleWheelEvent(axis == ScrollEventAxis::Vertical ? platformEvent->copyIgnoringHorizontalDelta() : platformEvent->copyIgnoringVerticalDelta());
321             else
322                 scrollingWasHandled = didScrollInScrollableAreaForSingleAxis(boxLayer, wheelEvent, axis);
323
324             if (scrollingWasHandled) {
325                 if (stopElement)
326                     *stopElement = currentEnclosingBox->element();
327                 return true;
328             }
329         }
330
331         if (stopElement && *stopElement && *stopElement == currentEnclosingBox->element())
332             return true;
333
334         currentEnclosingBox = currentEnclosingBox->containingBlock();
335         if (currentEnclosingBox && currentEnclosingBox->isRenderNamedFlowThread())
336             currentEnclosingBox = RenderNamedFlowThread::fragmentFromRenderBoxAsRenderBlock(currentEnclosingBox, roundedIntPoint(wheelEvent->absoluteLocation()), initialEnclosingBox);
337         if (!currentEnclosingBox || currentEnclosingBox->isRenderView())
338             return false;
339     }
340     return false;
341 }
342
343 #if (ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS))
344 static inline bool shouldGesturesTriggerActive()
345 {
346     // If the platform we're on supports GestureTapDown and GestureTapCancel then we'll
347     // rely on them to set the active state. Unfortunately there's no generic way to
348     // know in advance what event types are supported.
349     return false;
350 }
351 #endif
352
353 #if !PLATFORM(COCOA)
354
355 inline bool EventHandler::eventLoopHandleMouseUp(const MouseEventWithHitTestResults&)
356 {
357     return false;
358 }
359
360 #if ENABLE(DRAG_SUPPORT)
361 inline bool EventHandler::eventLoopHandleMouseDragged(const MouseEventWithHitTestResults&)
362 {
363     return false;
364 }
365 #endif
366
367 #endif
368
369 EventHandler::EventHandler(Frame& frame)
370     : m_frame(frame)
371     , m_mousePressed(false)
372     , m_capturesDragging(false)
373     , m_mouseDownMayStartSelect(false)
374 #if ENABLE(DRAG_SUPPORT)
375     , m_mouseDownMayStartDrag(false)
376     , m_dragMayStartSelectionInstead(false)
377 #endif
378     , m_mouseDownWasSingleClickInSelection(false)
379     , m_selectionInitiationState(HaveNotStartedSelection)
380     , m_hoverTimer(*this, &EventHandler::hoverTimerFired)
381 #if ENABLE(CURSOR_SUPPORT)
382     , m_cursorUpdateTimer(*this, &EventHandler::cursorUpdateTimerFired)
383 #endif
384     , m_longMousePressTimer(*this, &EventHandler::recognizeLongMousePress)
385     , m_didRecognizeLongMousePress(false)
386     , m_autoscrollController(std::make_unique<AutoscrollController>())
387     , m_mouseDownMayStartAutoscroll(false)
388     , m_mouseDownWasInSubframe(false)
389 #if !ENABLE(IOS_TOUCH_EVENTS)
390     , m_fakeMouseMoveEventTimer(*this, &EventHandler::fakeMouseMoveEventTimerFired)
391 #endif
392     , m_svgPan(false)
393     , m_resizeLayer(nullptr)
394     , m_eventHandlerWillResetCapturingMouseEventsElement(false)
395     , m_clickCount(0)
396 #if ENABLE(IOS_GESTURE_EVENTS)
397     , m_gestureInitialDiameter(GestureUnknown)
398     , m_gestureLastDiameter(GestureUnknown)
399     , m_gestureInitialRotation(GestureUnknown)
400     , m_gestureLastRotation(GestureUnknown)
401 #endif
402 #if ENABLE(IOS_TOUCH_EVENTS)
403     , m_firstTouchID(InvalidTouchIdentifier)
404 #endif
405     , m_mousePositionIsUnknown(true)
406     , m_mouseDownTimestamp(0)
407 #if PLATFORM(COCOA)
408     , m_mouseDownView(nil)
409     , m_sendingEventToSubview(false)
410 #if !PLATFORM(IOS)
411     , m_activationEventNumber(-1)
412 #endif // !PLATFORM(IOS)
413 #endif
414 #if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
415     , m_originatingTouchPointTargetKey(0)
416     , m_touchPressed(false)
417 #endif
418     , m_maxMouseMovedDuration(0)
419     , m_baseEventType(PlatformEvent::NoType)
420     , m_didStartDrag(false)
421     , m_didLongPressInvokeContextMenu(false)
422     , m_isHandlingWheelEvent(false)
423 #if ENABLE(CURSOR_VISIBILITY)
424     , m_autoHideCursorTimer(*this, &EventHandler::autoHideCursorTimerFired)
425 #endif
426     , m_immediateActionStage(ImmediateActionStage::None)
427 {
428 }
429
430 EventHandler::~EventHandler()
431 {
432 #if !ENABLE(IOS_TOUCH_EVENTS)
433     ASSERT(!m_fakeMouseMoveEventTimer.isActive());
434 #endif
435 #if ENABLE(CURSOR_VISIBILITY)
436     ASSERT(!m_autoHideCursorTimer.isActive());
437 #endif
438 }
439     
440 #if ENABLE(DRAG_SUPPORT)
441 DragState& EventHandler::dragState()
442 {
443     DEPRECATED_DEFINE_STATIC_LOCAL(DragState, state, ());
444     return state;
445 }
446 #endif // ENABLE(DRAG_SUPPORT)
447     
448 void EventHandler::clear()
449 {
450     m_hoverTimer.stop();
451 #if ENABLE(CURSOR_SUPPORT)
452     m_cursorUpdateTimer.stop();
453 #endif
454 #if !ENABLE(IOS_TOUCH_EVENTS)
455     m_fakeMouseMoveEventTimer.stop();
456 #endif
457 #if ENABLE(CURSOR_VISIBILITY)
458     cancelAutoHideCursorTimer();
459 #endif
460     clearLongMousePressState();
461     m_resizeLayer = nullptr;
462     m_elementUnderMouse = nullptr;
463     m_lastElementUnderMouse = nullptr;
464     m_lastMouseMoveEventSubframe = nullptr;
465     m_lastScrollbarUnderMouse = nullptr;
466     m_clickCount = 0;
467     m_clickNode = nullptr;
468 #if ENABLE(IOS_GESTURE_EVENTS)
469     m_gestureInitialDiameter = GestureUnknown;
470     m_gestureLastDiameter = GestureUnknown;
471     m_gestureInitialRotation = GestureUnknown;
472     m_gestureLastRotation = GestureUnknown;
473     m_gestureTargets.clear();
474 #endif
475 #if ENABLE(IOS_TOUCH_EVENTS)
476     m_touches.clear();
477     m_firstTouchID = InvalidTouchIdentifier;
478     m_touchEventTargetSubframe = nullptr;
479 #endif
480     m_frameSetBeingResized = nullptr;
481 #if ENABLE(DRAG_SUPPORT)
482     m_dragTarget = nullptr;
483     m_shouldOnlyFireDragOverEvent = false;
484 #endif
485     m_mousePositionIsUnknown = true;
486     m_lastKnownMousePosition = IntPoint();
487     m_lastKnownMouseGlobalPosition = IntPoint();
488     m_mousePressNode = nullptr;
489     m_mousePressed = false;
490     m_capturesDragging = false;
491     m_capturingMouseEventsElement = nullptr;
492 #if PLATFORM(MAC)
493     m_frame.mainFrame().resetLatchingState();
494 #endif
495 #if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
496     m_originatingTouchPointTargets.clear();
497     m_originatingTouchPointDocument = nullptr;
498     m_originatingTouchPointTargetKey = 0;
499 #endif
500     m_maxMouseMovedDuration = 0;
501     m_baseEventType = PlatformEvent::NoType;
502     m_didStartDrag = false;
503     m_didLongPressInvokeContextMenu = false;
504 }
505
506 void EventHandler::nodeWillBeRemoved(Node& nodeToBeRemoved)
507 {
508     if (nodeToBeRemoved.contains(m_clickNode.get()))
509         m_clickNode = nullptr;
510 }
511
512 static void setSelectionIfNeeded(FrameSelection& selection, const VisibleSelection& newSelection)
513 {
514     if (selection.selection() != newSelection && selection.shouldChangeSelection(newSelection))
515         selection.setSelection(newSelection);
516 }
517
518 static inline bool dispatchSelectStart(Node* node)
519 {
520     if (!node || !node->renderer())
521         return true;
522
523     return node->dispatchEvent(Event::create(eventNames().selectstartEvent, true, true));
524 }
525
526 static Node* nodeToSelectOnMouseDownForNode(Node& targetNode)
527 {
528 #if ENABLE(USERSELECT_ALL)
529     if (Node* rootUserSelectAll = Position::rootUserSelectAllForNode(&targetNode))
530         return rootUserSelectAll;
531 #endif
532
533     if (targetNode.shouldSelectOnMouseDown())
534         return &targetNode;
535
536     return nullptr;
537 }
538
539 static VisibleSelection expandSelectionToRespectSelectOnMouseDown(Node& targetNode, const VisibleSelection& selection)
540 {
541     Node* nodeToSelect = nodeToSelectOnMouseDownForNode(targetNode);
542     if (!nodeToSelect)
543         return selection;
544
545     VisibleSelection newSelection(selection);
546     newSelection.setBase(positionBeforeNode(nodeToSelect).upstream(CanCrossEditingBoundary));
547     newSelection.setExtent(positionAfterNode(nodeToSelect).downstream(CanCrossEditingBoundary));
548
549     return newSelection;
550 }
551
552 bool EventHandler::updateSelectionForMouseDownDispatchingSelectStart(Node* targetNode, const VisibleSelection& selection, TextGranularity granularity)
553 {
554     if (Position::nodeIsUserSelectNone(targetNode))
555         return false;
556
557     if (!dispatchSelectStart(targetNode))
558         return false;
559
560     if (selection.isRange())
561         m_selectionInitiationState = ExtendedSelection;
562     else {
563         granularity = CharacterGranularity;
564         m_selectionInitiationState = PlacedCaret;
565     }
566
567     m_frame.selection().setSelectionByMouseIfDifferent(selection, granularity);
568
569     return true;
570 }
571
572 void EventHandler::selectClosestWordFromHitTestResult(const HitTestResult& result, AppendTrailingWhitespace appendTrailingWhitespace)
573 {
574     Node* targetNode = result.targetNode();
575     VisibleSelection newSelection;
576
577     if (targetNode && targetNode->renderer()) {
578         VisiblePosition pos(targetNode->renderer()->positionForPoint(result.localPoint(), nullptr));
579         if (pos.isNotNull()) {
580             newSelection = VisibleSelection(pos);
581             newSelection.expandUsingGranularity(WordGranularity);
582         }
583
584         if (appendTrailingWhitespace == ShouldAppendTrailingWhitespace && newSelection.isRange())
585             newSelection.appendTrailingWhitespace();
586
587         updateSelectionForMouseDownDispatchingSelectStart(targetNode, expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), WordGranularity);
588     }
589 }
590
591 static AppendTrailingWhitespace shouldAppendTrailingWhitespace(const MouseEventWithHitTestResults& result, const Frame& frame)
592 {
593     return (result.event().clickCount() == 2 && frame.editor().isSelectTrailingWhitespaceEnabled()) ? ShouldAppendTrailingWhitespace : DontAppendTrailingWhitespace;
594 }
595
596 void EventHandler::selectClosestWordFromMouseEvent(const MouseEventWithHitTestResults& result)
597 {
598     if (m_mouseDownMayStartSelect)
599         selectClosestWordFromHitTestResult(result.hitTestResult(), shouldAppendTrailingWhitespace(result, m_frame));
600 }
601
602 #if !PLATFORM(MAC)
603 VisibleSelection EventHandler::selectClosestWordFromHitTestResultBasedOnLookup(const HitTestResult&)
604 {
605     return VisibleSelection();
606 }
607 #endif
608     
609 void EventHandler::selectClosestContextualWordFromMouseEvent(const MouseEventWithHitTestResults& mouseEvent)
610 {
611     Node* targetNode = mouseEvent.targetNode();
612     const HitTestResult& result = mouseEvent.hitTestResult();
613     VisibleSelection newSelection;
614     bool appendTrailingWhitespace = shouldAppendTrailingWhitespace(mouseEvent, m_frame);
615     
616     if (targetNode && targetNode->renderer()) {
617         newSelection = selectClosestWordFromHitTestResultBasedOnLookup(result);
618         if (newSelection.isNone()) {
619             VisiblePosition pos(targetNode->renderer()->positionForPoint(result.localPoint(), nullptr));
620             if (pos.isNotNull()) {
621                 newSelection = VisibleSelection(pos);
622                 newSelection.expandUsingGranularity(WordGranularity);
623             }
624         }
625         
626         if (appendTrailingWhitespace == ShouldAppendTrailingWhitespace && newSelection.isRange())
627             newSelection.appendTrailingWhitespace();
628         
629         updateSelectionForMouseDownDispatchingSelectStart(targetNode, expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), WordGranularity);
630     }
631 }
632     
633 void EventHandler::selectClosestContextualWordOrLinkFromMouseEvent(const MouseEventWithHitTestResults& result)
634 {
635     Element* urlElement = result.hitTestResult().URLElement();
636     if (!urlElement || !isDraggableLink(*urlElement)) {
637         if (Node* targetNode = result.targetNode()) {
638             if (isEditableNode(*targetNode))
639                 return selectClosestWordFromMouseEvent(result);
640         }
641
642         return selectClosestContextualWordFromMouseEvent(result);
643     }
644
645     Node* targetNode = result.targetNode();
646
647     if (targetNode && targetNode->renderer() && m_mouseDownMayStartSelect) {
648         VisibleSelection newSelection;
649         VisiblePosition pos(targetNode->renderer()->positionForPoint(result.localPoint(), nullptr));
650         if (pos.isNotNull() && pos.deepEquivalent().deprecatedNode()->isDescendantOf(urlElement))
651             newSelection = VisibleSelection::selectionFromContentsOfNode(urlElement);
652
653         updateSelectionForMouseDownDispatchingSelectStart(targetNode, expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), WordGranularity);
654     }
655 }
656
657 bool EventHandler::handleMousePressEventDoubleClick(const MouseEventWithHitTestResults& event)
658 {
659     if (event.event().button() != LeftButton)
660         return false;
661
662     if (m_frame.selection().isRange())
663         // A double-click when range is already selected
664         // should not change the selection.  So, do not call
665         // selectClosestWordFromMouseEvent, but do set
666         // m_beganSelectingText to prevent handleMouseReleaseEvent
667         // from setting caret selection.
668         m_selectionInitiationState = ExtendedSelection;
669     else
670         selectClosestWordFromMouseEvent(event);
671
672     return true;
673 }
674
675 bool EventHandler::handleMousePressEventTripleClick(const MouseEventWithHitTestResults& event)
676 {
677     if (event.event().button() != LeftButton)
678         return false;
679     
680     Node* targetNode = event.targetNode();
681     if (!(targetNode && targetNode->renderer() && m_mouseDownMayStartSelect))
682         return false;
683
684     VisibleSelection newSelection;
685     VisiblePosition pos(targetNode->renderer()->positionForPoint(event.localPoint(), nullptr));
686     if (pos.isNotNull()) {
687         newSelection = VisibleSelection(pos);
688         newSelection.expandUsingGranularity(ParagraphGranularity);
689     }
690
691     return updateSelectionForMouseDownDispatchingSelectStart(targetNode, expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), ParagraphGranularity);
692 }
693
694 static int textDistance(const Position& start, const Position& end)
695 {
696     RefPtr<Range> range = Range::create(start.anchorNode()->document(), start, end);
697     return TextIterator::rangeLength(range.get(), true);
698 }
699
700 bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
701 {
702     m_frame.document()->updateLayoutIgnorePendingStylesheets();
703     Node* targetNode = event.targetNode();
704     if (!(targetNode && targetNode->renderer() && m_mouseDownMayStartSelect))
705         return false;
706
707     // Extend the selection if the Shift key is down, unless the click is in a link.
708     bool extendSelection = event.event().shiftKey() && !event.isOverLink();
709
710     // Don't restart the selection when the mouse is pressed on an
711     // existing selection so we can allow for text dragging.
712     if (FrameView* view = m_frame.view()) {
713         LayoutPoint vPoint = view->windowToContents(event.event().position());
714         if (!extendSelection && m_frame.selection().contains(vPoint)) {
715             m_mouseDownWasSingleClickInSelection = true;
716             return false;
717         }
718     }
719
720     VisiblePosition visiblePos(targetNode->renderer()->positionForPoint(event.localPoint(), nullptr));
721     if (visiblePos.isNull())
722         visiblePos = VisiblePosition(firstPositionInOrBeforeNode(targetNode), DOWNSTREAM);
723     Position pos = visiblePos.deepEquivalent();
724
725     VisibleSelection newSelection = m_frame.selection().selection();
726     TextGranularity granularity = CharacterGranularity;
727
728     if (extendSelection && newSelection.isCaretOrRange()) {
729         VisibleSelection selectionInUserSelectAll = expandSelectionToRespectSelectOnMouseDown(*targetNode, VisibleSelection(pos));
730         if (selectionInUserSelectAll.isRange()) {
731             if (comparePositions(selectionInUserSelectAll.start(), newSelection.start()) < 0)
732                 pos = selectionInUserSelectAll.start();
733             else if (comparePositions(newSelection.end(), selectionInUserSelectAll.end()) < 0)
734                 pos = selectionInUserSelectAll.end();
735         }
736
737         if (!m_frame.editor().behavior().shouldConsiderSelectionAsDirectional() && pos.isNotNull()) {
738             // See <rdar://problem/3668157> REGRESSION (Mail): shift-click deselects when selection
739             // was created right-to-left
740             Position start = newSelection.start();
741             Position end = newSelection.end();
742             int distanceToStart = textDistance(start, pos);
743             int distanceToEnd = textDistance(pos, end);
744             if (distanceToStart <= distanceToEnd)
745                 newSelection = VisibleSelection(end, pos);
746             else
747                 newSelection = VisibleSelection(start, pos);
748         } else
749             newSelection.setExtent(pos);
750
751         if (m_frame.selection().granularity() != CharacterGranularity) {
752             granularity = m_frame.selection().granularity();
753             newSelection.expandUsingGranularity(m_frame.selection().granularity());
754         }
755     } else
756         newSelection = expandSelectionToRespectSelectOnMouseDown(*targetNode, visiblePos);
757
758     bool handled = updateSelectionForMouseDownDispatchingSelectStart(targetNode, newSelection, granularity);
759
760     if (event.event().button() == MiddleButton) {
761         // Ignore handled, since we want to paste to where the caret was placed anyway.
762         handled = handlePasteGlobalSelection(event.event()) || handled;
763     }
764     return handled;
765 }
766
767 static inline bool canMouseDownStartSelect(Node* node)
768 {
769     if (!node || !node->renderer())
770         return true;
771
772     return node->canStartSelection() || Position::nodeIsUserSelectAll(node);
773 }
774
775 bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& event)
776 {
777 #if ENABLE(DRAG_SUPPORT)
778     // Reset drag state.
779     dragState().source = nullptr;
780 #endif
781
782 #if !ENABLE(IOS_TOUCH_EVENTS)
783     cancelFakeMouseMoveEvent();
784 #endif
785
786     m_frame.document()->updateLayoutIgnorePendingStylesheets();
787
788     if (ScrollView* scrollView = m_frame.view()) {
789         if (scrollView->isPointInScrollbarCorner(event.event().position()))
790             return false;
791     }
792
793     bool singleClick = event.event().clickCount() <= 1;
794
795     // If we got the event back, that must mean it wasn't prevented,
796     // so it's allowed to start a drag or selection if it wasn't in a scrollbar.
797     m_mouseDownMayStartSelect = canMouseDownStartSelect(event.targetNode()) && !event.scrollbar();
798     
799 #if ENABLE(DRAG_SUPPORT)
800     // Careful that the drag starting logic stays in sync with eventMayStartDrag()
801     m_mouseDownMayStartDrag = singleClick;
802 #endif
803
804     m_mouseDownWasSingleClickInSelection = false;
805
806     m_mouseDown = event.event();
807
808     if (m_immediateActionStage != ImmediateActionStage::PerformedHitTest)
809         m_immediateActionStage = ImmediateActionStage::None;
810
811     if (event.isOverWidget() && passWidgetMouseDownEventToWidget(event))
812         return true;
813
814     if (is<SVGDocument>(*m_frame.document()) && downcast<SVGDocument>(*m_frame.document()).zoomAndPanEnabled()) {
815         if (event.event().shiftKey() && singleClick) {
816             m_svgPan = true;
817             downcast<SVGDocument>(*m_frame.document()).startPan(m_frame.view()->windowToContents(event.event().position()));
818             return true;
819         }
820     }
821
822     if (event.event().button() == LeftButton && event.isOverLink()) {
823         // FIXME 135703: Handle long press for more than just links.
824         beginTrackingPotentialLongMousePress(event.hitTestResult());
825     }
826
827     // We don't do this at the start of mouse down handling,
828     // because we don't want to do it until we know we didn't hit a widget.
829     if (singleClick)
830         focusDocumentView();
831
832     m_mousePressNode = event.targetNode();
833 #if ENABLE(DRAG_SUPPORT)
834     m_dragStartPos = event.event().position();
835 #endif
836
837     bool swallowEvent = false;
838     m_mousePressed = true;
839     m_selectionInitiationState = HaveNotStartedSelection;
840
841     if (event.event().clickCount() == 2)
842         swallowEvent = handleMousePressEventDoubleClick(event);
843     else if (event.event().clickCount() >= 3)
844         swallowEvent = handleMousePressEventTripleClick(event);
845     else
846         swallowEvent = handleMousePressEventSingleClick(event);
847     
848     m_mouseDownMayStartAutoscroll = m_mouseDownMayStartSelect
849         || (m_mousePressNode && m_mousePressNode->renderBox() && m_mousePressNode->renderBox()->canBeProgramaticallyScrolled());
850
851     return swallowEvent;
852 }
853
854 #if ENABLE(DRAG_SUPPORT)
855 bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& event)
856 {
857     if (!m_mousePressed)
858         return false;
859
860     if (handleDrag(event, ShouldCheckDragHysteresis))
861         return true;
862
863     Node* targetNode = event.targetNode();
864     if (event.event().button() != LeftButton || !targetNode)
865         return false;
866
867     RenderObject* renderer = targetNode->renderer();
868     if (!renderer) {
869         Element* parent = targetNode->parentOrShadowHostElement();
870         if (!parent)
871             return false;
872
873         renderer = parent->renderer();
874         if (!renderer || !renderer->isListBox())
875             return false;
876     }
877
878 #if PLATFORM(COCOA) // FIXME: Why does this assertion fire on other platforms?
879     ASSERT(m_mouseDownMayStartSelect || m_mouseDownMayStartAutoscroll);
880 #endif
881
882     m_mouseDownMayStartDrag = false;
883
884     if (m_mouseDownMayStartAutoscroll && !panScrollInProgress()) {
885         m_autoscrollController->startAutoscrollForSelection(renderer);
886         m_mouseDownMayStartAutoscroll = false;
887     }
888
889     if (m_selectionInitiationState != ExtendedSelection) {
890         HitTestResult result(m_mouseDownPos);
891         m_frame.document()->renderView()->hitTest(HitTestRequest(), result);
892
893         updateSelectionForMouseDrag(result);
894     }
895     updateSelectionForMouseDrag(event.hitTestResult());
896     return true;
897 }
898     
899 bool EventHandler::eventMayStartDrag(const PlatformMouseEvent& event) const
900 {
901     // This is a pre-flight check of whether the event might lead to a drag being started.  Be careful
902     // that its logic needs to stay in sync with handleMouseMoveEvent() and the way we setMouseDownMayStartDrag
903     // in handleMousePressEvent
904     RenderView* renderView = m_frame.contentRenderer();
905     if (!renderView)
906         return false;
907
908     if (event.button() != LeftButton || event.clickCount() != 1)
909         return false;
910
911     if (m_didRecognizeLongMousePress)
912         return false;
913     
914     FrameView* view = m_frame.view();
915     if (!view)
916         return false;
917
918     Page* page = m_frame.page();
919     if (!page)
920         return false;
921
922     updateDragSourceActionsAllowed();
923     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
924     HitTestResult result(view->windowToContents(event.position()));
925     renderView->hitTest(request, result);
926     DragState state;
927     return result.innerElement() && page->dragController().draggableElement(&m_frame, result.innerElement(), result.roundedPointInInnerNodeFrame(), state);
928 }
929
930 void EventHandler::updateSelectionForMouseDrag()
931 {
932     FrameView* view = m_frame.view();
933     if (!view)
934         return;
935     RenderView* renderView = m_frame.contentRenderer();
936     if (!renderView)
937         return;
938
939     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::Move | HitTestRequest::DisallowShadowContent);
940     HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
941     renderView->hitTest(request, result);
942     updateSelectionForMouseDrag(result);
943 }
944
945 static VisiblePosition selectionExtentRespectingEditingBoundary(const VisibleSelection& selection, const LayoutPoint& localPoint, Node* targetNode)
946 {
947     FloatPoint selectionEndPoint = localPoint;
948     Element* editableElement = selection.rootEditableElement();
949
950     if (!targetNode->renderer())
951         return VisiblePosition();
952
953     if (editableElement && !editableElement->contains(targetNode)) {
954         if (!editableElement->renderer())
955             return VisiblePosition();
956
957         FloatPoint absolutePoint = targetNode->renderer()->localToAbsolute(FloatPoint(selectionEndPoint));
958         selectionEndPoint = editableElement->renderer()->absoluteToLocal(absolutePoint);
959         targetNode = editableElement;
960     }
961
962     return targetNode->renderer()->positionForPoint(LayoutPoint(selectionEndPoint), nullptr);
963 }
964
965 void EventHandler::updateSelectionForMouseDrag(const HitTestResult& hitTestResult)
966 {
967     if (!m_mouseDownMayStartSelect)
968         return;
969
970     Node* target = hitTestResult.targetNode();
971     if (!target)
972         return;
973
974     VisiblePosition targetPosition = selectionExtentRespectingEditingBoundary(m_frame.selection().selection(), hitTestResult.localPoint(), target);
975
976     // Don't modify the selection if we're not on a node.
977     if (targetPosition.isNull())
978         return;
979
980     // Restart the selection if this is the first mouse move. This work is usually
981     // done in handleMousePressEvent, but not if the mouse press was on an existing selection.
982     VisibleSelection newSelection = m_frame.selection().selection();
983
984     // Special case to limit selection to the containing block for SVG text.
985     // FIXME: Isn't there a better non-SVG-specific way to do this?
986     if (Node* selectionBaseNode = newSelection.base().deprecatedNode())
987         if (RenderObject* selectionBaseRenderer = selectionBaseNode->renderer())
988             if (selectionBaseRenderer->isSVGText())
989                 if (target->renderer()->containingBlock() != selectionBaseRenderer->containingBlock())
990                     return;
991
992     if (m_selectionInitiationState == HaveNotStartedSelection && !dispatchSelectStart(target))
993         return;
994
995     if (m_selectionInitiationState != ExtendedSelection) {
996         // Always extend selection here because it's caused by a mouse drag
997         m_selectionInitiationState = ExtendedSelection;
998         newSelection = VisibleSelection(targetPosition);
999     }
1000
1001 #if ENABLE(USERSELECT_ALL)
1002     Node* rootUserSelectAllForMousePressNode = Position::rootUserSelectAllForNode(m_mousePressNode.get());
1003     if (rootUserSelectAllForMousePressNode && rootUserSelectAllForMousePressNode == Position::rootUserSelectAllForNode(target)) {
1004         newSelection.setBase(positionBeforeNode(rootUserSelectAllForMousePressNode).upstream(CanCrossEditingBoundary));
1005         newSelection.setExtent(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
1006     } else {
1007         // Reset base for user select all when base is inside user-select-all area and extent < base.
1008         if (rootUserSelectAllForMousePressNode && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint(), nullptr), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos, nullptr)) < 0)
1009             newSelection.setBase(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
1010         
1011         Node* rootUserSelectAllForTarget = Position::rootUserSelectAllForNode(target);
1012         if (rootUserSelectAllForTarget && m_mousePressNode->renderer() && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint(), nullptr), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos, nullptr)) < 0)
1013             newSelection.setExtent(positionBeforeNode(rootUserSelectAllForTarget).upstream(CanCrossEditingBoundary));
1014         else if (rootUserSelectAllForTarget && m_mousePressNode->renderer())
1015             newSelection.setExtent(positionAfterNode(rootUserSelectAllForTarget).downstream(CanCrossEditingBoundary));
1016         else
1017             newSelection.setExtent(targetPosition);
1018     }
1019 #else
1020     newSelection.setExtent(targetPosition);
1021 #endif
1022
1023     if (m_frame.selection().granularity() != CharacterGranularity)
1024         newSelection.expandUsingGranularity(m_frame.selection().granularity());
1025
1026     m_frame.selection().setSelectionByMouseIfDifferent(newSelection, m_frame.selection().granularity(),
1027         FrameSelection::AdjustEndpointsAtBidiBoundary);
1028 }
1029 #endif // ENABLE(DRAG_SUPPORT)
1030
1031 void EventHandler::lostMouseCapture()
1032 {
1033     m_frame.selection().setCaretBlinkingSuspended(false);
1034 }
1035
1036 bool EventHandler::handleMouseUp(const MouseEventWithHitTestResults& event)
1037 {
1038     if (eventLoopHandleMouseUp(event))
1039         return true;
1040     
1041     // If this was the first click in the window, we don't even want to clear the selection.
1042     // This case occurs when the user clicks on a draggable element, since we have to process
1043     // the mouse down and drag events to see if we might start a drag.  For other first clicks
1044     // in a window, we just don't acceptFirstMouse, and the whole down-drag-up sequence gets
1045     // ignored upstream of this layer.
1046     return eventActivatedView(event.event());
1047 }    
1048
1049 bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& event)
1050 {
1051     if (autoscrollInProgress())
1052         stopAutoscrollTimer();
1053
1054     if (handleMouseUp(event))
1055         return true;
1056
1057     // Used to prevent mouseMoveEvent from initiating a drag before
1058     // the mouse is pressed again.
1059     m_mousePressed = false;
1060     m_capturesDragging = false;
1061 #if ENABLE(DRAG_SUPPORT)
1062     m_mouseDownMayStartDrag = false;
1063 #endif
1064     m_mouseDownMayStartSelect = false;
1065     m_mouseDownMayStartAutoscroll = false;
1066     m_mouseDownWasInSubframe = false;
1067   
1068     bool handled = false;
1069     
1070     if (event.event().button() == LeftButton) {
1071         // FIXME 135767: Implement long mouse press for arbitrary mouse buttons.
1072         clearLongMousePressState();
1073     }
1074
1075     // Clear the selection if the mouse didn't move after the last mouse
1076     // press and it's not a context menu click.  We do this so when clicking
1077     // on the selection, the selection goes away.  However, if we are
1078     // editing, place the caret.
1079     if (m_mouseDownWasSingleClickInSelection && m_selectionInitiationState != ExtendedSelection
1080 #if ENABLE(DRAG_SUPPORT)
1081             && m_dragStartPos == event.event().position()
1082 #endif
1083             && m_frame.selection().isRange()
1084             && event.event().button() != RightButton) {
1085         VisibleSelection newSelection;
1086         Node* node = event.targetNode();
1087         bool caretBrowsing = m_frame.settings().caretBrowsingEnabled();
1088         if (node && node->renderer() && (caretBrowsing || node->hasEditableStyle())) {
1089             VisiblePosition pos = node->renderer()->positionForPoint(event.localPoint(), nullptr);
1090             newSelection = VisibleSelection(pos);
1091         }
1092
1093         setSelectionIfNeeded(m_frame.selection(), newSelection);
1094
1095         handled = true;
1096     }
1097
1098     if (event.event().button() == MiddleButton) {
1099         // Ignore handled, since we want to paste to where the caret was placed anyway.
1100         handled = handlePasteGlobalSelection(event.event()) || handled;
1101     }
1102
1103     return handled;
1104 }
1105
1106 #if ENABLE(PAN_SCROLLING)
1107
1108 void EventHandler::didPanScrollStart()
1109 {
1110     m_autoscrollController->didPanScrollStart();
1111 }
1112
1113 void EventHandler::didPanScrollStop()
1114 {
1115     m_autoscrollController->didPanScrollStop();
1116 }
1117
1118 void EventHandler::startPanScrolling(RenderElement* renderer)
1119 {
1120 #if !PLATFORM(IOS)
1121     if (!is<RenderBox>(*renderer))
1122         return;
1123     m_autoscrollController->startPanScrolling(downcast<RenderBox>(renderer), lastKnownMousePosition());
1124     invalidateClick();
1125 #endif
1126 }
1127
1128 #endif // ENABLE(PAN_SCROLLING)
1129
1130 RenderBox* EventHandler::autoscrollRenderer() const
1131 {
1132     return m_autoscrollController->autoscrollRenderer();
1133 }
1134
1135 void EventHandler::updateAutoscrollRenderer()
1136 {
1137     m_autoscrollController->updateAutoscrollRenderer();
1138 }
1139
1140 bool EventHandler::autoscrollInProgress() const
1141 {
1142     return m_autoscrollController->autoscrollInProgress();
1143 }
1144
1145 bool EventHandler::panScrollInProgress() const
1146 {
1147     return m_autoscrollController->panScrollInProgress();
1148 }
1149
1150 #if ENABLE(DRAG_SUPPORT)
1151 DragSourceAction EventHandler::updateDragSourceActionsAllowed() const
1152 {
1153     Page* page = m_frame.page();
1154     if (!page)
1155         return DragSourceActionNone;
1156
1157     FrameView* view = m_frame.view();
1158     if (!view)
1159         return DragSourceActionNone;
1160
1161     return page->dragController().delegateDragSourceAction(view->contentsToRootView(m_mouseDownPos));
1162 }
1163 #endif // ENABLE(DRAG_SUPPORT)
1164
1165 HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, HitTestRequest::HitTestRequestType hitType, const LayoutSize& padding)
1166 {
1167     // We always send hitTestResultAtPoint to the main frame if we have one,
1168     // otherwise we might hit areas that are obscured by higher frames.
1169     if (!m_frame.isMainFrame()) {
1170         Frame& mainFrame = m_frame.mainFrame();
1171         FrameView* frameView = m_frame.view();
1172         FrameView* mainView = mainFrame.view();
1173         if (frameView && mainView) {
1174             IntPoint mainFramePoint = mainView->rootViewToContents(frameView->contentsToRootView(roundedIntPoint(point)));
1175             return mainFrame.eventHandler().hitTestResultAtPoint(mainFramePoint, hitType, padding);
1176         }
1177     }
1178
1179     HitTestResult result(point, padding.height(), padding.width(), padding.height(), padding.width());
1180
1181     RenderView* renderView = m_frame.contentRenderer();
1182     if (!renderView)
1183         return result;
1184     
1185     // hitTestResultAtPoint is specifically used to hitTest into all frames, thus it always allows child frame content.
1186     HitTestRequest request(hitType | HitTestRequest::AllowChildFrameContent);
1187     renderView->hitTest(request, result);
1188     if (!request.readOnly())
1189         m_frame.document()->updateHoverActiveState(request, result.innerElement());
1190
1191     if (request.disallowsShadowContent())
1192         result.setToNonShadowAncestor();
1193
1194     return result;
1195 }
1196
1197 void EventHandler::stopAutoscrollTimer(bool rendererIsBeingDestroyed)
1198 {
1199     m_autoscrollController->stopAutoscrollTimer(rendererIsBeingDestroyed);
1200 }
1201
1202 bool EventHandler::scrollOverflow(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
1203 {
1204     Node* node = startingNode;
1205
1206     if (!node)
1207         node = m_frame.document()->focusedElement();
1208
1209     if (!node)
1210         node = m_mousePressNode.get();
1211     
1212     if (node) {
1213         auto r = node->renderer();
1214         if (r && !r->isListBox() && r->enclosingBox().scroll(direction, granularity)) {
1215             setFrameWasScrolledByUser();
1216             return true;
1217         }
1218     }
1219
1220     return false;
1221 }
1222
1223 bool EventHandler::logicalScrollOverflow(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
1224 {
1225     Node* node = startingNode;
1226
1227     if (!node)
1228         node = m_frame.document()->focusedElement();
1229
1230     if (!node)
1231         node = m_mousePressNode.get();
1232     
1233     if (node) {
1234         auto r = node->renderer();
1235         if (r && !r->isListBox() && r->enclosingBox().logicalScroll(direction, granularity)) {
1236             setFrameWasScrolledByUser();
1237             return true;
1238         }
1239     }
1240
1241     return false;
1242 }
1243
1244 bool EventHandler::scrollRecursively(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
1245 {
1246     // The layout needs to be up to date to determine if we can scroll. We may be
1247     // here because of an onLoad event, in which case the final layout hasn't been performed yet.
1248     m_frame.document()->updateLayoutIgnorePendingStylesheets();
1249     if (scrollOverflow(direction, granularity, startingNode))
1250         return true;    
1251     Frame* frame = &m_frame;
1252     FrameView* view = frame->view();
1253     if (view && view->scroll(direction, granularity))
1254         return true;
1255     frame = frame->tree().parent();
1256     if (!frame)
1257         return false;
1258     return frame->eventHandler().scrollRecursively(direction, granularity, m_frame.ownerElement());
1259 }
1260
1261 bool EventHandler::logicalScrollRecursively(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
1262 {
1263     // The layout needs to be up to date to determine if we can scroll. We may be
1264     // here because of an onLoad event, in which case the final layout hasn't been performed yet.
1265     m_frame.document()->updateLayoutIgnorePendingStylesheets();
1266     if (logicalScrollOverflow(direction, granularity, startingNode))
1267         return true;    
1268     Frame* frame = &m_frame;
1269     FrameView* view = frame->view();
1270     
1271     bool scrolled = false;
1272 #if PLATFORM(COCOA)
1273     // Mac also resets the scroll position in the inline direction.
1274     if (granularity == ScrollByDocument && view && view->logicalScroll(ScrollInlineDirectionBackward, ScrollByDocument))
1275         scrolled = true;
1276 #endif
1277     if (view && view->logicalScroll(direction, granularity))
1278         scrolled = true;
1279     
1280     if (scrolled)
1281         return true;
1282     
1283     frame = frame->tree().parent();
1284     if (!frame)
1285         return false;
1286
1287     return frame->eventHandler().logicalScrollRecursively(direction, granularity, m_frame.ownerElement());
1288 }
1289
1290 IntPoint EventHandler::lastKnownMousePosition() const
1291 {
1292     return m_lastKnownMousePosition;
1293 }
1294
1295 Frame* EventHandler::subframeForHitTestResult(const MouseEventWithHitTestResults& hitTestResult)
1296 {
1297     if (!hitTestResult.isOverWidget())
1298         return 0;
1299     return subframeForTargetNode(hitTestResult.targetNode());
1300 }
1301
1302 Frame* EventHandler::subframeForTargetNode(Node* node)
1303 {
1304     if (!node)
1305         return nullptr;
1306
1307     auto renderer = node->renderer();
1308     if (!is<RenderWidget>(renderer))
1309         return nullptr;
1310
1311     Widget* widget = downcast<RenderWidget>(*renderer).widget();
1312     if (!is<FrameView>(widget))
1313         return nullptr;
1314
1315     return &downcast<FrameView>(*widget).frame();
1316 }
1317
1318 #if ENABLE(CURSOR_SUPPORT)
1319 static bool isSubmitImage(Node* node)
1320 {
1321     return is<HTMLInputElement>(node) && downcast<HTMLInputElement>(*node).isImageButton();
1322 }
1323
1324 // Returns true if the node's editable block is not current focused for editing
1325 static bool nodeIsNotBeingEdited(const Node& node, const Frame& frame)
1326 {
1327     return frame.selection().selection().rootEditableElement() != node.rootEditableElement();
1328 }
1329
1330 bool EventHandler::useHandCursor(Node* node, bool isOverLink, bool shiftKey)
1331 {
1332     if (!node)
1333         return false;
1334
1335     bool editable = node->hasEditableStyle();
1336     bool editableLinkEnabled = false;
1337
1338     // If the link is editable, then we need to check the settings to see whether or not the link should be followed
1339     if (editable) {
1340         switch (m_frame.settings().editableLinkBehavior()) {
1341         default:
1342         case EditableLinkDefaultBehavior:
1343         case EditableLinkAlwaysLive:
1344             editableLinkEnabled = true;
1345             break;
1346
1347         case EditableLinkNeverLive:
1348             editableLinkEnabled = false;
1349             break;
1350
1351         case EditableLinkLiveWhenNotFocused:
1352             editableLinkEnabled = nodeIsNotBeingEdited(*node, m_frame) || shiftKey;
1353             break;
1354
1355         case EditableLinkOnlyLiveWithShiftKey:
1356             editableLinkEnabled = shiftKey;
1357             break;
1358         }
1359     }
1360
1361     return ((isOverLink || isSubmitImage(node)) && (!editable || editableLinkEnabled));
1362 }
1363
1364 void EventHandler::cursorUpdateTimerFired()
1365 {
1366     ASSERT(m_frame.document());
1367     updateCursor();
1368 }
1369
1370 void EventHandler::updateCursor()
1371 {
1372     if (m_mousePositionIsUnknown)
1373         return;
1374
1375     FrameView* view = m_frame.view();
1376     if (!view)
1377         return;
1378
1379     RenderView* renderView = view->renderView();
1380     if (!renderView)
1381         return;
1382
1383     if (!view->shouldSetCursor())
1384         return;
1385
1386     bool shiftKey;
1387     bool ctrlKey;
1388     bool altKey;
1389     bool metaKey;
1390     PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
1391
1392     HitTestRequest request(HitTestRequest::ReadOnly);
1393     HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
1394     renderView->hitTest(request, result);
1395
1396     OptionalCursor optionalCursor = selectCursor(result, shiftKey);
1397     if (optionalCursor.isCursorChange()) {
1398         m_currentMouseCursor = optionalCursor.cursor();
1399         view->setCursor(m_currentMouseCursor);
1400     }
1401 }
1402
1403 OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shiftKey)
1404 {
1405     if (m_resizeLayer && m_resizeLayer->inResizeMode())
1406         return NoCursorChange;
1407
1408     if (!m_frame.page())
1409         return NoCursorChange;
1410
1411 #if ENABLE(PAN_SCROLLING)
1412     if (m_frame.mainFrame().eventHandler().panScrollInProgress())
1413         return NoCursorChange;
1414 #endif
1415
1416     Node* node = result.targetNode();
1417     if (!node)
1418         return NoCursorChange;
1419
1420     auto renderer = node->renderer();
1421     RenderStyle* style = renderer ? &renderer->style() : nullptr;
1422     bool horizontalText = !style || style->isHorizontalWritingMode();
1423     const Cursor& iBeam = horizontalText ? iBeamCursor() : verticalTextCursor();
1424
1425 #if ENABLE(CURSOR_VISIBILITY)
1426     if (style && style->cursorVisibility() == CursorVisibilityAutoHide)
1427         startAutoHideCursorTimer();
1428     else
1429         cancelAutoHideCursorTimer();
1430 #endif
1431
1432     if (renderer) {
1433         Cursor overrideCursor;
1434         switch (renderer->getCursor(roundedIntPoint(result.localPoint()), overrideCursor)) {
1435         case SetCursorBasedOnStyle:
1436             break;
1437         case SetCursor:
1438             return overrideCursor;
1439         case DoNotSetCursor:
1440             return NoCursorChange;
1441         }
1442     }
1443
1444     if (style && style->cursors()) {
1445         const CursorList* cursors = style->cursors();
1446         for (unsigned i = 0; i < cursors->size(); ++i) {
1447             StyleImage* styleImage = (*cursors)[i].image();
1448             if (!styleImage)
1449                 continue;
1450             CachedImage* cachedImage = styleImage->cachedImage();
1451             if (!cachedImage)
1452                 continue;
1453             float scale = styleImage->imageScaleFactor();
1454             // Get hotspot and convert from logical pixels to physical pixels.
1455             IntPoint hotSpot = (*cursors)[i].hotSpot();
1456             FloatSize size = cachedImage->imageForRenderer(renderer)->size();
1457             if (cachedImage->errorOccurred())
1458                 continue;
1459             // Limit the size of cursors (in UI pixels) so that they cannot be
1460             // used to cover UI elements in chrome.
1461             size.scale(1 / scale);
1462             if (size.width() > maximumCursorSize || size.height() > maximumCursorSize)
1463                 continue;
1464
1465             Image* image = cachedImage->imageForRenderer(renderer);
1466 #if ENABLE(MOUSE_CURSOR_SCALE)
1467             // Ensure no overflow possible in calculations above.
1468             if (scale < minimumCursorScale)
1469                 continue;
1470             return Cursor(image, hotSpot, scale);
1471 #else
1472             ASSERT(scale == 1);
1473             return Cursor(image, hotSpot);
1474 #endif // ENABLE(MOUSE_CURSOR_SCALE)
1475         }
1476     }
1477
1478     // During selection, use an I-beam regardless of the content beneath the cursor.
1479     // If a drag may be starting or we're capturing mouse events for a particular node, don't treat this as a selection.
1480     if (m_mousePressed
1481         && m_mouseDownMayStartSelect
1482 #if ENABLE(DRAG_SUPPORT)
1483         && !m_mouseDownMayStartDrag
1484 #endif
1485         && m_frame.selection().isCaretOrRange()
1486         && !m_capturingMouseEventsElement)
1487         return iBeam;
1488
1489     switch (style ? style->cursor() : CursorAuto) {
1490     case CursorAuto: {
1491         bool editable = node->hasEditableStyle();
1492
1493         if (useHandCursor(node, result.isOverLink(), shiftKey))
1494             return handCursor();
1495
1496         bool inResizer = false;
1497         if (renderer) {
1498             if (RenderLayer* layer = renderer->enclosingLayer()) {
1499                 if (FrameView* view = m_frame.view())
1500                     inResizer = layer->isPointInResizeControl(view->windowToContents(roundedIntPoint(result.localPoint())));
1501             }
1502         }
1503
1504         if ((editable || (renderer && renderer->isText() && node->canStartSelection())) && !inResizer && !result.scrollbar())
1505             return iBeam;
1506         return pointerCursor();
1507     }
1508     case CursorCross:
1509         return crossCursor();
1510     case CursorPointer:
1511         return handCursor();
1512     case CursorMove:
1513         return moveCursor();
1514     case CursorAllScroll:
1515         return moveCursor();
1516     case CursorEResize:
1517         return eastResizeCursor();
1518     case CursorWResize:
1519         return westResizeCursor();
1520     case CursorNResize:
1521         return northResizeCursor();
1522     case CursorSResize:
1523         return southResizeCursor();
1524     case CursorNeResize:
1525         return northEastResizeCursor();
1526     case CursorSwResize:
1527         return southWestResizeCursor();
1528     case CursorNwResize:
1529         return northWestResizeCursor();
1530     case CursorSeResize:
1531         return southEastResizeCursor();
1532     case CursorNsResize:
1533         return northSouthResizeCursor();
1534     case CursorEwResize:
1535         return eastWestResizeCursor();
1536     case CursorNeswResize:
1537         return northEastSouthWestResizeCursor();
1538     case CursorNwseResize:
1539         return northWestSouthEastResizeCursor();
1540     case CursorColResize:
1541         return columnResizeCursor();
1542     case CursorRowResize:
1543         return rowResizeCursor();
1544     case CursorText:
1545         return iBeamCursor();
1546     case CursorWait:
1547         return waitCursor();
1548     case CursorHelp:
1549         return helpCursor();
1550     case CursorVerticalText:
1551         return verticalTextCursor();
1552     case CursorCell:
1553         return cellCursor();
1554     case CursorContextMenu:
1555         return contextMenuCursor();
1556     case CursorProgress:
1557         return progressCursor();
1558     case CursorNoDrop:
1559         return noDropCursor();
1560     case CursorAlias:
1561         return aliasCursor();
1562     case CursorCopy:
1563         return copyCursor();
1564     case CursorNone:
1565         return noneCursor();
1566     case CursorNotAllowed:
1567         return notAllowedCursor();
1568     case CursorDefault:
1569         return pointerCursor();
1570     case CursorZoomIn:
1571         return zoomInCursor();
1572     case CursorZoomOut:
1573         return zoomOutCursor();
1574     case CursorWebkitGrab:
1575         return grabCursor();
1576     case CursorWebkitGrabbing:
1577         return grabbingCursor();
1578     }
1579     return pointerCursor();
1580 }
1581 #endif // ENABLE(CURSOR_SUPPORT)
1582
1583 #if ENABLE(CURSOR_VISIBILITY)
1584 void EventHandler::startAutoHideCursorTimer()
1585 {
1586     Page* page = m_frame.page();
1587     if (!page)
1588         return;
1589
1590     m_autoHideCursorTimer.startOneShot(page->settings().timeWithoutMouseMovementBeforeHidingControls());
1591
1592 #if !ENABLE(IOS_TOUCH_EVENTS)
1593     // The fake mouse move event screws up the auto-hide feature (by resetting the auto-hide timer)
1594     // so cancel any pending fake mouse moves.
1595     if (m_fakeMouseMoveEventTimer.isActive())
1596         m_fakeMouseMoveEventTimer.stop();
1597 #endif
1598 }
1599
1600 void EventHandler::cancelAutoHideCursorTimer()
1601 {
1602     if (m_autoHideCursorTimer.isActive())
1603         m_autoHideCursorTimer.stop();
1604 }
1605
1606 void EventHandler::autoHideCursorTimerFired()
1607 {
1608     m_currentMouseCursor = noneCursor();
1609     FrameView* view = m_frame.view();
1610     if (view && view->isActive())
1611         view->setCursor(m_currentMouseCursor);
1612 }
1613 #endif
1614     
1615 void EventHandler::beginTrackingPotentialLongMousePress(const HitTestResult& hitTestResult)
1616 {
1617     clearLongMousePressState();
1618
1619     Page* page = m_frame.page();
1620     if (!(page && page->settings().longMousePressEnabled()))
1621         return;
1622
1623     m_longMousePressTimer.startOneShot(longMousePressRecognitionDelay);
1624
1625     page->chrome().didBeginTrackingPotentialLongMousePress(m_mouseDownPos, hitTestResult);
1626 }
1627     
1628 void EventHandler::recognizeLongMousePress()
1629 {
1630     Page* page = m_frame.page();
1631     if (!page)
1632         return;
1633
1634     m_didRecognizeLongMousePress = true;
1635
1636     // Clear mouse state to avoid initiating a drag.
1637     m_mousePressed = false;
1638     invalidateClick();
1639
1640     page->chrome().didRecognizeLongMousePress();
1641 }
1642     
1643 void EventHandler::cancelTrackingPotentialLongMousePress()
1644 {
1645     if (!m_longMousePressTimer.isActive())
1646         return;
1647
1648     clearLongMousePressState();
1649
1650     Page* page = m_frame.page();
1651     if (!page)
1652         return;
1653
1654     page->chrome().didCancelTrackingPotentialLongMousePress();
1655 }
1656
1657 void EventHandler::clearLongMousePressState()
1658 {
1659     m_longMousePressTimer.stop();
1660     m_didRecognizeLongMousePress = false;
1661 }
1662     
1663 bool EventHandler::handleLongMousePressMouseMovedEvent(const PlatformMouseEvent& mouseEvent)
1664 {
1665     if (mouseEvent.button() != LeftButton || mouseEvent.type() != PlatformEvent::MouseMoved)
1666         return false;
1667
1668     if (m_didRecognizeLongMousePress)
1669         return true;
1670
1671     if (!mouseMovementExceedsThreshold(mouseEvent.position(), maximumLongMousePressDragDistance))
1672         cancelTrackingPotentialLongMousePress();
1673
1674     return false;
1675 }
1676
1677 static LayoutPoint documentPointForWindowPoint(Frame& frame, const IntPoint& windowPoint)
1678 {
1679     FrameView* view = frame.view();
1680     // FIXME: Is it really OK to use the wrong coordinates here when view is 0?
1681     // Historically the code would just crash; this is clearly no worse than that.
1682     return view ? view->windowToContents(windowPoint) : windowPoint;
1683 }
1684
1685 bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& platformMouseEvent)
1686 {
1687     RefPtr<FrameView> protector(m_frame.view());
1688
1689     if (InspectorInstrumentation::handleMousePress(m_frame)) {
1690         invalidateClick();
1691         return true;
1692     }
1693
1694     if (m_frame.mainFrame().pageOverlayController().handleMouseEvent(platformMouseEvent))
1695         return true;
1696
1697 #if ENABLE(TOUCH_EVENTS)
1698     bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(platformMouseEvent);
1699     if (defaultPrevented)
1700         return true;
1701 #endif
1702
1703     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture, m_frame.document());
1704
1705     // FIXME (bug 68185): this call should be made at another abstraction layer
1706     m_frame.loader().resetMultipleFormSubmissionProtection();
1707
1708 #if !ENABLE(IOS_TOUCH_EVENTS)
1709     cancelFakeMouseMoveEvent();
1710 #endif
1711     m_mousePressed = true;
1712     m_capturesDragging = true;
1713     setLastKnownMousePosition(platformMouseEvent);
1714     m_mouseDownTimestamp = platformMouseEvent.timestamp();
1715 #if ENABLE(DRAG_SUPPORT)
1716     m_mouseDownMayStartDrag = false;
1717 #endif
1718     m_mouseDownMayStartSelect = false;
1719     m_mouseDownMayStartAutoscroll = false;
1720     if (FrameView* view = m_frame.view())
1721         m_mouseDownPos = view->windowToContents(platformMouseEvent.position());
1722     else {
1723         invalidateClick();
1724         return false;
1725     }
1726     m_mouseDownWasInSubframe = false;
1727
1728     HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
1729     // Save the document point we generate in case the window coordinate is invalidated by what happens
1730     // when we dispatch the event.
1731     LayoutPoint documentPoint = documentPointForWindowPoint(m_frame, platformMouseEvent.position());
1732     MouseEventWithHitTestResults mouseEvent = m_frame.document()->prepareMouseEvent(request, documentPoint, platformMouseEvent);
1733
1734     if (!mouseEvent.targetNode()) {
1735         invalidateClick();
1736         return false;
1737     }
1738
1739     m_mousePressNode = mouseEvent.targetNode();
1740
1741     RefPtr<Frame> subframe = subframeForHitTestResult(mouseEvent);
1742     if (subframe && passMousePressEventToSubframe(mouseEvent, subframe.get())) {
1743         // Start capturing future events for this frame.  We only do this if we didn't clear
1744         // the m_mousePressed flag, which may happen if an AppKit widget entered a modal event loop.
1745         m_capturesDragging = subframe->eventHandler().capturesDragging();
1746         if (m_mousePressed && m_capturesDragging) {
1747             m_capturingMouseEventsElement = subframe->ownerElement();
1748             m_eventHandlerWillResetCapturingMouseEventsElement = true;
1749         }
1750         invalidateClick();
1751         return true;
1752     }
1753
1754 #if ENABLE(PAN_SCROLLING)
1755     // We store whether pan scrolling is in progress before calling stopAutoscrollTimer()
1756     // because it will set m_autoscrollType to NoAutoscroll on return.
1757     bool isPanScrollInProgress = m_frame.mainFrame().eventHandler().panScrollInProgress();
1758     stopAutoscrollTimer();
1759     if (isPanScrollInProgress) {
1760         // We invalidate the click when exiting pan scrolling so that we don't inadvertently navigate
1761         // away from the current page (e.g. the click was on a hyperlink). See <rdar://problem/6095023>.
1762         invalidateClick();
1763         return true;
1764     }
1765 #endif
1766
1767     m_clickCount = platformMouseEvent.clickCount();
1768     m_clickNode = mouseEvent.targetNode();
1769
1770     if (!m_clickNode) {
1771         invalidateClick();
1772         return false;
1773     }
1774
1775     if (FrameView* view = m_frame.view()) {
1776         RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
1777         IntPoint p = view->windowToContents(platformMouseEvent.position());
1778         if (layer && layer->isPointInResizeControl(p)) {
1779             layer->setInResizeMode(true);
1780             m_resizeLayer = layer;
1781             m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
1782             invalidateClick();
1783             return true;
1784         }
1785     }
1786
1787     m_frame.selection().setCaretBlinkingSuspended(true);
1788
1789     bool swallowEvent = !dispatchMouseEvent(eventNames().mousedownEvent, mouseEvent.targetNode(), true, m_clickCount, platformMouseEvent, true);
1790     m_capturesDragging = !swallowEvent || mouseEvent.scrollbar();
1791
1792     // If the hit testing originally determined the event was in a scrollbar, refetch the MouseEventWithHitTestResults
1793     // in case the scrollbar widget was destroyed when the mouse event was handled.
1794     if (mouseEvent.scrollbar()) {
1795         const bool wasLastScrollBar = mouseEvent.scrollbar() == m_lastScrollbarUnderMouse.get();
1796         mouseEvent = m_frame.document()->prepareMouseEvent(HitTestRequest(), documentPoint, platformMouseEvent);
1797         if (wasLastScrollBar && mouseEvent.scrollbar() != m_lastScrollbarUnderMouse.get())
1798             m_lastScrollbarUnderMouse = nullptr;
1799     }
1800
1801     if (swallowEvent) {
1802         // scrollbars should get events anyway, even disabled controls might be scrollable
1803         Scrollbar* scrollbar = mouseEvent.scrollbar();
1804
1805         updateLastScrollbarUnderMouse(scrollbar, true);
1806
1807         if (scrollbar)
1808             passMousePressEventToScrollbar(mouseEvent, scrollbar);
1809     } else {
1810         // Refetch the event target node if it currently is the shadow node inside an <input> element.
1811         // If a mouse event handler changes the input element type to one that has a widget associated,
1812         // we'd like to EventHandler::handleMousePressEvent to pass the event to the widget and thus the
1813         // event target node can't still be the shadow node.
1814         if (is<ShadowRoot>(*mouseEvent.targetNode()) && is<HTMLInputElement>(*downcast<ShadowRoot>(*mouseEvent.targetNode()).hostElement()))
1815             mouseEvent = m_frame.document()->prepareMouseEvent(HitTestRequest(), documentPoint, platformMouseEvent);
1816
1817         FrameView* view = m_frame.view();
1818         Scrollbar* scrollbar = view ? view->scrollbarAtPoint(platformMouseEvent.position()) : 0;
1819         if (!scrollbar)
1820             scrollbar = mouseEvent.scrollbar();
1821
1822         updateLastScrollbarUnderMouse(scrollbar, true);
1823
1824         if (scrollbar && passMousePressEventToScrollbar(mouseEvent, scrollbar))
1825             swallowEvent = true;
1826         else
1827             swallowEvent = handleMousePressEvent(mouseEvent);
1828     }
1829
1830     return swallowEvent;
1831 }
1832
1833 // This method only exists for platforms that don't know how to deliver 
1834 bool EventHandler::handleMouseDoubleClickEvent(const PlatformMouseEvent& platformMouseEvent)
1835 {
1836     RefPtr<FrameView> protector(m_frame.view());
1837
1838     m_frame.selection().setCaretBlinkingSuspended(false);
1839
1840     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture, m_frame.document());
1841
1842     // We get this instead of a second mouse-up 
1843     m_mousePressed = false;
1844     setLastKnownMousePosition(platformMouseEvent);
1845
1846     HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
1847     MouseEventWithHitTestResults mouseEvent = prepareMouseEvent(request, platformMouseEvent);
1848     Frame* subframe = subframeForHitTestResult(mouseEvent);
1849     if (m_eventHandlerWillResetCapturingMouseEventsElement)
1850         m_capturingMouseEventsElement = nullptr;
1851     if (subframe && passMousePressEventToSubframe(mouseEvent, subframe))
1852         return true;
1853
1854     m_clickCount = platformMouseEvent.clickCount();
1855     bool swallowMouseUpEvent = !dispatchMouseEvent(eventNames().mouseupEvent, mouseEvent.targetNode(), true, m_clickCount, platformMouseEvent, false);
1856
1857     bool swallowClickEvent = platformMouseEvent.button() != RightButton && mouseEvent.targetNode() == m_clickNode && !dispatchMouseEvent(eventNames().clickEvent, mouseEvent.targetNode(), true, m_clickCount, platformMouseEvent, true);
1858
1859     if (m_lastScrollbarUnderMouse)
1860         swallowMouseUpEvent = m_lastScrollbarUnderMouse->mouseUp(platformMouseEvent);
1861
1862     bool swallowMouseReleaseEvent = !swallowMouseUpEvent && handleMouseReleaseEvent(mouseEvent);
1863
1864     invalidateClick();
1865
1866     return swallowMouseUpEvent || swallowClickEvent || swallowMouseReleaseEvent;
1867 }
1868
1869 static RenderLayer* layerForNode(Node* node)
1870 {
1871     if (!node)
1872         return 0;
1873
1874     auto renderer = node->renderer();
1875     if (!renderer)
1876         return 0;
1877
1878     RenderLayer* layer = renderer->enclosingLayer();
1879     if (!layer)
1880         return 0;
1881
1882     return layer;
1883 }
1884
1885 bool EventHandler::mouseMoved(const PlatformMouseEvent& event)
1886 {
1887     RefPtr<FrameView> protector(m_frame.view());
1888     MaximumDurationTracker maxDurationTracker(&m_maxMouseMovedDuration);
1889
1890     if (m_frame.mainFrame().pageOverlayController().handleMouseEvent(event))
1891         return true;
1892
1893     HitTestResult hoveredNode = HitTestResult(LayoutPoint());
1894     bool result = handleMouseMoveEvent(event, &hoveredNode);
1895
1896     Page* page = m_frame.page();
1897     if (!page)
1898         return result;
1899
1900     if (RenderLayer* layer = layerForNode(hoveredNode.innerNode())) {
1901         if (FrameView* frameView = m_frame.view()) {
1902             if (frameView->containsScrollableArea(layer))
1903                 layer->mouseMovedInContentArea();
1904         }
1905     }
1906
1907     if (FrameView* frameView = m_frame.view())
1908         frameView->mouseMovedInContentArea();  
1909
1910     hoveredNode.setToNonShadowAncestor();
1911     page->chrome().mouseDidMoveOverElement(hoveredNode, event.modifierFlags());
1912     page->chrome().setToolTip(hoveredNode);
1913     return result;
1914 }
1915
1916 bool EventHandler::passMouseMovedEventToScrollbars(const PlatformMouseEvent& event)
1917 {
1918     HitTestResult hoveredNode;
1919     return handleMouseMoveEvent(event, &hoveredNode, true);
1920 }
1921
1922 bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& platformMouseEvent, HitTestResult* hoveredNode, bool onlyUpdateScrollbars)
1923 {
1924 #if ENABLE(TOUCH_EVENTS)
1925     bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(platformMouseEvent);
1926     if (defaultPrevented)
1927         return true;
1928 #endif
1929
1930     if (handleLongMousePressMouseMovedEvent(platformMouseEvent))
1931         return true;
1932
1933     RefPtr<FrameView> protector(m_frame.view());
1934     
1935     setLastKnownMousePosition(platformMouseEvent);
1936
1937     if (m_hoverTimer.isActive())
1938         m_hoverTimer.stop();
1939
1940 #if ENABLE(CURSOR_SUPPORT)
1941     m_cursorUpdateTimer.stop();
1942 #endif
1943
1944 #if !ENABLE(IOS_TOUCH_EVENTS)
1945     cancelFakeMouseMoveEvent();
1946 #endif
1947
1948     if (m_svgPan) {
1949         downcast<SVGDocument>(*m_frame.document()).updatePan(m_frame.view()->windowToContents(m_lastKnownMousePosition));
1950         return true;
1951     }
1952
1953     if (m_frameSetBeingResized)
1954         return !dispatchMouseEvent(eventNames().mousemoveEvent, m_frameSetBeingResized.get(), false, 0, platformMouseEvent, false);
1955
1956     // On iOS, our scrollbars are managed by UIKit.
1957 #if !PLATFORM(IOS)
1958     // Send events right to a scrollbar if the mouse is pressed.
1959     if (m_lastScrollbarUnderMouse && m_mousePressed)
1960         return m_lastScrollbarUnderMouse->mouseMoved(platformMouseEvent);
1961 #endif
1962
1963     HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::DisallowShadowContent | HitTestRequest::AllowFrameScrollbars;
1964     if (m_mousePressed)
1965         hitType |= HitTestRequest::Active;
1966     else if (onlyUpdateScrollbars) {
1967         // Mouse events should be treated as "read-only" if we're updating only scrollbars. This  
1968         // means that :hover and :active freeze in the state they were in, rather than updating  
1969         // for nodes the mouse moves while the window is not key (which will be the case if 
1970         // onlyUpdateScrollbars is true). 
1971         hitType |= HitTestRequest::ReadOnly;
1972     }
1973
1974 #if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
1975     // Treat any mouse move events as readonly if the user is currently touching the screen.
1976     if (m_touchPressed)
1977         hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
1978 #endif
1979     HitTestRequest request(hitType);
1980     MouseEventWithHitTestResults mouseEvent = prepareMouseEvent(request, platformMouseEvent);
1981     if (hoveredNode)
1982         *hoveredNode = mouseEvent.hitTestResult();
1983
1984     if (m_resizeLayer && m_resizeLayer->inResizeMode())
1985         m_resizeLayer->resize(platformMouseEvent, m_offsetFromResizeCorner);
1986     else {
1987         Scrollbar* scrollbar = mouseEvent.scrollbar();
1988         updateLastScrollbarUnderMouse(scrollbar, !m_mousePressed);
1989
1990         // On iOS, our scrollbars are managed by UIKit.
1991 #if !PLATFORM(IOS)
1992         if (!m_mousePressed && scrollbar)
1993             scrollbar->mouseMoved(platformMouseEvent); // Handle hover effects on platforms that support visual feedback on scrollbar hovering.
1994 #endif
1995         if (onlyUpdateScrollbars)
1996             return true;
1997     }
1998
1999     bool swallowEvent = false;
2000     RefPtr<Frame> newSubframe = m_capturingMouseEventsElement.get() ? subframeForTargetNode(m_capturingMouseEventsElement.get()) : subframeForHitTestResult(mouseEvent);
2001  
2002     // We want mouseouts to happen first, from the inside out.  First send a move event to the last subframe so that it will fire mouseouts.
2003     if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree().isDescendantOf(&m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
2004         passMouseMoveEventToSubframe(mouseEvent, m_lastMouseMoveEventSubframe.get());
2005
2006     if (newSubframe) {
2007         // Update over/out state before passing the event to the subframe.
2008         updateMouseEventTargetNode(mouseEvent.targetNode(), platformMouseEvent, true);
2009         
2010         // Event dispatch in updateMouseEventTargetNode may have caused the subframe of the target
2011         // node to be detached from its FrameView, in which case the event should not be passed.
2012         if (newSubframe->view())
2013             swallowEvent |= passMouseMoveEventToSubframe(mouseEvent, newSubframe.get(), hoveredNode);
2014 #if ENABLE(CURSOR_SUPPORT)
2015     } else {
2016         if (FrameView* view = m_frame.view()) {
2017             OptionalCursor optionalCursor = selectCursor(mouseEvent.hitTestResult(), platformMouseEvent.shiftKey());
2018             if (optionalCursor.isCursorChange()) {
2019                 m_currentMouseCursor = optionalCursor.cursor();
2020                 view->setCursor(m_currentMouseCursor);
2021             }
2022         }
2023 #endif
2024     }
2025     
2026     m_lastMouseMoveEventSubframe = newSubframe;
2027
2028     if (swallowEvent)
2029         return true;
2030     
2031     swallowEvent = !dispatchMouseEvent(eventNames().mousemoveEvent, mouseEvent.targetNode(), false, 0, platformMouseEvent, true);
2032 #if ENABLE(DRAG_SUPPORT)
2033     if (!swallowEvent)
2034         swallowEvent = handleMouseDraggedEvent(mouseEvent);
2035 #endif // ENABLE(DRAG_SUPPORT)
2036
2037     return swallowEvent;
2038 }
2039
2040 void EventHandler::invalidateClick()
2041 {
2042     m_clickCount = 0;
2043     m_clickNode = nullptr;
2044 }
2045
2046 static Node* targetNodeForClickEvent(Node* mousePressNode, Node* mouseReleaseNode)
2047 {
2048     if (!mousePressNode || !mouseReleaseNode)
2049         return nullptr;
2050
2051     if (mousePressNode == mouseReleaseNode)
2052         return mouseReleaseNode;
2053
2054     Element* mouseReleaseShadowHost = mouseReleaseNode->shadowHost();
2055     if (mouseReleaseShadowHost && mouseReleaseShadowHost == mousePressNode->shadowHost()) {
2056         // We want to dispatch the click to the shadow tree host element to give listeners the illusion that the
2057         // shadom tree is a single element. For example, we want to give the illusion that <input type="range">
2058         // is a single element even though it is a composition of multiple shadom tree elements.
2059         return mouseReleaseShadowHost;
2060     }
2061     return nullptr;
2062 }
2063
2064 bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& platformMouseEvent)
2065 {
2066     RefPtr<FrameView> protector(m_frame.view());
2067
2068     m_frame.selection().setCaretBlinkingSuspended(false);
2069
2070     if (m_frame.mainFrame().pageOverlayController().handleMouseEvent(platformMouseEvent))
2071         return true;
2072
2073 #if ENABLE(TOUCH_EVENTS)
2074     bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(platformMouseEvent);
2075     if (defaultPrevented)
2076         return true;
2077 #endif
2078
2079     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture, m_frame.document());
2080
2081 #if ENABLE(PAN_SCROLLING)
2082     m_autoscrollController->handleMouseReleaseEvent(platformMouseEvent);
2083 #endif
2084
2085     m_mousePressed = false;
2086     setLastKnownMousePosition(platformMouseEvent);
2087
2088     if (m_svgPan) {
2089         m_svgPan = false;
2090         downcast<SVGDocument>(*m_frame.document()).updatePan(m_frame.view()->windowToContents(m_lastKnownMousePosition));
2091         return true;
2092     }
2093
2094     if (m_frameSetBeingResized)
2095         return !dispatchMouseEvent(eventNames().mouseupEvent, m_frameSetBeingResized.get(), true, m_clickCount, platformMouseEvent, false);
2096
2097     // If an immediate action began or was completed using this series of mouse events, then we should send mouseup to
2098     // the DOM and return now so that we don't perform our own default behaviors.
2099     if (m_immediateActionStage == ImmediateActionStage::ActionCompleted || m_immediateActionStage == ImmediateActionStage::ActionUpdated) {
2100         m_immediateActionStage = ImmediateActionStage::None;
2101         return !dispatchMouseEvent(eventNames().mouseupEvent, m_lastElementUnderMouse.get(), true, m_clickCount, platformMouseEvent, false);
2102     }
2103     m_immediateActionStage = ImmediateActionStage::None;
2104
2105     if (m_lastScrollbarUnderMouse) {
2106         invalidateClick();
2107         m_lastScrollbarUnderMouse->mouseUp(platformMouseEvent);
2108         bool cancelable = true;
2109         bool setUnder = false;
2110         return !dispatchMouseEvent(eventNames().mouseupEvent, m_lastElementUnderMouse.get(), cancelable, m_clickCount, platformMouseEvent, setUnder);
2111     }
2112
2113     HitTestRequest request(HitTestRequest::Release | HitTestRequest::DisallowShadowContent);
2114     MouseEventWithHitTestResults mouseEvent = prepareMouseEvent(request, platformMouseEvent);
2115     Frame* subframe = m_capturingMouseEventsElement.get() ? subframeForTargetNode(m_capturingMouseEventsElement.get()) : subframeForHitTestResult(mouseEvent);
2116     if (m_eventHandlerWillResetCapturingMouseEventsElement)
2117         m_capturingMouseEventsElement = nullptr;
2118     if (subframe && passMouseReleaseEventToSubframe(mouseEvent, subframe))
2119         return true;
2120
2121     bool swallowMouseUpEvent = !dispatchMouseEvent(eventNames().mouseupEvent, mouseEvent.targetNode(), true, m_clickCount, platformMouseEvent, false);
2122
2123     bool contextMenuEvent = platformMouseEvent.button() == RightButton;
2124
2125     Node* nodeToClick = targetNodeForClickEvent(m_clickNode.get(), mouseEvent.targetNode());
2126     bool swallowClickEvent = m_clickCount > 0 && !contextMenuEvent && nodeToClick && !dispatchMouseEvent(eventNames().clickEvent, nodeToClick, true, m_clickCount, platformMouseEvent, true);
2127
2128     if (m_resizeLayer) {
2129         m_resizeLayer->setInResizeMode(false);
2130         m_resizeLayer = nullptr;
2131     }
2132
2133     bool swallowMouseReleaseEvent = false;
2134     if (!swallowMouseUpEvent)
2135         swallowMouseReleaseEvent = handleMouseReleaseEvent(mouseEvent);
2136
2137     invalidateClick();
2138
2139     return swallowMouseUpEvent || swallowClickEvent || swallowMouseReleaseEvent;
2140 }
2141
2142 #if ENABLE(MOUSE_FORCE_EVENTS)
2143 bool EventHandler::handleMouseForceEvent(const PlatformMouseEvent& event)
2144 {
2145     RefPtr<FrameView> protector(m_frame.view());
2146
2147     setLastKnownMousePosition(event);
2148
2149     HitTestRequest::HitTestRequestType hitType = HitTestRequest::DisallowShadowContent | HitTestRequest::Active;
2150
2151     HitTestRequest request(hitType);
2152     MouseEventWithHitTestResults mouseEvent = prepareMouseEvent(request, event);
2153
2154     bool swallowedEvent = !dispatchMouseEvent(eventNames().webkitmouseforcechangedEvent, mouseEvent.targetNode(), false, 0, event, false);
2155     if (event.type() == PlatformEvent::MouseForceDown)
2156         swallowedEvent |= !dispatchMouseEvent(eventNames().webkitmouseforcedownEvent, mouseEvent.targetNode(), false, 0, event, false);
2157     if (event.type() == PlatformEvent::MouseForceUp)
2158         swallowedEvent |= !dispatchMouseEvent(eventNames().webkitmouseforceupEvent, mouseEvent.targetNode(), false, 0, event, false);
2159
2160     return swallowedEvent;
2161 }
2162 #else
2163 bool EventHandler::handleMouseForceEvent(const PlatformMouseEvent& )
2164 {
2165     return false;
2166 }
2167 #endif // #if ENABLE(MOUSE_FORCE_EVENTS)
2168
2169 bool EventHandler::handlePasteGlobalSelection(const PlatformMouseEvent& platformMouseEvent)
2170 {
2171     // If the event was a middle click, attempt to copy global selection in after
2172     // the newly set caret position.
2173     //
2174     // This code is called from either the mouse up or mouse down handling. There
2175     // is some debate about when the global selection is pasted:
2176     //   xterm: pastes on up.
2177     //   GTK: pastes on down.
2178     //   Qt: pastes on up.
2179     //   Firefox: pastes on up.
2180     //   Chromium: pastes on up.
2181     //
2182     // There is something of a webcompat angle to this well, as highlighted by
2183     // crbug.com/14608. Pages can clear text boxes 'onclick' and, if we paste on
2184     // down then the text is pasted just before the onclick handler runs and
2185     // clears the text box. So it's important this happens after the event
2186     // handlers have been fired.
2187 #if PLATFORM(GTK)
2188     if (platformMouseEvent.type() != PlatformEvent::MousePressed)
2189         return false;
2190 #else
2191     if (platformMouseEvent.type() != PlatformEvent::MouseReleased)
2192         return false;
2193 #endif
2194
2195     if (!m_frame.page())
2196         return false;
2197     Frame& focusFrame = m_frame.page()->focusController().focusedOrMainFrame();
2198     // Do not paste here if the focus was moved somewhere else.
2199     if (&m_frame == &focusFrame && m_frame.editor().client()->supportsGlobalSelection())
2200         return m_frame.editor().command(ASCIILiteral("PasteGlobalSelection")).execute();
2201
2202     return false;
2203 }
2204
2205 #if ENABLE(DRAG_SUPPORT)
2206
2207 bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Element& dragTarget, const PlatformMouseEvent& event, DataTransfer* dataTransfer)
2208 {
2209     FrameView* view = m_frame.view();
2210
2211     // FIXME: We might want to dispatch a dragleave even if the view is gone.
2212     if (!view)
2213         return false;
2214
2215     view->disableLayerFlushThrottlingTemporarilyForInteraction();
2216     RefPtr<MouseEvent> me = MouseEvent::create(eventType,
2217         true, true, event.timestamp(), m_frame.document()->defaultView(),
2218         0, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
2219 #if ENABLE(POINTER_LOCK)
2220         event.movementDelta().x(), event.movementDelta().y(),
2221 #endif
2222         event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(),
2223         0, 0, event.force(), dataTransfer);
2224
2225     dragTarget.dispatchEvent(me.get(), IGNORE_EXCEPTION);
2226     return me->defaultPrevented();
2227 }
2228
2229 static bool targetIsFrame(Node* target, Frame*& frame)
2230 {
2231     if (!is<HTMLFrameElementBase>(target))
2232         return false;
2233
2234     frame = downcast<HTMLFrameElementBase>(*target).contentFrame();
2235     return true;
2236 }
2237
2238 static DragOperation convertDropZoneOperationToDragOperation(const String& dragOperation)
2239 {
2240     if (dragOperation == "copy")
2241         return DragOperationCopy;
2242     if (dragOperation == "move")
2243         return DragOperationMove;
2244     if (dragOperation == "link")
2245         return DragOperationLink;
2246     return DragOperationNone;
2247 }
2248
2249 static String convertDragOperationToDropZoneOperation(DragOperation operation)
2250 {
2251     switch (operation) {
2252     case DragOperationCopy:
2253         return ASCIILiteral("copy");
2254     case DragOperationMove:
2255         return ASCIILiteral("move");
2256     case DragOperationLink:
2257         return ASCIILiteral("link");
2258     default:
2259         return ASCIILiteral("copy");
2260     }
2261 }
2262
2263 static bool hasDropZoneType(DataTransfer& dataTransfer, const String& keyword)
2264 {
2265     if (keyword.startsWith("file:"))
2266         return dataTransfer.hasFileOfType(keyword.substring(5));
2267
2268     if (keyword.startsWith("string:"))
2269         return dataTransfer.hasStringOfType(keyword.substring(7));
2270
2271     return false;
2272 }
2273
2274 static bool findDropZone(Node* target, DataTransfer* dataTransfer)
2275 {
2276     ASSERT(target);
2277     Element* element = is<Element>(*target) ? downcast<Element>(target) : target->parentElement();
2278     for (; element; element = element->parentElement()) {
2279         bool matched = false;
2280         String dropZoneStr = element->fastGetAttribute(webkitdropzoneAttr);
2281
2282         if (dropZoneStr.isEmpty())
2283             continue;
2284         
2285         dropZoneStr = dropZoneStr.lower();
2286         
2287         SpaceSplitString keywords(dropZoneStr, false);
2288         if (keywords.isEmpty())
2289             continue;
2290         
2291         DragOperation dragOperation = DragOperationNone;
2292         for (unsigned int i = 0; i < keywords.size(); i++) {
2293             DragOperation op = convertDropZoneOperationToDragOperation(keywords[i]);
2294             if (op != DragOperationNone) {
2295                 if (dragOperation == DragOperationNone)
2296                     dragOperation = op;
2297             } else
2298                 matched = matched || hasDropZoneType(*dataTransfer, keywords[i].string());
2299
2300             if (matched && dragOperation != DragOperationNone)
2301                 break;
2302         }
2303         if (matched) {
2304             dataTransfer->setDropEffect(convertDragOperationToDropZoneOperation(dragOperation));
2305             return true;
2306         }
2307     }
2308     return false;
2309 }
2310     
2311 bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, DataTransfer* dataTransfer)
2312 {
2313     bool accept = false;
2314
2315     if (!m_frame.view())
2316         return false;
2317
2318     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
2319     MouseEventWithHitTestResults mouseEvent = prepareMouseEvent(request, event);
2320
2321     RefPtr<Element> newTarget;
2322     if (Node* targetNode = mouseEvent.targetNode()) {
2323         // Drag events should never go to non-element nodes (following IE, and proper mouseover/out dispatch)
2324         if (!is<Element>(*targetNode))
2325             newTarget = targetNode->parentOrShadowHostElement();
2326         else
2327             newTarget = downcast<Element>(targetNode);
2328     }
2329
2330     m_autoscrollController->updateDragAndDrop(newTarget.get(), event.position(), event.timestamp());
2331
2332     if (m_dragTarget != newTarget) {
2333         // FIXME: this ordering was explicitly chosen to match WinIE. However,
2334         // it is sometimes incorrect when dragging within subframes, as seen with
2335         // LayoutTests/fast/events/drag-in-frames.html.
2336         //
2337         // Moreover, this ordering conforms to section 7.9.4 of the HTML 5 spec. <http://dev.w3.org/html5/spec/Overview.html#drag-and-drop-processing-model>.
2338         Frame* targetFrame;
2339         if (targetIsFrame(newTarget.get(), targetFrame)) {
2340             if (targetFrame)
2341                 accept = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
2342         } else if (newTarget) {
2343             // As per section 7.9.4 of the HTML 5 spec., we must always fire a drag event before firing a dragenter, dragleave, or dragover event.
2344             if (dragState().source && dragState().shouldDispatchEvents) {
2345                 // for now we don't care if event handler cancels default behavior, since there is none
2346                 dispatchDragSrcEvent(eventNames().dragEvent, event);
2347             }
2348             accept = dispatchDragEvent(eventNames().dragenterEvent, *newTarget, event, dataTransfer);
2349             if (!accept)
2350                 accept = findDropZone(newTarget.get(), dataTransfer);
2351         }
2352
2353         if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
2354             if (targetFrame)
2355                 accept = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
2356         } else if (m_dragTarget)
2357             dispatchDragEvent(eventNames().dragleaveEvent, *m_dragTarget, event, dataTransfer);
2358
2359         if (newTarget) {
2360             // We do not explicitly call dispatchDragEvent here because it could ultimately result in the appearance that
2361             // two dragover events fired. So, we mark that we should only fire a dragover event on the next call to this function.
2362             m_shouldOnlyFireDragOverEvent = true;
2363         }
2364     } else {
2365         Frame* targetFrame;
2366         if (targetIsFrame(newTarget.get(), targetFrame)) {
2367             if (targetFrame)
2368                 accept = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
2369         } else if (newTarget) {
2370             // Note, when dealing with sub-frames, we may need to fire only a dragover event as a drag event may have been fired earlier.
2371             if (!m_shouldOnlyFireDragOverEvent && dragState().source && dragState().shouldDispatchEvents) {
2372                 // for now we don't care if event handler cancels default behavior, since there is none
2373                 dispatchDragSrcEvent(eventNames().dragEvent, event);
2374             }
2375             accept = dispatchDragEvent(eventNames().dragoverEvent, *newTarget, event, dataTransfer);
2376             if (!accept)
2377                 accept = findDropZone(newTarget.get(), dataTransfer);
2378             m_shouldOnlyFireDragOverEvent = false;
2379         }
2380     }
2381     m_dragTarget = newTarget.release();
2382     return accept;
2383 }
2384
2385 void EventHandler::cancelDragAndDrop(const PlatformMouseEvent& event, DataTransfer* dataTransfer)
2386 {
2387     Frame* targetFrame;
2388     if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
2389         if (targetFrame)
2390             targetFrame->eventHandler().cancelDragAndDrop(event, dataTransfer);
2391     } else if (m_dragTarget) {
2392         if (dragState().source && dragState().shouldDispatchEvents)
2393             dispatchDragSrcEvent(eventNames().dragEvent, event);
2394         dispatchDragEvent(eventNames().dragleaveEvent, *m_dragTarget, event, dataTransfer);
2395     }
2396     clearDragState();
2397 }
2398
2399 bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, DataTransfer* dataTransfer)
2400 {
2401     Frame* targetFrame;
2402     bool preventedDefault = false;
2403     if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
2404         if (targetFrame)
2405             preventedDefault = targetFrame->eventHandler().performDragAndDrop(event, dataTransfer);
2406     } else if (m_dragTarget)
2407         preventedDefault = dispatchDragEvent(eventNames().dropEvent, *m_dragTarget, event, dataTransfer);
2408     clearDragState();
2409     return preventedDefault;
2410 }
2411
2412 void EventHandler::clearDragState()
2413 {
2414     stopAutoscrollTimer();
2415     m_dragTarget = nullptr;
2416     m_capturingMouseEventsElement = nullptr;
2417     m_shouldOnlyFireDragOverEvent = false;
2418 #if PLATFORM(COCOA)
2419     m_sendingEventToSubview = false;
2420 #endif
2421 }
2422 #endif // ENABLE(DRAG_SUPPORT)
2423
2424 void EventHandler::setCapturingMouseEventsElement(PassRefPtr<Element> element)
2425 {
2426     m_capturingMouseEventsElement = element;
2427     m_eventHandlerWillResetCapturingMouseEventsElement = false;
2428 }
2429
2430 MouseEventWithHitTestResults EventHandler::prepareMouseEvent(const HitTestRequest& request, const PlatformMouseEvent& mouseEvent)
2431 {
2432     ASSERT(m_frame.document());
2433     return m_frame.document()->prepareMouseEvent(request, documentPointForWindowPoint(m_frame, mouseEvent.position()), mouseEvent);
2434 }
2435
2436 static RenderElement* nearestCommonHoverAncestor(RenderElement* obj1, RenderElement* obj2)
2437 {
2438     if (!obj1 || !obj2)
2439         return nullptr;
2440
2441     for (RenderElement* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
2442         for (RenderElement* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
2443             if (currObj1 == currObj2)
2444                 return currObj1;
2445         }
2446     }
2447
2448     return nullptr;
2449 }
2450
2451 static bool hierarchyHasCapturingEventListeners(Element* element, const AtomicString& eventName)
2452 {
2453     for (ContainerNode* curr = element; curr; curr = curr->parentOrShadowHostNode()) {
2454         if (curr->hasCapturingEventListeners(eventName))
2455             return true;
2456     }
2457     return false;
2458 }
2459
2460 void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMouseEvent& platformMouseEvent, bool fireMouseOverOut)
2461 {
2462     Element* targetElement = nullptr;
2463     
2464     // If we're capturing, we always go right to that element.
2465     if (m_capturingMouseEventsElement)
2466         targetElement = m_capturingMouseEventsElement.get();
2467     else if (targetNode) {
2468         // If the target node is a non-element, dispatch on the parent. <rdar://problem/4196646>
2469         if (!is<Element>(*targetNode))
2470             targetElement = targetNode->parentOrShadowHostElement();
2471         else
2472             targetElement = downcast<Element>(targetNode);
2473     }
2474
2475     m_elementUnderMouse = targetElement;
2476
2477     // Fire mouseout/mouseover if the mouse has shifted to a different node.
2478     if (fireMouseOverOut) {
2479         RenderLayer* layerForLastNode = layerForNode(m_lastElementUnderMouse.get());
2480         RenderLayer* layerForNodeUnderMouse = layerForNode(m_elementUnderMouse.get());
2481         Page* page = m_frame.page();
2482
2483         if (m_lastElementUnderMouse && (!m_elementUnderMouse || &m_elementUnderMouse->document() != m_frame.document())) {
2484             // The mouse has moved between frames.
2485             if (Frame* frame = m_lastElementUnderMouse->document().frame()) {
2486                 if (FrameView* frameView = frame->view())
2487                     frameView->mouseExitedContentArea();
2488             }
2489         } else if (page && (layerForLastNode && (!layerForNodeUnderMouse || layerForNodeUnderMouse != layerForLastNode))) {
2490             // The mouse has moved between layers.
2491             if (Frame* frame = m_lastElementUnderMouse->document().frame()) {
2492                 if (FrameView* frameView = frame->view()) {
2493                     if (frameView->containsScrollableArea(layerForLastNode))
2494                         layerForLastNode->mouseExitedContentArea();
2495                 }
2496             }
2497         }
2498
2499         if (m_elementUnderMouse && (!m_lastElementUnderMouse || &m_lastElementUnderMouse->document() != m_frame.document())) {
2500             // The mouse has moved between frames.
2501             if (Frame* frame = m_elementUnderMouse->document().frame()) {
2502                 if (FrameView* frameView = frame->view())
2503                     frameView->mouseEnteredContentArea();
2504             }
2505         } else if (page && (layerForNodeUnderMouse && (!layerForLastNode || layerForNodeUnderMouse != layerForLastNode))) {
2506             // The mouse has moved between layers.
2507             if (Frame* frame = m_elementUnderMouse->document().frame()) {
2508                 if (FrameView* frameView = frame->view()) {
2509                     if (frameView->containsScrollableArea(layerForNodeUnderMouse))
2510                         layerForNodeUnderMouse->mouseEnteredContentArea();
2511                 }
2512             }
2513         }
2514
2515         if (m_lastElementUnderMouse && &m_lastElementUnderMouse->document() != m_frame.document()) {
2516             m_lastElementUnderMouse = nullptr;
2517             m_lastScrollbarUnderMouse = nullptr;
2518         }
2519
2520         if (m_lastElementUnderMouse != m_elementUnderMouse) {
2521             // mouseenter and mouseleave events are only dispatched if there is a capturing eventhandler on an ancestor
2522             // or a normal eventhandler on the element itself (they don't bubble).
2523             // This optimization is necessary since these events can cause O(n^2) capturing event-handler checks.
2524             bool hasCapturingMouseEnterListener = hierarchyHasCapturingEventListeners(m_elementUnderMouse.get(), eventNames().mouseenterEvent);
2525             bool hasCapturingMouseLeaveListener = hierarchyHasCapturingEventListeners(m_lastElementUnderMouse.get(), eventNames().mouseleaveEvent);
2526
2527             RenderElement* oldHoverRenderer = m_lastElementUnderMouse ? m_lastElementUnderMouse->renderer() : nullptr;
2528             RenderElement* newHoverRenderer = m_elementUnderMouse ? m_elementUnderMouse->renderer() : nullptr;
2529             RenderElement* ancestor = nearestCommonHoverAncestor(oldHoverRenderer, newHoverRenderer);
2530
2531             Vector<Ref<Element>, 32> leftElementsChain;
2532             if (oldHoverRenderer) {
2533                 for (RenderElement* curr = oldHoverRenderer; curr && curr != ancestor; curr = curr->hoverAncestor()) {
2534                     if (Element* element = curr->element())
2535                         leftElementsChain.append(*element);
2536                 }
2537             } else {
2538                 // If the old hovered element is not null but it's renderer is, it was probably detached.
2539                 // In this case, the old hovered element (and its ancestors) must be updated, to ensure it's normal style is re-applied.
2540                 for (Element* element = m_lastElementUnderMouse.get(); element; element = element->parentElement())
2541                     leftElementsChain.append(*element);
2542             }
2543
2544             Vector<Ref<Element>, 32> enteredElementsChain;
2545             const Element* ancestorElement = ancestor ? ancestor->element() : nullptr;
2546             for (RenderElement* curr = newHoverRenderer; curr; curr = curr->hoverAncestor()) {
2547                 if (Element *element = curr->element()) {
2548                     if (element == ancestorElement)
2549                         break;
2550                     enteredElementsChain.append(*element);
2551                 }
2552             }
2553
2554             // Send mouseout event to the old node.
2555             if (m_lastElementUnderMouse)
2556                 m_lastElementUnderMouse->dispatchMouseEvent(platformMouseEvent, eventNames().mouseoutEvent, 0, m_elementUnderMouse.get());
2557
2558             // Send mouseleave to the node hierarchy no longer under the mouse.
2559             for (auto& chain : leftElementsChain) {
2560                 if (hasCapturingMouseLeaveListener || chain->hasEventListeners(eventNames().mouseleaveEvent))
2561                     chain->dispatchMouseEvent(platformMouseEvent, eventNames().mouseleaveEvent, 0, m_elementUnderMouse.get());
2562             }
2563
2564             // Send mouseover event to the new node.
2565             if (m_elementUnderMouse)
2566                 m_elementUnderMouse->dispatchMouseEvent(platformMouseEvent, eventNames().mouseoverEvent, 0, m_lastElementUnderMouse.get());
2567
2568             // Send mouseleave event to the nodes hierarchy under the mouse.
2569             for (auto& chain : enteredElementsChain) {
2570                 if (hasCapturingMouseEnterListener || chain->hasEventListeners(eventNames().mouseenterEvent))
2571                     chain->dispatchMouseEvent(platformMouseEvent, eventNames().mouseenterEvent, 0, m_lastElementUnderMouse.get());
2572             }
2573         }
2574         m_lastElementUnderMouse = m_elementUnderMouse;
2575     }
2576 }
2577
2578 bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targetNode, bool /*cancelable*/, int clickCount, const PlatformMouseEvent& platformMouseEvent, bool setUnder)
2579 {
2580     if (FrameView* view = m_frame.view())
2581         view->disableLayerFlushThrottlingTemporarilyForInteraction();
2582
2583     updateMouseEventTargetNode(targetNode, platformMouseEvent, setUnder);
2584
2585     bool swallowEvent = false;
2586
2587     if (m_elementUnderMouse)
2588         swallowEvent = !(m_elementUnderMouse->dispatchMouseEvent(platformMouseEvent, eventType, clickCount));
2589
2590     if (!swallowEvent && eventType == eventNames().mousedownEvent) {
2591
2592         // If clicking on a frame scrollbar, do not mess up with content focus.
2593         if (FrameView* view = m_frame.view()) {
2594             if (view->scrollbarAtPoint(platformMouseEvent.position()))
2595                 return true;
2596         }
2597
2598         // The layout needs to be up to date to determine if an element is focusable.
2599         m_frame.document()->updateLayoutIgnorePendingStylesheets();
2600
2601         // Blur current focus node when a link/button is clicked; this
2602         // is expected by some sites that rely on onChange handlers running
2603         // from form fields before the button click is processed.
2604
2605         Element* element = m_elementUnderMouse.get();
2606
2607         // Walk up the DOM tree to search for an element to focus.
2608         while (element) {
2609             if (element->isMouseFocusable()) {
2610                 // To fix <rdar://problem/4895428> Can't drag selected ToDo, we don't focus a
2611                 // node on mouse down if it's selected and inside a focused node. It will be
2612                 // focused if the user does a mouseup over it, however, because the mouseup
2613                 // will set a selection inside it, which will call setFocuseNodeIfNeeded.
2614                 if (m_frame.selection().isRange()
2615                     && m_frame.selection().toNormalizedRange()->compareNode(element, IGNORE_EXCEPTION) == Range::NODE_INSIDE
2616                     && element->isDescendantOf(m_frame.document()->focusedElement()))
2617                     return true;
2618                     
2619                 break;
2620             }
2621             element = element->parentOrShadowHostElement();
2622         }
2623
2624         // Only change the focus when clicking scrollbars if it can transfered to a mouse focusable node.
2625         if ((!element || !element->isMouseFocusable()) && isInsideScrollbar(platformMouseEvent.position()))
2626             return false;
2627
2628         // If focus shift is blocked, we eat the event.  Note we should never clear swallowEvent
2629         // if the page already set it (e.g., by canceling default behavior).
2630         if (Page* page = m_frame.page()) {
2631             if (element && element->isMouseFocusable()) {
2632                 if (!page->focusController().setFocusedElement(element, &m_frame))
2633                     swallowEvent = true;
2634             } else if (!element || !element->focused()) {
2635                 if (!page->focusController().setFocusedElement(0, &m_frame))
2636                     swallowEvent = true;
2637             }
2638         }
2639     }
2640
2641     return !swallowEvent;
2642 }
2643
2644 bool EventHandler::isInsideScrollbar(const IntPoint& windowPoint) const
2645 {
2646     if (RenderView* renderView = m_frame.contentRenderer()) {
2647         HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
2648         HitTestResult result(windowPoint);
2649         renderView->hitTest(request, result);
2650         return result.scrollbar();
2651     }
2652
2653     return false;
2654 }
2655
2656 #if !PLATFORM(GTK)
2657
2658 bool EventHandler::shouldTurnVerticalTicksIntoHorizontal(const HitTestResult&, const PlatformWheelEvent&) const
2659 {
2660     return false;
2661 }
2662
2663 #endif
2664
2665 #if !PLATFORM(MAC)
2666
2667 void EventHandler::platformPrepareForWheelEvents(const PlatformWheelEvent&, const HitTestResult&, RefPtr<Element>&, RefPtr<ContainerNode>&, ScrollableArea*&, bool&)
2668 {
2669 }
2670
2671 void EventHandler::platformRecordWheelEvent(const PlatformWheelEvent& event)
2672 {
2673     m_frame.mainFrame().wheelEventDeltaTracker()->recordWheelEventDelta(event);
2674 }
2675
2676 bool EventHandler::platformCompleteWheelEvent(const PlatformWheelEvent& event, ContainerNode*, ScrollableArea*)
2677 {
2678     // We do another check on the frame view because the event handler can run JS which results in the frame getting destroyed.
2679     FrameView* view = m_frame.view();
2680     
2681     bool didHandleEvent = view ? view->wheelEvent(event) : false;
2682     m_isHandlingWheelEvent = false;
2683     return didHandleEvent;
2684 }
2685
2686 bool EventHandler::platformCompletePlatformWidgetWheelEvent(const PlatformWheelEvent&, const Widget&, ContainerNode*)
2687 {
2688     return true;
2689 }
2690
2691 void EventHandler::platformNotifyIfEndGesture(const PlatformWheelEvent&, ScrollableArea*)
2692 {
2693 }
2694
2695 #endif
2696
2697 bool EventHandler::handleWheelEvent(const PlatformWheelEvent& event)
2698 {
2699     RenderView* renderView = m_frame.contentRenderer();
2700     if (!renderView)
2701         return false;
2702
2703     RefPtr<FrameView> protector(m_frame.view());
2704
2705     FrameView* view = m_frame.view();
2706     if (!view)
2707         return false;
2708
2709     m_isHandlingWheelEvent = true;
2710     setFrameWasScrolledByUser();
2711
2712     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
2713     HitTestResult result(view->windowToContents(event.position()));
2714     renderView->hitTest(request, result);
2715
2716     RefPtr<Element> element = result.innerElement();
2717     RefPtr<ContainerNode> scrollableContainer;
2718     ScrollableArea* scrollableArea = nullptr;
2719     bool isOverWidget = result.isOverWidget();
2720     platformPrepareForWheelEvents(event, result, element, scrollableContainer, scrollableArea, isOverWidget);
2721
2722 #if PLATFORM(MAC)
2723     if (event.phase() == PlatformWheelEventPhaseNone && event.momentumPhase() == PlatformWheelEventPhaseNone)
2724         m_frame.mainFrame().resetLatchingState();
2725 #endif
2726
2727     // FIXME: It should not be necessary to do this mutation here.
2728     // Instead, the handlers should know convert vertical scrolls appropriately.
2729     PlatformWheelEvent adjustedEvent = event;
2730     if (m_baseEventType == PlatformEvent::NoType && shouldTurnVerticalTicksIntoHorizontal(result, event))
2731         adjustedEvent = event.copyTurningVerticalTicksIntoHorizontalTicks();
2732
2733     platformRecordWheelEvent(adjustedEvent);
2734
2735     if (element) {
2736         if (isOverWidget) {
2737             RenderElement* target = element->renderer();
2738             if (is<RenderWidget>(target)) {
2739                 Widget* widget = downcast<RenderWidget>(*target).widget();
2740                 if (widget && passWheelEventToWidget(event, *widget)) {
2741                     m_isHandlingWheelEvent = false;
2742                     if (scrollableArea)
2743                         scrollableArea->setScrolledProgrammatically(false);
2744                     platformNotifyIfEndGesture(adjustedEvent, scrollableArea);
2745                     if (!widget->platformWidget())
2746                         return true;
2747                     return platformCompletePlatformWidgetWheelEvent(event, *widget, scrollableContainer.get());
2748                 }
2749             }
2750         }
2751
2752         if (!element->dispatchWheelEvent(adjustedEvent)) {
2753             m_isHandlingWheelEvent = false;
2754             if (scrollableArea && scrollableArea->isScrolledProgrammatically()) {
2755                 // Web developer is controlling scrolling, so don't attempt to latch.
2756                 clearLatchedState();
2757                 scrollableArea->setScrolledProgrammatically(false);
2758             }
2759
2760             platformNotifyIfEndGesture(adjustedEvent, scrollableArea);
2761             return true;
2762         }
2763     }
2764
2765     if (scrollableArea)
2766         scrollableArea->setScrolledProgrammatically(false);
2767
2768     bool handledEvent = platformCompleteWheelEvent(event, scrollableContainer.get(), scrollableArea);
2769     platformNotifyIfEndGesture(adjustedEvent, scrollableArea);
2770     return handledEvent;
2771 }
2772
2773 void EventHandler::clearLatchedState()
2774 {
2775 #if PLATFORM(MAC)
2776     m_frame.mainFrame().resetLatchingState();
2777 #endif
2778     m_frame.mainFrame().wheelEventDeltaTracker()->endTrackingDeltas();
2779 }
2780
2781 void EventHandler::defaultWheelEventHandler(Node* startNode, WheelEvent* wheelEvent)
2782 {
2783     if (!startNode || !wheelEvent)
2784         return;
2785     
2786     DominantScrollGestureDirection dominantDirection = DominantScrollGestureDirection::None;
2787
2788 #if PLATFORM(MAC)
2789     ScrollLatchingState* latchedState = m_frame.mainFrame().latchingState();
2790     Element* stopElement = latchedState ? latchedState->previousWheelScrolledElement() : nullptr;
2791
2792     // Workaround for scrolling issues <rdar://problem/14758615>.
2793     if (m_frame.mainFrame().wheelEventDeltaTracker()->isTrackingDeltas())
2794         dominantDirection = m_frame.mainFrame().wheelEventDeltaTracker()->dominantScrollGestureDirection();
2795 #else
2796     Element* stopElement = nullptr;
2797 #endif
2798     
2799     // Break up into two scrolls if we need to.  Diagonal movement on 
2800     // a MacBook pro is an example of a 2-dimensional mouse wheel event (where both deltaX and deltaY can be set).
2801     if (dominantDirection != DominantScrollGestureDirection::Vertical && handleWheelEventInAppropriateEnclosingBoxForSingleAxis(startNode, wheelEvent, &stopElement, ScrollEventAxis::Horizontal))
2802         wheelEvent->setDefaultHandled();
2803     
2804     if (dominantDirection != DominantScrollGestureDirection::Horizontal && handleWheelEventInAppropriateEnclosingBoxForSingleAxis(startNode, wheelEvent, &stopElement, ScrollEventAxis::Vertical))
2805         wheelEvent->setDefaultHandled();
2806     
2807 #if PLATFORM(MAC)
2808     if (latchedState && !latchedState->wheelEventElement())
2809         latchedState->setPreviousWheelScrolledElement(stopElement);
2810 #endif
2811 }
2812
2813 #if ENABLE(CONTEXT_MENUS)
2814 bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
2815 {
2816     Document* doc = m_frame.document();
2817     FrameView* v = m_frame.view();
2818     if (!v)
2819         return false;
2820     
2821     // Clear mouse press state to avoid initiating a drag while context menu is up.
2822     m_mousePressed = false;
2823     bool swallowEvent;
2824     LayoutPoint viewportPos = v->windowToContents(event.position());
2825     HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
2826     MouseEventWithHitTestResults mouseEvent = doc->prepareMouseEvent(request, viewportPos, event);
2827
2828     if (m_frame.editor().behavior().shouldSelectOnContextualMenuClick()
2829         && !m_frame.selection().contains(viewportPos)
2830         && !mouseEvent.scrollbar()
2831         // FIXME: In the editable case, word selection sometimes selects content that isn't underneath the mouse.
2832         // If the selection is non-editable, we do word selection to make it easier to use the contextual menu items
2833         // available for text selections.  But only if we're above text.
2834         && (m_frame.selection().selection().isContentEditable() || (mouseEvent.targetNode() && mouseEvent.targetNode()->isTextNode()))) {
2835         m_mouseDownMayStartSelect = true; // context menu events are always allowed to perform a selection
2836         selectClosestContextualWordOrLinkFromMouseEvent(mouseEvent);
2837     }
2838
2839     swallowEvent = !dispatchMouseEvent(eventNames().contextmenuEvent, mouseEvent.targetNode(), true, 0, event, false);
2840     
2841     return swallowEvent;
2842 }
2843
2844 bool EventHandler::sendContextMenuEventForKey()
2845 {
2846     FrameView* view = m_frame.view();
2847     if (!view)
2848         return false;
2849
2850     Document* doc = m_frame.document();
2851     if (!doc)
2852         return false;
2853
2854     // Clear mouse press state to avoid initiating a drag while context menu is up.
2855     m_mousePressed = false;
2856
2857     static const int kContextMenuMargin = 1;
2858
2859 #if OS(WINDOWS)
2860     int rightAligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
2861 #else
2862     int rightAligned = 0;
2863 #endif
2864     IntPoint location;
2865
2866     Element* focusedElement = doc->focusedElement();
2867     const VisibleSelection& selection = m_frame.selection().selection();
2868     Position start = selection.start();
2869
2870     if (start.deprecatedNode() && (selection.rootEditableElement() || selection.isRange())) {
2871         RefPtr<Range> selectionRange = selection.toNormalizedRange();
2872         IntRect firstRect = m_frame.editor().firstRectForRange(selectionRange.get());
2873
2874         int x = rightAligned ? firstRect.maxX() : firstRect.x();
2875         // In a multiline edit, firstRect.maxY() would endup on the next line, so -1.
2876         int y = firstRect.maxY() ? firstRect.maxY() - 1 : 0;
2877         location = IntPoint(x, y);
2878     } else if (focusedElement) {
2879         RenderBoxModelObject* box = focusedElement->renderBoxModelObject();
2880         if (!box)
2881             return false;
2882         IntRect clippedRect = box->pixelSnappedAbsoluteClippedOverflowRect();
2883         location = IntPoint(clippedRect.x(), clippedRect.maxY() - 1);
2884     } else {
2885         location = IntPoint(
2886             rightAligned ? view->contentsWidth() - kContextMenuMargin : kContextMenuMargin,
2887             kContextMenuMargin);
2888     }
2889
2890     m_frame.view()->setCursor(pointerCursor());
2891
2892     IntPoint position = view->contentsToRootView(location);
2893     IntPoint globalPosition = view->hostWindow()->rootViewToScreen(IntRect(position, IntSize())).location();
2894
2895     Node* targetNode = doc->focusedElement();
2896     if (!targetNode)
2897         targetNode = doc;
2898
2899     // Use the focused node as the target for hover and active.
2900     HitTestResult result(position);
2901     result.setInnerNode(targetNode);
2902     doc->updateHoverActiveState(HitTestRequest::Active | HitTestRequest::DisallowShadowContent, result.innerElement());
2903
2904     // The contextmenu event is a mouse event even when invoked using the keyboard.
2905     // This is required for web compatibility.
2906
2907 #if OS(WINDOWS)
2908     PlatformEvent::Type eventType = PlatformEvent::MouseReleased;
2909 #else
2910     PlatformEvent::Type eventType = PlatformEvent::MousePressed;
2911 #endif
2912
2913     PlatformMouseEvent platformMouseEvent(position, globalPosition, RightButton, eventType, 1, false, false, false, false, WTF::currentTime(), ForceAtClick);
2914
2915     return !dispatchMouseEvent(eventNames().contextmenuEvent, targetNode, true, 0, platformMouseEvent, false);
2916 }
2917 #endif // ENABLE(CONTEXT_MENUS)
2918
2919 void EventHandler::scheduleHoverStateUpdate()
2920 {
2921     if (!m_hoverTimer.isActive())
2922         m_hoverTimer.startOneShot(0);
2923 }
2924
2925 #if ENABLE(CURSOR_SUPPORT)
2926 void EventHandler::scheduleCursorUpdate()
2927 {
2928     if (!m_cursorUpdateTimer.isActive())
2929         m_cursorUpdateTimer.startOneShot(cursorUpdateInterval);
2930 }
2931 #endif
2932
2933 void EventHandler::dispatchFakeMouseMoveEventSoon()
2934 {
2935 #if !ENABLE(IOS_TOUCH_EVENTS)
2936     if (m_mousePressed)
2937         return;
2938
2939     if (m_mousePositionIsUnknown)
2940         return;
2941
2942     if (Page* page = m_frame.page()) {
2943         if (!page->chrome().client().shouldDispatchFakeMouseMoveEvents())
2944             return;
2945     }
2946
2947     // If the content has ever taken longer than fakeMouseMoveShortInterval we
2948     // reschedule the timer and use a longer time. This will cause the content
2949     // to receive these moves only after the user is done scrolling, reducing
2950     // pauses during the scroll.
2951     if (m_fakeMouseMoveEventTimer.isActive())
2952         m_fakeMouseMoveEventTimer.stop();
2953     m_fakeMouseMoveEventTimer.startOneShot(m_maxMouseMovedDuration > fakeMouseMoveDurationThreshold ? fakeMouseMoveLongInterval : fakeMouseMoveShortInterval);
2954 #endif
2955 }
2956
2957 void EventHandler::dispatchFakeMouseMoveEventSoonInQuad(const FloatQuad& quad)
2958 {
2959 #if ENABLE(IOS_TOUCH_EVENTS)
2960     UNUSED_PARAM(quad);
2961 #else
2962     FrameView* view = m_frame.view();
2963     if (!view)
2964         return;
2965
2966     if (!quad.containsPoint(view->windowToContents(m_lastKnownMousePosition)))
2967         return;
2968
2969     dispatchFakeMouseMoveEventSoon();
2970 #endif
2971 }
2972
2973 #if !ENABLE(IOS_TOUCH_EVENTS)
2974 void EventHandler::cancelFakeMouseMoveEvent()
2975 {
2976     m_fakeMouseMoveEventTimer.stop();
2977 }
2978
2979 void EventHandler::fakeMouseMoveEventTimerFired()
2980 {
2981     ASSERT(!m_mousePressed);
2982
2983     FrameView* view = m_frame.view();
2984     if (!view)
2985         return;
2986
2987     if (!m_frame.page() || !m_frame.page()->isVisible() || !m_frame.page()->focusController().isActive())
2988         return;
2989
2990     bool shiftKey;
2991     bool ctrlKey;
2992     bool altKey;
2993     bool metaKey;
2994     PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
2995     PlatformMouseEvent fakeMouseMoveEvent(m_lastKnownMousePosition, m_lastKnownMouseGlobalPosition, NoButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey, metaKey, currentTime(), 0);
2996     mouseMoved(fakeMouseMoveEvent);
2997 }
2998 #endif // !ENABLE(IOS_TOUCH_EVENTS)
2999
3000 void EventHandler::setResizingFrameSet(HTMLFrameSetElement* frameSet)
3001 {
3002     m_frameSetBeingResized = frameSet;
3003 }
3004
3005 void EventHandler::resizeLayerDestroyed()
3006 {
3007     ASSERT(m_resizeLayer);
3008     m_resizeLayer = nullptr;
3009 }
3010
3011 void EventHandler::hoverTimerFired()
3012 {
3013     m_hoverTimer.stop();
3014
3015     ASSERT(m_frame.document());
3016
3017     if (RenderView* renderView = m_frame.contentRenderer()) {
3018         if (FrameView* view = m_frame.view()) {
3019             HitTestRequest request(HitTestRequest::Move | HitTestRequest::DisallowShadowContent);
3020             HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
3021             renderView->hitTest(request, result);
3022             m_frame.document()->updateHoverActiveState(request, result.innerElement());
3023         }
3024     }
3025 }
3026
3027 bool EventHandler::handleAccessKey(const PlatformKeyboardEvent& evt)
3028 {
3029     // FIXME: Ignoring the state of Shift key is what neither IE nor Firefox do.
3030     // IE matches lower and upper case access keys regardless of Shift key state - but if both upper and
3031     // lower case variants are present in a document, the correct element is matched based on Shift key state.
3032     // Firefox only matches an access key if Shift is not pressed, and does that case-insensitively.
3033     ASSERT(!(accessKeyModifiers() & PlatformEvent::ShiftKey));
3034     if ((evt.modifiers() & ~PlatformEvent::ShiftKey) != accessKeyModifiers())
3035         return false;
3036     String key = evt.unmodifiedText();
3037     Element* elem = m_frame.document()->getElementByAccessKey(key.lower());
3038     if (!elem)
3039         return false;
3040     elem->accessKeyAction(false);
3041     return true;
3042 }
3043
3044 #if !PLATFORM(MAC)
3045 bool EventHandler::needsKeyboardEventDisambiguationQuirks() const
3046 {
3047     return false;
3048 }
3049 #endif
3050
3051 #if ENABLE(FULLSCREEN_API)
3052 bool EventHandler::isKeyEventAllowedInFullScreen(const PlatformKeyboardEvent& keyEvent) const
3053 {
3054     Document* document = m_frame.document();
3055     if (document->webkitFullScreenKeyboardInputAllowed())
3056         return true;
3057
3058     if (keyEvent.type() == PlatformKeyboardEvent::Char) {
3059         if (keyEvent.text().length() != 1)
3060             return false;
3061         UChar character = keyEvent.text()[0];
3062         return character == ' ';
3063     }
3064
3065     int keyCode = keyEvent.windowsVirtualKeyCode();
3066     return (keyCode >= VK_BACK && keyCode <= VK_CAPITAL)
3067         || (keyCode >= VK_SPACE && keyCode <= VK_DELETE)
3068         || (keyCode >= VK_OEM_1 && keyCode <= VK_OEM_PLUS)
3069         || (keyCode >= VK_MULTIPLY && keyCode <= VK_OEM_8);
3070 }
3071 #endif
3072
3073 bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
3074 {
3075     RefPtr<FrameView> protector(m_frame.view());
3076
3077 #if ENABLE(FULLSCREEN_API)
3078     if (m_frame.document()->webkitIsFullScreen() && !isKeyEventAllowedInFullScreen(initialKeyEvent))
3079         return false;
3080 #endif
3081
3082     if (initialKeyEvent.windowsVirtualKeyCode() == VK_CAPITAL) {
3083         if (auto* element = m_frame.document()->focusedElement()) {
3084             if (is<HTMLInputElement>(*element))
3085                 downcast<HTMLInputElement>(*element).capsLockStateMayHaveChanged();
3086         }
3087     }
3088
3089 #if ENABLE(PAN_SCROLLING)
3090     if (m_frame.mainFrame().eventHandler().panScrollInProgress()) {
3091         // If a key is pressed while the panScroll is in progress then we want to stop
3092         if (initialKeyEvent.type() == PlatformEvent::KeyDown || initialKeyEvent.type() == PlatformEvent::RawKeyDown)
3093             stopAutoscrollTimer();
3094
3095         // If we were in panscroll mode, we swallow the key event
3096         return true;
3097     }
3098 #endif
3099
3100     // Check for cases where we are too early for events -- possible unmatched key up
3101     // from pressing return in the location bar.
3102     RefPtr<Element> element = eventTargetElementForDocument(m_frame.document());
3103     if (!element)
3104         return false;
3105
3106     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture, m_frame.document());
3107     UserTypingGestureIndicator typingGestureIndicator(m_frame);
3108
3109     if (FrameView* view = m_frame.view())
3110         view->disableLayerFlushThrottlingTemporarilyForInteraction();
3111
3112     // FIXME (bug 68185): this call should be made at another abstraction layer
3113     m_frame.loader().resetMultipleFormSubmissionProtection();
3114
3115     // In IE, access keys are special, they are handled after default keydown processing, but cannot be canceled - this is hard to match.
3116     // On Mac OS X, we process them before dispatching keydown, as the default keydown handler implements Emacs key bindings, which may conflict
3117     // with access keys. Then we dispatch keydown, but suppress its default handling.
3118     // On Windows, WebKit explicitly calls handleAccessKey() instead of dispatching a keypress event for WM_SYSCHAR messages.
3119     // Other platforms currently match either Mac or Windows behavior, depending on whether they send combined KeyDown events.
3120     bool matchedAnAccessKey = false;
3121     if (initialKeyEvent.type() == PlatformEvent::KeyDown)
3122         matchedAnAccessKey = handleAccessKey(initialKeyEvent);
3123
3124     // FIXME: it would be fair to let an input method handle KeyUp events before DOM dispatch.
3125     if (initialKeyEvent.type() == PlatformEvent::KeyUp || initialKeyEvent.type() == PlatformEvent::Char)
3126         return !element->dispatchKeyEvent(initialKeyEvent);
3127
3128     bool backwardCompatibilityMode = needsKeyboardEventDisambiguationQuirks();
3129
3130     PlatformKeyboardEvent keyDownEvent = initialKeyEvent;    
3131     if (keyDownEvent.type() != PlatformEvent::RawKeyDown)
3132         keyDownEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown, backwardCompatibilityMode);
3133     RefPtr<KeyboardEvent> keydown = KeyboardEvent::create(keyDownEvent, m_frame.document()->defaultView());
3134     if (matchedAnAccessKey)
3135         keydown->setDefaultPrevented(true);
3136     keydown->setTarget(element);
3137
3138     if (initialKeyEvent.type() == PlatformEvent::RawKeyDown) {
3139         element->dispatchEvent(keydown, IGNORE_EXCEPTION);
3140         // If frame changed as a result of keydown dispatch, then return true to avoid sending a subsequent keypress message to the new frame.
3141         bool changedFocusedFrame = m_frame.page() && &m_frame != &m_frame.page()->focusController().focusedOrMainFrame();
3142         return keydown->defaultHandled() || keydown->defaultPrevented() || changedFocusedFrame;
3143     }
3144
3145     // Run input method in advance of DOM event handling.  This may result in the IM
3146     // modifying the page prior the keydown event, but this behaviour is necessary
3147     // in order to match IE:
3148     // 1. preventing default handling of keydown and keypress events has no effect on IM input;
3149     // 2. if an input method handles the event, its keyCode is set to 229 in keydown event.
3150     m_frame.editor().handleInputMethodKeydown(keydown.get());
3151     
3152     bool handledByInputMethod = keydown->defaultHandled();
3153     
3154     if (handledByInputMethod) {
3155         keyDownEvent.setWindowsVirtualKeyCode(CompositionEventKeyCode);
3156         keydown = KeyboardEvent::create(keyDownEvent, m_frame.document()->defaultView());
3157         keydown->setTarget(element);
3158         keydown->setDefaultHandled();
3159     }
3160     
3161     if (accessibilityPreventsEventPropogation(keydown.get()))
3162         keydown->stopPropagation();
3163
3164     element->dispatchEvent(keydown, IGNORE_EXCEPTION);
3165     // If frame changed as a result of keydown dispatch, then return early to avoid sending a subsequent keypress message to the new frame.
3166     bool changedFocusedFrame = m_frame.page() && &m_frame != &m_frame.page()->focusController().focusedOrMainFrame();
3167     bool keydownResult = keydown->defaultHandled() || keydown->defaultPrevented() || changedFocusedFrame;
3168     if (handledByInputMethod || (keydownResult && !backwardCompatibilityMode))
3169         return keydownResult;
3170     
3171     // Focus may have changed during keydown handling, so refetch element.
3172     // But if we are dispatching a fake backward compatibility keypress, then we pretend that the keypress happened on the original element.
3173     if (!keydownResult) {
3174         element = eventTargetElementForDocument(m_frame.document());
3175         if (!element)
3176             return false;
3177     }
3178
3179     PlatformKeyboardEvent keyPressEvent = initialKeyEvent;
3180     keyPressEvent.disambiguateKeyDownEvent(PlatformEvent::Char, backwardCompatibilityMode);
3181     if (keyPressEvent.text().isEmpty())
3182         return keydownResult;
3183     RefPtr<KeyboardEvent> keypress = KeyboardEvent::create(keyPressEvent, m_frame.document()->defaultView());
3184     keypress->setTarget(element);
3185     if (keydownResult)
3186         keypress->setDefaultPrevented(true);
3187 #if PLATFORM(COCOA)
3188     keypress->keypressCommands() = keydown->keypressCommands();
3189 #endif
3190     element->dispatchEvent(keypress, IGNORE_EXCEPTION);
3191
3192     return keydownResult || keypress->defaultPrevented() || keypress->defaultHandled();
3193 }
3194
3195 static FocusDirection focusDirectionForKey(const AtomicString& keyIdentifier)
3196 {
3197     DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, Down, ("Down", AtomicString::ConstructFromLiteral));
3198     DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, Up, ("Up", AtomicString::ConstructFromLiteral));
3199     DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, Left, ("Left", AtomicString::ConstructFromLiteral));
3200     DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, Right, ("Right", AtomicString::ConstructFromLiteral));
3201
3202     FocusDirection retVal = FocusDirectionNone;
3203
3204     if (keyIdentifier == Down)
3205         retVal = FocusDirectionDown;
3206     else if (keyIdentifier == Up)
3207         retVal = FocusDirectionUp;
3208     else if (keyIdentifier == Left)
3209         retVal = FocusDirectionLeft;
3210     else if (keyIdentifier == Right)
3211         retVal = FocusDirectionRight;
3212
3213     return retVal;
3214 }
3215
3216 static void setInitialKeyboardSelection(Frame& frame, SelectionDirection direction)
3217 {
3218     Document* document = frame.document();
3219     if (!document)
3220         return;
3221
3222     FrameSelection& selection = frame.selection();
3223
3224     if (!selection.isNone())
3225         return;
3226
3227     Element* focusedElement = document->focusedElement();
3228     VisiblePosition visiblePosition;
3229
3230     switch (direction) {
3231     case DirectionBackward:
3232     case DirectionLeft:
3233         if (focusedElement)
3234             visiblePosition = VisiblePosition(positionBeforeNode(focusedElement));
3235         else
3236             visiblePosition = endOfDocument(document);
3237         break;
3238     case DirectionForward:
3239     case DirectionRight:
3240         if (focusedElement)
3241             visiblePosition = VisiblePosition(positionAfterNode(focusedElement));
3242         else
3243             visiblePosition = startOfDocument(document);
3244         break;
3245     }
3246
3247     AXTextStateChangeIntent intent(AXTextStateChangeTypeSelectionMove, AXTextSelection { AXTextSelectionDirectionDiscontiguous, AXTextSelectionGranularityUnknown, false });
3248     selection.setSelection(visiblePosition, FrameSelection::defaultSetSelectionOptions(UserTriggered), intent);
3249 }
3250
3251 static void handleKeyboardSelectionMovement(Frame& frame, KeyboardEvent* event)
3252 {
3253     if (!event)
3254         return;
3255
3256     FrameSelection& selection = frame.selection();
3257
3258     bool isCommanded = event->getModifierState("Meta");
3259     bool isOptioned = event->getModifierState("Alt");
3260     bool isSelection = !selection.isNone();
3261
3262     FrameSelection::EAlteration alternation = event->getModifierState("Shift") ? FrameSelection::AlterationExtend : FrameSelection::AlterationMove;
3263     SelectionDirection direction = DirectionForward;
3264     TextGranularity granularity = CharacterGranularity;
3265
3266     switch (focusDirectionForKey(event->keyIdentifier())) {
3267     case FocusDirectionNone:
3268         return;
3269     case FocusDirectionForward:
3270     case FocusDirectionBackward:
3271         ASSERT_NOT_REACHED();
3272         return;
3273     case FocusDirectionUp:
3274         direction = DirectionBackward;
3275         granularity = isCommanded ? DocumentBoundary : LineGranularity;
3276         break;
3277     case FocusDirectionDown:
3278         direction = DirectionForward;
3279         granularity = isCommanded ? DocumentBoundary : LineGranularity;
3280         break;
3281     case FocusDirectionLeft:
3282         direction = DirectionLeft;
3283         granularity = (isCommanded) ? LineBoundary : (isOptioned) ? WordGranularity : CharacterGranularity;
3284         break;
3285     case FocusDirectionRight:
3286         direction = DirectionRight;
3287         granularity = (isCommanded) ? LineBoundary : (isOptioned) ? WordGranularity : CharacterGranularity;
3288         break;
3289     }
3290
3291     if (isSelection)
3292         selection.modify(alternation, direction, granularity, UserTriggered);
3293     else
3294         setInitialKeyboardSelection(frame, direction);
3295
3296     event->setDefaultHandled();
3297 }
3298
3299 void EventHandler::handleKeyboardSelectionMovementForAccessibility(KeyboardEvent* event)
3300 {
3301     if (event->type() == eventNames().keydownEvent) {
3302         if (AXObjectCache::accessibilityEnhancedUserInterfaceEnabled())
3303             handleKeyboardSelectionMovement(m_frame, event);
3304     }
3305 }
3306
3307 bool EventHandler::accessibilityPreventsEventPropogation(KeyboardEvent* event)
3308 {
3309 #if PLATFORM(COCOA)
3310     if (!AXObjectCache::accessibilityEnhancedUserInterfaceEnabled())
3311         return false;
3312
3313     if (!m_frame.settings().preventKeyboardDOMEventDispatch())
3314         return false;
3315
3316     // Check for key events that are relevant to accessibility: tab and arrows keys that change focus
3317     if (event->keyIdentifier() == "U+0009")
3318         return true;
3319     FocusDirection direction = focusDirectionForKey(event->keyIdentifier());
3320     if (direction != FocusDirectionNone)
3321         return true;
3322 #else
3323     UNUSED_PARAM(event);
3324 #endif
3325     return false;
3326 }
3327
3328 void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
3329 {
3330     if (event->type() == eventNames().keydownEvent) {
3331         m_frame.editor().handleKeyboardEvent(event);
3332         if (event->defaultHandled())
3333             return;
3334         if (event->keyIdentifier() == "U+0009")
3335             defaultTabEventHandler(event);
3336         else if (event->keyIdentifier() == "U+0008")
3337             defaultBackspaceEventHandler(event);
3338         else {
3339             FocusDirection direction = focusDirectionForKey(event->keyIdentifier());
3340             if (direction != FocusDirectionNone)
3341                 defaultArrowEventHandler(direction, event);
3342         }
3343
3344         handleKeyboardSelectionMovementForAccessibility(event);
3345     }
3346     if (event->type() == eventNames().keypressEvent) {
3347         m_frame.editor().handleKeyboardEvent(event);
3348         if (event->defaultHandled())
3349             return;
3350         if (event->charCode() == ' ')
3351             defaultSpaceEventHandler(event);
3352     }
3353 }
3354
3355 #if ENABLE(DRAG_SUPPORT)
3356 bool EventHandler::dragHysteresisExceeded(const IntPoint& floatDragViewportLocation) const
3357 {
3358     FloatPoint dragViewportLocation(floatDragViewportLocation.x(), floatDragViewportLocation.y());
3359     return dragHysteresisExceeded(dragViewportLocation);
3360 }
3361
3362 bool EventHandler::dragHysteresisExceeded(const FloatPoint& dragViewportLocation) const
3363 {
3364     int threshold = GeneralDragHysteresis;
3365     switch (dragState().type) {
3366     case DragSourceActionSelection:
3367         threshold = TextDragHysteresis;
3368         break;
3369     case DragSourceActionImage:
3370 #if ENABLE(ATTACHMENT_ELEMENT)
3371     case DragSourceActionAttachment:
3372 #endif
3373         threshold = ImageDragHysteresis;
3374         break;
3375     case DragSourceActionLink:
3376         threshold = LinkDragHysteresis;
3377         break;
3378     case DragSourceActionDHTML:
3379         break;
3380     case DragSourceActionNone:
3381     case DragSourceActionAny:
3382         ASSERT_NOT_REACHED();
3383     }
3384     
3385     return mouseMovementExceedsThreshold(dragViewportLocation, threshold);
3386 }
3387     
3388 void EventHandler::freeDataTransfer()
3389 {
3390     if (!dragState().dataTransfer)
3391         return;
3392     dragState().dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb);
3393     dragState().dataTransfer = nullptr;
3394 }
3395
3396 void EventHandler::dragSourceEndedAt(const PlatformMouseEvent& event, DragOperation operation)
3397 {
3398     // Send a hit test request so that RenderLayer gets a chance to update the :hover and :active pseudoclasses.
3399     HitTestRequest request(HitTestRequest::Release | HitTestRequest::DisallowShadowContent);
3400     prepareMouseEvent(request, event);
3401
3402     if (dragState().source && dragState().shouldDispatchEvents) {
3403         dragState().dataTransfer->setDestinationOperation(operation);
3404         // For now we don't care if event handler cancels default behavior, since there is no default behavior.
3405         dispatchDragSrcEvent(eventNames().dragendEvent, event);
3406     }
3407     freeDataTransfer();
3408     dragState().source = nullptr;
3409     // In case the drag was ended due to an escape key press we need to ensure
3410     // that consecutive mousemove events don't reinitiate the drag and drop.
3411     m_mouseDownMayStartDrag = false;
3412 }
3413
3414 void EventHandler::updateDragStateAfterEditDragIfNeeded(Element* rootEditableElement)
3415 {
3416     // If inserting the dragged contents removed the drag source, we still want to fire dragend at the root editable element.
3417     if (dragState().source && !dragState().source->inDocument())
3418         dragState().source = rootEditableElement;
3419 }
3420
3421 // Return value indicates if we should continue "default processing", i.e., whether event handler canceled.
3422 bool EventHandler::dispatchDragSrcEvent(const AtomicString& eventType, const PlatformMouseEvent& event)
3423 {
3424     return !dispatchDragEvent(eventType, *dragState().source, event, dragState().dataTransfer.get());
3425 }
3426     
3427 static bool ExactlyOneBitSet(DragSourceAction n)
3428 {
3429     return n && !(n & (n - 1));
3430 }
3431
3432 bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDragHysteresis checkDragHysteresis)
3433 {
3434     if (event.event().button() != LeftButton || event.event().type() != PlatformEvent::MouseMoved) {
3435         // If we allowed the other side of the bridge to handle a drag
3436         // last time, then m_mousePressed might still be set. So we
3437         // clear it now to make sure the next move after a drag
3438         // doesn't look like a drag.
3439         m_mousePressed = false;
3440         return false;
3441     }
3442     
3443     if (eventLoopHandleMouseDragged(event))
3444         return true;
3445     
3446     // Careful that the drag starting logic stays in sync with eventMayStartDrag()
3447     
3448     if (m_mouseDownMayStartDrag && !dragState().source) {
3449         dragState().shouldDispatchEvents = (updateDragSourceActionsAllowed() & DragSourceActionDHTML);
3450
3451         // try to find an element that wants to be dragged
3452         HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
3453         HitTestResult result(m_mouseDownPos);
3454         m_frame.contentRenderer()->hitTest(request, result);
3455         if (m_frame.page())
3456             dragState().source = m_frame.page()->dragController().draggableElement(&m_frame, result.innerElement(), m_mouseDownPos, dragState());
3457         
3458         if (!dragState().source)
3459             m_mouseDownMayStartDrag = false; // no element is draggable
3460         else
3461             m_dragMayStartSelectionInstead = (dragState().type & DragSourceActionSelection);
3462     }
3463     
3464     // For drags starting in the selection, the user must wait between the mousedown and mousedrag,
3465     // or else we bail on the dragging stuff and allow selection to occur
3466     if (m_mouseDownMayStartDrag && m_dragMayStartSelectionInstead && (dragState().type & DragSourceActionSelection) && event.event().timestamp() - m_mouseDownTimestamp < TextDragDelay) {
3467         ASSERT(event.event().type() == PlatformEvent::MouseMoved);
3468         if ((dragState().type & DragSourceActionImage)) {
3469             // ... unless the mouse is over an image, then we start dragging just the image
3470             dragState().type = DragSourceActionImage;
3471         } else if (!(dragState().type & (DragSourceActionDHTML | DragSourceActionLink))) {
3472             // ... but only bail if we're not over an unselectable element.
3473             m_mouseDownMayStartDrag = false;
3474             dragState().source = nullptr;
3475             // ... but if this was the first click in the window, we don't even want to start selection
3476             if (eventActivatedView(event.event()))
3477                 m_mouseDownMayStartSelect = false;
3478         } else {
3479             // Prevent the following case from occuring:
3480             // 1. User starts a drag immediately after mouse down over an unselectable element.
3481             // 2. We enter this block and decided that since we're over an unselectable element, don't cancel the drag.
3482             // 3. The drag gets resolved as a potential selection drag below /but/ we haven't exceeded the drag hysteresis yet.
3483             // 4. We enter this block again, and since it's now marked as a selection drag, we cancel the drag.
3484             m_dragMayStartSelectionInstead = false;
3485         }
3486     }
3487     
3488     if (!m_mouseDownMayStartDrag)
3489         return !mouseDownMayStartSelect() && !m_mouseDownMayStartAutoscroll;
3490     
3491     if (!ExactlyOneBitSet(dragState().type)) {
3492         ASSERT((dragState().type & DragSourceActionSelection));
3493 #if ENABLE(ATTACHMENT_ELEMENT)
3494         ASSERT((dragState().type & ~DragSourceActionSelection) == DragSourceActionDHTML
3495                || (dragState().type & ~DragSourceActionSelection) == DragSourceActionImage
3496                || (dragState().type & ~DragSourceActionSelection) == DragSourceActionAttachment
3497                || (dragState().type & ~DragSourceActionSelection) == DragSourceActionLink);
3498 #else
3499         ASSERT((dragState().type & ~DragSourceActionSelection) == DragSourceActionDHTML
3500             || (dragState().type & ~DragSourceActionSelection) == DragSourceActionImage
3501             || (dragState().type & ~DragSourceActionSelection) == DragSourceActionLink);
3502 #endif
3503         dragState().type = DragSourceActionSelection;
3504     }
3505
3506     // We are starting a text/image/url drag, so the cursor should be an arrow
3507     if (FrameView* view = m_frame.view()) {
3508         // FIXME <rdar://7577595>: Custom cursors aren't supported during drag and drop (default to pointer).
3509         view->setCursor(pointerCursor());
3510     }
3511
3512     if (checkDragHysteresis == ShouldCheckDragHysteresis && !dragHysteresisExceeded(event.event().position()))
3513         return true;
3514     
3515     // Once we're past the hysteresis point, we don't want to treat this gesture as a click
3516     invalidateClick();
3517     
3518     DragOperation srcOp = DragOperationNone;      
3519     
3520     // This does work only if we missed a dragEnd. Do it anyway, just to make sure the old dataTransfer gets numbed.
3521     freeDataTransfer();
3522
3523     dragState().dataTransfer = createDraggingDataTransfer();
3524     
3525     if (dragState().shouldDispatchEvents) {
3526         // Check to see if the is a DOM based drag. If it is, get the DOM specified drag image and offset.
3527         if (dragState().type == DragSourceActionDHTML) {
3528             if (RenderObject* renderer = dragState().source->renderer()) {
3529                 // FIXME: This doesn't work correctly with transforms.
3530                 FloatPoint absPos = renderer->localToAbsolute();
3531                 IntSize delta = m_mouseDownPos - roundedIntPoint(absPos);
3532                 dragState().dataTransfer->setDragImage(dragState().source.get(), delta.width(), delta.height());
3533             } else {
3534                 // The renderer has disappeared, this can happen if the onStartDrag handler has hidden
3535                 // the element in some way.  In this case we just kill the drag.
3536                 m_mouseDownMayStartDrag = false;
3537                 goto cleanupDrag;
3538             }
3539         } 
3540         
3541         m_mouseDownMayStartDrag = dispatchDragSrcEvent(eventNames().dragstartEvent, m_mouseDown)
3542             && !m_frame.selection().selection().isInPasswordField();
3543         
3544         // Invalidate dataTransfer here against anymore pasteboard writing for security. The drag
3545         // image can still be changed as we drag, but not the pasteboard data.
3546         dragState().dataTransfer->setAccessPolicy(DataTransferAccessPolicy::ImageWritable);
3547         
3548         if (m_mouseDownMayStartDrag) {
3549             // Gather values from DHTML element, if it set any.
3550             srcOp = dragState().dataTransfer->sourceOperation();
3551             
3552             // Yuck, a draggedImage:moveTo: message can be fired as a result of kicking off the
3553             // drag with dragImage! Because of that dumb reentrancy, we may think we've not
3554             // started the drag when that happens. So we have to assume it's started before we kick it off.
3555             dragState().dataTransfer->setDragHasStarted();
3556         }
3557     }
3558     
3559     if (m_mouseDownMayStartDrag) {
3560         Page* page = m_frame.page();
3561         m_didStartDrag = page && page->dragController().startDrag(m_frame, dragState(), srcOp, event.event(), m_mouseDownPos);
3562         // In WebKit2 we could re-enter this code and start another drag.
3563         // On OS X this causes problems with the ownership of the pasteboard and the promised types.
3564         if (m_didStartDrag) {
3565             m_mouseDownMayStartDrag = false;
3566
3567             cancelTrackingPotentialLongMousePress();
3568             return true;
3569         }
3570         if (dragState().source && dragState().shouldDispatchEvents) {
3571             // Drag was canned at the last minute. We owe dragSource a dragend event.
3572             dispatchDragSrcEvent(eventNames().dragendEvent, event.event());
3573             m_mouseDownMayStartDrag = false;
3574         }
3575     } 
3576
3577 cleanupDrag:
3578     if (!m_mouseDownMayStartDrag) {
3579         // Something failed to start the drag, clean up.
3580         freeDataTransfer();
3581         dragState().source = nullptr;
3582     }
3583     
3584     // No more default handling (like selection), whether we're past the hysteresis bounds or not
3585     return true;
3586 }
3587 #endif // ENABLE(DRAG_SUPPORT)
3588
3589 bool EventHandler::mouseMovementExceedsThreshold(const FloatPoint& viewportLocation, int pointsThreshold) const
3590 {
3591     FrameView* view = m_frame.view();
3592     if (!view)
3593         return false;
3594     IntPoint location = view->windowToContents(flooredIntPoint(viewportLocation));
3595     IntSize delta = location - m_mouseDownPos;
3596     
3597     return abs(delta.width()) >= pointsThreshold || abs(delta.height()) >= pointsThreshold;
3598 }
3599
3600 bool EventHandler::handleTextInputEvent(const String& text, Event* underlyingEvent, TextEventInputType inputType)
3601 {
3602     // Platforms should differentiate real commands like selectAll from text input in disguise (like insertNewline),
3603     // and avoid dispatching text input events from keydown default handlers.
3604     ASSERT(!is<KeyboardEvent>(underlyingEvent) || downcast<KeyboardEvent>(*underlyingEvent).type() == eventNames().keypressEvent);
3605
3606     EventTarget* target;
3607     if (underlyingEvent)
3608         target = underlyingEvent->target();
3609     else
3610         target = eventTargetElementForDocument(m_frame.document());
3611     if (!target)
3612         return false;
3613     
3614     if (FrameView* view = m_frame.view())
3615         view->disableLayerFlushThrottlingTemporarilyForInteraction();
3616
3617     RefPtr<TextEvent> event = TextEvent::create(m_frame.document()->domWindow(), text, inputType);
3618     event->setUnderlyingEvent(underlyingEvent);
3619
3620     target->dispatchEvent(event, IGNORE_EXCEPTION);
3621     return event->defaultHandled();
3622 }
3623     
3624 bool EventHandler::isKeyboardOptionTab(KeyboardEvent* event)
3625 {
3626     return event
3627         && (event->type() == eventNames().keydownEvent || event->type() == eventNames().keypressEvent)
3628         && event->altKey()
3629         && event->keyIdentifier() == "U+0009";    
3630 }
3631
3632 bool EventHandler::eventInvertsTabsToLinksClientCallResult(KeyboardEvent* event)
3633 {
3634 #if PLATFORM(COCOA) || PLATFORM(EFL)
3635     return EventHandler::isKeyboardOptionTab(event);
3636 #else
3637     UNUSED_PARAM(event);
3638     return false;
3639 #endif
3640 }
3641
3642 bool EventHandler::tabsToLinks(KeyboardEvent* event) const
3643 {
3644     // FIXME: This function needs a better name. It can be called for keypresses other than Tab when spatial navigation is enabled.
3645
3646     Page* page = m_frame.page();
3647     if (!page)
3648         return false;
3649
3650     bool tabsToLinksClientCallResult = page->chrome().client().keyboardUIMode() & KeyboardAccessTabsToLinks;
3651     return eventInvertsTabsToLinksClientCallResult(event) ? !tabsToLinksClientCallResult : tabsToLinksClientCallResult;
3652 }
3653
3654 void EventHandler::defaultTextInputEventHandler(TextEvent* event)
3655 {
3656     if (m_frame.editor().handleTextEvent(event))
3657         event->setDefaultHandled();
3658 }
3659
3660
3661 void EventHandler::defaultSpaceEventHandler(KeyboardEvent* event)
3662 {
3663     ASSERT(event->type() == eventNames().keypressEvent);
3664
3665     if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
3666         return;
3667
3668     ScrollLogicalDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward;
3669     if (logicalScrollOverflow(direction, ScrollByPage)) {
3670         event->setDefaultHandled();
3671         return;
3672     }
3673
3674     FrameView* view = m_frame.view();
3675     if (!view)
3676         return;
3677
3678     if (view->logicalScroll(direction, ScrollByPage))
3679         event->setDefaultHandled();
3680 }
3681
3682 void EventHandler::defaultBackspaceEventHandler(KeyboardEvent* event)
3683 {
3684     ASSERT(event->type() == eventNames().keydownEvent);
3685
3686     if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
3687         return;
3688
3689     if (!m_frame.editor().behavior().shouldNavigateBackOnBackspace())
3690         return;
3691     
3692     Page* page = m_frame.page();
3693     if (!page)
3694         return;
3695
3696     if (!m_frame.settings().backspaceKeyNavigationEnabled())
3697         return;
3698     
3699     bool handledEvent = false;
3700
3701     if (event->shiftKey())
3702         handledEvent = page->backForward().goForward();
3703     else
3704         handledEvent = page->backForward().goBack();
3705
3706     if (handledEvent)
3707         event->setDefaultHandled();
3708 }
3709
3710
3711 void EventHandler::defaultArrowEventHandler(FocusDirection focusDirection, KeyboardEvent* event)
3712 {
3713     ASSERT(event->type() == eventNames().keydownEvent);
3714
3715     if (event->ctrlKey() || event->metaKey() || event->altGraphKey() || event->shiftKey())
3716         return;
3717
3718     Page* page = m_frame.page();
3719     if (!page)
3720         return;
3721
3722     if (!isSpatialNavigationEnabled(&m_frame))
3723         return;
3724
3725     // Arrows and other possible directional navigation keys can be used in design
3726     // mode editing.
3727     if (m_frame.document()->inDesignMode())
3728         return;
3729
3730     if (page->focusController().advanceFocus(focusDirection, event))
3731         event->setDefaultHandled();
3732 }
3733
3734 void EventHandler::defaultTabEventHandler(KeyboardEvent* event)
3735 {
3736     ASSERT(event->type() == eventNames().keydownEvent);
3737
3738     // We should only advance focus on tabs if no special modifier keys are held down.
3739     if (event->ctrlKey() || event->metaKey() || event->altGraphKey())
3740         return;
3741
3742     Page* page = m_frame.page();
3743     if (!page)
3744         return;
3745     if (!page->tabKeyCyclesThroughElements())
3746         return;
3747
3748     FocusDirection focusDirection = event->shiftKey() ? FocusDirectionBackward : FocusDirectionForward;
3749
3750     // Tabs can be used in design mode editing.
3751     if (m_frame.document()->inDesignMode())
3752         return;
3753
3754     if (page->focusController().advanceFocus(focusDirection, event))
3755         event->setDefaultHandled();
3756 }
3757
3758 void EventHandler::sendScrollEvent()
3759 {
3760     setFrameWasScrolledByUser();
3761     if (m_frame.view() && m_frame.document())
3762         m_frame.document()->eventQueue().enqueueOrDispatchScrollEvent(*m_frame.document());
3763 }
3764
3765 void EventHandler::setFrameWasScrolledByUser()
3766 {
3767     FrameView* v = m_frame.view();
3768     if (v)
3769         v->setWasScrolledByUser(true);
3770 }
3771
3772 bool EventHandler::passMousePressEventToScrollbar(MouseEventWithHitTestResults& mouseEvent, Scrollbar* scrollbar)
3773 {
3774     if (!scrollbar || !scrollbar->enabled())
3775         return false;
3776     setFrameWasScrolledByUser();
3777     return scrollbar->mouseDown(mouseEvent.event());
3778 }
3779
3780 // If scrollbar (under mouse) is different from last, send a mouse exited. Set
3781 // last to scrollbar if setLast is true; else set last to nullptr.
3782 void EventHandler::updateLastScrollbarUnderMouse(Scrollbar* scrollbar, bool setLast)
3783 {
3784     if (m_lastScrollbarUnderMouse.get() != scrollbar) {
3785         // Send mouse exited to the old scrollbar.
3786         if (m_lastScrollbarUnderMouse)
3787             m_lastScrollbarUnderMouse->mouseExited();
3788
3789         // Send mouse entered if we're setting a new scrollbar.
3790         if (scrollbar && setLast)
3791             scrollbar->mouseEntered();
3792
3793         if (setLast && scrollbar)
3794             m_lastScrollbarUnderMouse = scrollbar->createWeakPtr();
3795         else
3796             m_lastScrollbarUnderMouse = nullptr;
3797     }
3798 }
3799
3800 #if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
3801 static const AtomicString& eventNameForTouchPointState(PlatformTouchPoint::State state)
3802 {
3803     switch (state) {
3804     case PlatformTouchPoint::TouchReleased:
3805         return eventNames().touchendEvent;
3806     case PlatformTouchPoint::TouchCancelled:
3807         return eventNames().touchcancelEvent;
3808     case PlatformTouchPoint::TouchPressed:
3809         return eventNames().touchstartEvent;
3810     case PlatformTouchPoint::TouchMoved:
3811         return eventNames().touchmoveEvent;
3812     case PlatformTouchPoint::TouchStationary:
3813         // TouchStationary state is not converted to touch events, so fall through to assert.
3814     default:
3815         ASSERT_NOT_REACHED();
3816         return emptyAtom;
3817     }
3818 }
3819
3820 static HitTestResult hitTestResultInFrame(Frame* frame, const LayoutPoint& point, HitTestRequest::HitTestRequestType hitType)
3821 {
3822     HitTestResult result(point);
3823
3824     if (!frame || !frame->contentRenderer())
3825         return result;
3826
3827     if (frame->view()) {
3828         IntRect rect = frame->view()->visibleContentRect();
3829         if (!rect.contains(roundedIntPoint(point)))
3830             return result;
3831     }
3832     frame->contentRenderer()->hitTest(HitTestRequest(hitType), result);
3833     return result;
3834 }
3835
3836 bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
3837 {
3838     // First build up the lists to use for the 'touches', 'targetTouches' and 'changedTouches' attributes
3839     // in the JS event. See http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
3840     // for an overview of how these lists fit together.
3841
3842     // Holds the complete set of touches on the screen and will be used as the 'touches' list in the JS event.
3843     RefPtr<TouchList> touches = TouchList::create();
3844
3845     // A different view on the 'touches' list above, filtered and grouped by event target. Used for the
3846     // 'targetTouches' list in the JS event.
3847     typedef HashMap<EventTarget*, RefPtr<TouchList>> TargetTouchesMap;
3848     TargetTouchesMap touchesByTarget;
3849
3850     // Array of touches per state, used to assemble the 'changedTouches' list in the JS event.
3851     typedef HashSet<RefPtr<EventTarget>> EventTargetSet;
3852     struct {
3853         // The touches corresponding to the particular change state this struct instance represents.
3854         RefPtr<TouchList> m_touches;
3855         // Set of targets involved in m_touches.
3856         EventTargetSet m_targets;
3857     } changedTouches[PlatformTouchPoint::TouchStateEnd];
3858
3859     const Vector<PlatformTouchPoint>& points = event.touchPoints();
3860
3861     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture, m_frame.document());
3862
3863     bool freshTouchEvents = true;
3864     bool allTouchReleased = true;
3865     for (auto& point : points) {
3866         if (point.state() != PlatformTouchPoint::TouchPressed)
3867             freshTouchEvents = false;
3868         if (point.state() != PlatformTouchPoint::TouchReleased && point.state() != PlatformTouchPoint::TouchCancelled)
3869             allTouchReleased = false;
3870     }
3871
3872     for (auto& point : points) {
3873         PlatformTouchPoint::State pointState = point.state();
3874         LayoutPoint pagePoint = documentPointForWindowPoint(m_frame, point.pos());
3875
3876         HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
3877         // The HitTestRequest types used for mouse events map quite adequately
3878         // to touch events. Note that in addition to meaning that the hit test
3879         // should affect the active state of the current node if necessary,
3880         // HitTestRequest::Active signifies that the hit test is taking place
3881         // with the mouse (or finger in this case) being pressed.
3882         switch (pointState) {
3883         case PlatformTouchPoint::TouchPressed:
3884             hitType |= HitTestRequest::Active;
3885             break;
3886         case PlatformTouchPoint::TouchMoved:
3887             hitType |= HitTestRequest::Active | HitTestRequest::Move | HitTestRequest::ReadOnly;
3888             break;
3889         case PlatformTouchPoint::TouchReleased:
3890         case PlatformTouchPoint::TouchCancelled:
3891             hitType |= HitTestRequest::Release;
3892             break;
3893         case PlatformTouchPoint::TouchStationary:
3894             hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
3895             break;
3896         default:
3897             ASSERT_NOT_REACHED();
3898             break;
3899         }
3900
3901         if (shouldGesturesTriggerActive())
3902             hitType |= HitTestRequest::ReadOnly;
3903
3904         // Increment the platform touch id by 1 to avoid storing a key of 0 in the hashmap.
3905         unsigned touchPointTargetKey = point.id() + 1;
3906         RefPtr<EventTarget> touchTarget;
3907         if (pointState == PlatformTouchPoint::TouchPressed) {
3908             HitTestResult result;
3909             if (freshTouchEvents) {
3910                 result = hitTestResultAtPoint(pagePoint, hitType);
3911                 m_originatingTouchPointTargetKey = touchPointTargetKey;
3912             } else if (m_originatingTouchPointDocument.get() && m_originatingTouchPointDocument->frame()) {
3913                 LayoutPoint pagePointInOriginatingDocument = documentPointForWindowPoint(*m_originatingTouchPointDocument->frame(), point.pos());
3914                 result = hitTestResultInFrame(m_originatingTouchPointDocument->frame(), pagePointInOriginatingDocument, hitType);
3915                 if (!result.innerNode())
3916                     continue;
3917             } else
3918                 continue;
3919
3920             // FIXME: This code should use Element* instead of Node*.
3921             Node* node = result.innerElement();
3922             ASSERT(node);
3923
3924             if (node && InspectorInstrumentation::handleTouchEvent(m_frame, *node))
3925                 return true;
3926
3927             Document& doc = node->document();
3928             // Record the originating touch document even if it does not have a touch listener.
3929             if (freshTouchEvents) {
3930                 m_originatingTouchPointDocument = &doc;
3931                 freshTouchEvents = false;
3932             }
3933             if (!doc.hasTouchEventHandlers())
3934                 continue;
3935             m_originatingTouchPointTargets.set(touchPointTargetKey, node);
3936             touchTarget = node;
3937         } else if (pointState == PlatformTouchPoint::TouchReleased || pointState == PlatformTouchPoint::TouchCancelled) {
3938             // No need to perform a hit-test since we only need to unset :hover and :active states.
3939             if (!shouldGesturesTriggerActive() && allTouchReleased)
3940                 m_frame.document()->updateHoverActiveState(hitType, 0);
3941             if (touchPointTargetKey == m_originatingTouchPointTargetKey)
3942                 m_originatingTouchPointTargetKey = 0;
3943
3944             // The target should be the original target for this touch, so get it from the hashmap. As it's a release or cancel
3945             // we also remove it from the map.
3946             touchTarget = m_originatingTouchPointTargets.take(touchPointTargetKey);
3947         } else
3948             // No hittest is performed on move or stationary, since the target is not allowed to change anyway.
3949             touchTarget = m_originatingTouchPointTargets.get(touchPointTargetKey);
3950
3951         if (!touchTarget.get())
3952             continue;
3953         Document& doc = touchTarget->toNode()->document();
3954         if (!doc.hasTouchEventHandlers())
3955             continue;
3956         Frame* targetFrame = doc.frame();
3957         if (!targetFrame)
3958             continue;
3959
3960         if (&m_frame != targetFrame) {
3961             // pagePoint should always be relative to the target elements containing frame.
3962             pagePoint = documentPointForWindowPoint(*targetFrame, point.pos());
3963         }
3964
3965         float scaleFactor = targetFrame->pageZoomFactor() * targetFrame->frameScaleFactor();
3966
3967         int adjustedPageX = lroundf(pagePoint.x() / scaleFactor);
3968         int adjustedPageY = lroundf(pagePoint.y() / scaleFactor);
3969
3970         RefPtr<Touch> touch = Touch::create(targetFrame, touchTarget.get(), point.id(),
3971                                             point.screenPos().x(), point.screenPos().y(),
3972                                             adjustedPageX, adjustedPageY,
3973                                             point.radiusX(), point.radiusY(), point.rotationAngle(), point.force());
3974
3975         // Ensure this target's touch list exists, even if it ends up empty, so it can always be passed to TouchEvent::Create below.
3976         TargetTouchesMap::iterator targetTouchesIterator = touchesByTarget.find(touchTarget.get());
3977         if (targetTouchesIterator == touchesByTarget.end())
3978             targetTouchesIterator = touchesByTarget.set(touchTarget.get(), TouchList::create()).iterator;
3979
3980         // touches and targetTouches should only contain information about touches still on the screen, so if this point is
3981         // released or cancelled it will only appear in the changedTouches list.
3982         if (pointState != PlatformTouchPoint::TouchReleased && pointState != PlatformTouchPoint::TouchCancelled) {
3983             touches->append(touch);
3984             targetTouchesIterator->value->append(touch);
3985         }
3986
3987         // Now build up the correct list for changedTouches.
3988         // Note that  any touches that are in the TouchStationary state (e.g. if
3989         // the user had several points touched but did not move them all) should
3990         // never be in the changedTouches list so we do not handle them explicitly here.
3991         // See https://bugs.webkit.org/show_bug.cgi?id=37609 for further discussion
3992         // about the TouchStationary state.
3993         if (pointState != PlatformTouchPoint::TouchStationary) {
3994             ASSERT(pointState < PlatformTouchPoint::TouchStateEnd);
3995             if (!changedTouches[pointState].m_touches)
3996                 changedTouches[pointState].m_touches = TouchList::create();
3997             changedTouches[pointState].m_touches->append(touch);
3998             changedTouches[pointState].m_targets.add(touchTarget);
3999         }
4000     }
4001     m_touchPressed = touches->length() > 0;
4002     if (allTouchReleased)
4003         m_originatingTouchPointDocument = nullptr;
4004
4005     // Now iterate the changedTouches list and m_targets within it, sending events to the targets as required.
4006     bool swallowedEvent = false;
4007     RefPtr<TouchList> emptyList = TouchList::create();
4008     for (unsigned state = 0; state != PlatformTouchPoint::TouchStateEnd; ++state) {
4009         if (!changedTouches[state].m_touches)
4010             continue;
4011
4012         // When sending a touch cancel event, use empty touches and targetTouches lists.
4013         bool isTouchCancelEvent = (state == PlatformTouchPoint::TouchCancelled);
4014         RefPtr<TouchList>& effectiveTouches(isTouchCancelEvent ? emptyList : touches);
4015         const AtomicString& stateName(eventNameForTouchPointState(static_cast<PlatformTouchPoint::State>(state)));
4016
4017         for (auto& taget : changedTouches[state].m_targets) {
4018             EventTarget* touchEventTarget = taget.get();
4019             RefPtr<TouchList> targetTouches(isTouchCancelEvent ? emptyList : touchesByTarget.get(touchEventTarget));
4020             ASSERT(targetTouches);
4021
4022             RefPtr<TouchEvent> touchEvent =
4023                 TouchEvent::create(effectiveTouches.get(), targetTouches.get(), changedTouches[state].m_touches.get(),
4024                     stateName, touchEventTarget->toNode()->document().defaultView(),
4025                     0, 0, 0, 0, event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey());
4026             touchEventTarget->toNode()->dispatchTouchEvent(touchEvent.get());
4027             swallowedEvent = swallowedEvent || touchEvent->defaultPrevented() || touchEvent->defaultHandled();
4028         }
4029     }
4030
4031     return swallowedEvent;
4032 }
4033 #endif // ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
4034
4035 #if ENABLE(TOUCH_EVENTS)
4036 bool EventHandler::dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent& platformMouseEvent)
4037 {
4038 #if ENABLE(IOS_TOUCH_EVENTS)
4039     UNUSED_PARAM(platformMouseEvent);
4040     return false;
4041 #else
4042     if (!m_frame.settings().isTouchEventEmulationEnabled())
4043         return false;
4044
4045     PlatformEvent::Type eventType = platformMouseEvent.type();
4046     if (eventType != PlatformEvent::MouseMoved && eventType != PlatformEvent::MousePressed && eventType != PlatformEvent::MouseReleased)
4047         return false;
4048
4049     HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
4050     MouseEventWithHitTestResults mouseEvent = prepareMouseEvent(request, platformMouseEvent);
4051     if (mouseEvent.scrollbar() || subframeForHitTestResult(mouseEvent))
4052         return false;
4053
4054     // The order is important. This check should follow the subframe test: http://webkit.org/b/111292.
4055     if (eventType == PlatformEvent::MouseMoved && !m_touchPressed)
4056         return true;
4057