From 9502cc177cc53678c9ddcc01d4d046f69220e13b Mon Sep 17 00:00:00 2001 From: "Tadashi G. Takaoka" Date: Thu, 9 Dec 2010 21:06:26 +0900 Subject: Remove LatinIME prefix from classes This change also cleanups preference key string constants Change-Id: I58510f220a90d00d71a935731abeab87384675bb --- .../inputmethod/keyboard/KeyboardSwitcher.java | 18 +- .../inputmethod/keyboard/LatinKeyboardView.java | 8 +- .../com/android/inputmethod/latin/BackupAgent.java | 32 ++ .../android/inputmethod/latin/DebugSettings.java | 76 ++++ .../inputmethod/latin/InputLanguageSelection.java | 4 +- .../inputmethod/latin/LanguageSwitcher.java | 6 +- .../com/android/inputmethod/latin/LatinIME.java | 61 ++-- .../inputmethod/latin/LatinIMEBackupAgent.java | 32 -- .../inputmethod/latin/LatinIMEDebugSettings.java | 76 ---- .../inputmethod/latin/LatinIMESettings.java | 249 ------------- .../android/inputmethod/latin/LatinIMEUtil.java | 393 --------------------- .../com/android/inputmethod/latin/Settings.java | 258 ++++++++++++++ .../android/inputmethod/latin/SubtypeSwitcher.java | 2 +- .../src/com/android/inputmethod/latin/Suggest.java | 2 +- java/src/com/android/inputmethod/latin/Utils.java | 393 +++++++++++++++++++++ 15 files changed, 805 insertions(+), 805 deletions(-) create mode 100644 java/src/com/android/inputmethod/latin/BackupAgent.java create mode 100644 java/src/com/android/inputmethod/latin/DebugSettings.java delete mode 100644 java/src/com/android/inputmethod/latin/LatinIMEBackupAgent.java delete mode 100644 java/src/com/android/inputmethod/latin/LatinIMEDebugSettings.java delete mode 100644 java/src/com/android/inputmethod/latin/LatinIMESettings.java delete mode 100644 java/src/com/android/inputmethod/latin/LatinIMEUtil.java create mode 100644 java/src/com/android/inputmethod/latin/Settings.java create mode 100644 java/src/com/android/inputmethod/latin/Utils.java (limited to 'java/src') diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java index d3302fd6f..88e7ad5d0 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java @@ -17,8 +17,8 @@ package com.android.inputmethod.keyboard; import com.android.inputmethod.latin.LatinIME; -import com.android.inputmethod.latin.LatinIMESettings; -import com.android.inputmethod.latin.LatinIMEUtil; +import com.android.inputmethod.latin.Settings; +import com.android.inputmethod.latin.Utils; import com.android.inputmethod.latin.LatinImeLogger; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.SubtypeSwitcher; @@ -562,20 +562,20 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha newLayout = Integer.valueOf(DEFAULT_LAYOUT_ID); } - LatinIMEUtil.GCUtils.getInstance().reset(); + Utils.GCUtils.getInstance().reset(); boolean tryGC = true; - for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { + for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { mInputView = (LatinKeyboardView) mInputMethodService.getLayoutInflater( ).inflate(THEMES[newLayout], null); tryGC = false; } catch (OutOfMemoryError e) { Log.w(TAG, "load keyboard failed: " + e); - tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait( + tryGC = Utils.GCUtils.getInstance().tryGCOrWait( mLayoutId + "," + newLayout, e); } catch (InflateException e) { Log.w(TAG, "load keyboard failed: " + e); - tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait( + tryGC = Utils.GCUtils.getInstance().tryGCOrWait( mLayoutId + "," + newLayout, e); } } @@ -603,7 +603,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha sharedPreferences.getString(key, DEFAULT_LAYOUT_ID)); createInputViewInternal(layoutId, false); postSetInputView(); - } else if (LatinIMESettings.PREF_SETTINGS_KEY.equals(key)) { + } else if (Settings.PREF_SETTINGS_KEY.equals(key)) { mHasSettingsKey = getSettingsKeyMode(sharedPreferences, mInputMethodService); createInputViewInternal(mLayoutId, true); postSetInputView(); @@ -629,13 +629,13 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha final boolean showSettingsKeyOption = resources.getBoolean( R.bool.config_enable_show_settings_key_option); if (showSettingsKeyOption) { - final String settingsKeyMode = prefs.getString(LatinIMESettings.PREF_SETTINGS_KEY, + final String settingsKeyMode = prefs.getString(Settings.PREF_SETTINGS_KEY, resources.getString(DEFAULT_SETTINGS_KEY_MODE)); // We show the settings key when 1) SETTINGS_KEY_MODE_ALWAYS_SHOW or // 2) SETTINGS_KEY_MODE_AUTO and there are two or more enabled IMEs on the system if (settingsKeyMode.equals(resources.getString(SETTINGS_KEY_MODE_ALWAYS_SHOW)) || (settingsKeyMode.equals(resources.getString(SETTINGS_KEY_MODE_AUTO)) - && LatinIMEUtil.hasMultipleEnabledIMEsOrSubtypes( + && Utils.hasMultipleEnabledIMEsOrSubtypes( ((InputMethodManager) context.getSystemService( Context.INPUT_METHOD_SERVICE))))) { return true; diff --git a/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java b/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java index 5c1c62b05..79b0cbf52 100644 --- a/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java +++ b/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java @@ -16,7 +16,7 @@ package com.android.inputmethod.keyboard; -import com.android.inputmethod.latin.LatinIMEUtil; +import com.android.inputmethod.latin.Utils; import com.android.inputmethod.voice.VoiceIMEConnector; import android.content.Context; @@ -330,14 +330,14 @@ public class LatinKeyboardView extends KeyboardView { @Override public void draw(Canvas c) { - LatinIMEUtil.GCUtils.getInstance().reset(); + Utils.GCUtils.getInstance().reset(); boolean tryGC = true; - for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { + for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { super.draw(c); tryGC = false; } catch (OutOfMemoryError e) { - tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait("LatinKeyboardView", e); + tryGC = Utils.GCUtils.getInstance().tryGCOrWait("LatinKeyboardView", e); } } if (DEBUG_AUTO_PLAY) { diff --git a/java/src/com/android/inputmethod/latin/BackupAgent.java b/java/src/com/android/inputmethod/latin/BackupAgent.java new file mode 100644 index 000000000..ee070af75 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/BackupAgent.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2008 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.app.backup.BackupAgentHelper; +import android.app.backup.SharedPreferencesBackupHelper; + +/** + * Backs up the Latin IME shared preferences. + */ +public class BackupAgent extends BackupAgentHelper { + + @Override + public void onCreate() { + addHelper("shared_pref", new SharedPreferencesBackupHelper(this, + getPackageName() + "_preferences")); + } +} diff --git a/java/src/com/android/inputmethod/latin/DebugSettings.java b/java/src/com/android/inputmethod/latin/DebugSettings.java new file mode 100644 index 000000000..03211f36b --- /dev/null +++ b/java/src/com/android/inputmethod/latin/DebugSettings.java @@ -0,0 +1,76 @@ +/* + * 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.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager.NameNotFoundException; +import android.os.Bundle; +import android.preference.CheckBoxPreference; +import android.preference.PreferenceActivity; +import android.util.Log; + +public class DebugSettings extends PreferenceActivity + implements SharedPreferences.OnSharedPreferenceChangeListener { + + private static final String TAG = "DebugSettings"; + private static final String DEBUG_MODE_KEY = "debug_mode"; + + private CheckBoxPreference mDebugMode; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + addPreferencesFromResource(R.xml.prefs_for_debug); + SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); + prefs.registerOnSharedPreferenceChangeListener(this); + + mDebugMode = (CheckBoxPreference) findPreference(DEBUG_MODE_KEY); + updateDebugMode(); + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { + if (key.equals(DEBUG_MODE_KEY)) { + if (mDebugMode != null) { + mDebugMode.setChecked(prefs.getBoolean(DEBUG_MODE_KEY, false)); + updateDebugMode(); + } + } + } + + private void updateDebugMode() { + if (mDebugMode == null) { + return; + } + boolean isDebugMode = mDebugMode.isChecked(); + String version = ""; + try { + PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); + version = "Version " + info.versionName; + } catch (NameNotFoundException e) { + Log.e(TAG, "Could not find version info."); + } + if (!isDebugMode) { + mDebugMode.setTitle(version); + mDebugMode.setSummary(""); + } else { + mDebugMode.setTitle(getResources().getString(R.string.prefs_debug_mode)); + mDebugMode.setSummary(version); + } + } +} diff --git a/java/src/com/android/inputmethod/latin/InputLanguageSelection.java b/java/src/com/android/inputmethod/latin/InputLanguageSelection.java index ad3f1db9b..a55821659 100644 --- a/java/src/com/android/inputmethod/latin/InputLanguageSelection.java +++ b/java/src/com/android/inputmethod/latin/InputLanguageSelection.java @@ -69,7 +69,7 @@ public class InputLanguageSelection extends PreferenceActivity { addPreferencesFromResource(R.xml.language_prefs); // Get the settings preferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); - mSelectedLanguages = mPrefs.getString(LatinIME.PREF_SELECTED_LANGUAGES, ""); + mSelectedLanguages = mPrefs.getString(Settings.PREF_SELECTED_LANGUAGES, ""); String[] languageList = mSelectedLanguages.split(","); mAvailableLanguages = getUniqueLocales(); PreferenceGroup parent = getPreferenceScreen(); @@ -143,7 +143,7 @@ public class InputLanguageSelection extends PreferenceActivity { } if (checkedLanguages.length() < 1) checkedLanguages = null; // Save null Editor editor = mPrefs.edit(); - editor.putString(LatinIME.PREF_SELECTED_LANGUAGES, checkedLanguages); + editor.putString(Settings.PREF_SELECTED_LANGUAGES, checkedLanguages); SharedPreferencesCompat.apply(editor); } diff --git a/java/src/com/android/inputmethod/latin/LanguageSwitcher.java b/java/src/com/android/inputmethod/latin/LanguageSwitcher.java index fc725bf1b..6faf7f95e 100644 --- a/java/src/com/android/inputmethod/latin/LanguageSwitcher.java +++ b/java/src/com/android/inputmethod/latin/LanguageSwitcher.java @@ -52,8 +52,8 @@ public class LanguageSwitcher { * @return whether there was any change */ public boolean loadLocales(SharedPreferences sp) { - String selectedLanguages = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, null); - String currentLanguage = sp.getString(LatinIME.PREF_INPUT_LANGUAGE, null); + String selectedLanguages = sp.getString(Settings.PREF_SELECTED_LANGUAGES, null); + String currentLanguage = sp.getString(Settings.PREF_INPUT_LANGUAGE, null); if (selectedLanguages == null || selectedLanguages.length() < 1) { loadDefaults(); if (mLocales.size() == 0) { @@ -187,7 +187,7 @@ public class LanguageSwitcher { public void persist(SharedPreferences prefs) { Editor editor = prefs.edit(); - editor.putString(LatinIME.PREF_INPUT_LANGUAGE, getInputLanguage()); + editor.putString(Settings.PREF_INPUT_LANGUAGE, getInputLanguage()); SharedPreferencesCompat.apply(editor); } } diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index ed5ce6bb8..27af98e40 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -22,7 +22,7 @@ import com.android.inputmethod.keyboard.KeyboardId; import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.keyboard.KeyboardView; import com.android.inputmethod.keyboard.LatinKeyboardView; -import com.android.inputmethod.latin.LatinIMEUtil.RingCharBuffer; +import com.android.inputmethod.latin.Utils.RingCharBuffer; import com.android.inputmethod.voice.VoiceIMEConnector; import org.xmlpull.v1.XmlPullParserException; @@ -88,18 +88,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private static final boolean DEBUG = false; private static final boolean TRACE = false; - private static final String PREF_SOUND_ON = "sound_on"; - private static final String PREF_POPUP_ON = "popup_on"; - private static final String PREF_AUTO_CAP = "auto_cap"; - private static final String PREF_QUICK_FIXES = "quick_fixes"; - private static final String PREF_SHOW_SUGGESTIONS_SETTING = "show_suggestions_setting"; - private static final String PREF_AUTO_COMPLETION_THRESHOLD = "auto_completion_threshold"; - private static final String PREF_BIGRAM_SUGGESTIONS = "bigram_suggestion"; - - public static final String PREF_SELECTED_LANGUAGES = "selected_languages"; - public static final String PREF_INPUT_LANGUAGE = "input_language"; - private static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled"; - private static final int DELAY_UPDATE_SUGGESTIONS = 180; private static final int DELAY_UPDATE_OLD_SUGGESTIONS = 300; private static final int DELAY_UPDATE_SHIFT_STATE = 300; @@ -346,17 +334,17 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final Configuration conf = mResources.getConfiguration(); mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); - mReCorrectionEnabled = prefs.getBoolean(PREF_RECORRECTION_ENABLED, + mReCorrectionEnabled = prefs.getBoolean(Settings.PREF_RECORRECTION_ENABLED, getResources().getBoolean(R.bool.default_recorrection_enabled)); - LatinIMEUtil.GCUtils.getInstance().reset(); + Utils.GCUtils.getInstance().reset(); boolean tryGC = true; - for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { + for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { initSuggest(); tryGC = false; } catch (OutOfMemoryError e) { - tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait("InitSuggest", e); + tryGC = Utils.GCUtils.getInstance().tryGCOrWait("InitSuggest", e); } } @@ -419,7 +407,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mSuggest.close(); } final SharedPreferences prefs = mPrefs; - mQuickFixes = prefs.getBoolean(PREF_QUICK_FIXES, true); + mQuickFixes = prefs.getBoolean(Settings.PREF_QUICK_FIXES, true); int[] dictionaries = getDictionary(orig); mSuggest = new Suggest(this, dictionaries); @@ -1063,7 +1051,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private void onSettingsKeyPressed() { if (!isShowingOptionDialog()) { - if (LatinIMEUtil.hasMultipleEnabledIMEsOrSubtypes(mImm)) { + if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) { showOptionsMenu(); } else { launchSettings(); @@ -1073,7 +1061,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private void onSettingsKeyLongPressed() { if (!isShowingOptionDialog()) { - if (LatinIMEUtil.hasMultipleEnabledIMEsOrSubtypes(mImm)) { + if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) { mImm.showInputMethodPicker(); } else { launchSettings(); @@ -1898,10 +1886,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { mSubtypeSwitcher.onSharedPreferenceChanged(sharedPreferences, key); - if (PREF_SELECTED_LANGUAGES.equals(key)) { + if (Settings.PREF_SELECTED_LANGUAGES.equals(key)) { mRefreshKeyboardRequired = true; - } else if (PREF_RECORRECTION_ENABLED.equals(key)) { - mReCorrectionEnabled = sharedPreferences.getBoolean(PREF_RECORRECTION_ENABLED, + } else if (Settings.PREF_RECORRECTION_ENABLED.equals(key)) { + mReCorrectionEnabled = sharedPreferences.getBoolean( + Settings.PREF_RECORRECTION_ENABLED, getResources().getBoolean(R.bool.default_recorrection_enabled)); } } @@ -2071,8 +2060,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private void updateSuggestionVisibility(SharedPreferences prefs) { final String suggestionVisiblityStr = prefs.getString( - PREF_SHOW_SUGGESTIONS_SETTING, mResources.getString( - R.string.prefs_suggestion_visibility_default_value)); + Settings.PREF_SHOW_SUGGESTIONS_SETTING, + mResources.getString(R.string.prefs_suggestion_visibility_default_value)); for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) { if (suggestionVisiblityStr.equals(mResources.getString(visibility))) { mSuggestionVisibility = visibility; @@ -2082,11 +2071,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } protected void launchSettings() { - launchSettings(LatinIMESettings.class); + launchSettings(Settings.class); } public void launchDebugSettings() { - launchSettings(LatinIMEDebugSettings.class); + launchSettings(DebugSettings.class); } protected void launchSettings(Class settingsClass) { @@ -2102,12 +2091,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final SharedPreferences prefs = mPrefs; Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); mVibrateOn = vibrator != null && vibrator.hasVibrator() - && prefs.getBoolean(LatinIMESettings.PREF_VIBRATE_ON, false); - mSoundOn = prefs.getBoolean(PREF_SOUND_ON, false); - mPopupOn = prefs.getBoolean(PREF_POPUP_ON, + && prefs.getBoolean(Settings.PREF_VIBRATE_ON, false); + mSoundOn = prefs.getBoolean(Settings.PREF_SOUND_ON, false); + mPopupOn = prefs.getBoolean(Settings.PREF_POPUP_ON, mResources.getBoolean(R.bool.default_popup_preview)); - mAutoCap = prefs.getBoolean(PREF_AUTO_CAP, true); - mQuickFixes = prefs.getBoolean(PREF_QUICK_FIXES, true); + mAutoCap = prefs.getBoolean(Settings.PREF_AUTO_CAP, true); + mQuickFixes = prefs.getBoolean(Settings.PREF_QUICK_FIXES, true); mAutoCorrectEnabled = isAutoCorrectEnabled(prefs); mBigramSuggestionEnabled = mAutoCorrectEnabled && isBigramSuggestionEnabled(prefs); @@ -2131,7 +2120,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // When auto completion setting is turned off, the threshold is ignored. if (!isAutoCorrectEnabled(sp)) return; - final String currentAutoCompletionSetting = sp.getString(PREF_AUTO_COMPLETION_THRESHOLD, + 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); @@ -2159,7 +2149,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } private boolean isAutoCorrectEnabled(SharedPreferences sp) { - final String currentAutoCompletionSetting = sp.getString(PREF_AUTO_COMPLETION_THRESHOLD, + 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); @@ -2168,7 +2159,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private boolean isBigramSuggestionEnabled(SharedPreferences sp) { // TODO: Define default value instead of 'true'. - return sp.getBoolean(PREF_BIGRAM_SUGGESTIONS, true); + return sp.getBoolean(Settings.PREF_BIGRAM_SUGGESTIONS, true); } private void initSuggestPuncList() { diff --git a/java/src/com/android/inputmethod/latin/LatinIMEBackupAgent.java b/java/src/com/android/inputmethod/latin/LatinIMEBackupAgent.java deleted file mode 100644 index a14a4751f..000000000 --- a/java/src/com/android/inputmethod/latin/LatinIMEBackupAgent.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2008 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.app.backup.BackupAgentHelper; -import android.app.backup.SharedPreferencesBackupHelper; - -/** - * Backs up the Latin IME shared preferences. - */ -public class LatinIMEBackupAgent extends BackupAgentHelper { - - @Override - public void onCreate() { - addHelper("shared_pref", new SharedPreferencesBackupHelper(this, - getPackageName() + "_preferences")); - } -} diff --git a/java/src/com/android/inputmethod/latin/LatinIMEDebugSettings.java b/java/src/com/android/inputmethod/latin/LatinIMEDebugSettings.java deleted file mode 100644 index 68738eca1..000000000 --- a/java/src/com/android/inputmethod/latin/LatinIMEDebugSettings.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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.content.SharedPreferences; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager.NameNotFoundException; -import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.PreferenceActivity; -import android.util.Log; - -public class LatinIMEDebugSettings extends PreferenceActivity - implements SharedPreferences.OnSharedPreferenceChangeListener { - - private static final String TAG = "LatinIMEDebugSettings"; - private static final String DEBUG_MODE_KEY = "debug_mode"; - - private CheckBoxPreference mDebugMode; - - @Override - protected void onCreate(Bundle icicle) { - super.onCreate(icicle); - addPreferencesFromResource(R.xml.prefs_for_debug); - SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); - prefs.registerOnSharedPreferenceChangeListener(this); - - mDebugMode = (CheckBoxPreference) findPreference(DEBUG_MODE_KEY); - updateDebugMode(); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { - if (key.equals(DEBUG_MODE_KEY)) { - if (mDebugMode != null) { - mDebugMode.setChecked(prefs.getBoolean(DEBUG_MODE_KEY, false)); - updateDebugMode(); - } - } - } - - private void updateDebugMode() { - if (mDebugMode == null) { - return; - } - boolean isDebugMode = mDebugMode.isChecked(); - String version = ""; - try { - PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); - version = "Version " + info.versionName; - } catch (NameNotFoundException e) { - Log.e(TAG, "Could not find version info."); - } - if (!isDebugMode) { - mDebugMode.setTitle(version); - mDebugMode.setSummary(""); - } else { - mDebugMode.setTitle(getResources().getString(R.string.prefs_debug_mode)); - mDebugMode.setSummary(version); - } - } -} diff --git a/java/src/com/android/inputmethod/latin/LatinIMESettings.java b/java/src/com/android/inputmethod/latin/LatinIMESettings.java deleted file mode 100644 index 3aa89dd59..000000000 --- a/java/src/com/android/inputmethod/latin/LatinIMESettings.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (C) 2008 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 com.android.inputmethod.voice.VoiceIMEConnector; -import com.android.inputmethod.voice.VoiceInputLogger; - -import android.app.AlertDialog; -import android.app.Dialog; -import android.app.backup.BackupManager; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.os.Vibrator; -import android.preference.CheckBoxPreference; -import android.preference.ListPreference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceGroup; -import android.speech.SpeechRecognizer; -import android.text.AutoText; -import android.text.TextUtils; -import android.text.method.LinkMovementMethod; -import android.util.Log; -import android.widget.TextView; - -import java.util.Locale; - -public class LatinIMESettings extends PreferenceActivity - implements SharedPreferences.OnSharedPreferenceChangeListener, - DialogInterface.OnDismissListener { - - private static final String QUICK_FIXES_KEY = "quick_fixes"; - private static final String PREDICTION_SETTINGS_KEY = "prediction_settings"; - private static final String VOICE_SETTINGS_KEY = "voice_mode"; - private static final String PREF_AUTO_COMPLETION_THRESHOLD = "auto_completion_threshold"; - private static final String PREF_BIGRAM_SUGGESTIONS = "bigram_suggestion"; - public static final String PREF_SETTINGS_KEY = "settings_key"; - /* package */ static final String PREF_VIBRATE_ON = "vibrate_on"; - - private static final String TAG = "LatinIMESettings"; - - // Dialog ids - private static final int VOICE_INPUT_CONFIRM_DIALOG = 0; - - private CheckBoxPreference mQuickFixes; - private ListPreference mVoicePreference; - private ListPreference mSettingsKeyPreference; - private ListPreference mAutoCompletionThreshold; - private CheckBoxPreference mBigramSuggestion; - private boolean mVoiceOn; - - private AlertDialog mDialog; - - private VoiceInputLogger mLogger; - - 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)); - } - @Override - protected void onCreate(Bundle icicle) { - super.onCreate(icicle); - addPreferencesFromResource(R.xml.prefs); - mQuickFixes = (CheckBoxPreference) findPreference(QUICK_FIXES_KEY); - mVoicePreference = (ListPreference) findPreference(VOICE_SETTINGS_KEY); - mSettingsKeyPreference = (ListPreference) findPreference(PREF_SETTINGS_KEY); - SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); - prefs.registerOnSharedPreferenceChangeListener(this); - - mVoiceModeOff = getString(R.string.voice_mode_off); - mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff)); - mLogger = VoiceInputLogger.getLogger(this); - - mAutoCompletionThreshold = (ListPreference) findPreference(PREF_AUTO_COMPLETION_THRESHOLD); - mBigramSuggestion = (CheckBoxPreference) findPreference(PREF_BIGRAM_SUGGESTIONS); - ensureConsistencyOfAutoCompletionSettings(); - - final boolean showSettingsKeyOption = getResources().getBoolean( - R.bool.config_enable_show_settings_key_option); - if (!showSettingsKeyOption) { - getPreferenceScreen().removePreference(mSettingsKeyPreference); - } - - final boolean showVoiceKeyOption = getResources().getBoolean( - R.bool.config_enable_show_voice_key_option); - if (!showVoiceKeyOption) { - getPreferenceScreen().removePreference(mVoicePreference); - } - - Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); - if (vibrator == null || !vibrator.hasVibrator()) { - getPreferenceScreen().removePreference( - getPreferenceScreen().findPreference(PREF_VIBRATE_ON)); - } - } - - @Override - protected void onResume() { - super.onResume(); - int autoTextSize = AutoText.getSize(getListView()); - if (autoTextSize < 1) { - ((PreferenceGroup) findPreference(PREDICTION_SETTINGS_KEY)) - .removePreference(mQuickFixes); - } - if (!VoiceIMEConnector.VOICE_INSTALLED - || !SpeechRecognizer.isRecognitionAvailable(this)) { - getPreferenceScreen().removePreference(mVoicePreference); - } else { - updateVoiceModeSummary(); - } - updateSettingsKeySummary(); - } - - @Override - protected void onDestroy() { - getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( - this); - super.onDestroy(); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { - (new BackupManager(this)).dataChanged(); - // If turning on voice input, show dialog - if (key.equals(VOICE_SETTINGS_KEY) && !mVoiceOn) { - if (!prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff) - .equals(mVoiceModeOff)) { - showVoiceConfirmation(); - } - } - ensureConsistencyOfAutoCompletionSettings(); - mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff)); - updateVoiceModeSummary(); - updateSettingsKeySummary(); - } - - private void updateSettingsKeySummary() { - mSettingsKeyPreference.setSummary( - getResources().getStringArray(R.array.settings_key_modes) - [mSettingsKeyPreference.findIndexOfValue(mSettingsKeyPreference.getValue())]); - } - - private void showVoiceConfirmation() { - mOkClicked = false; - showDialog(VOICE_INPUT_CONFIRM_DIALOG); - // Make URL in the dialog message clickable - if (mDialog != null) { - TextView textView = (TextView) mDialog.findViewById(android.R.id.message); - if (textView != null) { - textView.setMovementMethod(LinkMovementMethod.getInstance()); - } - } - } - - private void updateVoiceModeSummary() { - mVoicePreference.setSummary( - getResources().getStringArray(R.array.voice_input_modes_summary) - [mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]); - } - - @Override - protected Dialog onCreateDialog(int id) { - switch (id) { - case VOICE_INPUT_CONFIRM_DIALOG: - DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int whichButton) { - if (whichButton == DialogInterface.BUTTON_NEGATIVE) { - mVoicePreference.setValue(mVoiceModeOff); - mLogger.settingsWarningDialogCancel(); - } else if (whichButton == DialogInterface.BUTTON_POSITIVE) { - mOkClicked = true; - mLogger.settingsWarningDialogOk(); - } - updateVoicePreference(); - } - }; - AlertDialog.Builder builder = new AlertDialog.Builder(this) - .setTitle(R.string.voice_warning_title) - .setPositiveButton(android.R.string.ok, listener) - .setNegativeButton(android.R.string.cancel, listener); - - // Get the current list of supported locales and check the current locale against - // that list, to decide whether to put a warning that voice input will not work in - // the current language as part of the pop-up confirmation dialog. - boolean localeSupported = SubtypeSwitcher.getInstance().isVoiceSupported( - Locale.getDefault().toString()); - - final CharSequence message; - if (localeSupported) { - message = TextUtils.concat( - getText(R.string.voice_warning_may_not_understand), "\n\n", - getText(R.string.voice_hint_dialog_message)); - } else { - message = TextUtils.concat( - getText(R.string.voice_warning_locale_not_supported), "\n\n", - getText(R.string.voice_warning_may_not_understand), "\n\n", - getText(R.string.voice_hint_dialog_message)); - } - builder.setMessage(message); - AlertDialog dialog = builder.create(); - mDialog = dialog; - dialog.setOnDismissListener(this); - mLogger.settingsWarningDialogShown(); - return dialog; - default: - Log.e(TAG, "unknown dialog " + id); - return null; - } - } - - @Override - public void onDismiss(DialogInterface dialog) { - mLogger.settingsWarningDialogDismissed(); - if (!mOkClicked) { - // This assumes that onPreferenceClick gets called first, and this if the user - // agreed after the warning, we set the mOkClicked value to true. - mVoicePreference.setValue(mVoiceModeOff); - } - } - - private void updateVoicePreference() { - boolean isChecked = !mVoicePreference.getValue().equals(mVoiceModeOff); - if (isChecked) { - mLogger.voiceInputSettingEnabled(); - } else { - mLogger.voiceInputSettingDisabled(); - } - } -} diff --git a/java/src/com/android/inputmethod/latin/LatinIMEUtil.java b/java/src/com/android/inputmethod/latin/LatinIMEUtil.java deleted file mode 100644 index f508b9ab8..000000000 --- a/java/src/com/android/inputmethod/latin/LatinIMEUtil.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * 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.inputmethodservice.InputMethodService; -import android.os.AsyncTask; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.Process; -import android.text.format.DateUtils; -import android.util.Log; -import android.view.inputmethod.InputMethodManager; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class LatinIMEUtil { - - /** - * Cancel an {@link AsyncTask}. - * - * @param mayInterruptIfRunning true if the thread executing this - * task should be interrupted; otherwise, in-progress tasks are allowed - * to complete. - */ - public static void cancelTask(AsyncTask task, boolean mayInterruptIfRunning) { - if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) { - task.cancel(mayInterruptIfRunning); - } - } - - public static class GCUtils { - private static final String TAG = "GCUtils"; - public static final int GC_TRY_COUNT = 2; - // GC_TRY_LOOP_MAX is used for the hard limit of GC wait, - // GC_TRY_LOOP_MAX should be greater than GC_TRY_COUNT. - public static final int GC_TRY_LOOP_MAX = 5; - private static final long GC_INTERVAL = DateUtils.SECOND_IN_MILLIS; - private static GCUtils sInstance = new GCUtils(); - private int mGCTryCount = 0; - - public static GCUtils getInstance() { - return sInstance; - } - - public void reset() { - mGCTryCount = 0; - } - - public boolean tryGCOrWait(String metaData, Throwable t) { - if (mGCTryCount == 0) { - System.gc(); - } - if (++mGCTryCount > GC_TRY_COUNT) { - LatinImeLogger.logOnException(metaData, t); - return false; - } else { - try { - Thread.sleep(GC_INTERVAL); - return true; - } catch (InterruptedException e) { - Log.e(TAG, "Sleep was interrupted."); - LatinImeLogger.logOnException(metaData, t); - return false; - } - } - } - } - - public static boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm) { - return imm.getEnabledInputMethodList().size() > 1 - // imm.getEnabledInputMethodSubtypeList(null) will return the current IME's enabled input - // method subtype (The current IME should be LatinIME.) - || imm.getEnabledInputMethodSubtypeList(null).size() > 1; - } - - /* package */ static class RingCharBuffer { - private static RingCharBuffer sRingCharBuffer = new RingCharBuffer(); - private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC'; - private static final int INVALID_COORDINATE = -2; - /* package */ static final int BUFSIZE = 20; - private InputMethodService mContext; - private boolean mEnabled = false; - private boolean mUsabilityStudy = false; - private int mEnd = 0; - /* package */ int mLength = 0; - private char[] mCharBuf = new char[BUFSIZE]; - private int[] mXBuf = new int[BUFSIZE]; - private int[] mYBuf = new int[BUFSIZE]; - - private RingCharBuffer() { - } - public static RingCharBuffer getInstance() { - return sRingCharBuffer; - } - public static RingCharBuffer init(InputMethodService context, boolean enabled, - boolean usabilityStudy) { - sRingCharBuffer.mContext = context; - sRingCharBuffer.mEnabled = enabled || usabilityStudy; - sRingCharBuffer.mUsabilityStudy = usabilityStudy; - UsabilityStudyLogUtils.getInstance().init(context); - return sRingCharBuffer; - } - private int normalize(int in) { - int ret = in % BUFSIZE; - return ret < 0 ? ret + BUFSIZE : ret; - } - public void push(char c, int x, int y) { - if (!mEnabled) return; - if (mUsabilityStudy) { - UsabilityStudyLogUtils.getInstance().writeChar(c, x, y); - } - mCharBuf[mEnd] = c; - mXBuf[mEnd] = x; - mYBuf[mEnd] = y; - mEnd = normalize(mEnd + 1); - if (mLength < BUFSIZE) { - ++mLength; - } - } - public char pop() { - if (mLength < 1) { - return PLACEHOLDER_DELIMITER_CHAR; - } else { - mEnd = normalize(mEnd - 1); - --mLength; - return mCharBuf[mEnd]; - } - } - public char getLastChar() { - if (mLength < 1) { - return PLACEHOLDER_DELIMITER_CHAR; - } else { - return mCharBuf[normalize(mEnd - 1)]; - } - } - public int getPreviousX(char c, int back) { - int index = normalize(mEnd - 2 - back); - if (mLength <= back - || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { - return INVALID_COORDINATE; - } else { - return mXBuf[index]; - } - } - public int getPreviousY(char c, int back) { - int index = normalize(mEnd - 2 - back); - if (mLength <= back - || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { - return INVALID_COORDINATE; - } else { - return mYBuf[index]; - } - } - public String getLastString() { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < mLength; ++i) { - char c = mCharBuf[normalize(mEnd - 1 - i)]; - if (!((LatinIME)mContext).isWordSeparator(c)) { - sb.append(c); - } else { - break; - } - } - return sb.reverse().toString(); - } - public void reset() { - mLength = 0; - } - } - - public static int editDistance(CharSequence s, CharSequence t) { - if (s == null || t == null) { - throw new IllegalArgumentException("editDistance: Arguments should not be null."); - } - final int sl = s.length(); - final int tl = t.length(); - int[][] dp = new int [sl + 1][tl + 1]; - for (int i = 0; i <= sl; i++) { - dp[i][0] = i; - } - for (int j = 0; j <= tl; j++) { - dp[0][j] = j; - } - for (int i = 0; i < sl; ++i) { - for (int j = 0; j < tl; ++j) { - if (s.charAt(i) == t.charAt(j)) { - dp[i + 1][j + 1] = dp[i][j]; - } else { - dp[i + 1][j + 1] = 1 + Math.min(dp[i][j], - Math.min(dp[i + 1][j], dp[i][j + 1])); - } - } - } - return dp[sl][tl]; - } - - // In dictionary.cpp, getSuggestion() method, - // suggestion scores are computed using the below formula. - // original score (called 'frequency') - // := pow(mTypedLetterMultiplier (this is defined 2), - // (the number of matched characters between typed word and suggested word)) - // * (individual word's score which defined in the unigram dictionary, - // and this score is defined in range [0, 255].) - // * (when before.length() == after.length(), - // mFullWordMultiplier (this is defined 2)) - // So, maximum original score is pow(2, before.length()) * 255 * 2 - // So, we can normalize original score by dividing this value. - private static final int MAX_INITIAL_SCORE = 255; - private static final int TYPED_LETTER_MULTIPLIER = 2; - private static final int FULL_WORD_MULTIPLYER = 2; - public static double calcNormalizedScore(CharSequence before, CharSequence after, int score) { - final int beforeLength = before.length(); - final int afterLength = after.length(); - final int distance = editDistance(before, after); - final double maximumScore = MAX_INITIAL_SCORE - * Math.pow(TYPED_LETTER_MULTIPLIER, beforeLength) - * FULL_WORD_MULTIPLYER; - // add a weight based on edit distance. - // distance <= max(afterLength, beforeLength) == afterLength, - // so, 0 <= distance / afterLength <= 1 - final double weight = 1.0 - (double) distance / afterLength; - return (score / maximumScore) * weight; - } - - public static class UsabilityStudyLogUtils { - private static final String TAG = "UsabilityStudyLogUtils"; - private static final String FILENAME = "log.txt"; - private static final UsabilityStudyLogUtils sInstance = - new UsabilityStudyLogUtils(); - private final Handler mLoggingHandler; - private File mFile; - private File mDirectory; - private InputMethodService mIms; - private PrintWriter mWriter; - private final Date mDate; - private final SimpleDateFormat mDateFormat; - - private UsabilityStudyLogUtils() { - mDate = new Date(); - mDateFormat = new SimpleDateFormat("dd MMM HH:mm:ss.SSS"); - - HandlerThread handlerThread = new HandlerThread("UsabilityStudyLogUtils logging task", - Process.THREAD_PRIORITY_BACKGROUND); - handlerThread.start(); - mLoggingHandler = new Handler(handlerThread.getLooper()); - } - - public static UsabilityStudyLogUtils getInstance() { - return sInstance; - } - - public void init(InputMethodService ims) { - mIms = ims; - mDirectory = ims.getFilesDir(); - } - - private void createLogFileIfNotExist() { - if ((mFile == null || !mFile.exists()) - && (mDirectory != null && mDirectory.exists())) { - try { - mWriter = getPrintWriter(mDirectory, FILENAME, false); - } catch (IOException e) { - Log.e(TAG, "Can't create log file."); - } - } - } - - public void writeBackSpace() { - UsabilityStudyLogUtils.getInstance().write("\t0\t0"); - } - - public void writeChar(char c, int x, int y) { - String inputChar = String.valueOf(c); - switch (c) { - case '\n': - inputChar = ""; - break; - case '\t': - inputChar = ""; - break; - case ' ': - inputChar = ""; - break; - } - UsabilityStudyLogUtils.getInstance().write(inputChar + "\t" + x + "\t" + y); - LatinImeLogger.onPrintAllUsabilityStudtyLogs(); - } - - public void write(final String log) { - mLoggingHandler.post(new Runnable() { - @Override - public void run() { - createLogFileIfNotExist(); - final long currentTime = System.currentTimeMillis(); - mDate.setTime(currentTime); - - final String printString = String.format("%s\t%d\t%s\n", - mDateFormat.format(mDate), currentTime, log); - if (LatinImeLogger.sDBG) { - Log.d(TAG, "Write: " + log); - } - mWriter.print(printString); - } - }); - } - - public void printAll() { - mLoggingHandler.post(new Runnable() { - @Override - public void run() { - mWriter.flush(); - StringBuilder sb = new StringBuilder(); - BufferedReader br = getBufferedReader(); - String line; - try { - while ((line = br.readLine()) != null) { - sb.append('\n'); - sb.append(line); - } - } catch (IOException e) { - Log.e(TAG, "Can't read log file."); - } finally { - if (LatinImeLogger.sDBG) { - Log.d(TAG, "output all logs\n" + sb.toString()); - } - mIms.getCurrentInputConnection().commitText(sb.toString(), 0); - try { - br.close(); - } catch (IOException e) { - } - } - } - }); - } - - public void clearAll() { - mLoggingHandler.post(new Runnable() { - @Override - public void run() { - if (mFile != null && mFile.exists()) { - if (LatinImeLogger.sDBG) { - Log.d(TAG, "Delete log file."); - } - mFile.delete(); - mWriter.close(); - } - } - }); - } - - private BufferedReader getBufferedReader() { - createLogFileIfNotExist(); - try { - return new BufferedReader(new FileReader(mFile)); - } catch (FileNotFoundException e) { - return null; - } - } - - private PrintWriter getPrintWriter( - File dir, String filename, boolean renew) throws IOException { - mFile = new File(dir, filename); - if (mFile.exists()) { - if (renew) { - mFile.delete(); - } - } - return new PrintWriter(new FileOutputStream(mFile), true /* autoFlush */); - } - } -} diff --git a/java/src/com/android/inputmethod/latin/Settings.java b/java/src/com/android/inputmethod/latin/Settings.java new file mode 100644 index 000000000..9c7c5aa71 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/Settings.java @@ -0,0 +1,258 @@ +/* + * Copyright (C) 2008 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 com.android.inputmethod.voice.VoiceIMEConnector; +import com.android.inputmethod.voice.VoiceInputLogger; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.backup.BackupManager; +import android.content.DialogInterface; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.Vibrator; +import android.preference.CheckBoxPreference; +import android.preference.ListPreference; +import android.preference.PreferenceActivity; +import android.preference.PreferenceGroup; +import android.speech.SpeechRecognizer; +import android.text.AutoText; +import android.text.TextUtils; +import android.text.method.LinkMovementMethod; +import android.util.Log; +import android.widget.TextView; + +import java.util.Locale; + +public class Settings extends PreferenceActivity + implements SharedPreferences.OnSharedPreferenceChangeListener, + DialogInterface.OnDismissListener { + private static final String TAG = "Settings"; + + public static final String PREF_VIBRATE_ON = "vibrate_on"; + public static final String PREF_SOUND_ON = "sound_on"; + public static final String PREF_POPUP_ON = "popup_on"; + public static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled"; + public static final String PREF_AUTO_CAP = "auto_cap"; + public static final String PREF_SETTINGS_KEY = "settings_key"; + 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_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_BIGRAM_SUGGESTIONS = "bigram_suggestion"; + + // Dialog ids + private static final int VOICE_INPUT_CONFIRM_DIALOG = 0; + + private CheckBoxPreference mQuickFixes; + private ListPreference mVoicePreference; + private ListPreference mSettingsKeyPreference; + private ListPreference mAutoCompletionThreshold; + private CheckBoxPreference mBigramSuggestion; + private boolean mVoiceOn; + + private AlertDialog mDialog; + + private VoiceInputLogger mLogger; + + 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)); + } + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + addPreferencesFromResource(R.xml.prefs); + mQuickFixes = (CheckBoxPreference) findPreference(PREF_QUICK_FIXES); + mVoicePreference = (ListPreference) findPreference(PREF_VOICE_SETTINGS_KEY); + mSettingsKeyPreference = (ListPreference) findPreference(PREF_SETTINGS_KEY); + SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); + prefs.registerOnSharedPreferenceChangeListener(this); + + mVoiceModeOff = getString(R.string.voice_mode_off); + mVoiceOn = !(prefs.getString(PREF_VOICE_SETTINGS_KEY, mVoiceModeOff) + .equals(mVoiceModeOff)); + mLogger = VoiceInputLogger.getLogger(this); + + mAutoCompletionThreshold = (ListPreference) findPreference(PREF_AUTO_COMPLETION_THRESHOLD); + mBigramSuggestion = (CheckBoxPreference) findPreference(PREF_BIGRAM_SUGGESTIONS); + ensureConsistencyOfAutoCompletionSettings(); + + final boolean showSettingsKeyOption = getResources().getBoolean( + R.bool.config_enable_show_settings_key_option); + if (!showSettingsKeyOption) { + getPreferenceScreen().removePreference(mSettingsKeyPreference); + } + + final boolean showVoiceKeyOption = getResources().getBoolean( + R.bool.config_enable_show_voice_key_option); + if (!showVoiceKeyOption) { + getPreferenceScreen().removePreference(mVoicePreference); + } + + Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); + if (vibrator == null || !vibrator.hasVibrator()) { + getPreferenceScreen().removePreference( + getPreferenceScreen().findPreference(PREF_VIBRATE_ON)); + } + } + + @Override + protected void onResume() { + super.onResume(); + int autoTextSize = AutoText.getSize(getListView()); + if (autoTextSize < 1) { + ((PreferenceGroup) findPreference(PREF_PREDICTION_SETTINGS_KEY)) + .removePreference(mQuickFixes); + } + if (!VoiceIMEConnector.VOICE_INSTALLED + || !SpeechRecognizer.isRecognitionAvailable(this)) { + getPreferenceScreen().removePreference(mVoicePreference); + } else { + updateVoiceModeSummary(); + } + updateSettingsKeySummary(); + } + + @Override + protected void onDestroy() { + getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( + this); + super.onDestroy(); + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { + (new BackupManager(this)).dataChanged(); + // If turning on voice input, show dialog + if (key.equals(PREF_VOICE_SETTINGS_KEY) && !mVoiceOn) { + if (!prefs.getString(PREF_VOICE_SETTINGS_KEY, mVoiceModeOff) + .equals(mVoiceModeOff)) { + showVoiceConfirmation(); + } + } + ensureConsistencyOfAutoCompletionSettings(); + mVoiceOn = !(prefs.getString(PREF_VOICE_SETTINGS_KEY, mVoiceModeOff) + .equals(mVoiceModeOff)); + updateVoiceModeSummary(); + updateSettingsKeySummary(); + } + + private void updateSettingsKeySummary() { + mSettingsKeyPreference.setSummary( + getResources().getStringArray(R.array.settings_key_modes) + [mSettingsKeyPreference.findIndexOfValue(mSettingsKeyPreference.getValue())]); + } + + private void showVoiceConfirmation() { + mOkClicked = false; + showDialog(VOICE_INPUT_CONFIRM_DIALOG); + // Make URL in the dialog message clickable + if (mDialog != null) { + TextView textView = (TextView) mDialog.findViewById(android.R.id.message); + if (textView != null) { + textView.setMovementMethod(LinkMovementMethod.getInstance()); + } + } + } + + private void updateVoiceModeSummary() { + mVoicePreference.setSummary( + getResources().getStringArray(R.array.voice_input_modes_summary) + [mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]); + } + + @Override + protected Dialog onCreateDialog(int id) { + switch (id) { + case VOICE_INPUT_CONFIRM_DIALOG: + DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + if (whichButton == DialogInterface.BUTTON_NEGATIVE) { + mVoicePreference.setValue(mVoiceModeOff); + mLogger.settingsWarningDialogCancel(); + } else if (whichButton == DialogInterface.BUTTON_POSITIVE) { + mOkClicked = true; + mLogger.settingsWarningDialogOk(); + } + updateVoicePreference(); + } + }; + AlertDialog.Builder builder = new AlertDialog.Builder(this) + .setTitle(R.string.voice_warning_title) + .setPositiveButton(android.R.string.ok, listener) + .setNegativeButton(android.R.string.cancel, listener); + + // Get the current list of supported locales and check the current locale against + // that list, to decide whether to put a warning that voice input will not work in + // the current language as part of the pop-up confirmation dialog. + boolean localeSupported = SubtypeSwitcher.getInstance().isVoiceSupported( + Locale.getDefault().toString()); + + final CharSequence message; + if (localeSupported) { + message = TextUtils.concat( + getText(R.string.voice_warning_may_not_understand), "\n\n", + getText(R.string.voice_hint_dialog_message)); + } else { + message = TextUtils.concat( + getText(R.string.voice_warning_locale_not_supported), "\n\n", + getText(R.string.voice_warning_may_not_understand), "\n\n", + getText(R.string.voice_hint_dialog_message)); + } + builder.setMessage(message); + AlertDialog dialog = builder.create(); + mDialog = dialog; + dialog.setOnDismissListener(this); + mLogger.settingsWarningDialogShown(); + return dialog; + default: + Log.e(TAG, "unknown dialog " + id); + return null; + } + } + + @Override + public void onDismiss(DialogInterface dialog) { + mLogger.settingsWarningDialogDismissed(); + if (!mOkClicked) { + // This assumes that onPreferenceClick gets called first, and this if the user + // agreed after the warning, we set the mOkClicked value to true. + mVoicePreference.setValue(mVoiceModeOff); + } + } + + private void updateVoicePreference() { + boolean isChecked = !mVoicePreference.getValue().equals(mVoiceModeOff); + if (isChecked) { + mLogger.voiceInputSettingEnabled(); + } else { + mLogger.voiceInputSettingDisabled(); + } + } +} diff --git a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java index 3ee4eb891..b67dd22fd 100644 --- a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java +++ b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java @@ -316,7 +316,7 @@ public class SubtypeSwitcher { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (USE_SPACEBAR_LANGUAGE_SWITCHER) { - if (LatinIME.PREF_SELECTED_LANGUAGES.equals(key)) { + if (Settings.PREF_SELECTED_LANGUAGES.equals(key)) { mLanguageSwitcher.loadLocales(sharedPreferences); } } diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java index 2f188879c..a6df187e6 100644 --- a/java/src/com/android/inputmethod/latin/Suggest.java +++ b/java/src/com/android/inputmethod/latin/Suggest.java @@ -284,7 +284,7 @@ public class Suggest implements Dictionary.WordCallback { && mSuggestions.size() > 0 && mPriorities.length > 0) { // 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 = LatinIMEUtil.calcNormalizedScore( + final double normalizedScore = Utils.calcNormalizedScore( mOriginalWord, mSuggestions.get(0), mPriorities[0]); if (LatinImeLogger.sDBG) { Log.d(TAG, "Normalized " + mOriginalWord + "," + mSuggestions.get(0) + "," diff --git a/java/src/com/android/inputmethod/latin/Utils.java b/java/src/com/android/inputmethod/latin/Utils.java new file mode 100644 index 000000000..0a73dde08 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/Utils.java @@ -0,0 +1,393 @@ +/* + * 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.inputmethodservice.InputMethodService; +import android.os.AsyncTask; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Process; +import android.text.format.DateUtils; +import android.util.Log; +import android.view.inputmethod.InputMethodManager; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class Utils { + + /** + * Cancel an {@link AsyncTask}. + * + * @param mayInterruptIfRunning true if the thread executing this + * task should be interrupted; otherwise, in-progress tasks are allowed + * to complete. + */ + public static void cancelTask(AsyncTask task, boolean mayInterruptIfRunning) { + if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) { + task.cancel(mayInterruptIfRunning); + } + } + + public static class GCUtils { + private static final String TAG = "GCUtils"; + public static final int GC_TRY_COUNT = 2; + // GC_TRY_LOOP_MAX is used for the hard limit of GC wait, + // GC_TRY_LOOP_MAX should be greater than GC_TRY_COUNT. + public static final int GC_TRY_LOOP_MAX = 5; + private static final long GC_INTERVAL = DateUtils.SECOND_IN_MILLIS; + private static GCUtils sInstance = new GCUtils(); + private int mGCTryCount = 0; + + public static GCUtils getInstance() { + return sInstance; + } + + public void reset() { + mGCTryCount = 0; + } + + public boolean tryGCOrWait(String metaData, Throwable t) { + if (mGCTryCount == 0) { + System.gc(); + } + if (++mGCTryCount > GC_TRY_COUNT) { + LatinImeLogger.logOnException(metaData, t); + return false; + } else { + try { + Thread.sleep(GC_INTERVAL); + return true; + } catch (InterruptedException e) { + Log.e(TAG, "Sleep was interrupted."); + LatinImeLogger.logOnException(metaData, t); + return false; + } + } + } + } + + public static boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm) { + return imm.getEnabledInputMethodList().size() > 1 + // imm.getEnabledInputMethodSubtypeList(null) will return the current IME's enabled input + // method subtype (The current IME should be LatinIME.) + || imm.getEnabledInputMethodSubtypeList(null).size() > 1; + } + + /* package */ static class RingCharBuffer { + private static RingCharBuffer sRingCharBuffer = new RingCharBuffer(); + private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC'; + private static final int INVALID_COORDINATE = -2; + /* package */ static final int BUFSIZE = 20; + private InputMethodService mContext; + private boolean mEnabled = false; + private boolean mUsabilityStudy = false; + private int mEnd = 0; + /* package */ int mLength = 0; + private char[] mCharBuf = new char[BUFSIZE]; + private int[] mXBuf = new int[BUFSIZE]; + private int[] mYBuf = new int[BUFSIZE]; + + private RingCharBuffer() { + } + public static RingCharBuffer getInstance() { + return sRingCharBuffer; + } + public static RingCharBuffer init(InputMethodService context, boolean enabled, + boolean usabilityStudy) { + sRingCharBuffer.mContext = context; + sRingCharBuffer.mEnabled = enabled || usabilityStudy; + sRingCharBuffer.mUsabilityStudy = usabilityStudy; + UsabilityStudyLogUtils.getInstance().init(context); + return sRingCharBuffer; + } + private int normalize(int in) { + int ret = in % BUFSIZE; + return ret < 0 ? ret + BUFSIZE : ret; + } + public void push(char c, int x, int y) { + if (!mEnabled) return; + if (mUsabilityStudy) { + UsabilityStudyLogUtils.getInstance().writeChar(c, x, y); + } + mCharBuf[mEnd] = c; + mXBuf[mEnd] = x; + mYBuf[mEnd] = y; + mEnd = normalize(mEnd + 1); + if (mLength < BUFSIZE) { + ++mLength; + } + } + public char pop() { + if (mLength < 1) { + return PLACEHOLDER_DELIMITER_CHAR; + } else { + mEnd = normalize(mEnd - 1); + --mLength; + return mCharBuf[mEnd]; + } + } + public char getLastChar() { + if (mLength < 1) { + return PLACEHOLDER_DELIMITER_CHAR; + } else { + return mCharBuf[normalize(mEnd - 1)]; + } + } + public int getPreviousX(char c, int back) { + int index = normalize(mEnd - 2 - back); + if (mLength <= back + || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { + return INVALID_COORDINATE; + } else { + return mXBuf[index]; + } + } + public int getPreviousY(char c, int back) { + int index = normalize(mEnd - 2 - back); + if (mLength <= back + || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { + return INVALID_COORDINATE; + } else { + return mYBuf[index]; + } + } + public String getLastString() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mLength; ++i) { + char c = mCharBuf[normalize(mEnd - 1 - i)]; + if (!((LatinIME)mContext).isWordSeparator(c)) { + sb.append(c); + } else { + break; + } + } + return sb.reverse().toString(); + } + public void reset() { + mLength = 0; + } + } + + public static int editDistance(CharSequence s, CharSequence t) { + if (s == null || t == null) { + throw new IllegalArgumentException("editDistance: Arguments should not be null."); + } + final int sl = s.length(); + final int tl = t.length(); + int[][] dp = new int [sl + 1][tl + 1]; + for (int i = 0; i <= sl; i++) { + dp[i][0] = i; + } + for (int j = 0; j <= tl; j++) { + dp[0][j] = j; + } + for (int i = 0; i < sl; ++i) { + for (int j = 0; j < tl; ++j) { + if (s.charAt(i) == t.charAt(j)) { + dp[i + 1][j + 1] = dp[i][j]; + } else { + dp[i + 1][j + 1] = 1 + Math.min(dp[i][j], + Math.min(dp[i + 1][j], dp[i][j + 1])); + } + } + } + return dp[sl][tl]; + } + + // In dictionary.cpp, getSuggestion() method, + // suggestion scores are computed using the below formula. + // original score (called 'frequency') + // := pow(mTypedLetterMultiplier (this is defined 2), + // (the number of matched characters between typed word and suggested word)) + // * (individual word's score which defined in the unigram dictionary, + // and this score is defined in range [0, 255].) + // * (when before.length() == after.length(), + // mFullWordMultiplier (this is defined 2)) + // So, maximum original score is pow(2, before.length()) * 255 * 2 + // So, we can normalize original score by dividing this value. + private static final int MAX_INITIAL_SCORE = 255; + private static final int TYPED_LETTER_MULTIPLIER = 2; + private static final int FULL_WORD_MULTIPLYER = 2; + public static double calcNormalizedScore(CharSequence before, CharSequence after, int score) { + final int beforeLength = before.length(); + final int afterLength = after.length(); + final int distance = editDistance(before, after); + final double maximumScore = MAX_INITIAL_SCORE + * Math.pow(TYPED_LETTER_MULTIPLIER, beforeLength) + * FULL_WORD_MULTIPLYER; + // add a weight based on edit distance. + // distance <= max(afterLength, beforeLength) == afterLength, + // so, 0 <= distance / afterLength <= 1 + final double weight = 1.0 - (double) distance / afterLength; + return (score / maximumScore) * weight; + } + + public static class UsabilityStudyLogUtils { + private static final String TAG = "UsabilityStudyLogUtils"; + private static final String FILENAME = "log.txt"; + private static final UsabilityStudyLogUtils sInstance = + new UsabilityStudyLogUtils(); + private final Handler mLoggingHandler; + private File mFile; + private File mDirectory; + private InputMethodService mIms; + private PrintWriter mWriter; + private final Date mDate; + private final SimpleDateFormat mDateFormat; + + private UsabilityStudyLogUtils() { + mDate = new Date(); + mDateFormat = new SimpleDateFormat("dd MMM HH:mm:ss.SSS"); + + HandlerThread handlerThread = new HandlerThread("UsabilityStudyLogUtils logging task", + Process.THREAD_PRIORITY_BACKGROUND); + handlerThread.start(); + mLoggingHandler = new Handler(handlerThread.getLooper()); + } + + public static UsabilityStudyLogUtils getInstance() { + return sInstance; + } + + public void init(InputMethodService ims) { + mIms = ims; + mDirectory = ims.getFilesDir(); + } + + private void createLogFileIfNotExist() { + if ((mFile == null || !mFile.exists()) + && (mDirectory != null && mDirectory.exists())) { + try { + mWriter = getPrintWriter(mDirectory, FILENAME, false); + } catch (IOException e) { + Log.e(TAG, "Can't create log file."); + } + } + } + + public void writeBackSpace() { + UsabilityStudyLogUtils.getInstance().write("\t0\t0"); + } + + public void writeChar(char c, int x, int y) { + String inputChar = String.valueOf(c); + switch (c) { + case '\n': + inputChar = ""; + break; + case '\t': + inputChar = ""; + break; + case ' ': + inputChar = ""; + break; + } + UsabilityStudyLogUtils.getInstance().write(inputChar + "\t" + x + "\t" + y); + LatinImeLogger.onPrintAllUsabilityStudtyLogs(); + } + + public void write(final String log) { + mLoggingHandler.post(new Runnable() { + @Override + public void run() { + createLogFileIfNotExist(); + final long currentTime = System.currentTimeMillis(); + mDate.setTime(currentTime); + + final String printString = String.format("%s\t%d\t%s\n", + mDateFormat.format(mDate), currentTime, log); + if (LatinImeLogger.sDBG) { + Log.d(TAG, "Write: " + log); + } + mWriter.print(printString); + } + }); + } + + public void printAll() { + mLoggingHandler.post(new Runnable() { + @Override + public void run() { + mWriter.flush(); + StringBuilder sb = new StringBuilder(); + BufferedReader br = getBufferedReader(); + String line; + try { + while ((line = br.readLine()) != null) { + sb.append('\n'); + sb.append(line); + } + } catch (IOException e) { + Log.e(TAG, "Can't read log file."); + } finally { + if (LatinImeLogger.sDBG) { + Log.d(TAG, "output all logs\n" + sb.toString()); + } + mIms.getCurrentInputConnection().commitText(sb.toString(), 0); + try { + br.close(); + } catch (IOException e) { + } + } + } + }); + } + + public void clearAll() { + mLoggingHandler.post(new Runnable() { + @Override + public void run() { + if (mFile != null && mFile.exists()) { + if (LatinImeLogger.sDBG) { + Log.d(TAG, "Delete log file."); + } + mFile.delete(); + mWriter.close(); + } + } + }); + } + + private BufferedReader getBufferedReader() { + createLogFileIfNotExist(); + try { + return new BufferedReader(new FileReader(mFile)); + } catch (FileNotFoundException e) { + return null; + } + } + + private PrintWriter getPrintWriter( + File dir, String filename, boolean renew) throws IOException { + mFile = new File(dir, filename); + if (mFile.exists()) { + if (renew) { + mFile.delete(); + } + } + return new PrintWriter(new FileOutputStream(mFile), true /* autoFlush */); + } + } +} -- cgit v1.2.3-83-g751a