2 * Copyright (C) 2010 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
31 // This file contains the definition for EventSender.
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.
44 #include "EventSender.h"
46 #include "TestShell.h"
47 #include "WebContextMenuData.h"
48 #include "WebDragData.h"
49 #include "WebDragOperation.h"
51 #include "WebString.h"
52 #include "WebTouchPoint.h"
54 #include "webkit/support/webkit_support.h"
55 #include <wtf/Deque.h>
56 #include <wtf/StringExtras.h>
59 #include "win/WebInputEventFactory.h"
62 // FIXME: layout before each event?
65 using namespace WebKit;
67 WebPoint EventSender::lastMousePos;
68 WebMouseEvent::Button EventSender::pressedButton = WebMouseEvent::ButtonNone;
69 WebMouseEvent::Button EventSender::lastButtonType = WebMouseEvent::ButtonNone;
80 WebMouseEvent::Button buttonType; // For MouseUp.
81 WebPoint pos; // For MouseMove.
82 int milliseconds; // For LeapForward.
86 , buttonType(WebMouseEvent::ButtonNone)
90 static WebDragData currentDragData;
91 static WebDragOperation currentDragEffect;
92 static WebDragOperationsMask currentDragEffectsAllowed;
93 static bool replayingSavedEvents = false;
94 static Deque<SavedEvent> mouseEventQueue;
95 static int touchModifiers;
96 static Vector<WebTouchPoint> touchPoints;
98 // Time and place of the last mouse up event.
99 static double lastClickTimeSec = 0;
100 static WebPoint lastClickPos;
101 static int clickCount = 0;
103 // maximum distance (in space and time) for a mouse click
104 // to register as a double or triple click
105 static const double multipleClickTimeSec = 1;
106 static const int multipleClickRadiusPixels = 5;
108 // How much we should scroll per event - the value here is chosen to
109 // match the WebKit impl and layout test results.
110 static const float scrollbarPixelsPerTick = 40.0f;
112 inline bool outsideMultiClickRadius(const WebPoint& a, const WebPoint& b)
114 return ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)) >
115 multipleClickRadiusPixels * multipleClickRadiusPixels;
118 // Used to offset the time the event hander things an event happened. This is
119 // done so tests can run without a delay, but bypass checks that are time
120 // dependent (e.g., dragging has a timeout vs selection).
121 static uint32 timeOffsetMs = 0;
123 static double getCurrentEventTimeSec()
125 return (webkit_support::GetCurrentTimeInMillisecond() + timeOffsetMs) / 1000.0;
128 static void advanceEventTime(int32_t deltaMs)
130 timeOffsetMs += deltaMs;
133 static void initMouseEvent(WebInputEvent::Type t, WebMouseEvent::Button b,
134 const WebPoint& pos, WebMouseEvent* e)
143 e->timeStampSeconds = getCurrentEventTimeSec();
144 e->clickCount = clickCount;
147 // Returns true if the specified key is the system key.
148 static bool applyKeyModifier(const string& modifierName, WebInputEvent* event)
150 bool isSystemKey = false;
151 const char* characters = modifierName.c_str();
152 if (!strcmp(characters, "ctrlKey")
154 || !strcmp(characters, "addSelectionKey")
157 event->modifiers |= WebInputEvent::ControlKey;
158 } else if (!strcmp(characters, "shiftKey") || !strcmp(characters, "rangeSelectionKey"))
159 event->modifiers |= WebInputEvent::ShiftKey;
160 else if (!strcmp(characters, "altKey")) {
161 event->modifiers |= WebInputEvent::AltKey;
163 // On Windows all keys with Alt modifier will be marked as system key.
164 // We keep the same behavior on Linux and everywhere non-Mac, see:
165 // WebKit/chromium/src/gtk/WebInputEventFactory.cpp
166 // If we want to change this behavior on Linux, this piece of code must be
167 // kept in sync with the related code in above file.
171 } else if (!strcmp(characters, "metaKey") || !strcmp(characters, "addSelectionKey")) {
172 event->modifiers |= WebInputEvent::MetaKey;
173 // On Mac only command key presses are marked as system key.
174 // See the related code in: WebKit/chromium/src/mac/WebInputEventFactory.cpp
175 // It must be kept in sync with the related code in above file.
178 } else if (!strcmp(characters, "metaKey")) {
179 event->modifiers |= WebInputEvent::MetaKey;
185 static bool applyKeyModifiers(const CppVariant* argument, WebInputEvent* event)
187 bool isSystemKey = false;
188 if (argument->isObject()) {
189 Vector<string> modifiers = argument->toStringVector();
190 for (Vector<string>::const_iterator i = modifiers.begin(); i != modifiers.end(); ++i)
191 isSystemKey |= applyKeyModifier(*i, event);
192 } else if (argument->isString())
193 isSystemKey = applyKeyModifier(argument->toString(), event);
197 // Get the edit command corresponding to a keyboard event.
198 // Returns true if the specified event corresponds to an edit command, the name
199 // of the edit command will be stored in |*name|.
200 bool getEditCommand(const WebKeyboardEvent& event, string* name)
203 // We only cares about Left,Right,Up,Down keys with Command or Command+Shift
204 // modifiers. These key events correspond to some special movement and
205 // selection editor commands, and was supposed to be handled in
206 // WebKit/chromium/src/EditorClientImpl.cpp. But these keys will be marked
207 // as system key, which prevents them from being handled. Thus they must be
208 // handled specially.
209 if ((event.modifiers & ~WebKeyboardEvent::ShiftKey) != WebKeyboardEvent::MetaKey)
212 switch (event.windowsKeyCode) {
213 case webkit_support::VKEY_LEFT:
214 *name = "MoveToBeginningOfLine";
216 case webkit_support::VKEY_RIGHT:
217 *name = "MoveToEndOfLine";
219 case webkit_support::VKEY_UP:
220 *name = "MoveToBeginningOfDocument";
222 case webkit_support::VKEY_DOWN:
223 *name = "MoveToEndOfDocument";
229 if (event.modifiers & WebKeyboardEvent::ShiftKey)
230 name->append("AndModifySelection");
238 // Key event location code introduced in DOM Level 3.
239 // See also: http://www.w3.org/TR/DOM-Level-3-Events/#events-keyboardevents
240 enum KeyLocationCode {
241 DOMKeyLocationStandard = 0x00,
242 DOMKeyLocationLeft = 0x01,
243 DOMKeyLocationRight = 0x02,
244 DOMKeyLocationNumpad = 0x03
247 EventSender::EventSender(TestShell* shell)
250 // Initialize the map that associates methods of this class with the names
251 // they will use when called by JavaScript. The actual binding of those
252 // names to their methods will be done by calling bindToJavaScript() (defined
253 // by CppBoundClass, the parent to EventSender).
254 bindMethod("addTouchPoint", &EventSender::addTouchPoint);
255 bindMethod("beginDragWithFiles", &EventSender::beginDragWithFiles);
256 bindMethod("cancelTouchPoint", &EventSender::cancelTouchPoint);
257 bindMethod("clearKillRing", &EventSender::clearKillRing);
258 bindMethod("clearTouchPoints", &EventSender::clearTouchPoints);
259 bindMethod("contextClick", &EventSender::contextClick);
260 bindMethod("continuousMouseScrollBy", &EventSender::continuousMouseScrollBy);
261 bindMethod("dispatchMessage", &EventSender::dispatchMessage);
262 bindMethod("dumpFilenameBeingDragged", &EventSender::dumpFilenameBeingDragged);
263 bindMethod("enableDOMUIEventLogging", &EventSender::enableDOMUIEventLogging);
264 bindMethod("fireKeyboardEventsToElement", &EventSender::fireKeyboardEventsToElement);
265 bindMethod("keyDown", &EventSender::keyDown);
266 bindMethod("leapForward", &EventSender::leapForward);
267 bindMethod("mouseDown", &EventSender::mouseDown);
268 bindMethod("mouseMoveTo", &EventSender::mouseMoveTo);
269 bindMethod("mouseScrollBy", &EventSender::mouseScrollBy);
270 bindMethod("mouseUp", &EventSender::mouseUp);
271 bindMethod("releaseTouchPoint", &EventSender::releaseTouchPoint);
272 bindMethod("scheduleAsynchronousClick", &EventSender::scheduleAsynchronousClick);
273 bindMethod("setTouchModifier", &EventSender::setTouchModifier);
274 bindMethod("textZoomIn", &EventSender::textZoomIn);
275 bindMethod("textZoomOut", &EventSender::textZoomOut);
276 bindMethod("touchCancel", &EventSender::touchCancel);
277 bindMethod("touchEnd", &EventSender::touchEnd);
278 bindMethod("touchMove", &EventSender::touchMove);
279 bindMethod("touchStart", &EventSender::touchStart);
280 bindMethod("updateTouchPoint", &EventSender::updateTouchPoint);
281 bindMethod("gestureScrollBegin", &EventSender::gestureScrollBegin);
282 bindMethod("gestureScrollEnd", &EventSender::gestureScrollEnd);
283 bindMethod("gestureTap", &EventSender::gestureTap);
284 bindMethod("zoomPageIn", &EventSender::zoomPageIn);
285 bindMethod("zoomPageOut", &EventSender::zoomPageOut);
286 bindMethod("scalePageBy", &EventSender::scalePageBy);
288 // When set to true (the default value), we batch mouse move and mouse up
289 // events so we can simulate drag & drop.
290 bindProperty("dragMode", &dragMode);
292 bindProperty("WM_KEYDOWN", &wmKeyDown);
293 bindProperty("WM_KEYUP", &wmKeyUp);
294 bindProperty("WM_CHAR", &wmChar);
295 bindProperty("WM_DEADCHAR", &wmDeadChar);
296 bindProperty("WM_SYSKEYDOWN", &wmSysKeyDown);
297 bindProperty("WM_SYSKEYUP", &wmSysKeyUp);
298 bindProperty("WM_SYSCHAR", &wmSysChar);
299 bindProperty("WM_SYSDEADCHAR", &wmSysDeadChar);
303 void EventSender::reset()
305 // The test should have finished a drag and the mouse button state.
306 ASSERT(currentDragData.isNull());
307 currentDragData.reset();
308 currentDragEffect = WebKit::WebDragOperationNone;
309 currentDragEffectsAllowed = WebKit::WebDragOperationNone;
310 pressedButton = WebMouseEvent::ButtonNone;
313 wmKeyDown.set(WM_KEYDOWN);
314 wmKeyUp.set(WM_KEYUP);
316 wmDeadChar.set(WM_DEADCHAR);
317 wmSysKeyDown.set(WM_SYSKEYDOWN);
318 wmSysKeyUp.set(WM_SYSKEYUP);
319 wmSysChar.set(WM_SYSCHAR);
320 wmSysDeadChar.set(WM_SYSDEADCHAR);
322 lastMousePos = WebPoint(0, 0);
323 lastClickTimeSec = 0;
324 lastClickPos = WebPoint(0, 0);
326 lastButtonType = WebMouseEvent::ButtonNone;
330 m_taskList.revokeAll();
333 WebView* EventSender::webview()
335 return m_shell->webView();
338 void EventSender::doDragDrop(const WebDragData& dragData, WebDragOperationsMask mask)
341 initMouseEvent(WebInputEvent::MouseDown, pressedButton, lastMousePos, &event);
342 WebPoint clientPoint(event.x, event.y);
343 WebPoint screenPoint(event.globalX, event.globalY);
344 currentDragData = dragData;
345 currentDragEffectsAllowed = mask;
346 currentDragEffect = webview()->dragTargetDragEnter(dragData, clientPoint, screenPoint, currentDragEffectsAllowed);
348 // Finish processing events.
352 void EventSender::dumpFilenameBeingDragged(const CppArgumentList&, CppVariant*)
354 printf("Filename being dragged: %s\n", currentDragData.fileContentFilename().utf8().data());
357 WebMouseEvent::Button EventSender::getButtonTypeFromButtonNumber(int buttonCode)
360 return WebMouseEvent::ButtonLeft;
362 return WebMouseEvent::ButtonRight;
363 return WebMouseEvent::ButtonMiddle;
366 int EventSender::getButtonNumberFromSingleArg(const CppArgumentList& arguments)
369 if (arguments.size() > 0 && arguments[0].isNumber())
370 buttonCode = arguments[0].toInt32();
374 void EventSender::updateClickCountForButton(WebMouseEvent::Button buttonType)
376 if ((getCurrentEventTimeSec() - lastClickTimeSec < multipleClickTimeSec)
377 && (!outsideMultiClickRadius(lastMousePos, lastClickPos))
378 && (buttonType == lastButtonType))
382 lastButtonType = buttonType;
387 // Implemented javascript methods.
390 void EventSender::mouseDown(const CppArgumentList& arguments, CppVariant* result)
392 if (result) // Could be 0 if invoked asynchronously.
397 int buttonNumber = getButtonNumberFromSingleArg(arguments);
398 ASSERT(buttonNumber != -1);
400 WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
402 updateClickCountForButton(buttonType);
405 pressedButton = buttonType;
406 initMouseEvent(WebInputEvent::MouseDown, buttonType, lastMousePos, &event);
407 if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
408 applyKeyModifiers(&(arguments[1]), &event);
409 webview()->handleInputEvent(event);
412 void EventSender::mouseUp(const CppArgumentList& arguments, CppVariant* result)
414 if (result) // Could be 0 if invoked asynchronously.
419 int buttonNumber = getButtonNumberFromSingleArg(arguments);
420 ASSERT(buttonNumber != -1);
422 WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
424 if (isDragMode() && !replayingSavedEvents) {
425 SavedEvent savedEvent;
426 savedEvent.type = SavedEvent::MouseUp;
427 savedEvent.buttonType = buttonType;
428 mouseEventQueue.append(savedEvent);
432 initMouseEvent(WebInputEvent::MouseUp, buttonType, lastMousePos, &event);
433 if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
434 applyKeyModifiers(&(arguments[1]), &event);
439 void EventSender::doMouseUp(const WebMouseEvent& e)
441 webview()->handleInputEvent(e);
443 pressedButton = WebMouseEvent::ButtonNone;
444 lastClickTimeSec = e.timeStampSeconds;
445 lastClickPos = lastMousePos;
447 // If we're in a drag operation, complete it.
448 if (currentDragData.isNull())
450 WebPoint clientPoint(e.x, e.y);
451 WebPoint screenPoint(e.globalX, e.globalY);
453 currentDragEffect = webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed);
454 if (currentDragEffect)
455 webview()->dragTargetDrop(clientPoint, screenPoint);
457 webview()->dragTargetDragLeave();
458 webview()->dragSourceEndedAt(clientPoint, screenPoint, currentDragEffect);
459 webview()->dragSourceSystemDragEnded();
461 currentDragData.reset();
464 void EventSender::mouseMoveTo(const CppArgumentList& arguments, CppVariant* result)
468 if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
472 WebPoint mousePos(arguments[0].toInt32(), arguments[1].toInt32());
474 if (isDragMode() && pressedButton == WebMouseEvent::ButtonLeft && !replayingSavedEvents) {
475 SavedEvent savedEvent;
476 savedEvent.type = SavedEvent::MouseMove;
477 savedEvent.pos = mousePos;
478 mouseEventQueue.append(savedEvent);
481 initMouseEvent(WebInputEvent::MouseMove, pressedButton, mousePos, &event);
486 void EventSender::doMouseMove(const WebMouseEvent& e)
488 lastMousePos = WebPoint(e.x, e.y);
490 webview()->handleInputEvent(e);
492 if (pressedButton == WebMouseEvent::ButtonNone || currentDragData.isNull())
494 WebPoint clientPoint(e.x, e.y);
495 WebPoint screenPoint(e.globalX, e.globalY);
496 currentDragEffect = webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed);
499 void EventSender::keyDown(const CppArgumentList& arguments, CppVariant* result)
502 if (arguments.size() < 1 || !arguments[0].isString())
504 bool generateChar = false;
506 // FIXME: I'm not exactly sure how we should convert the string to a key
507 // event. This seems to work in the cases I tested.
508 // FIXME: Should we also generate a KEY_UP?
509 string codeStr = arguments[0].toString();
511 // Convert \n -> VK_RETURN. Some layout tests use \n to mean "Enter", when
512 // Windows uses \r for "Enter".
515 bool needsShiftKeyModifier = false;
516 if ("\n" == codeStr) {
518 text = code = webkit_support::VKEY_RETURN;
519 } else if ("rightArrow" == codeStr)
520 code = webkit_support::VKEY_RIGHT;
521 else if ("downArrow" == codeStr)
522 code = webkit_support::VKEY_DOWN;
523 else if ("leftArrow" == codeStr)
524 code = webkit_support::VKEY_LEFT;
525 else if ("upArrow" == codeStr)
526 code = webkit_support::VKEY_UP;
527 else if ("insert" == codeStr)
528 code = webkit_support::VKEY_INSERT;
529 else if ("delete" == codeStr)
530 code = webkit_support::VKEY_DELETE;
531 else if ("pageUp" == codeStr)
532 code = webkit_support::VKEY_PRIOR;
533 else if ("pageDown" == codeStr)
534 code = webkit_support::VKEY_NEXT;
535 else if ("home" == codeStr)
536 code = webkit_support::VKEY_HOME;
537 else if ("end" == codeStr)
538 code = webkit_support::VKEY_END;
539 else if ("printScreen" == codeStr)
540 code = webkit_support::VKEY_SNAPSHOT;
541 else if ("menu" == codeStr)
542 // FIXME: Change this to webkit_support::VKEY_APPS.
545 // Compare the input string with the function-key names defined by the
546 // DOM spec (i.e. "F1",...,"F24"). If the input string is a function-key
547 // name, set its key code.
548 for (int i = 1; i <= 24; ++i) {
549 char functionChars[10];
550 snprintf(functionChars, 10, "F%d", i);
551 string functionKeyName(functionChars);
552 if (functionKeyName == codeStr) {
553 code = webkit_support::VKEY_F1 + (i - 1);
558 WebString webCodeStr = WebString::fromUTF8(codeStr.data(), codeStr.size());
559 ASSERT(webCodeStr.length() == 1);
560 text = code = webCodeStr.data()[0];
561 needsShiftKeyModifier = needsShiftModifier(code);
562 if ((code & 0xFF) >= 'a' && (code & 0xFF) <= 'z')
568 // For one generated keyboard event, we need to generate a keyDown/keyUp
569 // pair; refer to EventSender.cpp in Tools/DumpRenderTree/win.
570 // On Windows, we might also need to generate a char event to mimic the
571 // Windows event flow; on other platforms we create a merged event and test
572 // the event flow that that platform provides.
573 WebKeyboardEvent eventDown, eventChar, eventUp;
574 eventDown.type = WebInputEvent::RawKeyDown;
575 eventDown.modifiers = 0;
576 eventDown.windowsKeyCode = code;
578 eventDown.nativeKeyCode = webkit_support::NativeKeyCodeForWindowsKeyCode(code, needsShiftKeyModifier);
582 eventDown.text[0] = text;
583 eventDown.unmodifiedText[0] = text;
585 eventDown.setKeyIdentifierFromWindowsKeyCode();
587 if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
588 eventDown.isSystemKey = applyKeyModifiers(&(arguments[1]), &eventDown);
590 if (needsShiftKeyModifier)
591 eventDown.modifiers |= WebInputEvent::ShiftKey;
593 // See if KeyLocation argument is given.
594 if (arguments.size() >= 3 && arguments[2].isNumber()) {
595 int location = arguments[2].toInt32();
596 if (location == DOMKeyLocationNumpad)
597 eventDown.modifiers |= WebInputEvent::IsKeyPad;
600 eventChar = eventUp = eventDown;
601 eventUp.type = WebInputEvent::KeyUp;
602 // EventSender.m forces a layout here, with at least one
603 // test (fast/forms/focus-control-to-page.html) relying on this.
606 // In the browser, if a keyboard event corresponds to an editor command,
607 // the command will be dispatched to the renderer just before dispatching
608 // the keyboard event, and then it will be executed in the
609 // RenderView::handleCurrentKeyboardEvent() method, which is called from
610 // third_party/WebKit/Source/WebKit/chromium/src/EditorClientImpl.cpp.
611 // We just simulate the same behavior here.
613 if (getEditCommand(eventDown, &editCommand))
614 m_shell->webViewHost()->setEditCommand(editCommand, "");
616 webview()->handleInputEvent(eventDown);
618 m_shell->webViewHost()->clearEditCommand();
621 eventChar.type = WebInputEvent::Char;
622 eventChar.keyIdentifier[0] = '\0';
623 webview()->handleInputEvent(eventChar);
626 webview()->handleInputEvent(eventUp);
629 void EventSender::dispatchMessage(const CppArgumentList& arguments, CppVariant* result)
634 if (arguments.size() == 3) {
635 // Grab the message id to see if we need to dispatch it.
636 int msg = arguments[0].toInt32();
638 // WebKit's version of this function stuffs a MSG struct and uses
639 // TranslateMessage and DispatchMessage. We use a WebKeyboardEvent, which
640 // doesn't need to receive the DeadChar and SysDeadChar messages.
641 if (msg == WM_DEADCHAR || msg == WM_SYSDEADCHAR)
646 unsigned long lparam = static_cast<unsigned long>(arguments[2].toDouble());
647 webview()->handleInputEvent(WebInputEventFactory::keyboardEvent(0, msg, arguments[1].toInt32(), lparam));
649 ASSERT_NOT_REACHED();
653 bool EventSender::needsShiftModifier(int keyCode)
655 // If code is an uppercase letter, assign a SHIFT key to
656 // eventDown.modifier, this logic comes from
657 // Tools/DumpRenderTree/win/EventSender.cpp
658 return (keyCode & 0xFF) >= 'A' && (keyCode & 0xFF) <= 'Z';
661 void EventSender::leapForward(const CppArgumentList& arguments, CppVariant* result)
665 if (arguments.size() < 1 || !arguments[0].isNumber())
668 int milliseconds = arguments[0].toInt32();
669 if (isDragMode() && pressedButton == WebMouseEvent::ButtonLeft && !replayingSavedEvents) {
670 SavedEvent savedEvent;
671 savedEvent.type = SavedEvent::LeapForward;
672 savedEvent.milliseconds = milliseconds;
673 mouseEventQueue.append(savedEvent);
675 doLeapForward(milliseconds);
678 void EventSender::doLeapForward(int milliseconds)
680 advanceEventTime(milliseconds);
683 // Apple's port of WebKit zooms by a factor of 1.2 (see
684 // WebKit/WebView/WebView.mm)
685 void EventSender::textZoomIn(const CppArgumentList&, CppVariant* result)
687 webview()->setZoomLevel(true, webview()->zoomLevel() + 1);
691 void EventSender::textZoomOut(const CppArgumentList&, CppVariant* result)
693 webview()->setZoomLevel(true, webview()->zoomLevel() - 1);
697 void EventSender::zoomPageIn(const CppArgumentList&, CppVariant* result)
699 webview()->setZoomLevel(false, webview()->zoomLevel() + 1);
703 void EventSender::zoomPageOut(const CppArgumentList&, CppVariant* result)
705 webview()->setZoomLevel(false, webview()->zoomLevel() - 1);
709 void EventSender::scalePageBy(const CppArgumentList& arguments, CppVariant* result)
711 if (arguments.size() < 3 || !arguments[0].isNumber() || !arguments[1].isNumber() || !arguments[2].isNumber())
714 float scaleFactor = static_cast<float>(arguments[0].toDouble());
715 int x = arguments[1].toInt32();
716 int y = arguments[2].toInt32();
717 webview()->scalePage(scaleFactor, WebPoint(x, y));
721 void EventSender::mouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
723 handleMouseWheel(arguments, result, false);
726 void EventSender::continuousMouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
728 handleMouseWheel(arguments, result, true);
731 void EventSender::replaySavedEvents()
733 replayingSavedEvents = true;
734 while (!mouseEventQueue.isEmpty()) {
735 SavedEvent e = mouseEventQueue.takeFirst();
738 case SavedEvent::MouseMove: {
740 initMouseEvent(WebInputEvent::MouseMove, pressedButton, e.pos, &event);
744 case SavedEvent::LeapForward:
745 doLeapForward(e.milliseconds);
747 case SavedEvent::MouseUp: {
749 initMouseEvent(WebInputEvent::MouseUp, e.buttonType, lastMousePos, &event);
754 ASSERT_NOT_REACHED();
758 replayingSavedEvents = false;
761 // Because actual context menu is implemented by the browser side,
762 // this function does only what LayoutTests are expecting:
763 // - Many test checks the count of items. So returning non-zero value makes sense.
764 // - Some test compares the count before and after some action. So changing the count based on flags
765 // also makes sense. This function is doing such for some flags.
766 // - Some test even checks actual string content. So providing it would be also helpful.
768 static Vector<WebString> makeMenuItemStringsFor(WebContextMenuData* contextMenu, MockSpellCheck* spellcheck)
770 // These constants are based on Safari's context menu because tests are made for it.
771 static const char* nonEditableMenuStrings[] = { "Back", "Reload Page", "Open in Dashbaord", "<separator>", "View Source", "Save Page As", "Print Page", "Inspect Element", 0 };
772 static const char* editableMenuStrings[] = { "Cut", "Copy", "<separator>", "Paste", "Spelling and Grammar", "Substitutions, Transformations", "Font", "Speech", "Paragraph Direction", "<separator>", 0 };
774 // This is possible because mouse events are cancelleable.
776 return Vector<WebString>();
778 Vector<WebString> strings;
780 if (contextMenu->isEditable) {
781 for (const char** item = editableMenuStrings; *item; ++item)
782 strings.append(WebString::fromUTF8(*item));
783 Vector<WebString> suggestions;
784 spellcheck->fillSuggestionList(contextMenu->misspelledWord, &suggestions);
785 for (size_t i = 0; i < suggestions.size(); ++i)
786 strings.append(suggestions[i]);
788 for (const char** item = nonEditableMenuStrings; *item; ++item)
789 strings.append(WebString::fromUTF8(*item));
796 void EventSender::contextClick(const CppArgumentList& arguments, CppVariant* result)
800 updateClickCountForButton(WebMouseEvent::ButtonRight);
802 // Clears last context menu data because we need to know if the context menu be requested
803 // after following mouse events.
804 m_shell->webViewHost()->clearContextMenuData();
806 // Generate right mouse down and up.
808 pressedButton = WebMouseEvent::ButtonRight;
809 initMouseEvent(WebInputEvent::MouseDown, WebMouseEvent::ButtonRight, lastMousePos, &event);
810 webview()->handleInputEvent(event);
812 initMouseEvent(WebInputEvent::MouseUp, WebMouseEvent::ButtonRight, lastMousePos, &event);
813 webview()->handleInputEvent(event);
815 pressedButton = WebMouseEvent::ButtonNone;
817 WebContextMenuData* lastContextMenu = m_shell->webViewHost()->lastContextMenuData();
818 result->set(WebBindings::makeStringArray(makeMenuItemStringsFor(lastContextMenu, m_shell->webViewHost()->mockSpellCheck())));
821 class MouseDownTask: public MethodTask<EventSender> {
823 MouseDownTask(EventSender* obj, const CppArgumentList& arg)
824 : MethodTask<EventSender>(obj), m_arguments(arg) { }
825 virtual void runIfValid() { m_object->mouseDown(m_arguments, 0); }
828 CppArgumentList m_arguments;
831 class MouseUpTask: public MethodTask<EventSender> {
833 MouseUpTask(EventSender* obj, const CppArgumentList& arg)
834 : MethodTask<EventSender>(obj), m_arguments(arg) { }
835 virtual void runIfValid() { m_object->mouseUp(m_arguments, 0); }
838 CppArgumentList m_arguments;
841 void EventSender::scheduleAsynchronousClick(const CppArgumentList& arguments, CppVariant* result)
844 postTask(new MouseDownTask(this, arguments));
845 postTask(new MouseUpTask(this, arguments));
848 void EventSender::beginDragWithFiles(const CppArgumentList& arguments, CppVariant* result)
850 currentDragData.initialize();
851 Vector<string> files = arguments[0].toStringVector();
852 for (size_t i = 0; i < files.size(); ++i)
853 currentDragData.appendToFilenames(webkit_support::GetAbsoluteWebStringFromUTF8Path(files[i]));
854 currentDragEffectsAllowed = WebKit::WebDragOperationCopy;
856 // Provide a drag source.
857 webview()->dragTargetDragEnter(currentDragData, lastMousePos, lastMousePos, currentDragEffectsAllowed);
859 // dragMode saves events and then replays them later. We don't need/want that.
862 // Make the rest of eventSender think a drag is in progress.
863 pressedButton = WebMouseEvent::ButtonLeft;
868 void EventSender::addTouchPoint(const CppArgumentList& arguments, CppVariant* result)
872 WebTouchPoint touchPoint;
873 touchPoint.state = WebTouchPoint::StatePressed;
874 touchPoint.position = WebPoint(arguments[0].toInt32(), arguments[1].toInt32());
875 touchPoint.screenPosition = touchPoint.position;
878 for (size_t i = 0; i < touchPoints.size(); i++) {
879 if (touchPoints[i].id == lowestId)
882 touchPoint.id = lowestId;
883 touchPoints.append(touchPoint);
886 void EventSender::clearTouchPoints(const CppArgumentList&, CppVariant* result)
892 void EventSender::releaseTouchPoint(const CppArgumentList& arguments, CppVariant* result)
896 const unsigned index = arguments[0].toInt32();
897 ASSERT(index < touchPoints.size());
899 WebTouchPoint* touchPoint = &touchPoints[index];
900 touchPoint->state = WebTouchPoint::StateReleased;
903 void EventSender::setTouchModifier(const CppArgumentList& arguments, CppVariant* result)
908 const string keyName = arguments[0].toString();
909 if (keyName == "shift")
910 mask = WebInputEvent::ShiftKey;
911 else if (keyName == "alt")
912 mask = WebInputEvent::AltKey;
913 else if (keyName == "ctrl")
914 mask = WebInputEvent::ControlKey;
915 else if (keyName == "meta")
916 mask = WebInputEvent::MetaKey;
918 if (arguments[1].toBoolean())
919 touchModifiers |= mask;
921 touchModifiers &= ~mask;
924 void EventSender::updateTouchPoint(const CppArgumentList& arguments, CppVariant* result)
928 const unsigned index = arguments[0].toInt32();
929 ASSERT(index < touchPoints.size());
931 WebPoint position(arguments[1].toInt32(), arguments[2].toInt32());
932 WebTouchPoint* touchPoint = &touchPoints[index];
933 touchPoint->state = WebTouchPoint::StateMoved;
934 touchPoint->position = position;
935 touchPoint->screenPosition = position;
938 void EventSender::cancelTouchPoint(const CppArgumentList& arguments, CppVariant* result)
942 const unsigned index = arguments[0].toInt32();
943 ASSERT(index < touchPoints.size());
945 WebTouchPoint* touchPoint = &touchPoints[index];
946 touchPoint->state = WebTouchPoint::StateCancelled;
949 void EventSender::sendCurrentTouchEvent(const WebInputEvent::Type type)
951 ASSERT(static_cast<unsigned>(WebTouchEvent::touchesLengthCap) > touchPoints.size());
954 WebTouchEvent touchEvent;
955 touchEvent.type = type;
956 touchEvent.modifiers = touchModifiers;
957 touchEvent.timeStampSeconds = getCurrentEventTimeSec();
958 touchEvent.touchesLength = touchPoints.size();
959 for (unsigned i = 0; i < touchPoints.size(); ++i)
960 touchEvent.touches[i] = touchPoints[i];
961 webview()->handleInputEvent(touchEvent);
963 for (unsigned i = 0; i < touchPoints.size(); ++i) {
964 WebTouchPoint* touchPoint = &touchPoints[i];
965 if (touchPoint->state == WebTouchPoint::StateReleased) {
966 touchPoints.remove(i);
969 touchPoint->state = WebTouchPoint::StateStationary;
973 void EventSender::handleMouseWheel(const CppArgumentList& arguments, CppVariant* result, bool continuous)
977 if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
980 // Force a layout here just to make sure every position has been
981 // determined before we send events (as well as all the other methods
982 // that send an event do).
985 int horizontal = arguments[0].toInt32();
986 int vertical = arguments[1].toInt32();
988 WebMouseWheelEvent event;
989 initMouseEvent(WebInputEvent::MouseWheel, pressedButton, lastMousePos, &event);
990 event.wheelTicksX = static_cast<float>(horizontal);
991 event.wheelTicksY = static_cast<float>(vertical);
992 event.deltaX = event.wheelTicksX;
993 event.deltaY = event.wheelTicksY;
995 event.wheelTicksX /= scrollbarPixelsPerTick;
996 event.wheelTicksY /= scrollbarPixelsPerTick;
998 event.deltaX *= scrollbarPixelsPerTick;
999 event.deltaY *= scrollbarPixelsPerTick;
1001 webview()->handleInputEvent(event);
1004 void EventSender::touchEnd(const CppArgumentList&, CppVariant* result)
1007 sendCurrentTouchEvent(WebInputEvent::TouchEnd);
1010 void EventSender::touchMove(const CppArgumentList&, CppVariant* result)
1013 sendCurrentTouchEvent(WebInputEvent::TouchMove);
1016 void EventSender::touchStart(const CppArgumentList&, CppVariant* result)
1019 sendCurrentTouchEvent(WebInputEvent::TouchStart);
1022 void EventSender::touchCancel(const CppArgumentList&, CppVariant* result)
1025 sendCurrentTouchEvent(WebInputEvent::TouchCancel);
1028 void EventSender::gestureScrollBegin(const CppArgumentList& arguments, CppVariant* result)
1031 gestureEvent(WebInputEvent::GestureScrollBegin, arguments);
1034 void EventSender::gestureScrollEnd(const CppArgumentList& arguments, CppVariant* result)
1037 gestureEvent(WebInputEvent::GestureScrollEnd, arguments);
1040 void EventSender::gestureTap(const CppArgumentList& arguments, CppVariant* result)
1043 gestureEvent(WebInputEvent::GestureTap, arguments);
1046 void EventSender::gestureEvent(WebInputEvent::Type type, const CppArgumentList& arguments)
1048 if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
1051 WebPoint point(arguments[0].toInt32(), arguments[1].toInt32());
1053 WebGestureEvent event;
1057 event.globalX = point.x;
1058 event.globalY = point.y;
1059 event.timeStampSeconds = getCurrentEventTimeSec();
1060 webview()->handleInputEvent(event);
1064 // Unimplemented stubs
1067 void EventSender::enableDOMUIEventLogging(const CppArgumentList&, CppVariant* result)
1072 void EventSender::fireKeyboardEventsToElement(const CppArgumentList&, CppVariant* result)
1077 void EventSender::clearKillRing(const CppArgumentList&, CppVariant* result)