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("zoomPageIn", &EventSender::zoomPageIn);
282 bindMethod("zoomPageOut", &EventSender::zoomPageOut);
283 bindMethod("scalePageBy", &EventSender::scalePageBy);
285 // When set to true (the default value), we batch mouse move and mouse up
286 // events so we can simulate drag & drop.
287 bindProperty("dragMode", &dragMode);
289 bindProperty("WM_KEYDOWN", &wmKeyDown);
290 bindProperty("WM_KEYUP", &wmKeyUp);
291 bindProperty("WM_CHAR", &wmChar);
292 bindProperty("WM_DEADCHAR", &wmDeadChar);
293 bindProperty("WM_SYSKEYDOWN", &wmSysKeyDown);
294 bindProperty("WM_SYSKEYUP", &wmSysKeyUp);
295 bindProperty("WM_SYSCHAR", &wmSysChar);
296 bindProperty("WM_SYSDEADCHAR", &wmSysDeadChar);
300 void EventSender::reset()
302 // The test should have finished a drag and the mouse button state.
303 ASSERT(currentDragData.isNull());
304 currentDragData.reset();
305 currentDragEffect = WebKit::WebDragOperationNone;
306 currentDragEffectsAllowed = WebKit::WebDragOperationNone;
307 pressedButton = WebMouseEvent::ButtonNone;
310 wmKeyDown.set(WM_KEYDOWN);
311 wmKeyUp.set(WM_KEYUP);
313 wmDeadChar.set(WM_DEADCHAR);
314 wmSysKeyDown.set(WM_SYSKEYDOWN);
315 wmSysKeyUp.set(WM_SYSKEYUP);
316 wmSysChar.set(WM_SYSCHAR);
317 wmSysDeadChar.set(WM_SYSDEADCHAR);
319 lastMousePos = WebPoint(0, 0);
320 lastClickTimeSec = 0;
321 lastClickPos = WebPoint(0, 0);
323 lastButtonType = WebMouseEvent::ButtonNone;
327 m_taskList.revokeAll();
330 WebView* EventSender::webview()
332 return m_shell->webView();
335 void EventSender::doDragDrop(const WebDragData& dragData, WebDragOperationsMask mask)
338 initMouseEvent(WebInputEvent::MouseDown, pressedButton, lastMousePos, &event);
339 WebPoint clientPoint(event.x, event.y);
340 WebPoint screenPoint(event.globalX, event.globalY);
341 currentDragData = dragData;
342 currentDragEffectsAllowed = mask;
343 currentDragEffect = webview()->dragTargetDragEnter(dragData, clientPoint, screenPoint, currentDragEffectsAllowed);
345 // Finish processing events.
349 void EventSender::dumpFilenameBeingDragged(const CppArgumentList&, CppVariant*)
351 printf("Filename being dragged: %s\n", currentDragData.fileContentFilename().utf8().data());
354 WebMouseEvent::Button EventSender::getButtonTypeFromButtonNumber(int buttonCode)
357 return WebMouseEvent::ButtonLeft;
359 return WebMouseEvent::ButtonRight;
360 return WebMouseEvent::ButtonMiddle;
363 int EventSender::getButtonNumberFromSingleArg(const CppArgumentList& arguments)
366 if (arguments.size() > 0 && arguments[0].isNumber())
367 buttonCode = arguments[0].toInt32();
371 void EventSender::updateClickCountForButton(WebMouseEvent::Button buttonType)
373 if ((getCurrentEventTimeSec() - lastClickTimeSec < multipleClickTimeSec)
374 && (!outsideMultiClickRadius(lastMousePos, lastClickPos))
375 && (buttonType == lastButtonType))
379 lastButtonType = buttonType;
384 // Implemented javascript methods.
387 void EventSender::mouseDown(const CppArgumentList& arguments, CppVariant* result)
389 if (result) // Could be 0 if invoked asynchronously.
394 int buttonNumber = getButtonNumberFromSingleArg(arguments);
395 ASSERT(buttonNumber != -1);
397 WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
399 updateClickCountForButton(buttonType);
402 pressedButton = buttonType;
403 initMouseEvent(WebInputEvent::MouseDown, buttonType, lastMousePos, &event);
404 if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
405 applyKeyModifiers(&(arguments[1]), &event);
406 webview()->handleInputEvent(event);
409 void EventSender::mouseUp(const CppArgumentList& arguments, CppVariant* result)
411 if (result) // Could be 0 if invoked asynchronously.
416 int buttonNumber = getButtonNumberFromSingleArg(arguments);
417 ASSERT(buttonNumber != -1);
419 WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
421 if (isDragMode() && !replayingSavedEvents) {
422 SavedEvent savedEvent;
423 savedEvent.type = SavedEvent::MouseUp;
424 savedEvent.buttonType = buttonType;
425 mouseEventQueue.append(savedEvent);
429 initMouseEvent(WebInputEvent::MouseUp, buttonType, lastMousePos, &event);
430 if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
431 applyKeyModifiers(&(arguments[1]), &event);
436 void EventSender::doMouseUp(const WebMouseEvent& e)
438 webview()->handleInputEvent(e);
440 pressedButton = WebMouseEvent::ButtonNone;
441 lastClickTimeSec = e.timeStampSeconds;
442 lastClickPos = lastMousePos;
444 // If we're in a drag operation, complete it.
445 if (currentDragData.isNull())
447 WebPoint clientPoint(e.x, e.y);
448 WebPoint screenPoint(e.globalX, e.globalY);
450 currentDragEffect = webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed);
451 if (currentDragEffect)
452 webview()->dragTargetDrop(clientPoint, screenPoint);
454 webview()->dragTargetDragLeave();
455 webview()->dragSourceEndedAt(clientPoint, screenPoint, currentDragEffect);
456 webview()->dragSourceSystemDragEnded();
458 currentDragData.reset();
461 void EventSender::mouseMoveTo(const CppArgumentList& arguments, CppVariant* result)
465 if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
469 WebPoint mousePos(arguments[0].toInt32(), arguments[1].toInt32());
471 if (isDragMode() && pressedButton == WebMouseEvent::ButtonLeft && !replayingSavedEvents) {
472 SavedEvent savedEvent;
473 savedEvent.type = SavedEvent::MouseMove;
474 savedEvent.pos = mousePos;
475 mouseEventQueue.append(savedEvent);
478 initMouseEvent(WebInputEvent::MouseMove, pressedButton, mousePos, &event);
483 void EventSender::doMouseMove(const WebMouseEvent& e)
485 lastMousePos = WebPoint(e.x, e.y);
487 webview()->handleInputEvent(e);
489 if (pressedButton == WebMouseEvent::ButtonNone || currentDragData.isNull())
491 WebPoint clientPoint(e.x, e.y);
492 WebPoint screenPoint(e.globalX, e.globalY);
493 currentDragEffect = webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed);
496 void EventSender::keyDown(const CppArgumentList& arguments, CppVariant* result)
499 if (arguments.size() < 1 || !arguments[0].isString())
501 bool generateChar = false;
503 // FIXME: I'm not exactly sure how we should convert the string to a key
504 // event. This seems to work in the cases I tested.
505 // FIXME: Should we also generate a KEY_UP?
506 string codeStr = arguments[0].toString();
508 // Convert \n -> VK_RETURN. Some layout tests use \n to mean "Enter", when
509 // Windows uses \r for "Enter".
512 bool needsShiftKeyModifier = false;
513 if ("\n" == codeStr) {
515 text = code = webkit_support::VKEY_RETURN;
516 } else if ("rightArrow" == codeStr)
517 code = webkit_support::VKEY_RIGHT;
518 else if ("downArrow" == codeStr)
519 code = webkit_support::VKEY_DOWN;
520 else if ("leftArrow" == codeStr)
521 code = webkit_support::VKEY_LEFT;
522 else if ("upArrow" == codeStr)
523 code = webkit_support::VKEY_UP;
524 else if ("insert" == codeStr)
525 code = webkit_support::VKEY_INSERT;
526 else if ("delete" == codeStr)
527 code = webkit_support::VKEY_DELETE;
528 else if ("pageUp" == codeStr)
529 code = webkit_support::VKEY_PRIOR;
530 else if ("pageDown" == codeStr)
531 code = webkit_support::VKEY_NEXT;
532 else if ("home" == codeStr)
533 code = webkit_support::VKEY_HOME;
534 else if ("end" == codeStr)
535 code = webkit_support::VKEY_END;
536 else if ("printScreen" == codeStr)
537 code = webkit_support::VKEY_SNAPSHOT;
538 else if ("menu" == codeStr)
539 // FIXME: Change this to webkit_support::VKEY_APPS.
542 // Compare the input string with the function-key names defined by the
543 // DOM spec (i.e. "F1",...,"F24"). If the input string is a function-key
544 // name, set its key code.
545 for (int i = 1; i <= 24; ++i) {
546 char functionChars[10];
547 snprintf(functionChars, 10, "F%d", i);
548 string functionKeyName(functionChars);
549 if (functionKeyName == codeStr) {
550 code = webkit_support::VKEY_F1 + (i - 1);
555 WebString webCodeStr = WebString::fromUTF8(codeStr.data(), codeStr.size());
556 ASSERT(webCodeStr.length() == 1);
557 text = code = webCodeStr.data()[0];
558 needsShiftKeyModifier = needsShiftModifier(code);
559 if ((code & 0xFF) >= 'a' && (code & 0xFF) <= 'z')
565 // For one generated keyboard event, we need to generate a keyDown/keyUp
566 // pair; refer to EventSender.cpp in Tools/DumpRenderTree/win.
567 // On Windows, we might also need to generate a char event to mimic the
568 // Windows event flow; on other platforms we create a merged event and test
569 // the event flow that that platform provides.
570 WebKeyboardEvent eventDown, eventChar, eventUp;
571 eventDown.type = WebInputEvent::RawKeyDown;
572 eventDown.modifiers = 0;
573 eventDown.windowsKeyCode = code;
575 eventDown.text[0] = text;
576 eventDown.unmodifiedText[0] = text;
578 eventDown.setKeyIdentifierFromWindowsKeyCode();
580 if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
581 eventDown.isSystemKey = applyKeyModifiers(&(arguments[1]), &eventDown);
583 if (needsShiftKeyModifier)
584 eventDown.modifiers |= WebInputEvent::ShiftKey;
586 // See if KeyLocation argument is given.
587 if (arguments.size() >= 3 && arguments[2].isNumber()) {
588 int location = arguments[2].toInt32();
589 if (location == DOMKeyLocationNumpad)
590 eventDown.modifiers |= WebInputEvent::IsKeyPad;
593 eventChar = eventUp = eventDown;
594 eventUp.type = WebInputEvent::KeyUp;
595 // EventSender.m forces a layout here, with at least one
596 // test (fast/forms/focus-control-to-page.html) relying on this.
599 // In the browser, if a keyboard event corresponds to an editor command,
600 // the command will be dispatched to the renderer just before dispatching
601 // the keyboard event, and then it will be executed in the
602 // RenderView::handleCurrentKeyboardEvent() method, which is called from
603 // third_party/WebKit/Source/WebKit/chromium/src/EditorClientImpl.cpp.
604 // We just simulate the same behavior here.
606 if (getEditCommand(eventDown, &editCommand))
607 m_shell->webViewHost()->setEditCommand(editCommand, "");
609 webview()->handleInputEvent(eventDown);
611 m_shell->webViewHost()->clearEditCommand();
614 eventChar.type = WebInputEvent::Char;
615 eventChar.keyIdentifier[0] = '\0';
616 webview()->handleInputEvent(eventChar);
619 webview()->handleInputEvent(eventUp);
622 void EventSender::dispatchMessage(const CppArgumentList& arguments, CppVariant* result)
627 if (arguments.size() == 3) {
628 // Grab the message id to see if we need to dispatch it.
629 int msg = arguments[0].toInt32();
631 // WebKit's version of this function stuffs a MSG struct and uses
632 // TranslateMessage and DispatchMessage. We use a WebKeyboardEvent, which
633 // doesn't need to receive the DeadChar and SysDeadChar messages.
634 if (msg == WM_DEADCHAR || msg == WM_SYSDEADCHAR)
639 unsigned long lparam = static_cast<unsigned long>(arguments[2].toDouble());
640 webview()->handleInputEvent(WebInputEventFactory::keyboardEvent(0, msg, arguments[1].toInt32(), lparam));
642 ASSERT_NOT_REACHED();
646 bool EventSender::needsShiftModifier(int keyCode)
648 // If code is an uppercase letter, assign a SHIFT key to
649 // eventDown.modifier, this logic comes from
650 // Tools/DumpRenderTree/win/EventSender.cpp
651 return (keyCode & 0xFF) >= 'A' && (keyCode & 0xFF) <= 'Z';
654 void EventSender::leapForward(const CppArgumentList& arguments, CppVariant* result)
658 if (arguments.size() < 1 || !arguments[0].isNumber())
661 int milliseconds = arguments[0].toInt32();
662 if (isDragMode() && pressedButton == WebMouseEvent::ButtonLeft && !replayingSavedEvents) {
663 SavedEvent savedEvent;
664 savedEvent.type = SavedEvent::LeapForward;
665 savedEvent.milliseconds = milliseconds;
666 mouseEventQueue.append(savedEvent);
668 doLeapForward(milliseconds);
671 void EventSender::doLeapForward(int milliseconds)
673 advanceEventTime(milliseconds);
676 // Apple's port of WebKit zooms by a factor of 1.2 (see
677 // WebKit/WebView/WebView.mm)
678 void EventSender::textZoomIn(const CppArgumentList&, CppVariant* result)
680 webview()->setZoomLevel(true, webview()->zoomLevel() + 1);
684 void EventSender::textZoomOut(const CppArgumentList&, CppVariant* result)
686 webview()->setZoomLevel(true, webview()->zoomLevel() - 1);
690 void EventSender::zoomPageIn(const CppArgumentList&, CppVariant* result)
692 webview()->setZoomLevel(false, webview()->zoomLevel() + 1);
696 void EventSender::zoomPageOut(const CppArgumentList&, CppVariant* result)
698 webview()->setZoomLevel(false, webview()->zoomLevel() - 1);
702 void EventSender::scalePageBy(const CppArgumentList& arguments, CppVariant* result)
704 if (arguments.size() < 3 || !arguments[0].isNumber() || !arguments[1].isNumber() || !arguments[2].isNumber())
707 float scaleFactor = static_cast<float>(arguments[0].toDouble());
708 int x = arguments[1].toInt32();
709 int y = arguments[2].toInt32();
710 webview()->scalePage(scaleFactor, WebPoint(x, y));
714 void EventSender::mouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
716 handleMouseWheel(arguments, result, false);
719 void EventSender::continuousMouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
721 handleMouseWheel(arguments, result, true);
724 void EventSender::replaySavedEvents()
726 replayingSavedEvents = true;
727 while (!mouseEventQueue.isEmpty()) {
728 SavedEvent e = mouseEventQueue.takeFirst();
731 case SavedEvent::MouseMove: {
733 initMouseEvent(WebInputEvent::MouseMove, pressedButton, e.pos, &event);
737 case SavedEvent::LeapForward:
738 doLeapForward(e.milliseconds);
740 case SavedEvent::MouseUp: {
742 initMouseEvent(WebInputEvent::MouseUp, e.buttonType, lastMousePos, &event);
747 ASSERT_NOT_REACHED();
751 replayingSavedEvents = false;
754 // Because actual context menu is implemented by the browser side,
755 // this function does only what LayoutTests are expecting:
756 // - Many test checks the count of items. So returning non-zero value makes sense.
757 // - Some test compares the count before and after some action. So changing the count based on flags
758 // also makes sense. This function is doing such for some flags.
759 // - Some test even checks actual string content. So providing it would be also helpful.
761 static Vector<WebString> makeMenuItemStringsFor(WebContextMenuData* contextMenu, MockSpellCheck* spellcheck)
763 // These constants are based on Safari's context menu because tests are made for it.
764 static const char* nonEditableMenuStrings[] = { "Back", "Reload Page", "Open in Dashbaord", "<separator>", "View Source", "Save Page As", "Print Page", "Inspect Element", 0 };
765 static const char* editableMenuStrings[] = { "Cut", "Copy", "<separator>", "Paste", "Spelling and Grammar", "Substitutions, Transformations", "Font", "Speech", "Paragraph Direction", "<separator>", 0 };
767 // This is possible because mouse events are cancelleable.
769 return Vector<WebString>();
771 Vector<WebString> strings;
773 if (contextMenu->isEditable) {
774 for (const char** item = editableMenuStrings; *item; ++item)
775 strings.append(WebString::fromUTF8(*item));
776 Vector<WebString> suggestions;
777 spellcheck->fillSuggestionList(contextMenu->misspelledWord, &suggestions);
778 for (size_t i = 0; i < suggestions.size(); ++i)
779 strings.append(suggestions[i]);
781 for (const char** item = nonEditableMenuStrings; *item; ++item)
782 strings.append(WebString::fromUTF8(*item));
789 void EventSender::contextClick(const CppArgumentList& arguments, CppVariant* result)
793 updateClickCountForButton(WebMouseEvent::ButtonRight);
795 // Clears last context menu data because we need to know if the context menu be requested
796 // after following mouse events.
797 m_shell->webViewHost()->clearContextMenuData();
799 // Generate right mouse down and up.
801 pressedButton = WebMouseEvent::ButtonRight;
802 initMouseEvent(WebInputEvent::MouseDown, WebMouseEvent::ButtonRight, lastMousePos, &event);
803 webview()->handleInputEvent(event);
805 initMouseEvent(WebInputEvent::MouseUp, WebMouseEvent::ButtonRight, lastMousePos, &event);
806 webview()->handleInputEvent(event);
808 pressedButton = WebMouseEvent::ButtonNone;
810 WebContextMenuData* lastContextMenu = m_shell->webViewHost()->lastContextMenuData();
811 result->set(WebBindings::makeStringArray(makeMenuItemStringsFor(lastContextMenu, m_shell->webViewHost()->mockSpellCheck())));
814 class MouseDownTask: public MethodTask<EventSender> {
816 MouseDownTask(EventSender* obj, const CppArgumentList& arg)
817 : MethodTask<EventSender>(obj), m_arguments(arg) { }
818 virtual void runIfValid() { m_object->mouseDown(m_arguments, 0); }
821 CppArgumentList m_arguments;
824 class MouseUpTask: public MethodTask<EventSender> {
826 MouseUpTask(EventSender* obj, const CppArgumentList& arg)
827 : MethodTask<EventSender>(obj), m_arguments(arg) { }
828 virtual void runIfValid() { m_object->mouseUp(m_arguments, 0); }
831 CppArgumentList m_arguments;
834 void EventSender::scheduleAsynchronousClick(const CppArgumentList& arguments, CppVariant* result)
837 postTask(new MouseDownTask(this, arguments));
838 postTask(new MouseUpTask(this, arguments));
841 void EventSender::beginDragWithFiles(const CppArgumentList& arguments, CppVariant* result)
843 currentDragData.initialize();
844 Vector<string> files = arguments[0].toStringVector();
845 for (size_t i = 0; i < files.size(); ++i)
846 currentDragData.appendToFilenames(webkit_support::GetAbsoluteWebStringFromUTF8Path(files[i]));
847 currentDragEffectsAllowed = WebKit::WebDragOperationCopy;
849 // Provide a drag source.
850 webview()->dragTargetDragEnter(currentDragData, lastMousePos, lastMousePos, currentDragEffectsAllowed);
852 // dragMode saves events and then replays them later. We don't need/want that.
855 // Make the rest of eventSender think a drag is in progress.
856 pressedButton = WebMouseEvent::ButtonLeft;
861 void EventSender::addTouchPoint(const CppArgumentList& arguments, CppVariant* result)
865 WebTouchPoint touchPoint;
866 touchPoint.state = WebTouchPoint::StatePressed;
867 touchPoint.position = WebPoint(arguments[0].toInt32(), arguments[1].toInt32());
868 touchPoint.screenPosition = touchPoint.position;
871 for (size_t i = 0; i < touchPoints.size(); i++) {
872 if (touchPoints[i].id == lowestId)
875 touchPoint.id = lowestId;
876 touchPoints.append(touchPoint);
879 void EventSender::clearTouchPoints(const CppArgumentList&, CppVariant* result)
885 void EventSender::releaseTouchPoint(const CppArgumentList& arguments, CppVariant* result)
889 const unsigned index = arguments[0].toInt32();
890 ASSERT(index < touchPoints.size());
892 WebTouchPoint* touchPoint = &touchPoints[index];
893 touchPoint->state = WebTouchPoint::StateReleased;
896 void EventSender::setTouchModifier(const CppArgumentList& arguments, CppVariant* result)
901 const string keyName = arguments[0].toString();
902 if (keyName == "shift")
903 mask = WebInputEvent::ShiftKey;
904 else if (keyName == "alt")
905 mask = WebInputEvent::AltKey;
906 else if (keyName == "ctrl")
907 mask = WebInputEvent::ControlKey;
908 else if (keyName == "meta")
909 mask = WebInputEvent::MetaKey;
911 if (arguments[1].toBoolean())
912 touchModifiers |= mask;
914 touchModifiers &= ~mask;
917 void EventSender::updateTouchPoint(const CppArgumentList& arguments, CppVariant* result)
921 const unsigned index = arguments[0].toInt32();
922 ASSERT(index < touchPoints.size());
924 WebPoint position(arguments[1].toInt32(), arguments[2].toInt32());
925 WebTouchPoint* touchPoint = &touchPoints[index];
926 touchPoint->state = WebTouchPoint::StateMoved;
927 touchPoint->position = position;
928 touchPoint->screenPosition = position;
931 void EventSender::cancelTouchPoint(const CppArgumentList& arguments, CppVariant* result)
935 const unsigned index = arguments[0].toInt32();
936 ASSERT(index < touchPoints.size());
938 WebTouchPoint* touchPoint = &touchPoints[index];
939 touchPoint->state = WebTouchPoint::StateCancelled;
942 void EventSender::sendCurrentTouchEvent(const WebInputEvent::Type type)
944 ASSERT(static_cast<unsigned>(WebTouchEvent::touchPointsLengthCap) > touchPoints.size());
947 WebTouchEvent touchEvent;
948 touchEvent.type = type;
949 touchEvent.modifiers = touchModifiers;
950 touchEvent.timeStampSeconds = getCurrentEventTimeSec();
951 touchEvent.touchPointsLength = touchPoints.size();
952 for (unsigned i = 0; i < touchPoints.size(); ++i)
953 touchEvent.touchPoints[i] = touchPoints[i];
954 webview()->handleInputEvent(touchEvent);
956 for (unsigned i = 0; i < touchPoints.size(); ++i) {
957 WebTouchPoint* touchPoint = &touchPoints[i];
958 if (touchPoint->state == WebTouchPoint::StateReleased) {
959 touchPoints.remove(i);
962 touchPoint->state = WebTouchPoint::StateStationary;
966 void EventSender::handleMouseWheel(const CppArgumentList& arguments, CppVariant* result, bool continuous)
970 if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
973 // Force a layout here just to make sure every position has been
974 // determined before we send events (as well as all the other methods
975 // that send an event do).
978 int horizontal = arguments[0].toInt32();
979 int vertical = arguments[1].toInt32();
981 WebMouseWheelEvent event;
982 initMouseEvent(WebInputEvent::MouseWheel, pressedButton, lastMousePos, &event);
983 event.wheelTicksX = static_cast<float>(horizontal);
984 event.wheelTicksY = static_cast<float>(vertical);
985 event.deltaX = event.wheelTicksX;
986 event.deltaY = event.wheelTicksY;
988 event.wheelTicksX /= scrollbarPixelsPerTick;
989 event.wheelTicksY /= scrollbarPixelsPerTick;
991 event.deltaX *= scrollbarPixelsPerTick;
992 event.deltaY *= scrollbarPixelsPerTick;
994 webview()->handleInputEvent(event);
997 void EventSender::touchEnd(const CppArgumentList&, CppVariant* result)
1000 sendCurrentTouchEvent(WebInputEvent::TouchEnd);
1003 void EventSender::touchMove(const CppArgumentList&, CppVariant* result)
1006 sendCurrentTouchEvent(WebInputEvent::TouchMove);
1009 void EventSender::touchStart(const CppArgumentList&, CppVariant* result)
1012 sendCurrentTouchEvent(WebInputEvent::TouchStart);
1015 void EventSender::touchCancel(const CppArgumentList&, CppVariant* result)
1018 sendCurrentTouchEvent(WebInputEvent::TouchCancel);
1022 // Unimplemented stubs
1025 void EventSender::enableDOMUIEventLogging(const CppArgumentList&, CppVariant* result)
1030 void EventSender::fireKeyboardEventsToElement(const CppArgumentList&, CppVariant* result)
1035 void EventSender::clearKillRing(const CppArgumentList&, CppVariant* result)