diff options
Diffstat (limited to 'java/src/com/android/inputmethod')
10 files changed, 506 insertions, 206 deletions
diff --git a/java/src/com/android/inputmethod/compat/LocaleSpanCompatUtils.java b/java/src/com/android/inputmethod/compat/LocaleSpanCompatUtils.java index 967645878..f411f181b 100644 --- a/java/src/com/android/inputmethod/compat/LocaleSpanCompatUtils.java +++ b/java/src/com/android/inputmethod/compat/LocaleSpanCompatUtils.java @@ -16,30 +16,37 @@ package com.android.inputmethod.compat; +import android.text.Spannable; +import android.text.style.LocaleSpan; +import android.util.Log; + import com.android.inputmethod.annotations.UsedForTesting; -import com.android.inputmethod.compat.CompatUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.Locale; @UsedForTesting public final class LocaleSpanCompatUtils { + private static final String TAG = LocaleSpanCompatUtils.class.getSimpleName(); + // Note that LocaleSpan(Locale locale) has been introduced in API level 17 // (Build.VERSION_CODE.JELLY_BEAN_MR1). - private static Class<?> getLocalSpanClass() { + private static Class<?> getLocaleSpanClass() { try { return Class.forName("android.text.style.LocaleSpan"); } catch (ClassNotFoundException e) { return null; } } + private static final Class<?> LOCALE_SPAN_TYPE; private static final Constructor<?> LOCALE_SPAN_CONSTRUCTOR; private static final Method LOCALE_SPAN_GET_LOCALE; static { - final Class<?> localeSpanClass = getLocalSpanClass(); - LOCALE_SPAN_CONSTRUCTOR = CompatUtils.getConstructor(localeSpanClass, Locale.class); - LOCALE_SPAN_GET_LOCALE = CompatUtils.getMethod(localeSpanClass, "getLocale"); + LOCALE_SPAN_TYPE = getLocaleSpanClass(); + LOCALE_SPAN_CONSTRUCTOR = CompatUtils.getConstructor(LOCALE_SPAN_TYPE, Locale.class); + LOCALE_SPAN_GET_LOCALE = CompatUtils.getMethod(LOCALE_SPAN_TYPE, "getLocale"); } @UsedForTesting @@ -56,4 +63,162 @@ public final class LocaleSpanCompatUtils { public static Locale getLocaleFromLocaleSpan(final Object localeSpan) { return (Locale) CompatUtils.invoke(localeSpan, null, LOCALE_SPAN_GET_LOCALE); } + + /** + * Ensures that the specified range is covered with only one {@link LocaleSpan} with the given + * locale. If the region is already covered by one or more {@link LocaleSpan}, their ranges are + * updated so that each character has only one locale. + * @param spannable the spannable object to be updated. + * @param start the start index from which {@link LocaleSpan} is attached (inclusive). + * @param end the end index to which {@link LocaleSpan} is attached (exclusive). + * @param locale the locale to be attached to the specified range. + */ + @UsedForTesting + public static void updateLocaleSpan(final Spannable spannable, final int start, + final int end, final Locale locale) { + if (end < start) { + Log.e(TAG, "Invalid range: start=" + start + " end=" + end); + return; + } + if (!isLocaleSpanAvailable()) { + return; + } + // A brief summary of our strategy; + // 1. Enumerate all LocaleSpans between [start - 1, end + 1]. + // 2. For each LocaleSpan S: + // - Update the range of S so as not to cover [start, end] if S doesn't have the + // expected locale. + // - Mark S as "to be merged" if S has the expected locale. + // 3. Merge all the LocaleSpans that are marked as "to be merged" into one LocaleSpan. + // If no appropriate span is found, create a new one with newLocaleSpan method. + final int searchStart = Math.max(start - 1, 0); + final int searchEnd = Math.min(end + 1, spannable.length()); + // LocaleSpans found in the target range. See the step 1 in the above comment. + final Object[] existingLocaleSpans = spannable.getSpans(searchStart, searchEnd, + LOCALE_SPAN_TYPE); + // LocaleSpans that are marked as "to be merged". See the step 2 in the above comment. + final ArrayList<Object> existingLocaleSpansToBeMerged = new ArrayList<>(); + boolean isStartExclusive = true; + boolean isEndExclusive = true; + int newStart = start; + int newEnd = end; + for (final Object existingLocaleSpan : existingLocaleSpans) { + final Locale attachedLocale = getLocaleFromLocaleSpan(existingLocaleSpan); + if (!locale.equals(attachedLocale)) { + // This LocaleSpan does not have the expected locale. Update its range if it has + // an intersection with the range [start, end] (the first case of the step 2 in the + // above comment). + removeLocaleSpanFromRange(existingLocaleSpan, spannable, start, end); + continue; + } + final int spanStart = spannable.getSpanStart(existingLocaleSpan); + final int spanEnd = spannable.getSpanEnd(existingLocaleSpan); + if (spanEnd < spanStart) { + Log.e(TAG, "Invalid span: spanStart=" + spanStart + " spanEnd=" + spanEnd); + continue; + } + if (spanEnd < start || end < spanStart) { + // No intersection found. + continue; + } + + // Here existingLocaleSpan has the expected locale and an intersection with the + // range [start, end] (the second case of the the step 2 in the above comment). + final int spanFlag = spannable.getSpanFlags(existingLocaleSpan); + if (spanStart < newStart) { + newStart = spanStart; + isStartExclusive = ((spanFlag & Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) == + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + if (newEnd < spanEnd) { + newEnd = spanEnd; + isEndExclusive = ((spanFlag & Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) == + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + existingLocaleSpansToBeMerged.add(existingLocaleSpan); + } + + int originalLocaleSpanFlag = 0; + Object localeSpan = null; + if (existingLocaleSpansToBeMerged.isEmpty()) { + // If there is no LocaleSpan that is marked as to be merged, create a new one. + localeSpan = newLocaleSpan(locale); + } else { + // Reuse the first LocaleSpan to avoid unnecessary object instantiation. + localeSpan = existingLocaleSpansToBeMerged.get(0); + originalLocaleSpanFlag = spannable.getSpanFlags(localeSpan); + // No need to keep other instances. + for (int i = 1; i < existingLocaleSpansToBeMerged.size(); ++i) { + spannable.removeSpan(existingLocaleSpansToBeMerged.get(i)); + } + } + final int localeSpanFlag = getSpanFlag(originalLocaleSpanFlag, isStartExclusive, + isEndExclusive); + spannable.setSpan(localeSpan, newStart, newEnd, localeSpanFlag); + } + + private static void removeLocaleSpanFromRange(final Object localeSpan, + final Spannable spannable, final int removeStart, final int removeEnd) { + if (!isLocaleSpanAvailable()) { + return; + } + final int spanStart = spannable.getSpanStart(localeSpan); + final int spanEnd = spannable.getSpanEnd(localeSpan); + if (spanStart > spanEnd) { + Log.e(TAG, "Invalid span: spanStart=" + spanStart + " spanEnd=" + spanEnd); + return; + } + if (spanEnd < removeStart) { + // spanStart < spanEnd < removeStart < removeEnd + return; + } + if (removeEnd < spanStart) { + // spanStart < removeEnd < spanStart < spanEnd + return; + } + final int spanFlags = spannable.getSpanFlags(localeSpan); + if (spanStart < removeStart) { + if (removeEnd < spanEnd) { + // spanStart < removeStart < removeEnd < spanEnd + final Locale locale = getLocaleFromLocaleSpan(localeSpan); + spannable.setSpan(localeSpan, spanStart, removeStart, spanFlags); + final Object attionalLocaleSpan = newLocaleSpan(locale); + spannable.setSpan(attionalLocaleSpan, removeEnd, spanEnd, spanFlags); + return; + } + // spanStart < removeStart < spanEnd <= removeEnd + spannable.setSpan(localeSpan, spanStart, removeStart, spanFlags); + return; + } + if (removeEnd < spanEnd) { + // removeStart <= spanStart < removeEnd < spanEnd + spannable.setSpan(localeSpan, removeEnd, spanEnd, spanFlags); + return; + } + // removeStart <= spanStart < spanEnd < removeEnd + spannable.removeSpan(localeSpan); + } + + private static int getSpanFlag(final int originalFlag, + final boolean isStartExclusive, final boolean isEndExclusive) { + return (originalFlag & ~Spannable.SPAN_POINT_MARK_MASK) | + getSpanPointMarkFlag(isStartExclusive, isEndExclusive); + } + + private static int getSpanPointMarkFlag(final boolean isStartExclusive, + final boolean isEndExclusive) { + if (isStartExclusive) { + if (isEndExclusive) { + return Spannable.SPAN_EXCLUSIVE_EXCLUSIVE; + } else { + return Spannable.SPAN_EXCLUSIVE_INCLUSIVE; + } + } else { + if (isEndExclusive) { + return Spannable.SPAN_INCLUSIVE_EXCLUSIVE; + } else { + return Spannable.SPAN_INCLUSIVE_INCLUSIVE; + } + } + } } diff --git a/java/src/com/android/inputmethod/keyboard/Key.java b/java/src/com/android/inputmethod/keyboard/Key.java index 88cde1111..ed3b2b347 100644 --- a/java/src/com/android/inputmethod/keyboard/Key.java +++ b/java/src/com/android/inputmethod/keyboard/Key.java @@ -62,8 +62,11 @@ public class Key implements Comparable<Key> { private static final int LABEL_FLAGS_ALIGN_RIGHT = 0x02; private static final int LABEL_FLAGS_ALIGN_BUTTOM = 0x04; private static final int LABEL_FLAGS_ALIGN_LEFT_OF_CENTER = 0x08; + // Font typeface specification. + private static final int LABEL_FLAGS_FONT_MASK = 0x30; private static final int LABEL_FLAGS_FONT_NORMAL = 0x10; private static final int LABEL_FLAGS_FONT_MONO_SPACE = 0x20; + private static final int LABEL_FLAGS_FONT_DEFAULT = 0x30; // Start of key text ratio enum values private static final int LABEL_FLAGS_FOLLOW_KEY_TEXT_RATIO_MASK = 0x1C0; private static final int LABEL_FLAGS_FOLLOW_KEY_LARGE_LETTER_RATIO = 0x40; @@ -567,14 +570,16 @@ public class Key implements Comparable<Key> { } public final Typeface selectTypeface(final KeyDrawParams params) { - // TODO: Handle "bold" here too? - if ((mLabelFlags & LABEL_FLAGS_FONT_NORMAL) != 0) { + switch (mLabelFlags & LABEL_FLAGS_FONT_MASK) { + case LABEL_FLAGS_FONT_NORMAL: return Typeface.DEFAULT; - } - if ((mLabelFlags & LABEL_FLAGS_FONT_MONO_SPACE) != 0) { + case LABEL_FLAGS_FONT_MONO_SPACE: return Typeface.MONOSPACE; + case LABEL_FLAGS_FONT_DEFAULT: + default: + // The type-face is specified by keyTypeface attribute. + return params.mTypeface; } - return params.mTypeface; } public final int selectTextSize(final KeyDrawParams params) { diff --git a/java/src/com/android/inputmethod/latin/RichInputConnection.java b/java/src/com/android/inputmethod/latin/RichInputConnection.java index fdd47a40f..a6b3b710b 100644 --- a/java/src/com/android/inputmethod/latin/RichInputConnection.java +++ b/java/src/com/android/inputmethod/latin/RichInputConnection.java @@ -26,17 +26,16 @@ import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; -import com.android.inputmethod.latin.PrevWordsInfo.WordInfo; import com.android.inputmethod.latin.settings.SpacingAndPunctuations; import com.android.inputmethod.latin.utils.CapsModeUtils; import com.android.inputmethod.latin.utils.DebugLogUtils; +import com.android.inputmethod.latin.utils.PrevWordsInfoUtils; import com.android.inputmethod.latin.utils.ScriptUtils; 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; -import java.util.regex.Pattern; /** * Enrichment class for InputConnection to simplify interaction and add functionality. @@ -55,7 +54,6 @@ public final class RichInputConnection { private static final int LOOKBACK_CHARACTER_NUM = Constants.DICTIONARY_MAX_WORD_LENGTH * (Constants.MAX_PREV_WORD_COUNT_FOR_N_GRAM + 1) /* words */ + Constants.MAX_PREV_WORD_COUNT_FOR_N_GRAM /* separators */; - private static final Pattern spaceRegex = Pattern.compile("\\s+"); private static final int INVALID_CURSOR_POSITION = -1; /** @@ -541,85 +539,14 @@ public final class RichInputConnection { } } } - return getPrevWordsInfoFromNthPreviousWord(prev, spacingAndPunctuations, n); + return PrevWordsInfoUtils.getPrevWordsInfoFromNthPreviousWord( + prev, spacingAndPunctuations, n); } private static boolean isSeparator(final int code, final int[] sortedSeparators) { return Arrays.binarySearch(sortedSeparators, code) >= 0; } - // Get context information from nth word before the cursor. n = 1 retrieves the words - // immediately before the cursor, n = 2 retrieves the words before that, and so on. This splits - // on whitespace only. - // Also, it won't return words that end in a separator (if the nth word before the cursor - // ends in a separator, it returns information representing beginning-of-sentence). - // Example (when Constants.MAX_PREV_WORD_COUNT_FOR_N_GRAM is 2): - // (n = 1) "abc def|" -> abc, def - // (n = 1) "abc def |" -> abc, def - // (n = 1) "abc 'def|" -> empty, 'def - // (n = 1) "abc def. |" -> beginning-of-sentence - // (n = 1) "abc def . |" -> beginning-of-sentence - // (n = 2) "abc def|" -> beginning-of-sentence, abc - // (n = 2) "abc def |" -> beginning-of-sentence, abc - // (n = 2) "abc 'def|" -> empty. The context is different from "abc def", but we cannot - // represent this situation using PrevWordsInfo. See TODO in the method. - // TODO: The next example's result should be "abc, def". This have to be fixed before we - // retrieve the prior context of Beginning-of-Sentence. - // (n = 2) "abc def. |" -> beginning-of-sentence, abc - // (n = 2) "abc def . |" -> abc, def - // (n = 2) "abc|" -> beginning-of-sentence - // (n = 2) "abc |" -> beginning-of-sentence - // (n = 2) "abc. def|" -> beginning-of-sentence - public static PrevWordsInfo getPrevWordsInfoFromNthPreviousWord(final CharSequence prev, - final SpacingAndPunctuations spacingAndPunctuations, final int n) { - if (prev == null) return PrevWordsInfo.EMPTY_PREV_WORDS_INFO; - final String[] w = spaceRegex.split(prev); - final WordInfo[] prevWordsInfo = new WordInfo[Constants.MAX_PREV_WORD_COUNT_FOR_N_GRAM]; - for (int i = 0; i < prevWordsInfo.length; i++) { - final int focusedWordIndex = w.length - n - i; - // Referring to the word after the focused word. - if ((focusedWordIndex + 1) >= 0 && (focusedWordIndex + 1) < w.length) { - final String wordFollowingTheNthPrevWord = w[focusedWordIndex + 1]; - if (!wordFollowingTheNthPrevWord.isEmpty()) { - final char firstChar = wordFollowingTheNthPrevWord.charAt(0); - if (spacingAndPunctuations.isWordConnector(firstChar)) { - // The word following the focused word is starting with a word connector. - // TODO: Return meaningful context for this case. - prevWordsInfo[i] = WordInfo.EMPTY_WORD_INFO; - break; - } - } - } - // If we can't find (n + i) words, the context is beginning-of-sentence. - if (focusedWordIndex < 0) { - prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE; - break; - } - final String focusedWord = w[focusedWordIndex]; - // If the word is empty, the context is beginning-of-sentence. - final int length = focusedWord.length(); - if (length <= 0) { - prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE; - 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; - break; - } - // If ends in a word separator or connector, the context is unclear. - // TODO: Return meaningful context for this case. - if (spacingAndPunctuations.isWordSeparator(lastChar) - || spacingAndPunctuations.isWordConnector(lastChar)) { - prevWordsInfo[i] = WordInfo.EMPTY_WORD_INFO; - break; - } - prevWordsInfo[i] = new WordInfo(focusedWord); - } - return new PrevWordsInfo(prevWordsInfo); - } - /** * Returns the text surrounding the cursor. * diff --git a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java index 7758ac78e..7cf4eff92 100644 --- a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java +++ b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java @@ -64,8 +64,7 @@ public final class RichInputMethodManager { } public static void init(final Context context) { - final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - sInstance.initInternal(context, prefs); + sInstance.initInternal(context); } private boolean isInitialized() { @@ -78,7 +77,7 @@ public final class RichInputMethodManager { } } - private void initInternal(final Context context, final SharedPreferences prefs) { + private void initInternal(final Context context) { if (isInitialized()) { return; } @@ -88,11 +87,16 @@ public final class RichInputMethodManager { // Initialize additional subtypes. SubtypeLocaleUtils.init(context); + final InputMethodSubtype[] additionalSubtypes = getAdditionalSubtypes(context); + setAdditionalInputMethodSubtypes(additionalSubtypes); + } + + public InputMethodSubtype[] getAdditionalSubtypes(final Context context) { + SubtypeLocaleUtils.init(context); + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final String prefAdditionalSubtypes = Settings.readPrefAdditionalSubtypes( prefs, context.getResources()); - final InputMethodSubtype[] additionalSubtypes = - AdditionalSubtypeUtils.createAdditionalSubtypesArray(prefAdditionalSubtypes); - setAdditionalInputMethodSubtypes(additionalSubtypes); + return AdditionalSubtypeUtils.createAdditionalSubtypesArray(prefAdditionalSubtypes); } public InputMethodManager getInputMethodManager() { diff --git a/java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java b/java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java new file mode 100644 index 000000000..e4ee42660 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java @@ -0,0 +1,104 @@ +/* + * 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; + +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.os.Process; +import android.preference.PreferenceManager; +import android.util.Log; +import android.view.inputmethod.InputMethodManager; +import android.view.inputmethod.InputMethodSubtype; + +import com.android.inputmethod.compat.IntentCompatUtils; +import com.android.inputmethod.latin.settings.Settings; +import com.android.inputmethod.latin.setup.LauncherIconVisibilityManager; +import com.android.inputmethod.latin.setup.SetupActivity; +import com.android.inputmethod.latin.utils.UncachedInputMethodManagerUtils; + +/** + * This class detects the {@link Intent#ACTION_MY_PACKAGE_REPLACED} broadcast intent when this IME + * package has been replaced by a newer version of the same package. This class also detects + * {@link Intent#ACTION_BOOT_COMPLETED} and {@link Intent#ACTION_USER_INITIALIZE} broadcast intent. + * + * If this IME has already been installed in the system image and a new version of this IME has + * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is received by this receiver and it + * will hide the setup wizard's icon. + * + * If this IME has already been installed in the data partition and a new version of this IME has + * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is received by this receiver but it + * will not hide the setup wizard's icon, and the icon will appear on the launcher. + * + * If this IME hasn't been installed yet and has been newly installed, no + * {@link Intent#ACTION_MY_PACKAGE_REPLACED} will be sent and the setup wizard's icon will appear + * on the launcher. + * + * When the device has been booted, {@link Intent#ACTION_BOOT_COMPLETED} is received by this + * receiver and it checks whether the setup wizard's icon should be appeared or not on the launcher + * depending on which partition this IME is installed. + * + * When a multiuser account has been created, {@link Intent#ACTION_USER_INITIALIZE} is received + * by this receiver and it checks the whether the setup wizard's icon should be appeared or not on + * the launcher depending on which partition this IME is installed. + */ +public final class SystemBroadcastReceiver extends BroadcastReceiver { + private static final String TAG = SystemBroadcastReceiver.class.getSimpleName(); + + @Override + public void onReceive(final Context context, final Intent intent) { + final String intentAction = intent.getAction(); + if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(intentAction)) { + Log.i(TAG, "Package has been replaced: " + context.getPackageName()); + } else if (Intent.ACTION_BOOT_COMPLETED.equals(intentAction)) { + Log.i(TAG, "Boot has been completed"); + } else if (IntentCompatUtils.is_ACTION_USER_INITIALIZE(intentAction)) { + Log.i(TAG, "User initialize"); + } + + LauncherIconVisibilityManager.onReceiveGlobalIntent(intentAction, context); + + if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(intentAction)) { + // Need to restore additional subtypes because system always clears additional + // subtypes when the package is replaced. + RichInputMethodManager.init(context); + final RichInputMethodManager richImm = RichInputMethodManager.getInstance(); + final InputMethodSubtype[] additionalSubtypes = richImm.getAdditionalSubtypes(context); + richImm.setAdditionalInputMethodSubtypes(additionalSubtypes); + } + + // The process that hosts this broadcast receiver is invoked and remains alive even after + // 1) the package has been re-installed, 2) the device has just booted, + // 3) a new user has been created. + // There is no good reason to keep the process alive if this IME isn't a current IME. + final InputMethodManager imm = + (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); + // Called to check whether this IME has been triggered by the current user or not + final boolean isInputMethodManagerValidForUserOfThisProcess = + !imm.getInputMethodList().isEmpty(); + final boolean isCurrentImeOfCurrentUser = isInputMethodManagerValidForUserOfThisProcess + && UncachedInputMethodManagerUtils.isThisImeCurrent(context, imm); + if (!isCurrentImeOfCurrentUser) { + final int myPid = Process.myPid(); + Log.i(TAG, "Killing my process: pid=" + myPid); + Process.killProcess(myPid); + } + } +} diff --git a/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java b/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java index 050d8d26f..9585736e7 100644 --- a/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java +++ b/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java @@ -16,85 +16,51 @@ package com.android.inputmethod.latin.setup; -import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; -import android.os.Process; import android.preference.PreferenceManager; import android.util.Log; -import android.view.inputmethod.InputMethodManager; import com.android.inputmethod.compat.IntentCompatUtils; import com.android.inputmethod.latin.settings.Settings; /** - * This class detects the {@link Intent#ACTION_MY_PACKAGE_REPLACED} broadcast intent when this IME - * package has been replaced by a newer version of the same package. This class also detects + * This class handles the {@link Intent#ACTION_MY_PACKAGE_REPLACED} broadcast intent when this IME + * package has been replaced by a newer version of the same package. This class also handles * {@link Intent#ACTION_BOOT_COMPLETED} and {@link Intent#ACTION_USER_INITIALIZE} broadcast intent. * * If this IME has already been installed in the system image and a new version of this IME has - * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is received by this receiver and it - * will hide the setup wizard's icon. + * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is received to this class to hide the + * setup wizard's icon. * * If this IME has already been installed in the data partition and a new version of this IME has - * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is received by this receiver but it + * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is forwarded to this class but it * will not hide the setup wizard's icon, and the icon will appear on the launcher. * * If this IME hasn't been installed yet and has been newly installed, no * {@link Intent#ACTION_MY_PACKAGE_REPLACED} will be sent and the setup wizard's icon will appear * on the launcher. * - * When the device has been booted, {@link Intent#ACTION_BOOT_COMPLETED} is received by this - * receiver and it checks whether the setup wizard's icon should be appeared or not on the launcher + * When the device has been booted, {@link Intent#ACTION_BOOT_COMPLETED} is forwarded to this class + * to check whether the setup wizard's icon should be appeared or not on the launcher * depending on which partition this IME is installed. * - * When a multiuser account has been created, {@link Intent#ACTION_USER_INITIALIZE} is received - * by this receiver and it checks the whether the setup wizard's icon should be appeared or not on - * the launcher depending on which partition this IME is installed. + * When a multiuser account has been created, {@link Intent#ACTION_USER_INITIALIZE} is forwarded to + * this class to check whether the setup wizard's icon should be appeared or not on the launcher + * depending on which partition this IME is installed. */ -public final class LauncherIconVisibilityManager extends BroadcastReceiver { +public final class LauncherIconVisibilityManager { private static final String TAG = LauncherIconVisibilityManager.class.getSimpleName(); - @Override - public void onReceive(final Context context, final Intent intent) { - if (shouldHandleThisIntent(intent, context)) { + public static void onReceiveGlobalIntent(final String action, final Context context) { + if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(action) || + Intent.ACTION_BOOT_COMPLETED.equals(action) || + IntentCompatUtils.is_ACTION_USER_INITIALIZE(action)) { updateSetupWizardIconVisibility(context); } - - // The process that hosts this broadcast receiver is invoked and remains alive even after - // 1) the package has been re-installed, 2) the device has just booted, - // 3) a new user has been created. - // There is no good reason to keep the process alive if this IME isn't a current IME. - final InputMethodManager imm = - (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); - // Called to check whether this IME has been triggered by the current user or not - final boolean isInputMethodManagerValidForUserOfThisProcess = - !imm.getInputMethodList().isEmpty(); - final boolean isCurrentImeOfCurrentUser = isInputMethodManagerValidForUserOfThisProcess - && SetupActivity.isThisImeCurrent(context, imm); - if (!isCurrentImeOfCurrentUser) { - final int myPid = Process.myPid(); - Log.i(TAG, "Killing my process: pid=" + myPid); - Process.killProcess(myPid); - } - } - - private static boolean shouldHandleThisIntent(final Intent intent, final Context context) { - final String action = intent.getAction(); - if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(action)) { - Log.i(TAG, "Package has been replaced: " + context.getPackageName()); - return true; - } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { - Log.i(TAG, "Boot has been completed"); - return true; - } else if (IntentCompatUtils.is_ACTION_USER_INITIALIZE(action)) { - Log.i(TAG, "User initialize"); - return true; - } - return false; } public static void updateSetupWizardIconVisibility(final Context context) { diff --git a/java/src/com/android/inputmethod/latin/setup/SetupActivity.java b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java index a68f98fe7..b770ea512 100644 --- a/java/src/com/android/inputmethod/latin/setup/SetupActivity.java +++ b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java @@ -37,65 +37,4 @@ public final class SetupActivity extends Activity { finish(); } } - - /* - * We may not be able to get our own {@link InputMethodInfo} just after this IME is installed - * because {@link InputMethodManagerService} may not be aware of this IME yet. - * Note: {@link RichInputMethodManager} has similar methods. Here in setup wizard, we can't - * use it for the reason above. - */ - - /** - * Check if the IME specified by the context is enabled. - * CAVEAT: This may cause a round trip IPC. - * - * @param context package context of the IME to be checked. - * @param imm the {@link InputMethodManager}. - * @return true if this IME is enabled. - */ - /* package */ static boolean isThisImeEnabled(final Context context, - final InputMethodManager imm) { - final String packageName = context.getPackageName(); - for (final InputMethodInfo imi : imm.getEnabledInputMethodList()) { - if (packageName.equals(imi.getPackageName())) { - return true; - } - } - return false; - } - - /** - * Check if the IME specified by the context is the current IME. - * CAVEAT: This may cause a round trip IPC. - * - * @param context package context of the IME to be checked. - * @param imm the {@link InputMethodManager}. - * @return true if this IME is the current IME. - */ - /* package */ static boolean isThisImeCurrent(final Context context, - final InputMethodManager imm) { - final InputMethodInfo imi = getInputMethodInfoOf(context.getPackageName(), imm); - final String currentImeId = Settings.Secure.getString( - context.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD); - return imi != null && imi.getId().equals(currentImeId); - } - - /** - * Get {@link InputMethodInfo} of the IME specified by the package name. - * CAVEAT: This may cause a round trip IPC. - * - * @param packageName package name of the IME. - * @param imm the {@link InputMethodManager}. - * @return the {@link InputMethodInfo} of the IME specified by the <code>packageName</code>, - * or null if not found. - */ - /* package */ static InputMethodInfo getInputMethodInfoOf(final String packageName, - final InputMethodManager imm) { - for (final InputMethodInfo imi : imm.getInputMethodList()) { - if (packageName.equals(imi.getPackageName())) { - return imi; - } - } - return null; - } } diff --git a/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java b/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java index bcac05a6a..e455e53d3 100644 --- a/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java +++ b/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java @@ -38,6 +38,7 @@ import com.android.inputmethod.compat.ViewCompatUtils; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.settings.SettingsActivity; import com.android.inputmethod.latin.utils.LeakGuardHandlerWrapper; +import com.android.inputmethod.latin.utils.UncachedInputMethodManagerUtils; import java.util.ArrayList; @@ -93,7 +94,8 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL } switch (msg.what) { case MSG_POLLING_IME_SETTINGS: - if (SetupActivity.isThisImeEnabled(setupWizardActivity, mImmInHandler)) { + if (UncachedInputMethodManagerUtils.isThisImeEnabled(setupWizardActivity, + mImmInHandler)) { setupWizardActivity.invokeSetupWizardOfThisIme(); return; } @@ -277,7 +279,8 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL } void invokeSubtypeEnablerOfThisIme() { - final InputMethodInfo imi = SetupActivity.getInputMethodInfoOf(getPackageName(), mImm); + final InputMethodInfo imi = + UncachedInputMethodManagerUtils.getInputMethodInfoOf(getPackageName(), mImm); if (imi == null) { return; } @@ -301,10 +304,10 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL private int determineSetupStepNumber() { mHandler.cancelPollingImeSettings(); - if (!SetupActivity.isThisImeEnabled(this, mImm)) { + if (!UncachedInputMethodManagerUtils.isThisImeEnabled(this, mImm)) { return STEP_1; } - if (!SetupActivity.isThisImeCurrent(this, mImm)) { + if (!UncachedInputMethodManagerUtils.isThisImeCurrent(this, mImm)) { return STEP_2; } return STEP_3; diff --git a/java/src/com/android/inputmethod/latin/utils/PrevWordsInfoUtils.java b/java/src/com/android/inputmethod/latin/utils/PrevWordsInfoUtils.java new file mode 100644 index 000000000..3cd63612c --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/PrevWordsInfoUtils.java @@ -0,0 +1,103 @@ +/* + * 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 java.util.regex.Pattern; + +import com.android.inputmethod.latin.Constants; +import com.android.inputmethod.latin.PrevWordsInfo; +import com.android.inputmethod.latin.PrevWordsInfo.WordInfo; +import com.android.inputmethod.latin.settings.SpacingAndPunctuations; + +public final class PrevWordsInfoUtils { + private PrevWordsInfoUtils() { + // Intentional empty constructor for utility class. + } + + private static final Pattern SPACE_REGEX = Pattern.compile("\\s+"); + // Get context information from nth word before the cursor. n = 1 retrieves the words + // immediately before the cursor, n = 2 retrieves the words before that, and so on. This splits + // on whitespace only. + // Also, it won't return words that end in a separator (if the nth word before the cursor + // ends in a separator, it returns information representing beginning-of-sentence). + // Example (when Constants.MAX_PREV_WORD_COUNT_FOR_N_GRAM is 2): + // (n = 1) "abc def|" -> abc, def + // (n = 1) "abc def |" -> abc, def + // (n = 1) "abc 'def|" -> empty, 'def + // (n = 1) "abc def. |" -> beginning-of-sentence + // (n = 1) "abc def . |" -> beginning-of-sentence + // (n = 2) "abc def|" -> beginning-of-sentence, abc + // (n = 2) "abc def |" -> beginning-of-sentence, abc + // (n = 2) "abc 'def|" -> empty. The context is different from "abc def", but we cannot + // represent this situation using PrevWordsInfo. See TODO in the method. + // TODO: The next example's result should be "abc, def". This have to be fixed before we + // retrieve the prior context of Beginning-of-Sentence. + // (n = 2) "abc def. |" -> beginning-of-sentence, abc + // (n = 2) "abc def . |" -> abc, def + // (n = 2) "abc|" -> beginning-of-sentence + // (n = 2) "abc |" -> beginning-of-sentence + // (n = 2) "abc. def|" -> beginning-of-sentence + public static PrevWordsInfo getPrevWordsInfoFromNthPreviousWord(final CharSequence prev, + final SpacingAndPunctuations spacingAndPunctuations, final int n) { + if (prev == null) return PrevWordsInfo.EMPTY_PREV_WORDS_INFO; + final String[] w = SPACE_REGEX.split(prev); + final WordInfo[] prevWordsInfo = new WordInfo[Constants.MAX_PREV_WORD_COUNT_FOR_N_GRAM]; + for (int i = 0; i < prevWordsInfo.length; i++) { + final int focusedWordIndex = w.length - n - i; + // Referring to the word after the focused word. + if ((focusedWordIndex + 1) >= 0 && (focusedWordIndex + 1) < w.length) { + final String wordFollowingTheNthPrevWord = w[focusedWordIndex + 1]; + if (!wordFollowingTheNthPrevWord.isEmpty()) { + final char firstChar = wordFollowingTheNthPrevWord.charAt(0); + if (spacingAndPunctuations.isWordConnector(firstChar)) { + // The word following the focused word is starting with a word connector. + // TODO: Return meaningful context for this case. + prevWordsInfo[i] = WordInfo.EMPTY_WORD_INFO; + break; + } + } + } + // If we can't find (n + i) words, the context is beginning-of-sentence. + if (focusedWordIndex < 0) { + prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE; + 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; + 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; + break; + } + // If ends in a word separator or connector, the context is unclear. + // TODO: Return meaningful context for this case. + if (spacingAndPunctuations.isWordSeparator(lastChar) + || spacingAndPunctuations.isWordConnector(lastChar)) { + prevWordsInfo[i] = WordInfo.EMPTY_WORD_INFO; + break; + } + prevWordsInfo[i] = new WordInfo(focusedWord); + } + return new PrevWordsInfo(prevWordsInfo); + } +} diff --git a/java/src/com/android/inputmethod/latin/utils/UncachedInputMethodManagerUtils.java b/java/src/com/android/inputmethod/latin/utils/UncachedInputMethodManagerUtils.java new file mode 100644 index 000000000..5df00efb9 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/UncachedInputMethodManagerUtils.java @@ -0,0 +1,84 @@ +/* + * 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.Context; +import android.provider.Settings; +import android.view.inputmethod.InputMethodInfo; +import android.view.inputmethod.InputMethodManager; + +/* + * A utility class for {@link InputMethodManager}. Unlike {@link RichInputMethodManager}, this + * class provides synchronous, non-cached access to {@link InputMethodManager}. The setup activity + * is a good example to use this class because {@link InputMethodManagerService} may not be aware of + * this IME immediately after this IME is installed. + */ +public final class UncachedInputMethodManagerUtils { + /** + * Check if the IME specified by the context is enabled. + * CAVEAT: This may cause a round trip IPC. + * + * @param context package context of the IME to be checked. + * @param imm the {@link InputMethodManager}. + * @return true if this IME is enabled. + */ + public static boolean isThisImeEnabled(final Context context, + final InputMethodManager imm) { + final String packageName = context.getPackageName(); + for (final InputMethodInfo imi : imm.getEnabledInputMethodList()) { + if (packageName.equals(imi.getPackageName())) { + return true; + } + } + return false; + } + + /** + * Check if the IME specified by the context is the current IME. + * CAVEAT: This may cause a round trip IPC. + * + * @param context package context of the IME to be checked. + * @param imm the {@link InputMethodManager}. + * @return true if this IME is the current IME. + */ + public static boolean isThisImeCurrent(final Context context, + final InputMethodManager imm) { + final InputMethodInfo imi = getInputMethodInfoOf(context.getPackageName(), imm); + final String currentImeId = Settings.Secure.getString( + context.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD); + return imi != null && imi.getId().equals(currentImeId); + } + + /** + * Get {@link InputMethodInfo} of the IME specified by the package name. + * CAVEAT: This may cause a round trip IPC. + * + * @param packageName package name of the IME. + * @param imm the {@link InputMethodManager}. + * @return the {@link InputMethodInfo} of the IME specified by the <code>packageName</code>, + * or null if not found. + */ + public static InputMethodInfo getInputMethodInfoOf(final String packageName, + final InputMethodManager imm) { + for (final InputMethodInfo imi : imm.getInputMethodList()) { + if (packageName.equals(imi.getPackageName())) { + return imi; + } + } + return null; + } +} |