diff options
Diffstat (limited to 'java/src')
9 files changed, 369 insertions, 244 deletions
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java index 51e878c88..cd57db360 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java @@ -74,9 +74,9 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha private int mMode = KeyboardId.MODE_TEXT; /* default value */ private int mImeOptions; private boolean mIsSymbols; - /** mIsAutoCompletionActive indicates that auto completed word will be input instead of + /** mIsAutoCorrectionActive indicates that auto corrected word will be input instead of * what user actually typed. */ - private boolean mIsAutoCompletionActive; + private boolean mIsAutoCorrectionActive; private boolean mVoiceKeyEnabled; private boolean mVoiceButtonOnPrimary; private int mSymbolsModeState = SYMBOLS_MODE_STATE_NONE; @@ -197,7 +197,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha Log.d(TAG, "keyboard cache size=" + mKeyboardCache.size() + ": HIT id=" + id); } - keyboard.onAutoCompletionStateChanged(mIsAutoCompletionActive); + keyboard.onAutoCorrectionStateChanged(mIsAutoCorrectionActive); keyboard.setShifted(false); return keyboard; } @@ -617,12 +617,12 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha ? mInputView.getColorScheme() : KeyboardView.COLOR_SCHEME_WHITE; } - public void onAutoCompletionStateChanged(boolean isAutoCompletion) { - if (isAutoCompletion != mIsAutoCompletionActive) { + public void onAutoCorrectionStateChanged(boolean isAutoCorrection) { + if (isAutoCorrection != mIsAutoCorrectionActive) { LatinKeyboardView keyboardView = getInputView(); - mIsAutoCompletionActive = isAutoCompletion; + mIsAutoCorrectionActive = isAutoCorrection; keyboardView.invalidateKey(((LatinKeyboard) keyboardView.getKeyboard()) - .onAutoCompletionStateChanged(isAutoCompletion)); + .onAutoCorrectionStateChanged(isAutoCorrection)); } } diff --git a/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java b/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java index 8087f030e..0a42857ff 100644 --- a/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java +++ b/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java @@ -45,7 +45,7 @@ public class LatinKeyboard extends Keyboard { private static final int SPACE_LED_LENGTH_PERCENT = 80; private Drawable mShiftLockPreviewIcon; - private Drawable mSpaceAutoCompletionIndicator; + private Drawable mSpaceAutoCorrectionIndicator; private final Drawable mButtonArrowLeftIcon; private final Drawable mButtonArrowRightIcon; private final int mSpaceBarTextShadowColor; @@ -89,7 +89,7 @@ public class LatinKeyboard extends Keyboard { } mShiftLockPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_shift_locked); setDefaultBounds(mShiftLockPreviewIcon); - mSpaceAutoCompletionIndicator = res.getDrawable(R.drawable.sym_keyboard_space_led); + mSpaceAutoCorrectionIndicator = res.getDrawable(R.drawable.sym_keyboard_space_led); mButtonArrowLeftIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_left); mButtonArrowRightIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_right); sSpacebarVerticalCorrection = res.getDimensionPixelOffset( @@ -100,22 +100,22 @@ public class LatinKeyboard extends Keyboard { /** * @return a key which should be invalidated. */ - public Key onAutoCompletionStateChanged(boolean isAutoCompletion) { - updateSpaceBarForLocale(isAutoCompletion); + public Key onAutoCorrectionStateChanged(boolean isAutoCorrection) { + updateSpaceBarForLocale(isAutoCorrection); return mSpaceKey; } - private void updateSpaceBarForLocale(boolean isAutoCompletion) { + private void updateSpaceBarForLocale(boolean isAutoCorrection) { final Resources res = mRes; // If application locales are explicitly selected. if (SubtypeSwitcher.getInstance().needsToDisplayLanguage()) { mSpaceKey.setIcon(new BitmapDrawable(res, - drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCompletion))); + drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCorrection))); } else { // sym_keyboard_space_led can be shared with Black and White symbol themes. - if (isAutoCompletion) { + if (isAutoCorrection) { mSpaceKey.setIcon(new BitmapDrawable(res, - drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCompletion))); + drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCorrection))); } else { mSpaceKey.setIcon(mSpaceIcon); } @@ -173,7 +173,7 @@ public class LatinKeyboard extends Keyboard { } @SuppressWarnings("unused") - private Bitmap drawSpaceBar(int opacity, boolean isAutoCompletion) { + private Bitmap drawSpaceBar(int opacity, boolean isAutoCorrection) { final int width = mSpaceKey.mWidth; final int height = mSpaceIcon.getIntrinsicHeight(); final Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); @@ -212,13 +212,13 @@ public class LatinKeyboard extends Keyboard { } // Draw the spacebar icon at the bottom - if (isAutoCompletion) { + if (isAutoCorrection) { final int iconWidth = width * SPACE_LED_LENGTH_PERCENT / 100; - final int iconHeight = mSpaceAutoCompletionIndicator.getIntrinsicHeight(); + final int iconHeight = mSpaceAutoCorrectionIndicator.getIntrinsicHeight(); int x = (width - iconWidth) / 2; int y = height - iconHeight; - mSpaceAutoCompletionIndicator.setBounds(x, y, x + iconWidth, y + iconHeight); - mSpaceAutoCompletionIndicator.draw(canvas); + mSpaceAutoCorrectionIndicator.setBounds(x, y, x + iconWidth, y + iconHeight); + mSpaceAutoCorrectionIndicator.draw(canvas); } else { final int iconWidth = mSpaceIcon.getIntrinsicWidth(); final int iconHeight = mSpaceIcon.getIntrinsicHeight(); diff --git a/java/src/com/android/inputmethod/latin/CandidateView.java b/java/src/com/android/inputmethod/latin/CandidateView.java index 03ba1192b..784077a76 100644 --- a/java/src/com/android/inputmethod/latin/CandidateView.java +++ b/java/src/com/android/inputmethod/latin/CandidateView.java @@ -43,11 +43,9 @@ import android.widget.PopupWindow; import android.widget.TextView; import java.util.ArrayList; -import java.util.List; public class CandidateView extends LinearLayout implements OnClickListener, OnLongClickListener { private LatinIME mService; - private final ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>(); private final ArrayList<View> mWords = new ArrayList<View>(); private final TextView mPreviewText; @@ -64,27 +62,12 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo private final CharacterStyle mInvertedForegroundColorSpan; private final CharacterStyle mInvertedBackgroundColorSpan; - private boolean mShowingCompletions; + private SuggestedWords mSuggestions = SuggestedWords.EMPTY; private boolean mShowingAutoCorrectionInverted; - private boolean mShowingAddToDictionary; private final UiHandler mHandler = new UiHandler(); - private static class UpdateSuggestionsArgs { - public final List<CharSequence> mSuggestions; - public final boolean mCompletions; - public final boolean mTypedWordValid; - public final boolean mHaveMinimalSuggestion; - public UpdateSuggestionsArgs(List<CharSequence> suggestions, boolean completions, - boolean typedWordValid, boolean haveMinimalSuggestion) { - mSuggestions = suggestions; - mCompletions = completions; - mTypedWordValid = typedWordValid; - mHaveMinimalSuggestion = haveMinimalSuggestion; - } - } - private class UiHandler extends Handler { private static final int MSG_HIDE_PREVIEW = 0; private static final int MSG_UPDATE_SUGGESTION = 1; @@ -99,9 +82,7 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo hidePreview(); break; case MSG_UPDATE_SUGGESTION: - UpdateSuggestionsArgs args = (UpdateSuggestionsArgs)msg.obj; - updateSuggestions(args.mSuggestions, args.mCompletions, args.mTypedWordValid, - args.mHaveMinimalSuggestion); + updateSuggestions((SuggestedWords)msg.obj); break; } } @@ -115,11 +96,9 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo removeMessages(MSG_HIDE_PREVIEW); } - public void postUpdateSuggestions(List<CharSequence> suggestions, boolean completions, - boolean typedWordValid, boolean haveMinimalSuggestion) { + public void postUpdateSuggestions(SuggestedWords suggestions) { cancelUpdateSuggestions(); - sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION, new UpdateSuggestionsArgs( - suggestions, completions, typedWordValid, haveMinimalSuggestion)), + sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION, suggestions), DELAY_UPDATE_SUGGESTION); } @@ -167,7 +146,7 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo tv.setOnLongClickListener(this); ImageView divider = (ImageView)v.findViewById(R.id.candidate_divider); // Do not display divider of first candidate. - divider.setVisibility(i == 0 ? View.GONE : View.VISIBLE); + divider.setVisibility(i == 0 ? GONE : VISIBLE); mWords.add(v); } @@ -182,44 +161,35 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo mService = listener; } - public void setSuggestions(List<CharSequence> suggestions, boolean completions, - boolean typedWordValid, boolean haveMinimalSuggestion) { - // Don't update suggestions when there is zero or only one suggestion found. - if (suggestions != null && suggestions.size() <= 1) + public void setSuggestions(SuggestedWords suggestions) { + // Don't update suggestions when there is only one suggestion found. + // Empty (size zero) suggestions will be passed in order to clear candidate view. + if (suggestions == null || suggestions.size() == 1) return; if (mShowingAutoCorrectionInverted) { - mHandler.postUpdateSuggestions(suggestions, completions, typedWordValid, - haveMinimalSuggestion); + mHandler.postUpdateSuggestions(suggestions); } else { - updateSuggestions(suggestions, completions, typedWordValid, haveMinimalSuggestion); + updateSuggestions(suggestions); } } - private void updateSuggestions(List<CharSequence> suggestions, boolean completions, - boolean typedWordValid, boolean haveMinimalSuggestion) { + private void updateSuggestions(SuggestedWords suggestions) { clear(); - if (suggestions != null) { - int insertCount = Math.min(suggestions.size(), MAX_SUGGESTIONS); - for (CharSequence suggestion : suggestions) { - mSuggestions.add(suggestion); - if (--insertCount == 0) - break; - } - } - - final int count = mSuggestions.size(); - boolean existsAutoCompletion = false; - + mSuggestions = suggestions; + final int count = suggestions.size(); + final Object[] debugInfo = suggestions.mDebugInfo; for (int i = 0; i < count; i++) { - CharSequence suggestion = mSuggestions.get(i); - if (suggestion == null) continue; - final int wordLength = suggestion.length(); + CharSequence word = suggestions.getWord(i); + if (word == null) continue; + final int wordLength = word.length(); final View v = mWords.get(i); final TextView tv = (TextView)v.findViewById(R.id.candidate_word); + final TextView dv = (TextView)v.findViewById(R.id.candidate_debug_info); tv.setTextColor(mColorNormal); - if (haveMinimalSuggestion - && ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) { + if (suggestions.mHasMinimalSuggestion + && ((i == 1 && !suggestions.mTypedWordValid) || + (i == 0 && suggestions.mTypedWordValid))) { final CharacterStyle style; if (mConfigCandidateHighlightFontColorEnabled) { style = BOLD_SPAN; @@ -227,10 +197,9 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo } else { style = UNDERLINE_SPAN; } - final Spannable word = new SpannableString(suggestion); - word.setSpan(style, 0, wordLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - suggestion = word; - existsAutoCompletion = true; + final Spannable spannedWord = new SpannableString(word); + spannedWord.setSpan(style, 0, wordLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + word = spannedWord; } else if (i != 0 || (wordLength == 1 && count > 1)) { // HACK: even if i == 0, we use mColorOther when this // suggestion's length is 1 @@ -239,16 +208,18 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo if (mConfigCandidateHighlightFontColorEnabled) tv.setTextColor(mColorOther); } - tv.setText(suggestion); + tv.setText(word); tv.setClickable(true); + if (debugInfo != null && i < debugInfo.length && debugInfo[i] != null + && !TextUtils.isEmpty(debugInfo[i].toString())) { + dv.setText(debugInfo[i].toString()); + dv.setVisibility(VISIBLE); + } else { + dv.setVisibility(GONE); + } addView(v); } - mShowingCompletions = completions; - // TODO: Move this call back to LatinIME - if (mConfigCandidateHighlightFontColorEnabled) - mService.onAutoCompletionStateChanged(existsAutoCompletion); - scrollTo(0, getScrollY()); requestLayout(); } @@ -267,15 +238,19 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo mShowingAutoCorrectionInverted = true; } + public boolean isConfigCandidateHighlightFontColorEnabled() { + return mConfigCandidateHighlightFontColorEnabled; + } + public boolean isShowingAddToDictionaryHint() { return mShowingAddToDictionary; } public void showAddToDictionaryHint(CharSequence word) { - ArrayList<CharSequence> suggestions = new ArrayList<CharSequence>(); - suggestions.add(word); - suggestions.add(getContext().getText(R.string.hint_add_to_dictionary)); - setSuggestions(suggestions, false, false, false); + SuggestedWords.Builder builder = new SuggestedWords.Builder() + .addWord(word) + .addWord(getContext().getText(R.string.hint_add_to_dictionary)); + setSuggestions(builder.build()); mShowingAddToDictionary = true; // Disable R.string.hint_add_to_dictionary button TextView tv = (TextView)getChildAt(1).findViewById(R.id.candidate_word); @@ -288,14 +263,11 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo return true; } - /* package */ List<CharSequence> getSuggestions() { + public SuggestedWords getSuggestions() { return mSuggestions; } public void clear() { - // Don't call mSuggestions.clear() because it's being used for logging - // in LatinIME.pickSuggestionManually(). - mSuggestions.clear(); mShowingAddToDictionary = false; mShowingAutoCorrectionInverted = false; removeAllViews(); @@ -337,7 +309,7 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo @Override public boolean onLongClick(View view) { int index = (Integer) view.getTag(); - CharSequence word = mSuggestions.get(index); + CharSequence word = mSuggestions.getWord(index); if (word.length() < 2) return false; addToDictionary(word); @@ -347,12 +319,12 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo @Override public void onClick(View view) { int index = (Integer) view.getTag(); - CharSequence word = mSuggestions.get(index); + CharSequence word = mSuggestions.getWord(index); if (mShowingAddToDictionary && index == 0) { addToDictionary(word); } else { - if (!mShowingCompletions) { - TextEntryState.acceptedSuggestion(mSuggestions.get(0), word); + if (!mSuggestions.mIsApplicationSpecifiedCompletions) { + TextEntryState.acceptedSuggestion(mSuggestions.getWord(0), word); } mService.pickSuggestionManually(index, word); } diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index 99b6c739a..243306a35 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -63,6 +63,7 @@ import android.view.ViewParent; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; +import android.view.inputmethod.CorrectionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; @@ -77,7 +78,6 @@ import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import java.util.Locale; /** @@ -120,7 +120,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private View mCandidateViewContainer; private CandidateView mCandidateView; private Suggest mSuggest; - private CompletionInfo[] mCompletions; + private CompletionInfo[] mApplicationSpecifiedCompletions; private AlertDialog mOptionsDialog; @@ -142,7 +142,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private CharSequence mBestWord; private boolean mPredicting; private boolean mPredictionOn; - private boolean mCompletionOn; + private boolean mApplicationSpecifiedCompletionOn; private boolean mHasDictionary; private boolean mAutoSpace; private boolean mJustAddedAutoSpace; @@ -162,7 +162,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // Keep track of the last selection range to decide if we need to show word alternatives private int mLastSelectionStart; private int mLastSelectionEnd; - private List<CharSequence> mSuggestPuncList; + private SuggestedWords mSuggestPuncList; // Input type is such that we should not auto-correct private boolean mInputTypeNoAutoCorrect; @@ -212,7 +212,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen return mChosenWord; } - public abstract List<CharSequence> getAlternatives(); + public abstract SuggestedWords.Builder getAlternatives(); } public class TypedWordAlternatives extends WordAlternatives { @@ -233,7 +233,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } @Override - public List<CharSequence> getAlternatives() { + public SuggestedWords.Builder getAlternatives() { return getTypedSuggestions(word); } } @@ -394,7 +394,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen int[] dictionaries = getDictionary(orig); mSuggest = new Suggest(this, dictionaries); - loadAndSetAutoCompletionThreshold(prefs); + loadAndSetAutoCorrectionThreshold(prefs); if (mUserDictionary != null) mUserDictionary.close(); mUserDictionary = new UserDictionary(this, locale); if (mContactsDictionary == null) { @@ -520,8 +520,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mVoiceConnector.resetVoiceStates(isPasswordVariation(variation)); mInputTypeNoAutoCorrect = false; mPredictionOn = false; - mCompletionOn = false; - mCompletions = null; + mApplicationSpecifiedCompletionOn = false; + mApplicationSpecifiedCompletions = null; mEnteredText = null; final int mode; @@ -580,7 +580,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } if ((attribute.inputType & InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { mPredictionOn = false; - mCompletionOn = isFullscreenMode(); + mApplicationSpecifiedCompletionOn = isFullscreenMode(); } break; default: @@ -603,7 +603,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen setCandidatesViewShownInternal(isCandidateStripVisible(), false /* needsInputViewShown */ ); - updateSuggestions(); + // Delay updating suggestions because keyboard input view may not be shown at this point. + mHandler.postUpdateSuggestions(); // If the dictionary is not big enough, don't auto correct mHasDictionary = mSuggest.hasMainDictionary(); @@ -633,7 +634,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (isSuggestionShown() && isPredictionOn()) { // First get the cursor position. This is required by setOldSuggestions(), so that // it can pass the correct range to setComposingRegion(). At this point, we don't - // have valid values for mLastSelectionStart/Stop because onUpdateSelection() has + // have valid values for mLastSelectionStart/End because onUpdateSelection() has // not been called yet. ExtractedTextRequest etr = new ExtractedTextRequest(); etr.token = 0; // anything is fine here @@ -655,7 +656,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen super.onFinishInput(); LatinImeLogger.commit(); - onAutoCompletionStateChanged(false); + mKeyboardSwitcher.onAutoCorrectionStateChanged(false); mVoiceConnector.flushVoiceInputLogs(mConfigurationChanging); @@ -790,7 +791,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen @Override public void hideWindow() { LatinImeLogger.commit(); - onAutoCompletionStateChanged(false); + mKeyboardSwitcher.onAutoCorrectionStateChanged(false); if (TRACE) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { @@ -804,27 +805,28 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } @Override - public void onDisplayCompletions(CompletionInfo[] completions) { + public void onDisplayCompletions(CompletionInfo[] applicationSpecifiedCompletions) { if (DEBUG) { Log.i("foo", "Received completions:"); - for (int i=0; i<(completions != null ? completions.length : 0); i++) { - Log.i("foo", " #" + i + ": " + completions[i]); + final int count = (applicationSpecifiedCompletions != null) + ? applicationSpecifiedCompletions.length : 0; + for (int i = 0; i < count; i++) { + Log.i("foo", " #" + i + ": " + applicationSpecifiedCompletions[i]); } } - if (mCompletionOn) { - mCompletions = completions; - if (completions == null) { + if (mApplicationSpecifiedCompletionOn) { + mApplicationSpecifiedCompletions = applicationSpecifiedCompletions; + if (applicationSpecifiedCompletions == null) { clearSuggestions(); return; } - List<CharSequence> stringList = new ArrayList<CharSequence>(); - for (int i = 0; i < completions.length; i++) { - CompletionInfo ci = completions[i]; - if (ci != null) stringList.add(ci.getText()); - } + SuggestedWords.Builder builder = new SuggestedWords.Builder() + .setApplicationSpecifiedCompletions(applicationSpecifiedCompletions) + .setTypedWordValid(true) + .setHasMinimalSuggestion(true); // When in fullscreen mode, show completions generated by the application - setSuggestions(stringList, true, true, true); + setSuggestions(builder.build()); mBestWord = null; setCandidatesViewShown(true); } @@ -1293,7 +1295,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen boolean pickedDefault = false; // Handle separator - InputConnection ic = getCurrentInputConnection(); + final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); abortCorrection(false); @@ -1338,7 +1340,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen CharSequence typedWord = mWord.getTypedWord(); TextEntryState.backToAcceptedDefault(typedWord); if (!TextUtils.isEmpty(typedWord) && !typedWord.equals(mBestWord)) { - // TODO: Will call InputConnection.commitCorrection() here. + if (ic != null) { + CorrectionInfo correctionInfo = new CorrectionInfo( + mLastSelectionEnd - typedWord.length(), typedWord, mBestWord); + ic.commitCorrection(correctionInfo); + } if (mCandidateView != null) mCandidateView.onAutoCorrectionInverted(mBestWord); } @@ -1382,7 +1388,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } private boolean isShowingPunctuationList() { - return mSuggestPuncList.equals(mCandidateView.getSuggestions()); + return mSuggestPuncList == mCandidateView.getSuggestions(); } private boolean isSuggestionShown() { @@ -1394,8 +1400,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private boolean isCandidateStripVisible() { boolean forceVisible = mCandidateView.isShowingAddToDictionaryHint() || TextEntryState.isCorrecting(); - return forceVisible || (isSuggestionShown() - && (isPredictionOn() || mCompletionOn || isShowingPunctuationList())); + return forceVisible || ( + isSuggestionShown() && (isPredictionOn() || mApplicationSpecifiedCompletionOn + || isShowingPunctuationList())); } public void switchToKeyboardView() { @@ -1422,22 +1429,20 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } public void clearSuggestions() { - setSuggestions(null, false, false, false); + setSuggestions(SuggestedWords.EMPTY); } - public void setSuggestions( - List<CharSequence> suggestions, - boolean completions, - boolean typedWordValid, - boolean haveMinimalSuggestion) { - + public void setSuggestions(SuggestedWords words) { if (mVoiceConnector.getAndResetIsShowingHint()) { setCandidatesView(mCandidateViewContainer); } if (mCandidateView != null) { - mCandidateView.setSuggestions( - suggestions, completions, typedWordValid, haveMinimalSuggestion); + mCandidateView.setSuggestions(words); + if (mCandidateView.isConfigCandidateHighlightFontColorEnabled()) { + mKeyboardSwitcher.onAutoCorrectionStateChanged( + words.hasWordAboveAutoCorrectionScoreThreshold()); + } } } @@ -1457,16 +1462,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen showSuggestions(mWord); } - private List<CharSequence> getTypedSuggestions(WordComposer word) { - List<CharSequence> stringList = mSuggest.getSuggestions( - mKeyboardSwitcher.getInputView(), word, false, null); - return stringList; + private SuggestedWords.Builder getTypedSuggestions(WordComposer word) { + return mSuggest.getSuggestedWordBuilder(mKeyboardSwitcher.getInputView(), word, null); } private void showCorrections(WordAlternatives alternatives) { mKeyboardSwitcher.setPreferredLetters(null); - List<CharSequence> stringList = alternatives.getAlternatives(); - showSuggestions(stringList, alternatives.getOriginalWord(), false, false); + SuggestedWords.Builder builder = alternatives.getAlternatives(); + builder.setTypedWordValid(false).setHasMinimalSuggestion(false); + showSuggestions(builder.build(), alternatives.getOriginalWord()); } private void showSuggestions(WordComposer word) { @@ -1474,10 +1478,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // TODO Maybe need better way of retrieving previous word CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(), mWordSeparators); - List<CharSequence> stringList = mSuggest.getSuggestions( - mKeyboardSwitcher.getInputView(), word, false, prevWord); - // long stopTime = System.currentTimeMillis(); // TIME MEASUREMENT! - // Log.d("LatinIME","Suggest Total Time - " + (stopTime - startTime)); + SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder( + mKeyboardSwitcher.getInputView(), word, prevWord); int[] nextLettersFrequencies = mSuggest.getNextLettersFrequencies(); mKeyboardSwitcher.setPreferredLetters(nextLettersFrequencies); @@ -1497,15 +1499,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen correctionAvailable &= !word.isMostlyCaps(); correctionAvailable &= !TextEntryState.isCorrecting(); - showSuggestions(stringList, typedWord, typedWordValid, correctionAvailable); + builder.setTypedWordValid(typedWordValid).setHasMinimalSuggestion(correctionAvailable); + showSuggestions(builder.build(), typedWord); } - private void showSuggestions(List<CharSequence> stringList, CharSequence typedWord, - boolean typedWordValid, boolean correctionAvailable) { - setSuggestions(stringList, false, typedWordValid, correctionAvailable); - if (stringList.size() > 0) { - if (correctionAvailable && !typedWordValid && stringList.size() > 1) { - mBestWord = stringList.get(1); + private void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) { + setSuggestions(suggestedWords); + if (suggestedWords.size() > 0) { + if (suggestedWords.hasAutoCorrectionWord()) { + mBestWord = suggestedWords.getWord(1); } else { mBestWord = typedWord; } @@ -1534,7 +1536,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } public void pickSuggestionManually(int index, CharSequence suggestion) { - List<CharSequence> suggestions = mCandidateView.getSuggestions(); + SuggestedWords suggestions = mCandidateView.getSuggestions(); mVoiceConnector.flushAndLogAllTextModificationCounters(index, suggestion, mWordSeparators); final boolean correcting = TextEntryState.isCorrecting(); @@ -1542,9 +1544,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (ic != null) { ic.beginBatchEdit(); } - if (mCompletionOn && mCompletions != null && index >= 0 - && index < mCompletions.length) { - CompletionInfo ci = mCompletions[index]; + if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null + && index >= 0 && index < mApplicationSpecifiedCompletions.length) { + CompletionInfo ci = mApplicationSpecifiedCompletions[index]; if (ic != null) { ic.commitCompletion(ci); } @@ -1565,7 +1567,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( - "", suggestion.toString(), index, suggestions); + "", suggestion.toString(), index, suggestions.mWords); final char primaryCode = suggestion.charAt(0); onKey(primaryCode, new int[]{primaryCode}, KeyboardView.NOT_A_TOUCH_COORDINATE, KeyboardView.NOT_A_TOUCH_COORDINATE); @@ -1583,7 +1585,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen addToBigramDictionary(suggestion, 1); } LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(), - index, suggestions); + index, suggestions.mWords); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mAutoSpace && !correcting) { @@ -1655,7 +1657,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen break; } } - // If we didn't find a match, at least suggest completions + // If we didn't find a match, at least suggest corrections. if (foundWord == null && (mSuggest.isValidWord(touching.mWord) || mSuggest.isValidWord(touching.mWord.toString().toLowerCase()))) { @@ -1718,7 +1720,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private void setPunctuationSuggestions() { setCandidatesViewShown(isCandidateStripVisible()); - setSuggestions(mSuggestPuncList, false, false, false); + setSuggestions(mSuggestPuncList); } private void addToDictionaries(CharSequence suggestion, int frequencyDelta) { @@ -2043,7 +2045,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mAutoCorrectEnabled = isAutoCorrectEnabled(prefs); mBigramSuggestionEnabled = mAutoCorrectEnabled && isBigramSuggestionEnabled(prefs); - loadAndSetAutoCompletionThreshold(prefs); + loadAndSetAutoCorrectionThreshold(prefs); mVoiceConnector.loadSettings(attribute, prefs); @@ -2054,50 +2056,47 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } /** - * load Auto completion threshold from SharedPreferences, - * and modify mSuggest's threshold. + * Load Auto correction threshold from SharedPreferences, and modify mSuggest's threshold. */ - private void loadAndSetAutoCompletionThreshold(SharedPreferences sp) { + private void loadAndSetAutoCorrectionThreshold(SharedPreferences sp) { // When mSuggest is not initialized, cannnot modify mSuggest's threshold. if (mSuggest == null) return; - // When auto completion setting is turned off, the threshold is ignored. + // When auto correction setting is turned off, the threshold is ignored. if (!isAutoCorrectEnabled(sp)) return; - final String currentAutoCompletionSetting = sp.getString( - Settings.PREF_AUTO_COMPLETION_THRESHOLD, - mResources.getString(R.string.auto_completion_threshold_mode_value_modest)); - final String[] autoCompletionThresholdValues = mResources.getStringArray( - R.array.auto_complete_threshold_values); - // When autoCompletionThreshold is greater than 1.0, - // auto completion is virtually turned off. - double autoCompletionThreshold = Double.MAX_VALUE; + final String currentAutoCorrectionSetting = sp.getString( + Settings.PREF_AUTO_CORRECTION_THRESHOLD, + mResources.getString(R.string.auto_correction_threshold_mode_index_modest)); + final String[] autoCorrectionThresholdValues = mResources.getStringArray( + R.array.auto_correction_threshold_values); + // When autoCrrectionThreshold is greater than 1.0, auto correction is virtually turned off. + double autoCorrectionThreshold = Double.MAX_VALUE; try { - final int arrayIndex = Integer.valueOf(currentAutoCompletionSetting); - if (arrayIndex >= 0 && arrayIndex < autoCompletionThresholdValues.length) { - autoCompletionThreshold = Double.parseDouble( - autoCompletionThresholdValues[arrayIndex]); + final int arrayIndex = Integer.valueOf(currentAutoCorrectionSetting); + if (arrayIndex >= 0 && arrayIndex < autoCorrectionThresholdValues.length) { + autoCorrectionThreshold = Double.parseDouble( + autoCorrectionThresholdValues[arrayIndex]); } } catch (NumberFormatException e) { - // Whenever the threshold settings are correct, - // never come here. - autoCompletionThreshold = Double.MAX_VALUE; - Log.w(TAG, "Cannot load auto completion threshold setting." - + " currentAutoCompletionSetting: " + currentAutoCompletionSetting - + ", autoCompletionThresholdValues: " - + Arrays.toString(autoCompletionThresholdValues)); + // Whenever the threshold settings are correct, never come here. + autoCorrectionThreshold = Double.MAX_VALUE; + Log.w(TAG, "Cannot load auto correction threshold setting." + + " currentAutoCorrectionSetting: " + currentAutoCorrectionSetting + + ", autoCorrectionThresholdValues: " + + Arrays.toString(autoCorrectionThresholdValues)); } // TODO: This should be refactored : - // setAutoCompleteThreshold should be called outside of this method. - mSuggest.setAutoCompleteThreshold(autoCompletionThreshold); + // setAutoCorrectionThreshold should be called outside of this method. + mSuggest.setAutoCorrectionThreshold(autoCorrectionThreshold); } private boolean isAutoCorrectEnabled(SharedPreferences sp) { - final String currentAutoCompletionSetting = sp.getString( - Settings.PREF_AUTO_COMPLETION_THRESHOLD, - mResources.getString(R.string.auto_completion_threshold_mode_value_modest)); - final String autoCompletionOff = mResources.getString( - R.string.auto_completion_threshold_mode_value_off); - return !currentAutoCompletionSetting.equals(autoCompletionOff); + final String currentAutoCorrectionSetting = sp.getString( + Settings.PREF_AUTO_CORRECTION_THRESHOLD, + mResources.getString(R.string.auto_correction_threshold_mode_index_modest)); + final String autoCorrectionOff = mResources.getString( + R.string.auto_correction_threshold_mode_index_off); + return !currentAutoCorrectionSetting.equals(autoCorrectionOff); } private boolean isBigramSuggestionEnabled(SharedPreferences sp) { @@ -2106,13 +2105,17 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } private void initSuggestPuncList() { - mSuggestPuncList = new ArrayList<CharSequence>(); - mSuggestPuncs = mResources.getString(R.string.suggested_punctuations); - if (mSuggestPuncs != null) { - for (int i = 0; i < mSuggestPuncs.length(); i++) { - mSuggestPuncList.add(mSuggestPuncs.subSequence(i, i + 1)); + if (mSuggestPuncs != null || mSuggestPuncList != null) + return; + SuggestedWords.Builder builder = new SuggestedWords.Builder(); + String puncs = mResources.getString(R.string.suggested_punctuations); + if (puncs != null) { + for (int i = 0; i < puncs.length(); i++) { + builder.addWord(puncs.subSequence(i, i + 1)); } } + mSuggestPuncList = builder.build(); + mSuggestPuncs = puncs; } private boolean isSuggestedPunctuation(int code) { @@ -2167,7 +2170,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen p.println(" mPredicting=" + mPredicting); p.println(" mAutoCorrectOn=" + mAutoCorrectOn); p.println(" mAutoSpace=" + mAutoSpace); - p.println(" mCompletionOn=" + mCompletionOn); + p.println(" mApplicationSpecifiedCompletionOn=" + mApplicationSpecifiedCompletionOn); p.println(" TextEntryState.state=" + TextEntryState.getState()); p.println(" mSoundOn=" + mSoundOn); p.println(" mVibrateOn=" + mVibrateOn); @@ -2192,10 +2195,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total)); } - public void onAutoCompletionStateChanged(boolean isAutoCompletion) { - mKeyboardSwitcher.onAutoCompletionStateChanged(isAutoCompletion); - } - @Override public void onCurrentInputMethodSubtypeChanged(InputMethodSubtype subtype) { SubtypeSwitcher.getInstance().updateSubtype(subtype); diff --git a/java/src/com/android/inputmethod/latin/Settings.java b/java/src/com/android/inputmethod/latin/Settings.java index 9c7c5aa71..3f604a381 100644 --- a/java/src/com/android/inputmethod/latin/Settings.java +++ b/java/src/com/android/inputmethod/latin/Settings.java @@ -53,11 +53,12 @@ public class Settings extends PreferenceActivity public static final String PREF_VOICE_SETTINGS_KEY = "voice_mode"; public static final String PREF_INPUT_LANGUAGE = "input_language"; public static final String PREF_SELECTED_LANGUAGES = "selected_languages"; + public static final String PREF_SUBTYPES = "subtype_settings"; public static final String PREF_PREDICTION_SETTINGS_KEY = "prediction_settings"; public static final String PREF_QUICK_FIXES = "quick_fixes"; public static final String PREF_SHOW_SUGGESTIONS_SETTING = "show_suggestions_setting"; - public static final String PREF_AUTO_COMPLETION_THRESHOLD = "auto_completion_threshold"; + public static final String PREF_AUTO_CORRECTION_THRESHOLD = "auto_correction_threshold"; public static final String PREF_BIGRAM_SUGGESTIONS = "bigram_suggestion"; // Dialog ids @@ -66,7 +67,7 @@ public class Settings extends PreferenceActivity private CheckBoxPreference mQuickFixes; private ListPreference mVoicePreference; private ListPreference mSettingsKeyPreference; - private ListPreference mAutoCompletionThreshold; + private ListPreference mAutoCorrectionThreshold; private CheckBoxPreference mBigramSuggestion; private boolean mVoiceOn; @@ -77,11 +78,11 @@ public class Settings extends PreferenceActivity private boolean mOkClicked = false; private String mVoiceModeOff; - private void ensureConsistencyOfAutoCompletionSettings() { - final String autoCompletionOff = getResources().getString( - R.string.auto_completion_threshold_mode_value_off); - final String currentSetting = mAutoCompletionThreshold.getValue(); - mBigramSuggestion.setEnabled(!currentSetting.equals(autoCompletionOff)); + private void ensureConsistencyOfAutoCorrectionSettings() { + final String autoCorrectionOff = getResources().getString( + R.string.auto_correction_threshold_mode_index_off); + final String currentSetting = mAutoCorrectionThreshold.getValue(); + mBigramSuggestion.setEnabled(!currentSetting.equals(autoCorrectionOff)); } @Override protected void onCreate(Bundle icicle) { @@ -98,9 +99,9 @@ public class Settings extends PreferenceActivity .equals(mVoiceModeOff)); mLogger = VoiceInputLogger.getLogger(this); - mAutoCompletionThreshold = (ListPreference) findPreference(PREF_AUTO_COMPLETION_THRESHOLD); + mAutoCorrectionThreshold = (ListPreference) findPreference(PREF_AUTO_CORRECTION_THRESHOLD); mBigramSuggestion = (CheckBoxPreference) findPreference(PREF_BIGRAM_SUGGESTIONS); - ensureConsistencyOfAutoCompletionSettings(); + ensureConsistencyOfAutoCorrectionSettings(); final boolean showSettingsKeyOption = getResources().getBoolean( R.bool.config_enable_show_settings_key_option); @@ -119,6 +120,12 @@ public class Settings extends PreferenceActivity getPreferenceScreen().removePreference( getPreferenceScreen().findPreference(PREF_VIBRATE_ON)); } + + final boolean showSubtypeSettings = getResources().getBoolean( + R.bool.config_enable_show_subtype_settings); + if (!showSubtypeSettings) { + getPreferenceScreen().removePreference(findPreference(PREF_SUBTYPES)); + } } @Override @@ -155,7 +162,7 @@ public class Settings extends PreferenceActivity showVoiceConfirmation(); } } - ensureConsistencyOfAutoCompletionSettings(); + ensureConsistencyOfAutoCorrectionSettings(); mVoiceOn = !(prefs.getString(PREF_VOICE_SETTINGS_KEY, mVoiceModeOff) .equals(mVoiceModeOff)); updateVoiceModeSummary(); diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java index a6df187e6..a30ec1587 100644 --- a/java/src/com/android/inputmethod/latin/Suggest.java +++ b/java/src/com/android/inputmethod/latin/Suggest.java @@ -25,12 +25,10 @@ import android.view.View; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; -import java.util.List; /** * This class loads a dictionary and provides a list of suggestions for a given sequence of * characters. This includes corrections and completions. - * @hide pending API Council Approval */ public class Suggest implements Dictionary.WordCallback { @@ -83,7 +81,7 @@ public class Suggest implements Dictionary.WordCallback { private boolean mAutoTextEnabled; - private double mAutoCompleteThreshold; + private double mAutoCorrectionThreshold; private int[] mPriorities = new int[mPrefMaxSuggestions]; private int[] mBigramPriorities = new int[PREF_MAX_BIGRAMS]; @@ -97,7 +95,6 @@ public class Suggest implements Dictionary.WordCallback { ArrayList<CharSequence> mBigramSuggestions = new ArrayList<CharSequence>(); private ArrayList<CharSequence> mStringPool = new ArrayList<CharSequence>(); private boolean mHaveCorrection; - private CharSequence mOriginalWord; private String mLowerOriginalWord; // TODO: Remove these member variables by passing more context to addWord() callback method @@ -166,8 +163,8 @@ public class Suggest implements Dictionary.WordCallback { mUserBigramDictionary = userBigramDictionary; } - public void setAutoCompleteThreshold(double threshold) { - mAutoCompleteThreshold = threshold; + public void setAutoCorrectionThreshold(double threshold) { + mAutoCorrectionThreshold = threshold; } /** @@ -191,15 +188,21 @@ public class Suggest implements Dictionary.WordCallback { } /** - * Returns a list of words that match the list of character codes passed in. - * This list will be overwritten the next time this function is called. + * Returns a object which represents suggested words that match the list of character codes + * passed in. This object contents will be overwritten the next time this function is called. * @param view a view for retrieving the context for AutoText * @param wordComposer contains what is currently being typed * @param prevWordForBigram previous word (used only for bigram) - * @return list of suggestions. + * @return suggested words object. */ - public List<CharSequence> getSuggestions(View view, WordComposer wordComposer, - boolean includeTypedWordIfValid, CharSequence prevWordForBigram) { + public SuggestedWords getSuggestions(View view, WordComposer wordComposer, + CharSequence prevWordForBigram) { + return getSuggestedWordBuilder(view, wordComposer, prevWordForBigram).build(); + } + + // TODO: cleanup dictionaries looking up and suggestions building with SuggestedWords.Builder + public SuggestedWords.Builder getSuggestedWordBuilder(View view, WordComposer wordComposer, + CharSequence prevWordForBigram) { LatinImeLogger.onStartSuggestion(prevWordForBigram); mHaveCorrection = false; mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized(); @@ -209,13 +212,13 @@ public class Suggest implements Dictionary.WordCallback { Arrays.fill(mNextLettersFrequencies, 0); // Save a lowercase version of the original word - mOriginalWord = wordComposer.getTypedWord(); - if (mOriginalWord != null) { - final String mOriginalWordString = mOriginalWord.toString(); - mOriginalWord = mOriginalWordString; - mLowerOriginalWord = mOriginalWordString.toLowerCase(); + CharSequence typedWord = wordComposer.getTypedWord(); + if (typedWord != null) { + final String typedWordString = typedWord.toString(); + typedWord = typedWordString; + mLowerOriginalWord = typedWordString.toLowerCase(); // Treating USER_TYPED as UNIGRAM suggestion for logging now. - LatinImeLogger.onAddSuggestedWord(mOriginalWordString, Suggest.DIC_USER_TYPED, + LatinImeLogger.onAddSuggestedWord(typedWordString, Suggest.DIC_USER_TYPED, Dictionary.DataType.UNIGRAM); } else { mLowerOriginalWord = ""; @@ -273,7 +276,7 @@ public class Suggest implements Dictionary.WordCallback { mContactsDictionary.getWords(wordComposer, this, mNextLettersFrequencies); } - if (mSuggestions.size() > 0 && isValidWord(mOriginalWord) + if (mSuggestions.size() > 0 && isValidWord(typedWord) && (mCorrectionMode == CORRECTION_FULL || mCorrectionMode == CORRECTION_FULL_BIGRAM)) { mHaveCorrection = true; @@ -285,19 +288,19 @@ public class Suggest implements Dictionary.WordCallback { // TODO: when the normalized score of the first suggestion is nearly equals to // the normalized score of the second suggestion, behave less aggressive. final double normalizedScore = Utils.calcNormalizedScore( - mOriginalWord, mSuggestions.get(0), mPriorities[0]); + typedWord, mSuggestions.get(0), mPriorities[0]); if (LatinImeLogger.sDBG) { - Log.d(TAG, "Normalized " + mOriginalWord + "," + mSuggestions.get(0) + "," + Log.d(TAG, "Normalized " + typedWord + "," + mSuggestions.get(0) + "," + mPriorities[0] + normalizedScore - + "(" + mAutoCompleteThreshold + ")"); + + "(" + mAutoCorrectionThreshold + ")"); } - if (normalizedScore >= mAutoCompleteThreshold) { + if (normalizedScore >= mAutoCorrectionThreshold) { mHaveCorrection = true; } } } - if (mOriginalWord != null) { - mSuggestions.add(0, mOriginalWord.toString()); + if (typedWord != null) { + mSuggestions.add(0, typedWord.toString()); } if (mAutoTextEnabled) { int i = 0; @@ -342,7 +345,7 @@ public class Suggest implements Dictionary.WordCallback { } } removeDupes(); - return mSuggestions; + return new SuggestedWords.Builder().setWords(mSuggestions); } public int[] getNextLettersFrequencies() { diff --git a/java/src/com/android/inputmethod/latin/SuggestedWords.java b/java/src/com/android/inputmethod/latin/SuggestedWords.java new file mode 100644 index 000000000..0bb7c66d1 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/SuggestedWords.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package com.android.inputmethod.latin; + +import android.view.inputmethod.CompletionInfo; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class SuggestedWords { + public static final SuggestedWords EMPTY = new SuggestedWords(null, false, false, false, null); + + public final List<CharSequence> mWords; + public final boolean mIsApplicationSpecifiedCompletions; + public final boolean mTypedWordValid; + public final boolean mHasMinimalSuggestion; + public final Object[] mDebugInfo; + + private SuggestedWords(List<CharSequence> words, boolean isApplicationSpecifiedCompletions, + boolean typedWordValid, boolean hasMinamlSuggestion, Object[] debugInfo) { + if (words != null) { + mWords = words; + } else { + mWords = Collections.emptyList(); + } + mIsApplicationSpecifiedCompletions = isApplicationSpecifiedCompletions; + mTypedWordValid = typedWordValid; + mHasMinimalSuggestion = hasMinamlSuggestion; + mDebugInfo = debugInfo; + } + + public int size() { + return mWords.size(); + } + + public CharSequence getWord(int pos) { + return mWords.get(pos); + } + + public boolean hasAutoCorrectionWord() { + return mHasMinimalSuggestion && size() > 1 && !mTypedWordValid; + } + + public boolean hasWordAboveAutoCorrectionScoreThreshold() { + return mHasMinimalSuggestion && ((size() > 1 && !mTypedWordValid) || mTypedWordValid); + } + + public static class Builder { + private List<CharSequence> mWords; + private boolean mIsCompletions; + private boolean mTypedWordVallid; + private boolean mHasMinimalSuggestion; + private Object[] mDebugInfo; + + public Builder() { + // Nothing to do here. + } + + public Builder setWords(List<CharSequence> words) { + mWords = words; + return this; + } + + public Builder setDebugInfo(Object[] debuginfo) { + mDebugInfo = debuginfo; + return this; + } + + public Builder addWord(int pos, CharSequence word) { + if (mWords == null) + mWords = new ArrayList<CharSequence>(); + mWords.add(pos, word); + return this; + } + + public Builder addWord(CharSequence word) { + if (mWords == null) + mWords = new ArrayList<CharSequence>(); + mWords.add(word); + return this; + } + + public Builder setApplicationSpecifiedCompletions(CompletionInfo[] infos) { + for (CompletionInfo info : infos) + addWord(info.getText()); + mIsCompletions = true; + return this; + } + + public Builder setTypedWordValid(boolean typedWordValid) { + mTypedWordVallid = typedWordValid; + return this; + } + + public Builder setHasMinimalSuggestion(boolean hasMinamlSuggestion) { + mHasMinimalSuggestion = hasMinamlSuggestion; + return this; + } + + public CharSequence getWord(int pos) { + return mWords.get(pos); + } + + public SuggestedWords build() { + return new SuggestedWords(mWords, mIsCompletions, mTypedWordVallid, + mHasMinimalSuggestion, mDebugInfo); + } + } +} diff --git a/java/src/com/android/inputmethod/latin/UserDictionary.java b/java/src/com/android/inputmethod/latin/UserDictionary.java index 7a94ae480..e03f56498 100644 --- a/java/src/com/android/inputmethod/latin/UserDictionary.java +++ b/java/src/com/android/inputmethod/latin/UserDictionary.java @@ -21,6 +21,7 @@ import android.content.ContentValues; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; +import android.net.Uri; import android.provider.UserDictionary.Words; public class UserDictionary extends ExpandableDictionary { @@ -80,7 +81,7 @@ public class UserDictionary extends ExpandableDictionary { * @TODO use a higher or float range for frequency */ @Override - public synchronized void addWord(String word, int frequency) { + public synchronized void addWord(final String word, final int frequency) { // Force load the dictionary here synchronously if (getRequiresReload()) loadDictionaryAsync(); // Safeguard against adding long words. Can cause stack overflow. @@ -99,7 +100,22 @@ public class UserDictionary extends ExpandableDictionary { new Thread("addWord") { @Override public void run() { - contentResolver.insert(Words.CONTENT_URI, values); + Cursor cursor = contentResolver.query(Words.CONTENT_URI, PROJECTION, + "word=? and ((locale IS NULL) or (locale=?))", + new String[] { word, mLocale }, null); + if (cursor != null && cursor.moveToFirst()) { + String locale = cursor.getString(cursor.getColumnIndex(Words.LOCALE)); + // If locale is null, we will not override the entry. + if (locale != null && locale.equals(mLocale.toString())) { + long id = cursor.getLong(cursor.getColumnIndex(Words._ID)); + Uri uri = Uri.withAppendedPath(Words.CONTENT_URI, Long.toString(id)); + // Update the entry with new frequency value. + contentResolver.update(uri, values, null, null); + } + } else { + // Insert new entry. + contentResolver.insert(Words.CONTENT_URI, values); + } } }.start(); diff --git a/java/src/com/android/inputmethod/voice/VoiceIMEConnector.java b/java/src/com/android/inputmethod/voice/VoiceIMEConnector.java index 2052d9348..c532a0baf 100644 --- a/java/src/com/android/inputmethod/voice/VoiceIMEConnector.java +++ b/java/src/com/android/inputmethod/voice/VoiceIMEConnector.java @@ -22,6 +22,7 @@ import com.android.inputmethod.latin.LatinIME.UIHandler; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.SharedPreferencesCompat; import com.android.inputmethod.latin.SubtypeSwitcher; +import com.android.inputmethod.latin.SuggestedWords; import android.app.AlertDialog; import android.content.Context; @@ -424,17 +425,20 @@ public class VoiceIMEConnector implements VoiceInput.UiListener { if (mWordToSuggestions.containsKey(selectedWord)) { mShowingVoiceSuggestions = true; List<CharSequence> suggestions = mWordToSuggestions.get(selectedWord); + SuggestedWords.Builder builder = new SuggestedWords.Builder(); // If the first letter of touching is capitalized, make all the suggestions // start with a capital letter. if (Character.isUpperCase(touching.mWord.charAt(0))) { - for (int i = 0; i < suggestions.size(); i++) { - String origSugg = (String) suggestions.get(i); - String capsSugg = origSugg.toUpperCase().charAt(0) - + origSugg.subSequence(1, origSugg.length()).toString(); - suggestions.set(i, capsSugg); + for (CharSequence word : suggestions) { + String str = word.toString(); + word = Character.toUpperCase(str.charAt(0)) + str.substring(1); + builder.addWord(word); } + } else { + builder.setWords(suggestions); } - mContext.setSuggestions(suggestions, false, true, true); + builder.setTypedWordValid(true).setHasMinimalSuggestion(true); + mContext.setSuggestions(builder.build()); mContext.setCandidatesViewShown(true); return true; } |