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