Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / content / public / test / android / javatests / src / org / chromium / content / browser / test / util / KeyUtils.java
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package org.chromium.content.browser.test.util;
6
7 import android.app.Instrumentation;
8 import android.os.SystemClock;
9 import android.view.KeyEvent;
10 import android.view.View;
11
12 import org.chromium.base.ThreadUtils;
13
14 /**
15  * Collection of keyboard utilities.
16  */
17 public class KeyUtils {
18     /**
19      * Sends (synchronously) a single key down/up pair of events to the specified view.
20      * <p>
21      * Does not use the event injecting framework, but instead relies on
22      * {@link View#dispatchKeyEventPreIme(KeyEvent)} and {@link View#dispatchKeyEvent(KeyEvent)} of
23      * the view itself
24      * <p>
25      * The event injecting framework requires INJECT_EVENTS permission and that has been flaky on
26      * our perf bots.  So until a root cause of the issue can be found, we should use this instead
27      * of the functionality provided by {@link #sendKeys(int...)}.
28      *
29      * @param i The application being instrumented.
30      * @param v The view to receive the key event.
31      * @param keyCode The keycode for the event to be issued.
32      */
33     public static void singleKeyEventView(Instrumentation i, final View v, int keyCode) {
34         long downTime = SystemClock.uptimeMillis();
35         long eventTime = SystemClock.uptimeMillis();
36
37         final KeyEvent downEvent =
38                 new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN, keyCode, 0);
39         dispatchKeyEvent(i, v, downEvent);
40
41         downTime = SystemClock.uptimeMillis();
42         eventTime = SystemClock.uptimeMillis();
43         final KeyEvent upEvent =
44                 new KeyEvent(downTime, eventTime, KeyEvent.ACTION_UP, keyCode, 0);
45         dispatchKeyEvent(i, v, upEvent);
46     }
47
48     private static void dispatchKeyEvent(final Instrumentation i, final View v,
49             final KeyEvent event) {
50         ThreadUtils.runOnUiThreadBlocking(new Runnable() {
51             @Override
52             public void run() {
53                 if (!v.dispatchKeyEventPreIme(event)) {
54                     v.dispatchKeyEvent(event);
55                 }
56             }
57         });
58         i.waitForIdleSync();
59     }
60 }