SuggestedWords.java revision 8380f921f7edaeea2033a1e967a14941400fe246
1/*
2 * Copyright (C) 2010 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.text.TextUtils;
20import android.view.inputmethod.CompletionInfo;
21
22import com.android.inputmethod.annotations.UsedForTesting;
23import com.android.inputmethod.latin.define.DebugFlags;
24import com.android.inputmethod.latin.utils.StringUtils;
25
26import java.util.ArrayList;
27import java.util.Arrays;
28import java.util.HashSet;
29
30public class SuggestedWords {
31    public static final int INDEX_OF_TYPED_WORD = 0;
32    public static final int INDEX_OF_AUTO_CORRECTION = 1;
33    public static final int NOT_A_SEQUENCE_NUMBER = -1;
34
35    public static final int INPUT_STYLE_NONE = 0;
36    public static final int INPUT_STYLE_TYPING = 1;
37    public static final int INPUT_STYLE_UPDATE_BATCH = 2;
38    public static final int INPUT_STYLE_TAIL_BATCH = 3;
39    public static final int INPUT_STYLE_APPLICATION_SPECIFIED = 4;
40    public static final int INPUT_STYLE_RECORRECTION = 5;
41    public static final int INPUT_STYLE_PREDICTION = 6;
42
43    // The maximum number of suggestions available.
44    public static final int MAX_SUGGESTIONS = 18;
45
46    private static final ArrayList<SuggestedWordInfo> EMPTY_WORD_INFO_LIST = new ArrayList<>(0);
47    public static final SuggestedWords EMPTY = new SuggestedWords(
48            EMPTY_WORD_INFO_LIST, null /* rawSuggestions */, false /* typedWordValid */,
49            false /* willAutoCorrect */, false /* isObsoleteSuggestions */, INPUT_STYLE_NONE);
50
51    public final String mTypedWord;
52    public final boolean mTypedWordValid;
53    // Note: this INCLUDES cases where the word will auto-correct to itself. A good definition
54    // of what this flag means would be "the top suggestion is strong enough to auto-correct",
55    // whether this exactly matches the user entry or not.
56    public final boolean mWillAutoCorrect;
57    public final boolean mIsObsoleteSuggestions;
58    // How the input for these suggested words was done by the user. Must be one of the
59    // INPUT_STYLE_* constants above.
60    public final int mInputStyle;
61    public final int mSequenceNumber; // Sequence number for auto-commit.
62    protected final ArrayList<SuggestedWordInfo> mSuggestedWordInfoList;
63    public final ArrayList<SuggestedWordInfo> mRawSuggestions;
64
65    public SuggestedWords(final ArrayList<SuggestedWordInfo> suggestedWordInfoList,
66            final ArrayList<SuggestedWordInfo> rawSuggestions,
67            final boolean typedWordValid,
68            final boolean willAutoCorrect,
69            final boolean isObsoleteSuggestions,
70            final int inputStyle) {
71        this(suggestedWordInfoList, rawSuggestions, typedWordValid, willAutoCorrect,
72                isObsoleteSuggestions, inputStyle, NOT_A_SEQUENCE_NUMBER);
73    }
74
75    public SuggestedWords(final ArrayList<SuggestedWordInfo> suggestedWordInfoList,
76            final ArrayList<SuggestedWordInfo> rawSuggestions,
77            final boolean typedWordValid,
78            final boolean willAutoCorrect,
79            final boolean isObsoleteSuggestions,
80            final int inputStyle,
81            final int sequenceNumber) {
82        this(suggestedWordInfoList, rawSuggestions,
83                (suggestedWordInfoList.isEmpty() || INPUT_STYLE_PREDICTION == inputStyle) ? null
84                        : suggestedWordInfoList.get(INDEX_OF_TYPED_WORD).mWord,
85                typedWordValid, willAutoCorrect, isObsoleteSuggestions, inputStyle,
86                sequenceNumber);
87    }
88
89    public SuggestedWords(final ArrayList<SuggestedWordInfo> suggestedWordInfoList,
90            final ArrayList<SuggestedWordInfo> rawSuggestions,
91            final String typedWord,
92            final boolean typedWordValid,
93            final boolean willAutoCorrect,
94            final boolean isObsoleteSuggestions,
95            final int inputStyle,
96            final int sequenceNumber) {
97        mSuggestedWordInfoList = suggestedWordInfoList;
98        mRawSuggestions = rawSuggestions;
99        mTypedWordValid = typedWordValid;
100        mWillAutoCorrect = willAutoCorrect;
101        mIsObsoleteSuggestions = isObsoleteSuggestions;
102        mInputStyle = inputStyle;
103        mSequenceNumber = sequenceNumber;
104        mTypedWord = typedWord;
105    }
106
107    public boolean isEmpty() {
108        return mSuggestedWordInfoList.isEmpty();
109    }
110
111    public int size() {
112        return mSuggestedWordInfoList.size();
113    }
114
115    /**
116     * Get suggested word at <code>index</code>.
117     * @param index The index of the suggested word.
118     * @return The suggested word.
119     */
120    public String getWord(final int index) {
121        return mSuggestedWordInfoList.get(index).mWord;
122    }
123
124    /**
125     * Get displayed text at <code>index</code>.
126     * In RTL languages, the displayed text on the suggestion strip may be different from the
127     * suggested word that is returned from {@link #getWord(int)}. For example the displayed text
128     * of punctuation suggestion "(" should be ")".
129     * @param index The index of the text to display.
130     * @return The text to be displayed.
131     */
132    public String getLabel(final int index) {
133        return mSuggestedWordInfoList.get(index).mWord;
134    }
135
136    /**
137     * Get {@link SuggestedWordInfo} object at <code>index</code>.
138     * @param index The index of the {@link SuggestedWordInfo}.
139     * @return The {@link SuggestedWordInfo} object.
140     */
141    public SuggestedWordInfo getInfo(final int index) {
142        return mSuggestedWordInfoList.get(index);
143    }
144
145    public String getDebugString(final int pos) {
146        if (!DebugFlags.DEBUG_ENABLED) {
147            return null;
148        }
149        final SuggestedWordInfo wordInfo = getInfo(pos);
150        if (wordInfo == null) {
151            return null;
152        }
153        final String debugString = wordInfo.getDebugString();
154        if (TextUtils.isEmpty(debugString)) {
155            return null;
156        }
157        return debugString;
158    }
159
160    /**
161     * The predicator to tell whether this object represents punctuation suggestions.
162     * @return false if this object desn't represent punctuation suggestions.
163     */
164    public boolean isPunctuationSuggestions() {
165        return false;
166    }
167
168    @Override
169    public String toString() {
170        // Pretty-print method to help debug
171        return "SuggestedWords:"
172                + " mTypedWordValid=" + mTypedWordValid
173                + " mWillAutoCorrect=" + mWillAutoCorrect
174                + " words=" + Arrays.toString(mSuggestedWordInfoList.toArray());
175    }
176
177    public static ArrayList<SuggestedWordInfo> getFromApplicationSpecifiedCompletions(
178            final CompletionInfo[] infos) {
179        final ArrayList<SuggestedWordInfo> result = new ArrayList<>();
180        for (final CompletionInfo info : infos) {
181            if (null == info || null == info.getText()) {
182                continue;
183            }
184            result.add(new SuggestedWordInfo(info));
185        }
186        return result;
187    }
188
189    // Should get rid of the first one (what the user typed previously) from suggestions
190    // and replace it with what the user currently typed.
191    public static ArrayList<SuggestedWordInfo> getTypedWordAndPreviousSuggestions(
192            final String typedWord, final SuggestedWords previousSuggestions) {
193        final ArrayList<SuggestedWordInfo> suggestionsList = new ArrayList<>();
194        final HashSet<String> alreadySeen = new HashSet<>();
195        suggestionsList.add(new SuggestedWordInfo(typedWord, SuggestedWordInfo.MAX_SCORE,
196                SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED,
197                SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
198                SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */));
199        alreadySeen.add(typedWord.toString());
200        final int previousSize = previousSuggestions.size();
201        for (int index = 1; index < previousSize; index++) {
202            final SuggestedWordInfo prevWordInfo = previousSuggestions.getInfo(index);
203            final String prevWord = prevWordInfo.mWord;
204            // Filter out duplicate suggestions.
205            if (!alreadySeen.contains(prevWord)) {
206                suggestionsList.add(prevWordInfo);
207                alreadySeen.add(prevWord);
208            }
209        }
210        return suggestionsList;
211    }
212
213    public SuggestedWordInfo getAutoCommitCandidate() {
214        if (mSuggestedWordInfoList.size() <= 0) return null;
215        final SuggestedWordInfo candidate = mSuggestedWordInfoList.get(0);
216        return candidate.isEligibleForAutoCommit() ? candidate : null;
217    }
218
219    public static final class SuggestedWordInfo {
220        public static final int NOT_AN_INDEX = -1;
221        public static final int NOT_A_CONFIDENCE = -1;
222        public static final int MAX_SCORE = Integer.MAX_VALUE;
223
224        private static final int KIND_MASK_KIND = 0xFF; // Mask to get only the kind
225        public static final int KIND_TYPED = 0; // What user typed
226        public static final int KIND_CORRECTION = 1; // Simple correction/suggestion
227        public static final int KIND_COMPLETION = 2; // Completion (suggestion with appended chars)
228        public static final int KIND_WHITELIST = 3; // Whitelisted word
229        public static final int KIND_BLACKLIST = 4; // Blacklisted word
230        public static final int KIND_HARDCODED = 5; // Hardcoded suggestion, e.g. punctuation
231        public static final int KIND_APP_DEFINED = 6; // Suggested by the application
232        public static final int KIND_SHORTCUT = 7; // A shortcut
233        public static final int KIND_PREDICTION = 8; // A prediction (== a suggestion with no input)
234        // KIND_RESUMED: A resumed suggestion (comes from a span, currently this type is used only
235        // in java for re-correction)
236        public static final int KIND_RESUMED = 9;
237        public static final int KIND_OOV_CORRECTION = 10; // Most probable string correction
238
239        public static final int KIND_FLAG_POSSIBLY_OFFENSIVE = 0x80000000;
240        public static final int KIND_FLAG_EXACT_MATCH = 0x40000000;
241        public static final int KIND_FLAG_EXACT_MATCH_WITH_INTENTIONAL_OMISSION = 0x20000000;
242
243        public final String mWord;
244        // The completion info from the application. Null for suggestions that don't come from
245        // the application (including keyboard-computed ones, so this is almost always null)
246        public final CompletionInfo mApplicationSpecifiedCompletionInfo;
247        public final int mScore;
248        public final int mKindAndFlags;
249        public final int mCodePointCount;
250        public final Dictionary mSourceDict;
251        // For auto-commit. This keeps track of the index inside the touch coordinates array
252        // passed to native code to get suggestions for a gesture that corresponds to the first
253        // letter of the second word.
254        public final int mIndexOfTouchPointOfSecondWord;
255        // For auto-commit. This is a measure of how confident we are that we can commit the
256        // first word of this suggestion.
257        public final int mAutoCommitFirstWordConfidence;
258        private String mDebugString = "";
259
260        /**
261         * Create a new suggested word info.
262         * @param word The string to suggest.
263         * @param score A measure of how likely this suggestion is.
264         * @param kindAndFlags The kind of suggestion, as one of the above KIND_* constants with
265         * flags.
266         * @param sourceDict What instance of Dictionary produced this suggestion.
267         * @param indexOfTouchPointOfSecondWord See mIndexOfTouchPointOfSecondWord.
268         * @param autoCommitFirstWordConfidence See mAutoCommitFirstWordConfidence.
269         */
270        public SuggestedWordInfo(final String word, final int score, final int kindAndFlags,
271                final Dictionary sourceDict, final int indexOfTouchPointOfSecondWord,
272                final int autoCommitFirstWordConfidence) {
273            mWord = word;
274            mApplicationSpecifiedCompletionInfo = null;
275            mScore = score;
276            mKindAndFlags = kindAndFlags;
277            mSourceDict = sourceDict;
278            mCodePointCount = StringUtils.codePointCount(mWord);
279            mIndexOfTouchPointOfSecondWord = indexOfTouchPointOfSecondWord;
280            mAutoCommitFirstWordConfidence = autoCommitFirstWordConfidence;
281        }
282
283        /**
284         * Create a new suggested word info from an application-specified completion.
285         * If the passed argument or its contained text is null, this throws a NPE.
286         * @param applicationSpecifiedCompletion The application-specified completion info.
287         */
288        public SuggestedWordInfo(final CompletionInfo applicationSpecifiedCompletion) {
289            mWord = applicationSpecifiedCompletion.getText().toString();
290            mApplicationSpecifiedCompletionInfo = applicationSpecifiedCompletion;
291            mScore = SuggestedWordInfo.MAX_SCORE;
292            mKindAndFlags = SuggestedWordInfo.KIND_APP_DEFINED;
293            mSourceDict = Dictionary.DICTIONARY_APPLICATION_DEFINED;
294            mCodePointCount = StringUtils.codePointCount(mWord);
295            mIndexOfTouchPointOfSecondWord = SuggestedWordInfo.NOT_AN_INDEX;
296            mAutoCommitFirstWordConfidence = SuggestedWordInfo.NOT_A_CONFIDENCE;
297        }
298
299        public boolean isEligibleForAutoCommit() {
300            return (isKindOf(KIND_CORRECTION) && NOT_AN_INDEX != mIndexOfTouchPointOfSecondWord);
301        }
302
303        public int getKind() {
304            return (mKindAndFlags & KIND_MASK_KIND);
305        }
306
307        public boolean isKindOf(final int kind) {
308            return getKind() == kind;
309        }
310
311        public boolean isPossiblyOffensive() {
312            return (mKindAndFlags & KIND_FLAG_POSSIBLY_OFFENSIVE) != 0;
313        }
314
315        public boolean isExactMatch() {
316            return (mKindAndFlags & KIND_FLAG_EXACT_MATCH) != 0;
317        }
318
319        public boolean isExactMatchWithIntentionalOmission() {
320            return (mKindAndFlags & KIND_FLAG_EXACT_MATCH_WITH_INTENTIONAL_OMISSION) != 0;
321        }
322
323        public void setDebugString(final String str) {
324            if (null == str) throw new NullPointerException("Debug info is null");
325            mDebugString = str;
326        }
327
328        public String getDebugString() {
329            return mDebugString;
330        }
331
332        public int codePointAt(int i) {
333            return mWord.codePointAt(i);
334        }
335
336        @Override
337        public String toString() {
338            if (TextUtils.isEmpty(mDebugString)) {
339                return mWord;
340            } else {
341                return mWord + " (" + mDebugString + ")";
342            }
343        }
344
345        // This will always remove the higher index if a duplicate is found.
346        public static boolean removeDups(final String typedWord,
347                ArrayList<SuggestedWordInfo> candidates) {
348            if (candidates.isEmpty()) {
349                return false;
350            }
351            final boolean didRemoveTypedWord;
352            if (!TextUtils.isEmpty(typedWord)) {
353                didRemoveTypedWord = removeSuggestedWordInfoFrom(typedWord, candidates,
354                        -1 /* startIndexExclusive */);
355            } else {
356                didRemoveTypedWord = false;
357            }
358            for (int i = 0; i < candidates.size(); ++i) {
359                removeSuggestedWordInfoFrom(candidates.get(i).mWord, candidates,
360                        i /* startIndexExclusive */);
361            }
362            return didRemoveTypedWord;
363        }
364
365        private static boolean removeSuggestedWordInfoFrom(final String word,
366                final ArrayList<SuggestedWordInfo> candidates, final int startIndexExclusive) {
367            boolean didRemove = false;
368            for (int i = startIndexExclusive + 1; i < candidates.size(); ++i) {
369                final SuggestedWordInfo previous = candidates.get(i);
370                if (word.equals(previous.mWord)) {
371                    didRemove = true;
372                    candidates.remove(i);
373                    --i;
374                }
375            }
376            return didRemove;
377        }
378    }
379
380    public boolean isPrediction() {
381        return INPUT_STYLE_PREDICTION == mInputStyle;
382    }
383
384    // SuggestedWords is an immutable object, as much as possible. We must not just remove
385    // words from the member ArrayList as some other parties may expect the object to never change.
386    // This is only ever called by recorrection at the moment, hence the ForRecorrection moniker.
387    public SuggestedWords getSuggestedWordsExcludingTypedWordForRecorrection() {
388        final ArrayList<SuggestedWordInfo> newSuggestions = new ArrayList<>();
389        String typedWord = null;
390        for (int i = 0; i < mSuggestedWordInfoList.size(); ++i) {
391            final SuggestedWordInfo info = mSuggestedWordInfoList.get(i);
392            if (!info.isKindOf(SuggestedWordInfo.KIND_TYPED)) {
393                newSuggestions.add(info);
394            } else {
395                assert(null == typedWord);
396                typedWord = info.mWord;
397            }
398        }
399        // We should never autocorrect, so we say the typed word is valid. Also, in this case,
400        // no auto-correction should take place hence willAutoCorrect = false.
401        return new SuggestedWords(newSuggestions, null /* rawSuggestions */, typedWord,
402                true /* typedWordValid */, false /* willAutoCorrect */, mIsObsoleteSuggestions,
403                SuggestedWords.INPUT_STYLE_RECORRECTION, NOT_A_SEQUENCE_NUMBER);
404    }
405
406    // Creates a new SuggestedWordInfo from the currently suggested words that removes all but the
407    // last word of all suggestions, separated by a space. This is necessary because when we commit
408    // a multiple-word suggestion, the IME only retains the last word as the composing word, and
409    // we should only suggest replacements for this last word.
410    // TODO: make this work with languages without spaces.
411    public SuggestedWords getSuggestedWordsForLastWordOfPhraseGesture() {
412        final ArrayList<SuggestedWordInfo> newSuggestions = new ArrayList<>();
413        for (int i = 0; i < mSuggestedWordInfoList.size(); ++i) {
414            final SuggestedWordInfo info = mSuggestedWordInfoList.get(i);
415            final int indexOfLastSpace = info.mWord.lastIndexOf(Constants.CODE_SPACE) + 1;
416            final String lastWord = info.mWord.substring(indexOfLastSpace);
417            newSuggestions.add(new SuggestedWordInfo(lastWord, info.mScore, info.mKindAndFlags,
418                    info.mSourceDict, SuggestedWordInfo.NOT_AN_INDEX,
419                    SuggestedWordInfo.NOT_A_CONFIDENCE));
420        }
421        return new SuggestedWords(newSuggestions, null /* rawSuggestions */, mTypedWordValid,
422                mWillAutoCorrect, mIsObsoleteSuggestions, INPUT_STYLE_TAIL_BATCH);
423    }
424
425    /**
426     * @return the {@link SuggestedWordInfo} which corresponds to the word that is originally
427     * typed by the user. Otherwise returns {@code null}. Note that gesture input is not
428     * considered to be a typed word.
429     */
430    @UsedForTesting
431    public SuggestedWordInfo getTypedWordInfoOrNull() {
432        if (this == EMPTY) {
433            return null;
434        }
435        final SuggestedWordInfo info = getInfo(SuggestedWords.INDEX_OF_TYPED_WORD);
436        return (info.getKind() == SuggestedWordInfo.KIND_TYPED) ? info : null;
437    }
438}
439