1 /*
2  * Copyright (C) 2015 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 
17 package com.android.documentsui.bots;
18 
19 import static androidx.test.espresso.Espresso.onView;
20 import static androidx.test.espresso.action.ViewActions.pressImeActionButton;
21 import static androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom;
22 
23 import android.content.Context;
24 import android.support.test.uiautomator.UiDevice;
25 import android.view.inputmethod.InputMethodManager;
26 import android.widget.EditText;
27 
28 /**
29  * A test helper class that provides support for keyboard manipulation.
30  */
31 public class KeyboardBot extends Bots.BaseBot {
32 
KeyboardBot(UiDevice device, Context context, int timeout)33     public KeyboardBot(UiDevice device, Context context, int timeout) {
34         super(device, context, timeout);
35     }
36 
dismissKeyboardIfPresent()37     public void dismissKeyboardIfPresent() {
38         if(isKeyboardPresent()) {
39             mDevice.pressBack();
40         }
41     }
42 
43     // Indirect way to detect the keyboard.
isKeyboardPresent()44     private boolean isKeyboardPresent() {
45         InputMethodManager inputManager = (InputMethodManager) mContext
46                 .getSystemService(Context.INPUT_METHOD_SERVICE);
47         return inputManager.isAcceptingText();
48     }
49 
pressEnter()50     public void pressEnter() {
51       //TODO: There seems to be a bug on N/Espresso that makes pressing Enter not work
52       // This is a temporary workaround that somehow works
53       // See b/28399576
54         onView(isAssignableFrom(EditText.class)).perform(pressImeActionButton());
55     }
56 
pressKey(int keyCode)57     public void pressKey(int keyCode) {
58         mDevice.pressKeyCode(keyCode);
59     }
60 
pressKey(int keyCode, int metaState)61     public void pressKey(int keyCode, int metaState) {
62         mDevice.pressKeyCode(keyCode, metaState);
63     }
64 }
65