1/*
2 * Copyright (C) 2013 DroidDriver committers
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.android.droiddriver.actions;
18
19import android.os.Build;
20import android.os.SystemClock;
21import android.view.KeyCharacterMap;
22import android.view.KeyEvent;
23
24import com.google.android.droiddriver.UiElement;
25import com.google.android.droiddriver.exceptions.ActionException;
26import com.google.android.droiddriver.util.Preconditions;
27import com.google.android.droiddriver.util.Strings;
28
29/**
30 * An action to type text.
31 */
32public class TextAction extends KeyAction {
33
34  @SuppressWarnings("deprecation")
35  private static final KeyCharacterMap KEY_CHAR_MAP =
36      Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? KeyCharacterMap
37          .load(KeyCharacterMap.BUILT_IN_KEYBOARD) : KeyCharacterMap
38          .load(KeyCharacterMap.VIRTUAL_KEYBOARD);
39
40  private final String text;
41
42  /**
43   * Defaults timeoutMillis to 100.
44   */
45  public TextAction(String text) {
46    this(text, 100L, false);
47  }
48
49  public TextAction(String text, long timeoutMillis, boolean checkFocused) {
50    super(timeoutMillis, checkFocused);
51    this.text = Preconditions.checkNotNull(text);
52  }
53
54  @Override
55  public boolean perform(InputInjector injector, UiElement element) {
56    maybeCheckFocused(element);
57
58    // TODO: recycle events?
59    KeyEvent[] events = KEY_CHAR_MAP.getEvents(text.toCharArray());
60    boolean success = false;
61
62    if (events != null) {
63      for (KeyEvent event : events) {
64        // We have to change the time of an event before injecting it because
65        // all KeyEvents returned by KeyCharacterMap.getEvents() have the same
66        // time stamp and the system rejects too old events. Hence, it is
67        // possible for an event to become stale before it is injected if it
68        // takes too long to inject the preceding ones.
69        KeyEvent modifiedEvent = KeyEvent.changeTimeRepeat(event, SystemClock.uptimeMillis(), 0);
70        success = injector.injectInputEvent(modifiedEvent);
71        if (!success) {
72          break;
73        }
74      }
75    } else {
76      throw new ActionException("The given text is not supported: " + text);
77    }
78    return success;
79  }
80
81  @Override
82  public String toString() {
83    return Strings.toStringHelper(this).addValue(text).toString();
84  }
85}
86