initial import
[vuplus_webkit] / Tools / DumpRenderTree / chromium / EventSender.cpp
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 "config.h"
44 #include "EventSender.h"
45
46 #include "TestShell.h"
47 #include "WebContextMenuData.h"
48 #include "WebDragData.h"
49 #include "WebDragOperation.h"
50 #include "WebPoint.h"
51 #include "WebString.h"
52 #include "WebTouchPoint.h"
53 #include "WebView.h"
54 #include "webkit/support/webkit_support.h"
55 #include <wtf/Deque.h>
56 #include <wtf/StringExtras.h>
57
58 #if OS(WINDOWS)
59 #include "win/WebInputEventFactory.h"
60 #endif
61
62 // FIXME: layout before each event?
63
64 using namespace std;
65 using namespace WebKit;
66
67 WebPoint EventSender::lastMousePos;
68 WebMouseEvent::Button EventSender::pressedButton = WebMouseEvent::ButtonNone;
69 WebMouseEvent::Button EventSender::lastButtonType = WebMouseEvent::ButtonNone;
70
71 struct SavedEvent {
72     enum SavedEventType {
73         Unspecified,
74         MouseUp,
75         MouseMove,
76         LeapForward
77     };
78
79     SavedEventType type;
80     WebMouseEvent::Button buttonType; // For MouseUp.
81     WebPoint pos; // For MouseMove.
82     int milliseconds; // For LeapForward.
83
84     SavedEvent()
85         : type(Unspecified)
86         , buttonType(WebMouseEvent::ButtonNone)
87         , milliseconds(0) { }
88 };
89
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;
97
98 // Time and place of the last mouse up event.
99 static double lastClickTimeSec = 0;
100 static WebPoint lastClickPos;
101 static int clickCount = 0;
102
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;
107
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;
111
112 inline bool outsideMultiClickRadius(const WebPoint& a, const WebPoint& b)
113 {
114     return ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)) >
115         multipleClickRadiusPixels * multipleClickRadiusPixels;
116 }
117
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;
122
123 static double getCurrentEventTimeSec()
124 {
125     return (webkit_support::GetCurrentTimeInMillisecond() + timeOffsetMs) / 1000.0;
126 }
127
128 static void advanceEventTime(int32_t deltaMs)
129 {
130     timeOffsetMs += deltaMs;
131 }
132
133 static void initMouseEvent(WebInputEvent::Type t, WebMouseEvent::Button b,
134                            const WebPoint& pos, WebMouseEvent* e)
135 {
136     e->type = t;
137     e->button = b;
138     e->modifiers = 0;
139     e->x = pos.x;
140     e->y = pos.y;
141     e->globalX = pos.x;
142     e->globalY = pos.y;
143     e->timeStampSeconds = getCurrentEventTimeSec();
144     e->clickCount = clickCount;
145 }
146
147 // Returns true if the specified key is the system key.
148 static bool applyKeyModifier(const string& modifierName, WebInputEvent* event)
149 {
150     bool isSystemKey = false;
151     const char* characters = modifierName.c_str();
152     if (!strcmp(characters, "ctrlKey")
153 #if !OS(MAC_OS_X)
154         || !strcmp(characters, "addSelectionKey")
155 #endif
156         ) {
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;
162 #if !OS(MAC_OS_X)
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.
168         isSystemKey = true;
169 #endif
170 #if OS(MAC_OS_X)
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.
176         isSystemKey = true;
177 #else
178     } else if (!strcmp(characters, "metaKey")) {
179         event->modifiers |= WebInputEvent::MetaKey;
180 #endif
181     }
182     return isSystemKey;
183 }
184
185 static bool applyKeyModifiers(const CppVariant* argument, WebInputEvent* event)
186 {
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);
194     return isSystemKey;
195 }
196
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)
201 {
202 #if OS(MAC_OS_X)
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)
210         return false;
211
212     switch (event.windowsKeyCode) {
213     case webkit_support::VKEY_LEFT:
214         *name = "MoveToBeginningOfLine";
215         break;
216     case webkit_support::VKEY_RIGHT:
217         *name = "MoveToEndOfLine";
218         break;
219     case webkit_support::VKEY_UP:
220         *name = "MoveToBeginningOfDocument";
221         break;
222     case webkit_support::VKEY_DOWN:
223         *name = "MoveToEndOfDocument";
224         break;
225     default:
226         return false;
227     }
228
229     if (event.modifiers & WebKeyboardEvent::ShiftKey)
230         name->append("AndModifySelection");
231
232     return true;
233 #else
234     return false;
235 #endif
236 }
237
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
245 };
246
247 EventSender::EventSender(TestShell* shell)
248     : m_shell(shell)
249 {
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);
287
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);
291 #if OS(WINDOWS)
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);
300 #endif
301 }
302
303 void EventSender::reset()
304 {
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;
311     dragMode.set(true);
312 #if OS(WINDOWS)
313     wmKeyDown.set(WM_KEYDOWN);
314     wmKeyUp.set(WM_KEYUP);
315     wmChar.set(WM_CHAR);
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);
321 #endif
322     lastMousePos = WebPoint(0, 0);
323     lastClickTimeSec = 0;
324     lastClickPos = WebPoint(0, 0);
325     clickCount = 0;
326     lastButtonType = WebMouseEvent::ButtonNone;
327     timeOffsetMs = 0;
328     touchModifiers = 0;
329     touchPoints.clear();
330     m_taskList.revokeAll();
331 }
332
333 WebView* EventSender::webview()
334 {
335     return m_shell->webView();
336 }
337
338 void EventSender::doDragDrop(const WebDragData& dragData, WebDragOperationsMask mask)
339 {
340     WebMouseEvent event;
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);
347
348     // Finish processing events.
349     replaySavedEvents();
350 }
351
352 void EventSender::dumpFilenameBeingDragged(const CppArgumentList&, CppVariant*)
353 {
354     printf("Filename being dragged: %s\n", currentDragData.fileContentFilename().utf8().data());
355 }
356
357 WebMouseEvent::Button EventSender::getButtonTypeFromButtonNumber(int buttonCode)
358 {
359     if (!buttonCode)
360         return WebMouseEvent::ButtonLeft;
361     if (buttonCode == 2)
362         return WebMouseEvent::ButtonRight;
363     return WebMouseEvent::ButtonMiddle;
364 }
365
366 int EventSender::getButtonNumberFromSingleArg(const CppArgumentList& arguments)
367 {
368     int buttonCode = 0;
369     if (arguments.size() > 0 && arguments[0].isNumber())
370         buttonCode = arguments[0].toInt32();
371     return buttonCode;
372 }
373
374 void EventSender::updateClickCountForButton(WebMouseEvent::Button buttonType)
375 {
376     if ((getCurrentEventTimeSec() - lastClickTimeSec < multipleClickTimeSec)
377         && (!outsideMultiClickRadius(lastMousePos, lastClickPos))
378         && (buttonType == lastButtonType))
379         ++clickCount;
380     else {
381         clickCount = 1;
382         lastButtonType = buttonType;
383     }
384 }
385
386 //
387 // Implemented javascript methods.
388 //
389
390 void EventSender::mouseDown(const CppArgumentList& arguments, CppVariant* result)
391 {
392     if (result) // Could be 0 if invoked asynchronously.
393         result->setNull();
394
395     webview()->layout();
396
397     int buttonNumber = getButtonNumberFromSingleArg(arguments);
398     ASSERT(buttonNumber != -1);
399
400     WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
401
402     updateClickCountForButton(buttonType);
403
404     WebMouseEvent event;
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);
410 }
411
412 void EventSender::mouseUp(const CppArgumentList& arguments, CppVariant* result)
413 {
414     if (result) // Could be 0 if invoked asynchronously.
415         result->setNull();
416
417     webview()->layout();
418
419     int buttonNumber = getButtonNumberFromSingleArg(arguments);
420     ASSERT(buttonNumber != -1);
421
422     WebMouseEvent::Button buttonType = getButtonTypeFromButtonNumber(buttonNumber);
423
424     if (isDragMode() && !replayingSavedEvents) {
425         SavedEvent savedEvent;
426         savedEvent.type = SavedEvent::MouseUp;
427         savedEvent.buttonType = buttonType;
428         mouseEventQueue.append(savedEvent);
429         replaySavedEvents();
430     } else {
431         WebMouseEvent event;
432         initMouseEvent(WebInputEvent::MouseUp, buttonType, lastMousePos, &event);
433         if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
434             applyKeyModifiers(&(arguments[1]), &event);
435         doMouseUp(event);
436     }
437 }
438
439 void EventSender::doMouseUp(const WebMouseEvent& e)
440 {
441     webview()->handleInputEvent(e);
442
443     pressedButton = WebMouseEvent::ButtonNone;
444     lastClickTimeSec = e.timeStampSeconds;
445     lastClickPos = lastMousePos;
446
447     // If we're in a drag operation, complete it.
448     if (currentDragData.isNull())
449         return;
450     WebPoint clientPoint(e.x, e.y);
451     WebPoint screenPoint(e.globalX, e.globalY);
452
453     currentDragEffect = webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed);
454     if (currentDragEffect)
455         webview()->dragTargetDrop(clientPoint, screenPoint);
456     else
457         webview()->dragTargetDragLeave();
458     webview()->dragSourceEndedAt(clientPoint, screenPoint, currentDragEffect);
459     webview()->dragSourceSystemDragEnded();
460
461     currentDragData.reset();
462 }
463
464 void EventSender::mouseMoveTo(const CppArgumentList& arguments, CppVariant* result)
465 {
466     result->setNull();
467
468     if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
469         return;
470     webview()->layout();
471
472     WebPoint mousePos(arguments[0].toInt32(), arguments[1].toInt32());
473
474     if (isDragMode() && pressedButton == WebMouseEvent::ButtonLeft && !replayingSavedEvents) {
475         SavedEvent savedEvent;
476         savedEvent.type = SavedEvent::MouseMove;
477         savedEvent.pos = mousePos;
478         mouseEventQueue.append(savedEvent);
479     } else {
480         WebMouseEvent event;
481         initMouseEvent(WebInputEvent::MouseMove, pressedButton, mousePos, &event);
482         doMouseMove(event);
483     }
484 }
485
486 void EventSender::doMouseMove(const WebMouseEvent& e)
487 {
488     lastMousePos = WebPoint(e.x, e.y);
489
490     webview()->handleInputEvent(e);
491
492     if (pressedButton == WebMouseEvent::ButtonNone || currentDragData.isNull())
493         return;
494     WebPoint clientPoint(e.x, e.y);
495     WebPoint screenPoint(e.globalX, e.globalY);
496     currentDragEffect = webview()->dragTargetDragOver(clientPoint, screenPoint, currentDragEffectsAllowed);
497 }
498
499 void EventSender::keyDown(const CppArgumentList& arguments, CppVariant* result)
500 {
501     result->setNull();
502     if (arguments.size() < 1 || !arguments[0].isString())
503         return;
504     bool generateChar = false;
505
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();
510
511     // Convert \n -> VK_RETURN. Some layout tests use \n to mean "Enter", when
512     // Windows uses \r for "Enter".
513     int code = 0;
514     int text = 0;
515     bool needsShiftKeyModifier = false;
516     if ("\n" == codeStr) {
517         generateChar = true;
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.
543         code = 0x5D;
544     else {
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);
554                 break;
555             }
556         }
557         if (!code) {
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')
563                 code -= 'a' - 'A';
564             generateChar = true;
565         }
566     }
567
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;
577 #if OS(LINUX)
578     eventDown.nativeKeyCode = webkit_support::NativeKeyCodeForWindowsKeyCode(code, needsShiftKeyModifier);
579 #endif
580
581     if (generateChar) {
582         eventDown.text[0] = text;
583         eventDown.unmodifiedText[0] = text;
584     }
585     eventDown.setKeyIdentifierFromWindowsKeyCode();
586
587     if (arguments.size() >= 2 && (arguments[1].isObject() || arguments[1].isString()))
588         eventDown.isSystemKey = applyKeyModifiers(&(arguments[1]), &eventDown);
589
590     if (needsShiftKeyModifier)
591         eventDown.modifiers |= WebInputEvent::ShiftKey;
592
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;
598     }
599
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.
604     webview()->layout();
605
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.
612     string editCommand;
613     if (getEditCommand(eventDown, &editCommand))
614         m_shell->webViewHost()->setEditCommand(editCommand, "");
615
616     webview()->handleInputEvent(eventDown);
617
618     m_shell->webViewHost()->clearEditCommand();
619
620     if (generateChar) {
621         eventChar.type = WebInputEvent::Char;
622         eventChar.keyIdentifier[0] = '\0';
623         webview()->handleInputEvent(eventChar);
624     }
625
626     webview()->handleInputEvent(eventUp);
627 }
628
629 void EventSender::dispatchMessage(const CppArgumentList& arguments, CppVariant* result)
630 {
631     result->setNull();
632
633 #if OS(WINDOWS)
634     if (arguments.size() == 3) {
635         // Grab the message id to see if we need to dispatch it.
636         int msg = arguments[0].toInt32();
637
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)
642             return;
643
644         webview()->layout();
645
646         unsigned long lparam = static_cast<unsigned long>(arguments[2].toDouble());
647         webview()->handleInputEvent(WebInputEventFactory::keyboardEvent(0, msg, arguments[1].toInt32(), lparam));
648     } else
649         ASSERT_NOT_REACHED();
650 #endif
651 }
652
653 bool EventSender::needsShiftModifier(int keyCode)
654 {
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';
659 }
660
661 void EventSender::leapForward(const CppArgumentList& arguments, CppVariant* result)
662 {
663     result->setNull();
664
665     if (arguments.size() < 1 || !arguments[0].isNumber())
666         return;
667
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);
674     } else
675         doLeapForward(milliseconds);
676 }
677
678 void EventSender::doLeapForward(int milliseconds)
679 {
680     advanceEventTime(milliseconds);
681 }
682
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)
686 {
687     webview()->setZoomLevel(true, webview()->zoomLevel() + 1);
688     result->setNull();
689 }
690
691 void EventSender::textZoomOut(const CppArgumentList&, CppVariant* result)
692 {
693     webview()->setZoomLevel(true, webview()->zoomLevel() - 1);
694     result->setNull();
695 }
696
697 void EventSender::zoomPageIn(const CppArgumentList&, CppVariant* result)
698 {
699     webview()->setZoomLevel(false, webview()->zoomLevel() + 1);
700     result->setNull();
701 }
702
703 void EventSender::zoomPageOut(const CppArgumentList&, CppVariant* result)
704 {
705     webview()->setZoomLevel(false, webview()->zoomLevel() - 1);
706     result->setNull();
707 }
708
709 void EventSender::scalePageBy(const CppArgumentList& arguments, CppVariant* result)
710 {
711     if (arguments.size() < 3 || !arguments[0].isNumber() || !arguments[1].isNumber() || !arguments[2].isNumber())
712         return;
713
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));
718     result->setNull();
719 }
720
721 void EventSender::mouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
722 {
723     handleMouseWheel(arguments, result, false);
724 }
725
726 void EventSender::continuousMouseScrollBy(const CppArgumentList& arguments, CppVariant* result)
727 {
728     handleMouseWheel(arguments, result, true);
729 }
730
731 void EventSender::replaySavedEvents()
732 {
733     replayingSavedEvents = true;
734     while (!mouseEventQueue.isEmpty()) {
735         SavedEvent e = mouseEventQueue.takeFirst();
736
737         switch (e.type) {
738         case SavedEvent::MouseMove: {
739             WebMouseEvent event;
740             initMouseEvent(WebInputEvent::MouseMove, pressedButton, e.pos, &event);
741             doMouseMove(event);
742             break;
743         }
744         case SavedEvent::LeapForward:
745             doLeapForward(e.milliseconds);
746             break;
747         case SavedEvent::MouseUp: {
748             WebMouseEvent event;
749             initMouseEvent(WebInputEvent::MouseUp, e.buttonType, lastMousePos, &event);
750             doMouseUp(event);
751             break;
752         }
753         default:
754             ASSERT_NOT_REACHED();
755         }
756     }
757
758     replayingSavedEvents = false;
759 }
760
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.
767 //
768 static Vector<WebString> makeMenuItemStringsFor(WebContextMenuData* contextMenu, MockSpellCheck* spellcheck)
769 {
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 };
773
774     // This is possible because mouse events are cancelleable.
775     if (!contextMenu)
776         return Vector<WebString>();
777
778     Vector<WebString> strings;
779
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]);
787     } else {
788         for (const char** item = nonEditableMenuStrings; *item; ++item) 
789             strings.append(WebString::fromUTF8(*item));
790     }
791
792     return strings;
793 }
794
795
796 void EventSender::contextClick(const CppArgumentList& arguments, CppVariant* result)
797 {
798     webview()->layout();
799
800     updateClickCountForButton(WebMouseEvent::ButtonRight);
801
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();
805
806     // Generate right mouse down and up.
807     WebMouseEvent event;
808     pressedButton = WebMouseEvent::ButtonRight;
809     initMouseEvent(WebInputEvent::MouseDown, WebMouseEvent::ButtonRight, lastMousePos, &event);
810     webview()->handleInputEvent(event);
811
812     initMouseEvent(WebInputEvent::MouseUp, WebMouseEvent::ButtonRight, lastMousePos, &event);
813     webview()->handleInputEvent(event);
814
815     pressedButton = WebMouseEvent::ButtonNone;
816
817     WebContextMenuData* lastContextMenu = m_shell->webViewHost()->lastContextMenuData();
818     result->set(WebBindings::makeStringArray(makeMenuItemStringsFor(lastContextMenu, m_shell->webViewHost()->mockSpellCheck())));
819 }
820
821 class MouseDownTask: public MethodTask<EventSender> {
822 public:
823     MouseDownTask(EventSender* obj, const CppArgumentList& arg)
824         : MethodTask<EventSender>(obj), m_arguments(arg) { }
825     virtual void runIfValid() { m_object->mouseDown(m_arguments, 0); }
826
827 private:
828     CppArgumentList m_arguments;
829 };
830
831 class MouseUpTask: public MethodTask<EventSender> {
832 public:
833     MouseUpTask(EventSender* obj, const CppArgumentList& arg)
834         : MethodTask<EventSender>(obj), m_arguments(arg) { }
835     virtual void runIfValid() { m_object->mouseUp(m_arguments, 0); }
836
837 private:
838     CppArgumentList m_arguments;
839 };
840
841 void EventSender::scheduleAsynchronousClick(const CppArgumentList& arguments, CppVariant* result)
842 {
843     result->setNull();
844     postTask(new MouseDownTask(this, arguments));
845     postTask(new MouseUpTask(this, arguments));
846 }
847
848 void EventSender::beginDragWithFiles(const CppArgumentList& arguments, CppVariant* result)
849 {
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;
855
856     // Provide a drag source.
857     webview()->dragTargetDragEnter(currentDragData, lastMousePos, lastMousePos, currentDragEffectsAllowed);
858
859     // dragMode saves events and then replays them later. We don't need/want that.
860     dragMode.set(false);
861
862     // Make the rest of eventSender think a drag is in progress.
863     pressedButton = WebMouseEvent::ButtonLeft;
864
865     result->setNull();
866 }
867
868 void EventSender::addTouchPoint(const CppArgumentList& arguments, CppVariant* result)
869 {
870     result->setNull();
871
872     WebTouchPoint touchPoint;
873     touchPoint.state = WebTouchPoint::StatePressed;
874     touchPoint.position = WebPoint(arguments[0].toInt32(), arguments[1].toInt32());
875     touchPoint.screenPosition = touchPoint.position;
876
877     int lowestId = 0;
878     for (size_t i = 0; i < touchPoints.size(); i++) {
879         if (touchPoints[i].id == lowestId)
880             lowestId++;
881     }
882     touchPoint.id = lowestId;
883     touchPoints.append(touchPoint);
884 }
885
886 void EventSender::clearTouchPoints(const CppArgumentList&, CppVariant* result)
887 {
888     result->setNull();
889     touchPoints.clear();
890 }
891
892 void EventSender::releaseTouchPoint(const CppArgumentList& arguments, CppVariant* result)
893 {
894     result->setNull();
895
896     const unsigned index = arguments[0].toInt32();
897     ASSERT(index < touchPoints.size());
898
899     WebTouchPoint* touchPoint = &touchPoints[index];
900     touchPoint->state = WebTouchPoint::StateReleased;
901 }
902
903 void EventSender::setTouchModifier(const CppArgumentList& arguments, CppVariant* result)
904 {
905     result->setNull();
906
907     int mask = 0;
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;
917
918     if (arguments[1].toBoolean())
919         touchModifiers |= mask;
920     else
921         touchModifiers &= ~mask;
922 }
923
924 void EventSender::updateTouchPoint(const CppArgumentList& arguments, CppVariant* result)
925 {
926     result->setNull();
927
928     const unsigned index = arguments[0].toInt32();
929     ASSERT(index < touchPoints.size());
930
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;
936 }
937
938 void EventSender::cancelTouchPoint(const CppArgumentList& arguments, CppVariant* result)
939 {
940     result->setNull();
941
942     const unsigned index = arguments[0].toInt32();
943     ASSERT(index < touchPoints.size());
944
945     WebTouchPoint* touchPoint = &touchPoints[index];
946     touchPoint->state = WebTouchPoint::StateCancelled;
947 }
948
949 void EventSender::sendCurrentTouchEvent(const WebInputEvent::Type type)
950 {
951     ASSERT(static_cast<unsigned>(WebTouchEvent::touchesLengthCap) > touchPoints.size());
952     webview()->layout();
953
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);
962
963     for (unsigned i = 0; i < touchPoints.size(); ++i) {
964         WebTouchPoint* touchPoint = &touchPoints[i];
965         if (touchPoint->state == WebTouchPoint::StateReleased) {
966             touchPoints.remove(i);
967             --i;
968         } else
969             touchPoint->state = WebTouchPoint::StateStationary;
970     }
971 }
972
973 void EventSender::handleMouseWheel(const CppArgumentList& arguments, CppVariant* result, bool continuous)
974 {
975     result->setNull();
976
977     if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
978         return;
979
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).
983     webview()->layout();
984
985     int horizontal = arguments[0].toInt32();
986     int vertical = arguments[1].toInt32();
987
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;
994     if (continuous) {
995         event.wheelTicksX /= scrollbarPixelsPerTick;
996         event.wheelTicksY /= scrollbarPixelsPerTick;
997     } else {
998         event.deltaX *= scrollbarPixelsPerTick;
999         event.deltaY *= scrollbarPixelsPerTick;
1000     }
1001     webview()->handleInputEvent(event);
1002 }
1003
1004 void EventSender::touchEnd(const CppArgumentList&, CppVariant* result)
1005 {
1006     result->setNull();
1007     sendCurrentTouchEvent(WebInputEvent::TouchEnd);
1008 }
1009
1010 void EventSender::touchMove(const CppArgumentList&, CppVariant* result)
1011 {
1012     result->setNull();
1013     sendCurrentTouchEvent(WebInputEvent::TouchMove);
1014 }
1015
1016 void EventSender::touchStart(const CppArgumentList&, CppVariant* result)
1017 {
1018     result->setNull();
1019     sendCurrentTouchEvent(WebInputEvent::TouchStart);
1020 }
1021
1022 void EventSender::touchCancel(const CppArgumentList&, CppVariant* result)
1023 {
1024     result->setNull();
1025     sendCurrentTouchEvent(WebInputEvent::TouchCancel);
1026 }
1027
1028 void EventSender::gestureScrollBegin(const CppArgumentList& arguments, CppVariant* result)
1029 {
1030     result->setNull();
1031     gestureEvent(WebInputEvent::GestureScrollBegin, arguments);
1032 }
1033
1034 void EventSender::gestureScrollEnd(const CppArgumentList& arguments, CppVariant* result)
1035 {
1036     result->setNull();
1037     gestureEvent(WebInputEvent::GestureScrollEnd, arguments);
1038 }
1039
1040 void EventSender::gestureTap(const CppArgumentList& arguments, CppVariant* result)
1041 {
1042     result->setNull();
1043     gestureEvent(WebInputEvent::GestureTap, arguments);
1044 }
1045
1046 void EventSender::gestureEvent(WebInputEvent::Type type, const CppArgumentList& arguments)
1047 {
1048     if (arguments.size() < 2 || !arguments[0].isNumber() || !arguments[1].isNumber())
1049         return;
1050
1051     WebPoint point(arguments[0].toInt32(), arguments[1].toInt32());
1052
1053     WebGestureEvent event;
1054     event.type = type;
1055     event.x = point.x;
1056     event.y = point.y;
1057     event.globalX = point.x;
1058     event.globalY = point.y;
1059     event.timeStampSeconds = getCurrentEventTimeSec();
1060     webview()->handleInputEvent(event);
1061 }
1062
1063 //
1064 // Unimplemented stubs
1065 //
1066
1067 void EventSender::enableDOMUIEventLogging(const CppArgumentList&, CppVariant* result)
1068 {
1069     result->setNull();
1070 }
1071
1072 void EventSender::fireKeyboardEventsToElement(const CppArgumentList&, CppVariant* result)
1073 {
1074     result->setNull();
1075 }
1076
1077 void EventSender::clearKillRing(const CppArgumentList&, CppVariant* result)
1078 {
1079     result->setNull();
1080 }