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