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