Settings.java revision 6bb6d30344259b41387f15f0e05df2388beb1d1c
1/* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.inputmethod.latin.settings; 18 19import android.content.Context; 20import android.content.SharedPreferences; 21import android.content.pm.ApplicationInfo; 22import android.content.res.Configuration; 23import android.content.res.Resources; 24import android.os.Build; 25import android.preference.PreferenceManager; 26import android.util.Log; 27 28import com.android.inputmethod.compat.BuildCompatUtils; 29import com.android.inputmethod.latin.AudioAndHapticFeedbackManager; 30import com.android.inputmethod.latin.InputAttributes; 31import com.android.inputmethod.latin.R; 32import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; 33import com.android.inputmethod.latin.utils.ResourceUtils; 34import com.android.inputmethod.latin.utils.RunInLocale; 35import com.android.inputmethod.latin.utils.StringUtils; 36 37import java.util.Collections; 38import java.util.Locale; 39import java.util.Set; 40import java.util.concurrent.locks.ReentrantLock; 41 42public final class Settings implements SharedPreferences.OnSharedPreferenceChangeListener { 43 private static final String TAG = Settings.class.getSimpleName(); 44 // Settings screens 45 public static final String SCREEN_INPUT = "screen_input"; 46 public static final String SCREEN_THEME = "screen_theme"; 47 public static final String SCREEN_MULTI_LINGUAL = "screen_multi_lingual"; 48 public static final String SCREEN_GESTURE = "screen_gesture"; 49 public static final String SCREEN_CORRECTION = "screen_correction"; 50 public static final String SCREEN_ADVANCED = "screen_advanced"; 51 public static final String SCREEN_DEBUG = "screen_debug"; 52 // In the same order as xml/prefs.xml 53 public static final String PREF_AUTO_CAP = "auto_cap"; 54 public static final String PREF_VIBRATE_ON = "vibrate_on"; 55 public static final String PREF_SOUND_ON = "sound_on"; 56 public static final String PREF_POPUP_ON = "popup_on"; 57 // PREF_VOICE_MODE_OBSOLETE is obsolete. Use PREF_VOICE_INPUT_KEY instead. 58 public static final String PREF_VOICE_MODE_OBSOLETE = "voice_mode"; 59 public static final String PREF_VOICE_INPUT_KEY = "pref_voice_input_key"; 60 public static final String PREF_EDIT_PERSONAL_DICTIONARY = "edit_personal_dictionary"; 61 public static final String PREF_CONFIGURE_DICTIONARIES_KEY = "configure_dictionaries_key"; 62 public static final String PREF_AUTO_CORRECTION_THRESHOLD = "auto_correction_threshold"; 63 // PREF_SHOW_SUGGESTIONS_SETTING_OBSOLETE is obsolete. Use PREF_SHOW_SUGGESTIONS instead. 64 public static final String PREF_SHOW_SUGGESTIONS_SETTING_OBSOLETE = "show_suggestions_setting"; 65 public static final String PREF_SHOW_SUGGESTIONS = "show_suggestions"; 66 public static final String PREF_KEY_USE_CONTACTS_DICT = "pref_key_use_contacts_dict"; 67 public static final String PREF_KEY_USE_PERSONALIZED_DICTS = "pref_key_use_personalized_dicts"; 68 public static final String PREF_KEY_USE_DOUBLE_SPACE_PERIOD = 69 "pref_key_use_double_space_period"; 70 public static final String PREF_BLOCK_POTENTIALLY_OFFENSIVE = 71 "pref_key_block_potentially_offensive"; 72 public static final boolean ENABLE_SHOW_LANGUAGE_SWITCH_KEY_SETTINGS = 73 BuildCompatUtils.EFFECTIVE_SDK_INT <= Build.VERSION_CODES.KITKAT; 74 public static final boolean HAS_UI_TO_ACCEPT_TYPED_WORD = 75 BuildCompatUtils.EFFECTIVE_SDK_INT >= BuildCompatUtils.VERSION_CODES_LXX; 76 public static final String PREF_SHOW_LANGUAGE_SWITCH_KEY = 77 "pref_show_language_switch_key"; 78 public static final String PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST = 79 "pref_include_other_imes_in_language_switch_list"; 80 public static final String PREF_KEYBOARD_THEME = "pref_keyboard_theme"; 81 public static final String PREF_CUSTOM_INPUT_STYLES = "custom_input_styles"; 82 // TODO: consolidate key preview dismiss delay with the key preview animation parameters. 83 public static final String PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY = 84 "pref_key_preview_popup_dismiss_delay"; 85 public static final String PREF_BIGRAM_PREDICTIONS = "next_word_prediction"; 86 public static final String PREF_GESTURE_INPUT = "gesture_input"; 87 public static final String PREF_VIBRATION_DURATION_SETTINGS = 88 "pref_vibration_duration_settings"; 89 public static final String PREF_KEYPRESS_SOUND_VOLUME = 90 "pref_keypress_sound_volume"; 91 public static final String PREF_GESTURE_PREVIEW_TRAIL = "pref_gesture_preview_trail"; 92 public static final String PREF_GESTURE_FLOATING_PREVIEW_TEXT = 93 "pref_gesture_floating_preview_text"; 94 public static final String PREF_SHOW_SETUP_WIZARD_ICON = "pref_show_setup_wizard_icon"; 95 public static final String PREF_PHRASE_GESTURE_ENABLED = "pref_gesture_space_aware"; 96 97 public static final String PREF_INPUT_LANGUAGE = "input_language"; 98 public static final String PREF_SELECTED_LANGUAGES = "selected_languages"; 99 public static final String PREF_KEY_IS_INTERNAL = "pref_key_is_internal"; 100 101 public static final String PREF_ENABLE_METRICS_LOGGING = "pref_enable_metrics_logging"; 102 103 // This preference key is deprecated. Use {@link #PREF_SHOW_LANGUAGE_SWITCH_KEY} instead. 104 // This is being used only for the backward compatibility. 105 private static final String PREF_SUPPRESS_LANGUAGE_SWITCH_KEY = 106 "pref_suppress_language_switch_key"; 107 108 private static final String PREF_LAST_USED_PERSONALIZATION_TOKEN = 109 "pref_last_used_personalization_token"; 110 private static final String PREF_LAST_PERSONALIZATION_DICT_WIPED_TIME = 111 "pref_last_used_personalization_dict_wiped_time"; 112 private static final String PREF_CORPUS_HANDLES_FOR_PERSONALIZATION = 113 "pref_corpus_handles_for_personalization"; 114 115 // Emoji 116 public static final String PREF_EMOJI_RECENT_KEYS = "emoji_recent_keys"; 117 public static final String PREF_EMOJI_CATEGORY_LAST_TYPED_ID = "emoji_category_last_typed_id"; 118 public static final String PREF_LAST_SHOWN_EMOJI_CATEGORY_ID = "last_shown_emoji_category_id"; 119 120 private static final float UNDEFINED_PREFERENCE_VALUE_FLOAT = -1.0f; 121 private static final int UNDEFINED_PREFERENCE_VALUE_INT = -1; 122 123 private Context mContext; 124 private Resources mRes; 125 private SharedPreferences mPrefs; 126 private SettingsValues mSettingsValues; 127 private final ReentrantLock mSettingsValuesLock = new ReentrantLock(); 128 129 private static final Settings sInstance = new Settings(); 130 131 public static Settings getInstance() { 132 return sInstance; 133 } 134 135 public static void init(final Context context) { 136 sInstance.onCreate(context); 137 } 138 139 private Settings() { 140 // Intentional empty constructor for singleton. 141 } 142 143 private void onCreate(final Context context) { 144 mContext = context; 145 mRes = context.getResources(); 146 mPrefs = PreferenceManager.getDefaultSharedPreferences(context); 147 mPrefs.registerOnSharedPreferenceChangeListener(this); 148 } 149 150 public void onDestroy() { 151 mPrefs.unregisterOnSharedPreferenceChangeListener(this); 152 } 153 154 @Override 155 public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) { 156 mSettingsValuesLock.lock(); 157 try { 158 if (mSettingsValues == null) { 159 // TODO: Introduce a static function to register this class and ensure that 160 // loadSettings must be called before "onSharedPreferenceChanged" is called. 161 Log.w(TAG, "onSharedPreferenceChanged called before loadSettings."); 162 return; 163 } 164 loadSettings(mContext, mSettingsValues.mLocale, mSettingsValues.mInputAttributes); 165 } finally { 166 mSettingsValuesLock.unlock(); 167 } 168 } 169 170 public void loadSettings(final Context context, final Locale locale, 171 final InputAttributes inputAttributes) { 172 mSettingsValuesLock.lock(); 173 mContext = context; 174 try { 175 final SharedPreferences prefs = mPrefs; 176 final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() { 177 @Override 178 protected SettingsValues job(final Resources res) { 179 return new SettingsValues(context, prefs, res, inputAttributes); 180 } 181 }; 182 mSettingsValues = job.runInLocale(mRes, locale); 183 } finally { 184 mSettingsValuesLock.unlock(); 185 } 186 } 187 188 // TODO: Remove this method and add proxy method to SettingsValues. 189 public SettingsValues getCurrent() { 190 return mSettingsValues; 191 } 192 193 public boolean isInternal() { 194 return mSettingsValues.mIsInternal; 195 } 196 197 public boolean isWordSeparator(final int code) { 198 return mSettingsValues.isWordSeparator(code); 199 } 200 201 public boolean getBlockPotentiallyOffensive() { 202 return mSettingsValues.mBlockPotentiallyOffensive; 203 } 204 205 // Accessed from the settings interface, hence public 206 public static boolean readKeypressSoundEnabled(final SharedPreferences prefs, 207 final Resources res) { 208 return prefs.getBoolean(PREF_SOUND_ON, 209 res.getBoolean(R.bool.config_default_sound_enabled)); 210 } 211 212 public static boolean readVibrationEnabled(final SharedPreferences prefs, 213 final Resources res) { 214 final boolean hasVibrator = AudioAndHapticFeedbackManager.getInstance().hasVibrator(); 215 return hasVibrator && prefs.getBoolean(PREF_VIBRATE_ON, 216 res.getBoolean(R.bool.config_default_vibration_enabled)); 217 } 218 219 public static boolean readAutoCorrectEnabled(final String currentAutoCorrectionSetting, 220 final Resources res) { 221 final String autoCorrectionOff = res.getString( 222 R.string.auto_correction_threshold_mode_index_off); 223 return !currentAutoCorrectionSetting.equals(autoCorrectionOff); 224 } 225 226 public static boolean readBlockPotentiallyOffensive(final SharedPreferences prefs, 227 final Resources res) { 228 return prefs.getBoolean(PREF_BLOCK_POTENTIALLY_OFFENSIVE, 229 res.getBoolean(R.bool.config_block_potentially_offensive)); 230 } 231 232 public static boolean readFromBuildConfigIfGestureInputEnabled(final Resources res) { 233 return res.getBoolean(R.bool.config_gesture_input_enabled_by_build_config); 234 } 235 236 public static boolean readGestureInputEnabled(final SharedPreferences prefs, 237 final Resources res) { 238 return readFromBuildConfigIfGestureInputEnabled(res) 239 && prefs.getBoolean(PREF_GESTURE_INPUT, true); 240 } 241 242 public static boolean readPhraseGestureEnabled(final SharedPreferences prefs, 243 final Resources res) { 244 return prefs.getBoolean(PREF_PHRASE_GESTURE_ENABLED, 245 res.getBoolean(R.bool.config_default_phrase_gesture_enabled)); 246 } 247 248 public static boolean readFromBuildConfigIfToShowKeyPreviewPopupOption(final Resources res) { 249 return res.getBoolean(R.bool.config_enable_show_key_preview_popup_option); 250 } 251 252 public static boolean readKeyPreviewPopupEnabled(final SharedPreferences prefs, 253 final Resources res) { 254 final boolean defaultKeyPreviewPopup = res.getBoolean( 255 R.bool.config_default_key_preview_popup); 256 if (!readFromBuildConfigIfToShowKeyPreviewPopupOption(res)) { 257 return defaultKeyPreviewPopup; 258 } 259 return prefs.getBoolean(PREF_POPUP_ON, defaultKeyPreviewPopup); 260 } 261 262 public static int readKeyPreviewPopupDismissDelay(final SharedPreferences prefs, 263 final Resources res) { 264 return Integer.parseInt(prefs.getString(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY, 265 Integer.toString(res.getInteger( 266 R.integer.config_key_preview_linger_timeout)))); 267 } 268 269 public static boolean readShowsLanguageSwitchKey(final SharedPreferences prefs) { 270 if (prefs.contains(PREF_SUPPRESS_LANGUAGE_SWITCH_KEY)) { 271 final boolean suppressLanguageSwitchKey = prefs.getBoolean( 272 PREF_SUPPRESS_LANGUAGE_SWITCH_KEY, false); 273 final SharedPreferences.Editor editor = prefs.edit(); 274 editor.remove(PREF_SUPPRESS_LANGUAGE_SWITCH_KEY); 275 editor.putBoolean(PREF_SHOW_LANGUAGE_SWITCH_KEY, !suppressLanguageSwitchKey); 276 editor.apply(); 277 } 278 return prefs.getBoolean(PREF_SHOW_LANGUAGE_SWITCH_KEY, true); 279 } 280 281 public static String readPrefAdditionalSubtypes(final SharedPreferences prefs, 282 final Resources res) { 283 final String predefinedPrefSubtypes = AdditionalSubtypeUtils.createPrefSubtypes( 284 res.getStringArray(R.array.predefined_subtypes)); 285 return prefs.getString(PREF_CUSTOM_INPUT_STYLES, predefinedPrefSubtypes); 286 } 287 288 public static void writePrefAdditionalSubtypes(final SharedPreferences prefs, 289 final String prefSubtypes) { 290 prefs.edit().putString(PREF_CUSTOM_INPUT_STYLES, prefSubtypes).apply(); 291 } 292 293 public static float readKeypressSoundVolume(final SharedPreferences prefs, 294 final Resources res) { 295 final float volume = prefs.getFloat( 296 PREF_KEYPRESS_SOUND_VOLUME, UNDEFINED_PREFERENCE_VALUE_FLOAT); 297 return (volume != UNDEFINED_PREFERENCE_VALUE_FLOAT) ? volume 298 : readDefaultKeypressSoundVolume(res); 299 } 300 301 // Default keypress sound volume for unknown devices. 302 // The negative value means system default. 303 private static final String DEFAULT_KEYPRESS_SOUND_VOLUME = Float.toString(-1.0f); 304 305 public static float readDefaultKeypressSoundVolume(final Resources res) { 306 return Float.parseFloat(ResourceUtils.getDeviceOverrideValue(res, 307 R.array.keypress_volumes, DEFAULT_KEYPRESS_SOUND_VOLUME)); 308 } 309 310 public static int readKeyLongpressTimeout(final SharedPreferences prefs, 311 final Resources res) { 312 final int milliseconds = prefs.getInt( 313 DebugSettings.PREF_KEY_LONGPRESS_TIMEOUT, UNDEFINED_PREFERENCE_VALUE_INT); 314 return (milliseconds != UNDEFINED_PREFERENCE_VALUE_INT) ? milliseconds 315 : readDefaultKeyLongpressTimeout(res); 316 } 317 318 public static int readDefaultKeyLongpressTimeout(final Resources res) { 319 return res.getInteger(R.integer.config_default_longpress_key_timeout); 320 } 321 322 public static int readKeypressVibrationDuration(final SharedPreferences prefs, 323 final Resources res) { 324 final int milliseconds = prefs.getInt( 325 PREF_VIBRATION_DURATION_SETTINGS, UNDEFINED_PREFERENCE_VALUE_INT); 326 return (milliseconds != UNDEFINED_PREFERENCE_VALUE_INT) ? milliseconds 327 : readDefaultKeypressVibrationDuration(res); 328 } 329 330 // Default keypress vibration duration for unknown devices. 331 // The negative value means system default. 332 private static final String DEFAULT_KEYPRESS_VIBRATION_DURATION = Integer.toString(-1); 333 334 public static int readDefaultKeypressVibrationDuration(final Resources res) { 335 return Integer.parseInt(ResourceUtils.getDeviceOverrideValue(res, 336 R.array.keypress_vibration_durations, DEFAULT_KEYPRESS_VIBRATION_DURATION)); 337 } 338 339 public static float readKeyPreviewAnimationScale(final SharedPreferences prefs, 340 final String prefKey, final float defaultValue) { 341 final float fraction = prefs.getFloat(prefKey, UNDEFINED_PREFERENCE_VALUE_FLOAT); 342 return (fraction != UNDEFINED_PREFERENCE_VALUE_FLOAT) ? fraction : defaultValue; 343 } 344 345 public static int readKeyPreviewAnimationDuration(final SharedPreferences prefs, 346 final String prefKey, final int defaultValue) { 347 final int milliseconds = prefs.getInt(prefKey, UNDEFINED_PREFERENCE_VALUE_INT); 348 return (milliseconds != UNDEFINED_PREFERENCE_VALUE_INT) ? milliseconds : defaultValue; 349 } 350 351 public static boolean readUseFullscreenMode(final Resources res) { 352 return res.getBoolean(R.bool.config_use_fullscreen_mode); 353 } 354 355 public static boolean readShowSetupWizardIcon(final SharedPreferences prefs, 356 final Context context) { 357 final boolean enableSetupWizardByConfig = context.getResources().getBoolean( 358 R.bool.config_setup_wizard_available); 359 if (!enableSetupWizardByConfig) { 360 return false; 361 } 362 if (!prefs.contains(PREF_SHOW_SETUP_WIZARD_ICON)) { 363 final ApplicationInfo appInfo = context.getApplicationInfo(); 364 final boolean isApplicationInSystemImage = 365 (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 366 // Default value 367 return !isApplicationInSystemImage; 368 } 369 return prefs.getBoolean(PREF_SHOW_SETUP_WIZARD_ICON, false); 370 } 371 372 public static boolean readHasHardwareKeyboard(final Configuration conf) { 373 // The standard way of finding out whether we have a hardware keyboard. This code is taken 374 // from InputMethodService#onEvaluateInputShown, which canonically determines this. 375 // In a nutshell, we have a keyboard if the configuration says the type of hardware keyboard 376 // is NOKEYS and if it's not hidden (e.g. folded inside the device). 377 return conf.keyboard != Configuration.KEYBOARD_NOKEYS 378 && conf.hardKeyboardHidden != Configuration.HARDKEYBOARDHIDDEN_YES; 379 } 380 381 public static boolean isInternal(final SharedPreferences prefs) { 382 return prefs.getBoolean(PREF_KEY_IS_INTERNAL, false); 383 } 384 385 public void writeLastUsedPersonalizationToken(byte[] token) { 386 if (token == null) { 387 mPrefs.edit().remove(PREF_LAST_USED_PERSONALIZATION_TOKEN).apply(); 388 } else { 389 final String tokenStr = StringUtils.byteArrayToHexString(token); 390 mPrefs.edit().putString(PREF_LAST_USED_PERSONALIZATION_TOKEN, tokenStr).apply(); 391 } 392 } 393 394 public byte[] readLastUsedPersonalizationToken() { 395 final String tokenStr = mPrefs.getString(PREF_LAST_USED_PERSONALIZATION_TOKEN, null); 396 return StringUtils.hexStringToByteArray(tokenStr); 397 } 398 399 public void writeLastPersonalizationDictWipedTime(final long timestamp) { 400 mPrefs.edit().putLong(PREF_LAST_PERSONALIZATION_DICT_WIPED_TIME, timestamp).apply(); 401 } 402 403 public long readLastPersonalizationDictGeneratedTime() { 404 return mPrefs.getLong(PREF_LAST_PERSONALIZATION_DICT_WIPED_TIME, 0); 405 } 406 407 public void writeCorpusHandlesForPersonalization(final Set<String> corpusHandles) { 408 mPrefs.edit().putStringSet(PREF_CORPUS_HANDLES_FOR_PERSONALIZATION, corpusHandles).apply(); 409 } 410 411 public Set<String> readCorpusHandlesForPersonalization() { 412 final Set<String> emptySet = Collections.emptySet(); 413 return mPrefs.getStringSet(PREF_CORPUS_HANDLES_FOR_PERSONALIZATION, emptySet); 414 } 415 416 public static void writeEmojiRecentKeys(final SharedPreferences prefs, String str) { 417 prefs.edit().putString(PREF_EMOJI_RECENT_KEYS, str).apply(); 418 } 419 420 public static String readEmojiRecentKeys(final SharedPreferences prefs) { 421 return prefs.getString(PREF_EMOJI_RECENT_KEYS, ""); 422 } 423 424 public static void writeLastTypedEmojiCategoryPageId( 425 final SharedPreferences prefs, final int categoryId, final int categoryPageId) { 426 final String key = PREF_EMOJI_CATEGORY_LAST_TYPED_ID + categoryId; 427 prefs.edit().putInt(key, categoryPageId).apply(); 428 } 429 430 public static int readLastTypedEmojiCategoryPageId( 431 final SharedPreferences prefs, final int categoryId) { 432 final String key = PREF_EMOJI_CATEGORY_LAST_TYPED_ID + categoryId; 433 return prefs.getInt(key, 0); 434 } 435 436 public static void writeLastShownEmojiCategoryId( 437 final SharedPreferences prefs, final int categoryId) { 438 prefs.edit().putInt(PREF_LAST_SHOWN_EMOJI_CATEGORY_ID, categoryId).apply(); 439 } 440 441 public static int readLastShownEmojiCategoryId( 442 final SharedPreferences prefs, final int defValue) { 443 return prefs.getInt(PREF_LAST_SHOWN_EMOJI_CATEGORY_ID, defValue); 444 } 445} 446