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

commonMain.jetbrains.datalore.vis.canvas.EventPeer.kt Maven / Gradle / Ivy

There is a newer version: 4.5.3-alpha1
Show newest version
/*
 * Copyright (c) 2019. JetBrains s.r.o.
 * Use of this source code is governed by the MIT license that can be found in the LICENSE file.
 */

package jetbrains.datalore.vis.canvas

import jetbrains.datalore.base.observable.event.EventHandler
import jetbrains.datalore.base.observable.event.ListenerCaller
import jetbrains.datalore.base.observable.event.Listeners
import jetbrains.datalore.base.registration.Disposable
import jetbrains.datalore.base.registration.Registration
import kotlin.reflect.KClass


abstract class EventPeer, EventT>
protected constructor(
    @Suppress("UNUSED_PARAMETER") specClass: KClass // originally `specClass` was used to create EnumMap
) {
    private val myEventHandlers: MutableMap>> = HashMap()

    fun addEventHandler(eventSpec: SpecT, handler: EventHandler): Registration {
        if (!myEventHandlers.containsKey(eventSpec)) {
            myEventHandlers[eventSpec] = Listeners()
            onSpecAdded(eventSpec)
        }

        val addReg = myEventHandlers[eventSpec]!!.add(handler)
        return Registration.from(object : Disposable {
            override fun dispose() {
                addReg.remove()
                if (myEventHandlers[eventSpec]!!.isEmpty) {
                    myEventHandlers.remove(eventSpec)
                    onSpecRemoved(eventSpec)
                }
            }
        })
    }

    fun dispatch(eventSpec: SpecT, event: EventT) {
        myEventHandlers[eventSpec]?.fire(object : ListenerCaller> {
            override fun call(l: EventHandler) {
                l.onEvent(event)
            }
        })
    }

    protected abstract fun onSpecAdded(spec: SpecT)
    protected abstract fun onSpecRemoved(spec: SpecT)
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy