Initial commit for InventoryGui

This commit is contained in:
2026-01-19 22:03:03 +01:00
commit 6f72215414
20 changed files with 998 additions and 0 deletions
@@ -0,0 +1,27 @@
package com.alttd.inventory_gui.click;
import org.bukkit.event.inventory.InventoryClickEvent;
/**
* Represents a functional interface for handling click events in a graphical user interface (GUI).
* This interface defines a single abstract method, allowing custom behavior to be implemented
* when a user interacts with a clickable GUI element.
* <p>
* The method {@link #onClick(InventoryClickEvent)} is triggered when an {@code InventoryClickEvent}
* occurs, enabling developers to implement specific actions based on the nature of the event.
* <p>
* It is typically used in conjunction with classes that represent GUI components, such as
* {@code GuiItem}, where this interface is employed to define the click behavior of a component.
*/
@FunctionalInterface
public interface GuiClickHandler {
/**
* Handles an inventory click event, allowing custom actions to be performed when a user interacts
* with a graphical user interface (GUI) element.
*
* @param event the {@code InventoryClickEvent} representing the details of the user's interaction,
* including the clicked slot, the item involved, and the action performed.
*/
void onClick(InventoryClickEvent event);
}
@@ -0,0 +1,55 @@
package com.alttd.inventory_gui.click;
import lombok.Getter;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
/**
* Represents an item in a (inventory) graphical user interface (GUI).
* This class encapsulates an {@code ItemStack} with optional click handling behavior,
* allowing for the creation of both clickable and non-clickable GUI elements.
* Instances of this class are immutable and thread-safe.
*/
@SuppressWarnings("ClassCanBeRecord")
public final class GuiItem {
@Getter
private final ItemStack stack;
@Getter
private final boolean clickable;
private final GuiClickHandler handler;
private GuiItem(ItemStack stack, boolean clickable, GuiClickHandler handler) {
this.stack = stack;
this.clickable = clickable;
this.handler = handler;
}
/**
* Creates a new {@code GuiItem} with the given {@code ItemStack} and click handling behavior.
* @param stack the {@code ItemStack} to represent in the GUI
* @param handler the {@code GuiClickHandler} to handle click events for this item, or {@code null} for non-clickable items
* @return a new {@code GuiItem} instance
*/
public static GuiItem clickable(ItemStack stack, GuiClickHandler handler) {
return new GuiItem(stack, true, handler);
}
/**
* Creates a new non-clickable {@code GuiItem} with the given {@code ItemStack}.
* @param stack the {@code ItemStack} to represent in the GUI
* @return a new non-clickable {@code GuiItem} instance
*/
public static GuiItem nonClickable(ItemStack stack) {
return new GuiItem(stack, false, null);
}
/**
* Handles a click event for this item if a click handler has been specified.
* @param event the {@code InventoryClickEvent} representing the details of the user's interaction
*/
public void handle(InventoryClickEvent event) {
if (handler != null) {
handler.onClick(event);
}
}
}
@@ -0,0 +1,24 @@
package com.alttd.inventory_gui.gui;
/**
* Enum representing the policies for handling the closing of GUI inventory interfaces.
* The close policy determines whether players are allowed to close the GUI or if the
* GUI should attempt to prevent closure.
* <p>
* This enum is primarily used in conjunction with the {@code InventoryGui} class to
* define the behavior of GUI sessions when a player attempts to close the inventory.
* <p>
* The available policies are:
* - {@code ALLOW_CLOSE}: Allows players to close the GUI without intervention.
* - {@code BLOCK_CLOSE}: Attempts to prevent players from closing the GUI by reopening it.
*/
public enum GuiClosePolicy {
/**
* Allows players to close the GUI without intervention.
*/
ALLOW_CLOSE,
/**
* Attempts to prevent players from closing the GUI by reopening it.
*/
BLOCK_CLOSE
}
@@ -0,0 +1,92 @@
package com.alttd.inventory_gui.gui;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.Nullable;
/**
* The {@code GuiListener} class implements the {@code Listener} interface to handle
* inventory click and close events for GUI interactions in a Bukkit/Spigot plugin context.
* It ensures that proper event handling is delegated to the appropriate GUI session
* associated with a player.
* <p>
* This class relies on the {@code GuiSession} system to keep track of players' active
* GUI sessions and routes events to the corresponding {@code InventoryGui} instance.
* <p>
* The {@code GuiListener} is associated with a specific plugin by its name to ensure
* that event handling is scoped to the appropriate plugin's GUI instances.
*/
@SuppressWarnings("ClassCanBeRecord")
public final class GuiListener implements Listener {
private final String ownerPluginName;
/**
* Constructs a new {@code GuiListener} instance.
* @param ownerPluginName the name of the plugin that owns the GUI instances to which this listener should be attached
*/
public GuiListener(String ownerPluginName) {
this.ownerPluginName = ownerPluginName;
}
/**
* Handles interactions with inventories in the context of GUI sessions. This method ensures
* that the interaction is processed only if the player is part of an active GUI session.
* The method cancels the interaction event by default and delegates specific event handling
* to the associated GUI instance when applicable.
*
* @param event the {@code InventoryInteractEvent} triggered when a player interacts with an inventory
*/
@EventHandler
public void onInventoryInteract(InventoryInteractEvent event) {
if (!(event.getWhoClicked() instanceof Player player)) {
return;
}
GuiSession.Entry entry = getEntry(player, event.getInventory());
if (entry == null) {
return;
}
event.setCancelled(true);
if (event instanceof InventoryClickEvent inventoryClickEvent) {
entry.gui().handleClick(inventoryClickEvent);
}
}
/**
* Handles inventory close events for GUI interactions.
* @param event the {@code InventoryCloseEvent} representing the details of the user's interaction
*/
@EventHandler
public void onClose(InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player player)) {
return;
}
GuiSession.Entry entry = getEntry(player, event.getInventory());
if (entry == null) {
return;
}
entry.gui().handleClose(player);
GuiSession.clear(player.getUniqueId());
}
private GuiSession.@Nullable Entry getEntry(Player player, Inventory event) {
GuiSession.Entry entry = GuiSession.get(player.getUniqueId());
if (entry == null) {
return null;
}
if (!entry.ownerPluginName().equals(ownerPluginName)) {
return null;
}
if (event != entry.inv()) {
return null;
}
return entry;
}
}
@@ -0,0 +1,47 @@
package com.alttd.inventory_gui.gui;
import org.bukkit.inventory.Inventory;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* The {@code GuiSession} class provides a static utility for managing GUI sessions in a Bukkit/Spigot plugin.
* It holds associations between players, their open GUIs, and the owning plugin for the GUI.
* This class ensures that GUIs are properly maintained and can be cleared when no longer needed.
* <p>
* Key responsibilities:
* - Binding a GUI session to a player's UUID.
* - Retrieving the active GUI session for a specific player.
* - Clearing an individual player's GUI session.
* - Clearing all GUI sessions associated with a specific plugin.
* <p>
* This class operates using a thread-safe {@code ConcurrentHashMap} to manage GUI sessions.
*/
public final class GuiSession {
private GuiSession() {
}
private static final Map<UUID, Entry> SESSIONS = new ConcurrentHashMap<>();
static void bind(UUID playerId, String ownerPluginName, InventoryGui gui, Inventory inv) {
SESSIONS.put(playerId, new Entry(ownerPluginName, gui, inv));
}
static Entry get(UUID playerId) {
return SESSIONS.get(playerId);
}
static void clear(UUID playerId) {
SESSIONS.remove(playerId);
}
static void clearAllForOwner(String ownerPluginName) {
SESSIONS.entrySet().removeIf(e -> e.getValue().ownerPluginName().equals(ownerPluginName));
}
record Entry(String ownerPluginName, InventoryGui gui, Inventory inv) {}
}
@@ -0,0 +1,125 @@
package com.alttd.inventory_gui.gui;
import com.alttd.inventory_gui.click.GuiItem;
import com.alttd.inventory_gui.pane.GuiPane;
import com.alttd.inventory_gui.pane.SimplePane;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
/**
* The InventoryGui class represents a dynamic GUI system for Bukkit/Spigot plugins,
* using inventories to create interactive user experiences. It allows developers
* to define and manage custom GUI layouts and behaviors, enabling players to interact
* with plugin elements directly in Minecraft.
* <p>
* This class is built with flexibility and ease of use in mind, supporting various
* customization options, event handling, and row validation to maintain consistency.
*/
@Builder
public class InventoryGui {
@NonNull
@Getter
private final Plugin plugin;
@NonNull
private final Component title;
@NonNull
private final Integer rows;
@Getter
@Builder.Default
private final GuiClosePolicy closePolicy = GuiClosePolicy.ALLOW_CLOSE;
@Getter
private final GuiPane root;
private InventoryGui(@NotNull Plugin plugin, @NotNull Component title, int rows, GuiClosePolicy closePolicy, GuiPane root) {
validateRows(rows);
this.plugin = plugin;
this.title = title;
this.rows = rows;
this.closePolicy = closePolicy;
this.root = root != null ? root : new SimplePane(rows * 9);
}
private static void validateRows(int rows) {
if (rows < 1 || rows > 6) {
throw new IllegalArgumentException("Rows must be between 1 and 6");
}
}
/**
* Creates a new inventory for the specified player.
* @param player the player for whom to create the inventory
* @return a new inventory instance
*/
public Inventory createInventory(Player player) {
return Bukkit.createInventory(player, rows * 9, title);
}
/**
* Renders the GUI's contents into the specified inventory.
* @param inv the inventory into which to render the GUI's contents
*/
public void render(Inventory inv) {
inv.clear();
root.render(inv);
}
/**
* Opens the GUI for the specified player.
* @param player the player for whom to open the GUI
*/
public void open(Player player) {
InventoryGuiLib.ensureInit(plugin);
Inventory inv = createInventory(player);
render(inv);
GuiSession.bind(player.getUniqueId(), plugin.getName(), this, inv);
player.openInventory(inv);
}
/**
* Handles inventory click events for GUI interactions.
* @param event the {@code InventoryClickEvent} representing the details of the user's interaction
*/
public void handleClick(InventoryClickEvent event) {
event.setCancelled(true);
int raw = event.getRawSlot();
if (raw < 0 || raw >= event.getInventory().getSize()) {
return;
}
GuiItem item = root.getItem(raw);
if (item == null) {
return;
}
if (!item.isClickable()) {
event.setCancelled(true);
return;
}
item.handle(event);
}
/**
* Handles inventory close events for GUI interactions.
* @param player the player whose inventory was closed
*/
public void handleClose(Player player) {
if (closePolicy == GuiClosePolicy.ALLOW_CLOSE) {
return;
}
if (closePolicy == GuiClosePolicy.BLOCK_CLOSE) {
plugin.getServer().getScheduler().runTask(plugin, () -> open(player));
}
}
}
@@ -0,0 +1,69 @@
package com.alttd.inventory_gui.gui;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* Utility class providing dynamic GUI management for Bukkit/Spigot-based plugins.
* Uses event registration and session handling to manage inventory-based GUIs.
* <p>
* This class is designed to simplify the management of plugin-specific inventory GUIs,
* ensuring that events are handled appropriately and associated entities are cleaned up
* on plugin unregistration.
* <p>
* Thread-safety is achieved via {@link ConcurrentHashMap} for storing plugin-specific
* registrations. Utility methods include initialization, registration of listeners, and
* cleanup of resources.
*/
public final class InventoryGuiLib {
private InventoryGuiLib() {}
private static final ConcurrentHashMap<String, Registration> REGISTRATIONS = new ConcurrentHashMap<>();
static void ensureInit(Plugin plugin) {
Objects.requireNonNull(plugin, "plugin cannot be null");
REGISTRATIONS.computeIfAbsent(plugin.getName(), name -> {
Listener listener = new GuiListener(name);
plugin.getServer().getPluginManager().registerEvents(listener, plugin);
return new Registration(plugin, listener);
});
}
/**
* Initializes the library for the specified plugin. This method ensures that the plugin
* is properly registered in the library, including the setup of necessary listeners for
* managing inventory GUI events.
*
* @param plugin the plugin for which the library is being initialized; must not be null
*/
public static void init(Plugin plugin) {
Objects.requireNonNull(plugin, "plugin cannot be null");
ensureInit(plugin);
}
/**
* Unregisters the given plugin from the inventory GUI library, removing its associated
* event listeners and clearing all GUI sessions linked to the plugin.
*
* @param plugin the plugin to unregister; must not be null
*/
public static void unregister(Plugin plugin) {
Objects.requireNonNull(plugin, "plugin cannot be null");
Registration reg = REGISTRATIONS.remove(plugin.getName());
if (reg == null) return;
HandlerList.unregisterAll(reg.listener());
GuiSession.clearAllForOwner(reg.ownerName());
}
private record Registration(Plugin owner, Listener listener) {
String ownerName() { return owner.getName(); }
}
}
@@ -0,0 +1,36 @@
package com.alttd.inventory_gui.pane;
import com.alttd.inventory_gui.click.GuiItem;
import org.bukkit.inventory.Inventory;
/**
* Represents a pane in a (inventory) graphical user interface (GUI) inventory layout.
* A {@code GuiPane} acts as a container or layout for GUI items,
* enabling easier management of items in a specific section of an inventory.
* <p>
* Responsibilities:
* - Adding or removing items at specific slots within the pane.
* - Retrieving items from a specific slot in the pane.
* - Rendering the pane's contents into a provided inventory.
*/
public interface GuiPane {
/**
* Sets the item at the specified slot in the pane.
* @param slot the slot index at which to set the item
* @param item the item to set at the specified slot
*/
void setItem(int slot, GuiItem item);
/**
* Retrieves the item at the specified slot in the pane.
* @param slot the slot index from which to retrieve the item
* @return the item at the specified slot, or {@code null} if no item is present at that slot
*/
GuiItem getItem(int slot);
/**
* Renders the pane's contents into the provided inventory.
* @param inv the inventory into which to render the pane's contents
*/
void render(Inventory inv);
}
@@ -0,0 +1,57 @@
package com.alttd.inventory_gui.pane;
import com.alttd.inventory_gui.click.GuiItem;
import org.bukkit.inventory.Inventory;
/**
* The {@code SimplePane} class is an implementation of the {@code GuiPane} interface,
* designed to represent a simple container for GUI items within an inventory.
* <p>
* This class provides:
* - Management of a fixed-size array of {@code GuiItem} objects.
* - Methods to add, retrieve, and render items into an inventory.
* <p>
* Key Responsibilities:
* - Storing a collection of {@code GuiItem} objects in a fixed-sized pane.
* - Validating slot boundaries when setting or retrieving items.
* - Rendering the pane's items into a provided {@code Inventory}, ensuring item positions
* from the pane correspond to positions in the inventory.
*/
@SuppressWarnings("ClassCanBeRecord")
public final class SimplePane implements GuiPane {
private final GuiItem[] items;
/**
* Constructs a new {@code SimplePane} instance with the specified number of slots.
* @param size the number of slots in the pane
*/
public SimplePane(int size) {
this.items = new GuiItem[size];
}
@Override
public void setItem(int slot, GuiItem item) {
if (slot < 0 || slot >= items.length) {
throw new IndexOutOfBoundsException();
}
items[slot] = item;
}
@Override
public GuiItem getItem(int slot) {
if (slot < 0 || slot >= items.length) {
return null;
}
return items[slot];
}
@Override
public void render(Inventory inv) {
for (int i = 0; i < items.length && i < inv.getSize(); i++) {
GuiItem guiItem = items[i];
if (guiItem != null) {
inv.setItem(i, guiItem.getStack());
}
}
}
}