aboutsummaryrefslogtreecommitdiffstats
path: root/java/src/org/kelar/inputmethod/latin/utils
diff options
context:
space:
mode:
Diffstat (limited to 'java/src/org/kelar/inputmethod/latin/utils')
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/AdditionalSubtypeUtils.java238
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/ApplicationUtils.java83
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/AsyncResultHolder.java72
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/AutoCorrectionUtils.java62
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/BinaryDictionaryUtils.java128
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/CapsModeUtils.java357
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/CombinedFormatUtils.java109
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/CompletionInfoUtils.java43
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/CursorAnchorInfoUtils.java264
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/DebugLogUtils.java115
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/DialogUtils.java34
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/DictionaryHeaderUtils.java31
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/DictionaryInfoUtils.java613
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/ExecutorUtils.java152
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/FeedbackUtils.java38
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/FileTransforms.java38
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/FragmentUtils.java64
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/ImportantNoticeUtils.java140
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/InputTypeUtils.java117
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/IntentUtils.java45
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/JniUtils.java41
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/JsonUtils.java103
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/LanguageOnSpacebarUtils.java92
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/LeakGuardHandlerWrapper.java43
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/ManagedProfileUtils.java43
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/MetadataFileUriGetter.java39
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/NgramContextUtils.java113
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/RecapitalizeStatus.java221
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/ResourceUtils.java319
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/RunInLocale.java53
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/ScriptUtils.java195
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/SpannableStringUtils.java183
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/StatsUtils.java108
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/StatsUtilsManager.java56
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/SubtypeLocaleUtils.java351
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/SuggestionResults.java89
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/TargetPackageInfoGetterTask.java67
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/TextRange.java122
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/TypefaceUtils.java108
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/UncachedInputMethodManagerUtils.java84
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/ViewLayoutUtils.java93
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/WordInputEventForPersonalization.java106
-rw-r--r--java/src/org/kelar/inputmethod/latin/utils/XmlParseUtils.java83
43 files changed, 5455 insertions, 0 deletions
diff --git a/java/src/org/kelar/inputmethod/latin/utils/AdditionalSubtypeUtils.java b/java/src/org/kelar/inputmethod/latin/utils/AdditionalSubtypeUtils.java
new file mode 100644
index 000000000..2b44fcd91
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/AdditionalSubtypeUtils.java
@@ -0,0 +1,238 @@
+/*
+ * Copyright (C) 2012 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 org.kelar.inputmethod.latin.utils;
+
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.KEYBOARD_MODE;
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.ASCII_CAPABLE;
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.EMOJI_CAPABLE;
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.IS_ADDITIONAL_SUBTYPE;
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.KEYBOARD_LAYOUT_SET;
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME;
+
+import android.os.Build;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.inputmethod.InputMethodSubtype;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+import org.kelar.inputmethod.compat.InputMethodSubtypeCompatUtils;
+import org.kelar.inputmethod.latin.R;
+import org.kelar.inputmethod.latin.common.StringUtils;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+public final class AdditionalSubtypeUtils {
+ private static final String TAG = AdditionalSubtypeUtils.class.getSimpleName();
+
+ private static final InputMethodSubtype[] EMPTY_SUBTYPE_ARRAY = new InputMethodSubtype[0];
+
+ private AdditionalSubtypeUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ @UsedForTesting
+ public static boolean isAdditionalSubtype(final InputMethodSubtype subtype) {
+ return subtype.containsExtraValueKey(IS_ADDITIONAL_SUBTYPE);
+ }
+
+ private static final String LOCALE_AND_LAYOUT_SEPARATOR = ":";
+ private static final int INDEX_OF_LOCALE = 0;
+ private static final int INDEX_OF_KEYBOARD_LAYOUT = 1;
+ private static final int INDEX_OF_EXTRA_VALUE = 2;
+ private static final int LENGTH_WITHOUT_EXTRA_VALUE = (INDEX_OF_KEYBOARD_LAYOUT + 1);
+ private static final int LENGTH_WITH_EXTRA_VALUE = (INDEX_OF_EXTRA_VALUE + 1);
+ private static final String PREF_SUBTYPE_SEPARATOR = ";";
+
+ private static InputMethodSubtype createAdditionalSubtypeInternal(
+ final String localeString, final String keyboardLayoutSetName,
+ final boolean isAsciiCapable, final boolean isEmojiCapable) {
+ final int nameId = SubtypeLocaleUtils.getSubtypeNameId(localeString, keyboardLayoutSetName);
+ final String platformVersionDependentExtraValues = getPlatformVersionDependentExtraValue(
+ localeString, keyboardLayoutSetName, isAsciiCapable, isEmojiCapable);
+ final int platformVersionIndependentSubtypeId =
+ getPlatformVersionIndependentSubtypeId(localeString, keyboardLayoutSetName);
+ // NOTE: In KitKat and later, InputMethodSubtypeBuilder#setIsAsciiCapable is also available.
+ // TODO: Use InputMethodSubtypeBuilder#setIsAsciiCapable when appropriate.
+ return InputMethodSubtypeCompatUtils.newInputMethodSubtype(nameId,
+ R.drawable.ic_ime_switcher_dark, localeString, KEYBOARD_MODE,
+ platformVersionDependentExtraValues,
+ false /* isAuxiliary */, false /* overrideImplicitlyEnabledSubtype */,
+ platformVersionIndependentSubtypeId);
+ }
+
+ public static InputMethodSubtype createDummyAdditionalSubtype(
+ final String localeString, final String keyboardLayoutSetName) {
+ return createAdditionalSubtypeInternal(localeString, keyboardLayoutSetName,
+ false /* isAsciiCapable */, false /* isEmojiCapable */);
+ }
+
+ public static InputMethodSubtype createAsciiEmojiCapableAdditionalSubtype(
+ final String localeString, final String keyboardLayoutSetName) {
+ return createAdditionalSubtypeInternal(localeString, keyboardLayoutSetName,
+ true /* isAsciiCapable */, true /* isEmojiCapable */);
+ }
+
+ public static String getPrefSubtype(final InputMethodSubtype subtype) {
+ final String localeString = subtype.getLocale();
+ final String keyboardLayoutSetName = SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype);
+ final String layoutExtraValue = KEYBOARD_LAYOUT_SET + "=" + keyboardLayoutSetName;
+ final String extraValue = StringUtils.removeFromCommaSplittableTextIfExists(
+ layoutExtraValue, StringUtils.removeFromCommaSplittableTextIfExists(
+ IS_ADDITIONAL_SUBTYPE, subtype.getExtraValue()));
+ final String basePrefSubtype = localeString + LOCALE_AND_LAYOUT_SEPARATOR
+ + keyboardLayoutSetName;
+ return extraValue.isEmpty() ? basePrefSubtype
+ : basePrefSubtype + LOCALE_AND_LAYOUT_SEPARATOR + extraValue;
+ }
+
+ public static InputMethodSubtype[] createAdditionalSubtypesArray(final String prefSubtypes) {
+ if (TextUtils.isEmpty(prefSubtypes)) {
+ return EMPTY_SUBTYPE_ARRAY;
+ }
+ final String[] prefSubtypeArray = prefSubtypes.split(PREF_SUBTYPE_SEPARATOR);
+ final ArrayList<InputMethodSubtype> subtypesList = new ArrayList<>(prefSubtypeArray.length);
+ for (final String prefSubtype : prefSubtypeArray) {
+ final String elems[] = prefSubtype.split(LOCALE_AND_LAYOUT_SEPARATOR);
+ if (elems.length != LENGTH_WITHOUT_EXTRA_VALUE
+ && elems.length != LENGTH_WITH_EXTRA_VALUE) {
+ Log.w(TAG, "Unknown additional subtype specified: " + prefSubtype + " in "
+ + prefSubtypes);
+ continue;
+ }
+ final String localeString = elems[INDEX_OF_LOCALE];
+ final String keyboardLayoutSetName = elems[INDEX_OF_KEYBOARD_LAYOUT];
+ // Here we assume that all the additional subtypes have AsciiCapable and EmojiCapable.
+ // This is actually what the setting dialog for additional subtype is doing.
+ final InputMethodSubtype subtype = createAsciiEmojiCapableAdditionalSubtype(
+ localeString, keyboardLayoutSetName);
+ if (subtype.getNameResId() == SubtypeLocaleUtils.UNKNOWN_KEYBOARD_LAYOUT) {
+ // Skip unknown keyboard layout subtype. This may happen when predefined keyboard
+ // layout has been removed.
+ continue;
+ }
+ subtypesList.add(subtype);
+ }
+ return subtypesList.toArray(new InputMethodSubtype[subtypesList.size()]);
+ }
+
+ public static String createPrefSubtypes(final InputMethodSubtype[] subtypes) {
+ if (subtypes == null || subtypes.length == 0) {
+ return "";
+ }
+ final StringBuilder sb = new StringBuilder();
+ for (final InputMethodSubtype subtype : subtypes) {
+ if (sb.length() > 0) {
+ sb.append(PREF_SUBTYPE_SEPARATOR);
+ }
+ sb.append(getPrefSubtype(subtype));
+ }
+ return sb.toString();
+ }
+
+ public static String createPrefSubtypes(final String[] prefSubtypes) {
+ if (prefSubtypes == null || prefSubtypes.length == 0) {
+ return "";
+ }
+ final StringBuilder sb = new StringBuilder();
+ for (final String prefSubtype : prefSubtypes) {
+ if (sb.length() > 0) {
+ sb.append(PREF_SUBTYPE_SEPARATOR);
+ }
+ sb.append(prefSubtype);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Returns the extra value that is optimized for the running OS.
+ * <p>
+ * Historically the extra value has been used as the last resort to annotate various kinds of
+ * attributes. Some of these attributes are valid only on some platform versions. Thus we cannot
+ * assume that the extra values stored in a persistent storage are always valid. We need to
+ * regenerate the extra value on the fly instead.
+ * </p>
+ * @param localeString the locale string (e.g., "en_US").
+ * @param keyboardLayoutSetName the keyboard layout set name (e.g., "dvorak").
+ * @param isAsciiCapable true when ASCII characters are supported with this layout.
+ * @param isEmojiCapable true when Unicode Emoji characters are supported with this layout.
+ * @return extra value that is optimized for the running OS.
+ * @see #getPlatformVersionIndependentSubtypeId(String, String)
+ */
+ private static String getPlatformVersionDependentExtraValue(final String localeString,
+ final String keyboardLayoutSetName, final boolean isAsciiCapable,
+ final boolean isEmojiCapable) {
+ final ArrayList<String> extraValueItems = new ArrayList<>();
+ extraValueItems.add(KEYBOARD_LAYOUT_SET + "=" + keyboardLayoutSetName);
+ if (isAsciiCapable) {
+ extraValueItems.add(ASCII_CAPABLE);
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
+ SubtypeLocaleUtils.isExceptionalLocale(localeString)) {
+ extraValueItems.add(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME + "=" +
+ SubtypeLocaleUtils.getKeyboardLayoutSetDisplayName(keyboardLayoutSetName));
+ }
+ if (isEmojiCapable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ extraValueItems.add(EMOJI_CAPABLE);
+ }
+ extraValueItems.add(IS_ADDITIONAL_SUBTYPE);
+ return TextUtils.join(",", extraValueItems);
+ }
+
+ /**
+ * Returns the subtype ID that is supposed to be compatible between different version of OSes.
+ * <p>
+ * From the compatibility point of view, it is important to keep subtype id predictable and
+ * stable between different OSes. For this purpose, the calculation code in this method is
+ * carefully chosen and then fixed. Treat the following code as no more or less than a
+ * hash function. Each component to be hashed can be different from the corresponding value
+ * that is used to instantiate {@link InputMethodSubtype} actually.
+ * For example, you don't need to update <code>compatibilityExtraValueItems</code> in this
+ * method even when we need to add some new extra values for the actual instance of
+ * {@link InputMethodSubtype}.
+ * </p>
+ * @param localeString the locale string (e.g., "en_US").
+ * @param keyboardLayoutSetName the keyboard layout set name (e.g., "dvorak").
+ * @return a platform-version independent subtype ID.
+ * @see #getPlatformVersionDependentExtraValue(String, String, boolean, boolean)
+ */
+ private static int getPlatformVersionIndependentSubtypeId(final String localeString,
+ final String keyboardLayoutSetName) {
+ // For compatibility reasons, we concatenate the extra values in the following order.
+ // - KeyboardLayoutSet
+ // - AsciiCapable
+ // - UntranslatableReplacementStringInSubtypeName
+ // - EmojiCapable
+ // - isAdditionalSubtype
+ final ArrayList<String> compatibilityExtraValueItems = new ArrayList<>();
+ compatibilityExtraValueItems.add(KEYBOARD_LAYOUT_SET + "=" + keyboardLayoutSetName);
+ compatibilityExtraValueItems.add(ASCII_CAPABLE);
+ if (SubtypeLocaleUtils.isExceptionalLocale(localeString)) {
+ compatibilityExtraValueItems.add(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME + "=" +
+ SubtypeLocaleUtils.getKeyboardLayoutSetDisplayName(keyboardLayoutSetName));
+ }
+ compatibilityExtraValueItems.add(EMOJI_CAPABLE);
+ compatibilityExtraValueItems.add(IS_ADDITIONAL_SUBTYPE);
+ final String compatibilityExtraValues = TextUtils.join(",", compatibilityExtraValueItems);
+ return Arrays.hashCode(new Object[] {
+ localeString,
+ KEYBOARD_MODE,
+ compatibilityExtraValues,
+ false /* isAuxiliary */,
+ false /* overrideImplicitlyEnabledSubtype */ });
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/ApplicationUtils.java b/java/src/org/kelar/inputmethod/latin/utils/ApplicationUtils.java
new file mode 100644
index 000000000..13d5f2a00
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/ApplicationUtils.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.util.Log;
+
+public final class ApplicationUtils {
+ private static final String TAG = ApplicationUtils.class.getSimpleName();
+
+ private ApplicationUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static int getActivityTitleResId(final Context context,
+ final Class<? extends Activity> cls) {
+ final ComponentName cn = new ComponentName(context, cls);
+ try {
+ final ActivityInfo ai = context.getPackageManager().getActivityInfo(cn, 0);
+ if (ai != null) {
+ return ai.labelRes;
+ }
+ } catch (final NameNotFoundException e) {
+ Log.e(TAG, "Failed to get settings activity title res id.", e);
+ }
+ return 0;
+ }
+
+ /**
+ * A utility method to get the application's PackageInfo.versionName
+ * @return the application's PackageInfo.versionName
+ */
+ public static String getVersionName(final Context context) {
+ try {
+ if (context == null) {
+ return "";
+ }
+ final String packageName = context.getPackageName();
+ final PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
+ return info.versionName;
+ } catch (final NameNotFoundException e) {
+ Log.e(TAG, "Could not find version info.", e);
+ }
+ return "";
+ }
+
+ /**
+ * A utility method to get the application's PackageInfo.versionCode
+ * @return the application's PackageInfo.versionCode
+ */
+ public static int getVersionCode(final Context context) {
+ try {
+ if (context == null) {
+ return 0;
+ }
+ final String packageName = context.getPackageName();
+ final PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
+ return info.versionCode;
+ } catch (final NameNotFoundException e) {
+ Log.e(TAG, "Could not find version info.", e);
+ }
+ return 0;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/AsyncResultHolder.java b/java/src/org/kelar/inputmethod/latin/utils/AsyncResultHolder.java
new file mode 100644
index 000000000..b269f7f88
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/AsyncResultHolder.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.util.Log;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * This class is a holder of the result of an asynchronous computation.
+ *
+ * @param <E> the type of the result.
+ */
+public class AsyncResultHolder<E> {
+
+ private final Object mLock = new Object();
+
+ private E mResult;
+ private final String mTag;
+ private final CountDownLatch mLatch;
+
+ public AsyncResultHolder(final String tag) {
+ mTag = tag;
+ mLatch = new CountDownLatch(1);
+ }
+
+ /**
+ * Sets the result value of this holder.
+ *
+ * @param result the value to set.
+ */
+ public void set(final E result) {
+ synchronized(mLock) {
+ if (mLatch.getCount() > 0) {
+ mResult = result;
+ mLatch.countDown();
+ }
+ }
+ }
+
+ /**
+ * Gets the result value held in this holder.
+ * Causes the current thread to wait unless the value is set or the specified time is elapsed.
+ *
+ * @param defaultValue the default value.
+ * @param timeOut the maximum time to wait.
+ * @return if the result is set before the time limit then the result, otherwise defaultValue.
+ */
+ public E get(final E defaultValue, final long timeOut) {
+ try {
+ return mLatch.await(timeOut, TimeUnit.MILLISECONDS) ? mResult : defaultValue;
+ } catch (InterruptedException e) {
+ Log.w(mTag, "get() : Interrupted after " + timeOut + " ms");
+ return defaultValue;
+ }
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/AutoCorrectionUtils.java b/java/src/org/kelar/inputmethod/latin/utils/AutoCorrectionUtils.java
new file mode 100644
index 000000000..7410abddf
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/AutoCorrectionUtils.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2011 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 org.kelar.inputmethod.latin.utils;
+
+import android.util.Log;
+
+import org.kelar.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
+import org.kelar.inputmethod.latin.define.DebugFlags;
+
+public final class AutoCorrectionUtils {
+ private static final boolean DBG = DebugFlags.DEBUG_ENABLED;
+ private static final String TAG = AutoCorrectionUtils.class.getSimpleName();
+
+ private AutoCorrectionUtils() {
+ // Purely static class: can't instantiate.
+ }
+
+ public static boolean suggestionExceedsThreshold(final SuggestedWordInfo suggestion,
+ final String consideredWord, final float threshold) {
+ if (null != suggestion) {
+ // Shortlist a whitelisted word
+ if (suggestion.isKindOf(SuggestedWordInfo.KIND_WHITELIST)) {
+ return true;
+ }
+ // TODO: return suggestion.isAprapreateForAutoCorrection();
+ if (!suggestion.isAprapreateForAutoCorrection()) {
+ return false;
+ }
+ final int autoCorrectionSuggestionScore = suggestion.mScore;
+ // TODO: when the normalized score of the first suggestion is nearly equals to
+ // the normalized score of the second suggestion, behave less aggressive.
+ final float normalizedScore = BinaryDictionaryUtils.calcNormalizedScore(
+ consideredWord, suggestion.mWord, autoCorrectionSuggestionScore);
+ if (DBG) {
+ Log.d(TAG, "Normalized " + consideredWord + "," + suggestion + ","
+ + autoCorrectionSuggestionScore + ", " + normalizedScore
+ + "(" + threshold + ")");
+ }
+ if (normalizedScore >= threshold) {
+ if (DBG) {
+ Log.d(TAG, "Exceeds threshold.");
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/BinaryDictionaryUtils.java b/java/src/org/kelar/inputmethod/latin/utils/BinaryDictionaryUtils.java
new file mode 100644
index 000000000..4020ca62a
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/BinaryDictionaryUtils.java
@@ -0,0 +1,128 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+import org.kelar.inputmethod.latin.BinaryDictionary;
+import org.kelar.inputmethod.latin.common.StringUtils;
+import org.kelar.inputmethod.latin.makedict.DictionaryHeader;
+import org.kelar.inputmethod.latin.makedict.UnsupportedFormatException;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public final class BinaryDictionaryUtils {
+ private static final String TAG = BinaryDictionaryUtils.class.getSimpleName();
+
+ private BinaryDictionaryUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ static {
+ JniUtils.loadNativeLibrary();
+ }
+
+ @UsedForTesting
+ private static native boolean createEmptyDictFileNative(String filePath, long dictVersion,
+ String locale, String[] attributeKeyStringArray, String[] attributeValueStringArray);
+ private static native float calcNormalizedScoreNative(int[] before, int[] after, int score);
+ private static native int setCurrentTimeForTestNative(int currentTime);
+
+ public static DictionaryHeader getHeader(final File dictFile)
+ throws IOException, UnsupportedFormatException {
+ return getHeaderWithOffsetAndLength(dictFile, 0 /* offset */, dictFile.length());
+ }
+
+ public static DictionaryHeader getHeaderWithOffsetAndLength(final File dictFile,
+ final long offset, final long length) throws IOException, UnsupportedFormatException {
+ // dictType is never used for reading the header. Passing an empty string.
+ final BinaryDictionary binaryDictionary = new BinaryDictionary(
+ dictFile.getAbsolutePath(), offset, length,
+ true /* useFullEditDistance */, null /* locale */, "" /* dictType */,
+ false /* isUpdatable */);
+ final DictionaryHeader header = binaryDictionary.getHeader();
+ binaryDictionary.close();
+ if (header == null) {
+ throw new IOException();
+ }
+ return header;
+ }
+
+ public static boolean renameDict(final File dictFile, final File newDictFile) {
+ if (dictFile.isFile()) {
+ return dictFile.renameTo(newDictFile);
+ } else if (dictFile.isDirectory()) {
+ final String dictName = dictFile.getName();
+ final String newDictName = newDictFile.getName();
+ if (newDictFile.exists()) {
+ return false;
+ }
+ for (final File file : dictFile.listFiles()) {
+ if (!file.isFile()) {
+ continue;
+ }
+ final String fileName = file.getName();
+ final String newFileName = fileName.replaceFirst(
+ Pattern.quote(dictName), Matcher.quoteReplacement(newDictName));
+ if (!file.renameTo(new File(dictFile, newFileName))) {
+ return false;
+ }
+ }
+ return dictFile.renameTo(newDictFile);
+ }
+ return false;
+ }
+
+ @UsedForTesting
+ public static boolean createEmptyDictFile(final String filePath, final long dictVersion,
+ final Locale locale, final Map<String, String> attributeMap) {
+ final String[] keyArray = new String[attributeMap.size()];
+ final String[] valueArray = new String[attributeMap.size()];
+ int index = 0;
+ for (final String key : attributeMap.keySet()) {
+ keyArray[index] = key;
+ valueArray[index] = attributeMap.get(key);
+ index++;
+ }
+ return createEmptyDictFileNative(filePath, dictVersion, locale.toString(), keyArray,
+ valueArray);
+ }
+
+ public static float calcNormalizedScore(final String before, final String after,
+ final int score) {
+ return calcNormalizedScoreNative(StringUtils.toCodePointArray(before),
+ StringUtils.toCodePointArray(after), score);
+ }
+
+ /**
+ * Control the current time to be used in the native code. If currentTime >= 0, this method sets
+ * the current time and gets into test mode.
+ * In test mode, set timestamp is used as the current time in the native code.
+ * If currentTime < 0, quit the test mode and returns to using time() to get the current time.
+ *
+ * @param currentTime seconds since the unix epoch
+ * @return current time got in the native code.
+ */
+ @UsedForTesting
+ public static int setCurrentTimeForTest(final int currentTime) {
+ return setCurrentTimeForTestNative(currentTime);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/CapsModeUtils.java b/java/src/org/kelar/inputmethod/latin/utils/CapsModeUtils.java
new file mode 100644
index 000000000..ee42b4f59
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/CapsModeUtils.java
@@ -0,0 +1,357 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.text.InputType;
+import android.text.TextUtils;
+
+import org.kelar.inputmethod.latin.WordComposer;
+import org.kelar.inputmethod.latin.common.Constants;
+import org.kelar.inputmethod.latin.common.StringUtils;
+import org.kelar.inputmethod.latin.settings.SpacingAndPunctuations;
+
+import java.util.ArrayList;
+import java.util.Locale;
+
+public final class CapsModeUtils {
+ private CapsModeUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ /**
+ * Apply an auto-caps mode to a string.
+ *
+ * This intentionally does NOT apply manual caps mode. It only changes the capitalization if
+ * the mode is one of the auto-caps modes.
+ * @param s The string to capitalize.
+ * @param capitalizeMode The mode in which to capitalize.
+ * @param locale The locale for capitalizing.
+ * @return The capitalized string.
+ */
+ public static String applyAutoCapsMode(final String s, final int capitalizeMode,
+ final Locale locale) {
+ if (WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED == capitalizeMode) {
+ return s.toUpperCase(locale);
+ } else if (WordComposer.CAPS_MODE_AUTO_SHIFTED == capitalizeMode) {
+ return StringUtils.capitalizeFirstCodePoint(s, locale);
+ } else {
+ return s;
+ }
+ }
+
+ /**
+ * Return whether a constant represents an auto-caps mode (either auto-shift or auto-shift-lock)
+ * @param mode The mode to test for
+ * @return true if this represents an auto-caps mode, false otherwise
+ */
+ public static boolean isAutoCapsMode(final int mode) {
+ return WordComposer.CAPS_MODE_AUTO_SHIFTED == mode
+ || WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED == mode;
+ }
+
+ /**
+ * Helper method to find out if a code point is starting punctuation.
+ *
+ * This include the Unicode START_PUNCTUATION category, but also some other symbols that are
+ * starting, like the inverted question mark or the double quote.
+ *
+ * @param codePoint the code point
+ * @return true if it's starting punctuation, false otherwise.
+ */
+ private static boolean isStartPunctuation(final int codePoint) {
+ return (codePoint == Constants.CODE_DOUBLE_QUOTE || codePoint == Constants.CODE_SINGLE_QUOTE
+ || codePoint == Constants.CODE_INVERTED_QUESTION_MARK
+ || codePoint == Constants.CODE_INVERTED_EXCLAMATION_MARK
+ || Character.getType(codePoint) == Character.START_PUNCTUATION);
+ }
+
+ /**
+ * Determine what caps mode should be in effect at the current offset in
+ * the text. Only the mode bits set in <var>reqModes</var> will be
+ * checked. Note that the caps mode flags here are explicitly defined
+ * to match those in {@link InputType}.
+ *
+ * This code is a straight copy of TextUtils.getCapsMode (modulo namespace and formatting
+ * issues). This will change in the future as we simplify the code for our use and fix bugs.
+ *
+ * @param cs The text that should be checked for caps modes.
+ * @param reqModes The modes to be checked: may be any combination of
+ * {@link TextUtils#CAP_MODE_CHARACTERS}, {@link TextUtils#CAP_MODE_WORDS}, and
+ * {@link TextUtils#CAP_MODE_SENTENCES}.
+ * @param spacingAndPunctuations The current spacing and punctuations settings.
+ * @param hasSpaceBefore Whether we should consider there is a space inserted at the end of cs
+ *
+ * @return Returns the actual capitalization modes that can be in effect
+ * at the current position, which is any combination of
+ * {@link TextUtils#CAP_MODE_CHARACTERS}, {@link TextUtils#CAP_MODE_WORDS}, and
+ * {@link TextUtils#CAP_MODE_SENTENCES}.
+ */
+ public static int getCapsMode(final CharSequence cs, final int reqModes,
+ final SpacingAndPunctuations spacingAndPunctuations, final boolean hasSpaceBefore) {
+ // Quick description of what we want to do:
+ // CAP_MODE_CHARACTERS is always on.
+ // CAP_MODE_WORDS is on if there is some whitespace before the cursor.
+ // CAP_MODE_SENTENCES is on if there is some whitespace before the cursor, and the end
+ // of a sentence just before that.
+ // We ignore opening parentheses and the like just before the cursor for purposes of
+ // finding whitespace for WORDS and SENTENCES modes.
+ // The end of a sentence ends with a period, question mark or exclamation mark. If it's
+ // a period, it also needs not to be an abbreviation, which means it also needs to either
+ // be immediately preceded by punctuation, or by a string of only letters with single
+ // periods interleaved.
+
+ // Step 1 : check for cap MODE_CHARACTERS. If it's looked for, it's always on.
+ if ((reqModes & (TextUtils.CAP_MODE_WORDS | TextUtils.CAP_MODE_SENTENCES)) == 0) {
+ // Here we are not looking for MODE_WORDS or MODE_SENTENCES, so since we already
+ // evaluated MODE_CHARACTERS, we can return.
+ return TextUtils.CAP_MODE_CHARACTERS & reqModes;
+ }
+
+ // Step 2 : Skip (ignore at the end of input) any opening punctuation. This includes
+ // opening parentheses, brackets, opening quotes, everything that *opens* a span of
+ // text in the linguistic sense. In RTL languages, this is still an opening sign, although
+ // it may look like a right parenthesis for example. We also include double quote and
+ // single quote since they aren't start punctuation in the unicode sense, but should still
+ // be skipped for English. TODO: does this depend on the language?
+ int i;
+ if (hasSpaceBefore) {
+ i = cs.length() + 1;
+ } else {
+ for (i = cs.length(); i > 0; i--) {
+ final char c = cs.charAt(i - 1);
+ if (!isStartPunctuation(c)) {
+ break;
+ }
+ }
+ }
+
+ // We are now on the character that precedes any starting punctuation, so in the most
+ // frequent case this will be whitespace or a letter, although it may occasionally be a
+ // start of line, or some symbol.
+
+ // Step 3 : Search for the start of a paragraph. From the starting point computed in step 2,
+ // we go back over any space or tab char sitting there. We find the start of a paragraph
+ // if the first char that's not a space or tab is a start of line (as in \n, start of text,
+ // or some other similar characters).
+ int j = i;
+ char prevChar = Constants.CODE_SPACE;
+ if (hasSpaceBefore) --j;
+ while (j > 0) {
+ prevChar = cs.charAt(j - 1);
+ if (!Character.isSpaceChar(prevChar) && prevChar != Constants.CODE_TAB) break;
+ j--;
+ }
+ if (j <= 0 || Character.isWhitespace(prevChar)) {
+ if (spacingAndPunctuations.mUsesGermanRules) {
+ // In German typography rules, there is a specific case that the first character
+ // of a new line should not be capitalized if the previous line ends in a comma.
+ boolean hasNewLine = false;
+ while (--j >= 0 && Character.isWhitespace(prevChar)) {
+ if (Constants.CODE_ENTER == prevChar) {
+ hasNewLine = true;
+ }
+ prevChar = cs.charAt(j);
+ }
+ if (Constants.CODE_COMMA == prevChar && hasNewLine) {
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ }
+ }
+ // There are only spacing chars between the start of the paragraph and the cursor,
+ // defined as a isWhitespace() char that is neither a isSpaceChar() nor a tab. Both
+ // MODE_WORDS and MODE_SENTENCES should be active.
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
+ | TextUtils.CAP_MODE_SENTENCES) & reqModes;
+ }
+ if (i == j) {
+ // If we don't have whitespace before index i, it means neither MODE_WORDS
+ // nor mode sentences should be on so we can return right away.
+ return TextUtils.CAP_MODE_CHARACTERS & reqModes;
+ }
+ if ((reqModes & TextUtils.CAP_MODE_SENTENCES) == 0) {
+ // Here we know we have whitespace before the cursor (if not, we returned in the above
+ // if i == j clause), so we need MODE_WORDS to be on. And we don't need to evaluate
+ // MODE_SENTENCES so we can return right away.
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ }
+ // Please note that because of the reqModes & CAP_MODE_SENTENCES test a few lines above,
+ // we know that MODE_SENTENCES is being requested.
+
+ // Step 4 : Search for MODE_SENTENCES.
+ // English is a special case in that "American typography" rules, which are the most common
+ // in English, state that a sentence terminator immediately following a quotation mark
+ // should be swapped with it and de-duplicated (included in the quotation mark),
+ // e.g. <<Did they say, "let's go home?">>
+ // No other language has such a rule as far as I know, instead putting inside the quotation
+ // mark as the exact thing quoted and handling the surrounding punctuation independently,
+ // e.g. <<Did they say, "let's go home"?>>
+ if (spacingAndPunctuations.mUsesAmericanTypography) {
+ for (; j > 0; j--) {
+ // Here we look to go over any closing punctuation. This is because in dominant
+ // variants of English, the final period is placed within double quotes and maybe
+ // other closing punctuation signs. This is generally not true in other languages.
+ final char c = cs.charAt(j - 1);
+ if (c != Constants.CODE_DOUBLE_QUOTE && c != Constants.CODE_SINGLE_QUOTE
+ && Character.getType(c) != Character.END_PUNCTUATION) {
+ break;
+ }
+ }
+ }
+
+ if (j <= 0) return TextUtils.CAP_MODE_CHARACTERS & reqModes;
+ char c = cs.charAt(--j);
+
+ // We found the next interesting chunk of text ; next we need to determine if it's the
+ // end of a sentence. If we have a sentence terminator (typically a question mark or an
+ // exclamation mark), then it's the end of a sentence; however, we treat the abbreviation
+ // marker specially because usually is the same char as the sentence separator (the
+ // period in most languages) and in this case we need to apply a heuristic to determine
+ // in which of these senses it's used.
+ if (spacingAndPunctuations.isSentenceTerminator(c)
+ && !spacingAndPunctuations.isAbbreviationMarker(c)) {
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
+ | TextUtils.CAP_MODE_SENTENCES) & reqModes;
+ }
+ // If we reach here, we know we have whitespace before the cursor and before that there
+ // is something that either does not terminate the sentence, or a symbol preceded by the
+ // start of the text, or it's the sentence separator AND it happens to be the same code
+ // point as the abbreviation marker.
+ // If it's a symbol or something that does not terminate the sentence, then we need to
+ // return caps for MODE_CHARACTERS and MODE_WORDS, but not for MODE_SENTENCES.
+ if (!spacingAndPunctuations.isSentenceSeparator(c) || j <= 0) {
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ }
+
+ // We found out that we have a period. We need to determine if this is a full stop or
+ // otherwise sentence-ending period, or an abbreviation like "e.g.". An abbreviation
+ // looks like (\w\.){2,}. Moreover, in German, you put periods after digits for dates
+ // and some other things, and in German specifically we need to not go into autocaps after
+ // a whitespace-digits-period sequence.
+ // To find out, we will have a simple state machine with the following states :
+ // START, WORD, PERIOD, ABBREVIATION, NUMBER
+ // On START : (just before the first period)
+ // letter => WORD
+ // digit => NUMBER if German; end with caps otherwise
+ // whitespace => end with no caps (it was a stand-alone period)
+ // otherwise => end with caps (several periods/symbols in a row)
+ // On WORD : (within the word just before the first period)
+ // letter => WORD
+ // period => PERIOD
+ // otherwise => end with caps (it was a word with a full stop at the end)
+ // On PERIOD : (period within a potential abbreviation)
+ // letter => LETTER
+ // otherwise => end with caps (it was not an abbreviation)
+ // On LETTER : (letter within a potential abbreviation)
+ // letter => LETTER
+ // period => PERIOD
+ // otherwise => end with no caps (it was an abbreviation)
+ // On NUMBER : (period immediately preceded by one or more digits)
+ // digit => NUMBER
+ // letter => LETTER (promote to word)
+ // otherwise => end with no caps (it was a whitespace-digits-period sequence,
+ // or a punctuation-digits-period sequence like "11.11.")
+ // "Not an abbreviation" in the above chart essentially covers cases like "...yes.". This
+ // should capitalize.
+
+ final int START = 0;
+ final int WORD = 1;
+ final int PERIOD = 2;
+ final int LETTER = 3;
+ final int NUMBER = 4;
+ final int caps = (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
+ | TextUtils.CAP_MODE_SENTENCES) & reqModes;
+ final int noCaps = (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ int state = START;
+ while (j > 0) {
+ c = cs.charAt(--j);
+ switch (state) {
+ case START:
+ if (Character.isLetter(c)) {
+ state = WORD;
+ } else if (Character.isWhitespace(c)) {
+ return noCaps;
+ } else if (Character.isDigit(c) && spacingAndPunctuations.mUsesGermanRules) {
+ state = NUMBER;
+ } else {
+ return caps;
+ }
+ break;
+ case WORD:
+ if (Character.isLetter(c)) {
+ state = WORD;
+ } else if (spacingAndPunctuations.isSentenceSeparator(c)) {
+ state = PERIOD;
+ } else {
+ return caps;
+ }
+ break;
+ case PERIOD:
+ if (Character.isLetter(c)) {
+ state = LETTER;
+ } else {
+ return caps;
+ }
+ break;
+ case LETTER:
+ if (Character.isLetter(c)) {
+ state = LETTER;
+ } else if (spacingAndPunctuations.isSentenceSeparator(c)) {
+ state = PERIOD;
+ } else {
+ return noCaps;
+ }
+ break;
+ case NUMBER:
+ if (Character.isLetter(c)) {
+ state = WORD;
+ } else if (Character.isDigit(c)) {
+ state = NUMBER;
+ } else {
+ return noCaps;
+ }
+ }
+ }
+ // Here we arrived at the start of the line. This should behave exactly like whitespace.
+ return (START == state || LETTER == state) ? noCaps : caps;
+ }
+
+ /**
+ * Convert capitalize mode flags into human readable text.
+ *
+ * @param capsFlags The modes flags to be converted. It may be any combination of
+ * {@link TextUtils#CAP_MODE_CHARACTERS}, {@link TextUtils#CAP_MODE_WORDS}, and
+ * {@link TextUtils#CAP_MODE_SENTENCES}.
+ * @return the text that describe the <code>capsMode</code>.
+ */
+ public static String flagsToString(final int capsFlags) {
+ final int capsFlagsMask = TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
+ | TextUtils.CAP_MODE_SENTENCES;
+ if ((capsFlags & ~capsFlagsMask) != 0) {
+ return "unknown<0x" + Integer.toHexString(capsFlags) + ">";
+ }
+ final ArrayList<String> builder = new ArrayList<>();
+ if ((capsFlags & android.text.TextUtils.CAP_MODE_CHARACTERS) != 0) {
+ builder.add("characters");
+ }
+ if ((capsFlags & android.text.TextUtils.CAP_MODE_WORDS) != 0) {
+ builder.add("words");
+ }
+ if ((capsFlags & android.text.TextUtils.CAP_MODE_SENTENCES) != 0) {
+ builder.add("sentences");
+ }
+ return builder.isEmpty() ? "none" : TextUtils.join("|", builder);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/CombinedFormatUtils.java b/java/src/org/kelar/inputmethod/latin/utils/CombinedFormatUtils.java
new file mode 100644
index 000000000..62ecc8d04
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/CombinedFormatUtils.java
@@ -0,0 +1,109 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.latin.makedict.DictionaryHeader;
+import org.kelar.inputmethod.latin.makedict.NgramProperty;
+import org.kelar.inputmethod.latin.makedict.ProbabilityInfo;
+import org.kelar.inputmethod.latin.makedict.WordProperty;
+
+import java.util.HashMap;
+
+public class CombinedFormatUtils {
+ public static final String DICTIONARY_TAG = "dictionary";
+ public static final String BIGRAM_TAG = "bigram";
+ public static final String NGRAM_TAG = "ngram";
+ public static final String NGRAM_PREV_WORD_TAG = "prev_word";
+ public static final String PROBABILITY_TAG = "f";
+ public static final String HISTORICAL_INFO_TAG = "historicalInfo";
+ public static final String HISTORICAL_INFO_SEPARATOR = ":";
+ public static final String WORD_TAG = "word";
+ public static final String BEGINNING_OF_SENTENCE_TAG = "beginning_of_sentence";
+ public static final String NOT_A_WORD_TAG = "not_a_word";
+ public static final String POSSIBLY_OFFENSIVE_TAG = "possibly_offensive";
+ public static final String TRUE_VALUE = "true";
+
+ public static String formatAttributeMap(final HashMap<String, String> attributeMap) {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(DICTIONARY_TAG + "=");
+ if (attributeMap.containsKey(DictionaryHeader.DICTIONARY_ID_KEY)) {
+ builder.append(attributeMap.get(DictionaryHeader.DICTIONARY_ID_KEY));
+ }
+ for (final String key : attributeMap.keySet()) {
+ if (key.equals(DictionaryHeader.DICTIONARY_ID_KEY)) {
+ continue;
+ }
+ final String value = attributeMap.get(key);
+ builder.append("," + key + "=" + value);
+ }
+ builder.append("\n");
+ return builder.toString();
+ }
+
+ public static String formatWordProperty(final WordProperty wordProperty) {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(" " + WORD_TAG + "=" + wordProperty.mWord);
+ builder.append(",");
+ builder.append(formatProbabilityInfo(wordProperty.mProbabilityInfo));
+ if (wordProperty.mIsBeginningOfSentence) {
+ builder.append("," + BEGINNING_OF_SENTENCE_TAG + "=" + TRUE_VALUE);
+ }
+ if (wordProperty.mIsNotAWord) {
+ builder.append("," + NOT_A_WORD_TAG + "=" + TRUE_VALUE);
+ }
+ if (wordProperty.mIsPossiblyOffensive) {
+ builder.append("," + POSSIBLY_OFFENSIVE_TAG + "=" + TRUE_VALUE);
+ }
+ builder.append("\n");
+ if (wordProperty.mHasNgrams) {
+ for (final NgramProperty ngramProperty : wordProperty.mNgrams) {
+ builder.append(" " + NGRAM_TAG + "=" + ngramProperty.mTargetWord.mWord);
+ builder.append(",");
+ builder.append(formatProbabilityInfo(ngramProperty.mTargetWord.mProbabilityInfo));
+ builder.append("\n");
+ for (int i = 0; i < ngramProperty.mNgramContext.getPrevWordCount(); i++) {
+ builder.append(" " + NGRAM_PREV_WORD_TAG + "[" + i + "]="
+ + ngramProperty.mNgramContext.getNthPrevWord(i + 1));
+ if (ngramProperty.mNgramContext.isNthPrevWordBeginningOfSentence(i + 1)) {
+ builder.append("," + BEGINNING_OF_SENTENCE_TAG + "=true");
+ }
+ builder.append("\n");
+ }
+ }
+ }
+ return builder.toString();
+ }
+
+ public static String formatProbabilityInfo(final ProbabilityInfo probabilityInfo) {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(PROBABILITY_TAG + "=" + probabilityInfo.mProbability);
+ if (probabilityInfo.hasHistoricalInfo()) {
+ builder.append(",");
+ builder.append(HISTORICAL_INFO_TAG + "=");
+ builder.append(probabilityInfo.mTimestamp);
+ builder.append(HISTORICAL_INFO_SEPARATOR);
+ builder.append(probabilityInfo.mLevel);
+ builder.append(HISTORICAL_INFO_SEPARATOR);
+ builder.append(probabilityInfo.mCount);
+ }
+ return builder.toString();
+ }
+
+ public static boolean isLiteralTrue(final String value) {
+ return TRUE_VALUE.equalsIgnoreCase(value);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/CompletionInfoUtils.java b/java/src/org/kelar/inputmethod/latin/utils/CompletionInfoUtils.java
new file mode 100644
index 000000000..fde9594fd
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/CompletionInfoUtils.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.text.TextUtils;
+import android.view.inputmethod.CompletionInfo;
+
+import java.util.Arrays;
+
+/**
+ * Utilities to do various stuff with CompletionInfo.
+ */
+public class CompletionInfoUtils {
+ private CompletionInfoUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static CompletionInfo[] removeNulls(final CompletionInfo[] src) {
+ int j = 0;
+ final CompletionInfo[] dst = new CompletionInfo[src.length];
+ for (int i = 0; i < src.length; ++i) {
+ if (null != src[i] && !TextUtils.isEmpty(src[i].getText())) {
+ dst[j] = src[i];
+ ++j;
+ }
+ }
+ return Arrays.copyOfRange(dst, 0, j);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/CursorAnchorInfoUtils.java b/java/src/org/kelar/inputmethod/latin/utils/CursorAnchorInfoUtils.java
new file mode 100644
index 000000000..e79c8f376
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/CursorAnchorInfoUtils.java
@@ -0,0 +1,264 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.annotation.TargetApi;
+import android.graphics.Matrix;
+import android.graphics.Rect;
+import android.inputmethodservice.ExtractEditText;
+import android.inputmethodservice.InputMethodService;
+import android.os.Build;
+import android.text.Layout;
+import android.text.Spannable;
+import android.text.Spanned;
+import android.view.View;
+import android.view.ViewParent;
+import android.view.inputmethod.CursorAnchorInfo;
+import android.widget.TextView;
+
+import org.kelar.inputmethod.compat.BuildCompatUtils;
+import org.kelar.inputmethod.compat.CursorAnchorInfoCompatWrapper;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+/**
+ * This class allows input methods to extract {@link CursorAnchorInfo} directly from the given
+ * {@link TextView}. This is useful and even necessary to support full-screen mode where the default
+ * {@link InputMethodService#onUpdateCursorAnchorInfo(CursorAnchorInfo)} event callback must be
+ * ignored because it reports the character locations of the target application rather than
+ * characters on {@link ExtractEditText}.
+ */
+public final class CursorAnchorInfoUtils {
+ private CursorAnchorInfoUtils() {
+ // This helper class is not instantiable.
+ }
+
+ private static boolean isPositionVisible(final View view, final float positionX,
+ final float positionY) {
+ final float[] position = new float[] { positionX, positionY };
+ View currentView = view;
+
+ while (currentView != null) {
+ if (currentView != view) {
+ // Local scroll is already taken into account in positionX/Y
+ position[0] -= currentView.getScrollX();
+ position[1] -= currentView.getScrollY();
+ }
+
+ if (position[0] < 0 || position[1] < 0 ||
+ position[0] > currentView.getWidth() || position[1] > currentView.getHeight()) {
+ return false;
+ }
+
+ if (!currentView.getMatrix().isIdentity()) {
+ currentView.getMatrix().mapPoints(position);
+ }
+
+ position[0] += currentView.getLeft();
+ position[1] += currentView.getTop();
+
+ final ViewParent parent = currentView.getParent();
+ if (parent instanceof View) {
+ currentView = (View) parent;
+ } else {
+ // We've reached the ViewRoot, stop iterating
+ currentView = null;
+ }
+ }
+
+ // We've been able to walk up the view hierarchy and the position was never clipped
+ return true;
+ }
+
+ /**
+ * Extracts {@link CursorAnchorInfoCompatWrapper} from the given {@link TextView}.
+ * @param textView the target text view from which {@link CursorAnchorInfoCompatWrapper} is to
+ * be extracted.
+ * @return the {@link CursorAnchorInfoCompatWrapper} object based on the current layout.
+ * {@code null} if {@code Build.VERSION.SDK_INT} is 20 or prior or {@link TextView} is not
+ * ready to provide layout information.
+ */
+ @Nullable
+ public static CursorAnchorInfoCompatWrapper extractFromTextView(
+ @Nonnull final TextView textView) {
+ if (BuildCompatUtils.EFFECTIVE_SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
+ return null;
+ }
+ return CursorAnchorInfoCompatWrapper.wrap(extractFromTextViewInternal(textView));
+ }
+
+ /**
+ * Returns {@link CursorAnchorInfo} from the given {@link TextView}.
+ * @param textView the target text view from which {@link CursorAnchorInfo} is to be extracted.
+ * @return the {@link CursorAnchorInfo} object based on the current layout. {@code null} if it
+ * is not feasible.
+ */
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ @Nullable
+ private static CursorAnchorInfo extractFromTextViewInternal(@Nonnull final TextView textView) {
+ final Layout layout = textView.getLayout();
+ if (layout == null) {
+ return null;
+ }
+
+ final CursorAnchorInfo.Builder builder = new CursorAnchorInfo.Builder();
+
+ final int selectionStart = textView.getSelectionStart();
+ builder.setSelectionRange(selectionStart, textView.getSelectionEnd());
+
+ // Construct transformation matrix from view local coordinates to screen coordinates.
+ final Matrix viewToScreenMatrix = new Matrix(textView.getMatrix());
+ final int[] viewOriginInScreen = new int[2];
+ textView.getLocationOnScreen(viewOriginInScreen);
+ viewToScreenMatrix.postTranslate(viewOriginInScreen[0], viewOriginInScreen[1]);
+ builder.setMatrix(viewToScreenMatrix);
+
+ if (layout.getLineCount() == 0) {
+ return null;
+ }
+ final Rect lineBoundsWithoutOffset = new Rect();
+ final Rect lineBoundsWithOffset = new Rect();
+ layout.getLineBounds(0, lineBoundsWithoutOffset);
+ textView.getLineBounds(0, lineBoundsWithOffset);
+ final float viewportToContentHorizontalOffset = lineBoundsWithOffset.left
+ - lineBoundsWithoutOffset.left - textView.getScrollX();
+ final float viewportToContentVerticalOffset = lineBoundsWithOffset.top
+ - lineBoundsWithoutOffset.top - textView.getScrollY();
+
+ final CharSequence text = textView.getText();
+ if (text instanceof Spannable) {
+ // Here we assume that the composing text is marked as SPAN_COMPOSING flag. This is not
+ // necessarily true, but basically works.
+ int composingTextStart = text.length();
+ int composingTextEnd = 0;
+ final Spannable spannable = (Spannable) text;
+ final Object[] spans = spannable.getSpans(0, text.length(), Object.class);
+ for (Object span : spans) {
+ final int spanFlag = spannable.getSpanFlags(span);
+ if ((spanFlag & Spanned.SPAN_COMPOSING) != 0) {
+ composingTextStart = Math.min(composingTextStart,
+ spannable.getSpanStart(span));
+ composingTextEnd = Math.max(composingTextEnd, spannable.getSpanEnd(span));
+ }
+ }
+
+ final boolean hasComposingText =
+ (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
+ if (hasComposingText) {
+ final CharSequence composingText = text.subSequence(composingTextStart,
+ composingTextEnd);
+ builder.setComposingText(composingTextStart, composingText);
+
+ final int minLine = layout.getLineForOffset(composingTextStart);
+ final int maxLine = layout.getLineForOffset(composingTextEnd - 1);
+ for (int line = minLine; line <= maxLine; ++line) {
+ final int lineStart = layout.getLineStart(line);
+ final int lineEnd = layout.getLineEnd(line);
+ final int offsetStart = Math.max(lineStart, composingTextStart);
+ final int offsetEnd = Math.min(lineEnd, composingTextEnd);
+ final boolean ltrLine =
+ layout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT;
+ final float[] widths = new float[offsetEnd - offsetStart];
+ layout.getPaint().getTextWidths(text, offsetStart, offsetEnd, widths);
+ final float top = layout.getLineTop(line);
+ final float bottom = layout.getLineBottom(line);
+ for (int offset = offsetStart; offset < offsetEnd; ++offset) {
+ final float charWidth = widths[offset - offsetStart];
+ final boolean isRtl = layout.isRtlCharAt(offset);
+ final float primary = layout.getPrimaryHorizontal(offset);
+ final float secondary = layout.getSecondaryHorizontal(offset);
+ // TODO: This doesn't work perfectly for text with custom styles and TAB
+ // chars.
+ final float left;
+ final float right;
+ if (ltrLine) {
+ if (isRtl) {
+ left = secondary - charWidth;
+ right = secondary;
+ } else {
+ left = primary;
+ right = primary + charWidth;
+ }
+ } else {
+ if (!isRtl) {
+ left = secondary;
+ right = secondary + charWidth;
+ } else {
+ left = primary - charWidth;
+ right = primary;
+ }
+ }
+ // TODO: Check top-right and bottom-left as well.
+ final float localLeft = left + viewportToContentHorizontalOffset;
+ final float localRight = right + viewportToContentHorizontalOffset;
+ final float localTop = top + viewportToContentVerticalOffset;
+ final float localBottom = bottom + viewportToContentVerticalOffset;
+ final boolean isTopLeftVisible = isPositionVisible(textView,
+ localLeft, localTop);
+ final boolean isBottomRightVisible =
+ isPositionVisible(textView, localRight, localBottom);
+ int characterBoundsFlags = 0;
+ if (isTopLeftVisible || isBottomRightVisible) {
+ characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
+ }
+ if (!isTopLeftVisible || !isBottomRightVisible) {
+ characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
+ }
+ if (isRtl) {
+ characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL;
+ }
+ // Here offset is the index in Java chars.
+ builder.addCharacterBounds(offset, localLeft, localTop, localRight,
+ localBottom, characterBoundsFlags);
+ }
+ }
+ }
+ }
+
+ // Treat selectionStart as the insertion point.
+ if (0 <= selectionStart) {
+ final int offset = selectionStart;
+ final int line = layout.getLineForOffset(offset);
+ final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
+ + viewportToContentHorizontalOffset;
+ final float insertionMarkerTop = layout.getLineTop(line)
+ + viewportToContentVerticalOffset;
+ final float insertionMarkerBaseline = layout.getLineBaseline(line)
+ + viewportToContentVerticalOffset;
+ final float insertionMarkerBottom = layout.getLineBottom(line)
+ + viewportToContentVerticalOffset;
+ final boolean isTopVisible =
+ isPositionVisible(textView, insertionMarkerX, insertionMarkerTop);
+ final boolean isBottomVisible =
+ isPositionVisible(textView, insertionMarkerX, insertionMarkerBottom);
+ int insertionMarkerFlags = 0;
+ if (isTopVisible || isBottomVisible) {
+ insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
+ }
+ if (!isTopVisible || !isBottomVisible) {
+ insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
+ }
+ if (layout.isRtlCharAt(offset)) {
+ insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
+ }
+ builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
+ insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
+ }
+ return builder.build();
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/DebugLogUtils.java b/java/src/org/kelar/inputmethod/latin/utils/DebugLogUtils.java
new file mode 100644
index 000000000..6587304ac
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/DebugLogUtils.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2011 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 org.kelar.inputmethod.latin.utils;
+
+import android.util.Log;
+
+import org.kelar.inputmethod.latin.define.DebugFlags;
+
+/**
+ * A class for logging and debugging utility methods.
+ */
+public final class DebugLogUtils {
+ private final static String TAG = DebugLogUtils.class.getSimpleName();
+ private final static boolean sDBG = DebugFlags.DEBUG_ENABLED;
+
+ /**
+ * Calls .toString() on its non-null argument or returns "null"
+ * @param o the object to convert to a string
+ * @return the result of .toString() or null
+ */
+ public static String s(final Object o) {
+ return null == o ? "null" : o.toString();
+ }
+
+ /**
+ * Get the string representation of the current stack trace, for debugging purposes.
+ * @return a readable, carriage-return-separated string for the current stack trace.
+ */
+ public static String getStackTrace() {
+ return getStackTrace(Integer.MAX_VALUE - 1);
+ }
+
+ /**
+ * Get the string representation of the current stack trace, for debugging purposes.
+ * @param limit the maximum number of stack frames to be returned.
+ * @return a readable, carriage-return-separated string for the current stack trace.
+ */
+ public static String getStackTrace(final int limit) {
+ final StringBuilder sb = new StringBuilder();
+ try {
+ throw new RuntimeException();
+ } catch (final RuntimeException e) {
+ final StackTraceElement[] frames = e.getStackTrace();
+ // Start at 1 because the first frame is here and we don't care about it
+ for (int j = 1; j < frames.length && j < limit + 1; ++j) {
+ sb.append(frames[j].toString() + "\n");
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Get the stack trace contained in an exception as a human-readable string.
+ * @param t the throwable
+ * @return the human-readable stack trace
+ */
+ public static String getStackTrace(final Throwable t) {
+ final StringBuilder sb = new StringBuilder();
+ final StackTraceElement[] frames = t.getStackTrace();
+ for (int j = 0; j < frames.length; ++j) {
+ sb.append(frames[j].toString() + "\n");
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Helper log method to ease null-checks and adding spaces.
+ *
+ * This sends all arguments to the log, separated by spaces. Any null argument is converted
+ * to the "null" string. It uses a very visible tag and log level for debugging purposes.
+ *
+ * @param args the stuff to send to the log
+ */
+ public static void l(final Object... args) {
+ if (!sDBG) return;
+ final StringBuilder sb = new StringBuilder();
+ for (final Object o : args) {
+ sb.append(s(o).toString());
+ sb.append(" ");
+ }
+ Log.e(TAG, sb.toString());
+ }
+
+ /**
+ * Helper log method to put stuff in red.
+ *
+ * This does the same as #l but prints in red
+ *
+ * @param args the stuff to send to the log
+ */
+ public static void r(final Object... args) {
+ if (!sDBG) return;
+ final StringBuilder sb = new StringBuilder("\u001B[31m");
+ for (final Object o : args) {
+ sb.append(s(o).toString());
+ sb.append(" ");
+ }
+ sb.append("\u001B[0m");
+ Log.e(TAG, sb.toString());
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/DialogUtils.java b/java/src/org/kelar/inputmethod/latin/utils/DialogUtils.java
new file mode 100644
index 000000000..37a3fe57a
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/DialogUtils.java
@@ -0,0 +1,34 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.Context;
+import android.view.ContextThemeWrapper;
+
+import org.kelar.inputmethod.latin.R;
+
+public final class DialogUtils {
+ private DialogUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static Context getPlatformDialogThemeContext(final Context context) {
+ // Because {@link AlertDialog.Builder.create()} doesn't honor the specified theme with
+ // createThemeContextWrapper=false, the result dialog box has unneeded paddings around it.
+ return new ContextThemeWrapper(context, R.style.platformDialogTheme);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/DictionaryHeaderUtils.java b/java/src/org/kelar/inputmethod/latin/utils/DictionaryHeaderUtils.java
new file mode 100644
index 000000000..0c0843e11
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/DictionaryHeaderUtils.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2015 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.latin.AssetFileAddress;
+import org.kelar.inputmethod.latin.makedict.DictionaryHeader;
+
+import java.io.File;
+
+public class DictionaryHeaderUtils {
+
+ public static int getContentVersion(AssetFileAddress fileAddress) {
+ final DictionaryHeader header = DictionaryInfoUtils.getDictionaryFileHeaderOrNull(
+ new File(fileAddress.mFilename), fileAddress.mOffset, fileAddress.mLength);
+ return Integer.parseInt(header.mVersionString);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/DictionaryInfoUtils.java b/java/src/org/kelar/inputmethod/latin/utils/DictionaryInfoUtils.java
new file mode 100644
index 000000000..1cec4ff78
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/DictionaryInfoUtils.java
@@ -0,0 +1,613 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.res.AssetManager;
+import android.content.res.Resources;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.inputmethod.InputMethodSubtype;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+import org.kelar.inputmethod.dictionarypack.UpdateHandler;
+import org.kelar.inputmethod.latin.AssetFileAddress;
+import org.kelar.inputmethod.latin.BinaryDictionaryGetter;
+import org.kelar.inputmethod.latin.R;
+import org.kelar.inputmethod.latin.RichInputMethodManager;
+import org.kelar.inputmethod.latin.common.FileUtils;
+import org.kelar.inputmethod.latin.common.LocaleUtils;
+import org.kelar.inputmethod.latin.define.DecoderSpecificConstants;
+import org.kelar.inputmethod.latin.makedict.DictionaryHeader;
+import org.kelar.inputmethod.latin.makedict.UnsupportedFormatException;
+import org.kelar.inputmethod.latin.settings.SpacingAndPunctuations;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+/**
+ * This class encapsulates the logic for the Latin-IME side of dictionary information management.
+ */
+public class DictionaryInfoUtils {
+ private static final String TAG = DictionaryInfoUtils.class.getSimpleName();
+ public static final String RESOURCE_PACKAGE_NAME = R.class.getPackage().getName();
+ private static final String DEFAULT_MAIN_DICT = "main";
+ private static final String MAIN_DICT_PREFIX = "main_";
+ private static final String DECODER_DICT_SUFFIX = DecoderSpecificConstants.DECODER_DICT_SUFFIX;
+ // 6 digits - unicode is limited to 21 bits
+ private static final int MAX_HEX_DIGITS_FOR_CODEPOINT = 6;
+
+ private static final String TEMP_DICT_FILE_SUB = UpdateHandler.TEMP_DICT_FILE_SUB;
+
+ public static class DictionaryInfo {
+ private static final String LOCALE_COLUMN = "locale";
+ private static final String WORDLISTID_COLUMN = "id";
+ private static final String LOCAL_FILENAME_COLUMN = "filename";
+ private static final String DESCRIPTION_COLUMN = "description";
+ private static final String DATE_COLUMN = "date";
+ private static final String FILESIZE_COLUMN = "filesize";
+ private static final String VERSION_COLUMN = "version";
+
+ @Nonnull public final String mId;
+ @Nonnull public final Locale mLocale;
+ @Nullable public final String mDescription;
+ @Nullable public final String mFilename;
+ public final long mFilesize;
+ public final long mModifiedTimeMillis;
+ public final int mVersion;
+
+ public DictionaryInfo(@Nonnull String id, @Nonnull Locale locale,
+ @Nullable String description, @Nullable String filename,
+ long filesize, long modifiedTimeMillis, int version) {
+ mId = id;
+ mLocale = locale;
+ mDescription = description;
+ mFilename = filename;
+ mFilesize = filesize;
+ mModifiedTimeMillis = modifiedTimeMillis;
+ mVersion = version;
+ }
+
+ public ContentValues toContentValues() {
+ final ContentValues values = new ContentValues();
+ values.put(WORDLISTID_COLUMN, mId);
+ values.put(LOCALE_COLUMN, mLocale.toString());
+ values.put(DESCRIPTION_COLUMN, mDescription);
+ values.put(LOCAL_FILENAME_COLUMN, mFilename != null ? mFilename : "");
+ values.put(DATE_COLUMN, TimeUnit.MILLISECONDS.toSeconds(mModifiedTimeMillis));
+ values.put(FILESIZE_COLUMN, mFilesize);
+ values.put(VERSION_COLUMN, mVersion);
+ return values;
+ }
+
+ @Override
+ public String toString() {
+ return "DictionaryInfo : Id = '" + mId
+ + "' : Locale=" + mLocale
+ + " : Version=" + mVersion;
+ }
+ }
+
+ private DictionaryInfoUtils() {
+ // Private constructor to forbid instantation of this helper class.
+ }
+
+ /**
+ * Returns whether we may want to use this character as part of a file name.
+ *
+ * This basically only accepts ascii letters and numbers, and rejects everything else.
+ */
+ private static boolean isFileNameCharacter(int codePoint) {
+ if (codePoint >= 0x30 && codePoint <= 0x39) return true; // Digit
+ if (codePoint >= 0x41 && codePoint <= 0x5A) return true; // Uppercase
+ if (codePoint >= 0x61 && codePoint <= 0x7A) return true; // Lowercase
+ return codePoint == '_'; // Underscore
+ }
+
+ /**
+ * Escapes a string for any characters that may be suspicious for a file or directory name.
+ *
+ * Concretely this does a sort of URL-encoding except it will encode everything that's not
+ * alphanumeric or underscore. (true URL-encoding leaves alone characters like '*', which
+ * we cannot allow here)
+ */
+ // TODO: create a unit test for this method
+ public static String replaceFileNameDangerousCharacters(final String name) {
+ // This assumes '%' is fully available as a non-separator, normal
+ // character in a file name. This is probably true for all file systems.
+ final StringBuilder sb = new StringBuilder();
+ final int nameLength = name.length();
+ for (int i = 0; i < nameLength; i = name.offsetByCodePoints(i, 1)) {
+ final int codePoint = name.codePointAt(i);
+ if (DictionaryInfoUtils.isFileNameCharacter(codePoint)) {
+ sb.appendCodePoint(codePoint);
+ } else {
+ sb.append(String.format((Locale)null, "%%%1$0" + MAX_HEX_DIGITS_FOR_CODEPOINT + "x",
+ codePoint));
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Helper method to get the top level cache directory.
+ */
+ private static String getWordListCacheDirectory(final Context context) {
+ return context.getFilesDir() + File.separator + "dicts";
+ }
+
+ /**
+ * Helper method to get the top level cache directory.
+ */
+ public static String getWordListStagingDirectory(final Context context) {
+ return context.getFilesDir() + File.separator + "staging";
+ }
+
+ /**
+ * Helper method to get the top level temp directory.
+ */
+ public static String getWordListTempDirectory(final Context context) {
+ return context.getFilesDir() + File.separator + "tmp";
+ }
+
+ /**
+ * Reverse escaping done by {@link #replaceFileNameDangerousCharacters(String)}.
+ */
+ @Nonnull
+ public static String getWordListIdFromFileName(@Nonnull final String fname) {
+ final StringBuilder sb = new StringBuilder();
+ final int fnameLength = fname.length();
+ for (int i = 0; i < fnameLength; i = fname.offsetByCodePoints(i, 1)) {
+ final int codePoint = fname.codePointAt(i);
+ if ('%' != codePoint) {
+ sb.appendCodePoint(codePoint);
+ } else {
+ // + 1 to pass the % sign
+ final int encodedCodePoint = Integer.parseInt(
+ fname.substring(i + 1, i + 1 + MAX_HEX_DIGITS_FOR_CODEPOINT), 16);
+ i += MAX_HEX_DIGITS_FOR_CODEPOINT;
+ sb.appendCodePoint(encodedCodePoint);
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Helper method to the list of cache directories, one for each distinct locale.
+ */
+ public static File[] getCachedDirectoryList(final Context context) {
+ return new File(DictionaryInfoUtils.getWordListCacheDirectory(context)).listFiles();
+ }
+
+ public static File[] getStagingDirectoryList(final Context context) {
+ return new File(DictionaryInfoUtils.getWordListStagingDirectory(context)).listFiles();
+ }
+
+ @Nullable
+ public static File[] getUnusedDictionaryList(final Context context) {
+ return context.getFilesDir().listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String filename) {
+ return !TextUtils.isEmpty(filename) && filename.endsWith(".dict")
+ && filename.contains(TEMP_DICT_FILE_SUB);
+ }
+ });
+ }
+
+ /**
+ * Returns the category for a given file name.
+ *
+ * This parses the file name, extracts the category, and returns it. See
+ * {@link #getMainDictId(Locale)} and {@link #isMainWordListId(String)}.
+ * @return The category as a string or null if it can't be found in the file name.
+ */
+ @Nullable
+ public static String getCategoryFromFileName(@Nonnull final String fileName) {
+ final String id = getWordListIdFromFileName(fileName);
+ final String[] idArray = id.split(BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR);
+ // An id is supposed to be in format category:locale, so splitting on the separator
+ // should yield a 2-elements array
+ if (2 != idArray.length) {
+ return null;
+ }
+ return idArray[0];
+ }
+
+ /**
+ * Find out the cache directory associated with a specific locale.
+ */
+ public static String getCacheDirectoryForLocale(final String locale, final Context context) {
+ final String relativeDirectoryName = replaceFileNameDangerousCharacters(locale);
+ final String absoluteDirectoryName = getWordListCacheDirectory(context) + File.separator
+ + relativeDirectoryName;
+ final File directory = new File(absoluteDirectoryName);
+ if (!directory.exists()) {
+ if (!directory.mkdirs()) {
+ Log.e(TAG, "Could not create the directory for locale" + locale);
+ }
+ }
+ return absoluteDirectoryName;
+ }
+
+ /**
+ * Generates a file name for the id and locale passed as an argument.
+ *
+ * In the current implementation the file name returned will always be unique for
+ * any id/locale pair, but please do not expect that the id can be the same for
+ * different dictionaries with different locales. An id should be unique for any
+ * dictionary.
+ * The file name is pretty much an URL-encoded version of the id inside a directory
+ * named like the locale, except it will also escape characters that look dangerous
+ * to some file systems.
+ * @param id the id of the dictionary for which to get a file name
+ * @param locale the locale for which to get the file name as a string
+ * @param context the context to use for getting the directory
+ * @return the name of the file to be created
+ */
+ public static String getCacheFileName(String id, String locale, Context context) {
+ final String fileName = replaceFileNameDangerousCharacters(id);
+ return getCacheDirectoryForLocale(locale, context) + File.separator + fileName;
+ }
+
+ public static String getStagingFileName(String id, String locale, Context context) {
+ final String stagingDirectory = getWordListStagingDirectory(context);
+ // create the directory if it does not exist.
+ final File directory = new File(stagingDirectory);
+ if (!directory.exists()) {
+ if (!directory.mkdirs()) {
+ Log.e(TAG, "Could not create the staging directory.");
+ }
+ }
+ // e.g. id="main:en_in", locale ="en_IN"
+ final String fileName = replaceFileNameDangerousCharacters(
+ locale + TEMP_DICT_FILE_SUB + id);
+ return stagingDirectory + File.separator + fileName;
+ }
+
+ public static void moveStagingFilesIfExists(Context context) {
+ final File[] stagingFiles = DictionaryInfoUtils.getStagingDirectoryList(context);
+ if (stagingFiles != null && stagingFiles.length > 0) {
+ for (final File stagingFile : stagingFiles) {
+ final String fileName = stagingFile.getName();
+ final int index = fileName.indexOf(TEMP_DICT_FILE_SUB);
+ if (index == -1) {
+ // This should never happen.
+ Log.e(TAG, "Staging file does not have ___ substring.");
+ continue;
+ }
+ final String[] localeAndFileId = fileName.split(TEMP_DICT_FILE_SUB);
+ if (localeAndFileId.length != 2) {
+ Log.e(TAG, String.format("malformed staging file %s. Deleting.",
+ stagingFile.getAbsoluteFile()));
+ stagingFile.delete();
+ continue;
+ }
+
+ final String locale = localeAndFileId[0];
+ // already escaped while moving to staging.
+ final String fileId = localeAndFileId[1];
+ final String cacheDirectoryForLocale = getCacheDirectoryForLocale(locale, context);
+ final String cacheFilename = cacheDirectoryForLocale + File.separator + fileId;
+ final File cacheFile = new File(cacheFilename);
+ // move the staging file to cache file.
+ if (!FileUtils.renameTo(stagingFile, cacheFile)) {
+ Log.e(TAG, String.format("Failed to rename from %s to %s.",
+ stagingFile.getAbsoluteFile(), cacheFile.getAbsoluteFile()));
+ }
+ }
+ }
+ }
+
+ public static boolean isMainWordListId(final String id) {
+ final String[] idArray = id.split(BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR);
+ // An id is supposed to be in format category:locale, so splitting on the separator
+ // should yield a 2-elements array
+ if (2 != idArray.length) {
+ return false;
+ }
+ return BinaryDictionaryGetter.MAIN_DICTIONARY_CATEGORY.equals(idArray[0]);
+ }
+
+ /**
+ * Find out whether a dictionary is available for this locale.
+ * @param context the context on which to check resources.
+ * @param locale the locale to check for.
+ * @return whether a (non-placeholder) dictionary is available or not.
+ */
+ public static boolean isDictionaryAvailable(final Context context, final Locale locale) {
+ final Resources res = context.getResources();
+ return 0 != getMainDictionaryResourceIdIfAvailableForLocale(res, locale);
+ }
+
+ /**
+ * Helper method to return a dictionary res id for a locale, or 0 if none.
+ * @param res resources for the app
+ * @param locale dictionary locale
+ * @return main dictionary resource id
+ */
+ public static int getMainDictionaryResourceIdIfAvailableForLocale(final Resources res,
+ final Locale locale) {
+ int resId;
+ // Try to find main_language_country dictionary.
+ if (!locale.getCountry().isEmpty()) {
+ final String dictLanguageCountry = MAIN_DICT_PREFIX
+ + locale.toString().toLowerCase(Locale.ROOT) + DECODER_DICT_SUFFIX;
+ if ((resId = res.getIdentifier(
+ dictLanguageCountry, "raw", RESOURCE_PACKAGE_NAME)) != 0) {
+ return resId;
+ }
+ }
+
+ // Try to find main_language dictionary.
+ final String dictLanguage = MAIN_DICT_PREFIX + locale.getLanguage() + DECODER_DICT_SUFFIX;
+ if ((resId = res.getIdentifier(dictLanguage, "raw", RESOURCE_PACKAGE_NAME)) != 0) {
+ return resId;
+ }
+
+ // Not found, return 0
+ return 0;
+ }
+
+ /**
+ * Returns a main dictionary resource id
+ * @param res resources for the app
+ * @param locale dictionary locale
+ * @return main dictionary resource id
+ */
+ public static int getMainDictionaryResourceId(final Resources res, final Locale locale) {
+ int resourceId = getMainDictionaryResourceIdIfAvailableForLocale(res, locale);
+ if (0 != resourceId) {
+ return resourceId;
+ }
+ return res.getIdentifier(DEFAULT_MAIN_DICT + DecoderSpecificConstants.DECODER_DICT_SUFFIX,
+ "raw", RESOURCE_PACKAGE_NAME);
+ }
+
+ /**
+ * Returns the id associated with the main word list for a specified locale.
+ *
+ * Word lists stored in Kelar Keyboard's resources are referred to as the "main"
+ * word lists. Since they can be updated like any other list, we need to assign a
+ * unique ID to them. This ID is just the name of the language (locale-wise) they
+ * are for, and this method returns this ID.
+ */
+ public static String getMainDictId(@Nonnull final Locale locale) {
+ // This works because we don't include by default different dictionaries for
+ // different countries. This actually needs to return the id that we would
+ // like to use for word lists included in resources, and the following is okay.
+ return BinaryDictionaryGetter.MAIN_DICTIONARY_CATEGORY +
+ BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR + locale.toString().toLowerCase();
+ }
+
+ public static DictionaryHeader getDictionaryFileHeaderOrNull(final File file,
+ final long offset, final long length) {
+ try {
+ final DictionaryHeader header =
+ BinaryDictionaryUtils.getHeaderWithOffsetAndLength(file, offset, length);
+ return header;
+ } catch (UnsupportedFormatException e) {
+ return null;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns information of the dictionary.
+ *
+ * @param fileAddress the asset dictionary file address.
+ * @param locale Locale for this file.
+ * @return information of the specified dictionary.
+ */
+ private static DictionaryInfo createDictionaryInfoFromFileAddress(
+ @Nonnull final AssetFileAddress fileAddress, final Locale locale) {
+ final String id = getMainDictId(locale);
+ final int version = DictionaryHeaderUtils.getContentVersion(fileAddress);
+ final String description = SubtypeLocaleUtils
+ .getSubtypeLocaleDisplayName(locale.toString());
+ // Do not store the filename on db as it will try to move the filename from db to the
+ // cached directory. If the filename is already in cached directory, this is not
+ // necessary.
+ final String filenameToStoreOnDb = null;
+ return new DictionaryInfo(id, locale, description, filenameToStoreOnDb,
+ fileAddress.mLength, new File(fileAddress.mFilename).lastModified(), version);
+ }
+
+ /**
+ * Returns the information of the dictionary for the given {@link AssetFileAddress}.
+ * If the file is corrupted or a pre-fava file, then the file gets deleted and the null
+ * value is returned.
+ */
+ @Nullable
+ private static DictionaryInfo createDictionaryInfoForUnCachedFile(
+ @Nonnull final AssetFileAddress fileAddress, final Locale locale) {
+ final String id = getMainDictId(locale);
+ final int version = DictionaryHeaderUtils.getContentVersion(fileAddress);
+
+ if (version == -1) {
+ // Purge the pre-fava/corrupted unused dictionaires.
+ fileAddress.deleteUnderlyingFile();
+ return null;
+ }
+
+ final String description = SubtypeLocaleUtils
+ .getSubtypeLocaleDisplayName(locale.toString());
+
+ final File unCachedFile = new File(fileAddress.mFilename);
+ // Store just the filename and not the full path.
+ final String filenameToStoreOnDb = unCachedFile.getName();
+ return new DictionaryInfo(id, locale, description, filenameToStoreOnDb, fileAddress.mLength,
+ unCachedFile.lastModified(), version);
+ }
+
+ /**
+ * Returns dictionary information for the given locale.
+ */
+ private static DictionaryInfo createDictionaryInfoFromLocale(Locale locale) {
+ final String id = getMainDictId(locale);
+ final int version = -1;
+ final String description = SubtypeLocaleUtils
+ .getSubtypeLocaleDisplayName(locale.toString());
+ return new DictionaryInfo(id, locale, description, null, 0L, 0L, version);
+ }
+
+ private static void addOrUpdateDictInfo(final ArrayList<DictionaryInfo> dictList,
+ final DictionaryInfo newElement) {
+ final Iterator<DictionaryInfo> iter = dictList.iterator();
+ while (iter.hasNext()) {
+ final DictionaryInfo thisDictInfo = iter.next();
+ if (thisDictInfo.mLocale.equals(newElement.mLocale)) {
+ if (newElement.mVersion <= thisDictInfo.mVersion) {
+ return;
+ }
+ iter.remove();
+ }
+ }
+ dictList.add(newElement);
+ }
+
+ public static ArrayList<DictionaryInfo> getCurrentDictionaryFileNameAndVersionInfo(
+ final Context context) {
+ final ArrayList<DictionaryInfo> dictList = new ArrayList<>();
+
+ // Retrieve downloaded dictionaries from cached directories
+ final File[] directoryList = getCachedDirectoryList(context);
+ if (null != directoryList) {
+ for (final File directory : directoryList) {
+ final String localeString = getWordListIdFromFileName(directory.getName());
+ final File[] dicts = BinaryDictionaryGetter.getCachedWordLists(
+ localeString, context);
+ for (final File dict : dicts) {
+ final String wordListId = getWordListIdFromFileName(dict.getName());
+ if (!DictionaryInfoUtils.isMainWordListId(wordListId)) {
+ continue;
+ }
+ final Locale locale = LocaleUtils.constructLocaleFromString(localeString);
+ final AssetFileAddress fileAddress = AssetFileAddress.makeFromFile(dict);
+ final DictionaryInfo dictionaryInfo =
+ createDictionaryInfoFromFileAddress(fileAddress, locale);
+ // Protect against cases of a less-specific dictionary being found, like an
+ // en dictionary being used for an en_US locale. In this case, the en dictionary
+ // should be used for en_US but discounted for listing purposes.
+ if (dictionaryInfo == null || !dictionaryInfo.mLocale.equals(locale)) {
+ continue;
+ }
+ addOrUpdateDictInfo(dictList, dictionaryInfo);
+ }
+ }
+ }
+
+ // Retrieve downloaded dictionaries from the unused dictionaries.
+ File[] unusedDictionaryList = getUnusedDictionaryList(context);
+ if (unusedDictionaryList != null) {
+ for (File dictionaryFile : unusedDictionaryList) {
+ String fileName = dictionaryFile.getName();
+ int index = fileName.indexOf(TEMP_DICT_FILE_SUB);
+ if (index == -1) {
+ continue;
+ }
+ String locale = fileName.substring(0, index);
+ DictionaryInfo dictionaryInfo = createDictionaryInfoForUnCachedFile(
+ AssetFileAddress.makeFromFile(dictionaryFile),
+ LocaleUtils.constructLocaleFromString(locale));
+ if (dictionaryInfo != null) {
+ addOrUpdateDictInfo(dictList, dictionaryInfo);
+ }
+ }
+ }
+
+ // Retrieve files from assets
+ final Resources resources = context.getResources();
+ final AssetManager assets = resources.getAssets();
+ for (final String localeString : assets.getLocales()) {
+ final Locale locale = LocaleUtils.constructLocaleFromString(localeString);
+ final int resourceId =
+ DictionaryInfoUtils.getMainDictionaryResourceIdIfAvailableForLocale(
+ context.getResources(), locale);
+ if (0 == resourceId) {
+ continue;
+ }
+ final AssetFileAddress fileAddress =
+ BinaryDictionaryGetter.loadFallbackResource(context, resourceId);
+ final DictionaryInfo dictionaryInfo = createDictionaryInfoFromFileAddress(fileAddress,
+ locale);
+ // Protect against cases of a less-specific dictionary being found, like an
+ // en dictionary being used for an en_US locale. In this case, the en dictionary
+ // should be used for en_US but discounted for listing purposes.
+ // TODO: Remove dictionaryInfo == null when the static LMs have the headers.
+ if (dictionaryInfo == null || !dictionaryInfo.mLocale.equals(locale)) {
+ continue;
+ }
+ addOrUpdateDictInfo(dictList, dictionaryInfo);
+ }
+
+ // Generate the dictionary information from the enabled subtypes. This will not
+ // overwrite the real records.
+ RichInputMethodManager.init(context);
+ List<InputMethodSubtype> enabledSubtypes = RichInputMethodManager
+ .getInstance().getMyEnabledInputMethodSubtypeList(true);
+ for (InputMethodSubtype subtype : enabledSubtypes) {
+ Locale locale = LocaleUtils.constructLocaleFromString(subtype.getLocale());
+ DictionaryInfo dictionaryInfo = createDictionaryInfoFromLocale(locale);
+ addOrUpdateDictInfo(dictList, dictionaryInfo);
+ }
+
+ return dictList;
+ }
+
+ @UsedForTesting
+ public static boolean looksValidForDictionaryInsertion(final CharSequence text,
+ final SpacingAndPunctuations spacingAndPunctuations) {
+ if (TextUtils.isEmpty(text)) {
+ return false;
+ }
+ final int length = text.length();
+ if (length > DecoderSpecificConstants.DICTIONARY_MAX_WORD_LENGTH) {
+ return false;
+ }
+ int i = 0;
+ int digitCount = 0;
+ while (i < length) {
+ final int codePoint = Character.codePointAt(text, i);
+ final int charCount = Character.charCount(codePoint);
+ i += charCount;
+ if (Character.isDigit(codePoint)) {
+ // Count digits: see below
+ digitCount += charCount;
+ continue;
+ }
+ if (!spacingAndPunctuations.isWordCodePoint(codePoint)) {
+ return false;
+ }
+ }
+ // We reject strings entirely comprised of digits to avoid using PIN codes or credit
+ // card numbers. It would come in handy for word prediction though; a good example is
+ // when writing one's address where the street number is usually quite discriminative,
+ // as well as the postal code.
+ return digitCount < length;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/ExecutorUtils.java b/java/src/org/kelar/inputmethod/latin/utils/ExecutorUtils.java
new file mode 100644
index 000000000..2432febdd
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/ExecutorUtils.java
@@ -0,0 +1,152 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.util.Log;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Utilities to manage executors.
+ */
+public class ExecutorUtils {
+
+ private static final String TAG = "ExecutorUtils";
+
+ public static final String KEYBOARD = "Keyboard";
+ public static final String SPELLING = "Spelling";
+
+ private static ScheduledExecutorService sKeyboardExecutorService = newExecutorService(KEYBOARD);
+ private static ScheduledExecutorService sSpellingExecutorService = newExecutorService(SPELLING);
+
+ private static ScheduledExecutorService newExecutorService(final String name) {
+ return Executors.newSingleThreadScheduledExecutor(new ExecutorFactory(name));
+ }
+
+ private static class ExecutorFactory implements ThreadFactory {
+ private final String mName;
+
+ private ExecutorFactory(final String name) {
+ mName = name;
+ }
+
+ @Override
+ public Thread newThread(final Runnable runnable) {
+ Thread thread = new Thread(runnable, TAG);
+ thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
+ @Override
+ public void uncaughtException(Thread thread, Throwable ex) {
+ Log.w(mName + "-" + runnable.getClass().getSimpleName(), ex);
+ }
+ });
+ return thread;
+ }
+ }
+
+ @UsedForTesting
+ private static ScheduledExecutorService sExecutorServiceForTests;
+
+ @UsedForTesting
+ public static void setExecutorServiceForTests(
+ final ScheduledExecutorService executorServiceForTests) {
+ sExecutorServiceForTests = executorServiceForTests;
+ }
+
+ //
+ // Public methods used to schedule a runnable for execution.
+ //
+
+ /**
+ * @param name Executor's name.
+ * @return scheduled executor service used to run background tasks
+ */
+ public static ScheduledExecutorService getBackgroundExecutor(final String name) {
+ if (sExecutorServiceForTests != null) {
+ return sExecutorServiceForTests;
+ }
+ switch (name) {
+ case KEYBOARD:
+ return sKeyboardExecutorService;
+ case SPELLING:
+ return sSpellingExecutorService;
+ default:
+ throw new IllegalArgumentException("Invalid executor: " + name);
+ }
+ }
+
+ public static void killTasks(final String name) {
+ final ScheduledExecutorService executorService = getBackgroundExecutor(name);
+ executorService.shutdownNow();
+ try {
+ executorService.awaitTermination(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Log.wtf(TAG, "Failed to shut down: " + name);
+ }
+ if (executorService == sExecutorServiceForTests) {
+ // Don't do anything to the test service.
+ return;
+ }
+ switch (name) {
+ case KEYBOARD:
+ sKeyboardExecutorService = newExecutorService(KEYBOARD);
+ break;
+ case SPELLING:
+ sSpellingExecutorService = newExecutorService(SPELLING);
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid executor: " + name);
+ }
+ }
+
+ @UsedForTesting
+ public static Runnable chain(final Runnable... runnables) {
+ return new RunnableChain(runnables);
+ }
+
+ @UsedForTesting
+ public static class RunnableChain implements Runnable {
+ private final Runnable[] mRunnables;
+
+ private RunnableChain(final Runnable... runnables) {
+ if (runnables == null || runnables.length == 0) {
+ throw new IllegalArgumentException("Attempting to construct an empty chain");
+ }
+ mRunnables = runnables;
+ }
+
+ @UsedForTesting
+ public Runnable[] getRunnables() {
+ return mRunnables;
+ }
+
+ @Override
+ public void run() {
+ for (Runnable runnable : mRunnables) {
+ if (Thread.interrupted()) {
+ return;
+ }
+ runnable.run();
+ }
+ }
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/FeedbackUtils.java b/java/src/org/kelar/inputmethod/latin/utils/FeedbackUtils.java
new file mode 100644
index 000000000..72308c85f
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/FeedbackUtils.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.Context;
+import android.content.Intent;
+
+@SuppressWarnings("unused")
+public class FeedbackUtils {
+ public static boolean isHelpAndFeedbackFormSupported() {
+ return false;
+ }
+
+ public static void showHelpAndFeedbackForm(Context context) {
+ }
+
+ public static int getAboutKeyboardTitleResId() {
+ return 0;
+ }
+
+ public static Intent getAboutKeyboardIntent(Context context) {
+ return null;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/FileTransforms.java b/java/src/org/kelar/inputmethod/latin/utils/FileTransforms.java
new file mode 100644
index 000000000..5f918410d
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/FileTransforms.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2011 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 org.kelar.inputmethod.latin.utils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.zip.GZIPInputStream;
+
+public final class FileTransforms {
+ public static OutputStream getCryptedStream(OutputStream out) {
+ // Crypt the stream.
+ return out;
+ }
+
+ public static InputStream getDecryptedStream(InputStream in) {
+ // Decrypt the stream.
+ return in;
+ }
+
+ public static InputStream getUncompressedStream(InputStream in) throws IOException {
+ return new GZIPInputStream(in);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/FragmentUtils.java b/java/src/org/kelar/inputmethod/latin/utils/FragmentUtils.java
new file mode 100644
index 000000000..f015c7f73
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/FragmentUtils.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.dictionarypack.DictionarySettingsFragment;
+import org.kelar.inputmethod.latin.about.AboutPreferences;
+import org.kelar.inputmethod.latin.settings.AccountsSettingsFragment;
+import org.kelar.inputmethod.latin.settings.AdvancedSettingsFragment;
+import org.kelar.inputmethod.latin.settings.AppearanceSettingsFragment;
+import org.kelar.inputmethod.latin.settings.CorrectionSettingsFragment;
+import org.kelar.inputmethod.latin.settings.CustomInputStyleSettingsFragment;
+import org.kelar.inputmethod.latin.settings.DebugSettingsFragment;
+import org.kelar.inputmethod.latin.settings.GestureSettingsFragment;
+import org.kelar.inputmethod.latin.settings.PreferencesSettingsFragment;
+import org.kelar.inputmethod.latin.settings.SettingsFragment;
+import org.kelar.inputmethod.latin.settings.ThemeSettingsFragment;
+import org.kelar.inputmethod.latin.spellcheck.SpellCheckerSettingsFragment;
+import org.kelar.inputmethod.latin.userdictionary.UserDictionaryAddWordFragment;
+import org.kelar.inputmethod.latin.userdictionary.UserDictionaryList;
+import org.kelar.inputmethod.latin.userdictionary.UserDictionaryLocalePicker;
+import org.kelar.inputmethod.latin.userdictionary.UserDictionarySettings;
+
+import java.util.HashSet;
+
+public class FragmentUtils {
+ private static final HashSet<String> sLatinImeFragments = new HashSet<>();
+ static {
+ sLatinImeFragments.add(DictionarySettingsFragment.class.getName());
+ sLatinImeFragments.add(AboutPreferences.class.getName());
+ sLatinImeFragments.add(PreferencesSettingsFragment.class.getName());
+ sLatinImeFragments.add(AccountsSettingsFragment.class.getName());
+ sLatinImeFragments.add(AppearanceSettingsFragment.class.getName());
+ sLatinImeFragments.add(ThemeSettingsFragment.class.getName());
+ sLatinImeFragments.add(CustomInputStyleSettingsFragment.class.getName());
+ sLatinImeFragments.add(GestureSettingsFragment.class.getName());
+ sLatinImeFragments.add(CorrectionSettingsFragment.class.getName());
+ sLatinImeFragments.add(AdvancedSettingsFragment.class.getName());
+ sLatinImeFragments.add(DebugSettingsFragment.class.getName());
+ sLatinImeFragments.add(SettingsFragment.class.getName());
+ sLatinImeFragments.add(SpellCheckerSettingsFragment.class.getName());
+ sLatinImeFragments.add(UserDictionaryAddWordFragment.class.getName());
+ sLatinImeFragments.add(UserDictionaryList.class.getName());
+ sLatinImeFragments.add(UserDictionaryLocalePicker.class.getName());
+ sLatinImeFragments.add(UserDictionarySettings.class.getName());
+ }
+
+ public static boolean isValidFragment(String fragmentName) {
+ return sLatinImeFragments.contains(fragmentName);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/ImportantNoticeUtils.java b/java/src/org/kelar/inputmethod/latin/utils/ImportantNoticeUtils.java
new file mode 100644
index 000000000..d006cd3d5
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/ImportantNoticeUtils.java
@@ -0,0 +1,140 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.provider.Settings;
+import android.provider.Settings.SettingNotFoundException;
+import android.text.TextUtils;
+import android.util.Log;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+import org.kelar.inputmethod.latin.R;
+import org.kelar.inputmethod.latin.permissions.PermissionsUtil;
+import org.kelar.inputmethod.latin.settings.SettingsValues;
+
+import java.util.concurrent.TimeUnit;
+
+public final class ImportantNoticeUtils {
+ private static final String TAG = ImportantNoticeUtils.class.getSimpleName();
+
+ // {@link SharedPreferences} name to save the last important notice version that has been
+ // displayed to users.
+ private static final String PREFERENCE_NAME = "important_notice_pref";
+
+ private static final String KEY_SUGGEST_CONTACTS_NOTICE = "important_notice_suggest_contacts";
+
+ @UsedForTesting
+ static final String KEY_TIMESTAMP_OF_CONTACTS_NOTICE = "timestamp_of_suggest_contacts_notice";
+
+ @UsedForTesting
+ static final long TIMEOUT_OF_IMPORTANT_NOTICE = TimeUnit.HOURS.toMillis(23);
+
+ // Copy of the hidden {@link Settings.Secure#USER_SETUP_COMPLETE} settings key.
+ // The value is zero until each multiuser completes system setup wizard.
+ // Caveat: This is a hidden API.
+ private static final String Settings_Secure_USER_SETUP_COMPLETE = "user_setup_complete";
+ private static final int USER_SETUP_IS_NOT_COMPLETE = 0;
+
+ private ImportantNoticeUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ @UsedForTesting
+ static boolean isInSystemSetupWizard(final Context context) {
+ try {
+ final int userSetupComplete = Settings.Secure.getInt(
+ context.getContentResolver(), Settings_Secure_USER_SETUP_COMPLETE);
+ return userSetupComplete == USER_SETUP_IS_NOT_COMPLETE;
+ } catch (final SettingNotFoundException e) {
+ Log.w(TAG, "Can't find settings in Settings.Secure: key="
+ + Settings_Secure_USER_SETUP_COMPLETE);
+ return false;
+ }
+ }
+
+ @UsedForTesting
+ static SharedPreferences getImportantNoticePreferences(final Context context) {
+ return context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
+ }
+
+ @UsedForTesting
+ static boolean hasContactsNoticeShown(final Context context) {
+ return getImportantNoticePreferences(context).getBoolean(
+ KEY_SUGGEST_CONTACTS_NOTICE, false);
+ }
+
+ public static boolean shouldShowImportantNotice(final Context context,
+ final SettingsValues settingsValues) {
+ // Check to see whether "Use Contacts" is enabled by the user.
+ if (!settingsValues.mUseContactsDict) {
+ return false;
+ }
+
+ if (hasContactsNoticeShown(context)) {
+ return false;
+ }
+
+ // Don't show the dialog if we have all the permissions.
+ if (PermissionsUtil.checkAllPermissionsGranted(
+ context, Manifest.permission.READ_CONTACTS)) {
+ return false;
+ }
+
+ final String importantNoticeTitle = getSuggestContactsNoticeTitle(context);
+ if (TextUtils.isEmpty(importantNoticeTitle)) {
+ return false;
+ }
+ if (isInSystemSetupWizard(context)) {
+ return false;
+ }
+ if (hasContactsNoticeTimeoutPassed(context, System.currentTimeMillis())) {
+ updateContactsNoticeShown(context);
+ return false;
+ }
+ return true;
+ }
+
+ public static String getSuggestContactsNoticeTitle(final Context context) {
+ return context.getResources().getString(R.string.important_notice_suggest_contact_names);
+ }
+
+ @UsedForTesting
+ static boolean hasContactsNoticeTimeoutPassed(
+ final Context context, final long currentTimeInMillis) {
+ final SharedPreferences prefs = getImportantNoticePreferences(context);
+ if (!prefs.contains(KEY_TIMESTAMP_OF_CONTACTS_NOTICE)) {
+ prefs.edit()
+ .putLong(KEY_TIMESTAMP_OF_CONTACTS_NOTICE, currentTimeInMillis)
+ .apply();
+ }
+ final long firstDisplayTimeInMillis = prefs.getLong(
+ KEY_TIMESTAMP_OF_CONTACTS_NOTICE, currentTimeInMillis);
+ final long elapsedTime = currentTimeInMillis - firstDisplayTimeInMillis;
+ return elapsedTime >= TIMEOUT_OF_IMPORTANT_NOTICE;
+ }
+
+ public static void updateContactsNoticeShown(final Context context) {
+ getImportantNoticePreferences(context)
+ .edit()
+ .putBoolean(KEY_SUGGEST_CONTACTS_NOTICE, true)
+ .remove(KEY_TIMESTAMP_OF_CONTACTS_NOTICE)
+ .apply();
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/InputTypeUtils.java b/java/src/org/kelar/inputmethod/latin/utils/InputTypeUtils.java
new file mode 100644
index 000000000..3a4bae78c
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/InputTypeUtils.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2012 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 org.kelar.inputmethod.latin.utils;
+
+import android.text.InputType;
+import android.view.inputmethod.EditorInfo;
+
+public final class InputTypeUtils implements InputType {
+ private static final int WEB_TEXT_PASSWORD_INPUT_TYPE =
+ TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_PASSWORD;
+ private static final int WEB_TEXT_EMAIL_ADDRESS_INPUT_TYPE =
+ TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS;
+ private static final int NUMBER_PASSWORD_INPUT_TYPE =
+ TYPE_CLASS_NUMBER | TYPE_NUMBER_VARIATION_PASSWORD;
+ private static final int TEXT_PASSWORD_INPUT_TYPE =
+ TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PASSWORD;
+ private static final int TEXT_VISIBLE_PASSWORD_INPUT_TYPE =
+ TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
+ private static final int[] SUPPRESSING_AUTO_SPACES_FIELD_VARIATION = {
+ InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS,
+ InputType.TYPE_TEXT_VARIATION_PASSWORD,
+ InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD,
+ InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD };
+ public static final int IME_ACTION_CUSTOM_LABEL = EditorInfo.IME_MASK_ACTION + 1;
+
+ private InputTypeUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ private static boolean isWebEditTextInputType(final int inputType) {
+ return inputType == (TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_EDIT_TEXT);
+ }
+
+ private static boolean isWebPasswordInputType(final int inputType) {
+ return WEB_TEXT_PASSWORD_INPUT_TYPE != 0
+ && inputType == WEB_TEXT_PASSWORD_INPUT_TYPE;
+ }
+
+ private static boolean isWebEmailAddressInputType(final int inputType) {
+ return WEB_TEXT_EMAIL_ADDRESS_INPUT_TYPE != 0
+ && inputType == WEB_TEXT_EMAIL_ADDRESS_INPUT_TYPE;
+ }
+
+ private static boolean isNumberPasswordInputType(final int inputType) {
+ return NUMBER_PASSWORD_INPUT_TYPE != 0
+ && inputType == NUMBER_PASSWORD_INPUT_TYPE;
+ }
+
+ private static boolean isTextPasswordInputType(final int inputType) {
+ return inputType == TEXT_PASSWORD_INPUT_TYPE;
+ }
+
+ private static boolean isWebEmailAddressVariation(int variation) {
+ return variation == TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS;
+ }
+
+ public static boolean isEmailVariation(final int variation) {
+ return variation == TYPE_TEXT_VARIATION_EMAIL_ADDRESS
+ || isWebEmailAddressVariation(variation);
+ }
+
+ public static boolean isWebInputType(final int inputType) {
+ final int maskedInputType =
+ inputType & (TYPE_MASK_CLASS | TYPE_MASK_VARIATION);
+ return isWebEditTextInputType(maskedInputType) || isWebPasswordInputType(maskedInputType)
+ || isWebEmailAddressInputType(maskedInputType);
+ }
+
+ // Please refer to TextView.isPasswordInputType
+ public static boolean isPasswordInputType(final int inputType) {
+ final int maskedInputType =
+ inputType & (TYPE_MASK_CLASS | TYPE_MASK_VARIATION);
+ return isTextPasswordInputType(maskedInputType) || isWebPasswordInputType(maskedInputType)
+ || isNumberPasswordInputType(maskedInputType);
+ }
+
+ // Please refer to TextView.isVisiblePasswordInputType
+ public static boolean isVisiblePasswordInputType(final int inputType) {
+ final int maskedInputType =
+ inputType & (TYPE_MASK_CLASS | TYPE_MASK_VARIATION);
+ return maskedInputType == TEXT_VISIBLE_PASSWORD_INPUT_TYPE;
+ }
+
+ public static boolean isAutoSpaceFriendlyType(final int inputType) {
+ if (TYPE_CLASS_TEXT != (TYPE_MASK_CLASS & inputType)) return false;
+ final int variation = TYPE_MASK_VARIATION & inputType;
+ for (final int fieldVariation : SUPPRESSING_AUTO_SPACES_FIELD_VARIATION) {
+ if (variation == fieldVariation) return false;
+ }
+ return true;
+ }
+
+ public static int getImeOptionsActionIdFromEditorInfo(final EditorInfo editorInfo) {
+ if ((editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
+ return EditorInfo.IME_ACTION_NONE;
+ } else if (editorInfo.actionLabel != null) {
+ return IME_ACTION_CUSTOM_LABEL;
+ } else {
+ // Note: this is different from editorInfo.actionId, hence "ImeOptionsActionId"
+ return editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
+ }
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/IntentUtils.java b/java/src/org/kelar/inputmethod/latin/utils/IntentUtils.java
new file mode 100644
index 000000000..48e4b69e5
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/IntentUtils.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.Intent;
+import android.text.TextUtils;
+
+public final class IntentUtils {
+ private static final String EXTRA_INPUT_METHOD_ID = "input_method_id";
+ // TODO: Can these be constants instead of literal String constants?
+ private static final String INPUT_METHOD_SUBTYPE_SETTINGS =
+ "android.settings.INPUT_METHOD_SUBTYPE_SETTINGS";
+
+ private IntentUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static Intent getInputLanguageSelectionIntent(final String inputMethodId,
+ final int flagsForSubtypeSettings) {
+ // Refer to android.provider.Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS
+ final String action = INPUT_METHOD_SUBTYPE_SETTINGS;
+ final Intent intent = new Intent(action);
+ if (!TextUtils.isEmpty(inputMethodId)) {
+ intent.putExtra(EXTRA_INPUT_METHOD_ID, inputMethodId);
+ }
+ if (flagsForSubtypeSettings > 0) {
+ intent.setFlags(flagsForSubtypeSettings);
+ }
+ return intent;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/JniUtils.java b/java/src/org/kelar/inputmethod/latin/utils/JniUtils.java
new file mode 100644
index 000000000..c7506ca7b
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/JniUtils.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2012 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 org.kelar.inputmethod.latin.utils;
+
+import android.util.Log;
+
+import org.kelar.inputmethod.latin.define.JniLibName;
+
+public final class JniUtils {
+ private static final String TAG = JniUtils.class.getSimpleName();
+
+ static {
+ try {
+ System.loadLibrary(JniLibName.JNI_LIB_NAME);
+ } catch (UnsatisfiedLinkError ule) {
+ Log.e(TAG, "Could not load native library " + JniLibName.JNI_LIB_NAME, ule);
+ }
+ }
+
+ private JniUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static void loadNativeLibrary() {
+ // Ensures the static initializer is called
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/JsonUtils.java b/java/src/org/kelar/inputmethod/latin/utils/JsonUtils.java
new file mode 100644
index 000000000..7a2d2d92f
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/JsonUtils.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.util.JsonReader;
+import android.util.JsonWriter;
+import android.util.Log;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public final class JsonUtils {
+ private static final String TAG = JsonUtils.class.getSimpleName();
+
+ private static final String INTEGER_CLASS_NAME = Integer.class.getSimpleName();
+ private static final String STRING_CLASS_NAME = String.class.getSimpleName();
+
+ private static final String EMPTY_STRING = "";
+
+ public static List<Object> jsonStrToList(final String s) {
+ final ArrayList<Object> list = new ArrayList<>();
+ final JsonReader reader = new JsonReader(new StringReader(s));
+ try {
+ reader.beginArray();
+ while (reader.hasNext()) {
+ reader.beginObject();
+ while (reader.hasNext()) {
+ final String name = reader.nextName();
+ if (name.equals(INTEGER_CLASS_NAME)) {
+ list.add(reader.nextInt());
+ } else if (name.equals(STRING_CLASS_NAME)) {
+ list.add(reader.nextString());
+ } else {
+ Log.w(TAG, "Invalid name: " + name);
+ reader.skipValue();
+ }
+ }
+ reader.endObject();
+ }
+ reader.endArray();
+ return list;
+ } catch (final IOException e) {
+ } finally {
+ close(reader);
+ }
+ return Collections.<Object>emptyList();
+ }
+
+ public static String listToJsonStr(final List<Object> list) {
+ if (list == null || list.isEmpty()) {
+ return EMPTY_STRING;
+ }
+ final StringWriter sw = new StringWriter();
+ final JsonWriter writer = new JsonWriter(sw);
+ try {
+ writer.beginArray();
+ for (final Object o : list) {
+ writer.beginObject();
+ if (o instanceof Integer) {
+ writer.name(INTEGER_CLASS_NAME).value((Integer)o);
+ } else if (o instanceof String) {
+ writer.name(STRING_CLASS_NAME).value((String)o);
+ }
+ writer.endObject();
+ }
+ writer.endArray();
+ return sw.toString();
+ } catch (final IOException e) {
+ } finally {
+ close(writer);
+ }
+ return EMPTY_STRING;
+ }
+
+ private static void close(final Closeable closeable) {
+ try {
+ if (closeable != null) {
+ closeable.close();
+ }
+ } catch (final IOException e) {
+ // Ignore
+ }
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/LanguageOnSpacebarUtils.java b/java/src/org/kelar/inputmethod/latin/utils/LanguageOnSpacebarUtils.java
new file mode 100644
index 000000000..2bcfc82b8
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/LanguageOnSpacebarUtils.java
@@ -0,0 +1,92 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.view.inputmethod.InputMethodSubtype;
+
+import org.kelar.inputmethod.latin.RichInputMethodSubtype;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+
+import javax.annotation.Nonnull;
+
+/**
+ * This class determines that the language name on the spacebar should be displayed in what format.
+ */
+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;
+
+ private static List<InputMethodSubtype> sEnabledSubtypes = Collections.emptyList();
+ private static boolean sIsSystemLanguageSameAsInputLanguage;
+
+ 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 (sEnabledSubtypes.size() < 2 && sIsSystemLanguageSameAsInputLanguage) {
+ return FORMAT_TYPE_NONE;
+ }
+ final Locale locale = subtype.getLocale();
+ if (locale == null) {
+ return FORMAT_TYPE_NONE;
+ }
+ final String keyboardLanguage = locale.getLanguage();
+ final String keyboardLayout = subtype.getKeyboardLayoutSetName();
+ int sameLanguageAndLayoutCount = 0;
+ for (final InputMethodSubtype ims : sEnabledSubtypes) {
+ final String language = SubtypeLocaleUtils.getSubtypeLocale(ims).getLanguage();
+ if (keyboardLanguage.equals(language) && keyboardLayout.equals(
+ SubtypeLocaleUtils.getKeyboardLayoutSetName(ims))) {
+ sameLanguageAndLayoutCount++;
+ }
+ }
+ // Display full locale name only when there are multiple subtypes that have the same
+ // locale and keyboard layout. Otherwise displaying language name is enough.
+ return sameLanguageAndLayoutCount > 1 ? FORMAT_TYPE_FULL_LOCALE
+ : FORMAT_TYPE_LANGUAGE_ONLY;
+ }
+
+ public static void setEnabledSubtypes(@Nonnull final List<InputMethodSubtype> enabledSubtypes) {
+ sEnabledSubtypes = enabledSubtypes;
+ }
+
+ public static void onSubtypeChanged(@Nonnull final RichInputMethodSubtype subtype,
+ final boolean implicitlyEnabledSubtype, @Nonnull final Locale systemLocale) {
+ final Locale newLocale = subtype.getLocale();
+ if (systemLocale.equals(newLocale)) {
+ sIsSystemLanguageSameAsInputLanguage = true;
+ return;
+ }
+ if (!systemLocale.getLanguage().equals(newLocale.getLanguage())) {
+ 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.
+ sIsSystemLanguageSameAsInputLanguage = implicitlyEnabledSubtype;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/LeakGuardHandlerWrapper.java b/java/src/org/kelar/inputmethod/latin/utils/LeakGuardHandlerWrapper.java
new file mode 100644
index 000000000..37f7c3023
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/LeakGuardHandlerWrapper.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2011 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 org.kelar.inputmethod.latin.utils;
+
+import android.os.Handler;
+import android.os.Looper;
+
+import java.lang.ref.WeakReference;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+public class LeakGuardHandlerWrapper<T> extends Handler {
+ private final WeakReference<T> mOwnerInstanceRef;
+
+ public LeakGuardHandlerWrapper(@Nonnull final T ownerInstance) {
+ this(ownerInstance, Looper.myLooper());
+ }
+
+ public LeakGuardHandlerWrapper(@Nonnull final T ownerInstance, final Looper looper) {
+ super(looper);
+ mOwnerInstanceRef = new WeakReference<>(ownerInstance);
+ }
+
+ @Nullable
+ public T getOwnerInstance() {
+ return mOwnerInstanceRef.get();
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/ManagedProfileUtils.java b/java/src/org/kelar/inputmethod/latin/utils/ManagedProfileUtils.java
new file mode 100644
index 000000000..f0eb90ad6
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/ManagedProfileUtils.java
@@ -0,0 +1,43 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.Context;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+
+public class ManagedProfileUtils {
+ private static ManagedProfileUtils INSTANCE = new ManagedProfileUtils();
+ private static ManagedProfileUtils sTestInstance;
+
+ private ManagedProfileUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ @UsedForTesting
+ public static void setTestInstance(final ManagedProfileUtils testInstance) {
+ sTestInstance = testInstance;
+ }
+
+ public static ManagedProfileUtils getInstance() {
+ return sTestInstance == null ? INSTANCE : sTestInstance;
+ }
+
+ public boolean hasWorkProfile(final Context context) {
+ return false;
+ }
+} \ No newline at end of file
diff --git a/java/src/org/kelar/inputmethod/latin/utils/MetadataFileUriGetter.java b/java/src/org/kelar/inputmethod/latin/utils/MetadataFileUriGetter.java
new file mode 100644
index 000000000..ae3108747
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/MetadataFileUriGetter.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.latin.R;
+
+import android.content.Context;
+
+/**
+ * Helper class to get the metadata URI and the additional ID.
+ */
+@SuppressWarnings("unused")
+public class MetadataFileUriGetter {
+ private MetadataFileUriGetter() {
+ // This helper class is not instantiable.
+ }
+
+ public static String getMetadataUri(final Context context) {
+ return context.getString(R.string.dictionary_pack_metadata_uri);
+ }
+
+ public static String getMetadataAdditionalId(final Context context) {
+ return "";
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/NgramContextUtils.java b/java/src/org/kelar/inputmethod/latin/utils/NgramContextUtils.java
new file mode 100644
index 000000000..6f8437b06
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/NgramContextUtils.java
@@ -0,0 +1,113 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.latin.NgramContext;
+import org.kelar.inputmethod.latin.NgramContext.WordInfo;
+import org.kelar.inputmethod.latin.define.DecoderSpecificConstants;
+import org.kelar.inputmethod.latin.settings.SpacingAndPunctuations;
+
+import java.util.Arrays;
+import java.util.regex.Pattern;
+
+import javax.annotation.Nonnull;
+
+public final class NgramContextUtils {
+ private NgramContextUtils() {
+ // Intentional empty constructor for utility class.
+ }
+
+ private static final Pattern NEWLINE_REGEX = Pattern.compile("[\\r\\n]+");
+ 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 NgramContext. 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
+ @Nonnull
+ public static NgramContext getNgramContextFromNthPreviousWord(final CharSequence prev,
+ final SpacingAndPunctuations spacingAndPunctuations, final int n) {
+ if (prev == null) return NgramContext.EMPTY_PREV_WORDS_INFO;
+ final String[] lines = NEWLINE_REGEX.split(prev);
+ if (lines.length == 0) {
+ return new NgramContext(WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO);
+ }
+ final String[] w = SPACE_REGEX.split(lines[lines.length - 1]);
+ final WordInfo[] prevWordsInfo =
+ new WordInfo[DecoderSpecificConstants.MAX_PREV_WORD_COUNT_FOR_N_GRAM];
+ Arrays.fill(prevWordsInfo, WordInfo.EMPTY_WORD_INFO);
+ 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.
+ break;
+ }
+ }
+ }
+ // If we can't find (n + i) words, the context is beginning-of-sentence.
+ if (focusedWordIndex < 0) {
+ prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO;
+ 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_WORD_INFO;
+ break;
+ }
+ // If the word ends in a sentence terminator, the context is beginning-of-sentence.
+ final char lastChar = focusedWord.charAt(length - 1);
+ if (spacingAndPunctuations.isSentenceTerminator(lastChar)) {
+ prevWordsInfo[i] = WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO;
+ 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)) {
+ break;
+ }
+ prevWordsInfo[i] = new WordInfo(focusedWord);
+ }
+ return new NgramContext(prevWordsInfo);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/RecapitalizeStatus.java b/java/src/org/kelar/inputmethod/latin/utils/RecapitalizeStatus.java
new file mode 100644
index 000000000..438b9871a
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/RecapitalizeStatus.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.latin.common.StringUtils;
+
+import java.util.Locale;
+
+/**
+ * The status of the current recapitalize process.
+ */
+public class RecapitalizeStatus {
+ public static final int NOT_A_RECAPITALIZE_MODE = -1;
+ public static final int CAPS_MODE_ORIGINAL_MIXED_CASE = 0;
+ public static final int CAPS_MODE_ALL_LOWER = 1;
+ public static final int CAPS_MODE_FIRST_WORD_UPPER = 2;
+ public static final int CAPS_MODE_ALL_UPPER = 3;
+ // When adding a new mode, don't forget to update the CAPS_MODE_LAST constant.
+ public static final int CAPS_MODE_LAST = CAPS_MODE_ALL_UPPER;
+
+ private static final int[] ROTATION_STYLE = {
+ CAPS_MODE_ORIGINAL_MIXED_CASE,
+ CAPS_MODE_ALL_LOWER,
+ CAPS_MODE_FIRST_WORD_UPPER,
+ CAPS_MODE_ALL_UPPER
+ };
+
+ private static final int getStringMode(final String string, final int[] sortedSeparators) {
+ if (StringUtils.isIdenticalAfterUpcase(string)) {
+ return CAPS_MODE_ALL_UPPER;
+ } else if (StringUtils.isIdenticalAfterDowncase(string)) {
+ return CAPS_MODE_ALL_LOWER;
+ } else if (StringUtils.isIdenticalAfterCapitalizeEachWord(string, sortedSeparators)) {
+ return CAPS_MODE_FIRST_WORD_UPPER;
+ } else {
+ return CAPS_MODE_ORIGINAL_MIXED_CASE;
+ }
+ }
+
+ public static String modeToString(final int recapitalizeMode) {
+ switch (recapitalizeMode) {
+ case NOT_A_RECAPITALIZE_MODE: return "undefined";
+ case CAPS_MODE_ORIGINAL_MIXED_CASE: return "mixedCase";
+ case CAPS_MODE_ALL_LOWER: return "allLower";
+ case CAPS_MODE_FIRST_WORD_UPPER: return "firstWordUpper";
+ case CAPS_MODE_ALL_UPPER: return "allUpper";
+ default: return "unknown<" + recapitalizeMode + ">";
+ }
+ }
+
+ /**
+ * We store the location of the cursor and the string that was there before the recapitalize
+ * action was done, and the location of the cursor and the string that was there after.
+ */
+ private int mCursorStartBefore;
+ private String mStringBefore;
+ private int mCursorStartAfter;
+ private int mCursorEndAfter;
+ private int mRotationStyleCurrentIndex;
+ private boolean mSkipOriginalMixedCaseMode;
+ private Locale mLocale;
+ private int[] mSortedSeparators;
+ private String mStringAfter;
+ private boolean mIsStarted;
+ private boolean mIsEnabled = true;
+
+ private static final int[] EMPTY_STORTED_SEPARATORS = {};
+
+ public RecapitalizeStatus() {
+ // By default, initialize with fake values that won't match any real recapitalize.
+ start(-1, -1, "", Locale.getDefault(), EMPTY_STORTED_SEPARATORS);
+ stop();
+ }
+
+ public void start(final int cursorStart, final int cursorEnd, final String string,
+ final Locale locale, final int[] sortedSeparators) {
+ if (!mIsEnabled) {
+ return;
+ }
+ mCursorStartBefore = cursorStart;
+ mStringBefore = string;
+ mCursorStartAfter = cursorStart;
+ mCursorEndAfter = cursorEnd;
+ mStringAfter = string;
+ final int initialMode = getStringMode(mStringBefore, sortedSeparators);
+ mLocale = locale;
+ mSortedSeparators = sortedSeparators;
+ if (CAPS_MODE_ORIGINAL_MIXED_CASE == initialMode) {
+ mRotationStyleCurrentIndex = 0;
+ mSkipOriginalMixedCaseMode = false;
+ } else {
+ // Find the current mode in the array.
+ int currentMode;
+ for (currentMode = ROTATION_STYLE.length - 1; currentMode > 0; --currentMode) {
+ if (ROTATION_STYLE[currentMode] == initialMode) {
+ break;
+ }
+ }
+ mRotationStyleCurrentIndex = currentMode;
+ mSkipOriginalMixedCaseMode = true;
+ }
+ mIsStarted = true;
+ }
+
+ public void stop() {
+ mIsStarted = false;
+ }
+
+ public boolean isStarted() {
+ return mIsStarted;
+ }
+
+ public void enable() {
+ mIsEnabled = true;
+ }
+
+ public void disable() {
+ mIsEnabled = false;
+ }
+
+ public boolean mIsEnabled() {
+ return mIsEnabled;
+ }
+
+ public boolean isSetAt(final int cursorStart, final int cursorEnd) {
+ return cursorStart == mCursorStartAfter && cursorEnd == mCursorEndAfter;
+ }
+
+ /**
+ * Rotate through the different possible capitalization modes.
+ */
+ public void rotate() {
+ final String oldResult = mStringAfter;
+ int count = 0; // Protection against infinite loop.
+ do {
+ mRotationStyleCurrentIndex = (mRotationStyleCurrentIndex + 1) % ROTATION_STYLE.length;
+ if (CAPS_MODE_ORIGINAL_MIXED_CASE == ROTATION_STYLE[mRotationStyleCurrentIndex]
+ && mSkipOriginalMixedCaseMode) {
+ mRotationStyleCurrentIndex =
+ (mRotationStyleCurrentIndex + 1) % ROTATION_STYLE.length;
+ }
+ ++count;
+ switch (ROTATION_STYLE[mRotationStyleCurrentIndex]) {
+ case CAPS_MODE_ORIGINAL_MIXED_CASE:
+ mStringAfter = mStringBefore;
+ break;
+ case CAPS_MODE_ALL_LOWER:
+ mStringAfter = mStringBefore.toLowerCase(mLocale);
+ break;
+ case CAPS_MODE_FIRST_WORD_UPPER:
+ mStringAfter = StringUtils.capitalizeEachWord(mStringBefore, mSortedSeparators,
+ mLocale);
+ break;
+ case CAPS_MODE_ALL_UPPER:
+ mStringAfter = mStringBefore.toUpperCase(mLocale);
+ break;
+ default:
+ mStringAfter = mStringBefore;
+ }
+ } while (mStringAfter.equals(oldResult) && count < ROTATION_STYLE.length + 1);
+ mCursorEndAfter = mCursorStartAfter + mStringAfter.length();
+ }
+
+ /**
+ * Remove leading/trailing whitespace from the considered string.
+ */
+ public void trim() {
+ final int len = mStringBefore.length();
+ int nonWhitespaceStart = 0;
+ for (; nonWhitespaceStart < len;
+ nonWhitespaceStart = mStringBefore.offsetByCodePoints(nonWhitespaceStart, 1)) {
+ final int codePoint = mStringBefore.codePointAt(nonWhitespaceStart);
+ if (!Character.isWhitespace(codePoint)) break;
+ }
+ int nonWhitespaceEnd = len;
+ for (; nonWhitespaceEnd > 0;
+ nonWhitespaceEnd = mStringBefore.offsetByCodePoints(nonWhitespaceEnd, -1)) {
+ final int codePoint = mStringBefore.codePointBefore(nonWhitespaceEnd);
+ if (!Character.isWhitespace(codePoint)) break;
+ }
+ // If nonWhitespaceStart >= nonWhitespaceEnd, that means the selection contained only
+ // whitespace, so we leave it as is.
+ if ((0 != nonWhitespaceStart || len != nonWhitespaceEnd)
+ && nonWhitespaceStart < nonWhitespaceEnd) {
+ mCursorEndAfter = mCursorStartBefore + nonWhitespaceEnd;
+ mCursorStartBefore = mCursorStartAfter = mCursorStartBefore + nonWhitespaceStart;
+ mStringAfter = mStringBefore =
+ mStringBefore.substring(nonWhitespaceStart, nonWhitespaceEnd);
+ }
+ }
+
+ public String getRecapitalizedString() {
+ return mStringAfter;
+ }
+
+ public int getNewCursorStart() {
+ return mCursorStartAfter;
+ }
+
+ public int getNewCursorEnd() {
+ return mCursorEndAfter;
+ }
+
+ public int getCurrentMode() {
+ return ROTATION_STYLE[mRotationStyleCurrentIndex];
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/ResourceUtils.java b/java/src/org/kelar/inputmethod/latin/utils/ResourceUtils.java
new file mode 100644
index 000000000..96f206a7b
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/ResourceUtils.java
@@ -0,0 +1,319 @@
+/*
+ * Copyright (C) 2012 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.graphics.Insets;
+import android.os.Build;
+import android.text.TextUtils;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.util.TypedValue;
+import android.view.WindowInsets;
+import android.view.WindowManager;
+import android.view.WindowMetrics;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+import org.kelar.inputmethod.latin.R;
+import org.kelar.inputmethod.latin.settings.SettingsValues;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.regex.PatternSyntaxException;
+
+public final class ResourceUtils {
+ private static final String TAG = ResourceUtils.class.getSimpleName();
+
+ public static final float UNDEFINED_RATIO = -1.0f;
+ public static final int UNDEFINED_DIMENSION = -1;
+
+ private ResourceUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ private static final HashMap<String, String> sDeviceOverrideValueMap = new HashMap<>();
+
+ private static final String[] BUILD_KEYS_AND_VALUES = {
+ "HARDWARE", Build.HARDWARE,
+ "MODEL", Build.MODEL,
+ "BRAND", Build.BRAND,
+ "MANUFACTURER", Build.MANUFACTURER
+ };
+ private static final HashMap<String, String> sBuildKeyValues;
+ private static final String sBuildKeyValuesDebugString;
+
+ static {
+ sBuildKeyValues = new HashMap<>();
+ final ArrayList<String> keyValuePairs = new ArrayList<>();
+ final int keyCount = BUILD_KEYS_AND_VALUES.length / 2;
+ for (int i = 0; i < keyCount; i++) {
+ final int index = i * 2;
+ final String key = BUILD_KEYS_AND_VALUES[index];
+ final String value = BUILD_KEYS_AND_VALUES[index + 1];
+ sBuildKeyValues.put(key, value);
+ keyValuePairs.add(key + '=' + value);
+ }
+ sBuildKeyValuesDebugString = "[" + TextUtils.join(" ", keyValuePairs) + "]";
+ }
+
+ public static String getDeviceOverrideValue(final Resources res, final int overrideResId,
+ final String defaultValue) {
+ final int orientation = res.getConfiguration().orientation;
+ final String key = overrideResId + "-" + orientation;
+ if (sDeviceOverrideValueMap.containsKey(key)) {
+ return sDeviceOverrideValueMap.get(key);
+ }
+
+ final String[] overrideArray = res.getStringArray(overrideResId);
+ final String overrideValue = findConstantForKeyValuePairs(sBuildKeyValues, overrideArray);
+ // The overrideValue might be an empty string.
+ if (overrideValue != null) {
+ Log.i(TAG, "Find override value:"
+ + " resource="+ res.getResourceEntryName(overrideResId)
+ + " build=" + sBuildKeyValuesDebugString
+ + " override=" + overrideValue);
+ sDeviceOverrideValueMap.put(key, overrideValue);
+ return overrideValue;
+ }
+
+ sDeviceOverrideValueMap.put(key, defaultValue);
+ return defaultValue;
+ }
+
+ @SuppressWarnings("serial")
+ static class DeviceOverridePatternSyntaxError extends Exception {
+ public DeviceOverridePatternSyntaxError(final String message, final String expression) {
+ this(message, expression, null);
+ }
+
+ public DeviceOverridePatternSyntaxError(final String message, final String expression,
+ final Throwable throwable) {
+ super(message + ": " + expression, throwable);
+ }
+ }
+
+ /**
+ * Find the condition that fulfills specified key value pairs from an array of
+ * "condition,constant", and return the corresponding string constant. A condition is
+ * "pattern1[:pattern2...] (or an empty string for the default). A pattern is
+ * "key=regexp_value" string. The condition matches only if all patterns of the condition
+ * are true for the specified key value pairs.
+ *
+ * For example, "condition,constant" has the following format.
+ * - HARDWARE=mako,constantForNexus4
+ * - MODEL=Nexus 4:MANUFACTURER=LGE,constantForNexus4
+ * - ,defaultConstant
+ *
+ * @param keyValuePairs attributes to be used to look for a matched condition.
+ * @param conditionConstantArray an array of "condition,constant" elements to be searched.
+ * @return the constant part of the matched "condition,constant" element. Returns null if no
+ * condition matches.
+ * @see org.kelar.inputmethod.latin.utils.ResourceUtilsTests#testFindConstantForKeyValuePairsRegexp()
+ */
+ @UsedForTesting
+ static String findConstantForKeyValuePairs(final HashMap<String, String> keyValuePairs,
+ final String[] conditionConstantArray) {
+ if (conditionConstantArray == null || keyValuePairs == null) {
+ return null;
+ }
+ String foundValue = null;
+ for (final String conditionConstant : conditionConstantArray) {
+ final int posComma = conditionConstant.indexOf(',');
+ if (posComma < 0) {
+ Log.w(TAG, "Array element has no comma: " + conditionConstant);
+ continue;
+ }
+ final String condition = conditionConstant.substring(0, posComma);
+ if (condition.isEmpty()) {
+ Log.w(TAG, "Array element has no condition: " + conditionConstant);
+ continue;
+ }
+ try {
+ if (fulfillsCondition(keyValuePairs, condition)) {
+ // Take first match
+ if (foundValue == null) {
+ foundValue = conditionConstant.substring(posComma + 1);
+ }
+ // And continue walking through all conditions.
+ }
+ } catch (final DeviceOverridePatternSyntaxError e) {
+ Log.w(TAG, "Syntax error, ignored", e);
+ }
+ }
+ return foundValue;
+ }
+
+ private static boolean fulfillsCondition(final HashMap<String,String> keyValuePairs,
+ final String condition) throws DeviceOverridePatternSyntaxError {
+ final String[] patterns = condition.split(":");
+ // Check all patterns in a condition are true
+ boolean matchedAll = true;
+ for (final String pattern : patterns) {
+ final int posEqual = pattern.indexOf('=');
+ if (posEqual < 0) {
+ throw new DeviceOverridePatternSyntaxError("Pattern has no '='", condition);
+ }
+ final String key = pattern.substring(0, posEqual);
+ final String value = keyValuePairs.get(key);
+ if (value == null) {
+ throw new DeviceOverridePatternSyntaxError("Unknown key", condition);
+ }
+ final String patternRegexpValue = pattern.substring(posEqual + 1);
+ try {
+ if (!value.matches(patternRegexpValue)) {
+ matchedAll = false;
+ // And continue walking through all patterns.
+ }
+ } catch (final PatternSyntaxException e) {
+ throw new DeviceOverridePatternSyntaxError("Syntax error", condition, e);
+ }
+ }
+ return matchedAll;
+ }
+
+ public static int getDefaultKeyboardWidth(final Context context) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ // Since Android 15’s edge-to-edge enforcement, window insets should be considered.
+ final WindowManager wm = context.getSystemService(WindowManager.class);
+ final WindowMetrics windowMetrics = wm.getCurrentWindowMetrics();
+ final Insets insets =
+ windowMetrics
+ .getWindowInsets()
+ .getInsetsIgnoringVisibility(
+ WindowInsets.Type.systemBars()
+ | WindowInsets.Type.displayCutout());
+ return windowMetrics.getBounds().width() - insets.left - insets.right;
+ }
+ final DisplayMetrics dm = context.getResources().getDisplayMetrics();
+ return dm.widthPixels;
+ }
+
+ public static int getKeyboardHeight(final Resources res, final SettingsValues settingsValues) {
+ final int defaultKeyboardHeight = getDefaultKeyboardHeight(res);
+ if (settingsValues.mHasKeyboardResize) {
+ // mKeyboardHeightScale Ranges from [.5,1.2], from xml/prefs_screen_debug.xml
+ return (int)(defaultKeyboardHeight * settingsValues.mKeyboardHeightScale);
+ }
+ return defaultKeyboardHeight;
+ }
+
+ public static int getDefaultKeyboardHeight(final Resources res) {
+ final DisplayMetrics dm = res.getDisplayMetrics();
+ final String keyboardHeightInDp = getDeviceOverrideValue(
+ res, R.array.keyboard_heights, null /* defaultValue */);
+ final float keyboardHeight;
+ if (TextUtils.isEmpty(keyboardHeightInDp)) {
+ keyboardHeight = res.getDimension(R.dimen.config_default_keyboard_height);
+ } else {
+ keyboardHeight = Float.parseFloat(keyboardHeightInDp) * dm.density;
+ }
+ final float maxKeyboardHeight = res.getFraction(
+ R.fraction.config_max_keyboard_height, dm.heightPixels, dm.heightPixels);
+ float minKeyboardHeight = res.getFraction(
+ R.fraction.config_min_keyboard_height, dm.heightPixels, dm.heightPixels);
+ if (minKeyboardHeight < 0.0f) {
+ // Specified fraction was negative, so it should be calculated against display
+ // width.
+ minKeyboardHeight = -res.getFraction(
+ R.fraction.config_min_keyboard_height, dm.widthPixels, dm.widthPixels);
+ }
+ // Keyboard height will not exceed maxKeyboardHeight and will not be less than
+ // minKeyboardHeight.
+ return (int)Math.max(Math.min(keyboardHeight, maxKeyboardHeight), minKeyboardHeight);
+ }
+
+ public static boolean isValidFraction(final float fraction) {
+ return fraction >= 0.0f;
+ }
+
+ // {@link Resources#getDimensionPixelSize(int)} returns at least one pixel size.
+ public static boolean isValidDimensionPixelSize(final int dimension) {
+ return dimension > 0;
+ }
+
+ // {@link Resources#getDimensionPixelOffset(int)} may return zero pixel offset.
+ public static boolean isValidDimensionPixelOffset(final int dimension) {
+ return dimension >= 0;
+ }
+
+ public static float getFloatFromFraction(final Resources res, final int fractionResId) {
+ return res.getFraction(fractionResId, 1, 1);
+ }
+
+ public static float getFraction(final TypedArray a, final int index, final float defValue) {
+ final TypedValue value = a.peekValue(index);
+ if (value == null || !isFractionValue(value)) {
+ return defValue;
+ }
+ return a.getFraction(index, 1, 1, defValue);
+ }
+
+ public static float getFraction(final TypedArray a, final int index) {
+ return getFraction(a, index, UNDEFINED_RATIO);
+ }
+
+ public static int getDimensionPixelSize(final TypedArray a, final int index) {
+ final TypedValue value = a.peekValue(index);
+ if (value == null || !isDimensionValue(value)) {
+ return ResourceUtils.UNDEFINED_DIMENSION;
+ }
+ return a.getDimensionPixelSize(index, ResourceUtils.UNDEFINED_DIMENSION);
+ }
+
+ public static float getDimensionOrFraction(final TypedArray a, final int index, final int base,
+ final float defValue) {
+ final TypedValue value = a.peekValue(index);
+ if (value == null) {
+ return defValue;
+ }
+ if (isFractionValue(value)) {
+ return a.getFraction(index, base, base, defValue);
+ } else if (isDimensionValue(value)) {
+ return a.getDimension(index, defValue);
+ }
+ return defValue;
+ }
+
+ public static int getEnumValue(final TypedArray a, final int index, final int defValue) {
+ final TypedValue value = a.peekValue(index);
+ if (value == null) {
+ return defValue;
+ }
+ if (isIntegerValue(value)) {
+ return a.getInt(index, defValue);
+ }
+ return defValue;
+ }
+
+ public static boolean isFractionValue(final TypedValue v) {
+ return v.type == TypedValue.TYPE_FRACTION;
+ }
+
+ public static boolean isDimensionValue(final TypedValue v) {
+ return v.type == TypedValue.TYPE_DIMENSION;
+ }
+
+ public static boolean isIntegerValue(final TypedValue v) {
+ return v.type >= TypedValue.TYPE_FIRST_INT && v.type <= TypedValue.TYPE_LAST_INT;
+ }
+
+ public static boolean isStringValue(final TypedValue v) {
+ return v.type == TypedValue.TYPE_STRING;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/RunInLocale.java b/java/src/org/kelar/inputmethod/latin/utils/RunInLocale.java
new file mode 100644
index 000000000..f890118d1
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/RunInLocale.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.res.Configuration;
+import android.content.res.Resources;
+
+import java.util.Locale;
+
+public abstract class RunInLocale<T> {
+ private static final Object sLockForRunInLocale = new Object();
+
+ protected abstract T job(final Resources res);
+
+ /**
+ * Execute {@link #job(Resources)} method in specified system locale exclusively.
+ *
+ * @param res the resources to use.
+ * @param newLocale the locale to change to. Run in system locale if null.
+ * @return the value returned from {@link #job(Resources)}.
+ */
+ public T runInLocale(final Resources res, final Locale newLocale) {
+ synchronized (sLockForRunInLocale) {
+ final Configuration conf = res.getConfiguration();
+ if (newLocale == null || newLocale.equals(conf.locale)) {
+ return job(res);
+ }
+ final Locale savedLocale = conf.locale;
+ try {
+ conf.locale = newLocale;
+ res.updateConfiguration(conf, null);
+ return job(res);
+ } finally {
+ conf.locale = savedLocale;
+ res.updateConfiguration(conf, null);
+ }
+ }
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/ScriptUtils.java b/java/src/org/kelar/inputmethod/latin/utils/ScriptUtils.java
new file mode 100644
index 000000000..981bc6649
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/ScriptUtils.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright (C) 2012 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 org.kelar.inputmethod.latin.utils;
+
+import java.util.Locale;
+import java.util.TreeMap;
+
+/**
+ * A class to help with handling different writing scripts.
+ */
+public class ScriptUtils {
+
+ // Used for hardware keyboards
+ public static final int SCRIPT_UNKNOWN = -1;
+
+ public static final int SCRIPT_ARABIC = 0;
+ public static final int SCRIPT_ARMENIAN = 1;
+ public static final int SCRIPT_BENGALI = 2;
+ public static final int SCRIPT_CYRILLIC = 3;
+ public static final int SCRIPT_DEVANAGARI = 4;
+ public static final int SCRIPT_GEORGIAN = 5;
+ public static final int SCRIPT_GREEK = 6;
+ public static final int SCRIPT_HEBREW = 7;
+ public static final int SCRIPT_KANNADA = 8;
+ public static final int SCRIPT_KHMER = 9;
+ public static final int SCRIPT_LAO = 10;
+ public static final int SCRIPT_LATIN = 11;
+ public static final int SCRIPT_MALAYALAM = 12;
+ public static final int SCRIPT_MYANMAR = 13;
+ public static final int SCRIPT_SINHALA = 14;
+ public static final int SCRIPT_TAMIL = 15;
+ public static final int SCRIPT_TELUGU = 16;
+ public static final int SCRIPT_THAI = 17;
+
+ private static final TreeMap<String, Integer> mLanguageCodeToScriptCode;
+
+ static {
+ mLanguageCodeToScriptCode = new TreeMap<>();
+ mLanguageCodeToScriptCode.put("", SCRIPT_LATIN); // default
+ mLanguageCodeToScriptCode.put("ar", SCRIPT_ARABIC);
+ mLanguageCodeToScriptCode.put("hy", SCRIPT_ARMENIAN);
+ mLanguageCodeToScriptCode.put("bn", SCRIPT_BENGALI);
+ mLanguageCodeToScriptCode.put("bg", SCRIPT_CYRILLIC);
+ mLanguageCodeToScriptCode.put("sr", SCRIPT_CYRILLIC);
+ mLanguageCodeToScriptCode.put("ru", SCRIPT_CYRILLIC);
+ mLanguageCodeToScriptCode.put("ka", SCRIPT_GEORGIAN);
+ mLanguageCodeToScriptCode.put("el", SCRIPT_GREEK);
+ mLanguageCodeToScriptCode.put("iw", SCRIPT_HEBREW);
+ mLanguageCodeToScriptCode.put("km", SCRIPT_KHMER);
+ mLanguageCodeToScriptCode.put("lo", SCRIPT_LAO);
+ mLanguageCodeToScriptCode.put("ml", SCRIPT_MALAYALAM);
+ mLanguageCodeToScriptCode.put("my", SCRIPT_MYANMAR);
+ mLanguageCodeToScriptCode.put("si", SCRIPT_SINHALA);
+ mLanguageCodeToScriptCode.put("ta", SCRIPT_TAMIL);
+ mLanguageCodeToScriptCode.put("te", SCRIPT_TELUGU);
+ mLanguageCodeToScriptCode.put("th", SCRIPT_THAI);
+ }
+
+ /*
+ * Returns whether the code point is a letter that makes sense for the specified
+ * locale for this spell checker.
+ * The dictionaries supported by Latin IME are described in res/xml/spellchecker.xml
+ * and is limited to EFIGS languages and Russian.
+ * Hence at the moment this explicitly tests for Cyrillic characters or Latin characters
+ * as appropriate, and explicitly excludes CJK, Arabic and Hebrew characters.
+ */
+ public static boolean isLetterPartOfScript(final int codePoint, final int scriptId) {
+ switch (scriptId) {
+ case SCRIPT_ARABIC:
+ // Arabic letters can be in any of the following blocks:
+ // Arabic U+0600..U+06FF
+ // Arabic Supplement, Thaana U+0750..U+077F, U+0780..U+07BF
+ // Arabic Extended-A U+08A0..U+08FF
+ // Arabic Presentation Forms-A U+FB50..U+FDFF
+ // Arabic Presentation Forms-B U+FE70..U+FEFF
+ return (codePoint >= 0x600 && codePoint <= 0x6FF)
+ || (codePoint >= 0x750 && codePoint <= 0x7BF)
+ || (codePoint >= 0x8A0 && codePoint <= 0x8FF)
+ || (codePoint >= 0xFB50 && codePoint <= 0xFDFF)
+ || (codePoint >= 0xFE70 && codePoint <= 0xFEFF);
+ case SCRIPT_ARMENIAN:
+ // Armenian letters are in the Armenian unicode block, U+0530..U+058F and
+ // Alphabetic Presentation Forms block, U+FB00..U+FB4F, but only in the Armenian part
+ // of that block, which is U+FB13..U+FB17.
+ return (codePoint >= 0x530 && codePoint <= 0x58F
+ || codePoint >= 0xFB13 && codePoint <= 0xFB17);
+ case SCRIPT_BENGALI:
+ // Bengali unicode block is U+0980..U+09FF
+ return (codePoint >= 0x980 && codePoint <= 0x9FF);
+ case SCRIPT_CYRILLIC:
+ // All Cyrillic characters are in the 400~52F block. There are some in the upper
+ // Unicode range, but they are archaic characters that are not used in modern
+ // Russian and are not used by our dictionary.
+ return codePoint >= 0x400 && codePoint <= 0x52F && Character.isLetter(codePoint);
+ case SCRIPT_DEVANAGARI:
+ // Devanagari unicode block is +0900..U+097F
+ return (codePoint >= 0x900 && codePoint <= 0x97F);
+ case SCRIPT_GEORGIAN:
+ // Georgian letters are in the Georgian unicode block, U+10A0..U+10FF,
+ // or Georgian supplement block, U+2D00..U+2D2F
+ return (codePoint >= 0x10A0 && codePoint <= 0x10FF
+ || codePoint >= 0x2D00 && codePoint <= 0x2D2F);
+ case SCRIPT_GREEK:
+ // Greek letters are either in the 370~3FF range (Greek & Coptic), or in the
+ // 1F00~1FFF range (Greek extended). Our dictionary contains both sort of characters.
+ // Our dictionary also contains a few words with 0xF2; it would be best to check
+ // if that's correct, but a web search does return results for these words so
+ // they are probably okay.
+ return (codePoint >= 0x370 && codePoint <= 0x3FF)
+ || (codePoint >= 0x1F00 && codePoint <= 0x1FFF)
+ || codePoint == 0xF2;
+ case SCRIPT_HEBREW:
+ // Hebrew letters are in the Hebrew unicode block, which spans from U+0590 to U+05FF,
+ // or in the Alphabetic Presentation Forms block, U+FB00..U+FB4F, but only in the
+ // Hebrew part of that block, which is U+FB1D..U+FB4F.
+ return (codePoint >= 0x590 && codePoint <= 0x5FF
+ || codePoint >= 0xFB1D && codePoint <= 0xFB4F);
+ case SCRIPT_KANNADA:
+ // Kannada unicode block is U+0C80..U+0CFF
+ return (codePoint >= 0xC80 && codePoint <= 0xCFF);
+ case SCRIPT_KHMER:
+ // Khmer letters are in unicode block U+1780..U+17FF, and the Khmer symbols block
+ // is U+19E0..U+19FF
+ return (codePoint >= 0x1780 && codePoint <= 0x17FF
+ || codePoint >= 0x19E0 && codePoint <= 0x19FF);
+ case SCRIPT_LAO:
+ // The Lao block is U+0E80..U+0EFF
+ return (codePoint >= 0xE80 && codePoint <= 0xEFF);
+ case SCRIPT_LATIN:
+ // Our supported latin script dictionaries (EFIGS) at the moment only include
+ // characters in the C0, C1, Latin Extended A and B, IPA extensions unicode
+ // blocks. As it happens, those are back-to-back in the code range 0x40 to 0x2AF,
+ // so the below is a very efficient way to test for it. As for the 0-0x3F, it's
+ // excluded from isLetter anyway.
+ return codePoint <= 0x2AF && Character.isLetter(codePoint);
+ case SCRIPT_MALAYALAM:
+ // Malayalam unicode block is U+0D00..U+0D7F
+ return (codePoint >= 0xD00 && codePoint <= 0xD7F);
+ case SCRIPT_MYANMAR:
+ // Myanmar has three unicode blocks :
+ // Myanmar U+1000..U+109F
+ // Myanmar extended-A U+AA60..U+AA7F
+ // Myanmar extended-B U+A9E0..U+A9FF
+ return (codePoint >= 0x1000 && codePoint <= 0x109F
+ || codePoint >= 0xAA60 && codePoint <= 0xAA7F
+ || codePoint >= 0xA9E0 && codePoint <= 0xA9FF);
+ case SCRIPT_SINHALA:
+ // Sinhala unicode block is U+0D80..U+0DFF
+ return (codePoint >= 0xD80 && codePoint <= 0xDFF);
+ case SCRIPT_TAMIL:
+ // Tamil unicode block is U+0B80..U+0BFF
+ return (codePoint >= 0xB80 && codePoint <= 0xBFF);
+ case SCRIPT_TELUGU:
+ // Telugu unicode block is U+0C00..U+0C7F
+ return (codePoint >= 0xC00 && codePoint <= 0xC7F);
+ case SCRIPT_THAI:
+ // Thai unicode block is U+0E00..U+0E7F
+ return (codePoint >= 0xE00 && codePoint <= 0xE7F);
+ case SCRIPT_UNKNOWN:
+ return true;
+ default:
+ // Should never come here
+ throw new RuntimeException("Impossible value of script: " + scriptId);
+ }
+ }
+
+ /**
+ * @param locale spell checker locale
+ * @return internal Latin IME script code that maps to a language code
+ * {@see http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes}
+ */
+ public static int getScriptFromSpellCheckerLocale(final Locale locale) {
+ String language = locale.getLanguage();
+ Integer script = mLanguageCodeToScriptCode.get(language);
+ if (script == null) {
+ // Default to Latin.
+ script = mLanguageCodeToScriptCode.get("");
+ }
+ return script;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/SpannableStringUtils.java b/java/src/org/kelar/inputmethod/latin/utils/SpannableStringUtils.java
new file mode 100644
index 000000000..e3c6d60bf
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/SpannableStringUtils.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.text.Spannable;
+import android.text.SpannableString;
+import android.text.Spanned;
+import android.text.SpannedString;
+import android.text.TextUtils;
+import android.text.style.SuggestionSpan;
+import android.text.style.URLSpan;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+
+import java.util.ArrayList;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public final class SpannableStringUtils {
+ /**
+ * Copies the spans from the region <code>start...end</code> in
+ * <code>source</code> to the region
+ * <code>destoff...destoff+end-start</code> in <code>dest</code>.
+ * Spans in <code>source</code> that begin before <code>start</code>
+ * or end after <code>end</code> but overlap this range are trimmed
+ * as if they began at <code>start</code> or ended at <code>end</code>.
+ * Only SuggestionSpans that don't have the SPAN_PARAGRAPH span are copied.
+ *
+ * This code is almost entirely taken from {@link TextUtils#copySpansFrom}, except for the
+ * kind of span that is copied.
+ *
+ * @throws IndexOutOfBoundsException if any of the copied spans
+ * are out of range in <code>dest</code>.
+ */
+ public static void copyNonParagraphSuggestionSpansFrom(Spanned source, int start, int end,
+ Spannable dest, int destoff) {
+ Object[] spans = source.getSpans(start, end, SuggestionSpan.class);
+
+ for (int i = 0; i < spans.length; i++) {
+ int fl = source.getSpanFlags(spans[i]);
+ // We don't care about the PARAGRAPH flag in LatinIME code. However, if this flag
+ // is set, Spannable#setSpan will throw an exception unless the span is on the edge
+ // of a word. But the spans have been split into two by the getText{Before,After}Cursor
+ // methods, so after concatenation they may end in the middle of a word.
+ // Since we don't use them, we can just remove them and avoid crashing.
+ fl &= ~Spanned.SPAN_PARAGRAPH;
+
+ int st = source.getSpanStart(spans[i]);
+ int en = source.getSpanEnd(spans[i]);
+
+ if (st < start)
+ st = start;
+ if (en > end)
+ en = end;
+
+ dest.setSpan(spans[i], st - start + destoff, en - start + destoff,
+ fl);
+ }
+ }
+
+ /**
+ * Returns a CharSequence concatenating the specified CharSequences, retaining their
+ * SuggestionSpans that don't have the PARAGRAPH flag, but not other spans.
+ *
+ * This code is almost entirely taken from {@link TextUtils#concat(CharSequence...)}, except
+ * it calls copyNonParagraphSuggestionSpansFrom instead of {@link TextUtils#copySpansFrom}.
+ */
+ public static CharSequence concatWithNonParagraphSuggestionSpansOnly(CharSequence... text) {
+ if (text.length == 0) {
+ return "";
+ }
+
+ if (text.length == 1) {
+ return text[0];
+ }
+
+ boolean spanned = false;
+ for (int i = 0; i < text.length; i++) {
+ if (text[i] instanceof Spanned) {
+ spanned = true;
+ break;
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < text.length; i++) {
+ sb.append(text[i]);
+ }
+
+ if (!spanned) {
+ return sb.toString();
+ }
+
+ SpannableString ss = new SpannableString(sb);
+ int off = 0;
+ for (int i = 0; i < text.length; i++) {
+ int len = text[i].length();
+
+ if (text[i] instanceof Spanned) {
+ copyNonParagraphSuggestionSpansFrom((Spanned) text[i], 0, len, ss, off);
+ }
+
+ off += len;
+ }
+
+ return new SpannedString(ss);
+ }
+
+ public static boolean hasUrlSpans(final CharSequence text,
+ final int startIndex, final int endIndex) {
+ if (!(text instanceof Spanned)) {
+ return false; // Not spanned, so no link
+ }
+ final Spanned spanned = (Spanned)text;
+ // getSpans(x, y) does not return spans that start on x or end on y. x-1, y+1 does the
+ // trick, and works in all cases even if startIndex <= 0 or endIndex >= text.length().
+ final URLSpan[] spans = spanned.getSpans(startIndex - 1, endIndex + 1, URLSpan.class);
+ return null != spans && spans.length > 0;
+ }
+
+ /**
+ * Splits the given {@code charSequence} with at occurrences of the given {@code regex}.
+ * <p>
+ * This is equivalent to
+ * {@code charSequence.toString().split(regex, preserveTrailingEmptySegments ? -1 : 0)}
+ * except that the spans are preserved in the result array.
+ * </p>
+ * @param charSequence the character sequence to be split.
+ * @param regex the regex pattern to be used as the separator.
+ * @param preserveTrailingEmptySegments {@code true} to preserve the trailing empty
+ * segments. Otherwise, trailing empty segments will be removed before being returned.
+ * @return the array which contains the result. All the spans in the <code>charSequence</code>
+ * is preserved.
+ */
+ @UsedForTesting
+ public static CharSequence[] split(final CharSequence charSequence, final String regex,
+ final boolean preserveTrailingEmptySegments) {
+ // A short-cut for non-spanned strings.
+ if (!(charSequence instanceof Spanned)) {
+ // -1 means that trailing empty segments will be preserved.
+ return charSequence.toString().split(regex, preserveTrailingEmptySegments ? -1 : 0);
+ }
+
+ // Hereafter, emulate String.split for CharSequence.
+ final ArrayList<CharSequence> sequences = new ArrayList<>();
+ final Matcher matcher = Pattern.compile(regex).matcher(charSequence);
+ int nextStart = 0;
+ boolean matched = false;
+ while (matcher.find()) {
+ sequences.add(charSequence.subSequence(nextStart, matcher.start()));
+ nextStart = matcher.end();
+ matched = true;
+ }
+ if (!matched) {
+ // never matched. preserveTrailingEmptySegments is ignored in this case.
+ return new CharSequence[] { charSequence };
+ }
+ sequences.add(charSequence.subSequence(nextStart, charSequence.length()));
+ if (!preserveTrailingEmptySegments) {
+ for (int i = sequences.size() - 1; i >= 0; --i) {
+ if (!TextUtils.isEmpty(sequences.get(i))) {
+ break;
+ }
+ sequences.remove(i);
+ }
+ }
+ return sequences.toArray(new CharSequence[sequences.size()]);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/StatsUtils.java b/java/src/org/kelar/inputmethod/latin/utils/StatsUtils.java
new file mode 100644
index 000000000..f690eae3e
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/StatsUtils.java
@@ -0,0 +1,108 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.view.inputmethod.InputMethodSubtype;
+
+import org.kelar.inputmethod.latin.DictionaryFacilitator;
+import org.kelar.inputmethod.latin.RichInputMethodManager;
+import org.kelar.inputmethod.latin.SuggestedWords;
+import org.kelar.inputmethod.latin.settings.SettingsValues;
+
+@SuppressWarnings("unused")
+public final class StatsUtils {
+
+ private StatsUtils() {
+ // Intentional empty constructor.
+ }
+
+ public static void onCreate(final SettingsValues settingsValues,
+ RichInputMethodManager richImm) {
+ }
+
+ public static void onPickSuggestionManually(final SuggestedWords suggestedWords,
+ final SuggestedWords.SuggestedWordInfo suggestionInfo,
+ final DictionaryFacilitator dictionaryFacilitator) {
+ }
+
+ public static void onBackspaceWordDelete(int wordLength) {
+ }
+
+ public static void onBackspacePressed(int lengthToDelete) {
+ }
+
+ public static void onBackspaceSelectedText(int selectedTextLength) {
+ }
+
+ public static void onDeleteMultiCharInput(int multiCharLength) {
+ }
+
+ public static void onRevertAutoCorrect() {
+ }
+
+ public static void onRevertDoubleSpacePeriod() {
+ }
+
+ public static void onRevertSwapPunctuation() {
+ }
+
+ public static void onFinishInputView() {
+ }
+
+ public static void onCreateInputView() {
+ }
+
+ public static void onStartInputView(int inputType, int displayOrientation, boolean restarting) {
+ }
+
+ public static void onAutoCorrection(final String typedWord, final String autoCorrectionWord,
+ final boolean isBatchInput, final DictionaryFacilitator dictionaryFacilitator,
+ final String prevWordsContext) {
+ }
+
+ public static void onWordCommitUserTyped(final String commitWord, final boolean isBatchMode) {
+ }
+
+ public static void onWordCommitAutoCorrect(final String commitWord, final boolean isBatchMode) {
+ }
+
+ public static void onWordCommitSuggestionPickedManually(
+ final String commitWord, final boolean isBatchMode) {
+ }
+
+ public static void onDoubleSpacePeriod() {
+ }
+
+ public static void onLoadSettings(SettingsValues settingsValues) {
+ }
+
+ public static void onInvalidWordIdentification(final String invalidWord) {
+ }
+
+ public static void onSubtypeChanged(final InputMethodSubtype oldSubtype,
+ final InputMethodSubtype newSubtype) {
+ }
+
+ public static void onSettingsActivity(final String entryPoint) {
+ }
+
+ public static void onInputConnectionLaggy(final int operation, final long duration) {
+ }
+
+ public static void onDecoderLaggy(final int operation, final long duration) {
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/StatsUtilsManager.java b/java/src/org/kelar/inputmethod/latin/utils/StatsUtilsManager.java
new file mode 100644
index 000000000..5c86f020e
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/StatsUtilsManager.java
@@ -0,0 +1,56 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.Context;
+
+import org.kelar.inputmethod.latin.DictionaryFacilitator;
+import org.kelar.inputmethod.latin.settings.SettingsValues;
+
+@SuppressWarnings("unused")
+public class StatsUtilsManager {
+
+ private static final StatsUtilsManager sInstance = new StatsUtilsManager();
+ private static StatsUtilsManager sTestInstance = null;
+
+ /**
+ * @return the singleton instance of {@link StatsUtilsManager}.
+ */
+ public static StatsUtilsManager getInstance() {
+ return sTestInstance != null ? sTestInstance : sInstance;
+ }
+
+ public static void setTestInstance(final StatsUtilsManager testInstance) {
+ sTestInstance = testInstance;
+ }
+
+ public void onCreate(final Context context, final DictionaryFacilitator dictionaryFacilitator) {
+ }
+
+ public void onLoadSettings(final Context context, final SettingsValues settingsValues) {
+ }
+
+ public void onStartInputView() {
+ }
+
+ public void onFinishInputView() {
+ }
+
+ public void onDestroy(final Context context) {
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/SubtypeLocaleUtils.java b/java/src/org/kelar/inputmethod/latin/utils/SubtypeLocaleUtils.java
new file mode 100644
index 000000000..2be7ca5ba
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/SubtypeLocaleUtils.java
@@ -0,0 +1,351 @@
+/*
+ * Copyright (C) 2011 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 org.kelar.inputmethod.latin.utils;
+
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.COMBINING_RULES;
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.KEYBOARD_LAYOUT_SET;
+import static org.kelar.inputmethod.latin.common.Constants.Subtype.ExtraValue.UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.os.Build;
+import android.util.Log;
+import android.view.inputmethod.InputMethodSubtype;
+
+import org.kelar.inputmethod.latin.R;
+import org.kelar.inputmethod.latin.common.LocaleUtils;
+import org.kelar.inputmethod.latin.common.StringUtils;
+
+import java.util.HashMap;
+import java.util.Locale;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+/**
+ * A helper class to deal with subtype locales.
+ */
+// TODO: consolidate this into RichInputMethodSubtype
+public final class SubtypeLocaleUtils {
+ static final String TAG = SubtypeLocaleUtils.class.getSimpleName();
+
+ // This reference class {@link R} must be located in the same package as LatinIME.java.
+ private static final String RESOURCE_PACKAGE_NAME = R.class.getPackage().getName();
+
+ // Special language code to represent "no language".
+ public static final String NO_LANGUAGE = "zz";
+ public static final String QWERTY = "qwerty";
+ public static final String EMOJI = "emoji";
+ public static final int UNKNOWN_KEYBOARD_LAYOUT = R.string.subtype_generic;
+
+ private static volatile boolean sInitialized = false;
+ private static final Object sInitializeLock = new Object();
+ private static Resources sResources;
+ // Keyboard layout to its display name map.
+ private static final HashMap<String, String> sKeyboardLayoutToDisplayNameMap = new HashMap<>();
+ // Keyboard layout to subtype name resource id map.
+ private static final HashMap<String, Integer> sKeyboardLayoutToNameIdsMap = new HashMap<>();
+ // Exceptional locale whose name should be displayed in Locale.ROOT.
+ private static final HashMap<String, Integer> sExceptionalLocaleDisplayedInRootLocale =
+ new HashMap<>();
+ // Exceptional locale to subtype name resource id map.
+ private static final HashMap<String, Integer> sExceptionalLocaleToNameIdsMap = new HashMap<>();
+ // Exceptional locale to subtype name with layout resource id map.
+ private static final HashMap<String, Integer> sExceptionalLocaleToWithLayoutNameIdsMap =
+ new HashMap<>();
+ private static final String SUBTYPE_NAME_RESOURCE_PREFIX =
+ "string/subtype_";
+ private static final String SUBTYPE_NAME_RESOURCE_GENERIC_PREFIX =
+ "string/subtype_generic_";
+ private static final String SUBTYPE_NAME_RESOURCE_WITH_LAYOUT_PREFIX =
+ "string/subtype_with_layout_";
+ private static final String SUBTYPE_NAME_RESOURCE_NO_LANGUAGE_PREFIX =
+ "string/subtype_no_language_";
+ private static final String SUBTYPE_NAME_RESOURCE_IN_ROOT_LOCALE_PREFIX =
+ "string/subtype_in_root_locale_";
+ // Keyboard layout set name for the subtypes that don't have a keyboardLayoutSet extra value.
+ // This is for compatibility to keep the same subtype ids as pre-JellyBean.
+ private static final HashMap<String, String> sLocaleAndExtraValueToKeyboardLayoutSetMap =
+ new HashMap<>();
+
+ private SubtypeLocaleUtils() {
+ // Intentional empty constructor for utility class.
+ }
+
+ // Note that this initialization method can be called multiple times.
+ public static void init(final Context context) {
+ synchronized (sInitializeLock) {
+ if (sInitialized == false) {
+ initLocked(context);
+ sInitialized = true;
+ }
+ }
+ }
+
+ private static void initLocked(final Context context) {
+ final Resources res = context.getResources();
+ sResources = res;
+
+ final String[] predefinedLayoutSet = res.getStringArray(R.array.predefined_layouts);
+ final String[] layoutDisplayNames = res.getStringArray(
+ R.array.predefined_layout_display_names);
+ for (int i = 0; i < predefinedLayoutSet.length; i++) {
+ final String layoutName = predefinedLayoutSet[i];
+ sKeyboardLayoutToDisplayNameMap.put(layoutName, layoutDisplayNames[i]);
+ final String resourceName = SUBTYPE_NAME_RESOURCE_GENERIC_PREFIX + layoutName;
+ final int resId = res.getIdentifier(resourceName, null, RESOURCE_PACKAGE_NAME);
+ sKeyboardLayoutToNameIdsMap.put(layoutName, resId);
+ // Register subtype name resource id of "No language" with key "zz_<layout>"
+ final String noLanguageResName = SUBTYPE_NAME_RESOURCE_NO_LANGUAGE_PREFIX + layoutName;
+ final int noLanguageResId = res.getIdentifier(
+ noLanguageResName, null, RESOURCE_PACKAGE_NAME);
+ final String key = getNoLanguageLayoutKey(layoutName);
+ sKeyboardLayoutToNameIdsMap.put(key, noLanguageResId);
+ }
+
+ final String[] exceptionalLocaleInRootLocale = res.getStringArray(
+ R.array.subtype_locale_displayed_in_root_locale);
+ for (int i = 0; i < exceptionalLocaleInRootLocale.length; i++) {
+ final String localeString = exceptionalLocaleInRootLocale[i];
+ final String resourceName = SUBTYPE_NAME_RESOURCE_IN_ROOT_LOCALE_PREFIX + localeString;
+ final int resId = res.getIdentifier(resourceName, null, RESOURCE_PACKAGE_NAME);
+ sExceptionalLocaleDisplayedInRootLocale.put(localeString, resId);
+ }
+
+ final String[] exceptionalLocales = res.getStringArray(
+ R.array.subtype_locale_exception_keys);
+ for (int i = 0; i < exceptionalLocales.length; i++) {
+ final String localeString = exceptionalLocales[i];
+ final String resourceName = SUBTYPE_NAME_RESOURCE_PREFIX + localeString;
+ final int resId = res.getIdentifier(resourceName, null, RESOURCE_PACKAGE_NAME);
+ sExceptionalLocaleToNameIdsMap.put(localeString, resId);
+ final String resourceNameWithLayout =
+ SUBTYPE_NAME_RESOURCE_WITH_LAYOUT_PREFIX + localeString;
+ final int resIdWithLayout = res.getIdentifier(
+ resourceNameWithLayout, null, RESOURCE_PACKAGE_NAME);
+ sExceptionalLocaleToWithLayoutNameIdsMap.put(localeString, resIdWithLayout);
+ }
+
+ final String[] keyboardLayoutSetMap = res.getStringArray(
+ R.array.locale_and_extra_value_to_keyboard_layout_set_map);
+ for (int i = 0; i + 1 < keyboardLayoutSetMap.length; i += 2) {
+ final String key = keyboardLayoutSetMap[i];
+ final String keyboardLayoutSet = keyboardLayoutSetMap[i + 1];
+ sLocaleAndExtraValueToKeyboardLayoutSetMap.put(key, keyboardLayoutSet);
+ }
+ }
+
+ public static boolean isExceptionalLocale(final String localeString) {
+ return sExceptionalLocaleToNameIdsMap.containsKey(localeString);
+ }
+
+ private static final String getNoLanguageLayoutKey(final String keyboardLayoutName) {
+ return NO_LANGUAGE + "_" + keyboardLayoutName;
+ }
+
+ public static int getSubtypeNameId(final String localeString, final String keyboardLayoutName) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
+ && isExceptionalLocale(localeString)) {
+ return sExceptionalLocaleToWithLayoutNameIdsMap.get(localeString);
+ }
+ final String key = NO_LANGUAGE.equals(localeString)
+ ? getNoLanguageLayoutKey(keyboardLayoutName)
+ : keyboardLayoutName;
+ final Integer nameId = sKeyboardLayoutToNameIdsMap.get(key);
+ return nameId == null ? UNKNOWN_KEYBOARD_LAYOUT : nameId;
+ }
+
+ @Nonnull
+ public static Locale getDisplayLocaleOfSubtypeLocale(@Nonnull final String localeString) {
+ if (NO_LANGUAGE.equals(localeString)) {
+ return sResources.getConfiguration().locale;
+ }
+ if (sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {
+ return Locale.ROOT;
+ }
+ return LocaleUtils.constructLocaleFromString(localeString);
+ }
+
+ public static String getSubtypeLocaleDisplayNameInSystemLocale(
+ @Nonnull final String localeString) {
+ final Locale displayLocale = sResources.getConfiguration().locale;
+ return getSubtypeLocaleDisplayNameInternal(localeString, displayLocale);
+ }
+
+ @Nonnull
+ public static String getSubtypeLocaleDisplayName(@Nonnull final String localeString) {
+ final Locale displayLocale = getDisplayLocaleOfSubtypeLocale(localeString);
+ return getSubtypeLocaleDisplayNameInternal(localeString, displayLocale);
+ }
+
+ @Nonnull
+ public static String getSubtypeLanguageDisplayName(@Nonnull final String localeString) {
+ final Locale displayLocale = getDisplayLocaleOfSubtypeLocale(localeString);
+ final String languageString;
+ if (sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {
+ languageString = localeString;
+ } else {
+ languageString = LocaleUtils.constructLocaleFromString(localeString).getLanguage();
+ }
+ return getSubtypeLocaleDisplayNameInternal(languageString, displayLocale);
+ }
+
+ @Nonnull
+ private static String getSubtypeLocaleDisplayNameInternal(@Nonnull final String localeString,
+ @Nonnull final Locale displayLocale) {
+ if (NO_LANGUAGE.equals(localeString)) {
+ // No language subtype should be displayed in system locale.
+ return sResources.getString(R.string.subtype_no_language);
+ }
+ final Integer exceptionalNameResId;
+ if (displayLocale.equals(Locale.ROOT)
+ && sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {
+ exceptionalNameResId = sExceptionalLocaleDisplayedInRootLocale.get(localeString);
+ } else if (sExceptionalLocaleToNameIdsMap.containsKey(localeString)) {
+ exceptionalNameResId = sExceptionalLocaleToNameIdsMap.get(localeString);
+ } else {
+ exceptionalNameResId = null;
+ }
+
+ final String displayName;
+ if (exceptionalNameResId != null) {
+ final RunInLocale<String> getExceptionalName = new RunInLocale<String>() {
+ @Override
+ protected String job(final Resources res) {
+ return res.getString(exceptionalNameResId);
+ }
+ };
+ displayName = getExceptionalName.runInLocale(sResources, displayLocale);
+ } else {
+ displayName = LocaleUtils.constructLocaleFromString(localeString)
+ .getDisplayName(displayLocale);
+ }
+ return StringUtils.capitalizeFirstCodePoint(displayName, displayLocale);
+ }
+
+ // InputMethodSubtype's display name in its locale.
+ // isAdditionalSubtype (T=true, F=false)
+ // locale layout | display name
+ // ------ ------- - ----------------------
+ // en_US qwerty F English (US) exception
+ // en_GB qwerty F English (UK) exception
+ // es_US spanish F Español (EE.UU.) exception
+ // fr azerty F Français
+ // fr_CA qwerty F Français (Canada)
+ // fr_CH swiss F Français (Suisse)
+ // de qwertz F Deutsch
+ // de_CH swiss T Deutsch (Schweiz)
+ // zz qwerty F Alphabet (QWERTY) in system locale
+ // fr qwertz T Français (QWERTZ)
+ // de qwerty T Deutsch (QWERTY)
+ // en_US azerty T English (US) (AZERTY) exception
+ // zz azerty T Alphabet (AZERTY) in system locale
+
+ @Nonnull
+ private static String getReplacementString(@Nonnull final InputMethodSubtype subtype,
+ @Nonnull final Locale displayLocale) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
+ && subtype.containsExtraValueKey(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME)) {
+ return subtype.getExtraValueOf(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME);
+ }
+ return getSubtypeLocaleDisplayNameInternal(subtype.getLocale(), displayLocale);
+ }
+
+ @Nonnull
+ public static String getSubtypeDisplayNameInSystemLocale(
+ @Nonnull final InputMethodSubtype subtype) {
+ final Locale displayLocale = sResources.getConfiguration().locale;
+ return getSubtypeDisplayNameInternal(subtype, displayLocale);
+ }
+
+ @Nonnull
+ public static String getSubtypeNameForLogging(@Nullable final InputMethodSubtype subtype) {
+ if (subtype == null) {
+ return "<null subtype>";
+ }
+ return getSubtypeLocale(subtype) + "/" + getKeyboardLayoutSetName(subtype);
+ }
+
+ @Nonnull
+ private static String getSubtypeDisplayNameInternal(@Nonnull final InputMethodSubtype subtype,
+ @Nonnull final Locale displayLocale) {
+ final String replacementString = getReplacementString(subtype, displayLocale);
+ // TODO: rework this for multi-lingual subtypes
+ final int nameResId = subtype.getNameResId();
+ final RunInLocale<String> getSubtypeName = new RunInLocale<String>() {
+ @Override
+ protected String job(final Resources res) {
+ try {
+ return res.getString(nameResId, replacementString);
+ } catch (Resources.NotFoundException e) {
+ // TODO: Remove this catch when InputMethodManager.getCurrentInputMethodSubtype
+ // is fixed.
+ Log.w(TAG, "Unknown subtype: mode=" + subtype.getMode()
+ + " nameResId=" + subtype.getNameResId()
+ + " locale=" + subtype.getLocale()
+ + " extra=" + subtype.getExtraValue()
+ + "\n" + DebugLogUtils.getStackTrace());
+ return "";
+ }
+ }
+ };
+ return StringUtils.capitalizeFirstCodePoint(
+ getSubtypeName.runInLocale(sResources, displayLocale), displayLocale);
+ }
+
+ @Nonnull
+ public static Locale getSubtypeLocale(@Nonnull final InputMethodSubtype subtype) {
+ final String localeString = subtype.getLocale();
+ return LocaleUtils.constructLocaleFromString(localeString);
+ }
+
+ @Nonnull
+ public static String getKeyboardLayoutSetDisplayName(
+ @Nonnull final InputMethodSubtype subtype) {
+ final String layoutName = getKeyboardLayoutSetName(subtype);
+ return getKeyboardLayoutSetDisplayName(layoutName);
+ }
+
+ @Nonnull
+ public static String getKeyboardLayoutSetDisplayName(@Nonnull final String layoutName) {
+ return sKeyboardLayoutToDisplayNameMap.get(layoutName);
+ }
+
+ @Nonnull
+ public static String getKeyboardLayoutSetName(final InputMethodSubtype subtype) {
+ String keyboardLayoutSet = subtype.getExtraValueOf(KEYBOARD_LAYOUT_SET);
+ if (keyboardLayoutSet == null) {
+ // This subtype doesn't have a keyboardLayoutSet extra value, so lookup its keyboard
+ // layout set in sLocaleAndExtraValueToKeyboardLayoutSetMap to keep it compatible with
+ // pre-JellyBean.
+ final String key = subtype.getLocale() + ":" + subtype.getExtraValue();
+ keyboardLayoutSet = sLocaleAndExtraValueToKeyboardLayoutSetMap.get(key);
+ }
+ // TODO: Remove this null check when InputMethodManager.getCurrentInputMethodSubtype is
+ // fixed.
+ if (keyboardLayoutSet == null) {
+ android.util.Log.w(TAG, "KeyboardLayoutSet not found, use QWERTY: " +
+ "locale=" + subtype.getLocale() + " extraValue=" + subtype.getExtraValue());
+ return QWERTY;
+ }
+ return keyboardLayoutSet;
+ }
+
+ public static String getCombiningRulesExtraValue(final InputMethodSubtype subtype) {
+ return subtype.getExtraValueOf(COMBINING_RULES);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/SuggestionResults.java b/java/src/org/kelar/inputmethod/latin/utils/SuggestionResults.java
new file mode 100644
index 000000000..0cd484704
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/SuggestionResults.java
@@ -0,0 +1,89 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import org.kelar.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
+import org.kelar.inputmethod.latin.define.ProductionFlags;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.TreeSet;
+
+/**
+ * A TreeSet of SuggestedWordInfo that is bounded in size and throws everything that's smaller
+ * than its limit
+ */
+public final class SuggestionResults extends TreeSet<SuggestedWordInfo> {
+ public final ArrayList<SuggestedWordInfo> mRawSuggestions;
+ // TODO: Instead of a boolean , we may want to include the context of this suggestion results,
+ // such as {@link NgramContext}.
+ public final boolean mIsBeginningOfSentence;
+ public final boolean mFirstSuggestionExceedsConfidenceThreshold;
+ private final int mCapacity;
+
+ public SuggestionResults(final int capacity, final boolean isBeginningOfSentence,
+ final boolean firstSuggestionExceedsConfidenceThreshold) {
+ this(sSuggestedWordInfoComparator, capacity, isBeginningOfSentence,
+ firstSuggestionExceedsConfidenceThreshold);
+ }
+
+ private SuggestionResults(final Comparator<SuggestedWordInfo> comparator, final int capacity,
+ final boolean isBeginningOfSentence,
+ final boolean firstSuggestionExceedsConfidenceThreshold) {
+ super(comparator);
+ mCapacity = capacity;
+ if (ProductionFlags.INCLUDE_RAW_SUGGESTIONS) {
+ mRawSuggestions = new ArrayList<>();
+ } else {
+ mRawSuggestions = null;
+ }
+ mIsBeginningOfSentence = isBeginningOfSentence;
+ mFirstSuggestionExceedsConfidenceThreshold = firstSuggestionExceedsConfidenceThreshold;
+ }
+
+ @Override
+ public boolean add(final SuggestedWordInfo e) {
+ if (size() < mCapacity) return super.add(e);
+ if (comparator().compare(e, last()) > 0) return false;
+ super.add(e);
+ pollLast(); // removes the last element
+ return true;
+ }
+
+ @Override
+ public boolean addAll(final Collection<? extends SuggestedWordInfo> e) {
+ if (null == e) return false;
+ return super.addAll(e);
+ }
+
+ static final class SuggestedWordInfoComparator implements Comparator<SuggestedWordInfo> {
+ // This comparator ranks the word info with the higher frequency first. That's because
+ // that's the order we want our elements in.
+ @Override
+ public int compare(final SuggestedWordInfo o1, final SuggestedWordInfo o2) {
+ if (o1.mScore > o2.mScore) return -1;
+ if (o1.mScore < o2.mScore) return 1;
+ if (o1.mCodePointCount < o2.mCodePointCount) return -1;
+ if (o1.mCodePointCount > o2.mCodePointCount) return 1;
+ return o1.mWord.compareTo(o2.mWord);
+ }
+ }
+
+ private static final SuggestedWordInfoComparator sSuggestedWordInfoComparator =
+ new SuggestedWordInfoComparator();
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/TargetPackageInfoGetterTask.java b/java/src/org/kelar/inputmethod/latin/utils/TargetPackageInfoGetterTask.java
new file mode 100644
index 000000000..1d0a3e942
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/TargetPackageInfoGetterTask.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2012 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.os.AsyncTask;
+import android.util.LruCache;
+
+import org.kelar.inputmethod.compat.AppWorkaroundsUtils;
+
+public final class TargetPackageInfoGetterTask extends
+ AsyncTask<String, Void, PackageInfo> {
+ private static final int MAX_CACHE_ENTRIES = 64; // arbitrary
+ private static final LruCache<String, PackageInfo> sCache = new LruCache<>(MAX_CACHE_ENTRIES);
+
+ public static PackageInfo getCachedPackageInfo(final String packageName) {
+ if (null == packageName) return null;
+ return sCache.get(packageName);
+ }
+
+ public static void removeCachedPackageInfo(final String packageName) {
+ sCache.remove(packageName);
+ }
+
+ private Context mContext;
+ private final AsyncResultHolder<AppWorkaroundsUtils> mResult;
+
+ public TargetPackageInfoGetterTask(final Context context,
+ final AsyncResultHolder<AppWorkaroundsUtils> result) {
+ mContext = context;
+ mResult = result;
+ }
+
+ @Override
+ protected PackageInfo doInBackground(final String... packageName) {
+ final PackageManager pm = mContext.getPackageManager();
+ mContext = null; // Bazooka-powered anti-leak device
+ try {
+ final PackageInfo packageInfo = pm.getPackageInfo(packageName[0], 0 /* flags */);
+ sCache.put(packageName[0], packageInfo);
+ return packageInfo;
+ } catch (android.content.pm.PackageManager.NameNotFoundException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected void onPostExecute(final PackageInfo info) {
+ mResult.set(new AppWorkaroundsUtils(info));
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/TextRange.java b/java/src/org/kelar/inputmethod/latin/utils/TextRange.java
new file mode 100644
index 000000000..2b0397d8e
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/TextRange.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.text.Spanned;
+import android.text.style.SuggestionSpan;
+
+import java.util.Arrays;
+
+/**
+ * Represents a range of text, relative to the current cursor position.
+ */
+public final class TextRange {
+ private final CharSequence mTextAtCursor;
+ private final int mWordAtCursorStartIndex;
+ private final int mWordAtCursorEndIndex;
+ private final int mCursorIndex;
+
+ public final CharSequence mWord;
+ public final boolean mHasUrlSpans;
+
+ public int getNumberOfCharsInWordBeforeCursor() {
+ return mCursorIndex - mWordAtCursorStartIndex;
+ }
+
+ public int getNumberOfCharsInWordAfterCursor() {
+ return mWordAtCursorEndIndex - mCursorIndex;
+ }
+
+ public int length() {
+ return mWord.length();
+ }
+
+ /**
+ * Gets the suggestion spans that are put squarely on the word, with the exact start
+ * and end of the span matching the boundaries of the word.
+ * @return the list of spans.
+ */
+ public SuggestionSpan[] getSuggestionSpansAtWord() {
+ if (!(mTextAtCursor instanceof Spanned && mWord instanceof Spanned)) {
+ return new SuggestionSpan[0];
+ }
+ final Spanned text = (Spanned)mTextAtCursor;
+ // Note: it's fine to pass indices negative or greater than the length of the string
+ // to the #getSpans() method. The reason we need to get from -1 to +1 is that, the
+ // spans were cut at the cursor position, and #getSpans(start, end) does not return
+ // spans that end at `start' or begin at `end'. Consider the following case:
+ // this| is (The | symbolizes the cursor position
+ // ---- ---
+ // In this case, the cursor is in position 4, so the 0~7 span has been split into
+ // a 0~4 part and a 4~7 part.
+ // If we called #getSpans(0, 4) in this case, we would only get the part from 0 to 4
+ // of the span, and not the part from 4 to 7, so we would not realize the span actually
+ // extends from 0 to 7. But if we call #getSpans(-1, 5) we'll get both the 0~4 and
+ // the 4~7 spans and we can merge them accordingly.
+ // Any span starting more than 1 char away from the word boundaries in any direction
+ // does not touch the word, so we don't need to consider it. That's why requesting
+ // -1 ~ +1 is enough.
+ // Of course this is only relevant if the cursor is at one end of the word. If it's
+ // in the middle, the -1 and +1 are not necessary, but they are harmless.
+ final SuggestionSpan[] spans = text.getSpans(mWordAtCursorStartIndex - 1,
+ mWordAtCursorEndIndex + 1, SuggestionSpan.class);
+ int readIndex = 0;
+ int writeIndex = 0;
+ for (; readIndex < spans.length; ++readIndex) {
+ final SuggestionSpan span = spans[readIndex];
+ // The span may be null, as we null them when we find duplicates. Cf a few lines
+ // down.
+ if (null == span) continue;
+ // Tentative span start and end. This may be modified later if we realize the
+ // same span is also applied to other parts of the string.
+ int spanStart = text.getSpanStart(span);
+ int spanEnd = text.getSpanEnd(span);
+ for (int i = readIndex + 1; i < spans.length; ++i) {
+ if (span.equals(spans[i])) {
+ // We found the same span somewhere else. Read the new extent of this
+ // span, and adjust our values accordingly.
+ spanStart = Math.min(spanStart, text.getSpanStart(spans[i]));
+ spanEnd = Math.max(spanEnd, text.getSpanEnd(spans[i]));
+ // ...and mark the span as processed.
+ spans[i] = null;
+ }
+ }
+ if (spanStart == mWordAtCursorStartIndex && spanEnd == mWordAtCursorEndIndex) {
+ // If the span does not start and stop here, ignore it. It probably extends
+ // past the start or end of the word, as happens in missing space correction
+ // or EasyEditSpans put by voice input.
+ spans[writeIndex++] = spans[readIndex];
+ }
+ }
+ return writeIndex == readIndex ? spans : Arrays.copyOfRange(spans, 0, writeIndex);
+ }
+
+ public TextRange(final CharSequence textAtCursor, final int wordAtCursorStartIndex,
+ final int wordAtCursorEndIndex, final int cursorIndex, final boolean hasUrlSpans) {
+ if (wordAtCursorStartIndex < 0 || cursorIndex < wordAtCursorStartIndex
+ || cursorIndex > wordAtCursorEndIndex
+ || wordAtCursorEndIndex > textAtCursor.length()) {
+ throw new IndexOutOfBoundsException();
+ }
+ mTextAtCursor = textAtCursor;
+ mWordAtCursorStartIndex = wordAtCursorStartIndex;
+ mWordAtCursorEndIndex = wordAtCursorEndIndex;
+ mCursorIndex = cursorIndex;
+ mHasUrlSpans = hasUrlSpans;
+ mWord = mTextAtCursor.subSequence(mWordAtCursorStartIndex, mWordAtCursorEndIndex);
+ }
+} \ No newline at end of file
diff --git a/java/src/org/kelar/inputmethod/latin/utils/TypefaceUtils.java b/java/src/org/kelar/inputmethod/latin/utils/TypefaceUtils.java
new file mode 100644
index 000000000..5e0a985ed
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/TypefaceUtils.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 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 org.kelar.inputmethod.latin.utils;
+
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.Typeface;
+import android.util.SparseArray;
+
+public final class TypefaceUtils {
+ private static final char[] KEY_LABEL_REFERENCE_CHAR = { 'M' };
+ private static final char[] KEY_NUMERIC_HINT_LABEL_REFERENCE_CHAR = { '8' };
+
+ private TypefaceUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ // This sparse array caches key label text height in pixel indexed by key label text size.
+ private static final SparseArray<Float> sTextHeightCache = new SparseArray<>();
+ // Working variable for the following method.
+ private static final Rect sTextHeightBounds = new Rect();
+
+ private static float getCharHeight(final char[] referenceChar, final Paint paint) {
+ final int key = getCharGeometryCacheKey(referenceChar[0], paint);
+ synchronized (sTextHeightCache) {
+ final Float cachedValue = sTextHeightCache.get(key);
+ if (cachedValue != null) {
+ return cachedValue;
+ }
+
+ paint.getTextBounds(referenceChar, 0, 1, sTextHeightBounds);
+ final float height = sTextHeightBounds.height();
+ sTextHeightCache.put(key, height);
+ return height;
+ }
+ }
+
+ // This sparse array caches key label text width in pixel indexed by key label text size.
+ private static final SparseArray<Float> sTextWidthCache = new SparseArray<>();
+ // Working variable for the following method.
+ private static final Rect sTextWidthBounds = new Rect();
+
+ private static float getCharWidth(final char[] referenceChar, final Paint paint) {
+ final int key = getCharGeometryCacheKey(referenceChar[0], paint);
+ synchronized (sTextWidthCache) {
+ final Float cachedValue = sTextWidthCache.get(key);
+ if (cachedValue != null) {
+ return cachedValue;
+ }
+
+ paint.getTextBounds(referenceChar, 0, 1, sTextWidthBounds);
+ final float width = sTextWidthBounds.width();
+ sTextWidthCache.put(key, width);
+ return width;
+ }
+ }
+
+ private static int getCharGeometryCacheKey(final char referenceChar, final Paint paint) {
+ final int labelSize = (int)paint.getTextSize();
+ final Typeface face = paint.getTypeface();
+ final int codePointOffset = referenceChar << 15;
+ if (face == Typeface.DEFAULT) {
+ return codePointOffset + labelSize;
+ } else if (face == Typeface.DEFAULT_BOLD) {
+ return codePointOffset + labelSize + 0x1000;
+ } else if (face == Typeface.MONOSPACE) {
+ return codePointOffset + labelSize + 0x2000;
+ } else {
+ return codePointOffset + labelSize;
+ }
+ }
+
+ public static float getReferenceCharHeight(final Paint paint) {
+ return getCharHeight(KEY_LABEL_REFERENCE_CHAR, paint);
+ }
+
+ public static float getReferenceCharWidth(final Paint paint) {
+ return getCharWidth(KEY_LABEL_REFERENCE_CHAR, paint);
+ }
+
+ public static float getReferenceDigitWidth(final Paint paint) {
+ return getCharWidth(KEY_NUMERIC_HINT_LABEL_REFERENCE_CHAR, paint);
+ }
+
+ // Working variable for the following method.
+ private static final Rect sStringWidthBounds = new Rect();
+
+ public static float getStringWidth(final String string, final Paint paint) {
+ synchronized (sStringWidthBounds) {
+ paint.getTextBounds(string, 0, string.length(), sStringWidthBounds);
+ return sStringWidthBounds.width();
+ }
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/UncachedInputMethodManagerUtils.java b/java/src/org/kelar/inputmethod/latin/utils/UncachedInputMethodManagerUtils.java
new file mode 100644
index 000000000..fd29bf9e3
--- /dev/null
+++ b/java/src/org/kelar/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 org.kelar.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;
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/ViewLayoutUtils.java b/java/src/org/kelar/inputmethod/latin/utils/ViewLayoutUtils.java
new file mode 100644
index 000000000..3940375bb
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/ViewLayoutUtils.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2011 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 org.kelar.inputmethod.latin.utils;
+
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewGroup.MarginLayoutParams;
+import android.view.Window;
+import android.view.WindowManager;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.RelativeLayout;
+
+public final class ViewLayoutUtils {
+ private ViewLayoutUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static MarginLayoutParams newLayoutParam(final ViewGroup placer, final int width,
+ final int height) {
+ if (placer instanceof FrameLayout) {
+ return new FrameLayout.LayoutParams(width, height);
+ } else if (placer instanceof RelativeLayout) {
+ return new RelativeLayout.LayoutParams(width, height);
+ } else if (placer == null) {
+ throw new NullPointerException("placer is null");
+ } else {
+ throw new IllegalArgumentException("placer is neither FrameLayout nor RelativeLayout: "
+ + placer.getClass().getName());
+ }
+ }
+
+ public static void placeViewAt(final View view, final int x, final int y, final int w,
+ final int h) {
+ final ViewGroup.LayoutParams lp = view.getLayoutParams();
+ if (lp instanceof MarginLayoutParams) {
+ final MarginLayoutParams marginLayoutParams = (MarginLayoutParams)lp;
+ marginLayoutParams.width = w;
+ marginLayoutParams.height = h;
+ marginLayoutParams.setMargins(x, y, 0, 0);
+ }
+ }
+
+ public static void updateLayoutHeightOf(final Window window, final int layoutHeight) {
+ final WindowManager.LayoutParams params = window.getAttributes();
+ if (params != null && params.height != layoutHeight) {
+ params.height = layoutHeight;
+ window.setAttributes(params);
+ }
+ }
+
+ public static void updateLayoutHeightOf(final View view, final int layoutHeight) {
+ final ViewGroup.LayoutParams params = view.getLayoutParams();
+ if (params != null && params.height != layoutHeight) {
+ params.height = layoutHeight;
+ view.setLayoutParams(params);
+ }
+ }
+
+ public static void updateLayoutGravityOf(final View view, final int layoutGravity) {
+ final ViewGroup.LayoutParams lp = view.getLayoutParams();
+ if (lp instanceof LinearLayout.LayoutParams) {
+ final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)lp;
+ if (params.gravity != layoutGravity) {
+ params.gravity = layoutGravity;
+ view.setLayoutParams(params);
+ }
+ } else if (lp instanceof FrameLayout.LayoutParams) {
+ final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)lp;
+ if (params.gravity != layoutGravity) {
+ params.gravity = layoutGravity;
+ view.setLayoutParams(params);
+ }
+ } else {
+ throw new IllegalArgumentException("Layout parameter doesn't have gravity: "
+ + lp.getClass().getName());
+ }
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/WordInputEventForPersonalization.java b/java/src/org/kelar/inputmethod/latin/utils/WordInputEventForPersonalization.java
new file mode 100644
index 000000000..6e7f0603b
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/WordInputEventForPersonalization.java
@@ -0,0 +1,106 @@
+/*
+ * 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 org.kelar.inputmethod.latin.utils;
+
+import android.util.Log;
+
+import org.kelar.inputmethod.annotations.UsedForTesting;
+import org.kelar.inputmethod.latin.NgramContext;
+import org.kelar.inputmethod.latin.common.StringUtils;
+import org.kelar.inputmethod.latin.define.DecoderSpecificConstants;
+import org.kelar.inputmethod.latin.settings.SpacingAndPunctuations;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+// Note: this class is used as a parameter type of a native method. You should be careful when you
+// rename this class or field name. See BinaryDictionary#addMultipleDictionaryEntriesNative().
+public final class WordInputEventForPersonalization {
+ private static final String TAG = WordInputEventForPersonalization.class.getSimpleName();
+ private static final boolean DEBUG_TOKEN = false;
+
+ public final int[] mTargetWord;
+ public final int mPrevWordsCount;
+ public final int[][] mPrevWordArray =
+ new int[DecoderSpecificConstants.MAX_PREV_WORD_COUNT_FOR_N_GRAM][];
+ public final boolean[] mIsPrevWordBeginningOfSentenceArray =
+ new boolean[DecoderSpecificConstants.MAX_PREV_WORD_COUNT_FOR_N_GRAM];
+ // Time stamp in seconds.
+ public final int mTimestamp;
+
+ @UsedForTesting
+ public WordInputEventForPersonalization(final CharSequence targetWord,
+ final NgramContext ngramContext, final int timestamp) {
+ mTargetWord = StringUtils.toCodePointArray(targetWord);
+ mPrevWordsCount = ngramContext.getPrevWordCount();
+ ngramContext.outputToArray(mPrevWordArray, mIsPrevWordBeginningOfSentenceArray);
+ mTimestamp = timestamp;
+ }
+
+ // Process a list of words and return a list of {@link WordInputEventForPersonalization}
+ // objects.
+ public static ArrayList<WordInputEventForPersonalization> createInputEventFrom(
+ final List<String> tokens, final int timestamp,
+ final SpacingAndPunctuations spacingAndPunctuations, final Locale locale) {
+ final ArrayList<WordInputEventForPersonalization> inputEvents = new ArrayList<>();
+ final int N = tokens.size();
+ NgramContext ngramContext = NgramContext.EMPTY_PREV_WORDS_INFO;
+ for (int i = 0; i < N; ++i) {
+ final String tempWord = tokens.get(i);
+ if (StringUtils.isEmptyStringOrWhiteSpaces(tempWord)) {
+ // just skip this token
+ if (DEBUG_TOKEN) {
+ Log.d(TAG, "--- isEmptyStringOrWhiteSpaces: \"" + tempWord + "\"");
+ }
+ continue;
+ }
+ if (!DictionaryInfoUtils.looksValidForDictionaryInsertion(
+ tempWord, spacingAndPunctuations)) {
+ if (DEBUG_TOKEN) {
+ Log.d(TAG, "--- not looksValidForDictionaryInsertion: \""
+ + tempWord + "\"");
+ }
+ // Sentence terminator found. Split.
+ // TODO: Detect whether the context is beginning-of-sentence.
+ ngramContext = NgramContext.EMPTY_PREV_WORDS_INFO;
+ continue;
+ }
+ if (DEBUG_TOKEN) {
+ Log.d(TAG, "--- word: \"" + tempWord + "\"");
+ }
+ final WordInputEventForPersonalization inputEvent =
+ detectWhetherVaildWordOrNotAndGetInputEvent(
+ ngramContext, tempWord, timestamp, locale);
+ if (inputEvent == null) {
+ continue;
+ }
+ inputEvents.add(inputEvent);
+ ngramContext = ngramContext.getNextNgramContext(new NgramContext.WordInfo(tempWord));
+ }
+ return inputEvents;
+ }
+
+ private static WordInputEventForPersonalization detectWhetherVaildWordOrNotAndGetInputEvent(
+ final NgramContext ngramContext, final String targetWord, final int timestamp,
+ final Locale locale) {
+ if (locale == null) {
+ return null;
+ }
+ return new WordInputEventForPersonalization(targetWord, ngramContext, timestamp);
+ }
+}
diff --git a/java/src/org/kelar/inputmethod/latin/utils/XmlParseUtils.java b/java/src/org/kelar/inputmethod/latin/utils/XmlParseUtils.java
new file mode 100644
index 000000000..cbd476413
--- /dev/null
+++ b/java/src/org/kelar/inputmethod/latin/utils/XmlParseUtils.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2011 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 org.kelar.inputmethod.latin.utils;
+
+import android.content.res.TypedArray;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+
+public final class XmlParseUtils {
+ private XmlParseUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ @SuppressWarnings("serial")
+ public static class ParseException extends XmlPullParserException {
+ public ParseException(final String msg, final XmlPullParser parser) {
+ super(msg + " at " + parser.getPositionDescription());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public static final class IllegalStartTag extends ParseException {
+ public IllegalStartTag(final XmlPullParser parser, final String tag, final String parent) {
+ super("Illegal start tag " + tag + " in " + parent, parser);
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public static final class IllegalEndTag extends ParseException {
+ public IllegalEndTag(final XmlPullParser parser, final String tag, final String parent) {
+ super("Illegal end tag " + tag + " in " + parent, parser);
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public static final class IllegalAttribute extends ParseException {
+ public IllegalAttribute(final XmlPullParser parser, final String tag,
+ final String attribute) {
+ super("Tag " + tag + " has illegal attribute " + attribute, parser);
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public static final class NonEmptyTag extends ParseException{
+ public NonEmptyTag(final XmlPullParser parser, final String tag) {
+ super(tag + " must be empty tag", parser);
+ }
+ }
+
+ public static void checkEndTag(final String tag, final XmlPullParser parser)
+ throws XmlPullParserException, IOException {
+ if (parser.next() == XmlPullParser.END_TAG && tag.equals(parser.getName()))
+ return;
+ throw new NonEmptyTag(parser, tag);
+ }
+
+ public static void checkAttributeExists(final TypedArray attr, final int attrId,
+ final String attrName, final String tag, final XmlPullParser parser)
+ throws XmlPullParserException {
+ if (attr.hasValue(attrId)) {
+ return;
+ }
+ throw new ParseException(
+ "No " + attrName + " attribute found in <" + tag + "/>", parser);
+ }
+}