aboutsummaryrefslogtreecommitdiffstats
path: root/java/src/com/android/inputmethod/latin
diff options
context:
space:
mode:
Diffstat (limited to 'java/src/com/android/inputmethod/latin')
-rw-r--r--java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java112
-rw-r--r--java/src/com/android/inputmethod/latin/AutoCorrection.java18
-rw-r--r--java/src/com/android/inputmethod/latin/BinaryDictionary.java2
-rw-r--r--java/src/com/android/inputmethod/latin/ComposingStateManager.java68
-rw-r--r--java/src/com/android/inputmethod/latin/DebugSettings.java5
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryFactory.java14
-rw-r--r--java/src/com/android/inputmethod/latin/JniUtils.java41
-rw-r--r--java/src/com/android/inputmethod/latin/LatinIME.java138
-rw-r--r--java/src/com/android/inputmethod/latin/Settings.java2
-rw-r--r--java/src/com/android/inputmethod/latin/SettingsValues.java4
-rw-r--r--java/src/com/android/inputmethod/latin/StringUtils.java198
-rw-r--r--java/src/com/android/inputmethod/latin/SubtypeSwitcher.java2
-rw-r--r--java/src/com/android/inputmethod/latin/SubtypeUtils.java135
-rw-r--r--java/src/com/android/inputmethod/latin/Suggest.java50
-rw-r--r--java/src/com/android/inputmethod/latin/Utils.java398
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java10
-rw-r--r--java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java32
17 files changed, 609 insertions, 620 deletions
diff --git a/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java b/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java
new file mode 100644
index 000000000..1cbdbd650
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java
@@ -0,0 +1,112 @@
+/*
+ * 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 com.android.inputmethod.latin;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.media.AudioManager;
+import android.view.HapticFeedbackConstants;
+import android.view.View;
+
+import com.android.inputmethod.compat.VibratorCompatWrapper;
+import com.android.inputmethod.keyboard.Keyboard;
+
+/**
+ * This class gathers audio feedback and haptic feedback functions.
+ *
+ * It offers a consistent and simple interface that allows LatinIME to forget about the
+ * complexity of settings and the like.
+ */
+public class AudioAndHapticFeedbackManager extends BroadcastReceiver {
+ final private SettingsValues mSettingsValues;
+ final private AudioManager mAudioManager;
+ final private VibratorCompatWrapper mVibrator;
+ private boolean mSoundOn;
+
+ public AudioAndHapticFeedbackManager(final LatinIME latinIme,
+ final SettingsValues settingsValues) {
+ mSettingsValues = settingsValues;
+ mVibrator = VibratorCompatWrapper.getInstance(latinIme);
+ mAudioManager = (AudioManager) latinIme.getSystemService(Context.AUDIO_SERVICE);
+ mSoundOn = reevaluateIfSoundIsOn();
+ }
+
+ public void hapticAndAudioFeedback(final int primaryCode,
+ final View viewToPerformHapticFeedbackOn) {
+ vibrate(viewToPerformHapticFeedbackOn);
+ playKeyClick(primaryCode);
+ }
+
+ private boolean reevaluateIfSoundIsOn() {
+ if (!mSettingsValues.mSoundOn || mAudioManager == null) {
+ return false;
+ } else {
+ return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
+ }
+ }
+
+ private void playKeyClick(int primaryCode) {
+ // if mAudioManager is null, we can't play a sound anyway, so return
+ if (mAudioManager == null) return;
+ if (mSoundOn) {
+ final int sound;
+ switch (primaryCode) {
+ case Keyboard.CODE_DELETE:
+ sound = AudioManager.FX_KEYPRESS_DELETE;
+ break;
+ case Keyboard.CODE_ENTER:
+ sound = AudioManager.FX_KEYPRESS_RETURN;
+ break;
+ case Keyboard.CODE_SPACE:
+ sound = AudioManager.FX_KEYPRESS_SPACEBAR;
+ break;
+ default:
+ sound = AudioManager.FX_KEYPRESS_STANDARD;
+ break;
+ }
+ mAudioManager.playSoundEffect(sound, mSettingsValues.mFxVolume);
+ }
+ }
+
+ // TODO: make this private when LatinIME does not call it any more
+ public void vibrate(final View viewToPerformHapticFeedbackOn) {
+ if (!mSettingsValues.mVibrateOn) {
+ return;
+ }
+ if (mSettingsValues.mKeypressVibrationDuration < 0) {
+ // Go ahead with the system default
+ if (viewToPerformHapticFeedbackOn != null) {
+ viewToPerformHapticFeedbackOn.performHapticFeedback(
+ HapticFeedbackConstants.KEYBOARD_TAP,
+ HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
+ }
+ } else if (mVibrator != null) {
+ mVibrator.vibrate(mSettingsValues.mKeypressVibrationDuration);
+ }
+ }
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String action = intent.getAction();
+ // The following test is supposedly useless since we only listen for the ringer event.
+ // Still, it's a good safety measure.
+ if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
+ mSoundOn = reevaluateIfSoundIsOn();
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/AutoCorrection.java b/java/src/com/android/inputmethod/latin/AutoCorrection.java
index bcb78919d..425b5c3f3 100644
--- a/java/src/com/android/inputmethod/latin/AutoCorrection.java
+++ b/java/src/com/android/inputmethod/latin/AutoCorrection.java
@@ -25,44 +25,36 @@ import java.util.Map;
public class AutoCorrection {
private static final boolean DBG = LatinImeLogger.sDBG;
private static final String TAG = AutoCorrection.class.getSimpleName();
- private boolean mHasAutoCorrection;
private CharSequence mAutoCorrectionWord;
private double mNormalizedScore;
public void init() {
- mHasAutoCorrection = false;
mAutoCorrectionWord = null;
mNormalizedScore = Integer.MIN_VALUE;
}
public boolean hasAutoCorrection() {
- return mHasAutoCorrection;
- }
-
- public CharSequence getAutoCorrectionWord() {
- return mAutoCorrectionWord;
+ return null != mAutoCorrectionWord;
}
public double getNormalizedScore() {
return mNormalizedScore;
}
- public void updateAutoCorrectionStatus(Map<String, Dictionary> dictionaries,
+ public CharSequence updateAutoCorrectionStatus(Map<String, Dictionary> dictionaries,
WordComposer wordComposer, ArrayList<CharSequence> suggestions, int[] sortedScores,
CharSequence typedWord, double autoCorrectionThreshold, int correctionMode,
CharSequence whitelistedWord) {
if (hasAutoCorrectionForWhitelistedWord(whitelistedWord)) {
- mHasAutoCorrection = true;
mAutoCorrectionWord = whitelistedWord;
} else if (hasAutoCorrectionForTypedWord(
dictionaries, wordComposer, suggestions, typedWord, correctionMode)) {
- mHasAutoCorrection = true;
mAutoCorrectionWord = typedWord;
} else if (hasAutoCorrectionForBinaryDictionary(wordComposer, suggestions, correctionMode,
sortedScores, typedWord, autoCorrectionThreshold)) {
- mHasAutoCorrection = true;
mAutoCorrectionWord = suggestions.get(0);
}
+ return mAutoCorrectionWord;
}
public static boolean isValidWord(
@@ -110,8 +102,8 @@ public class AutoCorrection {
WordComposer wordComposer, ArrayList<CharSequence> suggestions, CharSequence typedWord,
int correctionMode) {
if (TextUtils.isEmpty(typedWord)) return false;
- boolean allowsAutoCorrect = allowsToBeAutoCorrected(dictionaries, typedWord, false);
- return wordComposer.size() > 1 && suggestions.size() > 0 && !allowsAutoCorrect
+ return wordComposer.size() > 1 && suggestions.size() > 0
+ && !allowsToBeAutoCorrected(dictionaries, typedWord, false)
&& (correctionMode == Suggest.CORRECTION_FULL
|| correctionMode == Suggest.CORRECTION_FULL_BIGRAM);
}
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionary.java b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
index 90ced6028..31ff4e7b4 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
@@ -104,7 +104,7 @@ public class BinaryDictionary extends Dictionary {
}
static {
- Utils.loadNativeLibrary();
+ JniUtils.loadNativeLibrary();
}
private native long openNative(String sourceDir, long dictOffset, long dictSize,
diff --git a/java/src/com/android/inputmethod/latin/ComposingStateManager.java b/java/src/com/android/inputmethod/latin/ComposingStateManager.java
deleted file mode 100644
index 8811f2023..000000000
--- a/java/src/com/android/inputmethod/latin/ComposingStateManager.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * 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 com.android.inputmethod.latin;
-
-import android.util.Log;
-
-public class ComposingStateManager {
- private static final String TAG = ComposingStateManager.class.getSimpleName();
- private static final ComposingStateManager sInstance = new ComposingStateManager();
- private boolean mAutoCorrectionIndicatorOn;
- private boolean mIsComposing;
-
- public static ComposingStateManager getInstance() {
- return sInstance;
- }
-
- private ComposingStateManager() {
- mAutoCorrectionIndicatorOn = false;
- mIsComposing = false;
- }
-
- public synchronized void onStartComposingText() {
- if (!mIsComposing) {
- if (LatinImeLogger.sDBG) {
- Log.i(TAG, "Start composing text.");
- }
- mAutoCorrectionIndicatorOn = false;
- mIsComposing = true;
- }
- }
-
- public synchronized void onFinishComposingText() {
- if (mIsComposing) {
- if (LatinImeLogger.sDBG) {
- Log.i(TAG, "Finish composing text.");
- }
- mAutoCorrectionIndicatorOn = false;
- mIsComposing = false;
- }
- }
-
- public synchronized boolean isAutoCorrectionIndicatorOn() {
- return mAutoCorrectionIndicatorOn;
- }
-
- public synchronized void setAutoCorrectionIndicatorOn(boolean on) {
- // Auto-correction indicator should be specified only when the current state is "composing".
- if (!mIsComposing) return;
- if (LatinImeLogger.sDBG) {
- Log.i(TAG, "Set auto correction Indicator: " + on);
- }
- mAutoCorrectionIndicatorOn = on;
- }
-}
diff --git a/java/src/com/android/inputmethod/latin/DebugSettings.java b/java/src/com/android/inputmethod/latin/DebugSettings.java
index 3805da154..870b33f9a 100644
--- a/java/src/com/android/inputmethod/latin/DebugSettings.java
+++ b/java/src/com/android/inputmethod/latin/DebugSettings.java
@@ -25,6 +25,8 @@ import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.util.Log;
+import com.android.inputmethod.keyboard.KeyboardSwitcher;
+
public class DebugSettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@@ -61,7 +63,8 @@ public class DebugSettings extends PreferenceActivity
updateDebugMode();
mServiceNeedsRestart = true;
}
- } else if (key.equals(FORCE_NON_DISTINCT_MULTITOUCH_KEY)) {
+ } else if (key.equals(FORCE_NON_DISTINCT_MULTITOUCH_KEY)
+ || key.equals(KeyboardSwitcher.PREF_KEYBOARD_LAYOUT)) {
mServiceNeedsRestart = true;
}
}
diff --git a/java/src/com/android/inputmethod/latin/DictionaryFactory.java b/java/src/com/android/inputmethod/latin/DictionaryFactory.java
index 1607f86a8..7a81f7bd5 100644
--- a/java/src/com/android/inputmethod/latin/DictionaryFactory.java
+++ b/java/src/com/android/inputmethod/latin/DictionaryFactory.java
@@ -164,7 +164,7 @@ public class DictionaryFactory {
final Resources res = context.getResources();
final Locale saveLocale = LocaleUtils.setSystemLocale(res, locale);
- final int resourceId = Utils.getMainDictionaryResourceId(res);
+ final int resourceId = getMainDictionaryResourceId(res);
final AssetFileDescriptor afd = res.openRawResourceFd(resourceId);
final boolean hasDictionary = isFullDictionary(afd);
try {
@@ -182,7 +182,7 @@ public class DictionaryFactory {
final Resources res = context.getResources();
final Locale saveLocale = LocaleUtils.setSystemLocale(res, locale);
- final int resourceId = Utils.getMainDictionaryResourceId(res);
+ final int resourceId = getMainDictionaryResourceId(res);
final AssetFileDescriptor afd = res.openRawResourceFd(resourceId);
final Long size = (afd != null && afd.getLength() > PLACEHOLDER_LENGTH)
? afd.getLength()
@@ -209,4 +209,14 @@ public class DictionaryFactory {
protected static boolean isFullDictionary(final AssetFileDescriptor afd) {
return (afd != null && afd.getLength() > PLACEHOLDER_LENGTH);
}
+
+ /**
+ * Returns a main dictionary resource id
+ * @return main dictionary resource id
+ */
+ public static int getMainDictionaryResourceId(Resources res) {
+ final String MAIN_DIC_NAME = "main";
+ String packageName = LatinIME.class.getPackage().getName();
+ return res.getIdentifier(MAIN_DIC_NAME, "raw", packageName);
+ }
}
diff --git a/java/src/com/android/inputmethod/latin/JniUtils.java b/java/src/com/android/inputmethod/latin/JniUtils.java
new file mode 100644
index 000000000..4808b867a
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/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 com.android.inputmethod.latin;
+
+import android.util.Log;
+
+import com.android.inputmethod.latin.define.JniLibName;
+
+public class JniUtils {
+ private static final String TAG = JniUtils.class.getSimpleName();
+
+ private JniUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static void loadNativeLibrary() {
+ try {
+ System.loadLibrary(JniLibName.JNI_LIB_NAME);
+ } catch (UnsatisfiedLinkError ule) {
+ Log.e(TAG, "Could not load native library " + JniLibName.JNI_LIB_NAME);
+ if (LatinImeLogger.sDBG) {
+ throw new RuntimeException(
+ "Could not load native library " + JniLibName.JNI_LIB_NAME);
+ }
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index 1858db949..273593dfb 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -40,12 +40,11 @@ import android.text.TextUtils;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
-import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
-import android.view.ViewParent;
import android.view.ViewGroup.LayoutParams;
+import android.view.ViewParent;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
@@ -61,7 +60,6 @@ import com.android.inputmethod.compat.InputMethodServiceCompatWrapper;
import com.android.inputmethod.compat.InputMethodSubtypeCompatWrapper;
import com.android.inputmethod.compat.InputTypeCompatUtils;
import com.android.inputmethod.compat.SuggestionSpanUtils;
-import com.android.inputmethod.compat.VibratorCompatWrapper;
import com.android.inputmethod.deprecated.LanguageSwitcherProxy;
import com.android.inputmethod.deprecated.VoiceProxy;
import com.android.inputmethod.keyboard.Keyboard;
@@ -223,10 +221,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
private int mDeleteCount;
private long mLastKeyTime;
- private AudioManager mAudioManager;
- private boolean mSilentModeOn; // System-wide current configuration
-
- private VibratorCompatWrapper mVibrator;
+ private AudioAndHapticFeedbackManager mFeedbackManager;
// Member variables for remembering the current device orientation.
private int mDisplayOrientation;
@@ -238,8 +233,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
- private final ComposingStateManager mComposingStateManager =
- ComposingStateManager.getInstance();
+ private boolean mIsAutoCorrectionIndicatorOn;
public final UIHandler mHandler = new UIHandler(this);
@@ -511,7 +505,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
super.onCreate();
mImm = InputMethodManagerCompatWrapper.getInstance();
- mVibrator = VibratorCompatWrapper.getInstance(this);
mHandler.onCreate();
DEBUG = LatinImeLogger.sDBG;
@@ -538,11 +531,14 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// Register to receive ringer mode change and network state change.
// Also receive installation and removal of a dictionary pack.
final IntentFilter filter = new IntentFilter();
- filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
mVoiceProxy = VoiceProxy.init(this, prefs, mHandler);
+ final IntentFilter ringerModeFilter = new IntentFilter();
+ ringerModeFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
+ registerReceiver(mFeedbackManager, ringerModeFilter);
+
final IntentFilter packageFilter = new IntentFilter();
packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
@@ -559,6 +555,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
/* package */ void loadSettings() {
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mSettingsValues = new SettingsValues(mPrefs, this, mSubtypeSwitcher.getInputLocaleStr());
+ mFeedbackManager = new AudioAndHapticFeedbackManager(this, mSettingsValues);
resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary());
}
@@ -576,7 +573,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
oldContactsDictionary = null;
}
- int mainDicResId = Utils.getMainDictionaryResourceId(res);
+ int mainDicResId = DictionaryFactory.getMainDictionaryResourceId(res);
mSuggest = new Suggest(this, mainDicResId, keyboardLocale);
if (mSettingsValues.mAutoCorrectEnabled) {
mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold);
@@ -636,7 +633,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
/* package private */ void resetSuggestMainDict() {
final String localeStr = mSubtypeSwitcher.getInputLocaleStr();
final Locale keyboardLocale = LocaleUtils.constructLocaleFromString(localeStr);
- int mainDicResId = Utils.getMainDictionaryResourceId(mResources);
+ int mainDicResId = DictionaryFactory.getMainDictionaryResourceId(mResources);
mSuggest.resetMainDict(this, mainDicResId, keyboardLocale);
}
@@ -647,6 +644,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
mSuggest = null;
}
unregisterReceiver(mReceiver);
+ unregisterReceiver(mFeedbackManager);
unregisterReceiver(mDictionaryPackInstallReceiver);
mVoiceProxy.destroy();
LatinImeLogger.commit();
@@ -657,7 +655,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
@Override
public void onConfigurationChanged(Configuration conf) {
mSubtypeSwitcher.onConfigurationChanged(conf);
- mComposingStateManager.onFinishComposingText();
// If orientation changed while predicting, commit the change
if (mDisplayOrientation != conf.orientation) {
mDisplayOrientation = conf.orientation;
@@ -745,12 +742,12 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
}
- if (Utils.inPrivateImeOptions(null, IME_OPTION_NO_MICROPHONE_COMPAT, editorInfo)) {
+ if (StringUtils.inPrivateImeOptions(null, IME_OPTION_NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + IME_OPTION_NO_MICROPHONE + " instead");
}
- if (Utils.inPrivateImeOptions(getPackageName(), IME_OPTION_FORCE_ASCII, editorInfo)) {
+ if (StringUtils.inPrivateImeOptions(getPackageName(), IME_OPTION_FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
@@ -1148,7 +1145,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// and the composingStateManager about it.
private void resetEntireInputState() {
resetComposingState(true /* alsoResetLastComposedWord */);
- mComposingStateManager.onFinishComposingText();
updateSuggestions();
final InputConnection ic = getCurrentInputConnection();
if (ic != null) {
@@ -1207,7 +1203,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
if (ic == null) return false;
final CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
- && Utils.canBeFollowedByPeriod(lastThree.charAt(0))
+ && StringUtils.canBeFollowedByPeriod(lastThree.charAt(0))
&& lastThree.charAt(1) == Keyboard.CODE_SPACE
&& lastThree.charAt(2) == Keyboard.CODE_SPACE
&& mHandler.isAcceptingDoubleSpaces()) {
@@ -1247,7 +1243,8 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
if (isShowingOptionDialog()) return;
if (InputMethodServiceCompatWrapper.CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) {
showSubtypeSelectorAndSettings();
- } else if (Utils.hasMultipleEnabledIMEsOrSubtypes(false /* exclude aux subtypes */)) {
+ } else if (SubtypeUtils.hasMultipleEnabledIMEsOrSubtypes(
+ false /* exclude aux subtypes */)) {
showOptionsMenu();
} else {
launchSettings();
@@ -1263,7 +1260,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
if (isShowingOptionDialog()) return false;
switch (requestCode) {
case CODE_SHOW_INPUT_METHOD_PICKER:
- if (Utils.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) {
+ if (SubtypeUtils.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) {
mImm.showInputMethodPicker();
return true;
}
@@ -1295,7 +1292,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
final IBinder token = getWindow().getWindow().getAttributes().token;
if (mShouldSwitchToLastSubtype) {
final InputMethodSubtypeCompatWrapper lastSubtype = mImm.getLastInputMethodSubtype();
- final boolean lastSubtypeBelongsToThisIme = Utils.checkIfSubtypeBelongsToThisIme(
+ final boolean lastSubtypeBelongsToThisIme = SubtypeUtils.checkIfSubtypeBelongsToThisIme(
this, lastSubtype);
if ((includesOtherImes || lastSubtypeBelongsToThisIme)
&& mImm.switchToLastInputMethod(token)) {
@@ -1339,6 +1336,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// all inputs that do not result in a special state. Each character handling is then
// free to override the state as they see fit.
final int spaceState = mSpaceState;
+ if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false;
// TODO: Consolidate the double space timer, mLastKeyTime, and the space state.
if (primaryCode != Keyboard.CODE_SPACE) {
@@ -1588,7 +1586,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// it entirely and resume suggestions on the previous word, we'd like to still
// have touch coordinates for it.
resetComposingState(false /* alsoResetLastComposedWord */);
- mComposingStateManager.onFinishComposingText();
clearSuggestions();
}
}
@@ -1599,7 +1596,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// If it's the first letter, make note of auto-caps state
if (mWordComposer.size() == 1) {
mWordComposer.setAutoCapitalized(getCurrentAutoCapsState());
- mComposingStateManager.onStartComposingText();
}
ic.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
}
@@ -1631,7 +1627,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
private boolean handleSeparator(final int primaryCode, final int x, final int y,
final int spaceState) {
mVoiceProxy.handleSeparator();
- mComposingStateManager.onFinishComposingText();
// Should dismiss the "Touch again to save" message when handling separator
if (mSuggestionsView != null && mSuggestionsView.dismissAddToDictionaryHint()) {
@@ -1711,7 +1706,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
}
private CharSequence getTextWithUnderline(final CharSequence text) {
- return mComposingStateManager.isAutoCorrectionIndicatorOn()
+ return mIsAutoCorrectionIndicatorOn
? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text)
: text;
}
@@ -1787,15 +1782,9 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// Put a blue underline to a word in TextView which will be auto-corrected.
final InputConnection ic = getCurrentInputConnection();
if (ic != null) {
- final boolean oldAutoCorrectionIndicator =
- mComposingStateManager.isAutoCorrectionIndicatorOn();
- if (oldAutoCorrectionIndicator != newAutoCorrectionIndicator) {
- mComposingStateManager.setAutoCorrectionIndicatorOn(newAutoCorrectionIndicator);
- if (DEBUG) {
- Log.d(TAG, "Flip the indicator. " + oldAutoCorrectionIndicator
- + " -> " + newAutoCorrectionIndicator);
- }
+ if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator) {
if (mWordComposer.isComposingWord()) {
+ mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator;
final CharSequence textWithUnderline =
getTextWithUnderline(mWordComposer.getTypedWord());
ic.setComposingText(textWithUnderline, 1);
@@ -1884,7 +1873,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions);
}
}
- if (Utils.shouldBlockAutoCorrectionBySafetyNet(builder, mSuggest)) {
+ if (Suggest.shouldBlockAutoCorrectionBySafetyNet(builder, mSuggest)) {
builder.setShouldBlockAutoCorrectionBySafetyNet();
}
showSuggestions(builder.build(), typedWord);
@@ -1941,7 +1930,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
@Override
public void pickSuggestionManually(final int index, final CharSequence suggestion) {
- mComposingStateManager.onFinishComposingText();
final SuggestedWords suggestedWords = mSuggestionsView.getSuggestions();
mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion,
mSettingsValues.mWordSeparators);
@@ -2144,14 +2132,12 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
public boolean isCursorTouchingWord() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
- CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
- CharSequence toRight = ic.getTextAfterCursor(1, 0);
- if (!TextUtils.isEmpty(toLeft)
- && !mSettingsValues.isWordSeparator(toLeft.charAt(0))) {
+ CharSequence before = ic.getTextBeforeCursor(1, 0);
+ CharSequence after = ic.getTextAfterCursor(1, 0);
+ if (!TextUtils.isEmpty(before) && !mSettingsValues.isWordSeparator(before.charAt(0))) {
return true;
}
- if (!TextUtils.isEmpty(toRight)
- && !mSettingsValues.isWordSeparator(toRight.charAt(0))) {
+ if (!TextUtils.isEmpty(after) && !mSettingsValues.isWordSeparator(after.charAt(0))) {
return true;
}
return false;
@@ -2212,7 +2198,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
private void restartSuggestionsOnWordBeforeCursor(final InputConnection ic,
final CharSequence word) {
mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard());
- mComposingStateManager.onStartComposingText();
ic.deleteSurroundingText(word.length(), 0);
ic.setComposingText(word, 1);
mHandler.postUpdateSuggestions();
@@ -2244,7 +2229,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
// This is the case when we cancel a manual pick.
// We should restart suggestion on the word right away.
mWordComposer.resumeSuggestionOnLastComposedWord(mLastComposedWord);
- mComposingStateManager.onStartComposingText();
ic.setComposingText(originallyTypedWord, 1);
} else {
ic.commitText(originallyTypedWord, 1);
@@ -2335,9 +2319,8 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
}
}
- public void hapticAndAudioFeedback(int primaryCode) {
- vibrate();
- playKeyClick(primaryCode);
+ public void hapticAndAudioFeedback(final int primaryCode) {
+ mFeedbackManager.hapticAndAudioFeedback(primaryCode, mKeyboardSwitcher.getKeyboardView());
}
@Override
@@ -2367,76 +2350,21 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
- if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
- updateRingerMode();
- } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
+ if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mSubtypeSwitcher.onNetworkStateChanged(intent);
}
}
};
- // update flags for silent mode
- private void updateRingerMode() {
- if (mAudioManager == null) {
- mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
- if (mAudioManager == null) return;
- }
- mSilentModeOn = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
- }
-
- private void playKeyClick(int primaryCode) {
- // if mAudioManager is null, we don't have the ringer state yet
- // mAudioManager will be set by updateRingerMode
- if (mAudioManager == null) {
- if (mKeyboardSwitcher.getKeyboardView() != null) {
- updateRingerMode();
- }
- }
- if (isSoundOn()) {
- final int sound;
- switch (primaryCode) {
- case Keyboard.CODE_DELETE:
- sound = AudioManager.FX_KEYPRESS_DELETE;
- break;
- case Keyboard.CODE_ENTER:
- sound = AudioManager.FX_KEYPRESS_RETURN;
- break;
- case Keyboard.CODE_SPACE:
- sound = AudioManager.FX_KEYPRESS_SPACEBAR;
- break;
- default:
- sound = AudioManager.FX_KEYPRESS_STANDARD;
- break;
- }
- mAudioManager.playSoundEffect(sound, mSettingsValues.mFxVolume);
- }
- }
-
+ // TODO: remove this method when VoiceProxy has been removed
public void vibrate() {
- if (!mSettingsValues.mVibrateOn) {
- return;
- }
- if (mSettingsValues.mKeypressVibrationDuration < 0) {
- // Go ahead with the system default
- LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
- if (inputView != null) {
- inputView.performHapticFeedback(
- HapticFeedbackConstants.KEYBOARD_TAP,
- HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
- }
- } else if (mVibrator != null) {
- mVibrator.vibrate(mSettingsValues.mKeypressVibrationDuration);
- }
+ mFeedbackManager.vibrate(mKeyboardSwitcher.getKeyboardView());
}
public boolean isAutoCapitalized() {
return mWordComposer.isAutoCapitalized();
}
- boolean isSoundOn() {
- return mSettingsValues.mSoundOn && !mSilentModeOn;
- }
-
private void updateCorrectionMode() {
// TODO: cleanup messy flags
final boolean shouldAutoCorrect = mSettingsValues.mAutoCorrectEnabled
@@ -2486,7 +2414,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar
switch (position) {
case 0:
Intent intent = CompatUtils.getInputLanguageSelectionIntent(
- Utils.getInputMethodId(getPackageName()),
+ SubtypeUtils.getInputMethodId(getPackageName()),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
diff --git a/java/src/com/android/inputmethod/latin/Settings.java b/java/src/com/android/inputmethod/latin/Settings.java
index 305cef22d..72391f31e 100644
--- a/java/src/com/android/inputmethod/latin/Settings.java
+++ b/java/src/com/android/inputmethod/latin/Settings.java
@@ -343,7 +343,7 @@ public class Settings extends InputMethodSettingsActivity
@Override
public boolean onPreferenceClick(Preference pref) {
if (pref == mInputLanguageSelection) {
- final String imeId = Utils.getInputMethodId(
+ final String imeId = SubtypeUtils.getInputMethodId(
getActivityInternal().getApplicationInfo().packageName);
startActivity(CompatUtils.getInputLanguageSelectionIntent(imeId, 0));
return true;
diff --git a/java/src/com/android/inputmethod/latin/SettingsValues.java b/java/src/com/android/inputmethod/latin/SettingsValues.java
index 69e45f619..abd1dc692 100644
--- a/java/src/com/android/inputmethod/latin/SettingsValues.java
+++ b/java/src/com/android/inputmethod/latin/SettingsValues.java
@@ -326,9 +326,9 @@ public class SettingsValues {
return false;
}
if (mIncludesOtherImesInLanguageSwitchList) {
- return Utils.hasMultipleEnabledIMEsOrSubtypes(/* include aux subtypes */false);
+ return SubtypeUtils.hasMultipleEnabledIMEsOrSubtypes(/* include aux subtypes */false);
} else {
- return Utils.hasMultipleEnabledSubtypesInThisIme(
+ return SubtypeUtils.hasMultipleEnabledSubtypesInThisIme(
context, /* include aux subtypes */false);
}
}
diff --git a/java/src/com/android/inputmethod/latin/StringUtils.java b/java/src/com/android/inputmethod/latin/StringUtils.java
new file mode 100644
index 000000000..81c3b4edf
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/StringUtils.java
@@ -0,0 +1,198 @@
+/*
+ * 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 com.android.inputmethod.latin;
+
+import android.text.TextUtils;
+import android.view.inputmethod.EditorInfo;
+
+import com.android.inputmethod.keyboard.Keyboard;
+
+import java.util.ArrayList;
+import java.util.Locale;
+
+public class StringUtils {
+ private StringUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static boolean canBeFollowedByPeriod(final int codePoint) {
+ // TODO: Check again whether there really ain't a better way to check this.
+ // TODO: This should probably be language-dependant...
+ return Character.isLetterOrDigit(codePoint)
+ || codePoint == Keyboard.CODE_SINGLE_QUOTE
+ || codePoint == Keyboard.CODE_DOUBLE_QUOTE
+ || codePoint == Keyboard.CODE_CLOSING_PARENTHESIS
+ || codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET
+ || codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET
+ || codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET;
+ }
+
+ public static int codePointCount(String text) {
+ if (TextUtils.isEmpty(text)) return 0;
+ return text.codePointCount(0, text.length());
+ }
+
+ public static boolean containsInCsv(String key, String csv) {
+ if (csv == null)
+ return false;
+ for (String option : csv.split(",")) {
+ if (option.equals(key))
+ return true;
+ }
+ return false;
+ }
+
+ public static boolean inPrivateImeOptions(String packageName, String key,
+ EditorInfo editorInfo) {
+ if (editorInfo == null)
+ return false;
+ return containsInCsv(packageName != null ? packageName + "." + key : key,
+ editorInfo.privateImeOptions);
+ }
+
+ /**
+ * Returns true if a and b are equal ignoring the case of the character.
+ * @param a first character to check
+ * @param b second character to check
+ * @return {@code true} if a and b are equal, {@code false} otherwise.
+ */
+ public static boolean equalsIgnoreCase(char a, char b) {
+ // Some language, such as Turkish, need testing both cases.
+ return a == b
+ || Character.toLowerCase(a) == Character.toLowerCase(b)
+ || Character.toUpperCase(a) == Character.toUpperCase(b);
+ }
+
+ /**
+ * Returns true if a and b are equal ignoring the case of the characters, including if they are
+ * both null.
+ * @param a first CharSequence to check
+ * @param b second CharSequence to check
+ * @return {@code true} if a and b are equal, {@code false} otherwise.
+ */
+ public static boolean equalsIgnoreCase(CharSequence a, CharSequence b) {
+ if (a == b)
+ return true; // including both a and b are null.
+ if (a == null || b == null)
+ return false;
+ final int length = a.length();
+ if (length != b.length())
+ return false;
+ for (int i = 0; i < length; i++) {
+ if (!equalsIgnoreCase(a.charAt(i), b.charAt(i)))
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns true if a and b are equal ignoring the case of the characters, including if a is null
+ * and b is zero length.
+ * @param a CharSequence to check
+ * @param b character array to check
+ * @param offset start offset of array b
+ * @param length length of characters in array b
+ * @return {@code true} if a and b are equal, {@code false} otherwise.
+ * @throws IndexOutOfBoundsException
+ * if {@code offset < 0 || length < 0 || offset + length > data.length}.
+ * @throws NullPointerException if {@code b == null}.
+ */
+ public static boolean equalsIgnoreCase(CharSequence a, char[] b, int offset, int length) {
+ if (offset < 0 || length < 0 || length > b.length - offset)
+ throw new IndexOutOfBoundsException("array.length=" + b.length + " offset=" + offset
+ + " length=" + length);
+ if (a == null)
+ return length == 0; // including a is null and b is zero length.
+ if (a.length() != length)
+ return false;
+ for (int i = 0; i < length; i++) {
+ if (!equalsIgnoreCase(a.charAt(i), b[offset + i]))
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Remove duplicates from an array of strings.
+ *
+ * This method will always keep the first occurence of all strings at their position
+ * in the array, removing the subsequent ones.
+ */
+ public static void removeDupes(final ArrayList<CharSequence> suggestions) {
+ if (suggestions.size() < 2) return;
+ int i = 1;
+ // Don't cache suggestions.size(), since we may be removing items
+ while (i < suggestions.size()) {
+ final CharSequence cur = suggestions.get(i);
+ // Compare each suggestion with each previous suggestion
+ for (int j = 0; j < i; j++) {
+ CharSequence previous = suggestions.get(j);
+ if (TextUtils.equals(cur, previous)) {
+ removeFromSuggestions(suggestions, i);
+ i--;
+ break;
+ }
+ }
+ i++;
+ }
+ }
+
+ private static void removeFromSuggestions(final ArrayList<CharSequence> suggestions,
+ final int index) {
+ final CharSequence garbage = suggestions.remove(index);
+ if (garbage instanceof StringBuilder) {
+ StringBuilderPool.recycle((StringBuilder)garbage);
+ }
+ }
+
+ public static String getFullDisplayName(Locale locale, boolean returnsNameInThisLocale) {
+ if (returnsNameInThisLocale) {
+ return toTitleCase(SubtypeLocale.getFullDisplayName(locale), locale);
+ } else {
+ return toTitleCase(locale.getDisplayName(), locale);
+ }
+ }
+
+ public static String getDisplayLanguage(Locale locale) {
+ return toTitleCase(SubtypeLocale.getFullDisplayName(locale), locale);
+ }
+
+ public static String getMiddleDisplayLanguage(Locale locale) {
+ return toTitleCase((LocaleUtils.constructLocaleFromString(
+ locale.getLanguage()).getDisplayLanguage(locale)), locale);
+ }
+
+ public static String getShortDisplayLanguage(Locale locale) {
+ return toTitleCase(locale.getLanguage(), locale);
+ }
+
+ public static String toTitleCase(String s, Locale locale) {
+ if (s.length() <= 1) {
+ // TODO: is this really correct? Shouldn't this be s.toUpperCase()?
+ return s;
+ }
+ // 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, which
+ // are two different characters but both should be capitalized as "IJ" as if they were
+ // a single letter.
+ // - It also does not work with unicode surrogate code points.
+ return s.toUpperCase(locale).charAt(0) + s.substring(1);
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
index f5778167a..ffbbf9bb8 100644
--- a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
+++ b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
@@ -512,7 +512,7 @@ public class SubtypeSwitcher {
}
public String getInputLanguageName() {
- return Utils.getDisplayLanguage(getInputLocale());
+ return StringUtils.getDisplayLanguage(getInputLocale());
}
/////////////////////////////
diff --git a/java/src/com/android/inputmethod/latin/SubtypeUtils.java b/java/src/com/android/inputmethod/latin/SubtypeUtils.java
new file mode 100644
index 000000000..cb2bcf43f
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/SubtypeUtils.java
@@ -0,0 +1,135 @@
+/*
+ * 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 com.android.inputmethod.latin;
+
+import android.content.Context;
+
+import com.android.inputmethod.compat.InputMethodInfoCompatWrapper;
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.compat.InputMethodSubtypeCompatWrapper;
+
+import java.util.Collections;
+import java.util.List;
+
+public class SubtypeUtils {
+ private SubtypeUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ // TODO: Cache my InputMethodInfo and/or InputMethodSubtype list.
+ public static boolean checkIfSubtypeBelongsToThisIme(Context context,
+ InputMethodSubtypeCompatWrapper ims) {
+ final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
+ if (imm == null) return false;
+
+ final InputMethodInfoCompatWrapper myImi = getInputMethodInfo(context.getPackageName());
+ final List<InputMethodSubtypeCompatWrapper> subtypes =
+ imm.getEnabledInputMethodSubtypeList(myImi, true);
+ for (final InputMethodSubtypeCompatWrapper subtype : subtypes) {
+ if (subtype.equals(ims)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static boolean hasMultipleEnabledIMEsOrSubtypes(
+ final boolean shouldIncludeAuxiliarySubtypes) {
+ final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
+ if (imm == null) return false;
+
+ final List<InputMethodInfoCompatWrapper> enabledImis = imm.getEnabledInputMethodList();
+ return hasMultipleEnabledSubtypes(shouldIncludeAuxiliarySubtypes, enabledImis);
+ }
+
+ public static boolean hasMultipleEnabledSubtypesInThisIme(Context context,
+ final boolean shouldIncludeAuxiliarySubtypes) {
+ final InputMethodInfoCompatWrapper myImi = getInputMethodInfo(context.getPackageName());
+ final List<InputMethodInfoCompatWrapper> imiList = Collections.singletonList(myImi);
+ return hasMultipleEnabledSubtypes(shouldIncludeAuxiliarySubtypes, imiList);
+ }
+
+ private static boolean hasMultipleEnabledSubtypes(final boolean shouldIncludeAuxiliarySubtypes,
+ List<InputMethodInfoCompatWrapper> imiList) {
+ final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
+ if (imm == null) return false;
+
+ // Number of the filtered IMEs
+ int filteredImisCount = 0;
+
+ for (InputMethodInfoCompatWrapper imi : imiList) {
+ // We can return true immediately after we find two or more filtered IMEs.
+ if (filteredImisCount > 1) return true;
+ final List<InputMethodSubtypeCompatWrapper> subtypes =
+ imm.getEnabledInputMethodSubtypeList(imi, true);
+ // IMEs that have no subtypes should be counted.
+ if (subtypes.isEmpty()) {
+ ++filteredImisCount;
+ continue;
+ }
+
+ int auxCount = 0;
+ for (InputMethodSubtypeCompatWrapper subtype : subtypes) {
+ if (subtype.isAuxiliary()) {
+ ++auxCount;
+ }
+ }
+ final int nonAuxCount = subtypes.size() - auxCount;
+
+ // IMEs that have one or more non-auxiliary subtypes should be counted.
+ // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
+ // subtypes should be counted as well.
+ if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
+ ++filteredImisCount;
+ continue;
+ }
+ }
+
+ if (filteredImisCount > 1) {
+ return true;
+ }
+ final List<InputMethodSubtypeCompatWrapper> subtypes =
+ imm.getEnabledInputMethodSubtypeList(null, true);
+ int keyboardCount = 0;
+ // imm.getEnabledInputMethodSubtypeList(null, true) will return the current IME's
+ // both explicitly and implicitly enabled input method subtype.
+ // (The current IME should be LatinIME.)
+ for (InputMethodSubtypeCompatWrapper subtype : subtypes) {
+ if (SubtypeSwitcher.KEYBOARD_MODE.equals(subtype.getMode())) {
+ ++keyboardCount;
+ }
+ }
+ return keyboardCount > 1;
+ }
+
+ public static String getInputMethodId(String packageName) {
+ return getInputMethodInfo(packageName).getId();
+ }
+
+ public static InputMethodInfoCompatWrapper getInputMethodInfo(String packageName) {
+ final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
+ if (imm == null) {
+ throw new RuntimeException("Input method manager not found");
+ }
+
+ for (final InputMethodInfoCompatWrapper imi : imm.getEnabledInputMethodList()) {
+ if (imi.getPackageName().equals(packageName))
+ return imi;
+ }
+ throw new RuntimeException("Can not find input method id for " + packageName);
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java
index 298ead665..671fb905d 100644
--- a/java/src/com/android/inputmethod/latin/Suggest.java
+++ b/java/src/com/android/inputmethod/latin/Suggest.java
@@ -108,6 +108,8 @@ public class Suggest implements Dictionary.WordCallback {
private boolean mIsAllUpperCase;
private int mTrailingSingleQuotesCount;
+ private static final int MINIMUM_SAFETY_NET_CHAR_LENGTH = 4;
+
public Suggest(final Context context, final int dictionaryResId, final Locale locale) {
initAsynchronously(context, dictionaryResId, locale);
}
@@ -383,7 +385,7 @@ public class Suggest implements Dictionary.WordCallback {
if (typedWord != null) {
mSuggestions.add(0, typedWord.toString());
}
- Utils.removeDupes(mSuggestions);
+ StringUtils.removeDupes(mSuggestions);
if (DBG) {
double normalizedScore = mAutoCorrection.getNormalizedScore();
@@ -434,7 +436,7 @@ public class Suggest implements Dictionary.WordCallback {
int pos = 0;
// Check if it's the same word, only caps are different
- if (Utils.equalsIgnoreCase(mConsideredWord, word, offset, length)) {
+ if (StringUtils.equalsIgnoreCase(mConsideredWord, word, offset, length)) {
// TODO: remove this surrounding if clause and move this logic to
// getSuggestedWordBuilder.
if (suggestions.size() > 0) {
@@ -443,7 +445,7 @@ public class Suggest implements Dictionary.WordCallback {
// frequency to determine the insertion position. This does not ensure strictly
// correct ordering, but ensures the top score is on top which is enough for
// removing duplicates correctly.
- if (Utils.equalsIgnoreCase(currentHighestWord, word, offset, length)
+ if (StringUtils.equalsIgnoreCase(currentHighestWord, word, offset, length)
&& score <= sortedScores[0]) {
pos = 1;
}
@@ -558,4 +560,46 @@ public class Suggest implements Dictionary.WordCallback {
}
mMainDict = null;
}
+
+ // TODO: Resolve the inconsistencies between the native auto correction algorithms and
+ // this safety net
+ public static boolean shouldBlockAutoCorrectionBySafetyNet(
+ SuggestedWords.Builder suggestedWordsBuilder, Suggest suggest) {
+ // Safety net for auto correction.
+ // Actually if we hit this safety net, it's actually a bug.
+ if (suggestedWordsBuilder.size() <= 1 || suggestedWordsBuilder.isTypedWordValid()) {
+ return false;
+ }
+ // If user selected aggressive auto correction mode, there is no need to use the safety
+ // net.
+ if (suggest.isAggressiveAutoCorrectionMode()) {
+ return false;
+ }
+ final CharSequence typedWord = suggestedWordsBuilder.getWord(0);
+ // If the length of typed word is less than MINIMUM_SAFETY_NET_CHAR_LENGTH,
+ // we should not use net because relatively edit distance can be big.
+ if (typedWord.length() < Suggest.MINIMUM_SAFETY_NET_CHAR_LENGTH) {
+ return false;
+ }
+ final CharSequence suggestionWord = suggestedWordsBuilder.getWord(1);
+ final int typedWordLength = typedWord.length();
+ final int maxEditDistanceOfNativeDictionary =
+ (typedWordLength < 5 ? 2 : typedWordLength / 2) + 1;
+ final int distance = BinaryDictionary.editDistance(
+ typedWord.toString(), suggestionWord.toString());
+ if (DBG) {
+ Log.d(TAG, "Autocorrected edit distance = " + distance
+ + ", " + maxEditDistanceOfNativeDictionary);
+ }
+ if (distance > maxEditDistanceOfNativeDictionary) {
+ if (DBG) {
+ Log.e(TAG, "Safety net: before = " + typedWord + ", after = " + suggestionWord);
+ Log.e(TAG, "(Error) The edit distance of this correction exceeds limit. "
+ + "Turning off auto-correction.");
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
}
diff --git a/java/src/com/android/inputmethod/latin/Utils.java b/java/src/com/android/inputmethod/latin/Utils.java
index a8679e07a..f8dd5ae42 100644
--- a/java/src/com/android/inputmethod/latin/Utils.java
+++ b/java/src/com/android/inputmethod/latin/Utils.java
@@ -19,7 +19,6 @@ package com.android.inputmethod.latin;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
-import android.content.res.Resources;
import android.inputmethodservice.InputMethodService;
import android.net.Uri;
import android.os.AsyncTask;
@@ -27,19 +26,9 @@ import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
-import android.text.InputType;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
-import android.view.inputmethod.EditorInfo;
-
-import com.android.inputmethod.compat.InputMethodInfoCompatWrapper;
-import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
-import com.android.inputmethod.compat.InputMethodSubtypeCompatWrapper;
-import com.android.inputmethod.compat.InputTypeCompatUtils;
-import com.android.inputmethod.keyboard.Keyboard;
-import com.android.inputmethod.keyboard.KeyboardId;
-import com.android.inputmethod.latin.define.JniLibName;
import java.io.BufferedReader;
import java.io.File;
@@ -51,20 +40,11 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collections;
import java.util.Date;
-import java.util.List;
-import java.util.Locale;
public class Utils {
- private static final String TAG = Utils.class.getSimpleName();
- private static final int MINIMUM_SAFETY_NET_CHAR_LENGTH = 4;
- private static boolean DBG = LatinImeLogger.sDBG;
- private static boolean DBG_EDIT_DISTANCE = false;
-
private Utils() {
- // Intentional empty constructor for utility class.
+ // This utility class is not publicly instantiable.
}
/**
@@ -118,166 +98,6 @@ public class Utils {
}
}
- // TODO: Move InputMethodSubtype related utility methods to its own utility class.
- // TODO: Cache my InputMethodInfo and/or InputMethodSubtype list.
- public static boolean checkIfSubtypeBelongsToThisIme(Context context,
- InputMethodSubtypeCompatWrapper ims) {
- final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
- if (imm == null) return false;
-
- final InputMethodInfoCompatWrapper myImi = Utils.getInputMethodInfo(
- context.getPackageName());
- final List<InputMethodSubtypeCompatWrapper> subtypes =
- imm.getEnabledInputMethodSubtypeList(myImi, true);
- for (final InputMethodSubtypeCompatWrapper subtype : subtypes) {
- if (subtype.equals(ims)) {
- return true;
- }
- }
- return false;
- }
-
- public static boolean hasMultipleEnabledIMEsOrSubtypes(
- final boolean shouldIncludeAuxiliarySubtypes) {
- final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
- if (imm == null) return false;
-
- final List<InputMethodInfoCompatWrapper> enabledImis = imm.getEnabledInputMethodList();
- return hasMultipleEnabledSubtypes(shouldIncludeAuxiliarySubtypes, enabledImis);
- }
-
- public static boolean hasMultipleEnabledSubtypesInThisIme(Context context,
- final boolean shouldIncludeAuxiliarySubtypes) {
- final InputMethodInfoCompatWrapper myImi = Utils.getInputMethodInfo(
- context.getPackageName());
- final List<InputMethodInfoCompatWrapper> imiList = Collections.singletonList(myImi);
- return Utils.hasMultipleEnabledSubtypes(shouldIncludeAuxiliarySubtypes, imiList);
- }
-
- private static boolean hasMultipleEnabledSubtypes(final boolean shouldIncludeAuxiliarySubtypes,
- List<InputMethodInfoCompatWrapper> imiList) {
- final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
- if (imm == null) return false;
-
- // Number of the filtered IMEs
- int filteredImisCount = 0;
-
- for (InputMethodInfoCompatWrapper imi : imiList) {
- // We can return true immediately after we find two or more filtered IMEs.
- if (filteredImisCount > 1) return true;
- final List<InputMethodSubtypeCompatWrapper> subtypes =
- imm.getEnabledInputMethodSubtypeList(imi, true);
- // IMEs that have no subtypes should be counted.
- if (subtypes.isEmpty()) {
- ++filteredImisCount;
- continue;
- }
-
- int auxCount = 0;
- for (InputMethodSubtypeCompatWrapper subtype : subtypes) {
- if (subtype.isAuxiliary()) {
- ++auxCount;
- }
- }
- final int nonAuxCount = subtypes.size() - auxCount;
-
- // IMEs that have one or more non-auxiliary subtypes should be counted.
- // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
- // subtypes should be counted as well.
- if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
- ++filteredImisCount;
- continue;
- }
- }
-
- if (filteredImisCount > 1) {
- return true;
- }
- final List<InputMethodSubtypeCompatWrapper> subtypes =
- imm.getEnabledInputMethodSubtypeList(null, true);
- int keyboardCount = 0;
- // imm.getEnabledInputMethodSubtypeList(null, true) will return the current IME's
- // both explicitly and implicitly enabled input method subtype.
- // (The current IME should be LatinIME.)
- for (InputMethodSubtypeCompatWrapper subtype : subtypes) {
- if (SubtypeSwitcher.KEYBOARD_MODE.equals(subtype.getMode())) {
- ++keyboardCount;
- }
- }
- return keyboardCount > 1;
- }
-
- public static String getInputMethodId(String packageName) {
- return getInputMethodInfo(packageName).getId();
- }
-
- public static InputMethodInfoCompatWrapper getInputMethodInfo(String packageName) {
- final InputMethodManagerCompatWrapper imm = InputMethodManagerCompatWrapper.getInstance();
- if (imm == null) {
- throw new RuntimeException("Input method manager not found");
- }
-
- for (final InputMethodInfoCompatWrapper imi : imm.getEnabledInputMethodList()) {
- if (imi.getPackageName().equals(packageName))
- return imi;
- }
- throw new RuntimeException("Can not find input method id for " + packageName);
- }
-
- // TODO: Resolve the inconsistencies between the native auto correction algorithms and
- // this safety net
- public static boolean shouldBlockAutoCorrectionBySafetyNet(
- SuggestedWords.Builder suggestedWordsBuilder, Suggest suggest) {
- // Safety net for auto correction.
- // Actually if we hit this safety net, it's actually a bug.
- if (suggestedWordsBuilder.size() <= 1 || suggestedWordsBuilder.isTypedWordValid()) {
- return false;
- }
- // If user selected aggressive auto correction mode, there is no need to use the safety
- // net.
- if (suggest.isAggressiveAutoCorrectionMode()) {
- return false;
- }
- final CharSequence typedWord = suggestedWordsBuilder.getWord(0);
- // If the length of typed word is less than MINIMUM_SAFETY_NET_CHAR_LENGTH,
- // we should not use net because relatively edit distance can be big.
- if (typedWord.length() < MINIMUM_SAFETY_NET_CHAR_LENGTH) {
- return false;
- }
- final CharSequence suggestionWord = suggestedWordsBuilder.getWord(1);
- final int typedWordLength = typedWord.length();
- final int maxEditDistanceOfNativeDictionary =
- (typedWordLength < 5 ? 2 : typedWordLength / 2) + 1;
- final int distance = BinaryDictionary.editDistance(
- typedWord.toString(), suggestionWord.toString());
- if (DBG) {
- Log.d(TAG, "Autocorrected edit distance = " + distance
- + ", " + maxEditDistanceOfNativeDictionary);
- }
- if (distance > maxEditDistanceOfNativeDictionary) {
- if (DBG) {
- Log.e(TAG, "Safety net: before = " + typedWord + ", after = " + suggestionWord);
- Log.e(TAG, "(Error) The edit distance of this correction exceeds limit. "
- + "Turning off auto-correction.");
- }
- return true;
- } else {
- return false;
- }
- }
-
- public static boolean canBeFollowedByPeriod(final int codePoint) {
- // TODO: Check again whether there really ain't a better way to check this.
- // TODO: This should probably be language-dependant...
- return Character.isLetterOrDigit(codePoint)
- || codePoint == Keyboard.CODE_SINGLE_QUOTE
- || codePoint == Keyboard.CODE_DOUBLE_QUOTE
- || codePoint == Keyboard.CODE_CLOSING_PARENTHESIS
- || codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET
- || codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET
- || codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET;
- }
-
/* package */ static class RingCharBuffer {
private static RingCharBuffer sRingCharBuffer = new RingCharBuffer();
private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC';
@@ -600,147 +420,6 @@ public class Utils {
}
}
- // TODO: Move this method to KeyboardSet class.
- public static int getKeyboardMode(EditorInfo editorInfo) {
- if (editorInfo == null)
- return KeyboardId.MODE_TEXT;
-
- final int inputType = editorInfo.inputType;
- final int variation = inputType & InputType.TYPE_MASK_VARIATION;
-
- switch (inputType & InputType.TYPE_MASK_CLASS) {
- case InputType.TYPE_CLASS_NUMBER:
- return KeyboardId.MODE_NUMBER;
- case InputType.TYPE_CLASS_DATETIME:
- switch (variation) {
- case InputType.TYPE_DATETIME_VARIATION_DATE:
- return KeyboardId.MODE_DATE;
- case InputType.TYPE_DATETIME_VARIATION_TIME:
- return KeyboardId.MODE_TIME;
- default: // InputType.TYPE_DATETIME_VARIATION_NORMAL
- return KeyboardId.MODE_DATETIME;
- }
- case InputType.TYPE_CLASS_PHONE:
- return KeyboardId.MODE_PHONE;
- case InputType.TYPE_CLASS_TEXT:
- if (InputTypeCompatUtils.isEmailVariation(variation)) {
- return KeyboardId.MODE_EMAIL;
- } else if (variation == InputType.TYPE_TEXT_VARIATION_URI) {
- return KeyboardId.MODE_URL;
- } else if (variation == InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
- return KeyboardId.MODE_IM;
- } else if (variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
- return KeyboardId.MODE_TEXT;
- } else {
- return KeyboardId.MODE_TEXT;
- }
- default:
- return KeyboardId.MODE_TEXT;
- }
- }
-
- public static boolean containsInCsv(String key, String csv) {
- if (csv == null)
- return false;
- for (String option : csv.split(",")) {
- if (option.equals(key))
- return true;
- }
- return false;
- }
-
- public static boolean inPrivateImeOptions(String packageName, String key,
- EditorInfo editorInfo) {
- if (editorInfo == null)
- return false;
- return containsInCsv(packageName != null ? packageName + "." + key : key,
- editorInfo.privateImeOptions);
- }
-
- /**
- * Returns a main dictionary resource id
- * @return main dictionary resource id
- */
- public static int getMainDictionaryResourceId(Resources res) {
- final String MAIN_DIC_NAME = "main";
- String packageName = LatinIME.class.getPackage().getName();
- return res.getIdentifier(MAIN_DIC_NAME, "raw", packageName);
- }
-
- public static void loadNativeLibrary() {
- try {
- System.loadLibrary(JniLibName.JNI_LIB_NAME);
- } catch (UnsatisfiedLinkError ule) {
- Log.e(TAG, "Could not load native library " + JniLibName.JNI_LIB_NAME);
- if (LatinImeLogger.sDBG) {
- throw new RuntimeException(
- "Could not load native library " + JniLibName.JNI_LIB_NAME);
- }
- }
- }
-
- /**
- * Returns true if a and b are equal ignoring the case of the character.
- * @param a first character to check
- * @param b second character to check
- * @return {@code true} if a and b are equal, {@code false} otherwise.
- */
- public static boolean equalsIgnoreCase(char a, char b) {
- // Some language, such as Turkish, need testing both cases.
- return a == b
- || Character.toLowerCase(a) == Character.toLowerCase(b)
- || Character.toUpperCase(a) == Character.toUpperCase(b);
- }
-
- /**
- * Returns true if a and b are equal ignoring the case of the characters, including if they are
- * both null.
- * @param a first CharSequence to check
- * @param b second CharSequence to check
- * @return {@code true} if a and b are equal, {@code false} otherwise.
- */
- public static boolean equalsIgnoreCase(CharSequence a, CharSequence b) {
- if (a == b)
- return true; // including both a and b are null.
- if (a == null || b == null)
- return false;
- final int length = a.length();
- if (length != b.length())
- return false;
- for (int i = 0; i < length; i++) {
- if (!equalsIgnoreCase(a.charAt(i), b.charAt(i)))
- return false;
- }
- return true;
- }
-
- /**
- * Returns true if a and b are equal ignoring the case of the characters, including if a is null
- * and b is zero length.
- * @param a CharSequence to check
- * @param b character array to check
- * @param offset start offset of array b
- * @param length length of characters in array b
- * @return {@code true} if a and b are equal, {@code false} otherwise.
- * @throws IndexOutOfBoundsException
- * if {@code offset < 0 || length < 0 || offset + length > data.length}.
- * @throws NullPointerException if {@code b == null}.
- */
- public static boolean equalsIgnoreCase(CharSequence a, char[] b, int offset, int length) {
- if (offset < 0 || length < 0 || length > b.length - offset)
- throw new IndexOutOfBoundsException("array.length=" + b.length + " offset=" + offset
- + " length=" + length);
- if (a == null)
- return length == 0; // including a is null and b is zero length.
- if (a.length() != length)
- return false;
- for (int i = 0; i < length; i++) {
- if (!equalsIgnoreCase(a.charAt(i), b[offset + i]))
- return false;
- }
- return true;
- }
-
public static float getDipScale(Context context) {
final float scale = context.getResources().getDisplayMetrics().density;
return scale;
@@ -751,76 +430,6 @@ public class Utils {
return (int) (dip * scale + 0.5);
}
- /**
- * Remove duplicates from an array of strings.
- *
- * This method will always keep the first occurence of all strings at their position
- * in the array, removing the subsequent ones.
- */
- public static void removeDupes(final ArrayList<CharSequence> suggestions) {
- if (suggestions.size() < 2) return;
- int i = 1;
- // Don't cache suggestions.size(), since we may be removing items
- while (i < suggestions.size()) {
- final CharSequence cur = suggestions.get(i);
- // Compare each suggestion with each previous suggestion
- for (int j = 0; j < i; j++) {
- CharSequence previous = suggestions.get(j);
- if (TextUtils.equals(cur, previous)) {
- removeFromSuggestions(suggestions, i);
- i--;
- break;
- }
- }
- i++;
- }
- }
-
- private static void removeFromSuggestions(final ArrayList<CharSequence> suggestions,
- final int index) {
- final CharSequence garbage = suggestions.remove(index);
- if (garbage instanceof StringBuilder) {
- StringBuilderPool.recycle((StringBuilder)garbage);
- }
- }
-
- public static String getFullDisplayName(Locale locale, boolean returnsNameInThisLocale) {
- if (returnsNameInThisLocale) {
- return toTitleCase(SubtypeLocale.getFullDisplayName(locale), locale);
- } else {
- return toTitleCase(locale.getDisplayName(), locale);
- }
- }
-
- public static String getDisplayLanguage(Locale locale) {
- return toTitleCase(SubtypeLocale.getFullDisplayName(locale), locale);
- }
-
- public static String getMiddleDisplayLanguage(Locale locale) {
- return toTitleCase((LocaleUtils.constructLocaleFromString(
- locale.getLanguage()).getDisplayLanguage(locale)), locale);
- }
-
- public static String getShortDisplayLanguage(Locale locale) {
- return toTitleCase(locale.getLanguage(), locale);
- }
-
- public static String toTitleCase(String s, Locale locale) {
- if (s.length() <= 1) {
- // TODO: is this really correct? Shouldn't this be s.toUpperCase()?
- return s;
- }
- // 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, which
- // are two different characters but both should be capitalized as "IJ" as if they were
- // a single letter.
- // - It also does not work with unicode surrogate code points.
- return s.toUpperCase(locale).charAt(0) + s.substring(1);
- }
-
public static class Stats {
public static void onNonSeparator(final char code, final int x,
final int y) {
@@ -845,9 +454,4 @@ public class Utils {
LatinImeLogger.logOnAutoCorrectionCancelled();
}
}
-
- public static int codePointCount(String text) {
- if (TextUtils.isEmpty(text)) return 0;
- return text.codePointCount(0, text.length());
- }
}
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java
index 755c75b2e..35a5c0f52 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java
@@ -37,9 +37,9 @@ import com.android.inputmethod.latin.DictionaryFactory;
import com.android.inputmethod.latin.Flag;
import com.android.inputmethod.latin.LocaleUtils;
import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.StringUtils;
import com.android.inputmethod.latin.SynchronouslyLoadedContactsDictionary;
import com.android.inputmethod.latin.SynchronouslyLoadedUserDictionary;
-import com.android.inputmethod.latin.Utils;
import com.android.inputmethod.latin.WhitelistDictionary;
import com.android.inputmethod.latin.WordComposer;
@@ -47,11 +47,11 @@ import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
-import java.util.HashSet;
/**
* Service for spell checking, using LatinIME's dictionaries and mechanisms.
@@ -316,7 +316,7 @@ public class AndroidSpellCheckerService extends SpellCheckerService
}
}
Collections.reverse(mSuggestions);
- Utils.removeDupes(mSuggestions);
+ StringUtils.removeDupes(mSuggestions);
if (CAPITALIZE_ALL == capitalizeType) {
for (int i = 0; i < mSuggestions.size(); ++i) {
// get(i) returns a CharSequence which is actually a String so .toString()
@@ -326,7 +326,7 @@ public class AndroidSpellCheckerService extends SpellCheckerService
} else if (CAPITALIZE_FIRST == capitalizeType) {
for (int i = 0; i < mSuggestions.size(); ++i) {
// Likewise
- mSuggestions.set(i, Utils.toTitleCase(mSuggestions.get(i).toString(),
+ mSuggestions.set(i, StringUtils.toTitleCase(mSuggestions.get(i).toString(),
locale));
}
}
@@ -396,7 +396,7 @@ public class AndroidSpellCheckerService extends SpellCheckerService
final ProximityInfo proximityInfo = ProximityInfo.createSpellCheckerProximityInfo(
SpellCheckerProximityInfo.getProximityForScript(script));
final Resources resources = getResources();
- final int fallbackResourceId = Utils.getMainDictionaryResourceId(resources);
+ final int fallbackResourceId = DictionaryFactory.getMainDictionaryResourceId(resources);
final DictionaryCollection dictionaryCollection =
DictionaryFactory.createDictionaryFromManager(this, locale, fallbackResourceId,
USE_FULL_EDIT_DISTANCE_FLAG_ARRAY);
diff --git a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java
index 1f7214777..f11b1a4c1 100644
--- a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java
+++ b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java
@@ -147,32 +147,22 @@ public class MoreSuggestionsView extends KeyboardView implements MoreKeysPanel {
mListener = listener;
final View container = (View)getParent();
final MoreSuggestions pane = (MoreSuggestions)getKeyboard();
-
- parentView.getLocationInWindow(mCoordinates);
- final int paneLeft = pointX - (pane.mOccupiedWidth / 2) + parentView.getPaddingLeft();
- final int x = wrapUp(Math.max(0, Math.min(paneLeft,
- parentView.getWidth() - pane.mOccupiedWidth))
- - container.getPaddingLeft() + mCoordinates[0],
- container.getMeasuredWidth(), 0, parentView.getWidth());
- final int y = pointY
- - (container.getMeasuredHeight() - container.getPaddingBottom())
- + parentView.getPaddingTop() + mCoordinates[1];
+ final int defaultCoordX = pane.mOccupiedWidth / 2;
+ // The coordinates of panel's left-top corner in parentView's coordinate system.
+ final int x = pointX - defaultCoordX - container.getPaddingLeft()
+ + parentView.getPaddingLeft();
+ final int y = pointY - container.getMeasuredHeight() + container.getPaddingBottom()
+ + parentView.getPaddingTop();
window.setContentView(container);
window.setWidth(container.getMeasuredWidth());
window.setHeight(container.getMeasuredHeight());
- window.showAtLocation(parentView, Gravity.NO_GRAVITY, x, y);
-
- mOriginX = x + container.getPaddingLeft() - mCoordinates[0];
- mOriginY = y + container.getPaddingTop() - mCoordinates[1];
- }
+ parentView.getLocationInWindow(mCoordinates);
+ window.showAtLocation(parentView, Gravity.NO_GRAVITY,
+ x + mCoordinates[0], y + mCoordinates[1]);
- private static int wrapUp(int x, int width, int left, int right) {
- if (x < left)
- return left;
- if (x + width > right)
- return right - width;
- return x;
+ mOriginX = x + container.getPaddingLeft();
+ mOriginY = y + container.getPaddingTop();
}
private boolean mIsDismissing;