diff options
author | 2014-10-21 15:06:54 +0000 | |
---|---|---|
committer | 2014-10-21 15:06:55 +0000 | |
commit | 46a007261fcbfbe887e22ecdf16307f95b1e4024 (patch) | |
tree | d47b90911c51c7ff6eabb6466f47a84d4574cbba /java/src/com/android/inputmethod/latin | |
parent | 0b8bb0c21bda18e77a52d980891d56430e113a6f (diff) | |
parent | 5f00fe09e9a611b647592188316e5999465df4d3 (diff) | |
download | latinime-46a007261fcbfbe887e22ecdf16307f95b1e4024.tar.gz latinime-46a007261fcbfbe887e22ecdf16307f95b1e4024.tar.xz latinime-46a007261fcbfbe887e22ecdf16307f95b1e4024.zip |
Merge "Fix some compiler warnings"
Diffstat (limited to 'java/src/com/android/inputmethod/latin')
45 files changed, 338 insertions, 335 deletions
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java index 867c18686..974fb14e9 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java @@ -121,12 +121,11 @@ final public class BinaryDictionaryGetter { // reason some dictionaries have been installed BUT the dictionary pack can't be // found anymore it's safer to actually supply installed dictionaries. return true; - } else { - // The default is true here for the same reasons as above. We got the dictionary - // pack but if we don't have any settings for it it means the user has never been - // to the settings yet. So by default, the main dictionaries should be on. - return mDictPreferences.getBoolean(dictId, true); } + // The default is true here for the same reasons as above. We got the dictionary + // pack but if we don't have any settings for it it means the user has never been + // to the settings yet. So by default, the main dictionaries should be on. + return mDictPreferences.getBoolean(dictId, true); } } diff --git a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java index 0542c4b27..19f4adc12 100644 --- a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java @@ -26,7 +26,6 @@ import android.os.SystemClock; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.provider.ContactsContract.Contacts; -import android.text.TextUtils; import android.util.Log; import com.android.inputmethod.annotations.UsedForTesting; @@ -164,7 +163,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary { } } - private boolean useFirstLastBigramsForLocale(final Locale locale) { + private static boolean useFirstLastBigramsForLocale(final Locale locale) { // TODO: Add firstname/lastname bigram rules for other languages. if (locale != null && locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) { return true; @@ -269,7 +268,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary { return end; } - private boolean haveContentsChanged() { + boolean haveContentsChanged() { final long startTime = SystemClock.uptimeMillis(); final int contactCount = getContactCount(); if (contactCount > MAX_CONTACT_COUNT) { diff --git a/java/src/com/android/inputmethod/latin/DicTraverseSession.java b/java/src/com/android/inputmethod/latin/DicTraverseSession.java index 2751c1250..710fdf4f3 100644 --- a/java/src/com/android/inputmethod/latin/DicTraverseSession.java +++ b/java/src/com/android/inputmethod/latin/DicTraverseSession.java @@ -70,7 +70,7 @@ public final class DicTraverseSession { mNativeDicTraverseSession, dictionary, previousWord, previousWordLength); } - private final long createNativeDicTraverseSession(String locale, long dictSize) { + private static long createNativeDicTraverseSession(String locale, long dictSize) { return setDicTraverseSessionNative(locale, dictSize); } diff --git a/java/src/com/android/inputmethod/latin/Dictionary.java b/java/src/com/android/inputmethod/latin/Dictionary.java index e66847b56..d8f1b2a20 100644 --- a/java/src/com/android/inputmethod/latin/Dictionary.java +++ b/java/src/com/android/inputmethod/latin/Dictionary.java @@ -72,9 +72,13 @@ public abstract class Dictionary { * Set out of the dictionary types listed above that are based on data specific to the user, * e.g., the user's contacts. */ - private static final HashSet<String> sUserSpecificDictionaryTypes = - new HashSet(Arrays.asList(new String[] { TYPE_USER_TYPED, TYPE_USER, TYPE_CONTACTS, - TYPE_USER_HISTORY, TYPE_PERSONALIZATION, TYPE_CONTEXTUAL })); + private static final HashSet<String> sUserSpecificDictionaryTypes = new HashSet<>(Arrays.asList( + TYPE_USER_TYPED, + TYPE_USER, + TYPE_CONTACTS, + TYPE_USER_HISTORY, + TYPE_PERSONALIZATION, + TYPE_CONTEXTUAL)); public Dictionary(final String dictType, final Locale locale) { mDictType = dictType; diff --git a/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java b/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java index 46ddccd09..7a17dcc56 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java +++ b/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java @@ -172,9 +172,8 @@ public class DictionaryFacilitator { public Dictionary getDict(final String dictType) { if (Dictionary.TYPE_MAIN.equals(dictType)) { return mMainDict; - } else { - return getSubDict(dictType); } + return getSubDict(dictType); } public ExpandableBinaryDictionary getSubDict(final String dictType) { @@ -184,9 +183,8 @@ public class DictionaryFacilitator { public boolean hasDict(final String dictType) { if (Dictionary.TYPE_MAIN.equals(dictType)) { return mMainDict != null; - } else { - return mSubDictMap.containsKey(dictType); } + return mSubDictMap.containsKey(dictType); } public void closeDict(final String dictType) { @@ -305,7 +303,7 @@ public class DictionaryFacilitator { usePersonalizedDicts, forceReloadMainDictionary, listener, "" /* dictNamePrefix */); } - private DictionaryGroup findDictionaryGroupWithLocale(final DictionaryGroup[] dictionaryGroups, + static DictionaryGroup findDictionaryGroupWithLocale(final DictionaryGroup[] dictionaryGroups, final Locale locale) { for (int i = 0; i < dictionaryGroups.length; ++i) { if (locale.equals(dictionaryGroups[i].mLocale)) { @@ -422,34 +420,41 @@ public class DictionaryFacilitator { ExecutorUtils.getExecutor("InitializeBinaryDictionary").execute(new Runnable() { @Override public void run() { - for (final Locale locale : locales) { - final DictionaryGroup dictionaryGroup = - findDictionaryGroupWithLocale(mDictionaryGroups, locale); - if (null == dictionaryGroup) { - // This should never happen, but better safe than crashy - Log.w(TAG, "Expected a dictionary group for " + locale + " but none found"); - continue; - } - final Dictionary mainDict = - DictionaryFactory.createMainDictionaryFromManager(context, locale); - synchronized (mLock) { - if (locale.equals(dictionaryGroup.mLocale)) { - dictionaryGroup.setMainDict(mainDict); - } else { - // Dictionary facilitator has been reset for another locale. - mainDict.close(); - } - } - } - if (listener != null) { - listener.onUpdateMainDictionaryAvailability( - hasAtLeastOneInitializedMainDictionary()); - } - latchForWaitingLoadingMainDictionary.countDown(); + doReloadUninitializedMainDictionaries( + context, locales, listener, latchForWaitingLoadingMainDictionary); } }); } + void doReloadUninitializedMainDictionaries(final Context context, final Locale[] locales, + final DictionaryInitializationListener listener, + final CountDownLatch latchForWaitingLoadingMainDictionary) { + for (final Locale locale : locales) { + final DictionaryGroup dictionaryGroup = + findDictionaryGroupWithLocale(mDictionaryGroups, locale); + if (null == dictionaryGroup) { + // This should never happen, but better safe than crashy + Log.w(TAG, "Expected a dictionary group for " + locale + " but none found"); + continue; + } + final Dictionary mainDict = + DictionaryFactory.createMainDictionaryFromManager(context, locale); + synchronized (mLock) { + if (locale.equals(dictionaryGroup.mLocale)) { + dictionaryGroup.setMainDict(mainDict); + } else { + // Dictionary facilitator has been reset for another locale. + mainDict.close(); + } + } + } + if (listener != null) { + listener.onUpdateMainDictionaryAvailability( + hasAtLeastOneInitializedMainDictionary()); + } + latchForWaitingLoadingMainDictionary.countDown(); + } + @UsedForTesting public void resetDictionariesForTesting(final Context context, final Locale[] locales, final ArrayList<String> dictionaryTypes, final HashMap<String, File> dictionaryFiles, diff --git a/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java b/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java index 1b33d9129..b578159eb 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java +++ b/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java @@ -31,7 +31,7 @@ import android.util.LruCache; * This class automatically creates and releases facilitator instances using LRU policy. */ public class DictionaryFacilitatorLruCache { - private static final String TAG = DictionaryFacilitatorLruCache.class.getSimpleName(); + static final String TAG = DictionaryFacilitatorLruCache.class.getSimpleName(); private static final int WAIT_FOR_LOADING_MAIN_DICT_IN_MILLISECONDS = 1000; private static final int MAX_RETRY_COUNT_FOR_WAITING_FOR_LOADING_DICT = 5; @@ -81,7 +81,8 @@ public class DictionaryFacilitatorLruCache { mDictionaryNamePrefix = dictionaryNamePrefix; } - private void waitForLoadingMainDictionary(final DictionaryFacilitator dictionaryFacilitator) { + private static void waitForLoadingMainDictionary( + final DictionaryFacilitator dictionaryFacilitator) { for (int i = 0; i < MAX_RETRY_COUNT_FOR_WAITING_FOR_LOADING_DICT; i++) { try { dictionaryFacilitator.waitForLoadingMainDictionaries( diff --git a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java index 66eeeca07..ff05a2fcd 100644 --- a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java @@ -21,11 +21,11 @@ import android.util.Log; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.keyboard.ProximityInfo; +import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.android.inputmethod.latin.makedict.DictionaryHeader; import com.android.inputmethod.latin.makedict.FormatSpec; import com.android.inputmethod.latin.makedict.UnsupportedFormatException; import com.android.inputmethod.latin.makedict.WordProperty; -import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.android.inputmethod.latin.settings.SettingsValuesForSuggestion; import com.android.inputmethod.latin.utils.AsyncResultHolder; import com.android.inputmethod.latin.utils.CombinedFormatUtils; @@ -47,6 +47,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * Abstract base class for an expandable dictionary that can be created and updated dynamically @@ -107,11 +108,11 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { */ protected abstract void loadInitialContentsLocked(); - private boolean matchesExpectedBinaryDictFormatVersionForThisType(final int formatVersion) { + static boolean matchesExpectedBinaryDictFormatVersionForThisType(final int formatVersion) { return formatVersion == FormatSpec.VERSION4; } - private boolean needsToMigrateDictionary(final int formatVersion) { + private static boolean needsToMigrateDictionary(final int formatVersion) { // When we bump up the dictionary format version, the old version should be added to here // for supporting migration. Note that native code has to support reading such formats. return formatVersion == FormatSpec.VERSION4_ONLY_FOR_TESTING; @@ -159,7 +160,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { asyncExecuteTaskWithLock(mLock.writeLock(), mDictName /* executorName */, task); } - private void asyncExecuteTaskWithLock(final Lock lock, final String executorName, + private static void asyncExecuteTaskWithLock(final Lock lock, final String executorName, final Runnable task) { asyncPreCheckAndExecuteTaskWithLock(lock, null /* preCheckTask */, executorName, task); } @@ -172,8 +173,9 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { } // Execute task with lock when the result of preCheckTask is true or preCheckTask is null. - private void asyncPreCheckAndExecuteTaskWithLock(final Lock lock, + private static void asyncPreCheckAndExecuteTaskWithLock(final Lock lock, final Callable<Boolean> preCheckTask, final String executorName, final Runnable task) { + final String tag = TAG; ExecutorUtils.getExecutor(executorName).execute(new Runnable() { @Override public void run() { @@ -183,7 +185,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { return; } } catch (final Exception e) { - Log.e(TAG, "The pre check task throws an exception.", e); + Log.e(tag, "The pre check task throws an exception.", e); return; } } @@ -197,6 +199,18 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { }); } + @Nullable + BinaryDictionary getBinaryDictionary() { + return mBinaryDictionary; + } + + void closeBinaryDictionary() { + if (mBinaryDictionary != null) { + mBinaryDictionary.close(); + mBinaryDictionary = null; + } + } + /** * Closes and cleans up the binary dictionary. */ @@ -205,10 +219,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { asyncExecuteTaskWithWriteLock(new Runnable() { @Override public void run() { - if (mBinaryDictionary != null) { - mBinaryDictionary.close(); - mBinaryDictionary = null; - } + closeBinaryDictionary(); } }); } @@ -234,14 +245,11 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { }); } - private void removeBinaryDictionaryLocked() { - if (mBinaryDictionary != null) { - mBinaryDictionary.close(); - } + void removeBinaryDictionaryLocked() { + closeBinaryDictionary(); if (mDictFile.exists() && !FileUtils.deleteRecursively(mDictFile)) { Log.e(TAG, "Can't remove a file: " + mDictFile.getName()); } - mBinaryDictionary = null; } private void openBinaryDictionaryLocked() { @@ -250,7 +258,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { true /* useFullEditDistance */, mLocale, mDictType, true /* isUpdatable */); } - private void createOnMemoryBinaryDictionaryLocked() { + void createOnMemoryBinaryDictionaryLocked() { mBinaryDictionary = new BinaryDictionary( mDictFile.getAbsolutePath(), true /* useFullEditDistance */, mLocale, mDictType, DICTIONARY_FORMAT_VERSION, getHeaderAttributeMap()); @@ -273,7 +281,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { asyncExecuteTaskWithWriteLock(new Runnable() { @Override public void run() { - if (mBinaryDictionary == null) { + if (getBinaryDictionary() == null) { return; } runGCIfRequiredLocked(mindsBlockByGC); @@ -291,24 +299,24 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { @Nonnull final Runnable updateTask, @Nonnull final String word, @Nonnull final DistracterFilter distracterFilter) { reloadDictionaryIfRequired(); - asyncPreCheckAndExecuteTaskWithWriteLock( - new Callable<Boolean>() { - @Override - public Boolean call() throws Exception { - return !distracterFilter.isDistracterToWordsInDictionaries( - NgramContext.EMPTY_PREV_WORDS_INFO, word, mLocale); - } - }, - new Runnable() { - @Override - public void run() { - if (mBinaryDictionary == null) { - return; - } - runGCIfRequiredLocked(true /* mindsBlockByGC */); - updateTask.run(); - } - }); + final Callable<Boolean> preCheckTask = new Callable<Boolean>() { + @Override + public Boolean call() throws Exception { + return !distracterFilter.isDistracterToWordsInDictionaries( + NgramContext.EMPTY_PREV_WORDS_INFO, word, mLocale); + } + }; + final Runnable task = new Runnable() { + @Override + public void run() { + if (getBinaryDictionary() == null) { + return; + } + runGCIfRequiredLocked(true /* mindsBlockByGC */); + updateTask.run(); + } + }; + asyncPreCheckAndExecuteTaskWithWriteLock(preCheckTask, task); } /** @@ -344,11 +352,12 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { asyncExecuteTaskWithWriteLock(new Runnable() { @Override public void run() { - if (mBinaryDictionary == null) { + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary == null) { return; } runGCIfRequiredLocked(true /* mindsBlockByGC */); - if (!mBinaryDictionary.removeUnigramEntry(word)) { + if (!binaryDictionary.removeUnigramEntry(word)) { if (DEBUG) { Log.i(TAG, "Cannot remove unigram entry: " + word); } @@ -366,7 +375,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { asyncExecuteTaskWithWriteLock(new Runnable() { @Override public void run() { - if (mBinaryDictionary == null) { + if (getBinaryDictionary() == null) { return; } runGCIfRequiredLocked(true /* mindsBlockByGC */); @@ -395,11 +404,12 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { asyncExecuteTaskWithWriteLock(new Runnable() { @Override public void run() { - if (mBinaryDictionary == null) { + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary == null) { return; } runGCIfRequiredLocked(true /* mindsBlockByGC */); - if (!mBinaryDictionary.removeNgramEntry(ngramContext, word)) { + if (!binaryDictionary.removeNgramEntry(ngramContext, word)) { if (DEBUG) { Log.i(TAG, "Cannot remove n-gram entry."); Log.i(TAG, " NgramContext: " + ngramContext + ", word: " + word); @@ -418,7 +428,11 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { updateDictionaryWithWriteLockIfWordIsNotADistracter(new Runnable() { @Override public void run() { - if (!mBinaryDictionary.updateEntriesForWordWithNgramContext(ngramContext, word, + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary == null) { + return; + } + if (!binaryDictionary.updateEntriesForWordWithNgramContext(ngramContext, word, isValidWord, count, timestamp)) { if (DEBUG) { Log.e(TAG, "Cannot update counter. word: " + word @@ -444,10 +458,11 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { @Override public void run() { try { - if (mBinaryDictionary == null) { + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary == null) { return; } - mBinaryDictionary.addMultipleDictionaryEntries( + binaryDictionary.addMultipleDictionaryEntries( languageModelParams.toArray( new LanguageModelParam[languageModelParams.size()])); } finally { @@ -555,7 +570,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { * Loads the current binary dictionary from internal storage. Assumes the dictionary file * exists. */ - private void loadBinaryDictionaryLocked() { + void loadBinaryDictionaryLocked() { if (DBG_STRESS_TEST) { // Test if this class does not cause problems when it takes long time to load binary // dictionary. @@ -583,7 +598,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { /** * Create a new binary dictionary and load initial contents. */ - private void createNewDictionaryLocked() { + void createNewDictionaryLocked() { removeBinaryDictionaryLocked(); createOnMemoryBinaryDictionaryLocked(); loadInitialContentsLocked(); @@ -599,6 +614,14 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { mNeedsToRecreate = true; } + void clearNeedsToRecreate() { + mNeedsToRecreate = false; + } + + boolean isNeededToRecreate() { + return mNeedsToRecreate; + } + /** * Load the current binary dictionary from internal storage. If the dictionary file doesn't * exists or needs to be regenerated, the new dictionary file will be asynchronously generated. @@ -621,35 +644,39 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { * Reloads the dictionary. Access is controlled on a per dictionary file basis. */ private final void asyncReloadDictionary() { - if (mIsReloading.compareAndSet(false, true)) { - asyncExecuteTaskWithWriteLock(new Runnable() { - @Override - public void run() { - try { - if (!mDictFile.exists() || mNeedsToRecreate) { - // If the dictionary file does not exist or contents have been updated, - // generate a new one. + final AtomicBoolean isReloading = mIsReloading; + if (!isReloading.compareAndSet(false, true)) { + return; + } + final File dictFile = mDictFile; + asyncExecuteTaskWithWriteLock(new Runnable() { + @Override + public void run() { + try { + if (!dictFile.exists() || isNeededToRecreate()) { + // If the dictionary file does not exist or contents have been updated, + // generate a new one. + createNewDictionaryLocked(); + } else if (getBinaryDictionary() == null) { + // Otherwise, load the existing dictionary. + loadBinaryDictionaryLocked(); + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary != null && !(isValidDictionaryLocked() + // TODO: remove the check below + && matchesExpectedBinaryDictFormatVersionForThisType( + binaryDictionary.getFormatVersion()))) { + // Binary dictionary or its format version is not valid. Regenerate + // the dictionary file. createNewDictionaryLocked will remove the + // existing files if appropriate. createNewDictionaryLocked(); - } else if (mBinaryDictionary == null) { - // Otherwise, load the existing dictionary. - loadBinaryDictionaryLocked(); - if (mBinaryDictionary != null && !(isValidDictionaryLocked() - // TODO: remove the check below - && matchesExpectedBinaryDictFormatVersionForThisType( - mBinaryDictionary.getFormatVersion()))) { - // Binary dictionary or its format version is not valid. Regenerate - // the dictionary file. createNewDictionaryLocked will remove the - // existing files if appropriate. - createNewDictionaryLocked(); - } } - mNeedsToRecreate = false; - } finally { - mIsReloading.set(false); } + clearNeedsToRecreate(); + } finally { + isReloading.set(false); } - }); - } + } + }); } /** @@ -659,19 +686,20 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { asyncExecuteTaskWithWriteLock(new Runnable() { @Override public void run() { - if (mBinaryDictionary == null) { + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary == null) { return; } - if (mBinaryDictionary.needsToRunGC(false /* mindsBlockByGC */)) { - mBinaryDictionary.flushWithGC(); + if (binaryDictionary.needsToRunGC(false /* mindsBlockByGC */)) { + binaryDictionary.flushWithGC(); } else { - mBinaryDictionary.flush(); + binaryDictionary.flush(); } } }); } - private static int parseEntryCount(final String entryCountStr) { + static int parseEntryCount(final String entryCountStr) { int entryCount; try { entryCount = Integer.parseInt(entryCountStr); @@ -683,23 +711,27 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { public DictionaryStats getDictionaryStats() { reloadDictionaryIfRequired(); + final String dictName = mDictName; + final File dictFile = mDictFile; final AsyncResultHolder<DictionaryStats> result = new AsyncResultHolder<>(); - asyncExecuteTaskWithLock(mLock.readLock(), mDictName /* executorName */, new Runnable() { + asyncExecuteTaskWithLock(mLock.readLock(), dictName /* executorName */, new Runnable() { @Override public void run() { - if (mBinaryDictionary == null) { - result.set(new DictionaryStats(mLocale, mDictName, mDictFile, + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary == null) { + result.set(new DictionaryStats(mLocale, dictName, dictFile, DictionaryStats.NOT_AN_ENTRY_COUNT, DictionaryStats.NOT_AN_ENTRY_COUNT)); + return; } final int unigramCount = parseEntryCount( - mBinaryDictionary.getPropertyForGettingStats( + binaryDictionary.getPropertyForGettingStats( BinaryDictionary.MAX_UNIGRAM_COUNT_QUERY)); // TODO: Get dedicated entry counts for bigram, trigram, and so on. - final int ngramCount = parseEntryCount(mBinaryDictionary.getPropertyForGettingStats( + final int ngramCount = parseEntryCount(binaryDictionary.getPropertyForGettingStats( BinaryDictionary.MAX_BIGRAM_COUNT_QUERY)); // TODO: Get more information from dictionary. - result.set(new DictionaryStats(mLocale, mDictName, mDictFile, unigramCount, + result.set(new DictionaryStats(mLocale, dictName, dictFile, unigramCount, ngramCount)); } }); @@ -731,28 +763,34 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { public void dumpAllWordsForDebug() { reloadDictionaryIfRequired(); + final String tag = TAG; + final String dictName = mDictName; asyncExecuteTaskWithLock(mLock.readLock(), "dumpAllWordsForDebug", new Runnable() { @Override public void run() { - Log.d(TAG, "Dump dictionary: " + mDictName + " for " + mLocale); + Log.d(tag, "Dump dictionary: " + dictName + " for " + mLocale); + final BinaryDictionary binaryDictionary = getBinaryDictionary(); + if (binaryDictionary == null) { + return; + } try { - final DictionaryHeader header = mBinaryDictionary.getHeader(); - Log.d(TAG, "Format version: " + mBinaryDictionary.getFormatVersion()); - Log.d(TAG, CombinedFormatUtils.formatAttributeMap( + final DictionaryHeader header = binaryDictionary.getHeader(); + Log.d(tag, "Format version: " + binaryDictionary.getFormatVersion()); + Log.d(tag, CombinedFormatUtils.formatAttributeMap( header.mDictionaryOptions.mAttributes)); } catch (final UnsupportedFormatException e) { - Log.d(TAG, "Cannot fetch header information.", e); + Log.d(tag, "Cannot fetch header information.", e); } int token = 0; do { final BinaryDictionary.GetNextWordPropertyResult result = - mBinaryDictionary.getNextWordProperty(token); + binaryDictionary.getNextWordProperty(token); final WordProperty wordProperty = result.mWordProperty; if (wordProperty == null) { - Log.d(TAG, " dictionary is empty."); + Log.d(tag, " dictionary is empty."); break; } - Log.d(TAG, wordProperty.toString()); + Log.d(tag, wordProperty.toString()); token = result.mNextToken; } while (token != 0); } diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index 91a4ec84c..e59b83954 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -119,15 +119,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen SuggestionStripView.Listener, SuggestionStripViewAccessor, DictionaryFacilitator.DictionaryInitializationListener, ImportantNoticeDialog.ImportantNoticeDialogListener { - private static final String TAG = LatinIME.class.getSimpleName(); + static final String TAG = LatinIME.class.getSimpleName(); private static final boolean TRACE = false; private static boolean DEBUG = false; private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; private static final int PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT = 2; private static final int PENDING_IMS_CALLBACK_DURATION_MILLIS = 800; - private static final long DELAY_WAIT_FOR_DICTIONARY_LOAD_MILLIS = TimeUnit.SECONDS.toMillis(2); - private static final long DELAY_DEALLOCATE_MEMORY_MILLIS = TimeUnit.SECONDS.toMillis(10); + static final long DELAY_WAIT_FOR_DICTIONARY_LOAD_MILLIS = TimeUnit.SECONDS.toMillis(2); + static final long DELAY_DEALLOCATE_MEMORY_MILLIS = TimeUnit.SECONDS.toMillis(10); /** * The name of the scheme used by the Package Manager to warn of a new package installation, @@ -135,7 +135,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen */ private static final String SCHEME_PACKAGE = "package"; - private final Settings mSettings; + final Settings mSettings; private final DictionaryFacilitator mDictionaryFacilitator = new DictionaryFacilitator(this /* context */); // TODO: Move from LatinIME. @@ -149,7 +149,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mHandler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_NONE); } }); - private final InputLogic mInputLogic = new InputLogic(this /* LatinIME */, + final InputLogic mInputLogic = new InputLogic(this /* LatinIME */, this /* SuggestionStripViewAccessor */, mDictionaryFacilitator); // We expect to have only one decoder in almost all cases, hence the default capacity of 1. // If it turns out we need several, it will get grown seamlessly. @@ -163,7 +163,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private RichInputMethodManager mRichImm; @UsedForTesting final KeyboardSwitcher mKeyboardSwitcher; - private final SubtypeSwitcher mSubtypeSwitcher; + final SubtypeSwitcher mSubtypeSwitcher; private final SubtypeState mSubtypeState = new SubtypeState(); private final SpecialKeyDetector mSpecialKeyDetector; private StatsUtilsManager mStatsUtilsManager; @@ -204,7 +204,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1; private static final int ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT = 2; private static final int ARG2_UNUSED = 0; - private static final int ARG1_FALSE = 0; private static final int ARG1_TRUE = 1; private int mDelayInMillisecondsToUpdateSuggestions; @@ -654,7 +653,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } - private void resetDictionaryFacilitatorIfNecessary() { + void resetDictionaryFacilitatorIfNecessary() { final Locale[] subtypeSwitcherLocales = mSubtypeSwitcher.getCurrentSubtypeLocales(); if (mDictionaryFacilitator.isForLocales(subtypeSwitcherLocales)) { return; @@ -791,17 +790,21 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } + void updateCursorAnchorInfo() { + // CursorAnchorInfo is used on L and later. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (isFullscreenMode() && mExtractEditText != null) { + mInputLogic.onUpdateCursorAnchorInfo( + CursorAnchorInfoUtils.extractFromTextView(mExtractEditText)); + } + } + } + private final ViewTreeObserver.OnPreDrawListener mExtractTextViewPreDrawListener = new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { - // CursorAnchorInfo is used on L and later. - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - if (isFullscreenMode() && mExtractEditText != null) { - mInputLogic.onUpdateCursorAnchorInfo( - CursorAnchorInfoUtils.extractFromTextView(mExtractEditText)); - } - } + updateCursorAnchorInfo(); return true; } }; @@ -846,12 +849,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen loadKeyboard(); } - private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) { + void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInput(editorInfo, restarting); } @SuppressWarnings("deprecation") - private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { + void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInputView(editorInfo, restarting); // Switch to the null consumer to handle cases leading to early exit below, for which we // also wouldn't be consuming gesture data. @@ -1034,7 +1037,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } - private void onFinishInputInternal() { + void onFinishInputInternal() { super.onFinishInput(); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); @@ -1043,7 +1046,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } - private void onFinishInputViewInternal(final boolean finishingInput) { + void onFinishInputViewInternal(final boolean finishingInput) { super.onFinishInputView(finishingInput); cleanupInternalStateForFinishInput(); } @@ -1295,11 +1298,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } - private int getCurrentAutoCapsState() { + int getCurrentAutoCapsState() { return mInputLogic.getCurrentAutoCapsState(mSettings.getCurrent()); } - private int getCurrentRecapitalizeState() { + int getCurrentRecapitalizeState() { return mInputLogic.getCurrentRecapitalizeState(); } @@ -1389,12 +1392,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final Keyboard currentKeyboard = mKeyboardSwitcher.getKeyboard(); if (null != currentKeyboard && currentKeyboard.mId.isAlphabetKeyboard()) { return codePoint; - } else { - return Constants.CODE_SYMBOL_SHIFT; } - } else { - return codePoint; + return Constants.CODE_SYMBOL_SHIFT; } + return codePoint; } // Implementation of {@link KeyboardActionListener}. @@ -1496,7 +1497,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } // This method must run on the UI Thread. - private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, + void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, final boolean dismissGestureFloatingPreviewText) { showSuggestionStrip(suggestedWords); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); @@ -1812,7 +1813,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } }; - private void launchSettings() { + void launchSettings() { mInputLogic.commitTyped(mSettings.getCurrent(), LastComposedWord.NOT_A_SEPARATOR); requestHideSelf(0); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); @@ -1836,6 +1837,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen languageSelectionTitle, getString(ApplicationUtils.getActivityTitleResId(this, SettingsActivity.class)) }; + final String imeId = mRichImm.getInputMethodIdOfThisIme(); final OnClickListener listener = new OnClickListener() { @Override public void onClick(DialogInterface di, int position) { @@ -1843,7 +1845,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen switch (position) { case 0: final Intent intent = IntentUtils.getInputLanguageSelectionIntent( - mRichImm.getInputMethodIdOfThisIme(), + imeId, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP); diff --git a/java/src/com/android/inputmethod/latin/NgramContext.java b/java/src/com/android/inputmethod/latin/NgramContext.java index a02531cc4..2dc409f9f 100644 --- a/java/src/com/android/inputmethod/latin/NgramContext.java +++ b/java/src/com/android/inputmethod/latin/NgramContext.java @@ -31,14 +31,14 @@ public class NgramContext { public static final NgramContext EMPTY_PREV_WORDS_INFO = new NgramContext(WordInfo.EMPTY_WORD_INFO); public static final NgramContext BEGINNING_OF_SENTENCE = - new NgramContext(WordInfo.BEGINNING_OF_SENTENCE); + new NgramContext(WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO); /** * Word information used to represent previous words information. */ public static class WordInfo { public static final WordInfo EMPTY_WORD_INFO = new WordInfo(null); - public static final WordInfo BEGINNING_OF_SENTENCE = new WordInfo(); + public static final WordInfo BEGINNING_OF_SENTENCE_WORD_INFO = new WordInfo(); // This is an empty char sequence when mIsBeginningOfSentence is true. public final CharSequence mWord; @@ -48,7 +48,7 @@ public class NgramContext { public final boolean mIsBeginningOfSentence; // Beginning of sentence. - public WordInfo() { + private WordInfo() { mWord = ""; mIsBeginningOfSentence = true; } @@ -96,18 +96,6 @@ public class NgramContext { mPrevWordsCount = prevWordsInfo.length; } - // Construct from WordInfo array and size. The caller shouldn't change prevWordsInfo after - // calling this method. - private NgramContext(final NgramContext ngramContext, final int prevWordsCount) { - if (ngramContext.mPrevWordsCount < prevWordsCount) { - throw new IndexOutOfBoundsException("ngramContext.mPrevWordsCount (" - + ngramContext.mPrevWordsCount + ") is smaller than prevWordsCount (" - + prevWordsCount + ")"); - } - mPrevWordsInfo = ngramContext.mPrevWordsInfo; - mPrevWordsCount = prevWordsCount; - } - // Create next prevWordsInfo using current prevWordsInfo. public NgramContext getNextNgramContext(final WordInfo wordInfo) { final int nextPrevWordCount = Math.min(Constants.MAX_PREV_WORD_COUNT_FOR_N_GRAM, diff --git a/java/src/com/android/inputmethod/latin/RichInputConnection.java b/java/src/com/android/inputmethod/latin/RichInputConnection.java index a3f7bb4d6..2c17660d8 100644 --- a/java/src/com/android/inputmethod/latin/RichInputConnection.java +++ b/java/src/com/android/inputmethod/latin/RichInputConnection.java @@ -44,8 +44,6 @@ import com.android.inputmethod.latin.utils.SpannableStringUtils; import com.android.inputmethod.latin.utils.StringUtils; import com.android.inputmethod.latin.utils.TextRange; -import java.util.Arrays; - /** * Enrichment class for InputConnection to simplify interaction and add functionality. * @@ -91,7 +89,7 @@ public final class RichInputConnection implements PrivateCommandPerformer { /** * This variable is a temporary object used in - * {@link #commitTextWithBackgroundColor(CharSequence, int, int)} to avoid object creation. + * {@link #commitTextWithBackgroundColor(CharSequence,int,int,int)} to avoid object creation. */ private SpannableStringBuilder mTempObjectForCommitText = new SpannableStringBuilder(); /** @@ -151,9 +149,8 @@ public final class RichInputConnection implements PrivateCommandPerformer { } else { if (DBG) { throw new RuntimeException("Nest level too deep"); - } else { - Log.e(TAG, "Nest level too deep : " + mNestLevel); } + Log.e(TAG, "Nest level too deep : " + mNestLevel); } if (DEBUG_BATCH_NESTING) checkBatchEdit(); if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); @@ -351,10 +348,9 @@ public final class RichInputConnection implements PrivateCommandPerformer { // If we have some composing text and a space before, then we should have // MODE_CHARACTERS and MODE_WORDS on. return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & inputType; - } else { - // We have some composing text - we should be in MODE_CHARACTERS only. - return TextUtils.CAP_MODE_CHARACTERS & inputType; } + // We have some composing text - we should be in MODE_CHARACTERS only. + return TextUtils.CAP_MODE_CHARACTERS & inputType; } // TODO: this will generally work, but there may be cases where the buffer contains SOME // information but not enough to determine the caps mode accurately. This may happen after @@ -624,10 +620,6 @@ public final class RichInputConnection implements PrivateCommandPerformer { prev, spacingAndPunctuations, n); } - private static boolean isSeparator(final int code, final int[] sortedSeparators) { - return Arrays.binarySearch(sortedSeparators, code) >= 0; - } - private static boolean isPartOfCompositionForScript(final int codePoint, final SpacingAndPunctuations spacingAndPunctuations, final int scriptId) { // We always consider word connectors part of compositions. @@ -977,7 +969,8 @@ public final class RichInputConnection implements PrivateCommandPerformer { /** * @return {@code true} if the application reported that the monitor mode of - * {@link InputMethodService#onUpdateCursorAnchorInfo(CursorAnchorInfo)} is currently enabled. + * {@link InputMethodService#onUpdateCursorAnchorInfo(android.view.inputmethod.CursorAnchorInfo)} + * is currently enabled. */ public boolean isCursorAnchorInfoMonitorEnabled() { return mCursorAnchorInfoMonitorEnabled; diff --git a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java index e6df35bea..113a20483 100644 --- a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java +++ b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java @@ -20,7 +20,6 @@ import static com.android.inputmethod.latin.Constants.Subtype.KEYBOARD_MODE; import android.content.Context; import android.content.SharedPreferences; -import android.content.res.Resources; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; diff --git a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java index 6fc549549..794475048 100644 --- a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java +++ b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java @@ -291,8 +291,9 @@ public final class SubtypeSwitcher { } private static RichInputMethodSubtype sForcedSubtypeForTesting = null; + @UsedForTesting - void forceSubtype(final InputMethodSubtype subtype) { + static void forceSubtype(final InputMethodSubtype subtype) { sForcedSubtypeForTesting = new RichInputMethodSubtype(subtype); } diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java index e6c138407..6042e7e37 100644 --- a/java/src/com/android/inputmethod/latin/Suggest.java +++ b/java/src/com/android/inputmethod/latin/Suggest.java @@ -328,7 +328,7 @@ public final class Suggest { * @param info the suggestion info * @return whether it's fine to auto-correct to this. */ - private boolean isAllowedByAutoCorrectionWithSpaceFilter(final SuggestedWordInfo info) { + private static boolean isAllowedByAutoCorrectionWithSpaceFilter(final SuggestedWordInfo info) { final Locale locale = info.mSourceDict.mLocale; if (null == locale) { return true; diff --git a/java/src/com/android/inputmethod/latin/SuggestedWords.java b/java/src/com/android/inputmethod/latin/SuggestedWords.java index e5bf25d5f..dffe97bd6 100644 --- a/java/src/com/android/inputmethod/latin/SuggestedWords.java +++ b/java/src/com/android/inputmethod/latin/SuggestedWords.java @@ -365,9 +365,8 @@ public class SuggestedWords { public String toString() { if (TextUtils.isEmpty(mDebugString)) { return mWord; - } else { - return mWord + " (" + mDebugString + ")"; } + return mWord + " (" + mDebugString + ")"; } // This will always remove the higher index if a duplicate is found. diff --git a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java index 9332e4a75..37dd3846c 100644 --- a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java @@ -64,7 +64,7 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { private static final String NAME = "userunigram"; private ContentObserver mObserver; - final private String mLocale; + final private String mLocaleString; final private boolean mAlsoUseMoreRestrictiveLocales; protected UserBinaryDictionary(final Context context, final Locale locale, @@ -74,9 +74,9 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { final String localeStr = locale.toString(); if (SubtypeLocaleUtils.NO_LANGUAGE.equals(localeStr)) { // If we don't have a locale, insert into the "all locales" user dictionary. - mLocale = USER_DICTIONARY_ALL_LANGUAGES; + mLocaleString = USER_DICTIONARY_ALL_LANGUAGES; } else { - mLocale = localeStr; + mLocaleString = localeStr; } mAlsoUseMoreRestrictiveLocales = alsoUseMoreRestrictiveLocales; ContentResolver cres = context.getContentResolver(); @@ -124,7 +124,7 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { // This is correct for locale processing. // For this example, we'll look at the "en_US_POSIX" case. final String[] localeElements = - TextUtils.isEmpty(mLocale) ? new String[] {} : mLocale.split("_", 3); + TextUtils.isEmpty(mLocaleString) ? new String[] {} : mLocaleString.split("_", 3); final int length = localeElements.length; final StringBuilder request = new StringBuilder("(locale is NULL)"); @@ -207,9 +207,8 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { if (client != null) { client.release(); return true; - } else { - return false; } + return false; } /** @@ -227,17 +226,16 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { HISTORICAL_DEFAULT_USER_DICTIONARY_FREQUENCY, null, locale); } - private int scaleFrequencyFromDefaultToLatinIme(final int defaultFrequency) { + private static int scaleFrequencyFromDefaultToLatinIme(final int defaultFrequency) { // The default frequency for the user dictionary is 250 for historical reasons. // Latin IME considers a good value for the default user dictionary frequency // is about 160 considering the scale we use. So we are scaling down the values. if (defaultFrequency > Integer.MAX_VALUE / LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY) { return (defaultFrequency / HISTORICAL_DEFAULT_USER_DICTIONARY_FREQUENCY) * LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY; - } else { - return (defaultFrequency * LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY) - / HISTORICAL_DEFAULT_USER_DICTIONARY_FREQUENCY; } + return (defaultFrequency * LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY) + / HISTORICAL_DEFAULT_USER_DICTIONARY_FREQUENCY; } private void addWordsLocked(final Cursor cursor) { diff --git a/java/src/com/android/inputmethod/latin/WordComposer.java b/java/src/com/android/inputmethod/latin/WordComposer.java index 5eb338eb3..6530e6bb9 100644 --- a/java/src/com/android/inputmethod/latin/WordComposer.java +++ b/java/src/com/android/inputmethod/latin/WordComposer.java @@ -353,9 +353,8 @@ public final class WordComposer { if (size() <= 1) { return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED || mCapitalizedMode == CAPS_MODE_MANUAL_SHIFT_LOCKED; - } else { - return mCapsCount == size(); } + return mCapsCount == size(); } public boolean wasShiftedNoLock() { diff --git a/java/src/com/android/inputmethod/latin/debug/ExternalDictionaryGetterForDebug.java b/java/src/com/android/inputmethod/latin/debug/ExternalDictionaryGetterForDebug.java index a87785b1a..d4be0e397 100644 --- a/java/src/com/android/inputmethod/latin/debug/ExternalDictionaryGetterForDebug.java +++ b/java/src/com/android/inputmethod/latin/debug/ExternalDictionaryGetterForDebug.java @@ -44,7 +44,7 @@ import java.util.Locale; * A class to read a local file as a dictionary for debugging purposes. */ public class ExternalDictionaryGetterForDebug { - private static final String SOURCE_FOLDER = Environment.getExternalStorageDirectory().getPath() + static final String SOURCE_FOLDER = Environment.getExternalStorageDirectory().getPath() + "/Download"; private static String[] findDictionariesInTheDownloadedFolder() { @@ -142,8 +142,7 @@ public class ExternalDictionaryGetterForDebug { }).create().show(); } - private static void installFile(final Context context, final File file, - final DictionaryHeader header) { + static void installFile(final Context context, final File file, final DictionaryHeader header) { BufferedOutputStream outputStream = null; File tempFile = null; try { diff --git a/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java b/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java index 5cc61db79..359ea12b5 100644 --- a/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java +++ b/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java @@ -75,7 +75,7 @@ public final class InputLogic { private static final String TAG = InputLogic.class.getSimpleName(); // TODO : Remove this member when we can. - private final LatinIME mLatinIME; + final LatinIME mLatinIME; private final SuggestionStripViewAccessor mSuggestionStripViewAccessor; // Never null. @@ -1512,12 +1512,6 @@ public final class InputLogic { } } final int[] codePoints = StringUtils.toCodePointArray(typedWord); - // We want the context of preceding words for suggestion. If we have chars in the word - // before the cursor, then we want the word before that, hence 2; otherwise, - // we want the word immediately before the cursor, hence 1. - final NgramContext ngramContext = getNgramContextFromNthPreviousWordForSuggestion( - settingsValues.mSpacingAndPunctuations, - 0 == numberOfCharsInWordBeforeCursor ? 1 : 2); mWordComposer.setComposingWord(codePoints, mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); mWordComposer.setCursorPositionWithinWord( @@ -1533,8 +1527,7 @@ public final class InputLogic { SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() { @Override public void onGetSuggestedWords(final SuggestedWords suggestedWords) { - mIsAutoCorrectionIndicatorOn = false; - mLatinIME.mHandler.showSuggestionStrip(suggestedWords); + doShowSuggestionsAndClearAutoCorrectionIndicator(suggestedWords); }}); } else { // We found suggestion spans in the word. We'll create the SuggestedWords out of @@ -1545,11 +1538,15 @@ public final class InputLogic { null /* rawSuggestions */, typedWord, false /* typedWordValid */, false /* willAutoCorrect */, false /* isObsoleteSuggestions */, SuggestedWords.INPUT_STYLE_RECORRECTION, SuggestedWords.NOT_A_SEQUENCE_NUMBER); - mIsAutoCorrectionIndicatorOn = false; - mLatinIME.mHandler.showSuggestionStrip(suggestedWords); + doShowSuggestionsAndClearAutoCorrectionIndicator(suggestedWords); } } + void doShowSuggestionsAndClearAutoCorrectionIndicator(final SuggestedWords suggestedWords) { + mIsAutoCorrectionIndicatorOn = false; + mLatinIME.mHandler.showSuggestionStrip(suggestedWords); + } + /** * Reverts a previous commit with auto-correction. * @@ -1761,12 +1758,12 @@ public final class InputLogic { // word information from textview. return mConnection.getNgramContextFromNthPreviousWord( spacingAndPunctuations, nthPreviousWord); - } else { - return LastComposedWord.NOT_A_COMPOSED_WORD == mLastComposedWord ? - NgramContext.BEGINNING_OF_SENTENCE : - new NgramContext(new NgramContext.WordInfo( - mLastComposedWord.mCommittedWord.toString())); } + if (LastComposedWord.NOT_A_COMPOSED_WORD == mLastComposedWord) { + return NgramContext.BEGINNING_OF_SENTENCE; + } + return new NgramContext(new NgramContext.WordInfo( + mLastComposedWord.mCommittedWord.toString())); } /** @@ -1819,9 +1816,8 @@ public final class InputLogic { // If no code point, #getCodePointBeforeCursor returns NOT_A_CODE_POINT. if (Constants.CODE_PERIOD == codePointBeforeCursor) { return text.substring(1); - } else { - return text; } + return text; } /** @@ -1877,7 +1873,7 @@ public final class InputLogic { * @param previousSuggestedWords The previously suggested words. * @return Obsolete suggestions with the newly typed word. */ - private SuggestedWords retrieveOlderSuggestions(final String typedWord, + static SuggestedWords retrieveOlderSuggestions(final String typedWord, final SuggestedWords previousSuggestedWords) { final SuggestedWords oldSuggestedWords = previousSuggestedWords.isPunctuationSuggestions() ? SuggestedWords.getEmptyInstance() : previousSuggestedWords; diff --git a/java/src/com/android/inputmethod/latin/inputlogic/InputLogicHandler.java b/java/src/com/android/inputmethod/latin/inputlogic/InputLogicHandler.java index c6f83d0b9..5f391dd9b 100644 --- a/java/src/com/android/inputmethod/latin/inputlogic/InputLogicHandler.java +++ b/java/src/com/android/inputmethod/latin/inputlogic/InputLogicHandler.java @@ -23,7 +23,6 @@ import android.os.Message; import com.android.inputmethod.compat.LooperCompatUtils; import com.android.inputmethod.latin.InputPointers; import com.android.inputmethod.latin.LatinIME; -import com.android.inputmethod.latin.Suggest; import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback; @@ -62,7 +61,7 @@ class InputLogicHandler implements Handler.Callback { final OnGetSuggestedWordsCallback callback) {} }; - private InputLogicHandler() { + InputLogicHandler() { mNonUIThreadHandler = null; mLatinIME = null; mInputLogic = null; @@ -134,30 +133,38 @@ class InputLogicHandler implements Handler.Callback { return; } mInputLogic.mWordComposer.setBatchInputPointers(batchPointers); + final OnGetSuggestedWordsCallback callback = new OnGetSuggestedWordsCallback() { + @Override + public void onGetSuggestedWords(final SuggestedWords suggestedWords) { + showGestureSuggestionsWithPreviewVisuals(suggestedWords, isTailBatchInput); + } + }; getSuggestedWords(isTailBatchInput ? SuggestedWords.INPUT_STYLE_TAIL_BATCH - : SuggestedWords.INPUT_STYLE_UPDATE_BATCH, sequenceNumber, - new OnGetSuggestedWordsCallback() { - @Override - public void onGetSuggestedWords(SuggestedWords suggestedWords) { - // We're now inside the callback. This always runs on the Non-UI thread, - // no matter what thread updateBatchInput was originally called on. - if (suggestedWords.isEmpty()) { - // Use old suggestions if we don't have any new ones. - // Previous suggestions are found in InputLogic#mSuggestedWords. - // Since these are the most recent ones and we just recomputed - // new ones to update them, then the previous ones are there. - suggestedWords = mInputLogic.mSuggestedWords; - } - mLatinIME.mHandler.showGesturePreviewAndSuggestionStrip(suggestedWords, - isTailBatchInput /* dismissGestureFloatingPreviewText */); - if (isTailBatchInput) { - mInBatchInput = false; - // The following call schedules onEndBatchInputInternal - // to be called on the UI thread. - mLatinIME.mHandler.showTailBatchInputResult(suggestedWords); - } - } - }); + : SuggestedWords.INPUT_STYLE_UPDATE_BATCH, sequenceNumber, callback); + } + } + + void showGestureSuggestionsWithPreviewVisuals(final SuggestedWords suggestedWordsForBatchInput, + final boolean isTailBatchInput) { + final SuggestedWords suggestedWordsToShowSuggestions; + // We're now inside the callback. This always runs on the Non-UI thread, + // no matter what thread updateBatchInput was originally called on. + if (suggestedWordsForBatchInput.isEmpty()) { + // Use old suggestions if we don't have any new ones. + // Previous suggestions are found in InputLogic#mSuggestedWords. + // Since these are the most recent ones and we just recomputed + // new ones to update them, then the previous ones are there. + suggestedWordsToShowSuggestions = mInputLogic.mSuggestedWords; + } else { + suggestedWordsToShowSuggestions = suggestedWordsForBatchInput; + } + mLatinIME.mHandler.showGesturePreviewAndSuggestionStrip(suggestedWordsToShowSuggestions, + isTailBatchInput /* dismissGestureFloatingPreviewText */); + if (isTailBatchInput) { + mInBatchInput = false; + // The following call schedules onEndBatchInputInternal + // to be called on the UI thread. + mLatinIME.mHandler.showTailBatchInputResult(suggestedWordsToShowSuggestions); } } diff --git a/java/src/com/android/inputmethod/latin/makedict/ProbabilityInfo.java b/java/src/com/android/inputmethod/latin/makedict/ProbabilityInfo.java index 5fcbb6357..03c2ece1d 100644 --- a/java/src/com/android/inputmethod/latin/makedict/ProbabilityInfo.java +++ b/java/src/com/android/inputmethod/latin/makedict/ProbabilityInfo.java @@ -40,11 +40,8 @@ public final class ProbabilityInfo { if (probabilityInfo2 == null) { return probabilityInfo1; } - if (probabilityInfo1.mProbability > probabilityInfo2.mProbability) { - return probabilityInfo1; - } else { - return probabilityInfo2; - } + return (probabilityInfo1.mProbability > probabilityInfo2.mProbability) ? probabilityInfo1 + : probabilityInfo2; } public ProbabilityInfo(final int probability) { @@ -67,9 +64,8 @@ public final class ProbabilityInfo { public int hashCode() { if (hasHistoricalInfo()) { return Arrays.hashCode(new Object[] { mProbability, mTimestamp, mLevel, mCount }); - } else { - return Arrays.hashCode(new Object[] { mProbability }); } + return Arrays.hashCode(new Object[] { mProbability }); } @Override diff --git a/java/src/com/android/inputmethod/latin/makedict/WordProperty.java b/java/src/com/android/inputmethod/latin/makedict/WordProperty.java index 5c6d8f5cb..b129c3e40 100644 --- a/java/src/com/android/inputmethod/latin/makedict/WordProperty.java +++ b/java/src/com/android/inputmethod/latin/makedict/WordProperty.java @@ -18,6 +18,7 @@ package com.android.inputmethod.latin.makedict; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.latin.BinaryDictionary; +import com.android.inputmethod.latin.Dictionary; import com.android.inputmethod.latin.NgramContext; import com.android.inputmethod.latin.NgramContext.WordInfo; import com.android.inputmethod.latin.utils.CombinedFormatUtils; @@ -61,10 +62,8 @@ public final class WordProperty implements Comparable<WordProperty> { } else { mNgrams = new ArrayList<>(); final NgramContext ngramContext = new NgramContext(new WordInfo(mWord)); - if (bigrams != null) { - for (final WeightedString bigramTarget : bigrams) { - mNgrams.add(new NgramProperty(bigramTarget, ngramContext)); - } + for (final WeightedString bigramTarget : bigrams) { + mNgrams.add(new NgramProperty(bigramTarget, ngramContext)); } } mIsBeginningOfSentence = false; @@ -104,7 +103,8 @@ public final class WordProperty implements Comparable<WordProperty> { final int relatedNgramCount = ngramTargets.size(); final WordInfo currentWordInfo = - mIsBeginningOfSentence ? WordInfo.BEGINNING_OF_SENTENCE : new WordInfo(mWord); + mIsBeginningOfSentence ? WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO + : new WordInfo(mWord); final NgramContext ngramContext = new NgramContext(currentWordInfo); for (int i = 0; i < relatedNgramCount; i++) { final String ngramTargetString = @@ -202,7 +202,7 @@ public final class WordProperty implements Comparable<WordProperty> { @UsedForTesting public boolean isValid() { - return getProbability() != BinaryDictionary.NOT_A_PROBABILITY; + return getProbability() != Dictionary.NOT_A_PROBABILITY; } @Override diff --git a/java/src/com/android/inputmethod/latin/network/BlockingHttpClient.java b/java/src/com/android/inputmethod/latin/network/BlockingHttpClient.java index e2d24fd0a..079d07eac 100644 --- a/java/src/com/android/inputmethod/latin/network/BlockingHttpClient.java +++ b/java/src/com/android/inputmethod/latin/network/BlockingHttpClient.java @@ -85,12 +85,11 @@ public class BlockingHttpClient { throw new AuthException(mConnection.getResponseMessage()); } throw new HttpException(responseCode); - } else { - if (DEBUG) { - Log.d(TAG, "request executed successfully"); - } - return responseProcessor.onSuccess(mConnection.getInputStream()); } + if (DEBUG) { + Log.d(TAG, "request executed successfully"); + } + return responseProcessor.onSuccess(mConnection.getInputStream()); } finally { mConnection.disconnect(); } diff --git a/java/src/com/android/inputmethod/latin/personalization/DecayingExpandableBinaryDictionaryBase.java b/java/src/com/android/inputmethod/latin/personalization/DecayingExpandableBinaryDictionaryBase.java index 1ba7b366f..78b51d9f4 100644 --- a/java/src/com/android/inputmethod/latin/personalization/DecayingExpandableBinaryDictionaryBase.java +++ b/java/src/com/android/inputmethod/latin/personalization/DecayingExpandableBinaryDictionaryBase.java @@ -39,14 +39,10 @@ public abstract class DecayingExpandableBinaryDictionaryBase extends ExpandableB public static final int FREQUENCY_FOR_WORDS_IN_DICTS = FREQUENCY_FOR_TYPED; public static final int FREQUENCY_FOR_WORDS_NOT_IN_DICTS = Dictionary.NOT_A_PROBABILITY; - /** The locale for this dictionary. */ - public final Locale mLocale; - protected DecayingExpandableBinaryDictionaryBase(final Context context, final String dictName, final Locale locale, final String dictionaryType, final File dictFile) { super(context, dictName, locale, dictionaryType, dictFile); - mLocale = locale; if (mLocale != null && mLocale.toString().length() > 1) { reloadDictionaryIfRequired(); } diff --git a/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java b/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java index 59761547d..e777c0bfa 100644 --- a/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java +++ b/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java @@ -17,7 +17,6 @@ package com.android.inputmethod.latin.personalization; import android.content.Context; -import android.text.TextUtils; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.latin.Constants; @@ -35,7 +34,6 @@ import java.util.Locale; */ public class UserHistoryDictionary extends DecayingExpandableBinaryDictionaryBase { /* package */ static final String NAME = UserHistoryDictionary.class.getSimpleName(); - private final static int SUPPORTED_NGRAM = 2; // TODO: 3 // TODO: Make this constructor private /* package */ UserHistoryDictionary(final Context context, final Locale locale) { diff --git a/java/src/com/android/inputmethod/latin/settings/CustomInputStylePreference.java b/java/src/com/android/inputmethod/latin/settings/CustomInputStylePreference.java index c07b60a0b..01398f467 100644 --- a/java/src/com/android/inputmethod/latin/settings/CustomInputStylePreference.java +++ b/java/src/com/android/inputmethod/latin/settings/CustomInputStylePreference.java @@ -259,6 +259,7 @@ final class CustomInputStylePreference extends DialogPreference mSubtype = (InputMethodSubtype)source.readParcelable(null); } + @SuppressWarnings("hiding") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override diff --git a/java/src/com/android/inputmethod/latin/settings/GestureSettingsFragment.java b/java/src/com/android/inputmethod/latin/settings/GestureSettingsFragment.java index 832fbf65a..22b0655b4 100644 --- a/java/src/com/android/inputmethod/latin/settings/GestureSettingsFragment.java +++ b/java/src/com/android/inputmethod/latin/settings/GestureSettingsFragment.java @@ -16,7 +16,6 @@ package com.android.inputmethod.latin.settings; -import android.content.SharedPreferences; import android.os.Bundle; import com.android.inputmethod.latin.R; diff --git a/java/src/com/android/inputmethod/latin/settings/MultiLingualSettingsFragment.java b/java/src/com/android/inputmethod/latin/settings/MultiLingualSettingsFragment.java index b71f8829b..c5930db1e 100644 --- a/java/src/com/android/inputmethod/latin/settings/MultiLingualSettingsFragment.java +++ b/java/src/com/android/inputmethod/latin/settings/MultiLingualSettingsFragment.java @@ -20,8 +20,6 @@ import android.os.Bundle; import com.android.inputmethod.latin.R; -import java.util.ArrayList; - /** * "Multilingual options" settings sub screen. * diff --git a/java/src/com/android/inputmethod/latin/settings/RadioButtonPreference.java b/java/src/com/android/inputmethod/latin/settings/RadioButtonPreference.java index c173d4706..91444604d 100644 --- a/java/src/com/android/inputmethod/latin/settings/RadioButtonPreference.java +++ b/java/src/com/android/inputmethod/latin/settings/RadioButtonPreference.java @@ -43,9 +43,7 @@ public class RadioButtonPreference extends Preference { private final View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { - if (mListener != null) { - mListener.onRadioButtonClicked(RadioButtonPreference.this); - } + callListenerOnRadioButtonClicked(); } }; @@ -67,6 +65,12 @@ public class RadioButtonPreference extends Preference { mListener = listener; } + void callListenerOnRadioButtonClicked() { + if (mListener != null) { + mListener.onRadioButtonClicked(this); + } + } + @Override protected void onBindView(final View view) { super.onBindView(view); diff --git a/java/src/com/android/inputmethod/latin/settings/SettingsValues.java b/java/src/com/android/inputmethod/latin/settings/SettingsValues.java index 660b4e095..5b99652b8 100644 --- a/java/src/com/android/inputmethod/latin/settings/SettingsValues.java +++ b/java/src/com/android/inputmethod/latin/settings/SettingsValues.java @@ -273,9 +273,8 @@ public class SettingsValues { final RichInputMethodManager imm = RichInputMethodManager.getInstance(); if (mIncludesOtherImesInLanguageSwitchList) { return imm.hasMultipleEnabledIMEsOrSubtypes(false /* include aux subtypes */); - } else { - return imm.hasMultipleEnabledSubtypesInThisIme(false /* include aux subtypes */); } + return imm.hasMultipleEnabledSubtypesInThisIme(false /* include aux subtypes */); } public boolean isSameInputType(final EditorInfo editorInfo) { diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java index 2a4e14ca7..f5c713195 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java @@ -50,9 +50,6 @@ import java.util.concurrent.Semaphore; */ public final class AndroidSpellCheckerService extends SpellCheckerService implements SharedPreferences.OnSharedPreferenceChangeListener { - private static final String TAG = AndroidSpellCheckerService.class.getSimpleName(); - private static final boolean DBG = false; - public static final String PREF_USE_CONTACTS_KEY = "pref_spellcheck_use_contacts"; private static final int SPELLCHECKER_DUMMY_KEYBOARD_WIDTH = 480; diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java index 7b6aacd15..06adf4b9f 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java @@ -312,11 +312,10 @@ public abstract class AndroidWordLevelSpellCheckerSession extends Session { // Don't kill the keyboard if there is a bug in the spell checker if (DBG) { throw e; - } else { - Log.e(TAG, "Exception while spellcheking", e); - return AndroidSpellCheckerService.getNotInDictEmptySuggestions( - false /* reportAsTypo */); } + Log.e(TAG, "Exception while spellcheking", e); + return AndroidSpellCheckerService.getNotInDictEmptySuggestions( + false /* reportAsTypo */); } } diff --git a/java/src/com/android/inputmethod/latin/spellcheck/SentenceLevelAdapter.java b/java/src/com/android/inputmethod/latin/spellcheck/SentenceLevelAdapter.java index 9ddee8629..3c9f261b9 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/SentenceLevelAdapter.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/SentenceLevelAdapter.java @@ -16,7 +16,9 @@ package com.android.inputmethod.latin.spellcheck; +import android.annotation.TargetApi; import android.content.res.Resources; +import android.os.Build; import android.view.textservice.SentenceSuggestionsInfo; import android.view.textservice.SuggestionsInfo; import android.view.textservice.TextInfo; @@ -76,19 +78,19 @@ public class SentenceLevelAdapter { private static class WordIterator { private final SpacingAndPunctuations mSpacingAndPunctuations; public WordIterator(final Resources res, final Locale locale) { - final RunInLocale<SpacingAndPunctuations> job - = new RunInLocale<SpacingAndPunctuations>() { + final RunInLocale<SpacingAndPunctuations> job = + new RunInLocale<SpacingAndPunctuations>() { @Override - protected SpacingAndPunctuations job(final Resources res) { - return new SpacingAndPunctuations(res); + protected SpacingAndPunctuations job(final Resources r) { + return new SpacingAndPunctuations(r); } }; mSpacingAndPunctuations = job.runInLocale(res, locale); } - public int getEndOfWord(final CharSequence sequence, int index) { + public int getEndOfWord(final CharSequence sequence, final int fromIndex) { final int length = sequence.length(); - index = index < 0 ? 0 : Character.offsetByCodePoints(sequence, index, 1); + int index = fromIndex < 0 ? 0 : Character.offsetByCodePoints(sequence, fromIndex, 1); while (index < length) { final int codePoint = Character.codePointAt(sequence, index); if (mSpacingAndPunctuations.isWordSeparator(codePoint)) { @@ -111,12 +113,12 @@ public class SentenceLevelAdapter { return index; } - public int getBeginningOfNextWord(final CharSequence sequence, int index) { + public int getBeginningOfNextWord(final CharSequence sequence, final int fromIndex) { final int length = sequence.length(); - if (index >= length) { + if (fromIndex >= length) { return -1; } - index = index < 0 ? 0 : Character.offsetByCodePoints(sequence, index, 1); + int index = fromIndex < 0 ? 0 : Character.offsetByCodePoints(sequence, fromIndex, 1); while (index < length) { final int codePoint = Character.codePointAt(sequence, index); if (!mSpacingAndPunctuations.isWordSeparator(codePoint)) { @@ -140,7 +142,7 @@ public class SentenceLevelAdapter { final int cookie = originalTextInfo.getCookie(); final int start = -1; final int end = originalText.length(); - final ArrayList<SentenceWordItem> wordItems = new ArrayList<SentenceWordItem>(); + final ArrayList<SentenceWordItem> wordItems = new ArrayList<>(); int wordStart = wordIterator.getBeginningOfNextWord(originalText, start); int wordEnd = wordIterator.getEndOfWord(originalText, wordStart); while (wordStart <= end && wordEnd != -1 && wordStart != -1) { @@ -158,6 +160,7 @@ public class SentenceLevelAdapter { return new SentenceTextInfoParams(originalTextInfo, wordItems); } + @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public static SentenceSuggestionsInfo reconstructSuggestions( SentenceTextInfoParams originalTextInfoParams, SuggestionsInfo[] results) { if (results == null || results.length == 0) { diff --git a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelper.java b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelper.java index 7b66bbb75..27a0f62ff 100644 --- a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelper.java +++ b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelper.java @@ -50,10 +50,8 @@ import com.android.inputmethod.latin.PunctuationSuggestions; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; -import com.android.inputmethod.latin.define.DebugFlags; import com.android.inputmethod.latin.settings.Settings; import com.android.inputmethod.latin.settings.SettingsValues; -import com.android.inputmethod.latin.utils.AutoCorrectionUtils; import com.android.inputmethod.latin.utils.ResourceUtils; import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; import com.android.inputmethod.latin.utils.ViewLayoutUtils; @@ -380,6 +378,7 @@ final class SuggestionStripLayoutHelper { final int countInStrip = mSuggestionsCountInStrip; mMoreSuggestionsAvailable = (wordCountToShow > countInStrip); + @SuppressWarnings("unused") int x = 0; for (int positionInStrip = 0; positionInStrip < countInStrip; positionInStrip++) { if (positionInStrip != 0) { diff --git a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java index cf2014a1a..9d89d57bc 100644 --- a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java +++ b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java @@ -177,12 +177,11 @@ public class UserDictionarySettings extends ListFragment { return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION, QUERY_SELECTION_ALL_LOCALES, null, "UPPER(" + UserDictionary.Words.WORD + ")"); - } else { - final String queryLocale = null != locale ? locale : Locale.getDefault().toString(); - return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION, - QUERY_SELECTION, new String[] { queryLocale }, - "UPPER(" + UserDictionary.Words.WORD + ")"); } + final String queryLocale = null != locale ? locale : Locale.getDefault().toString(); + return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION, + QUERY_SELECTION, new String[] { queryLocale }, + "UPPER(" + UserDictionary.Words.WORD + ")"); } private ListAdapter createAdapter() { diff --git a/java/src/com/android/inputmethod/latin/utils/AsyncResultHolder.java b/java/src/com/android/inputmethod/latin/utils/AsyncResultHolder.java index d12aad639..952ac2a62 100644 --- a/java/src/com/android/inputmethod/latin/utils/AsyncResultHolder.java +++ b/java/src/com/android/inputmethod/latin/utils/AsyncResultHolder.java @@ -59,11 +59,7 @@ public class AsyncResultHolder<E> { */ public E get(final E defaultValue, final long timeOut) { try { - if (mLatch.await(timeOut, TimeUnit.MILLISECONDS)) { - return mResult; - } else { - return defaultValue; - } + return mLatch.await(timeOut, TimeUnit.MILLISECONDS) ? mResult : defaultValue; } catch (InterruptedException e) { return defaultValue; } diff --git a/java/src/com/android/inputmethod/latin/utils/AutoCorrectionUtils.java b/java/src/com/android/inputmethod/latin/utils/AutoCorrectionUtils.java index cba769521..120cffbde 100644 --- a/java/src/com/android/inputmethod/latin/utils/AutoCorrectionUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/AutoCorrectionUtils.java @@ -24,7 +24,6 @@ import com.android.inputmethod.latin.define.DebugFlags; public final class AutoCorrectionUtils { private static final boolean DBG = DebugFlags.DEBUG_ENABLED; private static final String TAG = AutoCorrectionUtils.class.getSimpleName(); - private static final int MINIMUM_SAFETY_NET_CHAR_LENGTH = 4; private AutoCorrectionUtils() { // Purely static class: can't instantiate. diff --git a/java/src/com/android/inputmethod/latin/utils/CollectionUtils.java b/java/src/com/android/inputmethod/latin/utils/CollectionUtils.java index fb36b7c50..d0df72479 100644 --- a/java/src/com/android/inputmethod/latin/utils/CollectionUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/CollectionUtils.java @@ -18,9 +18,6 @@ package com.android.inputmethod.latin.utils; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.TreeMap; public final class CollectionUtils { private CollectionUtils() { @@ -47,7 +44,7 @@ public final class CollectionUtils { * @param c Collection to test. * @return Whether c contains no elements. */ - public static boolean isNullOrEmpty(final Collection c) { + public static boolean isNullOrEmpty(final Collection<?> c) { return c == null || c.isEmpty(); } } diff --git a/java/src/com/android/inputmethod/latin/utils/CursorAnchorInfoUtils.java b/java/src/com/android/inputmethod/latin/utils/CursorAnchorInfoUtils.java index e05618901..6c1449cee 100644 --- a/java/src/com/android/inputmethod/latin/utils/CursorAnchorInfoUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/CursorAnchorInfoUtils.java @@ -24,6 +24,7 @@ import android.inputmethodservice.InputMethodService; import android.os.Build; import android.text.Layout; import android.text.Spannable; +import android.text.Spanned; import android.view.View; import android.view.ViewParent; import android.view.inputmethod.CursorAnchorInfo; @@ -149,7 +150,7 @@ public final class CursorAnchorInfoUtils { final Object[] spans = spannable.getSpans(0, text.length(), Object.class); for (Object span : spans) { final int spanFlag = spannable.getSpanFlags(span); - if ((spanFlag & Spannable.SPAN_COMPOSING) != 0) { + if ((spanFlag & Spanned.SPAN_COMPOSING) != 0) { composingTextStart = Math.min(composingTextStart, spannable.getSpanStart(span)); composingTextEnd = Math.max(composingTextEnd, spannable.getSpanEnd(span)); diff --git a/java/src/com/android/inputmethod/latin/utils/DistracterFilterCheckingIsInDictionary.java b/java/src/com/android/inputmethod/latin/utils/DistracterFilterCheckingIsInDictionary.java index df6e97028..4c99fed9f 100644 --- a/java/src/com/android/inputmethod/latin/utils/DistracterFilterCheckingIsInDictionary.java +++ b/java/src/com/android/inputmethod/latin/utils/DistracterFilterCheckingIsInDictionary.java @@ -41,10 +41,9 @@ public class DistracterFilterCheckingIsInDictionary implements DistracterFilter // This filter treats entries that are already in the dictionary as non-distracters // because they have passed the filtering in the past. return false; - } else { - return mDistracterFilter.isDistracterToWordsInDictionaries( - ngramContext, testedWord, locale); } + return mDistracterFilter.isDistracterToWordsInDictionaries( + ngramContext, testedWord, locale); } @Override diff --git a/java/src/com/android/inputmethod/latin/utils/ExecutorUtils.java b/java/src/com/android/inputmethod/latin/utils/ExecutorUtils.java index 61da1b789..e77f6fd40 100644 --- a/java/src/com/android/inputmethod/latin/utils/ExecutorUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/ExecutorUtils.java @@ -27,7 +27,7 @@ import java.util.concurrent.ThreadFactory; * Utilities to manage executors. */ public class ExecutorUtils { - private static final ConcurrentHashMap<String, ExecutorService> sExecutorMap = + static final ConcurrentHashMap<String, ExecutorService> sExecutorMap = new ConcurrentHashMap<>(); private static class ThreadFactoryWithId implements ThreadFactory { @@ -49,7 +49,7 @@ public class ExecutorUtils { public static ExecutorService getExecutor(final String id) { ExecutorService executor = sExecutorMap.get(id); if (executor == null) { - synchronized(sExecutorMap) { + synchronized (sExecutorMap) { executor = sExecutorMap.get(id); if (executor == null) { executor = Executors.newSingleThreadExecutor(new ThreadFactoryWithId(id)); @@ -65,7 +65,7 @@ public class ExecutorUtils { */ @UsedForTesting public static void shutdownAllExecutors() { - synchronized(sExecutorMap) { + synchronized (sExecutorMap) { for (final ExecutorService executor : sExecutorMap.values()) { executor.execute(new Runnable() { @Override diff --git a/java/src/com/android/inputmethod/latin/utils/LanguageModelParam.java b/java/src/com/android/inputmethod/latin/utils/LanguageModelParam.java index 5560d2f36..3e5cb33ca 100644 --- a/java/src/com/android/inputmethod/latin/utils/LanguageModelParam.java +++ b/java/src/com/android/inputmethod/latin/utils/LanguageModelParam.java @@ -20,7 +20,6 @@ import android.util.Log; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.latin.Dictionary; -import com.android.inputmethod.latin.DictionaryFacilitator; import com.android.inputmethod.latin.NgramContext; import com.android.inputmethod.latin.settings.SpacingAndPunctuations; import com.android.inputmethod.latin.utils.DistracterFilter.HandlingType; diff --git a/java/src/com/android/inputmethod/latin/utils/NgramContextUtils.java b/java/src/com/android/inputmethod/latin/utils/NgramContextUtils.java index 34eeac2c2..95a1f0fb2 100644 --- a/java/src/com/android/inputmethod/latin/utils/NgramContextUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/NgramContextUtils.java @@ -74,20 +74,20 @@ public final class NgramContextUtils { } // If we can't find (n + i) words, the context is beginning-of-sentence. if (focusedWordIndex < 0) { - prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE; + prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO; break; } final String focusedWord = w[focusedWordIndex]; // If the word is, the context is beginning-of-sentence. final int length = focusedWord.length(); if (length <= 0) { - prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE; + prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO; break; } // If ends in a sentence separator, the context is beginning-of-sentence. final char lastChar = focusedWord.charAt(length - 1); if (spacingAndPunctuations.isSentenceSeparator(lastChar)) { - prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE; + prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO; break; } // If ends in a word separator or connector, the context is unclear. diff --git a/java/src/com/android/inputmethod/latin/utils/SpannableStringUtils.java b/java/src/com/android/inputmethod/latin/utils/SpannableStringUtils.java index 38164cb36..cea1d1d58 100644 --- a/java/src/com/android/inputmethod/latin/utils/SpannableStringUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/SpannableStringUtils.java @@ -51,7 +51,7 @@ public final class SpannableStringUtils { // of a word. But the spans have been split into two by the getText{Before,After}Cursor // methods, so after concatenation they may end in the middle of a word. // Since we don't use them, we can just remove them and avoid crashing. - fl &= ~Spannable.SPAN_PARAGRAPH; + fl &= ~Spanned.SPAN_PARAGRAPH; int st = source.getSpanStart(spans[i]); int en = source.getSpanEnd(spans[i]); diff --git a/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java b/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java index 61661cd52..352d6cdef 100644 --- a/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java @@ -39,7 +39,7 @@ import java.util.Locale; */ // TODO: consolidate this into RichInputMethodSubtype public final class SubtypeLocaleUtils { - private static final String TAG = SubtypeLocaleUtils.class.getSimpleName(); + static final String TAG = SubtypeLocaleUtils.class.getSimpleName(); // This reference class {@link Constants} must be located in the same package as LatinIME.java. private static final String RESOURCE_PACKAGE_NAME = Constants.class.getPackage().getName(); @@ -245,9 +245,8 @@ public final class SubtypeLocaleUtils { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && subtype.containsExtraValueKey(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME)) { return subtype.getExtraValueOf(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME); - } else { - return getSubtypeLocaleDisplayNameInternal(subtype.getLocale(), displayLocale); } + return getSubtypeLocaleDisplayNameInternal(subtype.getLocale(), displayLocale); } public static String getSubtypeDisplayNameInSystemLocale(final InputMethodSubtype subtype) { diff --git a/java/src/com/android/inputmethod/latin/utils/SuggestionResults.java b/java/src/com/android/inputmethod/latin/utils/SuggestionResults.java index 4e2e396c2..b319aeb8a 100644 --- a/java/src/com/android/inputmethod/latin/utils/SuggestionResults.java +++ b/java/src/com/android/inputmethod/latin/utils/SuggestionResults.java @@ -66,8 +66,7 @@ public final class SuggestionResults extends TreeSet<SuggestedWordInfo> { return super.addAll(e); } - private static final class SuggestedWordInfoComparator - implements Comparator<SuggestedWordInfo> { + static final class SuggestedWordInfoComparator implements Comparator<SuggestedWordInfo> { // This comparator ranks the word info with the higher frequency first. That's because // that's the order we want our elements in. @Override |