From f94d77cfaca77586ba9de3fad05be7e3a9e092c0 Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 14 Dec 2023 14:52:17 +0100 Subject: [PATCH 01/48] feat(gui): Begin first implementation of guis --- .../rushyverse/api/extension/_String.kt | 15 +++ .../com/github/rushyverse/api/gui/GUI.kt | 102 ++++++++++++++++++ .../github/rushyverse/api/gui/PersonalGUI.kt | 81 ++++++++++++++ .../github/rushyverse/api/gui/SharedGUI.kt | 80 ++++++++++++++ .../rushyverse/api/listener/GUIListener.kt | 45 ++++++++ .../github/rushyverse/api/player/Client.kt | 11 +- .../rushyverse/api/player/ClientManager.kt | 79 ++++++++++++-- .../api/player/ClientManagerImpl.kt | 64 ----------- .../rushyverse/api/player/gui/GUIManager.kt | 58 ++++++++++ 9 files changed, 461 insertions(+), 74 deletions(-) create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt delete mode 100644 src/main/kotlin/com/github/rushyverse/api/player/ClientManagerImpl.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt diff --git a/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt b/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt index 59523834..63ab7bfa 100644 --- a/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt +++ b/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt @@ -3,6 +3,8 @@ package com.github.rushyverse.api.extension +import com.github.rushyverse.api.translation.Translator +import com.github.rushyverse.api.translation.getComponent import net.kyori.adventure.text.Component import net.kyori.adventure.text.TextComponent import net.kyori.adventure.text.format.NamedTextColor @@ -263,3 +265,16 @@ public fun StringBuilder.deleteLast(size: Int): StringBuilder { else -> delete(length - size, length) } } + +/** + * If the string contains a dot, it will be considered as a translation path, and will be translated. + * However, if the string doesn't contain a dot, it will be considered as a component. + * @receiver String to translate or to convert to a component. + * @param translator Translator. + * @param locale Locale to use for translation. + * @return The translated component or the component created from the string. + */ +public fun String.toTranslatedComponent(translator: Translator, locale: Locale): Component { + return if (this.contains('.')) translator.getComponent(this, locale) + else this.asComponent() +} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt new file mode 100644 index 00000000..c60c3f4b --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -0,0 +1,102 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.koin.inject +import com.github.rushyverse.api.player.Client +import com.github.rushyverse.api.player.gui.GUIManager +import java.io.Closeable +import org.bukkit.Server +import org.bukkit.entity.HumanEntity +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack + +/** + * GUI that can be shared by multiple players. + * Only one inventory is created for all the viewers. + * @property server Server. + * @property manager Manager to register or unregister the GUI. + * @property viewers List of viewers. + */ +public abstract class GUI: Closeable { + + protected val server: Server by inject() + + private val manager: GUIManager by inject() + + public var isClosed: Boolean = false + + /** + * Create the inventory of the GUI. + * @return The inventory of the GUI. + */ + protected abstract suspend fun createInventory(client: Client): Inventory + + /** + * Open the inventory for the player. + * @param client Client to open the inventory for. + */ + public abstract suspend fun open(client: Client) + + /** + * Action to do when the client clicks on an item in the inventory. + * @param client Client who clicked. + * @param clickedItem Item clicked by the client. + * @param event Event of the click. + */ + public abstract suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) + + /** + * Close the inventory for the player. + * @param client Client to close the inventory for. + * @return True if the inventory was closed, false otherwise. + */ + public abstract suspend fun close(client: Client): Boolean + + /** + * Close the inventory. + * The inventory will be closed for all the viewers. + * The GUI will be removed from the listener and the [onClick] function will not be called anymore. + */ + public override fun close() { + isClosed = true + unregister() + } + + /** + * Verify that the GUI is open. + * If the GUI is closed, throw an exception. + */ + protected fun requireOpen() { + require(!isClosed) { "Cannot use a closed GUI" } + } + + /** + * Get the viewers of the GUI. + * @return List of viewers. + */ + public abstract suspend fun viewers(): List + + /** + * Check if the GUI contains the player. + * @param client Client to check. + * @return True if the GUI contains the player, false otherwise. + */ + public abstract suspend fun contains(client: Client): Boolean + + /** + * Register the GUI to the listener. + * @return True if the GUI was registered, false otherwise. + */ + protected fun register(): Boolean { + return manager.add(this) + } + + /** + * Unregister the GUI from the listener. + * @return True if the GUI was unregistered, false otherwise. + */ + protected fun unregister(): Boolean { + return manager.remove(this) + } + +} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt new file mode 100644 index 00000000..a2a7ca06 --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -0,0 +1,81 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.extension.toTranslatedComponent +import com.github.rushyverse.api.koin.inject +import com.github.rushyverse.api.player.Client +import com.github.rushyverse.api.translation.Translator +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.bukkit.entity.HumanEntity +import org.bukkit.event.inventory.InventoryType +import org.bukkit.inventory.Inventory + +/** + * GUI where a new inventory is created for each viewer. + * @property inventoryType InventoryType + * @property title String + * @property translator Translator + */ +public abstract class PersonalGUI( + public val inventoryType: InventoryType, + public val title: String +) : GUI() { + + private val translator: Translator by inject() + + private var inventories: MutableMap = mutableMapOf() + + private val mutex = Mutex() + + override suspend fun open(client: Client) { + requireOpen() + + val inventory = createInventory(client) + + mutex.withLock { + val oldInventory = inventories[client] + inventories[client] = inventory + oldInventory + }?.close() + + client.requirePlayer().openInventory(inventory) + } + + override suspend fun createInventory(client: Client): Inventory { + val player = client.requirePlayer() + val translatedTitle = title.toTranslatedComponent(translator, client.lang().locale) + return server.createInventory(player, inventoryType, translatedTitle).also { + fill(client, it) + } + } + + /** + * Fill the inventory with items for the client. + * This function is called when the inventory is created. + * @param client The client to fill the inventory for. + * @param inventory The inventory to fill. + */ + protected abstract suspend fun fill(client: Client, inventory: Inventory) + + override suspend fun close(client: Client): Boolean { + return mutex.withLock { inventories.remove(client) }?.close() == 1 + } + + override suspend fun viewers(): List { + return mutex.withLock { + inventories.values.flatMap(Inventory::getViewers) + } + } + + override suspend fun contains(client: Client): Boolean { + return mutex.withLock { + inventories.containsKey(client) + } + } + + override fun close() { + super.close() + inventories.values.forEach(Inventory::close) + inventories.clear() + } +} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt new file mode 100644 index 00000000..b984da53 --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -0,0 +1,80 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.player.Client +import net.kyori.adventure.text.Component +import org.bukkit.entity.HumanEntity +import org.bukkit.event.inventory.InventoryType +import org.bukkit.inventory.Inventory + +/** + * GUI that can be shared by multiple players. + * Only one inventory is created for all the viewers. + * @property inventoryType Type of the inventory. + * @property title Title of the inventory. + * @property server Server + * @property listener Listener to listen to the clicks on the inventory. + * @property viewers List of viewers. + * @property inventory Inventory shared by all the viewers. + */ +public abstract class SharedGUI( + public val inventoryType: InventoryType, + public val title: Component +): GUI() { + + private var inventory: Inventory? = null + + override suspend fun createInventory(client: Client): Inventory { + return server.createInventory(null, inventoryType, title).also { + fill(it) + } + } + + public override suspend fun open(client: Client) { + val inventory = getOrCreateInventory(client) + client.requirePlayer().openInventory(inventory) + } + + /** + * Get the inventory of the GUI. + * If the inventory is not created, create it. + * @return The inventory of the GUI. + */ + private suspend fun getOrCreateInventory(client: Client): Inventory { + require(!isClosed) { "The GUI is closed" } + + return inventory ?: createInventory(client).also { + inventory = it + register() + } + } + + override suspend fun close(client: Client): Boolean { + val player = client.requirePlayer() + if(player.openInventory.topInventory == inventory) { + player.closeInventory() + return true + } + return false + } + + override suspend fun viewers(): List { + return inventory?.viewers ?: emptyList() + } + + override suspend fun contains(client: Client): Boolean { + return client.player?.let { it in viewers() } == true + } + + override fun close() { + super.close() + inventory?.close() + inventory = null + } + + /** + * Fill the inventory with items for the client. + * This function is called when the inventory is created. + * @param inventory The inventory to fill. + */ + protected abstract suspend fun fill(inventory: Inventory) +} diff --git a/src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt new file mode 100644 index 00000000..3c76e379 --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt @@ -0,0 +1,45 @@ +package com.github.rushyverse.api.listener + +import com.github.rushyverse.api.koin.inject +import com.github.rushyverse.api.player.ClientManager +import org.bukkit.entity.HumanEntity +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.event.player.PlayerQuitEvent + +public class GUIListener : Listener { + + private val clients: ClientManager by inject() + + @EventHandler + public suspend fun onInventoryClick(event: InventoryClickEvent) { + val item = event.currentItem ?: return + val player = event.whoClicked + val client = clients.getClient(player) + client.gui()?.onClick(client, item, event) + } + + @EventHandler + public suspend fun onInventoryClose(event: InventoryCloseEvent) { + val player = event.player + quitOpenedGUI(player) + } + + @EventHandler + public suspend fun onPlayerQuit(event: PlayerQuitEvent) { + quitOpenedGUI(event.player) + } + + /** + * Quit the opened GUI for the player. + * @param player Player to quit the GUI for. + */ + private suspend fun quitOpenedGUI(player: HumanEntity) { + clients.getClientOrNull(player)?.let { + it.gui()?.close(it) + } + } + +} diff --git a/src/main/kotlin/com/github/rushyverse/api/player/Client.kt b/src/main/kotlin/com/github/rushyverse/api/player/Client.kt index 0127a2d3..b8cc4838 100644 --- a/src/main/kotlin/com/github/rushyverse/api/player/Client.kt +++ b/src/main/kotlin/com/github/rushyverse/api/player/Client.kt @@ -2,8 +2,10 @@ package com.github.rushyverse.api.player import com.github.rushyverse.api.delegate.DelegatePlayer import com.github.rushyverse.api.extension.asComponent +import com.github.rushyverse.api.gui.GUI import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.exception.PlayerNotFoundException +import com.github.rushyverse.api.player.gui.GUIManager import com.github.rushyverse.api.player.language.LanguageManager import com.github.rushyverse.api.player.scoreboard.ScoreboardManager import com.github.rushyverse.api.translation.SupportedLanguage @@ -28,6 +30,8 @@ public open class Client( private val languageManager: LanguageManager by inject() + private val guiManager: GUIManager by inject() + public val player: Player? by DelegatePlayer(playerUUID) /** @@ -60,7 +64,6 @@ public open class Client( send(message.asComponent()) } - /** * Retrieve the scoreboard of the player. * The scoreboard will be created if it doesn't exist. @@ -74,4 +77,10 @@ public open class Client( */ public suspend fun lang(): SupportedLanguage = languageManager.get(requirePlayer()) + /** + * Get the opened GUI of the player. + * @return The opened GUI of the player. + */ + public suspend fun gui(): GUI? = guiManager.get(this) + } diff --git a/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt b/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt index 0c88e8a6..dd00fe52 100644 --- a/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt +++ b/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt @@ -1,13 +1,16 @@ package com.github.rushyverse.api.player -import org.bukkit.entity.Player +import com.github.rushyverse.api.player.exception.ClientNotFoundException +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.bukkit.entity.HumanEntity /** * Get a client from the player instance. * @param player Player. * @return The client linked to a player. */ -public suspend inline fun ClientManager.getTypedClient(player: Player): T = getClient(player) as T +public suspend inline fun ClientManager.getTypedClient(player: HumanEntity): T = getClient(player) as T /** * Get a client from the key linked to a player. @@ -21,7 +24,7 @@ public suspend inline fun ClientManager.getTypedClient(key: * @param player Player. * @return The client linked to a player, `null` if not found. */ -public suspend inline fun ClientManager.getTypedClientOrNull(player: Player): T? = +public suspend inline fun ClientManager.getTypedClientOrNull(player: HumanEntity): T? = getClientOrNull(player) as T? /** @@ -45,28 +48,28 @@ public interface ClientManager { * @param client New client added. * @return The previous value associated with a key, or null there is none. */ - public suspend fun put(player: Player, client: Client): Client? + public suspend fun put(player: HumanEntity, client: Client): Client? /** * Put a new client in the server if no client is linked to the player. * @param client New client added. * @return The previous value associated with a key, or null there is none. */ - public suspend fun putIfAbsent(player: Player, client: Client): Client? + public suspend fun putIfAbsent(player: HumanEntity, client: Client): Client? /** * Remove a client from the server by a Player. * @param player Player linked to a Client. * @return The client that was removed null otherwise. */ - public suspend fun removeClient(player: Player): Client? + public suspend fun removeClient(player: HumanEntity): Client? /** * Get a client from the player instance. * @param player Player. * @return The client linked to a player. */ - public suspend fun getClient(player: Player): Client + public suspend fun getClient(player: HumanEntity): Client /** * Get a client from the key linked to a player. @@ -80,7 +83,7 @@ public interface ClientManager { * @param player Player. * @return The client linked to a player, `null` if not found. */ - public suspend fun getClientOrNull(player: Player): Client? + public suspend fun getClientOrNull(player: HumanEntity): Client? /** * Get a client from the key linked to a player. @@ -94,5 +97,63 @@ public interface ClientManager { * @param player Player. * @return `true` if there is a client for the player, `false` otherwise. */ - public suspend fun contains(player: Player): Boolean + public suspend fun contains(player: HumanEntity): Boolean +} + +/** + * Manage the existing client present in the server. + * The clients are stored with the name of the player. + * @property _clients Synchronized mutable map of clients as value and name of player as a key. + */ +public class ClientManagerImpl : ClientManager { + + private val mutex = Mutex() + + /** + * All clients in server linked by the name of player. + */ + private val _clients = mutableMapOf() + + override val clients: Map = _clients + + override suspend fun put( + player: HumanEntity, + client: Client + ): Client? = mutex.withLock { + _clients.put(player.name, client) + } + + override suspend fun putIfAbsent( + player: HumanEntity, + client: Client + ): Client? = mutex.withLock { + _clients.putIfAbsent(getKey(player), client) + } + + override suspend fun removeClient(player: HumanEntity): Client? = mutex.withLock { + _clients.remove(getKey(player)) + } + + override suspend fun getClient(player: HumanEntity): Client = getClient(getKey(player)) + + override suspend fun getClient(key: String): Client = + getClientOrNull(key) ?: throw ClientNotFoundException("No client is linked to the name [$key]") + + override suspend fun getClientOrNull(player: HumanEntity): Client? = getClientOrNull(getKey(player)) + + override suspend fun getClientOrNull(key: String): Client? = mutex.withLock { + _clients[key] + } + + /** + * Key use for the Map + * @param p Player that has the key + * @return The key for the Map + */ + private fun getKey(p: HumanEntity): String = p.name + + override suspend fun contains(player: HumanEntity): Boolean = mutex.withLock { + _clients.containsKey(getKey(player)) + } + } diff --git a/src/main/kotlin/com/github/rushyverse/api/player/ClientManagerImpl.kt b/src/main/kotlin/com/github/rushyverse/api/player/ClientManagerImpl.kt deleted file mode 100644 index 23aa19de..00000000 --- a/src/main/kotlin/com/github/rushyverse/api/player/ClientManagerImpl.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.github.rushyverse.api.player - -import com.github.rushyverse.api.player.exception.ClientNotFoundException -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import org.bukkit.entity.Player - -/** - * Manage the existing client present in the server. - * The clients are stored with the name of the player. - * @property _clients Synchronized mutable map of clients as value and name of player as a key. - */ -public class ClientManagerImpl : ClientManager { - - private val mutex = Mutex() - - /** - * All clients in server linked by the name of player. - */ - private val _clients = mutableMapOf() - - override val clients: Map = _clients - - override suspend fun put( - player: Player, - client: Client - ): Client? = mutex.withLock { - _clients.put(player.name, client) - } - - override suspend fun putIfAbsent( - player: Player, - client: Client - ): Client? = mutex.withLock { - _clients.putIfAbsent(getKey(player), client) - } - - override suspend fun removeClient(player: Player): Client? = mutex.withLock { - _clients.remove(getKey(player)) - } - - override suspend fun getClient(player: Player): Client = getClient(getKey(player)) - - override suspend fun getClient(key: String): Client = - getClientOrNull(key) ?: throw ClientNotFoundException("No client is linked to the name [$key]") - - override suspend fun getClientOrNull(player: Player): Client? = getClientOrNull(getKey(player)) - - override suspend fun getClientOrNull(key: String): Client? = mutex.withLock { - _clients[key] - } - - /** - * Key use for the Map - * @param p Player that has the key - * @return The key for the Map - */ - private fun getKey(p: Player): String = p.name - - override suspend fun contains(player: Player): Boolean = mutex.withLock { - _clients.containsKey(getKey(player)) - } - -} diff --git a/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt b/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt new file mode 100644 index 00000000..7ffecc6e --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt @@ -0,0 +1,58 @@ +package com.github.rushyverse.api.player.gui + +import com.github.rushyverse.api.gui.GUI +import com.github.rushyverse.api.player.Client +import kotlinx.coroutines.sync.Mutex + +/** + * Manages the GUIs for players within the game. + * This class ensures thread-safe operations on the GUIs by using mutex locks. + */ +public class GUIManager { + + /** + * Mutex used to ensure thread-safe operations. + */ + private val mutex = Mutex() + + /** + * Private mutable set storing GUIs. + */ + private val _guis = mutableSetOf() + + /** + * Immutable view of the GUIs set. + */ + public val guis: Set = _guis + + /** + * Retrieves the GUI for the specified player. + * This function is thread-safe and uses mutex locks to ensure atomic operations. + * + * @param client The player for whom the GUI is to be retrieved or created. + * @return The language associated with the player. + */ + public suspend fun get(client: Client): GUI? { + return _guis.firstOrNull { it.contains(client) } + } + + /** + * Add a GUI to the listener. + * @param gui GUI to add. + * @return True if the GUI was added, false otherwise. + */ + public fun add(gui: GUI): Boolean { + return _guis.add(gui) + } + + /** + * Remove a GUI from the listener. + * @param gui GUI to remove. + * @return True if the GUI was removed, false otherwise. + */ + public fun remove(gui: GUI): Boolean { + return _guis.remove(gui) + } + + +} From 9431249330741a2cfe075fbd21cfd2c88d126cc4 Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 14 Dec 2023 14:53:20 +0100 Subject: [PATCH 02/48] chore: Remove unused property --- src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt | 1 - .../com/github/rushyverse/api/player/gui/GUIManager.kt | 6 ------ 2 files changed, 7 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index b984da53..0bb0c84c 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -12,7 +12,6 @@ import org.bukkit.inventory.Inventory * @property inventoryType Type of the inventory. * @property title Title of the inventory. * @property server Server - * @property listener Listener to listen to the clicks on the inventory. * @property viewers List of viewers. * @property inventory Inventory shared by all the viewers. */ diff --git a/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt b/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt index 7ffecc6e..c390a91c 100644 --- a/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt +++ b/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt @@ -2,7 +2,6 @@ package com.github.rushyverse.api.player.gui import com.github.rushyverse.api.gui.GUI import com.github.rushyverse.api.player.Client -import kotlinx.coroutines.sync.Mutex /** * Manages the GUIs for players within the game. @@ -10,11 +9,6 @@ import kotlinx.coroutines.sync.Mutex */ public class GUIManager { - /** - * Mutex used to ensure thread-safe operations. - */ - private val mutex = Mutex() - /** * Private mutable set storing GUIs. */ From a960c1196790c34afa16ad2f29635c366724c2a9 Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 14 Dec 2023 18:15:46 +0100 Subject: [PATCH 03/48] fix: Stack overflow when close gui --- build.gradle.kts | 11 +++ gradle/wrapper/gradle-wrapper.properties | 2 +- .../com/github/rushyverse/api/APIPlugin.kt | 2 + .../com/github/rushyverse/api/Plugin.kt | 15 +++- .../com/github/rushyverse/api/gui/GUI.kt | 16 +++-- .../github/rushyverse/api/gui/GUIListener.kt | 72 +++++++++++++++++++ .../api/{player => }/gui/GUIManager.kt | 5 +- .../github/rushyverse/api/gui/PersonalGUI.kt | 9 ++- .../github/rushyverse/api/gui/SharedGUI.kt | 7 +- .../rushyverse/api/listener/GUIListener.kt | 45 ------------ .../github/rushyverse/api/player/Client.kt | 4 +- .../rushyverse/api/player/ClientManager.kt | 3 +- 12 files changed, 124 insertions(+), 67 deletions(-) create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt rename src/main/kotlin/com/github/rushyverse/api/{player => }/gui/GUIManager.kt (93%) delete mode 100644 src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt diff --git a/build.gradle.kts b/build.gradle.kts index b22c5bcc..153f3e40 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,3 +1,4 @@ +import io.gitlab.arturbosch.detekt.Detekt import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { @@ -130,6 +131,16 @@ tasks { targetCompatibility = javaVersionString } + withType().configureEach { + reports { + html.required.set(true) + xml.required.set(true) + txt.required.set(false) + sarif.required.set(false) + md.required.set(false) + } + } + test { useJUnitPlatform() } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index c9eb15be..a5952066 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-rc-1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt b/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt index 2bb5d419..e1b0480e 100644 --- a/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt +++ b/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt @@ -2,6 +2,7 @@ package com.github.rushyverse.api import com.github.rushyverse.api.extension.registerListener import com.github.rushyverse.api.game.SharedGameData +import com.github.rushyverse.api.gui.GUIManager import com.github.rushyverse.api.koin.CraftContext import com.github.rushyverse.api.koin.loadModule import com.github.rushyverse.api.listener.api.LanguageListener @@ -37,6 +38,7 @@ public class APIPlugin : JavaPlugin() { single { ScoreboardManager() } single { LanguageManager() } single { SharedGameData() } + single { GUIManager() } } registerListener { LanguageListener() } diff --git a/src/main/kotlin/com/github/rushyverse/api/Plugin.kt b/src/main/kotlin/com/github/rushyverse/api/Plugin.kt index 31d770e5..58315a14 100644 --- a/src/main/kotlin/com/github/rushyverse/api/Plugin.kt +++ b/src/main/kotlin/com/github/rushyverse/api/Plugin.kt @@ -7,6 +7,7 @@ import com.github.rushyverse.api.configuration.reader.IFileReader import com.github.rushyverse.api.configuration.reader.YamlFileReader import com.github.rushyverse.api.extension.asComponent import com.github.rushyverse.api.extension.registerListener +import com.github.rushyverse.api.gui.GUIListener import com.github.rushyverse.api.koin.CraftContext import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.koin.loadModule @@ -16,11 +17,21 @@ import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl import com.github.rushyverse.api.player.language.LanguageManager -import com.github.rushyverse.api.serializer.* +import com.github.rushyverse.api.serializer.ComponentSerializer +import com.github.rushyverse.api.serializer.DyeColorSerializer +import com.github.rushyverse.api.serializer.EnchantmentSerializer +import com.github.rushyverse.api.serializer.ItemStackSerializer +import com.github.rushyverse.api.serializer.LocationSerializer +import com.github.rushyverse.api.serializer.MaterialSerializer +import com.github.rushyverse.api.serializer.NamespacedSerializer +import com.github.rushyverse.api.serializer.PatternSerializer +import com.github.rushyverse.api.serializer.PatternTypeSerializer +import com.github.rushyverse.api.serializer.RangeDoubleSerializer import com.github.rushyverse.api.translation.ResourceBundleTranslator import com.github.rushyverse.api.translation.Translator import com.github.rushyverse.api.translation.registerResourceBundleForSupportedLocales import com.github.shynixn.mccoroutine.bukkit.SuspendingJavaPlugin +import java.util.* import kotlinx.serialization.modules.SerializersModule import kotlinx.serialization.modules.SerializersModuleBuilder import kotlinx.serialization.modules.contextual @@ -29,7 +40,6 @@ import org.bukkit.entity.Player import org.jetbrains.annotations.Blocking import org.koin.core.module.Module import org.koin.dsl.bind -import java.util.* /** * Represents the base functionality required to create a plugin. @@ -70,6 +80,7 @@ public abstract class Plugin( registerListener { PlayerListener(this) } registerListener { VillagerListener(this) } + registerListener { GUIListener(this) } } /** diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index c60c3f4b..6c6fada8 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -2,7 +2,6 @@ package com.github.rushyverse.api.gui import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.Client -import com.github.rushyverse.api.player.gui.GUIManager import java.io.Closeable import org.bukkit.Server import org.bukkit.entity.HumanEntity @@ -15,9 +14,9 @@ import org.bukkit.inventory.ItemStack * Only one inventory is created for all the viewers. * @property server Server. * @property manager Manager to register or unregister the GUI. - * @property viewers List of viewers. + * @property isClosed If true, the GUI is closed; otherwise it is open. */ -public abstract class GUI: Closeable { +public abstract class GUI : Closeable { protected val server: Server by inject() @@ -25,6 +24,10 @@ public abstract class GUI: Closeable { public var isClosed: Boolean = false + init { + register() + } + /** * Create the inventory of the GUI. * @return The inventory of the GUI. @@ -46,11 +49,12 @@ public abstract class GUI: Closeable { public abstract suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) /** - * Close the inventory for the player. - * @param client Client to close the inventory for. + * Remove the client has a viewer of the GUI. + * @param client Client to close the GUI for. + * @param closeInventory If true, the interface will be closed, otherwise it will be kept open. * @return True if the inventory was closed, false otherwise. */ - public abstract suspend fun close(client: Client): Boolean + public abstract suspend fun close(client: Client, closeInventory: Boolean = true): Boolean /** * Close the inventory. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt new file mode 100644 index 00000000..63c83452 --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt @@ -0,0 +1,72 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.Plugin +import com.github.rushyverse.api.extension.event.cancel +import com.github.rushyverse.api.koin.inject +import com.github.rushyverse.api.player.ClientManager +import org.bukkit.entity.HumanEntity +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.event.player.PlayerQuitEvent + +/** + * Listener for GUI events. + * @property clients Manager of clients. + */ +public class GUIListener(plugin: Plugin) : Listener { + + private val clients: ClientManager by inject(plugin.id) + + /** + * Called when a player clicks on an item in an inventory. + * If the click is detected in a GUI, the event is cancelled and the GUI is notified. + * @param event Event of the click. + */ + @EventHandler + public suspend fun onInventoryClick(event: InventoryClickEvent) { + if (event.isCancelled) return + val item = event.currentItem ?: return + val player = event.whoClicked + + val client = clients.getClient(player) + val gui = client.gui() ?: return + + // The item in a GUI is not supposed to be moved + event.cancel() + gui.onClick(client, item, event) + } + + /** + * Called when a player closes an inventory. + * If the inventory is a GUI, the GUI is notified that it is closed for this player. + * @param event Event of the close. + */ + @EventHandler + public suspend fun onInventoryClose(event: InventoryCloseEvent) { + quitOpenedGUI(event.player) + } + + /** + * Called when a player quits the server. + * If the player has a GUI opened, the GUI is notified that it is closed for this player. + * @param event Event of the quit. + */ + @EventHandler + public suspend fun onPlayerQuit(event: PlayerQuitEvent) { + quitOpenedGUI(event.player) + } + + /** + * Quit the opened GUI for the player. + * @param player Player to quit the GUI for. + */ + private suspend fun quitOpenedGUI(player: HumanEntity) { + val client = clients.getClientOrNull(player) + val gui = client?.gui() ?: return + // We don't close the inventory because it is closing due to event. + gui.close(client, false) + } + +} diff --git a/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt similarity index 93% rename from src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt rename to src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt index c390a91c..0f523eda 100644 --- a/src/main/kotlin/com/github/rushyverse/api/player/gui/GUIManager.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt @@ -1,6 +1,5 @@ -package com.github.rushyverse.api.player.gui +package com.github.rushyverse.api.gui -import com.github.rushyverse.api.gui.GUI import com.github.rushyverse.api.player.Client /** @@ -47,6 +46,4 @@ public class GUIManager { public fun remove(gui: GUI): Boolean { return _guis.remove(gui) } - - } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index a2a7ca06..0f7118ab 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -57,8 +57,13 @@ public abstract class PersonalGUI( */ protected abstract suspend fun fill(client: Client, inventory: Inventory) - override suspend fun close(client: Client): Boolean { - return mutex.withLock { inventories.remove(client) }?.close() == 1 + override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + return mutex.withLock { inventories.remove(client) }?.run { + if (closeInventory) { + close() + } + true + } == true } override suspend fun viewers(): List { diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index 0bb0c84c..4e701a09 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -18,7 +18,7 @@ import org.bukkit.inventory.Inventory public abstract class SharedGUI( public val inventoryType: InventoryType, public val title: Component -): GUI() { +) : GUI() { private var inventory: Inventory? = null @@ -43,13 +43,12 @@ public abstract class SharedGUI( return inventory ?: createInventory(client).also { inventory = it - register() } } - override suspend fun close(client: Client): Boolean { + override suspend fun close(client: Client, closeInventory: Boolean): Boolean { val player = client.requirePlayer() - if(player.openInventory.topInventory == inventory) { + if (closeInventory && player.openInventory.topInventory == inventory) { player.closeInventory() return true } diff --git a/src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt deleted file mode 100644 index 3c76e379..00000000 --- a/src/main/kotlin/com/github/rushyverse/api/listener/GUIListener.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.github.rushyverse.api.listener - -import com.github.rushyverse.api.koin.inject -import com.github.rushyverse.api.player.ClientManager -import org.bukkit.entity.HumanEntity -import org.bukkit.event.EventHandler -import org.bukkit.event.Listener -import org.bukkit.event.inventory.InventoryClickEvent -import org.bukkit.event.inventory.InventoryCloseEvent -import org.bukkit.event.player.PlayerQuitEvent - -public class GUIListener : Listener { - - private val clients: ClientManager by inject() - - @EventHandler - public suspend fun onInventoryClick(event: InventoryClickEvent) { - val item = event.currentItem ?: return - val player = event.whoClicked - val client = clients.getClient(player) - client.gui()?.onClick(client, item, event) - } - - @EventHandler - public suspend fun onInventoryClose(event: InventoryCloseEvent) { - val player = event.player - quitOpenedGUI(player) - } - - @EventHandler - public suspend fun onPlayerQuit(event: PlayerQuitEvent) { - quitOpenedGUI(event.player) - } - - /** - * Quit the opened GUI for the player. - * @param player Player to quit the GUI for. - */ - private suspend fun quitOpenedGUI(player: HumanEntity) { - clients.getClientOrNull(player)?.let { - it.gui()?.close(it) - } - } - -} diff --git a/src/main/kotlin/com/github/rushyverse/api/player/Client.kt b/src/main/kotlin/com/github/rushyverse/api/player/Client.kt index b8cc4838..bb6ff06f 100644 --- a/src/main/kotlin/com/github/rushyverse/api/player/Client.kt +++ b/src/main/kotlin/com/github/rushyverse/api/player/Client.kt @@ -3,18 +3,18 @@ package com.github.rushyverse.api.player import com.github.rushyverse.api.delegate.DelegatePlayer import com.github.rushyverse.api.extension.asComponent import com.github.rushyverse.api.gui.GUI +import com.github.rushyverse.api.gui.GUIManager import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.exception.PlayerNotFoundException -import com.github.rushyverse.api.player.gui.GUIManager import com.github.rushyverse.api.player.language.LanguageManager import com.github.rushyverse.api.player.scoreboard.ScoreboardManager import com.github.rushyverse.api.translation.SupportedLanguage import fr.mrmicky.fastboard.adventure.FastBoard +import java.util.* import kotlinx.coroutines.CoroutineScope import net.kyori.adventure.text.Component import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver import org.bukkit.entity.Player -import java.util.* /** * Client to store and manage data about player. diff --git a/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt b/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt index dd00fe52..6835f1d6 100644 --- a/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt +++ b/src/main/kotlin/com/github/rushyverse/api/player/ClientManager.kt @@ -10,7 +10,8 @@ import org.bukkit.entity.HumanEntity * @param player Player. * @return The client linked to a player. */ -public suspend inline fun ClientManager.getTypedClient(player: HumanEntity): T = getClient(player) as T +public suspend inline fun ClientManager.getTypedClient(player: HumanEntity): T = + getClient(player) as T /** * Get a client from the key linked to a player. From c532cf8e998f2ceb41a0e3252270d464e70bc39b Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 14 Dec 2023 19:29:55 +0100 Subject: [PATCH 04/48] fix: Add way to create inventory from scratch --- .../com/github/rushyverse/api/gui/GUI.kt | 1 + .../github/rushyverse/api/gui/PersonalGUI.kt | 20 +++++++++----- .../github/rushyverse/api/gui/SharedGUI.kt | 27 ++++++++++--------- 3 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 6c6fada8..ee6c0682 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -23,6 +23,7 @@ public abstract class GUI : Closeable { private val manager: GUIManager by inject() public var isClosed: Boolean = false + protected set init { register() diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 0f7118ab..749989d1 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -6,20 +6,19 @@ import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.translation.Translator import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import net.kyori.adventure.text.Component import org.bukkit.entity.HumanEntity +import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryType import org.bukkit.inventory.Inventory +import org.bukkit.inventory.InventoryHolder /** * GUI where a new inventory is created for each viewer. - * @property inventoryType InventoryType * @property title String * @property translator Translator */ -public abstract class PersonalGUI( - public val inventoryType: InventoryType, - public val title: String -) : GUI() { +public abstract class PersonalGUI(public val title: String) : GUI() { private val translator: Translator by inject() @@ -44,11 +43,20 @@ public abstract class PersonalGUI( override suspend fun createInventory(client: Client): Inventory { val player = client.requirePlayer() val translatedTitle = title.toTranslatedComponent(translator, client.lang().locale) - return server.createInventory(player, inventoryType, translatedTitle).also { + return createInventory(player, translatedTitle).also { fill(client, it) } } + /** + * Create the inventory for the client. + * This function is called when the [owner] wants to open the inventory. + * @param owner Player who wants to open the inventory. + * @param title Translated title of the inventory. + * @return The inventory for the client. + */ + protected abstract fun createInventory(owner: InventoryHolder, title: Component): Inventory + /** * Fill the inventory with items for the client. * This function is called when the inventory is created. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index 4e701a09..97fe5020 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -5,29 +5,19 @@ import net.kyori.adventure.text.Component import org.bukkit.entity.HumanEntity import org.bukkit.event.inventory.InventoryType import org.bukkit.inventory.Inventory +import org.bukkit.inventory.InventoryHolder /** * GUI that can be shared by multiple players. * Only one inventory is created for all the viewers. - * @property inventoryType Type of the inventory. - * @property title Title of the inventory. * @property server Server * @property viewers List of viewers. * @property inventory Inventory shared by all the viewers. */ -public abstract class SharedGUI( - public val inventoryType: InventoryType, - public val title: Component -) : GUI() { +public abstract class SharedGUI : GUI() { private var inventory: Inventory? = null - override suspend fun createInventory(client: Client): Inventory { - return server.createInventory(null, inventoryType, title).also { - fill(it) - } - } - public override suspend fun open(client: Client) { val inventory = getOrCreateInventory(client) client.requirePlayer().openInventory(inventory) @@ -46,6 +36,19 @@ public abstract class SharedGUI( } } + override suspend fun createInventory(client: Client): Inventory { + return createInventory().also { + fill(it) + } + } + + /** + * Create the inventory of the GUI. + * This function is called only once when the inventory is created. + * @return A new inventory. + */ + protected abstract fun createInventory(): Inventory + override suspend fun close(client: Client, closeInventory: Boolean): Boolean { val player = client.requirePlayer() if (closeInventory && player.openInventory.topInventory == inventory) { From 0fc9c1476b0b65244aecff4741e3025613dc3e14 Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 14 Dec 2023 19:32:16 +0100 Subject: [PATCH 05/48] fix: Use requireOpen function --- src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt | 1 - src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 749989d1..80761d60 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -28,7 +28,6 @@ public abstract class PersonalGUI(public val title: String) : GUI() { override suspend fun open(client: Client) { requireOpen() - val inventory = createInventory(client) mutex.withLock { diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index 97fe5020..6df1ccf0 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -29,8 +29,7 @@ public abstract class SharedGUI : GUI() { * @return The inventory of the GUI. */ private suspend fun getOrCreateInventory(client: Client): Inventory { - require(!isClosed) { "The GUI is closed" } - + requireOpen() return inventory ?: createInventory(client).also { inventory = it } From 74cd7045c83c02b092aa9940a6cd5145e477d874 Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 14 Dec 2023 19:33:03 +0100 Subject: [PATCH 06/48] chore: Format --- src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt | 2 -- src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt | 3 --- 2 files changed, 5 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 80761d60..30007e8e 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -8,8 +8,6 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import net.kyori.adventure.text.Component import org.bukkit.entity.HumanEntity -import org.bukkit.entity.Player -import org.bukkit.event.inventory.InventoryType import org.bukkit.inventory.Inventory import org.bukkit.inventory.InventoryHolder diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index 6df1ccf0..3a23d61a 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -1,11 +1,8 @@ package com.github.rushyverse.api.gui import com.github.rushyverse.api.player.Client -import net.kyori.adventure.text.Component import org.bukkit.entity.HumanEntity -import org.bukkit.event.inventory.InventoryType import org.bukkit.inventory.Inventory -import org.bukkit.inventory.InventoryHolder /** * GUI that can be shared by multiple players. From 96d23fb16696bf4c69dd79be26dea6250f18446a Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 14 Dec 2023 19:36:47 +0100 Subject: [PATCH 07/48] fix: Change scope property --- src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 30007e8e..959fb6bb 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -18,7 +18,7 @@ import org.bukkit.inventory.InventoryHolder */ public abstract class PersonalGUI(public val title: String) : GUI() { - private val translator: Translator by inject() + protected val translator: Translator by inject() private var inventories: MutableMap = mutableMapOf() From 85c1f89c4c3a94c56a21af8cf199e1ff91928988 Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 09:35:49 +0100 Subject: [PATCH 08/48] fix: Safe open by multiple check --- .../com/github/rushyverse/api/gui/GUI.kt | 36 ++++- .../github/rushyverse/api/gui/GUIManager.kt | 2 +- .../github/rushyverse/api/gui/PersonalGUI.kt | 26 ++-- .../github/rushyverse/api/gui/SharedGUI.kt | 19 +-- .../rushyverse/api/gui/GUIManagerTest.kt | 131 ++++++++++++++++++ .../rushyverse/api/player/ClientTest.kt | 88 +++++++++--- 6 files changed, 252 insertions(+), 50 deletions(-) create mode 100644 src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index ee6c0682..dafb3f9b 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -3,12 +3,14 @@ package com.github.rushyverse.api.gui import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.Client import java.io.Closeable +import mu.KotlinLogging import org.bukkit.Server import org.bukkit.entity.HumanEntity import org.bukkit.event.inventory.InventoryClickEvent -import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack +private val logger = KotlinLogging.logger {} + /** * GUI that can be shared by multiple players. * Only one inventory is created for all the viewers. @@ -30,16 +32,36 @@ public abstract class GUI : Closeable { } /** - * Create the inventory of the GUI. - * @return The inventory of the GUI. + * Open the GUI for the client only if the GUI is not closed. + * If the client has another GUI opened, close it. + * If the client has the same GUI opened, do nothing. + * @param client Client to open the GUI for. */ - protected abstract suspend fun createInventory(client: Client): Inventory + public suspend fun open(client: Client) { + requireOpen() + + val gui = client.gui() + if (gui == this) return + // If the client has another GUI opened, close it. + gui?.close(client, true) + + val player = client.player + if (player == null) { + logger.warn { "Cannot open inventory for player ${client.playerUUID}: player is null" } + return + } + // If the player is dead, do not open the GUI because the interface cannot be shown to the player. + if (player.isDead) return + + openGUI(client) + } /** - * Open the inventory for the player. - * @param client Client to open the inventory for. + * Open the GUI for the client. + * Called by [open] after all the checks. + * @param client Client to open the GUI for. */ - public abstract suspend fun open(client: Client) + protected abstract suspend fun openGUI(client: Client) /** * Action to do when the client clicks on an item in the inventory. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt index 0f523eda..f110d828 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt @@ -16,7 +16,7 @@ public class GUIManager { /** * Immutable view of the GUIs set. */ - public val guis: Set = _guis + public val guis: Collection get() = _guis /** * Retrieves the GUI for the specified player. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 959fb6bb..598849cd 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -13,8 +13,8 @@ import org.bukkit.inventory.InventoryHolder /** * GUI where a new inventory is created for each viewer. - * @property title String - * @property translator Translator + * @property title Title that can be translated. + * @property translator Translator to translate the title. */ public abstract class PersonalGUI(public val title: String) : GUI() { @@ -24,20 +24,24 @@ public abstract class PersonalGUI(public val title: String) : GUI() { private val mutex = Mutex() - override suspend fun open(client: Client) { - requireOpen() + override suspend fun openGUI(client: Client) { val inventory = createInventory(client) - mutex.withLock { - val oldInventory = inventories[client] - inventories[client] = inventory - oldInventory - }?.close() + mutex.withLock { inventories[client] }?.close() - client.requirePlayer().openInventory(inventory) + val player = client.requirePlayer() + player.openInventory(inventory) + + mutex.withLock { inventories[client] = inventory } } - override suspend fun createInventory(client: Client): Inventory { + /** + * Create the inventory for the client. + * Will translate the title and fill the inventory. + * @param client The client to create the inventory for. + * @return The inventory for the client. + */ + private suspend fun createInventory(client: Client): Inventory { val player = client.requirePlayer() val translatedTitle = title.toTranslatedComponent(translator, client.lang().locale) return createInventory(player, translatedTitle).also { diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index 3a23d61a..c023dcb6 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -7,7 +7,7 @@ import org.bukkit.inventory.Inventory /** * GUI that can be shared by multiple players. * Only one inventory is created for all the viewers. - * @property server Server + * @property server Server. * @property viewers List of viewers. * @property inventory Inventory shared by all the viewers. */ @@ -15,9 +15,10 @@ public abstract class SharedGUI : GUI() { private var inventory: Inventory? = null - public override suspend fun open(client: Client) { - val inventory = getOrCreateInventory(client) - client.requirePlayer().openInventory(inventory) + override suspend fun openGUI(client: Client) { + val player = client.requirePlayer() + val inventory = getOrCreateInventory() + player.openInventory(inventory) } /** @@ -25,15 +26,9 @@ public abstract class SharedGUI : GUI() { * If the inventory is not created, create it. * @return The inventory of the GUI. */ - private suspend fun getOrCreateInventory(client: Client): Inventory { - requireOpen() - return inventory ?: createInventory(client).also { + private suspend fun getOrCreateInventory(): Inventory { + return inventory ?: createInventory().also { inventory = it - } - } - - override suspend fun createInventory(client: Client): Inventory { - return createInventory().also { fill(it) } } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt new file mode 100644 index 00000000..e861e595 --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt @@ -0,0 +1,131 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.player.Client +import io.kotest.matchers.shouldBe +import io.mockk.coEvery +import io.mockk.mockk +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Nested + +class GUIManagerTest { + + private lateinit var manager: GUIManager + + @BeforeTest + fun onBefore() { + manager = GUIManager() + } + + @Nested + inner class Get { + + @Test + fun `should returns null if no GUI is registered`() = runTest { + val client = mockk() + manager.get(client) shouldBe null + } + + @Test + fun `should returns null if no GUI contains the client`() = runTest { + val client = mockk() + val gui = mockk { + coEvery { contains(any()) } returns false + } + manager.add(gui) + manager.get(client) shouldBe null + } + + @Test + fun `should returns GUI if contains the client`() = runTest { + val client = mockk() + val gui = mockk { + coEvery { contains(client) } returns true + } + manager.add(gui) + manager.get(client) shouldBe gui + } + + @Test + fun `should returns GUI if contains the asked client`() = runTest { + val client = mockk() + val client2 = mockk() + val gui = mockk { + coEvery { contains(client) } returns true + coEvery { contains(client2) } returns false + } + manager.add(gui) + manager.get(client) shouldBe gui + manager.get(client2) shouldBe null + } + + } + + @Nested + inner class Add { + + @Test + fun `should add non registered GUI`() { + val gui = mockk() + manager.add(gui) shouldBe true + manager.guis.contains(gui) shouldBe true + manager.guis.size shouldBe 1 + } + + @Test + fun `should not add registered GUI`() { + val gui = mockk() + manager.add(gui) shouldBe true + manager.add(gui) shouldBe false + manager.guis.contains(gui) shouldBe true + manager.guis.size shouldBe 1 + } + + @Test + fun `should add multiple GUIs`() { + val gui1 = mockk() + val gui2 = mockk() + manager.add(gui1) shouldBe true + manager.add(gui2) shouldBe true + manager.guis.contains(gui1) shouldBe true + manager.guis.contains(gui2) shouldBe true + manager.guis.size shouldBe 2 + } + + } + + @Nested + inner class Remove { + + @Test + fun `should remove registered GUI`() { + val gui = mockk() + manager.add(gui) shouldBe true + manager.remove(gui) shouldBe true + manager.guis.contains(gui) shouldBe false + manager.guis.size shouldBe 0 + } + + @Test + fun `should not remove non registered GUI`() { + val gui = mockk() + manager.remove(gui) shouldBe false + manager.guis.contains(gui) shouldBe false + manager.guis.size shouldBe 0 + } + + @Test + fun `should remove one GUI`() { + val gui1 = mockk() + val gui2 = mockk() + manager.add(gui1) shouldBe true + manager.add(gui2) shouldBe true + manager.remove(gui1) shouldBe true + manager.guis.contains(gui1) shouldBe false + manager.guis.contains(gui2) shouldBe true + manager.guis.size shouldBe 1 + } + + } +} diff --git a/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt b/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt index 554a6237..7d356af7 100644 --- a/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt @@ -4,17 +4,25 @@ import be.seeseemelk.mockbukkit.MockBukkit import be.seeseemelk.mockbukkit.ServerMock import be.seeseemelk.mockbukkit.entity.PlayerMock import com.github.rushyverse.api.AbstractKoinTest +import com.github.rushyverse.api.gui.GUI +import com.github.rushyverse.api.gui.GUIManager import com.github.rushyverse.api.player.exception.PlayerNotFoundException +import io.kotest.matchers.shouldBe +import io.mockk.coEvery +import io.mockk.mockk import kotlinx.coroutines.CoroutineScope import org.junit.jupiter.api.assertThrows import java.util.* import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.* +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Nested class ClientTest : AbstractKoinTest() { private lateinit var player: PlayerMock private lateinit var serverMock: ServerMock + private lateinit var guiManager: GUIManager @BeforeTest override fun onBefore() { @@ -22,6 +30,11 @@ class ClientTest : AbstractKoinTest() { serverMock = MockBukkit.mock().apply { player = addPlayer() } + guiManager = GUIManager() + + loadApiTestModule { + single { guiManager } + } } @AfterTest @@ -30,29 +43,66 @@ class ClientTest : AbstractKoinTest() { super.onAfter() } - @Test - fun `retrieve player instance not found returns null`() { - val client = Client(UUID.randomUUID(), CoroutineScope(EmptyCoroutineContext)) - assertNull(client.player) - } + @Nested + inner class GetPlayer { - @Test - fun `retrieve player instance found returns the instance`() { - val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) - assertEquals(player, client.player) - } + @Test + fun `retrieve player instance not found returns null`() { + val client = Client(UUID.randomUUID(), CoroutineScope(EmptyCoroutineContext)) + assertNull(client.player) + } + + @Test + fun `retrieve player instance found returns the instance`() { + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + assertEquals(player, client.player) + } + + @Test + fun `require player instance not found throws an exception`() { + val client = Client(UUID.randomUUID(), CoroutineScope(EmptyCoroutineContext)) + assertThrows { + client.requirePlayer() + } + } - @Test - fun `require player instance not found throws an exception`() { - val client = Client(UUID.randomUUID(), CoroutineScope(EmptyCoroutineContext)) - assertThrows { - client.requirePlayer() + @Test + fun `require player instance found returns the instance`() { + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + assertEquals(player, client.requirePlayer()) } + } - @Test - fun `require player instance found returns the instance`() { - val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) - assertEquals(player, client.requirePlayer()) + @Nested + inner class GetGUI { + + @Test + fun `get GUI returns null if no GUI is registered`() = runTest { + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + client.gui() shouldBe null + } + + @Test + fun `get GUI returns null if no GUI contains the client`() = runTest { + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + val gui = mockk { + coEvery { contains(client) } returns false + } + guiManager.add(gui) + client.gui() shouldBe null + } + + @Test + fun `get GUI returns GUI if contains the client`() = runTest { + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + val gui = mockk { + coEvery { contains(client) } returns true + } + guiManager.add(gui) + client.gui() shouldBe gui + } + } + } From 8b0980df6330de9ce6a6da6b982d7b8d9859c99b Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 12:37:27 +0100 Subject: [PATCH 09/48] test(gui-listener): Begin test about close GUI --- .../rushyverse/api/gui/GUIListenerTest.kt | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt new file mode 100644 index 00000000..647ea079 --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -0,0 +1,123 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.AbstractKoinTest +import com.github.rushyverse.api.player.Client +import com.github.rushyverse.api.player.ClientManager +import com.github.rushyverse.api.player.ClientManagerImpl +import com.github.rushyverse.api.utils.randomString +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import java.util.* +import kotlin.coroutines.EmptyCoroutineContext +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.test.runTest +import net.kyori.adventure.text.Component +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.event.player.PlayerQuitEvent +import org.junit.jupiter.api.Nested + +class GUIListenerTest : AbstractKoinTest() { + + private lateinit var guiManager: GUIManager + private lateinit var clientManager: ClientManager + private lateinit var listener: GUIListener + + @BeforeTest + override fun onBefore() { + super.onBefore() + guiManager = GUIManager() + clientManager = ClientManagerImpl() + listener = GUIListener(plugin) + + loadApiTestModule { + single { guiManager } + single { clientManager } + } + } + + @Nested + inner class OnInventoryClick { + + + } + + abstract inner class CloseGUIDuringEvent { + + @Test + fun `should do nothing if client doesn't have a GUI opened`() = runTest { + val (player, client) = registerPlayer() + val gui = registerGUI { + coEvery { contains(client) } returns false + } + + val event = PlayerQuitEvent(player, Component.empty(), PlayerQuitEvent.QuitReason.DISCONNECTED) + listener.onPlayerQuit(event) + + coVerify(exactly = 0) { gui.close(client, any()) } + } + + @Test + fun `should close the GUI if client has opened one`() = runTest { + val (player, client) = registerPlayer() + val gui = registerGUI { + coEvery { contains(client) } returns true + coEvery { close(client, any()) } returns true + } + + val gui2 = registerGUI { + coEvery { contains(client) } returns false + } + + callEvent(player) + + coVerify(exactly = 1) { gui.close(client, false) } + coVerify(exactly = 0) { gui2.close(client, any()) } + } + + protected abstract suspend fun callEvent(player: Player) + + } + + @Nested + inner class OnInventoryClose : CloseGUIDuringEvent() { + + override suspend fun callEvent(player: Player) { + val event = mockk { + every { getPlayer() } returns player + } + listener.onInventoryClose(event) + } + } + + @Nested + inner class OnPlayerQuit : CloseGUIDuringEvent() { + + override suspend fun callEvent(player: Player) { + val event = mockk { + every { getPlayer() } returns player + } + listener.onPlayerQuit(event) + } + } + + private suspend fun registerPlayer(): Pair { + val player = mockk { + every { name } returns randomString() + every { uniqueId } returns UUID.randomUUID() + } + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + clientManager.put(player, client) + return player to client + } + + private inline fun registerGUI(block: GUI.() -> Unit): GUI { + val gui = mockk(block = block) + guiManager.add(gui) + return gui + } +} From e058f80949fcd5473518787501bd6f876d68097b Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 12:37:58 +0100 Subject: [PATCH 10/48] chore: Return boolean when open GUI --- .../kotlin/com/github/rushyverse/api/gui/GUI.kt | 14 ++++++++------ .../com/github/rushyverse/api/gui/PersonalGUI.kt | 3 ++- .../com/github/rushyverse/api/gui/SharedGUI.kt | 3 ++- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index dafb3f9b..fbfab1ea 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -36,32 +36,34 @@ public abstract class GUI : Closeable { * If the client has another GUI opened, close it. * If the client has the same GUI opened, do nothing. * @param client Client to open the GUI for. + * @return True if the GUI was opened, false otherwise. */ - public suspend fun open(client: Client) { + public suspend fun open(client: Client): Boolean { requireOpen() val gui = client.gui() - if (gui == this) return + if (gui == this) return false // If the client has another GUI opened, close it. gui?.close(client, true) val player = client.player if (player == null) { logger.warn { "Cannot open inventory for player ${client.playerUUID}: player is null" } - return + return false } // If the player is dead, do not open the GUI because the interface cannot be shown to the player. - if (player.isDead) return + if (player.isDead) return false - openGUI(client) + return openGUI(client) } /** * Open the GUI for the client. * Called by [open] after all the checks. * @param client Client to open the GUI for. + * @return True if the GUI was opened, false otherwise. */ - protected abstract suspend fun openGUI(client: Client) + protected abstract suspend fun openGUI(client: Client): Boolean /** * Action to do when the client clicks on an item in the inventory. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 598849cd..4e24275a 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -24,7 +24,7 @@ public abstract class PersonalGUI(public val title: String) : GUI() { private val mutex = Mutex() - override suspend fun openGUI(client: Client) { + override suspend fun openGUI(client: Client): Boolean { val inventory = createInventory(client) mutex.withLock { inventories[client] }?.close() @@ -33,6 +33,7 @@ public abstract class PersonalGUI(public val title: String) : GUI() { player.openInventory(inventory) mutex.withLock { inventories[client] = inventory } + return true } /** diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index c023dcb6..fec7407b 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -15,10 +15,11 @@ public abstract class SharedGUI : GUI() { private var inventory: Inventory? = null - override suspend fun openGUI(client: Client) { + override suspend fun openGUI(client: Client): Boolean { val player = client.requirePlayer() val inventory = getOrCreateInventory() player.openInventory(inventory) + return true } /** From b42ba7c0a99c308bd2610728b5830eb3051164c2 Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 14:45:42 +0100 Subject: [PATCH 11/48] test: GUI on click --- .../github/rushyverse/api/gui/GUIListener.kt | 7 +- .../rushyverse/api/gui/GUIListenerTest.kt | 86 +++++++++++++++++++ 2 files changed, 91 insertions(+), 2 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt index 63c83452..f5314c31 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt @@ -4,6 +4,7 @@ import com.github.rushyverse.api.Plugin import com.github.rushyverse.api.extension.event.cancel import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.ClientManager +import org.bukkit.Material import org.bukkit.entity.HumanEntity import org.bukkit.event.EventHandler import org.bukkit.event.Listener @@ -27,9 +28,11 @@ public class GUIListener(plugin: Plugin) : Listener { @EventHandler public suspend fun onInventoryClick(event: InventoryClickEvent) { if (event.isCancelled) return - val item = event.currentItem ?: return - val player = event.whoClicked + val item = event.currentItem + if (item == null || item.type == Material.AIR) return + + val player = event.whoClicked val client = clients.getClient(player) val gui = client.gui() ?: return diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 647ea079..7375d3a0 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -1,6 +1,10 @@ package com.github.rushyverse.api.gui +import be.seeseemelk.mockbukkit.MockBukkit +import be.seeseemelk.mockbukkit.ServerMock import com.github.rushyverse.api.AbstractKoinTest +import com.github.rushyverse.api.extension.ItemStack +import com.github.rushyverse.api.extension.event.cancel import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl @@ -9,16 +13,21 @@ import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk +import io.mockk.verify import java.util.* import kotlin.coroutines.EmptyCoroutineContext +import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.test.runTest import net.kyori.adventure.text.Component +import org.bukkit.Material import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested class GUIListenerTest : AbstractKoinTest() { @@ -26,6 +35,7 @@ class GUIListenerTest : AbstractKoinTest() { private lateinit var guiManager: GUIManager private lateinit var clientManager: ClientManager private lateinit var listener: GUIListener + private lateinit var serverMock: ServerMock @BeforeTest override fun onBefore() { @@ -38,11 +48,87 @@ class GUIListenerTest : AbstractKoinTest() { single { guiManager } single { clientManager } } + + serverMock = MockBukkit.mock() + } + + @AfterTest + override fun onAfter() { + super.onAfter() + MockBukkit.unmock() } @Nested inner class OnInventoryClick { + @Test + fun `should do nothing if event is cancelled`() = runTest { + val (player, client) = registerPlayer() + val gui = registerGUI { + coEvery { contains(client) } returns true + } + + callEvent(true, player, ItemStack { type = Material.DIRT }) + coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + } + + @Test + fun `should do nothing if item is null or air`() = runTest { + val (player, client) = registerPlayer() + val gui = registerGUI { + coEvery { contains(client) } returns true + } + + suspend fun callEvent(item: ItemStack?) { + val event = callEvent(false, player, item) + coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + verify(exactly = 0) { event.cancel() } + } + + callEvent(null) + callEvent(ItemStack { type = Material.AIR }) + } + + @Test + fun `should do nothing if client doesn't have a GUI opened`() = runTest { + val (player, client) = registerPlayer() + val gui = registerGUI { + coEvery { contains(client) } returns false + } + + callEvent(false, player, ItemStack { type = Material.DIRT }) + coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + } + + @Test + fun `should call GUI onClick if client has opened one`() = runTest { + val (player, client) = registerPlayer() + val gui = registerGUI { + coEvery { contains(client) } returns true + coEvery { onClick(client, any(), any()) } returns Unit + } + + val item = ItemStack { type = Material.DIRT } + val event = callEvent(false, player, item) + coVerify(exactly = 1) { gui.onClick(client, item, event) } + verify(exactly = 1) { event.cancel() } + } + + private suspend fun callEvent( + cancel: Boolean, + player: Player, + item: ItemStack? + ): InventoryClickEvent { + val event = mockk { + every { isCancelled } returns cancel + every { whoClicked } returns player + every { currentItem } returns item + every { cancel() } returns Unit + } + + listener.onInventoryClick(event) + return event + } } From b613270a697b271d66688d294cf2cb6e95c93661 Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 16:13:17 +0100 Subject: [PATCH 12/48] test: Begin test for PersonalGUI close --- .../rushyverse/api/gui/GUIListenerTest.kt | 5 +- .../rushyverse/api/gui/PersonalGUITest.kt | 147 ++++++++++++++++++ 2 files changed, 148 insertions(+), 4 deletions(-) create mode 100644 src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 7375d3a0..29772d72 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -192,10 +192,7 @@ class GUIListenerTest : AbstractKoinTest() { } private suspend fun registerPlayer(): Pair { - val player = mockk { - every { name } returns randomString() - every { uniqueId } returns UUID.randomUUID() - } + val player = serverMock.addPlayer() val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) clientManager.put(player, client) return player to client diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt new file mode 100644 index 00000000..6ad873d7 --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt @@ -0,0 +1,147 @@ +package com.github.rushyverse.api.gui + +import be.seeseemelk.mockbukkit.MockBukkit +import be.seeseemelk.mockbukkit.ServerMock +import be.seeseemelk.mockbukkit.entity.PlayerMock +import com.github.rushyverse.api.AbstractKoinTest +import com.github.rushyverse.api.player.Client +import com.github.rushyverse.api.player.ClientManager +import com.github.rushyverse.api.player.ClientManagerImpl +import com.github.rushyverse.api.translation.Translator +import io.kotest.matchers.collections.shouldContainAll +import io.kotest.matchers.shouldBe +import kotlin.coroutines.EmptyCoroutineContext +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration.Companion.minutes +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.test.runTest +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryType +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.InventoryHolder +import org.bukkit.inventory.ItemStack +import org.junit.jupiter.api.Nested + +class PersonalGUITest: AbstractKoinTest() { + + private lateinit var guiManager: GUIManager + private lateinit var clientManager: ClientManager + private lateinit var translator: Translator + private lateinit var serverMock: ServerMock + + @BeforeTest + override fun onBefore() { + super.onBefore() + guiManager = GUIManager() + clientManager = ClientManagerImpl() + + + loadApiTestModule { + single { guiManager } + single { clientManager } + } + + serverMock = MockBukkit.mock() + } + + @AfterTest + override fun onAfter() { + super.onAfter() + MockBukkit.unmock() + } + + @Nested + inner class Open { + + } + + @Nested + inner class Viewers { + + } + + @Nested + inner class Contains { + + } + + @Nested + inner class CloseForClient { + + } + + @Nested + inner class Close { + + @Test + fun `should close all inventories and remove all viewers`() = runTest(timeout = 1.minutes) { + val type = InventoryType.HOPPER + val gui = object : PersonalGUI() { + override fun createInventory(owner: InventoryHolder, client: Client): Inventory { + return serverMock.createInventory(owner, type) + } + + override suspend fun fill(client: Client, inventory: Inventory) {} + + override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { + error("Should not be called") + } + } + + val playerClients = List(5) { registerPlayer() } + playerClients.forEach { (player, client) -> + gui.open(client) shouldBe true + player.assertInventoryView(type) + client.gui() shouldBe gui + } + + gui.close() + playerClients.forEach { (player, client) -> + player.assertInventoryView(InventoryType.CRAFTING) + client.gui() shouldBe null + } + } + + @Test + fun `should set isClosed to true`() { + val gui = createGUI() + gui.isClosed shouldBe false + gui.close() + gui.isClosed shouldBe true + } + + @Test + fun `should unregister the GUI`() { + val gui = createGUI() + guiManager.guis shouldContainAll listOf(gui) + gui.close() + guiManager.guis shouldContainAll listOf() + } + + private fun createGUI(): PersonalGUI { + return object : PersonalGUI() { + override fun createInventory(owner: InventoryHolder, client: Client): Inventory { + error("Should not be called") + } + + override suspend fun fill(client: Client, inventory: Inventory) { + error("Should not be called") + } + + override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { + error("Should not be called") + } + } + } + + } + + private suspend fun registerPlayer(): Pair { + val player = serverMock.addPlayer() + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + clientManager.put(player, client) + return player to client + } +} From c8d302ce9ee84a933de564a3e55b82c58c5937cc Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 16:15:28 +0100 Subject: [PATCH 13/48] fix(personal-gui): Create custom inventory for personal GUI --- .../github/rushyverse/api/gui/PersonalGUI.kt | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 4e24275a..2beb9532 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -1,24 +1,16 @@ package com.github.rushyverse.api.gui -import com.github.rushyverse.api.extension.toTranslatedComponent -import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.Client -import com.github.rushyverse.api.translation.Translator import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock -import net.kyori.adventure.text.Component import org.bukkit.entity.HumanEntity import org.bukkit.inventory.Inventory import org.bukkit.inventory.InventoryHolder /** * GUI where a new inventory is created for each viewer. - * @property title Title that can be translated. - * @property translator Translator to translate the title. */ -public abstract class PersonalGUI(public val title: String) : GUI() { - - protected val translator: Translator by inject() +public abstract class PersonalGUI : GUI() { private var inventories: MutableMap = mutableMapOf() @@ -44,8 +36,7 @@ public abstract class PersonalGUI(public val title: String) : GUI() { */ private suspend fun createInventory(client: Client): Inventory { val player = client.requirePlayer() - val translatedTitle = title.toTranslatedComponent(translator, client.lang().locale) - return createInventory(player, translatedTitle).also { + return createInventory(player, client).also { fill(client, it) } } @@ -54,10 +45,10 @@ public abstract class PersonalGUI(public val title: String) : GUI() { * Create the inventory for the client. * This function is called when the [owner] wants to open the inventory. * @param owner Player who wants to open the inventory. - * @param title Translated title of the inventory. + * @param client The client to create the inventory for. * @return The inventory for the client. */ - protected abstract fun createInventory(owner: InventoryHolder, title: Component): Inventory + protected abstract fun createInventory(owner: InventoryHolder, client: Client): Inventory /** * Fill the inventory with items for the client. From 2efa65cdc2a2dc36025f40b00cc15ae8704ce25e Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 18:38:10 +0100 Subject: [PATCH 14/48] fix: Click on item when inventory open --- .../com/github/rushyverse/api/APIPlugin.kt | 2 +- .../com/github/rushyverse/api/gui/GUI.kt | 15 ++++ .../github/rushyverse/api/gui/GUIListener.kt | 70 ++++++++++++++++++- .../github/rushyverse/api/gui/PersonalGUI.kt | 12 ++++ .../github/rushyverse/api/gui/SharedGUI.kt | 18 +++-- .../rushyverse/api/gui/GUIListenerTest.kt | 15 ++-- .../rushyverse/api/gui/PersonalGUITest.kt | 4 +- 7 files changed, 124 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt b/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt index e1b0480e..7b0abcc6 100644 --- a/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt +++ b/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt @@ -15,7 +15,7 @@ import org.bukkit.plugin.java.JavaPlugin /** * Plugin to enable the API in server. */ -public class APIPlugin : JavaPlugin() { +public open class APIPlugin : JavaPlugin() { public companion object { /** diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index fbfab1ea..d35563af 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -7,6 +7,7 @@ import mu.KotlinLogging import org.bukkit.Server import org.bukkit.entity.HumanEntity import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack private val logger = KotlinLogging.logger {} @@ -81,6 +82,20 @@ public abstract class GUI : Closeable { */ public abstract suspend fun close(client: Client, closeInventory: Boolean = true): Boolean + /** + * Check if the GUI contains the inventory. + * @param inventory Inventory to check. + * @return True if the GUI contains the inventory, false otherwise. + */ + public abstract suspend fun hasInventory(inventory: Inventory): Boolean + + /** + * Get the inventory of the GUI for the client. + * @param client Client to get the inventory for. + * @return The inventory of the GUI for the client. + */ + public abstract suspend fun getInventory(client: Client): Inventory? + /** * Close the inventory. * The inventory will be closed for all the viewers. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt index f5314c31..af3cebc9 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt @@ -4,22 +4,34 @@ import com.github.rushyverse.api.Plugin import com.github.rushyverse.api.extension.event.cancel import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.ClientManager +import com.github.shynixn.mccoroutine.bukkit.callSuspendingEvent +import kotlinx.coroutines.joinAll import org.bukkit.Material +import org.bukkit.Server +import org.bukkit.block.BlockFace import org.bukkit.entity.HumanEntity +import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener +import org.bukkit.event.block.Action import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import org.bukkit.inventory.PlayerInventory /** * Listener for GUI events. * @property clients Manager of clients. */ -public class GUIListener(plugin: Plugin) : Listener { +public class GUIListener(private val plugin: Plugin) : Listener { private val clients: ClientManager by inject(plugin.id) + private val server: Server by inject() + /** * Called when a player clicks on an item in an inventory. * If the click is detected in a GUI, the event is cancelled and the GUI is notified. @@ -32,15 +44,71 @@ public class GUIListener(plugin: Plugin) : Listener { val item = event.currentItem if (item == null || item.type == Material.AIR) return + val clickedInventory = event.clickedInventory ?: return + val player = event.whoClicked + if (clickedInventory is PlayerInventory) { + handleClickOnPlayerInventory(player as Player, item, event) + } else { + handleClickOnGUI(player, clickedInventory, item, event) + } + } + + /** + * Called when a player clicks on an item in an inventory. + * @param player Player who clicked. + * @param clickedInventory Inventory where the click was detected. + * @param item Item that was clicked. + * @param event Event of the click. + */ + private suspend fun handleClickOnGUI( + player: HumanEntity, + clickedInventory: Inventory, + item: ItemStack, + event: InventoryClickEvent + ) { val client = clients.getClient(player) val gui = client.gui() ?: return + if (!gui.hasInventory(clickedInventory)) { + return + } // The item in a GUI is not supposed to be moved event.cancel() gui.onClick(client, item, event) } + /** + * Called when a player clicks on an item in his inventory. + * To trigger the action linked to the clicked item, + * we produce a PlayerInteractEvent to simulate a right click with the item. + * @param player Player who clicked. + * @param item Item that was clicked. + */ + private suspend fun handleClickOnPlayerInventory(player: Player, item: ItemStack, event: InventoryClickEvent) { + event.cancel() + + val rightClickWithItemEvent = createRightClickWithItemEvent(player, item) + server.pluginManager.callSuspendingEvent(rightClickWithItemEvent, plugin).joinAll() + } + + /** + * Create a PlayerInteractEvent to simulate a right click with an item. + * @param player Player who clicked. + * @param item Item that was clicked. + * @return The new event. + */ + private fun createRightClickWithItemEvent( + player: Player, + item: ItemStack + ) = PlayerInteractEvent( + player, + Action.RIGHT_CLICK_AIR, + item, + null, + BlockFace.NORTH // random value not null + ) + /** * Called when a player closes an inventory. * If the inventory is a GUI, the GUI is notified that it is closed for this player. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 2beb9532..01c43ad4 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -79,6 +79,18 @@ public abstract class PersonalGUI : GUI() { } } + override suspend fun hasInventory(inventory: Inventory): Boolean { + return mutex.withLock { + inventories.values.contains(inventory) + } + } + + override suspend fun getInventory(client: Client): Inventory? { + return mutex.withLock { + inventories[client] + } + } + override fun close() { super.close() inventories.values.forEach(Inventory::close) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index fec7407b..e5b30630 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -43,11 +43,10 @@ public abstract class SharedGUI : GUI() { override suspend fun close(client: Client, closeInventory: Boolean): Boolean { val player = client.requirePlayer() - if (closeInventory && player.openInventory.topInventory == inventory) { + return if (closeInventory && player.openInventory.topInventory == inventory) { player.closeInventory() - return true - } - return false + true + } else false } override suspend fun viewers(): List { @@ -58,6 +57,17 @@ public abstract class SharedGUI : GUI() { return client.player?.let { it in viewers() } == true } + override suspend fun hasInventory(inventory: Inventory): Boolean { + return this.inventory == inventory + } + + override suspend fun getInventory(client: Client): Inventory? { + val player = client.player + return if (player != null && player in viewers()) { + inventory + } else null + } + override fun close() { super.close() inventory?.close() diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 29772d72..6cc9ff7f 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -27,6 +27,7 @@ import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested @@ -68,7 +69,7 @@ class GUIListenerTest : AbstractKoinTest() { coEvery { contains(client) } returns true } - callEvent(true, player, ItemStack { type = Material.DIRT }) + callEvent(true, player, ItemStack { type = Material.DIRT }, player.inventory) coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } } @@ -80,7 +81,7 @@ class GUIListenerTest : AbstractKoinTest() { } suspend fun callEvent(item: ItemStack?) { - val event = callEvent(false, player, item) + val event = callEvent(false, player, item, player.inventory) coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } verify(exactly = 0) { event.cancel() } } @@ -96,20 +97,22 @@ class GUIListenerTest : AbstractKoinTest() { coEvery { contains(client) } returns false } - callEvent(false, player, ItemStack { type = Material.DIRT }) + callEvent(false, player, ItemStack { type = Material.DIRT }, player.inventory) coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } } @Test fun `should call GUI onClick if client has opened one`() = runTest { val (player, client) = registerPlayer() + val inventory = mockk() val gui = registerGUI { coEvery { contains(client) } returns true coEvery { onClick(client, any(), any()) } returns Unit + coEvery { hasInventory(inventory) } returns true } val item = ItemStack { type = Material.DIRT } - val event = callEvent(false, player, item) + val event = callEvent(false, player, item, inventory) coVerify(exactly = 1) { gui.onClick(client, item, event) } verify(exactly = 1) { event.cancel() } } @@ -117,13 +120,15 @@ class GUIListenerTest : AbstractKoinTest() { private suspend fun callEvent( cancel: Boolean, player: Player, - item: ItemStack? + item: ItemStack?, + inventory: Inventory? ): InventoryClickEvent { val event = mockk { every { isCancelled } returns cancel every { whoClicked } returns player every { currentItem } returns item every { cancel() } returns Unit + every { clickedInventory } returns inventory } listener.onInventoryClick(event) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt index 6ad873d7..14558300 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt @@ -78,6 +78,7 @@ class PersonalGUITest: AbstractKoinTest() { @Test fun `should close all inventories and remove all viewers`() = runTest(timeout = 1.minutes) { val type = InventoryType.HOPPER + val initType = InventoryType.CRAFTING val gui = object : PersonalGUI() { override fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, type) @@ -92,6 +93,7 @@ class PersonalGUITest: AbstractKoinTest() { val playerClients = List(5) { registerPlayer() } playerClients.forEach { (player, client) -> + player.assertInventoryView(initType) gui.open(client) shouldBe true player.assertInventoryView(type) client.gui() shouldBe gui @@ -99,7 +101,7 @@ class PersonalGUITest: AbstractKoinTest() { gui.close() playerClients.forEach { (player, client) -> - player.assertInventoryView(InventoryType.CRAFTING) + player.assertInventoryView(initType) client.gui() shouldBe null } } From 8cd1bab75e849b684e85aa47b5227b9fd93c9616 Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 19:30:56 +0100 Subject: [PATCH 15/48] test: Fix test about call suspending event --- .../github/rushyverse/api/AbstractKoinTest.kt | 16 ++++++++++++++-- .../github/rushyverse/api/gui/GUIListenerTest.kt | 9 +++++++-- .../github/rushyverse/api/gui/PersonalGUITest.kt | 5 +---- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt b/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt index 4a7ea6aa..df562752 100644 --- a/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt @@ -5,15 +5,18 @@ import com.github.rushyverse.api.koin.loadModule import com.github.rushyverse.api.utils.randomString import io.mockk.every import io.mockk.mockk -import org.koin.core.module.Module -import org.koin.dsl.ModuleDeclaration import kotlin.test.AfterTest import kotlin.test.BeforeTest +import org.bukkit.Server +import org.koin.core.module.Module +import org.koin.dsl.ModuleDeclaration open class AbstractKoinTest { lateinit var plugin: Plugin + lateinit var server: Server + private lateinit var pluginId: String @BeforeTest @@ -22,13 +25,22 @@ open class AbstractKoinTest { CraftContext.startKoin(pluginId) { } CraftContext.startKoin(APIPlugin.ID_API) { } + server = mockk { + every { pluginManager } returns mockk() + } + loadTestModule { plugin = mockk { every { id } returns pluginId every { name } returns randomString() + every { server } returns this@AbstractKoinTest.server } single { plugin } } + + loadApiTestModule { + single { server } + } } @AfterTest diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 6cc9ff7f..3950cb2b 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -8,13 +8,13 @@ import com.github.rushyverse.api.extension.event.cancel import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl -import com.github.rushyverse.api.utils.randomString +import com.github.shynixn.mccoroutine.bukkit.callSuspendingEvent import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk +import io.mockk.mockkStatic import io.mockk.verify -import java.util.* import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.AfterTest import kotlin.test.BeforeTest @@ -97,6 +97,11 @@ class GUIListenerTest : AbstractKoinTest() { coEvery { contains(client) } returns false } + val pluginManager = server.pluginManager + + mockkStatic("com.github.shynixn.mccoroutine.bukkit.MCCoroutineKt") + every { pluginManager.callSuspendingEvent(any(), plugin) } returns emptyList() + callEvent(false, player, ItemStack { type = Material.DIRT }, player.inventory) coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt index 14558300..5879a493 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt @@ -7,7 +7,6 @@ import com.github.rushyverse.api.AbstractKoinTest import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl -import com.github.rushyverse.api.translation.Translator import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.shouldBe import kotlin.coroutines.EmptyCoroutineContext @@ -24,11 +23,10 @@ import org.bukkit.inventory.InventoryHolder import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested -class PersonalGUITest: AbstractKoinTest() { +class PersonalGUITest : AbstractKoinTest() { private lateinit var guiManager: GUIManager private lateinit var clientManager: ClientManager - private lateinit var translator: Translator private lateinit var serverMock: ServerMock @BeforeTest @@ -37,7 +35,6 @@ class PersonalGUITest: AbstractKoinTest() { guiManager = GUIManager() clientManager = ClientManagerImpl() - loadApiTestModule { single { guiManager } single { clientManager } From e3890f1d0f86a79bc8ff34d2a48c436b23ec9a5c Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 22:30:55 +0100 Subject: [PATCH 16/48] test: Add test to trigger call event --- .../rushyverse/api/gui/GUIListenerTest.kt | 47 +++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 3950cb2b..54900bb5 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -9,23 +9,31 @@ import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl import com.github.shynixn.mccoroutine.bukkit.callSuspendingEvent +import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic +import io.mockk.slot +import io.mockk.unmockkAll import io.mockk.verify import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.async +import kotlinx.coroutines.delay import kotlinx.coroutines.test.runTest import net.kyori.adventure.text.Component import org.bukkit.Material import org.bukkit.entity.Player +import org.bukkit.event.block.Action import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack @@ -51,12 +59,14 @@ class GUIListenerTest : AbstractKoinTest() { } serverMock = MockBukkit.mock() + mockkStatic("com.github.shynixn.mccoroutine.bukkit.MCCoroutineKt") } @AfterTest override fun onAfter() { super.onAfter() MockBukkit.unmock() + unmockkAll() } @Nested @@ -93,17 +103,48 @@ class GUIListenerTest : AbstractKoinTest() { @Test fun `should do nothing if client doesn't have a GUI opened`() = runTest { val (player, client) = registerPlayer() + val gui = registerGUI { coEvery { contains(client) } returns false + coEvery { hasInventory(any()) } returns false } val pluginManager = server.pluginManager - mockkStatic("com.github.shynixn.mccoroutine.bukkit.MCCoroutineKt") - every { pluginManager.callSuspendingEvent(any(), plugin) } returns emptyList() + val item = ItemStack { type = Material.DIRT } + callEvent(false, player, item, mockk()) + + coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + verify(exactly = 0) { pluginManager.callSuspendingEvent(any(), plugin) } + } + + @Test + fun `should trigger right click event if player select his own inventory`() = runTest { + val (player, client) = registerPlayer() + val gui = registerGUI { + coEvery { contains(client) } returns false + } + + val pluginManager = server.pluginManager + + val slot = slot() + val jobs = List(5) { + async { delay(1.seconds) } + } + every { pluginManager.callSuspendingEvent(capture(slot), plugin) } returns jobs + + val item = ItemStack { type = Material.DIRT } - callEvent(false, player, ItemStack { type = Material.DIRT }, player.inventory) + callEvent(false, player, item, player.inventory) coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + verify(exactly = 1) { pluginManager.callSuspendingEvent(any(), plugin) } + jobs.forEach { it.isCompleted shouldBe true } + + val event = slot.captured + event.player shouldBe player + event.action shouldBe Action.RIGHT_CLICK_AIR + event.item shouldBe item + event.clickedBlock shouldBe null } @Test From a93e84e7843a5a3b0e626fd55d9e3affb7af1f36 Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 23:44:23 +0100 Subject: [PATCH 17/48] test: Implement tests for Personal GUI --- .../com/github/rushyverse/api/gui/GUI.kt | 6 +- .../github/rushyverse/api/gui/PersonalGUI.kt | 26 ++-- .../rushyverse/api/gui/PersonalGUITest.kt | 131 +++++++++++++----- 3 files changed, 112 insertions(+), 51 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index d35563af..7b400183 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -19,7 +19,7 @@ private val logger = KotlinLogging.logger {} * @property manager Manager to register or unregister the GUI. * @property isClosed If true, the GUI is closed; otherwise it is open. */ -public abstract class GUI : Closeable { +public abstract class GUI { protected val server: Server by inject() @@ -101,7 +101,7 @@ public abstract class GUI : Closeable { * The inventory will be closed for all the viewers. * The GUI will be removed from the listener and the [onClick] function will not be called anymore. */ - public override fun close() { + public open suspend fun close() { isClosed = true unregister() } @@ -110,7 +110,7 @@ public abstract class GUI : Closeable { * Verify that the GUI is open. * If the GUI is closed, throw an exception. */ - protected fun requireOpen() { + private fun requireOpen() { require(!isClosed) { "Cannot use a closed GUI" } } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt index 01c43ad4..ad8d5be7 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt @@ -58,15 +58,6 @@ public abstract class PersonalGUI : GUI() { */ protected abstract suspend fun fill(client: Client, inventory: Inventory) - override suspend fun close(client: Client, closeInventory: Boolean): Boolean { - return mutex.withLock { inventories.remove(client) }?.run { - if (closeInventory) { - close() - } - true - } == true - } - override suspend fun viewers(): List { return mutex.withLock { inventories.values.flatMap(Inventory::getViewers) @@ -91,9 +82,20 @@ public abstract class PersonalGUI : GUI() { } } - override fun close() { + override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + return mutex.withLock { inventories.remove(client) }?.run { + if (closeInventory) { + client.player?.closeInventory() + } + true + } == true + } + + override suspend fun close() { super.close() - inventories.values.forEach(Inventory::close) - inventories.clear() + mutex.withLock { + inventories.values.forEach(Inventory::close) + inventories.clear() + } } } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt index 5879a493..fbf220b2 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt @@ -8,6 +8,7 @@ import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl import io.kotest.matchers.collections.shouldContainAll +import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.AfterTest @@ -57,16 +58,87 @@ class PersonalGUITest : AbstractKoinTest() { @Nested inner class Viewers { + @Test + fun `should return empty list if no client is viewing the GUI`() = runTest { + val gui = TestGUI(serverMock) + gui.viewers() shouldBe emptyList() + } + + @Test + fun `should return the list of clients viewing the GUI`() = runTest { + val gui = TestGUI(serverMock) + val playerClients = List(5) { registerPlayer() } + + playerClients.forEach { (_, client) -> + gui.open(client) shouldBe true + } + + gui.viewers() shouldContainExactlyInAnyOrder playerClients.map { it.first } + } + } @Nested inner class Contains { + @Test + fun `should return false if the client is not viewing the GUI`() = runTest { + val gui = TestGUI(serverMock) + val (_, client) = registerPlayer() + gui.contains(client) shouldBe false + } + + @Test + fun `should return true if the client is viewing the GUI`() = runTest { + val gui = TestGUI(serverMock) + val (_, client) = registerPlayer() + gui.open(client) shouldBe true + gui.contains(client) shouldBe true + } + } @Nested inner class CloseForClient { + @Test + fun `should return false if the client is not viewing the GUI`() = runTest(timeout = 1.minutes) { + val gui = TestGUI(serverMock) + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + player.assertInventoryView(initialInventoryViewType) + gui.close(client, true) shouldBe false + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should close the inventory if the client is viewing the GUI`() = runTest(timeout = 1.minutes) { + val gui = TestGUI(serverMock) + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + gui.open(client) shouldBe true + player.assertInventoryView(gui.type) + gui.close(client, true) shouldBe true + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should remove client inventory without closing it if closeInventory is false`() = + runTest(timeout = 1.minutes) { + val gui = TestGUI(serverMock) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + player.assertInventoryView(gui.type) + gui.close(client, false) shouldBe true + player.assertInventoryView(gui.type) + gui.contains(client) shouldBe false + } + } @Nested @@ -74,67 +146,41 @@ class PersonalGUITest : AbstractKoinTest() { @Test fun `should close all inventories and remove all viewers`() = runTest(timeout = 1.minutes) { - val type = InventoryType.HOPPER - val initType = InventoryType.CRAFTING - val gui = object : PersonalGUI() { - override fun createInventory(owner: InventoryHolder, client: Client): Inventory { - return serverMock.createInventory(owner, type) - } - - override suspend fun fill(client: Client, inventory: Inventory) {} - - override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { - error("Should not be called") - } - } + val gui = TestGUI(serverMock, InventoryType.BREWING) val playerClients = List(5) { registerPlayer() } + val initialInventoryViewType = playerClients.first().first.openInventory.type + playerClients.forEach { (player, client) -> - player.assertInventoryView(initType) + player.assertInventoryView(initialInventoryViewType) gui.open(client) shouldBe true - player.assertInventoryView(type) + player.assertInventoryView(gui.type) client.gui() shouldBe gui } gui.close() playerClients.forEach { (player, client) -> - player.assertInventoryView(initType) + player.assertInventoryView(initialInventoryViewType) client.gui() shouldBe null } } @Test - fun `should set isClosed to true`() { - val gui = createGUI() + fun `should set isClosed to true`() = runTest { + val gui = TestGUI(serverMock) gui.isClosed shouldBe false gui.close() gui.isClosed shouldBe true } @Test - fun `should unregister the GUI`() { - val gui = createGUI() + fun `should unregister the GUI`() = runTest { + val gui = TestGUI(serverMock) guiManager.guis shouldContainAll listOf(gui) gui.close() guiManager.guis shouldContainAll listOf() } - private fun createGUI(): PersonalGUI { - return object : PersonalGUI() { - override fun createInventory(owner: InventoryHolder, client: Client): Inventory { - error("Should not be called") - } - - override suspend fun fill(client: Client, inventory: Inventory) { - error("Should not be called") - } - - override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { - error("Should not be called") - } - } - } - } private suspend fun registerPlayer(): Pair { @@ -144,3 +190,16 @@ class PersonalGUITest : AbstractKoinTest() { return player to client } } + +private class TestGUI(val serverMock: ServerMock, val type: InventoryType = InventoryType.HOPPER) : PersonalGUI() { + override fun createInventory(owner: InventoryHolder, client: Client): Inventory { + return serverMock.createInventory(owner, type) + } + + override suspend fun fill(client: Client, inventory: Inventory) { + } + + override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { + error("Should not be called") + } +} From 7301933d6046ccca95ab448f56b2a5864aade131 Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 23:44:48 +0100 Subject: [PATCH 18/48] fix: Use mutex to avoid async issue --- .../github/rushyverse/api/gui/SharedGUI.kt | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index e5b30630..82c4c166 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -1,6 +1,8 @@ package com.github.rushyverse.api.gui import com.github.rushyverse.api.player.Client +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import org.bukkit.entity.HumanEntity import org.bukkit.inventory.Inventory @@ -15,6 +17,8 @@ public abstract class SharedGUI : GUI() { private var inventory: Inventory? = null + private val mutex = Mutex() + override suspend fun openGUI(client: Client): Boolean { val player = client.requirePlayer() val inventory = getOrCreateInventory() @@ -28,9 +32,11 @@ public abstract class SharedGUI : GUI() { * @return The inventory of the GUI. */ private suspend fun getOrCreateInventory(): Inventory { - return inventory ?: createInventory().also { - inventory = it - fill(it) + return mutex.withLock { + inventory ?: createInventory().also { + inventory = it + fill(it) + } } } @@ -42,15 +48,14 @@ public abstract class SharedGUI : GUI() { protected abstract fun createInventory(): Inventory override suspend fun close(client: Client, closeInventory: Boolean): Boolean { - val player = client.requirePlayer() - return if (closeInventory && player.openInventory.topInventory == inventory) { - player.closeInventory() + return if (closeInventory && contains(client)) { + client.player?.closeInventory() true } else false } override suspend fun viewers(): List { - return inventory?.viewers ?: emptyList() + return mutex.withLock { inventory?.viewers } ?: emptyList() } override suspend fun contains(client: Client): Boolean { @@ -58,20 +63,22 @@ public abstract class SharedGUI : GUI() { } override suspend fun hasInventory(inventory: Inventory): Boolean { - return this.inventory == inventory + return mutex.withLock { this.inventory } == inventory } override suspend fun getInventory(client: Client): Inventory? { - val player = client.player - return if (player != null && player in viewers()) { - inventory - } else null + return if (contains(client)) mutex.withLock { inventory } else null } - override fun close() { + override suspend fun close() { super.close() - inventory?.close() - inventory = null + mutex.withLock { + val inventory = inventory + if(inventory != null) { + inventory.close() + this.inventory = null + } + } } /** From 023777006301409193fda1750b7ea67f2e30299e Mon Sep 17 00:00:00 2001 From: Distractic Date: Fri, 15 Dec 2023 23:53:46 +0100 Subject: [PATCH 19/48] chore: Remove import --- src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 7b400183..7f36d1ad 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -2,7 +2,6 @@ package com.github.rushyverse.api.gui import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.Client -import java.io.Closeable import mu.KotlinLogging import org.bukkit.Server import org.bukkit.entity.HumanEntity From a47a1dc76942a119b92f9ed4437e6aae94d0ccdb Mon Sep 17 00:00:00 2001 From: Distractic Date: Sat, 16 Dec 2023 00:58:33 +0100 Subject: [PATCH 20/48] test: Open GUI for Personal GUI --- .../com/github/rushyverse/api/gui/GUI.kt | 16 ++- .../rushyverse/api/gui/PersonalGUITest.kt | 104 ++++++++++++++++++ 2 files changed, 117 insertions(+), 3 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 7f36d1ad..7ea5026c 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -11,6 +11,16 @@ import org.bukkit.inventory.ItemStack private val logger = KotlinLogging.logger {} +/** + * Exception concerning the GUI. + */ +public open class GUIException(message: String) : RuntimeException(message) + +/** + * Exception thrown when the GUI is closed. + */ +public class GUIClosedException(message: String) : GUIException(message) + /** * GUI that can be shared by multiple players. * Only one inventory is created for all the viewers. @@ -42,12 +52,12 @@ public abstract class GUI { requireOpen() val gui = client.gui() - if (gui == this) return false + if (gui === this) return false // If the client has another GUI opened, close it. gui?.close(client, true) val player = client.player - if (player == null) { + if (player === null) { logger.warn { "Cannot open inventory for player ${client.playerUUID}: player is null" } return false } @@ -110,7 +120,7 @@ public abstract class GUI { * If the GUI is closed, throw an exception. */ private fun requireOpen() { - require(!isClosed) { "Cannot use a closed GUI" } + if (isClosed) throw GUIClosedException("Cannot use a closed GUI") } /** diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt index fbf220b2..2fcea76c 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt @@ -4,12 +4,15 @@ import be.seeseemelk.mockbukkit.MockBukkit import be.seeseemelk.mockbukkit.ServerMock import be.seeseemelk.mockbukkit.entity.PlayerMock import com.github.rushyverse.api.AbstractKoinTest +import com.github.rushyverse.api.extension.ItemStack import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl +import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.AfterTest import kotlin.test.BeforeTest @@ -17,6 +20,7 @@ import kotlin.test.Test import kotlin.time.Duration.Companion.minutes import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.test.runTest +import org.bukkit.Material import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryType import org.bukkit.inventory.Inventory @@ -53,6 +57,90 @@ class PersonalGUITest : AbstractKoinTest() { @Nested inner class Open { + @Test + fun `should throw exception if GUI is closed`() = runTest { + val gui = TestGUI(serverMock) + gui.close() + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + shouldThrow { gui.open(client) } + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should do nothing if the client has the same GUI opened`() = runTest { + val gui = TestGUI(serverMock) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + player.assertInventoryView(gui.type) + + gui.open(client) shouldBe false + player.assertInventoryView(gui.type) + } + + @Test + fun `should close the previous GUI if the client has one opened`() = runTest { + val gui = TestGUI(serverMock, InventoryType.ENDER_CHEST) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + player.assertInventoryView(gui.type) + + val gui2 = TestGUI(serverMock, InventoryType.CHEST) + gui2.open(client) shouldBe true + player.assertInventoryView(gui2.type) + gui.contains(client) shouldBe false + gui2.contains(client) shouldBe true + } + + @Test + fun `should do nothing if the player is dead`() = runTest { + val gui = TestGUI(serverMock) + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + player.damage(Double.MAX_VALUE) + gui.open(client) shouldBe false + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should create a new inventory for the client`() = runTest { + val gui = TestGUI(serverMock) + val (player, client) = registerPlayer() + val (player2, client2) = registerPlayer() + + gui.open(client) shouldBe true + gui.open(client2) shouldBe true + + player.assertInventoryView(gui.type) + player2.assertInventoryView(gui.type) + + player.openInventory.topInventory shouldNotBe player2.openInventory.topInventory + } + + @Test + fun `should fill the inventory`() = runTest { + val gui = TestFilledGUI(serverMock) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + player.assertInventoryView(InventoryType.CHEST) + + val inventory = player.openInventory.topInventory + val content = inventory.contents + println(content.contentToString()) + content[0]!!.type shouldBe Material.DIAMOND_ORE + content[1]!!.type shouldBe Material.STICK + + for (i in 2 until content.size) { + content[i] shouldBe null + } + } + } @Nested @@ -197,6 +285,22 @@ private class TestGUI(val serverMock: ServerMock, val type: InventoryType = Inve } override suspend fun fill(client: Client, inventory: Inventory) { + // Do nothing + } + + override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { + error("Should not be called") + } +} + +private class TestFilledGUI(val serverMock: ServerMock) : PersonalGUI() { + override fun createInventory(owner: InventoryHolder, client: Client): Inventory { + return serverMock.createInventory(owner, InventoryType.CHEST) + } + + override suspend fun fill(client: Client, inventory: Inventory) { + inventory.setItem(0, ItemStack { type = Material.DIAMOND_ORE }) + inventory.setItem(1, ItemStack { type = Material.STICK }) } override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { From 5368455bc1db0990a9aaf6ef5613ee74940d6a61 Mon Sep 17 00:00:00 2001 From: Distractic Date: Sat, 16 Dec 2023 07:39:28 +0100 Subject: [PATCH 21/48] feat: Dedicate GUI for player or language --- .../github/rushyverse/api/gui/ClientGUI.kt | 52 ++++++++ .../github/rushyverse/api/gui/DedicatedGUI.kt | 112 ++++++++++++++++++ .../com/github/rushyverse/api/gui/GUI.kt | 7 -- .../github/rushyverse/api/gui/PersonalGUI.kt | 101 ---------------- .../github/rushyverse/api/gui/SharedGUI.kt | 6 +- .../rushyverse/api/gui/TranslateSharedGUI.kt | 33 ++++++ .../{PersonalGUITest.kt => ClientGUITest.kt} | 6 +- 7 files changed, 201 insertions(+), 116 deletions(-) create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/ClientGUI.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt delete mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/TranslateSharedGUI.kt rename src/test/kotlin/com/github/rushyverse/api/gui/{PersonalGUITest.kt => ClientGUITest.kt} (98%) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/ClientGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/ClientGUI.kt new file mode 100644 index 00000000..ddf62c8f --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/ClientGUI.kt @@ -0,0 +1,52 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.player.Client +import kotlinx.coroutines.sync.withLock +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.InventoryHolder + +/** + * GUI where a new inventory is created for each player. + * An inventory is created when the player opens the GUI and he is not sharing the GUI with another player. + */ +public abstract class ClientGUI : DedicatedGUI() { + + override suspend fun getKey(client: Client): Client { + return client + } + + /** + * Create the inventory for the client. + * Will translate the title and fill the inventory. + * @param key The client to create the inventory for. + * @return The inventory for the client. + */ + override suspend fun createInventory(key: Client): Inventory { + val player = key.requirePlayer() + return createInventory(player, key) + } + + /** + * Create the inventory for the client. + * This function is called when the [owner] wants to open the inventory. + * @param owner Player who wants to open the inventory. + * @param client The client to create the inventory for. + * @return The inventory for the client. + */ + protected abstract fun createInventory(owner: InventoryHolder, client: Client): Inventory + + override fun unsafeContains(client: Client): Boolean { + // Little optimization to avoid searching in the map from values. + return inventories.containsKey(client) + } + + override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + return mutex.withLock { inventories.remove(client) }?.run { + if (closeInventory) { + client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) + } + true + } == true + } +} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt new file mode 100644 index 00000000..164341ba --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt @@ -0,0 +1,112 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.player.Client +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.bukkit.entity.HumanEntity +import org.bukkit.inventory.Inventory + +/** + * GUI where a new inventory is created for each key used. + * @param T Type of the key. + * @property inventories Map of inventories for each key. + * @property mutex Mutex to process thread-safe operations. + */ +public abstract class DedicatedGUI : GUI() { + + protected var inventories: MutableMap = mutableMapOf() + + protected val mutex: Mutex = Mutex() + + override suspend fun openGUI(client: Client): Boolean { + val key = getKey(client) + val inventory = getOrCreateInventory(key) + + val player = client.requirePlayer() + player.openInventory(inventory) + + return true + } + + /** + * Get the inventory for the key. + * If the inventory does not exist, create it. + * @param key Key to get the inventory for. + * @return The inventory for the key. + */ + private suspend fun getOrCreateInventory(key: T): Inventory { + return mutex.withLock { + inventories[key] ?: createInventory(key).also { + inventories[key] = it + fill(key, it) + } + } + } + + /** + * Get the key linked to the client to interact with the GUI. + * @param client Client to get the key for. + * @return The key. + */ + protected abstract suspend fun getKey(client: Client): T + + /** + * Create the inventory for the key. + * @param key Key to create the inventory for. + * @return New created inventory. + */ + protected abstract suspend fun createInventory(key: T): Inventory + + /** + * Fill the inventory for the key. + * @param key Key to fill the inventory for. + * @param inventory Inventory to fill. + */ + protected abstract suspend fun fill(key: T, inventory: Inventory) + + override suspend fun hasInventory(inventory: Inventory): Boolean { + return mutex.withLock { + inventories.values.contains(inventory) + } + } + + override suspend fun viewers(): List { + return mutex.withLock { + unsafeViewers() + } + } + + /** + * Get the viewers of the inventory. + * This function is not thread-safe. + * @return The viewers of the inventory. + */ + protected open fun unsafeViewers(): List { + return inventories.values.flatMap(Inventory::getViewers) + } + + override suspend fun contains(client: Client): Boolean { + return mutex.withLock { + unsafeContains(client) + } + } + + /** + * Check if the GUI contains the client. + * This function is not thread-safe. + * @param client Client to check. + * @return True if the GUI contains the client, false otherwise. + */ + protected open fun unsafeContains(client: Client): Boolean { + val player = client.player ?: return false + return inventories.values.any { it.viewers.contains(player) } + } + + override suspend fun close() { + super.close() + mutex.withLock { + inventories.values.forEach(Inventory::close) + inventories.clear() + } + } +} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 7ea5026c..ced3136c 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -98,13 +98,6 @@ public abstract class GUI { */ public abstract suspend fun hasInventory(inventory: Inventory): Boolean - /** - * Get the inventory of the GUI for the client. - * @param client Client to get the inventory for. - * @return The inventory of the GUI for the client. - */ - public abstract suspend fun getInventory(client: Client): Inventory? - /** * Close the inventory. * The inventory will be closed for all the viewers. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt deleted file mode 100644 index ad8d5be7..00000000 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PersonalGUI.kt +++ /dev/null @@ -1,101 +0,0 @@ -package com.github.rushyverse.api.gui - -import com.github.rushyverse.api.player.Client -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import org.bukkit.entity.HumanEntity -import org.bukkit.inventory.Inventory -import org.bukkit.inventory.InventoryHolder - -/** - * GUI where a new inventory is created for each viewer. - */ -public abstract class PersonalGUI : GUI() { - - private var inventories: MutableMap = mutableMapOf() - - private val mutex = Mutex() - - override suspend fun openGUI(client: Client): Boolean { - val inventory = createInventory(client) - - mutex.withLock { inventories[client] }?.close() - - val player = client.requirePlayer() - player.openInventory(inventory) - - mutex.withLock { inventories[client] = inventory } - return true - } - - /** - * Create the inventory for the client. - * Will translate the title and fill the inventory. - * @param client The client to create the inventory for. - * @return The inventory for the client. - */ - private suspend fun createInventory(client: Client): Inventory { - val player = client.requirePlayer() - return createInventory(player, client).also { - fill(client, it) - } - } - - /** - * Create the inventory for the client. - * This function is called when the [owner] wants to open the inventory. - * @param owner Player who wants to open the inventory. - * @param client The client to create the inventory for. - * @return The inventory for the client. - */ - protected abstract fun createInventory(owner: InventoryHolder, client: Client): Inventory - - /** - * Fill the inventory with items for the client. - * This function is called when the inventory is created. - * @param client The client to fill the inventory for. - * @param inventory The inventory to fill. - */ - protected abstract suspend fun fill(client: Client, inventory: Inventory) - - override suspend fun viewers(): List { - return mutex.withLock { - inventories.values.flatMap(Inventory::getViewers) - } - } - - override suspend fun contains(client: Client): Boolean { - return mutex.withLock { - inventories.containsKey(client) - } - } - - override suspend fun hasInventory(inventory: Inventory): Boolean { - return mutex.withLock { - inventories.values.contains(inventory) - } - } - - override suspend fun getInventory(client: Client): Inventory? { - return mutex.withLock { - inventories[client] - } - } - - override suspend fun close(client: Client, closeInventory: Boolean): Boolean { - return mutex.withLock { inventories.remove(client) }?.run { - if (closeInventory) { - client.player?.closeInventory() - } - true - } == true - } - - override suspend fun close() { - super.close() - mutex.withLock { - inventories.values.forEach(Inventory::close) - inventories.clear() - } - } -} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt index 82c4c166..ab5ba5d7 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt @@ -66,15 +66,11 @@ public abstract class SharedGUI : GUI() { return mutex.withLock { this.inventory } == inventory } - override suspend fun getInventory(client: Client): Inventory? { - return if (contains(client)) mutex.withLock { inventory } else null - } - override suspend fun close() { super.close() mutex.withLock { val inventory = inventory - if(inventory != null) { + if (inventory != null) { inventory.close() this.inventory = null } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/TranslateSharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/TranslateSharedGUI.kt new file mode 100644 index 00000000..77386b99 --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/TranslateSharedGUI.kt @@ -0,0 +1,33 @@ +package com.github.rushyverse.api.gui + +import com.github.rushyverse.api.player.Client +import java.util.* +import kotlinx.coroutines.sync.withLock +import org.bukkit.event.inventory.InventoryCloseEvent + +/** + * GUI where a new inventory is created for each language. + * This is useful to share the GUI between multiple players with the same language. + * + * For example, if two players have the same language, they will share the same inventory. + * If one of them changes their language, he will have another inventory dedicated to his new language. + */ +public abstract class TranslateSharedGUI : DedicatedGUI() { + + override suspend fun getKey(client: Client): Locale { + return client.lang().locale + } + + override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + if (!closeInventory) { + return false + } + + return mutex.withLock { + if (unsafeContains(client)) { + client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) + true + } else false + } + } +} diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/ClientGUITest.kt similarity index 98% rename from src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt rename to src/test/kotlin/com/github/rushyverse/api/gui/ClientGUITest.kt index 2fcea76c..c6213a02 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PersonalGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/ClientGUITest.kt @@ -28,7 +28,7 @@ import org.bukkit.inventory.InventoryHolder import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested -class PersonalGUITest : AbstractKoinTest() { +class ClientGUITest : AbstractKoinTest() { private lateinit var guiManager: GUIManager private lateinit var clientManager: ClientManager @@ -279,7 +279,7 @@ class PersonalGUITest : AbstractKoinTest() { } } -private class TestGUI(val serverMock: ServerMock, val type: InventoryType = InventoryType.HOPPER) : PersonalGUI() { +private class TestGUI(val serverMock: ServerMock, val type: InventoryType = InventoryType.HOPPER) : ClientGUI() { override fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, type) } @@ -293,7 +293,7 @@ private class TestGUI(val serverMock: ServerMock, val type: InventoryType = Inve } } -private class TestFilledGUI(val serverMock: ServerMock) : PersonalGUI() { +private class TestFilledGUI(val serverMock: ServerMock) : ClientGUI() { override fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, InventoryType.CHEST) } From ef66b2ce09231419d5dece0acdc1e6247fdb8575 Mon Sep 17 00:00:00 2001 From: Distractic Date: Sat, 16 Dec 2023 08:26:32 +0100 Subject: [PATCH 22/48] chore: Rename classes --- .../api/gui/{TranslateSharedGUI.kt => LocaleGUI.kt} | 4 ++-- .../rushyverse/api/gui/{ClientGUI.kt => PlayerGUI.kt} | 2 +- .../rushyverse/api/gui/{SharedGUI.kt => SingleGUI.kt} | 2 +- .../api/gui/{ClientGUITest.kt => PlayerGUITest.kt} | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) rename src/main/kotlin/com/github/rushyverse/api/gui/{TranslateSharedGUI.kt => LocaleGUI.kt} (88%) rename src/main/kotlin/com/github/rushyverse/api/gui/{ClientGUI.kt => PlayerGUI.kt} (96%) rename src/main/kotlin/com/github/rushyverse/api/gui/{SharedGUI.kt => SingleGUI.kt} (98%) rename src/test/kotlin/com/github/rushyverse/api/gui/{ClientGUITest.kt => PlayerGUITest.kt} (98%) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/TranslateSharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt similarity index 88% rename from src/main/kotlin/com/github/rushyverse/api/gui/TranslateSharedGUI.kt rename to src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt index 77386b99..9c004504 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/TranslateSharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt @@ -6,13 +6,13 @@ import kotlinx.coroutines.sync.withLock import org.bukkit.event.inventory.InventoryCloseEvent /** - * GUI where a new inventory is created for each language. + * GUI where a new inventory is created for each [locale][Locale]. * This is useful to share the GUI between multiple players with the same language. * * For example, if two players have the same language, they will share the same inventory. * If one of them changes their language, he will have another inventory dedicated to his new language. */ -public abstract class TranslateSharedGUI : DedicatedGUI() { +public abstract class LocaleGUI : DedicatedGUI() { override suspend fun getKey(client: Client): Locale { return client.lang().locale diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/ClientGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt similarity index 96% rename from src/main/kotlin/com/github/rushyverse/api/gui/ClientGUI.kt rename to src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt index ddf62c8f..cd3524b9 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/ClientGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt @@ -10,7 +10,7 @@ import org.bukkit.inventory.InventoryHolder * GUI where a new inventory is created for each player. * An inventory is created when the player opens the GUI and he is not sharing the GUI with another player. */ -public abstract class ClientGUI : DedicatedGUI() { +public abstract class PlayerGUI : DedicatedGUI() { override suspend fun getKey(client: Client): Client { return client diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt similarity index 98% rename from src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt rename to src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt index ab5ba5d7..167c74d5 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SharedGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt @@ -13,7 +13,7 @@ import org.bukkit.inventory.Inventory * @property viewers List of viewers. * @property inventory Inventory shared by all the viewers. */ -public abstract class SharedGUI : GUI() { +public abstract class SingleGUI : GUI() { private var inventory: Inventory? = null diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/ClientGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt similarity index 98% rename from src/test/kotlin/com/github/rushyverse/api/gui/ClientGUITest.kt rename to src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt index c6213a02..949d4d15 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/ClientGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt @@ -28,7 +28,7 @@ import org.bukkit.inventory.InventoryHolder import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested -class ClientGUITest : AbstractKoinTest() { +class PlayerGUITest : AbstractKoinTest() { private lateinit var guiManager: GUIManager private lateinit var clientManager: ClientManager @@ -279,7 +279,7 @@ class ClientGUITest : AbstractKoinTest() { } } -private class TestGUI(val serverMock: ServerMock, val type: InventoryType = InventoryType.HOPPER) : ClientGUI() { +private class TestGUI(val serverMock: ServerMock, val type: InventoryType = InventoryType.HOPPER) : PlayerGUI() { override fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, type) } @@ -293,7 +293,7 @@ private class TestGUI(val serverMock: ServerMock, val type: InventoryType = Inve } } -private class TestFilledGUI(val serverMock: ServerMock) : ClientGUI() { +private class TestFilledGUI(val serverMock: ServerMock) : PlayerGUI() { override fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, InventoryType.CHEST) } From 0bc8fd13416706de91502dbeaa84724ad510f038 Mon Sep 17 00:00:00 2001 From: Distractic <46402441+Distractic@users.noreply.github.com> Date: Tue, 19 Dec 2023 10:20:27 +0100 Subject: [PATCH 23/48] feat: Loading GUI (#134) --- .../github/rushyverse/api/gui/DedicatedGUI.kt | 112 ------ .../com/github/rushyverse/api/gui/GUI.kt | 295 ++++++++++++-- .../github/rushyverse/api/gui/GUIListener.kt | 26 +- .../github/rushyverse/api/gui/GUIManager.kt | 25 +- .../github/rushyverse/api/gui/LocaleGUI.kt | 37 +- .../github/rushyverse/api/gui/PlayerGUI.kt | 33 +- .../github/rushyverse/api/gui/SingleGUI.kt | 91 ++--- .../api/gui/load/InventoryLoadingAnimation.kt | 18 + .../load/ShiftInventoryLoadingAnimation.kt | 48 +++ .../github/rushyverse/api/player/Client.kt | 2 +- .../github/rushyverse/api/AbstractKoinTest.kt | 2 + .../rushyverse/api/gui/AbstractGUITest.kt | 373 ++++++++++++++++++ .../rushyverse/api/gui/GUIListenerTest.kt | 45 +-- .../rushyverse/api/gui/GUIManagerTest.kt | 34 +- .../rushyverse/api/gui/LocalePlayerGUITest.kt | 226 +++++++++++ .../rushyverse/api/gui/PlayerGUITest.kt | 333 +++++----------- .../rushyverse/api/gui/SingleGUITest.kt | 195 +++++++++ .../rushyverse/api/player/ClientTest.kt | 16 +- 18 files changed, 1371 insertions(+), 540 deletions(-) delete mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/load/InventoryLoadingAnimation.kt create mode 100644 src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt create mode 100644 src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt create mode 100644 src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt create mode 100644 src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt deleted file mode 100644 index 164341ba..00000000 --- a/src/main/kotlin/com/github/rushyverse/api/gui/DedicatedGUI.kt +++ /dev/null @@ -1,112 +0,0 @@ -package com.github.rushyverse.api.gui - -import com.github.rushyverse.api.player.Client -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import org.bukkit.entity.HumanEntity -import org.bukkit.inventory.Inventory - -/** - * GUI where a new inventory is created for each key used. - * @param T Type of the key. - * @property inventories Map of inventories for each key. - * @property mutex Mutex to process thread-safe operations. - */ -public abstract class DedicatedGUI : GUI() { - - protected var inventories: MutableMap = mutableMapOf() - - protected val mutex: Mutex = Mutex() - - override suspend fun openGUI(client: Client): Boolean { - val key = getKey(client) - val inventory = getOrCreateInventory(key) - - val player = client.requirePlayer() - player.openInventory(inventory) - - return true - } - - /** - * Get the inventory for the key. - * If the inventory does not exist, create it. - * @param key Key to get the inventory for. - * @return The inventory for the key. - */ - private suspend fun getOrCreateInventory(key: T): Inventory { - return mutex.withLock { - inventories[key] ?: createInventory(key).also { - inventories[key] = it - fill(key, it) - } - } - } - - /** - * Get the key linked to the client to interact with the GUI. - * @param client Client to get the key for. - * @return The key. - */ - protected abstract suspend fun getKey(client: Client): T - - /** - * Create the inventory for the key. - * @param key Key to create the inventory for. - * @return New created inventory. - */ - protected abstract suspend fun createInventory(key: T): Inventory - - /** - * Fill the inventory for the key. - * @param key Key to fill the inventory for. - * @param inventory Inventory to fill. - */ - protected abstract suspend fun fill(key: T, inventory: Inventory) - - override suspend fun hasInventory(inventory: Inventory): Boolean { - return mutex.withLock { - inventories.values.contains(inventory) - } - } - - override suspend fun viewers(): List { - return mutex.withLock { - unsafeViewers() - } - } - - /** - * Get the viewers of the inventory. - * This function is not thread-safe. - * @return The viewers of the inventory. - */ - protected open fun unsafeViewers(): List { - return inventories.values.flatMap(Inventory::getViewers) - } - - override suspend fun contains(client: Client): Boolean { - return mutex.withLock { - unsafeContains(client) - } - } - - /** - * Check if the GUI contains the client. - * This function is not thread-safe. - * @param client Client to check. - * @return True if the GUI contains the client, false otherwise. - */ - protected open fun unsafeContains(client: Client): Boolean { - val player = client.player ?: return false - return inventories.values.any { it.viewers.contains(player) } - } - - override suspend fun close() { - super.close() - mutex.withLock { - inventories.values.forEach(Inventory::close) - inventories.clear() - } - } -} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index ced3136c..9f037538 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -1,26 +1,67 @@ package com.github.rushyverse.api.gui +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.Client +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.cancellable +import kotlinx.coroutines.flow.onCompletion +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import mu.KotlinLogging +import org.bukkit.Material import org.bukkit.Server import org.bukkit.entity.HumanEntity import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack +/** + * Pair of an index and an ItemStack. + */ +public typealias ItemStackIndex = Pair + +/** + * Data class to store the inventory and the loading job. + * Can be used to cancel the loading job if the inventory is closed. + * @property inventory Inventory created. + * @property job Loading job to fill & animate the loading of the inventory. + * @property isLoading If true, the inventory is loading; otherwise it is filled or cancelled. + */ +public data class InventoryData( + val inventory: Inventory, + val job: Job, +) { + + val isLoading: Boolean get() = job.isActive + +} + private val logger = KotlinLogging.logger {} /** * Exception concerning the GUI. */ -public open class GUIException(message: String) : RuntimeException(message) +public open class GUIException(message: String) : CancellationException(message) /** * Exception thrown when the GUI is closed. */ public class GUIClosedException(message: String) : GUIException(message) +/** + * Exception thrown when the GUI is closed for a specific client. + * @property client Client for which the GUI is closed. + */ +public class GUIClosedForClientException(public val client: Client) : + GUIException("GUI closed for client ${client.playerUUID}") + /** * GUI that can be shared by multiple players. * Only one inventory is created for all the viewers. @@ -28,18 +69,35 @@ public class GUIClosedException(message: String) : GUIException(message) * @property manager Manager to register or unregister the GUI. * @property isClosed If true, the GUI is closed; otherwise it is open. */ -public abstract class GUI { +public abstract class GUI( + private val loadingAnimation: InventoryLoadingAnimation? = null, + initialNumberInventories: Int = 16, +) { protected val server: Server by inject() - private val manager: GUIManager by inject() + protected val manager: GUIManager by inject() public var isClosed: Boolean = false protected set - init { - register() - } + protected var inventories: MutableMap = HashMap(initialNumberInventories) + + protected val mutex: Mutex = Mutex() + + /** + * Get the key linked to the client to interact with the GUI. + * @param client Client to get the key for. + * @return The key. + */ + protected abstract suspend fun getKey(client: Client): T + + /** + * Get the coroutine scope to fill the inventory and the loading animation. + * @param key Key to get the coroutine scope for. + * @return The coroutine scope. + */ + protected abstract suspend fun fillScope(key: T): CoroutineScope /** * Open the GUI for the client only if the GUI is not closed. @@ -51,11 +109,6 @@ public abstract class GUI { public suspend fun open(client: Client): Boolean { requireOpen() - val gui = client.gui() - if (gui === this) return false - // If the client has another GUI opened, close it. - gui?.close(client, true) - val player = client.player if (player === null) { logger.warn { "Cannot open inventory for player ${client.playerUUID}: player is null" } @@ -64,39 +117,174 @@ public abstract class GUI { // If the player is dead, do not open the GUI because the interface cannot be shown to the player. if (player.isDead) return false - return openGUI(client) + val gui = client.gui() + if (gui === this) return false + + // Here we don't need + // to force to close the GUI because the GUI is closed when the player opens another inventory + // (if not cancelled). + + val key = getKey(client) + val inventory = getOrCreateInventory(key) + + // We open the inventory out of the mutex to avoid blocking operation from registered Listener. + if (player.openInventory(inventory) == null) { + // If the opening was cancelled (null returned), + // We need to unregister the client from the GUI + // and maybe close the inventory if it is individual. + close(client, false) + return false + } + + return true } /** - * Open the GUI for the client. - * Called by [open] after all the checks. - * @param client Client to open the GUI for. - * @return True if the GUI was opened, false otherwise. + * Get the inventory for the key. + * If the inventory does not exist, create it. + * @param key Key to get the inventory for. + * @return The inventory for the key. */ - protected abstract suspend fun openGUI(client: Client): Boolean + private suspend fun getOrCreateInventory(key: T): Inventory { + return mutex.withLock { + val loadedInventory = inventories[key] + if (loadedInventory != null) { + return@withLock loadedInventory.inventory + } + + val inventory = createInventory(key) + // Start the fill asynchronously to avoid blocking the other inventory creation with the mutex. + val loadingJob = startLoadingInventory(key, inventory) + inventories[key] = InventoryData(inventory, loadingJob) + + inventory + } + } /** - * Action to do when the client clicks on an item in the inventory. - * @param client Client who clicked. - * @param clickedItem Item clicked by the client. - * @param event Event of the click. + * Start the asynchronous loading animation and fill the inventory. + * @param key Key to create the inventory for. + * @param inventory Inventory to fill and animate. + * @return The job that can be cancelled to stop the loading animation. + */ + private suspend fun startLoadingInventory(key: T, inventory: Inventory): Job { + // If no suspend operation is used in the flow, the fill will be done in the same thread & tick. + // That's why we start with unconfined dispatcher. + return fillScope(key).launch(Dispatchers.Unconfined) { + val size = inventory.size + val inventoryFlowItems = getItems(key, size).cancellable() + + if (loadingAnimation == null) { + // Will fill the inventory bit by bit. + inventoryFlowItems.collect { (index, item) -> inventory.setItem(index, item) } + } else { + val loadingAnimationJob = launch { loadingAnimation.loading(key, inventory) } + + // To avoid conflicts with the loading animation, + // we need to store the items in a temporary inventory + val temporaryInventory = arrayOfNulls(size) + + inventoryFlowItems + .onCompletion { exception -> + // When the flow is finished, we cancel the loading animation. + loadingAnimationJob.cancelAndJoin() + + // If the flow was completed successfully, we fill the inventory with the temporary inventory. + if (exception == null) { + inventory.contents = temporaryInventory + } + }.collect { (index, item) -> temporaryInventory[index] = item } + } + } + } + + /** + * Create the inventory for the key. + * @param key Key to create the inventory for. + * @return New created inventory. */ - public abstract suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) + protected abstract fun createInventory(key: T): Inventory /** - * Remove the client has a viewer of the GUI. - * @param client Client to close the GUI for. - * @param closeInventory If true, the interface will be closed, otherwise it will be kept open. - * @return True if the inventory was closed, false otherwise. + * Create a new flow of [Item][ItemStack] to fill the inventory with. + * ```kotlin + * flow { + * emit(0 to ItemStack(Material.STONE)) + * delay(1.seconds) // simulate a suspend operation + * emit(1 to ItemStack(Material.DIRT)) + * } + * ``` + * If the flow doesn't suspend the coroutine, + * the inventory will be filled in the same tick & thread than during the creation of the inventory. + * @param key Key to fill the inventory for. + * @param size Size of the inventory. + * @return Flow of [Item][ItemStack] with index. */ - public abstract suspend fun close(client: Client, closeInventory: Boolean = true): Boolean + protected abstract fun getItems(key: T, size: Int): Flow /** * Check if the GUI contains the inventory. * @param inventory Inventory to check. * @return True if the GUI contains the inventory, false otherwise. */ - public abstract suspend fun hasInventory(inventory: Inventory): Boolean + public open suspend fun hasInventory(inventory: Inventory): Boolean { + return mutex.withLock { + inventories.values.any { it.inventory == inventory } + } + } + + /** + * Check if the inventory is loading. + * @param inventory Inventory to check. + * @return True if the inventory is loading (all the items are not loaded), + * false if the inventory is loaded or not present in the GUI. + */ + public open suspend fun isInventoryLoading(inventory: Inventory): Boolean { + return mutex.withLock { + inventories.values.firstOrNull { it.inventory == inventory }?.isLoading == true + } + } + + /** + * Get the viewers of the GUI. + * @return List of viewers. + */ + public open suspend fun viewers(): Sequence { + return mutex.withLock { + unsafeViewers() + } + } + + /** + * Get the viewers of the inventory. + * This function is not thread-safe. + * @return The viewers of the inventory. + */ + protected open fun unsafeViewers(): Sequence { + return inventories.values.asSequence().map { it.inventory }.flatMap(Inventory::getViewers) + } + + /** + * Check if the GUI contains the player. + * @param client Client to check. + * @return True if the GUI contains the player, false otherwise. + */ + public open suspend fun contains(client: Client): Boolean { + return mutex.withLock { + unsafeContains(client) + } + } + + /** + * Check if the GUI contains the client. + * This function is not thread-safe. + * @param client Client to check. + * @return True if the GUI contains the client, false otherwise. + */ + protected open fun unsafeContains(client: Client): Boolean { + val player = client.player ?: return false + return unsafeViewers().any { it == player } + } /** * Close the inventory. @@ -106,8 +294,27 @@ public abstract class GUI { public open suspend fun close() { isClosed = true unregister() + + mutex.withLock { + inventories.values.forEach { + it.job.apply { + cancel(GUIClosedException("The GUI is closing")) + join() + } + it.inventory.close() + } + inventories.clear() + } } + /** + * Remove the client has a viewer of the GUI. + * @param client Client to close the GUI for. + * @param closeInventory If true, the interface will be closed, otherwise it will be kept open. + * @return True if the inventory was closed, false otherwise. + */ + public abstract suspend fun close(client: Client, closeInventory: Boolean = true): Boolean + /** * Verify that the GUI is open. * If the GUI is closed, throw an exception. @@ -116,33 +323,35 @@ public abstract class GUI { if (isClosed) throw GUIClosedException("Cannot use a closed GUI") } - /** - * Get the viewers of the GUI. - * @return List of viewers. - */ - public abstract suspend fun viewers(): List - - /** - * Check if the GUI contains the player. - * @param client Client to check. - * @return True if the GUI contains the player, false otherwise. - */ - public abstract suspend fun contains(client: Client): Boolean - /** * Register the GUI to the listener. * @return True if the GUI was registered, false otherwise. */ - protected fun register(): Boolean { + public open suspend fun register(): Boolean { + requireOpen() return manager.add(this) } /** * Unregister the GUI from the listener. + * Should be called when the GUI is closed with [close]. * @return True if the GUI was unregistered, false otherwise. */ - protected fun unregister(): Boolean { + protected open suspend fun unregister(): Boolean { return manager.remove(this) } + /** + * Action to do when the client clicks on an item in the inventory. + * @param client Client who clicked. + * @param clickedItem Item clicked by the client cannot be null or [AIR][Material.AIR] + * @param clickedInventory Inventory where the click was detected. + * @param event Event of the click. + */ + public abstract suspend fun onClick( + client: Client, + clickedInventory: Inventory, + clickedItem: ItemStack, + event: InventoryClickEvent + ) } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt index af3cebc9..8053552f 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt @@ -17,7 +17,6 @@ import org.bukkit.event.block.Action import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.event.player.PlayerInteractEvent -import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack import org.bukkit.inventory.PlayerInventory @@ -42,8 +41,10 @@ public class GUIListener(private val plugin: Plugin) : Listener { if (event.isCancelled) return val item = event.currentItem + // If the item is null or air, we should ignore the click if (item == null || item.type == Material.AIR) return + // If the click is not in an inventory, this is not a GUI click val clickedInventory = event.clickedInventory ?: return val player = event.whoClicked @@ -75,7 +76,7 @@ public class GUIListener(private val plugin: Plugin) : Listener { // The item in a GUI is not supposed to be moved event.cancel() - gui.onClick(client, item, event) + gui.onClick(client, clickedInventory, item, event) } /** @@ -116,27 +117,10 @@ public class GUIListener(private val plugin: Plugin) : Listener { */ @EventHandler public suspend fun onInventoryClose(event: InventoryCloseEvent) { - quitOpenedGUI(event.player) - } - - /** - * Called when a player quits the server. - * If the player has a GUI opened, the GUI is notified that it is closed for this player. - * @param event Event of the quit. - */ - @EventHandler - public suspend fun onPlayerQuit(event: PlayerQuitEvent) { - quitOpenedGUI(event.player) - } - - /** - * Quit the opened GUI for the player. - * @param player Player to quit the GUI for. - */ - private suspend fun quitOpenedGUI(player: HumanEntity) { - val client = clients.getClientOrNull(player) + val client = clients.getClientOrNull(event.player) val gui = client?.gui() ?: return // We don't close the inventory because it is closing due to event. + // That avoids an infinite loop of events and consequently a stack overflow. gui.close(client, false) } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt index f110d828..fc720077 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIManager.kt @@ -1,6 +1,8 @@ package com.github.rushyverse.api.gui import com.github.rushyverse.api.player.Client +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock /** * Manages the GUIs for players within the game. @@ -8,15 +10,20 @@ import com.github.rushyverse.api.player.Client */ public class GUIManager { + /** + * Mutex used to ensure thread-safe operations. + */ + private val mutex = Mutex() + /** * Private mutable set storing GUIs. */ - private val _guis = mutableSetOf() + private val _guis = mutableSetOf>() /** * Immutable view of the GUIs set. */ - public val guis: Collection get() = _guis + public val guis: Collection> get() = _guis /** * Retrieves the GUI for the specified player. @@ -25,8 +32,10 @@ public class GUIManager { * @param client The player for whom the GUI is to be retrieved or created. * @return The language associated with the player. */ - public suspend fun get(client: Client): GUI? { - return _guis.firstOrNull { it.contains(client) } + public suspend fun get(client: Client): GUI<*>? { + return mutex.withLock { + guis.firstOrNull { it.contains(client) } + } } /** @@ -34,8 +43,8 @@ public class GUIManager { * @param gui GUI to add. * @return True if the GUI was added, false otherwise. */ - public fun add(gui: GUI): Boolean { - return _guis.add(gui) + public suspend fun add(gui: GUI<*>): Boolean { + return mutex.withLock { _guis.add(gui) } } /** @@ -43,7 +52,7 @@ public class GUIManager { * @param gui GUI to remove. * @return True if the GUI was removed, false otherwise. */ - public fun remove(gui: GUI): Boolean { - return _guis.remove(gui) + public suspend fun remove(gui: GUI<*>): Boolean { + return mutex.withLock { _guis.remove(gui) } } } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt index 9c004504..4eaf1977 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt @@ -1,9 +1,16 @@ package com.github.rushyverse.api.gui +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client +import com.github.rushyverse.api.translation.SupportedLanguage +import com.github.shynixn.mccoroutine.bukkit.scope import java.util.* -import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.job +import kotlinx.coroutines.plus import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.plugin.Plugin /** * GUI where a new inventory is created for each [locale][Locale]. @@ -12,22 +19,28 @@ import org.bukkit.event.inventory.InventoryCloseEvent * For example, if two players have the same language, they will share the same inventory. * If one of them changes their language, he will have another inventory dedicated to his new language. */ -public abstract class LocaleGUI : DedicatedGUI() { +public abstract class LocaleGUI( + protected val plugin: Plugin, + loadingAnimation: InventoryLoadingAnimation? = null, + initialNumberInventories: Int = SupportedLanguage.entries.size +) : GUI( + loadingAnimation = loadingAnimation, + initialNumberInventories = initialNumberInventories +) { override suspend fun getKey(client: Client): Locale { return client.lang().locale } - override suspend fun close(client: Client, closeInventory: Boolean): Boolean { - if (!closeInventory) { - return false - } + override suspend fun fillScope(key: Locale): CoroutineScope { + val scope = plugin.scope + return scope + SupervisorJob(scope.coroutineContext.job) + } - return mutex.withLock { - if (unsafeContains(client)) { - client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) - true - } else false - } + override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + return if (closeInventory && contains(client)) { + client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) + true + } else false } } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt index cd3524b9..d5a096fc 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt @@ -1,8 +1,12 @@ package com.github.rushyverse.api.gui +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.job +import kotlinx.coroutines.plus import kotlinx.coroutines.sync.withLock -import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.inventory.Inventory import org.bukkit.inventory.InventoryHolder @@ -10,19 +14,25 @@ import org.bukkit.inventory.InventoryHolder * GUI where a new inventory is created for each player. * An inventory is created when the player opens the GUI and he is not sharing the GUI with another player. */ -public abstract class PlayerGUI : DedicatedGUI() { +public abstract class PlayerGUI( + loadingAnimation: InventoryLoadingAnimation? = null +) : GUI(loadingAnimation = loadingAnimation) { override suspend fun getKey(client: Client): Client { return client } + override suspend fun fillScope(key: Client): CoroutineScope { + return key + SupervisorJob(key.coroutineContext.job) + } + /** * Create the inventory for the client. * Will translate the title and fill the inventory. * @param key The client to create the inventory for. * @return The inventory for the client. */ - override suspend fun createInventory(key: Client): Inventory { + override fun createInventory(key: Client): Inventory { val player = key.requirePlayer() return createInventory(player, key) } @@ -42,11 +52,16 @@ public abstract class PlayerGUI : DedicatedGUI() { } override suspend fun close(client: Client, closeInventory: Boolean): Boolean { - return mutex.withLock { inventories.remove(client) }?.run { - if (closeInventory) { - client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) - } - true - } == true + val (inventory, job) = mutex.withLock { inventories.remove(client) } ?: return false + + job.cancel(GUIClosedForClientException(client)) + job.join() + + if (closeInventory) { + // Call out of the lock to avoid slowing down the mutex. + inventory.close() + } + + return true } } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt index 167c74d5..3ec24c71 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt @@ -1,86 +1,71 @@ package com.github.rushyverse.api.gui +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import org.bukkit.entity.HumanEntity +import com.github.shynixn.mccoroutine.bukkit.scope +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.job +import kotlinx.coroutines.plus +import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.inventory.Inventory +import org.bukkit.plugin.Plugin /** * GUI that can be shared by multiple players. * Only one inventory is created for all the viewers. * @property server Server. * @property viewers List of viewers. - * @property inventory Inventory shared by all the viewers. */ -public abstract class SingleGUI : GUI() { +public abstract class SingleGUI( + protected val plugin: Plugin, + loadingAnimation: InventoryLoadingAnimation? = null +) : GUI( + loadingAnimation = loadingAnimation, + initialNumberInventories = 1 +) { - private var inventory: Inventory? = null + public companion object { + /** + * Unique key for the GUI. + * This GUI is shared by all the players, so the key is the same for all of them. + * That allows creating a unique inventory. + */ + private val KEY = Any() + } - private val mutex = Mutex() + override suspend fun getKey(client: Client): Any { + return KEY + } - override suspend fun openGUI(client: Client): Boolean { - val player = client.requirePlayer() - val inventory = getOrCreateInventory() - player.openInventory(inventory) - return true + override suspend fun fillScope(key: Any): CoroutineScope { + val scope = plugin.scope + return scope + SupervisorJob(scope.coroutineContext.job) } - /** - * Get the inventory of the GUI. - * If the inventory is not created, create it. - * @return The inventory of the GUI. - */ - private suspend fun getOrCreateInventory(): Inventory { - return mutex.withLock { - inventory ?: createInventory().also { - inventory = it - fill(it) - } - } + override fun createInventory(key: Any): Inventory { + return createInventory() } /** - * Create the inventory of the GUI. - * This function is called only once when the inventory is created. - * @return A new inventory. + * @see createInventory(key) */ protected abstract fun createInventory(): Inventory override suspend fun close(client: Client, closeInventory: Boolean): Boolean { return if (closeInventory && contains(client)) { - client.player?.closeInventory() + client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) true } else false } - override suspend fun viewers(): List { - return mutex.withLock { inventory?.viewers } ?: emptyList() - } - - override suspend fun contains(client: Client): Boolean { - return client.player?.let { it in viewers() } == true - } - - override suspend fun hasInventory(inventory: Inventory): Boolean { - return mutex.withLock { this.inventory } == inventory - } - - override suspend fun close() { - super.close() - mutex.withLock { - val inventory = inventory - if (inventory != null) { - inventory.close() - this.inventory = null - } - } + override fun getItems(key: Any, size: Int): Flow { + return getItems(size) } /** - * Fill the inventory with items for the client. - * This function is called when the inventory is created. - * @param inventory The inventory to fill. + * @see getItems(key, size) */ - protected abstract suspend fun fill(inventory: Inventory) + protected abstract fun getItems(size: Int): Flow } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/load/InventoryLoadingAnimation.kt b/src/main/kotlin/com/github/rushyverse/api/gui/load/InventoryLoadingAnimation.kt new file mode 100644 index 00000000..a6179f74 --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/load/InventoryLoadingAnimation.kt @@ -0,0 +1,18 @@ +package com.github.rushyverse.api.gui.load + +import org.bukkit.inventory.Inventory + +/** + * Animate an inventory while it is being loaded in the background. + * @param T Type of the key. + */ +public fun interface InventoryLoadingAnimation { + + /** + * Animate the inventory while the real inventory is being loaded in the background. + * @param key Key to animate the inventory for. + * @param inventory Inventory to animate. + * @return A job that can be cancelled to stop the animation. + */ + public suspend fun loading(key: T, inventory: Inventory) +} diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt new file mode 100644 index 00000000..14f95f3e --- /dev/null +++ b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt @@ -0,0 +1,48 @@ +package com.github.rushyverse.api.gui.load + +import java.util.* +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack + +/** + * Animation that shifts the items in the inventory. + * The items are shifted by [shift] slots every [delay]. + * The items are placed in the inventory by calling [initialize]. + * If too few items are returned by [initialize], the remaining slots will be filled with null items. + * If too many items are returned by [initialize], the overflowing items will be ignored. + * @param T Type of the key. + * @property initialize Function that returns the sequence of items to place in the inventory. + * @property shift Number of slots to shift the items by. + * @property delay Delay between each shift. + */ +public class ShiftInventoryLoadingAnimation( + private val initialize: (T) -> Sequence, + private val shift: Int = 1, + private val delay: Duration = 100.milliseconds, +) : InventoryLoadingAnimation { + + override suspend fun loading(key: T, inventory: Inventory) { + coroutineScope { + val size = inventory.size + val contents = arrayOfNulls(size) + // Fill the inventory with the initial items. + // If the sequence is too short, it will be filled with null items. + // If the sequence is too long, the overflowing items will be ignored. + initialize(key).take(size).forEachIndexed { index, item -> + contents[index] = item + } + + val contentList = contents.toMutableList() + while (isActive) { + inventory.contents = contentList.toTypedArray() + delay(delay) + Collections.rotate(contentList, shift) + } + } + } +} diff --git a/src/main/kotlin/com/github/rushyverse/api/player/Client.kt b/src/main/kotlin/com/github/rushyverse/api/player/Client.kt index bb6ff06f..22c9cefe 100644 --- a/src/main/kotlin/com/github/rushyverse/api/player/Client.kt +++ b/src/main/kotlin/com/github/rushyverse/api/player/Client.kt @@ -81,6 +81,6 @@ public open class Client( * Get the opened GUI of the player. * @return The opened GUI of the player. */ - public suspend fun gui(): GUI? = guiManager.get(this) + public suspend fun gui(): GUI<*>? = guiManager.get(this) } diff --git a/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt b/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt index df562752..fef9664c 100644 --- a/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/AbstractKoinTest.kt @@ -5,6 +5,7 @@ import com.github.rushyverse.api.koin.loadModule import com.github.rushyverse.api.utils.randomString import io.mockk.every import io.mockk.mockk +import io.mockk.unmockkAll import kotlin.test.AfterTest import kotlin.test.BeforeTest import org.bukkit.Server @@ -47,6 +48,7 @@ open class AbstractKoinTest { open fun onAfter() { CraftContext.stopKoin(pluginId) CraftContext.stopKoin(APIPlugin.ID_API) + unmockkAll() } fun loadTestModule(moduleDeclaration: ModuleDeclaration): Module = diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt new file mode 100644 index 00000000..abf9ff48 --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt @@ -0,0 +1,373 @@ +package com.github.rushyverse.api.gui + +import be.seeseemelk.mockbukkit.MockBukkit +import be.seeseemelk.mockbukkit.ServerMock +import be.seeseemelk.mockbukkit.entity.PlayerMock +import com.github.rushyverse.api.AbstractKoinTest +import com.github.rushyverse.api.extension.ItemStack +import com.github.rushyverse.api.player.Client +import com.github.rushyverse.api.player.ClientManager +import com.github.rushyverse.api.player.ClientManagerImpl +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.collections.shouldContainAll +import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import kotlin.coroutines.EmptyCoroutineContext +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import org.bukkit.Material +import org.bukkit.event.inventory.InventoryType +import org.bukkit.inventory.ItemStack + +abstract class AbstractGUITest : AbstractKoinTest() { + + protected lateinit var guiManager: GUIManager + protected lateinit var clientManager: ClientManager + protected lateinit var serverMock: ServerMock + + @BeforeTest + override fun onBefore() { + super.onBefore() + guiManager = GUIManager() + clientManager = ClientManagerImpl() + + loadApiTestModule { + single { guiManager } + single { clientManager } + } + + serverMock = MockBukkit.mock() + } + + @AfterTest + override fun onAfter() { + super.onAfter() + MockBukkit.unmock() + } + + abstract inner class Register { + + @Test + fun `should register if not already registered`() = runTest { + val gui = createNonFillGUI() + gui.register() shouldBe true + guiManager.guis shouldContainAll listOf(gui) + } + + @Test + fun `should not register if already registered`() = runTest { + val gui = createNonFillGUI() + gui.register() shouldBe true + gui.register() shouldBe false + guiManager.guis shouldContainAll listOf(gui) + } + + @Test + fun `should throw exception if GUI is closed`() = runTest { + val gui = createNonFillGUI() + gui.close() + shouldThrow { gui.register() } + } + } + + abstract inner class Viewers { + + @Test + fun `should return empty list if no client is viewing the GUI`() = runTest { + val gui = createNonFillGUI() + gui.viewers().toList() shouldBe emptyList() + } + + @Test + fun `should return the list of clients viewing the GUI`() = runTest { + val gui = createNonFillGUI() + val playerClients = List(5) { registerPlayer() } + + playerClients.forEach { (_, client) -> + gui.open(client) shouldBe true + } + + gui.viewers().toList() shouldContainExactlyInAnyOrder playerClients.map { it.first } + } + + } + + abstract inner class Contains { + + @Test + fun `should return false if the client is not viewing the GUI`() = runTest { + val gui = createNonFillGUI() + val (_, client) = registerPlayer() + gui.contains(client) shouldBe false + } + + @Test + fun `should return true if the client is viewing the GUI`() = runTest { + val gui = createNonFillGUI() + val (_, client) = registerPlayer() + gui.open(client) shouldBe true + gui.contains(client) shouldBe true + } + + } + + abstract inner class Open { + + @Test + fun `should throw exception if GUI is closed`() = runTest { + val gui = createNonFillGUI() + gui.close() + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + shouldThrow { gui.open(client) } + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should do nothing if the client has the same GUI opened`() = runTest { + val type = InventoryType.HOPPER + val gui = createNonFillGUI(inventoryType = type) + gui.register() + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + player.assertInventoryView(type) + + gui.open(client) shouldBe false + player.assertInventoryView(type) + } + + @Test + fun `should do nothing if the player is dead`() = runTest { + val gui = createNonFillGUI() + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + player.health = 0.0 + gui.open(client) shouldBe false + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should fill the inventory in the same thread if no suspend operation`() { + + val items: Array = arrayOf( + ItemStack { type = Material.DIAMOND_ORE }, + ItemStack { type = Material.STICK }, + ) + + runBlocking { + val currentThread = Thread.currentThread() + + val type = InventoryType.ENDER_CHEST + val gui = createFillGUI(items, delay = null, inventoryType = type) + gui.register() + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + player.assertInventoryView(type) + + val inventory = player.openInventory.topInventory + gui.isInventoryLoading(inventory) shouldBe false + + val content = inventory.contents + items.forEachIndexed { index, item -> + content[index] shouldBe item + } + + for (i in items.size until content.size) { + content[i] shouldBe null + } + + getFillThreadBeforeSuspend(gui) shouldBe currentThread + getFillThreadAfterSuspend(gui) shouldBe currentThread + } + } + + @Test + fun `should fill the inventory in the other thread after suspend operation`() { + + val items: Array = arrayOf( + ItemStack { type = Material.DIAMOND_AXE }, + ItemStack { type = Material.ACACIA_LEAVES }, + ) + + runBlocking { + val currentThread = Thread.currentThread() + + val type = InventoryType.ENDER_CHEST + val delay = 100.milliseconds + val gui = createFillGUI(items = items, delay = delay, inventoryType = type) + gui.register() + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + player.assertInventoryView(type) + + val inventory = player.openInventory.topInventory + gui.isInventoryLoading(inventory) shouldBe true + + val content = inventory.contents + content.forEach { it shouldBe null } + + delay(delay * 2) + gui.isInventoryLoading(inventory) shouldBe false + + items.forEachIndexed { index, item -> + content[index] shouldBe item + } + + for (i in items.size until content.size) { + content[i] shouldBe null + } + + getFillThreadBeforeSuspend(gui) shouldBe currentThread + getFillThreadAfterSuspend(gui) shouldNotBe currentThread + } + } + + } + + abstract inner class Close { + + @Test + fun `should close all inventories and remove all viewers`() = runTest { + val type = InventoryType.BREWING + val gui = createNonFillGUI(type) + gui.register() + + val playerClients = List(5) { registerPlayer() } + val initialInventoryViewType = playerClients.first().first.openInventory.type + + playerClients.forEach { (player, client) -> + player.assertInventoryView(initialInventoryViewType) + gui.open(client) shouldBe true + player.assertInventoryView(type) + client.gui() shouldBe gui + } + + gui.close() + playerClients.forEach { (player, client) -> + player.assertInventoryView(initialInventoryViewType) + client.gui() shouldBe null + } + } + + @Test + fun `should set isClosed to true`() = runTest { + val gui = createNonFillGUI() + gui.isClosed shouldBe false + gui.close() + gui.isClosed shouldBe true + } + + @Test + fun `should unregister the GUI`() = runTest { + val gui = createNonFillGUI() + gui.register() + guiManager.guis shouldContainAll listOf(gui) + gui.close() + guiManager.guis shouldContainAll listOf() + } + + @Test + fun `should not be able to open the GUI after closing it`() = runTest { + val gui = createNonFillGUI() + gui.register() + val (_, client) = registerPlayer() + gui.close() + + shouldThrow { + gui.open(client) + } + } + + @Test + fun `should not be able to register the GUI after closing it`() = runTest { + val gui = createNonFillGUI() + gui.close() + shouldThrow { + gui.register() + } + } + } + + abstract inner class CloseForClient { + + @Test + fun `should return false if the client is not viewing the GUI`() = runTest { + val gui = createNonFillGUI() + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + player.assertInventoryView(initialInventoryViewType) + gui.close(client, true) shouldBe false + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should return true if the client is viewing the GUI`() = runTest { + val type = InventoryType.DISPENSER + val gui = createNonFillGUI(type) + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + gui.open(client) shouldBe true + player.assertInventoryView(type) + gui.close(client, true) shouldBe true + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should not close for other clients`() = runTest { + val type = InventoryType.HOPPER + val gui = createNonFillGUI(type) + val (player, client) = registerPlayer() + val (player2, client2) = registerPlayer() + val initialInventoryViewType = player2.openInventory.type + + gui.open(client) shouldBe true + gui.open(client2) shouldBe true + + player.assertInventoryView(type) + player2.assertInventoryView(type) + + gui.close(client2, true) shouldBe true + player.assertInventoryView(type) + player2.assertInventoryView(initialInventoryViewType) + } + + + } + + abstract fun createNonFillGUI(inventoryType: InventoryType = InventoryType.HOPPER): GUI<*> + + abstract fun createFillGUI( + items: Array, + inventoryType: InventoryType = InventoryType.HOPPER, + delay: Duration? = null + ): GUI<*> + + abstract fun getFillThreadBeforeSuspend(gui: GUI<*>): Thread? + + abstract fun getFillThreadAfterSuspend(gui: GUI<*>): Thread? + + protected suspend fun registerPlayer(): Pair { + val player = serverMock.addPlayer() + val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) + clientManager.put(player, client) + return player to client + } +} diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 54900bb5..6d9f6e27 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -27,14 +27,12 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.test.runTest -import net.kyori.adventure.text.Component import org.bukkit.Material import org.bukkit.entity.Player import org.bukkit.event.block.Action import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.event.player.PlayerInteractEvent -import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested @@ -80,7 +78,7 @@ class GUIListenerTest : AbstractKoinTest() { } callEvent(true, player, ItemStack { type = Material.DIRT }, player.inventory) - coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + coVerify(exactly = 0) { gui.onClick(any(), any(), any(), any()) } } @Test @@ -92,7 +90,7 @@ class GUIListenerTest : AbstractKoinTest() { suspend fun callEvent(item: ItemStack?) { val event = callEvent(false, player, item, player.inventory) - coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + coVerify(exactly = 0) { gui.onClick(any(), any(), any(), any()) } verify(exactly = 0) { event.cancel() } } @@ -114,7 +112,7 @@ class GUIListenerTest : AbstractKoinTest() { val item = ItemStack { type = Material.DIRT } callEvent(false, player, item, mockk()) - coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + coVerify(exactly = 0) { gui.onClick(any(), any(), any(), any()) } verify(exactly = 0) { pluginManager.callSuspendingEvent(any(), plugin) } } @@ -136,7 +134,7 @@ class GUIListenerTest : AbstractKoinTest() { val item = ItemStack { type = Material.DIRT } callEvent(false, player, item, player.inventory) - coVerify(exactly = 0) { gui.onClick(any(), any(), any()) } + coVerify(exactly = 0) { gui.onClick(any(), any(), any(), any()) } verify(exactly = 1) { pluginManager.callSuspendingEvent(any(), plugin) } jobs.forEach { it.isCompleted shouldBe true } @@ -153,13 +151,13 @@ class GUIListenerTest : AbstractKoinTest() { val inventory = mockk() val gui = registerGUI { coEvery { contains(client) } returns true - coEvery { onClick(client, any(), any()) } returns Unit + coEvery { onClick(client, any(), any(), any()) } returns Unit coEvery { hasInventory(inventory) } returns true } val item = ItemStack { type = Material.DIRT } val event = callEvent(false, player, item, inventory) - coVerify(exactly = 1) { gui.onClick(client, item, event) } + coVerify(exactly = 1) { gui.onClick(client, inventory, item, event) } verify(exactly = 1) { event.cancel() } } @@ -183,7 +181,8 @@ class GUIListenerTest : AbstractKoinTest() { } - abstract inner class CloseGUIDuringEvent { + @Nested + inner class OnInventoryClose { @Test fun `should do nothing if client doesn't have a GUI opened`() = runTest { @@ -192,9 +191,7 @@ class GUIListenerTest : AbstractKoinTest() { coEvery { contains(client) } returns false } - val event = PlayerQuitEvent(player, Component.empty(), PlayerQuitEvent.QuitReason.DISCONNECTED) - listener.onPlayerQuit(event) - + callEvent(player) coVerify(exactly = 0) { gui.close(client, any()) } } @@ -216,14 +213,7 @@ class GUIListenerTest : AbstractKoinTest() { coVerify(exactly = 0) { gui2.close(client, any()) } } - protected abstract suspend fun callEvent(player: Player) - - } - - @Nested - inner class OnInventoryClose : CloseGUIDuringEvent() { - - override suspend fun callEvent(player: Player) { + private suspend fun callEvent(player: Player) { val event = mockk { every { getPlayer() } returns player } @@ -231,17 +221,6 @@ class GUIListenerTest : AbstractKoinTest() { } } - @Nested - inner class OnPlayerQuit : CloseGUIDuringEvent() { - - override suspend fun callEvent(player: Player) { - val event = mockk { - every { getPlayer() } returns player - } - listener.onPlayerQuit(event) - } - } - private suspend fun registerPlayer(): Pair { val player = serverMock.addPlayer() val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) @@ -249,8 +228,8 @@ class GUIListenerTest : AbstractKoinTest() { return player to client } - private inline fun registerGUI(block: GUI.() -> Unit): GUI { - val gui = mockk(block = block) + private suspend inline fun registerGUI(block: GUI<*>.() -> Unit): GUI<*> { + val gui = mockk>(block = block) guiManager.add(gui) return gui } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt index e861e595..04c2c6b0 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIManagerTest.kt @@ -30,7 +30,7 @@ class GUIManagerTest { @Test fun `should returns null if no GUI contains the client`() = runTest { val client = mockk() - val gui = mockk { + val gui = mockk> { coEvery { contains(any()) } returns false } manager.add(gui) @@ -40,7 +40,7 @@ class GUIManagerTest { @Test fun `should returns GUI if contains the client`() = runTest { val client = mockk() - val gui = mockk { + val gui = mockk> { coEvery { contains(client) } returns true } manager.add(gui) @@ -51,7 +51,7 @@ class GUIManagerTest { fun `should returns GUI if contains the asked client`() = runTest { val client = mockk() val client2 = mockk() - val gui = mockk { + val gui = mockk> { coEvery { contains(client) } returns true coEvery { contains(client2) } returns false } @@ -66,16 +66,16 @@ class GUIManagerTest { inner class Add { @Test - fun `should add non registered GUI`() { - val gui = mockk() + fun `should add non registered GUI`() = runTest { + val gui = mockk>() manager.add(gui) shouldBe true manager.guis.contains(gui) shouldBe true manager.guis.size shouldBe 1 } @Test - fun `should not add registered GUI`() { - val gui = mockk() + fun `should not add registered GUI`() = runTest { + val gui = mockk>() manager.add(gui) shouldBe true manager.add(gui) shouldBe false manager.guis.contains(gui) shouldBe true @@ -83,9 +83,9 @@ class GUIManagerTest { } @Test - fun `should add multiple GUIs`() { - val gui1 = mockk() - val gui2 = mockk() + fun `should add multiple GUIs`() = runTest { + val gui1 = mockk>() + val gui2 = mockk>() manager.add(gui1) shouldBe true manager.add(gui2) shouldBe true manager.guis.contains(gui1) shouldBe true @@ -99,8 +99,8 @@ class GUIManagerTest { inner class Remove { @Test - fun `should remove registered GUI`() { - val gui = mockk() + fun `should remove registered GUI`() = runTest { + val gui = mockk>() manager.add(gui) shouldBe true manager.remove(gui) shouldBe true manager.guis.contains(gui) shouldBe false @@ -108,17 +108,17 @@ class GUIManagerTest { } @Test - fun `should not remove non registered GUI`() { - val gui = mockk() + fun `should not remove non registered GUI`() = runTest { + val gui = mockk>() manager.remove(gui) shouldBe false manager.guis.contains(gui) shouldBe false manager.guis.size shouldBe 0 } @Test - fun `should remove one GUI`() { - val gui1 = mockk() - val gui2 = mockk() + fun `should remove one GUI`() = runTest { + val gui1 = mockk>() + val gui2 = mockk>() manager.add(gui1) shouldBe true manager.add(gui2) shouldBe true manager.remove(gui1) shouldBe true diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt new file mode 100644 index 00000000..3e0fdce6 --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt @@ -0,0 +1,226 @@ +package com.github.rushyverse.api.gui + +import be.seeseemelk.mockbukkit.ServerMock +import com.github.rushyverse.api.player.Client +import com.github.rushyverse.api.player.language.LanguageManager +import com.github.rushyverse.api.translation.SupportedLanguage +import com.github.shynixn.mccoroutine.bukkit.scope +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import io.mockk.every +import io.mockk.mockkStatic +import java.util.* +import kotlin.coroutines.EmptyCoroutineContext +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryType +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import org.bukkit.plugin.Plugin +import org.junit.jupiter.api.Nested +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource + +class LocalePlayerGUITest : AbstractGUITest() { + + private lateinit var languageManager: LanguageManager + + @BeforeTest + override fun onBefore() { + super.onBefore() + languageManager = LanguageManager() + + loadApiTestModule { + single { languageManager } + } + + mockkStatic("com.github.shynixn.mccoroutine.bukkit.MCCoroutineKt") + every { plugin.scope } returns CoroutineScope(EmptyCoroutineContext) + } + + override fun createFillGUI(items: Array, inventoryType: InventoryType, delay: Duration?): GUI<*> { + return LocaleFillGUI(plugin, serverMock, inventoryType, items, delay) + } + + override fun createNonFillGUI(inventoryType: InventoryType): GUI<*> { + return LocaleNonFillGUI(plugin, serverMock, inventoryType) + } + + override fun getFillThreadAfterSuspend(gui: GUI<*>): Thread? { + return (gui as LocaleFillGUI).newThread + } + + override fun getFillThreadBeforeSuspend(gui: GUI<*>): Thread? { + return (gui as LocaleFillGUI).calledThread + } + + @Nested + inner class Register : AbstractGUITest.Register() + + @Nested + inner class Viewers : AbstractGUITest.Viewers() + + @Nested + inner class Contains : AbstractGUITest.Contains() + + @Nested + inner class Open : AbstractGUITest.Open() { + + @Test + fun `should create a new inventory according to the language client`() = runTest { + val type = InventoryType.HOPPER + val gui = createNonFillGUI(type) + val (player, client) = registerPlayer() + val (player2, client2) = registerPlayer() + languageManager.set(player, SupportedLanguage.ENGLISH) + languageManager.set(player2, SupportedLanguage.FRENCH) + + gui.open(client) shouldBe true + gui.open(client2) shouldBe true + + player.assertInventoryView(type) + player2.assertInventoryView(type) + + player.openInventory.topInventory shouldNotBe player2.openInventory.topInventory + } + + @Test + fun `should use the same inventory according to the language client`() = runTest { + val type = InventoryType.DISPENSER + val gui = createNonFillGUI(type) + val (player, client) = registerPlayer() + val (player2, client2) = registerPlayer() + languageManager.set(player, SupportedLanguage.FRENCH) + languageManager.set(player2, SupportedLanguage.FRENCH) + + gui.open(client) shouldBe true + gui.open(client2) shouldBe true + + player.assertInventoryView(type) + player2.assertInventoryView(type) + + player.openInventory.topInventory shouldBe player2.openInventory.topInventory + } + + @Test + fun `should not create a new inventory for the same client if previously closed`() = runTest { + val type = InventoryType.BREWING + val gui = createNonFillGUI(type) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + val firstInventory = player.openInventory.topInventory + + gui.close(client, true) shouldBe true + + gui.open(client) shouldBe true + player.openInventory.topInventory shouldBe firstInventory + + player.assertInventoryView(type) + } + + } + + @Nested + inner class Close : AbstractGUITest.Close() + + @Nested + inner class CloseForClient : AbstractGUITest.CloseForClient() { + + @ParameterizedTest + @ValueSource(booleans = [true, false]) + fun `should not stop loading the inventory if the client is viewing the GUI`(closeInventory: Boolean) { + runBlocking { + val type = InventoryType.HOPPER + val gui = createFillGUI(emptyArray(), delay = 10.minutes, inventoryType = type) + gui.register() + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + gui.open(client) shouldBe true + player.assertInventoryView(type) + + val openInventory = player.openInventory + val inventory = openInventory.topInventory + gui.isInventoryLoading(inventory) shouldBe true + + gui.close(client, closeInventory) shouldBe closeInventory + gui.isInventoryLoading(inventory) shouldBe true + + if (closeInventory) { + player.assertInventoryView(initialInventoryViewType) + gui.contains(client) shouldBe false + } else { + player.assertInventoryView(type) + gui.contains(client) shouldBe true + } + } + } + } +} + +private abstract class AbstractLocaleGUITest( + plugin: Plugin, + val serverMock: ServerMock, + val type: InventoryType = InventoryType.HOPPER +) : LocaleGUI(plugin) { + + override fun createInventory(key: Locale): Inventory { + return serverMock.createInventory(null, type) + } + + override suspend fun onClick( + client: Client, + clickedInventory: Inventory, + clickedItem: ItemStack, + event: InventoryClickEvent + ) { + error("Should not be called") + } +} + +private class LocaleNonFillGUI( + plugin: Plugin, + serverMock: ServerMock, + type: InventoryType +) : AbstractLocaleGUITest(plugin, serverMock, type) { + + override fun getItems(key: Locale, size: Int): Flow { + return emptyFlow() + } +} + +private class LocaleFillGUI( + plugin: Plugin, + serverMock: ServerMock, + type: InventoryType, + val items: Array, + val delay: Duration? +) : AbstractLocaleGUITest(plugin, serverMock, type) { + + var calledThread: Thread? = null + + var newThread: Thread? = null + + override fun getItems(key: Locale, size: Int): Flow { + calledThread = Thread.currentThread() + return flow { + delay?.let { delay(it) } + items.forEachIndexed { index, item -> + emit(index to item) + } + newThread = Thread.currentThread() + } + } +} diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt index 949d4d15..6f5877d4 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt @@ -1,309 +1,192 @@ package com.github.rushyverse.api.gui -import be.seeseemelk.mockbukkit.MockBukkit import be.seeseemelk.mockbukkit.ServerMock -import be.seeseemelk.mockbukkit.entity.PlayerMock -import com.github.rushyverse.api.AbstractKoinTest -import com.github.rushyverse.api.extension.ItemStack import com.github.rushyverse.api.player.Client -import com.github.rushyverse.api.player.ClientManager -import com.github.rushyverse.api.player.ClientManagerImpl -import io.kotest.assertions.throwables.shouldThrow -import io.kotest.matchers.collections.shouldContainAll -import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import kotlin.coroutines.EmptyCoroutineContext -import kotlin.test.AfterTest -import kotlin.test.BeforeTest import kotlin.test.Test +import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes -import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest -import org.bukkit.Material import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryType import org.bukkit.inventory.Inventory import org.bukkit.inventory.InventoryHolder import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource -class PlayerGUITest : AbstractKoinTest() { - - private lateinit var guiManager: GUIManager - private lateinit var clientManager: ClientManager - private lateinit var serverMock: ServerMock - - @BeforeTest - override fun onBefore() { - super.onBefore() - guiManager = GUIManager() - clientManager = ClientManagerImpl() - - loadApiTestModule { - single { guiManager } - single { clientManager } - } - - serverMock = MockBukkit.mock() - } - - @AfterTest - override fun onAfter() { - super.onAfter() - MockBukkit.unmock() - } +class PlayerGUITest : AbstractGUITest() { @Nested - inner class Open { - - @Test - fun `should throw exception if GUI is closed`() = runTest { - val gui = TestGUI(serverMock) - gui.close() - val (player, client) = registerPlayer() - - val initialInventoryViewType = player.openInventory.type - shouldThrow { gui.open(client) } - player.assertInventoryView(initialInventoryViewType) - } + inner class Register : AbstractGUITest.Register() - @Test - fun `should do nothing if the client has the same GUI opened`() = runTest { - val gui = TestGUI(serverMock) - val (player, client) = registerPlayer() - - gui.open(client) shouldBe true - player.assertInventoryView(gui.type) - - gui.open(client) shouldBe false - player.assertInventoryView(gui.type) - } - - @Test - fun `should close the previous GUI if the client has one opened`() = runTest { - val gui = TestGUI(serverMock, InventoryType.ENDER_CHEST) - val (player, client) = registerPlayer() - - gui.open(client) shouldBe true - player.assertInventoryView(gui.type) - - val gui2 = TestGUI(serverMock, InventoryType.CHEST) - gui2.open(client) shouldBe true - player.assertInventoryView(gui2.type) - gui.contains(client) shouldBe false - gui2.contains(client) shouldBe true - } - - @Test - fun `should do nothing if the player is dead`() = runTest { - val gui = TestGUI(serverMock) - val (player, client) = registerPlayer() + @Nested + inner class Viewers : AbstractGUITest.Viewers() - val initialInventoryViewType = player.openInventory.type + @Nested + inner class Contains : AbstractGUITest.Contains() - player.damage(Double.MAX_VALUE) - gui.open(client) shouldBe false - player.assertInventoryView(initialInventoryViewType) - } + @Nested + inner class Open : AbstractGUITest.Open() { @Test fun `should create a new inventory for the client`() = runTest { - val gui = TestGUI(serverMock) + val type = InventoryType.ENDER_CHEST + val gui = createNonFillGUI(type) val (player, client) = registerPlayer() val (player2, client2) = registerPlayer() gui.open(client) shouldBe true gui.open(client2) shouldBe true - player.assertInventoryView(gui.type) - player2.assertInventoryView(gui.type) + player.assertInventoryView(type) + player2.assertInventoryView(type) player.openInventory.topInventory shouldNotBe player2.openInventory.topInventory } @Test - fun `should fill the inventory`() = runTest { - val gui = TestFilledGUI(serverMock) + fun `should create a new inventory for the same client if previous is closed before`() = runTest { + val type = InventoryType.BREWING + val gui = createNonFillGUI(type) val (player, client) = registerPlayer() gui.open(client) shouldBe true - player.assertInventoryView(InventoryType.CHEST) - - val inventory = player.openInventory.topInventory - val content = inventory.contents - println(content.contentToString()) - content[0]!!.type shouldBe Material.DIAMOND_ORE - content[1]!!.type shouldBe Material.STICK - - for (i in 2 until content.size) { - content[i] shouldBe null - } - } - - } + val firstInventory = player.openInventory.topInventory - @Nested - inner class Viewers { - - @Test - fun `should return empty list if no client is viewing the GUI`() = runTest { - val gui = TestGUI(serverMock) - gui.viewers() shouldBe emptyList() - } - - @Test - fun `should return the list of clients viewing the GUI`() = runTest { - val gui = TestGUI(serverMock) - val playerClients = List(5) { registerPlayer() } + gui.close(client, true) shouldBe true - playerClients.forEach { (_, client) -> - gui.open(client) shouldBe true - } + gui.open(client) shouldBe true + player.openInventory.topInventory shouldNotBe firstInventory - gui.viewers() shouldContainExactlyInAnyOrder playerClients.map { it.first } + player.assertInventoryView(type) } - } @Nested - inner class Contains { - - @Test - fun `should return false if the client is not viewing the GUI`() = runTest { - val gui = TestGUI(serverMock) - val (_, client) = registerPlayer() - gui.contains(client) shouldBe false - } - - @Test - fun `should return true if the client is viewing the GUI`() = runTest { - val gui = TestGUI(serverMock) - val (_, client) = registerPlayer() - gui.open(client) shouldBe true - gui.contains(client) shouldBe true - } - - } + inner class Close : AbstractGUITest.Close() @Nested - inner class CloseForClient { - - @Test - fun `should return false if the client is not viewing the GUI`() = runTest(timeout = 1.minutes) { - val gui = TestGUI(serverMock) - val (player, client) = registerPlayer() + inner class CloseForClient : AbstractGUITest.CloseForClient() { + + @ParameterizedTest + @ValueSource(booleans = [true, false]) + fun `should stop loading the inventory if the client is viewing the GUI`(closeInventory: Boolean) { + runBlocking { + val type = InventoryType.DROPPER + val gui = createFillGUI(items = emptyArray(), inventoryType = type, delay = 10.minutes) + gui.register() + val (player, client) = registerPlayer() - val initialInventoryViewType = player.openInventory.type + val initialInventoryViewType = player.openInventory.type - player.assertInventoryView(initialInventoryViewType) - gui.close(client, true) shouldBe false - player.assertInventoryView(initialInventoryViewType) - } + gui.open(client) shouldBe true + player.assertInventoryView(type) - @Test - fun `should close the inventory if the client is viewing the GUI`() = runTest(timeout = 1.minutes) { - val gui = TestGUI(serverMock) - val (player, client) = registerPlayer() + val openInventory = player.openInventory + val inventory = openInventory.topInventory + gui.isInventoryLoading(inventory) shouldBe true - val initialInventoryViewType = player.openInventory.type + gui.close(client, closeInventory) shouldBe true + gui.isInventoryLoading(inventory) shouldBe false - gui.open(client) shouldBe true - player.assertInventoryView(gui.type) - gui.close(client, true) shouldBe true - player.assertInventoryView(initialInventoryViewType) + if (closeInventory) { + player.assertInventoryView(initialInventoryViewType) + } else { + player.assertInventoryView(type) + } + } } @Test fun `should remove client inventory without closing it if closeInventory is false`() = - runTest(timeout = 1.minutes) { - val gui = TestGUI(serverMock) + runTest { + val type = InventoryType.ENDER_CHEST + val gui = NonFillGUI(serverMock, type = type) val (player, client) = registerPlayer() gui.open(client) shouldBe true - player.assertInventoryView(gui.type) + player.assertInventoryView(type) + gui.close(client, false) shouldBe true - player.assertInventoryView(gui.type) + player.assertInventoryView(type) + gui.contains(client) shouldBe false } - } - @Nested - inner class Close { - - @Test - fun `should close all inventories and remove all viewers`() = runTest(timeout = 1.minutes) { - val gui = TestGUI(serverMock, InventoryType.BREWING) - - val playerClients = List(5) { registerPlayer() } - val initialInventoryViewType = playerClients.first().first.openInventory.type - - playerClients.forEach { (player, client) -> - player.assertInventoryView(initialInventoryViewType) - gui.open(client) shouldBe true - player.assertInventoryView(gui.type) - client.gui() shouldBe gui - } - - gui.close() - playerClients.forEach { (player, client) -> - player.assertInventoryView(initialInventoryViewType) - client.gui() shouldBe null - } - } - - @Test - fun `should set isClosed to true`() = runTest { - val gui = TestGUI(serverMock) - gui.isClosed shouldBe false - gui.close() - gui.isClosed shouldBe true - } + override fun createNonFillGUI(inventoryType: InventoryType): GUI<*> { + return NonFillGUI(serverMock, inventoryType) + } - @Test - fun `should unregister the GUI`() = runTest { - val gui = TestGUI(serverMock) - guiManager.guis shouldContainAll listOf(gui) - gui.close() - guiManager.guis shouldContainAll listOf() - } + override fun createFillGUI(items: Array, inventoryType: InventoryType, delay: Duration?): GUI<*> { + return FillGUI(serverMock, inventoryType, items, delay) + } + override fun getFillThreadBeforeSuspend(gui: GUI<*>): Thread? { + return (gui as FillGUI).calledThread } - private suspend fun registerPlayer(): Pair { - val player = serverMock.addPlayer() - val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) - clientManager.put(player, client) - return player to client + override fun getFillThreadAfterSuspend(gui: GUI<*>): Thread? { + return (gui as FillGUI).newThread } } -private class TestGUI(val serverMock: ServerMock, val type: InventoryType = InventoryType.HOPPER) : PlayerGUI() { +private abstract class AbstractPlayerGUITest( + val serverMock: ServerMock, + val type: InventoryType +) : PlayerGUI() { + override fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, type) } - override suspend fun fill(client: Client, inventory: Inventory) { - // Do nothing - } - - override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { + override suspend fun onClick( + client: Client, + clickedInventory: Inventory, + clickedItem: ItemStack, + event: InventoryClickEvent + ) { error("Should not be called") } } -private class TestFilledGUI(val serverMock: ServerMock) : PlayerGUI() { - override fun createInventory(owner: InventoryHolder, client: Client): Inventory { - return serverMock.createInventory(owner, InventoryType.CHEST) - } +private class NonFillGUI( + serverMock: ServerMock, + type: InventoryType +) : AbstractPlayerGUITest(serverMock, type) { - override suspend fun fill(client: Client, inventory: Inventory) { - inventory.setItem(0, ItemStack { type = Material.DIAMOND_ORE }) - inventory.setItem(1, ItemStack { type = Material.STICK }) + override fun getItems(key: Client, size: Int): Flow { + return emptyFlow() } +} - override suspend fun onClick(client: Client, clickedItem: ItemStack, event: InventoryClickEvent) { - error("Should not be called") +private class FillGUI( + serverMock: ServerMock, + type: InventoryType, + val items: Array, + val delay: Duration? +) : AbstractPlayerGUITest(serverMock, type) { + + var calledThread: Thread? = null + + var newThread: Thread? = null + + override fun getItems(key: Client, size: Int): Flow { + calledThread = Thread.currentThread() + return flow { + delay?.let { delay(it) } + items.forEachIndexed { index, item -> + emit(index to item) + } + newThread = Thread.currentThread() + } } } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt new file mode 100644 index 00000000..0cd3c26f --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -0,0 +1,195 @@ +package com.github.rushyverse.api.gui + +import be.seeseemelk.mockbukkit.ServerMock +import com.github.rushyverse.api.player.Client +import com.github.shynixn.mccoroutine.bukkit.scope +import io.kotest.matchers.shouldBe +import io.mockk.every +import io.mockk.mockkStatic +import kotlin.coroutines.EmptyCoroutineContext +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryType +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import org.bukkit.plugin.Plugin +import org.junit.jupiter.api.Nested +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource + +class SingleGUITest : AbstractGUITest() { + + @BeforeTest + override fun onBefore() { + super.onBefore() + mockkStatic("com.github.shynixn.mccoroutine.bukkit.MCCoroutineKt") + every { plugin.scope } returns CoroutineScope(EmptyCoroutineContext) + } + + override fun createNonFillGUI(inventoryType: InventoryType): GUI<*> { + return SingleNonFillGUI(plugin, serverMock, inventoryType) + } + + override fun createFillGUI(items: Array, inventoryType: InventoryType, delay: Duration?): GUI<*> { + return SingleFillGUI(plugin, serverMock, inventoryType, items, delay) + } + + override fun getFillThreadBeforeSuspend(gui: GUI<*>): Thread? { + return (gui as SingleFillGUI).calledThread + } + + override fun getFillThreadAfterSuspend(gui: GUI<*>): Thread? { + return (gui as SingleFillGUI).newThread + } + + @Nested + inner class Register : AbstractGUITest.Register() + + @Nested + inner class Viewers : AbstractGUITest.Viewers() + + @Nested + inner class Contains : AbstractGUITest.Contains() + + @Nested + inner class Open : AbstractGUITest.Open() { + + @Test + fun `should use the same inventory for all clients`() = runTest { + val type = InventoryType.ENDER_CHEST + val gui = createNonFillGUI(type) + val inventories = List(5) { + val (player, client) = registerPlayer() + gui.open(client) shouldBe true + player.assertInventoryView(type) + + player.openInventory.topInventory + } + + inventories.all { it === inventories.first() } shouldBe true + } + + @Test + fun `should not create a new inventory for the same client if previously closed`() = runTest { + val type = InventoryType.BREWING + val gui = createNonFillGUI(type) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + val firstInventory = player.openInventory.topInventory + + gui.close(client, true) shouldBe true + + gui.open(client) shouldBe true + player.openInventory.topInventory shouldBe firstInventory + + player.assertInventoryView(type) + } + } + + @Nested + inner class Close : AbstractGUITest.Close() + + @Nested + inner class CloseForClient : AbstractGUITest.CloseForClient() { + + @ParameterizedTest + @ValueSource(booleans = [true, false]) + fun `should not stop loading the inventory if the client is viewing the GUI`(closeInventory: Boolean) { + runBlocking { + val type = InventoryType.DROPPER + val gui = createFillGUI(emptyArray(), delay = 10.minutes, inventoryType = type) + gui.register() + val (player, client) = registerPlayer() + + val initialInventoryViewType = player.openInventory.type + + gui.open(client) shouldBe true + player.assertInventoryView(type) + + val openInventory = player.openInventory + val inventory = openInventory.topInventory + gui.isInventoryLoading(inventory) shouldBe true + + gui.close(client, closeInventory) shouldBe closeInventory + gui.isInventoryLoading(inventory) shouldBe true + + if (closeInventory) { + player.assertInventoryView(initialInventoryViewType) + gui.contains(client) shouldBe false + } else { + player.assertInventoryView(type) + gui.contains(client) shouldBe true + } + } + } + + } +} + +private abstract class AbstractSingleGUITest( + plugin: Plugin, + val serverMock: ServerMock, + val type: InventoryType +) : SingleGUI(plugin) { + + override fun createInventory(): Inventory { + return serverMock.createInventory(null, type) + } + + override suspend fun onClick( + client: Client, + clickedInventory: Inventory, + clickedItem: ItemStack, + event: InventoryClickEvent + ) { + error("Should not be called") + } + +} + +private class SingleNonFillGUI( + plugin: Plugin, + serverMock: ServerMock, + type: InventoryType +) : AbstractSingleGUITest(plugin, serverMock, type) { + + override fun getItems(size: Int): Flow { + return emptyFlow() + } + +} + +private class SingleFillGUI( + plugin: Plugin, + serverMock: ServerMock, + type: InventoryType, + val items: Array, + val delay: Duration? +) : AbstractSingleGUITest(plugin, serverMock, type) { + + var calledThread: Thread? = null + + var newThread: Thread? = null + + override fun getItems(size: Int): Flow { + calledThread = Thread.currentThread() + return flow { + delay?.let { delay(it) } + items.forEachIndexed { index, item -> + emit(index to item) + } + newThread = Thread.currentThread() + } + } +} diff --git a/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt b/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt index 7d356af7..205eb4cc 100644 --- a/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/player/ClientTest.kt @@ -10,13 +10,17 @@ import com.github.rushyverse.api.player.exception.PlayerNotFoundException import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.mockk -import kotlinx.coroutines.CoroutineScope -import org.junit.jupiter.api.assertThrows import java.util.* import kotlin.coroutines.EmptyCoroutineContext -import kotlin.test.* +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Nested +import org.junit.jupiter.api.assertThrows class ClientTest : AbstractKoinTest() { @@ -75,7 +79,7 @@ class ClientTest : AbstractKoinTest() { } @Nested - inner class GetGUI { + inner class GetGUI { @Test fun `get GUI returns null if no GUI is registered`() = runTest { @@ -86,7 +90,7 @@ class ClientTest : AbstractKoinTest() { @Test fun `get GUI returns null if no GUI contains the client`() = runTest { val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) - val gui = mockk { + val gui = mockk> { coEvery { contains(client) } returns false } guiManager.add(gui) @@ -96,7 +100,7 @@ class ClientTest : AbstractKoinTest() { @Test fun `get GUI returns GUI if contains the client`() = runTest { val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) - val gui = mockk { + val gui = mockk> { coEvery { contains(client) } returns true } guiManager.add(gui) From 67786706425c1578090e3a9ddef3fc08d83afec6 Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 11:00:06 +0100 Subject: [PATCH 24/48] feat: Implement update function --- .../com/github/rushyverse/api/gui/GUI.kt | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 9f037538..ae5ad80c 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -55,6 +55,11 @@ public open class GUIException(message: String) : CancellationException(message) */ public class GUIClosedException(message: String) : GUIException(message) +/** + * Exception thrown when the GUI is updating. + */ +public class GUIUpdatedException(message: String) : GUIException(message) + /** * Exception thrown when the GUI is closed for a specific client. * @property client Client for which the GUI is closed. @@ -106,7 +111,7 @@ public abstract class GUI( * @param client Client to open the GUI for. * @return True if the GUI was opened, false otherwise. */ - public suspend fun open(client: Client): Boolean { + public open suspend fun open(client: Client): Boolean { requireOpen() val player = client.player @@ -139,6 +144,48 @@ public abstract class GUI( return true } + /** + * Update the opened inventory for the client. + * + * If the client has the GUI opened, the inventory will be updated. + * If the client has another GUI opened, do nothing. + * + * Call [getItems] to get the new items to fill the inventory. + * @param client Client to update the inventory for. + * @param interruptLoading If true and if the inventory is loading, the loading will be interrupted + * to start a new loading animation. + * @return True if the inventory was updated, false otherwise. + * @see [getItems] + */ + public open suspend fun update(client: Client, interruptLoading: Boolean = false): Boolean { + return mutex.withLock { + val key = getKey(client) + val inventoryData = inventories[key] ?: return@withLock false + + // If the client doesn't have the GUI opened, do nothing. + if (!unsafeContains(client)) return@withLock false + + if (inventoryData.isLoading) { + // If we don't want to interrupt the loading and the inventory is loading, do nothing. + if (!interruptLoading) return@withLock false + else { + // If we want to interrupt the loading, we cancel the loading job. + // We need to wait for the job to be cancelled to avoid conflicts with the new loading animation. + inventoryData.job.apply { + cancel(GUIUpdatedException("The GUI is updating")) + join() + } + } + } + + val inventory = inventoryData.inventory + // Begin a new loading job and replace the old one. + val newLoadingJob = startLoadingInventory(key, inventory) + inventories[key] = InventoryData(inventory, newLoadingJob) + true + } + } + /** * Get the inventory for the key. * If the inventory does not exist, create it. From d25ea07d139b0159180f5a2446de34f54c5b1a96 Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 16:01:15 +0100 Subject: [PATCH 25/48] test: Add tests about update method --- .../com/github/rushyverse/api/gui/GUI.kt | 30 ++--- .../rushyverse/api/gui/AbstractGUITest.kt | 117 ++++++++++++------ .../rushyverse/api/gui/LocalePlayerGUITest.kt | 3 + .../rushyverse/api/gui/PlayerGUITest.kt | 3 + .../rushyverse/api/gui/SingleGUITest.kt | 3 + 5 files changed, 101 insertions(+), 55 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index ae5ad80c..78fbc024 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -58,7 +58,8 @@ public class GUIClosedException(message: String) : GUIException(message) /** * Exception thrown when the GUI is updating. */ -public class GUIUpdatedException(message: String) : GUIException(message) +public class GUIUpdatedException(public val client: Client) : + GUIException("GUI updating for client ${client.playerUUID}") /** * Exception thrown when the GUI is closed for a specific client. @@ -72,7 +73,6 @@ public class GUIClosedForClientException(public val client: Client) : * Only one inventory is created for all the viewers. * @property server Server. * @property manager Manager to register or unregister the GUI. - * @property isClosed If true, the GUI is closed; otherwise it is open. */ public abstract class GUI( private val loadingAnimation: InventoryLoadingAnimation? = null, @@ -83,9 +83,6 @@ public abstract class GUI( protected val manager: GUIManager by inject() - public var isClosed: Boolean = false - protected set - protected var inventories: MutableMap = HashMap(initialNumberInventories) protected val mutex: Mutex = Mutex() @@ -112,8 +109,6 @@ public abstract class GUI( * @return True if the GUI was opened, false otherwise. */ public open suspend fun open(client: Client): Boolean { - requireOpen() - val player = client.player if (player === null) { logger.warn { "Cannot open inventory for player ${client.playerUUID}: player is null" } @@ -158,8 +153,9 @@ public abstract class GUI( * @see [getItems] */ public open suspend fun update(client: Client, interruptLoading: Boolean = false): Boolean { + val key = getKey(client) + return mutex.withLock { - val key = getKey(client) val inventoryData = inventories[key] ?: return@withLock false // If the client doesn't have the GUI opened, do nothing. @@ -172,7 +168,7 @@ public abstract class GUI( // If we want to interrupt the loading, we cancel the loading job. // We need to wait for the job to be cancelled to avoid conflicts with the new loading animation. inventoryData.job.apply { - cancel(GUIUpdatedException("The GUI is updating")) + cancel(GUIUpdatedException(client)) join() } } @@ -219,6 +215,10 @@ public abstract class GUI( // That's why we start with unconfined dispatcher. return fillScope(key).launch(Dispatchers.Unconfined) { val size = inventory.size + // Empty the inventory, there is no effect if the inventory is new + // But avoid conflicts with old items if the inventory is updated. + inventory.contents = arrayOfNulls(size) + val inventoryFlowItems = getItems(key, size).cancellable() if (loadingAnimation == null) { @@ -339,7 +339,6 @@ public abstract class GUI( * The GUI will be removed from the listener and the [onClick] function will not be called anymore. */ public open suspend fun close() { - isClosed = true unregister() mutex.withLock { @@ -362,20 +361,13 @@ public abstract class GUI( */ public abstract suspend fun close(client: Client, closeInventory: Boolean = true): Boolean - /** - * Verify that the GUI is open. - * If the GUI is closed, throw an exception. - */ - private fun requireOpen() { - if (isClosed) throw GUIClosedException("Cannot use a closed GUI") - } - /** * Register the GUI to the listener. + * If the GUI is already registered, do nothing. + * If the GUI is closed, he will be opened again. * @return True if the GUI was registered, false otherwise. */ public open suspend fun register(): Boolean { - requireOpen() return manager.add(this) } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt index abf9ff48..4cf452b3 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt @@ -8,7 +8,6 @@ import com.github.rushyverse.api.extension.ItemStack import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl -import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe @@ -71,10 +70,10 @@ abstract class AbstractGUITest : AbstractKoinTest() { } @Test - fun `should throw exception if GUI is closed`() = runTest { + fun `should register GUI if was closed`() = runTest { val gui = createNonFillGUI() gui.close() - shouldThrow { gui.register() } + gui.register() shouldBe true } } @@ -122,14 +121,15 @@ abstract class AbstractGUITest : AbstractKoinTest() { abstract inner class Open { @Test - fun `should throw exception if GUI is closed`() = runTest { - val gui = createNonFillGUI() + fun `should open if GUI was closed`() = runTest { + val type = InventoryType.FURNACE + val gui = createNonFillGUI(type) gui.close() val (player, client) = registerPlayer() val initialInventoryViewType = player.openInventory.type - shouldThrow { gui.open(client) } - player.assertInventoryView(initialInventoryViewType) + gui.open(client) shouldBe true + player.assertInventoryView(type) } @Test @@ -238,6 +238,80 @@ abstract class AbstractGUITest : AbstractKoinTest() { } + abstract inner class Update { + + @Test + fun `should return false if the client is not viewing the GUI`() = runTest { + val gui = createNonFillGUI() + val (player, client) = registerPlayer() + val initialInventoryViewType = player.openInventory.type + gui.update(client) shouldBe false + + gui.viewers().toList() shouldBe emptyList() + gui.contains(client) shouldBe false + + player.assertInventoryView(initialInventoryViewType) + } + + @Test + fun `should return false if the client is viewing the GUI with a loading inventory`() { + runBlocking { + val type = InventoryType.DISPENSER + val delay = 100.milliseconds + val gui = createFillGUI(emptyArray(), inventoryType = type, delay = delay) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + + val guiInventory = player.openInventory.topInventory + gui.isInventoryLoading(guiInventory) shouldBe true + + // We're waiting the half of the delay to be sure that the inventory is loading + delay(50.milliseconds) + + gui.update(client) shouldBe false + player.assertInventoryView(type) + gui.viewers().toList() shouldContainExactlyInAnyOrder listOf(player) + gui.contains(client) shouldBe true + + // if we interrupt the loading, the inventory should be loading from 0 to new delay + // but here, we didn't interrupt the loading, so the inventory should be loaded (50 + 80 = 130 > 100) + delay(80.milliseconds) + + gui.isInventoryLoading(guiInventory) shouldBe false + } + } + + @Test + fun `should return true if the client is viewing the GUI with a loaded inventory`() { + runBlocking { + val type = InventoryType.DISPENSER + val delay = 100.milliseconds + val gui = createFillGUI(emptyArray(), inventoryType = type, delay = delay) + val (player, client) = registerPlayer() + + gui.open(client) shouldBe true + val guiInventory = player.openInventory.topInventory + gui.isInventoryLoading(guiInventory) shouldBe true + + // We're waiting the half of the delay to be sure that the inventory is loading + delay(70.milliseconds) + + gui.update(client, true) shouldBe true + player.assertInventoryView(type) + gui.viewers().toList() shouldContainExactlyInAnyOrder listOf(player) + gui.contains(client) shouldBe true + + // if we interrupt the loading, the inventory should be loading from 0 to new delay + delay(70.milliseconds) + gui.isInventoryLoading(guiInventory) shouldBe true + + delay(50.milliseconds) + gui.isInventoryLoading(guiInventory) shouldBe false + } + } + } + abstract inner class Close { @Test @@ -263,14 +337,6 @@ abstract class AbstractGUITest : AbstractKoinTest() { } } - @Test - fun `should set isClosed to true`() = runTest { - val gui = createNonFillGUI() - gui.isClosed shouldBe false - gui.close() - gui.isClosed shouldBe true - } - @Test fun `should unregister the GUI`() = runTest { val gui = createNonFillGUI() @@ -279,27 +345,6 @@ abstract class AbstractGUITest : AbstractKoinTest() { gui.close() guiManager.guis shouldContainAll listOf() } - - @Test - fun `should not be able to open the GUI after closing it`() = runTest { - val gui = createNonFillGUI() - gui.register() - val (_, client) = registerPlayer() - gui.close() - - shouldThrow { - gui.open(client) - } - } - - @Test - fun `should not be able to register the GUI after closing it`() = runTest { - val gui = createNonFillGUI() - gui.close() - shouldThrow { - gui.register() - } - } } abstract inner class CloseForClient { diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt index 3e0fdce6..b6e6c731 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt @@ -131,6 +131,9 @@ class LocalePlayerGUITest : AbstractGUITest() { } + @Nested + inner class Update : AbstractGUITest.Update() + @Nested inner class Close : AbstractGUITest.Close() diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt index 6f5877d4..071ecdd8 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt @@ -70,6 +70,9 @@ class PlayerGUITest : AbstractGUITest() { } } + @Nested + inner class Update : AbstractGUITest.Update() + @Nested inner class Close : AbstractGUITest.Close() diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt index 0cd3c26f..fe87fb90 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -97,6 +97,9 @@ class SingleGUITest : AbstractGUITest() { } } + @Nested + inner class Update : AbstractGUITest.Update() + @Nested inner class Close : AbstractGUITest.Close() From 10598830bc8e75c26de488386ef9f295eb1ae329 Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 16:15:33 +0100 Subject: [PATCH 26/48] chore: Move clear inventory out of Job --- src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 78fbc024..7b88d78a 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -211,14 +211,14 @@ public abstract class GUI( * @return The job that can be cancelled to stop the loading animation. */ private suspend fun startLoadingInventory(key: T, inventory: Inventory): Job { + val size = inventory.size + // Empty the inventory, there is no effect if the inventory is new + // But avoid conflicts with old items if the inventory is updated. + inventory.contents = arrayOfNulls(size) + // If no suspend operation is used in the flow, the fill will be done in the same thread & tick. // That's why we start with unconfined dispatcher. return fillScope(key).launch(Dispatchers.Unconfined) { - val size = inventory.size - // Empty the inventory, there is no effect if the inventory is new - // But avoid conflicts with old items if the inventory is updated. - inventory.contents = arrayOfNulls(size) - val inventoryFlowItems = getItems(key, size).cancellable() if (loadingAnimation == null) { From 9921afd5d1eced1e6ef0187460ed0a8533466a58 Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 16:18:00 +0100 Subject: [PATCH 27/48] doc: Add missing property documentation --- src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 7b88d78a..b12b832b 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -57,6 +57,7 @@ public class GUIClosedException(message: String) : GUIException(message) /** * Exception thrown when the GUI is updating. + * @property client Client for which the GUI is updating. */ public class GUIUpdatedException(public val client: Client) : GUIException("GUI updating for client ${client.playerUUID}") From 72cf8a37342584c67a29105ba4af993aaa1e6749 Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 17:51:16 +0100 Subject: [PATCH 28/48] fix: Use UNIT as singleton value --- .../com/github/rushyverse/api/gui/SingleGUI.kt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt index 3ec24c71..af370b83 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt @@ -20,8 +20,8 @@ import org.bukkit.plugin.Plugin */ public abstract class SingleGUI( protected val plugin: Plugin, - loadingAnimation: InventoryLoadingAnimation? = null -) : GUI( + loadingAnimation: InventoryLoadingAnimation? = null +) : GUI( loadingAnimation = loadingAnimation, initialNumberInventories = 1 ) { @@ -32,19 +32,19 @@ public abstract class SingleGUI( * This GUI is shared by all the players, so the key is the same for all of them. * That allows creating a unique inventory. */ - private val KEY = Any() + private val KEY = Unit } - override suspend fun getKey(client: Client): Any { + override suspend fun getKey(client: Client) { return KEY } - override suspend fun fillScope(key: Any): CoroutineScope { + override suspend fun fillScope(key: Unit): CoroutineScope { val scope = plugin.scope return scope + SupervisorJob(scope.coroutineContext.job) } - override fun createInventory(key: Any): Inventory { + override fun createInventory(key: Unit): Inventory { return createInventory() } @@ -60,7 +60,7 @@ public abstract class SingleGUI( } else false } - override fun getItems(key: Any, size: Int): Flow { + override fun getItems(key: Unit, size: Int): Flow { return getItems(size) } From 84af5c971d3877a1d46a9a2b26173f45eb4fbbaf Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 17:51:46 +0100 Subject: [PATCH 29/48] fix: Avoid unnecessary operation if shift is 0 --- .../load/ShiftInventoryLoadingAnimation.kt | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt index 14f95f3e..453b3af3 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt @@ -3,6 +3,7 @@ package com.github.rushyverse.api.gui.load import java.util.* import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.isActive @@ -27,16 +28,21 @@ public class ShiftInventoryLoadingAnimation( ) : InventoryLoadingAnimation { override suspend fun loading(key: T, inventory: Inventory) { - coroutineScope { - val size = inventory.size - val contents = arrayOfNulls(size) - // Fill the inventory with the initial items. - // If the sequence is too short, it will be filled with null items. - // If the sequence is too long, the overflowing items will be ignored. - initialize(key).take(size).forEachIndexed { index, item -> - contents[index] = item - } + val size = inventory.size + val contents = arrayOfNulls(size) + // Fill the inventory with the initial items. + // If the sequence is too short, it will be filled with null items. + // If the sequence is too long, the overflowing items will be ignored. + initialize(key).take(size).forEachIndexed { index, item -> + contents[index] = item + } + if(shift == 0) { + inventory.contents = contents + awaitCancellation() + } + + coroutineScope { val contentList = contents.toMutableList() while (isActive) { inventory.contents = contentList.toTypedArray() From 134ccf66778efeb7b9f55d7d120f860211d21920 Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 17:52:09 +0100 Subject: [PATCH 30/48] test: Begin test about shift inventory animation --- .../ShiftInventoryLoadingAnimationTest.kt | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt new file mode 100644 index 00000000..7554e431 --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt @@ -0,0 +1,71 @@ +package com.github.rushyverse.api.gui.load + +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.shouldBe +import io.mockk.every +import io.mockk.mockk +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack + +class ShiftInventoryLoadingAnimationTest { + + private lateinit var inventory: Inventory + + @BeforeTest + fun onBefore() { + inventory = mockk { + val contents = arrayOfNulls(9 * 3) + every { size } returns contents.size + every { getContents() } returns contents + every { setContents(any()) } answers { + val items = firstArg>() + items.forEachIndexed { index, itemStack -> + contents[index] = itemStack + } + } + } + } + + @Test + fun `should not change inventory if initialize is empty`() { + val delay = 10.milliseconds + val animation = ShiftInventoryLoadingAnimation( + initialize = { emptySequence() }, + shift = 1, + delay = delay + ) + + runBlocking { + val job = launch { animation.loading(Unit, inventory) } + delay(delay * 3) + job.cancelAndJoin() + } + + inventory.contents shouldBe arrayOfNulls(inventory.size) + } + + @Test + fun `should just initialize if shift is zero`() = runBlocking { + val delay = 10.milliseconds + val items = Array(inventory.size) { mockk() } + + val animation = ShiftInventoryLoadingAnimation( + initialize = { items.asSequence() }, + shift = 0, + delay = delay + ) + + val job = launch { animation.loading(Unit, inventory) } + delay(delay * 3) + job.cancelAndJoin() + + inventory.contents.toList() shouldContainExactly items.toList() + } +} From 817348967aaad163216c02f399f85eb8c26a170f Mon Sep 17 00:00:00 2001 From: Distractic Date: Tue, 19 Dec 2023 22:08:42 +0100 Subject: [PATCH 31/48] chore: Optimize and create new function for Client --- .../com/github/rushyverse/api/gui/GUI.kt | 135 +++++++++++------- .../github/rushyverse/api/gui/GUIListener.kt | 2 +- .../github/rushyverse/api/gui/LocaleGUI.kt | 2 +- .../github/rushyverse/api/gui/PlayerGUI.kt | 2 +- .../github/rushyverse/api/gui/SingleGUI.kt | 2 +- .../rushyverse/api/gui/AbstractGUITest.kt | 46 +++--- .../rushyverse/api/gui/GUIListenerTest.kt | 8 +- .../rushyverse/api/gui/LocalePlayerGUITest.kt | 24 ++-- .../rushyverse/api/gui/PlayerGUITest.kt | 24 ++-- .../rushyverse/api/gui/SingleGUITest.kt | 18 +-- 10 files changed, 150 insertions(+), 113 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index b12b832b..3d629acf 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -9,8 +9,12 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.cancellable +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onCompletion +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.toCollection import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -48,19 +52,18 @@ private val logger = KotlinLogging.logger {} /** * Exception concerning the GUI. */ -public open class GUIException(message: String) : CancellationException(message) +public open class GUIException(message: String? = null) : CancellationException(message) /** * Exception thrown when the GUI is closed. */ -public class GUIClosedException(message: String) : GUIException(message) +public class GUIClosedException(message: String? = null) : GUIException(message) /** * Exception thrown when the GUI is updating. * @property client Client for which the GUI is updating. */ -public class GUIUpdatedException(public val client: Client) : - GUIException("GUI updating for client ${client.playerUUID}") +public class GUIUpdatedException(public val client: Client?) : GUIException() /** * Exception thrown when the GUI is closed for a specific client. @@ -109,9 +112,9 @@ public abstract class GUI( * @param client Client to open the GUI for. * @return True if the GUI was opened, false otherwise. */ - public open suspend fun open(client: Client): Boolean { + public open suspend fun openClient(client: Client): Boolean { val player = client.player - if (player === null) { + if (player == null) { logger.warn { "Cannot open inventory for player ${client.playerUUID}: player is null" } return false } @@ -133,7 +136,7 @@ public abstract class GUI( // If the opening was cancelled (null returned), // We need to unregister the client from the GUI // and maybe close the inventory if it is individual. - close(client, false) + closeClient(client, false) return false } @@ -142,6 +145,7 @@ public abstract class GUI( /** * Update the opened inventory for the client. + * If the opened inventory is shared with other players, the inventory will be updated for all the viewers. * * If the client has the GUI opened, the inventory will be updated. * If the client has another GUI opened, do nothing. @@ -152,35 +156,69 @@ public abstract class GUI( * to start a new loading animation. * @return True if the inventory was updated, false otherwise. * @see [getItems] + * @see [update] */ - public open suspend fun update(client: Client, interruptLoading: Boolean = false): Boolean { + public open suspend fun updateClient(client: Client, interruptLoading: Boolean = false): Boolean { val key = getKey(client) - return mutex.withLock { - val inventoryData = inventories[key] ?: return@withLock false - - // If the client doesn't have the GUI opened, do nothing. - if (!unsafeContains(client)) return@withLock false - - if (inventoryData.isLoading) { - // If we don't want to interrupt the loading and the inventory is loading, do nothing. - if (!interruptLoading) return@withLock false - else { - // If we want to interrupt the loading, we cancel the loading job. - // We need to wait for the job to be cancelled to avoid conflicts with the new loading animation. - inventoryData.job.apply { - cancel(GUIUpdatedException(client)) - join() - } + if (!unsafeContains(client)) return false + unsafeUpdate(key, interruptLoading, client) + } + } + + /** + * Update the inventory for the key. + * If the inventory is shared with several players, the inventory will be updated for all the viewers. + * + * If the inventory is not loaded, the inventory will be updated. + * If the inventory is loading, the inventory will be updated if [interruptLoading] is true. + * + * Call [getItems] to get the new items to fill the inventory. + * @param key Key to update the inventory for. + * @param interruptLoading If true and if the inventory is loading, the loading will be interrupted + * to start a new loading animation. + * @return True if the inventory was updated, false otherwise. + */ + public suspend fun update(key: T, interruptLoading: Boolean = false): Boolean { + return mutex.withLock { unsafeUpdate(key, interruptLoading, null) } + } + + /** + * This function is not thread-safe. + * + * Update the inventory for the key. + * If the inventory is shared with several players, the inventory will be updated for all the viewers. + * + * If the inventory is not loaded, the inventory will be updated. + * If the inventory is loading, the inventory will be updated if [interruptLoading] is true. + * + * Call [getItems] to get the new items to fill the inventory. + * @param key Key to update the inventory for. + * @param interruptLoading If true and if the inventory is loading, the loading will be interrupted + * to start a new loading animation. + * @return True if the inventory was updated, false otherwise. + */ + private suspend fun unsafeUpdate(key: T, interruptLoading: Boolean = false, cause: Client? = null): Boolean { + val inventoryData = inventories[key] ?: return false + + if (inventoryData.isLoading) { + // If we don't want to interrupt the loading and the inventory is loading, do nothing. + if (!interruptLoading) return false + else { + // If we want to interrupt the loading, we cancel the loading job. + // We need to wait for the job to be cancelled to avoid conflicts with the new loading animation. + inventoryData.job.apply { + cancel(GUIUpdatedException(cause)) + join() } } - - val inventory = inventoryData.inventory - // Begin a new loading job and replace the old one. - val newLoadingJob = startLoadingInventory(key, inventory) - inventories[key] = InventoryData(inventory, newLoadingJob) - true } + + val inventory = inventoryData.inventory + // Begin a new loading job and replace the old one. + val newLoadingJob = startLoadingInventory(key, inventory) + inventories[key] = InventoryData(inventory, newLoadingJob) + return true } /** @@ -277,7 +315,7 @@ public abstract class GUI( */ public open suspend fun hasInventory(inventory: Inventory): Boolean { return mutex.withLock { - inventories.values.any { it.inventory == inventory } + inventories.values.any { it.inventory === inventory } } } @@ -289,7 +327,7 @@ public abstract class GUI( */ public open suspend fun isInventoryLoading(inventory: Inventory): Boolean { return mutex.withLock { - inventories.values.firstOrNull { it.inventory == inventory }?.isLoading == true + inventories.values.firstOrNull { it.inventory === inventory }?.isLoading == true } } @@ -298,9 +336,7 @@ public abstract class GUI( * @return List of viewers. */ public open suspend fun viewers(): Sequence { - return mutex.withLock { - unsafeViewers() - } + return mutex.withLock { unsafeViewers() } } /** @@ -318,9 +354,7 @@ public abstract class GUI( * @return True if the GUI contains the player, false otherwise. */ public open suspend fun contains(client: Client): Boolean { - return mutex.withLock { - unsafeContains(client) - } + return mutex.withLock { unsafeContains(client) } } /** @@ -331,7 +365,7 @@ public abstract class GUI( */ protected open fun unsafeContains(client: Client): Boolean { val player = client.player ?: return false - return unsafeViewers().any { it == player } + return unsafeViewers().any { it === player } } /** @@ -343,15 +377,18 @@ public abstract class GUI( unregister() mutex.withLock { - inventories.values.forEach { - it.job.apply { - cancel(GUIClosedException("The GUI is closing")) - join() + inventories.values.asFlow() + .onCompletion { inventories.clear() } + .onEach { + val job = it.job + job.cancel(GUIClosedException()) + job.join() } - it.inventory.close() - } - inventories.clear() - } + .map { it.inventory } + .toCollection(ArrayList(inventories.size)) + // Close the inventories out of the mutex + // to avoid slowing down the mutex with the events sent to the listeners. + }.forEach(Inventory::close) } /** @@ -360,7 +397,7 @@ public abstract class GUI( * @param closeInventory If true, the interface will be closed, otherwise it will be kept open. * @return True if the inventory was closed, false otherwise. */ - public abstract suspend fun close(client: Client, closeInventory: Boolean = true): Boolean + public abstract suspend fun closeClient(client: Client, closeInventory: Boolean = true): Boolean /** * Register the GUI to the listener. @@ -374,7 +411,7 @@ public abstract class GUI( /** * Unregister the GUI from the listener. - * Should be called when the GUI is closed with [close]. + * Should be called when the GUI is closed with [closeClient]. * @return True if the GUI was unregistered, false otherwise. */ protected open suspend fun unregister(): Boolean { diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt index 8053552f..276c56d0 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt @@ -121,7 +121,7 @@ public class GUIListener(private val plugin: Plugin) : Listener { val gui = client?.gui() ?: return // We don't close the inventory because it is closing due to event. // That avoids an infinite loop of events and consequently a stack overflow. - gui.close(client, false) + gui.closeClient(client, false) } } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt index 4eaf1977..5e3d3f07 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/LocaleGUI.kt @@ -37,7 +37,7 @@ public abstract class LocaleGUI( return scope + SupervisorJob(scope.coroutineContext.job) } - override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + override suspend fun closeClient(client: Client, closeInventory: Boolean): Boolean { return if (closeInventory && contains(client)) { client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) true diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt index d5a096fc..24099333 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt @@ -51,7 +51,7 @@ public abstract class PlayerGUI( return inventories.containsKey(client) } - override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + override suspend fun closeClient(client: Client, closeInventory: Boolean): Boolean { val (inventory, job) = mutex.withLock { inventories.remove(client) } ?: return false job.cancel(GUIClosedForClientException(client)) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt index af370b83..1f45e38f 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt @@ -53,7 +53,7 @@ public abstract class SingleGUI( */ protected abstract fun createInventory(): Inventory - override suspend fun close(client: Client, closeInventory: Boolean): Boolean { + override suspend fun closeClient(client: Client, closeInventory: Boolean): Boolean { return if (closeInventory && contains(client)) { client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) true diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt index 4cf452b3..9020840e 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt @@ -91,7 +91,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { val playerClients = List(5) { registerPlayer() } playerClients.forEach { (_, client) -> - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true } gui.viewers().toList() shouldContainExactlyInAnyOrder playerClients.map { it.first } @@ -112,13 +112,13 @@ abstract class AbstractGUITest : AbstractKoinTest() { fun `should return true if the client is viewing the GUI`() = runTest { val gui = createNonFillGUI() val (_, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true gui.contains(client) shouldBe true } } - abstract inner class Open { + abstract inner class OpenClient { @Test fun `should open if GUI was closed`() = runTest { @@ -128,7 +128,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { val (player, client) = registerPlayer() val initialInventoryViewType = player.openInventory.type - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) } @@ -139,10 +139,10 @@ abstract class AbstractGUITest : AbstractKoinTest() { gui.register() val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) - gui.open(client) shouldBe false + gui.openClient(client) shouldBe false player.assertInventoryView(type) } @@ -154,7 +154,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { val initialInventoryViewType = player.openInventory.type player.health = 0.0 - gui.open(client) shouldBe false + gui.openClient(client) shouldBe false player.assertInventoryView(initialInventoryViewType) } @@ -174,7 +174,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { gui.register() val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) val inventory = player.openInventory.topInventory @@ -211,7 +211,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { gui.register() val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) val inventory = player.openInventory.topInventory @@ -238,14 +238,14 @@ abstract class AbstractGUITest : AbstractKoinTest() { } - abstract inner class Update { + abstract inner class UpdateClient { @Test fun `should return false if the client is not viewing the GUI`() = runTest { val gui = createNonFillGUI() val (player, client) = registerPlayer() val initialInventoryViewType = player.openInventory.type - gui.update(client) shouldBe false + gui.updateClient(client) shouldBe false gui.viewers().toList() shouldBe emptyList() gui.contains(client) shouldBe false @@ -261,7 +261,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { val gui = createFillGUI(emptyArray(), inventoryType = type, delay = delay) val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true val guiInventory = player.openInventory.topInventory gui.isInventoryLoading(guiInventory) shouldBe true @@ -269,7 +269,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { // We're waiting the half of the delay to be sure that the inventory is loading delay(50.milliseconds) - gui.update(client) shouldBe false + gui.updateClient(client) shouldBe false player.assertInventoryView(type) gui.viewers().toList() shouldContainExactlyInAnyOrder listOf(player) gui.contains(client) shouldBe true @@ -290,14 +290,14 @@ abstract class AbstractGUITest : AbstractKoinTest() { val gui = createFillGUI(emptyArray(), inventoryType = type, delay = delay) val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true val guiInventory = player.openInventory.topInventory gui.isInventoryLoading(guiInventory) shouldBe true // We're waiting the half of the delay to be sure that the inventory is loading delay(70.milliseconds) - gui.update(client, true) shouldBe true + gui.updateClient(client, true) shouldBe true player.assertInventoryView(type) gui.viewers().toList() shouldContainExactlyInAnyOrder listOf(player) gui.contains(client) shouldBe true @@ -325,7 +325,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { playerClients.forEach { (player, client) -> player.assertInventoryView(initialInventoryViewType) - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) client.gui() shouldBe gui } @@ -347,7 +347,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { } } - abstract inner class CloseForClient { + abstract inner class CloseClient { @Test fun `should return false if the client is not viewing the GUI`() = runTest { @@ -357,7 +357,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { val initialInventoryViewType = player.openInventory.type player.assertInventoryView(initialInventoryViewType) - gui.close(client, true) shouldBe false + gui.closeClient(client, true) shouldBe false player.assertInventoryView(initialInventoryViewType) } @@ -369,9 +369,9 @@ abstract class AbstractGUITest : AbstractKoinTest() { val initialInventoryViewType = player.openInventory.type - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) - gui.close(client, true) shouldBe true + gui.closeClient(client, true) shouldBe true player.assertInventoryView(initialInventoryViewType) } @@ -383,13 +383,13 @@ abstract class AbstractGUITest : AbstractKoinTest() { val (player2, client2) = registerPlayer() val initialInventoryViewType = player2.openInventory.type - gui.open(client) shouldBe true - gui.open(client2) shouldBe true + gui.openClient(client) shouldBe true + gui.openClient(client2) shouldBe true player.assertInventoryView(type) player2.assertInventoryView(type) - gui.close(client2, true) shouldBe true + gui.closeClient(client2, true) shouldBe true player.assertInventoryView(type) player2.assertInventoryView(initialInventoryViewType) } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 6d9f6e27..2a86c9ed 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -192,7 +192,7 @@ class GUIListenerTest : AbstractKoinTest() { } callEvent(player) - coVerify(exactly = 0) { gui.close(client, any()) } + coVerify(exactly = 0) { gui.closeClient(client, any()) } } @Test @@ -200,7 +200,7 @@ class GUIListenerTest : AbstractKoinTest() { val (player, client) = registerPlayer() val gui = registerGUI { coEvery { contains(client) } returns true - coEvery { close(client, any()) } returns true + coEvery { closeClient(client, any()) } returns true } val gui2 = registerGUI { @@ -209,8 +209,8 @@ class GUIListenerTest : AbstractKoinTest() { callEvent(player) - coVerify(exactly = 1) { gui.close(client, false) } - coVerify(exactly = 0) { gui2.close(client, any()) } + coVerify(exactly = 1) { gui.closeClient(client, false) } + coVerify(exactly = 0) { gui2.closeClient(client, any()) } } private suspend fun callEvent(player: Player) { diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt index b6e6c731..53294335 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt @@ -74,7 +74,7 @@ class LocalePlayerGUITest : AbstractGUITest() { inner class Contains : AbstractGUITest.Contains() @Nested - inner class Open : AbstractGUITest.Open() { + inner class OpenClient : AbstractGUITest.OpenClient() { @Test fun `should create a new inventory according to the language client`() = runTest { @@ -85,8 +85,8 @@ class LocalePlayerGUITest : AbstractGUITest() { languageManager.set(player, SupportedLanguage.ENGLISH) languageManager.set(player2, SupportedLanguage.FRENCH) - gui.open(client) shouldBe true - gui.open(client2) shouldBe true + gui.openClient(client) shouldBe true + gui.openClient(client2) shouldBe true player.assertInventoryView(type) player2.assertInventoryView(type) @@ -103,8 +103,8 @@ class LocalePlayerGUITest : AbstractGUITest() { languageManager.set(player, SupportedLanguage.FRENCH) languageManager.set(player2, SupportedLanguage.FRENCH) - gui.open(client) shouldBe true - gui.open(client2) shouldBe true + gui.openClient(client) shouldBe true + gui.openClient(client2) shouldBe true player.assertInventoryView(type) player2.assertInventoryView(type) @@ -118,12 +118,12 @@ class LocalePlayerGUITest : AbstractGUITest() { val gui = createNonFillGUI(type) val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true val firstInventory = player.openInventory.topInventory - gui.close(client, true) shouldBe true + gui.closeClient(client, true) shouldBe true - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.openInventory.topInventory shouldBe firstInventory player.assertInventoryView(type) @@ -132,13 +132,13 @@ class LocalePlayerGUITest : AbstractGUITest() { } @Nested - inner class Update : AbstractGUITest.Update() + inner class UpdateClient : AbstractGUITest.UpdateClient() @Nested inner class Close : AbstractGUITest.Close() @Nested - inner class CloseForClient : AbstractGUITest.CloseForClient() { + inner class CloseClient : AbstractGUITest.CloseClient() { @ParameterizedTest @ValueSource(booleans = [true, false]) @@ -151,14 +151,14 @@ class LocalePlayerGUITest : AbstractGUITest() { val initialInventoryViewType = player.openInventory.type - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) val openInventory = player.openInventory val inventory = openInventory.topInventory gui.isInventoryLoading(inventory) shouldBe true - gui.close(client, closeInventory) shouldBe closeInventory + gui.closeClient(client, closeInventory) shouldBe closeInventory gui.isInventoryLoading(inventory) shouldBe true if (closeInventory) { diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt index 071ecdd8..358a8c79 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt @@ -34,7 +34,7 @@ class PlayerGUITest : AbstractGUITest() { inner class Contains : AbstractGUITest.Contains() @Nested - inner class Open : AbstractGUITest.Open() { + inner class OpenClient : AbstractGUITest.OpenClient() { @Test fun `should create a new inventory for the client`() = runTest { @@ -43,8 +43,8 @@ class PlayerGUITest : AbstractGUITest() { val (player, client) = registerPlayer() val (player2, client2) = registerPlayer() - gui.open(client) shouldBe true - gui.open(client2) shouldBe true + gui.openClient(client) shouldBe true + gui.openClient(client2) shouldBe true player.assertInventoryView(type) player2.assertInventoryView(type) @@ -58,12 +58,12 @@ class PlayerGUITest : AbstractGUITest() { val gui = createNonFillGUI(type) val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true val firstInventory = player.openInventory.topInventory - gui.close(client, true) shouldBe true + gui.closeClient(client, true) shouldBe true - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.openInventory.topInventory shouldNotBe firstInventory player.assertInventoryView(type) @@ -71,13 +71,13 @@ class PlayerGUITest : AbstractGUITest() { } @Nested - inner class Update : AbstractGUITest.Update() + inner class UpdateClient : AbstractGUITest.UpdateClient() @Nested inner class Close : AbstractGUITest.Close() @Nested - inner class CloseForClient : AbstractGUITest.CloseForClient() { + inner class CloseClient : AbstractGUITest.CloseClient() { @ParameterizedTest @ValueSource(booleans = [true, false]) @@ -90,14 +90,14 @@ class PlayerGUITest : AbstractGUITest() { val initialInventoryViewType = player.openInventory.type - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) val openInventory = player.openInventory val inventory = openInventory.topInventory gui.isInventoryLoading(inventory) shouldBe true - gui.close(client, closeInventory) shouldBe true + gui.closeClient(client, closeInventory) shouldBe true gui.isInventoryLoading(inventory) shouldBe false if (closeInventory) { @@ -115,10 +115,10 @@ class PlayerGUITest : AbstractGUITest() { val gui = NonFillGUI(serverMock, type = type) val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) - gui.close(client, false) shouldBe true + gui.closeClient(client, false) shouldBe true player.assertInventoryView(type) gui.contains(client) shouldBe false diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt index fe87fb90..7e27fc3b 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -62,7 +62,7 @@ class SingleGUITest : AbstractGUITest() { inner class Contains : AbstractGUITest.Contains() @Nested - inner class Open : AbstractGUITest.Open() { + inner class OpenClient : AbstractGUITest.OpenClient() { @Test fun `should use the same inventory for all clients`() = runTest { @@ -70,7 +70,7 @@ class SingleGUITest : AbstractGUITest() { val gui = createNonFillGUI(type) val inventories = List(5) { val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) player.openInventory.topInventory @@ -85,12 +85,12 @@ class SingleGUITest : AbstractGUITest() { val gui = createNonFillGUI(type) val (player, client) = registerPlayer() - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true val firstInventory = player.openInventory.topInventory - gui.close(client, true) shouldBe true + gui.closeClient(client, true) shouldBe true - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.openInventory.topInventory shouldBe firstInventory player.assertInventoryView(type) @@ -98,13 +98,13 @@ class SingleGUITest : AbstractGUITest() { } @Nested - inner class Update : AbstractGUITest.Update() + inner class UpdateClient : AbstractGUITest.UpdateClient() @Nested inner class Close : AbstractGUITest.Close() @Nested - inner class CloseForClient : AbstractGUITest.CloseForClient() { + inner class CloseClient : AbstractGUITest.CloseClient() { @ParameterizedTest @ValueSource(booleans = [true, false]) @@ -117,14 +117,14 @@ class SingleGUITest : AbstractGUITest() { val initialInventoryViewType = player.openInventory.type - gui.open(client) shouldBe true + gui.openClient(client) shouldBe true player.assertInventoryView(type) val openInventory = player.openInventory val inventory = openInventory.topInventory gui.isInventoryLoading(inventory) shouldBe true - gui.close(client, closeInventory) shouldBe closeInventory + gui.closeClient(client, closeInventory) shouldBe closeInventory gui.isInventoryLoading(inventory) shouldBe true if (closeInventory) { From b88592323e00e0075c0d4077c35d50a49db8dc3a Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 00:12:07 +0100 Subject: [PATCH 32/48] test: Add tests about inventory management --- .../com/github/rushyverse/api/gui/GUI.kt | 2 +- .../github/rushyverse/api/gui/PlayerGUI.kt | 4 + .../rushyverse/api/gui/AbstractGUITest.kt | 96 ++++++++++++++++++- .../rushyverse/api/gui/LocalePlayerGUITest.kt | 6 ++ .../rushyverse/api/gui/PlayerGUITest.kt | 6 ++ .../rushyverse/api/gui/SingleGUITest.kt | 6 ++ 6 files changed, 117 insertions(+), 3 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 3d629acf..6a389807 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -179,7 +179,7 @@ public abstract class GUI( * to start a new loading animation. * @return True if the inventory was updated, false otherwise. */ - public suspend fun update(key: T, interruptLoading: Boolean = false): Boolean { + public open suspend fun update(key: T, interruptLoading: Boolean = false): Boolean { return mutex.withLock { unsafeUpdate(key, interruptLoading, null) } } diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt index 24099333..116a43db 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt @@ -26,6 +26,10 @@ public abstract class PlayerGUI( return key + SupervisorJob(key.coroutineContext.job) } + override suspend fun update(key: Client, interruptLoading: Boolean): Boolean { + return super.updateClient(key, interruptLoading) + } + /** * Create the inventory for the client. * Will translate the title and fill the inventory. diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt index 9020840e..66655ded 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt @@ -1,6 +1,7 @@ package com.github.rushyverse.api.gui import be.seeseemelk.mockbukkit.MockBukkit +import be.seeseemelk.mockbukkit.MockPlugin import be.seeseemelk.mockbukkit.ServerMock import be.seeseemelk.mockbukkit.entity.PlayerMock import com.github.rushyverse.api.AbstractKoinTest @@ -12,6 +13,11 @@ import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe +import io.mockk.every +import io.mockk.mockk +import io.mockk.spyk +import java.net.InetSocketAddress +import java.util.* import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.AfterTest import kotlin.test.BeforeTest @@ -24,6 +30,7 @@ import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest import org.bukkit.Material import org.bukkit.event.inventory.InventoryType +import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack abstract class AbstractGUITest : AbstractKoinTest() { @@ -31,6 +38,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { protected lateinit var guiManager: GUIManager protected lateinit var clientManager: ClientManager protected lateinit var serverMock: ServerMock + protected lateinit var pluginMock: MockPlugin @BeforeTest override fun onBefore() { @@ -44,6 +52,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { } serverMock = MockBukkit.mock() + pluginMock = MockBukkit.createMockPlugin() } @AfterTest @@ -158,6 +167,24 @@ abstract class AbstractGUITest : AbstractKoinTest() { player.assertInventoryView(initialInventoryViewType) } + @Test + fun `should do nothing if the player open inventory is cancelled`() = runTest { + val gui = createNonFillGUI() + + val basePlayer = serverMock.addPlayer() + val uuid = UUID.randomUUID() + val player = spyk(basePlayer) { + every { uniqueId } returns uuid + every { address } returns InetSocketAddress(0) + every { openInventory(any()) } returns null + } + val (_, client) = registerPlayer(player) + + gui.openClient(client) shouldBe false + gui.contains(client) shouldBe false + gui.viewers().toList() shouldBe emptyList() + } + @Test fun `should fill the inventory in the same thread if no suspend operation`() { @@ -236,6 +263,11 @@ abstract class AbstractGUITest : AbstractKoinTest() { } } + @Test + fun `should use loading animation`() { + TODO() + } + } abstract inner class UpdateClient { @@ -312,6 +344,66 @@ abstract class AbstractGUITest : AbstractKoinTest() { } } + abstract inner class HasInventory { + + @Test + fun `should return false if the inventory doesn't come from GUI`() = runTest { + val gui = createNonFillGUI() + val (_, client) = registerPlayer() + gui.openClient(client) shouldBe true + gui.hasInventory(mockk()) shouldBe false + } + + @Test + fun `should return true if the client is viewing the GUI`() = runTest { + val gui = createNonFillGUI() + val (player, client) = registerPlayer() + gui.openClient(client) shouldBe true + + val inventory = player.openInventory.topInventory + gui.hasInventory(inventory) shouldBe true + } + + } + + abstract inner class IsInventoryLoading { + + @Test + fun `should return false if the inventory doesn't come from GUI`() = runTest { + val gui = createNonFillGUI() + val (_, client) = registerPlayer() + gui.openClient(client) shouldBe true + gui.isInventoryLoading(mockk()) shouldBe false + } + + @Test + fun `should return false if the inventory is not loading`() = runTest { + val gui = createNonFillGUI() + val (player, client) = registerPlayer() + gui.openClient(client) shouldBe true + + val inventory = player.openInventory.topInventory + gui.isInventoryLoading(inventory) shouldBe false + } + + @Test + fun `should return true if the inventory is loading`() { + runBlocking { + val delay = 50.milliseconds + val gui = createFillGUI(emptyArray(), delay = delay) + val (player, client) = registerPlayer() + gui.openClient(client) shouldBe true + + val inventory = player.openInventory.topInventory + gui.isInventoryLoading(inventory) shouldBe true + + delay(delay * 2) + + gui.isInventoryLoading(inventory) shouldBe false + } + } + } + abstract inner class Close { @Test @@ -409,8 +501,8 @@ abstract class AbstractGUITest : AbstractKoinTest() { abstract fun getFillThreadAfterSuspend(gui: GUI<*>): Thread? - protected suspend fun registerPlayer(): Pair { - val player = serverMock.addPlayer() + protected suspend fun registerPlayer(playerMock: PlayerMock? = null): Pair { + val player = playerMock?.also { serverMock.addPlayer(it) } ?: serverMock.addPlayer() val client = Client(player.uniqueId, CoroutineScope(EmptyCoroutineContext)) clientManager.put(player, client) return player to client diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt index 53294335..448ba205 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt @@ -134,6 +134,12 @@ class LocalePlayerGUITest : AbstractGUITest() { @Nested inner class UpdateClient : AbstractGUITest.UpdateClient() + @Nested + inner class HasInventory : AbstractGUITest.HasInventory() + + @Nested + inner class IsInventoryLoading : AbstractGUITest.IsInventoryLoading() + @Nested inner class Close : AbstractGUITest.Close() diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt index 358a8c79..629a1e46 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt @@ -73,6 +73,12 @@ class PlayerGUITest : AbstractGUITest() { @Nested inner class UpdateClient : AbstractGUITest.UpdateClient() + @Nested + inner class HasInventory : AbstractGUITest.HasInventory() + + @Nested + inner class IsInventoryLoading : AbstractGUITest.IsInventoryLoading() + @Nested inner class Close : AbstractGUITest.Close() diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt index 7e27fc3b..610ad7ad 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -100,6 +100,12 @@ class SingleGUITest : AbstractGUITest() { @Nested inner class UpdateClient : AbstractGUITest.UpdateClient() + @Nested + inner class HasInventory : AbstractGUITest.HasInventory() + + @Nested + inner class IsInventoryLoading : AbstractGUITest.IsInventoryLoading() + @Nested inner class Close : AbstractGUITest.Close() From 55f8c45aac78925e538802b53cfaf9184a802149 Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 09:56:45 +0100 Subject: [PATCH 33/48] fix: Add dedicated function to simplify management --- .../github/rushyverse/api/gui/PlayerGUI.kt | 15 ++++++++------- .../github/rushyverse/api/gui/SingleGUI.kt | 19 +++++++++++++++++-- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt index 116a43db..c94ca7ae 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt @@ -26,8 +26,14 @@ public abstract class PlayerGUI( return key + SupervisorJob(key.coroutineContext.job) } - override suspend fun update(key: Client, interruptLoading: Boolean): Boolean { - return super.updateClient(key, interruptLoading) + override suspend fun updateClient(client: Client, interruptLoading: Boolean): Boolean { + // Little optimization to avoid checking if the client is contained in map's values. + return super.update(client, interruptLoading) + } + + override fun unsafeContains(client: Client): Boolean { + // Little optimization to avoid checking if the client is contained in map's values. + return inventories.containsKey(client) } /** @@ -50,11 +56,6 @@ public abstract class PlayerGUI( */ protected abstract fun createInventory(owner: InventoryHolder, client: Client): Inventory - override fun unsafeContains(client: Client): Boolean { - // Little optimization to avoid searching in the map from values. - return inventories.containsKey(client) - } - override suspend fun closeClient(client: Client, closeInventory: Boolean): Boolean { val (inventory, job) = mutex.withLock { inventories.remove(client) } ?: return false diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt index 1f45e38f..ba9a2817 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt @@ -32,7 +32,7 @@ public abstract class SingleGUI( * This GUI is shared by all the players, so the key is the same for all of them. * That allows creating a unique inventory. */ - private val KEY = Unit + private val KEY: Unit get() = Unit } override suspend fun getKey(client: Client) { @@ -49,10 +49,25 @@ public abstract class SingleGUI( } /** - * @see createInventory(key) + * Create the inventory. + * @return New created inventory. */ protected abstract fun createInventory(): Inventory + /** + * Update the inventory. + * If the inventory is not loaded, the inventory will be updated. + * If the inventory is loading, the inventory will be updated if [interruptLoading] is true. + * + * Call [getItems] to get the new items to fill the inventory. + * @param interruptLoading If true and if the inventory is loading, the loading will be interrupted + * to start a new loading animation. + * @return True if the inventory was updated, false otherwise. + */ + public suspend fun update(interruptLoading: Boolean = false): Boolean { + return super.update(KEY, interruptLoading) + } + override suspend fun closeClient(client: Client, closeInventory: Boolean): Boolean { return if (closeInventory && contains(client)) { client.player?.closeInventory(InventoryCloseEvent.Reason.PLUGIN) From 5e5305deafa113f244cb45c6f760b3dc403211c1 Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 11:12:00 +0100 Subject: [PATCH 34/48] fix: Keep loading state if animation end --- src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 6a389807..3b4db03a 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow @@ -264,7 +265,12 @@ public abstract class GUI( // Will fill the inventory bit by bit. inventoryFlowItems.collect { (index, item) -> inventory.setItem(index, item) } } else { - val loadingAnimationJob = launch { loadingAnimation.loading(key, inventory) } + val loadingAnimationJob = launch { + loadingAnimation.loading(key, inventory) + // If the loading function is finished, the "loading" state must be continued + // until the flow is finished. + awaitCancellation() + } // To avoid conflicts with the loading animation, // we need to store the items in a temporary inventory From a54555d82bfc5dcb0089493f7e2f1ea0de843d32 Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 11:12:54 +0100 Subject: [PATCH 35/48] fix: Avoid useless shift for animation --- .../api/gui/load/ShiftInventoryLoadingAnimation.kt | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt index 453b3af3..726b67a9 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt @@ -23,10 +23,14 @@ import org.bukkit.inventory.ItemStack */ public class ShiftInventoryLoadingAnimation( private val initialize: (T) -> Sequence, - private val shift: Int = 1, - private val delay: Duration = 100.milliseconds, + public val shift: Int = 1, + public val delay: Duration = 100.milliseconds, ) : InventoryLoadingAnimation { + init { + require(delay > Duration.ZERO) { "Delay must be positive" } + } + override suspend fun loading(key: T, inventory: Inventory) { val size = inventory.size val contents = arrayOfNulls(size) @@ -37,9 +41,9 @@ public class ShiftInventoryLoadingAnimation( contents[index] = item } - if(shift == 0) { + if(shift == 0 || shift == inventory.size) { inventory.contents = contents - awaitCancellation() + return } coroutineScope { From 13589119e992c3ccd62a943689cadec31c2d52cf Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 13:12:11 +0100 Subject: [PATCH 36/48] test: Add tests about fill animation --- .../load/ShiftInventoryLoadingAnimation.kt | 1 - .../rushyverse/api/gui/AbstractGUITest.kt | 95 ++++++++++++++++++- .../rushyverse/api/gui/LocalePlayerGUITest.kt | 27 +++++- .../rushyverse/api/gui/PlayerGUITest.kt | 27 +++++- .../rushyverse/api/gui/SingleGUITest.kt | 27 +++++- .../ShiftInventoryLoadingAnimationTest.kt | 2 +- 6 files changed, 165 insertions(+), 14 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt index 726b67a9..513eda73 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimation.kt @@ -3,7 +3,6 @@ package com.github.rushyverse.api.gui.load import java.util.* import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds -import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.isActive diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt index 66655ded..ce2606c5 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt @@ -6,6 +6,7 @@ import be.seeseemelk.mockbukkit.ServerMock import be.seeseemelk.mockbukkit.entity.PlayerMock import com.github.rushyverse.api.AbstractKoinTest import com.github.rushyverse.api.extension.ItemStack +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl @@ -24,6 +25,7 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking @@ -127,7 +129,7 @@ abstract class AbstractGUITest : AbstractKoinTest() { } - abstract inner class OpenClient { + abstract inner class OpenClient { @Test fun `should open if GUI was closed`() = runTest { @@ -136,7 +138,6 @@ abstract class AbstractGUITest : AbstractKoinTest() { gui.close() val (player, client) = registerPlayer() - val initialInventoryViewType = player.openInventory.type gui.openClient(client) shouldBe true player.assertInventoryView(type) } @@ -265,9 +266,97 @@ abstract class AbstractGUITest : AbstractKoinTest() { @Test fun `should use loading animation`() { - TODO() + val loadingItem = ItemStack { type = Material.BARRIER } + val item1 = ItemStack { type = Material.APPLE } + val item2 = ItemStack { type = Material.BEEF } + + val animation = createAnimation(loadingItem) + + val gui = createDelayGUI( + item1, + item2, + delay = 1.seconds, + inventoryType = InventoryType.CHEST, + loadingAnimation = animation + ) + + runBlocking { + val (player, client) = registerPlayer() + gui.openClient(client) shouldBe true + val guiInventory = player.openInventory.topInventory + + // Animation should be called so the real items should not be in the inventory + val firstContents = guiInventory.contents + firstContents.getOrNull(0) shouldBe loadingItem + firstContents.getOrNull(1) shouldBe null + gui.isInventoryLoading(guiInventory) shouldBe true + + delay(100.milliseconds) + + // Until all items are emitted, the inventory should not be filled + val secondContents = guiInventory.contents + secondContents.getOrNull(0) shouldBe loadingItem + secondContents.getOrNull(1) shouldBe null + gui.isInventoryLoading(guiInventory) shouldBe true + + delay(1.seconds) + + // After all items are emitted, the inventory should be filled + val thirdContents = guiInventory.contents + thirdContents.getOrNull(0) shouldBe item1 + thirdContents.getOrNull(1) shouldBe item2 + gui.isInventoryLoading(guiInventory) shouldBe false + } + } + + @Test + fun `should set bit by bit if no loading animation`() { + val item1 = ItemStack { type = Material.APPLE } + val item2 = ItemStack { type = Material.BEEF } + + val gui = createDelayGUI( + item1, + item2, + delay = 1.seconds, + inventoryType = InventoryType.CHEST, + loadingAnimation = null + ) + + runBlocking { + val (player, client) = registerPlayer() + gui.openClient(client) shouldBe true + delay(100.milliseconds) + val guiInventory = player.openInventory.topInventory + + // Animation should be called so the real items should not be in the inventory + val firstContents = guiInventory.contents + firstContents.getOrNull(0) shouldBe item1 + firstContents.getOrNull(1) shouldBe null + gui.isInventoryLoading(guiInventory) shouldBe true + + delay(1.seconds) + + // After all items are emitted, the inventory should be filled + val secondContents = guiInventory.contents + secondContents.getOrNull(0) shouldBe item1 + secondContents.getOrNull(1) shouldBe item2 + gui.isInventoryLoading(guiInventory) shouldBe false + } } + private fun createAnimation(loadingItem: ItemStack) = + InventoryLoadingAnimation { _, inventory -> + inventory.setItem(0, loadingItem) + } + + protected abstract fun createDelayGUI( + item1: ItemStack, + item2: ItemStack, + delay: Duration, + inventoryType: InventoryType, + loadingAnimation: InventoryLoadingAnimation? + ): GUI + } abstract inner class UpdateClient { diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt index 448ba205..940d583e 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt @@ -1,6 +1,7 @@ package com.github.rushyverse.api.gui import be.seeseemelk.mockbukkit.ServerMock +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.language.LanguageManager import com.github.rushyverse.api.translation.SupportedLanguage @@ -15,6 +16,7 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow @@ -74,7 +76,7 @@ class LocalePlayerGUITest : AbstractGUITest() { inner class Contains : AbstractGUITest.Contains() @Nested - inner class OpenClient : AbstractGUITest.OpenClient() { + inner class OpenClient : AbstractGUITest.OpenClient() { @Test fun `should create a new inventory according to the language client`() = runTest { @@ -129,6 +131,24 @@ class LocalePlayerGUITest : AbstractGUITest() { player.assertInventoryView(type) } + override fun createDelayGUI( + item1: ItemStack, + item2: ItemStack, + delay: Duration, + inventoryType: InventoryType, + loadingAnimation: InventoryLoadingAnimation? + ): GUI { + return object : AbstractLocaleGUITest(plugin, serverMock, InventoryType.CHEST, loadingAnimation) { + override fun getItems(key: Locale, size: Int): Flow { + return flow { + emit(0 to item1) + delay(1.seconds) + emit(1 to item2) + } + } + } + } + } @Nested @@ -182,8 +202,9 @@ class LocalePlayerGUITest : AbstractGUITest() { private abstract class AbstractLocaleGUITest( plugin: Plugin, val serverMock: ServerMock, - val type: InventoryType = InventoryType.HOPPER -) : LocaleGUI(plugin) { + val type: InventoryType = InventoryType.HOPPER, + animation: InventoryLoadingAnimation? = null +) : LocaleGUI(plugin, animation) { override fun createInventory(key: Locale): Inventory { return serverMock.createInventory(null, type) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt index 629a1e46..5213edae 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt @@ -1,12 +1,14 @@ package com.github.rushyverse.api.gui import be.seeseemelk.mockbukkit.ServerMock +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import kotlin.test.Test import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow @@ -34,7 +36,7 @@ class PlayerGUITest : AbstractGUITest() { inner class Contains : AbstractGUITest.Contains() @Nested - inner class OpenClient : AbstractGUITest.OpenClient() { + inner class OpenClient : AbstractGUITest.OpenClient() { @Test fun `should create a new inventory for the client`() = runTest { @@ -68,6 +70,24 @@ class PlayerGUITest : AbstractGUITest() { player.assertInventoryView(type) } + + override fun createDelayGUI( + item1: ItemStack, + item2: ItemStack, + delay: Duration, + inventoryType: InventoryType, + loadingAnimation: InventoryLoadingAnimation? + ): GUI { + return object : AbstractPlayerGUITest(serverMock, InventoryType.CHEST, loadingAnimation) { + override fun getItems(key: Client, size: Int): Flow { + return flow { + emit(0 to item1) + delay(1.seconds) + emit(1 to item2) + } + } + } + } } @Nested @@ -150,8 +170,9 @@ class PlayerGUITest : AbstractGUITest() { private abstract class AbstractPlayerGUITest( val serverMock: ServerMock, - val type: InventoryType -) : PlayerGUI() { + val type: InventoryType, + loadingAnimation: InventoryLoadingAnimation? = null +) : PlayerGUI(loadingAnimation) { override fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, type) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt index 610ad7ad..edee2ab9 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -1,6 +1,7 @@ package com.github.rushyverse.api.gui import be.seeseemelk.mockbukkit.ServerMock +import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client import com.github.shynixn.mccoroutine.bukkit.scope import io.kotest.matchers.shouldBe @@ -11,6 +12,7 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow @@ -62,7 +64,7 @@ class SingleGUITest : AbstractGUITest() { inner class Contains : AbstractGUITest.Contains() @Nested - inner class OpenClient : AbstractGUITest.OpenClient() { + inner class OpenClient : AbstractGUITest.OpenClient() { @Test fun `should use the same inventory for all clients`() = runTest { @@ -95,6 +97,24 @@ class SingleGUITest : AbstractGUITest() { player.assertInventoryView(type) } + + override fun createDelayGUI( + item1: ItemStack, + item2: ItemStack, + delay: Duration, + inventoryType: InventoryType, + loadingAnimation: InventoryLoadingAnimation? + ): GUI { + return object : AbstractSingleGUITest(plugin, serverMock, InventoryType.CHEST, loadingAnimation) { + override fun getItems(size: Int): Flow { + return flow { + emit(0 to item1) + delay(1.seconds) + emit(1 to item2) + } + } + } + } } @Nested @@ -149,8 +169,9 @@ class SingleGUITest : AbstractGUITest() { private abstract class AbstractSingleGUITest( plugin: Plugin, val serverMock: ServerMock, - val type: InventoryType -) : SingleGUI(plugin) { + val type: InventoryType, + animation: InventoryLoadingAnimation? = null +) : SingleGUI(plugin, animation) { override fun createInventory(): Inventory { return serverMock.createInventory(null, type) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt index 7554e431..6e03eb7b 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt @@ -29,8 +29,8 @@ class ShiftInventoryLoadingAnimationTest { items.forEachIndexed { index, itemStack -> contents[index] = itemStack } - } } + } } @Test From 8f530e79b309847fec21df530a1a464244fb1b2f Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 13:33:24 +0100 Subject: [PATCH 37/48] test: Add verification for close GUI --- .../com/github/rushyverse/api/gui/AbstractGUITest.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt index ce2606c5..6d3c672a 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/AbstractGUITest.kt @@ -504,14 +504,20 @@ abstract class AbstractGUITest : AbstractKoinTest() { val playerClients = List(5) { registerPlayer() } val initialInventoryViewType = playerClients.first().first.openInventory.type - playerClients.forEach { (player, client) -> + val inventories = playerClients.map { (player, client) -> player.assertInventoryView(initialInventoryViewType) gui.openClient(client) shouldBe true player.assertInventoryView(type) client.gui() shouldBe gui + player.openInventory.topInventory } gui.close() + + inventories.forEach { inventory -> + gui.hasInventory(inventory) shouldBe false + } + playerClients.forEach { (player, client) -> player.assertInventoryView(initialInventoryViewType) client.gui() shouldBe null From 58e4ec914206e976aea8e9768723e1566c69df4c Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 13:38:59 +0100 Subject: [PATCH 38/48] test: Add test about update for single GUI --- .../rushyverse/api/gui/SingleGUITest.kt | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt index edee2ab9..e674c8c8 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -5,8 +5,11 @@ import com.github.rushyverse.api.gui.load.InventoryLoadingAnimation import com.github.rushyverse.api.player.Client import com.github.shynixn.mccoroutine.bukkit.scope import io.kotest.matchers.shouldBe +import io.mockk.coEvery +import io.mockk.coVerify import io.mockk.every import io.mockk.mockkStatic +import io.mockk.spyk import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.BeforeTest import kotlin.test.Test @@ -38,11 +41,11 @@ class SingleGUITest : AbstractGUITest() { every { plugin.scope } returns CoroutineScope(EmptyCoroutineContext) } - override fun createNonFillGUI(inventoryType: InventoryType): GUI<*> { + override fun createNonFillGUI(inventoryType: InventoryType): SingleGUI { return SingleNonFillGUI(plugin, serverMock, inventoryType) } - override fun createFillGUI(items: Array, inventoryType: InventoryType, delay: Duration?): GUI<*> { + override fun createFillGUI(items: Array, inventoryType: InventoryType, delay: Duration?): SingleGUI { return SingleFillGUI(plugin, serverMock, inventoryType, items, delay) } @@ -120,6 +123,22 @@ class SingleGUITest : AbstractGUITest() { @Nested inner class UpdateClient : AbstractGUITest.UpdateClient() + @Nested + inner class Update { + + @ParameterizedTest + @ValueSource(booleans = [true, false]) + fun `should call update function with generic key`(result: Boolean) = runTest { + val gui = spyk(createNonFillGUI()) { + coEvery { update(Unit, result) } returns result + } + + gui.update(result) shouldBe result + coVerify(exactly = 1) { gui.update(Unit, result) } + } + + } + @Nested inner class HasInventory : AbstractGUITest.HasInventory() From 5b8337136d2be80953fd52c72bc2a826c9894815 Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 13:54:05 +0100 Subject: [PATCH 39/48] test: Add test about shift constructor --- .../ShiftInventoryLoadingAnimationTest.kt | 68 ++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt index 6e03eb7b..75d7887e 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt @@ -1,18 +1,25 @@ package com.github.rushyverse.api.gui.load +import io.kotest.assertions.throwables.shouldNotThrow +import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk +import java.util.* import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.nanoseconds import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource class ShiftInventoryLoadingAnimationTest { @@ -33,6 +40,30 @@ class ShiftInventoryLoadingAnimationTest { } } + @ParameterizedTest + @ValueSource(ints = [0, -1, -2, -3, -4, -5, -6, -7, -8]) + fun `should throw if duration is not positive`(duration: Int) { + shouldThrow { + ShiftInventoryLoadingAnimation( + initialize = { emptySequence() }, + shift = 1, + delay = duration.milliseconds + ) + } + } + + @ParameterizedTest + @ValueSource(ints = [1, 2, 3, 4, 5, 6, 7, 8]) + fun `should not throw if duration is positive`(duration: Int) { + shouldNotThrow { + ShiftInventoryLoadingAnimation( + initialize = { emptySequence() }, + shift = 1, + delay = duration.nanoseconds + ) + } + } + @Test fun `should not change inventory if initialize is empty`() { val delay = 10.milliseconds @@ -53,12 +84,21 @@ class ShiftInventoryLoadingAnimationTest { @Test fun `should just initialize if shift is zero`() = runBlocking { + shouldJustInitializeWithoutShift(0) + } + + @Test + fun `should just initialize if shift is inventory size`() = runBlocking { + shouldJustInitializeWithoutShift(inventory.size) + } + + private suspend fun shouldJustInitializeWithoutShift(shift: Int) = coroutineScope { val delay = 10.milliseconds val items = Array(inventory.size) { mockk() } val animation = ShiftInventoryLoadingAnimation( initialize = { items.asSequence() }, - shift = 0, + shift = shift, delay = delay ) @@ -68,4 +108,30 @@ class ShiftInventoryLoadingAnimationTest { inventory.contents.toList() shouldContainExactly items.toList() } + + @ParameterizedTest + @ValueSource(ints = [1, 2, 3, 4, 5, 6, 7, 8]) + fun `should shift initialized items`(shift: Int) = runBlocking { + val delay = 100.milliseconds + val items = Array(inventory.size) { mockk() } + val itemList = items.toList() + + val animation = ShiftInventoryLoadingAnimation( + initialize = { items.asSequence() }, + shift = shift, + delay = delay + ) + + val job = launch { animation.loading(Unit, inventory) } + + delay(delay / 2) + repeat(5) { + inventory.contents.toList() shouldContainExactly itemList + delay(delay) + Collections.rotate(itemList, shift) + job.isActive shouldBe true + } + + job.cancelAndJoin() + } } From f21da9c0433d9cac7753124ce26c3ff7353e6da5 Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 13:55:58 +0100 Subject: [PATCH 40/48] chore: Remove property exception --- src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index 3b4db03a..e9c03500 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -62,9 +62,8 @@ public class GUIClosedException(message: String? = null) : GUIException(message) /** * Exception thrown when the GUI is updating. - * @property client Client for which the GUI is updating. */ -public class GUIUpdatedException(public val client: Client?) : GUIException() +public class GUIUpdatedException : GUIException() /** * Exception thrown when the GUI is closed for a specific client. @@ -163,7 +162,7 @@ public abstract class GUI( val key = getKey(client) return mutex.withLock { if (!unsafeContains(client)) return false - unsafeUpdate(key, interruptLoading, client) + unsafeUpdate(key, interruptLoading) } } @@ -181,7 +180,7 @@ public abstract class GUI( * @return True if the inventory was updated, false otherwise. */ public open suspend fun update(key: T, interruptLoading: Boolean = false): Boolean { - return mutex.withLock { unsafeUpdate(key, interruptLoading, null) } + return mutex.withLock { unsafeUpdate(key, interruptLoading) } } /** @@ -199,7 +198,7 @@ public abstract class GUI( * to start a new loading animation. * @return True if the inventory was updated, false otherwise. */ - private suspend fun unsafeUpdate(key: T, interruptLoading: Boolean = false, cause: Client? = null): Boolean { + private suspend fun unsafeUpdate(key: T, interruptLoading: Boolean = false): Boolean { val inventoryData = inventories[key] ?: return false if (inventoryData.isLoading) { @@ -209,7 +208,7 @@ public abstract class GUI( // If we want to interrupt the loading, we cancel the loading job. // We need to wait for the job to be cancelled to avoid conflicts with the new loading animation. inventoryData.job.apply { - cancel(GUIUpdatedException(cause)) + cancel(GUIUpdatedException()) join() } } From 94bc53b46814644a72621ce290db5f36d817f4e7 Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 14:01:45 +0100 Subject: [PATCH 41/48] test: Add check test about stop animation --- .../kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt | 8 ++++---- .../api/gui/load/ShiftInventoryLoadingAnimationTest.kt | 3 +++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt index e674c8c8..38634edd 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -128,13 +128,13 @@ class SingleGUITest : AbstractGUITest() { @ParameterizedTest @ValueSource(booleans = [true, false]) - fun `should call update function with generic key`(result: Boolean) = runTest { + fun `should call update function with generic key`(boolean: Boolean) = runTest { val gui = spyk(createNonFillGUI()) { - coEvery { update(Unit, result) } returns result + coEvery { update(Unit, boolean) } returns boolean } - gui.update(result) shouldBe result - coVerify(exactly = 1) { gui.update(Unit, result) } + gui.update(boolean) shouldBe boolean + coVerify(exactly = 1) { gui.update(Unit, boolean) } } } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt index 75d7887e..8c1e8c9c 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/load/ShiftInventoryLoadingAnimationTest.kt @@ -133,5 +133,8 @@ class ShiftInventoryLoadingAnimationTest { } job.cancelAndJoin() + delay(delay) + // The inventory should not have changed after the animation is finished. + inventory.contents.toList() shouldContainExactly itemList } } From b35071d1abb2bdf902f08b949d7904b6e7d95a79 Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 16:12:31 +0100 Subject: [PATCH 42/48] fix: Rollback scope API plugin --- src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt b/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt index 7b0abcc6..e1b0480e 100644 --- a/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt +++ b/src/main/kotlin/com/github/rushyverse/api/APIPlugin.kt @@ -15,7 +15,7 @@ import org.bukkit.plugin.java.JavaPlugin /** * Plugin to enable the API in server. */ -public open class APIPlugin : JavaPlugin() { +public class APIPlugin : JavaPlugin() { public companion object { /** From 728ae8773b68d45c09906b72a1c85920d1b8179f Mon Sep 17 00:00:00 2001 From: Distractic Date: Wed, 20 Dec 2023 19:16:27 +0100 Subject: [PATCH 43/48] chore: Remove unused method --- .../rushyverse/api/extension/_String.kt | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt b/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt index 63ab7bfa..3a59a649 100644 --- a/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt +++ b/src/main/kotlin/com/github/rushyverse/api/extension/_String.kt @@ -3,16 +3,14 @@ package com.github.rushyverse.api.extension -import com.github.rushyverse.api.translation.Translator -import com.github.rushyverse.api.translation.getComponent +import java.math.BigInteger +import java.util.* import net.kyori.adventure.text.Component import net.kyori.adventure.text.TextComponent import net.kyori.adventure.text.format.NamedTextColor import net.kyori.adventure.text.minimessage.MiniMessage import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver import net.kyori.adventure.text.minimessage.tag.standard.StandardTags -import java.math.BigInteger -import java.util.* /** * MiniMessage instance to deserialize components without strict mode. @@ -265,16 +263,3 @@ public fun StringBuilder.deleteLast(size: Int): StringBuilder { else -> delete(length - size, length) } } - -/** - * If the string contains a dot, it will be considered as a translation path, and will be translated. - * However, if the string doesn't contain a dot, it will be considered as a component. - * @receiver String to translate or to convert to a component. - * @param translator Translator. - * @param locale Locale to use for translation. - * @return The translated component or the component created from the string. - */ -public fun String.toTranslatedComponent(translator: Translator, locale: Locale): Component { - return if (this.contains('.')) translator.getComponent(this, locale) - else this.asComponent() -} From 3259de410e253ed263f089b92819fe2086f17b4d Mon Sep 17 00:00:00 2001 From: Distractic Date: Thu, 21 Dec 2023 14:50:35 +0100 Subject: [PATCH 44/48] fix: remove & move right click item on click inventory --- .../rushyverse/api/extension/event/_Event.kt | 37 +++++++++++ .../github/rushyverse/api/gui/GUIListener.kt | 51 +------------- .../api/extension/event/EventExtTest.kt | 66 +++++++++++++++++++ .../rushyverse/api/gui/GUIListenerTest.kt | 36 ---------- 4 files changed, 106 insertions(+), 84 deletions(-) create mode 100644 src/test/kotlin/com/github/rushyverse/api/extension/event/EventExtTest.kt diff --git a/src/main/kotlin/com/github/rushyverse/api/extension/event/_Event.kt b/src/main/kotlin/com/github/rushyverse/api/extension/event/_Event.kt index f1f1e25a..444d7b50 100644 --- a/src/main/kotlin/com/github/rushyverse/api/extension/event/_Event.kt +++ b/src/main/kotlin/com/github/rushyverse/api/extension/event/_Event.kt @@ -1,7 +1,16 @@ package com.github.rushyverse.api.extension.event +import com.github.shynixn.mccoroutine.bukkit.callSuspendingEvent +import kotlinx.coroutines.joinAll +import org.bukkit.Bukkit +import org.bukkit.block.BlockFace import org.bukkit.entity.Damageable +import org.bukkit.entity.Player +import org.bukkit.event.block.Action import org.bukkit.event.entity.EntityDamageEvent +import org.bukkit.event.player.PlayerInteractEvent +import org.bukkit.inventory.ItemStack +import org.bukkit.plugin.Plugin /** * Future life of the damaged entity. @@ -15,3 +24,31 @@ public fun EntityDamageEvent.finalDamagedHealth(): Double? { null } } + +/** + * Create a [PlayerInteractEvent] to simulate a right click with an item for a player and call it. + * @param plugin Plugin to call the event. + * @param player Player who clicked. + * @param item Item that was clicked. + */ +public suspend fun callRightClickOnItemEvent(plugin: Plugin, player: Player, item: ItemStack) { + val rightClickWithItemEvent = createRightClickEventWithItem(player, item) + Bukkit.getPluginManager().callSuspendingEvent(rightClickWithItemEvent, plugin).joinAll() +} + +/** + * Create a PlayerInteractEvent to simulate a right click with an item. + * @param player Player who clicked. + * @param item Item that was clicked. + * @return The new event. + */ +private fun createRightClickEventWithItem( + player: Player, + item: ItemStack +) = PlayerInteractEvent( + player, + Action.RIGHT_CLICK_AIR, + item, + null, + BlockFace.NORTH // random value not null +) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt index 276c56d0..3609bb14 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUIListener.kt @@ -4,22 +4,14 @@ import com.github.rushyverse.api.Plugin import com.github.rushyverse.api.extension.event.cancel import com.github.rushyverse.api.koin.inject import com.github.rushyverse.api.player.ClientManager -import com.github.shynixn.mccoroutine.bukkit.callSuspendingEvent -import kotlinx.coroutines.joinAll import org.bukkit.Material -import org.bukkit.Server -import org.bukkit.block.BlockFace import org.bukkit.entity.HumanEntity -import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener -import org.bukkit.event.block.Action import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent -import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack -import org.bukkit.inventory.PlayerInventory /** * Listener for GUI events. @@ -29,8 +21,6 @@ public class GUIListener(private val plugin: Plugin) : Listener { private val clients: ClientManager by inject(plugin.id) - private val server: Server by inject() - /** * Called when a player clicks on an item in an inventory. * If the click is detected in a GUI, the event is cancelled and the GUI is notified. @@ -48,11 +38,7 @@ public class GUIListener(private val plugin: Plugin) : Listener { val clickedInventory = event.clickedInventory ?: return val player = event.whoClicked - if (clickedInventory is PlayerInventory) { - handleClickOnPlayerInventory(player as Player, item, event) - } else { - handleClickOnGUI(player, clickedInventory, item, event) - } + handleClickOnGUI(player, clickedInventory, item, event) } /** @@ -79,37 +65,6 @@ public class GUIListener(private val plugin: Plugin) : Listener { gui.onClick(client, clickedInventory, item, event) } - /** - * Called when a player clicks on an item in his inventory. - * To trigger the action linked to the clicked item, - * we produce a PlayerInteractEvent to simulate a right click with the item. - * @param player Player who clicked. - * @param item Item that was clicked. - */ - private suspend fun handleClickOnPlayerInventory(player: Player, item: ItemStack, event: InventoryClickEvent) { - event.cancel() - - val rightClickWithItemEvent = createRightClickWithItemEvent(player, item) - server.pluginManager.callSuspendingEvent(rightClickWithItemEvent, plugin).joinAll() - } - - /** - * Create a PlayerInteractEvent to simulate a right click with an item. - * @param player Player who clicked. - * @param item Item that was clicked. - * @return The new event. - */ - private fun createRightClickWithItemEvent( - player: Player, - item: ItemStack - ) = PlayerInteractEvent( - player, - Action.RIGHT_CLICK_AIR, - item, - null, - BlockFace.NORTH // random value not null - ) - /** * Called when a player closes an inventory. * If the inventory is a GUI, the GUI is notified that it is closed for this player. @@ -117,8 +72,8 @@ public class GUIListener(private val plugin: Plugin) : Listener { */ @EventHandler public suspend fun onInventoryClose(event: InventoryCloseEvent) { - val client = clients.getClientOrNull(event.player) - val gui = client?.gui() ?: return + val client = clients.getClientOrNull(event.player) ?: return + val gui = client.gui() ?: return // We don't close the inventory because it is closing due to event. // That avoids an infinite loop of events and consequently a stack overflow. gui.closeClient(client, false) diff --git a/src/test/kotlin/com/github/rushyverse/api/extension/event/EventExtTest.kt b/src/test/kotlin/com/github/rushyverse/api/extension/event/EventExtTest.kt new file mode 100644 index 00000000..f54c2817 --- /dev/null +++ b/src/test/kotlin/com/github/rushyverse/api/extension/event/EventExtTest.kt @@ -0,0 +1,66 @@ +package com.github.rushyverse.api.extension.event + +import be.seeseemelk.mockbukkit.MockBukkit +import be.seeseemelk.mockbukkit.ServerMock +import com.github.rushyverse.api.extension.ItemStack +import com.github.shynixn.mccoroutine.bukkit.callSuspendingEvent +import io.kotest.matchers.shouldBe +import io.mockk.every +import io.mockk.mockkStatic +import io.mockk.slot +import io.mockk.unmockkAll +import io.mockk.verify +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.runTest +import org.bukkit.Material +import org.bukkit.event.block.Action +import org.bukkit.event.player.PlayerInteractEvent + +class EventExtTest { + + private lateinit var serverMock: ServerMock + + @BeforeTest + fun onBefore() { + serverMock = MockBukkit.mock() + mockkStatic("com.github.shynixn.mccoroutine.bukkit.MCCoroutineKt") + } + + @AfterTest + fun onAfter() { + MockBukkit.unmock() + unmockkAll() + } + + @Test + fun `should trigger right click`() = runTest { + val plugin = MockBukkit.createMockPlugin() + val player = serverMock.addPlayer() + val item = ItemStack { type = Material.DIRT } + val slot = slot() + + lateinit var jobs: List + val pluginManager = serverMock.pluginManager + every { pluginManager.callSuspendingEvent(capture(slot), plugin) } answers { + List(5) { async { delay(1.seconds) } }.apply { jobs = this } + } + + callRightClickOnItemEvent(plugin, player, item) + + verify(exactly = 1) { pluginManager.callSuspendingEvent(any(), plugin) } + jobs.forEach { it.isCompleted shouldBe true } + + val event = slot.captured + event.player shouldBe player + event.action shouldBe Action.RIGHT_CLICK_AIR + event.item shouldBe item + event.clickedBlock shouldBe null + } + +} diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt index 2a86c9ed..4b5d1566 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/GUIListenerTest.kt @@ -9,30 +9,23 @@ import com.github.rushyverse.api.player.Client import com.github.rushyverse.api.player.ClientManager import com.github.rushyverse.api.player.ClientManagerImpl import com.github.shynixn.mccoroutine.bukkit.callSuspendingEvent -import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic -import io.mockk.slot import io.mockk.unmockkAll import io.mockk.verify import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test -import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.async -import kotlinx.coroutines.delay import kotlinx.coroutines.test.runTest import org.bukkit.Material import org.bukkit.entity.Player -import org.bukkit.event.block.Action import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent -import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack import org.junit.jupiter.api.Nested @@ -116,35 +109,6 @@ class GUIListenerTest : AbstractKoinTest() { verify(exactly = 0) { pluginManager.callSuspendingEvent(any(), plugin) } } - @Test - fun `should trigger right click event if player select his own inventory`() = runTest { - val (player, client) = registerPlayer() - val gui = registerGUI { - coEvery { contains(client) } returns false - } - - val pluginManager = server.pluginManager - - val slot = slot() - val jobs = List(5) { - async { delay(1.seconds) } - } - every { pluginManager.callSuspendingEvent(capture(slot), plugin) } returns jobs - - val item = ItemStack { type = Material.DIRT } - - callEvent(false, player, item, player.inventory) - coVerify(exactly = 0) { gui.onClick(any(), any(), any(), any()) } - verify(exactly = 1) { pluginManager.callSuspendingEvent(any(), plugin) } - jobs.forEach { it.isCompleted shouldBe true } - - val event = slot.captured - event.player shouldBe player - event.action shouldBe Action.RIGHT_CLICK_AIR - event.item shouldBe item - event.clickedBlock shouldBe null - } - @Test fun `should call GUI onClick if client has opened one`() = runTest { val (player, client) = registerPlayer() From 2fd21151ce1bcdc2a19e2fcff4c5e7100db4bbbe Mon Sep 17 00:00:00 2001 From: Distractic Date: Sat, 23 Dec 2023 07:28:39 +0100 Subject: [PATCH 45/48] chore: Remove await cancellation --- src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index e9c03500..ad0f2f63 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -7,7 +7,6 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job -import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow @@ -264,12 +263,7 @@ public abstract class GUI( // Will fill the inventory bit by bit. inventoryFlowItems.collect { (index, item) -> inventory.setItem(index, item) } } else { - val loadingAnimationJob = launch { - loadingAnimation.loading(key, inventory) - // If the loading function is finished, the "loading" state must be continued - // until the flow is finished. - awaitCancellation() - } + val loadingAnimationJob = launch { loadingAnimation.loading(key, inventory) } // To avoid conflicts with the loading animation, // we need to store the items in a temporary inventory From 0ad4fa6d3de91262c5a374f098b829c0abe07041 Mon Sep 17 00:00:00 2001 From: Cizetux Date: Wed, 3 Jan 2024 17:13:47 +0100 Subject: [PATCH 46/48] refactor: Add suspend modifier to 'createInventory' across multiple classes --- src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt | 2 +- src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt | 4 ++-- src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt | 4 ++-- .../com/github/rushyverse/api/gui/LocalePlayerGUITest.kt | 2 +- .../kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt | 2 +- .../kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt index ad0f2f63..fb354055 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/GUI.kt @@ -288,7 +288,7 @@ public abstract class GUI( * @param key Key to create the inventory for. * @return New created inventory. */ - protected abstract fun createInventory(key: T): Inventory + protected abstract suspend fun createInventory(key: T): Inventory /** * Create a new flow of [Item][ItemStack] to fill the inventory with. diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt index c94ca7ae..d0238193 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/PlayerGUI.kt @@ -42,7 +42,7 @@ public abstract class PlayerGUI( * @param key The client to create the inventory for. * @return The inventory for the client. */ - override fun createInventory(key: Client): Inventory { + override suspend fun createInventory(key: Client): Inventory { val player = key.requirePlayer() return createInventory(player, key) } @@ -54,7 +54,7 @@ public abstract class PlayerGUI( * @param client The client to create the inventory for. * @return The inventory for the client. */ - protected abstract fun createInventory(owner: InventoryHolder, client: Client): Inventory + protected abstract suspend fun createInventory(owner: InventoryHolder, client: Client): Inventory override suspend fun closeClient(client: Client, closeInventory: Boolean): Boolean { val (inventory, job) = mutex.withLock { inventories.remove(client) } ?: return false diff --git a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt index ba9a2817..47b5ae5e 100644 --- a/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt +++ b/src/main/kotlin/com/github/rushyverse/api/gui/SingleGUI.kt @@ -44,7 +44,7 @@ public abstract class SingleGUI( return scope + SupervisorJob(scope.coroutineContext.job) } - override fun createInventory(key: Unit): Inventory { + override suspend fun createInventory(key: Unit): Inventory { return createInventory() } @@ -52,7 +52,7 @@ public abstract class SingleGUI( * Create the inventory. * @return New created inventory. */ - protected abstract fun createInventory(): Inventory + protected abstract suspend fun createInventory(): Inventory /** * Update the inventory. diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt index 940d583e..4249e861 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/LocalePlayerGUITest.kt @@ -206,7 +206,7 @@ private abstract class AbstractLocaleGUITest( animation: InventoryLoadingAnimation? = null ) : LocaleGUI(plugin, animation) { - override fun createInventory(key: Locale): Inventory { + override suspend fun createInventory(key: Locale): Inventory { return serverMock.createInventory(null, type) } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt index 5213edae..3672cda5 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/PlayerGUITest.kt @@ -174,7 +174,7 @@ private abstract class AbstractPlayerGUITest( loadingAnimation: InventoryLoadingAnimation? = null ) : PlayerGUI(loadingAnimation) { - override fun createInventory(owner: InventoryHolder, client: Client): Inventory { + override suspend fun createInventory(owner: InventoryHolder, client: Client): Inventory { return serverMock.createInventory(owner, type) } diff --git a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt index 38634edd..51601e76 100644 --- a/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt +++ b/src/test/kotlin/com/github/rushyverse/api/gui/SingleGUITest.kt @@ -192,7 +192,7 @@ private abstract class AbstractSingleGUITest( animation: InventoryLoadingAnimation? = null ) : SingleGUI(plugin, animation) { - override fun createInventory(): Inventory { + override suspend fun createInventory(): Inventory { return serverMock.createInventory(null, type) } From c4651307bf979c9780beb659deb87cf33d40e42f Mon Sep 17 00:00:00 2001 From: Cizetux Date: Sat, 7 Sep 2024 17:25:53 +0200 Subject: [PATCH 47/48] refactor: Add data colors to each GameState --- .../com/github/rushyverse/api/game/GameState.kt | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/com/github/rushyverse/api/game/GameState.kt b/src/main/kotlin/com/github/rushyverse/api/game/GameState.kt index 7029f34e..b66df1fe 100644 --- a/src/main/kotlin/com/github/rushyverse/api/game/GameState.kt +++ b/src/main/kotlin/com/github/rushyverse/api/game/GameState.kt @@ -1,33 +1,40 @@ package com.github.rushyverse.api.game +import net.kyori.adventure.text.format.NamedTextColor + /** * Represents the various states a game can be in at any given moment. * Each state corresponds to a different phase in the game's lifecycle. */ -public enum class GameState { +public enum class GameState( + public val color: NamedTextColor, + public val miniColor: String, +) { + + NOT_STARTED(NamedTextColor.BLUE, ""), /** * Represents the state where the game is waiting for necessary conditions to start. * This could be waiting for more players to join, or waiting for some setup process to finish. */ - WAITING, + WAITING(NamedTextColor.GOLD, ""), /** * Represents the state when the game is in the process of starting. * This is a transitional phase, initialization of game resources, * a countdown timer before the game starts, etc. */ - STARTING, + STARTING(NamedTextColor.YELLOW, ""), /** * Represents the state where the game has officially started. * Gameplay is active during this state. */ - STARTED, + STARTED(NamedTextColor.GREEN, ""), /** * Represents the state when the game is in the process of ending. * This is a transitional phase, where final scores might be calculated, game resources might be cleaned up, etc. */ - ENDING; + ENDED(NamedTextColor.RED, ""); } From 8f7281dff41193222e0149db25789bdc50f12317 Mon Sep 17 00:00:00 2001 From: Cizetux Date: Sat, 7 Sep 2024 17:27:51 +0200 Subject: [PATCH 48/48] refactor: Add 'permanent' field to handle games that are in permanent mode --- src/main/kotlin/com/github/rushyverse/api/game/GameData.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/kotlin/com/github/rushyverse/api/game/GameData.kt b/src/main/kotlin/com/github/rushyverse/api/game/GameData.kt index 0266b918..0b229ec4 100644 --- a/src/main/kotlin/com/github/rushyverse/api/game/GameData.kt +++ b/src/main/kotlin/com/github/rushyverse/api/game/GameData.kt @@ -13,4 +13,5 @@ public data class GameData( val id: Int, var players: Int = 0, var state: GameState = GameState.WAITING, + val permanent: Boolean = false )