Skip to content

Commit

Permalink
refactor(data): refactor AppPrefs ...
Browse files Browse the repository at this point in the history
- remove cache layer to directly read and edit sharedpreferences to avoid delay
- adjust the assignment to some variables to make them easier to use (hopefully)
- rename some variables to make them easier to understand what them do
- refactor other related parts to adapt to these changes
  • Loading branch information
WhiredPlanck committed Nov 11, 2022
1 parent cb4ab69 commit da4f6ab
Show file tree
Hide file tree
Showing 12 changed files with 49 additions and 180 deletions.
7 changes: 5 additions & 2 deletions app/src/main/java/com/osfans/trime/TrimeApplication.kt
Expand Up @@ -2,6 +2,7 @@ package com.osfans.trime

import android.app.Application
import android.os.Process
import androidx.preference.PreferenceManager
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.osfans.trime.data.AppPrefs
import com.osfans.trime.data.db.CollectionHelper
Expand Down Expand Up @@ -39,8 +40,10 @@ class TrimeApplication : Application() {
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
val prefs = AppPrefs.initDefault(this)
prefs.initDefaultPreferences()
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
AppPrefs.initDefault(sharedPreferences).apply {
initDefaultPreferences()
}
// record last pid for crash logs
val appPrefs = AppPrefs.defaultInstance()
val currentPid = Process.myPid()
Expand Down
23 changes: 10 additions & 13 deletions app/src/main/java/com/osfans/trime/core/Rime.java
Expand Up @@ -195,6 +195,7 @@ public RimeCandidate[] getCandidates() {
candidates[i].text = states.get(value).toString();

String kRightArrow = "→ ";
final boolean showSwitchArrow = getAppPrefs().getKeyboard().getSwitchArrowEnabled();
if (showSwitchArrow)
candidates[i].comment =
o.containsKey("options") ? "" : kRightArrow + states.get(1 - value).toString();
Expand Down Expand Up @@ -257,6 +258,12 @@ public void toggleOption(int i) {
System.loadLibrary("rime_jni");
}

@NonNull
private static AppPrefs getAppPrefs() {
return AppPrefs.defaultInstance();
}
;

/*
Android SDK包含了如下6个修饰键的状态,其中function键会被trime消费掉,因此只处理5个键
Android和librime对按键命名并不一致。读取可能有误。librime按键命名见如下链接,
Expand All @@ -269,16 +276,6 @@ public void toggleOption(int i) {
public static int META_META_ON = get_modifier_by_name("Meta");

public static int META_RELEASE_ON = get_modifier_by_name("Release");
private static boolean showSwitches = true;
private static boolean showSwitchArrow = false;

public static void setShowSwitches(boolean show) {
showSwitches = show;
}

public static void setShowSwitchArrow(boolean show) {
showSwitchArrow = show;
}

public static boolean hasMenu() {
return isComposing() && mContext.menu.num_candidates != 0;
Expand Down Expand Up @@ -373,9 +370,8 @@ private static void init(boolean full_check) {
"\t<TrimeInit>\t" + Thread.currentThread().getStackTrace()[2].getMethodName() + "\t";
Timber.d(methodName);
mOnMessage = false;
final AppPrefs appPrefs = AppPrefs.defaultInstance();
final String sharedDataDir = appPrefs.getProfile().getSharedDataDir();
final String userDataDir = appPrefs.getProfile().getUserDataDir();
final String sharedDataDir = getAppPrefs().getProfile().getSharedDataDir();
final String userDataDir = getAppPrefs().getProfile().getUserDataDir();

Timber.d(methodName + "setup");
// Initialize librime APIs
Expand Down Expand Up @@ -461,6 +457,7 @@ public static boolean onText(CharSequence text) {
}

public static RimeCandidate[] getCandidates() {
final boolean showSwitches = getAppPrefs().getKeyboard().getSwitchesEnabled();
if (!isComposing() && showSwitches) return mSchema.getCandidates();
return mContext.getCandidates();
}
Expand Down
91 changes: 21 additions & 70 deletions app/src/main/java/com/osfans/trime/data/AppPrefs.kt
Expand Up @@ -2,79 +2,43 @@ package com.osfans.trime.data

import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import androidx.core.os.UserManagerCompat
import androidx.preference.PreferenceManager
import com.blankj.utilcode.util.PathUtils
import com.osfans.trime.R
import com.osfans.trime.ime.enums.InlineModeType
import com.osfans.trime.ime.landscapeinput.LandscapeInputUIMode
import com.osfans.trime.util.appContext
import java.lang.ref.WeakReference

/**
* Helper class for an organized access to the shared preferences.
*/
class AppPrefs(
context: Context
private val shared : SharedPreferences
) {
var shared: SharedPreferences = if (!UserManagerCompat.isUserUnlocked(context) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
context.createDeviceProtectedStorageContext().getSharedPreferences("shared_prefs", Context.MODE_PRIVATE)
else
PreferenceManager.getDefaultSharedPreferences(context)

private val applicationContext: WeakReference<Context> = WeakReference(context.applicationContext)

private val cacheBoolean: HashMap<String, Boolean> = hashMapOf()
private val cacheInt: HashMap<String, Int> = hashMapOf()
private val cacheString: HashMap<String, String> = hashMapOf()
private val applicationContext: WeakReference<Context> = WeakReference(appContext)

val internal = Internal(this)
val keyboard = Keyboard(this)
val looks = ThemeColor(this)
val themeAndColor = ThemeAndColor(this)
val profile = Profile(this)
val other = Other(this)

/**
* Checks the cache if an entry for [key] exists, else calls [getPrefInternal] to retrieve the
* value. The type is automatically derived from the given [default] value.
* Fetches the value for [key] from the shared preferences and returns it.
* The type is automatically derived from the given [default] value.
* @return The value for [key] or [default].
*/
private inline fun <reified T> getPref(key: String, default: T): T {
return when {
false is T -> {
(cacheBoolean[key] ?: getPrefInternal(key, default)) as T
}
0 is T -> {
(cacheInt[key] ?: getPrefInternal(key, default)) as T
}
"" is T -> {
(cacheString[key] ?: getPrefInternal(key, default)) as T
}
else -> null as T
}
}

/**
* Fetches the value for [key] from the shared preferences, puts the value into the
* corresponding cache and returns it.
* @return The value for [key] or [default].
*/
private inline fun <reified T> getPrefInternal(key: String, default: T): T {
return when {
false is T -> {
val value = shared.getBoolean(key, default as Boolean)
cacheBoolean[key] = value
value as T
shared.getBoolean(key, default as Boolean) as T
}
0 is T -> {
val value = shared.getInt(key, default as Int)
cacheInt[key] = value
value as T
shared.getInt(key, default as Int) as T
}
"" is T -> {
val value = shared.getString(key, default as String) ?: (default as String)
cacheString[key] = value
value as T
(shared.getString(key, default as String) ?: (default as String)) as T
}
else -> null as T
}
Expand All @@ -88,25 +52,21 @@ class AppPrefs(
when {
false is T -> {
shared.edit().putBoolean(key, value as Boolean).apply()
cacheBoolean[key] = value as Boolean
}
0 is T -> {
shared.edit().putInt(key, value as Int).apply()
cacheInt[key] = value as Int
}
"" is T -> {
shared.edit().putString(key, value as String).apply()
cacheString[key] = value as String
}
}
}

companion object {
private var defaultInstance: AppPrefs? = null

@Synchronized
fun initDefault(context: Context): AppPrefs {
val instance = AppPrefs(context.applicationContext)
fun initDefault(sharedPreferences: SharedPreferences): AppPrefs {
val instance = AppPrefs(sharedPreferences)
defaultInstance = instance
return instance
}
Expand Down Expand Up @@ -140,15 +100,6 @@ class AppPrefs(
}
}

/**
* Syncs the system preference values and clears the cache.
*/
fun sync() {
cacheBoolean.clear()
cacheInt.clear()
cacheString.clear()
}

class Internal(private val prefs: AppPrefs) {
companion object {
const val LAST_VERSION_NAME = "general__last_version_name"
Expand Down Expand Up @@ -328,7 +279,7 @@ class AppPrefs(
/**
* Wrapper class of theme and color settings.
*/
class ThemeColor(private val prefs: AppPrefs) {
class ThemeAndColor(private val prefs: AppPrefs) {
companion object {
const val SELECTED_THEME = "theme_selected_theme"
const val SELECTED_COLOR = "theme_selected_color"
Expand Down Expand Up @@ -406,15 +357,15 @@ class AppPrefs(
var destroyOnQuit: Boolean = false
get() = prefs.getPref(DESTROY_ON_QUIT, false)
private set
var clipboardCompareRules: String
get() = prefs.getPref(CLIPBOARD_COMPARE_RULES, "")
set(v) = prefs.setPref(CLIPBOARD_COMPARE_RULES, v)
var clipboardOutputRules: String
get() = prefs.getPref(CLIPBOARD_OUTPUT_RULES, "")
set(v) = prefs.setPref(CLIPBOARD_OUTPUT_RULES, v)
var draftOutputRules: String
get() = prefs.getPref(DRAFT_OUTPUT_RULES, "")
set(v) = prefs.setPref(DRAFT_OUTPUT_RULES, v)
var clipboardCompareRules: List<String>
get() = prefs.getPref(CLIPBOARD_COMPARE_RULES, "").trim().split('\n')
set(v) = prefs.setPref(CLIPBOARD_COMPARE_RULES, v.joinToString("\n"))
var clipboardOutputRules: List<String>
get() = prefs.getPref(CLIPBOARD_OUTPUT_RULES, "").trim().split('\n')
set(v) = prefs.setPref(CLIPBOARD_OUTPUT_RULES, v.joinToString("\n"))
var draftOutputRules: List<String>
get() = prefs.getPref(DRAFT_OUTPUT_RULES, "").trim().split('\n')
set(v) = prefs.setPref(DRAFT_OUTPUT_RULES, v.joinToString("\n"))
var clipboardLimit: String
get() = prefs.getPref(CLIPBOARD_LIMIT, "50")
set(v) = prefs.setPref(CLIPBOARD_LIMIT, v)
Expand Down
51 changes: 7 additions & 44 deletions app/src/main/java/com/osfans/trime/data/Config.java
Expand Up @@ -50,17 +50,12 @@
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import kotlin.Pair;
import kotlin.collections.MapsKt;
import timber.log.Timber;

/** 解析 YAML 配置文件 */
public class Config {
// 默认的用户数据路径
private static final String RIME = "rime";
// private static final String TAG = "Config";

private static Config self = null;

private static final AppPrefs appPrefs = AppPrefs.defaultInstance();
Expand All @@ -83,10 +78,6 @@ public static Config get() {
private Map<String, Map<String, ?>> presetKeyboards;
private Map<String, ?> liquidKeyboard;

private static final Pattern pattern = Pattern.compile("\\s*\n\\s*");

private String[] clipBoardCompare, clipBoardOutput, draftOutput;

public Config() {
this(false);
}
Expand All @@ -96,7 +87,7 @@ public Config(boolean skipDeploy) {
"\t<TrimeInit>\t" + Thread.currentThread().getStackTrace()[2].getMethodName() + "\t";
Timber.d(methodName);
self = this;
themeName = appPrefs.getLooks().getSelectedTheme();
themeName = appPrefs.getThemeAndColor().getSelectedTheme();
soundPackageName = appPrefs.getKeyboard().getSoundPackage();

Timber.d(methodName + "sync");
Expand All @@ -113,35 +104,9 @@ public Config(boolean skipDeploy) {
Timber.d(methodName + "setSoundFromColor");
setSoundFromColor();

Timber.d(methodName + "setClipboard&draft");
clipBoardCompare = appPrefs.getOther().getClipboardCompareRules().trim().split("\n");
clipBoardOutput = appPrefs.getOther().getClipboardOutputRules().trim().split("\n");
draftOutput = appPrefs.getOther().getDraftOutputRules().trim().split("\n");

Timber.d(methodName + "finish");
}

public void setClipBoardCompare(String str) {
String s = pattern.matcher(str).replaceAll("\n").trim();
clipBoardCompare = s.split("\n");

appPrefs.getOther().setClipboardCompareRules(s);
}

public void setClipBoardOutput(String str) {
String s = pattern.matcher(str).replaceAll("\n").trim();
clipBoardOutput = s.split("\n");

appPrefs.getOther().setClipboardOutputRules(s);
}

public void setDraftOutput(String str) {
String s = pattern.matcher(str).replaceAll("\n").trim();
draftOutput = s.split("\n");

appPrefs.getOther().setDraftOutputRules(s);
}

public String getTheme() {
return themeName;
}
Expand All @@ -166,7 +131,7 @@ private void deployTheme() {

public void setTheme(String theme) {
themeName = theme;
appPrefs.getLooks().setSelectedTheme(themeName);
appPrefs.getThemeAndColor().setSelectedTheme(themeName);
init(false);
}

Expand Down Expand Up @@ -258,8 +223,6 @@ private void init(boolean skip_delopy) {
liquidKeyboard = globalThemeConfig.get("liquid_keyboard");
initLiquidKeyboard();
Timber.d("init() initLiquidKeyboard done");
Rime.setShowSwitches(appPrefs.getKeyboard().getSwitchesEnabled());
Rime.setShowSwitchArrow(appPrefs.getKeyboard().getSwitchArrowEnabled());
reset();
Timber.d("init() reset done");
initCurrentColors();
Expand Down Expand Up @@ -599,7 +562,7 @@ public String getString(String key) {
private Object getColorObject(String key) {
final Map<?, ?> map = (Map<?, ?>) presetColorSchemes.get(colorID);
if (map == null) return null;
appPrefs.getLooks().setSelectedColor(colorID);
appPrefs.getThemeAndColor().setSelectedColor(colorID);
Object o = map.get(key);
String fallbackKey = key;
while (o == null && fallbackColors.containsKey(fallbackKey)) {
Expand All @@ -617,7 +580,7 @@ private Object getColorObject(String key) {
* @return java.lang.String 首个已配置的主题方案名
*/
private String getColorSchemeName() {
String scheme = appPrefs.getLooks().getSelectedColor();
String scheme = appPrefs.getThemeAndColor().getSelectedColor();
if (!presetColorSchemes.containsKey(scheme)) scheme = getString("color_scheme"); // 主題中指定的配色
if (!presetColorSchemes.containsKey(scheme)) scheme = "default"; // 主題中的default配色
Map<String, ?> color = (Map<String, ?>) presetColorSchemes.get(scheme);
Expand All @@ -638,7 +601,7 @@ public boolean hasDarkLight() {
* @return 配色方案名称
*/
private String getColorSchemeName(boolean darkMode) {
String scheme = appPrefs.getLooks().getSelectedColor();
String scheme = appPrefs.getThemeAndColor().getSelectedColor();
if (!presetColorSchemes.containsKey(scheme)) scheme = getString("color_scheme"); // 主題中指定的配色
if (!presetColorSchemes.containsKey(scheme)) scheme = "default"; // 主題中的default配色
Map<String, ?> color = (Map<String, ?>) presetColorSchemes.get(scheme);
Expand Down Expand Up @@ -941,7 +904,7 @@ public void initCurrentColors() {
Timber.i("no colorID %s", colorID);
return;
}
appPrefs.getLooks().setSelectedColor(colorID);
appPrefs.getThemeAndColor().setSelectedColor(colorID);

for (Map.Entry<?, ?> entry : map.entrySet()) {
Object value = getColorRealValue(entry.getValue());
Expand Down Expand Up @@ -987,7 +950,7 @@ public void initCurrentColors(boolean darkMode) {
Timber.i("no colorID %s", colorID);
return;
}
appPrefs.getLooks().setSelectedColor(colorID);
appPrefs.getThemeAndColor().setSelectedColor(colorID);

for (Map.Entry<?, ?> entry : map.entrySet()) {
Object value = getColorRealValue(entry.getValue());
Expand Down
Expand Up @@ -50,9 +50,7 @@ object ClipboardHelper :

private val limit get() = AppPrefs.defaultInstance().other.clipboardLimit.toInt()
private val compare get() = AppPrefs.defaultInstance().other.clipboardCompareRules
.trim().split('\n')
private val output get() = AppPrefs.defaultInstance().other.clipboardOutputRules
.trim().split('\n')

var lastBean: DatabaseBean? = null

Expand Down

0 comments on commit da4f6ab

Please sign in to comment.