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