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