Refactor first run handling

This commit is contained in:
Rocka 2025-09-26 23:45:56 +08:00
parent 6758662833
commit aee18400c7
No known key found for this signature in database
GPG Key ID: 28031158FFDD6853

View File

@ -24,6 +24,7 @@ import org.fcitx.fcitx5.android.utils.Locales
import org.fcitx.fcitx5.android.utils.appContext
import org.fcitx.fcitx5.android.utils.toast
import timber.log.Timber
import java.util.concurrent.CopyOnWriteArrayList
/**
* Do not use this class directly, accessing fcitx via daemon instead
@ -220,7 +221,9 @@ class Fcitx(private val context: Context) : FcitxAPI, FcitxLifecycleOwner {
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
private val fcitxEventHandlers = ArrayList<(FcitxEvent<*>) -> Unit>()
// we may need to modify the list during iteration
// eg. remove the "first run" listener after first ReadyEvent
private val fcitxEventHandlers = CopyOnWriteArrayList<(FcitxEvent<*>) -> Unit>()
init {
System.loadLibrary("native-lib")
@ -377,8 +380,6 @@ class Fcitx(private val context: Context) : FcitxAPI, FcitxLifecycleOwner {
@JvmStatic
external fun scheduleEmpty()
private var firstRun by AppPrefs.getInstance().internal.firstRun
/**
* Called from native-lib
*/
@ -387,13 +388,6 @@ class Fcitx(private val context: Context) : FcitxAPI, FcitxLifecycleOwner {
fun handleFcitxEvent(type: Int, params: Array<Any>) {
val event = FcitxEvent.create(type, params)
Timber.d("Handling $event")
if (event is FcitxEvent.ReadyEvent) {
if (firstRun) {
// this method runs in same thread with `startupFcitx`
// block it will also block fcitx
onFirstRun()
}
}
fcitxEventHandlers.forEach { it.invoke(event) }
eventFlow_.tryEmit(event)
}
@ -401,7 +395,6 @@ class Fcitx(private val context: Context) : FcitxAPI, FcitxLifecycleOwner {
// will be called in fcitx main thread
private fun onFirstRun() {
Timber.i("onFirstRun")
firstRun = false
}
/**
@ -495,6 +488,18 @@ class Fcitx(private val context: Context) : FcitxAPI, FcitxLifecycleOwner {
}.let { ImmutableGraph(it) }
}
private var firstRun by AppPrefs.getInstance().internal.firstRun
private fun handleFirstRunReadyEvent(event: FcitxEvent<*>) {
if (event is FcitxEvent.ReadyEvent && firstRun) {
firstRun = false
// this method runs in same thread with `startupFcitx`
// block it will also block fcitx
onFirstRun()
unregisterFcitxEventHandler(::handleFcitxEvent)
}
}
private fun handleFcitxEvent(event: FcitxEvent<*>) {
when (event) {
is FcitxEvent.ReadyEvent -> lifecycleRegistry.postEvent(FcitxLifecycle.Event.ON_READY)
@ -520,6 +525,9 @@ class Fcitx(private val context: Context) : FcitxAPI, FcitxLifecycleOwner {
Timber.w("Skip starting fcitx: not at stopped state!")
return
}
if (firstRun) {
registerFcitxEventHandler(::handleFirstRunReadyEvent)
}
registerFcitxEventHandler(::handleFcitxEvent)
lifecycleRegistry.postEvent(FcitxLifecycle.Event.ON_START)
ClipboardManager.addOnUpdateListener(onClipboardUpdate)