Improve plugin enabling and disabling

This commit is contained in:
Him188 2020-08-23 19:52:40 +08:00
parent d2b7421df7
commit 9cc05f682b
3 changed files with 12 additions and 7 deletions

View File

@ -110,7 +110,7 @@ internal object JarPluginLoaderImpl :
}
override fun enable(plugin: JvmPlugin) {
if (plugin.isEnabled) throw IllegalStateException("Plugin is already enabled")
if (plugin.isEnabled) return
ensureActive()
if (plugin is JvmPluginInternal) {
plugin.internalOnEnable()
@ -118,7 +118,7 @@ internal object JarPluginLoaderImpl :
}
override fun disable(plugin: JvmPlugin) {
if (!plugin.isEnabled) throw IllegalStateException("Plugin is already disabled")
if (!plugin.isEnabled) return
if (plugin is JvmPluginInternal) {
plugin.internalOnDisable()

View File

@ -38,8 +38,7 @@ internal abstract class JvmPluginInternal(
) : JvmPlugin,
CoroutineScope {
override val isEnabled: Boolean
get() = job.isActive
override var isEnabled: Boolean = false
private val resourceContainerDelegate by lazy { this::class.java.classLoader.asResourceContainer() }
override fun getResourceAsStream(path: String): InputStream? = resourceContainerDelegate.getResourceAsStream(path)
@ -77,6 +76,7 @@ internal abstract class JvmPluginInternal(
cancel(CancellationException("Exception while enabling plugin", it))
}
)
isEnabled = false
}
@Throws(Throwable::class)
@ -90,6 +90,7 @@ internal abstract class JvmPluginInternal(
onEnable()
}.fold(
onSuccess = {
isEnabled = true
return true
},
onFailure = {
@ -121,7 +122,7 @@ internal abstract class JvmPluginInternal(
job.invokeOnCompletion { e ->
if (e != null) {
logger.error(e)
safeLoader.disable(this)
if (this.isEnabled) safeLoader.disable(this)
}
}
}

View File

@ -11,6 +11,8 @@
package net.mamoe.mirai.console.plugin
import net.mamoe.mirai.console.plugin.PluginManager.INSTANCE.disable
import net.mamoe.mirai.console.plugin.PluginManager.INSTANCE.enable
import net.mamoe.mirai.console.plugin.PluginManager.INSTANCE.register
import net.mamoe.mirai.console.plugin.dsecription.PluginDescription
import net.mamoe.mirai.console.plugin.jvm.JarPluginLoader
@ -75,8 +77,9 @@ public interface PluginLoader<P : Plugin, D : PluginDescription> {
* **实现细节**: 此函数可抛出 [PluginLoadException] 作为正常失败原因, 其他任意异常都属于意外错误.
* 当异常发生时, 插件将会直接被放弃加载, 并影响依赖它的其他插件.
*
* @throws IllegalStateException 当插件已经启用时抛出
* @throws PluginLoadException 在加载插件遇到意料之中的错误时抛出 (如找不到主类等).
*
* @see PluginManager.enable
*/
@Throws(IllegalStateException::class, PluginLoadException::class)
public fun enable(plugin: P)
@ -87,8 +90,9 @@ public interface PluginLoader<P : Plugin, D : PluginDescription> {
* **实现细节**: 此函数可抛出 [PluginLoadException] 作为正常失败原因, 其他任意异常都属于意外错误.
* 当异常发生时, 插件将会直接被放弃加载, 并影响依赖它的其他插件.
*
* @throws IllegalStateException 当插件已经禁用时抛出
* @throws PluginLoadException 在加载插件遇到意料之中的错误时抛出 (如找不到主类等).
*
* @see PluginManager.disable
*/
@Throws(IllegalStateException::class, PluginLoadException::class)
public fun disable(plugin: P)