InputTestsBase.java revision 7dc60f9db729e93cb591492574a436418c553ebf
1/*
2 * Copyright (C) 2012 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.android.inputmethod.latin;
18
19import android.content.Context;
20import android.content.SharedPreferences;
21import android.os.Looper;
22import android.preference.PreferenceManager;
23import android.test.ServiceTestCase;
24import android.text.InputType;
25import android.text.SpannableStringBuilder;
26import android.text.style.CharacterStyle;
27import android.text.style.SuggestionSpan;
28import android.view.LayoutInflater;
29import android.view.View;
30import android.view.ViewGroup;
31import android.view.inputmethod.EditorInfo;
32import android.view.inputmethod.InputConnection;
33import android.widget.EditText;
34import android.widget.FrameLayout;
35
36import com.android.inputmethod.keyboard.Key;
37import com.android.inputmethod.keyboard.Keyboard;
38import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
39import com.android.inputmethod.latin.utils.LocaleUtils;
40
41import java.util.Locale;
42
43public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> {
44
45    private static final String PREF_DEBUG_MODE = "debug_mode";
46
47    // The message that sets the underline is posted with a 100 ms delay
48    protected static final int DELAY_TO_WAIT_FOR_UNDERLINE = 200;
49
50    protected LatinIME mLatinIME;
51    protected Keyboard mKeyboard;
52    protected MyEditText mEditText;
53    protected View mInputView;
54    protected InputConnection mInputConnection;
55
56    // A helper class to ease span tests
57    public static class SpanGetter {
58        final SpannableStringBuilder mInputText;
59        final CharacterStyle mSpan;
60        final int mStart;
61        final int mEnd;
62        // The supplied CharSequence should be an instance of SpannableStringBuilder,
63        // and it should contain exactly zero or one span. Otherwise, an exception
64        // is thrown.
65        public SpanGetter(final CharSequence inputText,
66                final Class<? extends CharacterStyle> spanType) {
67            mInputText = (SpannableStringBuilder)inputText;
68            final CharacterStyle[] spans =
69                    mInputText.getSpans(0, mInputText.length(), spanType);
70            if (0 == spans.length) {
71                mSpan = null;
72                mStart = -1;
73                mEnd = -1;
74            } else if (1 == spans.length) {
75                mSpan = spans[0];
76                mStart = mInputText.getSpanStart(mSpan);
77                mEnd = mInputText.getSpanEnd(mSpan);
78            } else {
79                throw new RuntimeException("Expected one span, found " + spans.length);
80            }
81        }
82        public boolean isAutoCorrectionIndicator() {
83            return (mSpan instanceof SuggestionSpan) &&
84                    0 != (SuggestionSpan.FLAG_AUTO_CORRECTION & ((SuggestionSpan)mSpan).getFlags());
85        }
86        public String[] getSuggestions() {
87            return ((SuggestionSpan)mSpan).getSuggestions();
88        }
89    }
90
91    // A helper class to increase control over the EditText
92    public static class MyEditText extends EditText {
93        public Locale mCurrentLocale;
94        public MyEditText(final Context c) {
95            super(c);
96        }
97
98        @Override
99        public void onAttachedToWindow() {
100            // Make onAttachedToWindow "public"
101            super.onAttachedToWindow();
102        }
103
104        // overriding hidden API in EditText
105        public Locale getTextServicesLocale() {
106            // This method is necessary because EditText is asking this method for the language
107            // to check the spell in. If we don't override this, the spell checker will run in
108            // whatever language the keyboard is currently set on the test device, ignoring any
109            // settings we do inside the tests.
110            return mCurrentLocale;
111        }
112
113        // overriding hidden API in EditText
114        public Locale getSpellCheckerLocale() {
115            // This method is necessary because EditText is asking this method for the language
116            // to check the spell in. If we don't override this, the spell checker will run in
117            // whatever language the keyboard is currently set on the test device, ignoring any
118            // settings we do inside the tests.
119            return mCurrentLocale;
120        }
121
122    }
123
124    public InputTestsBase() {
125        super(LatinIMEForTests.class);
126    }
127
128    // TODO: Isn't there a way to make this generic somehow? We can take a <T> and return a <T>
129    // but we'd have to dispatch types on editor.put...() functions
130    protected boolean setBooleanPreference(final String key, final boolean value,
131            final boolean defaultValue) {
132        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mLatinIME);
133        final boolean previousSetting = prefs.getBoolean(key, defaultValue);
134        final SharedPreferences.Editor editor = prefs.edit();
135        editor.putBoolean(key, value);
136        editor.commit();
137        return previousSetting;
138    }
139
140    // returns the previous setting value
141    protected boolean setDebugMode(final boolean value) {
142        return setBooleanPreference(PREF_DEBUG_MODE, value, false);
143    }
144
145    @Override
146    protected void setUp() throws Exception {
147        super.setUp();
148        mEditText = new MyEditText(getContext());
149        final int inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
150                | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
151        mEditText.setInputType(inputType);
152        mEditText.setEnabled(true);
153        setupService();
154        mLatinIME = getService();
155        final boolean previousDebugSetting = setDebugMode(true);
156        mLatinIME.onCreate();
157        setDebugMode(previousDebugSetting);
158        final EditorInfo ei = new EditorInfo();
159        final InputConnection ic = mEditText.onCreateInputConnection(ei);
160        final LayoutInflater inflater =
161                (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
162        final ViewGroup vg = new FrameLayout(getContext());
163        mInputView = inflater.inflate(R.layout.input_view, vg);
164        mLatinIME.onCreateInputMethodInterface().startInput(ic, ei);
165        mLatinIME.setInputView(mInputView);
166        mLatinIME.onBindInput();
167        mLatinIME.onCreateInputView();
168        mLatinIME.onStartInputView(ei, false);
169        mInputConnection = ic;
170        changeLanguage("en_US");
171    }
172
173    // We need to run the messages added to the handler from LatinIME. The only way to do
174    // that is to call Looper#loop() on the right looper, so we're going to get the looper
175    // object and call #loop() here. The messages in the handler actually run on the UI
176    // thread of the keyboard by design of the handler, so we want to call it synchronously
177    // on the same thread that the tests are running on to mimic the actual environment as
178    // closely as possible.
179    // Now, Looper#loop() never exits in normal operation unless the Looper#quit() method
180    // is called, which has a lot of bad side effects. We can however just throw an exception
181    // in the runnable which will unwind the stack and allow us to exit.
182    private final class InterruptRunMessagesException extends RuntimeException {
183        // Empty class
184    }
185    protected void runMessages() {
186        mLatinIME.mHandler.post(new Runnable() {
187                @Override
188                public void run() {
189                    throw new InterruptRunMessagesException();
190                }
191            });
192        try {
193            Looper.loop();
194        } catch (InterruptRunMessagesException e) {
195            // Resume normal operation
196        }
197    }
198
199    // type(int) and type(String): helper methods to send a code point resp. a string to LatinIME.
200    protected void type(final int codePoint) {
201        // onPressKey and onReleaseKey are explicitly deactivated here, but they do happen in the
202        // code (although multitouch/slide input and other factors make the sequencing complicated).
203        // They are supposed to be entirely deconnected from the input logic from LatinIME point of
204        // view and only delegates to the parts of the code that care. So we don't include them here
205        // to keep these tests as pinpoint as possible and avoid bringing it too many dependencies,
206        // but keep them in mind if something breaks. Commenting them out as is should work.
207        //mLatinIME.onPressKey(codePoint, 0 /* repeatCount */, true /* isSinglePointer */);
208        final Key key = mKeyboard.getKey(codePoint);
209        if (key != null) {
210            final int x = key.getX() + key.getWidth() / 2;
211            final int y = key.getY() + key.getHeight() / 2;
212            mLatinIME.onCodeInput(codePoint, x, y);
213            return;
214        }
215        mLatinIME.onCodeInput(codePoint, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
216        //mLatinIME.onReleaseKey(codePoint, false /* withSliding */);
217    }
218
219    protected void type(final String stringToType) {
220        for (int i = 0; i < stringToType.length(); i = stringToType.offsetByCodePoints(i, 1)) {
221            type(stringToType.codePointAt(i));
222        }
223    }
224
225    protected void waitForDictionaryToBeLoaded() {
226        int remainingAttempts = 300;
227        while (remainingAttempts > 0 && mLatinIME.isCurrentlyWaitingForMainDictionary()) {
228            try {
229                Thread.sleep(200);
230            } catch (InterruptedException e) {
231                // Don't do much
232            } finally {
233                --remainingAttempts;
234            }
235        }
236        if (!mLatinIME.hasMainDictionary()) {
237            throw new RuntimeException("Can't initialize the main dictionary");
238        }
239    }
240
241    protected void changeLanguage(final String locale) {
242        mEditText.mCurrentLocale = LocaleUtils.constructLocaleFromString(locale);
243        SubtypeSwitcher.getInstance().forceLocale(mEditText.mCurrentLocale);
244        mLatinIME.loadKeyboard();
245        runMessages();
246        mKeyboard = mLatinIME.mKeyboardSwitcher.getKeyboard();
247        waitForDictionaryToBeLoaded();
248    }
249
250    protected void pickSuggestionManually(final int index, final String suggestion) {
251        mLatinIME.pickSuggestionManually(index, new SuggestedWordInfo(suggestion, 1,
252                SuggestedWordInfo.KIND_CORRECTION, "main"));
253    }
254
255    // Helper to avoid writing the try{}catch block each time
256    protected static void sleep(final int milliseconds) {
257        try {
258            Thread.sleep(milliseconds);
259        } catch (InterruptedException e) {}
260    }
261}
262