Home | History | Annotate | Download | only in runner
      1 /*
      2  * Copyright (C) 2010 Google Inc. All rights reserved.
      3  *
      4  * Redistribution and use in source and binary forms, with or without
      5  * modification, are permitted provided that the following conditions are
      6  * met:
      7  *
      8  *     * Redistributions of source code must retain the above copyright
      9  * notice, this list of conditions and the following disclaimer.
     10  *     * Redistributions in binary form must reproduce the above
     11  * copyright notice, this list of conditions and the following disclaimer
     12  * in the documentation and/or other materials provided with the
     13  * distribution.
     14  *     * Neither the name of Google Inc. nor the names of its
     15  * contributors may be used to endorse or promote products derived from
     16  * this software without specific prior written permission.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 // This file contains the definition for EventSender.
     32 //
     33 // Some notes about drag and drop handling:
     34 // Windows drag and drop goes through a system call to doDragDrop. At that
     35 // point, program control is given to Windows which then periodically makes
     36 // callbacks into the webview. This won't work for layout tests, so instead,
     37 // we queue up all the mouse move and mouse up events. When the test tries to
     38 // start a drag (by calling EvenSendingController::doDragDrop), we take the
     39 // events in the queue and replay them.
     40 // The behavior of queuing events and replaying them can be disabled by a
     41 // layout test by setting eventSender.dragMode to false.
     42 
     43 #include "EventSender.h"
     44 
     45 #include "KeyCodeMapping.h"
     46 #include "MockSpellCheck.h"
     47 #include "TestCommon.h"
     48 #include "public/platform/WebDragData.h"
     49 #include "public/platform/WebPoint.h"
     50 #include "public/platform/WebString.h"
     51 #include "public/platform/WebVector.h"
     52 #include "public/testing/WebTestDelegate.h"
     53 #include "public/web/WebContextMenuData.h"
     54 #include "public/web/WebDragOperation.h"
     55 #include "public/web/WebTouchPoint.h"
     56 #include "public/web/WebView.h"
     57 #include <deque>
     58 
     59 #ifdef WIN32
     60 #include "public/web/win/WebInputEventFactory.h"
     61 #endif
     62 
     63 // FIXME: layout before each event?
     64 
     65 using namespace std;
     66 using namespace WebKit;
     67 
     68 namespace WebTestRunner {
     69 
     70 WebPoint EventSender::lastMousePos;
     71 WebMouseEvent::Button EventSender::pressedButton = WebMouseEvent::ButtonNone;
     72 WebMouseEvent::Button EventSender::lastButtonType = WebMouseEvent::ButtonNone;
     73 
     74 namespace {
     75 
     76 struct SavedEvent {
     77     enum SavedEventType {
     78         Unspecified,
     79         MouseUp,
     80         MouseMove,
     81         LeapForward
     82     };
     83 
     84     SavedEventType type;
     85     WebMouseEvent::Button buttonType; // For MouseUp.
     86     WebPoint pos; // For MouseMove.
     87     int milliseconds; // For LeapForward.
     88 
     89     SavedEvent()
     90         : type(Unspecified)
     91         , buttonType(WebMouseEvent::ButtonNone)
     92         , milliseconds(0) { }
     93 };
     94 
     95 WebDragData currentDragData;
     96 WebDragOperation currentDragEffect;
     97 WebDragOperationsMask currentDragEffectsAllowed;
     98 bool replayingSavedEvents = false;
     99 deque<SavedEvent> mouseEventQueue;
    100 int touchModifiers;
    101 vector<WebTouchPoint> touchPoints;
    102 
    103 // Time and place of the last mouse up event.
    104 double lastClickTimeSec = 0;
    105 WebPoint lastClickPos;
    106 int clickCount = 0;
    107 
    108 // maximum distance (in space and time) for a mouse click
    109 // to register as a double or triple click
    110 const double multipleClickTimeSec = 1;
    111 const int multipleClickRadiusPixels = 5;
    112 
    113 // How much we should scroll per event - the value here is chosen to
    114 // match the WebKit impl and layout test results.
    115 const float scrollbarPixelsPerTick = 40.0f;
    116 
    117 inline bool outsideMultiClickRadius(const WebPoint& a, const WebPoint& b)
    118 {
    119     return ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)) >
    120         multipleClickRadiusPixels * multipleClickRadiusPixels;
    121 }
    122 
    123 // Used to offset the time the event hander things an event happened. This is
    124 // done so tests can run without a delay, but bypass checks that are time
    125 // dependent (e.g., dragging has a timeout vs selection).
    126 uint32 timeOffsetMs = 0;
    127 
    128 double getCurrentEventTimeSec(WebTestDelegate* delegate)
    129 {
    130     return (delegate->getCurrentTimeInMillisecond() + timeOffsetMs) / 1000.0;
    131 }
    132 
    133 void advanceEventTime(int32_t deltaMs)
    134 {
    135     timeOffsetMs += deltaMs;
    136 }
    137 
    138 void initMouseEvent(WebInputEvent::Type t, WebMouseEvent::Button b, const WebPoint& pos, WebMouseEvent* e, double ts)
    139 {
    140     e->type = t;
    141     e->button = b;
    142     e->modifiers = 0;
    143     e->x = pos.x;
    144     e->y = pos.y;
    145     e->globalX = pos.x;
    146     e->globalY = pos.y;
    147     e->timeStampSeconds = ts;
    148     e->clickCount = clickCount;
    149 }
    150 
    151 // Returns true if the specified key is the system key.
    152 bool applyKeyModifier(const string& modifierName, WebInputEvent* event)
    153 {
    154     bool isSystemKey = false;
    155     const char* characters = modifierName.c_str();
    156     if (!strcmp(characters, "ctrlKey")
    157 #ifndef __APPLE__
    158         || !strcmp(characters, "addSelectionKey")
    159 #endif
    160         ) {
    161         event->modifiers |= WebInputEvent::ControlKey;
    162     } else if (!strcmp(characters, "shiftKey") || !strcmp(characters, "rangeSelectionKey"))
    163         event->modifiers |= WebInputEvent::ShiftKey;
    164     else if (!strcmp(characters, "altKey")) {
    165         event->modifiers |= WebInputEvent::AltKey;
    166 #ifndef __APPLE__
    167         // On Windows all keys with Alt modifier will be marked as system key.
    168         // We keep the same behavior on Linux and everywhere non-Mac, see:
    169         // WebKit/chromium/src/gtk/WebInputEventFactory.cpp
    170         // If we want to change this behavior on Linux, this piece of code must be
    171         // kept in sync with the related code in above file.
    172         isSystemKey = true;
    173 #endif
    174 #ifdef __APPLE__
    175     } else if (!strcmp(characters, "metaKey") || !strcmp(characters, "addSelectionKey")) {
    176         event->modifiers |= WebInputEvent::MetaKey;
    177         // On Mac only command key presses are marked as system key.
    178         // See the related code in: WebKit/chromium/src/mac/WebInputEventFactory.cpp
    179         // It must be kept in sync with the related code in above file.
    180         isSystemKey = true;
    181 #else
    182     } else if (!strcmp(characters, "metaKey")) {
    183         event->modifiers |= WebInputEvent::MetaKey;
    184 #endif
    185     }
    186     return isSystemKey;
    187 }
    188 
    189 bool applyKeyModifiers(const CppVariant* argument, WebInputEvent* event)
    190 {
    191     bool isSystemKey = false;
    192     if (argument->isObject()) {
    193         vector<string> modifiers = argument->toStringVector();
    194         for (vector<string>::const_iterator i = modifiers.begin(); i != modifiers.end(); ++i)
    195             isSystemKey |= applyKeyModifier(*i, event);
    196     } else if (argument->isString())
    197         isSystemKey = applyKeyModifier(argument->toString(), event);
    198     return isSystemKey;
    199 }
    200 
    201 // Get the edit command corresponding to a keyboard event.
    202 // Returns true if the specified event corresponds to an edit command, the name
    203 // of the edit command will be stored in |*name|.
    204 bool getEditCommand(const WebKeyboardEvent& event, string* name)
    205 {
    206 #ifdef __APPLE__
    207     // We only cares about Left,Right,Up,Down keys with Command or Command+Shift
    208     // modifiers. These key events correspond to some special movement and
    209     // selection editor commands, and was supposed to be handled in
    210     // WebKit/chromium/src/EditorClientImpl.cpp. But these keys will be marked
    211     // as system key, which prevents them from being handled. Thus they must be
    212     // handled specially.
    213     if ((event.modifiers & ~WebKeyboardEvent::ShiftKey) != WebKeyboardEvent::MetaKey)
    214         return false;
    215 
    216     switch (event.windowsKeyCode) {
    217     case VKEY_LEFT:
    218         *name = "MoveToBeginningOfLine";
    219         break;
    220     case VKEY_RIGHT:
    221         *name = "MoveToEndOfLine";
    222         break;
    223     case VKEY_UP:
    224         *name = "MoveToBeginningOfDocument";
    225         break;
    226     case VKEY_DOWN:
    227         *name = "MoveToEndOfDocument";
    228         break;
    229     default:
    230         return false;
    231     }
    232 
    233     if (event.modifiers & WebKeyboardEvent::ShiftKey)
    234         name->append("AndModifySelection");
    235 
    236     return true;
    237 #else
    238     return false;
    239 #endif
    240 }
    241 
    242 // Key event location code introduced in DOM Level 3.
    243 // See also: http://www.w3.org/TR/DOM-Level-3-Events/#events-keyboardevents
    244 enum KeyLocationCode {
    245     DOMKeyLocationStandard      = 0x00,
    246     DOMKeyLocationLeft          = 0x01,
    247     DOMKeyLocationRight         = 0x02,
    248     DOMKeyLocationNumpad        = 0x03
    249 };
    250 
    251 }
    252 
    253 EventSender::EventSender()
    254     : m_delegate(0)
    255 {
    256     // Initialize the map that associates methods of this class with the names
    257     // they will use when called by JavaScript. The actual binding of those
    258     // names to their methods will be done by calling bindToJavaScript() (defined
    259     // by CppBoundClass, the parent to EventSender).
    260     bindMethod("addTouchPoint", &EventSender::addTouchPoint);
    261     bindMethod("beginDragWithFiles", &EventSender::beginDragWithFiles);
    262     bindMethod("cancelTouchPoint", &EventSender::cancelTouchPoint);
    263     bindMethod("clearKillRing", &EventSender::clearKillRing);
    264     bindMethod("clearTouchPoints", &EventSender::clearTouchPoints);
    265     bindMethod("contextClick", &EventSender::contextClick);
    266     bindMethod("continuousMouseScrollBy", &EventSender::continuousMouseScrollBy);
    267     bindMethod("dispatchMessage", &EventSender::dispatchMessage);
    268     bindMethod("dumpFilenameBeingDragged", &EventSender::dumpFilenameBeingDragged);
    269     bindMethod("enableDOMUIEventLogging", &EventSender::enableDOMUIEventLogging);
    270     bindMethod("fireKeyboardEventsToElement", &EventSender::fireKeyboardEventsToElement);
    271     bindMethod("keyDown", &EventSender::keyDown);
    272     bindMethod("leapForward", &EventSender::leapForward);
    273     bindMethod("mouseDown", &EventSender::mouseDown);
    274     bindMethod("mouseMoveTo", &EventSender::mouseMoveTo);
    275     bindMethod("mouseScrollBy", &EventSender::mouseScrollBy);
    276     bindMethod("mouseUp", &EventSender::mouseUp);
    277     bindMethod("mouseDragBegin", &EventSender::mouseDragBegin);
    278     bindMethod("releaseTouchPoint", &EventSender::releaseTouchPoint);
    279     bindMethod("scheduleAsynchronousClick", &EventSender::scheduleAsynchronousClick);
    280     bindMethod("scheduleAsynchronousKeyDown", &EventSender::scheduleAsynchronousKeyDown);
    281     bindMethod("setTouchModifier", &EventSender::setTouchModifier);
    282     bindMethod("textZoomIn", &EventSender::textZoomIn);
    283     bindMethod("textZoomOut", &EventSender::textZoomOut);
    284     bindMethod("touchCancel", &EventSender::touchCancel);
    285     bindMethod("touchEnd", &EventSender::touchEnd);
    286     bindMethod("touchMove", &EventSender::touchMove);
    287     bindMethod("touchStart", &EventSender::touchStart);
    288     bindMethod("updateTouchPoint", &EventSender::updateTouchPoint);
    289     bindMethod("gestureFlingCancel", &EventSender::gestureFlingCancel);
    290     bindMethod("gestureFlingStart", &EventSender::gestureFlingStart);
    291     bindMethod("gestureScrollBegin", &EventSender::gestureScrollBegin);
    292     bindMethod("gestureScrollEnd", &EventSender::gestureScrollEnd);
    293     bindMethod("gestureScrollFirstPoint", &EventSender::gestureScrollFirstPoint);
    294     bindMethod("gestureScrollUpdate", &EventSender::gestureScrollUpdate);
    295     bindMethod("gestureScrollUpdateWithoutPropagation", &EventSender::gestureScrollUpdateWithoutPropagation);
    296     bindMethod("gestureTap", &EventSender::gestureTap);
    297     bindMethod("gestureTapDown", &EventSender::gestureTapDown);
    298     bindMethod("gestureTapCancel", &EventSender::gestureTapCancel);
    299     bindMethod("gestureLongPress", &EventSender::gestureLongPress);
    300     bindMethod("gestureLongTap", &EventSender::gestureLongTap);
    301     bindMethod("gestureTwoFingerTap", &EventSender::gestureTwoFingerTap);
    302     bindMethod("zoomPageIn", &EventSender::zoomPageIn);
    303     bindMethod("zoomPageOut", &EventSender::zoomPageOut);
    304     bindMethod("setPageScaleFactor", &EventSender::setPageScaleFactor);
    305 
    306     bindProperty("forceLayoutOnEvents", &forceLayoutOnEvents);
    307 
    308     // When set to true (the default value), we batch mouse move and mouse up
    309     // events so we can simulate drag & drop.
    310     bindProperty("dragMode", &dragMode);
    311 #ifdef WIN32
    312     bindProperty("WM_KEYDOWN", &wmKeyDown);
    313     bindProperty("WM_KEYUP", &wmKeyUp);
    314     bindProperty("WM_CHAR", &wmChar);
    315     bindProperty("WM_DEADCHAR", &wmDeadChar);
    316     bindProperty("WM_SYSKEYDOWN", &wmSysKeyDown);
    317     bindProperty("WM_SYSKEYUP", &wmSysKeyUp);
    318     bindProperty("WM_SYSCHAR", &wmSysChar);
    319     bindProperty("WM_SYSDEADCHAR", &wmSysDeadChar);
    320 #endif
    321 }
    322 
    323 EventSender::~EventSender()
    324 {
    325 }
    326 
    327 void EventSender::setContextMenuData(const WebContextMenuData& contextMenuData)
    328 {
    329     m_lastContextMenuData = auto_ptr<WebContextMenuData>(new WebContextMenuData(contextMenuData));
    330 }
    331 
    332 void EventSender::reset()
    333 {
    334     // The test should have finished a drag and the mouse button state.
    335     WEBKIT_ASSERT(currentDragData.isNull());
    336     currentDragData.reset();
    337     currentDragEffect = WebKit::WebDragOperationNone;
    338     currentDragEffectsAllowed = WebKit::WebDragOperationNone;
    339     pressedButton = WebMouseEvent::ButtonNone;
    340     dragMode.set(true);
    341     forceLayoutOnEvents.set(true);
    342 #ifdef WIN32
    343     wmKeyDown.set(WM_KEYDOWN);
    344     wmKeyUp.set(WM_KEYUP);
    345     wmChar.set(WM_CHAR);
    346     wmDeadChar.set(WM_DEADCHAR);
    347     wmSysKeyDown.set(WM_SYSKEYDOWN);
    348     wmSysKeyUp.set(WM_SYSKEYUP);
    349     wmSysChar.set(WM_SYSCHAR);
    350     wmSysDeadChar.set(WM_SYSDEADCHAR);
    351 #endif
    352     lastMousePos = WebPoint(0, 0);
    353     lastClickTimeSec = 0;
    354     lastClickPos = WebPoint(0, 0);
    355     clickCount = 0;
    356     lastButtonType = WebMouseEvent::ButtonNone;
    357     timeOffsetMs = 0;
    358     touchModifiers = 0;
    359     touchPoints.clear();
    360     m_taskList.revokeAll();
    361     m_currentGestureLocation = WebPoint(0, 0);
    362 }
    363 
    364 void EventSender::doDragDrop(const WebDragData& dragData, WebDragOperationsMask mask)
    365 {
    366     WebMouseEvent event;
    367     initMouseEvent(WebInputEvent::MouseDown, pressedButton, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
    368     WebPoint clientPoint(event.x, event.y);
    369     WebPoint screenPoint(event.globalX, event.globalY);
    370     currentDragData = dragData;
    371     currentDragEffectsAllowed = mask;
    372     currentDragEffect = webview()->dragTargetDragEnter(dragData, clientPoint, screenPoint, currentDragEffectsAllowed, 0);
    373 
    374     // Finish processing events.
    375     replaySavedEvents();
    376 }
    377 
    378 void EventSender::dumpFilenameBeingDragged(const CppArgumentList&, CppVariant*)
    379 {
    380     WebString filename;
    381     WebVector<WebDragData::Item> items = currentDragData.items();
    382     for (size_t i = 0; i < items.size(); ++i) {
    383         if (items[i].storageType == WebDragData::Item::StorageTypeBinaryData) {
    384             filename = items[i].title;
    385             break;
    386         }
    387     }
    388     m_delegate->printMessage(std::string("Filename being dragged: ") + filename.utf8().data() + "\n");
    389 }
    390 
    391 WebMouseEvent::Button EventSender::getButtonTypeFromButtonNumber(int buttonCode)
    392 {
    393     if (!buttonCode)
    394         return WebMouseEvent::ButtonLeft;
    395     if (buttonCode == 2)
    396         return WebMouseEvent::ButtonRight;
    397     return WebMouseEvent::ButtonMiddle;
    398 }
    399 
    400 int EventSender::getButtonNumberFromSingleArg(const CppArgumentList& arguments)
    401 {
    402     int buttonCode = 0;
    403     if (arguments.size() > 0 && arguments[0].isNumber())
    404         buttonCode = arguments[0].toInt32();
    405     return buttonCode;
    406 }
    407 
    408 void EventSender::updateClickCountForButton(WebMouseEvent::Button buttonType)
    409 {
    410     if ((getCurrentEventTimeSec(m_delegate) - lastClickTimeSec < multipleClickTimeSec)
    411         && (!outsideMultiClickRadius(lastMousePos, lastClickPos))
    412         && (buttonType == lastButtonType))
    413         ++clickCount;
    414     else {
    415         clickCount = 1;
    416         lastButtonType = buttonType;
    417     }
    418 }
    419 
    420 //
    421 // Implemented javascript methods.
    422 //
    423 
    424 void EventSender::mouseDown(const CppArgumentList& arguments, CppVariant* result)
    425 {
    426     if (result) // Could be 0 if invoked asynchronously.
    427         result->setNull();
    428 
    429     if (shouldForceLayoutOnEvents())
    430         webview()->layout();
    431 
    432     int buttonNumber = getButtonNumberFromSingleArg(arguments);
    433     WEBKIT_ASSERT(buttonNumber != -1);
    434 
    435     WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
    436 
    437     updateClickCountForButton(buttonType);
    438 
    439     WebMouseEvent event;
    440     pressedButton = buttonType;
    441     initMouseEvent(WebInputEvent::MouseDown, buttonType, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
    442     if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
    443         applyKeyModifiers(&(arguments[1]), &event);
    444     webview()->handleInputEvent(event);
    445 }
    446 
    447 void EventSender::mouseUp(const CppArgumentList& arguments, CppVariant* result)
    448 {
    449     if (result) // Could be 0 if invoked asynchronously.
    450         result->setNull();
    451 
    452     if (shouldForceLayoutOnEvents())
    453         webview()->layout();
    454 
    455     int buttonNumber = getButtonNumberFromSingleArg(arguments);
    456     WEBKIT_ASSERT(buttonNumber != -1);
    457 
    458     WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
    459 
    460     if (isDragMode() && !replayingSavedEvents) {
    461         SavedEvent savedEvent;
    462         savedEvent.type = SavedEvent::MouseUp;
    463         savedEvent.buttonType = buttonType;
    464         mouseEventQueue.push_back(savedEvent);
    465         replaySavedEvents();
    466     } else {
    467         WebMouseEvent event;
    468         initMouseEvent(WebInputEvent::MouseUp, buttonType, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
    469         if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
    470             applyKeyModifiers(&(arguments[1]), &event);
    471         doMouseUp(event);
    472     }
    473 }
    474 
    475 void EventSender::doMouseUp(const WebMouseEvent& e)
    476 {
    477     webview()->handleInputEvent(e);
    478 
    479     pressedButton = WebMouseEvent::ButtonNone;
    480     lastClickTimeSec = e.timeStampSeconds;
    481     lastClickPos = lastMousePos;
    482 
    483     // If we're in a drag operation, complete it.
    484     if (currentDragData.isNull())
    485         return;
    486 
    487     WebPoint clientPoint(e.x, e.y);
    488     WebPoint screenPoint(e.globalX, e.globalY);
    489     finishDragAndDrop(e, webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed, 0));
    490 }
    491 
    492 void EventSender::finishDragAndDrop(const WebMouseEvent& e, WebKit::WebDragOperation dragEffect)
    493 {
    494     WebPoint clientPoint(e.x, e.y);
    495     WebPoint screenPoint(e.globalX, e.globalY);
    496     currentDragEffect = dragEffect;
    497     if (currentDragEffect)
    498         webview()->dragTargetDrop(clientPoint, screenPoint, 0);
    499     else
    500         webview()->dragTargetDragLeave();
    501     webview()->dragSourceEndedAt(clientPoint, screenPoint, currentDragEffect);
    502     webview()->dragSourceSystemDragEnded();
    503 
    504     currentDragData.reset();
    505 }
    506 
    507 void EventSender::mouseMoveTo(const CppArgumentList& arguments, CppVariant* result)
    508 {
    509     result->setNull();
    510 
    511     if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
    512         return;
    513     if (shouldForceLayoutOnEvents())
    514         webview()->layout();
    515 
    516     WebPoint mousePos(arguments[0].toInt32(), arguments[1].toInt32());
    517 
    518     if (isDragMode() && pressedButton == WebMouseEvent::ButtonLeft && !replayingSavedEvents) {
    519         SavedEvent savedEvent;
    520         savedEvent.type = SavedEvent::MouseMove;
    521         savedEvent.pos = mousePos;
    522         mouseEventQueue.push_back(savedEvent);
    523     } else {
    524         WebMouseEvent event;
    525         initMouseEvent(WebInputEvent::MouseMove, pressedButton, mousePos, &event, getCurrentEventTimeSec(m_delegate));
    526         if (arguments.size() >= 3 && (arguments[2].isObject() || arguments[2].isString()))
    527             applyKeyModifiers(&(arguments[2]), &event);
    528         doMouseMove(event);
    529     }
    530 }
    531 
    532 void EventSender::doMouseMove(const WebMouseEvent& e)
    533 {
    534     lastMousePos = WebPoint(e.x, e.y);
    535 
    536     webview()->handleInputEvent(e);
    537 
    538     if (pressedButton == WebMouseEvent::ButtonNone || currentDragData.isNull())
    539         return;
    540     WebPoint clientPoint(e.x, e.y);
    541     WebPoint screenPoint(e.globalX, e.globalY);
    542     currentDragEffect = webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed, 0);
    543 }
    544 
    545 void EventSender::keyDown(const CppArgumentList& arguments, CppVariant* result)
    546 {
    547     if (result)
    548         result->setNull();
    549     if (arguments.size() < 1 || !arguments[0].isString())
    550         return;
    551     bool generateChar = false;
    552 
    553     // FIXME: I'm not exactly sure how we should convert the string to a key
    554     // event. This seems to work in the cases I tested.
    555     // FIXME: Should we also generate a KEY_UP?
    556     string codeStr = arguments[0].toString();
    557 
    558     // Convert \n -> VK_RETURN. Some layout tests use \n to mean "Enter", when
    559     // Windows uses \r for "Enter".
    560     int code = 0;
    561     int text = 0;
    562     bool needsShiftKeyModifier = false;
    563     if ("\n" == codeStr) {
    564         generateChar = true;
    565         text = code = VKEY_RETURN;
    566     } else if ("rightArrow" == codeStr)
    567         code = VKEY_RIGHT;
    568     else if ("downArrow" == codeStr)
    569         code = VKEY_DOWN;
    570     else if ("leftArrow" == codeStr)
    571         code = VKEY_LEFT;
    572     else if ("upArrow" == codeStr)
    573         code = VKEY_UP;
    574     else if ("insert" == codeStr)
    575         code = VKEY_INSERT;
    576     else if ("delete" == codeStr)
    577         code = VKEY_DELETE;
    578     else if ("pageUp" == codeStr)
    579         code = VKEY_PRIOR;
    580     else if ("pageDown" == codeStr)
    581         code = VKEY_NEXT;
    582     else if ("home" == codeStr)
    583         code = VKEY_HOME;
    584     else if ("end" == codeStr)
    585         code = VKEY_END;
    586     else if ("printScreen" == codeStr)
    587         code = VKEY_SNAPSHOT;
    588     else if ("menu" == codeStr)
    589         code = VKEY_APPS;
    590     else if ("leftControl" == codeStr)
    591         code = VKEY_LCONTROL;
    592     else if ("rightControl" == codeStr)
    593         code = VKEY_RCONTROL;
    594     else if ("leftShift" == codeStr)
    595         code = VKEY_LSHIFT;
    596     else if ("rightShift" == codeStr)
    597         code = VKEY_RSHIFT;
    598     else if ("leftAlt" == codeStr)
    599         code = VKEY_LMENU;
    600     else if ("rightAlt" == codeStr)
    601         code = VKEY_RMENU;
    602     else {
    603         // Compare the input string with the function-key names defined by the
    604         // DOM spec (i.e. "F1",...,"F24"). If the input string is a function-key
    605         // name, set its key code.
    606         for (int i = 1; i <= 24; ++i) {
    607             char functionChars[10];
    608             snprintf(functionChars, 10, "F%d", i);
    609             string functionKeyName(functionChars);
    610             if (functionKeyName == codeStr) {
    611                 code = VKEY_F1 + (i - 1);
    612                 break;
    613             }
    614         }
    615         if (!code) {
    616             WebString webCodeStr = WebString::fromUTF8(codeStr.data(), codeStr.size());
    617             WEBKIT_ASSERT(webCodeStr.length() == 1);
    618             text = code = webCodeStr.at(0);
    619             needsShiftKeyModifier = needsShiftModifier(code);
    620             if ((code & 0xFF) >= 'a' && (code & 0xFF) <= 'z')
    621                 code -= 'a' - 'A';
    622             generateChar = true;
    623         }
    624 
    625         if ("(" == codeStr) {
    626             code = '9';
    627             needsShiftKeyModifier = true;
    628         }
    629     }
    630 
    631     // For one generated keyboard event, we need to generate a keyDown/keyUp
    632     // pair; refer to EventSender.cpp in Tools/DumpRenderTree/win.
    633     // On Windows, we might also need to generate a char event to mimic the
    634     // Windows event flow; on other platforms we create a merged event and test
    635     // the event flow that that platform provides.
    636     WebKeyboardEvent eventDown, eventChar, eventUp;
    637     eventDown.type = WebInputEvent::RawKeyDown;
    638     eventDown.modifiers = 0;
    639     eventDown.windowsKeyCode = code;
    640 #if defined(__linux__) && defined(TOOLKIT_GTK)
    641     eventDown.nativeKeyCode = NativeKeyCodeForWindowsKeyCode(code);
    642 #endif
    643 
    644     if (generateChar) {
    645         eventDown.text[0] = text;
    646         eventDown.unmodifiedText[0] = text;
    647     }
    648     eventDown.setKeyIdentifierFromWindowsKeyCode();
    649 
    650     if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
    651         eventDown.isSystemKey = applyKeyModifiers(&(arguments[1]), &eventDown);
    652 
    653     if (needsShiftKeyModifier)
    654         eventDown.modifiers |= WebInputEvent::ShiftKey;
    655 
    656     // See if KeyLocation argument is given.
    657     if (arguments.size() >= 3 && arguments[2].isNumber()) {
    658         int location = arguments[2].toInt32();
    659         if (location == DOMKeyLocationNumpad)
    660             eventDown.modifiers |= WebInputEvent::IsKeyPad;
    661     }
    662 
    663     eventChar = eventUp = eventDown;
    664     eventUp.type = WebInputEvent::KeyUp;
    665     // EventSender.m forces a layout here, with at least one
    666     // test (fast/forms/focus-control-to-page.html) relying on this.
    667     if (shouldForceLayoutOnEvents())
    668         webview()->layout();
    669 
    670     // In the browser, if a keyboard event corresponds to an editor command,
    671     // the command will be dispatched to the renderer just before dispatching
    672     // the keyboard event, and then it will be executed in the
    673     // RenderView::handleCurrentKeyboardEvent() method, which is called from
    674     // third_party/WebKit/Source/WebKit/chromium/src/EditorClientImpl.cpp.
    675     // We just simulate the same behavior here.
    676     string editCommand;
    677     if (getEditCommand(eventDown, &editCommand))
    678         m_delegate->setEditCommand(editCommand, "");
    679 
    680     webview()->handleInputEvent(eventDown);
    681 
    682     if (code == VKEY_ESCAPE && !currentDragData.isNull()) {
    683         WebMouseEvent event;
    684         initMouseEvent(WebInputEvent::MouseDown, pressedButton, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
    685         finishDragAndDrop(event, WebKit::WebDragOperationNone);
    686     }
    687 
    688     m_delegate->clearEditCommand();
    689 
    690     if (generateChar) {
    691         eventChar.type = WebInputEvent::Char;
    692         eventChar.keyIdentifier[0] = '\0';
    693         webview()->handleInputEvent(eventChar);
    694     }
    695 
    696     webview()->handleInputEvent(eventUp);
    697 }
    698 
    699 void EventSender::dispatchMessage(const CppArgumentList& arguments, CppVariant* result)
    700 {
    701     result->setNull();
    702 
    703 #ifdef WIN32
    704     if (arguments.size() == 3) {
    705         // Grab the message id to see if we need to dispatch it.
    706         int msg = arguments[0].toInt32();
    707 
    708         // WebKit's version of this function stuffs a MSG struct and uses
    709         // TranslateMessage and DispatchMessage. We use a WebKeyboardEvent, which
    710         // doesn't need to receive the DeadChar and SysDeadChar messages.
    711         if (msg == WM_DEADCHAR || msg == WM_SYSDEADCHAR)
    712             return;
    713 
    714         if (shouldForceLayoutOnEvents())
    715             webview()->layout();
    716 
    717         unsigned long lparam = static_cast<unsigned long>(arguments[2].toDouble());
    718         webview()->handleInputEvent(WebInputEventFactory::keyboardEvent(0, msg, arguments[1].toInt32(), lparam));
    719     } else
    720         WEBKIT_ASSERT_NOT_REACHED();
    721 #endif
    722 }
    723 
    724 bool EventSender::needsShiftModifier(int keyCode)
    725 {
    726     // If code is an uppercase letter, assign a SHIFT key to
    727     // eventDown.modifier, this logic comes from
    728     // Tools/DumpRenderTree/win/EventSender.cpp
    729     return (keyCode & 0xFF) >= 'A' && (keyCode & 0xFF) <= 'Z';
    730 }
    731 
    732 void EventSender::leapForward(const CppArgumentList& arguments, CppVariant* result)
    733 {
    734     result->setNull();
    735 
    736     if (arguments.size() < 1 || !arguments[0].isNumber())
    737         return;
    738 
    739     int milliseconds = arguments[0].toInt32();
    740     if (isDragMode() && pressedButton == WebMouseEvent::ButtonLeft && !replayingSavedEvents) {
    741         SavedEvent savedEvent;
    742         savedEvent.type = SavedEvent::LeapForward;
    743         savedEvent.milliseconds = milliseconds;
    744         mouseEventQueue.push_back(savedEvent);
    745     } else
    746         doLeapForward(milliseconds);
    747 }
    748 
    749 void EventSender::doLeapForward(int milliseconds)
    750 {
    751     advanceEventTime(milliseconds);
    752 }
    753 
    754 // Apple's port of WebKit zooms by a factor of 1.2 (see
    755 // WebKit/WebView/WebView.mm)
    756 void EventSender::textZoomIn(const CppArgumentList&, CppVariant* result)
    757 {
    758     webview()->setTextZoomFactor(webview()->textZoomFactor() * 1.2f);
    759     result->setNull();
    760 }
    761 
    762 void EventSender::textZoomOut(const CppArgumentList&, CppVariant* result)
    763 {
    764     webview()->setTextZoomFactor(webview()->textZoomFactor() / 1.2f);
    765     result->setNull();
    766 }
    767 
    768 void EventSender::zoomPageIn(const CppArgumentList&, CppVariant* result)
    769 {
    770     webview()->setZoomLevel(webview()->zoomLevel() + 1);
    771     result->setNull();
    772 }
    773 
    774 void EventSender::zoomPageOut(const CppArgumentList&, CppVariant* result)
    775 {
    776     webview()->setZoomLevel(webview()->zoomLevel() - 1);
    777     result->setNull();
    778 }
    779 
    780 void EventSender::setPageScaleFactor(const CppArgumentList& arguments, CppVariant* result)
    781 {
    782     if (arguments.size() < 3 || !arguments[0].isNumber() || !arguments[1].isNumber() || !arguments[2].isNumber())
    783         return;
    784 
    785     float scaleFactor = static_cast<float>(arguments[0].toDouble());
    786     int x = arguments[1].toInt32();
    787     int y = arguments[2].toInt32();
    788     webview()->setPageScaleFactorLimits(scaleFactor, scaleFactor);
    789     webview()->setPageScaleFactor(scaleFactor, WebPoint(x, y));
    790     result->setNull();
    791 }
    792 
    793 void EventSender::mouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
    794 {
    795     handleMouseWheel(arguments, result, false);
    796 }
    797 
    798 void EventSender::continuousMouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
    799 {
    800     handleMouseWheel(arguments, result, true);
    801 }
    802 
    803 void EventSender::replaySavedEvents()
    804 {
    805     replayingSavedEvents = true;
    806     while (!mouseEventQueue.empty()) {
    807         SavedEvent e = mouseEventQueue.front();
    808         mouseEventQueue.pop_front();
    809 
    810         switch (e.type) {
    811         case SavedEvent::MouseMove: {
    812             WebMouseEvent event;
    813             initMouseEvent(WebInputEvent::MouseMove, pressedButton, e.pos, &event, getCurrentEventTimeSec(m_delegate));
    814             doMouseMove(event);
    815             break;
    816         }
    817         case SavedEvent::LeapForward:
    818             doLeapForward(e.milliseconds);
    819             break;
    820         case SavedEvent::MouseUp: {
    821             WebMouseEvent event;
    822             initMouseEvent(WebInputEvent::MouseUp, e.buttonType, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
    823             doMouseUp(event);
    824             break;
    825         }
    826         default:
    827             WEBKIT_ASSERT_NOT_REACHED();
    828         }
    829     }
    830 
    831     replayingSavedEvents = false;
    832 }
    833 
    834 // Because actual context menu is implemented by the browser side,
    835 // this function does only what LayoutTests are expecting:
    836 // - Many test checks the count of items. So returning non-zero value makes sense.
    837 // - Some test compares the count before and after some action. So changing the count based on flags
    838 //   also makes sense. This function is doing such for some flags.
    839 // - Some test even checks actual string content. So providing it would be also helpful.
    840 //
    841 static vector<WebString> makeMenuItemStringsFor(WebContextMenuData* contextMenu, WebTestDelegate* delegate)
    842 {
    843     // These constants are based on Safari's context menu because tests are made for it.
    844     static const char* nonEditableMenuStrings[] = { "Back", "Reload Page", "Open in Dashbaord", "<separator>", "View Source", "Save Page As", "Print Page", "Inspect Element", 0 };
    845     static const char* editableMenuStrings[] = { "Cut", "Copy", "<separator>", "Paste", "Spelling and Grammar", "Substitutions, Transformations", "Font", "Speech", "Paragraph Direction", "<separator>", 0 };
    846 
    847     // This is possible because mouse events are cancelleable.
    848     if (!contextMenu)
    849         return vector<WebString>();
    850 
    851     vector<WebString> strings;
    852 
    853     if (contextMenu->isEditable) {
    854         for (const char** item = editableMenuStrings; *item; ++item)
    855             strings.push_back(WebString::fromUTF8(*item));
    856         WebVector<WebString> suggestions;
    857         MockSpellCheck::fillSuggestionList(contextMenu->misspelledWord, &suggestions);
    858         for (size_t i = 0; i < suggestions.size(); ++i)
    859             strings.push_back(suggestions[i]);
    860     } else {
    861         for (const char** item = nonEditableMenuStrings; *item; ++item)
    862             strings.push_back(WebString::fromUTF8(*item));
    863     }
    864 
    865     return strings;
    866 }
    867 
    868 void EventSender::contextClick(const CppArgumentList& arguments, CppVariant* result)
    869 {
    870     if (shouldForceLayoutOnEvents())
    871         webview()->layout();
    872 
    873     updateClickCountForButton(WebMouseEvent::ButtonRight);
    874 
    875     // Clears last context menu data because we need to know if the context menu be requested
    876     // after following mouse events.
    877     m_lastContextMenuData.reset();
    878 
    879     // Generate right mouse down and up.
    880     WebMouseEvent event;
    881     // This is a hack to work around only allowing a single pressed button since we want to
    882     // test the case where both the left and right mouse buttons are pressed.
    883     if (pressedButton == WebMouseEvent::ButtonNone)
    884         pressedButton = WebMouseEvent::ButtonRight;
    885     initMouseEvent(WebInputEvent::MouseDown, WebMouseEvent::ButtonRight, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
    886     webview()->handleInputEvent(event);
    887 
    888 #ifdef WIN32
    889     initMouseEvent(WebInputEvent::MouseUp, WebMouseEvent::ButtonRight, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
    890     webview()->handleInputEvent(event);
    891 
    892     pressedButton = WebMouseEvent::ButtonNone;
    893 #endif
    894 
    895     NPObject* resultArray = WebBindings::makeStringArray(makeMenuItemStringsFor(m_lastContextMenuData.get(), m_delegate));
    896     result->set(resultArray);
    897     WebBindings::releaseObject(resultArray);
    898 
    899     m_lastContextMenuData.reset();
    900 }
    901 
    902 class MouseDownTask: public WebMethodTask<EventSender> {
    903 public:
    904     MouseDownTask(EventSender* obj, const CppArgumentList& arg)
    905         : WebMethodTask<EventSender>(obj), m_arguments(arg) { }
    906     virtual void runIfValid() { m_object->mouseDown(m_arguments, 0); }
    907 
    908 private:
    909     CppArgumentList m_arguments;
    910 };
    911 
    912 class MouseUpTask: public WebMethodTask<EventSender> {
    913 public:
    914     MouseUpTask(EventSender* obj, const CppArgumentList& arg)
    915         : WebMethodTask<EventSender>(obj), m_arguments(arg) { }
    916     virtual void runIfValid() { m_object->mouseUp(m_arguments, 0); }
    917 
    918 private:
    919     CppArgumentList m_arguments;
    920 };
    921 
    922 void EventSender::scheduleAsynchronousClick(const CppArgumentList& arguments, CppVariant* result)
    923 {
    924     result->setNull();
    925     m_delegate->postTask(new MouseDownTask(this, arguments));
    926     m_delegate->postTask(new MouseUpTask(this, arguments));
    927 }
    928 
    929 class KeyDownTask : public WebMethodTask<EventSender> {
    930 public:
    931     KeyDownTask(EventSender* obj, const CppArgumentList& arg)
    932         : WebMethodTask<EventSender>(obj), m_arguments(arg) { }
    933     virtual void runIfValid() { m_object->keyDown(m_arguments, 0); }
    934 
    935 private:
    936     CppArgumentList m_arguments;
    937 };
    938 
    939 void EventSender::scheduleAsynchronousKeyDown(const CppArgumentList& arguments, CppVariant* result)
    940 {
    941     result->setNull();
    942     m_delegate->postTask(new KeyDownTask(this, arguments));
    943 }
    944 
    945 void EventSender::beginDragWithFiles(const CppArgumentList& arguments, CppVariant* result)
    946 {
    947     currentDragData.initialize();
    948     vector<string> files = arguments[0].toStringVector();
    949     WebVector<WebString> absoluteFilenames(files.size());
    950     for (size_t i = 0; i < files.size(); ++i) {
    951         WebDragData::Item item;
    952         item.storageType = WebDragData::Item::StorageTypeFilename;
    953         item.filenameData = m_delegate->getAbsoluteWebStringFromUTF8Path(files[i]);
    954         currentDragData.addItem(item);
    955         absoluteFilenames[i] = item.filenameData;
    956     }
    957     currentDragData.setFilesystemId(m_delegate->registerIsolatedFileSystem(absoluteFilenames));
    958     currentDragEffectsAllowed = WebKit::WebDragOperationCopy;
    959 
    960     // Provide a drag source.
    961     webview()->dragTargetDragEnter(currentDragData, lastMousePos, lastMousePos, currentDragEffectsAllowed, 0);
    962 
    963     // dragMode saves events and then replays them later. We don't need/want that.
    964     dragMode.set(false);
    965 
    966     // Make the rest of eventSender think a drag is in progress.
    967     pressedButton = WebMouseEvent::ButtonLeft;
    968 
    969     result->setNull();
    970 }
    971 
    972 void EventSender::addTouchPoint(const CppArgumentList& arguments, CppVariant* result)
    973 {
    974     result->setNull();
    975 
    976     WebTouchPoint touchPoint;
    977     touchPoint.state = WebTouchPoint::StatePressed;
    978     touchPoint.position = WebPoint(arguments[0].toInt32(), arguments[1].toInt32());
    979     touchPoint.screenPosition = touchPoint.position;
    980 
    981     int lowestId = 0;
    982     for (size_t i = 0; i < touchPoints.size(); i++) {
    983         if (touchPoints[i].id == lowestId)
    984             lowestId++;
    985     }
    986     touchPoint.id = lowestId;
    987     touchPoints.push_back(touchPoint);
    988 }
    989 
    990 void EventSender::clearTouchPoints(const CppArgumentList&, CppVariant* result)
    991 {
    992     result->setNull();
    993     touchPoints.clear();
    994 }
    995 
    996 void EventSender::releaseTouchPoint(const CppArgumentList& arguments, CppVariant* result)
    997 {
    998     result->setNull();
    999 
   1000     const unsigned index = arguments[0].toInt32();
   1001     WEBKIT_ASSERT(index < touchPoints.size());
   1002 
   1003     WebTouchPoint* touchPoint = &touchPoints[index];
   1004     touchPoint->state = WebTouchPoint::StateReleased;
   1005 }
   1006 
   1007 void EventSender::setTouchModifier(const CppArgumentList& arguments, CppVariant* result)
   1008 {
   1009     result->setNull();
   1010 
   1011     int mask = 0;
   1012     const string keyName = arguments[0].toString();
   1013     if (keyName == "shift")
   1014         mask = WebInputEvent::ShiftKey;
   1015     else if (keyName == "alt")
   1016         mask = WebInputEvent::AltKey;
   1017     else if (keyName == "ctrl")
   1018         mask = WebInputEvent::ControlKey;
   1019     else if (keyName == "meta")
   1020         mask = WebInputEvent::MetaKey;
   1021 
   1022     if (arguments[1].toBoolean())
   1023         touchModifiers |= mask;
   1024     else
   1025         touchModifiers &= ~mask;
   1026 }
   1027 
   1028 void EventSender::updateTouchPoint(const CppArgumentList& arguments, CppVariant* result)
   1029 {
   1030     result->setNull();
   1031 
   1032     const unsigned index = arguments[0].toInt32();
   1033     WEBKIT_ASSERT(index < touchPoints.size());
   1034 
   1035     WebPoint position(arguments[1].toInt32(), arguments[2].toInt32());
   1036     WebTouchPoint* touchPoint = &touchPoints[index];
   1037     touchPoint->state = WebTouchPoint::StateMoved;
   1038     touchPoint->position = position;
   1039     touchPoint->screenPosition = position;
   1040 }
   1041 
   1042 void EventSender::cancelTouchPoint(const CppArgumentList& arguments, CppVariant* result)
   1043 {
   1044     result->setNull();
   1045 
   1046     const unsigned index = arguments[0].toInt32();
   1047     WEBKIT_ASSERT(index < touchPoints.size());
   1048 
   1049     WebTouchPoint* touchPoint = &touchPoints[index];
   1050     touchPoint->state = WebTouchPoint::StateCancelled;
   1051 }
   1052 
   1053 void EventSender::sendCurrentTouchEvent(const WebInputEvent::Type type)
   1054 {
   1055     WEBKIT_ASSERT(static_cast<unsigned>(WebTouchEvent::touchesLengthCap) > touchPoints.size());
   1056     if (shouldForceLayoutOnEvents())
   1057         webview()->layout();
   1058 
   1059     WebTouchEvent touchEvent;
   1060     touchEvent.type = type;
   1061     touchEvent.modifiers = touchModifiers;
   1062     touchEvent.timeStampSeconds = getCurrentEventTimeSec(m_delegate);
   1063     touchEvent.touchesLength = touchPoints.size();
   1064     for (unsigned i = 0; i < touchPoints.size(); ++i)
   1065         touchEvent.touches[i] = touchPoints[i];
   1066     webview()->handleInputEvent(touchEvent);
   1067 
   1068     for (unsigned i = 0; i < touchPoints.size(); ++i) {
   1069         WebTouchPoint* touchPoint = &touchPoints[i];
   1070         if (touchPoint->state == WebTouchPoint::StateReleased) {
   1071             touchPoints.erase(touchPoints.begin() + i);
   1072             --i;
   1073         } else
   1074             touchPoint->state = WebTouchPoint::StateStationary;
   1075     }
   1076 }
   1077 
   1078 void EventSender::mouseDragBegin(const CppArgumentList& arguments, CppVariant* result)
   1079 {
   1080     WebMouseWheelEvent event;
   1081     initMouseEvent(WebInputEvent::MouseWheel, WebMouseEvent::ButtonNone, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
   1082     event.phase = WebMouseWheelEvent::PhaseBegan;
   1083     event.hasPreciseScrollingDeltas = true;
   1084     webview()->handleInputEvent(event);
   1085 }
   1086 
   1087 void EventSender::handleMouseWheel(const CppArgumentList& arguments, CppVariant* result, bool continuous)
   1088 {
   1089     result->setNull();
   1090 
   1091     if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
   1092         return;
   1093 
   1094     // Force a layout here just to make sure every position has been
   1095     // determined before we send events (as well as all the other methods
   1096     // that send an event do).
   1097     if (shouldForceLayoutOnEvents())
   1098         webview()->layout();
   1099 
   1100     int horizontal = arguments[0].toInt32();
   1101     int vertical = arguments[1].toInt32();
   1102     int paged = false;
   1103     int hasPreciseScrollingDeltas = false;
   1104 
   1105     if (arguments.size() > 2 && arguments[2].isBool())
   1106         paged = arguments[2].toBoolean();
   1107 
   1108     if (arguments.size() > 3 && arguments[3].isBool())
   1109         hasPreciseScrollingDeltas = arguments[3].toBoolean();
   1110 
   1111     WebMouseWheelEvent event;
   1112     initMouseEvent(WebInputEvent::MouseWheel, pressedButton, lastMousePos, &event, getCurrentEventTimeSec(m_delegate));
   1113     event.wheelTicksX = static_cast<float>(horizontal);
   1114     event.wheelTicksY = static_cast<float>(vertical);
   1115     event.deltaX = event.wheelTicksX;
   1116     event.deltaY = event.wheelTicksY;
   1117     event.scrollByPage = paged;
   1118     event.hasPreciseScrollingDeltas = hasPreciseScrollingDeltas;
   1119 
   1120     if (continuous) {
   1121         event.wheelTicksX /= scrollbarPixelsPerTick;
   1122         event.wheelTicksY /= scrollbarPixelsPerTick;
   1123     } else {
   1124         event.deltaX *= scrollbarPixelsPerTick;
   1125         event.deltaY *= scrollbarPixelsPerTick;
   1126     }
   1127     webview()->handleInputEvent(event);
   1128 }
   1129 
   1130 void EventSender::touchEnd(const CppArgumentList&, CppVariant* result)
   1131 {
   1132     result->setNull();
   1133     sendCurrentTouchEvent(WebInputEvent::TouchEnd);
   1134 }
   1135 
   1136 void EventSender::touchMove(const CppArgumentList&, CppVariant* result)
   1137 {
   1138     result->setNull();
   1139     sendCurrentTouchEvent(WebInputEvent::TouchMove);
   1140 }
   1141 
   1142 void EventSender::touchStart(const CppArgumentList&, CppVariant* result)
   1143 {
   1144     result->setNull();
   1145     sendCurrentTouchEvent(WebInputEvent::TouchStart);
   1146 }
   1147 
   1148 void EventSender::touchCancel(const CppArgumentList&, CppVariant* result)
   1149 {
   1150     result->setNull();
   1151     sendCurrentTouchEvent(WebInputEvent::TouchCancel);
   1152 }
   1153 
   1154 void EventSender::gestureScrollBegin(const CppArgumentList& arguments, CppVariant* result)
   1155 {
   1156     result->setNull();
   1157     gestureEvent(WebInputEvent::GestureScrollBegin, arguments);
   1158 }
   1159 
   1160 void EventSender::gestureScrollEnd(const CppArgumentList& arguments, CppVariant* result)
   1161 {
   1162     result->setNull();
   1163     gestureEvent(WebInputEvent::GestureScrollEnd, arguments);
   1164 }
   1165 
   1166 void EventSender::gestureScrollUpdate(const CppArgumentList& arguments, CppVariant* result)
   1167 {
   1168     result->setNull();
   1169     gestureEvent(WebInputEvent::GestureScrollUpdate, arguments);
   1170 }
   1171 
   1172 void EventSender::gestureScrollUpdateWithoutPropagation(const CppArgumentList& arguments, CppVariant* result)
   1173 {
   1174     result->setNull();
   1175     gestureEvent(WebInputEvent::GestureScrollUpdateWithoutPropagation, arguments);
   1176 }
   1177 
   1178 void EventSender::gestureTap(const CppArgumentList& arguments, CppVariant* result)
   1179 {
   1180     result->setNull();
   1181     gestureEvent(WebInputEvent::GestureTap, arguments);
   1182 }
   1183 
   1184 void EventSender::gestureTapDown(const CppArgumentList& arguments, CppVariant* result)
   1185 {
   1186     result->setNull();
   1187     gestureEvent(WebInputEvent::GestureTapDown, arguments);
   1188 }
   1189 
   1190 void EventSender::gestureTapCancel(const CppArgumentList& arguments, CppVariant* result)
   1191 {
   1192     result->setNull();
   1193     gestureEvent(WebInputEvent::GestureTapCancel, arguments);
   1194 }
   1195 
   1196 void EventSender::gestureLongPress(const CppArgumentList& arguments, CppVariant* result)
   1197 {
   1198     result->setNull();
   1199     gestureEvent(WebInputEvent::GestureLongPress, arguments);
   1200 }
   1201 
   1202 void EventSender::gestureLongTap(const CppArgumentList& arguments, CppVariant* result)
   1203 {
   1204     result->setNull();
   1205     gestureEvent(WebInputEvent::GestureLongTap, arguments);
   1206 }
   1207 
   1208 void EventSender::gestureTwoFingerTap(const CppArgumentList& arguments, CppVariant* result)
   1209 {
   1210     result->setNull();
   1211     gestureEvent(WebInputEvent::GestureTwoFingerTap, arguments);
   1212 }
   1213 
   1214 void EventSender::gestureScrollFirstPoint(const CppArgumentList& arguments, CppVariant* result)
   1215 {
   1216     result->setNull();
   1217     if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
   1218         return;
   1219 
   1220     WebPoint point(arguments[0].toInt32(), arguments[1].toInt32());
   1221     m_currentGestureLocation = point;
   1222 }
   1223 
   1224 void EventSender::gestureEvent(WebInputEvent::Type type, const CppArgumentList& arguments)
   1225 {
   1226     if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
   1227         return;
   1228 
   1229     WebPoint point(arguments[0].toInt32(), arguments[1].toInt32());
   1230 
   1231     WebGestureEvent event;
   1232     event.type = type;
   1233 
   1234     switch (type) {
   1235     case WebInputEvent::GestureScrollUpdate:
   1236     case WebInputEvent::GestureScrollUpdateWithoutPropagation:
   1237         event.data.scrollUpdate.deltaX = static_cast<float>(arguments[0].toDouble());
   1238         event.data.scrollUpdate.deltaY = static_cast<float>(arguments[1].toDouble());
   1239         event.x = m_currentGestureLocation.x;
   1240         event.y = m_currentGestureLocation.y;
   1241         m_currentGestureLocation.x = m_currentGestureLocation.x + event.data.scrollUpdate.deltaX;
   1242         m_currentGestureLocation.y = m_currentGestureLocation.y + event.data.scrollUpdate.deltaY;
   1243         break;
   1244 
   1245     case WebInputEvent::GestureScrollBegin:
   1246         m_currentGestureLocation = WebPoint(point.x, point.y);
   1247         event.x = m_currentGestureLocation.x;
   1248         event.y = m_currentGestureLocation.y;
   1249         break;
   1250     case WebInputEvent::GestureScrollEnd:
   1251         event.x = m_currentGestureLocation.x;
   1252         event.y = m_currentGestureLocation.y;
   1253         break;
   1254     case WebInputEvent::GestureTap:
   1255         if (arguments.size() >= 3)
   1256             event.data.tap.tapCount = static_cast<float>(arguments[2].toDouble());
   1257         else
   1258           event.data.tap.tapCount = 1;
   1259         event.x = point.x;
   1260         event.y = point.y;
   1261         break;
   1262     case WebInputEvent::GestureTapUnconfirmed:
   1263         if (arguments.size() >= 3)
   1264             event.data.tap.tapCount = static_cast<float>(arguments[2].toDouble());
   1265         else
   1266           event.data.tap.tapCount = 1;
   1267         event.x = point.x;
   1268         event.y = point.y;
   1269         break;
   1270     case WebInputEvent::GestureTapDown:
   1271         event.x = point.x;
   1272         event.y = point.y;
   1273         if (arguments.size() >= 4) {
   1274             event.data.tapDown.width = static_cast<float>(arguments[2].toDouble());
   1275             event.data.tapDown.height = static_cast<float>(arguments[3].toDouble());
   1276         }
   1277         break;
   1278     case WebInputEvent::GestureTapCancel:
   1279         event.x = point.x;
   1280         event.y = point.y;
   1281         break;
   1282     case WebInputEvent::GestureLongPress:
   1283         event.x = point.x;
   1284         event.y = point.y;
   1285         if (arguments.size() >= 4) {
   1286             event.data.longPress.width = static_cast<float>(arguments[2].toDouble());
   1287             event.data.longPress.height = static_cast<float>(arguments[3].toDouble());
   1288         }
   1289         break;
   1290     case WebInputEvent::GestureLongTap:
   1291         event.x = point.x;
   1292         event.y = point.y;
   1293         if (arguments.size() >= 4) {
   1294             event.data.longPress.width = static_cast<float>(arguments[2].toDouble());
   1295             event.data.longPress.height = static_cast<float>(arguments[3].toDouble());
   1296         }
   1297         break;
   1298     case WebInputEvent::GestureTwoFingerTap:
   1299         event.x = point.x;
   1300         event.y = point.y;
   1301         if (arguments.size() >= 4) {
   1302             event.data.twoFingerTap.firstFingerWidth = static_cast<float>(arguments[2].toDouble());
   1303             event.data.twoFingerTap.firstFingerHeight = static_cast<float>(arguments[3].toDouble());
   1304         }
   1305         break;
   1306     default:
   1307         WEBKIT_ASSERT_NOT_REACHED();
   1308     }
   1309 
   1310     event.globalX = event.x;
   1311     event.globalY = event.y;
   1312     event.timeStampSeconds = getCurrentEventTimeSec(m_delegate);
   1313 
   1314     if (shouldForceLayoutOnEvents())
   1315         webview()->layout();
   1316 
   1317     webview()->handleInputEvent(event);
   1318 
   1319     // Long press might start a drag drop session. Complete it if so.
   1320     if (type == WebInputEvent::GestureLongPress && !currentDragData.isNull()) {
   1321         WebMouseEvent mouseEvent;
   1322         initMouseEvent(WebInputEvent::MouseDown, pressedButton, point, &mouseEvent, getCurrentEventTimeSec(m_delegate));
   1323         finishDragAndDrop(mouseEvent, WebKit::WebDragOperationNone);
   1324     }
   1325 }
   1326 
   1327 void EventSender::gestureFlingCancel(const CppArgumentList&, CppVariant* result)
   1328 {
   1329     result->setNull();
   1330 
   1331     WebGestureEvent event;
   1332     event.type = WebInputEvent::GestureFlingCancel;
   1333     event.timeStampSeconds = getCurrentEventTimeSec(m_delegate);
   1334 
   1335     if (shouldForceLayoutOnEvents())
   1336         webview()->layout();
   1337 
   1338     webview()->handleInputEvent(event);
   1339 }
   1340 
   1341 void EventSender::gestureFlingStart(const CppArgumentList& arguments, CppVariant* result)
   1342 {
   1343     result->setNull();
   1344     if (arguments.size() < 4)
   1345         return;
   1346 
   1347     for (int i = 0; i < 4; i++)
   1348         if (!arguments[i].isNumber())
   1349             return;
   1350 
   1351     WebGestureEvent event;
   1352     event.type = WebInputEvent::GestureFlingStart;
   1353 
   1354     event.x = static_cast<float>(arguments[0].toDouble());
   1355     event.y = static_cast<float>(arguments[1].toDouble());
   1356     event.globalX = event.x;
   1357     event.globalY = event.y;
   1358 
   1359     event.data.flingStart.velocityX = static_cast<float>(arguments[2].toDouble());
   1360     event.data.flingStart.velocityY = static_cast<float>(arguments[3].toDouble());
   1361     event.timeStampSeconds = getCurrentEventTimeSec(m_delegate);
   1362 
   1363     if (shouldForceLayoutOnEvents())
   1364         webview()->layout();
   1365 
   1366     webview()->handleInputEvent(event);
   1367 }
   1368 
   1369 //
   1370 // Unimplemented stubs
   1371 //
   1372 
   1373 void EventSender::enableDOMUIEventLogging(const CppArgumentList&, CppVariant* result)
   1374 {
   1375     result->setNull();
   1376 }
   1377 
   1378 void EventSender::fireKeyboardEventsToElement(const CppArgumentList&, CppVariant* result)
   1379 {
   1380     result->setNull();
   1381 }
   1382 
   1383 void EventSender::clearKillRing(const CppArgumentList&, CppVariant* result)
   1384 {
   1385     result->setNull();
   1386 }
   1387 
   1388 }
   1389