diff options
Diffstat (limited to 'java/src')
18 files changed, 378 insertions, 271 deletions
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java index 5e3a5f17c..9dc57e308 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java @@ -34,26 +34,27 @@ import com.android.inputmethod.latin.InputView; import com.android.inputmethod.latin.LatinIME; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.RichInputMethodManager; -import com.android.inputmethod.latin.SubtypeSwitcher; import com.android.inputmethod.latin.WordComposer; import com.android.inputmethod.latin.define.ProductionFlags; import com.android.inputmethod.latin.settings.Settings; import com.android.inputmethod.latin.settings.SettingsValues; import com.android.inputmethod.latin.utils.CapsModeUtils; +import com.android.inputmethod.latin.utils.LanguageOnSpacebarUtils; +import com.android.inputmethod.latin.utils.NetworkConnectivityUtils; import com.android.inputmethod.latin.utils.RecapitalizeStatus; import com.android.inputmethod.latin.utils.ResourceUtils; import com.android.inputmethod.latin.utils.ScriptUtils; -public final class KeyboardSwitcher implements KeyboardState.SwitchActions { +public final class KeyboardSwitcher implements KeyboardState.SwitchActions, + NetworkConnectivityUtils.NetworkStateChangeListener { private static final String TAG = KeyboardSwitcher.class.getSimpleName(); - private SubtypeSwitcher mSubtypeSwitcher; - private InputView mCurrentInputView; private View mMainKeyboardFrame; private MainKeyboardView mKeyboardView; private EmojiPalettesView mEmojiPalettesView; private LatinIME mLatinIME; + private RichInputMethodManager mRichImm; private boolean mIsHardwareAcceleratedDrawingEnabled; private KeyboardState mState; @@ -81,7 +82,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions { private void initInternal(final LatinIME latinIme) { mLatinIME = latinIme; - mSubtypeSwitcher = SubtypeSwitcher.getInstance(); + mRichImm = RichInputMethodManager.getInstance(); mState = new KeyboardState(this); mIsHardwareAcceleratedDrawingEnabled = InputMethodServiceCompatUtils.enableHardwareAcceleration(mLatinIME); @@ -114,7 +115,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions { final int keyboardWidth = ResourceUtils.getDefaultKeyboardWidth(res); final int keyboardHeight = ResourceUtils.getKeyboardHeight(res, settingsValues); builder.setKeyboardGeometry(keyboardWidth, keyboardHeight); - builder.setSubtype(RichInputMethodManager.getInstance().getCurrentSubtype()); + builder.setSubtype(mRichImm.getCurrentSubtype()); builder.setVoiceInputKeyEnabled(settingsValues.mShowsVoiceInputKey); builder.setLanguageSwitchKeyEnabled(mLatinIME.shouldShowLanguageSwitchKey()); builder.setSplitLayoutEnabledByUser(ProductionFlags.IS_SPLIT_KEYBOARD_SUPPORTED @@ -123,9 +124,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions { try { mState.onLoadKeyboard(currentAutoCapsState, currentRecapitalizeState); // TODO: revisit this for multi-lingual input - mKeyboardTextsSet.setLocale( - RichInputMethodManager.getInstance().getCurrentSubtypeLocales()[0], - mThemeContext); + mKeyboardTextsSet.setLocale(mRichImm.getCurrentSubtypeLocales()[0], mThemeContext); } catch (KeyboardLayoutSetException e) { Log.w(TAG, "loading keyboard failed: " + e.mKeyboardId, e.getCause()); return; @@ -164,12 +163,12 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions { currentSettingsValues.mKeyPreviewDismissEndXScale, currentSettingsValues.mKeyPreviewDismissEndYScale, currentSettingsValues.mKeyPreviewDismissDuration); - keyboardView.updateShortcutKey(RichInputMethodManager.getInstance().isShortcutImeReady()); + keyboardView.updateShortcutKey(mRichImm.isShortcutImeReady()); final boolean subtypeChanged = (oldKeyboard == null) || !keyboard.mId.mSubtype.equals(oldKeyboard.mId.mSubtype); - final int languageOnSpacebarFormatType = mSubtypeSwitcher.getLanguageOnSpacebarFormatType( - keyboard.mId.mSubtype); - final boolean hasMultipleEnabledIMEsOrSubtypes = RichInputMethodManager.getInstance() + final int languageOnSpacebarFormatType = LanguageOnSpacebarUtils + .getLanguageOnSpacebarFormatType(keyboard.mId.mSubtype); + final boolean hasMultipleEnabledIMEsOrSubtypes = mRichImm .hasMultipleEnabledIMEsOrSubtypes(true /* shouldIncludeAuxiliarySubtypes */); keyboardView.startDisplayLanguageOnSpacebar(subtypeChanged, languageOnSpacebarFormatType, hasMultipleEnabledIMEsOrSubtypes); @@ -414,11 +413,13 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions { return mCurrentInputView; } + // {@link NetworkConnectivityUtils.NetworkStateChangeListener#onNetworkStateChanged(boolean)}. + @Override public void onNetworkStateChanged() { if (mKeyboardView == null) { return; } - mKeyboardView.updateShortcutKey(RichInputMethodManager.getInstance().isShortcutImeReady()); + mKeyboardView.updateShortcutKey(mRichImm.isShortcutImeReady()); } public int getKeyboardShiftMode() { diff --git a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java index eeac4755d..ab8b7515d 100644 --- a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java +++ b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java @@ -47,7 +47,6 @@ import com.android.inputmethod.keyboard.internal.KeyDrawParams; import com.android.inputmethod.keyboard.internal.KeyPreviewChoreographer; import com.android.inputmethod.keyboard.internal.KeyPreviewDrawParams; import com.android.inputmethod.keyboard.internal.KeyPreviewView; -import com.android.inputmethod.keyboard.internal.LanguageOnSpacebarHelper; import com.android.inputmethod.keyboard.internal.MoreKeySpec; import com.android.inputmethod.keyboard.internal.NonDistinctMultitouchHelper; import com.android.inputmethod.keyboard.internal.SlidingKeyInputDrawingPreview; @@ -58,6 +57,7 @@ import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.common.Constants; import com.android.inputmethod.latin.common.CoordinateUtils; import com.android.inputmethod.latin.settings.DebugSettings; +import com.android.inputmethod.latin.utils.LanguageOnSpacebarUtils; import com.android.inputmethod.latin.utils.TypefaceUtils; import java.util.Locale; @@ -783,10 +783,10 @@ public final class MainKeyboardView extends KeyboardView implements DrawingProxy mHasMultipleEnabledIMEsOrSubtypes = hasMultipleEnabledIMEsOrSubtypes; final ObjectAnimator animator = mLanguageOnSpacebarFadeoutAnimator; if (animator == null) { - mLanguageOnSpacebarFormatType = LanguageOnSpacebarHelper.FORMAT_TYPE_NONE; + mLanguageOnSpacebarFormatType = LanguageOnSpacebarUtils.FORMAT_TYPE_NONE; } else { if (subtypeChanged - && languageOnSpacebarFormatType != LanguageOnSpacebarHelper.FORMAT_TYPE_NONE) { + && languageOnSpacebarFormatType != LanguageOnSpacebarUtils.FORMAT_TYPE_NONE) { setLanguageOnSpacebarAnimAlpha(Constants.Color.ALPHA_OPAQUE); if (animator.isStarted()) { animator.cancel(); @@ -811,7 +811,7 @@ public final class MainKeyboardView extends KeyboardView implements DrawingProxy final int code = key.getCode(); if (code == Constants.CODE_SPACE) { // If input language are explicitly selected. - if (mLanguageOnSpacebarFormatType != LanguageOnSpacebarHelper.FORMAT_TYPE_NONE) { + if (mLanguageOnSpacebarFormatType != LanguageOnSpacebarUtils.FORMAT_TYPE_NONE) { drawLanguageOnSpacebar(key, canvas, paint); } // Whether space key needs to show the "..." popup hint for special purposes @@ -843,7 +843,7 @@ public final class MainKeyboardView extends KeyboardView implements DrawingProxy // Layout language name on spacebar. private String layoutLanguageOnSpacebar(final Paint paint, final RichInputMethodSubtype subtype, final int width) { - if (mLanguageOnSpacebarFormatType == LanguageOnSpacebarHelper.FORMAT_TYPE_MULTIPLE) { + if (mLanguageOnSpacebarFormatType == LanguageOnSpacebarUtils.FORMAT_TYPE_MULTIPLE) { final Locale[] locales = subtype.getLocales(); final String[] languages = new String[locales.length]; for (int i = 0; i < locales.length; ++i) { @@ -853,7 +853,7 @@ public final class MainKeyboardView extends KeyboardView implements DrawingProxy } // Choose appropriate language name to fit into the width. - if (mLanguageOnSpacebarFormatType == LanguageOnSpacebarHelper.FORMAT_TYPE_FULL_LOCALE) { + if (mLanguageOnSpacebarFormatType == LanguageOnSpacebarUtils.FORMAT_TYPE_FULL_LOCALE) { final String fullText = subtype.getFullDisplayName(); if (fitsTextIntoWidth(width, fullText, paint)) { return fullText; diff --git a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java index 59763c0fc..22fd90795 100644 --- a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java @@ -39,6 +39,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import javax.annotation.Nullable; + public class ContactsBinaryDictionary extends ExpandableBinaryDictionary { private static final String[] PROJECTION = {BaseColumns._ID, Contacts.DISPLAY_NAME}; @@ -86,7 +88,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary { // Note: This method is called by {@link DictionaryFacilitator} using Java reflection. @ExternallyReferenced public static ContactsBinaryDictionary getDictionary(final Context context, final Locale locale, - final File dictFile, final String dictNamePrefix) { + final File dictFile, final String dictNamePrefix, @Nullable final String account) { return new ContactsBinaryDictionary(context, locale, dictFile, dictNamePrefix + NAME); } diff --git a/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java b/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java index acf9cf10c..b8893a5d8 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java +++ b/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java @@ -44,6 +44,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -56,8 +57,16 @@ import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import javax.annotation.Nullable; -// TODO: Consolidate dictionaries in native code. +/** + * Facilitates interaction with different kinds of dictionaries. Provides APIs + * to instantiate and select the correct dictionaries (based on language or account), + * update entries and fetch suggestions. + * + * Currently AndroidSpellCheckerService and LatinIME both use DictionaryFacilitator as + * a client for interacting with dictionaries. + */ public class DictionaryFacilitator { + // TODO: Consolidate dictionaries in native code. public static final String TAG = DictionaryFacilitator.class.getSimpleName(); // HACK: This threshold is being used when adding a capitalized entry in the User History @@ -99,7 +108,7 @@ public class DictionaryFacilitator { private static final String DICT_FACTORY_METHOD_NAME = "getDictionary"; private static final Class<?>[] DICT_FACTORY_METHOD_ARG_TYPES = - new Class[] { Context.class, Locale.class, File.class, String.class }; + new Class[] { Context.class, Locale.class, File.class, String.class, String.class }; private static final String[] SUB_DICT_TYPES = Arrays.copyOfRange(DICT_TYPES_ORDERED_TO_GET_SUGGESTIONS, 1 /* start */, @@ -107,8 +116,8 @@ public class DictionaryFacilitator { /** * Returns whether this facilitator is exactly for this list of locales. + * * @param locales the list of locales to test against - * @return true if this facilitator handles exactly this list of locales, false otherwise */ public boolean isForLocales(final Locale[] locales) { if (locales.length != mDictionaryGroups.length) { @@ -130,33 +139,62 @@ public class DictionaryFacilitator { } /** + * Returns whether this facilitator is exactly for this account. + * + * @param account the account to test against. + */ + public boolean isForAccount(@Nullable final String account) { + for (final DictionaryGroup group : mDictionaryGroups) { + if (!TextUtils.equals(group.mAccount, account)) { + return false; + } + } + return true; + } + + /** * A group of dictionaries that work together for a single language. */ private static class DictionaryGroup { + // TODO: Add null analysis annotations. // TODO: Run evaluation to determine a reasonable value for these constants. The current // values are ad-hoc and chosen without any particular care or methodology. public static final float WEIGHT_FOR_MOST_PROBABLE_LANGUAGE = 1.0f; public static final float WEIGHT_FOR_GESTURING_IN_NOT_MOST_PROBABLE_LANGUAGE = 0.95f; public static final float WEIGHT_FOR_TYPING_IN_NOT_MOST_PROBABLE_LANGUAGE = 0.6f; - public final Locale mLocale; - private Dictionary mMainDict; + /** + * The locale associated with the dictionary group. + */ + @Nullable public final Locale mLocale; + + /** + * The user account associated with the dictionary group. + */ + @Nullable public final String mAccount; + + @Nullable private Dictionary mMainDict; // Confidence that the most probable language is actually the language the user is // typing in. For now, this is simply the number of times a word from this language // has been committed in a row. private int mConfidence = 0; + public float mWeightForTypingInLocale = WEIGHT_FOR_MOST_PROBABLE_LANGUAGE; public float mWeightForGesturingInLocale = WEIGHT_FOR_MOST_PROBABLE_LANGUAGE; public final ConcurrentHashMap<String, ExpandableBinaryDictionary> mSubDictMap = new ConcurrentHashMap<>(); public DictionaryGroup() { - mLocale = null; + this(null /* locale */, null /* mainDict */, null /* account */, + Collections.<String, ExpandableBinaryDictionary>emptyMap() /* subDicts */); } - public DictionaryGroup(final Locale locale, final Dictionary mainDict, + public DictionaryGroup(@Nullable final Locale locale, + @Nullable final Dictionary mainDict, + @Nullable final String account, final Map<String, ExpandableBinaryDictionary> subDicts) { mLocale = locale; + mAccount = account; // The main dictionary can be asynchronously loaded. setMainDict(mainDict); for (final Map.Entry<String, ExpandableBinaryDictionary> entry : subDicts.entrySet()) { @@ -190,10 +228,17 @@ public class DictionaryFacilitator { return mSubDictMap.get(dictType); } - public boolean hasDict(final String dictType) { + public boolean hasDict(final String dictType, @Nullable final String account) { if (Dictionary.TYPE_MAIN.equals(dictType)) { return mMainDict != null; } + if (Dictionary.TYPE_USER_HISTORY.equals(dictType) && + !TextUtils.equals(account, mAccount)) { + // If the dictionary type is user history, & if the account doesn't match, + // return immediately. If the account matches, continue looking it up in the + // sub dictionary map. + return false; + } return mSubDictMap.containsKey(dictType); } @@ -310,7 +355,7 @@ public class DictionaryFacilitator { @Nullable private static ExpandableBinaryDictionary getSubDict(final String dictType, final Context context, final Locale locale, final File dictFile, - final String dictNamePrefix) { + final String dictNamePrefix, @Nullable final String account) { final Class<? extends ExpandableBinaryDictionary> dictClass = DICT_TYPE_TO_CLASS.get(dictType); if (dictClass == null) { @@ -320,7 +365,7 @@ public class DictionaryFacilitator { final Method factoryMethod = dictClass.getMethod(DICT_FACTORY_METHOD_NAME, DICT_FACTORY_METHOD_ARG_TYPES); final Object dict = factoryMethod.invoke(null /* obj */, - new Object[] { context, locale, dictFile, dictNamePrefix }); + new Object[] { context, locale, dictFile, dictNamePrefix, account }); return (ExpandableBinaryDictionary) dict; } catch (final NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { @@ -332,17 +377,19 @@ public class DictionaryFacilitator { public void resetDictionaries(final Context context, final Locale[] newLocales, final boolean useContactsDict, final boolean usePersonalizedDicts, final boolean forceReloadMainDictionary, + @Nullable final String account, final DictionaryInitializationListener listener) { resetDictionariesWithDictNamePrefix(context, newLocales, useContactsDict, - usePersonalizedDicts, forceReloadMainDictionary, listener, "" /* dictNamePrefix */); + usePersonalizedDicts, forceReloadMainDictionary, listener, "" /* dictNamePrefix */, + account); } @Nullable static DictionaryGroup findDictionaryGroupWithLocale(final DictionaryGroup[] dictionaryGroups, final Locale locale) { - for (int i = 0; i < dictionaryGroups.length; ++i) { - if (locale.equals(dictionaryGroups[i].mLocale)) { - return dictionaryGroups[i]; + for (DictionaryGroup dictionaryGroup : dictionaryGroups) { + if (locale.equals(dictionaryGroup.mLocale)) { + return dictionaryGroup; } } return null; @@ -350,11 +397,13 @@ public class DictionaryFacilitator { public void resetDictionariesWithDictNamePrefix(final Context context, final Locale[] newLocales, - final boolean useContactsDict, final boolean usePersonalizedDicts, + final boolean useContactsDict, + final boolean usePersonalizedDicts, final boolean forceReloadMainDictionary, @Nullable final DictionaryInitializationListener listener, - final String dictNamePrefix) { - final HashMap<Locale, ArrayList<String>> existingDictsToCleanup = new HashMap<>(); + final String dictNamePrefix, + @Nullable final String account) { + final HashMap<Locale, ArrayList<String>> existingDictionariesToCleanup = new HashMap<>(); // TODO: Make subDictTypesToUse configurable by resource or a static final list. final HashSet<String> subDictTypesToUse = new HashSet<>(); subDictTypesToUse.add(Dictionary.TYPE_USER); @@ -369,20 +418,20 @@ public class DictionaryFacilitator { // Gather all dictionaries. We'll remove them from the list to clean up later. for (final Locale newLocale : newLocales) { - final ArrayList<String> dictsForLocale = new ArrayList<>(); - existingDictsToCleanup.put(newLocale, dictsForLocale); + final ArrayList<String> dictTypeForLocale = new ArrayList<>(); + existingDictionariesToCleanup.put(newLocale, dictTypeForLocale); final DictionaryGroup currentDictionaryGroupForLocale = findDictionaryGroupWithLocale(mDictionaryGroups, newLocale); if (null == currentDictionaryGroupForLocale) { continue; } for (final String dictType : SUB_DICT_TYPES) { - if (currentDictionaryGroupForLocale.hasDict(dictType)) { - dictsForLocale.add(dictType); + if (currentDictionaryGroupForLocale.hasDict(dictType, account)) { + dictTypeForLocale.add(dictType); } } - if (currentDictionaryGroupForLocale.hasDict(Dictionary.TYPE_MAIN)) { - dictsForLocale.add(Dictionary.TYPE_MAIN); + if (currentDictionaryGroupForLocale.hasDict(Dictionary.TYPE_MAIN, account)) { + dictTypeForLocale.add(Dictionary.TYPE_MAIN); } } @@ -391,34 +440,35 @@ public class DictionaryFacilitator { final Locale newLocale = newLocales[i]; final DictionaryGroup dictionaryGroupForLocale = findDictionaryGroupWithLocale(mDictionaryGroups, newLocale); - final ArrayList<String> dictsToCleanupForLocale = existingDictsToCleanup.get(newLocale); + final ArrayList<String> dictTypesToCleanupForLocale = + existingDictionariesToCleanup.get(newLocale); final boolean noExistingDictsForThisLocale = (null == dictionaryGroupForLocale); final Dictionary mainDict; if (forceReloadMainDictionary || noExistingDictsForThisLocale - || !dictionaryGroupForLocale.hasDict(Dictionary.TYPE_MAIN)) { + || !dictionaryGroupForLocale.hasDict(Dictionary.TYPE_MAIN, account)) { mainDict = null; } else { mainDict = dictionaryGroupForLocale.getDict(Dictionary.TYPE_MAIN); - dictsToCleanupForLocale.remove(Dictionary.TYPE_MAIN); + dictTypesToCleanupForLocale.remove(Dictionary.TYPE_MAIN); } final Map<String, ExpandableBinaryDictionary> subDicts = new HashMap<>(); for (final String subDictType : subDictTypesToUse) { final ExpandableBinaryDictionary subDict; if (noExistingDictsForThisLocale - || !dictionaryGroupForLocale.hasDict(subDictType)) { + || !dictionaryGroupForLocale.hasDict(subDictType, account)) { // Create a new dictionary. subDict = getSubDict(subDictType, context, newLocale, null /* dictFile */, - dictNamePrefix); + dictNamePrefix, account); } else { // Reuse the existing dictionary, and don't close it at the end subDict = dictionaryGroupForLocale.getSubDict(subDictType); - dictsToCleanupForLocale.remove(subDictType); + dictTypesToCleanupForLocale.remove(subDictType); } subDicts.put(subDictType, subDict); } - newDictionaryGroups[i] = new DictionaryGroup(newLocale, mainDict, subDicts); + newDictionaryGroups[i] = new DictionaryGroup(newLocale, mainDict, account, subDicts); } // Replace Dictionaries. @@ -437,9 +487,9 @@ public class DictionaryFacilitator { } // Clean up old dictionaries. - for (final Locale localeToCleanUp : existingDictsToCleanup.keySet()) { + for (final Locale localeToCleanUp : existingDictionariesToCleanup.keySet()) { final ArrayList<String> dictTypesToCleanUp = - existingDictsToCleanup.get(localeToCleanUp); + existingDictionariesToCleanup.get(localeToCleanUp); final DictionaryGroup dictionarySetToCleanup = findDictionaryGroupWithLocale(oldDictionaryGroups, localeToCleanUp); for (final String dictType : dictTypesToCleanUp) { @@ -493,7 +543,8 @@ public class DictionaryFacilitator { @UsedForTesting public void resetDictionariesForTesting(final Context context, final Locale[] locales, final ArrayList<String> dictionaryTypes, final HashMap<String, File> dictionaryFiles, - final Map<String, Map<String, String>> additionalDictAttributes) { + final Map<String, Map<String, String>> additionalDictAttributes, + @Nullable final String account) { Dictionary mainDictionary = null; final Map<String, ExpandableBinaryDictionary> subDicts = new HashMap<>(); @@ -507,7 +558,7 @@ public class DictionaryFacilitator { } else { final File dictFile = dictionaryFiles.get(dictType); final ExpandableBinaryDictionary dict = getSubDict( - dictType, context, locale, dictFile, "" /* dictNamePrefix */); + dictType, context, locale, dictFile, "" /* dictNamePrefix */, account); if (additionalDictAttributes.containsKey(dictType)) { dict.clearAndFlushDictionaryWithAdditionalAttributes( additionalDictAttributes.get(dictType)); @@ -520,7 +571,7 @@ public class DictionaryFacilitator { subDicts.put(dictType, dict); } } - dictionaryGroups[i] = new DictionaryGroup(locale, mainDictionary, subDicts); + dictionaryGroups[i] = new DictionaryGroup(locale, mainDictionary, account, subDicts); } mDictionaryGroups = dictionaryGroups; mMostProbableDictionaryGroup = dictionaryGroups[0]; @@ -576,7 +627,7 @@ public class DictionaryFacilitator { public boolean hasPersonalizationDictionary() { final DictionaryGroup[] dictionaryGroups = mDictionaryGroups; for (final DictionaryGroup dictionaryGroup : dictionaryGroups) { - if (dictionaryGroup.hasDict(Dictionary.TYPE_PERSONALIZATION)) { + if (dictionaryGroup.hasDict(Dictionary.TYPE_PERSONALIZATION, null /* account */)) { return true; } } @@ -677,7 +728,8 @@ public class DictionaryFacilitator { // History dictionary in order to avoid suggesting them until the dictionary // consolidation is done. // TODO: Remove this hack when ready. - final int lowerCaseFreqInMainDict = dictionaryGroup.hasDict(Dictionary.TYPE_MAIN) ? + final int lowerCaseFreqInMainDict = dictionaryGroup.hasDict(Dictionary.TYPE_MAIN, + null /* account */) ? dictionaryGroup.getDict(Dictionary.TYPE_MAIN).getFrequency(lowerCasedWord) : Dictionary.NOT_A_PROBABILITY; if (maxFreq < lowerCaseFreqInMainDict diff --git a/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java b/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java index b578159eb..3119ff82f 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java +++ b/java/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCache.java @@ -102,10 +102,12 @@ public class DictionaryFacilitatorLruCache { private void resetDictionariesForLocaleLocked(final DictionaryFacilitator dictionaryFacilitator, final Locale locale) { + // Note: Given that personalized dictionaries are not used here; we can pass null account. dictionaryFacilitator.resetDictionariesWithDictNamePrefix(mContext, new Locale[] { locale }, mUseContactsDictionary, false /* usePersonalizedDicts */, false /* forceReloadMainDictionary */, null /* listener */, - mDictionaryNamePrefix); + mDictionaryNamePrefix, + null /* account */); } public void setUseContactsDictionary(final boolean useContectsDictionary) { diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index 27115e266..45156a31e 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -32,7 +32,6 @@ import android.content.res.Configuration; import android.content.res.Resources; import android.inputmethodservice.InputMethodService; import android.media.AudioManager; -import android.net.ConnectivityManager; import android.os.Build; import android.os.Debug; import android.os.IBinder; @@ -100,6 +99,7 @@ import com.android.inputmethod.latin.utils.ImportantNoticeUtils; import com.android.inputmethod.latin.utils.IntentUtils; import com.android.inputmethod.latin.utils.JniUtils; import com.android.inputmethod.latin.utils.LeakGuardHandlerWrapper; +import com.android.inputmethod.latin.utils.NetworkConnectivityUtils; import com.android.inputmethod.latin.utils.StatsUtils; import com.android.inputmethod.latin.utils.StatsUtilsManager; import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; @@ -166,7 +166,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private RichInputMethodManager mRichImm; @UsedForTesting final KeyboardSwitcher mKeyboardSwitcher; - final SubtypeSwitcher mSubtypeSwitcher; private final SubtypeState mSubtypeState = new SubtypeState(); private final EmojiAltPhysicalKeyDetector mEmojiAltPhysicalKeyDetector = new EmojiAltPhysicalKeyDetector(); @@ -563,7 +562,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen public LatinIME() { super(); mSettings = Settings.getInstance(); - mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mStatsUtilsManager = StatsUtilsManager.getInstance(); mIsHardwareAcceleratedDrawingEnabled = @@ -577,7 +575,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen DebugFlags.init(PreferenceManager.getDefaultSharedPreferences(this)); RichInputMethodManager.init(this); mRichImm = RichInputMethodManager.getInstance(); - SubtypeSwitcher.init(this); KeyboardSwitcher.init(this); AudioAndHapticFeedbackManager.init(this); AccessibilityUtils.init(this); @@ -592,13 +589,14 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen loadSettings(); resetDictionaryFacilitatorIfNecessary(); - // Register to receive ringer mode change and network state change. - // Also receive installation and removal of a dictionary pack. + NetworkConnectivityUtils.onCreate(this /* context */, mKeyboardSwitcher /* listener */); + + // Register to receive ringer mode change. final IntentFilter filter = new IntentFilter(); - filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); - registerReceiver(mConnectivityAndRingerModeChangeReceiver, filter); + registerReceiver(mRingerModeChangeReceiver, filter); + // Register to receive installation and removal of a dictionary pack. final IntentFilter packageFilter = new IntentFilter(); packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); @@ -632,12 +630,13 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // been displayed. Opening dictionaries never affects responsivity as dictionaries are // asynchronously loaded. if (!mHandler.hasPendingReopenDictionaries()) { - resetDictionaryFacilitatorForLocale(locales); + resetDictionaryFacilitator(locales); } mDictionaryFacilitator.updateEnabledSubtypes(mRichImm.getMyEnabledInputMethodSubtypeList( true /* allowsImplicitlySelectedSubtypes */)); refreshPersonalizationDictionarySession(currentSettingsValues); mStatsUtilsManager.onLoadSettings(currentSettingsValues); + resetDictionaryFacilitatorIfNecessary(); } private void refreshPersonalizationDictionarySession( @@ -675,7 +674,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen void resetDictionaryFacilitatorIfNecessary() { final Locale[] subtypeSwitcherLocales = mRichImm.getCurrentSubtypeLocales(); - if (mDictionaryFacilitator.isForLocales(subtypeSwitcherLocales)) { + if (mDictionaryFacilitator.isForLocales(subtypeSwitcherLocales) + && mDictionaryFacilitator.isForAccount(mSettings.getCurrent().mAccount)) { return; } final Locale[] subtypeLocales; @@ -689,20 +689,23 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } else { subtypeLocales = subtypeSwitcherLocales; } - resetDictionaryFacilitatorForLocale(subtypeLocales); + resetDictionaryFacilitator(subtypeLocales); } /** - * Reset the facilitator by loading dictionaries for the locales and the current settings values + * Reset the facilitator by loading dictionaries for the locales and + * the current settings values. * * @param locales the locales */ - // TODO: make sure the current settings always have the right locales, and read from them - private void resetDictionaryFacilitatorForLocale(final Locale[] locales) { + // TODO: make sure the current settings always have the right locales, and read from them. + private void resetDictionaryFacilitator(final Locale[] locales) { final SettingsValues settingsValues = mSettings.getCurrent(); mDictionaryFacilitator.resetDictionaries(this /* context */, locales, settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, - false /* forceReloadMainDictionary */, this); + false /* forceReloadMainDictionary */, + settingsValues.mAccount, + this /* DictionaryInitializationListener */); if (settingsValues.mAutoCorrectionEnabledPerUserSettings) { mInputLogic.mSuggest.setAutoCorrectionThreshold( settingsValues.mAutoCorrectionThreshold); @@ -717,7 +720,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final SettingsValues settingsValues = mSettings.getCurrent(); mDictionaryFacilitator.resetDictionaries(this /* context */, mDictionaryFacilitator.getLocales(), settingsValues.mUseContactsDict, - settingsValues.mUsePersonalizedDicts, true /* forceReloadMainDictionary */, this); + settingsValues.mUsePersonalizedDicts, + true /* forceReloadMainDictionary */, + settingsValues.mAccount, + this /* DictionaryInitializationListener */); } @Override @@ -726,7 +732,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mPersonalizationDictionaryUpdater.onDestroy(); mContextualDictionaryUpdater.onDestroy(); mSettings.onDestroy(); - unregisterReceiver(mConnectivityAndRingerModeChangeReceiver); + NetworkConnectivityUtils.onDestroy(this /* context */); + unregisterReceiver(mRingerModeChangeReceiver); unregisterReceiver(mDictionaryPackInstallReceiver); unregisterReceiver(mDictionaryDumpBroadcastReceiver); mStatsUtilsManager.onDestroy(); @@ -738,7 +745,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen public void recycle() { unregisterReceiver(mDictionaryPackInstallReceiver); unregisterReceiver(mDictionaryDumpBroadcastReceiver); - unregisterReceiver(mConnectivityAndRingerModeChangeReceiver); + unregisterReceiver(mRingerModeChangeReceiver); + NetworkConnectivityUtils.onDestroy(this /* context */); mInputLogic.recycle(); } @@ -866,7 +874,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() // is not guaranteed. It may even be called at the same time on a different thread. mRichImm.onSubtypeChanged(subtype); - mSubtypeSwitcher.onSubtypeChanged(mRichImm.getCurrentSubtype()); mInputLogic.onSubtypeChanged(SubtypeLocaleUtils.getCombiningRulesExtraValue(subtype), mSettings.getCurrent()); loadKeyboard(); @@ -883,7 +890,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // also wouldn't be consuming gesture data. mGestureConsumer = GestureConsumer.NULL_GESTURE_CONSUMER; mRichImm.refreshSubtypeCaches(); - mSubtypeSwitcher.onSubtypeChanged(mRichImm.getCurrentSubtype()); final KeyboardSwitcher switcher = mKeyboardSwitcher; switcher.updateKeyboardTheme(); final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); @@ -945,10 +951,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen Settings.getInstance().getCurrent().mDisplayOrientation, !isDifferentTextField); - if (isDifferentTextField) { - mSubtypeSwitcher.updateParametersOnStartInputView(); - } - // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); @@ -1828,15 +1830,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // boolean onKeyLongPress(final int keyCode, final KeyEvent event); // boolean onKeyMultiple(final int keyCode, final int count, final KeyEvent event); - // receive ringer mode change and network state change. - private final BroadcastReceiver mConnectivityAndRingerModeChangeReceiver = - new BroadcastReceiver() { + // receive ringer mode change. + private final BroadcastReceiver mRingerModeChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); - if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { - mRichImm.onNetworkStateChanged(intent); - } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { + if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { AudioAndHapticFeedbackManager.getInstance().onRingerModeChanged(); } } @@ -1934,7 +1933,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final SettingsValues settingsValues = mSettings.getCurrent(); mDictionaryFacilitator.resetDictionaries(this, new Locale[] { locale }, settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, - false /* forceReloadMainDictionary */, this /* listener */); + false /* forceReloadMainDictionary */, + settingsValues.mAccount, + this /* DictionaryInitializationListener */); } // DO NOT USE THIS for any other purpose than testing. diff --git a/java/src/com/android/inputmethod/latin/PersonalizationHelperForDictionaryFacilitator.java b/java/src/com/android/inputmethod/latin/PersonalizationHelperForDictionaryFacilitator.java index 2dbab0a3f..8926c06b1 100644 --- a/java/src/com/android/inputmethod/latin/PersonalizationHelperForDictionaryFacilitator.java +++ b/java/src/com/android/inputmethod/latin/PersonalizationHelperForDictionaryFacilitator.java @@ -114,7 +114,7 @@ public class PersonalizationHelperForDictionaryFacilitator { return personalizationDict; } personalizationDict = PersonalizationDictionary.getDictionary(context, locale, - null /* dictFile */, "" /* dictNamePrefix */); + null /* dictFile */, "" /* dictNamePrefix */, null /* account */); mPersonalizationDictsToUpdate.put(locale, personalizationDict); return personalizationDict; } diff --git a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java index 462121789..811af4bd7 100644 --- a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java +++ b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java @@ -20,11 +20,8 @@ import static com.android.inputmethod.latin.common.Constants.Subtype.KEYBOARD_MO import static com.android.inputmethod.latin.common.Constants.Subtype.ExtraValue.REQ_NETWORK_CONNECTIVITY; import android.content.Context; -import android.content.Intent; import android.content.SharedPreferences; import android.inputmethodservice.InputMethodService; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.IBinder; @@ -36,10 +33,11 @@ import android.view.inputmethod.InputMethodSubtype; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.compat.InputMethodManagerCompatWrapper; -import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.latin.settings.AdditionalFeaturesSettingUtils; import com.android.inputmethod.latin.settings.Settings; import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; +import com.android.inputmethod.latin.utils.LanguageOnSpacebarUtils; +import com.android.inputmethod.latin.utils.NetworkConnectivityUtils; import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; import java.util.Collections; @@ -72,11 +70,6 @@ public class RichInputMethodManager { private RichInputMethodSubtype mCurrentRichInputMethodSubtype; private InputMethodInfo mShortcutInputMethodInfo; private InputMethodSubtype mShortcutSubtype; - private boolean mIsNetworkConnected; - final HashMap<InputMethodInfo, List<InputMethodSubtype>> - mSubtypeListCacheWithImplicitlySelectedSubtypes = new HashMap<>(); - final HashMap<InputMethodInfo, List<InputMethodSubtype>> - mSubtypeListCacheWithoutImplicitlySelectedSubtypes = new HashMap<>(); private static final int INDEX_NOT_FOUND = -1; @@ -116,11 +109,6 @@ public class RichInputMethodManager { // Initialize the current input method subtype and the shortcut IME. refreshSubtypeCaches(); - - final ConnectivityManager connectivityManager = - (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - final NetworkInfo info = connectivityManager.getActiveNetworkInfo(); - mIsNetworkConnected = (info != null && info.isConnected()); } public InputMethodSubtype[] getAdditionalSubtypes() { @@ -243,33 +231,57 @@ public class RichInputMethodManager { private final InputMethodManager mImm; private final String mImePackageName; - private InputMethodInfo mCachedValue; + private InputMethodInfo mCachedThisImeInfo; + private final HashMap<InputMethodInfo, List<InputMethodSubtype>> + mCachedSubtypeListWithImplicitlySelected; + private final HashMap<InputMethodInfo, List<InputMethodSubtype>> + mCachedSubtypeListOnlyExplicitlySelected; public InputMethodInfoCache(final InputMethodManager imm, final String imePackageName) { mImm = imm; mImePackageName = imePackageName; + mCachedSubtypeListWithImplicitlySelected = new HashMap<>(); + mCachedSubtypeListOnlyExplicitlySelected = new HashMap<>(); } - public synchronized InputMethodInfo get() { - if (mCachedValue != null) { - return mCachedValue; + public synchronized InputMethodInfo getInputMethodOfThisIme() { + if (mCachedThisImeInfo != null) { + return mCachedThisImeInfo; } for (final InputMethodInfo imi : mImm.getInputMethodList()) { if (imi.getPackageName().equals(mImePackageName)) { - mCachedValue = imi; + mCachedThisImeInfo = imi; return imi; } } throw new RuntimeException("Input method id for " + mImePackageName + " not found."); } + public synchronized List<InputMethodSubtype> getEnabledInputMethodSubtypeList( + final InputMethodInfo imi, final boolean allowsImplicitlySelectedSubtypes) { + final HashMap<InputMethodInfo, List<InputMethodSubtype>> cache = + allowsImplicitlySelectedSubtypes + ? mCachedSubtypeListWithImplicitlySelected + : mCachedSubtypeListOnlyExplicitlySelected; + final List<InputMethodSubtype> cachedList = cache.get(imi); + if (cachedList != null) { + return cachedList; + } + final List<InputMethodSubtype> result = mImm.getEnabledInputMethodSubtypeList( + imi, allowsImplicitlySelectedSubtypes); + cache.put(imi, result); + return result; + } + public synchronized void clear() { - mCachedValue = null; + mCachedThisImeInfo = null; + mCachedSubtypeListWithImplicitlySelected.clear(); + mCachedSubtypeListOnlyExplicitlySelected.clear(); } } public InputMethodInfo getInputMethodInfoOfThisIme() { - return mInputMethodInfoCache.get(); + return mInputMethodInfoCache.getInputMethodOfThisIme(); } public String getInputMethodIdOfThisIme() { @@ -454,21 +466,11 @@ public class RichInputMethodManager { private List<InputMethodSubtype> getEnabledInputMethodSubtypeList(final InputMethodInfo imi, final boolean allowsImplicitlySelectedSubtypes) { - final HashMap<InputMethodInfo, List<InputMethodSubtype>> cache = - allowsImplicitlySelectedSubtypes - ? mSubtypeListCacheWithImplicitlySelectedSubtypes - : mSubtypeListCacheWithoutImplicitlySelectedSubtypes; - final List<InputMethodSubtype> cachedList = cache.get(imi); - if (null != cachedList) return cachedList; - final List<InputMethodSubtype> result = mImmWrapper.mImm.getEnabledInputMethodSubtypeList( + return mInputMethodInfoCache.getEnabledInputMethodSubtypeList( imi, allowsImplicitlySelectedSubtypes); - cache.put(imi, result); - return result; } public void refreshSubtypeCaches() { - mSubtypeListCacheWithImplicitlySelectedSubtypes.clear(); - mSubtypeListCacheWithoutImplicitlySelectedSubtypes.clear(); mInputMethodInfoCache.clear(); updateCurrentSubtype(mImmWrapper.mImm.getCurrentInputMethodSubtype()); updateShortcutIme(); @@ -511,9 +513,7 @@ public class RichInputMethodManager { } private void updateCurrentSubtype(@Nonnull final InputMethodSubtype subtype) { - final RichInputMethodSubtype richSubtype = AdditionalFeaturesSettingUtils - .createRichInputMethodSubtype(this, subtype, mContext); - mCurrentRichInputMethodSubtype = richSubtype; + mCurrentRichInputMethodSubtype = new RichInputMethodSubtype(subtype); } private void updateShortcutIme() { @@ -524,6 +524,15 @@ public class RichInputMethodManager { + (mShortcutSubtype == null ? "<null>" : ( mShortcutSubtype.getLocale() + ", " + mShortcutSubtype.getMode()))); } + final RichInputMethodSubtype richSubtype = mCurrentRichInputMethodSubtype; + final boolean implicitlyEnabledSubtype = checkIfSubtypeBelongsToThisImeAndImplicitlyEnabled( + richSubtype.getRawSubtype()); + final Locale systemLocale = mContext.getResources().getConfiguration().locale; + LanguageOnSpacebarUtils.onSubtypeChanged( + richSubtype, implicitlyEnabledSubtype, systemLocale); + LanguageOnSpacebarUtils.setEnabledSubtypes(getMyEnabledInputMethodSubtypeList( + true /* allowsImplicitlySelectedSubtypes */)); + // TODO: Update an icon for shortcut IME final Map<InputMethodInfo, List<InputMethodSubtype>> shortcuts = getInputMethodManager().getShortcutInputMethodsAndSubtypes(); @@ -591,16 +600,8 @@ public class RichInputMethodManager { return true; } if (mShortcutSubtype.containsExtraValueKey(REQ_NETWORK_CONNECTIVITY)) { - return mIsNetworkConnected; + return NetworkConnectivityUtils.isNetworkConnected(); } return true; } - - public void onNetworkStateChanged(final Intent intent) { - final boolean noConnection = intent.getBooleanExtra( - ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); - mIsNetworkConnected = !noConnection; - - KeyboardSwitcher.getInstance().onNetworkStateChanged(); - } } diff --git a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java deleted file mode 100644 index 92ba6c2d9..000000000 --- a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.inputmethod.latin; - -import android.content.Context; -import android.content.res.Resources; -import android.view.inputmethod.InputMethodSubtype; - -import com.android.inputmethod.keyboard.internal.LanguageOnSpacebarHelper; -import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; - -import java.util.List; - -import javax.annotation.Nonnull; - -public final class SubtypeSwitcher { - private static final SubtypeSwitcher sInstance = new SubtypeSwitcher(); - - private /* final */ RichInputMethodManager mRichImm; - private /* final */ Resources mResources; - - private final LanguageOnSpacebarHelper mLanguageOnSpacebarHelper = - new LanguageOnSpacebarHelper(); - - public static SubtypeSwitcher getInstance() { - return sInstance; - } - - public static void init(final Context context) { - SubtypeLocaleUtils.init(context); - RichInputMethodManager.init(context); - sInstance.initialize(context); - } - - private SubtypeSwitcher() { - // Intentional empty constructor for singleton. - } - - private void initialize(final Context context) { - if (mResources != null) { - return; - } - mResources = context.getResources(); - mRichImm = RichInputMethodManager.getInstance(); - - onSubtypeChanged(mRichImm.getCurrentSubtype()); - updateParametersOnStartInputView(); - } - - /** - * Update parameters which are changed outside LatinIME. This parameters affect UI so that they - * should be updated every time onStartInputView is called. - */ - public void updateParametersOnStartInputView() { - final List<InputMethodSubtype> enabledSubtypesOfThisIme = - mRichImm.getMyEnabledInputMethodSubtypeList(true); - mLanguageOnSpacebarHelper.onUpdateEnabledSubtypes(enabledSubtypesOfThisIme); - } - - // Update the current subtype. LatinIME.onCurrentInputMethodSubtypeChanged calls this function. - public void onSubtypeChanged(@Nonnull final RichInputMethodSubtype richSubtype) { - final boolean implicitlyEnabledSubtype = mRichImm - .checkIfSubtypeBelongsToThisImeAndImplicitlyEnabled(richSubtype.getRawSubtype()); - mLanguageOnSpacebarHelper.onSubtypeChanged( - richSubtype, implicitlyEnabledSubtype, mResources.getConfiguration().locale); - } - - public int getLanguageOnSpacebarFormatType(final RichInputMethodSubtype subtype) { - return mLanguageOnSpacebarHelper.getLanguageOnSpacebarFormatType(subtype); - } -} diff --git a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java index 2b7fb1748..2d2b3d0a6 100644 --- a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java @@ -36,6 +36,8 @@ import java.io.File; import java.util.Arrays; import java.util.Locale; +import javax.annotation.Nullable; + /** * An expandable dictionary that stores the words in the user dictionary provider into a binary * dictionary file to use it from native code. @@ -104,7 +106,7 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { // Note: This method is called by {@link DictionaryFacilitator} using Java reflection. @ExternallyReferenced public static UserBinaryDictionary getDictionary(final Context context, final Locale locale, - final File dictFile, final String dictNamePrefix) { + final File dictFile, final String dictNamePrefix, @Nullable final String account) { return new UserBinaryDictionary(context, locale, false /* alsoUseMoreRestrictiveLocales */, dictFile, dictNamePrefix + NAME); } diff --git a/java/src/com/android/inputmethod/latin/personalization/ContextualDictionary.java b/java/src/com/android/inputmethod/latin/personalization/ContextualDictionary.java index 39d9596ef..f663fe96a 100644 --- a/java/src/com/android/inputmethod/latin/personalization/ContextualDictionary.java +++ b/java/src/com/android/inputmethod/latin/personalization/ContextualDictionary.java @@ -25,6 +25,8 @@ import com.android.inputmethod.latin.ExpandableBinaryDictionary; import java.io.File; import java.util.Locale; +import javax.annotation.Nullable; + public class ContextualDictionary extends ExpandableBinaryDictionary { /* package */ static final String NAME = ContextualDictionary.class.getSimpleName(); @@ -40,7 +42,7 @@ public class ContextualDictionary extends ExpandableBinaryDictionary { @SuppressWarnings("unused") @ExternallyReferenced public static ContextualDictionary getDictionary(final Context context, final Locale locale, - final File dictFile, final String dictNamePrefix) { + final File dictFile, final String dictNamePrefix, @Nullable final String account) { return new ContextualDictionary(context, locale, dictFile); } diff --git a/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionary.java b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionary.java index 33d1273f7..76451cc6b 100644 --- a/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionary.java +++ b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionary.java @@ -24,6 +24,8 @@ import com.android.inputmethod.latin.Dictionary; import java.io.File; import java.util.Locale; +import javax.annotation.Nullable; + public class PersonalizationDictionary extends DecayingExpandableBinaryDictionaryBase { /* package */ static final String NAME = PersonalizationDictionary.class.getSimpleName(); @@ -37,7 +39,8 @@ public class PersonalizationDictionary extends DecayingExpandableBinaryDictionar @SuppressWarnings("unused") @ExternallyReferenced public static PersonalizationDictionary getDictionary(final Context context, - final Locale locale, final File dictFile, final String dictNamePrefix) { + final Locale locale, final File dictFile, final String dictNamePrefix, + @Nullable final String account) { return PersonalizationHelper.getPersonalizationDictionary(context, locale); } } diff --git a/java/src/com/android/inputmethod/latin/personalization/PersonalizationHelper.java b/java/src/com/android/inputmethod/latin/personalization/PersonalizationHelper.java index b595f3974..4231450c1 100644 --- a/java/src/com/android/inputmethod/latin/personalization/PersonalizationHelper.java +++ b/java/src/com/android/inputmethod/latin/personalization/PersonalizationHelper.java @@ -64,7 +64,8 @@ public class PersonalizationHelper { return dict; } } - final UserHistoryDictionary dict = new UserHistoryDictionary(context, locale); + final UserHistoryDictionary dict = new UserHistoryDictionary( + context, locale, accountName); sLangUserHistoryDictCache.put(lookupStr, new SoftReference<>(dict)); return dict; } diff --git a/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java b/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java index 946835cbc..2e41027a4 100644 --- a/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java +++ b/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionary.java @@ -37,20 +37,18 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; /** - * Locally gathers stats about the words user types and various other signals like auto-correction - * cancellation or manual picks. This allows the keyboard to adapt to the typist over time. + * Locally gathers statistics about the words user types and various other signals like + * auto-correction cancellation or manual picks. This allows the keyboard to adapt to the + * typist over time. */ public class UserHistoryDictionary extends DecayingExpandableBinaryDictionaryBase { static final String NAME = UserHistoryDictionary.class.getSimpleName(); // TODO: Make this constructor private - UserHistoryDictionary(final Context context, final Locale locale) { + UserHistoryDictionary(final Context context, final Locale locale, + @Nullable final String account) { super(context, - getUserHistoryDictName( - NAME, - locale, - null /* dictFile */, - context), + getUserHistoryDictName(NAME, locale, null /* dictFile */, account), locale, Dictionary.TYPE_USER_HISTORY, null /* dictFile */); @@ -61,24 +59,21 @@ public class UserHistoryDictionary extends DecayingExpandableBinaryDictionaryBas */ @UsedForTesting static String getUserHistoryDictName(final String name, final Locale locale, - @Nullable final File dictFile, final Context context) { + @Nullable final File dictFile, @Nullable final String account) { if (!ProductionFlags.ENABLE_PER_ACCOUNT_USER_HISTORY_DICTIONARY) { return getDictName(name, locale, dictFile); } - return getUserHistoryDictNamePerAccount(name, locale, dictFile, context); + return getUserHistoryDictNamePerAccount(name, locale, dictFile, account); } /** * Uses the currently signed in account to determine the dictionary name. */ private static String getUserHistoryDictNamePerAccount(final String name, final Locale locale, - @Nullable final File dictFile, final Context context) { + @Nullable final File dictFile, @Nullable final String account) { if (dictFile != null) { return dictFile.getName(); } - final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - final String account = prefs.getString(LocalSettingsConstants.PREF_ACCOUNT_NAME, - null /* default */); String dictName = name + "." + locale.toString(); if (account != null) { dictName += "." + account; @@ -90,14 +85,7 @@ public class UserHistoryDictionary extends DecayingExpandableBinaryDictionaryBas @SuppressWarnings("unused") @ExternallyReferenced public static UserHistoryDictionary getDictionary(final Context context, final Locale locale, - final File dictFile, final String dictNamePrefix) { - final String account; - if (ProductionFlags.ENABLE_PER_ACCOUNT_USER_HISTORY_DICTIONARY) { - account = PreferenceManager.getDefaultSharedPreferences(context) - .getString(LocalSettingsConstants.PREF_ACCOUNT_NAME, null /* default */); - } else { - account = null; - } + final File dictFile, final String dictNamePrefix, @Nullable final String account) { return PersonalizationHelper.getUserHistoryDictionary(context, locale, account); } diff --git a/java/src/com/android/inputmethod/latin/settings/AccountsSettingsFragment.java b/java/src/com/android/inputmethod/latin/settings/AccountsSettingsFragment.java index 4bd15d037..8f4ec4f1b 100644 --- a/java/src/com/android/inputmethod/latin/settings/AccountsSettingsFragment.java +++ b/java/src/com/android/inputmethod/latin/settings/AccountsSettingsFragment.java @@ -33,9 +33,8 @@ import android.widget.Toast; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.latin.R; -import com.android.inputmethod.latin.SubtypeSwitcher; -import com.android.inputmethod.latin.accounts.LoginAccountUtils; import com.android.inputmethod.latin.accounts.AccountStateChangedListener; +import com.android.inputmethod.latin.accounts.LoginAccountUtils; import com.android.inputmethod.latin.define.ProductionFlags; import javax.annotation.Nullable; @@ -50,12 +49,15 @@ import javax.annotation.Nullable; */ public final class AccountsSettingsFragment extends SubScreenFragment { private static final String PREF_SYNC_NOW = "pref_beanstalk"; + private static final String PREF_CLEAR_SYNC_DATA = "pref_beanstalk_clear_data"; static final String PREF_ACCCOUNT_SWITCHER = "account_switcher"; private final DialogInterface.OnClickListener mAccountChangedListener = new AccountChangedListener(); private final Preference.OnPreferenceClickListener mSyncNowListener = new SyncNowListener(); + private final Preference.OnPreferenceClickListener mClearSyncDataListener = + new ClearSyncDataListener(); @Override public void onCreate(final Bundle icicle) { @@ -63,12 +65,6 @@ public final class AccountsSettingsFragment extends SubScreenFragment { addPreferencesFromResource(R.xml.prefs_screen_accounts); final Resources res = getResources(); - final Context context = getActivity(); - - // When we are called from the Settings application but we are not already running, some - // singleton and utility classes may not have been initialized. We have to call - // initialization method of these classes here. See {@link LatinIME#onCreate()}. - SubtypeSwitcher.init(context); if (ProductionFlags.IS_METRICS_LOGGING_SUPPORTED) { final Preference enableMetricsLogging = @@ -86,13 +82,18 @@ public final class AccountsSettingsFragment extends SubScreenFragment { removePreference(PREF_ACCCOUNT_SWITCHER); removePreference(PREF_ENABLE_CLOUD_SYNC); removePreference(PREF_SYNC_NOW); + removePreference(PREF_CLEAR_SYNC_DATA); } if (!ProductionFlags.ENABLE_PERSONAL_DICTIONARY_SYNC) { removePreference(PREF_ENABLE_CLOUD_SYNC); removePreference(PREF_SYNC_NOW); + removePreference(PREF_CLEAR_SYNC_DATA); } else { final Preference syncNowPreference = findPreference(PREF_SYNC_NOW); syncNowPreference.setOnPreferenceClickListener(mSyncNowListener); + + final Preference clearSyncDataPreference = findPreference(PREF_CLEAR_SYNC_DATA); + clearSyncDataPreference.setOnPreferenceClickListener(mClearSyncDataListener); } } @@ -136,7 +137,7 @@ public final class AccountsSettingsFragment extends SubScreenFragment { final String[] accountsForLogin = LoginAccountUtils.getAccountsForLogin(context); accountSwitcher.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override - public boolean onPreferenceClick(Preference preference) { + public boolean onPreferenceClick(final Preference preference) { if (accountsForLogin.length == 0) { // TODO: Handle account addition. Toast.makeText(getActivity(), getString(R.string.account_select_cancel), @@ -229,7 +230,7 @@ public final class AccountsSettingsFragment extends SubScreenFragment { */ class AccountChangedListener implements DialogInterface.OnClickListener { @Override - public void onClick(DialogInterface dialog, int which) { + public void onClick(final DialogInterface dialog, final int which) { final String oldAccount = getSignedInAccountName(); switch (which) { case DialogInterface.BUTTON_POSITIVE: // Signed in @@ -263,4 +264,30 @@ public final class AccountsSettingsFragment extends SubScreenFragment { return true; } } + + /** + * Listener that initiates the process of deleting user's data from the cloud. + */ + class ClearSyncDataListener implements Preference.OnPreferenceClickListener { + @Override + public boolean onPreferenceClick(final Preference preference) { + final AlertDialog confirmationDialog = new AlertDialog.Builder(getActivity()) + .setTitle(R.string.clear_sync_data_title) + .setMessage(R.string.clear_sync_data_confirmation) + .setPositiveButton(R.string.clear_sync_data_ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(final DialogInterface dialog, final int which) { + if (which == DialogInterface.BUTTON_POSITIVE) { + AccountStateChangedListener.forceDelete( + getSignedInAccountName()); + } + } + }) + .setNegativeButton(R.string.clear_sync_data_cancel, null /* OnClickListener */) + .create(); + confirmationDialog.show(); + return true; + } + } } diff --git a/java/src/com/android/inputmethod/latin/settings/SettingsValues.java b/java/src/com/android/inputmethod/latin/settings/SettingsValues.java index 5f1a7af44..0669026d8 100644 --- a/java/src/com/android/inputmethod/latin/settings/SettingsValues.java +++ b/java/src/com/android/inputmethod/latin/settings/SettingsValues.java @@ -36,6 +36,7 @@ import java.util.Arrays; import java.util.Locale; import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * When you call the constructor of this class, you may want to change the current system locale by @@ -120,6 +121,8 @@ public class SettingsValues { public final float mKeyPreviewDismissEndXScale; public final float mKeyPreviewDismissEndYScale; + @Nullable public final String mAccount; + public SettingsValues(final Context context, final SharedPreferences prefs, final Resources res, @Nonnull final InputAttributes inputAttributes) { mLocale = res.getConfiguration().locale; @@ -176,6 +179,8 @@ public class SettingsValues { mPlausibilityThreshold = Settings.readPlausibilityThreshold(res); mGestureInputEnabled = Settings.readGestureInputEnabled(prefs, res); mGestureTrailEnabled = prefs.getBoolean(Settings.PREF_GESTURE_PREVIEW_TRAIL, true); + mAccount = prefs.getString(LocalSettingsConstants.PREF_ACCOUNT_NAME, + null /* default */); mGestureFloatingPreviewTextEnabled = !mInputAttributes.mDisableGestureFloatingPreviewText && prefs.getBoolean(Settings.PREF_GESTURE_FLOATING_PREVIEW_TEXT, true); mPhraseGestureEnabled = Settings.readPhraseGestureEnabled(prefs, res); diff --git a/java/src/com/android/inputmethod/keyboard/internal/LanguageOnSpacebarHelper.java b/java/src/com/android/inputmethod/latin/utils/LanguageOnSpacebarUtils.java index 8ed80107a..fa1583b7a 100644 --- a/java/src/com/android/inputmethod/keyboard/internal/LanguageOnSpacebarHelper.java +++ b/java/src/com/android/inputmethod/latin/utils/LanguageOnSpacebarUtils.java @@ -14,12 +14,11 @@ * limitations under the License. */ -package com.android.inputmethod.keyboard.internal; +package com.android.inputmethod.latin.utils; import android.view.inputmethod.InputMethodSubtype; import com.android.inputmethod.latin.RichInputMethodSubtype; -import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; import java.util.Collections; import java.util.List; @@ -30,21 +29,26 @@ import javax.annotation.Nonnull; /** * This class determines that the language name on the spacebar should be displayed in what format. */ -public final class LanguageOnSpacebarHelper { +public final class LanguageOnSpacebarUtils { public static final int FORMAT_TYPE_NONE = 0; public static final int FORMAT_TYPE_LANGUAGE_ONLY = 1; public static final int FORMAT_TYPE_FULL_LOCALE = 2; public static final int FORMAT_TYPE_MULTIPLE = 3; - private List<InputMethodSubtype> mEnabledSubtypes = Collections.emptyList(); - private boolean mIsSystemLanguageSameAsInputLanguage; + private static List<InputMethodSubtype> sEnabledSubtypes = Collections.emptyList(); + private static boolean sIsSystemLanguageSameAsInputLanguage; - public int getLanguageOnSpacebarFormatType(@Nonnull final RichInputMethodSubtype subtype) { + private LanguageOnSpacebarUtils() { + // This utility class is not publicly instantiable. + } + + public static int getLanguageOnSpacebarFormatType( + @Nonnull final RichInputMethodSubtype subtype) { if (subtype.isNoLanguage()) { return FORMAT_TYPE_FULL_LOCALE; } // Only this subtype is enabled and equals to the system locale. - if (mEnabledSubtypes.size() < 2 && mIsSystemLanguageSameAsInputLanguage) { + if (sEnabledSubtypes.size() < 2 && sIsSystemLanguageSameAsInputLanguage) { return FORMAT_TYPE_NONE; } final Locale[] locales = subtype.getLocales(); @@ -54,7 +58,7 @@ public final class LanguageOnSpacebarHelper { final String keyboardLanguage = locales[0].getLanguage(); final String keyboardLayout = subtype.getKeyboardLayoutSetName(); int sameLanguageAndLayoutCount = 0; - for (final InputMethodSubtype ims : mEnabledSubtypes) { + for (final InputMethodSubtype ims : sEnabledSubtypes) { final String language = SubtypeLocaleUtils.getSubtypeLocale(ims).getLanguage(); if (keyboardLanguage.equals(language) && keyboardLayout.equals( SubtypeLocaleUtils.getKeyboardLayoutSetName(ims))) { @@ -67,30 +71,30 @@ public final class LanguageOnSpacebarHelper { : FORMAT_TYPE_LANGUAGE_ONLY; } - public void onUpdateEnabledSubtypes(@Nonnull final List<InputMethodSubtype> enabledSubtypes) { - mEnabledSubtypes = enabledSubtypes; + public static void setEnabledSubtypes(@Nonnull final List<InputMethodSubtype> enabledSubtypes) { + sEnabledSubtypes = enabledSubtypes; } - public void onSubtypeChanged(@Nonnull final RichInputMethodSubtype subtype, + public static void onSubtypeChanged(@Nonnull final RichInputMethodSubtype subtype, final boolean implicitlyEnabledSubtype, @Nonnull final Locale systemLocale) { final Locale[] newLocales = subtype.getLocales(); if (newLocales.length > 1) { // In multi-locales mode, the system language is never the same as the input language // because there is no single input language. - mIsSystemLanguageSameAsInputLanguage = false; + sIsSystemLanguageSameAsInputLanguage = false; return; } final Locale newLocale = newLocales[0]; if (systemLocale.equals(newLocale)) { - mIsSystemLanguageSameAsInputLanguage = true; + sIsSystemLanguageSameAsInputLanguage = true; return; } if (!systemLocale.getLanguage().equals(newLocale.getLanguage())) { - mIsSystemLanguageSameAsInputLanguage = false; + sIsSystemLanguageSameAsInputLanguage = false; return; } // If the subtype is enabled explicitly, the language name should be displayed even when // the keyboard language and the system language are equal. - mIsSystemLanguageSameAsInputLanguage = implicitlyEnabledSubtype; + sIsSystemLanguageSameAsInputLanguage = implicitlyEnabledSubtype; } } diff --git a/java/src/com/android/inputmethod/latin/utils/NetworkConnectivityUtils.java b/java/src/com/android/inputmethod/latin/utils/NetworkConnectivityUtils.java new file mode 100644 index 000000000..101c55067 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/NetworkConnectivityUtils.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; + +import javax.annotation.Nonnull; + +/** + * This class keeps track of the network connectivity state by receiving the system intent + * {@link ConnectivityManager#CONNECTIVITY_ACTION}, and invokes an registered call back to notify + * changes of the network connectivity state. + */ +public final class NetworkConnectivityUtils { + private static NetworkConnectivityReceiver sNetworkConnectivityReceiver; + + public interface NetworkStateChangeListener { + /** + * Called when the network connectivity state has changed. + */ + public void onNetworkStateChanged(); + } + + private static class NetworkConnectivityReceiver extends BroadcastReceiver { + @Nonnull + private final NetworkStateChangeListener mListener; + private boolean mIsNetworkConnected; + + public NetworkConnectivityReceiver(@Nonnull final NetworkStateChangeListener listener, + final boolean isNetworkConnected) { + mListener = listener; + mIsNetworkConnected = isNetworkConnected; + } + + public synchronized boolean isNetworkConnected() { + return mIsNetworkConnected; + } + + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { + final boolean noConnection = intent.getBooleanExtra( + ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); + synchronized (this) { + mIsNetworkConnected = !noConnection; + } + mListener.onNetworkStateChanged(); + } + } + } + + private NetworkConnectivityUtils() { + // This utility class is not publicly instantiable. + } + + public static void onCreate(@Nonnull final Context context, + @Nonnull final NetworkStateChangeListener listener) { + final ConnectivityManager connectivityManager = + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + final NetworkInfo info = connectivityManager.getActiveNetworkInfo(); + final boolean isNetworkConnected = (info != null && info.isConnected()); + + // Register {@link BroadcastReceiver} for the network connectivity state change. + final NetworkConnectivityReceiver receiver = new NetworkConnectivityReceiver( + listener, isNetworkConnected); + final IntentFilter filter = new IntentFilter(); + filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); + context.registerReceiver(receiver, filter); + + sNetworkConnectivityReceiver = receiver; + } + + public static void onDestroy(final Context context) { + context.unregisterReceiver(sNetworkConnectivityReceiver); + } + + public static boolean isNetworkConnected() { + final NetworkConnectivityReceiver receiver = sNetworkConnectivityReceiver; + return receiver != null && receiver.isNetworkConnected(); + } +} |