aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--common/src/com/android/inputmethod/latin/common/StringUtils.java47
-rw-r--r--java/res/xml/method.xml4
-rw-r--r--java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java10
-rw-r--r--java/src/com/android/inputmethod/keyboard/Key.java27
-rw-r--r--java/src/com/android/inputmethod/keyboard/MainKeyboardView.java4
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java14
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryFacilitator.java6
-rw-r--r--java/src/com/android/inputmethod/latin/LatinIME.java41
-rw-r--r--java/src/com/android/inputmethod/latin/PunctuationSuggestions.java4
-rw-r--r--java/src/com/android/inputmethod/latin/RichInputMethodManager.java9
-rw-r--r--java/src/com/android/inputmethod/latin/Suggest.java49
-rw-r--r--java/src/com/android/inputmethod/latin/SuggestedWords.java95
-rw-r--r--java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java2
-rw-r--r--java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java83
-rw-r--r--java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java3
-rw-r--r--native/dicttoolkit/NativeFileList.mk1
-rw-r--r--native/dicttoolkit/src/utils/arguments_parser.cpp16
-rw-r--r--native/dicttoolkit/src/utils/arguments_parser.h4
-rw-r--r--native/dicttoolkit/tests/utils/arguments_parser_test.cpp73
-rw-r--r--native/jni/Android.mk3
-rw-r--r--native/jni/src/utils/char_utils.cpp7
-rw-r--r--tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java24
-rw-r--r--tests/src/com/android/inputmethod/keyboard/KeyboardLayoutSetTestsBase.java2
-rw-r--r--tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyOutput.java2
-rw-r--r--tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyVisual.java3
-rw-r--r--tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java2
-rw-r--r--tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java15
-rw-r--r--tests/src/com/android/inputmethod/latin/common/StringUtilsTests.java (renamed from tests/src/com/android/inputmethod/latin/utils/StringAndJsonUtilsTests.java)354
-rw-r--r--tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java36
-rw-r--r--tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java169
-rw-r--r--tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java14
31 files changed, 746 insertions, 377 deletions
diff --git a/common/src/com/android/inputmethod/latin/common/StringUtils.java b/common/src/com/android/inputmethod/latin/common/StringUtils.java
index be7260308..572f0cd9b 100644
--- a/common/src/com/android/inputmethod/latin/common/StringUtils.java
+++ b/common/src/com/android/inputmethod/latin/common/StringUtils.java
@@ -201,22 +201,22 @@ public final class StringUtils {
public static String capitalizeFirstCodePoint(@Nonnull final String s,
@Nonnull final Locale locale) {
if (s.length() <= 1) {
- return s.toUpperCase(locale);
+ return s.toUpperCase(getLocaleUsedForToTitleCase(locale));
}
// Please refer to the comment below in
// {@link #capitalizeFirstAndDowncaseRest(String,Locale)} as this has the same shortcomings
final int cutoff = s.offsetByCodePoints(0, 1);
- return s.substring(0, cutoff).toUpperCase(locale) + s.substring(cutoff);
+ return s.substring(0, cutoff).toUpperCase(getLocaleUsedForToTitleCase(locale))
+ + s.substring(cutoff);
}
@Nonnull
public static String capitalizeFirstAndDowncaseRest(@Nonnull final String s,
@Nonnull final Locale locale) {
if (s.length() <= 1) {
- return s.toUpperCase(locale);
+ return s.toUpperCase(getLocaleUsedForToTitleCase(locale));
}
// TODO: fix the bugs below
- // - This does not work for Greek, because it returns upper case instead of title case.
// - It does not work for Serbian, because it fails to account for the "lj" character,
// which should be "Lj" in title case and "LJ" in upper case.
// - It does not work for Dutch, because it fails to account for the "ij" digraph when it's
@@ -224,7 +224,8 @@ public final class StringUtils {
// be capitalized as "IJ" as if they were a single letter in most words (not all). If the
// unicode char for the ligature is used however, it works.
final int cutoff = s.offsetByCodePoints(0, 1);
- return s.substring(0, cutoff).toUpperCase(locale) + s.substring(cutoff).toLowerCase(locale);
+ return s.substring(0, cutoff).toUpperCase(getLocaleUsedForToTitleCase(locale))
+ + s.substring(cutoff).toLowerCase(locale);
}
@Nonnull
@@ -584,25 +585,35 @@ public final class StringUtils {
return bytes;
}
- @Nullable
- public static String toUpperCaseOfStringForLocale(@Nullable final String text,
- final boolean needsToUpperCase, @Nonnull final Locale locale) {
- if (text == null || !needsToUpperCase) {
- return text;
+ private static final String LANGUAGE_GREEK = "el";
+
+ @Nonnull
+ private static Locale getLocaleUsedForToTitleCase(@Nonnull final Locale locale) {
+ // In Greek locale {@link String#toUpperCase(Locale)} eliminates accents from its result.
+ // In order to get accented upper case letter, {@link Locale#ROOT} should be used.
+ if (LANGUAGE_GREEK.equals(locale.getLanguage())) {
+ return Locale.ROOT;
}
- return text.toUpperCase(locale);
+ return locale;
}
- public static int toUpperCaseOfCodeForLocale(final int code, final boolean needsToUpperCase,
+ @Nullable
+ public static String toTitleCaseOfKeyLabel(@Nullable final String label,
@Nonnull final Locale locale) {
- if (!Constants.isLetterCode(code) || !needsToUpperCase) {
+ if (label == null) {
+ return label;
+ }
+ return label.toUpperCase(getLocaleUsedForToTitleCase(locale));
+ }
+
+ public static int toTitleCaseOfKeyCode(final int code, @Nonnull final Locale locale) {
+ if (!Constants.isLetterCode(code)) {
return code;
}
- final String text = newSingleCodePointString(code);
- final String casedText = toUpperCaseOfStringForLocale(
- text, needsToUpperCase, locale);
- return codePointCount(casedText) == 1
- ? casedText.codePointAt(0) : Constants.CODE_UNSPECIFIED;
+ final String label = newSingleCodePointString(code);
+ final String titleCaseLabel = toTitleCaseOfKeyLabel(label, locale);
+ return codePointCount(titleCaseLabel) == 1
+ ? titleCaseLabel.codePointAt(0) : Constants.CODE_UNSPECIFIED;
}
public static int getTrailingSingleQuotesCount(@Nonnull final CharSequence charSequence) {
diff --git a/java/res/xml/method.xml b/java/res/xml/method.xml
index 5f05e8b18..e14862206 100644
--- a/java/res/xml/method.xml
+++ b/java/res/xml/method.xml
@@ -28,7 +28,7 @@
be_BY: Belarusian (Belarus)/east_slavic
bg: Bulgarian/bulgarian
bg: Bulgarian/bulgarian_bds
- bn_BD: Bengali (Bangladesh)/bengali_akkhor # This is a preliminary keyboard layout.
+ bn_BD: Bengali (Bangladesh)/bengali_akkhor
bn_IN: Bengali (India)/bengali
ca: Catalan/spanish
cs: Czech/qwertz
@@ -181,8 +181,6 @@
android:imeSubtypeExtraValue="KeyboardLayoutSet=bulgarian_bds,EmojiCapable"
android:isAsciiCapable="false"
/>
- <!-- TODO: This Bengali (Bangladesh) keyboard is a preliminary layout.
- This isn't based on the final specification. -->
<subtype android:icon="@drawable/ic_ime_switcher_dark"
android:label="@string/subtype_generic"
android:subtypeId="0xa2144b0c"
diff --git a/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java b/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java
index 2762a9f25..b0072eebe 100644
--- a/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java
+++ b/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java
@@ -152,12 +152,16 @@ public final class AccessibilityUtils {
* will occur when a key is typed.
*
* @param suggestedWords the list of suggested auto-correction words
- * @param typedWord the currently typed word
*/
- public void setAutoCorrection(final SuggestedWords suggestedWords, final String typedWord) {
+ public void setAutoCorrection(final SuggestedWords suggestedWords) {
if (suggestedWords.mWillAutoCorrect) {
mAutoCorrectionWord = suggestedWords.getWord(SuggestedWords.INDEX_OF_AUTO_CORRECTION);
- mTypedWord = typedWord;
+ final SuggestedWords.SuggestedWordInfo typedWordInfo = suggestedWords.mTypedWordInfo;
+ if (null == typedWordInfo) {
+ mTypedWord = null;
+ } else {
+ mTypedWord = typedWordInfo.mWord;
+ }
} else {
mAutoCorrectionWord = null;
mTypedWord = null;
diff --git a/java/src/com/android/inputmethod/keyboard/Key.java b/java/src/com/android/inputmethod/keyboard/Key.java
index 6b2094b9e..06e552e3d 100644
--- a/java/src/com/android/inputmethod/keyboard/Key.java
+++ b/java/src/com/android/inputmethod/keyboard/Key.java
@@ -341,17 +341,24 @@ public class Key implements Comparable<Key> {
// code point nor as a surrogate pair.
mLabel = new StringBuilder().appendCodePoint(code).toString();
} else {
- mLabel = StringUtils.toUpperCaseOfStringForLocale(
- KeySpecParser.getLabel(keySpec), needsToUpcase, localeForUpcasing);
+ final String label = KeySpecParser.getLabel(keySpec);
+ mLabel = needsToUpcase
+ ? StringUtils.toTitleCaseOfKeyLabel(label, localeForUpcasing)
+ : label;
}
if ((mLabelFlags & LABEL_FLAGS_DISABLE_HINT_LABEL) != 0) {
mHintLabel = null;
} else {
- mHintLabel = StringUtils.toUpperCaseOfStringForLocale(style.getString(keyAttr,
- R.styleable.Keyboard_Key_keyHintLabel), needsToUpcase, localeForUpcasing);
+ final String hintLabel = style.getString(
+ keyAttr, R.styleable.Keyboard_Key_keyHintLabel);
+ mHintLabel = needsToUpcase
+ ? StringUtils.toTitleCaseOfKeyLabel(hintLabel, localeForUpcasing)
+ : hintLabel;
+ }
+ String outputText = KeySpecParser.getOutputText(keySpec);
+ if (needsToUpcase) {
+ outputText = StringUtils.toTitleCaseOfKeyLabel(outputText, localeForUpcasing);
}
- String outputText = StringUtils.toUpperCaseOfStringForLocale(
- KeySpecParser.getOutputText(keySpec), needsToUpcase, localeForUpcasing);
// Choose the first letter of the label as primary code if not specified.
if (code == CODE_UNSPECIFIED && TextUtils.isEmpty(outputText)
&& !TextUtils.isEmpty(mLabel)) {
@@ -377,12 +384,14 @@ public class Key implements Comparable<Key> {
mCode = CODE_OUTPUT_TEXT;
}
} else {
- mCode = StringUtils.toUpperCaseOfCodeForLocale(code, needsToUpcase, localeForUpcasing);
+ mCode = needsToUpcase ? StringUtils.toTitleCaseOfKeyCode(code, localeForUpcasing)
+ : code;
}
final int altCodeInAttr = KeySpecParser.parseCode(
style.getString(keyAttr, R.styleable.Keyboard_Key_altCode), CODE_UNSPECIFIED);
- final int altCode = StringUtils.toUpperCaseOfCodeForLocale(
- altCodeInAttr, needsToUpcase, localeForUpcasing);
+ final int altCode = needsToUpcase
+ ? StringUtils.toTitleCaseOfKeyCode(altCodeInAttr, localeForUpcasing)
+ : altCodeInAttr;
mOptionalAttributes = OptionalAttributes.newInstance(outputText, altCode,
disabledIconId, visualInsetsLeft, visualInsetsRight);
mKeyVisualAttributes = KeyVisualAttributes.newInstance(keyAttr);
diff --git a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
index cba7ff2a2..06b87bd9a 100644
--- a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
@@ -57,7 +57,6 @@ import com.android.inputmethod.latin.RichInputMethodSubtype;
import com.android.inputmethod.latin.SuggestedWords;
import com.android.inputmethod.latin.common.Constants;
import com.android.inputmethod.latin.common.CoordinateUtils;
-import com.android.inputmethod.latin.common.StringUtils;
import com.android.inputmethod.latin.settings.DebugSettings;
import com.android.inputmethod.latin.utils.TypefaceUtils;
@@ -874,8 +873,7 @@ public final class MainKeyboardView extends KeyboardView implements DrawingProxy
final Locale[] locales = subtype.getLocales();
final String[] languages = new String[locales.length];
for (int i = 0; i < locales.length; ++i) {
- languages[i] = StringUtils.toUpperCaseOfStringForLocale(
- locales[i].getLanguage(), true /* needsToUpperCase */, Locale.ROOT);
+ languages[i] = locales[i].getLanguage().toUpperCase(Locale.ROOT);
}
return TextUtils.join(" / ", languages);
}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java b/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java
index b1a3887d8..87c96cc0d 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java
@@ -55,10 +55,11 @@ public final class MoreKeySpec {
if (TextUtils.isEmpty(moreKeySpec)) {
throw new KeySpecParser.KeySpecParserError("Empty more key spec");
}
- mLabel = StringUtils.toUpperCaseOfStringForLocale(
- KeySpecParser.getLabel(moreKeySpec), needsToUpperCase, locale);
- final int code = StringUtils.toUpperCaseOfCodeForLocale(
- KeySpecParser.getCode(moreKeySpec), needsToUpperCase, locale);
+ final String label = KeySpecParser.getLabel(moreKeySpec);
+ mLabel = needsToUpperCase ? StringUtils.toTitleCaseOfKeyLabel(label, locale) : label;
+ final int codeInSpec = KeySpecParser.getCode(moreKeySpec);
+ final int code = needsToUpperCase ? StringUtils.toTitleCaseOfKeyCode(codeInSpec, locale)
+ : codeInSpec;
if (code == Constants.CODE_UNSPECIFIED) {
// Some letter, for example German Eszett (U+00DF: "ß"), has multiple characters
// upper case representation ("SS").
@@ -66,8 +67,9 @@ public final class MoreKeySpec {
mOutputText = mLabel;
} else {
mCode = code;
- mOutputText = StringUtils.toUpperCaseOfStringForLocale(
- KeySpecParser.getOutputText(moreKeySpec), needsToUpperCase, locale);
+ final String outputText = KeySpecParser.getOutputText(moreKeySpec);
+ mOutputText = needsToUpperCase
+ ? StringUtils.toTitleCaseOfKeyLabel(outputText, locale) : outputText;
}
mIconId = KeySpecParser.getIconId(moreKeySpec);
}
diff --git a/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java b/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java
index d23639a0d..b24fdea55 100644
--- a/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java
+++ b/java/src/com/android/inputmethod/latin/DictionaryFacilitator.java
@@ -266,6 +266,12 @@ public class DictionaryFacilitator {
}
final DictionaryGroup newMostProbableDictionaryGroup =
findDictionaryGroupWithLocale(mDictionaryGroups, locale);
+ if (null == newMostProbableDictionaryGroup) {
+ // It seems this may happen as a race condition; pressing the globe key and space
+ // in quick succession could commit a word out of a dictionary that's not in the
+ // facilitator any more. In this case, just not changing things is fine.
+ return;
+ }
mMostProbableDictionaryGroup.mWeightForTypingInLocale =
DictionaryGroup.WEIGHT_FOR_TYPING_IN_NOT_MOST_PROBABLE_LANGUAGE;
mMostProbableDictionaryGroup.mWeightForGesturingInLocale =
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index 719656b07..7b7b6d35e 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -201,8 +201,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private static final int MSG_RESET_CACHES = 7;
private static final int MSG_WAIT_FOR_DICTIONARY_LOAD = 8;
private static final int MSG_DEALLOCATE_MEMORY = 9;
+ private static final int MSG_RESUME_SUGGESTIONS_FOR_START_INPUT = 10;
// Update this when adding new messages
- private static final int MSG_LAST = MSG_DEALLOCATE_MEMORY;
+ private static final int MSG_LAST = MSG_RESUME_SUGGESTIONS_FOR_START_INPUT;
private static final int ARG1_NOT_GESTURE_INPUT = 0;
private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1;
@@ -257,7 +258,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
break;
case MSG_RESUME_SUGGESTIONS:
latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor(
- latinIme.mSettings.getCurrent(),
+ latinIme.mSettings.getCurrent(), false /* forStartInput */,
+ latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId());
+ break;
+ case MSG_RESUME_SUGGESTIONS_FOR_START_INPUT:
+ latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor(
+ latinIme.mSettings.getCurrent(), true /* forStartInput */,
latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId());
break;
case MSG_REOPEN_DICTIONARIES:
@@ -303,7 +309,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
sendMessage(obtainMessage(MSG_REOPEN_DICTIONARIES));
}
- public void postResumeSuggestions(final boolean shouldDelay) {
+ private void postResumeSuggestionsInternal(final boolean shouldDelay,
+ final boolean forStartInput) {
final LatinIME latinIme = getOwnerInstance();
if (latinIme == null) {
return;
@@ -312,14 +319,25 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
return;
}
removeMessages(MSG_RESUME_SUGGESTIONS);
+ removeMessages(MSG_RESUME_SUGGESTIONS_FOR_START_INPUT);
+ final int message = forStartInput ? MSG_RESUME_SUGGESTIONS_FOR_START_INPUT
+ : MSG_RESUME_SUGGESTIONS;
if (shouldDelay) {
- sendMessageDelayed(obtainMessage(MSG_RESUME_SUGGESTIONS),
+ sendMessageDelayed(obtainMessage(message),
mDelayInMillisecondsToUpdateSuggestions);
} else {
- sendMessage(obtainMessage(MSG_RESUME_SUGGESTIONS));
+ sendMessage(obtainMessage(message));
}
}
+ public void postResumeSuggestions(final boolean shouldDelay) {
+ postResumeSuggestionsInternal(shouldDelay, false /* forStartInput */);
+ }
+
+ public void postResumeSuggestionsForStartInput(final boolean shouldDelay) {
+ postResumeSuggestionsInternal(shouldDelay, true /* forStartInput */);
+ }
+
public void postResetCaches(final boolean tryResumeSuggestions, final int remainingTries) {
removeMessages(MSG_RESET_CACHES);
sendMessage(obtainMessage(MSG_RESET_CACHES, tryResumeSuggestions ? 1 : 0,
@@ -969,7 +987,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// initialSelStart and initialSelEnd sometimes are lying. Make a best effort to
// work around this bug.
mInputLogic.mConnection.tryFixLyingCursorPosition();
- mHandler.postResumeSuggestions(true /* shouldDelay */);
+ mHandler.postResumeSuggestionsForStartInput(true /* shouldDelay */);
needToCallLoadKeyboardLater = false;
}
} else {
@@ -1171,9 +1189,13 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
SuggestedWords.getFromApplicationSpecifiedCompletions(
applicationSpecifiedCompletions);
final SuggestedWords suggestedWords = new SuggestedWords(applicationSuggestedWords,
- null /* rawSuggestions */, false /* typedWordValid */, false /* willAutoCorrect */,
+ null /* rawSuggestions */,
+ null /* typedWord */,
+ false /* typedWordValid */,
+ false /* willAutoCorrect */,
false /* isObsoleteSuggestions */,
- SuggestedWords.INPUT_STYLE_APPLICATION_SPECIFIED /* inputStyle */);
+ SuggestedWords.INPUT_STYLE_APPLICATION_SPECIFIED /* inputStyle */,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
// When in fullscreen mode, show completions generated by the application forcibly
setSuggestedWords(suggestedWords);
}
@@ -1615,8 +1637,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
// Cache the auto-correction in accessibility code so we can speak it if the user
// touches a key that will insert it.
- AccessibilityUtils.getInstance().setAutoCorrection(suggestedWords,
- suggestedWords.mTypedWord);
+ AccessibilityUtils.getInstance().setAutoCorrection(suggestedWords);
}
// Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
diff --git a/java/src/com/android/inputmethod/latin/PunctuationSuggestions.java b/java/src/com/android/inputmethod/latin/PunctuationSuggestions.java
index a65304cd0..555bbc7d4 100644
--- a/java/src/com/android/inputmethod/latin/PunctuationSuggestions.java
+++ b/java/src/com/android/inputmethod/latin/PunctuationSuggestions.java
@@ -33,10 +33,12 @@ public final class PunctuationSuggestions extends SuggestedWords {
private PunctuationSuggestions(final ArrayList<SuggestedWordInfo> punctuationsList) {
super(punctuationsList,
null /* rawSuggestions */,
+ null /* typedWord */,
false /* typedWordValid */,
false /* hasAutoCorrectionCandidate */,
false /* isObsoleteSuggestions */,
- INPUT_STYLE_NONE /* inputStyle */);
+ INPUT_STYLE_NONE /* inputStyle */,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
}
/**
diff --git a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java
index a1ac55a20..686c3a4b2 100644
--- a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java
+++ b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java
@@ -110,7 +110,7 @@ public class RichInputMethodManager {
// Initialize additional subtypes.
SubtypeLocaleUtils.init(context);
- final InputMethodSubtype[] additionalSubtypes = getAdditionalSubtypes(context);
+ final InputMethodSubtype[] additionalSubtypes = getAdditionalSubtypes();
setAdditionalInputMethodSubtypes(additionalSubtypes);
final ConnectivityManager connectivityManager =
@@ -119,11 +119,10 @@ public class RichInputMethodManager {
mIsNetworkConnected = (info != null && info.isConnected());
}
- public InputMethodSubtype[] getAdditionalSubtypes(final Context context) {
- SubtypeLocaleUtils.init(context);
- final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ public InputMethodSubtype[] getAdditionalSubtypes() {
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
final String prefAdditionalSubtypes = Settings.readPrefAdditionalSubtypes(
- prefs, context.getResources());
+ prefs, mContext.getResources());
return AdditionalSubtypeUtils.createAdditionalSubtypesArray(prefAdditionalSubtypes);
}
diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java
index ee8d3f8cb..2d0ec42a6 100644
--- a/java/src/com/android/inputmethod/latin/Suggest.java
+++ b/java/src/com/android/inputmethod/latin/Suggest.java
@@ -32,6 +32,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
+import javax.annotation.Nullable;
+
/**
* This class loads a dictionary and provides a list of suggestions for a given sequence of
* characters. This includes corrections and completions.
@@ -133,23 +135,26 @@ public final class Suggest {
final SettingsValuesForSuggestion settingsValuesForSuggestion,
final int inputStyleIfNotPrediction, final boolean isCorrectionEnabled,
final int sequenceNumber, final OnGetSuggestedWordsCallback callback) {
- final String typedWord = wordComposer.getTypedWord();
- final int trailingSingleQuotesCount = StringUtils.getTrailingSingleQuotesCount(typedWord);
+ final String typedWordString = wordComposer.getTypedWord();
+ final int trailingSingleQuotesCount =
+ StringUtils.getTrailingSingleQuotesCount(typedWordString);
final String consideredWord = trailingSingleQuotesCount > 0
- ? typedWord.substring(0, typedWord.length() - trailingSingleQuotesCount)
- : typedWord;
+ ? typedWordString.substring(0, typedWordString.length() - trailingSingleQuotesCount)
+ : typedWordString;
final SuggestionResults suggestionResults = mDictionaryFacilitator.getSuggestionResults(
wordComposer, ngramContext, proximityInfo.getNativeProximityInfo(),
settingsValuesForSuggestion, SESSION_ID_TYPING);
+ final Locale mostProbableLocale = mDictionaryFacilitator.getMostProbableLocale();
final ArrayList<SuggestedWordInfo> suggestionsContainer =
getTransformedSuggestedWordInfoList(wordComposer, suggestionResults,
trailingSingleQuotesCount,
// For transforming suggestions that don't come for any dictionary, we
// use the currently most probable locale as it's our best bet.
- mDictionaryFacilitator.getMostProbableLocale());
- final boolean didRemoveTypedWord =
- SuggestedWordInfo.removeDups(wordComposer.getTypedWord(), suggestionsContainer);
+ mostProbableLocale);
+ @Nullable final Dictionary sourceDictionaryOfRemovedWord =
+ SuggestedWordInfo.removeDupsAndReturnSourceOfTypedWord(wordComposer.getTypedWord(),
+ mostProbableLocale /* preferredLocale */, suggestionsContainer);
final String whitelistedWord = getWhitelistedWordOrNull(suggestionsContainer);
final boolean resultsArePredictions = !wordComposer.isComposingWord();
@@ -157,7 +162,7 @@ public final class Suggest {
// We allow auto-correction if we have a whitelisted word, or if the word had more than
// one char and was not suggested.
final boolean allowsToBeAutoCorrected = (null != whitelistedWord)
- || (consideredWord.length() > 1 && !didRemoveTypedWord);
+ || (consideredWord.length() > 1 && (null == sourceDictionaryOfRemovedWord));
final boolean hasAutoCorrection;
// If correction is not enabled, we never auto-correct. This is for example for when
@@ -206,17 +211,20 @@ public final class Suggest {
}
}
- if (!TextUtils.isEmpty(typedWord)) {
- suggestionsContainer.add(0, new SuggestedWordInfo(typedWord,
- SuggestedWordInfo.MAX_SCORE, SuggestedWordInfo.KIND_TYPED,
- Dictionary.DICTIONARY_USER_TYPED,
- SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
- SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */));
+ final SuggestedWordInfo typedWordInfo = new SuggestedWordInfo(typedWordString,
+ SuggestedWordInfo.MAX_SCORE, SuggestedWordInfo.KIND_TYPED,
+ null == sourceDictionaryOfRemovedWord ? Dictionary.DICTIONARY_USER_TYPED
+ : sourceDictionaryOfRemovedWord,
+ SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
+ SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */);
+ if (!TextUtils.isEmpty(typedWordString)) {
+ suggestionsContainer.add(0, typedWordInfo);
}
final ArrayList<SuggestedWordInfo> suggestionsList;
if (DBG && !suggestionsContainer.isEmpty()) {
- suggestionsList = getSuggestionsInfoListWithDebugInfo(typedWord, suggestionsContainer);
+ suggestionsList = getSuggestionsInfoListWithDebugInfo(typedWordString,
+ suggestionsContainer);
} else {
suggestionsList = suggestionsContainer;
}
@@ -230,7 +238,7 @@ public final class Suggest {
inputStyle = inputStyleIfNotPrediction;
}
callback.onGetSuggestedWords(new SuggestedWords(suggestionsList,
- suggestionResults.mRawSuggestions, typedWord,
+ suggestionResults.mRawSuggestions, typedWordInfo,
// TODO: this first argument is lying. If this is a whitelisted word which is an
// actual word, it says typedWordValid = false, which looks wrong. We should either
// rename the attribute or change the value.
@@ -272,7 +280,8 @@ public final class Suggest {
final SuggestedWordInfo rejected = suggestionsContainer.remove(0);
suggestionsContainer.add(1, rejected);
}
- SuggestedWordInfo.removeDups(null /* typedWord */, suggestionsContainer);
+ SuggestedWordInfo.removeDupsAndReturnSourceOfTypedWord(null /* typedWord */,
+ null /* preferredLocale */, suggestionsContainer);
// For some reason some suggestions with MIN_VALUE are making their way here.
// TODO: Find a more robust way to detect distracters.
@@ -286,12 +295,12 @@ public final class Suggest {
// (typedWordValid=true), not as an "auto correct word" (willAutoCorrect=false).
// Note that because this method is never used to get predictions, there is no need to
// modify inputType such in getSuggestedWordsForNonBatchInput.
- final String pseudoTypedWord = suggestionsContainer.isEmpty() ? null
- : suggestionsContainer.get(0).mWord;
+ final SuggestedWordInfo pseudoTypedWordInfo = suggestionsContainer.isEmpty() ? null
+ : suggestionsContainer.get(0);
callback.onGetSuggestedWords(new SuggestedWords(suggestionsContainer,
suggestionResults.mRawSuggestions,
- pseudoTypedWord,
+ pseudoTypedWordInfo,
true /* typedWordValid */,
false /* willAutoCorrect */,
false /* isObsoleteSuggestions */,
diff --git a/java/src/com/android/inputmethod/latin/SuggestedWords.java b/java/src/com/android/inputmethod/latin/SuggestedWords.java
index bddeac495..cbf48f0c0 100644
--- a/java/src/com/android/inputmethod/latin/SuggestedWords.java
+++ b/java/src/com/android/inputmethod/latin/SuggestedWords.java
@@ -27,8 +27,10 @@ import com.android.inputmethod.latin.define.DebugFlags;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
+import java.util.Locale;
import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
public class SuggestedWords {
public static final int INDEX_OF_TYPED_WORD = 0;
@@ -50,10 +52,12 @@ public class SuggestedWords {
private static final ArrayList<SuggestedWordInfo> EMPTY_WORD_INFO_LIST = new ArrayList<>(0);
@Nonnull
private static final SuggestedWords EMPTY = new SuggestedWords(
- EMPTY_WORD_INFO_LIST, null /* rawSuggestions */, false /* typedWordValid */,
- false /* willAutoCorrect */, false /* isObsoleteSuggestions */, INPUT_STYLE_NONE);
+ EMPTY_WORD_INFO_LIST, null /* rawSuggestions */, null /* typedWord */,
+ false /* typedWordValid */, false /* willAutoCorrect */,
+ false /* isObsoleteSuggestions */, INPUT_STYLE_NONE, NOT_A_SEQUENCE_NUMBER);
- public final String mTypedWord;
+ @Nullable
+ public final SuggestedWordInfo mTypedWordInfo;
public final boolean mTypedWordValid;
// Note: this INCLUDES cases where the word will auto-correct to itself. A good definition
// of what this flag means would be "the top suggestion is strong enough to auto-correct",
@@ -64,25 +68,14 @@ public class SuggestedWords {
// INPUT_STYLE_* constants above.
public final int mInputStyle;
public final int mSequenceNumber; // Sequence number for auto-commit.
+ @Nonnull
protected final ArrayList<SuggestedWordInfo> mSuggestedWordInfoList;
+ @Nullable
public final ArrayList<SuggestedWordInfo> mRawSuggestions;
- public SuggestedWords(final ArrayList<SuggestedWordInfo> suggestedWordInfoList,
- final ArrayList<SuggestedWordInfo> rawSuggestions,
- final boolean typedWordValid,
- final boolean willAutoCorrect,
- final boolean isObsoleteSuggestions,
- final int inputStyle) {
- this(suggestedWordInfoList, rawSuggestions,
- (suggestedWordInfoList.isEmpty() || isPrediction(inputStyle)) ? null
- : suggestedWordInfoList.get(INDEX_OF_TYPED_WORD).mWord,
- typedWordValid, willAutoCorrect,
- isObsoleteSuggestions, inputStyle, NOT_A_SEQUENCE_NUMBER);
- }
-
- public SuggestedWords(final ArrayList<SuggestedWordInfo> suggestedWordInfoList,
- final ArrayList<SuggestedWordInfo> rawSuggestions,
- final String typedWord,
+ public SuggestedWords(@Nonnull final ArrayList<SuggestedWordInfo> suggestedWordInfoList,
+ @Nullable final ArrayList<SuggestedWordInfo> rawSuggestions,
+ @Nullable final SuggestedWordInfo typedWordInfo,
final boolean typedWordValid,
final boolean willAutoCorrect,
final boolean isObsoleteSuggestions,
@@ -95,7 +88,7 @@ public class SuggestedWords {
mIsObsoleteSuggestions = isObsoleteSuggestions;
mInputStyle = inputStyle;
mSequenceNumber = sequenceNumber;
- mTypedWord = typedWord;
+ mTypedWordInfo = typedWordInfo;
}
public boolean isEmpty() {
@@ -211,14 +204,12 @@ public class SuggestedWords {
// Should get rid of the first one (what the user typed previously) from suggestions
// and replace it with what the user currently typed.
public static ArrayList<SuggestedWordInfo> getTypedWordAndPreviousSuggestions(
- final String typedWord, final SuggestedWords previousSuggestions) {
+ @Nonnull final SuggestedWordInfo typedWordInfo,
+ @Nonnull final SuggestedWords previousSuggestions) {
final ArrayList<SuggestedWordInfo> suggestionsList = new ArrayList<>();
final HashSet<String> alreadySeen = new HashSet<>();
- suggestionsList.add(new SuggestedWordInfo(typedWord, SuggestedWordInfo.MAX_SCORE,
- SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED,
- SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
- SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */));
- alreadySeen.add(typedWord.toString());
+ suggestionsList.add(typedWordInfo);
+ alreadySeen.add(typedWordInfo.mWord);
final int previousSize = previousSuggestions.size();
for (int index = 1; index < previousSize; index++) {
final SuggestedWordInfo prevWordInfo = previousSuggestions.getInfo(index);
@@ -365,37 +356,53 @@ public class SuggestedWords {
}
// This will always remove the higher index if a duplicate is found.
- public static boolean removeDups(final String typedWord,
- ArrayList<SuggestedWordInfo> candidates) {
+ // Returns null if the typed word is not found. Always return the dictionary for the
+ // highest suggestion matching the locale if found, otherwise return the dictionary for
+ // the highest suggestion.
+ @Nullable
+ public static Dictionary removeDupsAndReturnSourceOfTypedWord(
+ @Nullable final String typedWord,
+ @Nullable final Locale preferredLocale,
+ @Nonnull ArrayList<SuggestedWordInfo> candidates) {
if (candidates.isEmpty()) {
- return false;
+ return null;
}
- final boolean didRemoveTypedWord;
+ final Dictionary sourceDictionaryOfTypedWord;
if (!TextUtils.isEmpty(typedWord)) {
- didRemoveTypedWord = removeSuggestedWordInfoFrom(typedWord, candidates,
- -1 /* startIndexExclusive */);
+ sourceDictionaryOfTypedWord =
+ removeSuggestedWordInfoFromListAndReturnSourceDictionary(typedWord,
+ preferredLocale, candidates, -1 /* startIndexExclusive */);
} else {
- didRemoveTypedWord = false;
+ sourceDictionaryOfTypedWord = null;
}
for (int i = 0; i < candidates.size(); ++i) {
- removeSuggestedWordInfoFrom(candidates.get(i).mWord, candidates,
- i /* startIndexExclusive */);
+ removeSuggestedWordInfoFromListAndReturnSourceDictionary(candidates.get(i).mWord,
+ null /* preferredLocale */, candidates, i /* startIndexExclusive */);
}
- return didRemoveTypedWord;
+ return sourceDictionaryOfTypedWord;
}
- private static boolean removeSuggestedWordInfoFrom(final String word,
- final ArrayList<SuggestedWordInfo> candidates, final int startIndexExclusive) {
- boolean didRemove = false;
+ @Nullable
+ private static Dictionary removeSuggestedWordInfoFromListAndReturnSourceDictionary(
+ @Nonnull final String word, @Nullable final Locale preferredLocale,
+ @Nonnull final ArrayList<SuggestedWordInfo> candidates,
+ final int startIndexExclusive) {
+ Dictionary sourceDictionaryOfTypedWord = null;
for (int i = startIndexExclusive + 1; i < candidates.size(); ++i) {
final SuggestedWordInfo previous = candidates.get(i);
if (word.equals(previous.mWord)) {
- didRemove = true;
+ if (null == sourceDictionaryOfTypedWord
+ || (null != preferredLocale
+ && preferredLocale.equals(previous.mSourceDict.mLocale))) {
+ if (Dictionary.TYPE_USER_HISTORY != previous.mSourceDict.mDictType) {
+ sourceDictionaryOfTypedWord = previous.mSourceDict;
+ }
+ }
candidates.remove(i);
--i;
}
}
- return didRemove;
+ return sourceDictionaryOfTypedWord;
}
}
@@ -423,8 +430,10 @@ public class SuggestedWords {
info.mSourceDict, SuggestedWordInfo.NOT_AN_INDEX,
SuggestedWordInfo.NOT_A_CONFIDENCE));
}
- return new SuggestedWords(newSuggestions, null /* rawSuggestions */, mTypedWordValid,
- mWillAutoCorrect, mIsObsoleteSuggestions, INPUT_STYLE_TAIL_BATCH);
+ return new SuggestedWords(newSuggestions, null /* rawSuggestions */,
+ newSuggestions.isEmpty() ? null : newSuggestions.get(0) /* typedWordInfo */,
+ mTypedWordValid, mWillAutoCorrect, mIsObsoleteSuggestions, INPUT_STYLE_TAIL_BATCH,
+ NOT_A_SEQUENCE_NUMBER);
}
/**
diff --git a/java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java b/java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java
index 123ab208c..982d4c690 100644
--- a/java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java
+++ b/java/src/com/android/inputmethod/latin/SystemBroadcastReceiver.java
@@ -69,7 +69,7 @@ public final class SystemBroadcastReceiver extends BroadcastReceiver {
// subtypes when the package is replaced.
RichInputMethodManager.init(context);
final RichInputMethodManager richImm = RichInputMethodManager.getInstance();
- final InputMethodSubtype[] additionalSubtypes = richImm.getAdditionalSubtypes(context);
+ final InputMethodSubtype[] additionalSubtypes = richImm.getAdditionalSubtypes();
richImm.setAdditionalInputMethodSubtypes(additionalSubtypes);
LauncherIconVisibilityManager.updateSetupWizardIconVisibility(context);
} else if (Intent.ACTION_BOOT_COMPLETED.equals(intentAction)) {
diff --git a/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java b/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java
index bafea178e..0185a04ef 100644
--- a/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java
+++ b/java/src/com/android/inputmethod/latin/inputlogic/InputLogic.java
@@ -255,7 +255,7 @@ public final class InputLogic {
handler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_TYPING);
final String text = performSpecificTldProcessingOnTextInput(rawText);
if (SpaceState.PHANTOM == mSpaceState) {
- promotePhantomSpace(settingsValues);
+ insertAutomaticSpaceIfOptionsAndTextAllow(settingsValues);
}
mConnection.commitText(text, 1);
StatsUtils.onWordCommitUserTyped(mEnteredText, mWordComposer.isBatchMode());
@@ -322,7 +322,7 @@ public final class InputLogic {
final int firstChar = Character.codePointAt(suggestion, 0);
if (!settingsValues.isWordSeparator(firstChar)
|| settingsValues.isUsuallyPrecededBySpace(firstChar)) {
- promotePhantomSpace(settingsValues);
+ insertAutomaticSpaceIfOptionsAndTextAllow(settingsValues);
}
}
@@ -584,7 +584,9 @@ public final class InputLogic {
if (candidate.mSourceDict.shouldAutoCommit(candidate)) {
final String[] commitParts = candidate.mWord.split(Constants.WORD_SEPARATOR, 2);
batchPointers.shift(candidate.mIndexOfTouchPointOfSecondWord);
- promotePhantomSpace(settingsValues);
+ if (SpaceState.PHANTOM == mSpaceState) {
+ insertAutomaticSpaceIfOptionsAndTextAllow(settingsValues);
+ }
mConnection.commitText(commitParts[0], 0);
StatsUtils.onWordCommitUserTyped(commitParts[0], mWordComposer.isBatchMode());
mSpaceState = SpaceState.PHANTOM;
@@ -621,11 +623,7 @@ public final class InputLogic {
} else {
// We can't use suggestedWords.getWord(SuggestedWords.INDEX_OF_TYPED_WORD)
// because it may differ from mWordComposer.mTypedWord.
- suggestedWordInfo = new SuggestedWordInfo(suggestedWords.mTypedWord,
- SuggestedWordInfo.MAX_SCORE,
- SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED,
- SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
- SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */);
+ suggestedWordInfo = suggestedWords.mTypedWordInfo;
}
mWordComposer.setAutoCorrection(suggestedWordInfo);
}
@@ -861,7 +859,7 @@ public final class InputLogic {
// Sanity check
throw new RuntimeException("Should not be composing here");
}
- promotePhantomSpace(settingsValues);
+ insertAutomaticSpaceIfOptionsAndTextAllow(settingsValues);
}
if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) {
@@ -972,7 +970,7 @@ public final class InputLogic {
}
if (needsPrecedingSpace) {
- promotePhantomSpace(settingsValues);
+ insertAutomaticSpaceIfOptionsAndTextAllow(settingsValues);
}
if (tryPerformDoubleSpacePeriod(event, inputTransaction)) {
@@ -1176,14 +1174,13 @@ public final class InputLogic {
StatsUtils.onBackspacePressed(totalDeletedLength);
}
}
- if (inputTransaction.mSettingsValues
- .isSuggestionsEnabledPerUserSettings()
+ if (inputTransaction.mSettingsValues.isSuggestionsEnabledPerUserSettings()
&& inputTransaction.mSettingsValues.mSpacingAndPunctuations
.mCurrentLanguageHasSpaces
&& !mConnection.isCursorFollowedByWordCharacter(
inputTransaction.mSettingsValues.mSpacingAndPunctuations)) {
restartSuggestionsOnWordTouchedByCursor(inputTransaction.mSettingsValues,
- currentKeyboardScriptId);
+ false /* forStartInput */, currentKeyboardScriptId);
}
}
}
@@ -1413,14 +1410,19 @@ public final class InputLogic {
new OnGetSuggestedWordsCallback() {
@Override
public void onGetSuggestedWords(final SuggestedWords suggestedWords) {
- final String typedWord = mWordComposer.getTypedWord();
+ final String typedWordString = mWordComposer.getTypedWord();
+ final SuggestedWordInfo typedWordInfo = new SuggestedWordInfo(
+ typedWordString, SuggestedWordInfo.MAX_SCORE,
+ SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED,
+ SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
+ SuggestedWordInfo.NOT_A_CONFIDENCE);
// Show new suggestions if we have at least one. Otherwise keep the old
// suggestions with the new typed word. Exception: if the length of the
// typed word is <= 1 (after a deletion typically) we clear old suggestions.
- if (suggestedWords.size() > 1 || typedWord.length() <= 1) {
+ if (suggestedWords.size() > 1 || typedWordString.length() <= 1) {
holder.set(suggestedWords);
} else {
- holder.set(retrieveOlderSuggestions(typedWord, mSuggestedWords));
+ holder.set(retrieveOlderSuggestions(typedWordInfo, mSuggestedWords));
}
}
}
@@ -1439,10 +1441,13 @@ public final class InputLogic {
* do nothing.
*
* @param settingsValues the current values of the settings.
- * suggestions in the suggestion list.
+ * @param forStartInput whether we're doing this in answer to starting the input (as opposed
+ * to a cursor move, for example). In ICS, there is a platform bug that we need to work
+ * around only when we come here at input start time.
*/
// TODO: make this private.
public void restartSuggestionsOnWordTouchedByCursor(final SettingsValues settingsValues,
+ final boolean forStartInput,
// TODO: remove this argument, put it into settingsValues
final int currentKeyboardScriptId) {
// HACK: We may want to special-case some apps that exhibit bad behavior in case of
@@ -1489,13 +1494,14 @@ public final class InputLogic {
final int numberOfCharsInWordBeforeCursor = range.getNumberOfCharsInWordBeforeCursor();
if (numberOfCharsInWordBeforeCursor > expectedCursorPosition) return;
final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<>();
- final String typedWord = range.mWord.toString();
- suggestions.add(new SuggestedWordInfo(typedWord,
+ final String typedWordString = range.mWord.toString();
+ final SuggestedWordInfo typedWordInfo = new SuggestedWordInfo(typedWordString,
SuggestedWords.MAX_SUGGESTIONS + 1,
SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED,
SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
- SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */));
- if (!isResumableWord(settingsValues, typedWord)) {
+ SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */);
+ suggestions.add(typedWordInfo);
+ if (!isResumableWord(settingsValues, typedWordString)) {
mSuggestionStripViewAccessor.setNeutralSuggestionStrip();
return;
}
@@ -1503,7 +1509,7 @@ public final class InputLogic {
for (final SuggestionSpan span : range.getSuggestionSpansAtWord()) {
for (final String s : span.getSuggestions()) {
++i;
- if (!TextUtils.equals(s, typedWord)) {
+ if (!TextUtils.equals(s, typedWordString)) {
suggestions.add(new SuggestedWordInfo(s,
SuggestedWords.MAX_SUGGESTIONS - i,
SuggestedWordInfo.KIND_RESUMED, Dictionary.DICTIONARY_RESUMED,
@@ -1513,12 +1519,14 @@ public final class InputLogic {
}
}
}
- final int[] codePoints = StringUtils.toCodePointArray(typedWord);
+ final int[] codePoints = StringUtils.toCodePointArray(typedWordString);
mWordComposer.setComposingWord(codePoints,
mLatinIME.getCoordinatesForCurrentKeyboard(codePoints));
mWordComposer.setCursorPositionWithinWord(
- typedWord.codePointCount(0, numberOfCharsInWordBeforeCursor));
- mConnection.maybeMoveTheCursorAroundAndRestoreToWorkaroundABug();
+ typedWordString.codePointCount(0, numberOfCharsInWordBeforeCursor));
+ if (forStartInput) {
+ mConnection.maybeMoveTheCursorAroundAndRestoreToWorkaroundABug();
+ }
mConnection.setComposingRegion(expectedCursorPosition - numberOfCharsInWordBeforeCursor,
expectedCursorPosition + range.getNumberOfCharsInWordAfterCursor());
if (suggestions.size() <= 1) {
@@ -1537,7 +1545,7 @@ public final class InputLogic {
// color of the word in the suggestion strip changes according to this parameter,
// and false gives the correct color.
final SuggestedWords suggestedWords = new SuggestedWords(suggestions,
- null /* rawSuggestions */, typedWord, false /* typedWordValid */,
+ null /* rawSuggestions */, typedWordInfo, false /* typedWordValid */,
false /* willAutoCorrect */, false /* isObsoleteSuggestions */,
SuggestedWords.INPUT_STYLE_RECORRECTION, SuggestedWords.NOT_A_SEQUENCE_NUMBER);
doShowSuggestionsAndClearAutoCorrectionIndicator(suggestedWords);
@@ -1870,20 +1878,21 @@ public final class InputLogic {
* Make a {@link com.android.inputmethod.latin.SuggestedWords} object containing a typed word
* and obsolete suggestions.
* See {@link com.android.inputmethod.latin.SuggestedWords#getTypedWordAndPreviousSuggestions(
- * String, com.android.inputmethod.latin.SuggestedWords)}.
- * @param typedWord The typed word as a string.
+ * SuggestedWordInfo, com.android.inputmethod.latin.SuggestedWords)}.
+ * @param typedWordInfo The typed word as a SuggestedWordInfo.
* @param previousSuggestedWords The previously suggested words.
* @return Obsolete suggestions with the newly typed word.
*/
- static SuggestedWords retrieveOlderSuggestions(final String typedWord,
+ static SuggestedWords retrieveOlderSuggestions(final SuggestedWordInfo typedWordInfo,
final SuggestedWords previousSuggestedWords) {
final SuggestedWords oldSuggestedWords = previousSuggestedWords.isPunctuationSuggestions()
? SuggestedWords.getEmptyInstance() : previousSuggestedWords;
final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions =
- SuggestedWords.getTypedWordAndPreviousSuggestions(typedWord, oldSuggestedWords);
+ SuggestedWords.getTypedWordAndPreviousSuggestions(typedWordInfo, oldSuggestedWords);
return new SuggestedWords(typedWordAndPreviousSuggestions, null /* rawSuggestions */,
- false /* typedWordValid */, false /* hasAutoCorrectionCandidate */,
- true /* isObsoleteSuggestions */, oldSuggestedWords.mInputStyle);
+ typedWordInfo, false /* typedWordValid */, false /* hasAutoCorrectionCandidate */,
+ true /* isObsoleteSuggestions */, oldSuggestedWords.mInputStyle,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
}
/**
@@ -1960,14 +1969,14 @@ public final class InputLogic {
}
/**
- * Promote a phantom space to an actual space.
+ * Insert an automatic space, if the options allow it.
*
- * This essentially inserts a space, and that's it. It just checks the options and the text
- * before the cursor are appropriate before doing it.
+ * This checks the options and the text before the cursor are appropriate before inserting
+ * an automatic space.
*
* @param settingsValues the current values of the settings.
*/
- private void promotePhantomSpace(final SettingsValues settingsValues) {
+ private void insertAutomaticSpaceIfOptionsAndTextAllow(final SettingsValues settingsValues) {
if (settingsValues.shouldInsertSpacesAutomatically()
&& settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces
&& !mConnection.textBeforeCursorLooksLikeURL()) {
@@ -1990,7 +1999,7 @@ public final class InputLogic {
}
mConnection.beginBatchEdit();
if (SpaceState.PHANTOM == mSpaceState) {
- promotePhantomSpace(settingsValues);
+ insertAutomaticSpaceIfOptionsAndTextAllow(settingsValues);
}
final SuggestedWordInfo autoCommitCandidate = mSuggestedWords.getAutoCommitCandidate();
// Commit except the last word for phrase gesture if the top suggestion is eligible for auto
diff --git a/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java b/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java
index 013f024c0..0e7f4717d 100644
--- a/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java
+++ b/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java
@@ -34,6 +34,7 @@ import java.util.HashMap;
import java.util.Locale;
import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
/**
* A helper class to deal with subtype locales.
@@ -273,7 +274,7 @@ public final class SubtypeLocaleUtils {
}
@Nonnull
- public static String getSubtypeNameForLogging(@Nonnull final InputMethodSubtype subtype) {
+ public static String getSubtypeNameForLogging(@Nullable final InputMethodSubtype subtype) {
if (subtype == null) {
return "<null subtype>";
}
diff --git a/native/dicttoolkit/NativeFileList.mk b/native/dicttoolkit/NativeFileList.mk
index d2c8c3a2c..9a547b054 100644
--- a/native/dicttoolkit/NativeFileList.mk
+++ b/native/dicttoolkit/NativeFileList.mk
@@ -39,5 +39,6 @@ LATIN_IME_DICT_TOOLKIT_TEST_FILES := \
$(addprefix offdevice_intermediate_dict/, \
offdevice_intermediate_dict_test.cpp) \
$(addprefix utils/, \
+ arguments_parser_test.cpp \
command_utils_test.cpp \
utf8_utils_test.cpp)
diff --git a/native/dicttoolkit/src/utils/arguments_parser.cpp b/native/dicttoolkit/src/utils/arguments_parser.cpp
index 039dae35b..52cc7b21d 100644
--- a/native/dicttoolkit/src/utils/arguments_parser.cpp
+++ b/native/dicttoolkit/src/utils/arguments_parser.cpp
@@ -16,18 +16,32 @@
#include "utils/arguments_parser.h"
+#include <unordered_set>
+
namespace latinime {
namespace dicttoolkit {
const int ArgumentSpec::UNLIMITED_COUNT = -1;
bool ArgumentsParser::validateSpecs() const {
+ std::unordered_set<std::string> argumentNameSet;
for (size_t i = 0; i < mArgumentSpecs.size() ; ++i) {
+ if (mArgumentSpecs[i].getMinCount() == 0 && mArgumentSpecs[i].getMaxCount() == 0) {
+ AKLOGE("minCount = maxCount = 0 for %s.", mArgumentSpecs[i].getName().c_str());
+ return false;
+ }
if (mArgumentSpecs[i].getMinCount() != mArgumentSpecs[i].getMaxCount()
&& i != mArgumentSpecs.size() - 1) {
- AKLOGE("Variable length argument must be at the end.");
+ AKLOGE("Variable length argument must be at the end.",
+ mArgumentSpecs[i].getName().c_str()v );
+ return false;
+ }
+ if (argumentNameSet.count(mArgumentSpecs[i].getName()) > 0) {
+ AKLOGE("Multiple arguments have the same name \"%s\".",
+ mArgumentSpecs[i].getName().c_str());
return false;
}
+ argumentNameSet.insert(mArgumentSpecs[i].getName());
}
return true;
}
diff --git a/native/dicttoolkit/src/utils/arguments_parser.h b/native/dicttoolkit/src/utils/arguments_parser.h
index be2dd8749..510a8722b 100644
--- a/native/dicttoolkit/src/utils/arguments_parser.h
+++ b/native/dicttoolkit/src/utils/arguments_parser.h
@@ -97,8 +97,8 @@ class ArgumentSpec {
class ArgumentsParser {
public:
- ArgumentsParser(std::unordered_map<std::string, OptionSpec> &&optionSpecs,
- std::vector<ArgumentSpec> &&argumentSpecs)
+ ArgumentsParser(const std::unordered_map<std::string, OptionSpec> &&optionSpecs,
+ const std::vector<ArgumentSpec> &&argumentSpecs)
: mOptionSpecs(std::move(optionSpecs)), mArgumentSpecs(std::move(argumentSpecs)) {}
const ArgumentsAndOptions parseArguments(const int argc, char **argv) const;
diff --git a/native/dicttoolkit/tests/utils/arguments_parser_test.cpp b/native/dicttoolkit/tests/utils/arguments_parser_test.cpp
new file mode 100644
index 000000000..e79425b87
--- /dev/null
+++ b/native/dicttoolkit/tests/utils/arguments_parser_test.cpp
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+
+#include "utils/arguments_parser.h"
+
+#include <gtest/gtest.h>
+
+namespace latinime {
+namespace dicttoolkit {
+namespace {
+
+TEST(ArgumentsParserTests, TestValitadeSpecs) {
+ {
+ std::unordered_map<std::string, OptionSpec> optionSpecs;
+ std::vector<ArgumentSpec> argumentSpecs;
+ EXPECT_TRUE(
+ ArgumentsParser(std::move(optionSpecs), std::move(argumentSpecs)).validateSpecs());
+ }
+ {
+ std::unordered_map<std::string, OptionSpec> optionSpecs;
+ optionSpecs["a"] = OptionSpec::keyValueOption("valueName", "default", "description");
+ const std::vector<ArgumentSpec> argumentSpecs = {
+ ArgumentSpec::singleArgument("name", "description"),
+ ArgumentSpec::variableLengthArguments("name2", 0 /* minCount */, 1 /* maxCount */,
+ "description2")
+ };
+ EXPECT_TRUE(
+ ArgumentsParser(std::move(optionSpecs), std::move(argumentSpecs)).validateSpecs());
+ }
+ {
+ const std::vector<ArgumentSpec> argumentSpecs = {
+ ArgumentSpec::variableLengthArguments("name", 0 /* minCount */, 0 /* maxCount */,
+ "description")
+ };
+ EXPECT_FALSE(ArgumentsParser(std::unordered_map<std::string, OptionSpec>(),
+ std::move(argumentSpecs)).validateSpecs());
+ }
+ {
+ const std::vector<ArgumentSpec> argumentSpecs = {
+ ArgumentSpec::singleArgument("name", "description"),
+ ArgumentSpec::variableLengthArguments("name", 0 /* minCount */, 1 /* maxCount */,
+ "description")
+ };
+ EXPECT_FALSE(ArgumentsParser(std::unordered_map<std::string, OptionSpec>(),
+ std::move(argumentSpecs)).validateSpecs());
+ }
+ {
+ const std::vector<ArgumentSpec> argumentSpecs = {
+ ArgumentSpec::variableLengthArguments("name", 0 /* minCount */, 1 /* maxCount */,
+ "description"),
+ ArgumentSpec::singleArgument("name2", "description2")
+ };
+ EXPECT_FALSE(ArgumentsParser(std::unordered_map<std::string, OptionSpec>(),
+ std::move(argumentSpecs)).validateSpecs());
+ }
+}
+
+} // namespace
+} // namespace dicttoolkit
+} // namespace latinime
diff --git a/native/jni/Android.mk b/native/jni/Android.mk
index 402cb3b67..6003a6f64 100644
--- a/native/jni/Android.mk
+++ b/native/jni/Android.mk
@@ -92,9 +92,6 @@ LOCAL_SDK_VERSION := 14
LOCAL_NDK_STL_VARIANT := c++_static
LOCAL_LDFLAGS += -ldl
-# TODO: Figure out what we should do with --hash-style=gnu for unbundled builds
-LOCAL_LDFLAGS += -Wl,--hash-style=sysv
-
include $(BUILD_SHARED_LIBRARY)
#################### Clean up the tmp vars
include $(LOCAL_PATH)/CleanupNativeFileList.mk
diff --git a/native/jni/src/utils/char_utils.cpp b/native/jni/src/utils/char_utils.cpp
index 3bb9055b2..a43e6dd62 100644
--- a/native/jni/src/utils/char_utils.cpp
+++ b/native/jni/src/utils/char_utils.cpp
@@ -1117,7 +1117,9 @@ static int compare_pair_capital(const void *a, const void *b) {
// TODO: Check if it's really acceptable to consider ø a diacritical variant of o
/* U+0100 */ 0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063,
/* U+0108 */ 0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064,
- /* U+0110 */ 0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065,
+ /* U+0110 */ 0x0046, 0x0064, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065,
+ // U+0110: Manually changed from 0110 to 0046
+ // U+0111: Manually changed from 0111 to 0064
/* U+0118 */ 0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067,
/* U+0120 */ 0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127,
/* U+0128 */ 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069,
@@ -1135,6 +1137,9 @@ static int compare_pair_capital(const void *a, const void *b) {
/* U+0170 */ 0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079,
/* U+0178 */ 0x0059, 0x005A, 0x007A, 0x005A, 0x007A, 0x005A, 0x007A, 0x0073,
/* U+0180 */ 0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187,
+ // TODO: A lot of letters are their own base code points, but for
+ // some (e.g. U+0180) it doesn't seem right. Ideally each code point should
+ // be checked individually with all languages it's used in.
/* U+0188 */ 0x0188, 0x0189, 0x018A, 0x018B, 0x018C, 0x018D, 0x018E, 0x018F,
/* U+0190 */ 0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197,
/* U+0198 */ 0x0198, 0x0199, 0x019A, 0x019B, 0x019C, 0x019D, 0x019E, 0x019F,
diff --git a/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java b/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java
index 1c320db1c..7bbf965f9 100644
--- a/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java
+++ b/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java
@@ -102,11 +102,11 @@ public class SuggestionSpanUtilsTest extends AndroidTestCase {
}
public void testGetTextWithSuggestionSpan() {
- final SuggestedWordInfo predicition1 =
+ final SuggestedWordInfo prediction1 =
createWordInfo("Quality", SuggestedWordInfo.KIND_PREDICTION);
- final SuggestedWordInfo predicition2 =
+ final SuggestedWordInfo prediction2 =
createWordInfo("Speed", SuggestedWordInfo.KIND_PREDICTION);
- final SuggestedWordInfo predicition3 =
+ final SuggestedWordInfo prediction3 =
createWordInfo("Price", SuggestedWordInfo.KIND_PREDICTION);
final SuggestedWordInfo typed =
@@ -122,13 +122,15 @@ public class SuggestionSpanUtilsTest extends AndroidTestCase {
// is specified.
{
final SuggestedWords predictedWords = new SuggestedWords(
- new ArrayList<>(Arrays.asList(predicition1, predicition2, predicition3)),
+ new ArrayList<>(Arrays.asList(prediction1, prediction2, prediction3)),
null /* rawSuggestions */,
+ null /* typedWord */,
false /* typedWordValid */,
false /* willAutoCorrect */,
false /* isObsoleteSuggestions */,
- SuggestedWords.INPUT_STYLE_PREDICTION);
- final String PICKED_WORD = predicition2.mWord;
+ SuggestedWords.INPUT_STYLE_PREDICTION,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
+ final String PICKED_WORD = prediction2.mWord;
assertNotSuggestionSpan(
PICKED_WORD,
SuggestionSpanUtils.getTextWithSuggestionSpan(getContext(), PICKED_WORD,
@@ -137,17 +139,19 @@ public class SuggestionSpanUtilsTest extends AndroidTestCase {
final ArrayList<SuggestedWordInfo> suggestedWordList = new ArrayList<>();
suggestedWordList.add(typed);
- suggestedWordList.add(predicition1);
- suggestedWordList.add(predicition2);
- suggestedWordList.add(predicition3);
+ suggestedWordList.add(prediction1);
+ suggestedWordList.add(prediction2);
+ suggestedWordList.add(prediction3);
suggestedWordList.addAll(Arrays.asList(corrections));
final SuggestedWords typedAndCollectedWords = new SuggestedWords(
suggestedWordList,
null /* rawSuggestions */,
+ null /* typedWord */,
false /* typedWordValid */,
false /* willAutoCorrect */,
false /* isObsoleteSuggestions */,
- SuggestedWords.INPUT_STYLE_TYPING);
+ SuggestedWords.INPUT_STYLE_TYPING,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
for (final SuggestedWordInfo pickedWord : suggestedWordList) {
final String PICKED_WORD = pickedWord.mWord;
diff --git a/tests/src/com/android/inputmethod/keyboard/KeyboardLayoutSetTestsBase.java b/tests/src/com/android/inputmethod/keyboard/KeyboardLayoutSetTestsBase.java
index 0246c49a1..7f828111d 100644
--- a/tests/src/com/android/inputmethod/keyboard/KeyboardLayoutSetTestsBase.java
+++ b/tests/src/com/android/inputmethod/keyboard/KeyboardLayoutSetTestsBase.java
@@ -75,7 +75,7 @@ public abstract class KeyboardLayoutSetTestsBase extends AndroidTestCase {
mRichImm = RichInputMethodManager.getInstance();
// Save and reset additional subtypes preference.
- mSavedAdditionalSubtypes = mRichImm.getAdditionalSubtypes(context);
+ mSavedAdditionalSubtypes = mRichImm.getAdditionalSubtypes();
final InputMethodSubtype[] predefinedAdditionalSubtypes =
AdditionalSubtypeUtils.createAdditionalSubtypesArray(
AdditionalSubtypeUtils.createPrefSubtypes(
diff --git a/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyOutput.java b/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyOutput.java
index 9bb5f187a..e7b0f091d 100644
--- a/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyOutput.java
+++ b/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyOutput.java
@@ -63,7 +63,7 @@ abstract class ExpectedKeyOutput {
final String codeString = StringUtils.newSingleCodePointString(mCode);
// A letter may have an upper case counterpart that consists of multiple code
// points, for instance the upper case of "ß" is "SS".
- return newInstance(codeString.toUpperCase(locale));
+ return newInstance(StringUtils.toTitleCaseOfKeyLabel(codeString, locale));
}
// A special negative value has no upper case.
return this;
diff --git a/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyVisual.java b/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyVisual.java
index 2f3a0c15f..3f9f12a2b 100644
--- a/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyVisual.java
+++ b/tests/src/com/android/inputmethod/keyboard/layout/expected/ExpectedKeyVisual.java
@@ -19,6 +19,7 @@ package com.android.inputmethod.keyboard.layout.expected;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.internal.KeyboardIconsSet;
import com.android.inputmethod.keyboard.internal.MoreKeySpec;
+import com.android.inputmethod.latin.common.StringUtils;
import java.util.Locale;
@@ -134,7 +135,7 @@ public abstract class ExpectedKeyVisual {
@Override
ExpectedKeyVisual toUpperCase(final Locale locale) {
- return new Label(mLabel.toUpperCase(locale));
+ return new Label(StringUtils.toTitleCaseOfKeyLabel(mLabel, locale));
}
@Override
diff --git a/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java b/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java
index aed7d6ad6..9c8e16511 100644
--- a/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java
+++ b/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java
@@ -76,7 +76,7 @@ public class RichInputMethodSubtypeTests extends AndroidTestCase {
mRichImm = RichInputMethodManager.getInstance();
// Save and reset additional subtypes
- mSavedAddtionalSubtypes = mRichImm.getAdditionalSubtypes(context);
+ mSavedAddtionalSubtypes = mRichImm.getAdditionalSubtypes();
final InputMethodSubtype[] predefinedAddtionalSubtypes =
AdditionalSubtypeUtils.createAdditionalSubtypesArray(
AdditionalSubtypeUtils.createPrefSubtypes(
diff --git a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java
index 90db75e39..f658d726b 100644
--- a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java
+++ b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java
@@ -89,9 +89,10 @@ public class SuggestedWordsTests extends AndroidTestCase {
public void testGetTypedWordInfoOrNull() {
final String TYPED_WORD = "typed";
+ final SuggestedWordInfo TYPED_WORD_INFO = createTypedWordInfo(TYPED_WORD);
final int NUMBER_OF_ADDED_SUGGESTIONS = 5;
final ArrayList<SuggestedWordInfo> list = new ArrayList<>();
- list.add(createTypedWordInfo(TYPED_WORD));
+ list.add(TYPED_WORD_INFO);
for (int i = 0; i < NUMBER_OF_ADDED_SUGGESTIONS; ++i) {
list.add(createCorrectionWordInfo(Integer.toString(i)));
}
@@ -99,10 +100,12 @@ public class SuggestedWordsTests extends AndroidTestCase {
// Make sure getTypedWordInfoOrNull() returns non-null object.
final SuggestedWords wordsWithTypedWord = new SuggestedWords(
list, null /* rawSuggestions */,
+ TYPED_WORD_INFO,
false /* typedWordValid */,
false /* willAutoCorrect */,
false /* isObsoleteSuggestions */,
- SuggestedWords.INPUT_STYLE_NONE);
+ SuggestedWords.INPUT_STYLE_NONE,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
final SuggestedWordInfo typedWord = wordsWithTypedWord.getTypedWordInfoOrNull();
assertNotNull(typedWord);
assertEquals(TYPED_WORD, typedWord.mWord);
@@ -111,10 +114,12 @@ public class SuggestedWordsTests extends AndroidTestCase {
list.remove(0);
final SuggestedWords wordsWithoutTypedWord = new SuggestedWords(
list, null /* rawSuggestions */,
+ null /* typedWord */,
false /* typedWordValid */,
false /* willAutoCorrect */,
false /* isObsoleteSuggestions */,
- SuggestedWords.INPUT_STYLE_NONE);
+ SuggestedWords.INPUT_STYLE_NONE,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
assertNull(wordsWithoutTypedWord.getTypedWordInfoOrNull());
// Make sure getTypedWordInfoOrNull() returns null.
@@ -122,10 +127,12 @@ public class SuggestedWordsTests extends AndroidTestCase {
final SuggestedWords emptySuggestedWords = new SuggestedWords(
new ArrayList<SuggestedWordInfo>(), null /* rawSuggestions */,
+ null /* typedWord */,
false /* typedWordValid */,
false /* willAutoCorrect */,
false /* isObsoleteSuggestions */,
- SuggestedWords.INPUT_STYLE_NONE);
+ SuggestedWords.INPUT_STYLE_NONE,
+ SuggestedWords.NOT_A_SEQUENCE_NUMBER);
assertNull(emptySuggestedWords.getTypedWordInfoOrNull());
assertNull(SuggestedWords.getEmptyInstance().getTypedWordInfoOrNull());
diff --git a/tests/src/com/android/inputmethod/latin/utils/StringAndJsonUtilsTests.java b/tests/src/com/android/inputmethod/latin/common/StringUtilsTests.java
index 0389fefb0..ec9d4be92 100644
--- a/tests/src/com/android/inputmethod/latin/utils/StringAndJsonUtilsTests.java
+++ b/tests/src/com/android/inputmethod/latin/common/StringUtilsTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,24 +14,177 @@
* limitations under the License.
*/
-package com.android.inputmethod.latin.utils;
+package com.android.inputmethod.latin.common;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
-import android.text.SpannableString;
-import android.text.Spanned;
-import android.text.SpannedString;
-import com.android.inputmethod.latin.common.Constants;
-import com.android.inputmethod.latin.common.StringUtils;
-import com.android.inputmethod.latin.utils.SpannableStringUtils;
-
-import java.util.Arrays;
-import java.util.List;
import java.util.Locale;
@SmallTest
-public class StringAndJsonUtilsTests extends AndroidTestCase {
+public class StringUtilsTests extends AndroidTestCase {
+ private static final Locale US = Locale.US;
+ private static final Locale GERMAN = Locale.GERMAN;
+ private static final Locale TURKEY = new Locale("tr", "TR");
+ private static final Locale GREECE = new Locale("el", "GR");
+
+ private static void assert_toTitleCaseOfKeyLabel(final Locale locale,
+ final String lowerCase, final String expected) {
+ assertEquals(lowerCase + " in " + locale, expected,
+ StringUtils.toTitleCaseOfKeyLabel(lowerCase, locale));
+ }
+
+ public void test_toTitleCaseOfKeyLabel() {
+ assert_toTitleCaseOfKeyLabel(US, null, null);
+ assert_toTitleCaseOfKeyLabel(US, "", "");
+ assert_toTitleCaseOfKeyLabel(US, "aeiou", "AEIOU");
+ // U+00E0: "à" LATIN SMALL LETTER A WITH GRAVE
+ // U+00E8: "è" LATIN SMALL LETTER E WITH GRAVE
+ // U+00EE: "î" LATIN SMALL LETTER I WITH CIRCUMFLEX
+ // U+00F6: "ö" LATIN SMALL LETTER O WITH DIAERESIS
+ // U+016B: "ū" LATIN SMALL LETTER U WITH MACRON
+ // U+00F1: "ñ" LATIN SMALL LETTER N WITH TILDE
+ // U+00E7: "ç" LATIN SMALL LETTER C WITH CEDILLA
+ // U+00C0: "À" LATIN CAPITAL LETTER A WITH GRAVE
+ // U+00C8: "È" LATIN CAPITAL LETTER E WITH GRAVE
+ // U+00CE: "Î" LATIN CAPITAL LETTER I WITH CIRCUMFLEX
+ // U+00D6: "Ö" LATIN CAPITAL LETTER O WITH DIAERESIS
+ // U+016A: "Ū" LATIN CAPITAL LETTER U WITH MACRON
+ // U+00D1: "Ñ" LATIN CAPITAL LETTER N WITH TILDE
+ // U+00C7: "Ç" LATIN CAPITAL LETTER C WITH CEDILLA
+ assert_toTitleCaseOfKeyLabel(US,
+ "\u00E0\u00E8\u00EE\u00F6\u016B\u00F1\u00E7",
+ "\u00C0\u00C8\u00CE\u00D6\u016A\u00D1\u00C7");
+ // U+00DF: "ß" LATIN SMALL LETTER SHARP S
+ // U+015B: "ś" LATIN SMALL LETTER S WITH ACUTE
+ // U+0161: "š" LATIN SMALL LETTER S WITH CARON
+ // U+015A: "Ś" LATIN CAPITAL LETTER S WITH ACUTE
+ // U+0160: "Š" LATIN CAPITAL LETTER S WITH CARONZ
+ assert_toTitleCaseOfKeyLabel(GERMAN,
+ "\u00DF\u015B\u0161",
+ "SS\u015A\u0160");
+ // U+0259: "ə" LATIN SMALL LETTER SCHWA
+ // U+0069: "i" LATIN SMALL LETTER I
+ // U+0131: "ı" LATIN SMALL LETTER DOTLESS I
+ // U+018F: "Ə" LATIN SMALL LETTER SCHWA
+ // U+0130: "İ" LATIN SMALL LETTER I WITH DOT ABOVE
+ // U+0049: "I" LATIN SMALL LETTER I
+ assert_toTitleCaseOfKeyLabel(TURKEY,
+ "\u0259\u0069\u0131",
+ "\u018F\u0130\u0049");
+ // U+03C3: "σ" GREEK SMALL LETTER SIGMA
+ // U+03C2: "ς" GREEK SMALL LETTER FINAL SIGMA
+ // U+03A3: "Σ" GREEK CAPITAL LETTER SIGMA
+ assert_toTitleCaseOfKeyLabel(GREECE,
+ "\u03C3\u03C2",
+ "\u03A3\u03A3");
+ // U+03AC: "ά" GREEK SMALL LETTER ALPHA WITH TONOS
+ // U+03AD: "έ" GREEK SMALL LETTER EPSILON WITH TONOS
+ // U+03AE: "ή" GREEK SMALL LETTER ETA WITH TONOS
+ // U+03AF: "ί" GREEK SMALL LETTER IOTA WITH TONOS
+ // U+03CC: "ό" GREEK SMALL LETTER OMICRON WITH TONOS
+ // U+03CD: "ύ" GREEK SMALL LETTER UPSILON WITH TONOS
+ // U+03CE: "ώ" GREEK SMALL LETTER OMEGA WITH TONOS
+ // U+0386: "Ά" GREEK CAPITAL LETTER ALPHA WITH TONOS
+ // U+0388: "Έ" GREEK CAPITAL LETTER EPSILON WITH TONOS
+ // U+0389: "Ή" GREEK CAPITAL LETTER ETA WITH TONOS
+ // U+038A: "Ί" GREEK CAPITAL LETTER IOTA WITH TONOS
+ // U+038C: "Ό" GREEK CAPITAL LETTER OMICRON WITH TONOS
+ // U+038E: "Ύ" GREEK CAPITAL LETTER UPSILON WITH TONOS
+ // U+038F: "Ώ" GREEK CAPITAL LETTER OMEGA WITH TONOS
+ assert_toTitleCaseOfKeyLabel(GREECE,
+ "\u03AC\u03AD\u03AE\u03AF\u03CC\u03CD\u03CE",
+ "\u0386\u0388\u0389\u038A\u038C\u038E\u038F");
+ // U+03CA: "ϊ" GREEK SMALL LETTER IOTA WITH DIALYTIKA
+ // U+03CB: "ϋ" GREEK SMALL LETTER UPSILON WITH DIALYTIKA
+ // U+0390: "ΐ" GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
+ // U+03B0: "ΰ" GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
+ // U+03AA: "Ϊ" GREEK CAPITAL LETTER IOTA WITH DIALYTIKA
+ // U+03AB: "Ϋ" GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA
+ // U+0399: "Ι" GREEK CAPITAL LETTER IOTA
+ // U+03A5: "Υ" GREEK CAPITAL LETTER UPSILON
+ // U+0308: COMBINING DIAERESIS
+ // U+0301: COMBINING GRAVE ACCENT
+ assert_toTitleCaseOfKeyLabel(GREECE,
+ "\u03CA\u03CB\u0390\u03B0",
+ "\u03AA\u03AB\u0399\u0308\u0301\u03A5\u0308\u0301");
+ }
+
+ private static void assert_toTitleCaseOfKeyCode(final Locale locale, final int lowerCase,
+ final int expected) {
+ assertEquals(lowerCase + " in " + locale, expected,
+ StringUtils.toTitleCaseOfKeyCode(lowerCase, locale));
+ }
+
+ public void test_toTitleCaseOfKeyCode() {
+ assert_toTitleCaseOfKeyCode(US, Constants.CODE_ENTER, Constants.CODE_ENTER);
+ assert_toTitleCaseOfKeyCode(US, Constants.CODE_SPACE, Constants.CODE_SPACE);
+ assert_toTitleCaseOfKeyCode(US, Constants.CODE_COMMA, Constants.CODE_COMMA);
+ // U+0069: "i" LATIN SMALL LETTER I
+ // U+0131: "ı" LATIN SMALL LETTER DOTLESS I
+ // U+0130: "İ" LATIN SMALL LETTER I WITH DOT ABOVE
+ // U+0049: "I" LATIN SMALL LETTER I
+ assert_toTitleCaseOfKeyCode(US, 0x0069, 0x0049); // i -> I
+ assert_toTitleCaseOfKeyCode(US, 0x0131, 0x0049); // ı -> I
+ assert_toTitleCaseOfKeyCode(TURKEY, 0x0069, 0x0130); // i -> İ
+ assert_toTitleCaseOfKeyCode(TURKEY, 0x0131, 0x0049); // ı -> I
+ // U+00DF: "ß" LATIN SMALL LETTER SHARP S
+ // The title case of "ß" is "SS".
+ assert_toTitleCaseOfKeyCode(US, 0x00DF, Constants.CODE_UNSPECIFIED);
+ // U+03AC: "ά" GREEK SMALL LETTER ALPHA WITH TONOS
+ // U+0386: "Ά" GREEK CAPITAL LETTER ALPHA WITH TONOS
+ assert_toTitleCaseOfKeyCode(GREECE, 0x03AC, 0x0386);
+ // U+03CA: "ϊ" GREEK SMALL LETTER IOTA WITH DIALYTIKA
+ // U+03AA: "Ϊ" GREEK CAPITAL LETTER IOTA WITH DIALYTIKA
+ assert_toTitleCaseOfKeyCode(GREECE, 0x03CA, 0x03AA);
+ // U+03B0: "ΰ" GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
+ // The title case of "ΰ" is "\u03A5\u0308\u0301".
+ assert_toTitleCaseOfKeyCode(GREECE, 0x03B0, Constants.CODE_UNSPECIFIED);
+ }
+
+ private static void assert_capitalizeFirstCodePoint(final Locale locale, final String text,
+ final String expected) {
+ assertEquals(text + " in " + locale, expected,
+ StringUtils.capitalizeFirstCodePoint(text, locale));
+ }
+
+ public void test_capitalizeFirstCodePoint() {
+ assert_capitalizeFirstCodePoint(US, "", "");
+ assert_capitalizeFirstCodePoint(US, "a", "A");
+ assert_capitalizeFirstCodePoint(US, "à", "À");
+ assert_capitalizeFirstCodePoint(US, "ß", "SS");
+ assert_capitalizeFirstCodePoint(US, "text", "Text");
+ assert_capitalizeFirstCodePoint(US, "iGoogle", "IGoogle");
+ assert_capitalizeFirstCodePoint(TURKEY, "iyi", "İyi");
+ assert_capitalizeFirstCodePoint(TURKEY, "ısırdı", "Isırdı");
+ assert_capitalizeFirstCodePoint(GREECE, "ά", "Ά");
+ assert_capitalizeFirstCodePoint(GREECE, "άνεση", "Άνεση");
+ }
+
+ private static void assert_capitalizeFirstAndDowncaseRest(final Locale locale,
+ final String text, final String expected) {
+ assertEquals(text + " in " + locale, expected,
+ StringUtils.capitalizeFirstAndDowncaseRest(text, locale));
+ }
+
+ public void test_capitalizeFirstAndDowncaseRest() {
+ assert_capitalizeFirstAndDowncaseRest(US, "", "");
+ assert_capitalizeFirstAndDowncaseRest(US, "a", "A");
+ assert_capitalizeFirstAndDowncaseRest(US, "à", "À");
+ assert_capitalizeFirstAndDowncaseRest(US, "ß", "SS");
+ assert_capitalizeFirstAndDowncaseRest(US, "text", "Text");
+ assert_capitalizeFirstAndDowncaseRest(US, "iGoogle", "Igoogle");
+ assert_capitalizeFirstAndDowncaseRest(US, "invite", "Invite");
+ assert_capitalizeFirstAndDowncaseRest(US, "INVITE", "Invite");
+ assert_capitalizeFirstAndDowncaseRest(TURKEY, "iyi", "İyi");
+ assert_capitalizeFirstAndDowncaseRest(TURKEY, "İYİ", "İyi");
+ assert_capitalizeFirstAndDowncaseRest(TURKEY, "ısırdı", "Isırdı");
+ assert_capitalizeFirstAndDowncaseRest(TURKEY, "ISIRDI", "Isırdı");
+ assert_capitalizeFirstAndDowncaseRest(GREECE, "ά", "Ά");
+ assert_capitalizeFirstAndDowncaseRest(GREECE, "άνεση", "Άνεση");
+ assert_capitalizeFirstAndDowncaseRest(GREECE, "ΆΝΕΣΗ", "Άνεση");
+ }
+
public void testContainsInArray() {
assertFalse("empty array", StringUtils.containsInArray("key", new String[0]));
assertFalse("not in 1 element", StringUtils.containsInArray("key", new String[] {
@@ -248,16 +401,6 @@ public class StringAndJsonUtilsTests extends AndroidTestCase {
assertTrue(bytesStr.equals(bytesStr2));
}
- public void testJsonUtils() {
- final Object[] objs = new Object[] { 1, "aaa", "bbb", 3 };
- final List<Object> objArray = Arrays.asList(objs);
- final String str = JsonUtils.listToJsonStr(objArray);
- final List<Object> newObjArray = JsonUtils.jsonStrToList(str);
- for (int i = 0; i < objs.length; ++i) {
- assertEquals(objs[i], newObjArray.get(i));
- }
- }
-
public void testToCodePointArray() {
final String STR_WITH_SUPPLEMENTARY_CHAR = "abcde\uD861\uDED7fgh\u0000\u2002\u2003\u3000xx";
final int[] EXPECTED_RESULT = new int[] { 'a', 'b', 'c', 'd', 'e', 0x286D7, 'f', 'g', 'h',
@@ -331,171 +474,4 @@ public class StringAndJsonUtilsTests extends AndroidTestCase {
assertEquals(1, StringUtils.getTrailingSingleQuotesCount("'word'"));
assertEquals(0, StringUtils.getTrailingSingleQuotesCount("I'm"));
}
-
- private static void assertSpanCount(final int expectedCount, final CharSequence cs) {
- final int actualCount;
- if (cs instanceof Spanned) {
- final Spanned spanned = (Spanned) cs;
- actualCount = spanned.getSpans(0, spanned.length(), Object.class).length;
- } else {
- actualCount = 0;
- }
- assertEquals(expectedCount, actualCount);
- }
-
- private static void assertSpan(final CharSequence cs, final Object expectedSpan,
- final int expectedStart, final int expectedEnd, final int expectedFlags) {
- assertTrue(cs instanceof Spanned);
- final Spanned spanned = (Spanned) cs;
- final Object[] actualSpans = spanned.getSpans(0, spanned.length(), Object.class);
- for (Object actualSpan : actualSpans) {
- if (actualSpan == expectedSpan) {
- final int actualStart = spanned.getSpanStart(actualSpan);
- final int actualEnd = spanned.getSpanEnd(actualSpan);
- final int actualFlags = spanned.getSpanFlags(actualSpan);
- assertEquals(expectedStart, actualStart);
- assertEquals(expectedEnd, actualEnd);
- assertEquals(expectedFlags, actualFlags);
- return;
- }
- }
- assertTrue(false);
- }
-
- public void testSplitCharSequenceWithSpan() {
- // text: " a bcd efg hij "
- // span1: ^^^^^^^
- // span2: ^^^^^
- // span3: ^
- final SpannableString spannableString = new SpannableString(" a bcd efg hij ");
- final Object span1 = new Object();
- final Object span2 = new Object();
- final Object span3 = new Object();
- final int SPAN1_FLAGS = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
- final int SPAN2_FLAGS = Spanned.SPAN_EXCLUSIVE_INCLUSIVE;
- final int SPAN3_FLAGS = Spanned.SPAN_INCLUSIVE_INCLUSIVE;
- spannableString.setSpan(span1, 0, 7, SPAN1_FLAGS);
- spannableString.setSpan(span2, 0, 5, SPAN2_FLAGS);
- spannableString.setSpan(span3, 12, 13, SPAN3_FLAGS);
- final CharSequence[] charSequencesFromSpanned = SpannableStringUtils.split(
- spannableString, " ", true /* preserveTrailingEmptySegmengs */);
- final CharSequence[] charSequencesFromString = SpannableStringUtils.split(
- spannableString.toString(), " ", true /* preserveTrailingEmptySegmengs */);
-
-
- assertEquals(7, charSequencesFromString.length);
- assertEquals(7, charSequencesFromSpanned.length);
-
- // text: ""
- // span1: ^
- // span2: ^
- // span3:
- assertEquals("", charSequencesFromString[0].toString());
- assertSpanCount(0, charSequencesFromString[0]);
- assertEquals("", charSequencesFromSpanned[0].toString());
- assertSpanCount(2, charSequencesFromSpanned[0]);
- assertSpan(charSequencesFromSpanned[0], span1, 0, 0, SPAN1_FLAGS);
- assertSpan(charSequencesFromSpanned[0], span2, 0, 0, SPAN2_FLAGS);
-
- // text: "a"
- // span1: ^
- // span2: ^
- // span3:
- assertEquals("a", charSequencesFromString[1].toString());
- assertSpanCount(0, charSequencesFromString[1]);
- assertEquals("a", charSequencesFromSpanned[1].toString());
- assertSpanCount(2, charSequencesFromSpanned[1]);
- assertSpan(charSequencesFromSpanned[1], span1, 0, 1, SPAN1_FLAGS);
- assertSpan(charSequencesFromSpanned[1], span2, 0, 1, SPAN2_FLAGS);
-
- // text: "bcd"
- // span1: ^^^
- // span2: ^^
- // span3:
- assertEquals("bcd", charSequencesFromString[2].toString());
- assertSpanCount(0, charSequencesFromString[2]);
- assertEquals("bcd", charSequencesFromSpanned[2].toString());
- assertSpanCount(2, charSequencesFromSpanned[2]);
- assertSpan(charSequencesFromSpanned[2], span1, 0, 3, SPAN1_FLAGS);
- assertSpan(charSequencesFromSpanned[2], span2, 0, 2, SPAN2_FLAGS);
-
- // text: "efg"
- // span1:
- // span2:
- // span3:
- assertEquals("efg", charSequencesFromString[3].toString());
- assertSpanCount(0, charSequencesFromString[3]);
- assertEquals("efg", charSequencesFromSpanned[3].toString());
- assertSpanCount(0, charSequencesFromSpanned[3]);
-
- // text: "hij"
- // span1:
- // span2:
- // span3: ^
- assertEquals("hij", charSequencesFromString[4].toString());
- assertSpanCount(0, charSequencesFromString[4]);
- assertEquals("hij", charSequencesFromSpanned[4].toString());
- assertSpanCount(1, charSequencesFromSpanned[4]);
- assertSpan(charSequencesFromSpanned[4], span3, 1, 2, SPAN3_FLAGS);
-
- // text: ""
- // span1:
- // span2:
- // span3:
- assertEquals("", charSequencesFromString[5].toString());
- assertSpanCount(0, charSequencesFromString[5]);
- assertEquals("", charSequencesFromSpanned[5].toString());
- assertSpanCount(0, charSequencesFromSpanned[5]);
-
- // text: ""
- // span1:
- // span2:
- // span3:
- assertEquals("", charSequencesFromString[6].toString());
- assertSpanCount(0, charSequencesFromString[6]);
- assertEquals("", charSequencesFromSpanned[6].toString());
- assertSpanCount(0, charSequencesFromSpanned[6]);
- }
-
- public void testSplitCharSequencePreserveTrailingEmptySegmengs() {
- assertEquals(1, SpannableStringUtils.split("", " ",
- false /* preserveTrailingEmptySegmengs */).length);
- assertEquals(1, SpannableStringUtils.split(new SpannedString(""), " ",
- false /* preserveTrailingEmptySegmengs */).length);
-
- assertEquals(1, SpannableStringUtils.split("", " ",
- true /* preserveTrailingEmptySegmengs */).length);
- assertEquals(1, SpannableStringUtils.split(new SpannedString(""), " ",
- true /* preserveTrailingEmptySegmengs */).length);
-
- assertEquals(0, SpannableStringUtils.split(" ", " ",
- false /* preserveTrailingEmptySegmengs */).length);
- assertEquals(0, SpannableStringUtils.split(new SpannedString(" "), " ",
- false /* preserveTrailingEmptySegmengs */).length);
-
- assertEquals(2, SpannableStringUtils.split(" ", " ",
- true /* preserveTrailingEmptySegmengs */).length);
- assertEquals(2, SpannableStringUtils.split(new SpannedString(" "), " ",
- true /* preserveTrailingEmptySegmengs */).length);
-
- assertEquals(3, SpannableStringUtils.split("a b c ", " ",
- false /* preserveTrailingEmptySegmengs */).length);
- assertEquals(3, SpannableStringUtils.split(new SpannedString("a b c "), " ",
- false /* preserveTrailingEmptySegmengs */).length);
-
- assertEquals(5, SpannableStringUtils.split("a b c ", " ",
- true /* preserveTrailingEmptySegmengs */).length);
- assertEquals(5, SpannableStringUtils.split(new SpannedString("a b c "), " ",
- true /* preserveTrailingEmptySegmengs */).length);
-
- assertEquals(6, SpannableStringUtils.split("a b ", " ",
- false /* preserveTrailingEmptySegmengs */).length);
- assertEquals(6, SpannableStringUtils.split(new SpannedString("a b "), " ",
- false /* preserveTrailingEmptySegmengs */).length);
-
- assertEquals(7, SpannableStringUtils.split("a b ", " ",
- true /* preserveTrailingEmptySegmengs */).length);
- assertEquals(7, SpannableStringUtils.split(new SpannedString("a b "), " ",
- true /* preserveTrailingEmptySegmengs */).length);
- }
}
diff --git a/tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java
new file mode 100644
index 000000000..194112070
--- /dev/null
+++ b/tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.latin.utils;
+
+import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import java.util.Arrays;
+import java.util.List;
+
+@SmallTest
+public class JsonUtilsTests extends AndroidTestCase {
+ public void testJsonUtils() {
+ final Object[] objs = new Object[] { 1, "aaa", "bbb", 3 };
+ final List<Object> objArray = Arrays.asList(objs);
+ final String str = JsonUtils.listToJsonStr(objArray);
+ final List<Object> newObjArray = JsonUtils.jsonStrToList(str);
+ for (int i = 0; i < objs.length; ++i) {
+ assertEquals(objs[i], newObjArray.get(i));
+ }
+ }
+}
diff --git a/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java
index 11d10aa2f..665d81ccd 100644
--- a/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java
+++ b/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java
@@ -20,8 +20,10 @@ import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.style.SuggestionSpan;
import android.text.style.URLSpan;
+import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
+import android.text.SpannedString;
@SmallTest
public class SpannableStringUtilsTests extends AndroidTestCase {
@@ -54,4 +56,171 @@ public class SpannableStringUtilsTests extends AndroidTestCase {
assertTrue("Should be a SuggestionSpan", spans[i] instanceof SuggestionSpan);
}
}
+
+ private static void assertSpanCount(final int expectedCount, final CharSequence cs) {
+ final int actualCount;
+ if (cs instanceof Spanned) {
+ final Spanned spanned = (Spanned) cs;
+ actualCount = spanned.getSpans(0, spanned.length(), Object.class).length;
+ } else {
+ actualCount = 0;
+ }
+ assertEquals(expectedCount, actualCount);
+ }
+
+ private static void assertSpan(final CharSequence cs, final Object expectedSpan,
+ final int expectedStart, final int expectedEnd, final int expectedFlags) {
+ assertTrue(cs instanceof Spanned);
+ final Spanned spanned = (Spanned) cs;
+ final Object[] actualSpans = spanned.getSpans(0, spanned.length(), Object.class);
+ for (Object actualSpan : actualSpans) {
+ if (actualSpan == expectedSpan) {
+ final int actualStart = spanned.getSpanStart(actualSpan);
+ final int actualEnd = spanned.getSpanEnd(actualSpan);
+ final int actualFlags = spanned.getSpanFlags(actualSpan);
+ assertEquals(expectedStart, actualStart);
+ assertEquals(expectedEnd, actualEnd);
+ assertEquals(expectedFlags, actualFlags);
+ return;
+ }
+ }
+ assertTrue(false);
+ }
+
+ public void testSplitCharSequenceWithSpan() {
+ // text: " a bcd efg hij "
+ // span1: ^^^^^^^
+ // span2: ^^^^^
+ // span3: ^
+ final SpannableString spannableString = new SpannableString(" a bcd efg hij ");
+ final Object span1 = new Object();
+ final Object span2 = new Object();
+ final Object span3 = new Object();
+ final int SPAN1_FLAGS = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
+ final int SPAN2_FLAGS = Spanned.SPAN_EXCLUSIVE_INCLUSIVE;
+ final int SPAN3_FLAGS = Spanned.SPAN_INCLUSIVE_INCLUSIVE;
+ spannableString.setSpan(span1, 0, 7, SPAN1_FLAGS);
+ spannableString.setSpan(span2, 0, 5, SPAN2_FLAGS);
+ spannableString.setSpan(span3, 12, 13, SPAN3_FLAGS);
+ final CharSequence[] charSequencesFromSpanned = SpannableStringUtils.split(
+ spannableString, " ", true /* preserveTrailingEmptySegmengs */);
+ final CharSequence[] charSequencesFromString = SpannableStringUtils.split(
+ spannableString.toString(), " ", true /* preserveTrailingEmptySegmengs */);
+
+
+ assertEquals(7, charSequencesFromString.length);
+ assertEquals(7, charSequencesFromSpanned.length);
+
+ // text: ""
+ // span1: ^
+ // span2: ^
+ // span3:
+ assertEquals("", charSequencesFromString[0].toString());
+ assertSpanCount(0, charSequencesFromString[0]);
+ assertEquals("", charSequencesFromSpanned[0].toString());
+ assertSpanCount(2, charSequencesFromSpanned[0]);
+ assertSpan(charSequencesFromSpanned[0], span1, 0, 0, SPAN1_FLAGS);
+ assertSpan(charSequencesFromSpanned[0], span2, 0, 0, SPAN2_FLAGS);
+
+ // text: "a"
+ // span1: ^
+ // span2: ^
+ // span3:
+ assertEquals("a", charSequencesFromString[1].toString());
+ assertSpanCount(0, charSequencesFromString[1]);
+ assertEquals("a", charSequencesFromSpanned[1].toString());
+ assertSpanCount(2, charSequencesFromSpanned[1]);
+ assertSpan(charSequencesFromSpanned[1], span1, 0, 1, SPAN1_FLAGS);
+ assertSpan(charSequencesFromSpanned[1], span2, 0, 1, SPAN2_FLAGS);
+
+ // text: "bcd"
+ // span1: ^^^
+ // span2: ^^
+ // span3:
+ assertEquals("bcd", charSequencesFromString[2].toString());
+ assertSpanCount(0, charSequencesFromString[2]);
+ assertEquals("bcd", charSequencesFromSpanned[2].toString());
+ assertSpanCount(2, charSequencesFromSpanned[2]);
+ assertSpan(charSequencesFromSpanned[2], span1, 0, 3, SPAN1_FLAGS);
+ assertSpan(charSequencesFromSpanned[2], span2, 0, 2, SPAN2_FLAGS);
+
+ // text: "efg"
+ // span1:
+ // span2:
+ // span3:
+ assertEquals("efg", charSequencesFromString[3].toString());
+ assertSpanCount(0, charSequencesFromString[3]);
+ assertEquals("efg", charSequencesFromSpanned[3].toString());
+ assertSpanCount(0, charSequencesFromSpanned[3]);
+
+ // text: "hij"
+ // span1:
+ // span2:
+ // span3: ^
+ assertEquals("hij", charSequencesFromString[4].toString());
+ assertSpanCount(0, charSequencesFromString[4]);
+ assertEquals("hij", charSequencesFromSpanned[4].toString());
+ assertSpanCount(1, charSequencesFromSpanned[4]);
+ assertSpan(charSequencesFromSpanned[4], span3, 1, 2, SPAN3_FLAGS);
+
+ // text: ""
+ // span1:
+ // span2:
+ // span3:
+ assertEquals("", charSequencesFromString[5].toString());
+ assertSpanCount(0, charSequencesFromString[5]);
+ assertEquals("", charSequencesFromSpanned[5].toString());
+ assertSpanCount(0, charSequencesFromSpanned[5]);
+
+ // text: ""
+ // span1:
+ // span2:
+ // span3:
+ assertEquals("", charSequencesFromString[6].toString());
+ assertSpanCount(0, charSequencesFromString[6]);
+ assertEquals("", charSequencesFromSpanned[6].toString());
+ assertSpanCount(0, charSequencesFromSpanned[6]);
+ }
+
+ public void testSplitCharSequencePreserveTrailingEmptySegmengs() {
+ assertEquals(1, SpannableStringUtils.split("", " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(1, SpannableStringUtils.split(new SpannedString(""), " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+
+ assertEquals(1, SpannableStringUtils.split("", " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(1, SpannableStringUtils.split(new SpannedString(""), " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+
+ assertEquals(0, SpannableStringUtils.split(" ", " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(0, SpannableStringUtils.split(new SpannedString(" "), " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+
+ assertEquals(2, SpannableStringUtils.split(" ", " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(2, SpannableStringUtils.split(new SpannedString(" "), " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+
+ assertEquals(3, SpannableStringUtils.split("a b c ", " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(3, SpannableStringUtils.split(new SpannedString("a b c "), " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+
+ assertEquals(5, SpannableStringUtils.split("a b c ", " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(5, SpannableStringUtils.split(new SpannedString("a b c "), " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+
+ assertEquals(6, SpannableStringUtils.split("a b ", " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(6, SpannableStringUtils.split(new SpannedString("a b "), " ",
+ false /* preserveTrailingEmptySegmengs */).length);
+
+ assertEquals(7, SpannableStringUtils.split("a b ", " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+ assertEquals(7, SpannableStringUtils.split(new SpannedString("a b "), " ",
+ true /* preserveTrailingEmptySegmengs */).length);
+ }
}
diff --git a/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java
index 03dcdfc78..111d5c56a 100644
--- a/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java
+++ b/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java
@@ -73,7 +73,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase {
mRichImm = RichInputMethodManager.getInstance();
// Save and reset additional subtypes
- mSavedAddtionalSubtypes = mRichImm.getAdditionalSubtypes(context);
+ mSavedAddtionalSubtypes = mRichImm.getAdditionalSubtypes();
final InputMethodSubtype[] predefinedAddtionalSubtypes =
AdditionalSubtypeUtils.createAdditionalSubtypesArray(
AdditionalSubtypeUtils.createPrefSubtypes(
@@ -418,9 +418,17 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase {
SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(HI));
// These are preliminary subtypes and may not exist.
if (HI_LATN != null) {
- assertEquals("hi_ZZ", "हिंग्लिश",
+ // TODO: Uncommented because of the current translation of these strings
+ // in Hindi are described in Latin script.
+ // assertEquals("hi_ZZ", "हिंग्लिश",
+ // SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(HI_LATN));
+ // assertEquals("hi_ZZ", "हिंग्लिश (Dvorak)",
+ // SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(HI_LATN_DVORAK));
+ // TODO: Remove these tests once the translation of these strings in Hindi
+ // are described in Devanagari script.
+ assertEquals("hi_ZZ", "Hinglish",
SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(HI_LATN));
- assertEquals("hi_ZZ", "हिंग्लिश (Dvorak)",
+ assertEquals("hi_ZZ", "Hinglish (Dvorak)",
SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(HI_LATN_DVORAK));
}
return null;