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

net.chestmc.common.extensions.Events.kt Maven / Gradle / Ivy

The newest version!
package net.chestmc.common.extensions

import net.chestmc.common.common.EventError
import net.chestmc.common.common.StandardListener
import org.bukkit.event.Event
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.plugin.Plugin
import kotlin.reflect.KClass

/**
 * Throws a [EventError] with the specified optional message.
 */
fun  T.fail(): Nothing = throw EventError()

/**
 * Calls this event.
 */
fun Event.call() = pluginManager.callEvent(this)

/**
 * Register a event listener with the specified event in generic type in this server.
 */
inline fun  Listener.listening(
  type: KClass,
  plugin: Plugin,
  priority: EventPriority = EventPriority.NORMAL,
  ignoreCancelled: Boolean = false,
  crossinline action: TransformAction,
) = pluginManager.registerEvent(
  type.java,
  this,
  priority,
  { _, event ->
    if (type.isInstance(event)) {
      runCatching {
        action(event.cast())
      }.onFailure {
        if (it !is EventError)
          it.printStackTrace()
      }
    }
  },
  plugin,
  ignoreCancelled
)


/**
 * Register a event listener with the specified event in generic type in this server.
 */
inline fun  Listener.listening(
  plugin: Plugin,
  priority: EventPriority = EventPriority.NORMAL,
  ignoreCancelled: Boolean = false,
  crossinline action: TransformAction,
) = listening(T::class, plugin, priority, ignoreCancelled, action)

/**
 * Register a event listener with the specified event in generic type in this server.
 */
inline fun  Plugin.listening(
  priority: EventPriority = EventPriority.NORMAL,
  ignoreCancelled: Boolean = false,
  crossinline action: TransformAction,
) = StandardListener().listening(this, priority, ignoreCancelled, action)

/**
 * Verify if the specified [valide] action is true, otherwise will throw a [EventError] exception.
 */
fun  T.validate(valide: Boolean): Boolean = if (valide) true else fail()

/**
 * Verify if the specified [valide] action is false, otherwise will throw a [EventError] exception.
 */
fun  T.validateNot(valide: Boolean): Boolean = if (!valide) true else fail()




© 2015 - 2025 Weber Informatics LLC | Privacy Policy