AndroidSpellCheckerService.java revision bb2b30fc7ff31182d314e4db9baf1913bf08522d
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.inputmethod.latin.spellcheck;
18
19import android.content.Intent;
20import android.content.SharedPreferences;
21import android.content.res.Resources;
22import android.preference.PreferenceManager;
23import android.service.textservice.SpellCheckerService;
24import android.text.TextUtils;
25import android.util.Log;
26import android.view.textservice.SuggestionsInfo;
27import android.view.textservice.TextInfo;
28
29import com.android.inputmethod.compat.ArraysCompatUtils;
30import com.android.inputmethod.keyboard.ProximityInfo;
31import com.android.inputmethod.latin.BinaryDictionary;
32import com.android.inputmethod.latin.Dictionary;
33import com.android.inputmethod.latin.Dictionary.DataType;
34import com.android.inputmethod.latin.Dictionary.WordCallback;
35import com.android.inputmethod.latin.DictionaryCollection;
36import com.android.inputmethod.latin.DictionaryFactory;
37import com.android.inputmethod.latin.Flag;
38import com.android.inputmethod.latin.LocaleUtils;
39import com.android.inputmethod.latin.R;
40import com.android.inputmethod.latin.SynchronouslyLoadedContactsDictionary;
41import com.android.inputmethod.latin.SynchronouslyLoadedUserDictionary;
42import com.android.inputmethod.latin.Utils;
43import com.android.inputmethod.latin.WhitelistDictionary;
44import com.android.inputmethod.latin.WordComposer;
45
46import java.lang.ref.WeakReference;
47import java.util.ArrayList;
48import java.util.Arrays;
49import java.util.Collections;
50import java.util.Iterator;
51import java.util.Locale;
52import java.util.Map;
53import java.util.TreeMap;
54import java.util.HashSet;
55
56/**
57 * Service for spell checking, using LatinIME's dictionaries and mechanisms.
58 */
59public class AndroidSpellCheckerService extends SpellCheckerService
60        implements SharedPreferences.OnSharedPreferenceChangeListener {
61    private static final String TAG = AndroidSpellCheckerService.class.getSimpleName();
62    private static final boolean DBG = false;
63    private static final int POOL_SIZE = 2;
64
65    public static final String PREF_USE_CONTACTS_KEY = "pref_spellcheck_use_contacts";
66
67    private static final int CAPITALIZE_NONE = 0; // No caps, or mixed case
68    private static final int CAPITALIZE_FIRST = 1; // First only
69    private static final int CAPITALIZE_ALL = 2; // All caps
70
71    private final static String[] EMPTY_STRING_ARRAY = new String[0];
72    private final static Flag[] USE_FULL_EDIT_DISTANCE_FLAG_ARRAY;
73    static {
74        // See BinaryDictionary.java for an explanation of these flags
75        // Specifially, ALL_CONFIG_FLAGS means that we want to consider all flags with the
76        // current dictionary configuration - for example, consider the UMLAUT flag
77        // so that it will be turned on for German dictionaries and off for others.
78        USE_FULL_EDIT_DISTANCE_FLAG_ARRAY = Arrays.copyOf(BinaryDictionary.ALL_CONFIG_FLAGS,
79                BinaryDictionary.ALL_CONFIG_FLAGS.length + 1);
80        USE_FULL_EDIT_DISTANCE_FLAG_ARRAY[BinaryDictionary.ALL_CONFIG_FLAGS.length] =
81                BinaryDictionary.FLAG_USE_FULL_EDIT_DISTANCE;
82    }
83    private Map<String, DictionaryPool> mDictionaryPools =
84            Collections.synchronizedMap(new TreeMap<String, DictionaryPool>());
85    private Map<String, Dictionary> mUserDictionaries =
86            Collections.synchronizedMap(new TreeMap<String, Dictionary>());
87    private Map<String, Dictionary> mWhitelistDictionaries =
88            Collections.synchronizedMap(new TreeMap<String, Dictionary>());
89    private SynchronouslyLoadedContactsDictionary mContactsDictionary;
90
91    // The threshold for a candidate to be offered as a suggestion.
92    private double mSuggestionThreshold;
93    // The threshold for a suggestion to be considered "recommended".
94    private double mRecommendedThreshold;
95    // Whether to use the contacts dictionary
96    private boolean mUseContactsDictionary;
97    private final Object mUseContactsLock = new Object();
98
99    private final HashSet<WeakReference<DictionaryCollection>> mDictionaryCollectionsList =
100            new HashSet<WeakReference<DictionaryCollection>>();
101
102    @Override public void onCreate() {
103        super.onCreate();
104        mSuggestionThreshold =
105                Double.parseDouble(getString(R.string.spellchecker_suggestion_threshold_value));
106        mRecommendedThreshold =
107                Double.parseDouble(getString(R.string.spellchecker_recommended_threshold_value));
108        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
109        prefs.registerOnSharedPreferenceChangeListener(this);
110        onSharedPreferenceChanged(prefs, PREF_USE_CONTACTS_KEY);
111    }
112
113    @Override
114    public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
115        if (!PREF_USE_CONTACTS_KEY.equals(key)) return;
116        synchronized(mUseContactsLock) {
117            mUseContactsDictionary = prefs.getBoolean(PREF_USE_CONTACTS_KEY, true);
118            if (mUseContactsDictionary) {
119                startUsingContactsDictionaryLocked();
120            } else {
121                stopUsingContactsDictionaryLocked();
122            }
123        }
124    }
125
126    private void startUsingContactsDictionaryLocked() {
127        if (null == mContactsDictionary) {
128            mContactsDictionary = new SynchronouslyLoadedContactsDictionary(this);
129        }
130        final Iterator<WeakReference<DictionaryCollection>> iterator =
131                mDictionaryCollectionsList.iterator();
132        while (iterator.hasNext()) {
133            final WeakReference<DictionaryCollection> dictRef = iterator.next();
134            final DictionaryCollection dict = dictRef.get();
135            if (null == dict) {
136                iterator.remove();
137            } else {
138                dict.addDictionary(mContactsDictionary);
139            }
140        }
141    }
142
143    private void stopUsingContactsDictionaryLocked() {
144        if (null == mContactsDictionary) return;
145        final SynchronouslyLoadedContactsDictionary contactsDict = mContactsDictionary;
146        mContactsDictionary = null;
147        final Iterator<WeakReference<DictionaryCollection>> iterator =
148                mDictionaryCollectionsList.iterator();
149        while (iterator.hasNext()) {
150            final WeakReference<DictionaryCollection> dictRef = iterator.next();
151            final DictionaryCollection dict = dictRef.get();
152            if (null == dict) {
153                iterator.remove();
154            } else {
155                dict.removeDictionary(contactsDict);
156            }
157        }
158        contactsDict.close();
159    }
160
161    @Override
162    public Session createSession() {
163        return new AndroidSpellCheckerSession(this);
164    }
165
166    private static SuggestionsInfo getNotInDictEmptySuggestions() {
167        return new SuggestionsInfo(0, EMPTY_STRING_ARRAY);
168    }
169
170    private static SuggestionsInfo getInDictEmptySuggestions() {
171        return new SuggestionsInfo(SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY,
172                EMPTY_STRING_ARRAY);
173    }
174
175    private static class SuggestionsGatherer implements WordCallback {
176        public static class Result {
177            public final String[] mSuggestions;
178            public final boolean mHasRecommendedSuggestions;
179            public Result(final String[] gatheredSuggestions,
180                    final boolean hasRecommendedSuggestions) {
181                mSuggestions = gatheredSuggestions;
182                mHasRecommendedSuggestions = hasRecommendedSuggestions;
183            }
184        }
185
186        private final ArrayList<CharSequence> mSuggestions;
187        private final int[] mScores;
188        private final String mOriginalText;
189        private final double mSuggestionThreshold;
190        private final double mRecommendedThreshold;
191        private final int mMaxLength;
192        private int mLength = 0;
193
194        // The two following attributes are only ever filled if the requested max length
195        // is 0 (or less, which is treated the same).
196        private String mBestSuggestion = null;
197        private int mBestScore = Integer.MIN_VALUE; // As small as possible
198
199        SuggestionsGatherer(final String originalText, final double suggestionThreshold,
200                final double recommendedThreshold, final int maxLength) {
201            mOriginalText = originalText;
202            mSuggestionThreshold = suggestionThreshold;
203            mRecommendedThreshold = recommendedThreshold;
204            mMaxLength = maxLength;
205            mSuggestions = new ArrayList<CharSequence>(maxLength + 1);
206            mScores = new int[mMaxLength];
207        }
208
209        @Override
210        synchronized public boolean addWord(char[] word, int wordOffset, int wordLength, int score,
211                int dicTypeId, DataType dataType) {
212            final int positionIndex = ArraysCompatUtils.binarySearch(mScores, 0, mLength, score);
213            // binarySearch returns the index if the element exists, and -<insertion index> - 1
214            // if it doesn't. See documentation for binarySearch.
215            final int insertIndex = positionIndex >= 0 ? positionIndex : -positionIndex - 1;
216
217            if (insertIndex == 0 && mLength >= mMaxLength) {
218                // In the future, we may want to keep track of the best suggestion score even if
219                // we are asked for 0 suggestions. In this case, we can use the following
220                // (tested) code to keep it:
221                // If the maxLength is 0 (should never be less, but if it is, it's treated as 0)
222                // then we need to keep track of the best suggestion in mBestScore and
223                // mBestSuggestion. This is so that we know whether the best suggestion makes
224                // the score cutoff, since we need to know that to return a meaningful
225                // looksLikeTypo.
226                // if (0 >= mMaxLength) {
227                //     if (score > mBestScore) {
228                //         mBestScore = score;
229                //         mBestSuggestion = new String(word, wordOffset, wordLength);
230                //     }
231                // }
232                return true;
233            }
234            if (insertIndex >= mMaxLength) {
235                // We found a suggestion, but its score is too weak to be kept considering
236                // the suggestion limit.
237                return true;
238            }
239
240            // Compute the normalized score and skip this word if it's normalized score does not
241            // make the threshold.
242            final String wordString = new String(word, wordOffset, wordLength);
243            final double normalizedScore =
244                    Utils.calcNormalizedScore(mOriginalText, wordString, score);
245            if (normalizedScore < mSuggestionThreshold) {
246                if (DBG) Log.i(TAG, wordString + " does not make the score threshold");
247                return true;
248            }
249
250            if (mLength < mMaxLength) {
251                final int copyLen = mLength - insertIndex;
252                ++mLength;
253                System.arraycopy(mScores, insertIndex, mScores, insertIndex + 1, copyLen);
254                mSuggestions.add(insertIndex, wordString);
255            } else {
256                System.arraycopy(mScores, 1, mScores, 0, insertIndex);
257                mSuggestions.add(insertIndex, wordString);
258                mSuggestions.remove(0);
259            }
260            mScores[insertIndex] = score;
261
262            return true;
263        }
264
265        public Result getResults(final int capitalizeType, final Locale locale) {
266            final String[] gatheredSuggestions;
267            final boolean hasRecommendedSuggestions;
268            if (0 == mLength) {
269                // Either we found no suggestions, or we found some BUT the max length was 0.
270                // If we found some mBestSuggestion will not be null. If it is null, then
271                // we found none, regardless of the max length.
272                if (null == mBestSuggestion) {
273                    gatheredSuggestions = null;
274                    hasRecommendedSuggestions = false;
275                } else {
276                    gatheredSuggestions = EMPTY_STRING_ARRAY;
277                    final double normalizedScore =
278                            Utils.calcNormalizedScore(mOriginalText, mBestSuggestion, mBestScore);
279                    hasRecommendedSuggestions = (normalizedScore > mRecommendedThreshold);
280                }
281            } else {
282                if (DBG) {
283                    if (mLength != mSuggestions.size()) {
284                        Log.e(TAG, "Suggestion size is not the same as stored mLength");
285                    }
286                    for (int i = mLength - 1; i >= 0; --i) {
287                        Log.i(TAG, "" + mScores[i] + " " + mSuggestions.get(i));
288                    }
289                }
290                Collections.reverse(mSuggestions);
291                Utils.removeDupes(mSuggestions);
292                if (CAPITALIZE_ALL == capitalizeType) {
293                    for (int i = 0; i < mSuggestions.size(); ++i) {
294                        // get(i) returns a CharSequence which is actually a String so .toString()
295                        // should return the same object.
296                        mSuggestions.set(i, mSuggestions.get(i).toString().toUpperCase(locale));
297                    }
298                } else if (CAPITALIZE_FIRST == capitalizeType) {
299                    for (int i = 0; i < mSuggestions.size(); ++i) {
300                        // Likewise
301                        mSuggestions.set(i, Utils.toTitleCase(mSuggestions.get(i).toString(),
302                                locale));
303                    }
304                }
305                // This returns a String[], while toArray() returns an Object[] which cannot be cast
306                // into a String[].
307                gatheredSuggestions = mSuggestions.toArray(EMPTY_STRING_ARRAY);
308
309                final int bestScore = mScores[mLength - 1];
310                final CharSequence bestSuggestion = mSuggestions.get(0);
311                final double normalizedScore =
312                        Utils.calcNormalizedScore(mOriginalText, bestSuggestion, bestScore);
313                hasRecommendedSuggestions = (normalizedScore > mRecommendedThreshold);
314                if (DBG) {
315                    Log.i(TAG, "Best suggestion : " + bestSuggestion + ", score " + bestScore);
316                    Log.i(TAG, "Normalized score = " + normalizedScore
317                            + " (threshold " + mRecommendedThreshold
318                            + ") => hasRecommendedSuggestions = " + hasRecommendedSuggestions);
319                }
320            }
321            return new Result(gatheredSuggestions, hasRecommendedSuggestions);
322        }
323    }
324
325    @Override
326    public boolean onUnbind(final Intent intent) {
327        final Map<String, DictionaryPool> oldPools = mDictionaryPools;
328        mDictionaryPools = Collections.synchronizedMap(new TreeMap<String, DictionaryPool>());
329        final Map<String, Dictionary> oldUserDictionaries = mUserDictionaries;
330        mUserDictionaries = Collections.synchronizedMap(new TreeMap<String, Dictionary>());
331        final Map<String, Dictionary> oldWhitelistDictionaries = mWhitelistDictionaries;
332        mWhitelistDictionaries = Collections.synchronizedMap(new TreeMap<String, Dictionary>());
333        for (DictionaryPool pool : oldPools.values()) {
334            pool.close();
335        }
336        for (Dictionary dict : oldUserDictionaries.values()) {
337            dict.close();
338        }
339        for (Dictionary dict : oldWhitelistDictionaries.values()) {
340            dict.close();
341        }
342        synchronized(mUseContactsLock) {
343            if (null != mContactsDictionary) {
344                // The synchronously loaded contacts dictionary should have been in one
345                // or several pools, but it is shielded against multiple closing and it's
346                // safe to call it several times.
347                final SynchronouslyLoadedContactsDictionary dictToClose = mContactsDictionary;
348                mContactsDictionary = null;
349                dictToClose.close();
350            }
351        }
352        return false;
353    }
354
355    private DictionaryPool getDictionaryPool(final String locale) {
356        DictionaryPool pool = mDictionaryPools.get(locale);
357        if (null == pool) {
358            final Locale localeObject = LocaleUtils.constructLocaleFromString(locale);
359            pool = new DictionaryPool(POOL_SIZE, this, localeObject);
360            mDictionaryPools.put(locale, pool);
361        }
362        return pool;
363    }
364
365    public DictAndProximity createDictAndProximity(final Locale locale) {
366        final ProximityInfo proximityInfo = ProximityInfo.createSpellCheckerProximityInfo();
367        final Resources resources = getResources();
368        final int fallbackResourceId = Utils.getMainDictionaryResourceId(resources);
369        final DictionaryCollection dictionaryCollection =
370                DictionaryFactory.createDictionaryFromManager(this, locale, fallbackResourceId,
371                        USE_FULL_EDIT_DISTANCE_FLAG_ARRAY);
372        final String localeStr = locale.toString();
373        Dictionary userDictionary = mUserDictionaries.get(localeStr);
374        if (null == userDictionary) {
375            userDictionary = new SynchronouslyLoadedUserDictionary(this, localeStr, true);
376            mUserDictionaries.put(localeStr, userDictionary);
377        }
378        dictionaryCollection.addDictionary(userDictionary);
379        Dictionary whitelistDictionary = mWhitelistDictionaries.get(localeStr);
380        if (null == whitelistDictionary) {
381            whitelistDictionary = new WhitelistDictionary(this, locale);
382            mWhitelistDictionaries.put(localeStr, whitelistDictionary);
383        }
384        dictionaryCollection.addDictionary(whitelistDictionary);
385        synchronized(mUseContactsLock) {
386            if (mUseContactsDictionary) {
387                if (null == mContactsDictionary) {
388                    mContactsDictionary = new SynchronouslyLoadedContactsDictionary(this);
389                }
390            }
391            dictionaryCollection.addDictionary(mContactsDictionary);
392            mDictionaryCollectionsList.add(
393                    new WeakReference<DictionaryCollection>(dictionaryCollection));
394        }
395        return new DictAndProximity(dictionaryCollection, proximityInfo);
396    }
397
398    // This method assumes the text is not empty or null.
399    private static int getCapitalizationType(String text) {
400        // If the first char is not uppercase, then the word is either all lower case,
401        // and in either case we return CAPITALIZE_NONE.
402        if (!Character.isUpperCase(text.codePointAt(0))) return CAPITALIZE_NONE;
403        final int len = text.codePointCount(0, text.length());
404        int capsCount = 1;
405        for (int i = 1; i < len; ++i) {
406            if (1 != capsCount && i != capsCount) break;
407            if (Character.isUpperCase(text.codePointAt(i))) ++capsCount;
408        }
409        // We know the first char is upper case. So we want to test if either everything
410        // else is lower case, or if everything else is upper case. If the string is
411        // exactly one char long, then we will arrive here with capsCount 1, and this is
412        // correct, too.
413        if (1 == capsCount) return CAPITALIZE_FIRST;
414        return (len == capsCount ? CAPITALIZE_ALL : CAPITALIZE_NONE);
415    }
416
417    private static class AndroidSpellCheckerSession extends Session {
418        private static final int SCRIPT_LATIN = 0;
419        private static final int SCRIPT_CYRILLIC = 1;
420        private static final TreeMap<String, Integer> mLanguageToScript;
421        static {
422            // List of the supported languages and their associated script. We won't check
423            // words written in another script than the selected script, because we know we
424            // don't have those in our dictionary so we will underline everything and we
425            // will never have any suggestions, so it makes no sense checking them.
426            mLanguageToScript = new TreeMap<String, Integer>();
427            mLanguageToScript.put("en", SCRIPT_LATIN);
428            mLanguageToScript.put("fr", SCRIPT_LATIN);
429            mLanguageToScript.put("de", SCRIPT_LATIN);
430            mLanguageToScript.put("nl", SCRIPT_LATIN);
431            mLanguageToScript.put("cs", SCRIPT_LATIN);
432            mLanguageToScript.put("es", SCRIPT_LATIN);
433            mLanguageToScript.put("it", SCRIPT_LATIN);
434            mLanguageToScript.put("ru", SCRIPT_CYRILLIC);
435        }
436
437        // Immutable, but need the locale which is not available in the constructor yet
438        private DictionaryPool mDictionaryPool;
439        // Likewise
440        private Locale mLocale;
441        // Cache this for performance
442        private int mScript; // One of SCRIPT_LATIN or SCRIPT_CYRILLIC for now.
443
444        private final AndroidSpellCheckerService mService;
445
446        AndroidSpellCheckerSession(final AndroidSpellCheckerService service) {
447            mService = service;
448        }
449
450        @Override
451        public void onCreate() {
452            final String localeString = getLocale();
453            mDictionaryPool = mService.getDictionaryPool(localeString);
454            mLocale = LocaleUtils.constructLocaleFromString(localeString);
455            final Integer script = mLanguageToScript.get(mLocale.getLanguage());
456            if (null == script) {
457                throw new RuntimeException("We have been called with an unsupported language: \""
458                        + mLocale.getLanguage() + "\". Framework bug?");
459            }
460            mScript = script;
461        }
462
463        /*
464         * Returns whether the code point is a letter that makes sense for the specified
465         * locale for this spell checker.
466         * The dictionaries supported by Latin IME are described in res/xml/spellchecker.xml
467         * and is limited to EFIGS languages and Russian.
468         * Hence at the moment this explicitly tests for Cyrillic characters or Latin characters
469         * as appropriate, and explicitly excludes CJK, Arabic and Hebrew characters.
470         */
471        private static boolean isLetterCheckableByLanguage(final int codePoint,
472                final int script) {
473            switch (script) {
474            case SCRIPT_LATIN:
475                // Our supported latin script dictionaries (EFIGS) at the moment only include
476                // characters in the C0, C1, Latin Extended A and B, IPA extensions unicode
477                // blocks. As it happens, those are back-to-back in the code range 0x40 to 0x2AF,
478                // so the below is a very efficient way to test for it. As for the 0-0x3F, it's
479                // excluded from isLetter anyway.
480                return codePoint <= 0x2AF && Character.isLetter(codePoint);
481            case SCRIPT_CYRILLIC:
482                // All Cyrillic characters are in the 400~52F block. There are some in the upper
483                // Unicode range, but they are archaic characters that are not used in modern
484                // russian and are not used by our dictionary.
485                return codePoint >= 0x400 && codePoint <= 0x52F && Character.isLetter(codePoint);
486            default:
487                // Should never come here
488                throw new RuntimeException("Impossible value of script: " + script);
489            }
490        }
491
492        /**
493         * Finds out whether a particular string should be filtered out of spell checking.
494         *
495         * This will loosely match URLs, numbers, symbols. To avoid always underlining words that
496         * we know we will never recognize, this accepts a script identifier that should be one
497         * of the SCRIPT_* constants defined above, to rule out quickly characters from very
498         * different languages.
499         *
500         * @param text the string to evaluate.
501         * @param script the identifier for the script this spell checker recognizes
502         * @return true if we should filter this text out, false otherwise
503         */
504        private static boolean shouldFilterOut(final String text, final int script) {
505            if (TextUtils.isEmpty(text) || text.length() <= 1) return true;
506
507            // TODO: check if an equivalent processing can't be done more quickly with a
508            // compiled regexp.
509            // Filter by first letter
510            final int firstCodePoint = text.codePointAt(0);
511            // Filter out words that don't start with a letter or an apostrophe
512            if (!isLetterCheckableByLanguage(firstCodePoint, script)
513                    && '\'' != firstCodePoint) return true;
514
515            // Filter contents
516            final int length = text.length();
517            int letterCount = 0;
518            for (int i = 0; i < length; ++i) {
519                final int codePoint = text.codePointAt(i);
520                // Any word containing a '@' is probably an e-mail address
521                // Any word containing a '/' is probably either an ad-hoc combination of two
522                // words or a URI - in either case we don't want to spell check that
523                if ('@' == codePoint
524                        || '/' == codePoint) return true;
525                if (isLetterCheckableByLanguage(codePoint, script)) ++letterCount;
526            }
527            // Guestimate heuristic: perform spell checking if at least 3/4 of the characters
528            // in this word are letters
529            return (letterCount * 4 < length * 3);
530        }
531
532        // Note : this must be reentrant
533        /**
534         * Gets a list of suggestions for a specific string. This returns a list of possible
535         * corrections for the text passed as an argument. It may split or group words, and
536         * even perform grammatical analysis.
537         */
538        @Override
539        public SuggestionsInfo onGetSuggestions(final TextInfo textInfo,
540                final int suggestionsLimit) {
541            try {
542                final String text = textInfo.getText();
543
544                if (shouldFilterOut(text, mScript)) {
545                    DictAndProximity dictInfo = null;
546                    try {
547                        dictInfo = mDictionaryPool.takeOrGetNull();
548                        if (null == dictInfo) return getNotInDictEmptySuggestions();
549                        return dictInfo.mDictionary.isValidWord(text) ? getInDictEmptySuggestions()
550                                : getNotInDictEmptySuggestions();
551                    } finally {
552                        if (null != dictInfo) {
553                            if (!mDictionaryPool.offer(dictInfo)) {
554                                Log.e(TAG, "Can't re-insert a dictionary into its pool");
555                            }
556                        }
557                    }
558                }
559
560                // TODO: Don't gather suggestions if the limit is <= 0 unless necessary
561                final SuggestionsGatherer suggestionsGatherer = new SuggestionsGatherer(text,
562                        mService.mSuggestionThreshold, mService.mRecommendedThreshold,
563                        suggestionsLimit);
564                final WordComposer composer = new WordComposer();
565                final int length = text.length();
566                for (int i = 0; i < length; ++i) {
567                    final int character = text.codePointAt(i);
568                    final int proximityIndex = SpellCheckerProximityInfo.getIndexOf(character);
569                    final int[] proximities;
570                    if (-1 == proximityIndex) {
571                        proximities = new int[] { character };
572                    } else {
573                        proximities = Arrays.copyOfRange(SpellCheckerProximityInfo.PROXIMITY,
574                                proximityIndex,
575                                proximityIndex + SpellCheckerProximityInfo.ROW_SIZE);
576                    }
577                    composer.add(character, proximities,
578                            WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
579                }
580
581                final int capitalizeType = getCapitalizationType(text);
582                boolean isInDict = true;
583                DictAndProximity dictInfo = null;
584                try {
585                    dictInfo = mDictionaryPool.takeOrGetNull();
586                    if (null == dictInfo) return getNotInDictEmptySuggestions();
587                    dictInfo.mDictionary.getWords(composer, suggestionsGatherer,
588                            dictInfo.mProximityInfo);
589                    isInDict = dictInfo.mDictionary.isValidWord(text);
590                    if (!isInDict && CAPITALIZE_NONE != capitalizeType) {
591                        // We want to test the word again if it's all caps or first caps only.
592                        // If it's fully down, we already tested it, if it's mixed case, we don't
593                        // want to test a lowercase version of it.
594                        isInDict = dictInfo.mDictionary.isValidWord(text.toLowerCase(mLocale));
595                    }
596                } finally {
597                    if (null != dictInfo) {
598                        if (!mDictionaryPool.offer(dictInfo)) {
599                            Log.e(TAG, "Can't re-insert a dictionary into its pool");
600                        }
601                    }
602                }
603
604                final SuggestionsGatherer.Result result = suggestionsGatherer.getResults(
605                        capitalizeType, mLocale);
606
607                if (DBG) {
608                    Log.i(TAG, "Spell checking results for " + text + " with suggestion limit "
609                            + suggestionsLimit);
610                    Log.i(TAG, "IsInDict = " + isInDict);
611                    Log.i(TAG, "LooksLikeTypo = " + (!isInDict));
612                    Log.i(TAG, "HasRecommendedSuggestions = " + result.mHasRecommendedSuggestions);
613                    if (null != result.mSuggestions) {
614                        for (String suggestion : result.mSuggestions) {
615                            Log.i(TAG, suggestion);
616                        }
617                    }
618                }
619
620                final int flags =
621                        (isInDict ? SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY
622                                : SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO)
623                        | (result.mHasRecommendedSuggestions
624                                ? SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS
625                                : 0);
626                return new SuggestionsInfo(flags, result.mSuggestions);
627            } catch (RuntimeException e) {
628                // Don't kill the keyboard if there is a bug in the spell checker
629                if (DBG) {
630                    throw e;
631                } else {
632                    Log.e(TAG, "Exception while spellcheking: " + e);
633                    return getNotInDictEmptySuggestions();
634                }
635            }
636        }
637    }
638}
639