Initial commit for InventoryGui

This commit is contained in:
akastijn 2026-01-19 22:03:03 +01:00
commit 6f72215414
20 changed files with 998 additions and 0 deletions

43
.gitignore vendored Normal file
View File

@ -0,0 +1,43 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
.kotlin
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

16
.idea/gradle.xml Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

10
.idea/misc.xml Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="corretto-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

53
build.gradle.kts Normal file
View File

@ -0,0 +1,53 @@
import org.gradle.api.publish.maven.MavenPublication
plugins {
`java-library`
`maven-publish`
}
val nexusUser = providers.gradleProperty("alttdSnapshotUsername").orNull ?: System.getenv("NEXUS_USERNAME")
val nexusPass = providers.gradleProperty("alttdSnapshotPassword").orNull ?: System.getenv("NEXUS_PASSWORD")
group = "com.alttd.inventory_gui"
version = "1.1.0-SNAPSHOT"
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
}
dependencies {
compileOnly("org.projectlombok:lombok:1.18.30")
annotationProcessor("org.projectlombok:lombok:1.18.30")
compileOnly("io.papermc.paper:paper-api:1.21.11-R0.1-SNAPSHOT")
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
withSourcesJar()
withJavadocJar()
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release.set(21)
}
publishing {
repositories {
maven {
url = uri("https://repo.alttd.com/repository/alttd-snapshot/")
credentials {
username = nexusUser
password = nexusPass
}
}
}
publications {
create<MavenPublication>("mavenJava") {
from(components["java"])
}
}
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Mon Jan 19 20:48:34 CET 2026
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
settings.gradle.kts Normal file
View File

@ -0,0 +1 @@
rootProject.name = "InventoryGUI"

View File

@ -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);
}

View File

@ -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);
}
}
}

View File

@ -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
}

View File

@ -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;
}
}

View File

@ -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) {}
}

View File

@ -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));
}
}
}

View File

@ -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(); }
}
}

View File

@ -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);
}

View File

@ -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());
}
}
}
}