1/* 2 * Copyright (C) 2014 The Android Open Source Project 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.apps.common.testing.ui.espresso.base; 18 19import static com.google.common.base.Preconditions.checkNotNull; 20 21import com.google.android.apps.common.testing.ui.espresso.InjectEventSecurityException; 22 23import android.os.Build; 24import android.os.SystemClock; 25import android.util.Log; 26import android.view.KeyEvent; 27import android.view.MotionEvent; 28 29/** 30 * Responsible for selecting the proper strategy for injecting MotionEvents to the application under 31 * test. 32 */ 33final class EventInjector { 34 private static final String TAG = EventInjector.class.getSimpleName(); 35 private final EventInjectionStrategy injectionStrategy; 36 37 EventInjector(EventInjectionStrategy injectionStrategy) { 38 this.injectionStrategy = checkNotNull(injectionStrategy); 39 } 40 41 boolean injectKeyEvent(KeyEvent event) throws InjectEventSecurityException { 42 long downTime = event.getDownTime(); 43 long eventTime = event.getEventTime(); 44 int action = event.getAction(); 45 int code = event.getKeyCode(); 46 int repeatCount = event.getRepeatCount(); 47 int metaState = event.getMetaState(); 48 int deviceId = event.getDeviceId(); 49 int scancode = event.getScanCode(); 50 int flags = event.getFlags(); 51 52 if (eventTime == 0) { 53 eventTime = SystemClock.uptimeMillis(); 54 } 55 56 if (downTime == 0) { 57 downTime = eventTime; 58 } 59 60 // API < 9 does not have constructor with source (nor has source field). 61 KeyEvent newEvent; 62 if (Build.VERSION.SDK_INT < 9) { 63 newEvent = new KeyEvent(downTime, 64 eventTime, 65 action, 66 code, 67 repeatCount, 68 metaState, 69 deviceId, 70 scancode, 71 flags | KeyEvent.FLAG_FROM_SYSTEM); 72 } else { 73 int source = event.getSource(); 74 newEvent = new KeyEvent(downTime, 75 eventTime, 76 action, 77 code, 78 repeatCount, 79 metaState, 80 deviceId, 81 scancode, 82 flags | KeyEvent.FLAG_FROM_SYSTEM, 83 source); 84 } 85 86 Log.v( 87 "ESP_TRACE", 88 String.format( 89 "%s:Injecting event for character (%c) with key code (%s) downtime: (%s)", TAG, 90 newEvent.getUnicodeChar(), newEvent.getKeyCode(), newEvent.getDownTime())); 91 92 return injectionStrategy.injectKeyEvent(newEvent); 93 } 94 95 boolean injectMotionEvent(MotionEvent event) throws InjectEventSecurityException { 96 return injectionStrategy.injectMotionEvent(event); 97 } 98 99} 100