#include "config.h"
#include "EventHandler.h"
#include "AXObjectCache.h"
#include "CachedImage.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "Cursor.h"
#include "CursorList.h"
#include "Document.h"
#include "DocumentEventQueue.h"
#include "DragController.h"
#include "DragState.h"
#include "Editor.h"
#include "EventNames.h"
#include "FloatPoint.h"
#include "FloatRect.h"
#include "FocusController.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "htmlediting.h"
#include "HTMLFrameElementBase.h"
#include "HTMLFrameSetElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "Image.h"
#include "InspectorInstrumentation.h"
#include "KeyboardEvent.h"
#include "MouseEvent.h"
#include "MouseEventWithHitTestResults.h"
#include "Page.h"
#include "PlatformEvent.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformWheelEvent.h"
#include "PluginDocument.h"
#include "RenderFrameSet.h"
#include "RenderLayer.h"
#include "RenderTextControlSingleLine.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ScrollAnimator.h"
#include "Scrollbar.h"
#include "Settings.h"
#include "SpatialNavigation.h"
#include "StaticHashSetNodeList.h"
#include "StyleCachedImage.h"
#include "TextEvent.h"
#include "TextIterator.h"
#include "UserGestureIndicator.h"
#include "UserTypingGestureIndicator.h"
#include "WheelEvent.h"
#include "WindowsKeyboardCodes.h"
#include <wtf/Assertions.h>
#include <wtf/CurrentTime.h>
#include <wtf/StdLibExtras.h>
#include <wtf/TemporaryChange.h>
#include <wtf/UnusedParam.h>
#if ENABLE(GESTURE_EVENTS)
#include "PlatformGestureEvent.h"
#endif
#if ENABLE(TOUCH_ADJUSTMENT)
#include "TouchAdjustment.h"
#endif
#if ENABLE(SVG)
#include "SVGDocument.h"
#include "SVGElementInstance.h"
#include "SVGNames.h"
#include "SVGUseElement.h"
#endif
#include "Touch.h"
#include "PlatformTouchEventIOS.h"
#include "TouchEvent.h"
#include "TouchList.h"
namespace WebCore {
using namespace HTMLNames;
#if ENABLE(DRAG_SUPPORT)
const int LinkDragHysteresis = 40;
const int ImageDragHysteresis = 5;
const int TextDragHysteresis = 3;
const int GeneralDragHysteresis = 3;
#endif // ENABLE(DRAG_SUPPORT)
const float GestureUnknown = 0.0f;
const int CompositionEventKeyCode = 229;
#if ENABLE(SVG)
using namespace SVGNames;
#endif
const double autoscrollInterval = 0.05;
const double fakeMouseMoveShortInterval = 0.1;
const double fakeMouseMoveLongInterval = 0.250;
enum NoCursorChangeType { NoCursorChange };
class OptionalCursor {
public:
OptionalCursor(NoCursorChangeType) : m_isCursorChange(false) { }
OptionalCursor(const Cursor& cursor) : m_isCursorChange(true), m_cursor(cursor) { }
bool isCursorChange() const { return m_isCursorChange; }
const Cursor& cursor() const { return m_cursor; }
private:
bool m_isCursorChange;
Cursor m_cursor;
};
class MaximumDurationTracker {
public:
explicit MaximumDurationTracker(double *maxDuration)
: m_maxDuration(maxDuration)
, m_start(monotonicallyIncreasingTime())
{
}
~MaximumDurationTracker()
{
*m_maxDuration = max(*m_maxDuration, monotonicallyIncreasingTime() - m_start);
}
private:
double* m_maxDuration;
double m_start;
};
static inline ScrollGranularity wheelGranularityToScrollGranularity(WheelEvent::Granularity granularity)
{
switch (granularity) {
case WheelEvent::Page:
return ScrollByPage;
case WheelEvent::Line:
return ScrollByLine;
case WheelEvent::Pixel:
return ScrollByPixel;
}
return ScrollByPixel;
}
static inline bool scrollNode(float delta, ScrollGranularity granularity, ScrollDirection positiveDirection, ScrollDirection negativeDirection, Node* node, Node** stopNode)
{
if (!delta)
return false;
if (!node->renderer())
return false;
RenderBox* enclosingBox = node->renderer()->enclosingBox();
float absDelta = delta > 0 ? delta : -delta;
return enclosingBox->scroll(delta < 0 ? negativeDirection : positiveDirection, granularity, absDelta, stopNode);
}
#if !PLATFORM(MAC)
inline bool EventHandler::eventLoopHandleMouseUp(const MouseEventWithHitTestResults&)
{
return false;
}
#if ENABLE(DRAG_SUPPORT)
inline bool EventHandler::eventLoopHandleMouseDragged(const MouseEventWithHitTestResults&)
{
return false;
}
#endif
#endif
EventHandler::EventHandler(Frame* frame)
: m_frame(frame)
, m_mousePressed(false)
, m_capturesDragging(false)
, m_mouseDownMayStartSelect(false)
#if ENABLE(DRAG_SUPPORT)
, m_mouseDownMayStartDrag(false)
, m_dragMayStartSelectionInstead(false)
#endif
, m_mouseDownWasSingleClickInSelection(false)
, m_selectionInitiationState(HaveNotStartedSelection)
, m_panScrollInProgress(false)
, m_panScrollButtonPressed(false)
, m_springLoadedPanScrollInProgress(false)
, m_hoverTimer(this, &EventHandler::hoverTimerFired)
, m_autoscrollTimer(this, &EventHandler::autoscrollTimerFired)
, m_autoscrollRenderer(0)
, m_autoscrollInProgress(false)
, m_mouseDownMayStartAutoscroll(false)
, m_mouseDownWasInSubframe(false)
, m_fakeMouseMoveEventTimer(this, &EventHandler::fakeMouseMoveEventTimerFired)
#if ENABLE(SVG)
, m_svgPan(false)
#endif
, m_resizeLayer(0)
, m_eventHandlerWillResetCapturingMouseEventsNode(0)
, m_clickCount(0)
, m_gestureInitialDiameter(GestureUnknown)
, m_gestureLastDiameter(GestureUnknown)
, m_gestureInitialRotation(GestureUnknown)
, m_gestureLastRotation(GestureUnknown)
, m_touchEventTargetSubframe(0)
, m_mouseDownTimestamp(0)
, m_useLatchedWheelEventNode(false)
, m_widgetIsLatched(false)
#if PLATFORM(MAC)
, m_mouseDownView(nil)
, m_sendingEventToSubview(false)
#endif
, m_maxMouseMovedDuration(0)
, m_baseEventType(PlatformEvent::NoType)
{
}
EventHandler::~EventHandler()
{
ASSERT(!m_fakeMouseMoveEventTimer.isActive());
}
#if ENABLE(DRAG_SUPPORT)
DragState& EventHandler::dragState()
{
DEFINE_STATIC_LOCAL(DragState, state, ());
return state;
}
#endif // ENABLE(DRAG_SUPPORT)
void EventHandler::clear()
{
m_hoverTimer.stop();
m_fakeMouseMoveEventTimer.stop();
m_resizeLayer = 0;
m_nodeUnderMouse = 0;
m_lastNodeUnderMouse = 0;
#if ENABLE(SVG)
m_instanceUnderMouse = 0;
m_lastInstanceUnderMouse = 0;
#endif
m_lastMouseMoveEventSubframe = 0;
m_lastScrollbarUnderMouse = 0;
m_clickCount = 0;
m_clickNode = 0;
m_gestureInitialDiameter = GestureUnknown;
m_gestureLastDiameter = GestureUnknown;
m_gestureInitialRotation = GestureUnknown;
m_gestureLastRotation = GestureUnknown;
m_touches.clear();
m_gestureTargets.clear();
m_touchEventTargetSubframe = 0;
m_frameSetBeingResized = 0;
#if ENABLE(DRAG_SUPPORT)
m_dragTarget = 0;
m_shouldOnlyFireDragOverEvent = false;
#endif
m_currentMousePosition = IntPoint();
m_mousePressNode = 0;
m_mousePressed = false;
m_capturesDragging = false;
m_capturingMouseEventsNode = 0;
m_latchedWheelEventNode = 0;
m_previousWheelScrolledNode = 0;
m_maxMouseMovedDuration = 0;
#if ENABLE(GESTURE_EVENTS)
m_baseEventType = PlatformEvent::NoType;
#endif
}
void EventHandler::nodeWillBeRemoved(Node* nodeToBeRemoved)
{
if (nodeToBeRemoved->contains(m_clickNode.get()))
m_clickNode = 0;
}
static void setSelectionIfNeeded(FrameSelection* selection, const VisibleSelection& newSelection)
{
ASSERT(selection);
if (selection->selection() != newSelection && selection->shouldChangeSelection(newSelection))
selection->setSelection(newSelection);
}
static inline bool dispatchSelectStart(Node* node)
{
if (!node || !node->renderer())
return true;
return node->dispatchEvent(Event::create(eventNames().selectstartEvent, true, true));
}
bool EventHandler::updateSelectionForMouseDownDispatchingSelectStart(Node* targetNode, const VisibleSelection& newSelection, TextGranularity granularity)
{
if (Position::nodeIsUserSelectNone(targetNode))
return false;
if (!dispatchSelectStart(targetNode))
return false;
if (newSelection.isRange())
m_selectionInitiationState = ExtendedSelection;
else {
granularity = CharacterGranularity;
m_selectionInitiationState = PlacedCaret;
}
m_frame->selection()->setNonDirectionalSelectionIfNeeded(newSelection, granularity);
return true;
}
void EventHandler::selectClosestWordFromMouseEvent(const MouseEventWithHitTestResults& result)
{
Node* innerNode = targetNode(result);
VisibleSelection newSelection;
if (innerNode && innerNode->renderer() && m_mouseDownMayStartSelect) {
VisiblePosition pos(innerNode->renderer()->positionForPoint(result.localPoint()));
if (pos.isNotNull()) {
newSelection = VisibleSelection(pos);
newSelection.expandUsingGranularity(WordGranularity);
}
if (newSelection.isRange() && result.event().clickCount() == 2 && m_frame->editor()->isSelectTrailingWhitespaceEnabled())
newSelection.appendTrailingWhitespace();
updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, WordGranularity);
}
}
void EventHandler::selectClosestWordOrLinkFromMouseEvent(const MouseEventWithHitTestResults& result)
{
if (!result.hitTestResult().isLiveLink())
return selectClosestWordFromMouseEvent(result);
Node* innerNode = targetNode(result);
if (innerNode && innerNode->renderer() && m_mouseDownMayStartSelect) {
VisibleSelection newSelection;
Element* URLElement = result.hitTestResult().URLElement();
VisiblePosition pos(innerNode->renderer()->positionForPoint(result.localPoint()));
if (pos.isNotNull() && pos.deepEquivalent().deprecatedNode()->isDescendantOf(URLElement))
newSelection = VisibleSelection::selectionFromContentsOfNode(URLElement);
updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, WordGranularity);
}
}
bool EventHandler::handleMousePressEventDoubleClick(const MouseEventWithHitTestResults& event)
{
if (event.event().button() != LeftButton)
return false;
if (m_frame->selection()->isRange())
m_selectionInitiationState = ExtendedSelection;
else
selectClosestWordFromMouseEvent(event);
return true;
}
bool EventHandler::handleMousePressEventTripleClick(const MouseEventWithHitTestResults& event)
{
if (event.event().button() != LeftButton)
return false;
Node* innerNode = targetNode(event);
if (!(innerNode && innerNode->renderer() && m_mouseDownMayStartSelect))
return false;
VisibleSelection newSelection;
VisiblePosition pos(innerNode->renderer()->positionForPoint(event.localPoint()));
if (pos.isNotNull()) {
newSelection = VisibleSelection(pos);
newSelection.expandUsingGranularity(ParagraphGranularity);
}
return updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, ParagraphGranularity);
}
static int textDistance(const Position& start, const Position& end)
{
RefPtr<Range> range = Range::create(start.anchorNode()->document(), start, end);
return TextIterator::rangeLength(range.get(), true);
}
bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
{
Node* innerNode = targetNode(event);
if (!(innerNode && innerNode->renderer() && m_mouseDownMayStartSelect))
return false;
bool extendSelection = event.event().shiftKey() && !event.isOverLink();
if (FrameView* view = m_frame->view()) {
LayoutPoint vPoint = view->windowToContents(event.event().position());
if (!extendSelection && m_frame->selection()->contains(vPoint)) {
m_mouseDownWasSingleClickInSelection = true;
return false;
}
}
VisiblePosition visiblePos(innerNode->renderer()->positionForPoint(event.localPoint()));
if (visiblePos.isNull())
visiblePos = VisiblePosition(firstPositionInOrBeforeNode(innerNode), DOWNSTREAM);
Position pos = visiblePos.deepEquivalent();
VisibleSelection newSelection = m_frame->selection()->selection();
TextGranularity granularity = CharacterGranularity;
if (extendSelection && newSelection.isCaretOrRange()) {
ASSERT(m_frame->settings());
if (m_frame->settings()->editingBehaviorType() == EditingMacBehavior) {
Position start = newSelection.start();
Position end = newSelection.end();
int distanceToStart = textDistance(start, pos);
int distanceToEnd = textDistance(pos, end);
if (distanceToStart <= distanceToEnd)
newSelection = VisibleSelection(end, pos);
else
newSelection = VisibleSelection(start, pos);
} else
newSelection.setExtent(pos);
if (m_frame->selection()->granularity() != CharacterGranularity) {
granularity = m_frame->selection()->granularity();
newSelection.expandUsingGranularity(m_frame->selection()->granularity());
}
} else
newSelection = VisibleSelection(visiblePos);
return updateSelectionForMouseDownDispatchingSelectStart(innerNode, newSelection, granularity);
}
static inline bool canMouseDownStartSelect(Node* node)
{
if (!node || !node->renderer())
return true;
if (!node->canStartSelection())
return false;
return true;
}
bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& event)
{
#if ENABLE(DRAG_SUPPORT)
dragState().m_dragSrc = 0;
#endif
cancelFakeMouseMoveEvent();
m_frame->document()->updateLayoutIgnorePendingStylesheets();
if (ScrollView* scrollView = m_frame->view()) {
if (scrollView->isPointInScrollbarCorner(event.event().position()))
return false;
}
bool singleClick = event.event().clickCount() <= 1;
m_mouseDownMayStartSelect = canMouseDownStartSelect(targetNode(event));
#if ENABLE(DRAG_SUPPORT)
m_mouseDownMayStartDrag = singleClick;
#endif
m_mouseDownWasSingleClickInSelection = false;
m_mouseDown = event.event();
if (event.isOverWidget() && passWidgetMouseDownEventToWidget(event))
return true;
#if ENABLE(SVG)
if (m_frame->document()->isSVGDocument()
&& static_cast<SVGDocument*>(m_frame->document())->zoomAndPanEnabled()) {
if (event.event().shiftKey() && singleClick) {
m_svgPan = true;
static_cast<SVGDocument*>(m_frame->document())->startPan(m_frame->view()->windowToContents(event.event().position()));
return true;
}
}
#endif
if (singleClick)
focusDocumentView();
Node* innerNode = targetNode(event);
m_mousePressNode = innerNode;
#if ENABLE(DRAG_SUPPORT)
m_dragStartPos = event.event().position();
#endif
bool swallowEvent = false;
m_mousePressed = true;
m_selectionInitiationState = HaveNotStartedSelection;
if (event.event().clickCount() == 2)
swallowEvent = handleMousePressEventDoubleClick(event);
else if (event.event().clickCount() >= 3)
swallowEvent = handleMousePressEventTripleClick(event);
else
swallowEvent = handleMousePressEventSingleClick(event);
m_mouseDownMayStartAutoscroll = m_mouseDownMayStartSelect
|| (m_mousePressNode && m_mousePressNode->renderBox() && m_mousePressNode->renderBox()->canBeProgramaticallyScrolled());
return swallowEvent;
}
static bool canAutoscroll(RenderObject* renderer)
{
if (!renderer->isBox())
return false;
if (toRenderBox(renderer)->canBeScrolledAndHasScrollableArea())
return true;
if (renderer->node() != renderer->document())
return false;
Frame* frame = renderer->frame();
if (!frame)
return false;
Page* page = frame->page();
return page && page->mainFrame() == frame;
}
#if ENABLE(DRAG_SUPPORT)
bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& event)
{
if (handleDrag(event))
return true;
if (!m_mousePressed)
return false;
Node* targetNode = EventHandler::targetNode(event);
if (event.event().button() != LeftButton || !targetNode)
return false;
RenderObject* renderer = targetNode->renderer();
if (!renderer) {
renderer = targetNode->parentNode() ? targetNode->parentNode()->renderer() : 0;
if (!renderer || !renderer->isListBox())
return false;
}
#if PLATFORM(MAC) // FIXME: Why does this assertion fire on other platforms?
ASSERT(m_mouseDownMayStartSelect || m_mouseDownMayStartAutoscroll);
#endif
m_mouseDownMayStartDrag = false;
if (m_mouseDownMayStartAutoscroll && !m_panScrollInProgress) {
while (renderer && !canAutoscroll(renderer)) {
if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document()->ownerElement())
renderer = renderer->document()->ownerElement()->renderer();
else
renderer = renderer->parent();
}
if (renderer) {
m_autoscrollInProgress = true;
handleAutoscroll(renderer);
}
m_mouseDownMayStartAutoscroll = false;
}
if (m_selectionInitiationState != ExtendedSelection) {
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
HitTestResult result(m_mouseDownPos);
m_frame->document()->renderView()->hitTest(request, result);
updateSelectionForMouseDrag(result);
}
updateSelectionForMouseDrag(event.hitTestResult());
return true;
}
bool EventHandler::eventMayStartDrag(const PlatformMouseEvent& event) const
{
if (!m_frame->contentRenderer() || !m_frame->contentRenderer()->hasLayer())
return false;
if (event.button() != LeftButton || event.clickCount() != 1)
return false;
FrameView* view = m_frame->view();
if (!view)
return false;
Page* page = m_frame->page();
if (!page)
return false;
updateDragSourceActionsAllowed();
HitTestRequest request(HitTestRequest::ReadOnly);
HitTestResult result(view->windowToContents(event.position()));
m_frame->contentRenderer()->hitTest(request, result);
DragState state;
return result.innerNode() && page->dragController()->draggableNode(m_frame, result.innerNode(), roundedIntPoint(result.point()), state);
}
void EventHandler::updateSelectionForMouseDrag()
{
FrameView* view = m_frame->view();
if (!view)
return;
RenderView* renderer = m_frame->contentRenderer();
if (!renderer)
return;
HitTestRequest request(HitTestRequest::ReadOnly |
HitTestRequest::Active |
HitTestRequest::Move);
HitTestResult result(view->windowToContents(m_currentMousePosition));
renderer->hitTest(request, result);
updateSelectionForMouseDrag(result);
}
static VisiblePosition selectionExtentRespectingEditingBoundary(const VisibleSelection& selection, const LayoutPoint& localPoint, Node* targetNode)
{
LayoutPoint selectionEndPoint = localPoint;
Element* editableElement = selection.rootEditableElement();
if (!targetNode->renderer())
return VisiblePosition();
if (editableElement && !editableElement->contains(targetNode)) {
if (!editableElement->renderer())
return VisiblePosition();
FloatPoint absolutePoint = targetNode->renderer()->localToAbsolute(FloatPoint(selectionEndPoint));
selectionEndPoint = roundedLayoutPoint(editableElement->renderer()->absoluteToLocal(absolutePoint));
targetNode = editableElement;
}
return targetNode->renderer()->positionForPoint(selectionEndPoint);
}
void EventHandler::updateSelectionForMouseDrag(const HitTestResult& hitTestResult)
{
if (!m_mouseDownMayStartSelect)
return;
Node* target = targetNode(hitTestResult);
if (!target)
return;
VisiblePosition targetPosition = selectionExtentRespectingEditingBoundary(m_frame->selection()->selection(), hitTestResult.localPoint(), target);
if (targetPosition.isNull())
return;
VisibleSelection newSelection = m_frame->selection()->selection();
#if ENABLE(SVG)
if (Node* selectionBaseNode = newSelection.base().deprecatedNode())
if (RenderObject* selectionBaseRenderer = selectionBaseNode->renderer())
if (selectionBaseRenderer->isSVGText())
if (target->renderer()->containingBlock() != selectionBaseRenderer->containingBlock())
return;
#endif
if (m_selectionInitiationState == HaveNotStartedSelection && !dispatchSelectStart(target))
return;
if (m_selectionInitiationState != ExtendedSelection) {
m_selectionInitiationState = ExtendedSelection;
newSelection = VisibleSelection(targetPosition);
}
newSelection.setExtent(targetPosition);
if (m_frame->selection()->granularity() != CharacterGranularity)
newSelection.expandUsingGranularity(m_frame->selection()->granularity());
m_frame->selection()->setNonDirectionalSelectionIfNeeded(newSelection, m_frame->selection()->granularity(),
FrameSelection::AdjustEndpointsAtBidiBoundary);
}
#endif // ENABLE(DRAG_SUPPORT)
void EventHandler::lostMouseCapture()
{
m_frame->selection()->setCaretBlinkingSuspended(false);
}
bool EventHandler::handleMouseUp(const MouseEventWithHitTestResults& event)
{
if (eventLoopHandleMouseUp(event))
return true;
return eventActivatedView(event.event());
}
bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& event)
{
if (m_autoscrollInProgress)
stopAutoscrollTimer();
if (handleMouseUp(event))
return true;
m_frame->selection()->setCaretBlinkingSuspended(false);
m_mousePressed = false;
m_capturesDragging = false;
#if ENABLE(DRAG_SUPPORT)
m_mouseDownMayStartDrag = false;
#endif
m_mouseDownMayStartSelect = false;
m_mouseDownMayStartAutoscroll = false;
m_mouseDownWasInSubframe = false;
bool handled = false;
if (m_mouseDownWasSingleClickInSelection && m_selectionInitiationState != ExtendedSelection
#if ENABLE(DRAG_SUPPORT)
&& m_dragStartPos == event.event().position()
#endif
&& m_frame->selection()->isRange()
&& event.event().button() != RightButton) {
VisibleSelection newSelection;
Node* node = targetNode(event);
bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
if (node && (caretBrowsing || node->rendererIsEditable()) && node->renderer()) {
VisiblePosition pos = node->renderer()->positionForPoint(event.localPoint());
newSelection = VisibleSelection(pos);
}
setSelectionIfNeeded(m_frame->selection(), newSelection);
handled = true;
}
m_frame->selection()->notifyRendererOfSelectionChange(UserTriggered);
m_frame->selection()->selectFrameElementInParentIfFullySelected();
return handled;
}
void EventHandler::handleAutoscroll(RenderObject* renderer)
{
if (m_autoscrollTimer.isActive())
return;
setAutoscrollRenderer(renderer);
#if ENABLE(PAN_SCROLLING)
if (m_panScrollInProgress) {
m_panScrollStartPos = currentMousePosition();
if (FrameView* view = m_frame->view())
view->addPanScrollIcon(m_panScrollStartPos);
if (Page* page = m_frame->page()) {
Frame* mainFrame = page->mainFrame();
if (m_frame != mainFrame)
mainFrame->eventHandler()->m_panScrollInProgress = true;
}
}
#endif
startAutoscrollTimer();
}
void EventHandler::autoscrollTimerFired(Timer<EventHandler>*)
{
RenderObject* r = autoscrollRenderer();
if (!r || !r->isBox()) {
stopAutoscrollTimer();
return;
}
if (m_autoscrollInProgress) {
if (!m_mousePressed) {
stopAutoscrollTimer();
return;
}
toRenderBox(r)->autoscroll();
} else {
if (Page* page = m_frame->page()) {
if (!page->mainFrame()->eventHandler()->m_panScrollInProgress) {
stopAutoscrollTimer();
return;
}
}
#if ENABLE(PAN_SCROLLING)
updatePanScrollState();
toRenderBox(r)->panScroll(m_panScrollStartPos);
#endif
}
}
#if ENABLE(PAN_SCROLLING)
void EventHandler::startPanScrolling(RenderObject* renderer)
{
m_panScrollInProgress = true;
m_panScrollButtonPressed = true;
handleAutoscroll(renderer);
invalidateClick();
}
void EventHandler::updatePanScrollState()
{
}
#endif // ENABLE(PAN_SCROLLING)
RenderObject* EventHandler::autoscrollRenderer() const
{
return m_autoscrollRenderer;
}
void EventHandler::updateAutoscrollRenderer()
{
if (!m_autoscrollRenderer)
return;
HitTestResult hitTest = hitTestResultAtPoint(m_panScrollStartPos, true);
if (Node* nodeAtPoint = hitTest.innerNode())
m_autoscrollRenderer = nodeAtPoint->renderer();
while (m_autoscrollRenderer && !canAutoscroll(m_autoscrollRenderer))
m_autoscrollRenderer = m_autoscrollRenderer->parent();
}
void EventHandler::setAutoscrollRenderer(RenderObject* renderer)
{
m_autoscrollRenderer = renderer;
}
#if ENABLE(DRAG_SUPPORT)
DragSourceAction EventHandler::updateDragSourceActionsAllowed() const
{
if (!m_frame)
return DragSourceActionNone;
Page* page = m_frame->page();
if (!page)
return DragSourceActionNone;
FrameView* view = m_frame->view();
if (!view)
return DragSourceActionNone;
return page->dragController()->delegateDragSourceAction(view->contentsToRootView(m_mouseDownPos));
}
#endif // ENABLE(DRAG_SUPPORT)
HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, bool allowShadowContent, bool ignoreClipping, HitTestScrollbars testScrollbars, HitTestRequest::HitTestRequestType hitType, const LayoutSize& padding)
{
enum ShadowContentFilterPolicy shadowContentFilterPolicy = allowShadowContent ? AllowShadowContent : DoNotAllowShadowContent;
HitTestResult result(point, padding.height(), padding.width(), padding.height(), padding.width(), shadowContentFilterPolicy);
if (!m_frame->contentRenderer())
return result;
if (ignoreClipping)
hitType |= HitTestRequest::IgnoreClipping;
m_frame->contentRenderer()->hitTest(HitTestRequest(hitType), result);
while (true) {
Node* n = result.innerNode();
if (!result.isOverWidget() || !n || !n->renderer() || !n->renderer()->isWidget())
break;
RenderWidget* renderWidget = toRenderWidget(n->renderer());
Widget* widget = renderWidget->widget();
if (!widget || !widget->isFrameView())
break;
Frame* frame = static_cast<HTMLFrameElementBase*>(n)->contentFrame();
if (!frame || !frame->contentRenderer())
break;
FrameView* view = static_cast<FrameView*>(widget);
LayoutPoint widgetPoint(result.localPoint().x() + view->scrollX() - renderWidget->borderLeft() - renderWidget->paddingLeft(),
result.localPoint().y() + view->scrollY() - renderWidget->borderTop() - renderWidget->paddingTop());
HitTestResult widgetHitTestResult(widgetPoint, padding.height(), padding.width(), padding.height(), padding.width(), shadowContentFilterPolicy);
frame->contentRenderer()->hitTest(HitTestRequest(hitType), widgetHitTestResult);
result = widgetHitTestResult;
if (testScrollbars == ShouldHitTestScrollbars) {
Scrollbar* eventScrollbar = view->scrollbarAtPoint(roundedIntPoint(point));
if (eventScrollbar)
result.setScrollbar(eventScrollbar);
}
}
Frame* resultFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : 0;
if (Page* page = m_frame->page()) {
Frame* mainFrame = page->mainFrame();
if (m_frame != mainFrame && resultFrame && resultFrame != mainFrame && !resultFrame->editor()->insideVisibleArea(result.point())) {
FrameView* resultView = resultFrame->view();
FrameView* mainView = mainFrame->view();
if (resultView && mainView) {
IntPoint mainFramePoint = mainView->rootViewToContents(resultView->contentsToRootView(roundedIntPoint(result.point())));
result = mainFrame->eventHandler()->hitTestResultAtPoint(mainFramePoint, allowShadowContent, ignoreClipping, testScrollbars, hitType, padding);
}
}
}
if (!allowShadowContent)
result.setToNonShadowAncestor();
return result;
}
void EventHandler::startAutoscrollTimer()
{
m_autoscrollTimer.startRepeating(autoscrollInterval);
}
void EventHandler::stopAutoscrollTimer(bool rendererIsBeingDestroyed)
{
if (m_autoscrollInProgress) {
if (m_mouseDownWasInSubframe) {
if (Frame* subframe = subframeForTargetNode(m_mousePressNode.get()))
subframe->eventHandler()->stopAutoscrollTimer(rendererIsBeingDestroyed);
return;
}
}
if (autoscrollRenderer()) {
if (!rendererIsBeingDestroyed && (m_autoscrollInProgress || m_panScrollInProgress))
toRenderBox(autoscrollRenderer())->stopAutoscroll();
#if ENABLE(PAN_SCROLLING)
if (m_panScrollInProgress) {
if (FrameView* view = m_frame->view()) {
view->removePanScrollIcon();
view->setCursor(pointerCursor());
}
}
#endif
setAutoscrollRenderer(0);
}
m_autoscrollTimer.stop();
m_panScrollInProgress = false;
m_springLoadedPanScrollInProgress = false;
if (Page* page = m_frame->page()) {
Frame* mainFrame = page->mainFrame();
if (m_frame != mainFrame)
mainFrame->eventHandler()->m_panScrollInProgress = false;
}
m_autoscrollInProgress = false;
}
Node* EventHandler::mousePressNode() const
{
return m_mousePressNode.get();
}
void EventHandler::setMousePressNode(PassRefPtr<Node> node)
{
m_mousePressNode = node;
}
bool EventHandler::scrollOverflow(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
{
Node* node = startingNode;
if (!node)
node = m_frame->document()->focusedNode();
if (!node)
node = m_mousePressNode.get();
if (node) {
RenderObject* r = node->renderer();
if (r && !r->isListBox() && r->enclosingBox()->scroll(direction, granularity)) {
setFrameWasScrolledByUser();
return true;
}
}
return false;
}
bool EventHandler::logicalScrollOverflow(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
{
Node* node = startingNode;
if (!node)
node = m_frame->document()->focusedNode();
if (!node)
node = m_mousePressNode.get();
if (node) {
RenderObject* r = node->renderer();
if (r && !r->isListBox() && r->enclosingBox()->logicalScroll(direction, granularity)) {
setFrameWasScrolledByUser();
return true;
}
}
return false;
}
bool EventHandler::scrollRecursively(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
{
m_frame->document()->updateLayoutIgnorePendingStylesheets();
if (scrollOverflow(direction, granularity, startingNode))
return true;
Frame* frame = m_frame;
FrameView* view = frame->view();
if (view && view->scroll(direction, granularity))
return true;
frame = frame->tree()->parent();
if (!frame)
return false;
return frame->eventHandler()->scrollRecursively(direction, granularity, m_frame->ownerElement());
}
bool EventHandler::logicalScrollRecursively(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
{
m_frame->document()->updateLayoutIgnorePendingStylesheets();
if (logicalScrollOverflow(direction, granularity, startingNode))
return true;
Frame* frame = m_frame;
FrameView* view = frame->view();
bool scrolled = false;
#if PLATFORM(MAC)
if (granularity == ScrollByDocument && view && view->logicalScroll(ScrollInlineDirectionBackward, ScrollByDocument))
scrolled = true;
#endif
if (view && view->logicalScroll(direction, granularity))
scrolled = true;
if (scrolled)
return true;
frame = frame->tree()->parent();
if (!frame)
return false;
return frame->eventHandler()->logicalScrollRecursively(direction, granularity, m_frame->ownerElement());
}
IntPoint EventHandler::currentMousePosition() const
{
return m_currentMousePosition;
}
Frame* EventHandler::subframeForHitTestResult(const MouseEventWithHitTestResults& hitTestResult)
{
if (!hitTestResult.isOverWidget())
return 0;
return subframeForTargetNode(targetNode(hitTestResult));
}
Frame* EventHandler::subframeForTargetNode(Node* node)
{
if (!node)
return 0;
RenderObject* renderer = node->renderer();
if (!renderer || !renderer->isWidget())
return 0;
Widget* widget = toRenderWidget(renderer)->widget();
if (!widget || !widget->isFrameView())
return 0;
return static_cast<FrameView*>(widget)->frame();
}
static LayoutPoint documentPointForWindowPoint(Frame* frame, const IntPoint& windowPoint)
{
FrameView* view = frame->view();
return view ? view->windowToContents(windowPoint) : windowPoint;
}
Node* EventHandler::targetNode(const MouseEventWithHitTestResults& event)
{
return targetNode(event.hitTestResult());
}
Node* EventHandler::targetNode(const HitTestResult& hitTestResult)
{
Node* node = hitTestResult.innerNode();
if (!node)
return 0;
if (node->inDocument())
return node;
Element* element = node->parentElement();
if (element && element->inDocument())
return element;
return node;
}
bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
{
RefPtr<FrameView> protector(m_frame->view());
bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(mouseEvent);
if (defaultPrevented)
return true;
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
m_frame->loader()->resetMultipleFormSubmissionProtection();
cancelFakeMouseMoveEvent();
m_mousePressed = true;
m_capturesDragging = true;
m_currentMousePosition = mouseEvent.position();
m_mouseDownTimestamp = mouseEvent.timestamp();
#if ENABLE(DRAG_SUPPORT)
m_mouseDownMayStartDrag = false;
#endif
m_mouseDownMayStartSelect = false;
m_mouseDownMayStartAutoscroll = false;
if (FrameView* view = m_frame->view())
m_mouseDownPos = view->windowToContents(mouseEvent.position());
else {
invalidateClick();
return false;
}
m_mouseDownWasInSubframe = false;
HitTestRequest request(HitTestRequest::Active);
LayoutPoint documentPoint = documentPointForWindowPoint(m_frame, mouseEvent.position());
MouseEventWithHitTestResults mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
if (!targetNode(mev)) {
invalidateClick();
return false;
}
m_mousePressNode = targetNode(mev);
if (InspectorInstrumentation::handleMousePress(m_frame->page())) {
invalidateClick();
return true;
}
Frame* subframe = subframeForHitTestResult(mev);
if (subframe && passMousePressEventToSubframe(mev, subframe)) {
m_capturesDragging = subframe->eventHandler()->capturesDragging();
if (m_mousePressed && m_capturesDragging) {
m_capturingMouseEventsNode = targetNode(mev);
m_eventHandlerWillResetCapturingMouseEventsNode = true;
}
invalidateClick();
return true;
}
#if ENABLE(PAN_SCROLLING)
bool isPanScrollInProgress = m_frame->page() && m_frame->page()->mainFrame()->eventHandler()->m_panScrollInProgress;
if (isPanScrollInProgress || m_autoscrollInProgress)
stopAutoscrollTimer();
if (isPanScrollInProgress) {
invalidateClick();
return true;
}
#endif
m_clickCount = mouseEvent.clickCount();
m_clickNode = targetNode(mev);
if (!m_clickNode) {
invalidateClick();
return false;
}
if (FrameView* view = m_frame->view()) {
RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
IntPoint p = view->windowToContents(mouseEvent.position());
if (layer && layer->isPointInResizeControl(p)) {
layer->setInResizeMode(true);
m_resizeLayer = layer;
m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
invalidateClick();
return true;
}
}
m_frame->selection()->setCaretBlinkingSuspended(true);
bool swallowEvent = dispatchMouseEvent(eventNames().mousedownEvent, targetNode(mev), true, m_clickCount, mouseEvent, true);
m_capturesDragging = !swallowEvent || mev.scrollbar();
if (mev.scrollbar()) {
const bool wasLastScrollBar = mev.scrollbar() == m_lastScrollbarUnderMouse.get();
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
if (wasLastScrollBar && mev.scrollbar() != m_lastScrollbarUnderMouse.get())
m_lastScrollbarUnderMouse = 0;
}
if (swallowEvent) {
Scrollbar* scrollbar = mev.scrollbar();
updateLastScrollbarUnderMouse(scrollbar, true);
if (scrollbar)
passMousePressEventToScrollbar(mev, scrollbar);
} else {
if (targetNode(mev)->isShadowRoot() && targetNode(mev)->shadowHost()->hasTagName(inputTag)) {
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
}
FrameView* view = m_frame->view();
Scrollbar* scrollbar = view ? view->scrollbarAtPoint(mouseEvent.position()) : 0;
if (!scrollbar)
scrollbar = mev.scrollbar();
updateLastScrollbarUnderMouse(scrollbar, true);
if (scrollbar && passMousePressEventToScrollbar(mev, scrollbar))
swallowEvent = true;
else
swallowEvent = handleMousePressEvent(mev);
}
return swallowEvent;
}
bool EventHandler::handleMouseDoubleClickEvent(const PlatformMouseEvent& mouseEvent)
{
RefPtr<FrameView> protector(m_frame->view());
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
m_mousePressed = false;
m_currentMousePosition = mouseEvent.position();
HitTestRequest request(HitTestRequest::Active);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
Frame* subframe = subframeForHitTestResult(mev);
if (m_eventHandlerWillResetCapturingMouseEventsNode)
m_capturingMouseEventsNode = 0;
if (subframe && passMousePressEventToSubframe(mev, subframe))
return true;
m_clickCount = mouseEvent.clickCount();
bool swallowMouseUpEvent = dispatchMouseEvent(eventNames().mouseupEvent, targetNode(mev), true, m_clickCount, mouseEvent, false);
bool swallowClickEvent = mouseEvent.button() != RightButton && targetNode(mev) == m_clickNode && dispatchMouseEvent(eventNames().clickEvent, targetNode(mev), true, m_clickCount, mouseEvent, true);
if (m_lastScrollbarUnderMouse)
swallowMouseUpEvent = m_lastScrollbarUnderMouse->mouseUp(mouseEvent);
bool swallowMouseReleaseEvent = !swallowMouseUpEvent && handleMouseReleaseEvent(mev);
invalidateClick();
return swallowMouseUpEvent || swallowClickEvent || swallowMouseReleaseEvent;
}
static RenderLayer* layerForNode(Node* node)
{
if (!node)
return 0;
RenderObject* renderer = node->renderer();
if (!renderer)
return 0;
RenderLayer* layer = renderer->enclosingLayer();
if (!layer)
return 0;
return layer;
}
bool EventHandler::mouseMoved(const PlatformMouseEvent& event)
{
MaximumDurationTracker maxDurationTracker(&m_maxMouseMovedDuration);
RefPtr<FrameView> protector(m_frame->view());
bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(event);
if (defaultPrevented)
return true;
HitTestResult hoveredNode = HitTestResult(LayoutPoint());
bool result = handleMouseMoveEvent(event, &hoveredNode);
Page* page = m_frame->page();
if (!page)
return result;
if (RenderLayer* layer = layerForNode(hoveredNode.innerNode())) {
if (FrameView* frameView = m_frame->view()) {
if (frameView->containsScrollableArea(layer))
layer->mouseMovedInContentArea();
}
}
if (FrameView* frameView = m_frame->view())
frameView->mouseMovedInContentArea();
hoveredNode.setToNonShadowAncestor();
page->chrome()->mouseDidMoveOverElement(hoveredNode, event.modifierFlags());
page->chrome()->setToolTip(hoveredNode);
return result;
}
bool EventHandler::passMouseMovedEventToScrollbars(const PlatformMouseEvent& event)
{
HitTestResult hoveredNode;
return handleMouseMoveEvent(event, &hoveredNode, true);
}
bool EventHandler::handleMouseMoveEvent(const PlatformMouseEvent& mouseEvent, HitTestResult* hoveredNode, bool onlyUpdateScrollbars)
{
ASSERT(m_frame);
if (!m_frame)
return false;
RefPtr<FrameView> protector(m_frame->view());
m_currentMousePosition = mouseEvent.position();
if (m_hoverTimer.isActive())
m_hoverTimer.stop();
cancelFakeMouseMoveEvent();
#if ENABLE(SVG)
if (m_svgPan) {
static_cast<SVGDocument*>(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_currentMousePosition));
return true;
}
#endif
if (m_frameSetBeingResized)
return dispatchMouseEvent(eventNames().mousemoveEvent, m_frameSetBeingResized.get(), false, 0, mouseEvent, false);
HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move;
if (m_mousePressed)
hitType |= HitTestRequest::Active;
else if (onlyUpdateScrollbars) {
hitType |= HitTestRequest::ReadOnly;
}
HitTestRequest request(hitType);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
if (hoveredNode)
*hoveredNode = mev.hitTestResult();
Scrollbar* scrollbar = 0;
if (m_resizeLayer && m_resizeLayer->inResizeMode())
m_resizeLayer->resize(mouseEvent, m_offsetFromResizeCorner);
else {
if (FrameView* view = m_frame->view())
scrollbar = view->scrollbarAtPoint(mouseEvent.position());
if (!scrollbar)
scrollbar = mev.scrollbar();
updateLastScrollbarUnderMouse(scrollbar, !m_mousePressed);
if (onlyUpdateScrollbars)
return true;
}
bool swallowEvent = false;
RefPtr<Frame> newSubframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree()->isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
passMouseMoveEventToSubframe(mev, m_lastMouseMoveEventSubframe.get());
if (newSubframe) {
updateMouseEventTargetNode(targetNode(mev), mouseEvent, true);
if (newSubframe->view())
swallowEvent |= passMouseMoveEventToSubframe(mev, newSubframe.get(), hoveredNode);
}
m_lastMouseMoveEventSubframe = newSubframe;
if (swallowEvent)
return true;
swallowEvent = dispatchMouseEvent(eventNames().mousemoveEvent, targetNode(mev), false, 0, mouseEvent, true);
#if ENABLE(DRAG_SUPPORT)
if (!swallowEvent)
swallowEvent = handleMouseDraggedEvent(mev);
#endif // ENABLE(DRAG_SUPPORT)
return swallowEvent;
}
void EventHandler::invalidateClick()
{
m_clickCount = 0;
m_clickNode = 0;
}
bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
{
RefPtr<FrameView> protector(m_frame->view());
bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(mouseEvent);
if (defaultPrevented)
return true;
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
#if ENABLE(PAN_SCROLLING)
if (mouseEvent.button() == MiddleButton)
m_panScrollButtonPressed = false;
if (m_springLoadedPanScrollInProgress)
stopAutoscrollTimer();
#endif
m_mousePressed = false;
m_currentMousePosition = mouseEvent.position();
#if ENABLE(SVG)
if (m_svgPan) {
m_svgPan = false;
static_cast<SVGDocument*>(m_frame->document())->updatePan(m_frame->view()->windowToContents(m_currentMousePosition));
return true;
}
#endif
if (m_frameSetBeingResized)
return dispatchMouseEvent(eventNames().mouseupEvent, m_frameSetBeingResized.get(), true, m_clickCount, mouseEvent, false);
if (m_lastScrollbarUnderMouse) {
invalidateClick();
return m_lastScrollbarUnderMouse->mouseUp(mouseEvent);
}
HitTestRequest request(HitTestRequest::Release);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
Frame* subframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
if (m_eventHandlerWillResetCapturingMouseEventsNode)
m_capturingMouseEventsNode = 0;
if (subframe && passMouseReleaseEventToSubframe(mev, subframe))
return true;
m_capturingMouseEventsNode = 0;
bool swallowMouseUpEvent = dispatchMouseEvent(eventNames().mouseupEvent, targetNode(mev), true, m_clickCount, mouseEvent, false);
bool swallowClickEvent = m_clickCount > 0 && mouseEvent.button() != RightButton && targetNode(mev) == m_clickNode && dispatchMouseEvent(eventNames().clickEvent, targetNode(mev), true, m_clickCount, mouseEvent, true);
if (m_resizeLayer) {
m_resizeLayer->setInResizeMode(false);
m_resizeLayer = 0;
}
bool swallowMouseReleaseEvent = false;
if (!swallowMouseUpEvent)
swallowMouseReleaseEvent = handleMouseReleaseEvent(mev);
invalidateClick();
return swallowMouseUpEvent || swallowClickEvent || swallowMouseReleaseEvent;
}
#if ENABLE(DRAG_SUPPORT)
bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Node* dragTarget, const PlatformMouseEvent& event, Clipboard* clipboard)
{
FrameView* view = m_frame->view();
if (!view)
return false;
view->resetDeferredRepaintDelay();
RefPtr<MouseEvent> me = MouseEvent::create(eventType,
true, true, m_frame->document()->defaultView(),
0, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
#if ENABLE(POINTER_LOCK)
event.movementDelta().x(), event.movementDelta().y(),
#endif
event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(),
0, 0, clipboard);
ExceptionCode ec;
dragTarget->dispatchEvent(me.get(), ec);
return me->defaultPrevented();
}
static bool targetIsFrame(Node* target, Frame*& frame)
{
if (!target)
return false;
if (!target->hasTagName(frameTag) && !target->hasTagName(iframeTag))
return false;
frame = static_cast<HTMLFrameElementBase*>(target)->contentFrame();
return true;
}
static bool findDropZone(Node* target, Clipboard* clipboard)
{
Element* element = target->isElementNode() ? toElement(target) : target->parentElement();
for (; element; element = element->parentElement()) {
bool matched = false;
String dropZoneStr = element->fastGetAttribute(webkitdropzoneAttr);
if (dropZoneStr.isEmpty())
continue;
dropZoneStr.makeLower();
SpaceSplitString keywords(dropZoneStr, false);
if (keywords.isNull())
continue;
DragOperation dragOperation = DragOperationNone;
for (unsigned int i = 0; i < keywords.size(); i++) {
DragOperation op = convertDropZoneOperationToDragOperation(keywords[i]);
if (op != DragOperationNone) {
if (dragOperation == DragOperationNone)
dragOperation = op;
} else
matched = matched || clipboard->hasDropZoneType(keywords[i].string());
if (matched && dragOperation != DragOperationNone)
break;
}
if (matched) {
clipboard->setDropEffect(convertDragOperationToDropZoneOperation(dragOperation));
return true;
}
}
return false;
}
bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
{
bool accept = false;
if (!m_frame->view())
return false;
HitTestRequest request(HitTestRequest::ReadOnly);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
RefPtr<Node> newTarget = targetNode(mev);
if (newTarget && newTarget->isTextNode())
newTarget = newTarget->parentNode();
if (newTarget)
newTarget = newTarget->shadowAncestorNode();
if (m_dragTarget != newTarget) {
Frame* targetFrame;
if (targetIsFrame(newTarget.get(), targetFrame)) {
if (targetFrame)
accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
} else if (newTarget) {
if (dragState().m_dragSrc && dragState().shouldDispatchEvents()) {
dispatchDragSrcEvent(eventNames().dragEvent, event);
}
accept = dispatchDragEvent(eventNames().dragenterEvent, newTarget.get(), event, clipboard);
if (!accept)
accept = findDropZone(newTarget.get(), clipboard);
}
if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
if (targetFrame)
accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
} else if (m_dragTarget)
dispatchDragEvent(eventNames().dragleaveEvent, m_dragTarget.get(), event, clipboard);
if (newTarget) {
m_shouldOnlyFireDragOverEvent = true;
}
} else {
Frame* targetFrame;
if (targetIsFrame(newTarget.get(), targetFrame)) {
if (targetFrame)
accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
} else if (newTarget) {
if (!m_shouldOnlyFireDragOverEvent && dragState().m_dragSrc && dragState().shouldDispatchEvents()) {
dispatchDragSrcEvent(eventNames().dragEvent, event);
}
accept = dispatchDragEvent(eventNames().dragoverEvent, newTarget.get(), event, clipboard);
if (!accept)
accept = findDropZone(newTarget.get(), clipboard);
m_shouldOnlyFireDragOverEvent = false;
}
}
m_dragTarget = newTarget;
return accept;
}
void EventHandler::cancelDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
{
Frame* targetFrame;
if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
if (targetFrame)
targetFrame->eventHandler()->cancelDragAndDrop(event, clipboard);
} else if (m_dragTarget.get()) {
if (dragState().m_dragSrc && dragState().shouldDispatchEvents())
dispatchDragSrcEvent(eventNames().dragEvent, event);
dispatchDragEvent(eventNames().dragleaveEvent, m_dragTarget.get(), event, clipboard);
}
clearDragState();
}
bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, Clipboard* clipboard)
{
Frame* targetFrame;
bool preventedDefault = false;
if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
if (targetFrame)
preventedDefault = targetFrame->eventHandler()->performDragAndDrop(event, clipboard);
} else if (m_dragTarget.get())
preventedDefault = dispatchDragEvent(eventNames().dropEvent, m_dragTarget.get(), event, clipboard);
clearDragState();
return preventedDefault;
}
void EventHandler::clearDragState()
{
m_dragTarget = 0;
m_capturingMouseEventsNode = 0;
m_shouldOnlyFireDragOverEvent = false;
#if PLATFORM(MAC)
m_sendingEventToSubview = false;
#endif
}
#endif // ENABLE(DRAG_SUPPORT)
void EventHandler::setCapturingMouseEventsNode(PassRefPtr<Node> n)
{
m_capturingMouseEventsNode = n;
m_eventHandlerWillResetCapturingMouseEventsNode = false;
}
MouseEventWithHitTestResults EventHandler::prepareMouseEvent(const HitTestRequest& request, const PlatformMouseEvent& mev)
{
ASSERT(m_frame);
ASSERT(m_frame->document());
return m_frame->document()->prepareMouseEvent(request, documentPointForWindowPoint(m_frame, mev.position()), mev);
}
#if ENABLE(SVG)
static inline SVGElementInstance* instanceAssociatedWithShadowTreeElement(Node* referenceNode)
{
if (!referenceNode || !referenceNode->isSVGElement())
return 0;
Node* shadowTreeElement = referenceNode->shadowTreeRootNode();
if (!shadowTreeElement)
return 0;
Element* shadowTreeParentElement = shadowTreeElement->shadowHost();
if (!shadowTreeParentElement)
return 0;
ASSERT(shadowTreeParentElement->hasTagName(useTag));
return static_cast<SVGUseElement*>(shadowTreeParentElement)->instanceForShadowTreeElement(referenceNode);
}
#endif
void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMouseEvent& mouseEvent, bool fireMouseOverOut)
{
Node* result = targetNode;
if (m_capturingMouseEventsNode)
result = m_capturingMouseEventsNode.get();
else {
if (result && result->isTextNode())
result = result->parentNode();
}
m_nodeUnderMouse = result;
#if ENABLE(SVG)
m_instanceUnderMouse = instanceAssociatedWithShadowTreeElement(result);
if (m_lastInstanceUnderMouse) {
SVGElement* lastCorrespondingElement = m_lastInstanceUnderMouse->correspondingElement();
SVGElement* lastCorrespondingUseElement = m_lastInstanceUnderMouse->correspondingUseElement();
if (lastCorrespondingElement && lastCorrespondingUseElement) {
HashSet<SVGElementInstance*> instances = lastCorrespondingElement->instancesForElement();
HashSet<SVGElementInstance*>::iterator end = instances.end();
for (HashSet<SVGElementInstance*>::iterator it = instances.begin(); it != end; ++it) {
SVGElementInstance* instance = (*it);
ASSERT(instance->correspondingElement() == lastCorrespondingElement);
if (instance == m_lastInstanceUnderMouse)
continue;
if (instance->correspondingUseElement() != lastCorrespondingUseElement)
continue;
SVGElement* shadowTreeElement = instance->shadowTreeElement();
if (!shadowTreeElement->inDocument() || m_lastNodeUnderMouse == shadowTreeElement)
continue;
m_lastNodeUnderMouse = shadowTreeElement;
m_lastInstanceUnderMouse = instance;
break;
}
}
}
#endif
if (fireMouseOverOut) {
RenderLayer* layerForLastNode = layerForNode(m_lastNodeUnderMouse.get());
RenderLayer* layerForNodeUnderMouse = layerForNode(m_nodeUnderMouse.get());
Page* page = m_frame->page();
if (m_lastNodeUnderMouse && (!m_nodeUnderMouse || m_nodeUnderMouse->document() != m_frame->document())) {
if (Frame* frame = m_lastNodeUnderMouse->document()->frame()) {
if (FrameView* frameView = frame->view())
frameView->mouseExitedContentArea();
}
} else if (page && (layerForLastNode && (!layerForNodeUnderMouse || layerForNodeUnderMouse != layerForLastNode))) {
if (Frame* frame = m_lastNodeUnderMouse->document()->frame()) {
if (FrameView* frameView = frame->view()) {
if (frameView->containsScrollableArea(layerForLastNode))
layerForLastNode->mouseExitedContentArea();
}
}
}
if (m_nodeUnderMouse && (!m_lastNodeUnderMouse || m_lastNodeUnderMouse->document() != m_frame->document())) {
if (Frame* frame = m_nodeUnderMouse->document()->frame()) {
if (FrameView* frameView = frame->view())
frameView->mouseEnteredContentArea();
}
} else if (page && (layerForNodeUnderMouse && (!layerForLastNode || layerForNodeUnderMouse != layerForLastNode))) {
if (Frame* frame = m_nodeUnderMouse->document()->frame()) {
if (FrameView* frameView = frame->view()) {
if (frameView->containsScrollableArea(layerForNodeUnderMouse))
layerForNodeUnderMouse->mouseEnteredContentArea();
}
}
}
if (m_lastNodeUnderMouse && m_lastNodeUnderMouse->document() != m_frame->document()) {
m_lastNodeUnderMouse = 0;
m_lastScrollbarUnderMouse = 0;
#if ENABLE(SVG)
m_lastInstanceUnderMouse = 0;
#endif
}
if (m_lastNodeUnderMouse != m_nodeUnderMouse) {
if (m_lastNodeUnderMouse)
m_lastNodeUnderMouse->dispatchMouseEvent(mouseEvent, eventNames().mouseoutEvent, 0, m_nodeUnderMouse.get());
if (m_nodeUnderMouse)
m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventNames().mouseoverEvent, 0, m_lastNodeUnderMouse.get());
}
m_lastNodeUnderMouse = m_nodeUnderMouse;
#if ENABLE(SVG)
m_lastInstanceUnderMouse = instanceAssociatedWithShadowTreeElement(m_nodeUnderMouse.get());
#endif
}
}
bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targetNode, bool , int clickCount, const PlatformMouseEvent& mouseEvent, bool setUnder)
{
if (FrameView* view = m_frame->view())
view->resetDeferredRepaintDelay();
updateMouseEventTargetNode(targetNode, mouseEvent, setUnder);
bool swallowEvent = false;
if (m_nodeUnderMouse)
swallowEvent = m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventType, clickCount);
if (!swallowEvent && eventType == eventNames().mousedownEvent) {
if (FrameView* view = m_frame->view()) {
if (view->scrollbarAtPoint(mouseEvent.position()))
return false;
}
m_frame->document()->updateLayoutIgnorePendingStylesheets();
Node* node = m_nodeUnderMouse.get();
while (node) {
if (node->isMouseFocusable()) {
ExceptionCode ec = 0;
Node* n = node->isShadowRoot() ? node->shadowHost() : node;
if (m_frame->selection()->isRange()
&& m_frame->selection()->toNormalizedRange()->compareNode(n, ec) == Range::NODE_INSIDE
&& n->isDescendantOf(m_frame->document()->focusedNode()))
return false;
break;
}
node = node->parentOrHostNode();
}
if (Page* page = m_frame->page()) {
if (node && node->isMouseFocusable()) {
if (!page->focusController()->setFocusedNode(node, m_frame))
swallowEvent = true;
} else if (!node || !node->focused()) {
if (!page->focusController()->setFocusedNode(0, m_frame))
swallowEvent = true;
}
}
}
return swallowEvent;
}
#if !PLATFORM(GTK) && !(PLATFORM(CHROMIUM) && (OS(UNIX) && !OS(DARWIN)))
bool EventHandler::shouldTurnVerticalTicksIntoHorizontal(const HitTestResult&) const
{
return false;
}
#endif
bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
{
Document* doc = m_frame->document();
RenderObject* docRenderer = doc->renderer();
if (!docRenderer)
return false;
RefPtr<FrameView> protector(m_frame->view());
FrameView* view = m_frame->view();
if (!view)
return false;
setFrameWasScrolledByUser();
LayoutPoint vPoint = view->windowToContents(e.position());
Node* node;
bool isOverWidget;
HitTestRequest request(HitTestRequest::ReadOnly);
HitTestResult result(vPoint);
doc->renderView()->hitTest(request, result);
#if PLATFORM(MAC)
m_useLatchedWheelEventNode = e.momentumPhase() == PlatformWheelEventPhaseBegan || e.momentumPhase() == PlatformWheelEventPhaseChanged;
#endif
if (m_useLatchedWheelEventNode) {
if (!m_latchedWheelEventNode) {
m_latchedWheelEventNode = result.innerNode();
m_widgetIsLatched = result.isOverWidget();
}
node = m_latchedWheelEventNode.get();
isOverWidget = m_widgetIsLatched;
} else {
if (m_latchedWheelEventNode)
m_latchedWheelEventNode = 0;
if (m_previousWheelScrolledNode)
m_previousWheelScrolledNode = 0;
node = result.innerNode();
isOverWidget = result.isOverWidget();
}
PlatformWheelEvent event = e;
if (m_baseEventType == PlatformEvent::NoType && shouldTurnVerticalTicksIntoHorizontal(result))
event = event.copyTurningVerticalTicksIntoHorizontalTicks();
if (node) {
RenderObject* target = node->renderer();
if (isOverWidget && target && target->isWidget()) {
Widget* widget = toRenderWidget(target)->widget();
if (widget && passWheelEventToWidget(e, widget))
return true;
}
node = node->shadowAncestorNode();
if (node && !node->dispatchWheelEvent(event))
return true;
}
view = m_frame->view();
if (!view)
return false;
return view->wheelEvent(event);
}
void EventHandler::defaultWheelEventHandler(Node* startNode, WheelEvent* wheelEvent)
{
if (!startNode || !wheelEvent)
return;
Node* stopNode = m_previousWheelScrolledNode.get();
ScrollGranularity granularity = m_baseEventType == PlatformEvent::GestureScrollEnd ? ScrollByPixelVelocity : wheelGranularityToScrollGranularity(wheelEvent->granularity());
if (scrollNode(wheelEvent->rawDeltaX(), granularity, ScrollLeft, ScrollRight, startNode, &stopNode))
wheelEvent->setDefaultHandled();
if (scrollNode(wheelEvent->rawDeltaY(), granularity, ScrollUp, ScrollDown, startNode, &stopNode))
wheelEvent->setDefaultHandled();
if (!m_useLatchedWheelEventNode)
m_previousWheelScrolledNode = stopNode;
}
#if ENABLE(GESTURE_EVENTS)
bool EventHandler::handleGestureTapDown()
{
FrameView* view = m_frame->view();
if (!view)
return false;
if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
scrollAnimator->cancelAnimations();
const FrameView::ScrollableAreaSet* areas = view->scrollableAreas();
if (!areas)
return false;
for (FrameView::ScrollableAreaSet::const_iterator it = areas->begin(); it != areas->end(); ++it) {
ScrollableArea* sa = *it;
ScrollAnimator* animator = sa->scrollAnimator();
if (animator)
animator->cancelAnimations();
}
return false;
}
bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
{
TemporaryChange<PlatformEvent::Type> baseEventType(m_baseEventType, gestureEvent.type());
switch (gestureEvent.type()) {
case PlatformEvent::GestureScrollBegin:
return handleGestureScrollCore(gestureEvent, ScrollByPixelWheelEvent, false);
case PlatformEvent::GestureScrollEnd:
return handleGestureScrollCore(gestureEvent, ScrollByPixelVelocityWheelEvent, true);
case PlatformEvent::GestureScrollUpdate:
return handleGestureScrollUpdate(gestureEvent);
case PlatformEvent::GestureTap:
return handleGestureTap(gestureEvent);
case PlatformEvent::GestureTapDown:
return handleGestureTapDown();
case PlatformEvent::GestureDoubleTap:
case PlatformEvent::GestureLongPress:
case PlatformEvent::GesturePinchBegin:
case PlatformEvent::GesturePinchEnd:
case PlatformEvent::GesturePinchUpdate:
break;
default:
ASSERT_NOT_REACHED();
}
return false;
}
bool EventHandler::handleGestureTap(const PlatformGestureEvent& gestureEvent, Node* preTargetedNode)
{
IntPoint adjustedPoint = gestureEvent.position();
#if ENABLE(TOUCH_ADJUSTMENT)
if (!gestureEvent.area().isEmpty() && !preTargetedNode) {
Node* targetNode = 0;
bestClickableNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode);
if (!targetNode)
return false;
}
#endif
if (preTargetedNode)
adjustedPoint = preTargetedNode->getPixelSnappedRect().center();
bool defaultPrevented = false;
PlatformMouseEvent fakeMouseMove(adjustedPoint, gestureEvent.globalPosition(), NoButton, PlatformEvent::MouseMoved, 1, gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
PlatformMouseEvent fakeMouseDown(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1, gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
PlatformMouseEvent fakeMouseUp(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MouseReleased, 1, gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
mouseMoved(fakeMouseMove);
defaultPrevented |= handleMousePressEvent(fakeMouseDown);
defaultPrevented |= handleMouseReleaseEvent(fakeMouseUp);
return defaultPrevented;
}
bool EventHandler::handleGestureScrollUpdate(const PlatformGestureEvent& gestureEvent)
{
return handleGestureScrollCore(gestureEvent, ScrollByPixelWheelEvent, true);
}
bool EventHandler::handleGestureScrollCore(const PlatformGestureEvent& gestureEvent, PlatformWheelEventGranularity granularity, bool latchedWheel)
{
TemporaryChange<bool> latched(m_useLatchedWheelEventNode, latchedWheel);
const float tickDivisor = (float)WheelEvent::tickMultiplier;
IntPoint point(gestureEvent.position().x(), gestureEvent.position().y());
IntPoint globalPoint(gestureEvent.globalPosition().x(), gestureEvent.globalPosition().y());
PlatformWheelEvent syntheticWheelEvent(point, globalPoint,
gestureEvent.deltaX(), gestureEvent.deltaY(), gestureEvent.deltaX() / tickDivisor, gestureEvent.deltaY() / tickDivisor,
granularity,
gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey());
return handleWheelEvent(syntheticWheelEvent);
}
#endif
#if ENABLE(TOUCH_ADJUSTMENT)
bool EventHandler::bestClickableNodeForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntPoint& targetPoint, Node*& targetNode)
{
HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
HitTestResult result = hitTestResultAtPoint(touchCenter, false, false, DontHitTestScrollbars, hitType, touchRadius);
IntRect touchRect = result.rectForPoint(touchCenter);
RefPtr<StaticHashSetNodeList> nodeList = StaticHashSetNodeList::adopt(result.rectBasedTestResult());
return findBestClickableCandidate(targetNode, targetPoint, touchCenter, touchRect, *nodeList.get());
}
bool EventHandler::bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode)
{
HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
HitTestResult result = hitTestResultAtPoint(touchCenter, false, false, DontHitTestScrollbars, hitType, touchRadius);
IntRect touchRect = result.rectForPoint(touchCenter);
RefPtr<StaticHashSetNodeList> nodeList = StaticHashSetNodeList::adopt(result.rectBasedTestResult());
return findBestZoomableArea(targetNode, targetArea, touchCenter, touchRect, *nodeList.get());
}
#endif
#if ENABLE(CONTEXT_MENUS)
bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
{
Document* doc = m_frame->document();
FrameView* v = m_frame->view();
if (!v)
return false;
bool swallowEvent;
LayoutPoint viewportPos = v->windowToContents(event.position());
HitTestRequest request(HitTestRequest::Active);
MouseEventWithHitTestResults mev = doc->prepareMouseEvent(request, viewportPos, event);
if (m_frame->editor()->behavior().shouldSelectOnContextualMenuClick()
&& !m_frame->selection()->contains(viewportPos)
&& (m_frame->selection()->isContentEditable() || (targetNode(mev) && targetNode(mev)->isTextNode()))) {
m_mouseDownMayStartSelect = true; selectClosestWordOrLinkFromMouseEvent(mev);
}
swallowEvent = dispatchMouseEvent(eventNames().contextmenuEvent, targetNode(mev), true, 0, event, false);
return swallowEvent;
}
bool EventHandler::sendContextMenuEventForKey()
{
FrameView* view = m_frame->view();
if (!view)
return false;
Document* doc = m_frame->document();
if (!doc)
return false;
static const int kContextMenuMargin = 1;
#if OS(WINDOWS) && !OS(WINCE)
int rightAligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
#else
int rightAligned = 0;
#endif
IntPoint location;
Node* focusedNode = doc->focusedNode();
FrameSelection* selection = m_frame->selection();
Position start = selection->selection().start();
if (start.deprecatedNode() && (selection->rootEditableElement() || selection->isRange())) {
RefPtr<Range> selectionRange = selection->toNormalizedRange();
IntRect firstRect = m_frame->editor()->firstRectForRange(selectionRange.get());
int x = rightAligned ? firstRect.maxX() : firstRect.x();
int y = firstRect.maxY() ? firstRect.maxY() - 1 : 0;
location = IntPoint(x, y);
} else if (focusedNode) {
RenderBoxModelObject* box = focusedNode->renderBoxModelObject();
if (!box)
return false;
IntRect clippedRect = box->pixelSnappedAbsoluteClippedOverflowRect();
location = IntPoint(clippedRect.x(), clippedRect.maxY() - 1);
} else {
location = IntPoint(
rightAligned ? view->contentsWidth() - kContextMenuMargin : kContextMenuMargin,
kContextMenuMargin);
}
m_frame->view()->setCursor(pointerCursor());
IntPoint position = view->contentsToRootView(location);
IntPoint globalPosition = view->hostWindow()->rootViewToScreen(IntRect(position, IntSize())).location();
Node* targetNode = doc->focusedNode();
if (!targetNode)
targetNode = doc;
HitTestResult result(position);
result.setInnerNode(targetNode);
HitTestRequest request(HitTestRequest::Active);
doc->renderView()->layer()->updateHoverActiveState(request, result);
doc->updateStyleIfNeeded();
#if OS(WINDOWS)
PlatformEvent::Type eventType = PlatformEvent::MouseReleased;
#else
PlatformEvent::Type eventType = PlatformEvent::MousePressed;
#endif
PlatformMouseEvent mouseEvent(position, globalPosition, RightButton, eventType, 1, false, false, false, false, WTF::currentTime());
return dispatchMouseEvent(eventNames().contextmenuEvent, targetNode, true, 0, mouseEvent, false);
}
#endif // ENABLE(CONTEXT_MENUS)
void EventHandler::scheduleHoverStateUpdate()
{
if (!m_hoverTimer.isActive())
m_hoverTimer.startOneShot(0);
}
void EventHandler::dispatchFakeMouseMoveEventSoon()
{
if (m_mousePressed)
return;
if (m_maxMouseMovedDuration > fakeMouseMoveShortInterval) {
if (m_fakeMouseMoveEventTimer.isActive())
m_fakeMouseMoveEventTimer.stop();
m_fakeMouseMoveEventTimer.startOneShot(fakeMouseMoveLongInterval);
} else {
if (!m_fakeMouseMoveEventTimer.isActive())
m_fakeMouseMoveEventTimer.startOneShot(fakeMouseMoveShortInterval);
}
}
void EventHandler::dispatchFakeMouseMoveEventSoonInQuad(const FloatQuad& quad)
{
FrameView* view = m_frame->view();
if (!view)
return;
if (!quad.containsPoint(view->windowToContents(m_currentMousePosition)))
return;
dispatchFakeMouseMoveEventSoon();
}
void EventHandler::cancelFakeMouseMoveEvent()
{
m_fakeMouseMoveEventTimer.stop();
}
void EventHandler::fakeMouseMoveEventTimerFired(Timer<EventHandler>* timer)
{
ASSERT_UNUSED(timer, timer == &m_fakeMouseMoveEventTimer);
ASSERT(!m_mousePressed);
FrameView* view = m_frame->view();
if (!view)
return;
bool shiftKey;
bool ctrlKey;
bool altKey;
bool metaKey;
PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
IntPoint globalPoint = view->contentsToScreen(IntRect(view->windowToContents(m_currentMousePosition), IntSize())).location();
PlatformMouseEvent fakeMouseMoveEvent(m_currentMousePosition, globalPoint, NoButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey, metaKey, currentTime());
mouseMoved(fakeMouseMoveEvent);
}
void EventHandler::setResizingFrameSet(HTMLFrameSetElement* frameSet)
{
m_frameSetBeingResized = frameSet;
}
void EventHandler::resizeLayerDestroyed()
{
ASSERT(m_resizeLayer);
m_resizeLayer = 0;
}
void EventHandler::hoverTimerFired(Timer<EventHandler>*)
{
m_hoverTimer.stop();
ASSERT(m_frame);
ASSERT(m_frame->document());
if (RenderView* renderer = m_frame->contentRenderer()) {
if (FrameView* view = m_frame->view()) {
HitTestRequest request(HitTestRequest::Move);
HitTestResult result(view->windowToContents(m_currentMousePosition));
renderer->hitTest(request, result);
m_frame->document()->updateStyleIfNeeded();
}
}
}
bool EventHandler::handleAccessKey(const PlatformKeyboardEvent& evt)
{
ASSERT(!(accessKeyModifiers() & PlatformEvent::ShiftKey));
if ((evt.modifiers() & ~PlatformEvent::ShiftKey) != accessKeyModifiers())
return false;
String key = evt.unmodifiedText();
Element* elem = m_frame->document()->getElementByAccessKey(key.lower());
if (!elem)
return false;
elem->accessKeyAction(false);
return true;
}
bool EventHandler::needsKeyboardEventDisambiguationQuirks() const
{
return false;
}
#if ENABLE(FULLSCREEN_API)
bool EventHandler::isKeyEventAllowedInFullScreen(const PlatformKeyboardEvent& keyEvent) const
{
Document* document = m_frame->document();
if (document->webkitFullScreenKeyboardInputAllowed())
return true;
if (keyEvent.type() == PlatformKeyboardEvent::Char) {
if (keyEvent.text().length() != 1)
return false;
UChar character = keyEvent.text()[0];
return character == ' ';
}
int keyCode = keyEvent.windowsVirtualKeyCode();
return (keyCode >= VK_BACK && keyCode <= VK_CAPITAL)
|| (keyCode >= VK_SPACE && keyCode <= VK_DELETE)
|| (keyCode >= VK_OEM_1 && keyCode <= VK_OEM_PLUS)
|| (keyCode >= VK_MULTIPLY && keyCode <= VK_OEM_8);
}
#endif
bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
{
RefPtr<FrameView> protector(m_frame->view());
#if ENABLE(FULLSCREEN_API)
if (m_frame->document()->webkitIsFullScreen() && !isKeyEventAllowedInFullScreen(initialKeyEvent))
return false;
#endif
if (initialKeyEvent.windowsVirtualKeyCode() == VK_CAPITAL)
capsLockStateMayHaveChanged();
#if ENABLE(PAN_SCROLLING)
if (Page* page = m_frame->page()) {
if (page->mainFrame()->eventHandler()->m_panScrollInProgress) {
if (initialKeyEvent.type() == PlatformEvent::KeyDown || initialKeyEvent.type() == PlatformEvent::RawKeyDown)
stopAutoscrollTimer();
return true;
}
}
#endif
RefPtr<Node> node = eventTargetNodeForDocument(m_frame->document());
if (!node)
return false;
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
UserTypingGestureIndicator typingGestureIndicator(m_frame);
if (FrameView* view = m_frame->view())
view->resetDeferredRepaintDelay();
m_frame->loader()->resetMultipleFormSubmissionProtection();
bool matchedAnAccessKey = false;
if (initialKeyEvent.type() == PlatformEvent::KeyDown)
matchedAnAccessKey = handleAccessKey(initialKeyEvent);
if (initialKeyEvent.type() == PlatformEvent::KeyUp || initialKeyEvent.type() == PlatformEvent::Char)
return !node->dispatchKeyEvent(initialKeyEvent);
bool backwardCompatibilityMode = needsKeyboardEventDisambiguationQuirks();
ExceptionCode ec;
PlatformKeyboardEvent keyDownEvent = initialKeyEvent;
if (keyDownEvent.type() != PlatformEvent::RawKeyDown)
keyDownEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown, backwardCompatibilityMode);
RefPtr<KeyboardEvent> keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->defaultView());
if (matchedAnAccessKey)
keydown->setDefaultPrevented(true);
keydown->setTarget(node);
if (initialKeyEvent.type() == PlatformEvent::RawKeyDown) {
node->dispatchEvent(keydown, ec);
bool changedFocusedFrame = m_frame->page() && m_frame != m_frame->page()->focusController()->focusedOrMainFrame();
return keydown->defaultHandled() || keydown->defaultPrevented() || changedFocusedFrame;
}
m_frame->editor()->handleInputMethodKeydown(keydown.get());
bool handledByInputMethod = keydown->defaultHandled();
if (handledByInputMethod) {
keyDownEvent.setWindowsVirtualKeyCode(CompositionEventKeyCode);
keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->defaultView());
keydown->setTarget(node);
keydown->setDefaultHandled();
}
node->dispatchEvent(keydown, ec);
bool changedFocusedFrame = m_frame->page() && m_frame != m_frame->page()->focusController()->focusedOrMainFrame();
bool keydownResult = keydown->defaultHandled() || keydown->defaultPrevented() || changedFocusedFrame;
if (handledByInputMethod || (keydownResult && !backwardCompatibilityMode))
return keydownResult;
if (!keydownResult) {
node = eventTargetNodeForDocument(m_frame->document());
if (!node)
return false;
}
PlatformKeyboardEvent keyPressEvent = initialKeyEvent;
keyPressEvent.disambiguateKeyDownEvent(PlatformEvent::Char, backwardCompatibilityMode);
if (keyPressEvent.text().isEmpty())
return keydownResult;
RefPtr<KeyboardEvent> keypress = KeyboardEvent::create(keyPressEvent, m_frame->document()->defaultView());
keypress->setTarget(node);
if (keydownResult)
keypress->setDefaultPrevented(true);
#if PLATFORM(MAC)
keypress->keypressCommands() = keydown->keypressCommands();
#endif
node->dispatchEvent(keypress, ec);
return keydownResult || keypress->defaultPrevented() || keypress->defaultHandled();
}
static FocusDirection focusDirectionForKey(const AtomicString& keyIdentifier)
{
DEFINE_STATIC_LOCAL(AtomicString, Down, ("Down"));
DEFINE_STATIC_LOCAL(AtomicString, Up, ("Up"));
DEFINE_STATIC_LOCAL(AtomicString, Left, ("Left"));
DEFINE_STATIC_LOCAL(AtomicString, Right, ("Right"));
FocusDirection retVal = FocusDirectionNone;
if (keyIdentifier == Down)
retVal = FocusDirectionDown;
else if (keyIdentifier == Up)
retVal = FocusDirectionUp;
else if (keyIdentifier == Left)
retVal = FocusDirectionLeft;
else if (keyIdentifier == Right)
retVal = FocusDirectionRight;
return retVal;
}
static void handleKeyboardSelectionMovement(FrameSelection* selection, KeyboardEvent* event)
{
if (!event)
return;
bool isOptioned = event->getModifierState("Alt");
bool isCommanded = event->getModifierState("Meta");
SelectionDirection direction = DirectionForward;
TextGranularity granularity = CharacterGranularity;
switch (focusDirectionForKey(event->keyIdentifier())) {
case FocusDirectionNone:
return;
case FocusDirectionForward:
case FocusDirectionBackward:
ASSERT_NOT_REACHED();
return;
case FocusDirectionUp:
direction = DirectionBackward;
granularity = isCommanded ? DocumentBoundary : LineGranularity;
break;
case FocusDirectionDown:
direction = DirectionForward;
granularity = isCommanded ? DocumentBoundary : LineGranularity;
break;
case FocusDirectionLeft:
direction = DirectionLeft;
granularity = (isCommanded) ? LineBoundary : (isOptioned) ? WordGranularity : CharacterGranularity;
break;
case FocusDirectionRight:
direction = DirectionRight;
granularity = (isCommanded) ? LineBoundary : (isOptioned) ? WordGranularity : CharacterGranularity;
break;
}
FrameSelection::EAlteration alternation = event->getModifierState("Shift") ? FrameSelection::AlterationExtend : FrameSelection::AlterationMove;
selection->modify(alternation, direction, granularity, UserTriggered);
event->setDefaultHandled();
}
void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
{
if (event->type() == eventNames().keydownEvent) {
m_frame->editor()->handleKeyboardEvent(event);
if (event->defaultHandled())
return;
if (event->keyIdentifier() == "U+0009")
defaultTabEventHandler(event);
else if (event->keyIdentifier() == "U+0008")
defaultBackspaceEventHandler(event);
else {
FocusDirection direction = focusDirectionForKey(event->keyIdentifier());
if (direction != FocusDirectionNone)
defaultArrowEventHandler(direction, event);
}
if (AXObjectCache::accessibilityEnhancedUserInterfaceEnabled())
handleKeyboardSelectionMovement(m_frame->selection(), event);
}
if (event->type() == eventNames().keypressEvent) {
m_frame->editor()->handleKeyboardEvent(event);
if (event->defaultHandled())
return;
if (event->charCode() == ' ')
defaultSpaceEventHandler(event);
}
}
#if ENABLE(DRAG_SUPPORT)
bool EventHandler::dragHysteresisExceeded(const IntPoint& floatDragViewportLocation) const
{
FloatPoint dragViewportLocation(floatDragViewportLocation.x(), floatDragViewportLocation.y());
return dragHysteresisExceeded(dragViewportLocation);
}
bool EventHandler::dragHysteresisExceeded(const FloatPoint& dragViewportLocation) const
{
FrameView* view = m_frame->view();
if (!view)
return false;
IntPoint dragLocation = view->windowToContents(flooredIntPoint(dragViewportLocation));
IntSize delta = dragLocation - m_mouseDownPos;
int threshold = GeneralDragHysteresis;
switch (dragState().m_dragType) {
case DragSourceActionSelection:
threshold = TextDragHysteresis;
break;
case DragSourceActionImage:
threshold = ImageDragHysteresis;
break;
case DragSourceActionLink:
threshold = LinkDragHysteresis;
break;
case DragSourceActionDHTML:
break;
case DragSourceActionNone:
case DragSourceActionAny:
ASSERT_NOT_REACHED();
}
return abs(delta.width()) >= threshold || abs(delta.height()) >= threshold;
}
void EventHandler::freeClipboard()
{
if (dragState().m_dragClipboard)
dragState().m_dragClipboard->setAccessPolicy(ClipboardNumb);
}
void EventHandler::dragSourceEndedAt(const PlatformMouseEvent& event, DragOperation operation)
{
HitTestRequest request(HitTestRequest::Release);
prepareMouseEvent(request, event);
if (dragState().m_dragSrc && dragState().shouldDispatchEvents()) {
dragState().m_dragClipboard->setDestinationOperation(operation);
dispatchDragSrcEvent(eventNames().dragendEvent, event);
}
freeClipboard();
dragState().m_dragSrc = 0;
m_mouseDownMayStartDrag = false;
}
void EventHandler::updateDragStateAfterEditDragIfNeeded(Element* rootEditableElement)
{
if (dragState().m_dragSrc && !dragState().m_dragSrc->inDocument())
dragState().m_dragSrc = rootEditableElement;
}
bool EventHandler::dispatchDragSrcEvent(const AtomicString& eventType, const PlatformMouseEvent& event)
{
return !dispatchDragEvent(eventType, dragState().m_dragSrc.get(), event, dragState().m_dragClipboard.get());
}
static bool ExactlyOneBitSet(DragSourceAction n)
{
return n && !(n & (n - 1));
}
bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event)
{
if (event.event().button() != LeftButton || event.event().type() != PlatformEvent::MouseMoved) {
m_mousePressed = false;
return false;
}
if (eventLoopHandleMouseDragged(event))
return true;
if (m_mouseDownMayStartDrag && !dragState().m_dragSrc) {
dragState().m_eventDispatchPolicy = (updateDragSourceActionsAllowed() & DragSourceActionDHTML) ? DragState::DispatchEvents: DragState::DoNotDispatchEvents;
HitTestRequest request(HitTestRequest::ReadOnly);
HitTestResult result(m_mouseDownPos);
m_frame->contentRenderer()->hitTest(request, result);
Node* node = result.innerNode();
if (node && m_frame->page())
dragState().m_dragSrc = m_frame->page()->dragController()->draggableNode(m_frame, node, m_mouseDownPos, dragState());
else
dragState().m_dragSrc = 0;
if (!dragState().m_dragSrc)
m_mouseDownMayStartDrag = false; else
m_dragMayStartSelectionInstead = (dragState().m_dragType & DragSourceActionSelection);
}
if (m_mouseDownMayStartDrag && m_dragMayStartSelectionInstead && (dragState().m_dragType & DragSourceActionSelection) && event.event().timestamp() - m_mouseDownTimestamp < TextDragDelay) {
ASSERT(event.event().type() == PlatformEvent::MouseMoved);
if ((dragState().m_dragType & DragSourceActionImage)) {
dragState().m_dragType = DragSourceActionImage;
} else if (!(dragState().m_dragType & (DragSourceActionDHTML | DragSourceActionLink))) {
m_mouseDownMayStartDrag = false;
dragState().m_dragSrc = 0;
if (eventActivatedView(event.event()))
m_mouseDownMayStartSelect = false;
} else {
m_dragMayStartSelectionInstead = false;
}
}
if (!m_mouseDownMayStartDrag)
return !mouseDownMayStartSelect() && !m_mouseDownMayStartAutoscroll;
if (!ExactlyOneBitSet(dragState().m_dragType)) {
ASSERT((dragState().m_dragType & DragSourceActionSelection));
ASSERT((dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionDHTML
|| (dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionImage
|| (dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionLink);
dragState().m_dragType = DragSourceActionSelection;
}
if (FrameView* view = m_frame->view()) {
view->setCursor(pointerCursor());
}
if (!dragHysteresisExceeded(event.event().position()))
return true;
invalidateClick();
DragOperation srcOp = DragOperationNone;
freeClipboard(); dragState().m_dragClipboard = createDraggingClipboard();
if (dragState().shouldDispatchEvents()) {
if (dragState().m_dragType == DragSourceActionDHTML) {
if (RenderObject* renderer = dragState().m_dragSrc->renderer()) {
FloatPoint absPos = renderer->localToAbsolute();
IntSize delta = m_mouseDownPos - roundedIntPoint(absPos);
dragState().m_dragClipboard->setDragImageElement(dragState().m_dragSrc.get(), toPoint(delta));
} else {
m_mouseDownMayStartDrag = false;
goto cleanupDrag;
}
}
m_mouseDownMayStartDrag = dispatchDragSrcEvent(eventNames().dragstartEvent, m_mouseDown)
&& !m_frame->selection()->isInPasswordField();
dragState().m_dragClipboard->setAccessPolicy(ClipboardImageWritable);
if (m_mouseDownMayStartDrag) {
srcOp = dragState().m_dragClipboard->sourceOperation();
dragState().m_dragClipboard->setDragHasStarted();
}
}
if (m_mouseDownMayStartDrag) {
Page* page = m_frame->page();
DragController* dragController = page ? page->dragController() : 0;
bool startedDrag = dragController && dragController->startDrag(m_frame, dragState(), srcOp, event.event(), m_mouseDownPos);
if (startedDrag) {
m_mouseDownMayStartDrag = false;
return true;
}
if (dragState().shouldDispatchEvents()) {
dispatchDragSrcEvent(eventNames().dragendEvent, event.event());
m_mouseDownMayStartDrag = false;
}
}
cleanupDrag:
if (!m_mouseDownMayStartDrag) {
freeClipboard();
dragState().m_dragSrc = 0;
}
return true;
}
#endif // ENABLE(DRAG_SUPPORT)
bool EventHandler::handleTextInputEvent(const String& text, Event* underlyingEvent, TextEventInputType inputType)
{
ASSERT(!underlyingEvent || !underlyingEvent->isKeyboardEvent() || static_cast<KeyboardEvent*>(underlyingEvent)->type() == eventNames().keypressEvent);
if (!m_frame)
return false;
EventTarget* target;
if (underlyingEvent)
target = underlyingEvent->target();
else
target = eventTargetNodeForDocument(m_frame->document());
if (!target)
return false;
if (FrameView* view = m_frame->view())
view->resetDeferredRepaintDelay();
RefPtr<TextEvent> event = TextEvent::create(m_frame->domWindow(), text, inputType);
event->setUnderlyingEvent(underlyingEvent);
ExceptionCode ec;
target->dispatchEvent(event, ec);
return event->defaultHandled();
}
bool EventHandler::isKeyboardOptionTab(KeyboardEvent* event)
{
return event
&& (event->type() == eventNames().keydownEvent || event->type() == eventNames().keypressEvent)
&& event->altKey()
&& event->keyIdentifier() == "U+0009";
}
bool EventHandler::eventInvertsTabsToLinksClientCallResult(KeyboardEvent* event)
{
return EventHandler::isKeyboardOptionTab(event);
}
bool EventHandler::tabsToLinks(KeyboardEvent* event) const
{
Page* page = m_frame->page();
if (!page)
return false;
bool tabsToLinksClientCallResult = page->chrome()->client()->keyboardUIMode() & KeyboardAccessTabsToLinks;
return eventInvertsTabsToLinksClientCallResult(event) ? !tabsToLinksClientCallResult : tabsToLinksClientCallResult;
}
void EventHandler::defaultTextInputEventHandler(TextEvent* event)
{
if (m_frame->editor()->handleTextEvent(event))
event->setDefaultHandled();
}
#if PLATFORM(QT)
void EventHandler::defaultSpaceEventHandler(KeyboardEvent*)
{
}
#else
void EventHandler::defaultSpaceEventHandler(KeyboardEvent* event)
{
ASSERT(event->type() == eventNames().keypressEvent);
if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
return;
ScrollLogicalDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward;
if (logicalScrollOverflow(direction, ScrollByPage)) {
event->setDefaultHandled();
return;
}
FrameView* view = m_frame->view();
if (!view)
return;
if (view->logicalScroll(direction, ScrollByPage))
event->setDefaultHandled();
}
#endif
void EventHandler::defaultBackspaceEventHandler(KeyboardEvent* event)
{
ASSERT(event->type() == eventNames().keydownEvent);
if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
return;
if (!m_frame->editor()->behavior().shouldNavigateBackOnBackspace())
return;
Page* page = m_frame->page();
if (!page)
return;
if (!m_frame->settings()->backspaceKeyNavigationEnabled())
return;
bool handledEvent = false;
if (event->shiftKey())
handledEvent = page->goForward();
else
handledEvent = page->goBack();
if (handledEvent)
event->setDefaultHandled();
}
void EventHandler::defaultArrowEventHandler(FocusDirection focusDirection, KeyboardEvent* event)
{
ASSERT(event->type() == eventNames().keydownEvent);
if (event->ctrlKey() || event->metaKey() || event->altGraphKey() || event->shiftKey())
return;
Page* page = m_frame->page();
if (!page)
return;
if (!isSpatialNavigationEnabled(m_frame))
return;
if (m_frame->document()->inDesignMode())
return;
if (page->focusController()->advanceFocus(focusDirection, event))
event->setDefaultHandled();
}
void EventHandler::defaultTabEventHandler(KeyboardEvent* event)
{
ASSERT(event->type() == eventNames().keydownEvent);
if (event->ctrlKey() || event->metaKey() || event->altGraphKey())
return;
Page* page = m_frame->page();
if (!page)
return;
if (!page->tabKeyCyclesThroughElements())
return;
FocusDirection focusDirection = event->shiftKey() ? FocusDirectionBackward : FocusDirectionForward;
if (m_frame->document()->inDesignMode())
return;
if (page->focusController()->advanceFocus(focusDirection, event))
event->setDefaultHandled();
}
void EventHandler::capsLockStateMayHaveChanged()
{
Document* d = m_frame->document();
if (Node* node = d->focusedNode()) {
if (RenderObject* r = node->renderer()) {
if (r->isTextField())
toRenderTextControlSingleLine(r)->capsLockStateMayHaveChanged();
}
}
}
void EventHandler::sendResizeEvent()
{
m_frame->document()->enqueueWindowEvent(Event::create(eventNames().resizeEvent, false, false));
}
void EventHandler::sendScrollEvent()
{
setFrameWasScrolledByUser();
if (m_frame->view() && m_frame->document())
m_frame->document()->eventQueue()->enqueueOrDispatchScrollEvent(m_frame->document(), DocumentEventQueue::ScrollEventDocumentTarget);
}
void EventHandler::setFrameWasScrolledByUser()
{
FrameView* v = m_frame->view();
if (v)
v->setWasScrolledByUser(true);
}
bool EventHandler::passMousePressEventToScrollbar(MouseEventWithHitTestResults& mev, Scrollbar* scrollbar)
{
if (!scrollbar || !scrollbar->enabled())
return false;
setFrameWasScrolledByUser();
return scrollbar->mouseDown(mev.event());
}
void EventHandler::updateLastScrollbarUnderMouse(Scrollbar* scrollbar, bool setLast)
{
if (m_lastScrollbarUnderMouse != scrollbar) {
if (m_lastScrollbarUnderMouse)
m_lastScrollbarUnderMouse->mouseExited();
if (scrollbar && setLast)
scrollbar->mouseEntered();
m_lastScrollbarUnderMouse = setLast ? scrollbar : 0;
}
}
bool EventHandler::dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent&)
{
return false;
}
}