2 * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
3 * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
28 #include "EventHandler.h"
30 #include "CachedImage.h"
31 #include "ChromeClient.h"
34 #include "DragController.h"
36 #include "EventNames.h"
37 #include "FloatPoint.h"
38 #include "FocusController.h"
40 #include "FrameLoader.h"
41 #include "FrameTree.h"
42 #include "FrameView.h"
43 #include "HitTestRequest.h"
44 #include "HitTestResult.h"
45 #include "HTMLFrameSetElement.h"
46 #include "HTMLFrameElementBase.h"
47 #include "HTMLInputElement.h"
48 #include "HTMLNames.h"
50 #include "KeyboardEvent.h"
51 #include "MouseEvent.h"
52 #include "MouseEventWithHitTestResults.h"
54 #include "PlatformKeyboardEvent.h"
55 #include "PlatformScrollBar.h"
56 #include "PlatformWheelEvent.h"
57 #include "RenderWidget.h"
58 #include "SelectionController.h"
60 #include "TextEvent.h"
63 #include "SVGCursorElement.h"
64 #include "SVGDocument.h"
65 #include "SVGLength.h"
71 using namespace EventNames;
72 using namespace HTMLNames;
74 // The link drag hysteresis is much larger than the others because there
75 // needs to be enough space to cancel the link press without starting a link drag,
76 // and because dragging links is rare.
77 const int LinkDragHysteresis = 40;
78 const int ImageDragHysteresis = 5;
79 const int TextDragHysteresis = 3;
80 const int GeneralDragHysteresis = 3;
81 const double TextDragDelay = 0.15;
83 // Match key code of composition keydown event on windows.
84 // IE sends VK_PROCESSKEY which has value 229;
85 const int CompositionEventKeyCode = 229;
88 using namespace SVGNames;
91 const double autoscrollInterval = 0.1;
93 static Frame* subframeForTargetNode(Node* node);
95 EventHandler::EventHandler(Frame* frame)
97 , m_mousePressed(false)
98 , m_mouseDownMayStartSelect(false)
99 , m_mouseDownMayStartDrag(false)
100 , m_mouseDownWasSingleClickInSelection(false)
101 , m_beganSelectingText(false)
102 , m_hoverTimer(this, &EventHandler::hoverTimerFired)
103 , m_autoscrollTimer(this, &EventHandler::autoscrollTimerFired)
104 , m_autoscrollRenderer(0)
105 , m_mouseDownMayStartAutoscroll(false)
106 , m_mouseDownWasInSubframe(false)
111 , m_capturingMouseEventsNode(0)
113 , m_mouseDownTimestamp(0)
115 , m_mouseDownView(nil)
116 , m_sendingEventToSubview(false)
117 , m_activationEventNumber(0)
122 EventHandler::~EventHandler()
126 EventHandler::EventHandlerDragState& EventHandler::dragState()
128 static EventHandlerDragState state;
132 void EventHandler::clear()
136 m_nodeUnderMouse = 0;
137 m_lastNodeUnderMouse = 0;
138 m_lastMouseMoveEventSubframe = 0;
139 m_lastScrollbarUnderMouse = 0;
142 m_frameSetBeingResized = 0;
144 m_currentMousePosition = IntPoint();
145 m_mousePressNode = 0;
146 m_mousePressed = false;
147 m_capturingMouseEventsNode = 0;
150 void EventHandler::selectClosestWordFromMouseEvent(const MouseEventWithHitTestResults& result)
152 Node* innerNode = result.targetNode();
153 Selection newSelection;
155 if (innerNode && innerNode->renderer() && m_mouseDownMayStartSelect) {
156 VisiblePosition pos(innerNode->renderer()->positionForPoint(result.localPoint()));
157 if (pos.isNotNull()) {
158 newSelection = Selection(pos);
159 newSelection.expandUsingGranularity(WordGranularity);
162 if (newSelection.isRange()) {
163 m_frame->setSelectionGranularity(WordGranularity);
164 m_beganSelectingText = true;
167 if (m_frame->shouldChangeSelection(newSelection))
168 m_frame->selectionController()->setSelection(newSelection);
172 void EventHandler::selectClosestWordOrLinkFromMouseEvent(const MouseEventWithHitTestResults& result)
174 if (!result.hitTestResult().isLiveLink())
175 return selectClosestWordFromMouseEvent(result);
177 Node* innerNode = result.targetNode();
179 if (innerNode && innerNode->renderer() && m_mouseDownMayStartSelect) {
180 Selection newSelection;
181 Element* URLElement = result.hitTestResult().URLElement();
182 VisiblePosition pos(innerNode->renderer()->positionForPoint(result.localPoint()));
183 if (pos.isNotNull() && pos.deepEquivalent().node()->isDescendantOf(URLElement))
184 newSelection = Selection::selectionFromContentsOfNode(URLElement);
186 if (newSelection.isRange()) {
187 m_frame->setSelectionGranularity(WordGranularity);
188 m_beganSelectingText = true;
191 if (m_frame->shouldChangeSelection(newSelection))
192 m_frame->selectionController()->setSelection(newSelection);
196 bool EventHandler::handleMousePressEventDoubleClick(const MouseEventWithHitTestResults& event)
198 if (event.event().button() != LeftButton)
201 if (m_frame->selectionController()->isRange())
202 // A double-click when range is already selected
203 // should not change the selection. So, do not call
204 // selectClosestWordFromMouseEvent, but do set
205 // m_beganSelectingText to prevent handleMouseReleaseEvent
206 // from setting caret selection.
207 m_beganSelectingText = true;
209 selectClosestWordFromMouseEvent(event);
214 bool EventHandler::handleMousePressEventTripleClick(const MouseEventWithHitTestResults& event)
216 if (event.event().button() != LeftButton)
219 Node* innerNode = event.targetNode();
220 if (!(innerNode && innerNode->renderer() && m_mouseDownMayStartSelect))
223 Selection newSelection;
224 VisiblePosition pos(innerNode->renderer()->positionForPoint(event.localPoint()));
225 if (pos.isNotNull()) {
226 newSelection = Selection(pos);
227 newSelection.expandUsingGranularity(ParagraphGranularity);
229 if (newSelection.isRange()) {
230 m_frame->setSelectionGranularity(ParagraphGranularity);
231 m_beganSelectingText = true;
234 if (m_frame->shouldChangeSelection(newSelection))
235 m_frame->selectionController()->setSelection(newSelection);
240 bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
242 if (event.event().button() != LeftButton)
245 Node* innerNode = event.targetNode();
246 if (!(innerNode && innerNode->renderer() && m_mouseDownMayStartSelect))
249 // Extend the selection if the Shift key is down, unless the click is in a link.
250 bool extendSelection = event.event().shiftKey() && !event.isOverLink();
252 // Don't restart the selection when the mouse is pressed on an
253 // existing selection so we can allow for text dragging.
254 IntPoint vPoint = m_frame->view()->windowToContents(event.event().pos());
255 if (!extendSelection && m_frame->selectionController()->contains(vPoint)) {
256 m_mouseDownWasSingleClickInSelection = true;
260 VisiblePosition visiblePos(innerNode->renderer()->positionForPoint(event.localPoint()));
261 if (visiblePos.isNull())
262 visiblePos = VisiblePosition(innerNode, 0, DOWNSTREAM);
263 Position pos = visiblePos.deepEquivalent();
265 Selection newSelection = m_frame->selectionController()->selection();
266 if (extendSelection && newSelection.isCaretOrRange()) {
267 m_frame->selectionController()->setLastChangeWasHorizontalExtension(false);
269 // See <rdar://problem/3668157> REGRESSION (Mail): shift-click deselects when selection
270 // was created right-to-left
271 Position start = newSelection.start();
272 Position end = newSelection.end();
273 short before = Range::compareBoundaryPoints(pos.node(), pos.offset(), start.node(), start.offset());
275 newSelection = Selection(pos, end);
277 newSelection = Selection(start, pos);
279 if (m_frame->selectionGranularity() != CharacterGranularity)
280 newSelection.expandUsingGranularity(m_frame->selectionGranularity());
281 m_beganSelectingText = true;
283 newSelection = Selection(visiblePos);
284 m_frame->setSelectionGranularity(CharacterGranularity);
287 if (m_frame->shouldChangeSelection(newSelection))
288 m_frame->selectionController()->setSelection(newSelection);
293 bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& event)
296 dragState().m_dragSrc = 0;
298 bool singleClick = event.event().clickCount() <= 1;
300 // If we got the event back, that must mean it wasn't prevented,
301 // so it's allowed to start a drag or selection.
302 m_mouseDownMayStartSelect = canMouseDownStartSelect(event.targetNode());
304 // Careful that the drag starting logic stays in sync with eventMayStartDrag()
305 m_mouseDownMayStartDrag = singleClick;
307 m_mouseDownWasSingleClickInSelection = false;
309 if (passWidgetMouseDownEventToWidget(event))
313 if (m_frame->document()->isSVGDocument() &&
314 static_cast<SVGDocument*>(m_frame->document())->zoomAndPanEnabled()) {
315 if (event.event().shiftKey() && singleClick) {
317 static_cast<SVGDocument*>(m_frame->document())->startPan(event.event().pos());
323 // We don't do this at the start of mouse down handling,
324 // because we don't want to do it until we know we didn't hit a widget.
328 Node* innerNode = event.targetNode();
330 m_mousePressNode = innerNode;
331 m_dragStartPos = event.event().pos();
333 bool swallowEvent = false;
334 if (event.event().button() == LeftButton || event.event().button() == MiddleButton) {
335 m_frame->selectionController()->setCaretBlinkingSuspended(true);
336 m_mousePressed = true;
337 m_beganSelectingText = false;
339 if (event.event().clickCount() == 2)
340 swallowEvent = handleMousePressEventDoubleClick(event);
341 else if (event.event().clickCount() >= 3)
342 swallowEvent = handleMousePressEventTripleClick(event);
344 swallowEvent = handleMousePressEventSingleClick(event);
347 m_mouseDownMayStartAutoscroll = m_mouseDownMayStartSelect ||
348 (m_mousePressNode && m_mousePressNode->renderer() && m_mousePressNode->renderer()->shouldAutoscroll());
353 bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& event)
355 if (handleDrag(event))
361 Node* targetNode = event.targetNode();
362 if (event.event().button() != LeftButton || !targetNode || !targetNode->renderer())
365 #if PLATFORM(MAC) // FIXME: Why does this assertion fire on other platforms?
366 ASSERT(m_mouseDownMayStartSelect || m_mouseDownMayStartAutoscroll);
369 m_mouseDownMayStartDrag = false;
371 if (m_mouseDownMayStartAutoscroll) {
372 // If the selection is contained in a layer that can scroll, that layer should handle the autoscroll
373 // Otherwise, let the bridge handle it so the view can scroll itself.
374 RenderObject* renderer = targetNode->renderer();
375 while (renderer && !renderer->shouldAutoscroll())
376 renderer = renderer->parent();
378 handleAutoscroll(renderer);
381 updateSelectionForMouseDrag(targetNode, event.localPoint());
385 bool EventHandler::eventMayStartDrag(const PlatformMouseEvent& event) const
387 // This is a pre-flight check of whether the event might lead to a drag being started. Be careful
388 // that its logic needs to stay in sync with handleMouseMoveEvent() and the way we setMouseDownMayStartDrag
389 // in handleMousePressEvent
391 if (!m_frame->renderer() || !m_frame->renderer()->hasLayer()
392 || event.button() != LeftButton || event.clickCount() != 1)
397 allowDHTMLDrag(DHTMLFlag, UAFlag);
398 if (!DHTMLFlag && !UAFlag)
401 HitTestRequest request(true, false);
402 HitTestResult result(m_frame->view()->windowToContents(event.pos()));
403 m_frame->renderer()->layer()->hitTest(request, result);
405 return result.innerNode() && result.innerNode()->renderer()->draggableNode(DHTMLFlag, UAFlag, result.point().x(), result.point().y(), srcIsDHTML);
408 void EventHandler::updateSelectionForMouseDrag()
410 FrameView* view = m_frame->view();
413 RenderObject* renderer = m_frame->renderer();
416 RenderLayer* layer = renderer->layer();
420 HitTestResult result(view->windowToContents(m_currentMousePosition));
421 layer->hitTest(HitTestRequest(true, true, true), result);
422 updateSelectionForMouseDrag(result.innerNode(), result.localPoint());
425 void EventHandler::updateSelectionForMouseDrag(Node* targetNode, const IntPoint& localPoint)
427 if (!m_mouseDownMayStartSelect)
433 RenderObject* targetRenderer = targetNode->renderer();
437 if (!canMouseDragExtendSelect(targetNode))
440 VisiblePosition targetPosition(targetRenderer->positionForPoint(localPoint));
442 // Don't modify the selection if we're not on a node.
443 if (targetPosition.isNull())
446 // Restart the selection if this is the first mouse move. This work is usually
447 // done in handleMousePressEvent, but not if the mouse press was on an existing selection.
448 Selection newSelection = m_frame->selectionController()->selection();
451 // Special case to limit selection to the containing block for SVG text.
452 // FIXME: Isn't there a better non-SVG-specific way to do this?
453 if (Node* selectionBaseNode = newSelection.base().node())
454 if (RenderObject* selectionBaseRenderer = selectionBaseNode->renderer())
455 if (selectionBaseRenderer->isSVGText())
456 if (targetNode->renderer()->containingBlock() != selectionBaseRenderer->containingBlock())
460 if (!m_beganSelectingText) {
461 m_beganSelectingText = true;
462 newSelection = Selection(targetPosition);
465 newSelection.setExtent(targetPosition);
466 if (m_frame->selectionGranularity() != CharacterGranularity)
467 newSelection.expandUsingGranularity(m_frame->selectionGranularity());
469 if (m_frame->shouldChangeSelection(newSelection)) {
470 m_frame->selectionController()->setLastChangeWasHorizontalExtension(false);
471 m_frame->selectionController()->setSelection(newSelection);
475 bool EventHandler::handleMouseUp(const MouseEventWithHitTestResults& event)
477 if (eventLoopHandleMouseUp(event))
480 // If this was the first click in the window, we don't even want to clear the selection.
481 // This case occurs when the user clicks on a draggable element, since we have to process
482 // the mouse down and drag events to see if we might start a drag. For other first clicks
483 // in a window, we just don't acceptFirstMouse, and the whole down-drag-up sequence gets
484 // ignored upstream of this layer.
485 return eventActivatedView(event.event());
488 bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& event)
490 stopAutoscrollTimer();
492 if (handleMouseUp(event))
495 // Used to prevent mouseMoveEvent from initiating a drag before
496 // the mouse is pressed again.
497 m_frame->selectionController()->setCaretBlinkingSuspended(false);
498 m_mousePressed = false;
499 m_mouseDownMayStartDrag = false;
500 m_mouseDownMayStartSelect = false;
501 m_mouseDownMayStartAutoscroll = false;
502 m_mouseDownWasInSubframe = false;
504 bool handled = false;
506 // Clear the selection if the mouse didn't move after the last mouse press.
507 // We do this so when clicking on the selection, the selection goes away.
508 // However, if we are editing, place the caret.
509 if (m_mouseDownWasSingleClickInSelection && !m_beganSelectingText
510 && m_dragStartPos == event.event().pos()
511 && m_frame->selectionController()->isRange()) {
512 Selection newSelection;
513 Node *node = event.targetNode();
514 if (node && node->isContentEditable() && node->renderer()) {
515 VisiblePosition pos = node->renderer()->positionForPoint(event.localPoint());
516 newSelection = Selection(pos);
518 if (m_frame->shouldChangeSelection(newSelection))
519 m_frame->selectionController()->setSelection(newSelection);
524 m_frame->notifyRendererOfSelectionChange(true);
526 m_frame->selectionController()->selectFrameElementInParentIfFullySelected();
531 void EventHandler::handleAutoscroll(RenderObject* renderer)
533 if (m_autoscrollTimer.isActive())
535 setAutoscrollRenderer(renderer);
536 startAutoscrollTimer();
539 void EventHandler::autoscrollTimerFired(Timer<EventHandler>*)
541 if (!m_mousePressed) {
542 stopAutoscrollTimer();
545 if (RenderObject* r = autoscrollRenderer())
549 RenderObject* EventHandler::autoscrollRenderer() const
551 return m_autoscrollRenderer;
554 void EventHandler::setAutoscrollRenderer(RenderObject* renderer)
556 m_autoscrollRenderer = renderer;
559 void EventHandler::allowDHTMLDrag(bool& flagDHTML, bool& flagUA) const
561 if (!m_frame || !m_frame->document()) {
566 unsigned mask = m_frame->page()->dragController()->delegateDragSourceAction(m_frame->view()->contentsToWindow(m_mouseDownPos));
567 flagDHTML = (mask & DragSourceActionDHTML) != DragSourceActionNone;
568 flagUA = ((mask & DragSourceActionImage) || (mask & DragSourceActionLink) || (mask & DragSourceActionSelection));
571 HitTestResult EventHandler::hitTestResultAtPoint(const IntPoint& point, bool allowShadowContent)
573 HitTestResult result(point);
574 if (!m_frame->renderer())
576 m_frame->renderer()->layer()->hitTest(HitTestRequest(true, true), result);
578 IntPoint widgetPoint(point);
580 Node* n = result.innerNode();
581 if (!n || !n->renderer() || !n->renderer()->isWidget())
583 Widget* widget = static_cast<RenderWidget*>(n->renderer())->widget();
584 if (!widget || !widget->isFrameView())
586 Frame* frame = static_cast<HTMLFrameElementBase*>(n)->contentFrame();
587 if (!frame || !frame->renderer())
590 n->renderer()->absolutePosition(absX, absY, true);
591 FrameView* view = static_cast<FrameView*>(widget);
592 widgetPoint.move(view->contentsX() - absX, view->contentsY() - absY);
593 HitTestResult widgetHitTestResult(widgetPoint);
594 frame->renderer()->layer()->hitTest(HitTestRequest(true, true), widgetHitTestResult);
595 result = widgetHitTestResult;
598 if (!allowShadowContent)
599 result.setToNonShadowAncestor();
605 void EventHandler::startAutoscrollTimer()
607 m_autoscrollTimer.startRepeating(autoscrollInterval);
610 void EventHandler::stopAutoscrollTimer(bool rendererIsBeingDestroyed)
612 if (m_mouseDownWasInSubframe) {
613 if (Frame* subframe = subframeForTargetNode(m_mousePressNode.get()))
614 subframe->eventHandler()->stopAutoscrollTimer(rendererIsBeingDestroyed);
618 if (!rendererIsBeingDestroyed && autoscrollRenderer())
619 autoscrollRenderer()->stopAutoscroll();
620 setAutoscrollRenderer(0);
621 m_autoscrollTimer.stop();
624 Node* EventHandler::mousePressNode() const
626 return m_mousePressNode.get();
629 void EventHandler::setMousePressNode(PassRefPtr<Node> node)
631 m_mousePressNode = node;
634 bool EventHandler::scrollOverflow(ScrollDirection direction, ScrollGranularity granularity)
636 if (!m_frame->document())
639 Node* node = m_frame->document()->focusedNode();
641 node = m_mousePressNode.get();
644 RenderObject *r = node->renderer();
645 if (r && !r->isListBox())
646 return r->scroll(direction, granularity);
652 IntPoint EventHandler::currentMousePosition() const
654 return m_currentMousePosition;
657 Frame* subframeForTargetNode(Node* node)
662 RenderObject* renderer = node->renderer();
663 if (!renderer || !renderer->isWidget())
666 Widget* widget = static_cast<RenderWidget*>(renderer)->widget();
667 if (!widget || !widget->isFrameView())
670 return static_cast<FrameView*>(widget)->frame();
673 static bool isSubmitImage(Node* node)
675 return node && node->hasTagName(inputTag)
676 && static_cast<HTMLInputElement*>(node)->inputType() == HTMLInputElement::IMAGE;
679 // Returns true if the node's editable block is not current focused for editing
680 static bool nodeIsNotBeingEdited(Node* node, Frame* frame)
682 return frame->selectionController()->rootEditableElement() != node->rootEditableElement();
685 Cursor EventHandler::selectCursor(const MouseEventWithHitTestResults& event, PlatformScrollbar* scrollbar)
687 // During selection, use an I-beam no matter what we're over.
688 // If you're capturing mouse events for a particular node, don't treat this as a selection.
689 if (m_mousePressed && m_mouseDownMayStartSelect && m_frame->selectionController()->isCaretOrRange() && !m_capturingMouseEventsNode)
690 return iBeamCursor();
692 Node* node = event.targetNode();
693 RenderObject* renderer = node ? node->renderer() : 0;
694 RenderStyle* style = renderer ? renderer->style() : 0;
696 if (style && style->cursors()) {
697 const CursorList* cursors = style->cursors();
698 for (unsigned i = 0; i < cursors->size(); ++i) {
699 CachedImage* cimage = (*cursors)[i].cursorImage;
700 IntPoint hotSpot = (*cursors)[i].hotSpot;
703 Element* e = node->document()->getElementById((*cursors)[i].cursorFragmentId);
704 if (e && e->hasTagName(cursorTag)) {
705 hotSpot.setX(int(static_cast<SVGCursorElement*>(e)->x().value()));
706 hotSpot.setY(int(static_cast<SVGCursorElement*>(e)->y().value()));
707 cimage = static_cast<SVGCursorElement*>(e)->cachedImage();
713 if (cimage->image()->isNull())
715 if (!cimage->errorOccurred())
716 return Cursor(cimage->image(), hotSpot);
720 switch (style ? style->cursor() : CURSOR_AUTO) {
722 bool editable = (node && node->isContentEditable());
723 bool editableLinkEnabled = false;
725 // If the link is editable, then we need to check the settings to see whether or not the link should be followed
727 ASSERT(m_frame->settings());
728 switch(m_frame->settings()->editableLinkBehavior()) {
730 case EditableLinkDefaultBehavior:
731 case EditableLinkAlwaysLive:
732 editableLinkEnabled = true;
735 case EditableLinkNeverLive:
736 editableLinkEnabled = false;
739 case EditableLinkLiveWhenNotFocused:
740 editableLinkEnabled = nodeIsNotBeingEdited(node, m_frame) || event.event().shiftKey();
743 case EditableLinkOnlyLiveWithShiftKey:
744 editableLinkEnabled = event.event().shiftKey();
749 if ((event.isOverLink() || isSubmitImage(node)) && (!editable || editableLinkEnabled))
751 RenderLayer* layer = renderer ? renderer->enclosingLayer() : 0;
752 bool inResizer = false;
753 if (m_frame->view() && layer && layer->isPointInResizeControl(m_frame->view()->windowToContents(event.event().pos())))
755 if ((editable || (renderer && renderer->isText() && node->canStartSelection())) && !inResizer && !scrollbar)
756 return iBeamCursor();
757 return pointerCursor();
760 return crossCursor();
765 case CURSOR_ALL_SCROLL:
767 case CURSOR_E_RESIZE:
768 return eastResizeCursor();
769 case CURSOR_W_RESIZE:
770 return westResizeCursor();
771 case CURSOR_N_RESIZE:
772 return northResizeCursor();
773 case CURSOR_S_RESIZE:
774 return southResizeCursor();
775 case CURSOR_NE_RESIZE:
776 return northEastResizeCursor();
777 case CURSOR_SW_RESIZE:
778 return southWestResizeCursor();
779 case CURSOR_NW_RESIZE:
780 return northWestResizeCursor();
781 case CURSOR_SE_RESIZE:
782 return southEastResizeCursor();
783 case CURSOR_NS_RESIZE:
784 return northSouthResizeCursor();
785 case CURSOR_EW_RESIZE:
786 return eastWestResizeCursor();
787 case CURSOR_NESW_RESIZE:
788 return northEastSouthWestResizeCursor();
789 case CURSOR_NWSE_RESIZE:
790 return northWestSouthEastResizeCursor();
791 case CURSOR_COL_RESIZE:
792 return columnResizeCursor();
793 case CURSOR_ROW_RESIZE:
794 return rowResizeCursor();
796 return iBeamCursor();
801 case CURSOR_VERTICAL_TEXT:
802 return verticalTextCursor();
805 case CURSOR_CONTEXT_MENU:
806 return contextMenuCursor();
807 case CURSOR_PROGRESS:
808 return progressCursor();
810 return noDropCursor();
812 return aliasCursor();
817 case CURSOR_NOT_ALLOWED:
818 return notAllowedCursor();
820 return pointerCursor();
821 case CURSOR_WEBKIT_ZOOM_IN:
822 return zoomInCursor();
823 case CURSOR_WEBKIT_ZOOM_OUT:
824 return zoomOutCursor();
826 return pointerCursor();
829 bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
831 if (!m_frame->document())
834 RefPtr<FrameView> protector(m_frame->view());
836 m_mousePressed = true;
837 m_currentMousePosition = mouseEvent.pos();
838 m_mouseDownTimestamp = mouseEvent.timestamp();
839 m_mouseDownMayStartDrag = false;
840 m_mouseDownMayStartSelect = false;
841 m_mouseDownMayStartAutoscroll = false;
842 m_mouseDownPos = m_frame->view()->windowToContents(mouseEvent.pos());
843 m_mouseDownWasInSubframe = false;
845 MouseEventWithHitTestResults mev = prepareMouseEvent(HitTestRequest(false, true), mouseEvent);
847 if (!mev.targetNode()) {
852 m_mousePressNode = mev.targetNode();
854 Frame* subframe = subframeForTargetNode(mev.targetNode());
855 if (subframe && passMousePressEventToSubframe(mev, subframe)) {
856 // Start capturing future events for this frame. We only do this if we didn't clear
857 // the m_mousePressed flag, which may happen if an AppKit widget entered a modal event loop.
859 m_capturingMouseEventsNode = mev.targetNode();
864 m_clickCount = mouseEvent.clickCount();
865 m_clickNode = mev.targetNode();
867 RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
868 IntPoint p = m_frame->view()->windowToContents(mouseEvent.pos());
869 if (layer && layer->isPointInResizeControl(p)) {
870 layer->setInResizeMode(true);
871 m_resizeLayer = layer;
872 m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
877 bool swallowEvent = dispatchMouseEvent(mousedownEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
879 // If the hit testing originally determined the event was in a scrollbar, refetch the MouseEventWithHitTestResults
880 // in case the scrollbar widget was destroyed when the mouse event was handled.
881 if (mev.scrollbar()) {
882 const bool wasLastScrollBar = mev.scrollbar() == m_lastScrollbarUnderMouse.get();
883 mev = prepareMouseEvent(HitTestRequest(true, true), mouseEvent);
885 if (wasLastScrollBar && mev.scrollbar() != m_lastScrollbarUnderMouse.get())
886 m_lastScrollbarUnderMouse = 0;
890 // scrollbars should get events anyway, even disabled controls might be scrollable
892 passMousePressEventToScrollbar(mev, mev.scrollbar());
894 // Refetch the event target node if it currently is the shadow node inside an <input> element.
895 // If a mouse event handler changes the input element type to one that has a widget associated,
896 // we'd like to EventHandler::handleMousePressEvent to pass the event to the widget and thus the
897 // event target node can't still be the shadow node.
898 if (mev.targetNode()->isShadowNode() && mev.targetNode()->shadowParentNode()->hasTagName(inputTag))
899 mev = prepareMouseEvent(HitTestRequest(true, true), mouseEvent);
901 PlatformScrollbar* scrollbar = m_frame->view()->scrollbarUnderMouse(mouseEvent);
903 scrollbar = mev.scrollbar();
904 if (scrollbar && passMousePressEventToScrollbar(mev, scrollbar))
907 swallowEvent = handleMousePressEvent(mev);
913 // This method only exists for platforms that don't know how to deliver
914 bool EventHandler::handleMouseDoubleClickEvent(const PlatformMouseEvent& mouseEvent)
916 if (!m_frame->document())
919 RefPtr<FrameView> protector(m_frame->view());
921 // We get this instead of a second mouse-up
922 m_mousePressed = false;
923 m_currentMousePosition = mouseEvent.pos();
925 MouseEventWithHitTestResults mev = prepareMouseEvent(HitTestRequest(false, true), mouseEvent);
926 Frame* subframe = subframeForTargetNode(mev.targetNode());
927 if (subframe && passMousePressEventToSubframe(mev, subframe)) {
928 m_capturingMouseEventsNode = 0;
932 m_clickCount = mouseEvent.clickCount();
933 bool swallowMouseUpEvent = dispatchMouseEvent(mouseupEvent, mev.targetNode(), true, m_clickCount, mouseEvent, false);
935 bool swallowClickEvent = false;
936 // Don't ever dispatch click events for right clicks
937 if (mouseEvent.button() != RightButton && mev.targetNode() == m_clickNode)
938 swallowClickEvent = dispatchMouseEvent(clickEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
940 bool swallowMouseReleaseEvent = false;
941 if (!swallowMouseUpEvent)
942 swallowMouseReleaseEvent = handleMouseReleaseEvent(mev);
946 return swallowMouseUpEvent || swallowClickEvent || swallowMouseReleaseEvent;
949 bool EventHandler::mouseMoved(const PlatformMouseEvent& event)
951 HitTestResult hoveredNode = HitTestResult(IntPoint());
952 bool result = handleMouseMoveEvent(event, &hoveredNode);
954 Page* page = m_frame->page();
958 hoveredNode.setToNonShadowAncestor();
959 page->chrome()->mouseDidMoveOverElement(hoveredNode, event.modifierFlags());
960 page->chrome()->setToolTip(hoveredNode);
964 bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& mouseEvent, HitTestResult* hoveredNode)
966 // in Radar 3703768 we saw frequent crashes apparently due to the
967 // part being null here, which seems impossible, so check for nil
968 // but also assert so that we can try to figure this out in debug
969 // builds, if it happens.
971 if (!m_frame || !m_frame->document())
974 RefPtr<FrameView> protector(m_frame->view());
975 m_currentMousePosition = mouseEvent.pos();
977 if (m_hoverTimer.isActive())
982 static_cast<SVGDocument*>(m_frame->document())->updatePan(m_currentMousePosition);
987 if (m_frameSetBeingResized)
988 return dispatchMouseEvent(mousemoveEvent, m_frameSetBeingResized.get(), false, 0, mouseEvent, false);
990 // Send events right to a scrollbar if the mouse is pressed.
991 if (m_lastScrollbarUnderMouse && m_mousePressed)
992 return m_lastScrollbarUnderMouse->handleMouseMoveEvent(mouseEvent);
994 // Treat mouse move events while the mouse is pressed as "read-only" in prepareMouseEvent
995 // if we are allowed to select.
996 // This means that :hover and :active freeze in the state they were in when the mouse
997 // was pressed, rather than updating for nodes the mouse moves over as you hold the mouse down.
998 HitTestRequest request(m_mousePressed && m_mouseDownMayStartSelect, m_mousePressed, true);
999 MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
1001 *hoveredNode = mev.hitTestResult();
1003 PlatformScrollbar* scrollbar = 0;
1005 if (m_resizeLayer && m_resizeLayer->inResizeMode())
1006 m_resizeLayer->resize(mouseEvent, m_offsetFromResizeCorner);
1008 if (m_frame->view())
1009 scrollbar = m_frame->view()->scrollbarUnderMouse(mouseEvent);
1012 scrollbar = mev.scrollbar();
1014 if (m_lastScrollbarUnderMouse != scrollbar) {
1015 // Send mouse exited to the old scrollbar.
1016 if (m_lastScrollbarUnderMouse)
1017 m_lastScrollbarUnderMouse->handleMouseOutEvent(mouseEvent);
1018 m_lastScrollbarUnderMouse = m_mousePressed ? 0 : scrollbar;
1022 bool swallowEvent = false;
1023 Node* targetNode = m_capturingMouseEventsNode ? m_capturingMouseEventsNode.get() : mev.targetNode();
1024 RefPtr<Frame> newSubframe = subframeForTargetNode(targetNode);
1026 // 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.
1027 if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree()->isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
1028 passMouseMoveEventToSubframe(mev, m_lastMouseMoveEventSubframe.get());
1031 // Update over/out state before passing the event to the subframe.
1032 updateMouseEventTargetNode(mev.targetNode(), mouseEvent, true);
1033 swallowEvent |= passMouseMoveEventToSubframe(mev, newSubframe.get(), hoveredNode);
1035 if (scrollbar && !m_mousePressed)
1036 scrollbar->handleMouseMoveEvent(mouseEvent); // Handle hover effects on platforms that support visual feedback on scrollbar hovering.
1037 if ((!m_resizeLayer || !m_resizeLayer->inResizeMode()) && m_frame->view())
1038 m_frame->view()->setCursor(selectCursor(mev, scrollbar));
1041 m_lastMouseMoveEventSubframe = newSubframe;
1046 swallowEvent = dispatchMouseEvent(mousemoveEvent, mev.targetNode(), false, 0, mouseEvent, true);
1048 swallowEvent = handleMouseDraggedEvent(mev);
1050 return swallowEvent;
1053 void EventHandler::invalidateClick()
1059 bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
1061 if (!m_frame->document())
1064 RefPtr<FrameView> protector(m_frame->view());
1066 m_mousePressed = false;
1067 m_currentMousePosition = mouseEvent.pos();
1072 static_cast<SVGDocument*>(m_frame->document())->updatePan(m_currentMousePosition);
1077 if (m_frameSetBeingResized)
1078 return dispatchMouseEvent(mouseupEvent, m_frameSetBeingResized.get(), true, m_clickCount, mouseEvent, false);
1080 if (m_lastScrollbarUnderMouse) {
1082 return m_lastScrollbarUnderMouse->handleMouseReleaseEvent(mouseEvent);
1085 MouseEventWithHitTestResults mev = prepareMouseEvent(HitTestRequest(false, false, false, true), mouseEvent);
1086 Node* targetNode = m_capturingMouseEventsNode.get() ? m_capturingMouseEventsNode.get() : mev.targetNode();
1087 Frame* subframe = subframeForTargetNode(targetNode);
1088 if (subframe && passMouseReleaseEventToSubframe(mev, subframe)) {
1089 m_capturingMouseEventsNode = 0;
1093 bool swallowMouseUpEvent = dispatchMouseEvent(mouseupEvent, mev.targetNode(), true, m_clickCount, mouseEvent, false);
1095 // Don't ever dispatch click events for right clicks
1096 bool swallowClickEvent = false;
1097 if (m_clickCount > 0 && mouseEvent.button() != RightButton && mev.targetNode() == m_clickNode)
1098 swallowClickEvent = dispatchMouseEvent(clickEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
1100 if (m_resizeLayer) {
1101 m_resizeLayer->setInResizeMode(false);
1105 bool swallowMouseReleaseEvent = false;
1106 if (!swallowMouseUpEvent)
1107 swallowMouseReleaseEvent = handleMouseReleaseEvent(mev);
1111 return swallowMouseUpEvent || swallowClickEvent || swallowMouseReleaseEvent;
1114 bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Node* dragTarget, const PlatformMouseEvent& event, Clipboard* clipboard)
1116 IntPoint contentsPos = m_frame->view()->windowToContents(event.pos());
1118 RefPtr<MouseEvent> me = new MouseEvent(eventType,
1119 true, true, m_frame->document()->defaultView(),
1120 0, event.globalX(), event.globalY(), contentsPos.x(), contentsPos.y(),
1121 event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(),
1124 ExceptionCode ec = 0;
1125 EventTargetNodeCast(dragTarget)->dispatchEvent(me.get(), ec, true);
1126 return me->defaultPrevented();
1129 bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
1131 bool accept = false;
1133 if (!m_frame->document())
1136 if (!m_frame->view())
1139 MouseEventWithHitTestResults mev = prepareMouseEvent(HitTestRequest(true, false), event);
1141 // Drag events should never go to text nodes (following IE, and proper mouseover/out dispatch)
1142 Node* newTarget = mev.targetNode();
1143 if (newTarget && newTarget->isTextNode())
1144 newTarget = newTarget->parentNode();
1146 newTarget = newTarget->shadowAncestorNode();
1148 if (m_dragTarget != newTarget) {
1149 // FIXME: this ordering was explicitly chosen to match WinIE. However,
1150 // it is sometimes incorrect when dragging within subframes, as seen with
1151 // LayoutTests/fast/events/drag-in-frames.html.
1153 if (newTarget->hasTagName(frameTag) || newTarget->hasTagName(iframeTag))
1154 accept = static_cast<HTMLFrameElementBase*>(newTarget)->contentFrame()->eventHandler()->updateDragAndDrop(event, clipboard);
1156 accept = dispatchDragEvent(dragenterEvent, newTarget, event, clipboard);
1159 Frame* frame = (m_dragTarget->hasTagName(frameTag) || m_dragTarget->hasTagName(iframeTag))
1160 ? static_cast<HTMLFrameElementBase*>(m_dragTarget.get())->contentFrame() : 0;
1162 accept = frame->eventHandler()->updateDragAndDrop(event, clipboard);
1164 dispatchDragEvent(dragleaveEvent, m_dragTarget.get(), event, clipboard);
1168 if (newTarget->hasTagName(frameTag) || newTarget->hasTagName(iframeTag))
1169 accept = static_cast<HTMLFrameElementBase*>(newTarget)->contentFrame()->eventHandler()->updateDragAndDrop(event, clipboard);
1171 accept = dispatchDragEvent(dragoverEvent, newTarget, event, clipboard);
1173 m_dragTarget = newTarget;
1178 void EventHandler::cancelDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
1181 Frame* frame = (m_dragTarget->hasTagName(frameTag) || m_dragTarget->hasTagName(iframeTag))
1182 ? static_cast<HTMLFrameElementBase*>(m_dragTarget.get())->contentFrame() : 0;
1184 frame->eventHandler()->cancelDragAndDrop(event, clipboard);
1186 dispatchDragEvent(dragleaveEvent, m_dragTarget.get(), event, clipboard);
1191 bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
1193 bool accept = false;
1195 Frame* frame = (m_dragTarget->hasTagName(frameTag) || m_dragTarget->hasTagName(iframeTag))
1196 ? static_cast<HTMLFrameElementBase*>(m_dragTarget.get())->contentFrame() : 0;
1198 accept = frame->eventHandler()->performDragAndDrop(event, clipboard);
1200 accept = dispatchDragEvent(dropEvent, m_dragTarget.get(), event, clipboard);
1206 void EventHandler::clearDragState()
1209 m_capturingMouseEventsNode = 0;
1211 m_sendingEventToSubview = false;
1215 Node* EventHandler::nodeUnderMouse() const
1217 return m_nodeUnderMouse.get();
1220 void EventHandler::setCapturingMouseEventsNode(PassRefPtr<Node> n)
1222 m_capturingMouseEventsNode = n;
1225 MouseEventWithHitTestResults EventHandler::prepareMouseEvent(const HitTestRequest& request, const PlatformMouseEvent& mev)
1228 ASSERT(m_frame->document());
1230 IntPoint documentPoint = m_frame->view()->windowToContents(mev.pos());
1231 return m_frame->document()->prepareMouseEvent(request, documentPoint, mev);
1234 void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMouseEvent& mouseEvent, bool fireMouseOverOut)
1236 Node* result = targetNode;
1238 // If we're capturing, we always go right to that node.
1239 if (m_capturingMouseEventsNode)
1240 result = m_capturingMouseEventsNode.get();
1242 // If the target node is a text node, dispatch on the parent node - rdar://4196646
1243 if (result && result->isTextNode())
1244 result = result->parentNode();
1246 result = result->shadowAncestorNode();
1248 m_nodeUnderMouse = result;
1250 // Fire mouseout/mouseover if the mouse has shifted to a different node.
1251 if (fireMouseOverOut) {
1252 if (m_lastNodeUnderMouse && m_lastNodeUnderMouse->document() != m_frame->document()) {
1253 m_lastNodeUnderMouse = 0;
1254 m_lastScrollbarUnderMouse = 0;
1257 if (m_lastNodeUnderMouse != m_nodeUnderMouse) {
1258 // send mouseout event to the old node
1259 if (m_lastNodeUnderMouse)
1260 EventTargetNodeCast(m_lastNodeUnderMouse.get())->dispatchMouseEvent(mouseEvent, mouseoutEvent, 0, m_nodeUnderMouse.get());
1261 // send mouseover event to the new node
1262 if (m_nodeUnderMouse)
1263 EventTargetNodeCast(m_nodeUnderMouse.get())->dispatchMouseEvent(mouseEvent, mouseoverEvent, 0, m_lastNodeUnderMouse.get());
1265 m_lastNodeUnderMouse = m_nodeUnderMouse;
1269 bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targetNode, bool cancelable, int clickCount, const PlatformMouseEvent& mouseEvent, bool setUnder)
1271 updateMouseEventTargetNode(targetNode, mouseEvent, setUnder);
1273 bool swallowEvent = false;
1275 if (m_nodeUnderMouse)
1276 swallowEvent = EventTargetNodeCast(m_nodeUnderMouse.get())->dispatchMouseEvent(mouseEvent, eventType, clickCount);
1278 if (!swallowEvent && eventType == mousedownEvent) {
1279 // Blur current focus node when a link/button is clicked; this
1280 // is expected by some sites that rely on onChange handlers running
1281 // from form fields before the button click is processed.
1282 Node* node = m_nodeUnderMouse.get();
1283 RenderObject* renderer = node ? node->renderer() : 0;
1285 // Walk up the render tree to search for a node to focus.
1286 // Walking up the DOM tree wouldn't work for shadow trees, like those behind the engine-based text fields.
1288 node = renderer->element();
1289 if (node && node->isFocusable()) {
1290 // To fix <rdar://problem/4895428> Can't drag selected ToDo, we don't focus a
1291 // node on mouse down if it's selected and inside a focused node. It will be
1292 // focused if the user does a mouseup over it, however, because the mouseup
1293 // will set a selection inside it, which will call setFocuseNodeIfNeeded.
1294 ExceptionCode ec = 0;
1295 Node* n = node->isShadowNode() ? node->shadowParentNode() : node;
1296 if (m_frame->selectionController()->isRange() &&
1297 m_frame->selectionController()->toRange()->compareNode(n, ec) == Range::NODE_INSIDE &&
1298 n->isDescendantOf(m_frame->document()->focusedNode()))
1304 renderer = renderer->parent();
1306 // If focus shift is blocked, we eat the event. Note we should never clear swallowEvent
1307 // if the page already set it (e.g., by canceling default behavior).
1308 if (node && node->isMouseFocusable()) {
1309 if (!m_frame->page()->focusController()->setFocusedNode(node, m_frame))
1310 swallowEvent = true;
1311 } else if (!node || !node->focused()) {
1312 if (!m_frame->page()->focusController()->setFocusedNode(0, m_frame))
1313 swallowEvent = true;
1317 return swallowEvent;
1320 bool EventHandler::handleWheelEvent(PlatformWheelEvent& e)
1322 Document* doc = m_frame->document();
1326 RenderObject* docRenderer = doc->renderer();
1330 IntPoint vPoint = m_frame->view()->windowToContents(e.pos());
1332 HitTestRequest request(true, false);
1333 HitTestResult result(vPoint);
1334 doc->renderer()->layer()->hitTest(request, result);
1335 Node* node = result.innerNode();
1338 // Figure out which view to send the event to.
1339 RenderObject* target = node->renderer();
1341 if (target && target->isWidget()) {
1342 Widget* widget = static_cast<RenderWidget*>(target)->widget();
1344 if (widget && passWheelEventToWidget(e, widget)) {
1350 node = node->shadowAncestorNode();
1351 EventTargetNodeCast(node)->dispatchWheelEvent(e);
1355 if (node->renderer()) {
1356 // Just break up into two scrolls if we need to. Diagonal movement on
1357 // a MacBook pro is an example of a 2-dimensional mouse wheel event (where both deltaX and deltaY can be set).
1358 float deltaX = e.isContinuous() ? e.continuousDeltaX() : e.deltaX();
1359 float deltaY = e.isContinuous() ? e.continuousDeltaY() : e.deltaY();
1360 if (deltaX && node->renderer()->scroll(deltaX < 0 ? ScrollRight : ScrollLeft, e.isContinuous() ? ScrollByPixel : ScrollByLine,
1361 deltaX < 0 ? -deltaX : deltaX))
1363 if (deltaY && node->renderer()->scroll(deltaY < 0 ? ScrollDown : ScrollUp, e.isContinuous() ? ScrollByPixel : ScrollByLine,
1364 deltaY < 0 ? -deltaY : deltaY))
1369 if (!e.isAccepted())
1370 m_frame->view()->wheelEvent(e);
1372 return e.isAccepted();
1375 bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
1377 Document* doc = m_frame->document();
1378 FrameView* v = m_frame->view();
1383 IntPoint viewportPos = v->windowToContents(event.pos());
1384 MouseEventWithHitTestResults mev = doc->prepareMouseEvent(HitTestRequest(false, true), viewportPos, event);
1386 if (!m_frame->selectionController()->contains(viewportPos) &&
1387 // FIXME: In the editable case, word selection sometimes selects content that isn't underneath the mouse.
1388 // If the selection is non-editable, we do word selection to make it easier to use the contextual menu items
1389 // available for text selections. But only if we're above text.
1390 (m_frame->selectionController()->isContentEditable() || mev.targetNode() && mev.targetNode()->isTextNode())) {
1391 m_mouseDownMayStartSelect = true; // context menu events are always allowed to perform a selection
1392 selectClosestWordOrLinkFromMouseEvent(mev);
1395 swallowEvent = dispatchMouseEvent(contextmenuEvent, mev.targetNode(), true, 0, event, true);
1397 return swallowEvent;
1400 void EventHandler::scheduleHoverStateUpdate()
1402 if (!m_hoverTimer.isActive())
1403 m_hoverTimer.startOneShot(0);
1406 // Whether or not a mouse down can begin the creation of a selection. Fires the selectStart event.
1407 bool EventHandler::canMouseDownStartSelect(Node* node)
1409 if (!node || !node->renderer())
1412 // Some controls and images can't start a select on a mouse down.
1413 if (!node->canStartSelection())
1416 for (RenderObject* curr = node->renderer(); curr; curr = curr->parent())
1417 if (Node* node = curr->element())
1418 return EventTargetNodeCast(node)->dispatchHTMLEvent(selectstartEvent, true, true);
1423 bool EventHandler::canMouseDragExtendSelect(Node* node)
1425 if (!node || !node->renderer())
1428 for (RenderObject* curr = node->renderer(); curr; curr = curr->parent())
1429 if (Node* node = curr->element())
1430 return EventTargetNodeCast(node)->dispatchHTMLEvent(selectstartEvent, true, true);
1435 void EventHandler::setResizingFrameSet(HTMLFrameSetElement* frameSet)
1437 m_frameSetBeingResized = frameSet;
1440 void EventHandler::hoverTimerFired(Timer<EventHandler>*)
1442 m_hoverTimer.stop();
1445 ASSERT(m_frame->document());
1447 if (RenderObject* renderer = m_frame->renderer()) {
1448 HitTestResult result(m_frame->view()->windowToContents(m_currentMousePosition));
1449 renderer->layer()->hitTest(HitTestRequest(false, false, true), result);
1450 m_frame->document()->updateRendering();
1454 static EventTargetNode* eventTargetNodeForDocument(Document* doc)
1458 Node* node = doc->focusedNode();
1460 if (doc->isHTMLDocument())
1463 node = doc->documentElement();
1467 return EventTargetNodeCast(node);
1470 bool EventHandler::handleAccessKey(const PlatformKeyboardEvent& evt)
1478 String key = evt.unmodifiedText();
1479 Element* elem = m_frame->document()->getElementByAccessKey(key.lower());
1481 elem->accessKeyAction(false);
1490 bool EventHandler::needsKeyboardEventDisambiguationQuirks() const
1496 bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
1498 // Check for cases where we are too early for events -- possible unmatched key up
1499 // from pressing return in the location bar.
1500 RefPtr<EventTargetNode> node = eventTargetNodeForDocument(m_frame->document());
1504 // FIXME: what is this doing here, in keyboard event handler?
1505 m_frame->loader()->resetMultipleFormSubmissionProtection();
1507 // In IE, access keys are special, they are handled after default keydown processing, but cannot be canceled - this is hard to match.
1508 // On Mac OS X, we process them before dispatching keydown, as the default keydown handler implements Emacs key bindings, which may conflict
1509 // with access keys. Then we dispatch keydown, but suppress its default handling.
1510 // On Windows, WebKit explicitly calls handleAccessKey() instead of dispatching a keypress event for WM_SYSCHAR messages.
1511 // Other platforms currently match either Mac or Windows behavior, depending on whether they send combined KeyDown events.
1512 bool matchedAnAccessKey = false;
1513 if (initialKeyEvent.type() == PlatformKeyboardEvent::KeyDown)
1514 matchedAnAccessKey = handleAccessKey(initialKeyEvent);
1516 // FIXME: it would be fair to let an input method handle KeyUp events before DOM dispatch.
1517 if (initialKeyEvent.type() == PlatformKeyboardEvent::KeyUp || initialKeyEvent.type() == PlatformKeyboardEvent::Char)
1518 return !node->dispatchKeyEvent(initialKeyEvent);
1520 bool backwardCompatibilityMode = needsKeyboardEventDisambiguationQuirks();
1523 PlatformKeyboardEvent keyDownEvent = initialKeyEvent;
1524 if (keyDownEvent.type() != PlatformKeyboardEvent::RawKeyDown)
1525 keyDownEvent.disambiguateKeyDownEvent(PlatformKeyboardEvent::RawKeyDown, backwardCompatibilityMode);
1526 RefPtr<KeyboardEvent> keydown = new KeyboardEvent(keyDownEvent, m_frame->document()->defaultView());
1527 if (matchedAnAccessKey)
1528 keydown->setDefaultPrevented(true);
1529 keydown->setTarget(node);
1531 if (initialKeyEvent.type() == PlatformKeyboardEvent::RawKeyDown) {
1532 node->dispatchEvent(keydown, ec, true);
1533 return keydown->defaultHandled() || keydown->defaultPrevented();
1536 // Run input method in advance of DOM event handling. This may result in the IM
1537 // modifying the page prior the keydown event, but this behaviour is necessary
1538 // in order to match IE:
1539 // 1. preventing default handling of keydown and keypress events has no effect on IM input;
1540 // 2. if an input method handles the event, its keyCode is set to 229 in keydown event.
1541 m_frame->editor()->handleInputMethodKeydown(keydown.get());
1543 bool handledByInputMethod = keydown->defaultHandled();
1545 if (handledByInputMethod) {
1546 keyDownEvent.setWindowsVirtualKeyCode(CompositionEventKeyCode);
1547 keydown = new KeyboardEvent(keyDownEvent, m_frame->document()->defaultView());
1548 keydown->setTarget(node);
1549 keydown->setDefaultHandled();
1552 node->dispatchEvent(keydown, ec, true);
1553 bool keydownResult = keydown->defaultHandled() || keydown->defaultPrevented();
1554 if (handledByInputMethod || (keydownResult && !backwardCompatibilityMode))
1555 return keydownResult;
1557 // Focus may have changed during keydown handling, so refetch node.
1558 // But if we are dispatching a fake backward compatibility keypress, then we pretend that the keypress happened on the original node.
1559 if (!keydownResult) {
1560 node = eventTargetNodeForDocument(m_frame->document());
1565 PlatformKeyboardEvent keyPressEvent = initialKeyEvent;
1566 keyPressEvent.disambiguateKeyDownEvent(PlatformKeyboardEvent::Char, backwardCompatibilityMode);
1567 if (keyPressEvent.text().isEmpty())
1568 return keydownResult;
1569 RefPtr<KeyboardEvent> keypress = new KeyboardEvent(keyPressEvent, m_frame->document()->defaultView());
1570 keypress->setTarget(node);
1572 keypress->setDefaultPrevented(true);
1574 keypress->keypressCommands() = keydown->keypressCommands();
1576 node->dispatchEvent(keypress, ec, true);
1578 return keydownResult || keypress->defaultPrevented() || keypress->defaultHandled();
1581 void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
1583 if (event->type() == keydownEvent) {
1584 m_frame->editor()->handleKeyboardEvent(event);
1585 if (event->defaultHandled())
1587 if (event->keyIdentifier() == "U+0009")
1588 defaultTabEventHandler(event, false);
1590 if (event->type() == keypressEvent) {
1591 m_frame->editor()->handleKeyboardEvent(event);
1592 if (event->defaultHandled())
1597 bool EventHandler::dragHysteresisExceeded(const FloatPoint& floatDragViewportLocation) const
1599 IntPoint dragViewportLocation((int)floatDragViewportLocation.x(), (int)floatDragViewportLocation.y());
1600 return dragHysteresisExceeded(dragViewportLocation);
1603 bool EventHandler::dragHysteresisExceeded(const IntPoint& dragViewportLocation) const
1605 IntPoint dragLocation = m_frame->view()->windowToContents(dragViewportLocation);
1606 IntSize delta = dragLocation - m_mouseDownPos;
1608 int threshold = GeneralDragHysteresis;
1609 if (dragState().m_dragSrcIsImage)
1610 threshold = ImageDragHysteresis;
1611 else if (dragState().m_dragSrcIsLink)
1612 threshold = LinkDragHysteresis;
1613 else if (dragState().m_dragSrcInSelection)
1614 threshold = TextDragHysteresis;
1616 return abs(delta.width()) >= threshold || abs(delta.height()) >= threshold;
1619 void EventHandler::freeClipboard()
1621 if (dragState().m_dragClipboard)
1622 dragState().m_dragClipboard->setAccessPolicy(ClipboardNumb);
1625 bool EventHandler::shouldDragAutoNode(Node* node, const IntPoint& point) const
1628 if (node->hasChildNodes() || !m_frame->view())
1630 return m_frame->page() && m_frame->page()->dragController()->mayStartDragAtEventLocation(m_frame, point);
1633 void EventHandler::dragSourceMovedTo(const PlatformMouseEvent& event)
1635 if (dragState().m_dragSrc && dragState().m_dragSrcMayBeDHTML)
1636 // for now we don't care if event handler cancels default behavior, since there is none
1637 dispatchDragSrcEvent(dragEvent, event);
1640 void EventHandler::dragSourceEndedAt(const PlatformMouseEvent& event, DragOperation operation)
1642 if (dragState().m_dragSrc && dragState().m_dragSrcMayBeDHTML) {
1643 dragState().m_dragClipboard->setDestinationOperation(operation);
1644 // for now we don't care if event handler cancels default behavior, since there is none
1645 dispatchDragSrcEvent(dragendEvent, event);
1648 dragState().m_dragSrc = 0;
1651 // returns if we should continue "default processing", i.e., whether eventhandler canceled
1652 bool EventHandler::dispatchDragSrcEvent(const AtomicString& eventType, const PlatformMouseEvent& event)
1654 return !dispatchDragEvent(eventType, dragState().m_dragSrc.get(), event, dragState().m_dragClipboard.get());
1657 bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event)
1659 if (event.event().button() != LeftButton || event.event().eventType() != MouseEventMoved) {
1660 // If we allowed the other side of the bridge to handle a drag
1661 // last time, then m_mousePressed might still be set. So we
1662 // clear it now to make sure the next move after a drag
1663 // doesn't look like a drag.
1664 m_mousePressed = false;
1668 if (eventLoopHandleMouseDragged(event))
1671 // Careful that the drag starting logic stays in sync with eventMayStartDrag()
1673 if (m_mouseDownMayStartDrag && !dragState().m_dragSrc) {
1674 allowDHTMLDrag(dragState().m_dragSrcMayBeDHTML, dragState().m_dragSrcMayBeUA);
1675 if (!dragState().m_dragSrcMayBeDHTML && !dragState().m_dragSrcMayBeUA)
1676 m_mouseDownMayStartDrag = false; // no element is draggable
1679 if (m_mouseDownMayStartDrag && !dragState().m_dragSrc) {
1680 // try to find an element that wants to be dragged
1681 HitTestRequest request(true, false);
1682 HitTestResult result(m_mouseDownPos);
1683 m_frame->renderer()->layer()->hitTest(request, result);
1684 Node* node = result.innerNode();
1685 if (node && node->renderer())
1686 dragState().m_dragSrc = node->renderer()->draggableNode(dragState().m_dragSrcMayBeDHTML, dragState().m_dragSrcMayBeUA,
1687 m_mouseDownPos.x(), m_mouseDownPos.y(), dragState().m_dragSrcIsDHTML);
1689 dragState().m_dragSrc = 0;
1691 if (!dragState().m_dragSrc)
1692 m_mouseDownMayStartDrag = false; // no element is draggable
1694 // remember some facts about this source, while we have a HitTestResult handy
1695 node = result.URLElement();
1696 dragState().m_dragSrcIsLink = node && node->isLink();
1698 node = result.innerNonSharedNode();
1699 dragState().m_dragSrcIsImage = node && node->renderer() && node->renderer()->isImage();
1701 dragState().m_dragSrcInSelection = m_frame->selectionController()->contains(m_mouseDownPos);
1705 // For drags starting in the selection, the user must wait between the mousedown and mousedrag,
1706 // or else we bail on the dragging stuff and allow selection to occur
1707 if (m_mouseDownMayStartDrag && !dragState().m_dragSrcIsImage && dragState().m_dragSrcInSelection && event.event().timestamp() - m_mouseDownTimestamp < TextDragDelay) {
1708 m_mouseDownMayStartDrag = false;
1709 dragState().m_dragSrc = 0;
1710 // ...but if this was the first click in the window, we don't even want to start selection
1711 if (eventActivatedView(event.event()))
1712 m_mouseDownMayStartSelect = false;
1715 if (!m_mouseDownMayStartDrag)
1716 return !mouseDownMayStartSelect() && !m_mouseDownMayStartAutoscroll;
1718 // We are starting a text/image/url drag, so the cursor should be an arrow
1719 m_frame->view()->setCursor(pointerCursor());
1721 if (!dragHysteresisExceeded(event.event().pos()))
1724 // Once we're past the hysteresis point, we don't want to treat this gesture as a click
1727 DragOperation srcOp = DragOperationNone;
1729 freeClipboard(); // would only happen if we missed a dragEnd. Do it anyway, just
1730 // to make sure it gets numbified
1731 dragState().m_dragClipboard = createDraggingClipboard();
1733 if (dragState().m_dragSrcMayBeDHTML) {
1734 // Check to see if the is a DOM based drag, if it is get the DOM specified drag
1736 if (dragState().m_dragSrcIsDHTML) {
1738 dragState().m_dragSrc->renderer()->absolutePosition(srcX, srcY);
1739 IntSize delta = m_mouseDownPos - IntPoint(srcX, srcY);
1740 dragState().m_dragClipboard->setDragImageElement(dragState().m_dragSrc.get(), IntPoint() + delta);
1743 m_mouseDownMayStartDrag = dispatchDragSrcEvent(dragstartEvent, m_mouseDown)
1744 && !m_frame->selectionController()->isInPasswordField();
1746 // Invalidate clipboard here against anymore pasteboard writing for security. The drag
1747 // image can still be changed as we drag, but not the pasteboard data.
1748 dragState().m_dragClipboard->setAccessPolicy(ClipboardImageWritable);
1750 if (m_mouseDownMayStartDrag) {
1751 // gather values from DHTML element, if it set any
1752 dragState().m_dragClipboard->sourceOperation(srcOp);
1754 // Yuck, dragSourceMovedTo() can be called as a result of kicking off the drag with
1755 // dragImage! Because of that dumb reentrancy, we may think we've not started the
1756 // drag when that happens. So we have to assume it's started before we kick it off.
1757 dragState().m_dragClipboard->setDragHasStarted();
1761 if (m_mouseDownMayStartDrag) {
1762 DragController* dragController = m_frame->page() ? m_frame->page()->dragController() : 0;
1763 bool startedDrag = dragController && dragController->startDrag(m_frame, dragState().m_dragClipboard.get(), srcOp, event.event(), m_mouseDownPos, dragState().m_dragSrcIsDHTML);
1764 if (!startedDrag && dragState().m_dragSrcMayBeDHTML) {
1765 // Drag was canned at the last minute - we owe m_dragSrc a DRAGEND event
1766 dispatchDragSrcEvent(dragendEvent, event.event());
1767 m_mouseDownMayStartDrag = false;
1771 if (!m_mouseDownMayStartDrag) {
1772 // something failed to start the drag, cleanup
1774 dragState().m_dragSrc = 0;
1777 // No more default handling (like selection), whether we're past the hysteresis bounds or not
1781 bool EventHandler::handleTextInputEvent(const String& text, Event* underlyingEvent,
1782 bool isLineBreak, bool isBackTab)
1787 // Platforms should differentiate real commands like selectAll from text input in disguise (like insertNewline),
1788 // and avoid dispatching text input events from keydown default handlers.
1789 if (underlyingEvent && underlyingEvent->isKeyboardEvent())
1790 ASSERT(static_cast<KeyboardEvent*>(underlyingEvent)->type() == keypressEvent);
1792 EventTarget* target;
1793 if (underlyingEvent)
1794 target = underlyingEvent->target();
1796 target = eventTargetNodeForDocument(m_frame->document());
1799 RefPtr<TextEvent> event = new TextEvent(m_frame->domWindow(), text);
1800 event->setUnderlyingEvent(underlyingEvent);
1801 event->setIsLineBreak(isLineBreak);
1802 event->setIsBackTab(isBackTab);
1804 return target->dispatchEvent(event.release(), ec, true);
1808 #if !PLATFORM(MAC) && !PLATFORM(QT)
1809 bool EventHandler::invertSenseOfTabsToLinks(KeyboardEvent*) const
1815 bool EventHandler::tabsToLinks(KeyboardEvent* event) const
1817 Page* page = m_frame->page();
1821 if (page->chrome()->client()->tabsToLinks())
1822 return !invertSenseOfTabsToLinks(event);
1824 return invertSenseOfTabsToLinks(event);
1827 void EventHandler::defaultTextInputEventHandler(TextEvent* event)
1829 String data = event->data();
1831 if (event->isLineBreak()) {
1832 if (m_frame->editor()->insertLineBreak())
1833 event->setDefaultHandled();
1835 if (m_frame->editor()->insertParagraphSeparator())
1836 event->setDefaultHandled();
1839 if (m_frame->editor()->insertTextWithoutSendingTextEvent(data, false, event))
1840 event->setDefaultHandled();
1844 void EventHandler::defaultTabEventHandler(Event* event, bool isBackTab)
1846 Page* page = m_frame->page();
1847 // Tabs can be used in design mode editing. You can still move out with back tab.
1848 if (!page || !page->tabKeyCyclesThroughElements() || (m_frame->document()->inDesignMode() && !isBackTab))
1850 FocusController* focus = page->focusController();
1851 KeyboardEvent* keyboardEvent = findKeyboardEvent(event);
1854 handled = focus->advanceFocus(FocusDirectionBackward, keyboardEvent);
1856 handled = focus->advanceFocus(keyboardEvent); // get direction from keyboard event
1858 event->setDefaultHandled();
1861 void EventHandler::capsLockStateMayHaveChanged()
1863 if (Document* d = m_frame->document())
1864 if (Node* node = d->focusedNode())
1865 if (RenderObject* r = node->renderer())
1866 r->capsLockStateMayHaveChanged();