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