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