Suggest.java revision 6080f6878b10916013a8a5e1d5f58f8041452c56
1/*
2 * Copyright (C) 2008 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;
18
19import android.content.Context;
20import android.text.TextUtils;
21import android.util.Log;
22
23import com.android.inputmethod.keyboard.Keyboard;
24import com.android.inputmethod.keyboard.ProximityInfo;
25import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
26
27import java.io.File;
28import java.util.ArrayList;
29import java.util.HashSet;
30import java.util.Locale;
31import java.util.concurrent.ConcurrentHashMap;
32
33/**
34 * This class loads a dictionary and provides a list of suggestions for a given sequence of
35 * characters. This includes corrections and completions.
36 */
37public class Suggest implements Dictionary.WordCallback {
38    public static final String TAG = Suggest.class.getSimpleName();
39
40    public static final int APPROX_MAX_WORD_LENGTH = 32;
41
42    public static final int CORRECTION_NONE = 0;
43    public static final int CORRECTION_FULL = 1;
44    public static final int CORRECTION_FULL_BIGRAM = 2;
45
46    // It seems the following values are only used for logging.
47    public static final int DIC_USER_TYPED = 0;
48    public static final int DIC_MAIN = 1;
49    public static final int DIC_USER = 2;
50    public static final int DIC_USER_HISTORY = 3;
51    public static final int DIC_CONTACTS = 4;
52    public static final int DIC_WHITELIST = 6;
53    // If you add a type of dictionary, increment DIC_TYPE_LAST_ID
54    // TODO: this value seems unused. Remove it?
55    public static final int DIC_TYPE_LAST_ID = 6;
56    public static final String DICT_KEY_MAIN = "main";
57    public static final String DICT_KEY_CONTACTS = "contacts";
58    // User dictionary, the system-managed one.
59    public static final String DICT_KEY_USER = "user";
60    // User history dictionary for the unigram map, internal to LatinIME
61    public static final String DICT_KEY_USER_HISTORY_UNIGRAM = "history_unigram";
62    // User history dictionary for the bigram map, internal to LatinIME
63    public static final String DICT_KEY_USER_HISTORY_BIGRAM = "history_bigram";
64    public static final String DICT_KEY_WHITELIST ="whitelist";
65
66    private static final boolean DBG = LatinImeLogger.sDBG;
67
68    private Dictionary mMainDictionary;
69    private ContactsBinaryDictionary mContactsDict;
70    private WhitelistDictionary mWhiteListDictionary;
71    private final ConcurrentHashMap<String, Dictionary> mUnigramDictionaries =
72            new ConcurrentHashMap<String, Dictionary>();
73    private final ConcurrentHashMap<String, Dictionary> mBigramDictionaries =
74            new ConcurrentHashMap<String, Dictionary>();
75
76    private int mPrefMaxSuggestions = 18;
77
78    private static final int PREF_MAX_BIGRAMS = 60;
79
80    private float mAutoCorrectionThreshold;
81
82    private ArrayList<SuggestedWordInfo> mSuggestions = new ArrayList<SuggestedWordInfo>();
83    private ArrayList<SuggestedWordInfo> mBigramSuggestions = new ArrayList<SuggestedWordInfo>();
84    private CharSequence mConsideredWord;
85
86    // TODO: Remove these member variables by passing more context to addWord() callback method
87    private boolean mIsFirstCharCapitalized;
88    private boolean mIsAllUpperCase;
89    private int mTrailingSingleQuotesCount;
90
91    private static final int MINIMUM_SAFETY_NET_CHAR_LENGTH = 4;
92
93    public Suggest(final Context context, final Locale locale) {
94        initAsynchronously(context, locale);
95    }
96
97    /* package for test */ Suggest(final Context context, final File dictionary,
98            final long startOffset, final long length, final Locale locale) {
99        final Dictionary mainDict = DictionaryFactory.createDictionaryForTest(context, dictionary,
100                startOffset, length /* useFullEditDistance */, false, locale);
101        mMainDictionary = mainDict;
102        addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_MAIN, mainDict);
103        addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_MAIN, mainDict);
104        initWhitelistAndAutocorrectAndPool(context, locale);
105    }
106
107    private void initWhitelistAndAutocorrectAndPool(final Context context, final Locale locale) {
108        mWhiteListDictionary = new WhitelistDictionary(context, locale);
109        addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_WHITELIST, mWhiteListDictionary);
110    }
111
112    private void initAsynchronously(final Context context, final Locale locale) {
113        resetMainDict(context, locale);
114
115        // TODO: read the whitelist and init the pool asynchronously too.
116        // initPool should be done asynchronously now that the pool is thread-safe.
117        initWhitelistAndAutocorrectAndPool(context, locale);
118    }
119
120    private static void addOrReplaceDictionary(
121            final ConcurrentHashMap<String, Dictionary> dictionaries,
122            final String key, final Dictionary dict) {
123        final Dictionary oldDict = (dict == null)
124                ? dictionaries.remove(key)
125                : dictionaries.put(key, dict);
126        if (oldDict != null && dict != oldDict) {
127            oldDict.close();
128        }
129    }
130
131    public void resetMainDict(final Context context, final Locale locale) {
132        mMainDictionary = null;
133        new Thread("InitializeBinaryDictionary") {
134            @Override
135            public void run() {
136                final DictionaryCollection newMainDict =
137                        DictionaryFactory.createMainDictionaryFromManager(context, locale);
138                addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_MAIN, newMainDict);
139                addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_MAIN, newMainDict);
140                mMainDictionary = newMainDict;
141            }
142        }.start();
143    }
144
145    // The main dictionary could have been loaded asynchronously.  Don't cache the return value
146    // of this method.
147    public boolean hasMainDictionary() {
148        return null != mMainDictionary && mMainDictionary.isInitialized();
149    }
150
151    public Dictionary getMainDictionary() {
152        return mMainDictionary;
153    }
154
155    public ContactsBinaryDictionary getContactsDictionary() {
156        return mContactsDict;
157    }
158
159    public ConcurrentHashMap<String, Dictionary> getUnigramDictionaries() {
160        return mUnigramDictionaries;
161    }
162
163    public static int getApproxMaxWordLength() {
164        return APPROX_MAX_WORD_LENGTH;
165    }
166
167    /**
168     * Sets an optional user dictionary resource to be loaded. The user dictionary is consulted
169     * before the main dictionary, if set. This refers to the system-managed user dictionary.
170     */
171    public void setUserDictionary(UserBinaryDictionary userDictionary) {
172        addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_USER, userDictionary);
173    }
174
175    /**
176     * Sets an optional contacts dictionary resource to be loaded. It is also possible to remove
177     * the contacts dictionary by passing null to this method. In this case no contacts dictionary
178     * won't be used.
179     */
180    public void setContactsDictionary(ContactsBinaryDictionary contactsDictionary) {
181        mContactsDict = contactsDictionary;
182        addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_CONTACTS, contactsDictionary);
183        addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_CONTACTS, contactsDictionary);
184    }
185
186    public void setUserHistoryDictionary(UserHistoryDictionary userHistoryDictionary) {
187        addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_USER_HISTORY_UNIGRAM,
188                userHistoryDictionary);
189        addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_USER_HISTORY_BIGRAM,
190                userHistoryDictionary);
191    }
192
193    public void setAutoCorrectionThreshold(float threshold) {
194        mAutoCorrectionThreshold = threshold;
195    }
196
197    private static CharSequence capitalizeWord(final boolean all, final boolean first,
198            final CharSequence word) {
199        if (TextUtils.isEmpty(word) || !(all || first)) return word;
200        final int wordLength = word.length();
201        final StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
202        // TODO: Must pay attention to locale when changing case.
203        if (all) {
204            sb.append(word.toString().toUpperCase());
205        } else if (first) {
206            sb.append(Character.toUpperCase(word.charAt(0)));
207            if (wordLength > 1) {
208                sb.append(word.subSequence(1, wordLength));
209            }
210        }
211        return sb;
212    }
213
214    protected void addBigramToSuggestions(SuggestedWordInfo bigram) {
215        mSuggestions.add(bigram);
216    }
217
218    private static final WordComposer sEmptyWordComposer = new WordComposer();
219    public SuggestedWords getBigramPredictions(CharSequence prevWordForBigram) {
220        LatinImeLogger.onStartSuggestion(prevWordForBigram);
221        mIsFirstCharCapitalized = false;
222        mIsAllUpperCase = false;
223        mTrailingSingleQuotesCount = 0;
224        mSuggestions = new ArrayList<SuggestedWordInfo>(mPrefMaxSuggestions);
225
226        // Treating USER_TYPED as UNIGRAM suggestion for logging now.
227        LatinImeLogger.onAddSuggestedWord("", Suggest.DIC_USER_TYPED, Dictionary.UNIGRAM);
228        mConsideredWord = "";
229
230        mBigramSuggestions = new ArrayList<SuggestedWordInfo>(PREF_MAX_BIGRAMS);
231
232        getAllBigrams(prevWordForBigram, sEmptyWordComposer);
233
234        // Nothing entered: return all bigrams for the previous word
235        int insertCount = Math.min(mBigramSuggestions.size(), mPrefMaxSuggestions);
236        for (int i = 0; i < insertCount; ++i) {
237            addBigramToSuggestions(mBigramSuggestions.get(i));
238        }
239
240        SuggestedWordInfo.removeDups(mSuggestions);
241
242        return new SuggestedWords(mSuggestions,
243                false /* typedWordValid */,
244                false /* hasAutoCorrectionCandidate */,
245                false /* allowsToBeAutoCorrected */,
246                false /* isPunctuationSuggestions */,
247                false /* isObsoleteSuggestions */,
248                true /* isPrediction */);
249    }
250
251    // TODO: cleanup dictionaries looking up and suggestions building with SuggestedWords.Builder
252    public SuggestedWords getSuggestedWords(
253            final WordComposer wordComposer, CharSequence prevWordForBigram,
254            final ProximityInfo proximityInfo, final int correctionMode) {
255        LatinImeLogger.onStartSuggestion(prevWordForBigram);
256        mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
257        mIsAllUpperCase = wordComposer.isAllUpperCase();
258        mTrailingSingleQuotesCount = wordComposer.trailingSingleQuotesCount();
259        mSuggestions = new ArrayList<SuggestedWordInfo>(mPrefMaxSuggestions);
260
261        final String typedWord = wordComposer.getTypedWord();
262        final String consideredWord = mTrailingSingleQuotesCount > 0
263                ? typedWord.substring(0, typedWord.length() - mTrailingSingleQuotesCount)
264                : typedWord;
265        // Treating USER_TYPED as UNIGRAM suggestion for logging now.
266        LatinImeLogger.onAddSuggestedWord(typedWord, Suggest.DIC_USER_TYPED, Dictionary.UNIGRAM);
267        mConsideredWord = consideredWord;
268
269        if (wordComposer.size() <= 1 && (correctionMode == CORRECTION_FULL_BIGRAM)) {
270            // At first character typed, search only the bigrams
271            mBigramSuggestions = new ArrayList<SuggestedWordInfo>(PREF_MAX_BIGRAMS);
272
273            if (!TextUtils.isEmpty(prevWordForBigram)) {
274                getAllBigrams(prevWordForBigram, wordComposer);
275                if (TextUtils.isEmpty(consideredWord)) {
276                    // Nothing entered: return all bigrams for the previous word
277                    int insertCount = Math.min(mBigramSuggestions.size(), mPrefMaxSuggestions);
278                    for (int i = 0; i < insertCount; ++i) {
279                        addBigramToSuggestions(mBigramSuggestions.get(i));
280                    }
281                } else {
282                    // Word entered: return only bigrams that match the first char of the typed word
283                    final char currentChar = consideredWord.charAt(0);
284                    // TODO: Must pay attention to locale when changing case.
285                    // TODO: Use codepoint instead of char
286                    final char currentCharUpper = Character.toUpperCase(currentChar);
287                    int count = 0;
288                    final int bigramSuggestionSize = mBigramSuggestions.size();
289                    for (int i = 0; i < bigramSuggestionSize; i++) {
290                        final SuggestedWordInfo bigramSuggestion = mBigramSuggestions.get(i);
291                        final char bigramSuggestionFirstChar =
292                                (char)bigramSuggestion.codePointAt(0);
293                        if (bigramSuggestionFirstChar == currentChar
294                                || bigramSuggestionFirstChar == currentCharUpper) {
295                            addBigramToSuggestions(bigramSuggestion);
296                            if (++count > mPrefMaxSuggestions) break;
297                        }
298                    }
299                }
300            }
301
302        } else if (wordComposer.size() > 1) {
303            final WordComposer wordComposerForLookup;
304            if (mTrailingSingleQuotesCount > 0) {
305                wordComposerForLookup = new WordComposer(wordComposer);
306                for (int i = mTrailingSingleQuotesCount - 1; i >= 0; --i) {
307                    wordComposerForLookup.deleteLast();
308                }
309            } else {
310                wordComposerForLookup = wordComposer;
311            }
312            // At second character typed, search the unigrams (scores being affected by bigrams)
313            for (final String key : mUnigramDictionaries.keySet()) {
314                // Skip UserUnigramDictionary and WhitelistDictionary to lookup
315                if (key.equals(DICT_KEY_USER_HISTORY_UNIGRAM) || key.equals(DICT_KEY_WHITELIST))
316                    continue;
317                final Dictionary dictionary = mUnigramDictionaries.get(key);
318                dictionary.getWords(wordComposerForLookup, prevWordForBigram, this, proximityInfo);
319            }
320        }
321
322        final CharSequence whitelistedWord = capitalizeWord(mIsAllUpperCase,
323                mIsFirstCharCapitalized, mWhiteListDictionary.getWhitelistedWord(consideredWord));
324
325        final boolean hasAutoCorrection;
326        if (CORRECTION_FULL == correctionMode || CORRECTION_FULL_BIGRAM == correctionMode) {
327            final CharSequence autoCorrection =
328                    AutoCorrection.computeAutoCorrectionWord(mUnigramDictionaries, wordComposer,
329                            mSuggestions, consideredWord, mAutoCorrectionThreshold,
330                            whitelistedWord);
331            hasAutoCorrection = (null != autoCorrection);
332        } else {
333            hasAutoCorrection = false;
334        }
335
336        if (whitelistedWord != null) {
337            if (mTrailingSingleQuotesCount > 0) {
338                final StringBuilder sb = new StringBuilder(whitelistedWord);
339                for (int i = mTrailingSingleQuotesCount - 1; i >= 0; --i) {
340                    sb.appendCodePoint(Keyboard.CODE_SINGLE_QUOTE);
341                }
342                mSuggestions.add(0, new SuggestedWordInfo(
343                        sb.toString(), SuggestedWordInfo.MAX_SCORE));
344            } else {
345                mSuggestions.add(0, new SuggestedWordInfo(
346                        whitelistedWord, SuggestedWordInfo.MAX_SCORE));
347            }
348        }
349
350        mSuggestions.add(0, new SuggestedWordInfo(typedWord, SuggestedWordInfo.MAX_SCORE));
351        SuggestedWordInfo.removeDups(mSuggestions);
352
353        final ArrayList<SuggestedWordInfo> suggestionsList;
354        if (DBG) {
355            suggestionsList = getSuggestionsInfoListWithDebugInfo(typedWord, mSuggestions);
356        } else {
357            suggestionsList = mSuggestions;
358        }
359
360        // TODO: Change this scheme - a boolean is not enough. A whitelisted word may be "valid"
361        // but still autocorrected from - in the case the whitelist only capitalizes the word.
362        // The whitelist should be case-insensitive, so it's not possible to be consistent with
363        // a boolean flag. Right now this is handled with a slight hack in
364        // WhitelistDictionary#shouldForciblyAutoCorrectFrom.
365        final boolean allowsToBeAutoCorrected = AutoCorrection.allowsToBeAutoCorrected(
366                getUnigramDictionaries(), consideredWord, wordComposer.isFirstCharCapitalized())
367        // If we don't have a main dictionary, we never want to auto-correct. The reason for this
368        // is, the user may have a contact whose name happens to match a valid word in their
369        // language, and it will unexpectedly auto-correct. For example, if the user types in
370        // English with no dictionary and has a "Will" in their contact list, "will" would
371        // always auto-correct to "Will" which is unwanted. Hence, no main dict => no auto-correct.
372                && hasMainDictionary();
373
374        boolean autoCorrectionAvailable = hasAutoCorrection;
375        if (correctionMode == CORRECTION_FULL || correctionMode == CORRECTION_FULL_BIGRAM) {
376            autoCorrectionAvailable |= !allowsToBeAutoCorrected;
377        }
378        // Don't auto-correct words with multiple capital letter
379        autoCorrectionAvailable &= !wordComposer.isMostlyCaps();
380        autoCorrectionAvailable &= !wordComposer.isResumed();
381        if (allowsToBeAutoCorrected && suggestionsList.size() > 1 && mAutoCorrectionThreshold > 0
382                && Suggest.shouldBlockAutoCorrectionBySafetyNet(typedWord,
383                        suggestionsList.get(1).mWord)) {
384            autoCorrectionAvailable = false;
385        }
386        return new SuggestedWords(suggestionsList,
387                !allowsToBeAutoCorrected /* typedWordValid */,
388                autoCorrectionAvailable /* hasAutoCorrectionCandidate */,
389                allowsToBeAutoCorrected /* allowsToBeAutoCorrected */,
390                false /* isPunctuationSuggestions */,
391                false /* isObsoleteSuggestions */,
392                false /* isPrediction */);
393    }
394
395    /**
396     * Adds all bigram predictions for prevWord. Also checks the lower case version of prevWord if
397     * it contains any upper case characters.
398     */
399    private void getAllBigrams(final CharSequence prevWord, final WordComposer wordComposer) {
400        if (StringUtils.hasUpperCase(prevWord)) {
401            // TODO: Must pay attention to locale when changing case.
402            final CharSequence lowerPrevWord = prevWord.toString().toLowerCase();
403            for (final Dictionary dictionary : mBigramDictionaries.values()) {
404                dictionary.getBigrams(wordComposer, lowerPrevWord, this);
405            }
406        }
407        for (final Dictionary dictionary : mBigramDictionaries.values()) {
408            dictionary.getBigrams(wordComposer, prevWord, this);
409        }
410    }
411
412    private static ArrayList<SuggestedWordInfo> getSuggestionsInfoListWithDebugInfo(
413            final String typedWord, final ArrayList<SuggestedWordInfo> suggestions) {
414        final SuggestedWordInfo typedWordInfo = suggestions.get(0);
415        typedWordInfo.setDebugString("+");
416        final int suggestionsSize = suggestions.size();
417        final ArrayList<SuggestedWordInfo> suggestionsList =
418                new ArrayList<SuggestedWordInfo>(suggestionsSize);
419        suggestionsList.add(typedWordInfo);
420        // Note: i here is the index in mScores[], but the index in mSuggestions is one more
421        // than i because we added the typed word to mSuggestions without touching mScores.
422        for (int i = 0; i < suggestionsSize - 1; ++i) {
423            final SuggestedWordInfo cur = suggestions.get(i + 1);
424            final float normalizedScore = BinaryDictionary.calcNormalizedScore(
425                    typedWord, cur.toString(), cur.mScore);
426            final String scoreInfoString;
427            if (normalizedScore > 0) {
428                scoreInfoString = String.format("%d (%4.2f)", cur.mScore, normalizedScore);
429            } else {
430                scoreInfoString = Integer.toString(cur.mScore);
431            }
432            cur.setDebugString(scoreInfoString);
433            suggestionsList.add(cur);
434        }
435        return suggestionsList;
436    }
437
438    // TODO: Use codepoint instead of char
439    @Override
440    public boolean addWord(final char[] word, final int offset, final int length, int score,
441            final int dicTypeId, final int dataType) {
442        int dataTypeForLog = dataType;
443        final ArrayList<SuggestedWordInfo> suggestions;
444        final int prefMaxSuggestions;
445        if (dataType == Dictionary.BIGRAM) {
446            suggestions = mBigramSuggestions;
447            prefMaxSuggestions = PREF_MAX_BIGRAMS;
448        } else {
449            suggestions = mSuggestions;
450            prefMaxSuggestions = mPrefMaxSuggestions;
451        }
452
453        int pos = 0;
454
455        // Check if it's the same word, only caps are different
456        if (StringUtils.equalsIgnoreCase(mConsideredWord, word, offset, length)) {
457            // TODO: remove this surrounding if clause and move this logic to
458            // getSuggestedWordBuilder.
459            if (suggestions.size() > 0) {
460                final SuggestedWordInfo currentHighestWord = suggestions.get(0);
461                // If the current highest word is also equal to typed word, we need to compare
462                // frequency to determine the insertion position. This does not ensure strictly
463                // correct ordering, but ensures the top score is on top which is enough for
464                // removing duplicates correctly.
465                if (StringUtils.equalsIgnoreCase(currentHighestWord.mWord, word, offset, length)
466                        && score <= currentHighestWord.mScore) {
467                    pos = 1;
468                }
469            }
470        } else {
471            // Check the last one's score and bail
472            if (suggestions.size() >= prefMaxSuggestions
473                    && suggestions.get(prefMaxSuggestions - 1).mScore >= score) return true;
474            while (pos < suggestions.size()) {
475                final int curScore = suggestions.get(pos).mScore;
476                if (curScore < score
477                        || (curScore == score && length < suggestions.get(pos).codePointCount())) {
478                    break;
479                }
480                pos++;
481            }
482        }
483        if (pos >= prefMaxSuggestions) {
484            return true;
485        }
486
487        final StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
488        // TODO: Must pay attention to locale when changing case.
489        if (mIsAllUpperCase) {
490            sb.append(new String(word, offset, length).toUpperCase());
491        } else if (mIsFirstCharCapitalized) {
492            sb.append(Character.toUpperCase(word[offset]));
493            if (length > 1) {
494                sb.append(word, offset + 1, length - 1);
495            }
496        } else {
497            sb.append(word, offset, length);
498        }
499        for (int i = mTrailingSingleQuotesCount - 1; i >= 0; --i) {
500            sb.appendCodePoint(Keyboard.CODE_SINGLE_QUOTE);
501        }
502        suggestions.add(pos, new SuggestedWordInfo(sb, score));
503        if (suggestions.size() > prefMaxSuggestions) {
504            suggestions.remove(prefMaxSuggestions);
505        } else {
506            LatinImeLogger.onAddSuggestedWord(sb.toString(), dicTypeId, dataTypeForLog);
507        }
508        return true;
509    }
510
511    public void close() {
512        final HashSet<Dictionary> dictionaries = new HashSet<Dictionary>();
513        dictionaries.addAll(mUnigramDictionaries.values());
514        dictionaries.addAll(mBigramDictionaries.values());
515        for (final Dictionary dictionary : dictionaries) {
516            dictionary.close();
517        }
518        mMainDictionary = null;
519    }
520
521    // TODO: Resolve the inconsistencies between the native auto correction algorithms and
522    // this safety net
523    public static boolean shouldBlockAutoCorrectionBySafetyNet(final String typedWord,
524            final CharSequence suggestion) {
525        // Safety net for auto correction.
526        // Actually if we hit this safety net, it's a bug.
527        // If user selected aggressive auto correction mode, there is no need to use the safety
528        // net.
529        // If the length of typed word is less than MINIMUM_SAFETY_NET_CHAR_LENGTH,
530        // we should not use net because relatively edit distance can be big.
531        final int typedWordLength = typedWord.length();
532        if (typedWordLength < Suggest.MINIMUM_SAFETY_NET_CHAR_LENGTH) {
533            return false;
534        }
535        final int maxEditDistanceOfNativeDictionary =
536                (typedWordLength < 5 ? 2 : typedWordLength / 2) + 1;
537        final int distance = BinaryDictionary.editDistance(typedWord, suggestion.toString());
538        if (DBG) {
539            Log.d(TAG, "Autocorrected edit distance = " + distance
540                    + ", " + maxEditDistanceOfNativeDictionary);
541        }
542        if (distance > maxEditDistanceOfNativeDictionary) {
543            if (DBG) {
544                Log.e(TAG, "Safety net: before = " + typedWord + ", after = " + suggestion);
545                Log.e(TAG, "(Error) The edit distance of this correction exceeds limit. "
546                        + "Turning off auto-correction.");
547            }
548            return true;
549        } else {
550            return false;
551        }
552    }
553}
554