All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.kontur.mobile.visualfsm.Action.kt Maven / Gradle / Ivy

Go to download

VisualFSM - Kotlin Multiplatform library for FSM with visualization and analysis tools

There is a newer version: 3.0.0
Show newest version
package ru.kontur.mobile.visualfsm

/**
 * Is an input object for the State machine.
 * The [action][Action] chooses [transition][Transition] and performs it
 */
abstract class Action {

    /**
     * Returns every [Transition] declared inside [Action]
     *
     * @return every [Transition] declared inside [Action]
     */
    abstract fun getTransitions(): List>

    /**
     * Selects and starts a [transition][Transition].
     * Calls [transition callbacks][TransitionCallbacks] methods.
     *
     * @param oldState current [state][State]
     * @param callbacks [transition callbacks][TransitionCallbacks]
     * @return [new state][State]
     */
    fun run(oldState: STATE, callbacks: TransitionCallbacks?): STATE {
        callbacks?.onActionLaunched(this, oldState)

        val availableTransitions = getAvailableTransitions(oldState)

        if (availableTransitions.size > 1) {
            callbacks?.onMultipleTransitionError(this, oldState)
        }

        val selectedTransition = availableTransitions.firstOrNull()

        if (selectedTransition == null) {
            callbacks?.onNoTransitionError(this, oldState)
            return oldState
        }

        callbacks?.onTransitionSelected(this, selectedTransition, oldState)

        val newState = selectedTransition.transform(oldState)

        callbacks?.onNewStateReduced(this, selectedTransition, oldState, newState)

        return newState
    }

    @Suppress("UNCHECKED_CAST")
    private fun getAvailableTransitions(oldState: STATE): List> =
        (getTransitions() as List>).filter { isCorrectTransition(it, oldState) }

    private fun isCorrectTransition(
        transition: Transition,
        oldState: STATE
    ): Boolean =
        (transition.fromState == oldState::class) && transition.predicate(oldState)
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy