Skip to content

Commit

Permalink
refactor: reduce redundant nesting during key processing
Browse files Browse the repository at this point in the history
  • Loading branch information
WhiredPlanck committed Nov 9, 2024
1 parent 0d58abf commit 60c1586
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 85 deletions.
1 change: 0 additions & 1 deletion app/src/main/java/com/osfans/trime/ime/core/InputView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ class InputView(
private val themedContext = context.withTheme(android.R.style.Theme_DeviceDefault_Settings)
private val inputComponent = InputComponent::class.create(this, themedContext, theme, service, rime)
private val broadcaster = inputComponent.broadcaster
val commonKeyboardActionListener = inputComponent.commonKeyboardActionListener
private val enterKeyLabel = inputComponent.enterKeyLabel
private val windowManager = inputComponent.windowManager
private val quickBar: QuickBar = inputComponent.quickBar
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,14 @@ import com.osfans.trime.daemon.RimeSession
import com.osfans.trime.data.db.DraftHelper
import com.osfans.trime.data.prefs.AppPrefs
import com.osfans.trime.data.theme.ColorManager
import com.osfans.trime.data.theme.KeyActionManager
import com.osfans.trime.data.theme.Theme
import com.osfans.trime.data.theme.ThemeManager
import com.osfans.trime.ime.broadcast.IntentReceiver
import com.osfans.trime.ime.enums.FullscreenMode
import com.osfans.trime.ime.enums.InlinePreeditMode
import com.osfans.trime.ime.enums.Keycode
import com.osfans.trime.ime.keyboard.CommonKeyboardActionListener
import com.osfans.trime.ime.keyboard.InitializationUi
import com.osfans.trime.ime.keyboard.InputFeedbackManager
import com.osfans.trime.util.ShortcutUtils
import com.osfans.trime.util.ShortcutUtils.openCategory
import com.osfans.trime.util.findSectionFrom
import com.osfans.trime.util.isLandscape
import com.osfans.trime.util.isNightMode
Expand Down Expand Up @@ -87,16 +83,12 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
private val prefs: AppPrefs
get() = AppPrefs.defaultInstance()
var inputView: InputView? = null
private val commonKeyboardActionListener: CommonKeyboardActionListener?
get() = inputView?.commonKeyboardActionListener
private var initializationUi: InitializationUi? = null
private var mIntentReceiver: IntentReceiver? = null
private var isWindowShown = false // 键盘窗口是否已显示
private var isComposable: Boolean = false
private val locales = Array(2) { Locale.getDefault() }

var shouldUpdateRimeOption = false

var lastCommittedText: CharSequence = ""
private set

Expand Down Expand Up @@ -161,18 +153,13 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
isWindowShown = false
}

