diff options
author | 2011-05-11 15:19:24 +0900 | |
---|---|---|
committer | 2011-05-12 20:26:24 +0900 | |
commit | f733074aaecdfd6e89cfee2daff8a9c1233b60f1 (patch) | |
tree | cb9e90c71c874bfb2bc098f5420f689354555f1b /java/src/com/android/inputmethod/deprecated | |
parent | 4f3b59711f6985d39e0cc908d2431ae6715d9b26 (diff) | |
download | latinime-f733074aaecdfd6e89cfee2daff8a9c1233b60f1.tar.gz latinime-f733074aaecdfd6e89cfee2daff8a9c1233b60f1.tar.xz latinime-f733074aaecdfd6e89cfee2daff8a9c1233b60f1.zip |
Fix the available input locales and moved Recorrection
Bug: 4409091
Change-Id: I6efd23ebb9528bf1bd35320057a0ea264c187451
Diffstat (limited to 'java/src/com/android/inputmethod/deprecated')
3 files changed, 391 insertions, 40 deletions
diff --git a/java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java b/java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java index a1b49b475..b8655d112 100644 --- a/java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java +++ b/java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java @@ -43,6 +43,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; +import java.util.Map.Entry; +import java.util.TreeMap; public class InputLanguageSelection extends PreferenceActivity { @@ -51,21 +53,17 @@ public class InputLanguageSelection extends PreferenceActivity { private HashMap<CheckBoxPreference, Locale> mLocaleMap = new HashMap<CheckBoxPreference, Locale>(); - private static class Loc implements Comparable<Object> { + private static class LocaleEntry implements Comparable<Object> { private static Collator sCollator = Collator.getInstance(); private String mLabel; public final Locale mLocale; - public Loc(String label, Locale locale) { + public LocaleEntry(String label, Locale locale) { this.mLabel = label; this.mLocale = locale; } - public void setLabel(String label) { - this.mLabel = label; - } - @Override public String toString() { return this.mLabel; @@ -73,7 +71,7 @@ public class InputLanguageSelection extends PreferenceActivity { @Override public int compareTo(Object o) { - return sCollator.compare(this.mLabel, ((Loc) o).mLabel); + return sCollator.compare(this.mLabel, ((LocaleEntry) o).mLabel); } } @@ -85,21 +83,58 @@ public class InputLanguageSelection extends PreferenceActivity { mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mSelectedLanguages = mPrefs.getString(Settings.PREF_SELECTED_LANGUAGES, ""); String[] languageList = mSelectedLanguages.split(","); - ArrayList<Loc> availableLanguages = getUniqueLocales(); + ArrayList<LocaleEntry> availableLanguages = getUniqueLocales(); PreferenceGroup parent = getPreferenceScreen(); + final HashMap<Long, LocaleEntry> dictionaryIdLocaleMap = new HashMap<Long, LocaleEntry>(); + final TreeMap<LocaleEntry, Boolean> localeHasDictionaryMap = + new TreeMap<LocaleEntry, Boolean>(); for (int i = 0; i < availableLanguages.size(); i++) { - Locale locale = availableLanguages.get(i).mLocale; - final Pair<Boolean, Boolean> hasDictionaryOrLayout = hasDictionaryOrLayout(locale); - final boolean hasDictionary = hasDictionaryOrLayout.first; + LocaleEntry loc = availableLanguages.get(i); + Locale locale = loc.mLocale; + final Pair<Long, Boolean> hasDictionaryOrLayout = hasDictionaryOrLayout(locale); + final Long dictionaryId = hasDictionaryOrLayout.first; final boolean hasLayout = hasDictionaryOrLayout.second; + final boolean hasDictionary = dictionaryId != null; // Add this locale to the supported list if: - // 1) this locale has a layout/ 2) this locale has a dictionary and the length - // of the locale is equal to or larger than 5. - if (!hasLayout && !(hasDictionary && locale.toString().length() >= 5)) { + // 1) this locale has a layout/ 2) this locale has a dictionary + // If some locales have no layout but have a same dictionary, the shortest locale + // will be added to the supported list. + if (!hasLayout && !hasDictionary) { continue; } + if (hasLayout) { + localeHasDictionaryMap.put(loc, hasDictionary); + } + if (!hasDictionary) { + continue; + } + if (dictionaryIdLocaleMap.containsKey(dictionaryId)) { + final String newLocale = locale.toString(); + final String oldLocale = + dictionaryIdLocaleMap.get(dictionaryId).mLocale.toString(); + // Check if this locale is more appropriate to be the candidate of the input locale. + if (oldLocale.length() <= newLocale.length() && !hasLayout) { + // Don't add this new locale to the map<dictionary id, locale> if: + // 1) the new locale's name is longer than the existing one, and + // 2) the new locale doesn't have its layout + continue; + } + } + dictionaryIdLocaleMap.put(dictionaryId, loc); + } + + for (LocaleEntry localeEntry : dictionaryIdLocaleMap.values()) { + if (!localeHasDictionaryMap.containsKey(localeEntry)) { + localeHasDictionaryMap.put(localeEntry, true); + } + } + + for (Entry<LocaleEntry, Boolean> entry : localeHasDictionaryMap.entrySet()) { + final LocaleEntry localeEntry = entry.getKey(); + final Locale locale = localeEntry.mLocale; + final Boolean hasDictionary = entry.getValue(); CheckBoxPreference pref = new CheckBoxPreference(this); - pref.setTitle(SubtypeSwitcher.getFullDisplayName(locale, true)); + pref.setTitle(localeEntry.mLabel); boolean checked = isLocaleIn(locale, languageList); pref.setChecked(checked); if (hasDictionary) { @@ -118,11 +153,11 @@ public class InputLanguageSelection extends PreferenceActivity { return false; } - private Pair<Boolean, Boolean> hasDictionaryOrLayout(Locale locale) { - if (locale == null) return new Pair<Boolean, Boolean>(false, false); + private Pair<Long, Boolean> hasDictionaryOrLayout(Locale locale) { + if (locale == null) return new Pair<Long, Boolean>(null, false); final Resources res = getResources(); final Locale saveLocale = Utils.setSystemLocale(res, locale); - final boolean hasDictionary = DictionaryFactory.isDictionaryAvailable(this, locale); + final Long dictionaryId = DictionaryFactory.getDictionaryId(this, locale); boolean hasLayout = false; try { @@ -141,7 +176,7 @@ public class InputLanguageSelection extends PreferenceActivity { } catch (IOException e) { } Utils.setSystemLocale(res, saveLocale); - return new Pair<Boolean, Boolean>(hasDictionary, hasLayout); + return new Pair<Long, Boolean>(dictionaryId, hasLayout); } private String get5Code(Locale locale) { @@ -174,13 +209,13 @@ public class InputLanguageSelection extends PreferenceActivity { SharedPreferencesCompat.apply(editor); } - public ArrayList<Loc> getUniqueLocales() { + public ArrayList<LocaleEntry> getUniqueLocales() { String[] locales = getAssets().getLocales(); Arrays.sort(locales); - ArrayList<Loc> uniqueLocales = new ArrayList<Loc>(); + ArrayList<LocaleEntry> uniqueLocales = new ArrayList<LocaleEntry>(); final int origSize = locales.length; - Loc[] preprocess = new Loc[origSize]; + LocaleEntry[] preprocess = new LocaleEntry[origSize]; int finalSize = 0; for (int i = 0 ; i < origSize; i++ ) { String s = locales[i]; @@ -202,26 +237,13 @@ public class InputLanguageSelection extends PreferenceActivity { if (finalSize == 0) { preprocess[finalSize++] = - new Loc(SubtypeSwitcher.getFullDisplayName(l, true), l); + new LocaleEntry(SubtypeSwitcher.getFullDisplayName(l, false), l); } else { - // check previous entry: - // same lang and a country -> upgrade to full name and - // insert ours with full name - // diff lang -> insert ours with lang-only name - if (preprocess[finalSize-1].mLocale.getLanguage().equals( - language)) { - preprocess[finalSize-1].setLabel(SubtypeSwitcher.getFullDisplayName( - preprocess[finalSize-1].mLocale, false)); - preprocess[finalSize++] = - new Loc(SubtypeSwitcher.getFullDisplayName(l, false), l); + if (s.equals("zz_ZZ")) { + // ignore this locale } else { - String displayName; - if (s.equals("zz_ZZ")) { - // ignore this locale - } else { - displayName = SubtypeSwitcher.getFullDisplayName(l, true); - preprocess[finalSize++] = new Loc(displayName, l); - } + final String displayName = SubtypeSwitcher.getFullDisplayName(l, false); + preprocess[finalSize++] = new LocaleEntry(displayName, l); } } } diff --git a/java/src/com/android/inputmethod/deprecated/recorrection/Recorrection.java b/java/src/com/android/inputmethod/deprecated/recorrection/Recorrection.java new file mode 100644 index 000000000..adf4204f8 --- /dev/null +++ b/java/src/com/android/inputmethod/deprecated/recorrection/Recorrection.java @@ -0,0 +1,267 @@ +/* + * 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.deprecated.recorrection; + +import com.android.inputmethod.compat.InputConnectionCompatUtils; +import com.android.inputmethod.deprecated.VoiceProxy; +import com.android.inputmethod.keyboard.KeyboardSwitcher; +import com.android.inputmethod.latin.AutoCorrection; +import com.android.inputmethod.latin.CandidateView; +import com.android.inputmethod.latin.EditingUtils; +import com.android.inputmethod.latin.LatinIME; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.Settings; +import com.android.inputmethod.latin.Suggest; +import com.android.inputmethod.latin.SuggestedWords; +import com.android.inputmethod.latin.TextEntryState; +import com.android.inputmethod.latin.WordComposer; + +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.text.TextUtils; +import android.view.inputmethod.ExtractedText; +import android.view.inputmethod.ExtractedTextRequest; +import android.view.inputmethod.InputConnection; + +import java.util.ArrayList; + +/** + * Manager of re-correction functionalities + */ +public class Recorrection { + private static final Recorrection sInstance = new Recorrection(); + + private LatinIME mService; + private boolean mRecorrectionEnabled = false; + private final ArrayList<RecorrectionSuggestionEntries> mRecorrectionSuggestionsList = + new ArrayList<RecorrectionSuggestionEntries>(); + + public static Recorrection getInstance() { + return sInstance; + } + + public static void init(LatinIME context, SharedPreferences prefs) { + if (context == null || prefs == null) { + return; + } + sInstance.initInternal(context, prefs); + } + + private Recorrection() { + } + + public boolean isRecorrectionEnabled() { + return mRecorrectionEnabled; + } + + private void initInternal(LatinIME context, SharedPreferences prefs) { + final Resources res = context.getResources(); + // If the option should not be shown, do not read the re-correction preference + // but always use the default setting defined in the resources. + if (res.getBoolean(R.bool.config_enable_show_recorrection_option)) { + mRecorrectionEnabled = prefs.getBoolean(Settings.PREF_RECORRECTION_ENABLED, + res.getBoolean(R.bool.config_default_recorrection_enabled)); + } else { + mRecorrectionEnabled = res.getBoolean(R.bool.config_default_recorrection_enabled); + } + mService = context; + } + + public void checkRecorrectionOnStart() { + if (!mRecorrectionEnabled) return; + + final InputConnection ic = mService.getCurrentInputConnection(); + if (ic == null) return; + // There could be a pending composing span. Clean it up first. + ic.finishComposingText(); + + if (mService.isShowingSuggestionsStrip() && mService.isSuggestionsRequested()) { + // 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/End because onUpdateSelection() has + // not been called yet. + ExtractedTextRequest etr = new ExtractedTextRequest(); + etr.token = 0; // anything is fine here + ExtractedText et = ic.getExtractedText(etr, 0); + if (et == null) return; + mService.setLastSelection( + et.startOffset + et.selectionStart, et.startOffset + et.selectionEnd); + + // Then look for possible corrections in a delayed fashion + if (!TextUtils.isEmpty(et.text) && mService.isCursorTouchingWord()) { + mService.mHandler.postUpdateOldSuggestions(); + } + } + } + + public void updateRecorrectionSelection(KeyboardSwitcher keyboardSwitcher, + CandidateView candidateView, int candidatesStart, int candidatesEnd, + int newSelStart, int newSelEnd, int oldSelStart, int lastSelectionStart, + int lastSelectionEnd, boolean hasUncommittedTypedChars) { + if (!mRecorrectionEnabled) return; + if (!mService.isShowingSuggestionsStrip()) return; + if (!keyboardSwitcher.isInputViewShown()) return; + if (!mService.isSuggestionsRequested()) return; + // Don't look for corrections if the keyboard is not visible + // Check if we should go in or out of correction mode. + if ((candidatesStart == candidatesEnd || newSelStart != oldSelStart || TextEntryState + .isRecorrecting()) + && (newSelStart < newSelEnd - 1 || !hasUncommittedTypedChars)) { + if (mService.isCursorTouchingWord() || lastSelectionStart < lastSelectionEnd) { + mService.mHandler.cancelUpdateBigramPredictions(); + mService.mHandler.postUpdateOldSuggestions(); + } else { + abortRecorrection(false); + // If showing the "touch again to save" hint, do not replace it. Else, + // show the bigrams if we are at the end of the text, punctuation + // otherwise. + if (candidateView != null && !candidateView.isShowingAddToDictionaryHint()) { + InputConnection ic = mService.getCurrentInputConnection(); + if (null == ic || !TextUtils.isEmpty(ic.getTextAfterCursor(1, 0))) { + if (!mService.isShowingPunctuationList()) { + mService.setPunctuationSuggestions(); + } + } else { + mService.mHandler.postUpdateBigramPredictions(); + } + } + } + } + } + + public void saveRecorrectionSuggestion(WordComposer word, CharSequence result) { + if (!mRecorrectionEnabled) return; + if (word.size() <= 1) { + return; + } + // Skip if result is null. It happens in some edge case. + if (TextUtils.isEmpty(result)) { + return; + } + + // Make a copy of the CharSequence, since it is/could be a mutable CharSequence + final String resultCopy = result.toString(); + RecorrectionSuggestionEntries entry = new RecorrectionSuggestionEntries( + resultCopy, new WordComposer(word)); + mRecorrectionSuggestionsList.add(entry); + } + + public void clearWordsInHistory() { + mRecorrectionSuggestionsList.clear(); + } + + /** + * Tries to apply any typed alternatives for the word if we have any cached alternatives, + * otherwise tries to find new corrections and completions for the word. + * @param touching The word that the cursor is touching, with position information + * @return true if an alternative was found, false otherwise. + */ + public boolean applyTypedAlternatives(WordComposer word, Suggest suggest, + KeyboardSwitcher keyboardSwitcher, EditingUtils.SelectedWord touching) { + // If we didn't find a match, search for result in typed word history + WordComposer foundWord = null; + RecorrectionSuggestionEntries alternatives = null; + // Search old suggestions to suggest re-corrected suggestions. + for (RecorrectionSuggestionEntries entry : mRecorrectionSuggestionsList) { + if (TextUtils.equals(entry.getChosenWord(), touching.mWord)) { + foundWord = entry.mWordComposer; + alternatives = entry; + break; + } + } + // If we didn't find a match, at least suggest corrections as re-corrected suggestions. + if (foundWord == null + && (AutoCorrection.isValidWord(suggest.getUnigramDictionaries(), + touching.mWord, true))) { + foundWord = new WordComposer(); + for (int i = 0; i < touching.mWord.length(); i++) { + foundWord.add(touching.mWord.charAt(i), + new int[] { touching.mWord.charAt(i) }, WordComposer.NOT_A_COORDINATE, + WordComposer.NOT_A_COORDINATE); + } + foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.mWord.charAt(0))); + } + // Found a match, show suggestions + if (foundWord != null || alternatives != null) { + if (alternatives == null) { + alternatives = new RecorrectionSuggestionEntries(touching.mWord, foundWord); + } + showRecorrections(suggest, keyboardSwitcher, alternatives); + if (foundWord != null) { + word.init(foundWord); + } else { + word.reset(); + } + return true; + } + return false; + } + + + private void showRecorrections(Suggest suggest, KeyboardSwitcher keyboardSwitcher, + RecorrectionSuggestionEntries entries) { + SuggestedWords.Builder builder = entries.getAlternatives(suggest, keyboardSwitcher); + builder.setTypedWordValid(false).setHasMinimalSuggestion(false); + mService.showSuggestions(builder.build(), entries.getOriginalWord()); + } + + public void setRecorrectionSuggestions(VoiceProxy voiceProxy, CandidateView candidateView, + Suggest suggest, KeyboardSwitcher keyboardSwitcher, WordComposer word, + boolean hasUncommittedTypedChars, int lastSelectionStart, int lastSelectionEnd, + String wordSeparators) { + if (!InputConnectionCompatUtils.RECORRECTION_SUPPORTED) return; + voiceProxy.setShowingVoiceSuggestions(false); + if (candidateView != null && candidateView.isShowingAddToDictionaryHint()) { + return; + } + InputConnection ic = mService.getCurrentInputConnection(); + if (ic == null) return; + if (!hasUncommittedTypedChars) { + // Extract the selected or touching text + EditingUtils.SelectedWord touching = EditingUtils.getWordAtCursorOrSelection(ic, + lastSelectionStart, lastSelectionEnd, wordSeparators); + + if (touching != null && touching.mWord.length() > 1) { + ic.beginBatchEdit(); + + if (applyTypedAlternatives(word, suggest, keyboardSwitcher, touching) + || voiceProxy.applyVoiceAlternatives(touching)) { + TextEntryState.selectedForRecorrection(); + InputConnectionCompatUtils.underlineWord(ic, touching); + } else { + abortRecorrection(true); + } + + ic.endBatchEdit(); + } else { + abortRecorrection(true); + mService.setPunctuationSuggestions(); // Show the punctuation suggestions list + } + } else { + abortRecorrection(true); + } + } + + public void abortRecorrection(boolean force) { + if (force || TextEntryState.isRecorrecting()) { + TextEntryState.onAbortRecorrection(); + mService.setCandidatesViewShown(mService.isCandidateStripVisible()); + mService.getCurrentInputConnection().finishComposingText(); + mService.clearSuggestions(); + } + } +} diff --git a/java/src/com/android/inputmethod/deprecated/recorrection/RecorrectionSuggestionEntries.java b/java/src/com/android/inputmethod/deprecated/recorrection/RecorrectionSuggestionEntries.java new file mode 100644 index 000000000..914e2cbc1 --- /dev/null +++ b/java/src/com/android/inputmethod/deprecated/recorrection/RecorrectionSuggestionEntries.java @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package com.android.inputmethod.deprecated.recorrection; + +import com.android.inputmethod.keyboard.KeyboardSwitcher; +import com.android.inputmethod.latin.Suggest; +import com.android.inputmethod.latin.SuggestedWords; +import com.android.inputmethod.latin.WordComposer; + +import android.text.TextUtils; + +public class RecorrectionSuggestionEntries { + public final CharSequence mChosenWord; + public final WordComposer mWordComposer; + + public RecorrectionSuggestionEntries(CharSequence chosenWord, WordComposer wordComposer) { + mChosenWord = chosenWord; + mWordComposer = wordComposer; + } + + public CharSequence getChosenWord() { + return mChosenWord; + } + + public CharSequence getOriginalWord() { + return mWordComposer.getTypedWord(); + } + + public SuggestedWords.Builder getAlternatives( + Suggest suggest, KeyboardSwitcher keyboardSwitcher) { + return getTypedSuggestions(suggest, keyboardSwitcher, mWordComposer); + } + + @Override + public int hashCode() { + return mChosenWord.hashCode(); + } + + @Override + public boolean equals(Object o) { + return o instanceof CharSequence && TextUtils.equals(mChosenWord, (CharSequence)o); + } + + private static SuggestedWords.Builder getTypedSuggestions( + Suggest suggest, KeyboardSwitcher keyboardSwitcher, WordComposer word) { + return suggest.getSuggestedWordBuilder(keyboardSwitcher.getInputView(), word, null); + } +} |