private fun updateRimeOption(): Boolean {
private suspend fun updateRimeOption(api: RimeApi) {
try {
if (shouldUpdateRimeOption) {
Rime.setOption("soft_cursor", prefs.keyboard.softCursorEnabled) // 軟光標
Rime.setOption("_horizontal", ThemeManager.activeTheme.generalStyle.horizontal) // 水平模式
shouldUpdateRimeOption = false
}
api.setRuntimeOption("soft_cursor", prefs.keyboard.softCursorEnabled) // 軟光標
api.setRuntimeOption("_horizontal", ThemeManager.activeTheme.generalStyle.horizontal) // 水平模式
} catch (e: Exception) {
Timber.e(e)
return false
}
return true
}

/** 防止重启系统 强行停止应用时alarm任务丢失 */
Expand Down Expand Up @@ -204,6 +191,9 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {

override fun onCreate() {
rime = RimeDaemon.createSession(javaClass.name)
postRimeJob {
updateRimeOption(this)
}
lifecycleScope.launch {
jobs.consumeEach { it.join() }
}
Expand Down Expand Up @@ -231,7 +221,6 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
ThemeManager.init()
InputFeedbackManager.init()
restartSystemStartTimingSync()
shouldUpdateRimeOption = true
val theme = ThemeManager.activeTheme
val defaultLocale = theme.generalStyle.locale.split(DELIMITER_SPLITTER)
locales[0] =
Expand Down Expand Up @@ -259,7 +248,7 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
when (it) {
is RimeNotification.OptionNotification -> {
val value = it.value.value
when (val option = it.value.option) {
when (it.value.option) {
"ascii_mode" -> {
InputFeedbackManager.ttsLanguage =
locales[if (value) 1 else 0]
Expand All @@ -269,16 +258,6 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
-> {
setCandidatesViewShown(isComposable && !value)
}
else ->
if (option.startsWith("_key_") && option.length > 5 && value) {
shouldUpdateRimeOption = false // 防止在 handleRimeNotification 中 setOption
val key = option.substring(5)
inputView
?.commonKeyboardActionListener
?.listener
?.onAction(KeyActionManager.getAction(key))
shouldUpdateRimeOption = true
}
}
}
is RimeEvent.IpcResponseEvent ->
Expand Down Expand Up @@ -322,7 +301,6 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
*
* 重置鍵盤、候選條、狀態欄等 !!注意,如果其中調用Rime.setOption,切換方案會卡住 */
fun recreateInputView(theme: Theme) {
shouldUpdateRimeOption = true // 不能在Rime.onMessage中調用set_option,會卡死
updateComposing() // 切換主題時刷新候選
setInputView(InputView(this, rime, theme).also { inputView = it })
initializationUi = null
Expand Down Expand Up @@ -822,40 +800,6 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
}
}

// 处理键盘事件(Android keycode)
fun handleKey(
keyEventCode: Int,
metaState: Int,
): Boolean { // 軟鍵盤
commonKeyboardActionListener?.shouldReleaseKey = false
val value =
RimeKeyMapping
.keyCodeToVal(keyEventCode)
.takeIf { it != RimeKeyMapping.RimeKey_VoidSymbol }
?: Rime.getRimeKeycodeByName(Keycode.keyNameOf(keyEventCode))
val modifiers = KeyModifiers.fromMetaState(metaState).modifiers
val code = ScancodeMapping.keyCodeToScancode(keyEventCode)
var result = false
postRimeJob {
if (!processKey(value, modifiers, code)) {
if (!hookKeyboard(keyEventCode, metaState)) {
if (!openCategory(keyEventCode)) {
result = false
} else {
Timber.d("handleKey: openCategory")
}
} else {
Timber.d("handleKey: hook")
}
} else {
commonKeyboardActionListener?.shouldReleaseKey = true
Timber.d("handleKey: processKey")
}
}
if (!result) commonKeyboardActionListener?.shouldReleaseKey = true
return result
}

fun shareText(): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val ic = currentInputConnection ?: return false
Expand All @@ -867,7 +811,7 @@ open class TrimeInputMethodService : LifecycleInputMethodService() {
}

/** 編輯操作 */
private fun hookKeyboard(
fun hookKeyboard(
code: Int,
mask: Int,
): Boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,23 @@ import android.view.KeyEvent
import androidx.lifecycle.lifecycleScope
import com.osfans.trime.R
import com.osfans.trime.core.KeyModifier
import com.osfans.trime.core.KeyModifiers
import com.osfans.trime.core.Rime
import com.osfans.trime.core.RimeApi
import com.osfans.trime.core.RimeKeyMapping
import com.osfans.trime.core.ScancodeMapping
import com.osfans.trime.daemon.RimeSession
import com.osfans.trime.daemon.launchOnReady
import com.osfans.trime.data.prefs.AppPrefs
import com.osfans.trime.data.theme.ColorManager
import com.osfans.trime.data.theme.KeyActionManager
import com.osfans.trime.data.theme.ThemeManager
import com.osfans.trime.ime.core.InputView
import com.osfans.trime.ime.core.Speech
import com.osfans.trime.ime.core.TrimeInputMethodService
import com.osfans.trime.ime.dependency.InputScope
import com.osfans.trime.ime.dialog.AvailableSchemaPickerDialog
import com.osfans.trime.ime.dialog.EnabledSchemaPickerDialog
import com.osfans.trime.ime.enums.Keycode
import com.osfans.trime.ime.symbol.LiquidKeyboard
import com.osfans.trime.ime.symbol.SymbolBoardType
import com.osfans.trime.ime.symbol.TabManager
Expand All @@ -34,10 +36,12 @@ import com.osfans.trime.ui.main.settings.ColorPickerDialog
import com.osfans.trime.ui.main.settings.KeySoundEffectPickerDialog
import com.osfans.trime.ui.main.settings.ThemePickerDialog
import com.osfans.trime.util.ShortcutUtils
import com.osfans.trime.util.ShortcutUtils.openCategory
import com.osfans.trime.util.isAsciiPrintable
import kotlinx.coroutines.launch
import me.tatarka.inject.annotations.Inject
import splitties.systemservices.inputMethodManager
import timber.log.Timber

@InputScope
@Inject
Expand All @@ -59,7 +63,7 @@ class CommonKeyboardActionListener(

private val prefs = AppPrefs.defaultInstance()

var shouldReleaseKey: Boolean = false
private var shouldReleaseKey: Boolean = false

private fun showDialog(dialog: suspend (RimeApi) -> Dialog) {
rime.launchOnReady { api ->
Expand Down Expand Up @@ -118,11 +122,6 @@ class CommonKeyboardActionListener(

override fun onRelease(keyEventCode: Int) {
if (shouldReleaseKey) {
if (service.shouldUpdateRimeOption) {
Rime.setOption("soft_cursors", prefs.keyboard.softCursorEnabled)
Rime.setOption("_horizontal", ThemeManager.activeTheme.generalStyle.horizontal)
service.shouldUpdateRimeOption = false
}
// FIXME: 释放按键可能不对
val value = RimeKeyMapping.keyCodeToVal(keyEventCode)
if (value != RimeKeyMapping.RimeKey_VoidSymbol) {
Expand Down Expand Up @@ -255,18 +254,41 @@ class CommonKeyboardActionListener(
keyEventCode: Int,
metaState: Int,
) {
// 优先由librime处理按键事件
if (service.handleKey(keyEventCode, metaState)) return

shouldReleaseKey = false
val value =
RimeKeyMapping
.keyCodeToVal(keyEventCode)
.takeIf { it != RimeKeyMapping.RimeKey_VoidSymbol }
?: Rime.getRimeKeycodeByName(Keycode.keyNameOf(keyEventCode))
val modifiers = KeyModifiers.fromMetaState(metaState).modifiers
val code = ScancodeMapping.keyCodeToScancode(keyEventCode)
service.postRimeJob {
if (processKey(value, modifiers, code)) {
shouldReleaseKey = true
Timber.d("handleKey: processKey")
return@postRimeJob
}
if (service.hookKeyboard(keyEventCode, metaState)) {
Timber.d("handleKey: hook")
return@postRimeJob
}
if (context.openCategory(keyEventCode)) {
Timber.d("handleKey: openCategory")
return@postRimeJob
}
shouldReleaseKey = false

when (keyEventCode) {
KeyEvent.KEYCODE_ENTER -> service.handleReturnKey()
KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_ESCAPE -> service.requestHideSelf(0)
else -> {
// 小键盘自动增加锁定
if (keyEventCode in KeyEvent.KEYCODE_NUMPAD_0..KeyEvent.KEYCODE_NUMPAD_EQUALS) {
service.sendDownUpKeyEvent(keyEventCode, metaState or KeyEvent.META_NUM_LOCK_ON)
when (keyEventCode) {
KeyEvent.KEYCODE_ENTER -> service.handleReturnKey()
KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_ESCAPE -> service.requestHideSelf(0)
else -> {
// 小键盘自动增加锁定
if (keyEventCode in KeyEvent.KEYCODE_NUMPAD_0..KeyEvent.KEYCODE_NUMPAD_EQUALS) {
service.sendDownUpKeyEvent(
keyEventCode,
metaState or KeyEvent.META_NUM_LOCK_ON,
)
}
}
}
}
Expand Down
19 changes: 16 additions & 3 deletions app/src/main/java/com/osfans/trime/ime/keyboard/KeyboardWindow.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import com.osfans.trime.core.SchemaItem
import com.osfans.trime.daemon.RimeSession
import com.osfans.trime.data.prefs.AppPrefs
import com.osfans.trime.data.schema.SchemaManager
import com.osfans.trime.data.theme.KeyActionManager
import com.osfans.trime.data.theme.Theme
import com.osfans.trime.ime.broadcast.InputBroadcastReceiver
import com.osfans.trime.ime.core.TrimeInputMethodService
Expand Down Expand Up @@ -245,9 +246,21 @@ class KeyboardWindow(
"_hide_key_hint" -> mainKeyboardView.showKeyHint = !value.value
"_hide_key_symbol" -> mainKeyboardView.showKeySymbol = !value.value
else -> {
if (opt.matches("^_keyboard_.+".toRegex())) {
switchKeyboard(opt.removePrefix("_keyboard_"))
return
when {
opt.startsWith("_keyboard_") -> {
val target = opt.removePrefix("_keyboard_")
if (target.isNotEmpty()) {
switchKeyboard(target)
}
}
opt.startsWith("_key_") -> {
val what = opt.removePrefix("_key_")
if (what.isNotEmpty() && value.value) {
commonKeyboardActionListener
.listener
.onAction(KeyActionManager.getAction(what))
}
}
}
}
}
Expand Down

0 comments on commit 60c1586

Please sign in to comment.